@msafe/sui3-sdk 0.0.49-pre-efcd628.0 → 0.0.49-pre-a7668b7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var Hp=Object.create;var Vi=Object.defineProperty;var Zp=Object.getOwnPropertyDescriptor;var Kp=Object.getOwnPropertyNames;var Jp=Object.getPrototypeOf,Xp=Object.prototype.hasOwnProperty;var Yp=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),fc=(t,e)=>{for(var r in e)Vi(t,r,{get:e[r],enumerable:!0})},hc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Kp(e))!Xp.call(t,i)&&i!==r&&Vi(t,i,{get:()=>e[i],enumerable:!(n=Zp(e,i))||n.enumerable});return t};var de=(t,e,r)=>(r=t!=null?Hp(Jp(t)):{},hc(e||!t||!t.__esModule?Vi(r,"default",{value:t,enumerable:!0}):r,t)),pc=t=>hc(Vi({},"__esModule",{value:!0}),t);var wc=Fr((U_,gc)=>{"use strict";gc.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var bc=Fr(($_,yc)=>{"use strict";var Ws=wc();yc.exports=(t,e={})=>{if(!Ws(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:r}=e,n=[],i=[],o=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d=[];return n.push(u),i.push(d),d.push(...u.map(b=>Array.isArray(b)?o(b):Ws(b)?s(b):b)),d},s=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d={},b=Object.keys(u).sort(e.compare);n.push(u),i.push(d);for(let _ of b){let T=u[_],x;r&&Array.isArray(T)?x=o(T):x=r&&Ws(T)?s(T):T,Object.defineProperty(d,_,{...Object.getOwnPropertyDescriptor(u,_),value:x})}return d};return Array.isArray(t)?r?o(t):t.slice():s(t)}});var Tc=Fr((G_,vc)=>{"use strict";var Qp=Object.prototype.toString;vc.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var r=typeof e;if(r==="boolean")return"boolean";if(r==="string")return"string";if(r==="number")return"number";if(r==="symbol")return"symbol";if(r==="function")return im(e)?"generatorfunction":"function";if(em(e))return"array";if(am(e))return"buffer";if(sm(e))return"arguments";if(rm(e))return"date";if(tm(e))return"error";if(nm(e))return"regexp";switch(_c(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(om(e))return"generator";switch(r=Qp.call(e),r){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return r.slice(8,-1).toLowerCase().replace(/\s/g,"")};function _c(t){return typeof t.constructor=="function"?t.constructor.name:null}function em(t){return Array.isArray?Array.isArray(t):t instanceof Array}function tm(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function rm(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function nm(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function im(t,e){return _c(t)==="GeneratorFunction"}function om(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function sm(t){try{if(typeof t.length=="number"&&typeof t.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function am(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Wi=Fr((V_,Ac)=>{"use strict";var um=bc(),Hs=Tc(),Sc=(t,e)=>!e||Hs(e)!=="array"?!1:e.indexOf(t)>-1,cm=(t,e)=>um(t,{compare:e}),xc=(t,e)=>{let r=e&&e.compareFunction;return t.slice().sort(r)};function kc(t,e){let r=e&&e.compareFunction,n=cm(t,r);return Object.keys(t).forEach(function(i){let o=n[i],s=Hs(o);if(s==="object"){(!e||!Sc(i,e.ignoreObjectAtKeys))&&(n[i]=kc(o,e));return}s==="array"&&(!e||!Sc(i,e.ignoreArrayAtKeys))&&(n[i]=xc(o,e))}),n}var Un=(t,e)=>{let r=Hs(t);return Un[r]?Un[r](t,e):t};Un.array=xc;Un.object=kc;Ac.exports=Un});var we=Fr((Ic,Zs)=>{"use strict";(function(t,e){"use strict";function r(k,a){if(!k)throw new Error(a||"Assertion failed")}function n(k,a){k.super_=a;var c=function(){};c.prototype=a.prototype,k.prototype=new c,k.prototype.constructor=k}function i(k,a,c){if(i.isBN(k))return k;this.negative=0,this.words=null,this.length=0,this.red=null,k!==null&&((a==="le"||a==="be")&&(c=a,a=10),this._init(k||0,a||10,c||"be"))}typeof t=="object"?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=require("buffer").Buffer}catch{}i.isBN=function(a){return a instanceof i?!0:a!==null&&typeof a=="object"&&a.constructor.wordSize===i.wordSize&&Array.isArray(a.words)},i.max=function(a,c){return a.cmp(c)>0?a:c},i.min=function(a,c){return a.cmp(c)<0?a:c},i.prototype._init=function(a,c,m){if(typeof a=="number")return this._initNumber(a,c,m);if(typeof a=="object")return this._initArray(a,c,m);c==="hex"&&(c=16),r(c===(c|0)&&c>=2&&c<=36),a=a.toString().replace(/\s+/g,"");var y=0;a[0]==="-"&&(y++,this.negative=1),y<a.length&&(c===16?this._parseHex(a,y,m):(this._parseBase(a,c,y),m==="le"&&this._initArray(this.toArray(),c,m)))},i.prototype._initNumber=function(a,c,m){a<0&&(this.negative=1,a=-a),a<67108864?(this.words=[a&67108863],this.length=1):a<4503599627370496?(this.words=[a&67108863,a/67108864&67108863],this.length=2):(r(a<9007199254740992),this.words=[a&67108863,a/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),c,m)},i.prototype._initArray=function(a,c,m){if(r(typeof a.length=="number"),a.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(a.length/3),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p,h,w=0;if(m==="be")for(y=a.length-1,p=0;y>=0;y-=3)h=a[y]|a[y-1]<<8|a[y-2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);else if(m==="le")for(y=0,p=0;y<a.length;y+=3)h=a[y]|a[y+1]<<8|a[y+2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);return this._strip()};function s(k,a){var c=k.charCodeAt(a);if(c>=48&&c<=57)return c-48;if(c>=65&&c<=70)return c-55;if(c>=97&&c<=102)return c-87;r(!1,"Invalid character in "+k)}function u(k,a,c){var m=s(k,c);return c-1>=a&&(m|=s(k,c-1)<<4),m}i.prototype._parseHex=function(a,c,m){this.length=Math.ceil((a.length-c)/6),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p=0,h=0,w;if(m==="be")for(y=a.length-1;y>=c;y-=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8;else{var g=a.length-c;for(y=g%2===0?c+1:c;y<a.length;y+=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8}this._strip()};function l(k,a,c,m){for(var y=0,p=0,h=Math.min(k.length,c),w=a;w<h;w++){var g=k.charCodeAt(w)-48;y*=m,g>=49?p=g-49+10:g>=17?p=g-17+10:p=g,r(g>=0&&p<m,"Invalid character"),y+=p}return y}i.prototype._parseBase=function(a,c,m){this.words=[0],this.length=1;for(var y=0,p=1;p<=67108863;p*=c)y++;y--,p=p/c|0;for(var h=a.length-m,w=h%y,g=Math.min(h,h-w)+m,f=0,v=m;v<g;v+=y)f=l(a,v,v+y,c),this.imuln(p),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f);if(w!==0){var O=1;for(f=l(a,v,a.length,c),v=0;v<w;v++)O*=c;this.imuln(O),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f)}this._strip()},i.prototype.copy=function(a){a.words=new Array(this.length);for(var c=0;c<this.length;c++)a.words[c]=this.words[c];a.length=this.length,a.negative=this.negative,a.red=this.red};function d(k,a){k.words=a.words,k.length=a.length,k.negative=a.negative,k.red=a.red}if(i.prototype._move=function(a){d(a,this)},i.prototype.clone=function(){var a=new i(null);return this.copy(a),a},i.prototype._expand=function(a){for(;this.length<a;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=b}catch{i.prototype.inspect=b}else i.prototype.inspect=b;function b(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var _=["","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"],T=[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],x=[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];i.prototype.toString=function(a,c){a=a||10,c=c|0||1;var m;if(a===16||a==="hex"){m="";for(var y=0,p=0,h=0;h<this.length;h++){var w=this.words[h],g=((w<<y|p)&16777215).toString(16);p=w>>>24-y&16777215,y+=2,y>=26&&(y-=26,h--),p!==0||h!==this.length-1?m=_[6-g.length]+g+m:m=g+m}for(p!==0&&(m=p.toString(16)+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(a===(a|0)&&a>=2&&a<=36){var f=T[a],v=x[a];m="";var O=this.clone();for(O.negative=0;!O.isZero();){var M=O.modrn(v).toString(a);O=O.idivn(v),O.isZero()?m=M+m:m=_[f-M.length]+M+m}for(this.isZero()&&(m="0"+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var a=this.words[0];return this.length===2?a+=this.words[1]*67108864:this.length===3&&this.words[2]===1?a+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-a:a},i.prototype.toJSON=function(){return this.toString(16,2)},o&&(i.prototype.toBuffer=function(a,c){return this.toArrayLike(o,a,c)}),i.prototype.toArray=function(a,c){return this.toArrayLike(Array,a,c)};var A=function(a,c){return a.allocUnsafe?a.allocUnsafe(c):new a(c)};i.prototype.toArrayLike=function(a,c,m){this._strip();var y=this.byteLength(),p=m||Math.max(1,y);r(y<=p,"byte array longer than desired length"),r(p>0,"Requested array length <= 0");var h=A(a,p),w=c==="le"?"LE":"BE";return this["_toArrayLike"+w](h,y),h},i.prototype._toArrayLikeLE=function(a,c){for(var m=0,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m++]=w&255,m<a.length&&(a[m++]=w>>8&255),m<a.length&&(a[m++]=w>>16&255),h===6?(m<a.length&&(a[m++]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m<a.length)for(a[m++]=y;m<a.length;)a[m++]=0},i.prototype._toArrayLikeBE=function(a,c){for(var m=a.length-1,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m--]=w&255,m>=0&&(a[m--]=w>>8&255),m>=0&&(a[m--]=w>>16&255),h===6?(m>=0&&(a[m--]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m>=0)for(a[m--]=y;m>=0;)a[m--]=0},Math.clz32?i.prototype._countBits=function(a){return 32-Math.clz32(a)}:i.prototype._countBits=function(a){var c=a,m=0;return c>=4096&&(m+=13,c>>>=13),c>=64&&(m+=7,c>>>=7),c>=8&&(m+=4,c>>>=4),c>=2&&(m+=2,c>>>=2),m+c},i.prototype._zeroBits=function(a){if(a===0)return 26;var c=a,m=0;return c&8191||(m+=13,c>>>=13),c&127||(m+=7,c>>>=7),c&15||(m+=4,c>>>=4),c&3||(m+=2,c>>>=2),c&1||m++,m},i.prototype.bitLength=function(){var a=this.words[this.length-1],c=this._countBits(a);return(this.length-1)*26+c};function I(k){for(var a=new Array(k.bitLength()),c=0;c<a.length;c++){var m=c/26|0,y=c%26;a[c]=k.words[m]>>>y&1}return a}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var a=0,c=0;c<this.length;c++){var m=this._zeroBits(this.words[c]);if(a+=m,m!==26)break}return a},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(a){return this.negative!==0?this.abs().inotn(a).iaddn(1):this.clone()},i.prototype.fromTwos=function(a){return this.testn(a-1)?this.notn(a).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(a){for(;this.length<a.length;)this.words[this.length++]=0;for(var c=0;c<a.length;c++)this.words[c]=this.words[c]|a.words[c];return this._strip()},i.prototype.ior=function(a){return r((this.negative|a.negative)===0),this.iuor(a)},i.prototype.or=function(a){return this.length>a.length?this.clone().ior(a):a.clone().ior(this)},i.prototype.uor=function(a){return this.length>a.length?this.clone().iuor(a):a.clone().iuor(this)},i.prototype.iuand=function(a){var c;this.length>a.length?c=a:c=this;for(var m=0;m<c.length;m++)this.words[m]=this.words[m]&a.words[m];return this.length=c.length,this._strip()},i.prototype.iand=function(a){return r((this.negative|a.negative)===0),this.iuand(a)},i.prototype.and=function(a){return this.length>a.length?this.clone().iand(a):a.clone().iand(this)},i.prototype.uand=function(a){return this.length>a.length?this.clone().iuand(a):a.clone().iuand(this)},i.prototype.iuxor=function(a){var c,m;this.length>a.length?(c=this,m=a):(c=a,m=this);for(var y=0;y<m.length;y++)this.words[y]=c.words[y]^m.words[y];if(this!==c)for(;y<c.length;y++)this.words[y]=c.words[y];return this.length=c.length,this._strip()},i.prototype.ixor=function(a){return r((this.negative|a.negative)===0),this.iuxor(a)},i.prototype.xor=function(a){return this.length>a.length?this.clone().ixor(a):a.clone().ixor(this)},i.prototype.uxor=function(a){return this.length>a.length?this.clone().iuxor(a):a.clone().iuxor(this)},i.prototype.inotn=function(a){r(typeof a=="number"&&a>=0);var c=Math.ceil(a/26)|0,m=a%26;this._expand(c),m>0&&c--;for(var y=0;y<c;y++)this.words[y]=~this.words[y]&67108863;return m>0&&(this.words[y]=~this.words[y]&67108863>>26-m),this._strip()},i.prototype.notn=function(a){return this.clone().inotn(a)},i.prototype.setn=function(a,c){r(typeof a=="number"&&a>=0);var m=a/26|0,y=a%26;return this._expand(m+1),c?this.words[m]=this.words[m]|1<<y:this.words[m]=this.words[m]&~(1<<y),this._strip()},i.prototype.iadd=function(a){var c;if(this.negative!==0&&a.negative===0)return this.negative=0,c=this.isub(a),this.negative^=1,this._normSign();if(this.negative===0&&a.negative!==0)return a.negative=0,c=this.isub(a),a.negative=1,c._normSign();var m,y;this.length>a.length?(m=this,y=a):(m=a,y=this);for(var p=0,h=0;h<y.length;h++)c=(m.words[h]|0)+(y.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;for(;p!==0&&h<m.length;h++)c=(m.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;if(this.length=m.length,p!==0)this.words[this.length]=p,this.length++;else if(m!==this)for(;h<m.length;h++)this.words[h]=m.words[h];return this},i.prototype.add=function(a){var c;return a.negative!==0&&this.negative===0?(a.negative=0,c=this.sub(a),a.negative^=1,c):a.negative===0&&this.negative!==0?(this.negative=0,c=a.sub(this),this.negative=1,c):this.length>a.length?this.clone().iadd(a):a.clone().iadd(this)},i.prototype.isub=function(a){if(a.negative!==0){a.negative=0;var c=this.iadd(a);return a.negative=1,c._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(a),this.negative=1,this._normSign();var m=this.cmp(a);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var y,p;m>0?(y=this,p=a):(y=a,p=this);for(var h=0,w=0;w<p.length;w++)c=(y.words[w]|0)-(p.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;for(;h!==0&&w<y.length;w++)c=(y.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;if(h===0&&w<y.length&&y!==this)for(;w<y.length;w++)this.words[w]=y.words[w];return this.length=Math.max(this.length,w),y!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(a){return this.clone().isub(a)};function C(k,a,c){c.negative=a.negative^k.negative;var m=k.length+a.length|0;c.length=m,m=m-1|0;var y=k.words[0]|0,p=a.words[0]|0,h=y*p,w=h&67108863,g=h/67108864|0;c.words[0]=w;for(var f=1;f<m;f++){for(var v=g>>>26,O=g&67108863,M=Math.min(f,a.length-1),R=Math.max(0,f-k.length+1);R<=M;R++){var B=f-R|0;y=k.words[B]|0,p=a.words[R]|0,h=y*p+O,v+=h/67108864|0,O=h&67108863}c.words[f]=O|0,g=v|0}return g!==0?c.words[f]=g|0:c.length--,c._strip()}var E=function(a,c,m){var y=a.words,p=c.words,h=m.words,w=0,g,f,v,O=y[0]|0,M=O&8191,R=O>>>13,B=y[1]|0,G=B&8191,Z=B>>>13,se=y[2]|0,te=se&8191,ue=se>>>13,dt=y[3]|0,ve=dt&8191,xe=dt>>>13,an=y[4]|0,Ae=an&8191,Me=an>>>13,Gi=y[5]|0,De=Gi&8191,Be=Gi>>>13,Yu=y[6]|0,Ne=Yu&8191,Re=Yu>>>13,Qu=y[7]|0,je=Qu&8191,Fe=Qu>>>13,ec=y[8]|0,qe=ec&8191,Le=ec>>>13,tc=y[9]|0,Ue=tc&8191,$e=tc>>>13,rc=p[0]|0,Ge=rc&8191,Ve=rc>>>13,nc=p[1]|0,ze=nc&8191,We=nc>>>13,ic=p[2]|0,He=ic&8191,Ze=ic>>>13,oc=p[3]|0,Ke=oc&8191,Je=oc>>>13,sc=p[4]|0,Xe=sc&8191,Ye=sc>>>13,ac=p[5]|0,Qe=ac&8191,et=ac>>>13,uc=p[6]|0,tt=uc&8191,rt=uc>>>13,cc=p[7]|0,nt=cc&8191,it=cc>>>13,lc=p[8]|0,ot=lc&8191,st=lc>>>13,dc=p[9]|0,at=dc&8191,ut=dc>>>13;m.negative=a.negative^c.negative,m.length=19,g=Math.imul(M,Ge),f=Math.imul(M,Ve),f=f+Math.imul(R,Ge)|0,v=Math.imul(R,Ve);var Is=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Is>>>26)|0,Is&=67108863,g=Math.imul(G,Ge),f=Math.imul(G,Ve),f=f+Math.imul(Z,Ge)|0,v=Math.imul(Z,Ve),g=g+Math.imul(M,ze)|0,f=f+Math.imul(M,We)|0,f=f+Math.imul(R,ze)|0,v=v+Math.imul(R,We)|0;var Cs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Cs>>>26)|0,Cs&=67108863,g=Math.imul(te,Ge),f=Math.imul(te,Ve),f=f+Math.imul(ue,Ge)|0,v=Math.imul(ue,Ve),g=g+Math.imul(G,ze)|0,f=f+Math.imul(G,We)|0,f=f+Math.imul(Z,ze)|0,v=v+Math.imul(Z,We)|0,g=g+Math.imul(M,He)|0,f=f+Math.imul(M,Ze)|0,f=f+Math.imul(R,He)|0,v=v+Math.imul(R,Ze)|0;var Os=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Os>>>26)|0,Os&=67108863,g=Math.imul(ve,Ge),f=Math.imul(ve,Ve),f=f+Math.imul(xe,Ge)|0,v=Math.imul(xe,Ve),g=g+Math.imul(te,ze)|0,f=f+Math.imul(te,We)|0,f=f+Math.imul(ue,ze)|0,v=v+Math.imul(ue,We)|0,g=g+Math.imul(G,He)|0,f=f+Math.imul(G,Ze)|0,f=f+Math.imul(Z,He)|0,v=v+Math.imul(Z,Ze)|0,g=g+Math.imul(M,Ke)|0,f=f+Math.imul(M,Je)|0,f=f+Math.imul(R,Ke)|0,v=v+Math.imul(R,Je)|0;var Ms=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ms>>>26)|0,Ms&=67108863,g=Math.imul(Ae,Ge),f=Math.imul(Ae,Ve),f=f+Math.imul(Me,Ge)|0,v=Math.imul(Me,Ve),g=g+Math.imul(ve,ze)|0,f=f+Math.imul(ve,We)|0,f=f+Math.imul(xe,ze)|0,v=v+Math.imul(xe,We)|0,g=g+Math.imul(te,He)|0,f=f+Math.imul(te,Ze)|0,f=f+Math.imul(ue,He)|0,v=v+Math.imul(ue,Ze)|0,g=g+Math.imul(G,Ke)|0,f=f+Math.imul(G,Je)|0,f=f+Math.imul(Z,Ke)|0,v=v+Math.imul(Z,Je)|0,g=g+Math.imul(M,Xe)|0,f=f+Math.imul(M,Ye)|0,f=f+Math.imul(R,Xe)|0,v=v+Math.imul(R,Ye)|0;var Es=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Es>>>26)|0,Es&=67108863,g=Math.imul(De,Ge),f=Math.imul(De,Ve),f=f+Math.imul(Be,Ge)|0,v=Math.imul(Be,Ve),g=g+Math.imul(Ae,ze)|0,f=f+Math.imul(Ae,We)|0,f=f+Math.imul(Me,ze)|0,v=v+Math.imul(Me,We)|0,g=g+Math.imul(ve,He)|0,f=f+Math.imul(ve,Ze)|0,f=f+Math.imul(xe,He)|0,v=v+Math.imul(xe,Ze)|0,g=g+Math.imul(te,Ke)|0,f=f+Math.imul(te,Je)|0,f=f+Math.imul(ue,Ke)|0,v=v+Math.imul(ue,Je)|0,g=g+Math.imul(G,Xe)|0,f=f+Math.imul(G,Ye)|0,f=f+Math.imul(Z,Xe)|0,v=v+Math.imul(Z,Ye)|0,g=g+Math.imul(M,Qe)|0,f=f+Math.imul(M,et)|0,f=f+Math.imul(R,Qe)|0,v=v+Math.imul(R,et)|0;var Ps=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ps>>>26)|0,Ps&=67108863,g=Math.imul(Ne,Ge),f=Math.imul(Ne,Ve),f=f+Math.imul(Re,Ge)|0,v=Math.imul(Re,Ve),g=g+Math.imul(De,ze)|0,f=f+Math.imul(De,We)|0,f=f+Math.imul(Be,ze)|0,v=v+Math.imul(Be,We)|0,g=g+Math.imul(Ae,He)|0,f=f+Math.imul(Ae,Ze)|0,f=f+Math.imul(Me,He)|0,v=v+Math.imul(Me,Ze)|0,g=g+Math.imul(ve,Ke)|0,f=f+Math.imul(ve,Je)|0,f=f+Math.imul(xe,Ke)|0,v=v+Math.imul(xe,Je)|0,g=g+Math.imul(te,Xe)|0,f=f+Math.imul(te,Ye)|0,f=f+Math.imul(ue,Xe)|0,v=v+Math.imul(ue,Ye)|0,g=g+Math.imul(G,Qe)|0,f=f+Math.imul(G,et)|0,f=f+Math.imul(Z,Qe)|0,v=v+Math.imul(Z,et)|0,g=g+Math.imul(M,tt)|0,f=f+Math.imul(M,rt)|0,f=f+Math.imul(R,tt)|0,v=v+Math.imul(R,rt)|0;var Ds=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ds>>>26)|0,Ds&=67108863,g=Math.imul(je,Ge),f=Math.imul(je,Ve),f=f+Math.imul(Fe,Ge)|0,v=Math.imul(Fe,Ve),g=g+Math.imul(Ne,ze)|0,f=f+Math.imul(Ne,We)|0,f=f+Math.imul(Re,ze)|0,v=v+Math.imul(Re,We)|0,g=g+Math.imul(De,He)|0,f=f+Math.imul(De,Ze)|0,f=f+Math.imul(Be,He)|0,v=v+Math.imul(Be,Ze)|0,g=g+Math.imul(Ae,Ke)|0,f=f+Math.imul(Ae,Je)|0,f=f+Math.imul(Me,Ke)|0,v=v+Math.imul(Me,Je)|0,g=g+Math.imul(ve,Xe)|0,f=f+Math.imul(ve,Ye)|0,f=f+Math.imul(xe,Xe)|0,v=v+Math.imul(xe,Ye)|0,g=g+Math.imul(te,Qe)|0,f=f+Math.imul(te,et)|0,f=f+Math.imul(ue,Qe)|0,v=v+Math.imul(ue,et)|0,g=g+Math.imul(G,tt)|0,f=f+Math.imul(G,rt)|0,f=f+Math.imul(Z,tt)|0,v=v+Math.imul(Z,rt)|0,g=g+Math.imul(M,nt)|0,f=f+Math.imul(M,it)|0,f=f+Math.imul(R,nt)|0,v=v+Math.imul(R,it)|0;var Bs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Bs>>>26)|0,Bs&=67108863,g=Math.imul(qe,Ge),f=Math.imul(qe,Ve),f=f+Math.imul(Le,Ge)|0,v=Math.imul(Le,Ve),g=g+Math.imul(je,ze)|0,f=f+Math.imul(je,We)|0,f=f+Math.imul(Fe,ze)|0,v=v+Math.imul(Fe,We)|0,g=g+Math.imul(Ne,He)|0,f=f+Math.imul(Ne,Ze)|0,f=f+Math.imul(Re,He)|0,v=v+Math.imul(Re,Ze)|0,g=g+Math.imul(De,Ke)|0,f=f+Math.imul(De,Je)|0,f=f+Math.imul(Be,Ke)|0,v=v+Math.imul(Be,Je)|0,g=g+Math.imul(Ae,Xe)|0,f=f+Math.imul(Ae,Ye)|0,f=f+Math.imul(Me,Xe)|0,v=v+Math.imul(Me,Ye)|0,g=g+Math.imul(ve,Qe)|0,f=f+Math.imul(ve,et)|0,f=f+Math.imul(xe,Qe)|0,v=v+Math.imul(xe,et)|0,g=g+Math.imul(te,tt)|0,f=f+Math.imul(te,rt)|0,f=f+Math.imul(ue,tt)|0,v=v+Math.imul(ue,rt)|0,g=g+Math.imul(G,nt)|0,f=f+Math.imul(G,it)|0,f=f+Math.imul(Z,nt)|0,v=v+Math.imul(Z,it)|0,g=g+Math.imul(M,ot)|0,f=f+Math.imul(M,st)|0,f=f+Math.imul(R,ot)|0,v=v+Math.imul(R,st)|0;var Ns=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ns>>>26)|0,Ns&=67108863,g=Math.imul(Ue,Ge),f=Math.imul(Ue,Ve),f=f+Math.imul($e,Ge)|0,v=Math.imul($e,Ve),g=g+Math.imul(qe,ze)|0,f=f+Math.imul(qe,We)|0,f=f+Math.imul(Le,ze)|0,v=v+Math.imul(Le,We)|0,g=g+Math.imul(je,He)|0,f=f+Math.imul(je,Ze)|0,f=f+Math.imul(Fe,He)|0,v=v+Math.imul(Fe,Ze)|0,g=g+Math.imul(Ne,Ke)|0,f=f+Math.imul(Ne,Je)|0,f=f+Math.imul(Re,Ke)|0,v=v+Math.imul(Re,Je)|0,g=g+Math.imul(De,Xe)|0,f=f+Math.imul(De,Ye)|0,f=f+Math.imul(Be,Xe)|0,v=v+Math.imul(Be,Ye)|0,g=g+Math.imul(Ae,Qe)|0,f=f+Math.imul(Ae,et)|0,f=f+Math.imul(Me,Qe)|0,v=v+Math.imul(Me,et)|0,g=g+Math.imul(ve,tt)|0,f=f+Math.imul(ve,rt)|0,f=f+Math.imul(xe,tt)|0,v=v+Math.imul(xe,rt)|0,g=g+Math.imul(te,nt)|0,f=f+Math.imul(te,it)|0,f=f+Math.imul(ue,nt)|0,v=v+Math.imul(ue,it)|0,g=g+Math.imul(G,ot)|0,f=f+Math.imul(G,st)|0,f=f+Math.imul(Z,ot)|0,v=v+Math.imul(Z,st)|0,g=g+Math.imul(M,at)|0,f=f+Math.imul(M,ut)|0,f=f+Math.imul(R,at)|0,v=v+Math.imul(R,ut)|0;var Rs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Rs>>>26)|0,Rs&=67108863,g=Math.imul(Ue,ze),f=Math.imul(Ue,We),f=f+Math.imul($e,ze)|0,v=Math.imul($e,We),g=g+Math.imul(qe,He)|0,f=f+Math.imul(qe,Ze)|0,f=f+Math.imul(Le,He)|0,v=v+Math.imul(Le,Ze)|0,g=g+Math.imul(je,Ke)|0,f=f+Math.imul(je,Je)|0,f=f+Math.imul(Fe,Ke)|0,v=v+Math.imul(Fe,Je)|0,g=g+Math.imul(Ne,Xe)|0,f=f+Math.imul(Ne,Ye)|0,f=f+Math.imul(Re,Xe)|0,v=v+Math.imul(Re,Ye)|0,g=g+Math.imul(De,Qe)|0,f=f+Math.imul(De,et)|0,f=f+Math.imul(Be,Qe)|0,v=v+Math.imul(Be,et)|0,g=g+Math.imul(Ae,tt)|0,f=f+Math.imul(Ae,rt)|0,f=f+Math.imul(Me,tt)|0,v=v+Math.imul(Me,rt)|0,g=g+Math.imul(ve,nt)|0,f=f+Math.imul(ve,it)|0,f=f+Math.imul(xe,nt)|0,v=v+Math.imul(xe,it)|0,g=g+Math.imul(te,ot)|0,f=f+Math.imul(te,st)|0,f=f+Math.imul(ue,ot)|0,v=v+Math.imul(ue,st)|0,g=g+Math.imul(G,at)|0,f=f+Math.imul(G,ut)|0,f=f+Math.imul(Z,at)|0,v=v+Math.imul(Z,ut)|0;var js=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(js>>>26)|0,js&=67108863,g=Math.imul(Ue,He),f=Math.imul(Ue,Ze),f=f+Math.imul($e,He)|0,v=Math.imul($e,Ze),g=g+Math.imul(qe,Ke)|0,f=f+Math.imul(qe,Je)|0,f=f+Math.imul(Le,Ke)|0,v=v+Math.imul(Le,Je)|0,g=g+Math.imul(je,Xe)|0,f=f+Math.imul(je,Ye)|0,f=f+Math.imul(Fe,Xe)|0,v=v+Math.imul(Fe,Ye)|0,g=g+Math.imul(Ne,Qe)|0,f=f+Math.imul(Ne,et)|0,f=f+Math.imul(Re,Qe)|0,v=v+Math.imul(Re,et)|0,g=g+Math.imul(De,tt)|0,f=f+Math.imul(De,rt)|0,f=f+Math.imul(Be,tt)|0,v=v+Math.imul(Be,rt)|0,g=g+Math.imul(Ae,nt)|0,f=f+Math.imul(Ae,it)|0,f=f+Math.imul(Me,nt)|0,v=v+Math.imul(Me,it)|0,g=g+Math.imul(ve,ot)|0,f=f+Math.imul(ve,st)|0,f=f+Math.imul(xe,ot)|0,v=v+Math.imul(xe,st)|0,g=g+Math.imul(te,at)|0,f=f+Math.imul(te,ut)|0,f=f+Math.imul(ue,at)|0,v=v+Math.imul(ue,ut)|0;var Fs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Fs>>>26)|0,Fs&=67108863,g=Math.imul(Ue,Ke),f=Math.imul(Ue,Je),f=f+Math.imul($e,Ke)|0,v=Math.imul($e,Je),g=g+Math.imul(qe,Xe)|0,f=f+Math.imul(qe,Ye)|0,f=f+Math.imul(Le,Xe)|0,v=v+Math.imul(Le,Ye)|0,g=g+Math.imul(je,Qe)|0,f=f+Math.imul(je,et)|0,f=f+Math.imul(Fe,Qe)|0,v=v+Math.imul(Fe,et)|0,g=g+Math.imul(Ne,tt)|0,f=f+Math.imul(Ne,rt)|0,f=f+Math.imul(Re,tt)|0,v=v+Math.imul(Re,rt)|0,g=g+Math.imul(De,nt)|0,f=f+Math.imul(De,it)|0,f=f+Math.imul(Be,nt)|0,v=v+Math.imul(Be,it)|0,g=g+Math.imul(Ae,ot)|0,f=f+Math.imul(Ae,st)|0,f=f+Math.imul(Me,ot)|0,v=v+Math.imul(Me,st)|0,g=g+Math.imul(ve,at)|0,f=f+Math.imul(ve,ut)|0,f=f+Math.imul(xe,at)|0,v=v+Math.imul(xe,ut)|0;var qs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(qs>>>26)|0,qs&=67108863,g=Math.imul(Ue,Xe),f=Math.imul(Ue,Ye),f=f+Math.imul($e,Xe)|0,v=Math.imul($e,Ye),g=g+Math.imul(qe,Qe)|0,f=f+Math.imul(qe,et)|0,f=f+Math.imul(Le,Qe)|0,v=v+Math.imul(Le,et)|0,g=g+Math.imul(je,tt)|0,f=f+Math.imul(je,rt)|0,f=f+Math.imul(Fe,tt)|0,v=v+Math.imul(Fe,rt)|0,g=g+Math.imul(Ne,nt)|0,f=f+Math.imul(Ne,it)|0,f=f+Math.imul(Re,nt)|0,v=v+Math.imul(Re,it)|0,g=g+Math.imul(De,ot)|0,f=f+Math.imul(De,st)|0,f=f+Math.imul(Be,ot)|0,v=v+Math.imul(Be,st)|0,g=g+Math.imul(Ae,at)|0,f=f+Math.imul(Ae,ut)|0,f=f+Math.imul(Me,at)|0,v=v+Math.imul(Me,ut)|0;var Ls=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ls>>>26)|0,Ls&=67108863,g=Math.imul(Ue,Qe),f=Math.imul(Ue,et),f=f+Math.imul($e,Qe)|0,v=Math.imul($e,et),g=g+Math.imul(qe,tt)|0,f=f+Math.imul(qe,rt)|0,f=f+Math.imul(Le,tt)|0,v=v+Math.imul(Le,rt)|0,g=g+Math.imul(je,nt)|0,f=f+Math.imul(je,it)|0,f=f+Math.imul(Fe,nt)|0,v=v+Math.imul(Fe,it)|0,g=g+Math.imul(Ne,ot)|0,f=f+Math.imul(Ne,st)|0,f=f+Math.imul(Re,ot)|0,v=v+Math.imul(Re,st)|0,g=g+Math.imul(De,at)|0,f=f+Math.imul(De,ut)|0,f=f+Math.imul(Be,at)|0,v=v+Math.imul(Be,ut)|0;var Us=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Us>>>26)|0,Us&=67108863,g=Math.imul(Ue,tt),f=Math.imul(Ue,rt),f=f+Math.imul($e,tt)|0,v=Math.imul($e,rt),g=g+Math.imul(qe,nt)|0,f=f+Math.imul(qe,it)|0,f=f+Math.imul(Le,nt)|0,v=v+Math.imul(Le,it)|0,g=g+Math.imul(je,ot)|0,f=f+Math.imul(je,st)|0,f=f+Math.imul(Fe,ot)|0,v=v+Math.imul(Fe,st)|0,g=g+Math.imul(Ne,at)|0,f=f+Math.imul(Ne,ut)|0,f=f+Math.imul(Re,at)|0,v=v+Math.imul(Re,ut)|0;var $s=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+($s>>>26)|0,$s&=67108863,g=Math.imul(Ue,nt),f=Math.imul(Ue,it),f=f+Math.imul($e,nt)|0,v=Math.imul($e,it),g=g+Math.imul(qe,ot)|0,f=f+Math.imul(qe,st)|0,f=f+Math.imul(Le,ot)|0,v=v+Math.imul(Le,st)|0,g=g+Math.imul(je,at)|0,f=f+Math.imul(je,ut)|0,f=f+Math.imul(Fe,at)|0,v=v+Math.imul(Fe,ut)|0;var Gs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Gs>>>26)|0,Gs&=67108863,g=Math.imul(Ue,ot),f=Math.imul(Ue,st),f=f+Math.imul($e,ot)|0,v=Math.imul($e,st),g=g+Math.imul(qe,at)|0,f=f+Math.imul(qe,ut)|0,f=f+Math.imul(Le,at)|0,v=v+Math.imul(Le,ut)|0;var Vs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Vs>>>26)|0,Vs&=67108863,g=Math.imul(Ue,at),f=Math.imul(Ue,ut),f=f+Math.imul($e,at)|0,v=Math.imul($e,ut);var zs=(w+g|0)+((f&8191)<<13)|0;return w=(v+(f>>>13)|0)+(zs>>>26)|0,zs&=67108863,h[0]=Is,h[1]=Cs,h[2]=Os,h[3]=Ms,h[4]=Es,h[5]=Ps,h[6]=Ds,h[7]=Bs,h[8]=Ns,h[9]=Rs,h[10]=js,h[11]=Fs,h[12]=qs,h[13]=Ls,h[14]=Us,h[15]=$s,h[16]=Gs,h[17]=Vs,h[18]=zs,w!==0&&(h[19]=w,m.length++),m};Math.imul||(E=C);function P(k,a,c){c.negative=a.negative^k.negative,c.length=k.length+a.length;for(var m=0,y=0,p=0;p<c.length-1;p++){var h=y;y=0;for(var w=m&67108863,g=Math.min(p,a.length-1),f=Math.max(0,p-k.length+1);f<=g;f++){var v=p-f,O=k.words[v]|0,M=a.words[f]|0,R=O*M,B=R&67108863;h=h+(R/67108864|0)|0,B=B+w|0,w=B&67108863,h=h+(B>>>26)|0,y+=h>>>26,h&=67108863}c.words[p]=w,m=h,h=y}return m!==0?c.words[p]=m:c.length--,c._strip()}function D(k,a,c){return P(k,a,c)}i.prototype.mulTo=function(a,c){var m,y=this.length+a.length;return this.length===10&&a.length===10?m=E(this,a,c):y<63?m=C(this,a,c):y<1024?m=P(this,a,c):m=D(this,a,c),m};function L(k,a){this.x=k,this.y=a}L.prototype.makeRBT=function(a){for(var c=new Array(a),m=i.prototype._countBits(a)-1,y=0;y<a;y++)c[y]=this.revBin(y,m,a);return c},L.prototype.revBin=function(a,c,m){if(a===0||a===m-1)return a;for(var y=0,p=0;p<c;p++)y|=(a&1)<<c-p-1,a>>=1;return y},L.prototype.permute=function(a,c,m,y,p,h){for(var w=0;w<h;w++)y[w]=c[a[w]],p[w]=m[a[w]]},L.prototype.transform=function(a,c,m,y,p,h){this.permute(h,a,c,m,y,p);for(var w=1;w<p;w<<=1)for(var g=w<<1,f=Math.cos(2*Math.PI/g),v=Math.sin(2*Math.PI/g),O=0;O<p;O+=g)for(var M=f,R=v,B=0;B<w;B++){var G=m[O+B],Z=y[O+B],se=m[O+B+w],te=y[O+B+w],ue=M*se-R*te;te=M*te+R*se,se=ue,m[O+B]=G+se,y[O+B]=Z+te,m[O+B+w]=G-se,y[O+B+w]=Z-te,B!==g&&(ue=f*M-v*R,R=f*R+v*M,M=ue)}},L.prototype.guessLen13b=function(a,c){var m=Math.max(c,a)|1,y=m&1,p=0;for(m=m/2|0;m;m=m>>>1)p++;return 1<<p+1+y},L.prototype.conjugate=function(a,c,m){if(!(m<=1))for(var y=0;y<m/2;y++){var p=a[y];a[y]=a[m-y-1],a[m-y-1]=p,p=c[y],c[y]=-c[m-y-1],c[m-y-1]=-p}},L.prototype.normalize13b=function(a,c){for(var m=0,y=0;y<c/2;y++){var p=Math.round(a[2*y+1]/c)*8192+Math.round(a[2*y]/c)+m;a[y]=p&67108863,p<67108864?m=0:m=p/67108864|0}return a},L.prototype.convert13b=function(a,c,m,y){for(var p=0,h=0;h<c;h++)p=p+(a[h]|0),m[2*h]=p&8191,p=p>>>13,m[2*h+1]=p&8191,p=p>>>13;for(h=2*c;h<y;++h)m[h]=0;r(p===0),r((p&-8192)===0)},L.prototype.stub=function(a){for(var c=new Array(a),m=0;m<a;m++)c[m]=0;return c},L.prototype.mulp=function(a,c,m){var y=2*this.guessLen13b(a.length,c.length),p=this.makeRBT(y),h=this.stub(y),w=new Array(y),g=new Array(y),f=new Array(y),v=new Array(y),O=new Array(y),M=new Array(y),R=m.words;R.length=y,this.convert13b(a.words,a.length,w,y),this.convert13b(c.words,c.length,v,y),this.transform(w,h,g,f,y,p),this.transform(v,h,O,M,y,p);for(var B=0;B<y;B++){var G=g[B]*O[B]-f[B]*M[B];f[B]=g[B]*M[B]+f[B]*O[B],g[B]=G}return this.conjugate(g,f,y),this.transform(g,f,R,h,y,p),this.conjugate(R,h,y),this.normalize13b(R,y),m.negative=a.negative^c.negative,m.length=a.length+c.length,m._strip()},i.prototype.mul=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),this.mulTo(a,c)},i.prototype.mulf=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),D(this,a,c)},i.prototype.imul=function(a){return this.clone().mulTo(a,this)},i.prototype.imuln=function(a){var c=a<0;c&&(a=-a),r(typeof a=="number"),r(a<67108864);for(var m=0,y=0;y<this.length;y++){var p=(this.words[y]|0)*a,h=(p&67108863)+(m&67108863);m>>=26,m+=p/67108864|0,m+=h>>>26,this.words[y]=h&67108863}return m!==0&&(this.words[y]=m,this.length++),c?this.ineg():this},i.prototype.muln=function(a){return this.clone().imuln(a)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(a){var c=I(a);if(c.length===0)return new i(1);for(var m=this,y=0;y<c.length&&c[y]===0;y++,m=m.sqr());if(++y<c.length)for(var p=m.sqr();y<c.length;y++,p=p.sqr())c[y]!==0&&(m=m.mul(p));return m},i.prototype.iushln=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=67108863>>>26-c<<26-c,p;if(c!==0){var h=0;for(p=0;p<this.length;p++){var w=this.words[p]&y,g=(this.words[p]|0)-w<<c;this.words[p]=g|h,h=w>>>26-c}h&&(this.words[p]=h,this.length++)}if(m!==0){for(p=this.length-1;p>=0;p--)this.words[p+m]=this.words[p];for(p=0;p<m;p++)this.words[p]=0;this.length+=m}return this._strip()},i.prototype.ishln=function(a){return r(this.negative===0),this.iushln(a)},i.prototype.iushrn=function(a,c,m){r(typeof a=="number"&&a>=0);var y;c?y=(c-c%26)/26:y=0;var p=a%26,h=Math.min((a-p)/26,this.length),w=67108863^67108863>>>p<<p,g=m;if(y-=h,y=Math.max(0,y),g){for(var f=0;f<h;f++)g.words[f]=this.words[f];g.length=h}if(h!==0)if(this.length>h)for(this.length-=h,f=0;f<this.length;f++)this.words[f]=this.words[f+h];else this.words[0]=0,this.length=1;var v=0;for(f=this.length-1;f>=0&&(v!==0||f>=y);f--){var O=this.words[f]|0;this.words[f]=v<<26-p|O>>>p,v=O&w}return g&&v!==0&&(g.words[g.length++]=v),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(a,c,m){return r(this.negative===0),this.iushrn(a,c,m)},i.prototype.shln=function(a){return this.clone().ishln(a)},i.prototype.ushln=function(a){return this.clone().iushln(a)},i.prototype.shrn=function(a){return this.clone().ishrn(a)},i.prototype.ushrn=function(a){return this.clone().iushrn(a)},i.prototype.testn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return!1;var p=this.words[m];return!!(p&y)},i.prototype.imaskn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(c!==0&&m++,this.length=Math.min(m,this.length),c!==0){var y=67108863^67108863>>>c<<c;this.words[this.length-1]&=y}return this._strip()},i.prototype.maskn=function(a){return this.clone().imaskn(a)},i.prototype.iaddn=function(a){return r(typeof a=="number"),r(a<67108864),a<0?this.isubn(-a):this.negative!==0?this.length===1&&(this.words[0]|0)<=a?(this.words[0]=a-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(a),this.negative=1,this):this._iaddn(a)},i.prototype._iaddn=function(a){this.words[0]+=a;for(var c=0;c<this.length&&this.words[c]>=67108864;c++)this.words[c]-=67108864,c===this.length-1?this.words[c+1]=1:this.words[c+1]++;return this.length=Math.max(this.length,c+1),this},i.prototype.isubn=function(a){if(r(typeof a=="number"),r(a<67108864),a<0)return this.iaddn(-a);if(this.negative!==0)return this.negative=0,this.iaddn(a),this.negative=1,this;if(this.words[0]-=a,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var c=0;c<this.length&&this.words[c]<0;c++)this.words[c]+=67108864,this.words[c+1]-=1;return this._strip()},i.prototype.addn=function(a){return this.clone().iaddn(a)},i.prototype.subn=function(a){return this.clone().isubn(a)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(a,c,m){var y=a.length+m,p;this._expand(y);var h,w=0;for(p=0;p<a.length;p++){h=(this.words[p+m]|0)+w;var g=(a.words[p]|0)*c;h-=g&67108863,w=(h>>26)-(g/67108864|0),this.words[p+m]=h&67108863}for(;p<this.length-m;p++)h=(this.words[p+m]|0)+w,w=h>>26,this.words[p+m]=h&67108863;if(w===0)return this._strip();for(r(w===-1),w=0,p=0;p<this.length;p++)h=-(this.words[p]|0)+w,w=h>>26,this.words[p]=h&67108863;return this.negative=1,this._strip()},i.prototype._wordDiv=function(a,c){var m=this.length-a.length,y=this.clone(),p=a,h=p.words[p.length-1]|0,w=this._countBits(h);m=26-w,m!==0&&(p=p.ushln(m),y.iushln(m),h=p.words[p.length-1]|0);var g=y.length-p.length,f;if(c!=="mod"){f=new i(null),f.length=g+1,f.words=new Array(f.length);for(var v=0;v<f.length;v++)f.words[v]=0}var O=y.clone()._ishlnsubmul(p,1,g);O.negative===0&&(y=O,f&&(f.words[g]=1));for(var M=g-1;M>=0;M--){var R=(y.words[p.length+M]|0)*67108864+(y.words[p.length+M-1]|0);for(R=Math.min(R/h|0,67108863),y._ishlnsubmul(p,R,M);y.negative!==0;)R--,y.negative=0,y._ishlnsubmul(p,1,M),y.isZero()||(y.negative^=1);f&&(f.words[M]=R)}return f&&f._strip(),y._strip(),c!=="div"&&m!==0&&y.iushrn(m),{div:f||null,mod:y}},i.prototype.divmod=function(a,c,m){if(r(!a.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var y,p,h;return this.negative!==0&&a.negative===0?(h=this.neg().divmod(a,c),c!=="mod"&&(y=h.div.neg()),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.iadd(a)),{div:y,mod:p}):this.negative===0&&a.negative!==0?(h=this.divmod(a.neg(),c),c!=="mod"&&(y=h.div.neg()),{div:y,mod:h.mod}):this.negative&a.negative?(h=this.neg().divmod(a.neg(),c),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.isub(a)),{div:h.div,mod:p}):a.length>this.length||this.cmp(a)<0?{div:new i(0),mod:this}:a.length===1?c==="div"?{div:this.divn(a.words[0]),mod:null}:c==="mod"?{div:null,mod:new i(this.modrn(a.words[0]))}:{div:this.divn(a.words[0]),mod:new i(this.modrn(a.words[0]))}:this._wordDiv(a,c)},i.prototype.div=function(a){return this.divmod(a,"div",!1).div},i.prototype.mod=function(a){return this.divmod(a,"mod",!1).mod},i.prototype.umod=function(a){return this.divmod(a,"mod",!0).mod},i.prototype.divRound=function(a){var c=this.divmod(a);if(c.mod.isZero())return c.div;var m=c.div.negative!==0?c.mod.isub(a):c.mod,y=a.ushrn(1),p=a.andln(1),h=m.cmp(y);return h<0||p===1&&h===0?c.div:c.div.negative!==0?c.div.isubn(1):c.div.iaddn(1)},i.prototype.modrn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=(1<<26)%a,y=0,p=this.length-1;p>=0;p--)y=(m*y+(this.words[p]|0))%a;return c?-y:y},i.prototype.modn=function(a){return this.modrn(a)},i.prototype.idivn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=0,y=this.length-1;y>=0;y--){var p=(this.words[y]|0)+m*67108864;this.words[y]=p/a|0,m=p%a}return this._strip(),c?this.ineg():this},i.prototype.divn=function(a){return this.clone().idivn(a)},i.prototype.egcd=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=new i(0),w=new i(1),g=0;c.isEven()&&m.isEven();)c.iushrn(1),m.iushrn(1),++g;for(var f=m.clone(),v=c.clone();!c.isZero();){for(var O=0,M=1;!(c.words[0]&M)&&O<26;++O,M<<=1);if(O>0)for(c.iushrn(O);O-- >0;)(y.isOdd()||p.isOdd())&&(y.iadd(f),p.isub(v)),y.iushrn(1),p.iushrn(1);for(var R=0,B=1;!(m.words[0]&B)&&R<26;++R,B<<=1);if(R>0)for(m.iushrn(R);R-- >0;)(h.isOdd()||w.isOdd())&&(h.iadd(f),w.isub(v)),h.iushrn(1),w.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(h),p.isub(w)):(m.isub(c),h.isub(y),w.isub(p))}return{a:h,b:w,gcd:m.iushln(g)}},i.prototype._invmp=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=m.clone();c.cmpn(1)>0&&m.cmpn(1)>0;){for(var w=0,g=1;!(c.words[0]&g)&&w<26;++w,g<<=1);if(w>0)for(c.iushrn(w);w-- >0;)y.isOdd()&&y.iadd(h),y.iushrn(1);for(var f=0,v=1;!(m.words[0]&v)&&f<26;++f,v<<=1);if(f>0)for(m.iushrn(f);f-- >0;)p.isOdd()&&p.iadd(h),p.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(p)):(m.isub(c),p.isub(y))}var O;return c.cmpn(1)===0?O=y:O=p,O.cmpn(0)<0&&O.iadd(a),O},i.prototype.gcd=function(a){if(this.isZero())return a.abs();if(a.isZero())return this.abs();var c=this.clone(),m=a.clone();c.negative=0,m.negative=0;for(var y=0;c.isEven()&&m.isEven();y++)c.iushrn(1),m.iushrn(1);do{for(;c.isEven();)c.iushrn(1);for(;m.isEven();)m.iushrn(1);var p=c.cmp(m);if(p<0){var h=c;c=m,m=h}else if(p===0||m.cmpn(1)===0)break;c.isub(m)}while(!0);return m.iushln(y)},i.prototype.invm=function(a){return this.egcd(a).a.umod(a)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(a){return this.words[0]&a},i.prototype.bincn=function(a){r(typeof a=="number");var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return this._expand(m+1),this.words[m]|=y,this;for(var p=y,h=m;p!==0&&h<this.length;h++){var w=this.words[h]|0;w+=p,p=w>>>26,w&=67108863,this.words[h]=w}return p!==0&&(this.words[h]=p,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(a){var c=a<0;if(this.negative!==0&&!c)return-1;if(this.negative===0&&c)return 1;this._strip();var m;if(this.length>1)m=1;else{c&&(a=-a),r(a<=67108863,"Number is too big");var y=this.words[0]|0;m=y===a?0:y<a?-1:1}return this.negative!==0?-m|0:m},i.prototype.cmp=function(a){if(this.negative!==0&&a.negative===0)return-1;if(this.negative===0&&a.negative!==0)return 1;var c=this.ucmp(a);return this.negative!==0?-c|0:c},i.prototype.ucmp=function(a){if(this.length>a.length)return 1;if(this.length<a.length)return-1;for(var c=0,m=this.length-1;m>=0;m--){var y=this.words[m]|0,p=a.words[m]|0;if(y!==p){y<p?c=-1:y>p&&(c=1);break}}return c},i.prototype.gtn=function(a){return this.cmpn(a)===1},i.prototype.gt=function(a){return this.cmp(a)===1},i.prototype.gten=function(a){return this.cmpn(a)>=0},i.prototype.gte=function(a){return this.cmp(a)>=0},i.prototype.ltn=function(a){return this.cmpn(a)===-1},i.prototype.lt=function(a){return this.cmp(a)===-1},i.prototype.lten=function(a){return this.cmpn(a)<=0},i.prototype.lte=function(a){return this.cmp(a)<=0},i.prototype.eqn=function(a){return this.cmpn(a)===0},i.prototype.eq=function(a){return this.cmp(a)===0},i.red=function(a){return new j(a)},i.prototype.toRed=function(a){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),a.convertTo(this)._forceRed(a)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(a){return this.red=a,this},i.prototype.forceRed=function(a){return r(!this.red,"Already a number in reduction context"),this._forceRed(a)},i.prototype.redAdd=function(a){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,a)},i.prototype.redIAdd=function(a){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,a)},i.prototype.redSub=function(a){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,a)},i.prototype.redISub=function(a){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,a)},i.prototype.redShl=function(a){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,a)},i.prototype.redMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.mul(this,a)},i.prototype.redIMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.imul(this,a)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(a){return r(this.red&&!a.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,a)};var H={k256:null,p224:null,p192:null,p25519:null};function W(k,a){this.name=k,this.p=new i(a,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}W.prototype._tmp=function(){var a=new i(null);return a.words=new Array(Math.ceil(this.n/13)),a},W.prototype.ireduce=function(a){var c=a,m;do this.split(c,this.tmp),c=this.imulK(c),c=c.iadd(this.tmp),m=c.bitLength();while(m>this.n);var y=m<this.n?-1:c.ucmp(this.p);return y===0?(c.words[0]=0,c.length=1):y>0?c.isub(this.p):c.strip!==void 0?c.strip():c._strip(),c},W.prototype.split=function(a,c){a.iushrn(this.n,0,c)},W.prototype.imulK=function(a){return a.imul(this.k)};function K(){W.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(K,W),K.prototype.split=function(a,c){for(var m=4194303,y=Math.min(a.length,9),p=0;p<y;p++)c.words[p]=a.words[p];if(c.length=y,a.length<=9){a.words[0]=0,a.length=1;return}var h=a.words[9];for(c.words[c.length++]=h&m,p=10;p<a.length;p++){var w=a.words[p]|0;a.words[p-10]=(w&m)<<4|h>>>22,h=w}h>>>=22,a.words[p-10]=h,h===0&&a.length>10?a.length-=10:a.length-=9},K.prototype.imulK=function(a){a.words[a.length]=0,a.words[a.length+1]=0,a.length+=2;for(var c=0,m=0;m<a.length;m++){var y=a.words[m]|0;c+=y*977,a.words[m]=c&67108863,c=y*64+(c/67108864|0)}return a.words[a.length-1]===0&&(a.length--,a.words[a.length-1]===0&&a.length--),a};function F(){W.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(F,W);function U(){W.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(U,W);function N(){W.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(N,W),N.prototype.imulK=function(a){for(var c=0,m=0;m<a.length;m++){var y=(a.words[m]|0)*19+c,p=y&67108863;y>>>=26,a.words[m]=p,c=y}return c!==0&&(a.words[a.length++]=c),a},i._prime=function(a){if(H[a])return H[a];var c;if(a==="k256")c=new K;else if(a==="p224")c=new F;else if(a==="p192")c=new U;else if(a==="p25519")c=new N;else throw new Error("Unknown prime "+a);return H[a]=c,c};function j(k){if(typeof k=="string"){var a=i._prime(k);this.m=a.p,this.prime=a}else r(k.gtn(1),"modulus must be greater than 1"),this.m=k,this.prime=null}j.prototype._verify1=function(a){r(a.negative===0,"red works only with positives"),r(a.red,"red works only with red numbers")},j.prototype._verify2=function(a,c){r((a.negative|c.negative)===0,"red works only with positives"),r(a.red&&a.red===c.red,"red works only with red numbers")},j.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(d(a,a.umod(this.m)._forceRed(this)),a)},j.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},j.prototype.add=function(a,c){this._verify2(a,c);var m=a.add(c);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},j.prototype.iadd=function(a,c){this._verify2(a,c);var m=a.iadd(c);return m.cmp(this.m)>=0&&m.isub(this.m),m},j.prototype.sub=function(a,c){this._verify2(a,c);var m=a.sub(c);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},j.prototype.isub=function(a,c){this._verify2(a,c);var m=a.isub(c);return m.cmpn(0)<0&&m.iadd(this.m),m},j.prototype.shl=function(a,c){return this._verify1(a),this.imod(a.ushln(c))},j.prototype.imul=function(a,c){return this._verify2(a,c),this.imod(a.imul(c))},j.prototype.mul=function(a,c){return this._verify2(a,c),this.imod(a.mul(c))},j.prototype.isqr=function(a){return this.imul(a,a.clone())},j.prototype.sqr=function(a){return this.mul(a,a)},j.prototype.sqrt=function(a){if(a.isZero())return a.clone();var c=this.m.andln(3);if(r(c%2===1),c===3){var m=this.m.add(new i(1)).iushrn(2);return this.pow(a,m)}for(var y=this.m.subn(1),p=0;!y.isZero()&&y.andln(1)===0;)p++,y.iushrn(1);r(!y.isZero());var h=new i(1).toRed(this),w=h.redNeg(),g=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);this.pow(f,g).cmp(w)!==0;)f.redIAdd(w);for(var v=this.pow(f,y),O=this.pow(a,y.addn(1).iushrn(1)),M=this.pow(a,y),R=p;M.cmp(h)!==0;){for(var B=M,G=0;B.cmp(h)!==0;G++)B=B.redSqr();r(G<R);var Z=this.pow(v,new i(1).iushln(R-G-1));O=O.redMul(Z),v=Z.redSqr(),M=M.redMul(v),R=G}return O},j.prototype.invm=function(a){var c=a._invmp(this.m);return c.negative!==0?(c.negative=0,this.imod(c).redNeg()):this.imod(c)},j.prototype.pow=function(a,c){if(c.isZero())return new i(1).toRed(this);if(c.cmpn(1)===0)return a.clone();var m=4,y=new Array(1<<m);y[0]=new i(1).toRed(this),y[1]=a;for(var p=2;p<y.length;p++)y[p]=this.mul(y[p-1],a);var h=y[0],w=0,g=0,f=c.bitLength()%26;for(f===0&&(f=26),p=c.length-1;p>=0;p--){for(var v=c.words[p],O=f-1;O>=0;O--){var M=v>>O&1;if(h!==y[0]&&(h=this.sqr(h)),M===0&&w===0){g=0;continue}w<<=1,w|=M,g++,!(g!==m&&(p!==0||O!==0))&&(h=this.mul(h,y[w]),g=0,w=0)}f=26}return h},j.prototype.convertTo=function(a){var c=a.umod(this.m);return c===a?c.clone():c},j.prototype.convertFrom=function(a){var c=a.clone();return c.red=null,c},i.mont=function(a){return new S(a)};function S(k){j.call(this,k),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(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)}n(S,j),S.prototype.convertTo=function(a){return this.imod(a.ushln(this.shift))},S.prototype.convertFrom=function(a){var c=this.imod(a.mul(this.rinv));return c.red=null,c},S.prototype.imul=function(a,c){if(a.isZero()||c.isZero())return a.words[0]=0,a.length=1,a;var m=a.imul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.mul=function(a,c){if(a.isZero()||c.isZero())return new i(0)._forceRed(this);var m=a.mul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.invm=function(a){var c=this.imod(a._invmp(this.m).mul(this.r2));return c._forceRed(this)}})(typeof Zs>"u"||Zs,Ic)});var ll={};fc(ll,{__addDisposableResource:()=>ul,__assign:()=>eo,__asyncDelegator:()=>el,__asyncGenerator:()=>Qc,__asyncValues:()=>tl,__await:()=>fn,__awaiter:()=>Hc,__classPrivateFieldGet:()=>ol,__classPrivateFieldIn:()=>al,__classPrivateFieldSet:()=>sl,__createBinding:()=>ro,__decorate:()=>Vc,__disposeResources:()=>cl,__esDecorate:()=>ng,__exportStar:()=>Kc,__extends:()=>$c,__generator:()=>Zc,__importDefault:()=>il,__importStar:()=>nl,__makeTemplateObject:()=>rl,__metadata:()=>Wc,__param:()=>zc,__propKey:()=>og,__read:()=>ia,__rest:()=>Gc,__runInitializers:()=>ig,__setFunctionName:()=>sg,__spread:()=>Jc,__spreadArray:()=>Yc,__spreadArrays:()=>Xc,__values:()=>to,default:()=>cg});function $c(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");na(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Gc(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<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Vc(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var u=t.length-1;u>=0;u--)(s=t[u])&&(o=(i<3?s(o):i>3?s(e,r,o):s(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function zc(t,e){return function(r,n){e(r,n,t)}}function ng(t,e,r,n,i,o){function s(E){if(E!==void 0&&typeof E!="function")throw new TypeError("Function expected");return E}for(var u=n.kind,l=u==="getter"?"get":u==="setter"?"set":"value",d=!e&&t?n.static?t:t.prototype:null,b=e||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),_,T=!1,x=r.length-1;x>=0;x--){var A={};for(var I in n)A[I]=I==="access"?{}:n[I];for(var I in n.access)A.access[I]=n.access[I];A.addInitializer=function(E){if(T)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(E||null))};var C=(0,r[x])(u==="accessor"?{get:b.get,set:b.set}:b[l],A);if(u==="accessor"){if(C===void 0)continue;if(C===null||typeof C!="object")throw new TypeError("Object expected");(_=s(C.get))&&(b.get=_),(_=s(C.set))&&(b.set=_),(_=s(C.init))&&i.unshift(_)}else(_=s(C))&&(u==="field"?i.unshift(_):b[l]=_)}d&&Object.defineProperty(d,n.name,b),T=!0}function ig(t,e,r){for(var n=arguments.length>2,i=0;i<e.length;i++)r=n?e[i].call(t,r):e[i].call(t);return n?r:void 0}function og(t){return typeof t=="symbol"?t:"".concat(t)}function sg(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function Wc(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Hc(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function u(b){try{d(n.next(b))}catch(_){s(_)}}function l(b){try{d(n.throw(b))}catch(_){s(_)}}function d(b){b.done?o(b.value):i(b.value).then(u,l)}d((n=n.apply(t,e||[])).next())})}function Zc(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(d){return function(b){return l([d,b])}}function l(d){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(r=0)),r;)try{if(n=1,i&&(o=d[0]&2?i.return:d[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,d[1])).done)return o;switch(i=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,i=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){r.label=d[1];break}if(d[0]===6&&r.label<o[1]){r.label=o[1],o=d;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(d);break}o[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(b){d=[6,b],i=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function Kc(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ro(e,t,r)}function to(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=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 ia(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function Jc(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ia(arguments[e]));return t}function Xc(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],s=0,u=o.length;s<u;s++,i++)n[i]=o[s];return n}function Yc(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}function fn(t){return this instanceof fn?(this.v=t,this):new fn(t)}function Qc(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(T){n[T]&&(i[T]=function(x){return new Promise(function(A,I){o.push([T,x,A,I])>1||u(T,x)})})}function u(T,x){try{l(n[T](x))}catch(A){_(o[0][3],A)}}function l(T){T.value instanceof fn?Promise.resolve(T.value.v).then(d,b):_(o[0][2],T)}function d(T){u("next",T)}function b(T){u("throw",T)}function _(T,x){T(x),o.shift(),o.length&&u(o[0][0],o[0][1])}}function el(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,o){e[i]=t[i]?function(s){return(r=!r)?{value:fn(t[i](s)),done:!1}:o?o(s):s}:o}}function tl(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 to=="function"?to(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(u,l){s=t[o](s),i(u,l,s.done,s.value)})}}function i(o,s,u,l){Promise.resolve(l).then(function(d){o({value:d,done:u})},s)}}function rl(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function nl(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)&&ro(e,t,r);return ag(e,t),e}function il(t){return t&&t.__esModule?t:{default:t}}function ol(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function sl(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function al(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function ul(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function cl(t){function e(n){t.error=t.hasError?new ug(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}function r(){for(;t.stack.length;){var n=t.stack.pop();try{var i=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(i).then(r,function(o){return e(o),r()})}catch(o){e(o)}}if(t.hasError)throw t.error}return r()}var na,eo,ro,ag,ug,cg,dl=Yp(()=>{"use strict";na=function(t,e){return na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},na(t,e)};eo=function(){return eo=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},eo.apply(this,arguments)};ro=Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]};ag=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};ug=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};cg={__extends:$c,__assign:eo,__rest:Gc,__decorate:Vc,__param:zc,__metadata:Wc,__awaiter:Hc,__generator:Zc,__createBinding:ro,__exportStar:Kc,__values:to,__read:ia,__spread:Jc,__spreadArrays:Xc,__spreadArray:Yc,__await:fn,__asyncGenerator:Qc,__asyncDelegator:el,__asyncValues:tl,__makeTemplateObject:rl,__importStar:nl,__importDefault:il,__classPrivateFieldGet:ol,__classPrivateFieldSet:sl,__classPrivateFieldIn:al,__addDisposableResource:ul,__disposeResources:cl}});var hl=Fr((no,fl)=>{"use strict";(function(t,e){typeof no=="object"&&typeof fl<"u"?e(no,(dl(),pc(ll))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(no,function(t,e){"use strict";var r=function(){function p(h,w,g){g===void 0&&(g=0),this.startVertex=h,this.endVertex=w,this.weight=g}return p.prototype.getKey=function(){var h=this.startVertex.getKey(),w=this.endVertex.getKey();return h+"_"+w},p.prototype.reverse=function(){var h=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=h,this},p.prototype.clone=function(){return new p(this.startVertex,this.endVertex,this.weight)},p.prototype.toString=function(){return this.getKey()},p}();function n(p,h,w){if(w===void 0&&(w="cc-graph"),!p)throw new Error((w?"["+w+"]":"")+" Invariant failed: "+h)}function i(p,h){h===void 0&&(h=!0);var w=typeof p<"u"&&p!==null;return h?w&&p!=="undefined"&&p!=="null":w}var o=function(){function p(h){n(i(h),"Graph vertex must have a value"),this.value=h,this.edges=new Map}return p.prototype.addEdge=function(h){return this.edges.set(h.getKey(),h),this},p.prototype.deleteEdge=function(h){this.edges.delete(h.getKey())},p.prototype.getNeighbors=function(){var h=this,w=this.getEdges(),g=function(f){return f.startVertex===h?f.endVertex:f.startVertex};return w.map(g)},p.prototype.getEdges=function(){return Array.from(this.edges.values())},p.prototype.getDegree=function(){return this.getEdges().length},p.prototype.hasEdge=function(h){var w=this.getEdges().find(function(g){return g===h});return!!w},p.prototype.hasNeighbor=function(h){var w=this.getEdges().find(function(g){return g.startVertex===h||g.endVertex===h});return!!w},p.prototype.findEdge=function(h){var w=function(f){return f.startVertex===h||f.endVertex===h},g=this.getEdges().find(w);return g||null},p.prototype.getKey=function(){return this.value},p.prototype.deleteAllEdges=function(){var h=this;return this.getEdges().forEach(function(w){return h.deleteEdge(w)}),this},p.prototype.toString=function(h){return h?h(this.value):""+this.value},p}(),s;(function(p){p[p.EQUAL=0]="EQUAL",p[p.GREATER=1]="GREATER",p[p.LESS=-1]="LESS"})(s||(s={}));var u=function(){function p(h){this.compare=h||p.defaultCompareFunction}return p.defaultCompareFunction=function(h,w){return h===w?s.EQUAL:h<w?s.LESS:s.GREATER},p.prototype.equal=function(h,w){return this.compare(h,w)===s.EQUAL},p.prototype.lessThan=function(h,w){return this.compare(h,w)===s.LESS},p.prototype.greaterThan=function(h,w){return this.compare(h,w)===s.GREATER},p.prototype.lessThanOrEqual=function(h,w){return this.lessThan(h,w)||this.equal(h,w)},p.prototype.greaterThanOrEqual=function(h,w){return this.greaterThan(h,w)||this.equal(h,w)},p.prototype.reverse=function(){var h=this.compare;this.compare=function(w,g){return h(g,w)}},p}(),l=function(){function p(h){this.value=h,this.next=null}return p}(),d=function(){function p(h){this.value=h,this.next=null,this.prev=null}return p}();var b=function(p,h){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,g){w.__proto__=g}||function(w,g){for(var f in g)g.hasOwnProperty(f)&&(w[f]=g[f])},b(p,h)};function _(p,h){b(p,h);function w(){this.constructor=p}p.prototype=h===null?Object.create(h):(w.prototype=h.prototype,new w)}function T(p,h){var w={label:0,sent:function(){if(v[0]&1)throw v[1];return v[1]},trys:[],ops:[]},g,f,v,O;return O={next:M(0),throw:M(1),return:M(2)},typeof Symbol=="function"&&(O[Symbol.iterator]=function(){return this}),O;function M(B){return function(G){return R([B,G])}}function R(B){if(g)throw new TypeError("Generator is already executing.");for(;w;)try{if(g=1,f&&(v=B[0]&2?f.return:B[0]?f.throw||((v=f.return)&&v.call(f),0):f.next)&&!(v=v.call(f,B[1])).done)return v;switch(f=0,v&&(B=[B[0]&2,v.value]),B[0]){case 0:case 1:v=B;break;case 4:return w.label++,{value:B[1],done:!1};case 5:w.label++,f=B[1],B=[0];continue;case 7:B=w.ops.pop(),w.trys.pop();continue;default:if(v=w.trys,!(v=v.length>0&&v[v.length-1])&&(B[0]===6||B[0]===2)){w=0;continue}if(B[0]===3&&(!v||B[1]>v[0]&&B[1]<v[3])){w.label=B[1];break}if(B[0]===6&&w.label<v[1]){w.label=v[1],v=B;break}if(v&&w.label<v[2]){w.label=v[2],w.ops.push(B);break}v[2]&&w.ops.pop(),w.trys.pop();continue}B=h.call(p,w)}catch(G){B=[6,G],f=0}finally{g=v=0}if(B[0]&5)throw B[1];return{value:B[0]?B[1]:void 0,done:!0}}}function x(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function A(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(x(arguments[h]));return p}var I="obfuse error occur";function C(p,h){if(!p)throw new Error("[linked-list] "+(h||I))}var E=-1,P=function(){function p(){for(var h=this,w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];this._head=null,this._tail=null,this._length=0,this.compare=new u,w.length>0&&w.forEach(function(f){h.append(f)})}return Object.defineProperty(p.prototype,"head",{get:function(){return this._head?this._head.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"tail",{get:function(){return this._tail?this._tail.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"loopLength",{get:function(){var h=!1,w=1;if(!this._head)return 0;for(var g=this._head,f=this._head;f.next&&f.next.next;)if(f=f.next.next,g=g.next,g===f){h=!0;break}if(h){for(f=f.next;g!==f;)w++,f=f.next;return w}else return 0},enumerable:!0,configurable:!0}),p.prototype.getNode=function(h){var w=this._length;C(w>0&&h>=0&&h<w,"[linked-list] index "+h+" out of scope of list, which length is "+w);for(var g=this._head,f=0;f<h;)g=g.next,f++;return g},p.prototype.get=function(h){var w=this.getNode(h);return w?w.value:null},p.prototype.find=function(h){var w=h.value,g=h.callback;if(!this._head)return null;for(var f=this._head;f;){if(g&&g(f.value)||w!==void 0&&this.compare.equal(f.value,w))return f;f=f.next}return null},p.prototype.indexOf=function(h){if(!this._head)return E;for(var w=this._head,g=-1;w.next;){if(g++,this.compare.equal(w.value,h))return g;w=w.next}return w===this._tail&&this.compare.equal(w.value,h)&&(g+=1),g},p.prototype.first=function(h){C(h>=0,"[linked-list] param 'num' ("+h+") should not less than 0");for(var w=this.iterator(),g=[],f=Math.min(h,this.length),v=0;v<f;v++){var O=w.next();g.push(O.value)}return g},p.prototype.toArray=function(){return A(this)},p.prototype.isEmpty=function(){return this._head===null},p.prototype.iterator=function(){var h;return T(this,function(w){switch(w.label){case 0:h=this._head,w.label=1;case 1:return h?[4,h.value]:[3,3];case 2:return w.sent(),h=h.next,[3,1];case 3:return[2]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p}(),D=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new l(w);return this._tail?(this._tail.next=g,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new l(w);return this._head?(g.next=this._head,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,g.next=null):this._head=this._tail=null,this._length--,w;for(var f=g;;){if(this.compare.equal(g.value,w))return g.next?f.next=g.next:(this._tail=f,this._tail.next=null),g.next=null,this._length--,w;if(g.next)f=g,g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w){if(!this._head.next)this._head=null,this._tail=null;else{for(var g=this._head;g.next!==w;)g=g.next;g.next=null,this._tail=g}return this._length--,w.value}},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),L=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(D),H=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},h.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(L),W=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new d(w);return this._tail?(this._tail.next=g,g.prev=this._tail,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new d(w);return this._head?(g.next=this._head,this._head.prev=g,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,this._head.prev=null,g.next=g.prev=null):this._head=this._tail=null,this._length--,w;for(;;){if(this.compare.equal(g.value,w))return g.next?(g.prev.next=g.next,g.next.prev=g.prev,g.next=g.prev=null):(g.prev.next=null,this._tail=g.prev,g.next=g.prev=null),this._length--,g.value;if(g.next)g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(w.next.prev=null,this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w)return this._head.next?(w.prev.next=null,this._tail=w.prev,w.next=w.prev=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,w.prev=f,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),K=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(W),F=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},h.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(K);function U(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function N(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(U(arguments[h]));return p}var j=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.queue=new(D.bind.apply(D,N([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.queue.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.queue.head},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.queue.isEmpty()},p.prototype.enqueue=function(h){return this.queue.append(h)},p.prototype.dequeue=function(){var h=this.queue.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.queue.toArray()},p}();function S(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function k(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(S(arguments[h]));return p}var a=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.stack=new(D.bind.apply(D,k([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.stack.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.stack.tail},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.stack.isEmpty()},p.prototype.push=function(h){return this.stack.append(h)},p.prototype.pop=function(){var h=this.stack.removeTail();return typeof h<"u"?h:void 0},p.prototype.popBottom=function(){var h=this.stack.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.stack.toArray()},p}();function c(p,h,w,g){if(p){h.push(p),g.set(p.getKey(),!0);var f=p.getNeighbors().filter(function(v){return!g.get(v.getKey())});w.push(f)}}function m(p,h,w){var g=p.pop();g&&w.set(g.getKey(),!1),h.pop()}var y=function(){function p(h){h===void 0&&(h=!1),this.vertices={},this.edges={},this.isDirected=h}return p.prototype.addVertex=function(h){return this.vertices[h.getKey()]=h,this},p.prototype.getVertexByKey=function(h){return this.vertices[h]},p.prototype.getNeighbors=function(h){return h.getNeighbors()},p.prototype.getAllVertices=function(){return Object.values(this.vertices)},p.prototype.getAllEdges=function(){return Object.values(this.edges)},p.prototype.addEdge=function(h,w){if(w===void 0&&(w=!1),this.edges[h.getKey()]){if(w)return this;n(!1,"Edge has already been added before")}var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());if(g||(this.addVertex(h.startVertex),g=this.getVertexByKey(h.startVertex.getKey())),f||(this.addVertex(h.endVertex),f=this.getVertexByKey(h.endVertex.getKey())),this.edges[h.getKey()]=h,this.isDirected)g.addEdge(h);else{g.addEdge(h);var v=h.clone();f.addEdge(v.reverse())}return this},p.prototype.deleteEdge=function(h,w){if(w===void 0&&(w=!1),!this.edges[h.getKey()]){if(w)return this;n(!1,"Edge not found in graph")}delete this.edges[h.getKey()];var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());return g.deleteEdge(h),f.deleteEdge(h),this},p.prototype.findEdge=function(h,w){var g=this.getVertexByKey(h.getKey());return g?g.findEdge(w):null},p.prototype.getWeight=function(){return this.getAllEdges().reduce(function(h,w){return h+w.weight},0)},p.prototype.reverse=function(){var h=this;return this.getAllEdges().forEach(function(w){h.deleteEdge(w),w.reverse(),h.addEdge(w)}),this},p.prototype.getVerticesIndices=function(){var h={};return this.getAllVertices().forEach(function(w,g){h[w.getKey()]=g}),h},p.prototype.getAdjacencyMatrix=function(){var h=this,w=this.getAllVertices(),g=this.getVerticesIndices(),f=Array(w.length).fill(null).map(function(){return Array(w.length).fill(1/0)});return w.forEach(function(v,O){v.getNeighbors().forEach(function(M){var R=g[M.getKey()],B=h.findEdge(v,M);B&&(f[O][R]=B.weight)})}),f},p.prototype.toString=function(){return Object.keys(this.vertices).toString()},p.prototype.bfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new j,g.enqueue(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.dequeue(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.enqueue(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.dfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new a,g.push(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.pop(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.push(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.findAllPath=function(h,w){var g,f,v,O,M,R,B;return e.__generator(this,function(G){switch(G.label){case 0:return g=[],h!==w?[3,2]:(g.push(h),[4,g]);case 1:return G.sent(),[2];case 2:f=new Map,v=new a,O=new a,c(h,v,O,f),G.label=3;case 3:if(v.isEmpty())return[3,6];if(M=O.pop(),M&&M.length)R=M.shift(),O.push(M),R&&c(R,v,O,f);else return O.push(M),m(v,O,f),[3,3];return B=v.peek,B!==w?[3,5]:[4,v.toArray()];case 4:G.sent(),m(v,O,f),G.label=5;case 5:return[3,3];case 6:return[2]}})},p}();t.GraphEdge=r,t.GraphVertex=o,t.Graph=y,Object.defineProperty(t,"__esModule",{value:!0})})});var If=Fr((hu,pu)=>{"use strict";(function(t,e){typeof hu=="object"&&typeof pu<"u"?pu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(hu,function(){"use strict";var t=Math.imul,e=Math.clz32;function r(F){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U},r(F)}function n(F,U){if(!(F instanceof U))throw new TypeError("Cannot call a class as a function")}function i(F,U){for(var N,j=0;j<U.length;j++)N=U[j],N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(F,N.key,N)}function o(F,U,N){return U&&i(F.prototype,U),N&&i(F,N),Object.defineProperty(F,"prototype",{writable:!1}),F}function s(F,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(U&&U.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),U&&l(F,U)}function u(F){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(U){return U.__proto__||Object.getPrototypeOf(U)},u(F)}function l(F,U){return l=Object.setPrototypeOf||function(N,j){return N.__proto__=j,N},l(F,U)}function d(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function b(){return b=d()?Reflect.construct:function(F,U,N){var j=[null];j.push.apply(j,U);var S=Function.bind.apply(F,j),k=new S;return N&&l(k,N.prototype),k},b.apply(null,arguments)}function _(F){return Function.toString.call(F).indexOf("[native code]")!==-1}function T(F){var U=typeof Map=="function"?new Map:void 0;return T=function(N){function j(){return b(N,arguments,u(this).constructor)}if(N===null||!_(N))return N;if(typeof N!="function")throw new TypeError("Super expression must either be null or a function");if(typeof U<"u"){if(U.has(N))return U.get(N);U.set(N,j)}return j.prototype=Object.create(N.prototype,{constructor:{value:j,enumerable:!1,writable:!0,configurable:!0}}),l(j,N)},T(F)}function x(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}function A(F,U){if(U&&(typeof U=="object"||typeof U=="function"))return U;if(U!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return x(F)}function I(F){var U=d();return function(){var N,j=u(F);if(U){var S=u(this).constructor;N=Reflect.construct(j,arguments,S)}else N=j.apply(this,arguments);return A(this,N)}}function C(F,U){return E(F)||P(F,U)||D(F,U)||H()}function E(F){if(Array.isArray(F))return F}function P(F,U){var N=F==null?null:typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(N!=null){var j,S,k=[],a=!0,c=!1;try{for(N=N.call(F);!(a=(j=N.next()).done)&&(k.push(j.value),!(U&&k.length===U));a=!0);}catch(m){c=!0,S=m}finally{try{a||N.return==null||N.return()}finally{if(c)throw S}}return k}}function D(F,U){if(F){if(typeof F=="string")return L(F,U);var N=Object.prototype.toString.call(F).slice(8,-1);return N==="Object"&&F.constructor&&(N=F.constructor.name),N==="Map"||N==="Set"?Array.from(F):N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N)?L(F,U):void 0}}function L(F,U){(U==null||U>F.length)&&(U=F.length);for(var N=0,j=Array(U);N<U;N++)j[N]=F[N];return j}function H(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1
+ "use strict";var Hp=Object.create;var Vi=Object.defineProperty;var Zp=Object.getOwnPropertyDescriptor;var Kp=Object.getOwnPropertyNames;var Jp=Object.getPrototypeOf,Xp=Object.prototype.hasOwnProperty;var Yp=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),fc=(t,e)=>{for(var r in e)Vi(t,r,{get:e[r],enumerable:!0})},hc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Kp(e))!Xp.call(t,i)&&i!==r&&Vi(t,i,{get:()=>e[i],enumerable:!(n=Zp(e,i))||n.enumerable});return t};var de=(t,e,r)=>(r=t!=null?Hp(Jp(t)):{},hc(e||!t||!t.__esModule?Vi(r,"default",{value:t,enumerable:!0}):r,t)),pc=t=>hc(Vi({},"__esModule",{value:!0}),t);var wc=Fr((U_,gc)=>{"use strict";gc.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var bc=Fr(($_,yc)=>{"use strict";var Ws=wc();yc.exports=(t,e={})=>{if(!Ws(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:r}=e,n=[],i=[],o=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d=[];return n.push(u),i.push(d),d.push(...u.map(b=>Array.isArray(b)?o(b):Ws(b)?s(b):b)),d},s=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d={},b=Object.keys(u).sort(e.compare);n.push(u),i.push(d);for(let _ of b){let T=u[_],x;r&&Array.isArray(T)?x=o(T):x=r&&Ws(T)?s(T):T,Object.defineProperty(d,_,{...Object.getOwnPropertyDescriptor(u,_),value:x})}return d};return Array.isArray(t)?r?o(t):t.slice():s(t)}});var Tc=Fr((G_,vc)=>{"use strict";var Qp=Object.prototype.toString;vc.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var r=typeof e;if(r==="boolean")return"boolean";if(r==="string")return"string";if(r==="number")return"number";if(r==="symbol")return"symbol";if(r==="function")return im(e)?"generatorfunction":"function";if(em(e))return"array";if(am(e))return"buffer";if(sm(e))return"arguments";if(rm(e))return"date";if(tm(e))return"error";if(nm(e))return"regexp";switch(_c(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(om(e))return"generator";switch(r=Qp.call(e),r){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return r.slice(8,-1).toLowerCase().replace(/\s/g,"")};function _c(t){return typeof t.constructor=="function"?t.constructor.name:null}function em(t){return Array.isArray?Array.isArray(t):t instanceof Array}function tm(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function rm(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function nm(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function im(t,e){return _c(t)==="GeneratorFunction"}function om(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function sm(t){try{if(typeof t.length=="number"&&typeof t.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function am(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Wi=Fr((V_,Ac)=>{"use strict";var um=bc(),Hs=Tc(),Sc=(t,e)=>!e||Hs(e)!=="array"?!1:e.indexOf(t)>-1,cm=(t,e)=>um(t,{compare:e}),xc=(t,e)=>{let r=e&&e.compareFunction;return t.slice().sort(r)};function kc(t,e){let r=e&&e.compareFunction,n=cm(t,r);return Object.keys(t).forEach(function(i){let o=n[i],s=Hs(o);if(s==="object"){(!e||!Sc(i,e.ignoreObjectAtKeys))&&(n[i]=kc(o,e));return}s==="array"&&(!e||!Sc(i,e.ignoreArrayAtKeys))&&(n[i]=xc(o,e))}),n}var Un=(t,e)=>{let r=Hs(t);return Un[r]?Un[r](t,e):t};Un.array=xc;Un.object=kc;Ac.exports=Un});var we=Fr((Ic,Zs)=>{"use strict";(function(t,e){"use strict";function r(k,a){if(!k)throw new Error(a||"Assertion failed")}function n(k,a){k.super_=a;var c=function(){};c.prototype=a.prototype,k.prototype=new c,k.prototype.constructor=k}function i(k,a,c){if(i.isBN(k))return k;this.negative=0,this.words=null,this.length=0,this.red=null,k!==null&&((a==="le"||a==="be")&&(c=a,a=10),this._init(k||0,a||10,c||"be"))}typeof t=="object"?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=require("buffer").Buffer}catch{}i.isBN=function(a){return a instanceof i?!0:a!==null&&typeof a=="object"&&a.constructor.wordSize===i.wordSize&&Array.isArray(a.words)},i.max=function(a,c){return a.cmp(c)>0?a:c},i.min=function(a,c){return a.cmp(c)<0?a:c},i.prototype._init=function(a,c,m){if(typeof a=="number")return this._initNumber(a,c,m);if(typeof a=="object")return this._initArray(a,c,m);c==="hex"&&(c=16),r(c===(c|0)&&c>=2&&c<=36),a=a.toString().replace(/\s+/g,"");var y=0;a[0]==="-"&&(y++,this.negative=1),y<a.length&&(c===16?this._parseHex(a,y,m):(this._parseBase(a,c,y),m==="le"&&this._initArray(this.toArray(),c,m)))},i.prototype._initNumber=function(a,c,m){a<0&&(this.negative=1,a=-a),a<67108864?(this.words=[a&67108863],this.length=1):a<4503599627370496?(this.words=[a&67108863,a/67108864&67108863],this.length=2):(r(a<9007199254740992),this.words=[a&67108863,a/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),c,m)},i.prototype._initArray=function(a,c,m){if(r(typeof a.length=="number"),a.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(a.length/3),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p,h,w=0;if(m==="be")for(y=a.length-1,p=0;y>=0;y-=3)h=a[y]|a[y-1]<<8|a[y-2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);else if(m==="le")for(y=0,p=0;y<a.length;y+=3)h=a[y]|a[y+1]<<8|a[y+2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);return this._strip()};function s(k,a){var c=k.charCodeAt(a);if(c>=48&&c<=57)return c-48;if(c>=65&&c<=70)return c-55;if(c>=97&&c<=102)return c-87;r(!1,"Invalid character in "+k)}function u(k,a,c){var m=s(k,c);return c-1>=a&&(m|=s(k,c-1)<<4),m}i.prototype._parseHex=function(a,c,m){this.length=Math.ceil((a.length-c)/6),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p=0,h=0,w;if(m==="be")for(y=a.length-1;y>=c;y-=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8;else{var g=a.length-c;for(y=g%2===0?c+1:c;y<a.length;y+=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8}this._strip()};function l(k,a,c,m){for(var y=0,p=0,h=Math.min(k.length,c),w=a;w<h;w++){var g=k.charCodeAt(w)-48;y*=m,g>=49?p=g-49+10:g>=17?p=g-17+10:p=g,r(g>=0&&p<m,"Invalid character"),y+=p}return y}i.prototype._parseBase=function(a,c,m){this.words=[0],this.length=1;for(var y=0,p=1;p<=67108863;p*=c)y++;y--,p=p/c|0;for(var h=a.length-m,w=h%y,g=Math.min(h,h-w)+m,f=0,v=m;v<g;v+=y)f=l(a,v,v+y,c),this.imuln(p),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f);if(w!==0){var O=1;for(f=l(a,v,a.length,c),v=0;v<w;v++)O*=c;this.imuln(O),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f)}this._strip()},i.prototype.copy=function(a){a.words=new Array(this.length);for(var c=0;c<this.length;c++)a.words[c]=this.words[c];a.length=this.length,a.negative=this.negative,a.red=this.red};function d(k,a){k.words=a.words,k.length=a.length,k.negative=a.negative,k.red=a.red}if(i.prototype._move=function(a){d(a,this)},i.prototype.clone=function(){var a=new i(null);return this.copy(a),a},i.prototype._expand=function(a){for(;this.length<a;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=b}catch{i.prototype.inspect=b}else i.prototype.inspect=b;function b(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var _=["","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"],T=[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],x=[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];i.prototype.toString=function(a,c){a=a||10,c=c|0||1;var m;if(a===16||a==="hex"){m="";for(var y=0,p=0,h=0;h<this.length;h++){var w=this.words[h],g=((w<<y|p)&16777215).toString(16);p=w>>>24-y&16777215,y+=2,y>=26&&(y-=26,h--),p!==0||h!==this.length-1?m=_[6-g.length]+g+m:m=g+m}for(p!==0&&(m=p.toString(16)+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(a===(a|0)&&a>=2&&a<=36){var f=T[a],v=x[a];m="";var O=this.clone();for(O.negative=0;!O.isZero();){var M=O.modrn(v).toString(a);O=O.idivn(v),O.isZero()?m=M+m:m=_[f-M.length]+M+m}for(this.isZero()&&(m="0"+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var a=this.words[0];return this.length===2?a+=this.words[1]*67108864:this.length===3&&this.words[2]===1?a+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-a:a},i.prototype.toJSON=function(){return this.toString(16,2)},o&&(i.prototype.toBuffer=function(a,c){return this.toArrayLike(o,a,c)}),i.prototype.toArray=function(a,c){return this.toArrayLike(Array,a,c)};var A=function(a,c){return a.allocUnsafe?a.allocUnsafe(c):new a(c)};i.prototype.toArrayLike=function(a,c,m){this._strip();var y=this.byteLength(),p=m||Math.max(1,y);r(y<=p,"byte array longer than desired length"),r(p>0,"Requested array length <= 0");var h=A(a,p),w=c==="le"?"LE":"BE";return this["_toArrayLike"+w](h,y),h},i.prototype._toArrayLikeLE=function(a,c){for(var m=0,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m++]=w&255,m<a.length&&(a[m++]=w>>8&255),m<a.length&&(a[m++]=w>>16&255),h===6?(m<a.length&&(a[m++]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m<a.length)for(a[m++]=y;m<a.length;)a[m++]=0},i.prototype._toArrayLikeBE=function(a,c){for(var m=a.length-1,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m--]=w&255,m>=0&&(a[m--]=w>>8&255),m>=0&&(a[m--]=w>>16&255),h===6?(m>=0&&(a[m--]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m>=0)for(a[m--]=y;m>=0;)a[m--]=0},Math.clz32?i.prototype._countBits=function(a){return 32-Math.clz32(a)}:i.prototype._countBits=function(a){var c=a,m=0;return c>=4096&&(m+=13,c>>>=13),c>=64&&(m+=7,c>>>=7),c>=8&&(m+=4,c>>>=4),c>=2&&(m+=2,c>>>=2),m+c},i.prototype._zeroBits=function(a){if(a===0)return 26;var c=a,m=0;return c&8191||(m+=13,c>>>=13),c&127||(m+=7,c>>>=7),c&15||(m+=4,c>>>=4),c&3||(m+=2,c>>>=2),c&1||m++,m},i.prototype.bitLength=function(){var a=this.words[this.length-1],c=this._countBits(a);return(this.length-1)*26+c};function I(k){for(var a=new Array(k.bitLength()),c=0;c<a.length;c++){var m=c/26|0,y=c%26;a[c]=k.words[m]>>>y&1}return a}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var a=0,c=0;c<this.length;c++){var m=this._zeroBits(this.words[c]);if(a+=m,m!==26)break}return a},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(a){return this.negative!==0?this.abs().inotn(a).iaddn(1):this.clone()},i.prototype.fromTwos=function(a){return this.testn(a-1)?this.notn(a).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(a){for(;this.length<a.length;)this.words[this.length++]=0;for(var c=0;c<a.length;c++)this.words[c]=this.words[c]|a.words[c];return this._strip()},i.prototype.ior=function(a){return r((this.negative|a.negative)===0),this.iuor(a)},i.prototype.or=function(a){return this.length>a.length?this.clone().ior(a):a.clone().ior(this)},i.prototype.uor=function(a){return this.length>a.length?this.clone().iuor(a):a.clone().iuor(this)},i.prototype.iuand=function(a){var c;this.length>a.length?c=a:c=this;for(var m=0;m<c.length;m++)this.words[m]=this.words[m]&a.words[m];return this.length=c.length,this._strip()},i.prototype.iand=function(a){return r((this.negative|a.negative)===0),this.iuand(a)},i.prototype.and=function(a){return this.length>a.length?this.clone().iand(a):a.clone().iand(this)},i.prototype.uand=function(a){return this.length>a.length?this.clone().iuand(a):a.clone().iuand(this)},i.prototype.iuxor=function(a){var c,m;this.length>a.length?(c=this,m=a):(c=a,m=this);for(var y=0;y<m.length;y++)this.words[y]=c.words[y]^m.words[y];if(this!==c)for(;y<c.length;y++)this.words[y]=c.words[y];return this.length=c.length,this._strip()},i.prototype.ixor=function(a){return r((this.negative|a.negative)===0),this.iuxor(a)},i.prototype.xor=function(a){return this.length>a.length?this.clone().ixor(a):a.clone().ixor(this)},i.prototype.uxor=function(a){return this.length>a.length?this.clone().iuxor(a):a.clone().iuxor(this)},i.prototype.inotn=function(a){r(typeof a=="number"&&a>=0);var c=Math.ceil(a/26)|0,m=a%26;this._expand(c),m>0&&c--;for(var y=0;y<c;y++)this.words[y]=~this.words[y]&67108863;return m>0&&(this.words[y]=~this.words[y]&67108863>>26-m),this._strip()},i.prototype.notn=function(a){return this.clone().inotn(a)},i.prototype.setn=function(a,c){r(typeof a=="number"&&a>=0);var m=a/26|0,y=a%26;return this._expand(m+1),c?this.words[m]=this.words[m]|1<<y:this.words[m]=this.words[m]&~(1<<y),this._strip()},i.prototype.iadd=function(a){var c;if(this.negative!==0&&a.negative===0)return this.negative=0,c=this.isub(a),this.negative^=1,this._normSign();if(this.negative===0&&a.negative!==0)return a.negative=0,c=this.isub(a),a.negative=1,c._normSign();var m,y;this.length>a.length?(m=this,y=a):(m=a,y=this);for(var p=0,h=0;h<y.length;h++)c=(m.words[h]|0)+(y.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;for(;p!==0&&h<m.length;h++)c=(m.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;if(this.length=m.length,p!==0)this.words[this.length]=p,this.length++;else if(m!==this)for(;h<m.length;h++)this.words[h]=m.words[h];return this},i.prototype.add=function(a){var c;return a.negative!==0&&this.negative===0?(a.negative=0,c=this.sub(a),a.negative^=1,c):a.negative===0&&this.negative!==0?(this.negative=0,c=a.sub(this),this.negative=1,c):this.length>a.length?this.clone().iadd(a):a.clone().iadd(this)},i.prototype.isub=function(a){if(a.negative!==0){a.negative=0;var c=this.iadd(a);return a.negative=1,c._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(a),this.negative=1,this._normSign();var m=this.cmp(a);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var y,p;m>0?(y=this,p=a):(y=a,p=this);for(var h=0,w=0;w<p.length;w++)c=(y.words[w]|0)-(p.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;for(;h!==0&&w<y.length;w++)c=(y.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;if(h===0&&w<y.length&&y!==this)for(;w<y.length;w++)this.words[w]=y.words[w];return this.length=Math.max(this.length,w),y!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(a){return this.clone().isub(a)};function C(k,a,c){c.negative=a.negative^k.negative;var m=k.length+a.length|0;c.length=m,m=m-1|0;var y=k.words[0]|0,p=a.words[0]|0,h=y*p,w=h&67108863,g=h/67108864|0;c.words[0]=w;for(var f=1;f<m;f++){for(var v=g>>>26,O=g&67108863,M=Math.min(f,a.length-1),R=Math.max(0,f-k.length+1);R<=M;R++){var B=f-R|0;y=k.words[B]|0,p=a.words[R]|0,h=y*p+O,v+=h/67108864|0,O=h&67108863}c.words[f]=O|0,g=v|0}return g!==0?c.words[f]=g|0:c.length--,c._strip()}var E=function(a,c,m){var y=a.words,p=c.words,h=m.words,w=0,g,f,v,O=y[0]|0,M=O&8191,R=O>>>13,B=y[1]|0,G=B&8191,Z=B>>>13,oe=y[2]|0,te=oe&8191,ae=oe>>>13,dt=y[3]|0,ve=dt&8191,xe=dt>>>13,an=y[4]|0,Ae=an&8191,Me=an>>>13,Gi=y[5]|0,De=Gi&8191,Be=Gi>>>13,Yu=y[6]|0,Ne=Yu&8191,Re=Yu>>>13,Qu=y[7]|0,je=Qu&8191,Fe=Qu>>>13,ec=y[8]|0,qe=ec&8191,Le=ec>>>13,tc=y[9]|0,Ue=tc&8191,$e=tc>>>13,rc=p[0]|0,Ge=rc&8191,Ve=rc>>>13,nc=p[1]|0,ze=nc&8191,We=nc>>>13,ic=p[2]|0,He=ic&8191,Ze=ic>>>13,oc=p[3]|0,Ke=oc&8191,Je=oc>>>13,sc=p[4]|0,Xe=sc&8191,Ye=sc>>>13,ac=p[5]|0,Qe=ac&8191,et=ac>>>13,uc=p[6]|0,tt=uc&8191,rt=uc>>>13,cc=p[7]|0,nt=cc&8191,it=cc>>>13,lc=p[8]|0,ot=lc&8191,st=lc>>>13,dc=p[9]|0,at=dc&8191,ut=dc>>>13;m.negative=a.negative^c.negative,m.length=19,g=Math.imul(M,Ge),f=Math.imul(M,Ve),f=f+Math.imul(R,Ge)|0,v=Math.imul(R,Ve);var Is=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Is>>>26)|0,Is&=67108863,g=Math.imul(G,Ge),f=Math.imul(G,Ve),f=f+Math.imul(Z,Ge)|0,v=Math.imul(Z,Ve),g=g+Math.imul(M,ze)|0,f=f+Math.imul(M,We)|0,f=f+Math.imul(R,ze)|0,v=v+Math.imul(R,We)|0;var Cs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Cs>>>26)|0,Cs&=67108863,g=Math.imul(te,Ge),f=Math.imul(te,Ve),f=f+Math.imul(ae,Ge)|0,v=Math.imul(ae,Ve),g=g+Math.imul(G,ze)|0,f=f+Math.imul(G,We)|0,f=f+Math.imul(Z,ze)|0,v=v+Math.imul(Z,We)|0,g=g+Math.imul(M,He)|0,f=f+Math.imul(M,Ze)|0,f=f+Math.imul(R,He)|0,v=v+Math.imul(R,Ze)|0;var Os=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Os>>>26)|0,Os&=67108863,g=Math.imul(ve,Ge),f=Math.imul(ve,Ve),f=f+Math.imul(xe,Ge)|0,v=Math.imul(xe,Ve),g=g+Math.imul(te,ze)|0,f=f+Math.imul(te,We)|0,f=f+Math.imul(ae,ze)|0,v=v+Math.imul(ae,We)|0,g=g+Math.imul(G,He)|0,f=f+Math.imul(G,Ze)|0,f=f+Math.imul(Z,He)|0,v=v+Math.imul(Z,Ze)|0,g=g+Math.imul(M,Ke)|0,f=f+Math.imul(M,Je)|0,f=f+Math.imul(R,Ke)|0,v=v+Math.imul(R,Je)|0;var Ms=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ms>>>26)|0,Ms&=67108863,g=Math.imul(Ae,Ge),f=Math.imul(Ae,Ve),f=f+Math.imul(Me,Ge)|0,v=Math.imul(Me,Ve),g=g+Math.imul(ve,ze)|0,f=f+Math.imul(ve,We)|0,f=f+Math.imul(xe,ze)|0,v=v+Math.imul(xe,We)|0,g=g+Math.imul(te,He)|0,f=f+Math.imul(te,Ze)|0,f=f+Math.imul(ae,He)|0,v=v+Math.imul(ae,Ze)|0,g=g+Math.imul(G,Ke)|0,f=f+Math.imul(G,Je)|0,f=f+Math.imul(Z,Ke)|0,v=v+Math.imul(Z,Je)|0,g=g+Math.imul(M,Xe)|0,f=f+Math.imul(M,Ye)|0,f=f+Math.imul(R,Xe)|0,v=v+Math.imul(R,Ye)|0;var Es=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Es>>>26)|0,Es&=67108863,g=Math.imul(De,Ge),f=Math.imul(De,Ve),f=f+Math.imul(Be,Ge)|0,v=Math.imul(Be,Ve),g=g+Math.imul(Ae,ze)|0,f=f+Math.imul(Ae,We)|0,f=f+Math.imul(Me,ze)|0,v=v+Math.imul(Me,We)|0,g=g+Math.imul(ve,He)|0,f=f+Math.imul(ve,Ze)|0,f=f+Math.imul(xe,He)|0,v=v+Math.imul(xe,Ze)|0,g=g+Math.imul(te,Ke)|0,f=f+Math.imul(te,Je)|0,f=f+Math.imul(ae,Ke)|0,v=v+Math.imul(ae,Je)|0,g=g+Math.imul(G,Xe)|0,f=f+Math.imul(G,Ye)|0,f=f+Math.imul(Z,Xe)|0,v=v+Math.imul(Z,Ye)|0,g=g+Math.imul(M,Qe)|0,f=f+Math.imul(M,et)|0,f=f+Math.imul(R,Qe)|0,v=v+Math.imul(R,et)|0;var Ps=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ps>>>26)|0,Ps&=67108863,g=Math.imul(Ne,Ge),f=Math.imul(Ne,Ve),f=f+Math.imul(Re,Ge)|0,v=Math.imul(Re,Ve),g=g+Math.imul(De,ze)|0,f=f+Math.imul(De,We)|0,f=f+Math.imul(Be,ze)|0,v=v+Math.imul(Be,We)|0,g=g+Math.imul(Ae,He)|0,f=f+Math.imul(Ae,Ze)|0,f=f+Math.imul(Me,He)|0,v=v+Math.imul(Me,Ze)|0,g=g+Math.imul(ve,Ke)|0,f=f+Math.imul(ve,Je)|0,f=f+Math.imul(xe,Ke)|0,v=v+Math.imul(xe,Je)|0,g=g+Math.imul(te,Xe)|0,f=f+Math.imul(te,Ye)|0,f=f+Math.imul(ae,Xe)|0,v=v+Math.imul(ae,Ye)|0,g=g+Math.imul(G,Qe)|0,f=f+Math.imul(G,et)|0,f=f+Math.imul(Z,Qe)|0,v=v+Math.imul(Z,et)|0,g=g+Math.imul(M,tt)|0,f=f+Math.imul(M,rt)|0,f=f+Math.imul(R,tt)|0,v=v+Math.imul(R,rt)|0;var Ds=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ds>>>26)|0,Ds&=67108863,g=Math.imul(je,Ge),f=Math.imul(je,Ve),f=f+Math.imul(Fe,Ge)|0,v=Math.imul(Fe,Ve),g=g+Math.imul(Ne,ze)|0,f=f+Math.imul(Ne,We)|0,f=f+Math.imul(Re,ze)|0,v=v+Math.imul(Re,We)|0,g=g+Math.imul(De,He)|0,f=f+Math.imul(De,Ze)|0,f=f+Math.imul(Be,He)|0,v=v+Math.imul(Be,Ze)|0,g=g+Math.imul(Ae,Ke)|0,f=f+Math.imul(Ae,Je)|0,f=f+Math.imul(Me,Ke)|0,v=v+Math.imul(Me,Je)|0,g=g+Math.imul(ve,Xe)|0,f=f+Math.imul(ve,Ye)|0,f=f+Math.imul(xe,Xe)|0,v=v+Math.imul(xe,Ye)|0,g=g+Math.imul(te,Qe)|0,f=f+Math.imul(te,et)|0,f=f+Math.imul(ae,Qe)|0,v=v+Math.imul(ae,et)|0,g=g+Math.imul(G,tt)|0,f=f+Math.imul(G,rt)|0,f=f+Math.imul(Z,tt)|0,v=v+Math.imul(Z,rt)|0,g=g+Math.imul(M,nt)|0,f=f+Math.imul(M,it)|0,f=f+Math.imul(R,nt)|0,v=v+Math.imul(R,it)|0;var Bs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Bs>>>26)|0,Bs&=67108863,g=Math.imul(qe,Ge),f=Math.imul(qe,Ve),f=f+Math.imul(Le,Ge)|0,v=Math.imul(Le,Ve),g=g+Math.imul(je,ze)|0,f=f+Math.imul(je,We)|0,f=f+Math.imul(Fe,ze)|0,v=v+Math.imul(Fe,We)|0,g=g+Math.imul(Ne,He)|0,f=f+Math.imul(Ne,Ze)|0,f=f+Math.imul(Re,He)|0,v=v+Math.imul(Re,Ze)|0,g=g+Math.imul(De,Ke)|0,f=f+Math.imul(De,Je)|0,f=f+Math.imul(Be,Ke)|0,v=v+Math.imul(Be,Je)|0,g=g+Math.imul(Ae,Xe)|0,f=f+Math.imul(Ae,Ye)|0,f=f+Math.imul(Me,Xe)|0,v=v+Math.imul(Me,Ye)|0,g=g+Math.imul(ve,Qe)|0,f=f+Math.imul(ve,et)|0,f=f+Math.imul(xe,Qe)|0,v=v+Math.imul(xe,et)|0,g=g+Math.imul(te,tt)|0,f=f+Math.imul(te,rt)|0,f=f+Math.imul(ae,tt)|0,v=v+Math.imul(ae,rt)|0,g=g+Math.imul(G,nt)|0,f=f+Math.imul(G,it)|0,f=f+Math.imul(Z,nt)|0,v=v+Math.imul(Z,it)|0,g=g+Math.imul(M,ot)|0,f=f+Math.imul(M,st)|0,f=f+Math.imul(R,ot)|0,v=v+Math.imul(R,st)|0;var Ns=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ns>>>26)|0,Ns&=67108863,g=Math.imul(Ue,Ge),f=Math.imul(Ue,Ve),f=f+Math.imul($e,Ge)|0,v=Math.imul($e,Ve),g=g+Math.imul(qe,ze)|0,f=f+Math.imul(qe,We)|0,f=f+Math.imul(Le,ze)|0,v=v+Math.imul(Le,We)|0,g=g+Math.imul(je,He)|0,f=f+Math.imul(je,Ze)|0,f=f+Math.imul(Fe,He)|0,v=v+Math.imul(Fe,Ze)|0,g=g+Math.imul(Ne,Ke)|0,f=f+Math.imul(Ne,Je)|0,f=f+Math.imul(Re,Ke)|0,v=v+Math.imul(Re,Je)|0,g=g+Math.imul(De,Xe)|0,f=f+Math.imul(De,Ye)|0,f=f+Math.imul(Be,Xe)|0,v=v+Math.imul(Be,Ye)|0,g=g+Math.imul(Ae,Qe)|0,f=f+Math.imul(Ae,et)|0,f=f+Math.imul(Me,Qe)|0,v=v+Math.imul(Me,et)|0,g=g+Math.imul(ve,tt)|0,f=f+Math.imul(ve,rt)|0,f=f+Math.imul(xe,tt)|0,v=v+Math.imul(xe,rt)|0,g=g+Math.imul(te,nt)|0,f=f+Math.imul(te,it)|0,f=f+Math.imul(ae,nt)|0,v=v+Math.imul(ae,it)|0,g=g+Math.imul(G,ot)|0,f=f+Math.imul(G,st)|0,f=f+Math.imul(Z,ot)|0,v=v+Math.imul(Z,st)|0,g=g+Math.imul(M,at)|0,f=f+Math.imul(M,ut)|0,f=f+Math.imul(R,at)|0,v=v+Math.imul(R,ut)|0;var Rs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Rs>>>26)|0,Rs&=67108863,g=Math.imul(Ue,ze),f=Math.imul(Ue,We),f=f+Math.imul($e,ze)|0,v=Math.imul($e,We),g=g+Math.imul(qe,He)|0,f=f+Math.imul(qe,Ze)|0,f=f+Math.imul(Le,He)|0,v=v+Math.imul(Le,Ze)|0,g=g+Math.imul(je,Ke)|0,f=f+Math.imul(je,Je)|0,f=f+Math.imul(Fe,Ke)|0,v=v+Math.imul(Fe,Je)|0,g=g+Math.imul(Ne,Xe)|0,f=f+Math.imul(Ne,Ye)|0,f=f+Math.imul(Re,Xe)|0,v=v+Math.imul(Re,Ye)|0,g=g+Math.imul(De,Qe)|0,f=f+Math.imul(De,et)|0,f=f+Math.imul(Be,Qe)|0,v=v+Math.imul(Be,et)|0,g=g+Math.imul(Ae,tt)|0,f=f+Math.imul(Ae,rt)|0,f=f+Math.imul(Me,tt)|0,v=v+Math.imul(Me,rt)|0,g=g+Math.imul(ve,nt)|0,f=f+Math.imul(ve,it)|0,f=f+Math.imul(xe,nt)|0,v=v+Math.imul(xe,it)|0,g=g+Math.imul(te,ot)|0,f=f+Math.imul(te,st)|0,f=f+Math.imul(ae,ot)|0,v=v+Math.imul(ae,st)|0,g=g+Math.imul(G,at)|0,f=f+Math.imul(G,ut)|0,f=f+Math.imul(Z,at)|0,v=v+Math.imul(Z,ut)|0;var js=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(js>>>26)|0,js&=67108863,g=Math.imul(Ue,He),f=Math.imul(Ue,Ze),f=f+Math.imul($e,He)|0,v=Math.imul($e,Ze),g=g+Math.imul(qe,Ke)|0,f=f+Math.imul(qe,Je)|0,f=f+Math.imul(Le,Ke)|0,v=v+Math.imul(Le,Je)|0,g=g+Math.imul(je,Xe)|0,f=f+Math.imul(je,Ye)|0,f=f+Math.imul(Fe,Xe)|0,v=v+Math.imul(Fe,Ye)|0,g=g+Math.imul(Ne,Qe)|0,f=f+Math.imul(Ne,et)|0,f=f+Math.imul(Re,Qe)|0,v=v+Math.imul(Re,et)|0,g=g+Math.imul(De,tt)|0,f=f+Math.imul(De,rt)|0,f=f+Math.imul(Be,tt)|0,v=v+Math.imul(Be,rt)|0,g=g+Math.imul(Ae,nt)|0,f=f+Math.imul(Ae,it)|0,f=f+Math.imul(Me,nt)|0,v=v+Math.imul(Me,it)|0,g=g+Math.imul(ve,ot)|0,f=f+Math.imul(ve,st)|0,f=f+Math.imul(xe,ot)|0,v=v+Math.imul(xe,st)|0,g=g+Math.imul(te,at)|0,f=f+Math.imul(te,ut)|0,f=f+Math.imul(ae,at)|0,v=v+Math.imul(ae,ut)|0;var Fs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Fs>>>26)|0,Fs&=67108863,g=Math.imul(Ue,Ke),f=Math.imul(Ue,Je),f=f+Math.imul($e,Ke)|0,v=Math.imul($e,Je),g=g+Math.imul(qe,Xe)|0,f=f+Math.imul(qe,Ye)|0,f=f+Math.imul(Le,Xe)|0,v=v+Math.imul(Le,Ye)|0,g=g+Math.imul(je,Qe)|0,f=f+Math.imul(je,et)|0,f=f+Math.imul(Fe,Qe)|0,v=v+Math.imul(Fe,et)|0,g=g+Math.imul(Ne,tt)|0,f=f+Math.imul(Ne,rt)|0,f=f+Math.imul(Re,tt)|0,v=v+Math.imul(Re,rt)|0,g=g+Math.imul(De,nt)|0,f=f+Math.imul(De,it)|0,f=f+Math.imul(Be,nt)|0,v=v+Math.imul(Be,it)|0,g=g+Math.imul(Ae,ot)|0,f=f+Math.imul(Ae,st)|0,f=f+Math.imul(Me,ot)|0,v=v+Math.imul(Me,st)|0,g=g+Math.imul(ve,at)|0,f=f+Math.imul(ve,ut)|0,f=f+Math.imul(xe,at)|0,v=v+Math.imul(xe,ut)|0;var qs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(qs>>>26)|0,qs&=67108863,g=Math.imul(Ue,Xe),f=Math.imul(Ue,Ye),f=f+Math.imul($e,Xe)|0,v=Math.imul($e,Ye),g=g+Math.imul(qe,Qe)|0,f=f+Math.imul(qe,et)|0,f=f+Math.imul(Le,Qe)|0,v=v+Math.imul(Le,et)|0,g=g+Math.imul(je,tt)|0,f=f+Math.imul(je,rt)|0,f=f+Math.imul(Fe,tt)|0,v=v+Math.imul(Fe,rt)|0,g=g+Math.imul(Ne,nt)|0,f=f+Math.imul(Ne,it)|0,f=f+Math.imul(Re,nt)|0,v=v+Math.imul(Re,it)|0,g=g+Math.imul(De,ot)|0,f=f+Math.imul(De,st)|0,f=f+Math.imul(Be,ot)|0,v=v+Math.imul(Be,st)|0,g=g+Math.imul(Ae,at)|0,f=f+Math.imul(Ae,ut)|0,f=f+Math.imul(Me,at)|0,v=v+Math.imul(Me,ut)|0;var Ls=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ls>>>26)|0,Ls&=67108863,g=Math.imul(Ue,Qe),f=Math.imul(Ue,et),f=f+Math.imul($e,Qe)|0,v=Math.imul($e,et),g=g+Math.imul(qe,tt)|0,f=f+Math.imul(qe,rt)|0,f=f+Math.imul(Le,tt)|0,v=v+Math.imul(Le,rt)|0,g=g+Math.imul(je,nt)|0,f=f+Math.imul(je,it)|0,f=f+Math.imul(Fe,nt)|0,v=v+Math.imul(Fe,it)|0,g=g+Math.imul(Ne,ot)|0,f=f+Math.imul(Ne,st)|0,f=f+Math.imul(Re,ot)|0,v=v+Math.imul(Re,st)|0,g=g+Math.imul(De,at)|0,f=f+Math.imul(De,ut)|0,f=f+Math.imul(Be,at)|0,v=v+Math.imul(Be,ut)|0;var Us=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Us>>>26)|0,Us&=67108863,g=Math.imul(Ue,tt),f=Math.imul(Ue,rt),f=f+Math.imul($e,tt)|0,v=Math.imul($e,rt),g=g+Math.imul(qe,nt)|0,f=f+Math.imul(qe,it)|0,f=f+Math.imul(Le,nt)|0,v=v+Math.imul(Le,it)|0,g=g+Math.imul(je,ot)|0,f=f+Math.imul(je,st)|0,f=f+Math.imul(Fe,ot)|0,v=v+Math.imul(Fe,st)|0,g=g+Math.imul(Ne,at)|0,f=f+Math.imul(Ne,ut)|0,f=f+Math.imul(Re,at)|0,v=v+Math.imul(Re,ut)|0;var $s=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+($s>>>26)|0,$s&=67108863,g=Math.imul(Ue,nt),f=Math.imul(Ue,it),f=f+Math.imul($e,nt)|0,v=Math.imul($e,it),g=g+Math.imul(qe,ot)|0,f=f+Math.imul(qe,st)|0,f=f+Math.imul(Le,ot)|0,v=v+Math.imul(Le,st)|0,g=g+Math.imul(je,at)|0,f=f+Math.imul(je,ut)|0,f=f+Math.imul(Fe,at)|0,v=v+Math.imul(Fe,ut)|0;var Gs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Gs>>>26)|0,Gs&=67108863,g=Math.imul(Ue,ot),f=Math.imul(Ue,st),f=f+Math.imul($e,ot)|0,v=Math.imul($e,st),g=g+Math.imul(qe,at)|0,f=f+Math.imul(qe,ut)|0,f=f+Math.imul(Le,at)|0,v=v+Math.imul(Le,ut)|0;var Vs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Vs>>>26)|0,Vs&=67108863,g=Math.imul(Ue,at),f=Math.imul(Ue,ut),f=f+Math.imul($e,at)|0,v=Math.imul($e,ut);var zs=(w+g|0)+((f&8191)<<13)|0;return w=(v+(f>>>13)|0)+(zs>>>26)|0,zs&=67108863,h[0]=Is,h[1]=Cs,h[2]=Os,h[3]=Ms,h[4]=Es,h[5]=Ps,h[6]=Ds,h[7]=Bs,h[8]=Ns,h[9]=Rs,h[10]=js,h[11]=Fs,h[12]=qs,h[13]=Ls,h[14]=Us,h[15]=$s,h[16]=Gs,h[17]=Vs,h[18]=zs,w!==0&&(h[19]=w,m.length++),m};Math.imul||(E=C);function P(k,a,c){c.negative=a.negative^k.negative,c.length=k.length+a.length;for(var m=0,y=0,p=0;p<c.length-1;p++){var h=y;y=0;for(var w=m&67108863,g=Math.min(p,a.length-1),f=Math.max(0,p-k.length+1);f<=g;f++){var v=p-f,O=k.words[v]|0,M=a.words[f]|0,R=O*M,B=R&67108863;h=h+(R/67108864|0)|0,B=B+w|0,w=B&67108863,h=h+(B>>>26)|0,y+=h>>>26,h&=67108863}c.words[p]=w,m=h,h=y}return m!==0?c.words[p]=m:c.length--,c._strip()}function D(k,a,c){return P(k,a,c)}i.prototype.mulTo=function(a,c){var m,y=this.length+a.length;return this.length===10&&a.length===10?m=E(this,a,c):y<63?m=C(this,a,c):y<1024?m=P(this,a,c):m=D(this,a,c),m};function L(k,a){this.x=k,this.y=a}L.prototype.makeRBT=function(a){for(var c=new Array(a),m=i.prototype._countBits(a)-1,y=0;y<a;y++)c[y]=this.revBin(y,m,a);return c},L.prototype.revBin=function(a,c,m){if(a===0||a===m-1)return a;for(var y=0,p=0;p<c;p++)y|=(a&1)<<c-p-1,a>>=1;return y},L.prototype.permute=function(a,c,m,y,p,h){for(var w=0;w<h;w++)y[w]=c[a[w]],p[w]=m[a[w]]},L.prototype.transform=function(a,c,m,y,p,h){this.permute(h,a,c,m,y,p);for(var w=1;w<p;w<<=1)for(var g=w<<1,f=Math.cos(2*Math.PI/g),v=Math.sin(2*Math.PI/g),O=0;O<p;O+=g)for(var M=f,R=v,B=0;B<w;B++){var G=m[O+B],Z=y[O+B],oe=m[O+B+w],te=y[O+B+w],ae=M*oe-R*te;te=M*te+R*oe,oe=ae,m[O+B]=G+oe,y[O+B]=Z+te,m[O+B+w]=G-oe,y[O+B+w]=Z-te,B!==g&&(ae=f*M-v*R,R=f*R+v*M,M=ae)}},L.prototype.guessLen13b=function(a,c){var m=Math.max(c,a)|1,y=m&1,p=0;for(m=m/2|0;m;m=m>>>1)p++;return 1<<p+1+y},L.prototype.conjugate=function(a,c,m){if(!(m<=1))for(var y=0;y<m/2;y++){var p=a[y];a[y]=a[m-y-1],a[m-y-1]=p,p=c[y],c[y]=-c[m-y-1],c[m-y-1]=-p}},L.prototype.normalize13b=function(a,c){for(var m=0,y=0;y<c/2;y++){var p=Math.round(a[2*y+1]/c)*8192+Math.round(a[2*y]/c)+m;a[y]=p&67108863,p<67108864?m=0:m=p/67108864|0}return a},L.prototype.convert13b=function(a,c,m,y){for(var p=0,h=0;h<c;h++)p=p+(a[h]|0),m[2*h]=p&8191,p=p>>>13,m[2*h+1]=p&8191,p=p>>>13;for(h=2*c;h<y;++h)m[h]=0;r(p===0),r((p&-8192)===0)},L.prototype.stub=function(a){for(var c=new Array(a),m=0;m<a;m++)c[m]=0;return c},L.prototype.mulp=function(a,c,m){var y=2*this.guessLen13b(a.length,c.length),p=this.makeRBT(y),h=this.stub(y),w=new Array(y),g=new Array(y),f=new Array(y),v=new Array(y),O=new Array(y),M=new Array(y),R=m.words;R.length=y,this.convert13b(a.words,a.length,w,y),this.convert13b(c.words,c.length,v,y),this.transform(w,h,g,f,y,p),this.transform(v,h,O,M,y,p);for(var B=0;B<y;B++){var G=g[B]*O[B]-f[B]*M[B];f[B]=g[B]*M[B]+f[B]*O[B],g[B]=G}return this.conjugate(g,f,y),this.transform(g,f,R,h,y,p),this.conjugate(R,h,y),this.normalize13b(R,y),m.negative=a.negative^c.negative,m.length=a.length+c.length,m._strip()},i.prototype.mul=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),this.mulTo(a,c)},i.prototype.mulf=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),D(this,a,c)},i.prototype.imul=function(a){return this.clone().mulTo(a,this)},i.prototype.imuln=function(a){var c=a<0;c&&(a=-a),r(typeof a=="number"),r(a<67108864);for(var m=0,y=0;y<this.length;y++){var p=(this.words[y]|0)*a,h=(p&67108863)+(m&67108863);m>>=26,m+=p/67108864|0,m+=h>>>26,this.words[y]=h&67108863}return m!==0&&(this.words[y]=m,this.length++),c?this.ineg():this},i.prototype.muln=function(a){return this.clone().imuln(a)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(a){var c=I(a);if(c.length===0)return new i(1);for(var m=this,y=0;y<c.length&&c[y]===0;y++,m=m.sqr());if(++y<c.length)for(var p=m.sqr();y<c.length;y++,p=p.sqr())c[y]!==0&&(m=m.mul(p));return m},i.prototype.iushln=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=67108863>>>26-c<<26-c,p;if(c!==0){var h=0;for(p=0;p<this.length;p++){var w=this.words[p]&y,g=(this.words[p]|0)-w<<c;this.words[p]=g|h,h=w>>>26-c}h&&(this.words[p]=h,this.length++)}if(m!==0){for(p=this.length-1;p>=0;p--)this.words[p+m]=this.words[p];for(p=0;p<m;p++)this.words[p]=0;this.length+=m}return this._strip()},i.prototype.ishln=function(a){return r(this.negative===0),this.iushln(a)},i.prototype.iushrn=function(a,c,m){r(typeof a=="number"&&a>=0);var y;c?y=(c-c%26)/26:y=0;var p=a%26,h=Math.min((a-p)/26,this.length),w=67108863^67108863>>>p<<p,g=m;if(y-=h,y=Math.max(0,y),g){for(var f=0;f<h;f++)g.words[f]=this.words[f];g.length=h}if(h!==0)if(this.length>h)for(this.length-=h,f=0;f<this.length;f++)this.words[f]=this.words[f+h];else this.words[0]=0,this.length=1;var v=0;for(f=this.length-1;f>=0&&(v!==0||f>=y);f--){var O=this.words[f]|0;this.words[f]=v<<26-p|O>>>p,v=O&w}return g&&v!==0&&(g.words[g.length++]=v),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(a,c,m){return r(this.negative===0),this.iushrn(a,c,m)},i.prototype.shln=function(a){return this.clone().ishln(a)},i.prototype.ushln=function(a){return this.clone().iushln(a)},i.prototype.shrn=function(a){return this.clone().ishrn(a)},i.prototype.ushrn=function(a){return this.clone().iushrn(a)},i.prototype.testn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return!1;var p=this.words[m];return!!(p&y)},i.prototype.imaskn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(c!==0&&m++,this.length=Math.min(m,this.length),c!==0){var y=67108863^67108863>>>c<<c;this.words[this.length-1]&=y}return this._strip()},i.prototype.maskn=function(a){return this.clone().imaskn(a)},i.prototype.iaddn=function(a){return r(typeof a=="number"),r(a<67108864),a<0?this.isubn(-a):this.negative!==0?this.length===1&&(this.words[0]|0)<=a?(this.words[0]=a-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(a),this.negative=1,this):this._iaddn(a)},i.prototype._iaddn=function(a){this.words[0]+=a;for(var c=0;c<this.length&&this.words[c]>=67108864;c++)this.words[c]-=67108864,c===this.length-1?this.words[c+1]=1:this.words[c+1]++;return this.length=Math.max(this.length,c+1),this},i.prototype.isubn=function(a){if(r(typeof a=="number"),r(a<67108864),a<0)return this.iaddn(-a);if(this.negative!==0)return this.negative=0,this.iaddn(a),this.negative=1,this;if(this.words[0]-=a,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var c=0;c<this.length&&this.words[c]<0;c++)this.words[c]+=67108864,this.words[c+1]-=1;return this._strip()},i.prototype.addn=function(a){return this.clone().iaddn(a)},i.prototype.subn=function(a){return this.clone().isubn(a)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(a,c,m){var y=a.length+m,p;this._expand(y);var h,w=0;for(p=0;p<a.length;p++){h=(this.words[p+m]|0)+w;var g=(a.words[p]|0)*c;h-=g&67108863,w=(h>>26)-(g/67108864|0),this.words[p+m]=h&67108863}for(;p<this.length-m;p++)h=(this.words[p+m]|0)+w,w=h>>26,this.words[p+m]=h&67108863;if(w===0)return this._strip();for(r(w===-1),w=0,p=0;p<this.length;p++)h=-(this.words[p]|0)+w,w=h>>26,this.words[p]=h&67108863;return this.negative=1,this._strip()},i.prototype._wordDiv=function(a,c){var m=this.length-a.length,y=this.clone(),p=a,h=p.words[p.length-1]|0,w=this._countBits(h);m=26-w,m!==0&&(p=p.ushln(m),y.iushln(m),h=p.words[p.length-1]|0);var g=y.length-p.length,f;if(c!=="mod"){f=new i(null),f.length=g+1,f.words=new Array(f.length);for(var v=0;v<f.length;v++)f.words[v]=0}var O=y.clone()._ishlnsubmul(p,1,g);O.negative===0&&(y=O,f&&(f.words[g]=1));for(var M=g-1;M>=0;M--){var R=(y.words[p.length+M]|0)*67108864+(y.words[p.length+M-1]|0);for(R=Math.min(R/h|0,67108863),y._ishlnsubmul(p,R,M);y.negative!==0;)R--,y.negative=0,y._ishlnsubmul(p,1,M),y.isZero()||(y.negative^=1);f&&(f.words[M]=R)}return f&&f._strip(),y._strip(),c!=="div"&&m!==0&&y.iushrn(m),{div:f||null,mod:y}},i.prototype.divmod=function(a,c,m){if(r(!a.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var y,p,h;return this.negative!==0&&a.negative===0?(h=this.neg().divmod(a,c),c!=="mod"&&(y=h.div.neg()),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.iadd(a)),{div:y,mod:p}):this.negative===0&&a.negative!==0?(h=this.divmod(a.neg(),c),c!=="mod"&&(y=h.div.neg()),{div:y,mod:h.mod}):this.negative&a.negative?(h=this.neg().divmod(a.neg(),c),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.isub(a)),{div:h.div,mod:p}):a.length>this.length||this.cmp(a)<0?{div:new i(0),mod:this}:a.length===1?c==="div"?{div:this.divn(a.words[0]),mod:null}:c==="mod"?{div:null,mod:new i(this.modrn(a.words[0]))}:{div:this.divn(a.words[0]),mod:new i(this.modrn(a.words[0]))}:this._wordDiv(a,c)},i.prototype.div=function(a){return this.divmod(a,"div",!1).div},i.prototype.mod=function(a){return this.divmod(a,"mod",!1).mod},i.prototype.umod=function(a){return this.divmod(a,"mod",!0).mod},i.prototype.divRound=function(a){var c=this.divmod(a);if(c.mod.isZero())return c.div;var m=c.div.negative!==0?c.mod.isub(a):c.mod,y=a.ushrn(1),p=a.andln(1),h=m.cmp(y);return h<0||p===1&&h===0?c.div:c.div.negative!==0?c.div.isubn(1):c.div.iaddn(1)},i.prototype.modrn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=(1<<26)%a,y=0,p=this.length-1;p>=0;p--)y=(m*y+(this.words[p]|0))%a;return c?-y:y},i.prototype.modn=function(a){return this.modrn(a)},i.prototype.idivn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=0,y=this.length-1;y>=0;y--){var p=(this.words[y]|0)+m*67108864;this.words[y]=p/a|0,m=p%a}return this._strip(),c?this.ineg():this},i.prototype.divn=function(a){return this.clone().idivn(a)},i.prototype.egcd=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=new i(0),w=new i(1),g=0;c.isEven()&&m.isEven();)c.iushrn(1),m.iushrn(1),++g;for(var f=m.clone(),v=c.clone();!c.isZero();){for(var O=0,M=1;!(c.words[0]&M)&&O<26;++O,M<<=1);if(O>0)for(c.iushrn(O);O-- >0;)(y.isOdd()||p.isOdd())&&(y.iadd(f),p.isub(v)),y.iushrn(1),p.iushrn(1);for(var R=0,B=1;!(m.words[0]&B)&&R<26;++R,B<<=1);if(R>0)for(m.iushrn(R);R-- >0;)(h.isOdd()||w.isOdd())&&(h.iadd(f),w.isub(v)),h.iushrn(1),w.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(h),p.isub(w)):(m.isub(c),h.isub(y),w.isub(p))}return{a:h,b:w,gcd:m.iushln(g)}},i.prototype._invmp=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=m.clone();c.cmpn(1)>0&&m.cmpn(1)>0;){for(var w=0,g=1;!(c.words[0]&g)&&w<26;++w,g<<=1);if(w>0)for(c.iushrn(w);w-- >0;)y.isOdd()&&y.iadd(h),y.iushrn(1);for(var f=0,v=1;!(m.words[0]&v)&&f<26;++f,v<<=1);if(f>0)for(m.iushrn(f);f-- >0;)p.isOdd()&&p.iadd(h),p.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(p)):(m.isub(c),p.isub(y))}var O;return c.cmpn(1)===0?O=y:O=p,O.cmpn(0)<0&&O.iadd(a),O},i.prototype.gcd=function(a){if(this.isZero())return a.abs();if(a.isZero())return this.abs();var c=this.clone(),m=a.clone();c.negative=0,m.negative=0;for(var y=0;c.isEven()&&m.isEven();y++)c.iushrn(1),m.iushrn(1);do{for(;c.isEven();)c.iushrn(1);for(;m.isEven();)m.iushrn(1);var p=c.cmp(m);if(p<0){var h=c;c=m,m=h}else if(p===0||m.cmpn(1)===0)break;c.isub(m)}while(!0);return m.iushln(y)},i.prototype.invm=function(a){return this.egcd(a).a.umod(a)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(a){return this.words[0]&a},i.prototype.bincn=function(a){r(typeof a=="number");var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return this._expand(m+1),this.words[m]|=y,this;for(var p=y,h=m;p!==0&&h<this.length;h++){var w=this.words[h]|0;w+=p,p=w>>>26,w&=67108863,this.words[h]=w}return p!==0&&(this.words[h]=p,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(a){var c=a<0;if(this.negative!==0&&!c)return-1;if(this.negative===0&&c)return 1;this._strip();var m;if(this.length>1)m=1;else{c&&(a=-a),r(a<=67108863,"Number is too big");var y=this.words[0]|0;m=y===a?0:y<a?-1:1}return this.negative!==0?-m|0:m},i.prototype.cmp=function(a){if(this.negative!==0&&a.negative===0)return-1;if(this.negative===0&&a.negative!==0)return 1;var c=this.ucmp(a);return this.negative!==0?-c|0:c},i.prototype.ucmp=function(a){if(this.length>a.length)return 1;if(this.length<a.length)return-1;for(var c=0,m=this.length-1;m>=0;m--){var y=this.words[m]|0,p=a.words[m]|0;if(y!==p){y<p?c=-1:y>p&&(c=1);break}}return c},i.prototype.gtn=function(a){return this.cmpn(a)===1},i.prototype.gt=function(a){return this.cmp(a)===1},i.prototype.gten=function(a){return this.cmpn(a)>=0},i.prototype.gte=function(a){return this.cmp(a)>=0},i.prototype.ltn=function(a){return this.cmpn(a)===-1},i.prototype.lt=function(a){return this.cmp(a)===-1},i.prototype.lten=function(a){return this.cmpn(a)<=0},i.prototype.lte=function(a){return this.cmp(a)<=0},i.prototype.eqn=function(a){return this.cmpn(a)===0},i.prototype.eq=function(a){return this.cmp(a)===0},i.red=function(a){return new j(a)},i.prototype.toRed=function(a){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),a.convertTo(this)._forceRed(a)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(a){return this.red=a,this},i.prototype.forceRed=function(a){return r(!this.red,"Already a number in reduction context"),this._forceRed(a)},i.prototype.redAdd=function(a){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,a)},i.prototype.redIAdd=function(a){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,a)},i.prototype.redSub=function(a){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,a)},i.prototype.redISub=function(a){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,a)},i.prototype.redShl=function(a){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,a)},i.prototype.redMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.mul(this,a)},i.prototype.redIMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.imul(this,a)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(a){return r(this.red&&!a.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,a)};var H={k256:null,p224:null,p192:null,p25519:null};function W(k,a){this.name=k,this.p=new i(a,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}W.prototype._tmp=function(){var a=new i(null);return a.words=new Array(Math.ceil(this.n/13)),a},W.prototype.ireduce=function(a){var c=a,m;do this.split(c,this.tmp),c=this.imulK(c),c=c.iadd(this.tmp),m=c.bitLength();while(m>this.n);var y=m<this.n?-1:c.ucmp(this.p);return y===0?(c.words[0]=0,c.length=1):y>0?c.isub(this.p):c.strip!==void 0?c.strip():c._strip(),c},W.prototype.split=function(a,c){a.iushrn(this.n,0,c)},W.prototype.imulK=function(a){return a.imul(this.k)};function K(){W.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(K,W),K.prototype.split=function(a,c){for(var m=4194303,y=Math.min(a.length,9),p=0;p<y;p++)c.words[p]=a.words[p];if(c.length=y,a.length<=9){a.words[0]=0,a.length=1;return}var h=a.words[9];for(c.words[c.length++]=h&m,p=10;p<a.length;p++){var w=a.words[p]|0;a.words[p-10]=(w&m)<<4|h>>>22,h=w}h>>>=22,a.words[p-10]=h,h===0&&a.length>10?a.length-=10:a.length-=9},K.prototype.imulK=function(a){a.words[a.length]=0,a.words[a.length+1]=0,a.length+=2;for(var c=0,m=0;m<a.length;m++){var y=a.words[m]|0;c+=y*977,a.words[m]=c&67108863,c=y*64+(c/67108864|0)}return a.words[a.length-1]===0&&(a.length--,a.words[a.length-1]===0&&a.length--),a};function F(){W.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(F,W);function U(){W.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(U,W);function N(){W.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(N,W),N.prototype.imulK=function(a){for(var c=0,m=0;m<a.length;m++){var y=(a.words[m]|0)*19+c,p=y&67108863;y>>>=26,a.words[m]=p,c=y}return c!==0&&(a.words[a.length++]=c),a},i._prime=function(a){if(H[a])return H[a];var c;if(a==="k256")c=new K;else if(a==="p224")c=new F;else if(a==="p192")c=new U;else if(a==="p25519")c=new N;else throw new Error("Unknown prime "+a);return H[a]=c,c};function j(k){if(typeof k=="string"){var a=i._prime(k);this.m=a.p,this.prime=a}else r(k.gtn(1),"modulus must be greater than 1"),this.m=k,this.prime=null}j.prototype._verify1=function(a){r(a.negative===0,"red works only with positives"),r(a.red,"red works only with red numbers")},j.prototype._verify2=function(a,c){r((a.negative|c.negative)===0,"red works only with positives"),r(a.red&&a.red===c.red,"red works only with red numbers")},j.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(d(a,a.umod(this.m)._forceRed(this)),a)},j.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},j.prototype.add=function(a,c){this._verify2(a,c);var m=a.add(c);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},j.prototype.iadd=function(a,c){this._verify2(a,c);var m=a.iadd(c);return m.cmp(this.m)>=0&&m.isub(this.m),m},j.prototype.sub=function(a,c){this._verify2(a,c);var m=a.sub(c);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},j.prototype.isub=function(a,c){this._verify2(a,c);var m=a.isub(c);return m.cmpn(0)<0&&m.iadd(this.m),m},j.prototype.shl=function(a,c){return this._verify1(a),this.imod(a.ushln(c))},j.prototype.imul=function(a,c){return this._verify2(a,c),this.imod(a.imul(c))},j.prototype.mul=function(a,c){return this._verify2(a,c),this.imod(a.mul(c))},j.prototype.isqr=function(a){return this.imul(a,a.clone())},j.prototype.sqr=function(a){return this.mul(a,a)},j.prototype.sqrt=function(a){if(a.isZero())return a.clone();var c=this.m.andln(3);if(r(c%2===1),c===3){var m=this.m.add(new i(1)).iushrn(2);return this.pow(a,m)}for(var y=this.m.subn(1),p=0;!y.isZero()&&y.andln(1)===0;)p++,y.iushrn(1);r(!y.isZero());var h=new i(1).toRed(this),w=h.redNeg(),g=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);this.pow(f,g).cmp(w)!==0;)f.redIAdd(w);for(var v=this.pow(f,y),O=this.pow(a,y.addn(1).iushrn(1)),M=this.pow(a,y),R=p;M.cmp(h)!==0;){for(var B=M,G=0;B.cmp(h)!==0;G++)B=B.redSqr();r(G<R);var Z=this.pow(v,new i(1).iushln(R-G-1));O=O.redMul(Z),v=Z.redSqr(),M=M.redMul(v),R=G}return O},j.prototype.invm=function(a){var c=a._invmp(this.m);return c.negative!==0?(c.negative=0,this.imod(c).redNeg()):this.imod(c)},j.prototype.pow=function(a,c){if(c.isZero())return new i(1).toRed(this);if(c.cmpn(1)===0)return a.clone();var m=4,y=new Array(1<<m);y[0]=new i(1).toRed(this),y[1]=a;for(var p=2;p<y.length;p++)y[p]=this.mul(y[p-1],a);var h=y[0],w=0,g=0,f=c.bitLength()%26;for(f===0&&(f=26),p=c.length-1;p>=0;p--){for(var v=c.words[p],O=f-1;O>=0;O--){var M=v>>O&1;if(h!==y[0]&&(h=this.sqr(h)),M===0&&w===0){g=0;continue}w<<=1,w|=M,g++,!(g!==m&&(p!==0||O!==0))&&(h=this.mul(h,y[w]),g=0,w=0)}f=26}return h},j.prototype.convertTo=function(a){var c=a.umod(this.m);return c===a?c.clone():c},j.prototype.convertFrom=function(a){var c=a.clone();return c.red=null,c},i.mont=function(a){return new S(a)};function S(k){j.call(this,k),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(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)}n(S,j),S.prototype.convertTo=function(a){return this.imod(a.ushln(this.shift))},S.prototype.convertFrom=function(a){var c=this.imod(a.mul(this.rinv));return c.red=null,c},S.prototype.imul=function(a,c){if(a.isZero()||c.isZero())return a.words[0]=0,a.length=1,a;var m=a.imul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.mul=function(a,c){if(a.isZero()||c.isZero())return new i(0)._forceRed(this);var m=a.mul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.invm=function(a){var c=this.imod(a._invmp(this.m).mul(this.r2));return c._forceRed(this)}})(typeof Zs>"u"||Zs,Ic)});var ll={};fc(ll,{__addDisposableResource:()=>ul,__assign:()=>eo,__asyncDelegator:()=>el,__asyncGenerator:()=>Qc,__asyncValues:()=>tl,__await:()=>fn,__awaiter:()=>Hc,__classPrivateFieldGet:()=>ol,__classPrivateFieldIn:()=>al,__classPrivateFieldSet:()=>sl,__createBinding:()=>ro,__decorate:()=>Vc,__disposeResources:()=>cl,__esDecorate:()=>ng,__exportStar:()=>Kc,__extends:()=>$c,__generator:()=>Zc,__importDefault:()=>il,__importStar:()=>nl,__makeTemplateObject:()=>rl,__metadata:()=>Wc,__param:()=>zc,__propKey:()=>og,__read:()=>ia,__rest:()=>Gc,__runInitializers:()=>ig,__setFunctionName:()=>sg,__spread:()=>Jc,__spreadArray:()=>Yc,__spreadArrays:()=>Xc,__values:()=>to,default:()=>cg});function $c(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");na(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Gc(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<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Vc(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var u=t.length-1;u>=0;u--)(s=t[u])&&(o=(i<3?s(o):i>3?s(e,r,o):s(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function zc(t,e){return function(r,n){e(r,n,t)}}function ng(t,e,r,n,i,o){function s(E){if(E!==void 0&&typeof E!="function")throw new TypeError("Function expected");return E}for(var u=n.kind,l=u==="getter"?"get":u==="setter"?"set":"value",d=!e&&t?n.static?t:t.prototype:null,b=e||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),_,T=!1,x=r.length-1;x>=0;x--){var A={};for(var I in n)A[I]=I==="access"?{}:n[I];for(var I in n.access)A.access[I]=n.access[I];A.addInitializer=function(E){if(T)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(E||null))};var C=(0,r[x])(u==="accessor"?{get:b.get,set:b.set}:b[l],A);if(u==="accessor"){if(C===void 0)continue;if(C===null||typeof C!="object")throw new TypeError("Object expected");(_=s(C.get))&&(b.get=_),(_=s(C.set))&&(b.set=_),(_=s(C.init))&&i.unshift(_)}else(_=s(C))&&(u==="field"?i.unshift(_):b[l]=_)}d&&Object.defineProperty(d,n.name,b),T=!0}function ig(t,e,r){for(var n=arguments.length>2,i=0;i<e.length;i++)r=n?e[i].call(t,r):e[i].call(t);return n?r:void 0}function og(t){return typeof t=="symbol"?t:"".concat(t)}function sg(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function Wc(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Hc(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function u(b){try{d(n.next(b))}catch(_){s(_)}}function l(b){try{d(n.throw(b))}catch(_){s(_)}}function d(b){b.done?o(b.value):i(b.value).then(u,l)}d((n=n.apply(t,e||[])).next())})}function Zc(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(d){return function(b){return l([d,b])}}function l(d){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(r=0)),r;)try{if(n=1,i&&(o=d[0]&2?i.return:d[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,d[1])).done)return o;switch(i=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,i=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){r.label=d[1];break}if(d[0]===6&&r.label<o[1]){r.label=o[1],o=d;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(d);break}o[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(b){d=[6,b],i=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function Kc(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ro(e,t,r)}function to(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=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 ia(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function Jc(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ia(arguments[e]));return t}function Xc(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],s=0,u=o.length;s<u;s++,i++)n[i]=o[s];return n}function Yc(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}function fn(t){return this instanceof fn?(this.v=t,this):new fn(t)}function Qc(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(T){n[T]&&(i[T]=function(x){return new Promise(function(A,I){o.push([T,x,A,I])>1||u(T,x)})})}function u(T,x){try{l(n[T](x))}catch(A){_(o[0][3],A)}}function l(T){T.value instanceof fn?Promise.resolve(T.value.v).then(d,b):_(o[0][2],T)}function d(T){u("next",T)}function b(T){u("throw",T)}function _(T,x){T(x),o.shift(),o.length&&u(o[0][0],o[0][1])}}function el(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,o){e[i]=t[i]?function(s){return(r=!r)?{value:fn(t[i](s)),done:!1}:o?o(s):s}:o}}function tl(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 to=="function"?to(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(u,l){s=t[o](s),i(u,l,s.done,s.value)})}}function i(o,s,u,l){Promise.resolve(l).then(function(d){o({value:d,done:u})},s)}}function rl(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function nl(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)&&ro(e,t,r);return ag(e,t),e}function il(t){return t&&t.__esModule?t:{default:t}}function ol(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function sl(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function al(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function ul(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function cl(t){function e(n){t.error=t.hasError?new ug(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}function r(){for(;t.stack.length;){var n=t.stack.pop();try{var i=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(i).then(r,function(o){return e(o),r()})}catch(o){e(o)}}if(t.hasError)throw t.error}return r()}var na,eo,ro,ag,ug,cg,dl=Yp(()=>{"use strict";na=function(t,e){return na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},na(t,e)};eo=function(){return eo=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},eo.apply(this,arguments)};ro=Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]};ag=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};ug=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};cg={__extends:$c,__assign:eo,__rest:Gc,__decorate:Vc,__param:zc,__metadata:Wc,__awaiter:Hc,__generator:Zc,__createBinding:ro,__exportStar:Kc,__values:to,__read:ia,__spread:Jc,__spreadArrays:Xc,__spreadArray:Yc,__await:fn,__asyncGenerator:Qc,__asyncDelegator:el,__asyncValues:tl,__makeTemplateObject:rl,__importStar:nl,__importDefault:il,__classPrivateFieldGet:ol,__classPrivateFieldSet:sl,__classPrivateFieldIn:al,__addDisposableResource:ul,__disposeResources:cl}});var hl=Fr((no,fl)=>{"use strict";(function(t,e){typeof no=="object"&&typeof fl<"u"?e(no,(dl(),pc(ll))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(no,function(t,e){"use strict";var r=function(){function p(h,w,g){g===void 0&&(g=0),this.startVertex=h,this.endVertex=w,this.weight=g}return p.prototype.getKey=function(){var h=this.startVertex.getKey(),w=this.endVertex.getKey();return h+"_"+w},p.prototype.reverse=function(){var h=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=h,this},p.prototype.clone=function(){return new p(this.startVertex,this.endVertex,this.weight)},p.prototype.toString=function(){return this.getKey()},p}();function n(p,h,w){if(w===void 0&&(w="cc-graph"),!p)throw new Error((w?"["+w+"]":"")+" Invariant failed: "+h)}function i(p,h){h===void 0&&(h=!0);var w=typeof p<"u"&&p!==null;return h?w&&p!=="undefined"&&p!=="null":w}var o=function(){function p(h){n(i(h),"Graph vertex must have a value"),this.value=h,this.edges=new Map}return p.prototype.addEdge=function(h){return this.edges.set(h.getKey(),h),this},p.prototype.deleteEdge=function(h){this.edges.delete(h.getKey())},p.prototype.getNeighbors=function(){var h=this,w=this.getEdges(),g=function(f){return f.startVertex===h?f.endVertex:f.startVertex};return w.map(g)},p.prototype.getEdges=function(){return Array.from(this.edges.values())},p.prototype.getDegree=function(){return this.getEdges().length},p.prototype.hasEdge=function(h){var w=this.getEdges().find(function(g){return g===h});return!!w},p.prototype.hasNeighbor=function(h){var w=this.getEdges().find(function(g){return g.startVertex===h||g.endVertex===h});return!!w},p.prototype.findEdge=function(h){var w=function(f){return f.startVertex===h||f.endVertex===h},g=this.getEdges().find(w);return g||null},p.prototype.getKey=function(){return this.value},p.prototype.deleteAllEdges=function(){var h=this;return this.getEdges().forEach(function(w){return h.deleteEdge(w)}),this},p.prototype.toString=function(h){return h?h(this.value):""+this.value},p}(),s;(function(p){p[p.EQUAL=0]="EQUAL",p[p.GREATER=1]="GREATER",p[p.LESS=-1]="LESS"})(s||(s={}));var u=function(){function p(h){this.compare=h||p.defaultCompareFunction}return p.defaultCompareFunction=function(h,w){return h===w?s.EQUAL:h<w?s.LESS:s.GREATER},p.prototype.equal=function(h,w){return this.compare(h,w)===s.EQUAL},p.prototype.lessThan=function(h,w){return this.compare(h,w)===s.LESS},p.prototype.greaterThan=function(h,w){return this.compare(h,w)===s.GREATER},p.prototype.lessThanOrEqual=function(h,w){return this.lessThan(h,w)||this.equal(h,w)},p.prototype.greaterThanOrEqual=function(h,w){return this.greaterThan(h,w)||this.equal(h,w)},p.prototype.reverse=function(){var h=this.compare;this.compare=function(w,g){return h(g,w)}},p}(),l=function(){function p(h){this.value=h,this.next=null}return p}(),d=function(){function p(h){this.value=h,this.next=null,this.prev=null}return p}();var b=function(p,h){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,g){w.__proto__=g}||function(w,g){for(var f in g)g.hasOwnProperty(f)&&(w[f]=g[f])},b(p,h)};function _(p,h){b(p,h);function w(){this.constructor=p}p.prototype=h===null?Object.create(h):(w.prototype=h.prototype,new w)}function T(p,h){var w={label:0,sent:function(){if(v[0]&1)throw v[1];return v[1]},trys:[],ops:[]},g,f,v,O;return O={next:M(0),throw:M(1),return:M(2)},typeof Symbol=="function"&&(O[Symbol.iterator]=function(){return this}),O;function M(B){return function(G){return R([B,G])}}function R(B){if(g)throw new TypeError("Generator is already executing.");for(;w;)try{if(g=1,f&&(v=B[0]&2?f.return:B[0]?f.throw||((v=f.return)&&v.call(f),0):f.next)&&!(v=v.call(f,B[1])).done)return v;switch(f=0,v&&(B=[B[0]&2,v.value]),B[0]){case 0:case 1:v=B;break;case 4:return w.label++,{value:B[1],done:!1};case 5:w.label++,f=B[1],B=[0];continue;case 7:B=w.ops.pop(),w.trys.pop();continue;default:if(v=w.trys,!(v=v.length>0&&v[v.length-1])&&(B[0]===6||B[0]===2)){w=0;continue}if(B[0]===3&&(!v||B[1]>v[0]&&B[1]<v[3])){w.label=B[1];break}if(B[0]===6&&w.label<v[1]){w.label=v[1],v=B;break}if(v&&w.label<v[2]){w.label=v[2],w.ops.push(B);break}v[2]&&w.ops.pop(),w.trys.pop();continue}B=h.call(p,w)}catch(G){B=[6,G],f=0}finally{g=v=0}if(B[0]&5)throw B[1];return{value:B[0]?B[1]:void 0,done:!0}}}function x(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function A(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(x(arguments[h]));return p}var I="obfuse error occur";function C(p,h){if(!p)throw new Error("[linked-list] "+(h||I))}var E=-1,P=function(){function p(){for(var h=this,w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];this._head=null,this._tail=null,this._length=0,this.compare=new u,w.length>0&&w.forEach(function(f){h.append(f)})}return Object.defineProperty(p.prototype,"head",{get:function(){return this._head?this._head.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"tail",{get:function(){return this._tail?this._tail.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"loopLength",{get:function(){var h=!1,w=1;if(!this._head)return 0;for(var g=this._head,f=this._head;f.next&&f.next.next;)if(f=f.next.next,g=g.next,g===f){h=!0;break}if(h){for(f=f.next;g!==f;)w++,f=f.next;return w}else return 0},enumerable:!0,configurable:!0}),p.prototype.getNode=function(h){var w=this._length;C(w>0&&h>=0&&h<w,"[linked-list] index "+h+" out of scope of list, which length is "+w);for(var g=this._head,f=0;f<h;)g=g.next,f++;return g},p.prototype.get=function(h){var w=this.getNode(h);return w?w.value:null},p.prototype.find=function(h){var w=h.value,g=h.callback;if(!this._head)return null;for(var f=this._head;f;){if(g&&g(f.value)||w!==void 0&&this.compare.equal(f.value,w))return f;f=f.next}return null},p.prototype.indexOf=function(h){if(!this._head)return E;for(var w=this._head,g=-1;w.next;){if(g++,this.compare.equal(w.value,h))return g;w=w.next}return w===this._tail&&this.compare.equal(w.value,h)&&(g+=1),g},p.prototype.first=function(h){C(h>=0,"[linked-list] param 'num' ("+h+") should not less than 0");for(var w=this.iterator(),g=[],f=Math.min(h,this.length),v=0;v<f;v++){var O=w.next();g.push(O.value)}return g},p.prototype.toArray=function(){return A(this)},p.prototype.isEmpty=function(){return this._head===null},p.prototype.iterator=function(){var h;return T(this,function(w){switch(w.label){case 0:h=this._head,w.label=1;case 1:return h?[4,h.value]:[3,3];case 2:return w.sent(),h=h.next,[3,1];case 3:return[2]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p}(),D=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new l(w);return this._tail?(this._tail.next=g,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new l(w);return this._head?(g.next=this._head,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,g.next=null):this._head=this._tail=null,this._length--,w;for(var f=g;;){if(this.compare.equal(g.value,w))return g.next?f.next=g.next:(this._tail=f,this._tail.next=null),g.next=null,this._length--,w;if(g.next)f=g,g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w){if(!this._head.next)this._head=null,this._tail=null;else{for(var g=this._head;g.next!==w;)g=g.next;g.next=null,this._tail=g}return this._length--,w.value}},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),L=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(D),H=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},h.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(L),W=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new d(w);return this._tail?(this._tail.next=g,g.prev=this._tail,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new d(w);return this._head?(g.next=this._head,this._head.prev=g,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,this._head.prev=null,g.next=g.prev=null):this._head=this._tail=null,this._length--,w;for(;;){if(this.compare.equal(g.value,w))return g.next?(g.prev.next=g.next,g.next.prev=g.prev,g.next=g.prev=null):(g.prev.next=null,this._tail=g.prev,g.next=g.prev=null),this._length--,g.value;if(g.next)g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(w.next.prev=null,this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w)return this._head.next?(w.prev.next=null,this._tail=w.prev,w.next=w.prev=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,w.prev=f,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),K=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(W),F=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},h.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(K);function U(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function N(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(U(arguments[h]));return p}var j=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.queue=new(D.bind.apply(D,N([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.queue.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.queue.head},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.queue.isEmpty()},p.prototype.enqueue=function(h){return this.queue.append(h)},p.prototype.dequeue=function(){var h=this.queue.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.queue.toArray()},p}();function S(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function k(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(S(arguments[h]));return p}var a=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.stack=new(D.bind.apply(D,k([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.stack.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.stack.tail},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.stack.isEmpty()},p.prototype.push=function(h){return this.stack.append(h)},p.prototype.pop=function(){var h=this.stack.removeTail();return typeof h<"u"?h:void 0},p.prototype.popBottom=function(){var h=this.stack.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.stack.toArray()},p}();function c(p,h,w,g){if(p){h.push(p),g.set(p.getKey(),!0);var f=p.getNeighbors().filter(function(v){return!g.get(v.getKey())});w.push(f)}}function m(p,h,w){var g=p.pop();g&&w.set(g.getKey(),!1),h.pop()}var y=function(){function p(h){h===void 0&&(h=!1),this.vertices={},this.edges={},this.isDirected=h}return p.prototype.addVertex=function(h){return this.vertices[h.getKey()]=h,this},p.prototype.getVertexByKey=function(h){return this.vertices[h]},p.prototype.getNeighbors=function(h){return h.getNeighbors()},p.prototype.getAllVertices=function(){return Object.values(this.vertices)},p.prototype.getAllEdges=function(){return Object.values(this.edges)},p.prototype.addEdge=function(h,w){if(w===void 0&&(w=!1),this.edges[h.getKey()]){if(w)return this;n(!1,"Edge has already been added before")}var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());if(g||(this.addVertex(h.startVertex),g=this.getVertexByKey(h.startVertex.getKey())),f||(this.addVertex(h.endVertex),f=this.getVertexByKey(h.endVertex.getKey())),this.edges[h.getKey()]=h,this.isDirected)g.addEdge(h);else{g.addEdge(h);var v=h.clone();f.addEdge(v.reverse())}return this},p.prototype.deleteEdge=function(h,w){if(w===void 0&&(w=!1),!this.edges[h.getKey()]){if(w)return this;n(!1,"Edge not found in graph")}delete this.edges[h.getKey()];var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());return g.deleteEdge(h),f.deleteEdge(h),this},p.prototype.findEdge=function(h,w){var g=this.getVertexByKey(h.getKey());return g?g.findEdge(w):null},p.prototype.getWeight=function(){return this.getAllEdges().reduce(function(h,w){return h+w.weight},0)},p.prototype.reverse=function(){var h=this;return this.getAllEdges().forEach(function(w){h.deleteEdge(w),w.reverse(),h.addEdge(w)}),this},p.prototype.getVerticesIndices=function(){var h={};return this.getAllVertices().forEach(function(w,g){h[w.getKey()]=g}),h},p.prototype.getAdjacencyMatrix=function(){var h=this,w=this.getAllVertices(),g=this.getVerticesIndices(),f=Array(w.length).fill(null).map(function(){return Array(w.length).fill(1/0)});return w.forEach(function(v,O){v.getNeighbors().forEach(function(M){var R=g[M.getKey()],B=h.findEdge(v,M);B&&(f[O][R]=B.weight)})}),f},p.prototype.toString=function(){return Object.keys(this.vertices).toString()},p.prototype.bfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new j,g.enqueue(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.dequeue(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.enqueue(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.dfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new a,g.push(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.pop(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.push(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.findAllPath=function(h,w){var g,f,v,O,M,R,B;return e.__generator(this,function(G){switch(G.label){case 0:return g=[],h!==w?[3,2]:(g.push(h),[4,g]);case 1:return G.sent(),[2];case 2:f=new Map,v=new a,O=new a,c(h,v,O,f),G.label=3;case 3:if(v.isEmpty())return[3,6];if(M=O.pop(),M&&M.length)R=M.shift(),O.push(M),R&&c(R,v,O,f);else return O.push(M),m(v,O,f),[3,3];return B=v.peek,B!==w?[3,5]:[4,v.toArray()];case 4:G.sent(),m(v,O,f),G.label=5;case 5:return[3,3];case 6:return[2]}})},p}();t.GraphEdge=r,t.GraphVertex=o,t.Graph=y,Object.defineProperty(t,"__esModule",{value:!0})})});var If=Fr((hu,pu)=>{"use strict";(function(t,e){typeof hu=="object"&&typeof pu<"u"?pu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(hu,function(){"use strict";var t=Math.imul,e=Math.clz32;function r(F){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U},r(F)}function n(F,U){if(!(F instanceof U))throw new TypeError("Cannot call a class as a function")}function i(F,U){for(var N,j=0;j<U.length;j++)N=U[j],N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(F,N.key,N)}function o(F,U,N){return U&&i(F.prototype,U),N&&i(F,N),Object.defineProperty(F,"prototype",{writable:!1}),F}function s(F,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(U&&U.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),U&&l(F,U)}function u(F){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(U){return U.__proto__||Object.getPrototypeOf(U)},u(F)}function l(F,U){return l=Object.setPrototypeOf||function(N,j){return N.__proto__=j,N},l(F,U)}function d(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function b(){return b=d()?Reflect.construct:function(F,U,N){var j=[null];j.push.apply(j,U);var S=Function.bind.apply(F,j),k=new S;return N&&l(k,N.prototype),k},b.apply(null,arguments)}function _(F){return Function.toString.call(F).indexOf("[native code]")!==-1}function T(F){var U=typeof Map=="function"?new Map:void 0;return T=function(N){function j(){return b(N,arguments,u(this).constructor)}if(N===null||!_(N))return N;if(typeof N!="function")throw new TypeError("Super expression must either be null or a function");if(typeof U<"u"){if(U.has(N))return U.get(N);U.set(N,j)}return j.prototype=Object.create(N.prototype,{constructor:{value:j,enumerable:!1,writable:!0,configurable:!0}}),l(j,N)},T(F)}function x(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}function A(F,U){if(U&&(typeof U=="object"||typeof U=="function"))return U;if(U!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return x(F)}function I(F){var U=d();return function(){var N,j=u(F);if(U){var S=u(this).constructor;N=Reflect.construct(j,arguments,S)}else N=j.apply(this,arguments);return A(this,N)}}function C(F,U){return E(F)||P(F,U)||D(F,U)||H()}function E(F){if(Array.isArray(F))return F}function P(F,U){var N=F==null?null:typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(N!=null){var j,S,k=[],a=!0,c=!1;try{for(N=N.call(F);!(a=(j=N.next()).done)&&(k.push(j.value),!(U&&k.length===U));a=!0);}catch(m){c=!0,S=m}finally{try{a||N.return==null||N.return()}finally{if(c)throw S}}return k}}function D(F,U){if(F){if(typeof F=="string")return L(F,U);var N=Object.prototype.toString.call(F).slice(8,-1);return N==="Object"&&F.constructor&&(N=F.constructor.name),N==="Map"||N==="Set"?Array.from(F):N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N)?L(F,U):void 0}}function L(F,U){(U==null||U>F.length)&&(U=F.length);for(var N=0,j=Array(U);N<U;N++)j[N]=F[N];return j}function H(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
2
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function W(F,U){var N=typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(!N){if(Array.isArray(F)||(N=D(F))||U&&F&&typeof F.length=="number"){N&&(F=N);var j=0,S=function(){};return{s:S,n:function(){return j>=F.length?{done:!0}:{done:!1,value:F[j++]}},e:function(m){throw m},f:S}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
3
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var k,a=!0,c=!1;return{s:function(){N=N.call(F)},n:function(){var m=N.next();return a=m.done,m},e:function(m){c=!0,k=m},f:function(){try{a||N.return==null||N.return()}finally{if(c)throw k}}}}var K=function(F){var U=Math.abs,N=Math.max,j=Math.floor;function S(a,c){var m;if(n(this,S),m=k.call(this,a),m.sign=c,Object.setPrototypeOf(x(m),S.prototype),a>S.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return m}s(S,F);var k=I(S);return o(S,[{key:"toDebugString",value:function(){var a,c=["BigInt["],m=W(this);try{for(m.s();!(a=m.n()).done;){var y=a.value;c.push((y&&(y>>>0).toString(16))+", ")}}catch(p){m.e(p)}finally{m.f()}return c.push("]"),c.join("")}},{key:"toString",value:function(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>a||36<a)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":a&a-1?S.__toStringGeneric(this,a,!1):S.__toStringBasePowerOfTwo(this,a)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var a=new S(this.length,this.sign),c=0;c<this.length;c++)a[c]=this[c];return a}},{key:"__trim",value:function(){for(var a=this.length,c=this[a-1];c===0;)a--,c=this[a-1],this.pop();return a===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var a=0;a<this.length;a++)this[a]=0}},{key:"__clzmsd",value:function(){return S.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(a,c,m){m>this.length&&(m=this.length);for(var y=32767&a,p=a>>>15,h=0,w=c,g=0;g<m;g++){var f=this.__digit(g),v=32767&f,O=f>>>15,M=S.__imul(v,y),R=S.__imul(v,p),B=S.__imul(O,y),G=S.__imul(O,p),Z=w+M+h;h=Z>>>30,Z&=1073741823,Z+=((32767&R)<<15)+((32767&B)<<15),h+=Z>>>30,w=G+(R>>>15)+(B>>>15),this.__setDigit(g,1073741823&Z)}if(h!==0||w!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(a,c,m){for(var y,p=0,h=0;h<m;h++)y=this.__halfDigit(c+h)+a.__halfDigit(h)+p,p=y>>>15,this.__setHalfDigit(c+h,32767&y);return p}},{key:"__inplaceSub",value:function(a,c,m){var y=0;if(1&c){c>>=1;for(var p=this.__digit(c),h=32767&p,w=0;w<m-1>>>1;w++){var g=a.__digit(w),f=(p>>>15)-(32767&g)-y;y=1&f>>>15,this.__setDigit(c+w,(32767&f)<<15|32767&h),p=this.__digit(c+w+1),h=(32767&p)-(g>>>15)-y,y=1&h>>>15}var v=a.__digit(w),O=(p>>>15)-(32767&v)-y;if(y=1&O>>>15,this.__setDigit(c+w,(32767&O)<<15|32767&h),c+w+1>=this.length)throw new RangeError("out of bounds");!(1&m)&&(p=this.__digit(c+w+1),h=(32767&p)-(v>>>15)-y,y=1&h>>>15,this.__setDigit(c+a.length,1073709056&p|32767&h))}else{c>>=1;for(var M=0;M<a.length-1;M++){var R=this.__digit(c+M),B=a.__digit(M),G=(32767&R)-(32767&B)-y;y=1&G>>>15;var Z=(R>>>15)-(B>>>15)-y;y=1&Z>>>15,this.__setDigit(c+M,(32767&Z)<<15|32767&G)}var se=this.__digit(c+M),te=a.__digit(M),ue=(32767&se)-(32767&te)-y;y=1&ue>>>15;var dt=0;!(1&m)&&(dt=(se>>>15)-(te>>>15)-y,y=1&dt>>>15),this.__setDigit(c+M,(32767&dt)<<15|32767&ue)}return y}},{key:"__inplaceRightShift",value:function(a){if(a!==0){for(var c,m=this.__digit(0)>>>a,y=this.length-1,p=0;p<y;p++)c=this.__digit(p+1),this.__setDigit(p,1073741823&c<<30-a|m),m=c>>>a;this.__setDigit(y,m)}}},{key:"__digit",value:function(a){return this[a]}},{key:"__unsignedDigit",value:function(a){return this[a]>>>0}},{key:"__setDigit",value:function(a,c){this[a]=0|c}},{key:"__setDigitGrow",value:function(a,c){this[a]=0|c}},{key:"__halfDigitLength",value:function(){var a=this.length;return 32767>=this.__unsignedDigit(a-1)?2*a-1:2*a}},{key:"__halfDigit",value:function(a){return 32767&this[a>>>1]>>>15*(1&a)}},{key:"__setHalfDigit",value:function(a,c){var m=a>>>1,y=this.__digit(m),p=1&a?32767&y|c<<15:1073709056&y|32767&c;this.__setDigit(m,p)}}],[{key:"BigInt",value:function(a){var c=Number.isFinite;if(typeof a=="number"){if(a===0)return S.__zero();if(S.__isOneDigitInt(a))return 0>a?S.__oneDigit(-a,!0):S.__oneDigit(a,!1);if(!c(a)||j(a)!==a)throw new RangeError("The number "+a+" cannot be converted to BigInt because it is not an integer");return S.__fromDouble(a)}if(typeof a=="string"){var m=S.__fromString(a);if(m===null)throw new SyntaxError("Cannot convert "+a+" to a BigInt");return m}if(typeof a=="boolean")return a===!0?S.__oneDigit(1,!1):S.__zero();if(r(a)==="object"){if(a.constructor===S)return a;var y=S.__toPrimitive(a);return S.BigInt(y)}throw new TypeError("Cannot convert "+a+" to a BigInt")}},{key:"toNumber",value:function(a){var c=a.length;if(c===0)return 0;if(c===1){var m=a.__unsignedDigit(0);return a.sign?-m:m}var y=a.__digit(c-1),p=S.__clz30(y),h=30*c-p;if(1024<h)return a.sign?-1/0:1/0;var w=h-1,g=y,f=c-1,v=p+3,O=v===32?0:g<<v;O>>>=12;var M=v-12,R=12<=v?0:g<<20+v,B=20+v;for(0<M&&0<f&&(f--,g=a.__digit(f),O|=g>>>30-M,R=g<<M+2,B=M+2);0<B&&0<f;)f--,g=a.__digit(f),R|=30<=B?g<<B-30:g>>>30-B,B-=30;var G=S.__decideRounding(a,B,f,g);if((G===1||G===0&&(1&R)==1)&&(R=R+1>>>0,R===0&&(O++,O>>>20!=0&&(O=0,w++,1023<w))))return a.sign?-1/0:1/0;var Z=a.sign?-2147483648:0;return w=w+1023<<20,S.__kBitConversionInts[1]=Z|w|O,S.__kBitConversionInts[0]=R,S.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(a){if(a.length===0)return a;var c=a.__copy();return c.sign=!a.sign,c}},{key:"bitwiseNot",value:function(a){return a.sign?S.__absoluteSubOne(a).__trim():S.__absoluteAddOne(a,!0)}},{key:"exponentiate",value:function(a,c){if(c.sign)throw new RangeError("Exponent must be positive");if(c.length===0)return S.__oneDigit(1,!1);if(a.length===0)return a;if(a.length===1&&a.__digit(0)===1)return a.sign&&!(1&c.__digit(0))?S.unaryMinus(a):a;if(1<c.length)throw new RangeError("BigInt too big");var m=c.__unsignedDigit(0);if(m===1)return a;if(m>=S.__kMaxLengthBits)throw new RangeError("BigInt too big");if(a.length===1&&a.__digit(0)===2){var y=1+(0|m/30),p=a.sign&&(1&m)!=0,h=new S(y,p);h.__initializeDigits();var w=1<<m%30;return h.__setDigit(y-1,w),h}var g=null,f=a;for(1&m&&(g=a),m>>=1;m!==0;m>>=1)f=S.multiply(f,f),1&m&&(g===null?g=f:g=S.multiply(g,f));return g}},{key:"multiply",value:function(a,c){if(a.length===0)return a;if(c.length===0)return c;var m=a.length+c.length;30<=a.__clzmsd()+c.__clzmsd()&&m--;var y=new S(m,a.sign!==c.sign);y.__initializeDigits();for(var p=0;p<a.length;p++)S.__multiplyAccumulate(c,a.__digit(p),y,p);return y.__trim()}},{key:"divide",value:function(a,c){if(c.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(a,c))return S.__zero();var m,y=a.sign!==c.sign,p=c.__unsignedDigit(0);if(c.length===1&&32767>=p){if(p===1)return y===a.sign?a:S.unaryMinus(a);m=S.__absoluteDivSmall(a,p,null)}else m=S.__absoluteDivLarge(a,c,!0,!1);return m.sign=y,m.__trim()}},{key:"remainder",value:function(c,m){if(m.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(c,m))return c;var y=m.__unsignedDigit(0);if(m.length===1&&32767>=y){if(y===1)return S.__zero();var p=S.__absoluteModSmall(c,y);return p===0?S.__zero():S.__oneDigit(p,c.sign)}var h=S.__absoluteDivLarge(c,m,!1,!0);return h.sign=c.sign,h.__trim()}},{key:"add",value:function(a,c){var m=a.sign;return m===c.sign?S.__absoluteAdd(a,c,m):0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m)}},{key:"subtract",value:function(a,c){var m=a.sign;return m===c.sign?0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m):S.__absoluteAdd(a,c,m)}},{key:"leftShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__rightShiftByAbsolute(a,c):S.__leftShiftByAbsolute(a,c)}},{key:"signedRightShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__leftShiftByAbsolute(a,c):S.__rightShiftByAbsolute(a,c)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(a,c){return 0>S.__compareToBigInt(a,c)}},{key:"lessThanOrEqual",value:function(a,c){return 0>=S.__compareToBigInt(a,c)}},{key:"greaterThan",value:function(a,c){return 0<S.__compareToBigInt(a,c)}},{key:"greaterThanOrEqual",value:function(a,c){return 0<=S.__compareToBigInt(a,c)}},{key:"equal",value:function(a,c){if(a.sign!==c.sign||a.length!==c.length)return!1;for(var m=0;m<a.length;m++)if(a.__digit(m)!==c.__digit(m))return!1;return!0}},{key:"notEqual",value:function(a,c){return!S.equal(a,c)}},{key:"bitwiseAnd",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteAnd(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length)+1,y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteOr(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}return S.__absoluteAndNot(a,S.__absoluteSubOne(c)).__trim()}},{key:"bitwiseXor",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteXor(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length),y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return S.__absoluteXor(y,p,y).__trim()}var h=N(a.length,c.length)+1;if(a.sign){var w=[c,a];a=w[0],c=w[1]}var g=S.__absoluteSubOne(c,h);return g=S.__absoluteXor(g,a,g),S.__absoluteAddOne(g,!0,g).__trim()}},{key:"bitwiseOr",value:function(a,c){var m=N(a.length,c.length);if(!a.sign&&!c.sign)return S.__absoluteOr(a,c).__trim();if(a.sign&&c.sign){var y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteAnd(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}var w=S.__absoluteSubOne(c,m);return w=S.__absoluteAndNot(w,a,w),S.__absoluteAddOne(w,!0,w).__trim()}},{key:"asIntN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=c.__unsignedDigit(m-1),p=1<<(a-1)%30;if(c.length===m&&y<p)return c;if((y&p)!==p)return S.__truncateToNBits(a,c);if(!c.sign)return S.__truncateAndSubFromPowerOfTwo(a,c,!0);if(!(y&p-1)){for(var h=m-2;0<=h;h--)if(c.__digit(h)!==0)return S.__truncateAndSubFromPowerOfTwo(a,c,!1);return c.length===m&&y===p?c:S.__truncateToNBits(a,c)}return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}},{key:"asUintN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(c.sign){if(a>S.__kMaxLengthBits)throw new RangeError("BigInt too big");return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=a%30;if(c.length==m){if(y===0)return c;var p=c.__digit(m-1);if(!(p>>>y))return c}return S.__truncateToNBits(a,c)}},{key:"ADD",value:function(a,c){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string")return typeof c!="string"&&(c=c.toString()),a+c;if(typeof c=="string")return a.toString()+c;if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)&&S.__isBigInt(c))return S.add(a,c);if(typeof a=="number"&&typeof c=="number")return a+c;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(a,c){return S.__compare(a,c,0)}},{key:"LE",value:function(a,c){return S.__compare(a,c,1)}},{key:"GT",value:function(a,c){return S.__compare(a,c,2)}},{key:"GE",value:function(a,c){return S.__compare(a,c,3)}},{key:"EQ",value:function(a,c){for(;;){if(S.__isBigInt(a))return S.__isBigInt(c)?S.equal(a,c):S.EQ(c,a);if(typeof a=="number"){if(S.__isBigInt(c))return S.__equalToNumber(c,a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="string"){if(S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.equal(a,c);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="boolean"){if(S.__isBigInt(c))return S.__equalToNumber(c,+a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="symbol"){if(S.__isBigInt(c))return!1;if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="object"){if(r(c)==="object"&&c.constructor!==S)return a==c;a=S.__toPrimitive(a)}else return a==c}}},{key:"NE",value:function(a,c){return!S.EQ(a,c)}},{key:"DataViewGetBigInt64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return S.asIntN(64,S.DataViewGetBigUint64(a,c,m))}},{key:"DataViewGetBigUint64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2],y=m?[4,0]:[0,4],p=C(y,2),h=p[0],w=p[1],g=a.getUint32(c+h,m),f=a.getUint32(c+w,m),v=new S(3,!1);return v.__setDigit(0,1073741823&f),v.__setDigit(1,(268435455&g)<<2|f>>>30),v.__setDigit(2,g>>>28),v.__trim()}},{key:"DataViewSetBigInt64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];S.DataViewSetBigUint64(a,c,m,y)}},{key:"DataViewSetBigUint64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];m=S.asUintN(64,m);var p=0,h=0;if(0<m.length&&(h=m.__digit(0),1<m.length)){var w=m.__digit(1);h|=w<<30,p=w>>>2,2<m.length&&(p|=m.__digit(2)<<28)}var g=y?[4,0]:[0,4],f=C(g,2),v=f[0],O=f[1];a.setUint32(c+v,p,y),a.setUint32(c+O,h,y)}},{key:"__zero",value:function(){return new S(0,!1)}},{key:"__oneDigit",value:function(a,c){var m=new S(1,c);return m.__setDigit(0,a),m}},{key:"__decideRounding",value:function(a,c,m,y){if(0<c)return-1;var p;if(0>c)p=-c-1;else{if(m===0)return-1;m--,y=a.__digit(m),p=29}var h=1<<p;if(!(y&h))return-1;if(h-=1,(y&h)!=0)return 1;for(;0<m;)if(m--,a.__digit(m)!==0)return 1;return 0}},{key:"__fromDouble",value:function(a){S.__kBitConversionDouble[0]=a;var c,m=2047&S.__kBitConversionInts[1]>>>20,y=m-1023,p=(0|y/30)+1,h=new S(p,0>a),w=1048575&S.__kBitConversionInts[1]|1048576,g=S.__kBitConversionInts[0],f=20,v=y%30,O=0;if(v<f){var M=f-v;O=M+32,c=w>>>M,w=w<<32-M|g>>>M,g<<=32-M}else if(v===f)O=32,c=w,w=g,g=0;else{var R=v-f;O=32-R,c=w<<R|g>>>32-R,w=g<<R,g=0}h.__setDigit(p-1,c);for(var B=p-2;0<=B;B--)0<O?(O-=30,c=w>>>2,w=w<<30|g>>>2,g<<=30):c=0,h.__setDigit(B,c);return h.__trim()}},{key:"__isWhitespace",value:function(a){return 13>=a&&9<=a||(159>=a?a==32:131071>=a?a==160||a==5760:196607>=a?(a&=131071,10>=a||a==40||a==41||a==47||a==95||a==4096):a==65279)}},{key:"__fromString",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,m=0,y=a.length,p=0;if(p===y)return S.__zero();for(var h=a.charCodeAt(p);S.__isWhitespace(h);){if(++p===y)return S.__zero();h=a.charCodeAt(p)}if(h===43){if(++p===y)return null;h=a.charCodeAt(p),m=1}else if(h===45){if(++p===y)return null;h=a.charCodeAt(p),m=-1}if(c===0){if(c=10,h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(c=16,++p===y)return null;h=a.charCodeAt(p)}else if(h===79||h===111){if(c=8,++p===y)return null;h=a.charCodeAt(p)}else if(h===66||h===98){if(c=2,++p===y)return null;h=a.charCodeAt(p)}}}else if(c===16&&h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(++p===y)return null;h=a.charCodeAt(p)}}if(m!==0&&c!==10)return null;for(;h===48;){if(++p===y)return S.__zero();h=a.charCodeAt(p)}var w=y-p,g=S.__kMaxBitsPerChar[c],f=S.__kBitsPerCharTableMultiplier-1;if(w>1073741824/g)return null;var v=g*w+f>>>S.__kBitsPerCharTableShift,O=new S(0|(v+29)/30,!1),M=10>c?c:10,R=10<c?c-10:0;if(c&c-1){O.__initializeDigits();var dt=!1,ve=0;do{for(var xe,an=0,Ae=1;;){if(xe=void 0,h-48>>>0<M)xe=h-48;else if((32|h)-97>>>0<R)xe=(32|h)-87;else{dt=!0;break}var Me=Ae*c;if(1073741823<Me)break;if(Ae=Me,an=an*c+xe,ve++,++p===y){dt=!0;break}h=a.charCodeAt(p)}f=30*S.__kBitsPerCharTableMultiplier-1;var Gi=0|(g*ve+f>>>S.__kBitsPerCharTableShift)/30;O.__inplaceMultiplyAdd(Ae,an,Gi)}while(!dt)}else{g>>=S.__kBitsPerCharTableShift;var B=[],G=[],Z=!1;do{for(var se,te=0,ue=0;;){if(se=void 0,h-48>>>0<M)se=h-48;else if((32|h)-97>>>0<R)se=(32|h)-87;else{Z=!0;break}if(ue+=g,te=te<<g|se,++p===y){Z=!0;break}if(h=a.charCodeAt(p),30<ue+g)break}B.push(te),G.push(ue)}while(!Z);S.__fillFromParts(O,B,G)}if(p!==y){if(!S.__isWhitespace(h))return null;for(p++;p<y;p++)if(h=a.charCodeAt(p),!S.__isWhitespace(h))return null}return O.sign=m===-1,O.__trim()}},{key:"__fillFromParts",value:function(a,c,m){for(var y=0,p=0,h=0,w=c.length-1;0<=w;w--){var g=c[w],f=m[w];p|=g<<h,h+=f,h===30?(a.__setDigit(y++,p),h=0,p=0):30<h&&(a.__setDigit(y++,1073741823&p),h-=30,p=g>>>f-h)}if(p!==0){if(y>=a.length)throw new Error("implementation bug");a.__setDigit(y++,p)}for(;y<a.length;y++)a.__setDigit(y,0)}},{key:"__toStringBasePowerOfTwo",value:function(a,c){var m=a.length,y=c-1;y=(85&y>>>1)+(85&y),y=(51&y>>>2)+(51&y),y=(15&y>>>4)+(15&y);var p=y,h=c-1,w=a.__digit(m-1),g=S.__clz30(w),f=0|(30*m-g+p-1)/p;if(a.sign&&f++,268435456<f)throw new Error("string too long");for(var v=Array(f),O=f-1,M=0,R=0,B=0;B<m-1;B++){var G=a.__digit(B),Z=(M|G<<R)&h;v[O--]=S.__kConversionChars[Z];var se=p-R;for(M=G>>>se,R=30-se;R>=p;)v[O--]=S.__kConversionChars[M&h],M>>>=p,R-=p}var te=(M|w<<R)&h;for(v[O--]=S.__kConversionChars[te],M=w>>>p-R;M!==0;)v[O--]=S.__kConversionChars[M&h],M>>>=p;if(a.sign&&(v[O--]="-"),O!==-1)throw new Error("implementation bug");return v.join("")}},{key:"__toStringGeneric",value:function(a,c,m){var y=a.length;if(y===0)return"";if(y===1){var p=a.__unsignedDigit(0).toString(c);return m===!1&&a.sign&&(p="-"+p),p}var h=30*y-S.__clz30(a.__digit(y-1)),w=S.__kMaxBitsPerChar[c],g=w-1,f=h*S.__kBitsPerCharTableMultiplier;f+=g-1,f=0|f/g;var v,O,M=f+1>>1,R=S.exponentiate(S.__oneDigit(c,!1),S.__oneDigit(M,!1)),B=R.__unsignedDigit(0);if(R.length===1&&32767>=B){v=new S(a.length,!1),v.__initializeDigits();for(var G,Z=0,se=2*a.length-1;0<=se;se--)G=Z<<15|a.__halfDigit(se),v.__setHalfDigit(se,0|G/B),Z=0|G%B;O=Z.toString(c)}else{var te=S.__absoluteDivLarge(a,R,!0,!0);v=te.quotient;var ue=te.remainder.__trim();O=S.__toStringGeneric(ue,c,!0)}v.__trim();for(var dt=S.__toStringGeneric(v,c,!0);O.length<M;)O="0"+O;return m===!1&&a.sign&&(dt="-"+dt),dt+O}},{key:"__unequalSign",value:function(a){return a?-1:1}},{key:"__absoluteGreater",value:function(a){return a?-1:1}},{key:"__absoluteLess",value:function(a){return a?1:-1}},{key:"__compareToBigInt",value:function(a,c){var m=a.sign;if(m!==c.sign)return S.__unequalSign(m);var y=S.__absoluteCompare(a,c);return 0<y?S.__absoluteGreater(m):0>y?S.__absoluteLess(m):0}},{key:"__compareToNumber",value:function(a,c){if(S.__isOneDigitInt(c)){var m=a.sign,y=0>c;if(m!==y)return S.__unequalSign(m);if(a.length===0){if(y)throw new Error("implementation bug");return c===0?0:-1}if(1<a.length)return S.__absoluteGreater(m);var p=U(c),h=a.__unsignedDigit(0);return h>p?S.__absoluteGreater(m):h<p?S.__absoluteLess(m):0}return S.__compareToDouble(a,c)}},{key:"__compareToDouble",value:function(a,c){if(c!==c)return c;if(c===1/0)return-1;if(c===-1/0)return 1;var m=a.sign;if(m!==0>c)return S.__unequalSign(m);if(c===0)throw new Error("implementation bug: should be handled elsewhere");if(a.length===0)return-1;S.__kBitConversionDouble[0]=c;var y=2047&S.__kBitConversionInts[1]>>>20;if(y==2047)throw new Error("implementation bug: handled elsewhere");var p=y-1023;if(0>p)return S.__absoluteGreater(m);var h=a.length,w=a.__digit(h-1),g=S.__clz30(w),f=30*h-g,v=p+1;if(f<v)return S.__absoluteLess(m);if(f>v)return S.__absoluteGreater(m);var O=1048576|1048575&S.__kBitConversionInts[1],M=S.__kBitConversionInts[0],R=20,B=29-g;if(B!==(0|(f-1)%30))throw new Error("implementation bug");var G,Z=0;if(B<R){var se=R-B;Z=se+32,G=O>>>se,O=O<<32-se|M>>>se,M<<=32-se}else if(B===R)Z=32,G=O,O=M,M=0;else{var te=B-R;Z=32-te,G=O<<te|M>>>32-te,O=M<<te,M=0}if(w>>>=0,G>>>=0,w>G)return S.__absoluteGreater(m);if(w<G)return S.__absoluteLess(m);for(var ue=h-2;0<=ue;ue--){0<Z?(Z-=30,G=O>>>2,O=O<<30|M>>>2,M<<=30):G=0;var dt=a.__unsignedDigit(ue);if(dt>G)return S.__absoluteGreater(m);if(dt<G)return S.__absoluteLess(m)}if(O!==0||M!==0){if(Z===0)throw new Error("implementation bug");return S.__absoluteLess(m)}return 0}},{key:"__equalToNumber",value:function(a,c){return S.__isOneDigitInt(c)?c===0?a.length===0:a.length===1&&a.sign===0>c&&a.__unsignedDigit(0)===U(c):S.__compareToDouble(a,c)===0}},{key:"__comparisonResultToBool",value:function(a,c){return c===0?0>a:c===1?0>=a:c===2?0<a:c===3?0<=a:void 0}},{key:"__compare",value:function(a,c,m){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string"&&typeof c=="string")switch(m){case 0:return a<c;case 1:return a<=c;case 2:return a>c;case 3:return a>=c}if(S.__isBigInt(a)&&typeof c=="string")return c=S.__fromString(c),c!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof a=="string"&&S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)){if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof c!="number")throw new Error("implementation bug");return S.__comparisonResultToBool(S.__compareToNumber(a,c),m)}if(typeof a!="number")throw new Error("implementation bug");if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToNumber(c,a),2^m);if(typeof c!="number")throw new Error("implementation bug");return m===0?a<c:m===1?a<=c:m===2?a>c:m===3?a>=c:void 0}},{key:"__absoluteAdd",value:function(a,c,m){if(a.length<c.length)return S.__absoluteAdd(c,a,m);if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);var y=a.length;(a.__clzmsd()===0||c.length===a.length&&c.__clzmsd()===0)&&y++;for(var p,h=new S(y,m),w=0,g=0;g<c.length;g++)p=a.__digit(g)+c.__digit(g)+w,w=p>>>30,h.__setDigit(g,1073741823&p);for(;g<a.length;g++){var f=a.__digit(g)+w;w=f>>>30,h.__setDigit(g,1073741823&f)}return g<h.length&&h.__setDigit(g,w),h.__trim()}},{key:"__absoluteSub",value:function(a,c,m){if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);for(var y,p=new S(a.length,m),h=0,w=0;w<c.length;w++)y=a.__digit(w)-c.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);for(;w<a.length;w++){var g=a.__digit(w)-h;h=1&g>>>30,p.__setDigit(w,1073741823&g)}return p.__trim()}},{key:"__absoluteAddOne",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length;m===null?m=new S(y,c):m.sign=c;for(var p,h=1,w=0;w<y;w++)p=a.__digit(w)+h,h=p>>>30,m.__setDigit(w,1073741823&p);return h!==0&&m.__setDigitGrow(y,1),m}},{key:"__absoluteSubOne",value:function(a,c){var m=a.length;c=c||m;for(var y,p=new S(c,!1),h=1,w=0;w<m;w++)y=a.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);if(h!==0)throw new Error("implementation bug");for(var g=m;g<c;g++)p.__setDigit(g,0);return p}},{key:"__absoluteAnd",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=h;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)&c.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteAndNot",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;y<p&&(h=y);var w=y;m===null?m=new S(w,!1):w=m.length;for(var g=0;g<h;g++)m.__setDigit(g,a.__digit(g)&~c.__digit(g));for(;g<y;g++)m.__setDigit(g,a.__digit(g));for(;g<w;g++)m.__setDigit(g,0);return m}},{key:"__absoluteOr",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)|c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteXor",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)^c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteCompare",value:function(a,c){var m=a.length-c.length;if(m!=0)return m;for(var y=a.length-1;0<=y&&a.__digit(y)===c.__digit(y);)y--;return 0>y?0:a.__unsignedDigit(y)>c.__unsignedDigit(y)?1:-1}},{key:"__multiplyAccumulate",value:function(a,c,m,y){if(c!==0){for(var p=32767&c,h=c>>>15,w=0,g=0,f=0;f<a.length;f++,y++){var v=m.__digit(y),O=a.__digit(f),M=32767&O,R=O>>>15,B=S.__imul(M,p),G=S.__imul(M,h),Z=S.__imul(R,p),se=S.__imul(R,h);v+=g+B+w,w=v>>>30,v&=1073741823,v+=((32767&G)<<15)+((32767&Z)<<15),w+=v>>>30,g=se+(G>>>15)+(Z>>>15),m.__setDigit(y,1073741823&v)}for(;w!==0||g!==0;y++){var te=m.__digit(y);te+=w+g,g=0,w=te>>>30,m.__setDigit(y,1073741823&te)}}}},{key:"__internalMultiplyAdd",value:function(a,c,m,y,p){for(var h=m,w=0,g=0;g<y;g++){var f=a.__digit(g),v=S.__imul(32767&f,c),O=S.__imul(f>>>15,c),M=v+((32767&O)<<15)+w+h;h=M>>>30,w=O>>>15,p.__setDigit(g,1073741823&M)}if(p.length>y)for(p.__setDigit(y++,h+w);y<p.length;)p.__setDigit(y++,0);else if(h+w!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;m===null&&(m=new S(a.length,!1));for(var y=0,p=2*a.length-1;0<=p;p-=2){var h=(y<<15|a.__halfDigit(p))>>>0,w=0|h/c;y=0|h%c,h=(y<<15|a.__halfDigit(p-1))>>>0;var g=0|h/c;y=0|h%c,m.__setDigit(p>>>1,w<<15|g)}return m}},{key:"__absoluteModSmall",value:function(a,c){for(var m,y=0,p=2*a.length-1;0<=p;p--)m=(y<<15|a.__halfDigit(p))>>>0,y=0|m%c;return y}},{key:"__absoluteDivLarge",value:function(a,c,m,y){var p=c.__halfDigitLength(),h=c.length,w=a.__halfDigitLength()-p,g=null;m&&(g=new S(w+2>>>1,!1),g.__initializeDigits());var f=new S(p+2>>>1,!1);f.__initializeDigits();var v=S.__clz15(c.__halfDigit(p-1));0<v&&(c=S.__specialLeftShift(c,v,0));for(var O=S.__specialLeftShift(a,v,1),M=c.__halfDigit(p-1),R=0,B=w;0<=B;B--){var G=32767,Z=O.__halfDigit(B+p);if(Z!==M){var se=(Z<<15|O.__halfDigit(B+p-1))>>>0;G=0|se/M;for(var te=0|se%M,ue=c.__halfDigit(p-2),dt=O.__halfDigit(B+p-2);S.__imul(G,ue)>>>0>(te<<16|dt)>>>0&&(G--,te+=M,!(32767<te)););}S.__internalMultiplyAdd(c,G,0,h,f);var ve=O.__inplaceSub(f,B,p+1);ve!==0&&(ve=O.__inplaceAdd(c,B,p),O.__setHalfDigit(B+p,32767&O.__halfDigit(B+p)+ve),G--),m&&(1&B?R=G<<15:g.__setDigit(B>>>1,R|G))}if(y)return O.__inplaceRightShift(v),m?{quotient:g,remainder:O}:O;if(m)return g;throw new Error("unreachable")}},{key:"__clz15",value:function(a){return S.__clz30(a)-15}},{key:"__specialLeftShift",value:function(a,c,m){var y=a.length,p=new S(y+m,!1);if(c===0){for(var h=0;h<y;h++)p.__setDigit(h,a.__digit(h));return 0<m&&p.__setDigit(y,0),p}for(var w,g=0,f=0;f<y;f++)w=a.__digit(f),p.__setDigit(f,1073741823&w<<c|g),g=w>>>30-c;return 0<m&&p.__setDigit(y,g),p}},{key:"__leftShiftByAbsolute",value:function(a,c){var m=S.__toShiftAmount(c);if(0>m)throw new RangeError("BigInt too big");var y=0|m/30,p=m%30,h=a.length,w=p!==0&&a.__digit(h-1)>>>30-p!=0,g=h+y+(w?1:0),f=new S(g,a.sign);if(p===0){for(var v=0;v<y;v++)f.__setDigit(v,0);for(;v<g;v++)f.__setDigit(v,a.__digit(v-y))}else{for(var O=0,M=0;M<y;M++)f.__setDigit(M,0);for(var R,B=0;B<h;B++)R=a.__digit(B),f.__setDigit(B+y,1073741823&R<<p|O),O=R>>>30-p;if(w)f.__setDigit(h+y,O);else if(O!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(a,c){var m=a.length,y=a.sign,p=S.__toShiftAmount(c);if(0>p)return S.__rightShiftByMaximum(y);var h=0|p/30,w=p%30,g=m-h;if(0>=g)return S.__rightShiftByMaximum(y);var f=!1;if(y){if(a.__digit(h)&(1<<w)-1)f=!0;else for(var v=0;v<h;v++)if(a.__digit(v)!==0){f=!0;break}}if(f&&w===0){var O=a.__digit(m-1);!~O&&g++}var M=new S(g,y);if(w===0){M.__setDigit(g-1,0);for(var R=h;R<m;R++)M.__setDigit(R-h,a.__digit(R))}else{for(var B,G=a.__digit(h)>>>w,Z=m-h-1,se=0;se<Z;se++)B=a.__digit(se+h+1),M.__setDigit(se,1073741823&B<<30-w|G),G=B>>>w;M.__setDigit(Z,G)}return f&&(M=S.__absoluteAddOne(M,!0,M)),M.__trim()}},{key:"__rightShiftByMaximum",value:function(a){return a?S.__oneDigit(1,!0):S.__zero()}},{key:"__toShiftAmount",value:function(a){if(1<a.length)return-1;var c=a.__unsignedDigit(0);return c>S.__kMaxLengthBits?-1:c}},{key:"__toPrimitive",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(r(a)!=="object"||a.constructor===S)return a;if(typeof Symbol<"u"&&r(Symbol.toPrimitive)==="symbol"){var m=a[Symbol.toPrimitive];if(m){var y=m(c);if(r(y)!=="object")return y;throw new TypeError("Cannot convert object to primitive value")}}var p=a.valueOf;if(p){var h=p.call(a);if(r(h)!=="object")return h}var w=a.toString;if(w){var g=w.call(a);if(r(g)!=="object")return g}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(a){return S.__isBigInt(a)?a:+a}},{key:"__isBigInt",value:function(a){return r(a)==="object"&&a!==null&&a.constructor===S}},{key:"__truncateToNBits",value:function(a,c){for(var m=0|(a+29)/30,y=new S(m,c.sign),p=m-1,h=0;h<p;h++)y.__setDigit(h,c.__digit(h));var w=c.__digit(p);if(a%30!=0){var g=32-a%30;w=w<<g>>>g}return y.__setDigit(p,w),y.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(a,c,m){for(var y=Math.min,p,h=0|(a+29)/30,w=new S(h,m),g=0,f=h-1,v=0,O=y(f,c.length);g<O;g++)p=0-c.__digit(g)-v,v=1&p>>>30,w.__setDigit(g,1073741823&p);for(;g<f;g++)w.__setDigit(g,0|1073741823&-v);var M,R=f<c.length?c.__digit(f):0,B=a%30;if(B===0)M=0-R-v,M&=1073741823;else{var G=32-B;R=R<<G>>>G;var Z=1<<32-G;M=Z-R-v,M&=Z-1}return w.__setDigit(f,M),w.__trim()}},{key:"__digitPow",value:function(a,c){for(var m=1;0<c;)1&c&&(m*=a),c>>>=1,a*=a;return m}},{key:"__isOneDigitInt",value:function(a){return(1073741823&a)===a}}]),S}(T(Array));return K.__kMaxLength=33554432,K.__kMaxLengthBits=K.__kMaxLength<<5,K.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],K.__kBitsPerCharTableShift=5,K.__kBitsPerCharTableMultiplier=1<<K.__kBitsPerCharTableShift,K.__kConversionChars=["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"],K.__kBitConversionBuffer=new ArrayBuffer(8),K.__kBitConversionDouble=new Float64Array(K.__kBitConversionBuffer),K.__kBitConversionInts=new Int32Array(K.__kBitConversionBuffer),K.__clz30=e?function(F){return e(F)-2}:function(F){var U=Math.LN2,N=Math.log;return F===0?30:0|29-(0|N(F>>>0)/U)},K.__imul=t||function(F,U){return 0|F*U},K})});var E_={};fc(E_,{AddressBookSDK:()=>cn,COIN_TYPE_ARG_REGEX:()=>Lu,Coin:()=>qi,CoinHelper:()=>Fi,CreateHelper:()=>un,DEV_API_URL:()=>Up,DEV_SYNCING_URL:()=>$p,ENV_CONFIGS:()=>zp,Formatter:()=>fr,HexToUint8Array:()=>ms,LOCAL_API_URL:()=>Ku,LOCAL_SYNCING_URL:()=>Ju,MAINNET_RPC_URL:()=>Zu,MSafeAccount:()=>sn,MSafeClient:()=>ks,MSafeEnv:()=>Lp,MSafeGlobals:()=>$i,PREV_API_URL:()=>Gp,PROD_API_URL:()=>Vp,SUI_COIN:()=>C_,SignatureVerifier:()=>$u,TESTNET_RPC_URL:()=>xs,Uint8ArrayToHex:()=>I_,addPrefix:()=>Uu,getAllCoins:()=>M_,getMSafeConfig:()=>Xu,getPublicKeyFromChain:()=>Gu,stringToBuffer:()=>ps});module.exports=pc(E_);var ir=require("@msafe/sui3-utils"),un=class{constructor(e,r){this.globals=e;this.pkHelper=r}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let r=await this.reduceCreationInfoToRawConfig(e);return new ir.MultiSigAccount(r).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,r){let n=ir.PublicKeySerde.de(r);if(!(0,ir.isSameAddress)(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let r=await this.validateCreateInfo(e),n=ir.SigningMessageHelper.createMSafeMessage(r),i=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,i.signature),r}async reduceCreationInfoToRawConfig(e){let r=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return r.forEach((n,i)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[i].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,i)=>({publicKey:r[i],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,r){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(i=>i.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((i,o)=>({address:i.address,weight:i.weight,...ir.PublicKeySerde.ser(n[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:r})}};var As=require("@msafe/sui3-utils");var mc=require("@msafe/sui3-utils"),cn=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let r=mc.SigningMessageHelper.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:r});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var zi=class{constructor(e){this.globals=e}async getMSafeByStatus(e,r){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:r})}async updateMSafeStatus(e,r){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:r})}};var ch=require("@msafe/sui3-utils"),lh=de(Wi(),1);var zn=require("@mysten/sui.js/utils"),wn=require("@mysten/sui.js/transactions"),Rt=de(we(),1);var Ks=8192;function Js(t){if(t.length<Ks)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=Ks){let n=t.slice(r,r+Ks);e+=String.fromCharCode(...n)}return btoa(e)}var Ag=require("@mysten/sui.js/keypairs/ed25519"),Ig=require("@mysten/sui.js/keypairs/secp256k1"),wr=de(we(),1),ct=de(we(),1);var ln=9e15,gr=1e9,Xs="0123456789abcdef",Zi="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ki="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ys={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ln,maxE:ln,crypto:!1},Ec,or,ie=!0,Xi="[DecimalError] ",mr=Xi+"Invalid argument: ",Pc=Xi+"Precision limit exceeded",Dc=Xi+"crypto unavailable",Bc="[object Decimal]",xt=Math.floor,ft=Math.pow,lm=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,dm=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,fm=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Nc=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,$t=1e7,re=7,hm=9007199254740991,pm=Zi.length-1,Qs=Ki.length-1,q={toStringTag:Bc};q.absoluteValue=q.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),J(t)};q.ceil=function(){return J(new this.constructor(this),this.e+1,2)};q.clampedTo=q.clamp=function(t,e){var r,n=this,i=n.constructor;if(t=new i(t),e=new i(e),!t.s||!e.s)return new i(NaN);if(t.gt(e))throw Error(mr+e);return r=n.cmp(t),r<0?t:n.cmp(e)>0?e:new i(n)};q.comparedTo=q.cmp=function(t){var e,r,n,i,o=this,s=o.d,u=(t=new o.constructor(t)).d,l=o.s,d=t.s;if(!s||!u)return!l||!d?NaN:l!==d?l:s===u?0:!s^l<0?1:-1;if(!s[0]||!u[0])return s[0]?l:u[0]?-d:0;if(l!==d)return l;if(o.e!==t.e)return o.e>t.e^l<0?1:-1;for(n=s.length,i=u.length,e=0,r=n<i?n:i;e<r;++e)if(s[e]!==u[e])return s[e]>u[e]^l<0?1:-1;return n===i?0:n>i^l<0?1:-1};q.cosine=q.cos=function(){var t,e,r=this,n=r.constructor;return r.d?r.d[0]?(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=mm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or==2||or==3?r.neg():r,t,e,!0)):new n(1):new n(NaN)};q.cubeRoot=q.cbrt=function(){var t,e,r,n,i,o,s,u,l,d,b=this,_=b.constructor;if(!b.isFinite()||b.isZero())return new _(b);for(ie=!1,o=b.s*ft(b.s*b,1/3),!o||Math.abs(o)==1/0?(r=gt(b.d),t=b.e,(o=(t-r.length+1)%3)&&(r+=o==1||o==-2?"0":"00"),o=ft(r,1/3),t=xt((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?r="5e"+t:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+t),n=new _(r),n.s=b.s):n=new _(o.toString()),s=(t=_.precision)+3;;)if(u=n,l=u.times(u).times(u),d=l.plus(b),n=Te(d.plus(b).times(u),d.plus(l),s+2,1),gt(u.d).slice(0,s)===(r=gt(n.d)).slice(0,s))if(r=r.slice(s-3,s+1),r=="9999"||!i&&r=="4999"){if(!i&&(J(u,t+1,0),u.times(u).times(u).eq(b))){n=u;break}s+=4,i=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(J(n,t+1,1),e=!n.times(n).times(n).eq(b));break}return ie=!0,J(n,t,_.rounding,e)};q.decimalPlaces=q.dp=function(){var t,e=this.d,r=NaN;if(e){if(t=e.length-1,r=(t-xt(this.e/re))*re,t=e[t],t)for(;t%10==0;t/=10)r--;r<0&&(r=0)}return r};q.dividedBy=q.div=function(t){return Te(this,new this.constructor(t))};q.dividedToIntegerBy=q.divToInt=function(t){var e=this,r=e.constructor;return J(Te(e,new r(t),0,1,1),r.precision,r.rounding)};q.equals=q.eq=function(t){return this.cmp(t)===0};q.floor=function(){return J(new this.constructor(this),this.e+1,3)};q.greaterThan=q.gt=function(t){return this.cmp(t)>0};q.greaterThanOrEqualTo=q.gte=function(t){var e=this.cmp(t);return e==1||e===0};q.hyperbolicCosine=q.cosh=function(){var t,e,r,n,i,o=this,s=o.constructor,u=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return u;r=s.precision,n=s.rounding,s.precision=r+Math.max(o.e,o.sd())+4,s.rounding=1,i=o.d.length,i<32?(t=Math.ceil(i/3),e=(1/Qi(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=dn(s,1,o.times(e),new s(1),!0);for(var l,d=t,b=new s(8);d--;)l=o.times(o),o=u.minus(l.times(b.minus(l.times(b))));return J(o,s.precision=r,s.rounding=n,!0)};q.hyperbolicSine=q.sinh=function(){var t,e,r,n,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(e=o.precision,r=o.rounding,o.precision=e+Math.max(i.e,i.sd())+4,o.rounding=1,n=i.d.length,n<3)i=dn(o,2,i,i,!0);else{t=1.4*Math.sqrt(n),t=t>16?16:t|0,i=i.times(1/Qi(5,t)),i=dn(o,2,i,i,!0);for(var s,u=new o(5),l=new o(16),d=new o(20);t--;)s=i.times(i),i=i.times(u.plus(s.times(l.times(s).plus(d))))}return o.precision=e,o.rounding=r,J(i,e,r,!0)};q.hyperbolicTangent=q.tanh=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+7,n.rounding=1,Te(r.sinh(),r.cosh(),n.precision=t,n.rounding=e)):new n(r.s)};q.inverseCosine=q.acos=function(){var t,e=this,r=e.constructor,n=e.abs().cmp(1),i=r.precision,o=r.rounding;return n!==-1?n===0?e.isNeg()?Ut(r,i,o):new r(0):new r(NaN):e.isZero()?Ut(r,i+4,o).times(.5):(r.precision=i+6,r.rounding=1,e=e.asin(),t=Ut(r,i+4,o).times(.5),r.precision=i,r.rounding=o,t.minus(e))};q.inverseHyperbolicCosine=q.acosh=function(){var t,e,r=this,n=r.constructor;return r.lte(1)?new n(r.eq(1)?0:NaN):r.isFinite()?(t=n.precision,e=n.rounding,n.precision=t+Math.max(Math.abs(r.e),r.sd())+4,n.rounding=1,ie=!1,r=r.times(r).minus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln()):new n(r)};q.inverseHyperbolicSine=q.asinh=function(){var t,e,r=this,n=r.constructor;return!r.isFinite()||r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+2*Math.max(Math.abs(r.e),r.sd())+6,n.rounding=1,ie=!1,r=r.times(r).plus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln())};q.inverseHyperbolicTangent=q.atanh=function(){var t,e,r,n,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(t=o.precision,e=o.rounding,n=i.sd(),Math.max(n,t)<2*-i.e-1?J(new o(i),t,e,!0):(o.precision=r=n-i.e,i=Te(i.plus(1),new o(1).minus(i),r+t,1),o.precision=t+4,o.rounding=1,i=i.ln(),o.precision=t,o.rounding=e,i.times(.5))):new o(NaN)};q.inverseSine=q.asin=function(){var t,e,r,n,i=this,o=i.constructor;return i.isZero()?new o(i):(e=i.abs().cmp(1),r=o.precision,n=o.rounding,e!==-1?e===0?(t=Ut(o,r+4,n).times(.5),t.s=i.s,t):new o(NaN):(o.precision=r+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=r,o.rounding=n,i.times(2)))};q.inverseTangent=q.atan=function(){var t,e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding;if(d.isFinite()){if(d.isZero())return new b(d);if(d.abs().eq(1)&&_+4<=Qs)return s=Ut(b,_+4,T).times(.25),s.s=d.s,s}else{if(!d.s)return new b(NaN);if(_+4<=Qs)return s=Ut(b,_+4,T).times(.5),s.s=d.s,s}for(b.precision=u=_+10,b.rounding=1,r=Math.min(28,u/re+2|0),t=r;t;--t)d=d.div(d.times(d).plus(1).sqrt().plus(1));for(ie=!1,e=Math.ceil(u/re),n=1,l=d.times(d),s=new b(d),i=d;t!==-1;)if(i=i.times(l),o=s.minus(i.div(n+=2)),i=i.times(l),s=o.plus(i.div(n+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return r&&(s=s.times(2<<r-1)),ie=!0,J(s,b.precision=_,b.rounding=T,!0)};q.isFinite=function(){return!!this.d};q.isInteger=q.isInt=function(){return!!this.d&&xt(this.e/re)>this.d.length-2};q.isNaN=function(){return!this.s};q.isNegative=q.isNeg=function(){return this.s<0};q.isPositive=q.isPos=function(){return this.s>0};q.isZero=function(){return!!this.d&&this.d[0]===0};q.lessThan=q.lt=function(t){return this.cmp(t)<0};q.lessThanOrEqualTo=q.lte=function(t){return this.cmp(t)<1};q.logarithm=q.log=function(t){var e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding,x=5;if(t==null)t=new b(10),e=!0;else{if(t=new b(t),r=t.d,t.s<0||!r||!r[0]||t.eq(1))return new b(NaN);e=t.eq(10)}if(r=d.d,d.s<0||!r||!r[0]||d.eq(1))return new b(r&&!r[0]?-1/0:d.s!=1?NaN:r?0:1/0);if(e)if(r.length>1)o=!0;else{for(i=r[0];i%10===0;)i/=10;o=i!==1}if(ie=!1,u=_+x,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),$n(l.d,i=_,T))do if(u+=10,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),!o){+gt(l.d).slice(i+1,i+15)+1==1e14&&(l=J(l,_+1,0));break}while($n(l.d,i+=10,T));return ie=!0,J(l,_,T)};q.minus=q.sub=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.constructor;if(t=new A(t),!x.d||!t.d)return!x.s||!t.s?t=new A(NaN):x.d?t.s=-t.s:t=new A(t.d||x.s!==t.s?x:NaN),t;if(x.s!=t.s)return t.s=-t.s,x.plus(t);if(d=x.d,T=t.d,u=A.precision,l=A.rounding,!d[0]||!T[0]){if(T[0])t.s=-t.s;else if(d[0])t=new A(x);else return new A(l===3?-0:0);return ie?J(t,u,l):t}if(r=xt(t.e/re),b=xt(x.e/re),d=d.slice(),o=b-r,o){for(_=o<0,_?(e=d,o=-o,s=T.length):(e=T,r=b,s=d.length),n=Math.max(Math.ceil(u/re),s)+2,o>n&&(o=n,e.length=1),e.reverse(),n=o;n--;)e.push(0);e.reverse()}else{for(n=d.length,s=T.length,_=n<s,_&&(s=n),n=0;n<s;n++)if(d[n]!=T[n]){_=d[n]<T[n];break}o=0}for(_&&(e=d,d=T,T=e,t.s=-t.s),s=d.length,n=T.length-s;n>0;--n)d[s++]=0;for(n=T.length;n>o;){if(d[--n]<T[n]){for(i=n;i&&d[--i]===0;)d[i]=$t-1;--d[i],d[n]+=$t}d[n]-=T[n]}for(;d[--s]===0;)d.pop();for(;d[0]===0;d.shift())--r;return d[0]?(t.d=d,t.e=Yi(d,r),ie?J(t,u,l):t):new A(l===3?-0:0)};q.modulo=q.mod=function(t){var e,r=this,n=r.constructor;return t=new n(t),!r.d||!t.s||t.d&&!t.d[0]?new n(NaN):!t.d||r.d&&!r.d[0]?J(new n(r),n.precision,n.rounding):(ie=!1,n.modulo==9?(e=Te(r,t.abs(),0,3,1),e.s*=t.s):e=Te(r,t,0,n.modulo,1),e=e.times(t),ie=!0,r.minus(e))};q.naturalExponential=q.exp=function(){return ea(this)};q.naturalLogarithm=q.ln=function(){return pr(this)};q.negated=q.neg=function(){var t=new this.constructor(this);return t.s=-t.s,J(t)};q.plus=q.add=function(t){var e,r,n,i,o,s,u,l,d,b,_=this,T=_.constructor;if(t=new T(t),!_.d||!t.d)return!_.s||!t.s?t=new T(NaN):_.d||(t=new T(t.d||_.s===t.s?_:NaN)),t;if(_.s!=t.s)return t.s=-t.s,_.minus(t);if(d=_.d,b=t.d,u=T.precision,l=T.rounding,!d[0]||!b[0])return b[0]||(t=new T(_)),ie?J(t,u,l):t;if(o=xt(_.e/re),n=xt(t.e/re),d=d.slice(),i=o-n,i){for(i<0?(r=d,i=-i,s=b.length):(r=b,n=o,s=d.length),o=Math.ceil(u/re),s=o>s?o+1:s+1,i>s&&(i=s,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(s=d.length,i=b.length,s-i<0&&(i=s,r=b,b=d,d=r),e=0;i;)e=(d[--i]=d[i]+b[i]+e)/$t|0,d[i]%=$t;for(e&&(d.unshift(e),++n),s=d.length;d[--s]==0;)d.pop();return t.d=d,t.e=Yi(d,n),ie?J(t,u,l):t};q.precision=q.sd=function(t){var e,r=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(mr+t);return r.d?(e=Rc(r.d),t&&r.e+1>e&&(e=r.e+1)):e=NaN,e};q.round=function(){var t=this,e=t.constructor;return J(new e(t),t.e+1,e.rounding)};q.sine=q.sin=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=wm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or>2?r.neg():r,t,e,!0)):new n(NaN)};q.squareRoot=q.sqrt=function(){var t,e,r,n,i,o,s=this,u=s.d,l=s.e,d=s.s,b=s.constructor;if(d!==1||!u||!u[0])return new b(!d||d<0&&(!u||u[0])?NaN:u?s:1/0);for(ie=!1,d=Math.sqrt(+s),d==0||d==1/0?(e=gt(u),(e.length+l)%2==0&&(e+="0"),d=Math.sqrt(e),l=xt((l+1)/2)-(l<0||l%2),d==1/0?e="5e"+l:(e=d.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),n=new b(e)):n=new b(d.toString()),r=(l=b.precision)+3;;)if(o=n,n=o.plus(Te(s,o,r+2,1)).times(.5),gt(o.d).slice(0,r)===(e=gt(n.d)).slice(0,r))if(e=e.slice(r-3,r+1),e=="9999"||!i&&e=="4999"){if(!i&&(J(o,l+1,0),o.times(o).eq(s))){n=o;break}r+=4,i=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(J(n,l+1,1),t=!n.times(n).eq(s));break}return ie=!0,J(n,l,b.rounding,t)};q.tangent=q.tan=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+10,n.rounding=1,r=r.sin(),r.s=1,r=Te(r,new n(1).minus(r.times(r)).sqrt(),t+10,0),n.precision=t,n.rounding=e,J(or==2||or==4?r.neg():r,t,e,!0)):new n(NaN)};q.times=q.mul=function(t){var e,r,n,i,o,s,u,l,d,b=this,_=b.constructor,T=b.d,x=(t=new _(t)).d;if(t.s*=b.s,!T||!T[0]||!x||!x[0])return new _(!t.s||T&&!T[0]&&!x||x&&!x[0]&&!T?NaN:!T||!x?t.s/0:t.s*0);for(r=xt(b.e/re)+xt(t.e/re),l=T.length,d=x.length,l<d&&(o=T,T=x,x=o,s=l,l=d,d=s),o=[],s=l+d,n=s;n--;)o.push(0);for(n=d;--n>=0;){for(e=0,i=l+n;i>n;)u=o[i]+x[n]*T[i-n-1]+e,o[i--]=u%$t|0,e=u/$t|0;o[i]=(o[i]+e)%$t|0}for(;!o[--s];)o.pop();return e?++r:o.shift(),t.d=o,t.e=Yi(o,r),ie?J(t,_.precision,_.rounding):t};q.toBinary=function(t,e){return ra(this,2,t,e)};q.toDecimalPlaces=q.toDP=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(Ct(t,0,gr),e===void 0?e=n.rounding:Ct(e,0,8),J(r,t+r.e+1,e))};q.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,!0):(Ct(t,0,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t+1,e),r=Yt(n,!0,t+1)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?r=Yt(i):(Ct(t,0,gr),e===void 0?e=o.rounding:Ct(e,0,8),n=J(new o(i),t+i.e+1,e),r=Yt(n,!1,t+n.e+1)),i.isNeg()&&!i.isZero()?"-"+r:r};q.toFraction=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.d,I=x.constructor;if(!A)return new I(x);if(d=r=new I(1),n=l=new I(0),e=new I(n),o=e.e=Rc(A)-x.e-1,s=o%re,e.d[0]=ft(10,s<0?re+s:s),t==null)t=o>0?e:d;else{if(u=new I(t),!u.isInt()||u.lt(d))throw Error(mr+u);t=u.gt(e)?o>0?e:d:u}for(ie=!1,u=new I(gt(A)),b=I.precision,I.precision=o=A.length*re*2;_=Te(u,e,0,1,1),i=r.plus(_.times(n)),i.cmp(t)!=1;)r=n,n=i,i=d,d=l.plus(_.times(i)),l=i,i=e,e=u.minus(_.times(i)),u=i;return i=Te(t.minus(r),n,0,1,1),l=l.plus(i.times(d)),r=r.plus(i.times(n)),l.s=d.s=x.s,T=Te(d,n,o,1).minus(x).abs().cmp(Te(l,r,o,1).minus(x).abs())<1?[d,n]:[l,r],I.precision=b,ie=!0,T};q.toHexadecimal=q.toHex=function(t,e){return ra(this,16,t,e)};q.toNearest=function(t,e){var r=this,n=r.constructor;if(r=new n(r),t==null){if(!r.d)return r;t=new n(1),e=n.rounding}else{if(t=new n(t),e===void 0?e=n.rounding:Ct(e,0,8),!r.d)return t.s?r:t;if(!t.d)return t.s&&(t.s=r.s),t}return t.d[0]?(ie=!1,r=Te(r,t,0,e,1).times(t),ie=!0,J(r)):(t.s=r.s,r=t),r};q.toNumber=function(){return+this};q.toOctal=function(t,e){return ra(this,8,t,e)};q.toPower=q.pow=function(t){var e,r,n,i,o,s,u=this,l=u.constructor,d=+(t=new l(t));if(!u.d||!t.d||!u.d[0]||!t.d[0])return new l(ft(+u,d));if(u=new l(u),u.eq(1))return u;if(n=l.precision,o=l.rounding,t.eq(1))return J(u,n,o);if(e=xt(t.e/re),e>=t.d.length-1&&(r=d<0?-d:d)<=hm)return i=jc(l,u,r,n),t.s<0?new l(1).div(i):J(i,n,o);if(s=u.s,s<0){if(e<t.d.length-1)return new l(NaN);if(t.d[e]&1||(s=1),u.e==0&&u.d[0]==1&&u.d.length==1)return u.s=s,u}return r=ft(+u,d),e=r==0||!isFinite(r)?xt(d*(Math.log("0."+gt(u.d))/Math.LN10+u.e+1)):new l(r+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(ie=!1,l.rounding=u.s=1,r=Math.min(12,(e+"").length),i=ea(t.times(pr(u,n+r)),n),i.d&&(i=J(i,n+5,1),$n(i.d,n,o)&&(e=n+10,i=J(ea(t.times(pr(u,e+r)),e),e+5,1),+gt(i.d).slice(n+1,n+15)+1==1e14&&(i=J(i,n+1,0)))),i.s=s,ie=!0,l.rounding=o,J(i,n,o))};q.toPrecision=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,n.e<=i.toExpNeg||n.e>=i.toExpPos):(Ct(t,1,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t,e),r=Yt(n,t<=n.e||n.e<=i.toExpNeg,t)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toSignificantDigits=q.toSD=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(Ct(t,1,gr),e===void 0?e=n.rounding:Ct(e,0,8)),J(new n(r),t,e)};q.toString=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+r:r};q.truncated=q.trunc=function(){return J(new this.constructor(this),this.e+1,1)};q.valueOf=q.toJSON=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+r:r};function gt(t){var e,r,n,i=t.length-1,o="",s=t[0];if(i>0){for(o+=s,e=1;e<i;e++)n=t[e]+"",r=re-n.length,r&&(o+=hr(r)),o+=n;s=t[e],n=s+"",r=re-n.length,r&&(o+=hr(r))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Ct(t,e,r){if(t!==~~t||t<e||t>r)throw Error(mr+t)}function $n(t,e,r,n){var i,o,s,u;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=re,i=0):(i=Math.ceil((e+1)/re),e%=re),o=ft(10,re-e),u=t[i]%o|0,n==null?e<3?(e==0?u=u/100|0:e==1&&(u=u/10|0),s=r<4&&u==99999||r>3&&u==49999||u==5e4||u==0):s=(r<4&&u+1==o||r>3&&u+1==o/2)&&(t[i+1]/o/100|0)==ft(10,e-2)-1||(u==o/2||u==0)&&(t[i+1]/o/100|0)==0:e<4?(e==0?u=u/1e3|0:e==1?u=u/100|0:e==2&&(u=u/10|0),s=(n||r<4)&&u==9999||!n&&r>3&&u==4999):s=((n||r<4)&&u+1==o||!n&&r>3&&u+1==o/2)&&(t[i+1]/o/1e3|0)==ft(10,e-3)-1,s}function Hi(t,e,r){for(var n,i=[0],o,s=0,u=t.length;s<u;){for(o=i.length;o--;)i[o]*=e;for(i[0]+=Xs.indexOf(t.charAt(s++)),n=0;n<i.length;n++)i[n]>r-1&&(i[n+1]===void 0&&(i[n+1]=0),i[n+1]+=i[n]/r|0,i[n]%=r)}return i.reverse()}function mm(t,e){var r,n,i;if(e.isZero())return e;n=e.d.length,n<32?(r=Math.ceil(n/3),i=(1/Qi(4,r)).toString()):(r=16,i="2.3283064365386962890625e-10"),t.precision+=r,e=dn(t,1,e.times(i),new t(1));for(var o=r;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=r,e}var Te=function(){function t(n,i,o){var s,u=0,l=n.length;for(n=n.slice();l--;)s=n[l]*i+u,n[l]=s%o|0,u=s/o|0;return u&&n.unshift(u),n}function e(n,i,o,s){var u,l;if(o!=s)l=o>s?1:-1;else for(u=l=0;u<o;u++)if(n[u]!=i[u]){l=n[u]>i[u]?1:-1;break}return l}function r(n,i,o,s){for(var u=0;o--;)n[o]-=u,u=n[o]<i[o]?1:0,n[o]=u*s+n[o]-i[o];for(;!n[0]&&n.length>1;)n.shift()}return function(n,i,o,s,u,l){var d,b,_,T,x,A,I,C,E,P,D,L,H,W,K,F,U,N,j,S,k=n.constructor,a=n.s==i.s?1:-1,c=n.d,m=i.d;if(!c||!c[0]||!m||!m[0])return new k(!n.s||!i.s||(c?m&&c[0]==m[0]:!m)?NaN:c&&c[0]==0||!m?a*0:a/0);for(l?(x=1,b=n.e-i.e):(l=$t,x=re,b=xt(n.e/x)-xt(i.e/x)),j=m.length,U=c.length,E=new k(a),P=E.d=[],_=0;m[_]==(c[_]||0);_++);if(m[_]>(c[_]||0)&&b--,o==null?(W=o=k.precision,s=k.rounding):u?W=o+(n.e-i.e)+1:W=o,W<0)P.push(1),A=!0;else{if(W=W/x+2|0,_=0,j==1){for(T=0,m=m[0],W++;(_<U||T)&&W--;_++)K=T*l+(c[_]||0),P[_]=K/m|0,T=K%m|0;A=T||_<U}else{for(T=l/(m[0]+1)|0,T>1&&(m=t(m,T,l),c=t(c,T,l),j=m.length,U=c.length),F=j,D=c.slice(0,j),L=D.length;L<j;)D[L++]=0;S=m.slice(),S.unshift(0),N=m[0],m[1]>=l/2&&++N;do T=0,d=e(m,D,j,L),d<0?(H=D[0],j!=L&&(H=H*l+(D[1]||0)),T=H/N|0,T>1?(T>=l&&(T=l-1),I=t(m,T,l),C=I.length,L=D.length,d=e(I,D,C,L),d==1&&(T--,r(I,j<C?S:m,C,l))):(T==0&&(d=T=1),I=m.slice()),C=I.length,C<L&&I.unshift(0),r(D,I,L,l),d==-1&&(L=D.length,d=e(m,D,j,L),d<1&&(T++,r(D,j<L?S:m,L,l))),L=D.length):d===0&&(T++,D=[0]),P[_++]=T,d&&D[0]?D[L++]=c[F]||0:(D=[c[F]],L=1);while((F++<U||D[0]!==void 0)&&W--);A=D[0]!==void 0}P[0]||P.shift()}if(x==1)E.e=b,Ec=A;else{for(_=1,T=P[0];T>=10;T/=10)_++;E.e=_+b*x-1,J(E,u?o+E.e+1:o,s,A)}return E}}();function J(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor;e:if(e!=null){if(_=t.d,!_)return t;for(i=1,u=_[0];u>=10;u/=10)i++;if(o=e-i,o<0)o+=re,s=e,b=_[T=0],l=b/ft(10,i-s-1)%10|0;else if(T=Math.ceil((o+1)/re),u=_.length,T>=u)if(n){for(;u++<=T;)_.push(0);b=l=0,i=1,o%=re,s=o-re+1}else break e;else{for(b=u=_[T],i=1;u>=10;u/=10)i++;o%=re,s=o-re+i,l=s<0?0:b/ft(10,i-s-1)%10|0}if(n=n||e<0||_[T+1]!==void 0||(s<0?b:b%ft(10,i-s-1)),d=r<4?(l||n)&&(r==0||r==(t.s<0?3:2)):l>5||l==5&&(r==4||n||r==6&&(o>0?s>0?b/ft(10,i-s):0:_[T-1])%10&1||r==(t.s<0?8:7)),e<1||!_[0])return _.length=0,d?(e-=t.e+1,_[0]=ft(10,(re-e%re)%re),t.e=-e||0):_[0]=t.e=0,t;if(o==0?(_.length=T,u=1,T--):(_.length=T+1,u=ft(10,re-o),_[T]=s>0?(b/ft(10,i-s)%ft(10,s)|0)*u:0),d)for(;;)if(T==0){for(o=1,s=_[0];s>=10;s/=10)o++;for(s=_[0]+=u,u=1;s>=10;s/=10)u++;o!=u&&(t.e++,_[0]==$t&&(_[0]=1));break}else{if(_[T]+=u,_[T]!=$t)break;_[T--]=0,u=1}for(o=_.length;_[--o]===0;)_.pop()}return ie&&(t.e>x.maxE?(t.d=null,t.e=NaN):t.e<x.minE&&(t.e=0,t.d=[0])),t}function Yt(t,e,r){if(!t.isFinite())return qc(t);var n,i=t.e,o=gt(t.d),s=o.length;return e?(r&&(n=r-s)>0?o=o.charAt(0)+"."+o.slice(1)+hr(n):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):i<0?(o="0."+hr(-i-1)+o,r&&(n=r-s)>0&&(o+=hr(n))):i>=s?(o+=hr(i+1-s),r&&(n=r-i-1)>0&&(o=o+"."+hr(n))):((n=i+1)<s&&(o=o.slice(0,n)+"."+o.slice(n)),r&&(n=r-s)>0&&(i+1===s&&(o+="."),o+=hr(n))),o}function Yi(t,e){var r=t[0];for(e*=re;r>=10;r/=10)e++;return e}function Ji(t,e,r){if(e>pm)throw ie=!0,r&&(t.precision=r),Error(Pc);return J(new t(Zi),e,1,!0)}function Ut(t,e,r){if(e>Qs)throw Error(Pc);return J(new t(Ki),e,r,!0)}function Rc(t){var e=t.length-1,r=e*re+1;if(e=t[e],e){for(;e%10==0;e/=10)r--;for(e=t[0];e>=10;e/=10)r++}return r}function hr(t){for(var e="";t--;)e+="0";return e}function jc(t,e,r,n){var i,o=new t(1),s=Math.ceil(n/re+4);for(ie=!1;;){if(r%2&&(o=o.times(e),Oc(o.d,s)&&(i=!0)),r=xt(r/2),r===0){r=o.d.length-1,i&&o.d[r]===0&&++o.d[r];break}e=e.times(e),Oc(e.d,s)}return ie=!0,o}function Cc(t){return t.d[t.d.length-1]&1}function Fc(t,e,r){for(var n,i=new t(e[0]),o=0;++o<e.length;)if(n=new t(e[o]),n.s)i[r](n)&&(i=n);else{i=n;break}return i}function ea(t,e){var r,n,i,o,s,u,l,d=0,b=0,_=0,T=t.constructor,x=T.rounding,A=T.precision;if(!t.d||!t.d[0]||t.e>17)return new T(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(ie=!1,l=A):l=e,u=new T(.03125);t.e>-2;)t=t.times(u),_+=5;for(n=Math.log(ft(2,_))/Math.LN10*2+5|0,l+=n,r=o=s=new T(1),T.precision=l;;){if(o=J(o.times(t),l,1),r=r.times(++b),u=s.plus(Te(o,r,l,1)),gt(u.d).slice(0,l)===gt(s.d).slice(0,l)){for(i=_;i--;)s=J(s.times(s),l,1);if(e==null)if(d<3&&$n(s.d,l-n,x,d))T.precision=l+=10,r=o=u=new T(1),b=0,d++;else return J(s,T.precision=A,x,ie=!0);else return T.precision=A,s}s=u}}function pr(t,e){var r,n,i,o,s,u,l,d,b,_,T,x=1,A=10,I=t,C=I.d,E=I.constructor,P=E.rounding,D=E.precision;if(I.s<0||!C||!C[0]||!I.e&&C[0]==1&&C.length==1)return new E(C&&!C[0]?-1/0:I.s!=1?NaN:C?0:I);if(e==null?(ie=!1,b=D):b=e,E.precision=b+=A,r=gt(C),n=r.charAt(0),Math.abs(o=I.e)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)I=I.times(t),r=gt(I.d),n=r.charAt(0),x++;o=I.e,n>1?(I=new E("0."+r),o++):I=new E(n+"."+r.slice(1))}else return d=Ji(E,b+2,D).times(o+""),I=pr(new E(n+"."+r.slice(1)),b-A).plus(d),E.precision=D,e==null?J(I,D,P,ie=!0):I;for(_=I,l=s=I=Te(I.minus(1),I.plus(1),b,1),T=J(I.times(I),b,1),i=3;;){if(s=J(s.times(T),b,1),d=l.plus(Te(s,new E(i),b,1)),gt(d.d).slice(0,b)===gt(l.d).slice(0,b))if(l=l.times(2),o!==0&&(l=l.plus(Ji(E,b+2,D).times(o+""))),l=Te(l,new E(x),b,1),e==null)if($n(l.d,b-A,P,u))E.precision=b+=A,d=s=I=Te(_.minus(1),_.plus(1),b,1),T=J(I.times(I),b,1),i=u=1;else return J(l,E.precision=D,P,ie=!0);else return E.precision=D,l;l=d,i+=2}}function qc(t){return String(t.s*t.s/0)}function ta(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;n++);for(i=e.length;e.charCodeAt(i-1)===48;--i);if(e=e.slice(n,i),e){if(i-=n,t.e=r=r-n-1,t.d=[],n=(r+1)%re,r<0&&(n+=re),n<i){for(n&&t.d.push(+e.slice(0,n)),i-=re;n<i;)t.d.push(+e.slice(n,n+=re));e=e.slice(n),n=re-e.length}else n-=i;for(;n--;)e+="0";t.d.push(+e),ie&&(t.e>t.constructor.maxE?(t.d=null,t.e=NaN):t.e<t.constructor.minE&&(t.e=0,t.d=[0]))}else t.e=0,t.d=[0];return t}function gm(t,e){var r,n,i,o,s,u,l,d,b;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Nc.test(e))return ta(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(dm.test(e))r=16,e=e.toLowerCase();else if(lm.test(e))r=2;else if(fm.test(e))r=8;else throw Error(mr+e);for(o=e.search(/p/i),o>0?(l=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,n=t.constructor,s&&(e=e.replace(".",""),u=e.length,o=u-o,i=jc(n,new n(r),o,o*2)),d=Hi(e,r,$t),b=d.length-1,o=b;d[o]===0;--o)d.pop();return o<0?new n(t.s*0):(t.e=Yi(d,b),t.d=d,ie=!1,s&&(t=Te(t,i,u*4)),l&&(t=t.times(Math.abs(l)<54?ft(2,l):Gn.pow(2,l))),ie=!0,t)}function wm(t,e){var r,n=e.d.length;if(n<3)return e.isZero()?e:dn(t,2,e,e);r=1.4*Math.sqrt(n),r=r>16?16:r|0,e=e.times(1/Qi(5,r)),e=dn(t,2,e,e);for(var i,o=new t(5),s=new t(16),u=new t(20);r--;)i=e.times(e),e=e.times(o.plus(i.times(s.times(i).minus(u))));return e}function dn(t,e,r,n,i){var o,s,u,l,d=1,b=t.precision,_=Math.ceil(b/re);for(ie=!1,l=r.times(r),u=new t(n);;){if(s=Te(u.times(l),new t(e++*e++),b,1),u=i?n.plus(s):n.minus(s),n=Te(s.times(l),new t(e++*e++),b,1),s=u.plus(n),s.d[_]!==void 0){for(o=_;s.d[o]===u.d[o]&&o--;);if(o==-1)break}o=u,u=n,n=s,s=o,d++}return ie=!0,s.d.length=_+1,s}function Qi(t,e){for(var r=t;--e;)r*=t;return r}function Lc(t,e){var r,n=e.s<0,i=Ut(t,t.precision,1),o=i.times(.5);if(e=e.abs(),e.lte(o))return or=n?4:1,e;if(r=e.divToInt(i),r.isZero())or=n?3:2;else{if(e=e.minus(r.times(i)),e.lte(o))return or=Cc(r)?n?2:3:n?4:1,e;or=Cc(r)?n?1:4:n?3:2}return e.minus(i).abs()}function ra(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor,A=r!==void 0;if(A?(Ct(r,1,gr),n===void 0?n=x.rounding:Ct(n,0,8)):(r=x.precision,n=x.rounding),!t.isFinite())b=qc(t);else{for(b=Yt(t),s=b.indexOf("."),A?(i=2,e==16?r=r*4-3:e==8&&(r=r*3-2)):i=e,s>=0&&(b=b.replace(".",""),T=new x(1),T.e=b.length-s,T.d=Hi(Yt(T),10,i),T.e=T.d.length),_=Hi(b,10,i),o=l=_.length;_[--l]==0;)_.pop();if(!_[0])b=A?"0p+0":"0";else{if(s<0?o--:(t=new x(t),t.d=_,t.e=o,t=Te(t,T,r,n,0,i),_=t.d,o=t.e,d=Ec),s=_[r],u=i/2,d=d||_[r+1]!==void 0,d=n<4?(s!==void 0||d)&&(n===0||n===(t.s<0?3:2)):s>u||s===u&&(n===4||d||n===6&&_[r-1]&1||n===(t.s<0?8:7)),_.length=r,d)for(;++_[--r]>i-1;)_[r]=0,r||(++o,_.unshift(1));for(l=_.length;!_[l-1];--l);for(s=0,b="";s<l;s++)b+=Xs.charAt(_[s]);if(A){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)b+="0";for(_=Hi(b,i,e),l=_.length;!_[l-1];--l);for(s=1,b="1.";s<l;s++)b+=Xs.charAt(_[s])}else b=b.charAt(0)+"."+b.slice(1);b=b+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)b="0"+b;b="0."+b}else if(++o>l)for(o-=l;o--;)b+="0";else o<l&&(b=b.slice(0,o)+"."+b.slice(o))}b=(e==16?"0x":e==2?"0b":e==8?"0o":"")+b}return t.s<0?"-"+b:b}function Oc(t,e){if(t.length>e)return t.length=e,!0}function ym(t){return new this(t).abs()}function bm(t){return new this(t).acos()}function _m(t){return new this(t).acosh()}function vm(t,e){return new this(t).plus(e)}function Tm(t){return new this(t).asin()}function Sm(t){return new this(t).asinh()}function xm(t){return new this(t).atan()}function km(t){return new this(t).atanh()}function Am(t,e){t=new this(t),e=new this(e);var r,n=this.precision,i=this.rounding,o=n+4;return!t.s||!e.s?r=new this(NaN):!t.d&&!e.d?(r=Ut(this,o,1).times(e.s>0?.25:.75),r.s=t.s):!e.d||t.isZero()?(r=e.s<0?Ut(this,n,i):new this(0),r.s=t.s):!t.d||e.isZero()?(r=Ut(this,o,1).times(.5),r.s=t.s):e.s<0?(this.precision=o,this.rounding=1,r=this.atan(Te(t,e,o,1)),e=Ut(this,o,1),this.precision=n,this.rounding=i,r=t.s<0?r.minus(e):r.plus(e)):r=this.atan(Te(t,e,o,1)),r}function Im(t){return new this(t).cbrt()}function Cm(t){return J(t=new this(t),t.e+1,2)}function Om(t,e,r){return new this(t).clamp(e,r)}function Mm(t){if(!t||typeof t!="object")throw Error(Xi+"Object expected");var e,r,n,i=t.defaults===!0,o=["precision",1,gr,"rounding",0,8,"toExpNeg",-ln,0,"toExpPos",0,ln,"maxE",0,ln,"minE",-ln,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(r=o[e],i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(xt(n)===n&&n>=o[e+1]&&n<=o[e+2])this[r]=n;else throw Error(mr+r+": "+n);if(r="crypto",i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[r]=!0;else throw Error(Dc);else this[r]=!1;else throw Error(mr+r+": "+n);return this}function Em(t){return new this(t).cos()}function Pm(t){return new this(t).cosh()}function Uc(t){var e,r,n;function i(o){var s,u,l,d=this;if(!(d instanceof i))return new i(o);if(d.constructor=i,Mc(o)){d.s=o.s,ie?!o.d||o.e>i.maxE?(d.e=NaN,d.d=null):o.e<i.minE?(d.e=0,d.d=[0]):(d.e=o.e,d.d=o.d.slice()):(d.e=o.e,d.d=o.d?o.d.slice():o.d);return}if(l=typeof o,l==="number"){if(o===0){d.s=1/o<0?-1:1,d.e=0,d.d=[0];return}if(o<0?(o=-o,d.s=-1):d.s=1,o===~~o&&o<1e7){for(s=0,u=o;u>=10;u/=10)s++;ie?s>i.maxE?(d.e=NaN,d.d=null):s<i.minE?(d.e=0,d.d=[0]):(d.e=s,d.d=[o]):(d.e=s,d.d=[o]);return}else if(o*0!==0){o||(d.s=NaN),d.e=NaN,d.d=null;return}return ta(d,o.toString())}else if(l!=="string")throw Error(mr+o);return(u=o.charCodeAt(0))===45?(o=o.slice(1),d.s=-1):(u===43&&(o=o.slice(1)),d.s=1),Nc.test(o)?ta(d,o):gm(d,o)}if(i.prototype=q,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Mm,i.clone=Uc,i.isDecimal=Mc,i.abs=ym,i.acos=bm,i.acosh=_m,i.add=vm,i.asin=Tm,i.asinh=Sm,i.atan=xm,i.atanh=km,i.atan2=Am,i.cbrt=Im,i.ceil=Cm,i.clamp=Om,i.cos=Em,i.cosh=Pm,i.div=Dm,i.exp=Bm,i.floor=Nm,i.hypot=Rm,i.ln=jm,i.log=Fm,i.log10=Lm,i.log2=qm,i.max=Um,i.min=$m,i.mod=Gm,i.mul=Vm,i.pow=zm,i.random=Wm,i.round=Hm,i.sign=Zm,i.sin=Km,i.sinh=Jm,i.sqrt=Xm,i.sub=Ym,i.sum=Qm,i.tan=eg,i.tanh=tg,i.trunc=rg,t===void 0&&(t={}),t&&t.defaults!==!0)for(n=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<n.length;)t.hasOwnProperty(r=n[e++])||(t[r]=this[r]);return i.config(t),i}function Dm(t,e){return new this(t).div(e)}function Bm(t){return new this(t).exp()}function Nm(t){return J(t=new this(t),t.e+1,3)}function Rm(){var t,e,r=new this(0);for(ie=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)r.d&&(r=r.plus(e.times(e)));else{if(e.s)return ie=!0,new this(1/0);r=e}return ie=!0,r.sqrt()}function Mc(t){return t instanceof Gn||t&&t.toStringTag===Bc||!1}function jm(t){return new this(t).ln()}function Fm(t,e){return new this(t).log(e)}function qm(t){return new this(t).log(2)}function Lm(t){return new this(t).log(10)}function Um(){return Fc(this,arguments,"lt")}function $m(){return Fc(this,arguments,"gt")}function Gm(t,e){return new this(t).mod(e)}function Vm(t,e){return new this(t).mul(e)}function zm(t,e){return new this(t).pow(e)}function Wm(t){var e,r,n,i,o=0,s=new this(1),u=[];if(t===void 0?t=this.precision:Ct(t,1,gr),n=Math.ceil(t/re),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(n));o<n;)i=e[o],i>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:u[o++]=i%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(n*=4);o<n;)i=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(e,o):(u.push(i%1e7),o+=4);o=n/4}else throw Error(Dc);else for(;o<n;)u[o++]=Math.random()*1e7|0;for(n=u[--o],t%=re,n&&t&&(i=ft(10,re-t),u[o]=(n/i|0)*i);u[o]===0;o--)u.pop();if(o<0)r=0,u=[0];else{for(r=-1;u[0]===0;r-=re)u.shift();for(n=1,i=u[0];i>=10;i/=10)n++;n<re&&(r-=re-n)}return s.e=r,s.d=u,s}function Hm(t){return J(t=new this(t),t.e+1,this.rounding)}function Zm(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function Km(t){return new this(t).sin()}function Jm(t){return new this(t).sinh()}function Xm(t){return new this(t).sqrt()}function Ym(t,e){return new this(t).sub(e)}function Qm(){var t=0,e=arguments,r=new this(e[t]);for(ie=!1;r.s&&++t<e.length;)r=r.plus(e[t]);return ie=!0,J(r,this.precision,this.rounding)}function eg(t){return new this(t).tan()}function tg(t){return new this(t).tanh()}function rg(t){return J(t=new this(t),t.e+1,1)}q[Symbol.for("nodejs.util.inspect.custom")]=q.toString;q[Symbol.toStringTag]="Decimal";var Gn=q.constructor=Uc(Ys);Zi=new Gn(Zi);Ki=new Gn(Ki);var $=Gn;var Ll=de(we(),1),Kn=de(we(),1);var ee=de(we(),1),ye=de(we(),1),Ul=de(we(),1),To=require("@mysten/sui.js/utils"),r0=de(we(),1),n0=de(we(),1),o0=de(we(),1);var qr=de(we(),1),Hn=de(we(),1);var Lr=require("@mysten/sui.js/transactions"),w0=require("@mysten/sui.js/utils"),y0=require("@mysten/sui.js/transactions"),bt=de(we(),1),po=require("@mysten/sui.js/transactions"),ga=de(we(),1),Ur=require("@mysten/sui.js/transactions"),Xl=require("@mysten/sui.js/utils"),Se=de(we(),1),mo=require("@mysten/sui.js/transactions"),Et=de(we(),1),Wr=de(hl(),1),Yl=require("@mysten/sui.js/transactions"),$r=de(we(),1);var wa=require("@mysten/sui.js/transactions");var bl="3.7.7",lg=bl,pn=typeof Buffer=="function",pl=typeof TextDecoder=="function"?new TextDecoder:void 0,ml=typeof TextEncoder=="function"?new TextEncoder:void 0,dg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Vn=Array.prototype.slice.call(dg),io=(t=>{let e={};return t.forEach((r,n)=>e[r]=n),e})(Vn),fg=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,wt=String.fromCharCode.bind(String),gl=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),_l=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),vl=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Tl=t=>{let e,r,n,i,o="",s=t.length%3;for(let u=0;u<t.length;){if((r=t.charCodeAt(u++))>255||(n=t.charCodeAt(u++))>255||(i=t.charCodeAt(u++))>255)throw new TypeError("invalid character found");e=r<<16|n<<8|i,o+=Vn[e>>18&63]+Vn[e>>12&63]+Vn[e>>6&63]+Vn[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},aa=typeof btoa=="function"?t=>btoa(t):pn?t=>Buffer.from(t,"binary").toString("base64"):Tl,oa=pn?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let n=0,i=t.length;n<i;n+=4096)r.push(wt.apply(null,t.subarray(n,n+4096)));return aa(r.join(""))},oo=(t,e=!1)=>e?_l(oa(t)):oa(t),hg=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?wt(192|e>>>6)+wt(128|e&63):wt(224|e>>>12&15)+wt(128|e>>>6&63)+wt(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return wt(240|e>>>18&7)+wt(128|e>>>12&63)+wt(128|e>>>6&63)+wt(128|e&63)}},pg=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Sl=t=>t.replace(pg,hg),wl=pn?t=>Buffer.from(t,"utf8").toString("base64"):ml?t=>oa(ml.encode(t)):t=>aa(Sl(t)),hn=(t,e=!1)=>e?_l(wl(t)):wl(t),yl=t=>hn(t,!0),mg=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,gg=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return wt((r>>>10)+55296)+wt((r&1023)+56320);case 3:return wt((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return wt((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},xl=t=>t.replace(mg,gg),kl=t=>{if(t=t.replace(/\s+/g,""),!fg.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r="",n,i;for(let o=0;o<t.length;)e=io[t.charAt(o++)]<<18|io[t.charAt(o++)]<<12|(n=io[t.charAt(o++)])<<6|(i=io[t.charAt(o++)]),r+=n===64?wt(e>>16&255):i===64?wt(e>>16&255,e>>8&255):wt(e>>16&255,e>>8&255,e&255);return r},ua=typeof atob=="function"?t=>atob(vl(t)):pn?t=>Buffer.from(t,"base64").toString("binary"):kl,Al=pn?t=>gl(Buffer.from(t,"base64")):t=>gl(ua(t).split("").map(e=>e.charCodeAt(0))),Il=t=>Al(Cl(t)),wg=pn?t=>Buffer.from(t,"base64").toString("utf8"):pl?t=>pl.decode(Al(t)):t=>xl(ua(t)),Cl=t=>vl(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),sa=t=>wg(Cl(t)),yg=t=>{if(typeof t!="string")return!1;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},Ol=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Ml=function(){let t=(e,r)=>Object.defineProperty(String.prototype,e,Ol(r));t("fromBase64",function(){return sa(this)}),t("toBase64",function(e){return hn(this,e)}),t("toBase64URI",function(){return hn(this,!0)}),t("toBase64URL",function(){return hn(this,!0)}),t("toUint8Array",function(){return Il(this)})},El=function(){let t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,Ol(r));t("toBase64",function(e){return oo(this,e)}),t("toBase64URI",function(){return oo(this,!0)}),t("toBase64URL",function(){return oo(this,!0)})},bg=()=>{Ml(),El()},mn={version:bl,VERSION:lg,atob:ua,atobPolyfill:kl,btoa:aa,btoaPolyfill:Tl,fromBase64:sa,toBase64:hn,encode:hn,encodeURI:yl,encodeURL:yl,utob:Sl,btou:xl,decode:sa,isValid:yg,fromUint8Array:oo,toUint8Array:Il,extendString:Ml,extendUint8Array:El,extendBuiltins:bg};var ya=require("@mysten/sui.js/transactions"),Ql=require("@mysten/sui.js/utils"),Gt=de(we(),1);var so,_g=new Uint8Array(16);function ca(){if(!so&&(so=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!so))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return so(_g)}var yt=[];for(let t=0;t<256;++t)yt.push((t+256).toString(16).slice(1));function Pl(t,e=0){return yt[t[e+0]]+yt[t[e+1]]+yt[t[e+2]]+yt[t[e+3]]+"-"+yt[t[e+4]]+yt[t[e+5]]+"-"+yt[t[e+6]]+yt[t[e+7]]+"-"+yt[t[e+8]]+yt[t[e+9]]+"-"+yt[t[e+10]]+yt[t[e+11]]+yt[t[e+12]]+yt[t[e+13]]+yt[t[e+14]]+yt[t[e+15]]}var vg=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),la={randomUUID:vg};function Tg(t,e,r){if(la.randomUUID&&!e&&!t)return la.randomUUID();t=t||{};let n=t.random||(t.rng||ca)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Pl(n)}var ao=Tg;var go=require("@mysten/sui.js/utils"),ed=require("@mysten/sui.js/transactions"),td=require("@mysten/sui.js/client"),rd=require("@mysten/sui.js/bcs");var Sg=Object.defineProperty,xg=(t,e,r)=>e in t?Sg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kg=(t,e,r)=>(xg(t,typeof e!="symbol"?e+"":e,r),r),yo=5*60*1e3,Oe=24*60*60*1e3;function er(t){return Date.parse(new Date().toString())+t}var Zn=class{overdueTime;value;constructor(t,e=0){this.overdueTime=e,this.value=t}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};$.config({precision:64,rounding:$.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var _t=$,V=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof V&&t.errorCode===e}},Y=new ct.default(0),Qt=new ct.default(1),bo=new ct.default(2),uv=bo.pow(new ct.default(128)),_n=bo.pow(new ct.default(64)).sub(Qt),Cg=bo.pow(new ct.default(128)).sub(Qt),fe=class{static toX64_BN(t){return t.mul(new ct.default(2).pow(new ct.default(64)))}static toX64_Decimal(t){return t.mul(_t.pow(2,64))}static toX64(t){return new ct.default(t.mul(_t.pow(2,64)).floor().toFixed())}static fromX64(t){return new _t(t.toString()).mul(_t.pow(2,-64))}static fromX64_Decimal(t){return t.mul(_t.pow(2,-64))}static fromX64_BN(t){return t.div(new ct.default(2).pow(new ct.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(_n).gt(Y)&&(e=e.add(Qt)),e}static divRoundUp(t,e){return t.mod(e).eq(Y)?t.div(e):t.div(e).add(new ct.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(Cg):t.sub(e)}static checkUnsignedSub(t,e){let r=t.sub(e);if(r.isNeg())throw new V("Unsigned integer sub overflow","UnsignedIntegerOverflow");return r}static checkMul(t,e,r){let n=t.mul(e);if(this.isOverflow(n,r))throw new V("Multiplication overflow","MultiplicationOverflow");return n}static checkMulDivFloor(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivCeil(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).add(r.sub(Qt)).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivRound(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e.add(r.shrn(1))).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulShiftRight(t,e,r,n){let i=t.mul(e).div(new ct.default(2).pow(new ct.default(r)));if(this.isOverflow(i,n))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return i}static checkMulShiftRight64RoundUpIf(t,e,r,n){let i=t.mul(e),s=n&&i.and(_n).gt(Y)?i.shrn(64).add(Qt):i.shrn(64);if(this.isOverflow(s,r))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return s}static checkMulShiftLeft(t,e,r,n){let i=t.mul(e).shln(r);if(this.isOverflow(i,n))throw new V("Multiplication shift left overflow","MulShiftLeftOverflow");return i}static checkDivRoundUpIf(t,e,r){if(e.eq(Y))throw new V("Devide by zero","DivideByZero");return r?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(bo.pow(new ct.default(e)))}static sign(t){return t.testn(127)?1:0}static is_neg(t){return this.sign(t)===1}static abs_u128(t){return t.gt(Y)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new ct.default("ffffffffffffffffffffffffffffffff",16))}static neg(t){return this.is_neg(t)?t.abs():this.neg_from(t)}static abs(t){return this.sign(t)===0?t:this.u128_neg(t.sub(new ct.default(1)))}static neg_from(t){return t.eq(Y)?t:this.u128_neg(t).add(new ct.default(1)).or(new ct.default(1).shln(127))}};function Og(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new wr.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new wr.default(t.fee_growth_global_a),feeGrowthGlobalB:new wr.default(t.fee_growth_global_b),feeProtocolCoinA:new wr.default(t.fee_protocol_coin_a),feeProtocolCoinB:new wr.default(t.fee_protocol_coin_b),feeRate:new wr.default(t.fee_rate),liquidity:new wr.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var _o="79226673515401279992447579055";var vo="4295048016",yn=new Ll.default(1e6),Ce="0x0000000000000000000000000000000000000000000000000000000000000006",Mg="partner",fo="pool_script",Gr="pool_script_v2",Wn="router",da="router_with_partner",Vr="fetcher_script",Eg="expect_swap",Dl="utils";var fa="custodian_v2",Pg="clob_v2",Dg="endpoints_v2";function be(t){if(t.config===void 0)throw new V(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var Bg=14,Ng="59543866431248",Rg="184467440737095516",jg="15793534762490258745",Fg=443636;function qg(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}function ce(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}function Lg(t){let e;return t&1?e=new ee.default("79232123823359799118286999567"):e=new ee.default("79228162514264337593543950336"),t&2&&(e=ce(e.mul(new ee.default("79236085330515764027303304731")),96,256)),t&4&&(e=ce(e.mul(new ee.default("79244008939048815603706035061")),96,256)),t&8&&(e=ce(e.mul(new ee.default("79259858533276714757314932305")),96,256)),t&16&&(e=ce(e.mul(new ee.default("79291567232598584799939703904")),96,256)),t&32&&(e=ce(e.mul(new ee.default("79355022692464371645785046466")),96,256)),t&64&&(e=ce(e.mul(new ee.default("79482085999252804386437311141")),96,256)),t&128&&(e=ce(e.mul(new ee.default("79736823300114093921829183326")),96,256)),t&256&&(e=ce(e.mul(new ee.default("80248749790819932309965073892")),96,256)),t&512&&(e=ce(e.mul(new ee.default("81282483887344747381513967011")),96,256)),t&1024&&(e=ce(e.mul(new ee.default("83390072131320151908154831281")),96,256)),t&2048&&(e=ce(e.mul(new ee.default("87770609709833776024991924138")),96,256)),t&4096&&(e=ce(e.mul(new ee.default("97234110755111693312479820773")),96,256)),t&8192&&(e=ce(e.mul(new ee.default("119332217159966728226237229890")),96,256)),t&16384&&(e=ce(e.mul(new ee.default("179736315981702064433883588727")),96,256)),t&32768&&(e=ce(e.mul(new ee.default("407748233172238350107850275304")),96,256)),t&65536&&(e=ce(e.mul(new ee.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=ce(e.mul(new ee.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=ce(e.mul(new ee.default("38992368544603139932233054999993551")),96,256)),ce(e,32,256)}function Ug(t){let e=Math.abs(t),r;return e&1?r=new ee.default("18445821805675392311"):r=new ee.default("18446744073709551616"),e&2&&(r=ce(r.mul(new ee.default("18444899583751176498")),64,256)),e&4&&(r=ce(r.mul(new ee.default("18443055278223354162")),64,256)),e&8&&(r=ce(r.mul(new ee.default("18439367220385604838")),64,256)),e&16&&(r=ce(r.mul(new ee.default("18431993317065449817")),64,256)),e&32&&(r=ce(r.mul(new ee.default("18417254355718160513")),64,256)),e&64&&(r=ce(r.mul(new ee.default("18387811781193591352")),64,256)),e&128&&(r=ce(r.mul(new ee.default("18329067761203520168")),64,256)),e&256&&(r=ce(r.mul(new ee.default("18212142134806087854")),64,256)),e&512&&(r=ce(r.mul(new ee.default("17980523815641551639")),64,256)),e&1024&&(r=ce(r.mul(new ee.default("17526086738831147013")),64,256)),e&2048&&(r=ce(r.mul(new ee.default("16651378430235024244")),64,256)),e&4096&&(r=ce(r.mul(new ee.default("15030750278693429944")),64,256)),e&8192&&(r=ce(r.mul(new ee.default("12247334978882834399")),64,256)),e&16384&&(r=ce(r.mul(new ee.default("8131365268884726200")),64,256)),e&32768&&(r=ce(r.mul(new ee.default("3584323654723342297")),64,256)),e&65536&&(r=ce(r.mul(new ee.default("696457651847595233")),64,256)),e&131072&&(r=ce(r.mul(new ee.default("26294789957452057")),64,256)),e&262144&&(r=ce(r.mul(new ee.default("37481735321082")),64,256)),r}var ke=class{static priceToSqrtPriceX64(t,e,r){return fe.toX64(t.mul(_t.pow(10,r-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,r){return fe.fromX64(t).pow(2).mul(_t.pow(10,e-r))}static tickIndexToSqrtPriceX64(t){return t>0?new ee.default(Lg(t)):new ee.default(Ug(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ee.default(_o))||t.lt(new ee.default(vo)))throw new V("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,r=new ee.default(e-64),n=qg(r,32,128),i=new ee.default("8000000000000000","hex"),o=0,s=new ee.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new ee.default(0))&&o<Bg;){u=u.mul(u);let A=u.shrn(127);u=u.shrn(63+A.toNumber()),s=s.add(i.mul(A)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new ee.default(Ng)),_=ce(b.sub(new ee.default(Rg)),64,128).toNumber(),T=ce(b.add(new ee.default(jg)),64,128).toNumber();return _===T?_:ke.tickIndexToSqrtPriceX64(T).lte(t)?T:_}static tickIndexToPrice(t,e,r){return ke.sqrtPriceX64ToPrice(ke.tickIndexToSqrtPriceX64(t),e,r)}static priceToTickIndex(t,e,r){return ke.sqrtPriceX64ToTickIndex(ke.priceToSqrtPriceX64(t,e,r))}static priceToInitializableTickIndex(t,e,r,n){return ke.getInitializableTickIndex(ke.priceToTickIndex(t,e,r),n)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)-e}};function $g(t){return vt(t).add(vt(Fg))}var lv=new Kn.default(365),dv=new Kn.default(24),fv=new Kn.default(3600),hv=new Kn.default(.5);var yr=class{static getDefaultSqrtPriceLimit(t){return new Ul.default(t?vo:_o)}static getDefaultOtherAmountThreshold(t){return t?Y:_n}};function $l(t,e,r,n){if(r.eq(Y))return t;let i=fe.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=fe.checkMul(t,r,256);if(!n&&o.lte(s))throw new V("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let u=n?fe.checkDivRoundUpIf(i,o.add(s),!0):fe.checkDivRoundUpIf(i,o.sub(s),!0);if(u.lt(new ye.default(vo)))throw new V("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(u.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return u}function Gl(t,e,r,n){let i=fe.checkDivRoundUpIf(r.shln(64),e,!n),o=n?t.add(i):t.sub(i);if(o.lt(new ye.default(vo))||o.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function Gg(t,e,r,n){return n?$l(t,e,r,!0):Gl(t,e,r,!0)}function Vg(t,e,r,n){return n?Gl(t,e,r,!1):$l(t,e,r,!1)}function Bl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n){let s=new ye.default(r).mul(new ye.default(i)).shln(64),u=e.mul(t),l=s.div(u);o=s.mod(u).eq(Y)?l:l.add(Qt)}else{let s=new ye.default(r).mul(new ye.default(i));o=s.and(_n).gt(Y)?s.shrn(64).add(Qt):s.shrn(64)}return o}function Nl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n)o=r.mul(i).shrn(64);else{let s=r.mul(i).shln(64),u=e.mul(t);o=s.div(u)}return o}function zg(t,e,r,n,i,o){if(r===Y)return{amountIn:Y,amountOut:Y,nextSqrtPrice:e,feeAmount:Y};let s=t.gte(e),u,l,d,b;if(o){let _=fe.checkMulDivFloor(n,fe.checkUnsignedSub(yn,i),yn,64),T=Bl(t,e,r,s);T.gt(_)?(u=_,b=fe.checkUnsignedSub(n,_),d=Gg(t,r,_,s)):(u=T,b=fe.checkMulDivCeil(u,i,yn.sub(i),64),d=e),l=Nl(t,d,r,s)}else{let _=Nl(t,e,r,s);_.gt(n)?(l=n,d=Vg(t,r,n,s)):(l=_,d=e),u=Bl(t,d,r,s),b=fe.checkMulDivCeil(u,i,yn.sub(i),64)}return{amountIn:u,amountOut:l,nextSqrtPrice:d,feeAmount:b}}function Wg(t,e,r,n,i){let o=r,s=n.liquidity,{currentSqrtPrice:u}=n,l={amountIn:Y,amountOut:Y,feeAmount:Y,refAmount:Y,nextSqrtPrice:Y,crossTickNum:0},d,b,_=yr.getDefaultSqrtPriceLimit(t);for(let T of i){if(t&&n.currentTickIndex<T.index||!t&&n.currentTickIndex>=T.index||T===null)continue;t&&_.gt(T.sqrtPrice)||!t&&_.lt(T.sqrtPrice)?d=_:d=T.sqrtPrice;let x=zg(u,d,s,o,n.feeRate,e);if(x.amountIn.eq(Y)||(o=e?o.sub(x.amountIn.add(x.feeAmount)):o.sub(x.amountOut)),l.amountIn=l.amountIn.add(x.amountIn),l.amountOut=l.amountOut.add(x.amountOut),l.feeAmount=l.feeAmount.add(x.feeAmount),x.nextSqrtPrice.eq(T.sqrtPrice)?(b=T.liquidityNet.mul(new ye.default(-1)),t?fe.is_neg(b)?s=s.add(new ye.default(Vt(BigInt(b.toString()),128))):s=s.add(b):fe.is_neg(b)?s=s.sub(new ye.default(Vt(BigInt(b.toString()),128))):s=s.sub(b),u=T.sqrtPrice):u=x.nextSqrtPrice,l.crossTickNum+=1,o.eq(Y))break}return l.amountIn=l.amountIn.add(l.feeAmount),l.nextSqrtPrice=u,l}function uo(t,e,r){let n=ye.default.min(t,e),i=ye.default.max(t,e),o=fe.fromX64_BN(r.mul(i).mul(n)),s=i.sub(n);return o.div(s)}function co(t,e,r){let n=ye.default.min(t,e),o=ye.default.max(t,e).sub(n);return r.shln(64).div(o)}var ho=class{static updateFeeRate(t,e,r,n,i){let o=fe.checkMulDivCeil(e,new ye.default(n),yn,64),s=r===0?Y:fe.checkMulDivFloor(e,new ye.default(r),yn,64),u=e.mul(o).mul(s);if(i?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),u.eq(Y)||t.liquidity.eq(Y))return{refFee:s,clmm:t};let l=u.shln(64).div(t.liquidity);return i?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(l):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(l),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,r,n,i){let o=new _t(t.toString()),s=new _t(e.toString()),u=new _t(r.toString()),l=new _t(n.toString()),d,b;return e.lt(r)?(d=fe.toX64_Decimal(o).mul(l.sub(u)).div(u.mul(l)),b=new _t(0)):e.lt(n)?(d=fe.toX64_Decimal(o).mul(l.sub(s)).div(s.mul(l)),b=fe.fromX64_Decimal(o.mul(s.sub(u)))):(d=new _t(0),b=fe.fromX64_Decimal(o.mul(l.sub(u)))),i?{coinA:new ye.default(d.ceil().toString()),coinB:new ye.default(b.ceil().toString())}:{coinA:new ye.default(d.floor().toString()),coinB:new ye.default(b.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,r,n,i,o,s){let u=ke.sqrtPriceX64ToTickIndex(s),l=ke.tickIndexToSqrtPriceX64(t),d=ke.tickIndexToSqrtPriceX64(e),b;if(u<t){if(!n)throw new V("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");b=uo(l,d,r)}else if(u>e){if(n)throw new V("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");b=co(d,l,r)}else n?b=uo(s,d,r):b=co(s,l,r);let _=ho.getCoinAmountFromLiquidity(b,s,l,d,i),T=i?vt(_.coinA.toString()).mul(1+o).toString():vt(_.coinA.toString()).mul(1-o).toString(),x=i?vt(_.coinB.toString()).mul(1+o).toString():vt(_.coinB.toString()).mul(1-o).toString();return{coinAmountA:_.coinA,coinAmountB:_.coinB,tokenMaxA:i?new ye.default(_t.ceil(T).toString()):new ye.default(_t.floor(T).toString()),tokenMaxB:i?new ye.default(_t.ceil(x).toString()):new ye.default(_t.floor(x).toString()),liquidityAmount:b,fix_amount_a:n}}static estimateLiquidityFromcoinAmounts(t,e,r,n){if(e>r)throw new V("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let i=ke.sqrtPriceX64ToTickIndex(t),o=ke.tickIndexToSqrtPriceX64(e),s=ke.tickIndexToSqrtPriceX64(r);if(i<e)return uo(o,s,n.coinA);if(i>=r)return co(s,o,n.coinB);let u=uo(t,s,n.coinA),l=co(t,o,n.coinB);return ye.default.min(u,l)}static estCoinAmountsFromTotalAmount(t,e,r,n,i,o){let{ratioA:s,ratioB:u}=ho.calculateDepositRatioFixTokenA(t,e,r),l=vt(n).mul(s).div(i),d=vt(n).mul(u).div(o);return{amountA:l,amountB:d}}static calculateDepositRatioFixTokenA(t,e,r){let n=new ye.default(1e8),{coinAmountB:i}=ho.estLiquidityAndcoinAmountFromOneAmounts(t,e,n,!0,!0,0,r),o=ke.sqrtPriceX64ToPrice(r,0,0),s=vt(n.toString()).mul(o),u=s.add(i.toString()),l=s.div(u),d=vt(i.toString()).div(u);return{ratioA:l,ratioB:d}}};function Hg(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var Zg=0,Vl=1,Kg=2;function Rl(t,e){return t===e?Zg:t<e?Vl:Kg}function Jg(t,e){let r=0,n=t.length<=e.length?t.length:e.length,i=Rl(t.length,e.length);for(;r<n;){let o=Rl(t.charCodeAt(r),e.charCodeAt(r));if(r+=1,o!==0)return o}return i}function jl(t,e){return Jg(t,e)===Vl}function Fl(t,...e){let r=Array.isArray(e[e.length-1])?e.pop():[],i=[t,...e].filter(Boolean).join("::");return r&&r.length&&(i+=`<${r.join(", ")}>`),i}function ae(t){try{let e=t.replace(/\s/g,""),n=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){e=e.slice(0,e.indexOf("<"));let l={...ae(e),type_arguments:n.map(d=>ae(d).source_address)};return l.type_arguments=l.type_arguments.map(d=>Ie.isSuiCoin(d)?d:ae(d).source_address),l.source_address=Fl(l.full_address,l.type_arguments),l}let i=e.split("::"),s={full_address:e,address:e===Wl||e===t0?"0x2":(0,To.normalizeSuiObjectId)(i[0]),module:i[1],name:i[2],type_arguments:[],source_address:""};return s.full_address=`${s.address}::${s.module}::${s.name}`,s.source_address=Fl(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function sr(t){return ae(t).source_address}function Xg(t){return t.toLowerCase().startsWith("0x")?(0,To.normalizeSuiObjectId)(t):t}var Yg=(t,e=!0)=>{let r=t.split("::"),n=r.shift(),i=(0,To.normalizeSuiObjectId)(n);return e&&(i=Hg(i)),`${i}::${r.join("::")}`};function zl(t){for(let e in t){let r=typeof t[e];if(r==="object")zl(t[e]);else if(r==="string"){let n=t[e];n&&!n.includes("::")&&(t[e]=Xg(n))}}}var Qg="0x2::coin::Coin",e0=/^0x2::coin::Coin<(.+)>$/;var Wl="0x2::sui::SUI",t0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie=class{static getCoinTypeArg(t){let e=t.type.match(e0);return e?e[1]:null}static isSUI(t){let e=Ie.getCoinTypeArg(t);return e?Ie.getCoinSymbol(e)==="SUI":!1}static getCoinSymbol(t){return t.substring(t.lastIndexOf(":")+1)}static getBalance(t){return BigInt(t.fields.balance)}static totalBalance(t,e){let r=BigInt(0);return t.forEach(n=>{e===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(t){return t.fields.id.id}static getCoinTypeFromArg(t){return`${Qg}<${t}>`}static getFaucetCoins(t){let{events:e}=t,r=[];return e?.forEach(n=>{let{type:i}=n;if(ae(i).name==="InitEvent"){let o=n.parsedJson;r.push({transactionModule:n.transactionModule,suplyID:o.suplyID,decimals:o.decimals})}}),r}static getCoinAssets(t,e){let r=[];return e.forEach(n=>{sr(n.coinAddress)===sr(t)&&r.push(n)}),r}static isSuiCoin(t){return ae(t).full_address===Wl}static selectCoinObjectIdGreaterThanOrEqual(t,e,r=[]){let n=Ie.selectCoinAssetGreaterThanOrEqual(t,e,r),i=n.selectedCoins.map(u=>u.coinObjectId),o=n.remainingCoins,s=n.selectedCoins.map(u=>u.balance.toString());return{objectArray:i,remainCoins:o,amountArray:s}}static selectCoinAssetGreaterThanOrEqual(t,e,r=[]){let n=Ie.sortByBalance(t.filter(l=>!r.includes(l.coinObjectId))),i=Ie.calculateTotalBalance(n);if(i<e)return{selectedCoins:[],remainingCoins:n};if(i===e)return{selectedCoins:n,remainingCoins:[]};let o=BigInt(0),s=[],u=[...n];for(;o<i;){let l=e-o,d=u.findIndex(_=>_.balance>=l);if(d!==-1){s.push(u[d]),u.splice(d,1);break}let b=u.pop();b.balance>0&&(s.push(b),o+=b.balance)}return{selectedCoins:Ie.sortByBalance(s),remainingCoins:Ie.sortByBalance(u)}}static sortByBalance(t){return t.sort((e,r)=>e.balance<r.balance?-1:e.balance>r.balance?1:0)}static sortByBalanceDes(t){return t.sort((e,r)=>e.balance>r.balance?-1:e.balance<r.balance?0:1)}static calculateTotalBalance(t){return t.reduce((e,r)=>e+r.balance,BigInt(0))}};function i0(t,{numerator:e,denominator:r},n){return n?t.mul(r.add(e)).div(r):t.mul(r).div(r.add(e))}function vt(t){return $.isDecimal(t)?t:new $(t===void 0?0:t)}function Jn(t){return t.data}function Hl(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let{error:e}=t;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Zl(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function s0(t){if("reference"in t)return t.reference;let e=Jn(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Hl(t)}function bn(t){return"objectId"in t?t.objectId:s0(t)?.objectId??Zl(t)}function a0(t){return t.data!==void 0}function u0(t){return t.content!==void 0}function Kl(t){let e="data"in t?Jn(t):t;if(!(!e||!u0(e)||e.content.dataType!=="moveObject"))return e.content}function ba(t){return Kl(t)?.type}function c0(t){let e=a0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":ba(t):e?.type}function _a(t){return Jn(t)?.previousTransaction}function l0(t){return Jn(t)?.owner}function d0(t){let e=Jn(t)?.display;return e||{data:null,error:null}}function br(t){let e=Kl(t)?.fields;if(e)return"fields"in e?e.fields:e}function Vt(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function zr(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function f0(t,e,r){let n=ae(t).name,i=ae(e).name;return`${n}-${i}[${r}]`}function ha(t){let e=ba(t),r=ae(e),n=br(t);if(n==null)throw new V(`Pool id ${bn(t)} not exists.`,"InvalidPoolObject");let i=[];n.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:u}=s.fields,l=fe.fromX64(new Rt.default(u)),d=Math.floor(l.toNumber()*60*60*24);i.push({emissions_per_second:u,coinAddress:ae(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:d})});let o={poolAddress:bn(t),poolType:e,coinTypeA:r.type_arguments[0],coinTypeB:r.type_arguments[1],coinAmountA:n.coin_a,coinAmountB:n.coin_b,current_sqrt_price:n.current_sqrt_price,current_tick_index:zr(BigInt(n.current_tick_index.fields.bits)),fee_growth_global_a:n.fee_growth_global_a,fee_growth_global_b:n.fee_growth_global_b,fee_protocol_coin_a:n.fee_protocol_coin_a,fee_protocol_coin_b:n.fee_protocol_coin_b,fee_rate:n.fee_rate,is_pause:n.is_pause,liquidity:n.liquidity,position_manager:{positions_handle:n.position_manager.fields.positions.fields.id.id,size:n.position_manager.fields.positions.fields.size},rewarder_infos:i,rewarder_last_updated_time:n.rewarder_manager.fields.last_updated_time,tickSpacing:n.tick_spacing,ticks_handle:n.tick_manager.fields.ticks.fields.id.id,uri:n.url,index:Number(n.index),name:""};return o.name=f0(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function h0(t){let e=d0(t).data,r={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(r.creator=e.creator,r.description=e.description,r.image_url=e.image_url,r.link=e.link,r.name=e.name,r.project_url=e.project_url),r}function pa(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Position not exists. Get Position error:${t.error}`,"InvalidPositionObject");let e={creator:"",description:"",image_url:"",link:"",name:"",project_url:""},r={...e,pos_object_id:"",owner:"",type:"",coin_type_a:"",coin_type_b:"",liquidity:"",tick_lower_index:0,tick_upper_index:0,index:0,pool:"",reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"},n=br(t);if(n){let s=ba(t),u=l0(t);"nft"in n?(n=n.nft.fields,e.description=n.description,e.name=n.name,e.link=n.url):e=h0(t),r={...e,pos_object_id:n.id.id,owner:u.AddressOwner,type:s,coin_type_a:n.coin_type_a.fields.name,coin_type_b:n.coin_type_b.fields.name,liquidity:n.liquidity,tick_lower_index:zr(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:zr(BigInt(n.tick_upper_index.fields.bits)),index:n.index,pool:n.pool,reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"}}let i=Hl(t);i&&(r.pos_object_id=i.objectId,r.position_status="Deleted");let o=Zl(t);return o&&(r.pos_object_id=o,r.position_status="NotExists"),r}function Jl(t){let e={reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0"};t="fields"in t?t.fields:t,t.rewards.forEach((o,s)=>{let{amount_owned:u,growth_inside:l}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=u,e.reward_growth_inside_0=l):s===1?(e.reward_amount_owed_1=u,e.reward_growth_inside_1=l):s===2&&(e.reward_amount_owed_2=u,e.reward_growth_inside_2=l)});let r="fields"in t.tick_lower_index?t.tick_lower_index.fields.bits:t.tick_lower_index.bits,n="fields"in t.tick_upper_index?t.tick_upper_index.fields.bits:t.tick_upper_index.bits;return{liquidity:t.liquidity,tick_lower_index:zr(BigInt(r)),tick_upper_index:zr(BigInt(n)),...e,fee_growth_inside_a:t.fee_growth_inside_a,fee_owed_a:t.fee_owned_a,fee_growth_inside_b:t.fee_growth_inside_b,fee_owed_b:t.fee_owned_b,pos_object_id:t.position_id}}function ma(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let r=br(t).value.fields.value.fields;return{objectId:bn(t),index:zr(BigInt(r.index.fields.bits)),sqrtPrice:new Rt.default(r.sqrt_price),liquidityNet:new Rt.default(r.liquidity_net.fields.bits),liquidityGross:new Rt.default(r.liquidity_gross),feeGrowthOutsideA:new Rt.default(r.fee_growth_outside_a),feeGrowthOutsideB:new Rt.default(r.fee_growth_outside_b),rewardersGrowthOutside:r.rewards_growth_outside}}function p0(t){if(!t||!t.index||!t.sqrt_price||!t.liquidity_net||!t.liquidity_gross||!t.fee_growth_outside_a||!t.fee_growth_outside_b)throw new V("Invalid tick fields.","InvalidTickFields");let e=zr(BigInt(t.index.bits)),r=new Rt.default(t.sqrt_price),n=new Rt.default(t.liquidity_net.bits),i=new Rt.default(t.liquidity_gross),o=new Rt.default(t.fee_growth_outside_a),s=new Rt.default(t.fee_growth_outside_b),u=t.rewards_growth_outside||[];return{objectId:"",index:e,sqrtPrice:r,liquidityNet:n,liquidityGross:i,feeGrowthOutsideA:o,feeGrowthOutsideB:s,rewardersGrowthOutside:u}}function m0(t,e,r,n,i,o){let s=t.rewarder_infos,u=[];for(let l=0;l<s.length;l+=1){let d=o[l];e!==null&&(t.current_tick_index<n?d=o[l].sub(new qr.default(e.rewardersGrowthOutside[l])):d=e.rewardersGrowthOutside[l]);let b=new qr.default(0);r!==null&&(t.current_tick_index>=i?b=o[l].sub(new qr.default(r.rewardersGrowthOutside[l])):b=r.rewardersGrowthOutside[l]);let _=fe.subUnderflowU128(fe.subUnderflowU128(new qr.default(o[l]),new qr.default(d)),new qr.default(b));u.push(_)}return u}function wo(t){let e=Ie.isSuiCoin(t.coinTypeA),r=Ie.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:r}}function g0(t,e){return $.ceil(vt(t).div(1+e)).toString()}var X=class{static createCollectRewarderAndFeeParams(t,e,r,n,i,o){i===void 0&&(i=[...n]),o===void 0&&(o=[...n]);let s=sr(r.coinTypeA),u=sr(r.coinTypeB);if(r.collect_fee){let d=X.buildCoinForAmount(e,i,BigInt(0),s,!1);i=d.remainCoins;let b=X.buildCoinForAmount(e,o,BigInt(0),u,!1);o=b.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:r.pool_id,pos_id:r.pos_id,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB},e,d.targetCoin,b.targetCoin)}let l=[];return r.rewarder_coin_types.forEach(d=>{switch(sr(d)){case s:l.push(X.buildCoinForAmount(e,i,BigInt(0),d,!1).targetCoin);break;case u:l.push(X.buildCoinForAmount(e,o,BigInt(0),d,!1).targetCoin);break;default:l.push(X.buildCoinForAmount(e,n,BigInt(0),d,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(r,e,l),e}static async adjustTransactionForGas(t,e,r,n){n.setSender(t.senderAddress);let i=Ie.selectCoinAssetGreaterThanOrEqual(e,r).selectedCoins;if(i.length===0)throw new V("Insufficient balance","InsufficientBalance");let o=Ie.calculateTotalBalance(e);if(o-r>1e9)return{fixAmount:r};let s=await t.fullClient.calculationTxGas(n);if(Ie.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),i.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(s)+BigInt(500);if(o-r<l){if(r-=l,r<0)throw new V("gas Insufficient balance","InsufficientBalance");let d=new Lr.TransactionBlock;return{fixAmount:r,newTx:d}}}return{fixAmount:r}}static async buildAddLiquidityFixTokenForGas(t,e,r,n){let i=await X.buildAddLiquidityFixToken(t,e,r),{isAdjustCoinA:o}=wo(r),s=o?r.amount_a:r.amount_b,u=await X.adjustTransactionForGas(t,Ie.getCoinAssets(o?r.coinTypeA:r.coinTypeB,e),BigInt(s),i),{fixAmount:l}=u,{newTx:d}=u;if(d!==void 0){let b,_;if(o)r.amount_a=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,l.toString(),r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);else return r.amount_b=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,l.toString(),r.slippage,r.coinTypeB,e,!1),r=X.fixAddLiquidityFixTokenParams(r,n.slippage,n.curSqrtPrice),i=await X.buildAddLiquidityFixTokenArgs(d,t,e,r,b,_),i}return i}static async buildAddLiquidityFixToken(t,e,r){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=new Lr.TransactionBlock,i=X.buildAddLiquidityFixTokenCoinInput(n,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),o=X.buildAddLiquidityFixTokenCoinInput(n,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);return n=X.buildAddLiquidityFixTokenArgs(n,t,e,r,i,o),n}static buildAddLiquidityFixTokenCoinInput(t,e,r,n,i,o,s=!0){return e?X.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(g0(r,n)),amountFirst:BigInt(r)},i,s):X.buildCoinForAmount(t,o,BigInt(r),i,s)}static fixAddLiquidityFixTokenParams(t,e,r){let n=t.fix_amount_a?t.amount_a:t.amount_b,i=ho.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new Hn.default(n),t.fix_amount_a,!0,e,r);return t.amount_a=t.fix_amount_a?t.amount_a:i.tokenMaxA.toNumber(),t.amount_b=t.fix_amount_a?i.tokenMaxB.toNumber():t.amount_b,t}static buildAddLiquidityFixTokenArgs(t,e,r,n,i,o){let s=[n.coinTypeA,n.coinTypeB],u=n.is_open?"open_position_with_liquidity_by_fix_coin":"add_liquidity_by_fix_coin",{clmm_pool:l,integrate:d}=e.sdkOptions;n.is_open||(t=X.createCollectRewarderAndFeeParams(e,t,n,r,i.remainCoins,o.remainCoins));let b=be(l),_=n.is_open?[t.object(b.global_config_id),t.object(n.pool_id),t.pure(Vt(BigInt(n.tick_lower)).toString()),t.pure(Vt(BigInt(n.tick_upper)).toString()),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)]:[t.object(b.global_config_id),t.object(n.pool_id),t.object(n.pos_id),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)];return t.moveCall({target:`${d.published_at}::${Gr}::${u}`,typeArguments:s,arguments:_}),t}static async buildSwapTransactionForGas(t,e,r,n){let i=X.buildSwapTransaction(t,e,r);i.setSender(t.senderAddress);let o=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:s,newTx:u}=o;if(u!==void 0){u.setSender(t.senderAddress),e.by_amount_in?e.amount=s.toString():e.amount_limit=s.toString(),e=await X.fixSwapParams(t,e,n);let l=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),d=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);i=X.buildSwapTransactionArgs(u,e,t.sdkOptions,l,d)}return i}static buildSwapTransaction(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return n=X.buildSwapTransactionArgs(n,e,t.sdkOptions,i,o),n}static buildSwapTransactionArgs(t,e,r,n,i){let{clmm_pool:o,integrate:s}=r,u=yr.getDefaultSqrtPriceLimit(e.a2b),l=[e.coinTypeA,e.coinTypeB],{global_config_id:d}=be(o);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=e.swap_partner!==void 0,_=b?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",T=b?[t.pure(d),t.pure(e.pool_id),t.pure(e.swap_partner),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)]:[t.pure(d),t.pure(e.pool_id),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)];return t.moveCall({target:`${s.published_at}::${Gr}::${_}`,typeArguments:l,arguments:T}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,r,n){let{tx:i,coinABs:o}=X.buildSwapTransactionWithoutTransferCoins(t,e,r);i.setSender(t.senderAddress);let s=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:u,newTx:l}=s;if(l!==void 0){l.setSender(t.senderAddress),e.by_amount_in?e.amount=u.toString():e.amount_limit=u.toString(),e=await X.fixSwapParams(t,e,n);let d=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),b=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),_=X.buildSwapTransactionWithoutTransferCoinArgs(t,l,e,t.sdkOptions,d,b);i=_.tx,o=_.txRes}return{tx:i,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=X.buildSwapTransactionWithoutTransferCoinArgs(t,n,e,t.sdkOptions,i,o);return{tx:s.tx,coinABs:s.txRes}}static buildSwapTransactionWithoutTransferCoinArgs(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=n,l=yr.getDefaultSqrtPriceLimit(r.a2b),{global_config_id:d}=be(s);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=r.swap_partner!==void 0,_=b?"swap_with_partner":"swap",T=b?da:Wn,x=b?[e.pure(d),e.pure(r.pool_id),e.pure(r.swap_partner),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)]:[e.pure(d),e.pure(r.pool_id),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)],A=[r.coinTypeA,r.coinTypeB],I=e.moveCall({target:`${u.published_at}::${T}::${_}`,typeArguments:A,arguments:x});if(r.by_amount_in){let C=r.a2b?r.coinTypeB:r.coinTypeA,E=r.a2b?I[1]:I[0],P=Number(r.amount_limit);this.checkCoinThreshold(t,r.by_amount_in,e,E,P,C)}return{tx:e,txRes:I}}static async fixSwapParams(t,e,r){let{currentPool:n}=r;try{let i=await t.Swap.preswap({decimalsA:r.decimalsA,decimalsB:r.decimalsB,a2b:e.a2b,byAmountIn:e.by_amount_in,amount:e.amount,pool:n,currentSqrtPrice:n.current_sqrt_price,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB}),o=r.byAmountIn?i.estimatedAmountOut:i.estimatedAmountIn,s=i0(o,r.slippage,!r.byAmountIn);e.amount_limit=s.toString()}catch(i){console.log("fixSwapParams",i)}return e}static async syncBuildCoinInputForAmount(t,e,r,n,i=!0){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let o=await t.getOwnerCoinAssets(t.senderAddress,n);return X.buildCoinForAmount(e,o,r,n,i).targetCoin}static buildCoinForAmount(t,e,r,n,i=!0,o=!1){let s=Ie.getCoinAssets(n,e);if(r===BigInt(0)&&s.length===0)return X.buildZeroValueCoin(e,t,n,i);let u=Ie.calculateTotalBalance(s);if(u<r)throw new V(`The amount(${u}) is Insufficient balance for ${n} , expect ${r} `,"InsufficientBalance");return X.buildCoin(t,e,s,r,n,i,o)}static buildCoin(t,e,r,n,i,o=!0,s=!1){if(Ie.isSuiCoin(i)){if(o){let P=t.splitCoins(t.gas,[t.pure(n.toString())]);return{targetCoin:t.makeMoveVec({objects:[P]}),remainCoins:e,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(n===0n&&r.length>1){let P=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.object(P.objectArray[0]),remainCoins:P.remainCoins,tragetCoinAmount:P.amountArray[0],isMintZeroCoin:!1}}let C=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.splitCoins(t.gas,[t.pure(n.toString())]),remainCoins:C.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let u=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n),l=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),d=u.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:d.map(C=>t.object(C))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),isMintZeroCoin:!1};let[b,..._]=d,T=t.object(b),x=T,A=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),I;return _.length>0&&t.mergeCoins(T,_.map(C=>t.object(C))),s&&Number(l)>Number(n)&&(x=t.splitCoins(T,[t.pure(n.toString())]),A=n.toString(),I=T),{targetCoin:x,remainCoins:u.remainCoins,originalSplitedCoin:I,tragetCoinAmount:A,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,r,n=!0){let i=X.callMintZeroValueCoin(e,r),o;return n?o=e.makeMoveVec({objects:[i]}):o=i,{targetCoin:o,remainCoins:t,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(t,e,r,n,i=!0){let o=Ie.getCoinAssets(n,e);if(r.amountFirst===BigInt(0))return o.length>0?X.buildCoin(t,[...e],[...o],r.amountFirst,n,i):X.buildZeroValueCoin(e,t,n,i);let s=Ie.calculateTotalBalance(o);if(s>=r.amountFirst)return X.buildCoin(t,[...e],[...o],r.amountFirst,n,i);if(s<r.amountSecond)throw new V(`The amount(${s}) is Insufficient balance for ${n} , expect ${r.amountSecond} `,"InsufficientBalance");return X.buildCoin(t,[...e],[...o],r.amountSecond,n,i)}static async buildRouterSwapTransaction(t,e,r,n,i){let o=new Lr.TransactionBlock;return e.paths.length>1&&(e.partner=""),o=await this.buildRouterBasePathTx(t,e,r,n,o,i),o}static async buildRouterBasePathTx(t,e,r,n,i,o){let s=e.paths.filter(D=>D&&D.poolAddress),u=Number(s.reduce((D,L)=>D.add(L.amountIn),Y).toString()),l=Number(s.reduce((D,L)=>D.add(L.amountOut),Y).toString()),d=Math.round(r?Number(l.toString())*(1-e.priceSlippagePoint):Number(u.toString())*(1+e.priceSlippagePoint)),b=e.paths[0].coinType[0],_=e.paths[0].coinType[e.paths[0].coinType.length-1],T=X.buildCoinForAmount(i,n,BigInt(r?u:d),b,!1,!0),x=T.originalSplitedCoin!==void 0,A=X.buildCoinForAmount(i,n,0n,_,!1),I=await this.buildRouterBasePathReturnCoins(t,e,r,T,A,i),C=[],{toCoin:E,fromCoin:P}=I;if(i=I.tx,A.isMintZeroCoin?C.push({coinType:_,coin:E}):A.originalSplitedCoin!==void 0?i.mergeCoins(A.originalSplitedCoin,[E]):i.mergeCoins(A.targetCoin,[E]),x){let D=T?.originalSplitedCoin;i.mergeCoins(D,[P])}else C.push({coinType:b,coin:P});for(let D=0;D<C.length;D++)this.buildTransferCoin(t,i,C[D].coin,C[D].coinType,o);return i}static async buildRouterBasePathReturnCoins(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=t.sdkOptions,l=be(s).global_config_id,d=e.paths.filter(D=>D&&D.poolAddress),b=Number(d.reduce((D,L)=>D.add(L.amountIn),Y).toString()),_=Number(d.reduce((D,L)=>D.add(L.amountOut),Y).toString()),T=Math.round(r?Number(_.toString())*(1-e.priceSlippagePoint):Number(b.toString())*(1+e.priceSlippagePoint)),x=e.paths[0].coinType[0],A=e.paths[0].coinType[e.paths[0].coinType.length-1],I=n.targetCoin,C;i.isMintZeroCoin||i.originalSplitedCoin!==void 0?C=i.targetCoin:C=X.callMintZeroValueCoin(o,A);let E=e.partner==="",P=E?Wn:da;for(let D of d)if(D.poolAddress.length===1){let L=D.a2b[0],H={amount:Number(D.amountIn.toString()),amountLimit:T,poolCoinA:D.a2b[0]?x:A,poolCoinB:D.a2b[0]?A:x},W=E?"swap":"swap_with_partner",K=L?I:C,F=L?C:I,U=r?D.amountIn.toString():D.amountOut.toString(),N=yr.getDefaultSqrtPriceLimit(L).toString(),j=E?[o.object(l),o.object(D.poolAddress[0]),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.pure(e.partner),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)],S=[H.poolCoinA,H.poolCoinB],k=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${P}::${W}`,typeArguments:S,arguments:j});I=L?k[0]:k[1],C=L?k[1]:k[0]}else{let L=r?D.amountIn:D.rawAmountLimit[0],H=r?0:D.amountOut,W="";D.a2b[0]?D.a2b[1]?W="swap_ab_bc":W="swap_ab_cb":D.a2b[1]?W="swap_ba_bc":W="swap_ba_cb",E||(W=`${W}_with_partner`);let K=yr.getDefaultSqrtPriceLimit(D.a2b[0]),F=yr.getDefaultSqrtPriceLimit(D.a2b[1]),U=E?[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),o.pure(e.partner),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)],N=[D.coinType[0],D.coinType[1],D.coinType[2]],j=o.moveCall({target:`${u.published_at}::${P}::${W}`,typeArguments:N,arguments:U});I=j[0],C=j[1]}return this.checkCoinThreshold(t,r,o,C,T,A),{fromCoin:I,toCoin:C,tx:o}}static async buildAggregatorSwapReturnCoins(t,e,r,n,i,o,s,u){if(u==null){if(t.senderAddress.length===0)throw Error("recipient and this config sdk senderAddress all not set");u=t.senderAddress}e.splitPaths.length>1&&(i="");let l,d,b=e.splitPaths.some(_=>_.basePaths.some(T=>T.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!b){let _=[];for(let A of e.splitPaths){let I=[],C=[],E=[],P=[];for(let L=0;L<A.basePaths.length;L+=1){let H=A.basePaths[L];I.push(H.direction),C.push(H.poolAddress),E.push(new Hn.default(H.inputAmount.toString())),L===0?P.push(H.fromCoin,H.toCoin):P.push(H.toCoin)}let D={amountIn:new Hn.default(A.inputAmount.toString()),amountOut:new Hn.default(A.outputAmount.toString()),poolAddress:C,a2b:I,rawAmountLimit:E,isExceed:!1,coinType:P};_.push(D)}let T={paths:_,partner:i,priceSlippagePoint:o},x=await this.buildRouterBasePathReturnCoins(t,T,e.byAmountIn,r,n,s);l=x.fromCoin,d=x.toCoin,s=x.tx}else{let _=Math.round(e.outputAmount*(1-o));l=r.targetCoin,n.isMintZeroCoin||n.originalSplitedCoin!==void 0?d=n.targetCoin:d=X.callMintZeroValueCoin(s,e.toCoin);let T=!1,x;if(b){let[A,I]=ql.createAccountCap(u,t.sdkOptions,s);s=I,x=A,T=!0}for(let A=0;A<e.splitPaths.length;A+=1){let I=e.splitPaths[A],C;for(let E=0;E<I.basePaths.length;E+=1){let P=I.basePaths[E];if(P.label==="Deepbook")if(E===0)if(I.basePaths.length===1){let D=this.buildDeepbookBasePathTx(t,P,s,x,l,d,!1);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildDeepbookBasePathTx(t,P,s,x,l,C,!1);l=D.from,C=D.to}else{let D=this.buildDeepbookBasePathTx(t,P,s,x,C,d,!0);C=D.from,d=D.to}if(P.label==="Cetus")if(E===0)if(I.basePaths.length===1){let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,d,!1,i);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,C,!1,i);l=D.from,C=D.to}else{let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,C,d,!0,i);C=D.from,d=D.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::send_coin`,typeArguments:[P.fromCoin],arguments:[C,s.pure(u)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,d,_,e.toCoin),T&&(s=ql.deleteAccountCapByObject(x,t.sdkOptions,s))}return{fromCoin:l,toCoin:d,tx:s}}static async buildAggregatorSwapTransaction(t,e,r,n,i,o){let s=new Lr.TransactionBlock,u=e.byAmountIn?Math.round(e.outputAmount*(1-i)):Math.round(e.inputAmount*(1+i)),l=X.buildCoinForAmount(s,r,e.byAmountIn?BigInt(e.inputAmount):BigInt(u),e.fromCoin,!1,!0),d=l.originalSplitedCoin!=null,b=X.buildCoinForAmount(s,r,0n,e.toCoin,!1),_=await this.buildAggregatorSwapReturnCoins(t,e,l,b,n,i,s,o),{fromCoin:T,toCoin:x}=_;s=_.tx;let A=[];if(b.isMintZeroCoin?A.push({coinType:e.toCoin,coin:x}):b.originalSplitedCoin!=null?s.mergeCoins(b.originalSplitedCoin,[x]):s.mergeCoins(b.targetCoin,[x]),d){let I=l.originalSplitedCoin;s.mergeCoins(I,[T])}else A.push({coinType:e.fromCoin,coin:T});for(let I=0;I<A.length;I++)this.buildTransferCoin(t,s,A[I].coin,A[I].coinType,o);return s}static checkCoinThreshold(t,e,r,n,i,o){e&&r.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Wn}::check_coin_threshold`,typeArguments:[o],arguments:[n,r.pure(i)]})}static buildDeepbookBasePathTx(t,e,r,n,i,o,s){let u=e.direction?i:o,l=e.direction?o:i,d=[r.object(e.poolAddress),n,r.pure(e.inputAmount),r.pure(0),r.pure(e.direction),u,l,r.pure(s),r.object(Ce)],b=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],_=r.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:b,arguments:d});return i=e.direction?_[0]:_[1],o=e.direction?_[1]:_[0],{from:i,to:o,tx:r}}static buildClmmBasePathTx(t,e,r,n,i,o,s,u){let{clmm_pool:l,integrate:d}=t.sdkOptions,b=be(l).global_config_id,_=e.direction?i:o,T=e.direction?o:i,x=u==="",A=x?Wn:da,I=x?"swap":"swap_with_partner",C=n?e.inputAmount.toString():e.outputAmount.toString(),E=yr.getDefaultSqrtPriceLimit(e.direction),P=x?[r.object(b),r.object(e.poolAddress),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)]:[r.object(b),r.object(e.poolAddress),r.pure(u),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)],D=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],L=r.moveCall({target:`${d.published_at}::${A}::${I}`,typeArguments:D,arguments:P});return _=L[0],T=L[1],i=e.direction?_:T,o=e.direction?T:_,{from:i,to:o,tx:r}}static buildCoinTypePair(t,e){let r=[];if(t.length===2){let n=[];n.push(t[0],t[1]),r.push(n)}else{let n=[];n.push(t[0],t[t.length-1]),r.push(n);for(let i=1;i<t.length-1;i+=1){if(e[i-1]===0)continue;let o=[];o.push(t[0],t[i],t[t.length-1]),r.push(o)}}return r}static buildTransferCoinToSender(t,e,r,n){e.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::transfer_coin_to_sender`,typeArguments:[n],arguments:[r]})}static buildTransferCoin(t,e,r,n,i){i!=null?e.transferObjects([r],e.pure(i)):X.buildTransferCoinToSender(t,e,r,n)}},Pe=X;kg(Pe,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function kt(t){return!(!t.startsWith("0x")||t.length!==66)}var gn=new bt.default(1e9),ql=class{static createAccountCap(t,e,r,n=!1){if(t.length===0)throw Error("this config sdk senderAddress is empty");let{deepbook:i}=e,[o]=r.moveCall({target:`${i.published_at}::${Pg}::create_account`,typeArguments:[],arguments:[]});return n&&r.transferObjects([o],r.pure(t)),[o,r]}static deleteAccountCap(t,e,r){let{deepbook:n}=e,i=[r.pure(t)];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static deleteAccountCapByObject(t,e,r){let{deepbook:n}=e,i=[t];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static async getAccountCap(t){let e=await t.fullClient.getOwnedObjectsByPage(t.senderAddress,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{MoveModule:{package:t.sdkOptions.deepbook.package_id,module:fa}}});return e.data.length===0?"":e.data[0].data.objectId}static async getPools(t){let e=t.sdkOptions.deepbook.package_id,r=[];try{(await t.fullClient.queryEventsByPage({MoveEventType:`${e}::clob_v2::PoolCreated`})).data.forEach(i=>{let o=i.parsedJson;o&&r.push({poolID:o.pool_id,tickSize:Number(o.tick_size),lotSize:Number(o.lot_size),takerFeeRate:Number(o.taker_fee_rate),makerRebateRate:Number(o.maker_rebate_rate),baseAsset:o.base_asset.name,quoteAsset:o.quote_asset.name})})}catch(n){console.log("getPoolImmutables",n)}return r}static async getPoolAsks(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>ae(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async getPoolBids(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>ae(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async preSwap(t,e,r,n){let i=!1,o=Y,s=new bt.default(n),u=Y,l=new bt.default(n);if(r){let d=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0),d=d.sort((b,_)=>_.price-b.price);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].quantity),T=new bt.default(d[b].price),x=_.mul(new bt.default(T)).mul(new bt.default(e.takerFeeRate)).div(gn).div(gn);if(s.gt(_))s=s.sub(_),o=o.add(_.mul(T).div(gn).sub(x)),u=u.add(x);else{let A=s.mul(new bt.default(d[b].price)).div(gn),I=A.mul(new bt.default(e.takerFeeRate)).div(gn);o=o.add(A.sub(I)),s=s.sub(s),u=u.add(I)}if(s.eq(Y))break}}else{let d=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].price).mul(new bt.default(d[b].quantity)).div(new bt.default(1e9)),T=_.mul(new bt.default(e.takerFeeRate)).div(gn),x=_.add(T);if(s.gt(_))o=o.add(new bt.default(d[b].quantity)),s=s.sub(x),u=u.add(T);else{let A=new bt.default(d[b].quantity).div(new bt.default(e.lotSize)),I=x.div(A),C=s.div(I);o=o.add(C.muln(e.lotSize)),s=s.sub(C.mul(I)),u=u.add(C.div(A).mul(T))}if(s.eq(Y))break}}return{poolAddress:e.poolID,estimatedAmountIn:l.sub(s).toNumber(),estimatedAmountOut:o.toNumber(),estimatedFeeAmount:u,isExceed:i,amount:Number(n),aToB:r,byAmountIn:!0}}static async simulateSwap(t,e,r,n,i,o){let{deepbook_endpoint_v2:s}=t.sdkOptions,u=new po.TransactionBlock,l=await this.getAccountCap(t),d;if(l===""){let H=this.createAccountCap(t.senderAddress,t.sdkOptions,u),W=H[0];u=H[1],d=W}else d=u.pure(l);let b=await t.getOwnerCoinAssets(t.senderAddress),T=Pe.buildCoinForAmount(u,b,BigInt(o),r,!1)?.targetCoin,A=Pe.buildCoinForAmount(u,b,BigInt(o),n,!1)?.targetCoin,I=[r,n],C=[u.pure(e),d,u.pure(o),u.pure(0),u.pure(i),T,A,u.pure(Ce)];u.moveCall({target:`${s.published_at}::${Dg}::swap`,arguments:C,typeArguments:I});let{simulationAccount:E}=t.sdkOptions,D=(await t.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:E.address})).events?.filter(H=>ae(H.type).name==="DeepbookSwapEvent");if(D.length===0)return null;let L=D[0].parsedJson;return{poolAddress:L.pool,estimatedAmountIn:L.amount_in,estimatedAmountOut:L.amount_out,aToB:L.atob}}},b0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPositionList(t,e="all"){let r={data:[],hasNextPage:!0},n=await this._sdk.fullClient.getDynamicFieldsByPage(t,e);r.hasNextPage=n.hasNextPage,r.nextCursor=n.nextCursor;let i=n.data.map(s=>{if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getPositionList get position objects error: ${s.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");return s.name.value}),o=await this._sdk.Position.getSipmlePositionList(i);return r.data=o,r}async getPoolImmutables(t=[],e=0,r=100,n=!1){let{package_id:i}=this._sdk.sdkOptions.clmm_pool,o=`${i}_getInitPoolEvent`,s=this.getCache(o,n),u=[],l=[];if(s!==void 0&&u.push(...s),u.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${i}::factory::CreatePoolEvent`})).data.forEach(_=>{let T=_.parsedJson;T&&u.push({poolAddress:T.pool_id,tickSpacing:T.tick_spacing,coinTypeA:ae(T.coin_type_a).full_address,coinTypeB:ae(T.coin_type_b).full_address})}),this.updateCache(o,u,Oe)}catch(b){console.log("getPoolImmutables",b)}let d=t.length>0;for(let b=0;b<u.length;b+=1){let _=u[b];d&&!t.includes(_.poolAddress)||!d&&(b<e||b>=e+r)||l.push(_)}return l}async getPools(t=[],e=0,r=100){let n=[],i=[];t.length>0?i=[...t]:(await this.getPoolImmutables([],e,r,!1)).forEach(u=>i.push(u.poolAddress));let o=await this._sdk.fullClient.batchGetObjects(i,{showContent:!0,showType:!0});for(let s of o){if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let u=ha(s);n.push(u);let l=`${u.poolAddress}_getPoolObject`;this.updateCache(l,u,Oe)}return n}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:r}=this._sdk.sdkOptions.clmm_pool,n=[],i={data:[],hasNextPage:!1},o=t==="all",s=`${r}_getPoolImmutables`;if(o){let u=this.getCache(s,e);u&&n.push(...u)}if(n.length===0)try{let u=`${r}::factory::CreatePoolEvent`,l=await this._sdk.fullClient.queryEventsByPage({MoveEventType:u},t);i.hasNextPage=l.hasNextPage,i.nextCursor=l.nextCursor,l.data.forEach(d=>{let b=d.parsedJson;if(b){let _={poolAddress:b.pool_id,tickSpacing:b.tick_spacing,coinTypeA:ae(b.coin_type_a).full_address,coinTypeB:ae(b.coin_type_b).full_address};n.push(_)}})}catch(u){console.log("getPoolImmutables",u)}return i.data=n,o&&this.updateCache(`${r}_getPoolImmutables`,n,Oe),i}async getPoolsWithPage(t=[]){let e=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutablesWithPage()).data.forEach(o=>r.push(o.poolAddress));let n=await this._sdk.fullClient.batchGetObjects(r,{showContent:!0,showType:!0});for(let i of n){if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPoolWithPages error code: ${i.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=ha(i);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,Oe)}return e}async getPool(t,e=!0){let r=`${t}_getPoolObject`,n=this.getCache(r,e);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPool error code: ${i.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=ha(i);return this.updateCache(r,o),o}async creatPoolsTransactionPayload(t){for(let r of t)if(jl((0,zn.normalizeSuiAddress)(r.coinTypeA),(0,zn.normalizeSuiAddress)(r.coinTypeB))){let n=r.coinTypeB;r.coinTypeB=r.coinTypeA,r.coinTypeA=n}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(jl((0,zn.normalizeSuiAddress)(t.coinTypeA),(0,zn.normalizeSuiAddress)(t.coinTypeB))){let e=t.coinTypeB;t.coinTypeB=t.coinTypeA,t.coinTypeA=e}return"fix_amount_a"in t?await this.creatPoolAndAddLiquidity(t):await this.creatPool([t])}async getClmmConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.clmm_pool,r=`${e}_getInitEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=(await this._sdk.fullClient.queryEventsByPage({Transaction:o})).data,u={pools_id:"",global_config_id:"",global_vault_id:"",admin_cap_id:""};return s.length>0&&(s.forEach(l=>{let d=l.parsedJson;if(l.type)switch(ae(l.type).full_address){case`${e}::config::InitConfigEvent`:u.global_config_id=d.global_config_id,u.admin_cap_id=d.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:u.pools_id=d.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:u.global_vault_id=d.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:u.partners_id=d.partners_id;break;default:break}}),this.updateCache(r,u,Oe)),u}async getSuiTransactionResponse(t,e=!1){let r=`${t}_getSuiTransactionResponse`,n=this.getCache(r,e);if(n!==void 0)return n;let i;try{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,i,Oe),i}async creatPool(t){let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id;return t.forEach(u=>{let l=[e.object(o),e.object(s),e.pure(u.tick_spacing.toString()),e.pure(u.initialize_sqrt_price),e.pure(u.uri),e.object(Ce)];e.moveCall({target:`${r.published_at}::${fo}::create_pool`,typeArguments:[u.coinTypeA,u.coinTypeB],arguments:l})}),e}async creatPoolAndAddLiquidity(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id,u=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),l=Pe.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,u,!1),d=Pe.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,u,!1),b=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),l.targetCoin,d.targetCoin,e.pure(Vt(BigInt(t.tick_lower)).toString()),e.pure(Vt(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(Ce)];return e.moveCall({target:`${r.published_at}::${Gr}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:b}),e}async fetchTicks(t){let e=[],r=[];for(;;){let i=await this.getTicks({pool_id:t.pool_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,start:r,limit:512});if(e=[...e,...i],i.length<512)break;r=[i[i.length-1].index]}return e}async getTicks(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[t.coinTypeA,t.coinTypeB],o=new wn.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Vr}::fetch_ticks`,arguments:s,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let u=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address});if(u.error!=null)throw new V(`getTicks error code: ${u.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return u.events?.forEach(l=>{ae(l.type).name==="FetchTicksResultEvent"&&l.parsedJson.ticks.forEach(d=>{n.push(p0(d))})}),n}async fetchPositionRewardList(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[],o=512;for(;;){let s=[t.coinTypeA,t.coinTypeB],u=new wn.TransactionBlock,l=[u.object(t.pool_id),u.pure(i,"u64"),u.pure(o.toString(),"u64")];if(u.moveCall({target:`${e.published_at}::${Vr}::fetch_positions`,arguments:l,typeArguments:s}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let d=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:r.address});if(d.error!=null)throw new V(`fetch position reward error code: ${d.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let b=[];if(d?.events?.forEach(_=>{ae(_.type).name==="FetchPositionsEvent"&&_.parsedJson.positions.forEach(T=>{let x=Jl(T);b.push(x)})}),n.push(...b),b.length<o)break;i=[b[b.length-1].pos_object_id]}return n}async fetchTicksByRpc(t){let e=[],r=null,n=512;for(;;){let i=[],o=await this.sdk.fullClient.getDynamicFields({parentId:t,cursor:r,limit:n});if(r=o.nextCursor,o.data.forEach(s=>{ae(s.objectType).module==="skip_list"&&i.push(s.objectId)}),e=[...e,...await this.getTicksByRpc(i)],r===null||o.data.length<n)break}return e}async getTicksByRpc(t){let e=[],r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0,showType:!0});for(let n of r){if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${n.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let i=ma(n);i!=null&&e.push(i)}return e}async getTickDataByIndex(t,e){let r={type:"u64",value:Vt(BigInt($g(e).toString())).toString()},n=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:r});if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`get tick by index: ${e} error: ${n.error}`,"InvalidTickIndex");return ma(n)}async getTickDataByObjectId(t){let e=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0}});if(e.error!=null||e.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return ma(e)}async getPartnerRefFeeAmount(t){let e=await this._sdk.fullClient.batchGetObjects([t],{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0});if(e[0].error!=null||e[0].data?.content?.dataType!=="moveObject")throw new V(`get partner by object id: ${t} error: ${e[0].error}`,"NotFoundPartnerObject");let r=e[0].data.content.fields.balances,n=await this._sdk.fullClient.getDynamicFieldsByPage(r.fields.id.id),i=[];n.data.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`when getPartnerRefFeeAmount get partner object error: ${u.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");i.push(u.objectId)});let o=[];return(await this._sdk.fullClient.batchGetObjects(i,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`get coin by object id: ${u.data.objectId} error: ${u.error}`,"InvalidParnterRefFeeFields");let l={coinAddress:u.data.content.fields.name,coinObjectId:u.data.objectId,balance:BigInt(u.data.content.fields.value)};o.push(l)}),o}async claimPartnerRefFeePayload(t,e,r){let n=new wn.TransactionBlock,{clmm_pool:i}=this.sdk.sdkOptions,{global_config_id:o}=be(i),s=[r],u=[n.object(o),n.object(t),n.object(e)];return n.moveCall({target:`${i.published_at}::${Mg}::claim_ref_fee`,arguments:u,typeArguments:s}),n}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},_0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildPositionType(){return`${this._sdk.sdkOptions.clmm_pool.package_id}::position::Position`}async getPositionList(t,e=[]){let r=[],n=await this._sdk.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.clmm_pool.package_id}}),i=e.length>0;for(let o of n.data)if(ae(o.data.type).full_address===this.buildPositionType()){let u=pa(o),l=`${u.pos_object_id}_getPositionList`;this.updateCache(l,u,Oe),i?e.includes(u.pool)&&r.push(u):r.push(u)}return r}async getPosition(t,e,r=!0){let n=await this.getSimplePosition(e);return r&&(n=await this.updatePositionRewarders(t,n)),n}async getPositionById(t,e=!0){let r=await this.getSimplePosition(t);if(e){let n=await this._sdk.Pool.getPool(r.pool,!1);return await this.updatePositionRewarders(n.position_manager.positions_handle,r)}return r}async getSimplePosition(t){let e=`${t}_getPositionList`,r=this.getSimplePositionByCache(t);if(r===void 0){let n=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0,showType:!0,showDisplay:!0,showOwner:!0}});r=pa(n),this.updateCache(e,r,Oe)}return r}getSimplePositionByCache(t){let e=`${t}_getPositionList`;return this.getCache(e)}async getSipmlePositionList(t){let e=[],r=[];return t.forEach(n=>{let i=this.getSimplePositionByCache(n);i?e.push(i):r.push(n)}),r.length>0&&(await this._sdk.fullClient.batchGetObjects(r,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(i=>{let o=pa(i);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,Oe)}),e}async updatePositionRewarders(t,e){let r=await this.getPositionRewarders(t,e.pos_object_id);return{...e,...r}}async getPositionRewarders(t,e){try{let r=await this._sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=br(r.data).value.fields.value;return Jl(i)}catch(r){console.log(r);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new Ur.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(l=>ae(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new ga.default(d.fee_owned_a),feeOwedB:new ga.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async createAddLiquidityFixTokenPayload(t,e){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t=t,t.fix_amount_a&&n||!t.fix_amount_a&&i)return await Pe.buildAddLiquidityFixTokenForGas(this._sdk,r,t,e)}return Pe.buildAddLiquidityFixToken(this._sdk,r,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:r}=this._sdk.sdkOptions;if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let n=Vt(BigInt(t.tick_lower)).toString(),i=Vt(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new Ur.TransactionBlock,u=!(0,Xl.isValidSuiObjectId)(t.pos_id),l=BigInt(t.max_amount_a),d=BigInt(t.max_amount_b),b=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),_=Pe.buildCoinForAmount(s,b,l,t.coinTypeA,!1),T=Pe.buildCoinForAmount(s,b,d,t.coinTypeB,!1);return u?s.moveCall({target:`${e.published_at}::${Gr}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.pure(n),s.pure(i),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]}):(s=Pe.createCollectRewarderAndFeeParams(this._sdk,s,t,b,_.remainCoins,T.remainCoins),s.moveCall({target:`${e.published_at}::${Gr}::add_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.object(t.pos_id),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]})),s}async removeLiquidityTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n="remove_liquidity",i=new Ur.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);i=Pe.createCollectRewarderAndFeeParams(this._sdk,i,t,s);let u=[i.object(be(e).global_config_id),i.object(t.pool_id),i.object(t.pos_id),i.pure(t.delta_liquidity),i.pure(t.min_amount_a),i.pure(t.min_amount_b),i.object(Ce)];return i.moveCall({target:`${r.published_at}::${fo}::${n}`,typeArguments:o,arguments:u}),i}async closePositionTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return n=Pe.createCollectRewarderAndFeeParams(this._sdk,n,t,o),n.moveCall({target:`${r.published_at}::${fo}::close_position`,typeArguments:i,arguments:[n.object(be(e).global_config_id),n.object(t.pool_id),n.object(t.pos_id),n.pure(t.min_amount_a),n.pure(t.min_amount_b),n.object(Ce)]}),n}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=Vt(BigInt(t.tick_lower)).toString(),s=Vt(BigInt(t.tick_upper)).toString(),u=[n.pure(be(e).global_config_id),n.pure(t.pool_id),n.pure(o),n.pure(s)];return n.moveCall({target:`${r.published_at}::${fo}::open_position`,typeArguments:i,arguments:u}),n}async collectFeeTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),r=new Ur.TransactionBlock,n=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeA,!1),i=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeB,!1);return this.createCollectFeePaylod(t,r,n.targetCoin,i.targetCoin),r}createCollectFeePaylod(t,e,r,n){let{clmm_pool:i,integrate:o}=this.sdk.sdkOptions,s=[t.coinTypeA,t.coinTypeB],u=[e.object(be(i).global_config_id),e.object(t.pool_id),e.object(t.pos_id),r,n];return e.moveCall({target:`${o.published_at}::${Gr}::collect_fee`,typeArguments:s,arguments:u}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.fullClient.devInspectTransactionBlock({transactionBlock:e,sender:this._sdk.senderAddress});for(let n of r.events)if(ae(n.type).name==="CollectFeeEvent"){let i=n.parsedJson;return{feeOwedA:i.amount_a,feeOwedB:i.amount_b}}return{feeOwedA:"0",feeOwedB:"0"}}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},v0=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[Y,Y,Y]}get sdk(){return this._sdk}async emissionsEveryDay(t){let r=(await this.sdk.Pool.getPool(t)).rewarder_infos;if(!r)return null;let n=[];for(let i of r){let o=fe.fromX64(new Se.default(i.emissions_per_second));n.push({emissions:Math.floor(o.toNumber()*60*60*24),coin_address:i.coinAddress})}return n}async updatePoolRewarder(t,e){let r=await this.sdk.Pool.getPool(t),n=r.rewarder_last_updated_time;if(r.rewarder_last_updated_time=e.toString(),Number(r.liquidity)===0||e.eq(new Se.default(n)))return r;let i=e.div(new Se.default(1e3)).sub(new Se.default(n)).add(new Se.default(15)),o=r.rewarder_infos;for(let s=0;s<o.length;s+=1){let u=o[s],l=fe.checkMulDivFloor(i,new Se.default(u.emissions_per_second),new Se.default(r.liquidity),128);this.growthGlobal[s]=new Se.default(u.growth_global).add(new Se.default(l))}return r}async posRewardersAmount(t,e,r){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(t,new Se.default(n)),o=await this.sdk.Position.getPositionRewarders(e,r);if(o===void 0)return[];let s=i.ticks_handle,u=await this.sdk.Pool.getTickDataByIndex(s,o.tick_lower_index),l=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(i,o,u,l)}async poolRewardersAmount(t,e){let r=Date.parse(new Date().toString()),n=await this.updatePoolRewarder(e,new Se.default(r)),i=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(n.ticks_handle,i),s=[Y,Y,Y];for(let u=0;u<i.length;u+=1){let l=await this.posRewardersAmountInternal(n,i[u],o[0][u],o[1][u]);for(let d=0;d<3;d+=1)s[d]=s[d].add(l[d].amount_owed)}return s}posRewardersAmountInternal(t,e,r,n){let i=e.tick_lower_index,o=e.tick_upper_index,s=m0(t,r,n,i,o,this.growthGlobal),u=[],l=[];if(s.length>0){let d=fe.subUnderflowU128(s[0],new Se.default(e.reward_growth_inside_0));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[0]),l.push({amount_owed:new Se.default(e.reward_amount_owed_0).add(b),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let d=fe.subUnderflowU128(s[1],new Se.default(e.reward_growth_inside_1));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[1]),l.push({amount_owed:new Se.default(e.reward_amount_owed_1).add(b),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let d=fe.subUnderflowU128(s[2],new Se.default(e.reward_growth_inside_2));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[2]),l.push({amount_owed:new Se.default(e.reward_amount_owed_2).add(b),coin_address:t.rewarder_infos[2].coinAddress})}return l}async batchFetchPositionRewarders(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB,rewarderInfo:o.rewarder_infos})}let r={};if(e.length>0){let n=await this.fetchPosRewardersAmount(e);for(let i of n)r[i.positionId]=i.rewarderAmountOwed;return r}return r}async fetchPositionRewarders(t,e){let r={poolAddress:t.poolAddress,positionId:e,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,rewarderInfo:t.rewarder_infos};return(await this.fetchPosRewardersAmount([r]))[0].rewarderAmountOwed}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(l=>ae(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new Se.default(d.fee_owned_a),feeOwedB:new Se.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId),i.object(Ce)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_rewards`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V(`this config simulationAccount: ${n.address} is not set right`,"InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(l=>ae(l.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new V("valueData.length !== params.pools.length");let u=[];for(let l=0;l<s.length;l+=1){let d={poolAddress:t[l].poolAddress,positionId:t[l].positionId,rewarderAmountOwed:[]};for(let b=0;b<t[l].rewarderInfo.length;b+=1)d.rewarderAmountOwed.push({amount_owed:new Se.default(s[l].parsedJson.data[b]),coin_address:t[l].rewarderInfo[b].coinAddress});u.push(d)}return u}async fetchPoolRewardersAmount(t,e){let r=await this.sdk.Pool.getPool(e),n=await this.sdk.Position.getPositionList(t,[e]),i=[];for(let u of n)i.push({poolAddress:r.poolAddress,positionId:u.pos_object_id,rewarderInfo:r.rewarder_infos,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB});let o=await this.fetchPosRewardersAmount(i),s=[Y,Y,Y];if(o!=null)for(let u of o)for(let l=0;l<u.rewarderAmountOwed.length;l+=1)s[l]=s[l].add(u.rewarderAmountOwed[l].amount_owed);return s}async getPoolLowerAndUpperTicks(t,e){let r=[],n=[];for(let i of e){let o=await this.sdk.Pool.getTickDataByIndex(t,i.tick_lower_index),s=await this.sdk.Pool.getTickDataByIndex(t,i.tick_upper_index);r.push(o),n.push(s)}return[r,n]}async collectRewarderTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),r=new mo.TransactionBlock;return r=Pe.createCollectRewarderAndFeeParams(this._sdk,r,t,e),r}createCollectRewarderPaylod(t,e,r){let{clmm_pool:n,integrate:i}=this.sdk.sdkOptions,o=be(n),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((u,l)=>{e&&e.moveCall({target:`${i.published_at}::${Gr}::collect_reward`,typeArguments:[...s,u],arguments:[e.object(o.global_config_id),e.object(t.pool_id),e.object(t.pos_id),e.object(o.global_vault_id),r[l],e.object(Ce)]})}),e}};function lo(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var T0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new Wr.Graph(!1),this._coinAddressMap=new Map,this.poolAddressMap=new Map,this._sdk=t,this.getPoolAddressMapAndDirection=this.getPoolAddressMapAndDirection.bind(this),this.setCoinList=this.setCoinList.bind(this),this.loadGraph=this.loadGraph.bind(this),this.addCoinProvider=this.addCoinProvider.bind(this),this.addPathProvider=this.addPathProvider.bind(this),this.preRouterSwapA2B2C=this.preRouterSwapA2B2C.bind(this),this.price=this.price.bind(this),this.getPoolWithTVL=this.getPoolWithTVL.bind(this)}get sdk(){return this._sdk}getPoolAddressMapAndDirection(t,e){let{pair:r,reversePair:n}=lo(t,e),i=this.poolAddressMap.get(r);if(i!=null)return{addressMap:i,direction:!0};if(i=this.poolAddressMap.get(n),i!=null)return{addressMap:i,direction:!1}}setCoinList(){this.coinProviders.coins.forEach(t=>{this._coinAddressMap.set(t.address,t)})}loadGraph(t,e){this.addCoinProvider(t),this.addPathProvider(e),this.setCoinList(),this.pathProviders.forEach(r=>{let{paths:n}=r;n.forEach(i=>{let o=this.graph.getVertexByKey(i.base)??new Wr.GraphVertex(i.base),s=this.graph.getVertexByKey(i.quote)??new Wr.GraphVertex(i.quote);this.graph.addEdge(new Wr.GraphEdge(o,s));let u=this._coinAddressMap.get(i.base),l=this._coinAddressMap.get(i.quote);if(u!=null&&l!=null){let d=lo(i.base,i.quote).pair;this.poolAddressMap.set(d,i.addressMap)}})})}addPathProvider(t){for(let e=0;e<t.paths.length;e+=1){let{base:r,quote:n}=t.paths[e];r.localeCompare(n)<0&&(t.paths[e].base=n,t.paths[e].quote=r),r==="0x2::sui::SUI"&&(t.paths[e].base=n,t.paths[e].quote=r),n==="0x2::sui::SUI"&&(t.paths[e].base=r,t.paths[e].quote=n)}return this.pathProviders.push(t),this}addCoinProvider(t){return this.coinProviders=t,this}tokenInfo(t){return this._coinAddressMap.get(t)}getFeeRate(t,e,r){let n=lo(t,e).pair,i=this.poolAddressMap.get(n);if(i!=null){for(let[u,l]of i.entries())if(l===r)return u*100}let o=lo(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[u,l]of s.entries())if(l===r)return u*100}return 0}async price(t,e,r,n,i,o,s){let u=this.tokenInfo(t),l=this.tokenInfo(e);if(u===void 0||l===void 0)throw new V("From/To coin is undefined","InvalidCoin");let d=this.graph.getVertexByKey(u.address),b=this.graph.getVertexByKey(l.address),_=this.graph.findAllPath(d,b),T=Array.from(_);if(T.length===0)throw new V("No find valid path in coin graph","NotFoundPath");let x=[];for(let N=0;N<T.length;N+=1){let j=T[N];if(j.length>3)continue;let S=[],k=[],a=[],c=[];for(let m=0;m<j.length-1;m+=1){let y=j[m].value.toString(),p=j[m+1].value.toString(),h=this.getPoolAddressMapAndDirection(y,p),w=h?.addressMap,g=h?.direction;w!=null&&g!=null&&(k.push(g),S.push(y),S.push(p),w.forEach(f=>{m===0?a.push(f):c.push(f)}))}for(let m of a)if(c.length>0)for(let y of c){let p={stepNums:2,poolAB:m,poolBC:y,a2b:k[0],b2c:k[1],amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:S[3]};x.push(p)}else{let y={stepNums:1,poolAB:m,poolBC:void 0,a2b:k[0],b2c:void 0,amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:void 0};x.push(y)}}let A=x.filter(N=>N.stepNums===1),I=x.filter(N=>N.stepNums!==1),C=[];try{C=await this.getPoolWithTVL()}catch{C=[]}if(C.length>0){let N=new Map(C.map(j=>[j.poolAddress,j]));I.sort((j,S)=>{let k=0,a=0;if(N.has(j.poolAB)&&N.has(j.poolBC)){let c=N.get(j.poolAB),m=N.get(j.poolBC);k=Math.min(c.tvl,m.tvl)}if(N.has(S.poolAB)&&N.has(S.poolBC)){let c=N.get(S.poolAB),m=N.get(S.poolBC);a=Math.min(c.tvl,m.tvl)}return a-k})}if(x=[...A,...I],x.length===0){if(s!=null){let N=await this.sdk.Swap.preSwapWithMultiPool(s),j={amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),poolAddress:[N.poolAddress],a2b:[N.aToB],rawAmountLimit:n?[N.estimatedAmountOut]:[N.estimatedAmountIn],isExceed:N.isExceed,coinType:[t,e]},S={paths:[j],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),paths:[j],a2b:N.aToB,b2c:void 0,byAmountIn:n,isExceed:N.isExceed,targetSqrtPrice:[N.estimatedEndSqrtPrice],currentSqrtPrice:[N.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:S}}throw new V("No parameters available for service downgrade","NoDowngradeNeedParams")}let E=await this.preRouterSwapA2B2C(x.slice(0,16));if(E==null){if(s!=null){let j=await this.sdk.Swap.preSwapWithMultiPool(s),S={amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),poolAddress:[j.poolAddress],a2b:[j.aToB],rawAmountLimit:n?[j.estimatedAmountOut]:[j.estimatedAmountIn],isExceed:j.isExceed,coinType:[t,e]},k={paths:[S],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),paths:[S],a2b:j.aToB,b2c:void 0,byAmountIn:n,isExceed:j.isExceed,targetSqrtPrice:[j.estimatedEndSqrtPrice],currentSqrtPrice:[j.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:k}}return{amountIn:Y,amountOut:Y,paths:[],a2b:!1,b2c:!1,byAmountIn:n,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let P=E.index,D=x[P].poolBC!=null?[x[P].poolAB,x[P].poolBC]:[x[P].poolAB],L=n?[E.amountMedium,E.amountOut]:[E.amountIn,E.amountMedium],H=[];H.push(x[P].a2b),E.stepNum>1&&H.push(x[P].b2c);let W=[];W.push(x[P].coinTypeA),W.push(x[P].coinTypeB),E.stepNum>1&&W.push(x[P].coinTypeC);let K={amountIn:E.amountIn,amountOut:E.amountOut,poolAddress:D,a2b:H,rawAmountLimit:L,isExceed:E.isExceed,coinType:W},F={paths:[K],partner:o,priceSlippagePoint:i};return{amountIn:E.amountIn,amountOut:E.amountOut,paths:[K],a2b:x[P].a2b,b2c:E.stepNum>1?x[P].b2c:void 0,byAmountIn:n,isExceed:E.isExceed,targetSqrtPrice:E.targetSqrtPrice,currentSqrtPrice:E.currentSqrtPrice,coinTypeA:x[P].coinTypeA,coinTypeB:x[P].coinTypeB,coinTypeC:E.stepNum>1?x[P].coinTypeC:void 0,createTxParams:F}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new Yl.TransactionBlock;for(let _ of t)if(_.stepNums>1){let T=[n.object(_.poolAB),n.object(_.poolBC),n.pure(_.a2b),n.pure(_.b2c),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=[];_.a2b?x.push(_.coinTypeA,_.coinTypeB):x.push(_.coinTypeB,_.coinTypeA),_.b2c?x.push(_.coinTypeB,_.coinTypeC):x.push(_.coinTypeC,_.coinTypeB),n.moveCall({target:`${e.published_at}::${Wn}::calculate_router_swap_result`,typeArguments:x,arguments:T})}else{let T=[n.pure(_.poolAB),n.pure(_.a2b),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=_.a2b?[_.coinTypeA,_.coinTypeB]:[_.coinTypeB,_.coinTypeA];n.moveCall({target:`${e.published_at}::${Eg}::get_expect_swap_result`,arguments:T,typeArguments:x})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address})).events?.filter(_=>ae(_.type).name==="CalculatedRouterSwapResultEvent"||ae(_.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?Y:_n,u=0;for(let _=0;_<o.length;_+=1)if(!o[_].parsedJson.data.is_exceed)if(t[0].byAmountIn){let T=new Et.default(o[_].parsedJson.data.amount_out);T.gt(s)&&(u=_,s=T)}else{let T=t[_].stepNums>1?new Et.default(o[_].parsedJson.data.amount_in):new Et.default(o[_].parsedJson.data.amount_in).add(new Et.default(o[_].parsedJson.data.fee_amount));T.lt(s)&&(u=_,s=T)}let l=[],d=[];return t[u].stepNums>1?(d.push(o[u].parsedJson.data.target_sqrt_price_ab,o[u].parsedJson.data.target_sqrt_price_cd),l.push(o[u].parsedJson.data.current_sqrt_price_ab,o[u].parsedJson.data.current_sqrt_price_cd)):(d.push(o[u].parsedJson.data.after_sqrt_price),l.push(o[u].parsedJson.current_sqrt_price)),{index:u,amountIn:t[0].byAmountIn?t[u].amount:s,amountMedium:o[u].parsedJson.data.amount_medium,amountOut:t[0].byAmountIn?s:t[u].amount,targetSqrtPrice:d,currentSqrtPrice:l,isExceed:o[u].parsedJson.data.is_exceed,stepNum:t[u].stepNums}}async getPoolWithTVL(){let t=[],{swapCountUrl:e}=this._sdk.sdkOptions;if(!e)return t;let r;try{r=await fetch(e)}catch{throw new V(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let n;try{n=await r.json()}catch{throw new V(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(n.code!==200)throw new V(`Failed to get pool list from ${e}. Statu code is ${n.code}.`,"InvalidSwapCountUrl");let{pools:i}=n.data;for(let o of i)t.push({poolAddress:o.swap_account,tvl:Number(o.tvl_in_usd)});return t}};var S0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n>0){let i=r.basePaths[0],o=i.label==="Cetus"?new $(i.feeRate).div(10**6):new $(i.feeRate).div(10**9),s=vt(i.inputAmount).div(10**i.fromDecimal).mul(o);if(e=e.add(s),n>1){let u=r.basePaths[1],l=i.direction?i.currentPrice:new $(1).div(i.currentPrice),d=u.direction?u.currentPrice:new $(1).div(u.currentPrice),b=u.label==="Cetus"?new $(u.feeRate).div(10**6):new $(u.feeRate).div(10**9),T=vt(u.outputAmount).div(10**u.toDecimal).mul(b).div(l.mul(d));e=e.add(T)}}}),e.toString()}calculateSwapPriceImpact(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n===1){let i=r.basePaths[0],o=vt(i.outputAmount).div(10**i.toDecimal),s=vt(i.inputAmount).div(10**i.fromDecimal),u=o.div(s),l=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice);e=e.add(this.calculateSingleImpact(u,l))}if(n===2){let i=r.basePaths[0],o=r.basePaths[1],s=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice),u=o.direction?new $(o.currentPrice):new $(1).div(o.currentPrice),l=s.mul(u),d=new $(o.outputAmount).div(10**o.toDecimal),b=new $(i.inputAmount).div(10**i.fromDecimal),_=d.div(b);e=e.add(this.calculateSingleImpact(_,l))}}),e.toString()}calculateSingleImpact=(t,e)=>e.minus(t).div(e).mul(100);async preSwapWithMultiPool(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB];for(let d=0;d<t.poolAddresses.length;d+=1){let b=[n.pure(t.poolAddresses[d]),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:b,typeArguments:i})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(o.error!=null)throw new V(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(d=>ae(d.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new V("valueData.length !== params.pools.length","ParamsLengthNotEqual");let u=t.byAmountIn?Y:_n,l=0;for(let d=0;d<s.length;d+=1)if(!s[d].parsedJson.data.is_exceed)if(t.byAmountIn){let b=new $r.default(s[d].parsedJson.data.amount_out);b.gt(u)&&(l=d,u=b)}else{let b=new $r.default(s[d].parsedJson.data.amount_out);b.lt(u)&&(l=d,u=b)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[l],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[l].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=[n.pure(t.pool.poolAddress),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];if(n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:o,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let s=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(s.error!=null)throw new V(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let u=s.events?.filter(l=>ae(l.type).name==="CalculatedSwapResultEvent");return u.length===0?null:this.transformSwapData(t,u[0].parsedJson.data)}transformSwapData(t,e){let r=e.amount_in&&e.fee_amount?new $r.default(e.amount_in).add(new $r.default(e.fee_amount)).toString():"";return{poolAddress:t.pool.poolAddress,currentSqrtPrice:t.currentSqrtPrice,estimatedAmountIn:r,estimatedAmountOut:e.amount_out,estimatedEndSqrtPrice:e.after_sqrt_price,estimatedFeeAmount:e.fee_amount,isExceed:e.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}transformSwapWithMultiPoolData(t,e){let{data:r}=e,n=r.amount_in&&r.fee_amount?new $r.default(r.amount_in).add(new $r.default(r.fee_amount)).toString():"";return{poolAddress:t.poolAddress,estimatedAmountIn:n,estimatedAmountOut:r.amount_out,estimatedEndSqrtPrice:r.after_sqrt_price,estimatedStartSqrtPrice:e.current_sqrt_price,estimatedFeeAmount:r.fee_amount,isExceed:r.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}calculateRates(t){let{currentPool:e}=t,r=Og(e),n;t.a2b?n=t.swapTicks.sort((_,T)=>T.index-_.index):n=t.swapTicks.sort((_,T)=>_.index-T.index);let i=Wg(t.a2b,t.byAmountIn,t.amount,r,n),o=!1;t.byAmountIn?o=i.amountIn.lt(t.amount):o=i.amountOut.lt(t.amount);let s=yr.getDefaultSqrtPriceLimit(t.a2b);t.a2b&&i.nextSqrtPrice.lt(s)&&(o=!0),!t.a2b&&i.nextSqrtPrice.gt(s)&&(o=!0);let u=0;i.crossTickNum>6&&i.crossTickNum<40&&(u=22e3*(i.crossTickNum-6)),i.crossTickNum>40&&(o=!0);let l=ke.sqrtPriceX64ToPrice(r.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),d=ke.sqrtPriceX64ToPrice(i.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),b=Math.abs(l-d)/l*100;return{estimatedAmountIn:i.amountIn,estimatedAmountOut:i.amountOut,estimatedEndSqrtPrice:i.nextSqrtPrice,estimatedFeeAmount:i.feeAmount,isExceed:o,extraComputeLimit:u,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn,priceImpactPct:b}}async createSwapTransactionPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionForGas(this._sdk,t,r,e)}return Pe.buildSwapTransaction(this.sdk,t,r)}async createSwapTransactionWithoutTransferCoinsPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,r,e)}return Pe.buildSwapTransactionWithoutTransferCoins(this.sdk,t,r)}},x0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getAllRegisteredTokenList(t=!1){return await this.factchTokenList("",t)}async getOwnerTokenList(t="",e=!1){return await this.factchTokenList(t,e)}async getAllRegisteredPoolList(t=!1){return await this.factchPoolList("",t)}async getOwnerPoolList(t="",e=!1){return await this.factchPoolList(t,e)}async getWarpPoolList(t=!1){return await this.factchWarpPoolList("","",t)}async getOwnerWarpPoolList(t="",e="",r=!1){return await this.factchWarpPoolList(t,e,r)}async getTokenListByCoinTypes(t){let e={},n=this.getCache("getAllRegisteredTokenList");if(n!==void 0){let o=n;for(let s of t)for(let u of o)if(sr(s)===sr(u.address)){e[s]=u;continue}}let i=t.filter(o=>e[o]===void 0);for(let o of i){let s=`${o}_metadata`,u=this.getCache(s);if(u!==void 0)e[o]=u;else{let l=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(l){let d={id:l.id,name:l.name,symbol:l.symbol,official_symbol:l.symbol,coingecko_id:"",decimals:l.decimals,project_url:"",logo_url:l.iconUrl,address:o};e[o]=d,this.updateCache(s,d,Oe)}}}return e}async factchTokenList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredTokenList",e);if(o!==void 0)return o;let s=t.length>0,u=512,l=0,d=[];if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;_.moveCall({target:`${n.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[_.pure(b.coin_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.coin_registry_id),_.pure(l),_.pure(u)]});let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{ae(A.type).full_address===`${n.published_at}::coin_list::FetchCoinListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!1))})}),d=[...d,...x],x.length<u)break;l=d.length}return d}async factchPoolList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredPoolList",e);if(o!==void 0)return o;let s=[],u=512,l=0,d=t.length>0;if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;if(_.moveCall({target:`${n.published_at}::lp_list::${d?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:d?[_.pure(b.pool_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.pool_registry_id),_.pure(l),_.pure(u)]}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{ae(A.type).full_address===`${n.published_at}::lp_list::FetchPoolListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!0))})}),s=[...s,...x],x.length<u)break;l=s.length}return s}async factchWarpPoolList(t="",e="",r=!1){let n=await this.factchPoolList(t,r);if(n.length===0)return[];let i=await this.factchTokenList(e,r),o=[];for(let s of n){for(let u of i)u.address===s.coin_a_address&&(s.coinA=u),u.address===s.coin_b_address&&(s.coinB=u);o.push(s)}return o}async getTokenConfigEvent(t=!1){let e=this._sdk.sdkOptions.token.package_id,r=`${e}_getTokenConfigEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_registry_id:"",pool_registry_id:"",coin_list_owner:"",pool_list_owner:""};return s.data.length>0&&s.data.forEach(l=>{let d=ae(l.type);if(l.transactionModule==="coin_list")switch(d.name){case"InitListEvent":u.coin_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent":u.coin_registry_id=l.parsedJson.registry_id;break;default:break}else if(l.transactionModule==="lp_list")switch(d.name){case"InitListEvent<address>":u.pool_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent<address>":u.pool_registry_id=l.parsedJson.registry_id;break;default:break}}),u.coin_registry_id.length>0&&this.updateCache(r,u,Oe),u}transformData(t,e){let r={...t};if(e)try{r.coin_a_address=ae(r.coin_a_address).full_address,r.coin_b_address=ae(r.coin_b_address).full_address}catch{}else r.address=ae(r.address).full_address;if(t.extensions){let n=t.extensions.contents;for(let i of n){let{key:o}=i,{value:s}=i;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}o==="pyth_id"&&(s=(0,Ql.normalizeSuiObjectId)(s)),r[o]=s}delete r.extensions}return r}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},k0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculatePrice(t,e,r,n,i){let o=n?e:r,s=n?r:e;return i==="Cetus"?ke.sqrtPriceX64ToPrice(t,o,s):new $(t.toString()).div(new $(10).pow(new $(s+9-o)))}parseJsonResult(t){return{isExceed:t.is_exceed,isTimeout:t.is_timeout,inputAmount:t.input_amount,outputAmount:t.output_amount,fromCoin:t.from_coin,toCoin:t.to_coin,byAmountIn:t.by_amount_in,splitPaths:t.split_paths.map(r=>({pathIndex:r.path_index,lastQuoteOutput:r.last_quote_output,percent:r.percent,basePaths:r.best_path.map(i=>({direction:i.direction,label:i.label,poolAddress:i.provider,fromCoin:i.from_coin,toCoin:i.to_coin,outputAmount:i.output_amount,inputAmount:i.input_amount,feeRate:i.fee_rate,currentSqrtPrice:new Gt.default(i.current_sqrt_price.toString()),afterSqrtPrice:i.label==="Cetus"?new Gt.default(i.after_sqrt_price.toString()):Y,fromDecimal:i.from_decimal,toDecimal:i.to_decimal,currentPrice:this.calculatePrice(new Gt.default(i.current_sqrt_price.toString()),i.from_decimal,i.to_decimal,i.direction,i.label)})),inputAmount:r.input_amount,outputAmount:r.output_amount}))}}async fetchWithTimeout(t,e,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let o=await fetch(t,{...e,signal:n.signal});return clearTimeout(i),o}catch{return null}}async fetchAndParseData(t,e){try{let n=await this.fetchWithTimeout(t,e,1500);return n.status===200?this.parseJsonResult(await n.json()):null}catch{return null}}async getBestRouter(t,e,r,n,i,o,s,u,l=!1,d=!1,b=[]){let _=null,T="v2",x={},A=this.sdk.sdkOptions.aggregatorUrl;if(b.length>0){let I=new URL(A);A=`${I.protocol}//${I.hostname}/router_with_lp_changes`,x={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:r,by_amount_in:n,order_split:l,external_router:d,sender_address:"None",request_id:encodeURIComponent(ao()),lp_changes:b})}}else A=`
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var k,a=!0,c=!1;return{s:function(){N=N.call(F)},n:function(){var m=N.next();return a=m.done,m},e:function(m){c=!0,k=m},f:function(){try{a||N.return==null||N.return()}finally{if(c)throw k}}}}var K=function(F){var U=Math.abs,N=Math.max,j=Math.floor;function S(a,c){var m;if(n(this,S),m=k.call(this,a),m.sign=c,Object.setPrototypeOf(x(m),S.prototype),a>S.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return m}s(S,F);var k=I(S);return o(S,[{key:"toDebugString",value:function(){var a,c=["BigInt["],m=W(this);try{for(m.s();!(a=m.n()).done;){var y=a.value;c.push((y&&(y>>>0).toString(16))+", ")}}catch(p){m.e(p)}finally{m.f()}return c.push("]"),c.join("")}},{key:"toString",value:function(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>a||36<a)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":a&a-1?S.__toStringGeneric(this,a,!1):S.__toStringBasePowerOfTwo(this,a)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var a=new S(this.length,this.sign),c=0;c<this.length;c++)a[c]=this[c];return a}},{key:"__trim",value:function(){for(var a=this.length,c=this[a-1];c===0;)a--,c=this[a-1],this.pop();return a===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var a=0;a<this.length;a++)this[a]=0}},{key:"__clzmsd",value:function(){return S.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(a,c,m){m>this.length&&(m=this.length);for(var y=32767&a,p=a>>>15,h=0,w=c,g=0;g<m;g++){var f=this.__digit(g),v=32767&f,O=f>>>15,M=S.__imul(v,y),R=S.__imul(v,p),B=S.__imul(O,y),G=S.__imul(O,p),Z=w+M+h;h=Z>>>30,Z&=1073741823,Z+=((32767&R)<<15)+((32767&B)<<15),h+=Z>>>30,w=G+(R>>>15)+(B>>>15),this.__setDigit(g,1073741823&Z)}if(h!==0||w!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(a,c,m){for(var y,p=0,h=0;h<m;h++)y=this.__halfDigit(c+h)+a.__halfDigit(h)+p,p=y>>>15,this.__setHalfDigit(c+h,32767&y);return p}},{key:"__inplaceSub",value:function(a,c,m){var y=0;if(1&c){c>>=1;for(var p=this.__digit(c),h=32767&p,w=0;w<m-1>>>1;w++){var g=a.__digit(w),f=(p>>>15)-(32767&g)-y;y=1&f>>>15,this.__setDigit(c+w,(32767&f)<<15|32767&h),p=this.__digit(c+w+1),h=(32767&p)-(g>>>15)-y,y=1&h>>>15}var v=a.__digit(w),O=(p>>>15)-(32767&v)-y;if(y=1&O>>>15,this.__setDigit(c+w,(32767&O)<<15|32767&h),c+w+1>=this.length)throw new RangeError("out of bounds");!(1&m)&&(p=this.__digit(c+w+1),h=(32767&p)-(v>>>15)-y,y=1&h>>>15,this.__setDigit(c+a.length,1073709056&p|32767&h))}else{c>>=1;for(var M=0;M<a.length-1;M++){var R=this.__digit(c+M),B=a.__digit(M),G=(32767&R)-(32767&B)-y;y=1&G>>>15;var Z=(R>>>15)-(B>>>15)-y;y=1&Z>>>15,this.__setDigit(c+M,(32767&Z)<<15|32767&G)}var oe=this.__digit(c+M),te=a.__digit(M),ae=(32767&oe)-(32767&te)-y;y=1&ae>>>15;var dt=0;!(1&m)&&(dt=(oe>>>15)-(te>>>15)-y,y=1&dt>>>15),this.__setDigit(c+M,(32767&dt)<<15|32767&ae)}return y}},{key:"__inplaceRightShift",value:function(a){if(a!==0){for(var c,m=this.__digit(0)>>>a,y=this.length-1,p=0;p<y;p++)c=this.__digit(p+1),this.__setDigit(p,1073741823&c<<30-a|m),m=c>>>a;this.__setDigit(y,m)}}},{key:"__digit",value:function(a){return this[a]}},{key:"__unsignedDigit",value:function(a){return this[a]>>>0}},{key:"__setDigit",value:function(a,c){this[a]=0|c}},{key:"__setDigitGrow",value:function(a,c){this[a]=0|c}},{key:"__halfDigitLength",value:function(){var a=this.length;return 32767>=this.__unsignedDigit(a-1)?2*a-1:2*a}},{key:"__halfDigit",value:function(a){return 32767&this[a>>>1]>>>15*(1&a)}},{key:"__setHalfDigit",value:function(a,c){var m=a>>>1,y=this.__digit(m),p=1&a?32767&y|c<<15:1073709056&y|32767&c;this.__setDigit(m,p)}}],[{key:"BigInt",value:function(a){var c=Number.isFinite;if(typeof a=="number"){if(a===0)return S.__zero();if(S.__isOneDigitInt(a))return 0>a?S.__oneDigit(-a,!0):S.__oneDigit(a,!1);if(!c(a)||j(a)!==a)throw new RangeError("The number "+a+" cannot be converted to BigInt because it is not an integer");return S.__fromDouble(a)}if(typeof a=="string"){var m=S.__fromString(a);if(m===null)throw new SyntaxError("Cannot convert "+a+" to a BigInt");return m}if(typeof a=="boolean")return a===!0?S.__oneDigit(1,!1):S.__zero();if(r(a)==="object"){if(a.constructor===S)return a;var y=S.__toPrimitive(a);return S.BigInt(y)}throw new TypeError("Cannot convert "+a+" to a BigInt")}},{key:"toNumber",value:function(a){var c=a.length;if(c===0)return 0;if(c===1){var m=a.__unsignedDigit(0);return a.sign?-m:m}var y=a.__digit(c-1),p=S.__clz30(y),h=30*c-p;if(1024<h)return a.sign?-1/0:1/0;var w=h-1,g=y,f=c-1,v=p+3,O=v===32?0:g<<v;O>>>=12;var M=v-12,R=12<=v?0:g<<20+v,B=20+v;for(0<M&&0<f&&(f--,g=a.__digit(f),O|=g>>>30-M,R=g<<M+2,B=M+2);0<B&&0<f;)f--,g=a.__digit(f),R|=30<=B?g<<B-30:g>>>30-B,B-=30;var G=S.__decideRounding(a,B,f,g);if((G===1||G===0&&(1&R)==1)&&(R=R+1>>>0,R===0&&(O++,O>>>20!=0&&(O=0,w++,1023<w))))return a.sign?-1/0:1/0;var Z=a.sign?-2147483648:0;return w=w+1023<<20,S.__kBitConversionInts[1]=Z|w|O,S.__kBitConversionInts[0]=R,S.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(a){if(a.length===0)return a;var c=a.__copy();return c.sign=!a.sign,c}},{key:"bitwiseNot",value:function(a){return a.sign?S.__absoluteSubOne(a).__trim():S.__absoluteAddOne(a,!0)}},{key:"exponentiate",value:function(a,c){if(c.sign)throw new RangeError("Exponent must be positive");if(c.length===0)return S.__oneDigit(1,!1);if(a.length===0)return a;if(a.length===1&&a.__digit(0)===1)return a.sign&&!(1&c.__digit(0))?S.unaryMinus(a):a;if(1<c.length)throw new RangeError("BigInt too big");var m=c.__unsignedDigit(0);if(m===1)return a;if(m>=S.__kMaxLengthBits)throw new RangeError("BigInt too big");if(a.length===1&&a.__digit(0)===2){var y=1+(0|m/30),p=a.sign&&(1&m)!=0,h=new S(y,p);h.__initializeDigits();var w=1<<m%30;return h.__setDigit(y-1,w),h}var g=null,f=a;for(1&m&&(g=a),m>>=1;m!==0;m>>=1)f=S.multiply(f,f),1&m&&(g===null?g=f:g=S.multiply(g,f));return g}},{key:"multiply",value:function(a,c){if(a.length===0)return a;if(c.length===0)return c;var m=a.length+c.length;30<=a.__clzmsd()+c.__clzmsd()&&m--;var y=new S(m,a.sign!==c.sign);y.__initializeDigits();for(var p=0;p<a.length;p++)S.__multiplyAccumulate(c,a.__digit(p),y,p);return y.__trim()}},{key:"divide",value:function(a,c){if(c.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(a,c))return S.__zero();var m,y=a.sign!==c.sign,p=c.__unsignedDigit(0);if(c.length===1&&32767>=p){if(p===1)return y===a.sign?a:S.unaryMinus(a);m=S.__absoluteDivSmall(a,p,null)}else m=S.__absoluteDivLarge(a,c,!0,!1);return m.sign=y,m.__trim()}},{key:"remainder",value:function(c,m){if(m.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(c,m))return c;var y=m.__unsignedDigit(0);if(m.length===1&&32767>=y){if(y===1)return S.__zero();var p=S.__absoluteModSmall(c,y);return p===0?S.__zero():S.__oneDigit(p,c.sign)}var h=S.__absoluteDivLarge(c,m,!1,!0);return h.sign=c.sign,h.__trim()}},{key:"add",value:function(a,c){var m=a.sign;return m===c.sign?S.__absoluteAdd(a,c,m):0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m)}},{key:"subtract",value:function(a,c){var m=a.sign;return m===c.sign?0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m):S.__absoluteAdd(a,c,m)}},{key:"leftShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__rightShiftByAbsolute(a,c):S.__leftShiftByAbsolute(a,c)}},{key:"signedRightShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__leftShiftByAbsolute(a,c):S.__rightShiftByAbsolute(a,c)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(a,c){return 0>S.__compareToBigInt(a,c)}},{key:"lessThanOrEqual",value:function(a,c){return 0>=S.__compareToBigInt(a,c)}},{key:"greaterThan",value:function(a,c){return 0<S.__compareToBigInt(a,c)}},{key:"greaterThanOrEqual",value:function(a,c){return 0<=S.__compareToBigInt(a,c)}},{key:"equal",value:function(a,c){if(a.sign!==c.sign||a.length!==c.length)return!1;for(var m=0;m<a.length;m++)if(a.__digit(m)!==c.__digit(m))return!1;return!0}},{key:"notEqual",value:function(a,c){return!S.equal(a,c)}},{key:"bitwiseAnd",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteAnd(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length)+1,y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteOr(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}return S.__absoluteAndNot(a,S.__absoluteSubOne(c)).__trim()}},{key:"bitwiseXor",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteXor(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length),y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return S.__absoluteXor(y,p,y).__trim()}var h=N(a.length,c.length)+1;if(a.sign){var w=[c,a];a=w[0],c=w[1]}var g=S.__absoluteSubOne(c,h);return g=S.__absoluteXor(g,a,g),S.__absoluteAddOne(g,!0,g).__trim()}},{key:"bitwiseOr",value:function(a,c){var m=N(a.length,c.length);if(!a.sign&&!c.sign)return S.__absoluteOr(a,c).__trim();if(a.sign&&c.sign){var y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteAnd(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}var w=S.__absoluteSubOne(c,m);return w=S.__absoluteAndNot(w,a,w),S.__absoluteAddOne(w,!0,w).__trim()}},{key:"asIntN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=c.__unsignedDigit(m-1),p=1<<(a-1)%30;if(c.length===m&&y<p)return c;if((y&p)!==p)return S.__truncateToNBits(a,c);if(!c.sign)return S.__truncateAndSubFromPowerOfTwo(a,c,!0);if(!(y&p-1)){for(var h=m-2;0<=h;h--)if(c.__digit(h)!==0)return S.__truncateAndSubFromPowerOfTwo(a,c,!1);return c.length===m&&y===p?c:S.__truncateToNBits(a,c)}return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}},{key:"asUintN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(c.sign){if(a>S.__kMaxLengthBits)throw new RangeError("BigInt too big");return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=a%30;if(c.length==m){if(y===0)return c;var p=c.__digit(m-1);if(!(p>>>y))return c}return S.__truncateToNBits(a,c)}},{key:"ADD",value:function(a,c){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string")return typeof c!="string"&&(c=c.toString()),a+c;if(typeof c=="string")return a.toString()+c;if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)&&S.__isBigInt(c))return S.add(a,c);if(typeof a=="number"&&typeof c=="number")return a+c;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(a,c){return S.__compare(a,c,0)}},{key:"LE",value:function(a,c){return S.__compare(a,c,1)}},{key:"GT",value:function(a,c){return S.__compare(a,c,2)}},{key:"GE",value:function(a,c){return S.__compare(a,c,3)}},{key:"EQ",value:function(a,c){for(;;){if(S.__isBigInt(a))return S.__isBigInt(c)?S.equal(a,c):S.EQ(c,a);if(typeof a=="number"){if(S.__isBigInt(c))return S.__equalToNumber(c,a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="string"){if(S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.equal(a,c);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="boolean"){if(S.__isBigInt(c))return S.__equalToNumber(c,+a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="symbol"){if(S.__isBigInt(c))return!1;if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="object"){if(r(c)==="object"&&c.constructor!==S)return a==c;a=S.__toPrimitive(a)}else return a==c}}},{key:"NE",value:function(a,c){return!S.EQ(a,c)}},{key:"DataViewGetBigInt64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return S.asIntN(64,S.DataViewGetBigUint64(a,c,m))}},{key:"DataViewGetBigUint64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2],y=m?[4,0]:[0,4],p=C(y,2),h=p[0],w=p[1],g=a.getUint32(c+h,m),f=a.getUint32(c+w,m),v=new S(3,!1);return v.__setDigit(0,1073741823&f),v.__setDigit(1,(268435455&g)<<2|f>>>30),v.__setDigit(2,g>>>28),v.__trim()}},{key:"DataViewSetBigInt64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];S.DataViewSetBigUint64(a,c,m,y)}},{key:"DataViewSetBigUint64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];m=S.asUintN(64,m);var p=0,h=0;if(0<m.length&&(h=m.__digit(0),1<m.length)){var w=m.__digit(1);h|=w<<30,p=w>>>2,2<m.length&&(p|=m.__digit(2)<<28)}var g=y?[4,0]:[0,4],f=C(g,2),v=f[0],O=f[1];a.setUint32(c+v,p,y),a.setUint32(c+O,h,y)}},{key:"__zero",value:function(){return new S(0,!1)}},{key:"__oneDigit",value:function(a,c){var m=new S(1,c);return m.__setDigit(0,a),m}},{key:"__decideRounding",value:function(a,c,m,y){if(0<c)return-1;var p;if(0>c)p=-c-1;else{if(m===0)return-1;m--,y=a.__digit(m),p=29}var h=1<<p;if(!(y&h))return-1;if(h-=1,(y&h)!=0)return 1;for(;0<m;)if(m--,a.__digit(m)!==0)return 1;return 0}},{key:"__fromDouble",value:function(a){S.__kBitConversionDouble[0]=a;var c,m=2047&S.__kBitConversionInts[1]>>>20,y=m-1023,p=(0|y/30)+1,h=new S(p,0>a),w=1048575&S.__kBitConversionInts[1]|1048576,g=S.__kBitConversionInts[0],f=20,v=y%30,O=0;if(v<f){var M=f-v;O=M+32,c=w>>>M,w=w<<32-M|g>>>M,g<<=32-M}else if(v===f)O=32,c=w,w=g,g=0;else{var R=v-f;O=32-R,c=w<<R|g>>>32-R,w=g<<R,g=0}h.__setDigit(p-1,c);for(var B=p-2;0<=B;B--)0<O?(O-=30,c=w>>>2,w=w<<30|g>>>2,g<<=30):c=0,h.__setDigit(B,c);return h.__trim()}},{key:"__isWhitespace",value:function(a){return 13>=a&&9<=a||(159>=a?a==32:131071>=a?a==160||a==5760:196607>=a?(a&=131071,10>=a||a==40||a==41||a==47||a==95||a==4096):a==65279)}},{key:"__fromString",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,m=0,y=a.length,p=0;if(p===y)return S.__zero();for(var h=a.charCodeAt(p);S.__isWhitespace(h);){if(++p===y)return S.__zero();h=a.charCodeAt(p)}if(h===43){if(++p===y)return null;h=a.charCodeAt(p),m=1}else if(h===45){if(++p===y)return null;h=a.charCodeAt(p),m=-1}if(c===0){if(c=10,h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(c=16,++p===y)return null;h=a.charCodeAt(p)}else if(h===79||h===111){if(c=8,++p===y)return null;h=a.charCodeAt(p)}else if(h===66||h===98){if(c=2,++p===y)return null;h=a.charCodeAt(p)}}}else if(c===16&&h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(++p===y)return null;h=a.charCodeAt(p)}}if(m!==0&&c!==10)return null;for(;h===48;){if(++p===y)return S.__zero();h=a.charCodeAt(p)}var w=y-p,g=S.__kMaxBitsPerChar[c],f=S.__kBitsPerCharTableMultiplier-1;if(w>1073741824/g)return null;var v=g*w+f>>>S.__kBitsPerCharTableShift,O=new S(0|(v+29)/30,!1),M=10>c?c:10,R=10<c?c-10:0;if(c&c-1){O.__initializeDigits();var dt=!1,ve=0;do{for(var xe,an=0,Ae=1;;){if(xe=void 0,h-48>>>0<M)xe=h-48;else if((32|h)-97>>>0<R)xe=(32|h)-87;else{dt=!0;break}var Me=Ae*c;if(1073741823<Me)break;if(Ae=Me,an=an*c+xe,ve++,++p===y){dt=!0;break}h=a.charCodeAt(p)}f=30*S.__kBitsPerCharTableMultiplier-1;var Gi=0|(g*ve+f>>>S.__kBitsPerCharTableShift)/30;O.__inplaceMultiplyAdd(Ae,an,Gi)}while(!dt)}else{g>>=S.__kBitsPerCharTableShift;var B=[],G=[],Z=!1;do{for(var oe,te=0,ae=0;;){if(oe=void 0,h-48>>>0<M)oe=h-48;else if((32|h)-97>>>0<R)oe=(32|h)-87;else{Z=!0;break}if(ae+=g,te=te<<g|oe,++p===y){Z=!0;break}if(h=a.charCodeAt(p),30<ae+g)break}B.push(te),G.push(ae)}while(!Z);S.__fillFromParts(O,B,G)}if(p!==y){if(!S.__isWhitespace(h))return null;for(p++;p<y;p++)if(h=a.charCodeAt(p),!S.__isWhitespace(h))return null}return O.sign=m===-1,O.__trim()}},{key:"__fillFromParts",value:function(a,c,m){for(var y=0,p=0,h=0,w=c.length-1;0<=w;w--){var g=c[w],f=m[w];p|=g<<h,h+=f,h===30?(a.__setDigit(y++,p),h=0,p=0):30<h&&(a.__setDigit(y++,1073741823&p),h-=30,p=g>>>f-h)}if(p!==0){if(y>=a.length)throw new Error("implementation bug");a.__setDigit(y++,p)}for(;y<a.length;y++)a.__setDigit(y,0)}},{key:"__toStringBasePowerOfTwo",value:function(a,c){var m=a.length,y=c-1;y=(85&y>>>1)+(85&y),y=(51&y>>>2)+(51&y),y=(15&y>>>4)+(15&y);var p=y,h=c-1,w=a.__digit(m-1),g=S.__clz30(w),f=0|(30*m-g+p-1)/p;if(a.sign&&f++,268435456<f)throw new Error("string too long");for(var v=Array(f),O=f-1,M=0,R=0,B=0;B<m-1;B++){var G=a.__digit(B),Z=(M|G<<R)&h;v[O--]=S.__kConversionChars[Z];var oe=p-R;for(M=G>>>oe,R=30-oe;R>=p;)v[O--]=S.__kConversionChars[M&h],M>>>=p,R-=p}var te=(M|w<<R)&h;for(v[O--]=S.__kConversionChars[te],M=w>>>p-R;M!==0;)v[O--]=S.__kConversionChars[M&h],M>>>=p;if(a.sign&&(v[O--]="-"),O!==-1)throw new Error("implementation bug");return v.join("")}},{key:"__toStringGeneric",value:function(a,c,m){var y=a.length;if(y===0)return"";if(y===1){var p=a.__unsignedDigit(0).toString(c);return m===!1&&a.sign&&(p="-"+p),p}var h=30*y-S.__clz30(a.__digit(y-1)),w=S.__kMaxBitsPerChar[c],g=w-1,f=h*S.__kBitsPerCharTableMultiplier;f+=g-1,f=0|f/g;var v,O,M=f+1>>1,R=S.exponentiate(S.__oneDigit(c,!1),S.__oneDigit(M,!1)),B=R.__unsignedDigit(0);if(R.length===1&&32767>=B){v=new S(a.length,!1),v.__initializeDigits();for(var G,Z=0,oe=2*a.length-1;0<=oe;oe--)G=Z<<15|a.__halfDigit(oe),v.__setHalfDigit(oe,0|G/B),Z=0|G%B;O=Z.toString(c)}else{var te=S.__absoluteDivLarge(a,R,!0,!0);v=te.quotient;var ae=te.remainder.__trim();O=S.__toStringGeneric(ae,c,!0)}v.__trim();for(var dt=S.__toStringGeneric(v,c,!0);O.length<M;)O="0"+O;return m===!1&&a.sign&&(dt="-"+dt),dt+O}},{key:"__unequalSign",value:function(a){return a?-1:1}},{key:"__absoluteGreater",value:function(a){return a?-1:1}},{key:"__absoluteLess",value:function(a){return a?1:-1}},{key:"__compareToBigInt",value:function(a,c){var m=a.sign;if(m!==c.sign)return S.__unequalSign(m);var y=S.__absoluteCompare(a,c);return 0<y?S.__absoluteGreater(m):0>y?S.__absoluteLess(m):0}},{key:"__compareToNumber",value:function(a,c){if(S.__isOneDigitInt(c)){var m=a.sign,y=0>c;if(m!==y)return S.__unequalSign(m);if(a.length===0){if(y)throw new Error("implementation bug");return c===0?0:-1}if(1<a.length)return S.__absoluteGreater(m);var p=U(c),h=a.__unsignedDigit(0);return h>p?S.__absoluteGreater(m):h<p?S.__absoluteLess(m):0}return S.__compareToDouble(a,c)}},{key:"__compareToDouble",value:function(a,c){if(c!==c)return c;if(c===1/0)return-1;if(c===-1/0)return 1;var m=a.sign;if(m!==0>c)return S.__unequalSign(m);if(c===0)throw new Error("implementation bug: should be handled elsewhere");if(a.length===0)return-1;S.__kBitConversionDouble[0]=c;var y=2047&S.__kBitConversionInts[1]>>>20;if(y==2047)throw new Error("implementation bug: handled elsewhere");var p=y-1023;if(0>p)return S.__absoluteGreater(m);var h=a.length,w=a.__digit(h-1),g=S.__clz30(w),f=30*h-g,v=p+1;if(f<v)return S.__absoluteLess(m);if(f>v)return S.__absoluteGreater(m);var O=1048576|1048575&S.__kBitConversionInts[1],M=S.__kBitConversionInts[0],R=20,B=29-g;if(B!==(0|(f-1)%30))throw new Error("implementation bug");var G,Z=0;if(B<R){var oe=R-B;Z=oe+32,G=O>>>oe,O=O<<32-oe|M>>>oe,M<<=32-oe}else if(B===R)Z=32,G=O,O=M,M=0;else{var te=B-R;Z=32-te,G=O<<te|M>>>32-te,O=M<<te,M=0}if(w>>>=0,G>>>=0,w>G)return S.__absoluteGreater(m);if(w<G)return S.__absoluteLess(m);for(var ae=h-2;0<=ae;ae--){0<Z?(Z-=30,G=O>>>2,O=O<<30|M>>>2,M<<=30):G=0;var dt=a.__unsignedDigit(ae);if(dt>G)return S.__absoluteGreater(m);if(dt<G)return S.__absoluteLess(m)}if(O!==0||M!==0){if(Z===0)throw new Error("implementation bug");return S.__absoluteLess(m)}return 0}},{key:"__equalToNumber",value:function(a,c){return S.__isOneDigitInt(c)?c===0?a.length===0:a.length===1&&a.sign===0>c&&a.__unsignedDigit(0)===U(c):S.__compareToDouble(a,c)===0}},{key:"__comparisonResultToBool",value:function(a,c){return c===0?0>a:c===1?0>=a:c===2?0<a:c===3?0<=a:void 0}},{key:"__compare",value:function(a,c,m){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string"&&typeof c=="string")switch(m){case 0:return a<c;case 1:return a<=c;case 2:return a>c;case 3:return a>=c}if(S.__isBigInt(a)&&typeof c=="string")return c=S.__fromString(c),c!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof a=="string"&&S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)){if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof c!="number")throw new Error("implementation bug");return S.__comparisonResultToBool(S.__compareToNumber(a,c),m)}if(typeof a!="number")throw new Error("implementation bug");if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToNumber(c,a),2^m);if(typeof c!="number")throw new Error("implementation bug");return m===0?a<c:m===1?a<=c:m===2?a>c:m===3?a>=c:void 0}},{key:"__absoluteAdd",value:function(a,c,m){if(a.length<c.length)return S.__absoluteAdd(c,a,m);if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);var y=a.length;(a.__clzmsd()===0||c.length===a.length&&c.__clzmsd()===0)&&y++;for(var p,h=new S(y,m),w=0,g=0;g<c.length;g++)p=a.__digit(g)+c.__digit(g)+w,w=p>>>30,h.__setDigit(g,1073741823&p);for(;g<a.length;g++){var f=a.__digit(g)+w;w=f>>>30,h.__setDigit(g,1073741823&f)}return g<h.length&&h.__setDigit(g,w),h.__trim()}},{key:"__absoluteSub",value:function(a,c,m){if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);for(var y,p=new S(a.length,m),h=0,w=0;w<c.length;w++)y=a.__digit(w)-c.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);for(;w<a.length;w++){var g=a.__digit(w)-h;h=1&g>>>30,p.__setDigit(w,1073741823&g)}return p.__trim()}},{key:"__absoluteAddOne",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length;m===null?m=new S(y,c):m.sign=c;for(var p,h=1,w=0;w<y;w++)p=a.__digit(w)+h,h=p>>>30,m.__setDigit(w,1073741823&p);return h!==0&&m.__setDigitGrow(y,1),m}},{key:"__absoluteSubOne",value:function(a,c){var m=a.length;c=c||m;for(var y,p=new S(c,!1),h=1,w=0;w<m;w++)y=a.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);if(h!==0)throw new Error("implementation bug");for(var g=m;g<c;g++)p.__setDigit(g,0);return p}},{key:"__absoluteAnd",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=h;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)&c.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteAndNot",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;y<p&&(h=y);var w=y;m===null?m=new S(w,!1):w=m.length;for(var g=0;g<h;g++)m.__setDigit(g,a.__digit(g)&~c.__digit(g));for(;g<y;g++)m.__setDigit(g,a.__digit(g));for(;g<w;g++)m.__setDigit(g,0);return m}},{key:"__absoluteOr",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)|c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteXor",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)^c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteCompare",value:function(a,c){var m=a.length-c.length;if(m!=0)return m;for(var y=a.length-1;0<=y&&a.__digit(y)===c.__digit(y);)y--;return 0>y?0:a.__unsignedDigit(y)>c.__unsignedDigit(y)?1:-1}},{key:"__multiplyAccumulate",value:function(a,c,m,y){if(c!==0){for(var p=32767&c,h=c>>>15,w=0,g=0,f=0;f<a.length;f++,y++){var v=m.__digit(y),O=a.__digit(f),M=32767&O,R=O>>>15,B=S.__imul(M,p),G=S.__imul(M,h),Z=S.__imul(R,p),oe=S.__imul(R,h);v+=g+B+w,w=v>>>30,v&=1073741823,v+=((32767&G)<<15)+((32767&Z)<<15),w+=v>>>30,g=oe+(G>>>15)+(Z>>>15),m.__setDigit(y,1073741823&v)}for(;w!==0||g!==0;y++){var te=m.__digit(y);te+=w+g,g=0,w=te>>>30,m.__setDigit(y,1073741823&te)}}}},{key:"__internalMultiplyAdd",value:function(a,c,m,y,p){for(var h=m,w=0,g=0;g<y;g++){var f=a.__digit(g),v=S.__imul(32767&f,c),O=S.__imul(f>>>15,c),M=v+((32767&O)<<15)+w+h;h=M>>>30,w=O>>>15,p.__setDigit(g,1073741823&M)}if(p.length>y)for(p.__setDigit(y++,h+w);y<p.length;)p.__setDigit(y++,0);else if(h+w!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;m===null&&(m=new S(a.length,!1));for(var y=0,p=2*a.length-1;0<=p;p-=2){var h=(y<<15|a.__halfDigit(p))>>>0,w=0|h/c;y=0|h%c,h=(y<<15|a.__halfDigit(p-1))>>>0;var g=0|h/c;y=0|h%c,m.__setDigit(p>>>1,w<<15|g)}return m}},{key:"__absoluteModSmall",value:function(a,c){for(var m,y=0,p=2*a.length-1;0<=p;p--)m=(y<<15|a.__halfDigit(p))>>>0,y=0|m%c;return y}},{key:"__absoluteDivLarge",value:function(a,c,m,y){var p=c.__halfDigitLength(),h=c.length,w=a.__halfDigitLength()-p,g=null;m&&(g=new S(w+2>>>1,!1),g.__initializeDigits());var f=new S(p+2>>>1,!1);f.__initializeDigits();var v=S.__clz15(c.__halfDigit(p-1));0<v&&(c=S.__specialLeftShift(c,v,0));for(var O=S.__specialLeftShift(a,v,1),M=c.__halfDigit(p-1),R=0,B=w;0<=B;B--){var G=32767,Z=O.__halfDigit(B+p);if(Z!==M){var oe=(Z<<15|O.__halfDigit(B+p-1))>>>0;G=0|oe/M;for(var te=0|oe%M,ae=c.__halfDigit(p-2),dt=O.__halfDigit(B+p-2);S.__imul(G,ae)>>>0>(te<<16|dt)>>>0&&(G--,te+=M,!(32767<te)););}S.__internalMultiplyAdd(c,G,0,h,f);var ve=O.__inplaceSub(f,B,p+1);ve!==0&&(ve=O.__inplaceAdd(c,B,p),O.__setHalfDigit(B+p,32767&O.__halfDigit(B+p)+ve),G--),m&&(1&B?R=G<<15:g.__setDigit(B>>>1,R|G))}if(y)return O.__inplaceRightShift(v),m?{quotient:g,remainder:O}:O;if(m)return g;throw new Error("unreachable")}},{key:"__clz15",value:function(a){return S.__clz30(a)-15}},{key:"__specialLeftShift",value:function(a,c,m){var y=a.length,p=new S(y+m,!1);if(c===0){for(var h=0;h<y;h++)p.__setDigit(h,a.__digit(h));return 0<m&&p.__setDigit(y,0),p}for(var w,g=0,f=0;f<y;f++)w=a.__digit(f),p.__setDigit(f,1073741823&w<<c|g),g=w>>>30-c;return 0<m&&p.__setDigit(y,g),p}},{key:"__leftShiftByAbsolute",value:function(a,c){var m=S.__toShiftAmount(c);if(0>m)throw new RangeError("BigInt too big");var y=0|m/30,p=m%30,h=a.length,w=p!==0&&a.__digit(h-1)>>>30-p!=0,g=h+y+(w?1:0),f=new S(g,a.sign);if(p===0){for(var v=0;v<y;v++)f.__setDigit(v,0);for(;v<g;v++)f.__setDigit(v,a.__digit(v-y))}else{for(var O=0,M=0;M<y;M++)f.__setDigit(M,0);for(var R,B=0;B<h;B++)R=a.__digit(B),f.__setDigit(B+y,1073741823&R<<p|O),O=R>>>30-p;if(w)f.__setDigit(h+y,O);else if(O!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(a,c){var m=a.length,y=a.sign,p=S.__toShiftAmount(c);if(0>p)return S.__rightShiftByMaximum(y);var h=0|p/30,w=p%30,g=m-h;if(0>=g)return S.__rightShiftByMaximum(y);var f=!1;if(y){if(a.__digit(h)&(1<<w)-1)f=!0;else for(var v=0;v<h;v++)if(a.__digit(v)!==0){f=!0;break}}if(f&&w===0){var O=a.__digit(m-1);!~O&&g++}var M=new S(g,y);if(w===0){M.__setDigit(g-1,0);for(var R=h;R<m;R++)M.__setDigit(R-h,a.__digit(R))}else{for(var B,G=a.__digit(h)>>>w,Z=m-h-1,oe=0;oe<Z;oe++)B=a.__digit(oe+h+1),M.__setDigit(oe,1073741823&B<<30-w|G),G=B>>>w;M.__setDigit(Z,G)}return f&&(M=S.__absoluteAddOne(M,!0,M)),M.__trim()}},{key:"__rightShiftByMaximum",value:function(a){return a?S.__oneDigit(1,!0):S.__zero()}},{key:"__toShiftAmount",value:function(a){if(1<a.length)return-1;var c=a.__unsignedDigit(0);return c>S.__kMaxLengthBits?-1:c}},{key:"__toPrimitive",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(r(a)!=="object"||a.constructor===S)return a;if(typeof Symbol<"u"&&r(Symbol.toPrimitive)==="symbol"){var m=a[Symbol.toPrimitive];if(m){var y=m(c);if(r(y)!=="object")return y;throw new TypeError("Cannot convert object to primitive value")}}var p=a.valueOf;if(p){var h=p.call(a);if(r(h)!=="object")return h}var w=a.toString;if(w){var g=w.call(a);if(r(g)!=="object")return g}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(a){return S.__isBigInt(a)?a:+a}},{key:"__isBigInt",value:function(a){return r(a)==="object"&&a!==null&&a.constructor===S}},{key:"__truncateToNBits",value:function(a,c){for(var m=0|(a+29)/30,y=new S(m,c.sign),p=m-1,h=0;h<p;h++)y.__setDigit(h,c.__digit(h));var w=c.__digit(p);if(a%30!=0){var g=32-a%30;w=w<<g>>>g}return y.__setDigit(p,w),y.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(a,c,m){for(var y=Math.min,p,h=0|(a+29)/30,w=new S(h,m),g=0,f=h-1,v=0,O=y(f,c.length);g<O;g++)p=0-c.__digit(g)-v,v=1&p>>>30,w.__setDigit(g,1073741823&p);for(;g<f;g++)w.__setDigit(g,0|1073741823&-v);var M,R=f<c.length?c.__digit(f):0,B=a%30;if(B===0)M=0-R-v,M&=1073741823;else{var G=32-B;R=R<<G>>>G;var Z=1<<32-G;M=Z-R-v,M&=Z-1}return w.__setDigit(f,M),w.__trim()}},{key:"__digitPow",value:function(a,c){for(var m=1;0<c;)1&c&&(m*=a),c>>>=1,a*=a;return m}},{key:"__isOneDigitInt",value:function(a){return(1073741823&a)===a}}]),S}(T(Array));return K.__kMaxLength=33554432,K.__kMaxLengthBits=K.__kMaxLength<<5,K.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],K.__kBitsPerCharTableShift=5,K.__kBitsPerCharTableMultiplier=1<<K.__kBitsPerCharTableShift,K.__kConversionChars=["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"],K.__kBitConversionBuffer=new ArrayBuffer(8),K.__kBitConversionDouble=new Float64Array(K.__kBitConversionBuffer),K.__kBitConversionInts=new Int32Array(K.__kBitConversionBuffer),K.__clz30=e?function(F){return e(F)-2}:function(F){var U=Math.LN2,N=Math.log;return F===0?30:0|29-(0|N(F>>>0)/U)},K.__imul=t||function(F,U){return 0|F*U},K})});var E_={};fc(E_,{AddressBookSDK:()=>cn,COIN_TYPE_ARG_REGEX:()=>Lu,Coin:()=>qi,CoinHelper:()=>Fi,CreateHelper:()=>un,DEV_API_URL:()=>Up,DEV_SYNCING_URL:()=>$p,ENV_CONFIGS:()=>zp,Formatter:()=>fr,HexToUint8Array:()=>ms,LOCAL_API_URL:()=>Ku,LOCAL_SYNCING_URL:()=>Ju,MAINNET_RPC_URL:()=>Zu,MSafeAccount:()=>sn,MSafeClient:()=>ks,MSafeEnv:()=>Lp,MSafeGlobals:()=>$i,PREV_API_URL:()=>Gp,PROD_API_URL:()=>Vp,SUI_COIN:()=>C_,SignatureVerifier:()=>$u,TESTNET_RPC_URL:()=>xs,Uint8ArrayToHex:()=>I_,addPrefix:()=>Uu,getAllCoins:()=>M_,getMSafeConfig:()=>Xu,getPublicKeyFromChain:()=>Gu,stringToBuffer:()=>ps});module.exports=pc(E_);var ir=require("@msafe/sui3-utils"),un=class{constructor(e,r){this.globals=e;this.pkHelper=r}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let r=await this.reduceCreationInfoToRawConfig(e);return new ir.MultiSigAccount(r).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,r){let n=ir.PublicKeySerde.de(r);if(!(0,ir.isSameAddress)(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let r=await this.validateCreateInfo(e),n=ir.SigningMessageHelper.createMSafeMessage(r),i=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,i.signature),r}async reduceCreationInfoToRawConfig(e){let r=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return r.forEach((n,i)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[i].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,i)=>({publicKey:r[i],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,r){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(i=>i.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((i,o)=>({address:i.address,weight:i.weight,...ir.PublicKeySerde.ser(n[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:r})}};var As=require("@msafe/sui3-utils");var mc=require("@msafe/sui3-utils"),cn=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let r=mc.SigningMessageHelper.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:r});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var zi=class{constructor(e){this.globals=e}async getMSafeByStatus(e,r){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:r})}async updateMSafeStatus(e,r){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:r})}};var ch=require("@msafe/sui3-utils"),lh=de(Wi(),1);var zn=require("@mysten/sui.js/utils"),wn=require("@mysten/sui.js/transactions"),Rt=de(we(),1);var Ks=8192;function Js(t){if(t.length<Ks)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=Ks){let n=t.slice(r,r+Ks);e+=String.fromCharCode(...n)}return btoa(e)}var Ag=require("@mysten/sui.js/keypairs/ed25519"),Ig=require("@mysten/sui.js/keypairs/secp256k1"),wr=de(we(),1),ct=de(we(),1);var ln=9e15,gr=1e9,Xs="0123456789abcdef",Zi="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ki="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ys={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ln,maxE:ln,crypto:!1},Ec,or,ie=!0,Xi="[DecimalError] ",mr=Xi+"Invalid argument: ",Pc=Xi+"Precision limit exceeded",Dc=Xi+"crypto unavailable",Bc="[object Decimal]",xt=Math.floor,ft=Math.pow,lm=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,dm=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,fm=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Nc=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,$t=1e7,re=7,hm=9007199254740991,pm=Zi.length-1,Qs=Ki.length-1,q={toStringTag:Bc};q.absoluteValue=q.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),J(t)};q.ceil=function(){return J(new this.constructor(this),this.e+1,2)};q.clampedTo=q.clamp=function(t,e){var r,n=this,i=n.constructor;if(t=new i(t),e=new i(e),!t.s||!e.s)return new i(NaN);if(t.gt(e))throw Error(mr+e);return r=n.cmp(t),r<0?t:n.cmp(e)>0?e:new i(n)};q.comparedTo=q.cmp=function(t){var e,r,n,i,o=this,s=o.d,u=(t=new o.constructor(t)).d,l=o.s,d=t.s;if(!s||!u)return!l||!d?NaN:l!==d?l:s===u?0:!s^l<0?1:-1;if(!s[0]||!u[0])return s[0]?l:u[0]?-d:0;if(l!==d)return l;if(o.e!==t.e)return o.e>t.e^l<0?1:-1;for(n=s.length,i=u.length,e=0,r=n<i?n:i;e<r;++e)if(s[e]!==u[e])return s[e]>u[e]^l<0?1:-1;return n===i?0:n>i^l<0?1:-1};q.cosine=q.cos=function(){var t,e,r=this,n=r.constructor;return r.d?r.d[0]?(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=mm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or==2||or==3?r.neg():r,t,e,!0)):new n(1):new n(NaN)};q.cubeRoot=q.cbrt=function(){var t,e,r,n,i,o,s,u,l,d,b=this,_=b.constructor;if(!b.isFinite()||b.isZero())return new _(b);for(ie=!1,o=b.s*ft(b.s*b,1/3),!o||Math.abs(o)==1/0?(r=gt(b.d),t=b.e,(o=(t-r.length+1)%3)&&(r+=o==1||o==-2?"0":"00"),o=ft(r,1/3),t=xt((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?r="5e"+t:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+t),n=new _(r),n.s=b.s):n=new _(o.toString()),s=(t=_.precision)+3;;)if(u=n,l=u.times(u).times(u),d=l.plus(b),n=Te(d.plus(b).times(u),d.plus(l),s+2,1),gt(u.d).slice(0,s)===(r=gt(n.d)).slice(0,s))if(r=r.slice(s-3,s+1),r=="9999"||!i&&r=="4999"){if(!i&&(J(u,t+1,0),u.times(u).times(u).eq(b))){n=u;break}s+=4,i=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(J(n,t+1,1),e=!n.times(n).times(n).eq(b));break}return ie=!0,J(n,t,_.rounding,e)};q.decimalPlaces=q.dp=function(){var t,e=this.d,r=NaN;if(e){if(t=e.length-1,r=(t-xt(this.e/re))*re,t=e[t],t)for(;t%10==0;t/=10)r--;r<0&&(r=0)}return r};q.dividedBy=q.div=function(t){return Te(this,new this.constructor(t))};q.dividedToIntegerBy=q.divToInt=function(t){var e=this,r=e.constructor;return J(Te(e,new r(t),0,1,1),r.precision,r.rounding)};q.equals=q.eq=function(t){return this.cmp(t)===0};q.floor=function(){return J(new this.constructor(this),this.e+1,3)};q.greaterThan=q.gt=function(t){return this.cmp(t)>0};q.greaterThanOrEqualTo=q.gte=function(t){var e=this.cmp(t);return e==1||e===0};q.hyperbolicCosine=q.cosh=function(){var t,e,r,n,i,o=this,s=o.constructor,u=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return u;r=s.precision,n=s.rounding,s.precision=r+Math.max(o.e,o.sd())+4,s.rounding=1,i=o.d.length,i<32?(t=Math.ceil(i/3),e=(1/Qi(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=dn(s,1,o.times(e),new s(1),!0);for(var l,d=t,b=new s(8);d--;)l=o.times(o),o=u.minus(l.times(b.minus(l.times(b))));return J(o,s.precision=r,s.rounding=n,!0)};q.hyperbolicSine=q.sinh=function(){var t,e,r,n,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(e=o.precision,r=o.rounding,o.precision=e+Math.max(i.e,i.sd())+4,o.rounding=1,n=i.d.length,n<3)i=dn(o,2,i,i,!0);else{t=1.4*Math.sqrt(n),t=t>16?16:t|0,i=i.times(1/Qi(5,t)),i=dn(o,2,i,i,!0);for(var s,u=new o(5),l=new o(16),d=new o(20);t--;)s=i.times(i),i=i.times(u.plus(s.times(l.times(s).plus(d))))}return o.precision=e,o.rounding=r,J(i,e,r,!0)};q.hyperbolicTangent=q.tanh=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+7,n.rounding=1,Te(r.sinh(),r.cosh(),n.precision=t,n.rounding=e)):new n(r.s)};q.inverseCosine=q.acos=function(){var t,e=this,r=e.constructor,n=e.abs().cmp(1),i=r.precision,o=r.rounding;return n!==-1?n===0?e.isNeg()?Ut(r,i,o):new r(0):new r(NaN):e.isZero()?Ut(r,i+4,o).times(.5):(r.precision=i+6,r.rounding=1,e=e.asin(),t=Ut(r,i+4,o).times(.5),r.precision=i,r.rounding=o,t.minus(e))};q.inverseHyperbolicCosine=q.acosh=function(){var t,e,r=this,n=r.constructor;return r.lte(1)?new n(r.eq(1)?0:NaN):r.isFinite()?(t=n.precision,e=n.rounding,n.precision=t+Math.max(Math.abs(r.e),r.sd())+4,n.rounding=1,ie=!1,r=r.times(r).minus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln()):new n(r)};q.inverseHyperbolicSine=q.asinh=function(){var t,e,r=this,n=r.constructor;return!r.isFinite()||r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+2*Math.max(Math.abs(r.e),r.sd())+6,n.rounding=1,ie=!1,r=r.times(r).plus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln())};q.inverseHyperbolicTangent=q.atanh=function(){var t,e,r,n,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(t=o.precision,e=o.rounding,n=i.sd(),Math.max(n,t)<2*-i.e-1?J(new o(i),t,e,!0):(o.precision=r=n-i.e,i=Te(i.plus(1),new o(1).minus(i),r+t,1),o.precision=t+4,o.rounding=1,i=i.ln(),o.precision=t,o.rounding=e,i.times(.5))):new o(NaN)};q.inverseSine=q.asin=function(){var t,e,r,n,i=this,o=i.constructor;return i.isZero()?new o(i):(e=i.abs().cmp(1),r=o.precision,n=o.rounding,e!==-1?e===0?(t=Ut(o,r+4,n).times(.5),t.s=i.s,t):new o(NaN):(o.precision=r+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=r,o.rounding=n,i.times(2)))};q.inverseTangent=q.atan=function(){var t,e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding;if(d.isFinite()){if(d.isZero())return new b(d);if(d.abs().eq(1)&&_+4<=Qs)return s=Ut(b,_+4,T).times(.25),s.s=d.s,s}else{if(!d.s)return new b(NaN);if(_+4<=Qs)return s=Ut(b,_+4,T).times(.5),s.s=d.s,s}for(b.precision=u=_+10,b.rounding=1,r=Math.min(28,u/re+2|0),t=r;t;--t)d=d.div(d.times(d).plus(1).sqrt().plus(1));for(ie=!1,e=Math.ceil(u/re),n=1,l=d.times(d),s=new b(d),i=d;t!==-1;)if(i=i.times(l),o=s.minus(i.div(n+=2)),i=i.times(l),s=o.plus(i.div(n+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return r&&(s=s.times(2<<r-1)),ie=!0,J(s,b.precision=_,b.rounding=T,!0)};q.isFinite=function(){return!!this.d};q.isInteger=q.isInt=function(){return!!this.d&&xt(this.e/re)>this.d.length-2};q.isNaN=function(){return!this.s};q.isNegative=q.isNeg=function(){return this.s<0};q.isPositive=q.isPos=function(){return this.s>0};q.isZero=function(){return!!this.d&&this.d[0]===0};q.lessThan=q.lt=function(t){return this.cmp(t)<0};q.lessThanOrEqualTo=q.lte=function(t){return this.cmp(t)<1};q.logarithm=q.log=function(t){var e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding,x=5;if(t==null)t=new b(10),e=!0;else{if(t=new b(t),r=t.d,t.s<0||!r||!r[0]||t.eq(1))return new b(NaN);e=t.eq(10)}if(r=d.d,d.s<0||!r||!r[0]||d.eq(1))return new b(r&&!r[0]?-1/0:d.s!=1?NaN:r?0:1/0);if(e)if(r.length>1)o=!0;else{for(i=r[0];i%10===0;)i/=10;o=i!==1}if(ie=!1,u=_+x,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),$n(l.d,i=_,T))do if(u+=10,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),!o){+gt(l.d).slice(i+1,i+15)+1==1e14&&(l=J(l,_+1,0));break}while($n(l.d,i+=10,T));return ie=!0,J(l,_,T)};q.minus=q.sub=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.constructor;if(t=new A(t),!x.d||!t.d)return!x.s||!t.s?t=new A(NaN):x.d?t.s=-t.s:t=new A(t.d||x.s!==t.s?x:NaN),t;if(x.s!=t.s)return t.s=-t.s,x.plus(t);if(d=x.d,T=t.d,u=A.precision,l=A.rounding,!d[0]||!T[0]){if(T[0])t.s=-t.s;else if(d[0])t=new A(x);else return new A(l===3?-0:0);return ie?J(t,u,l):t}if(r=xt(t.e/re),b=xt(x.e/re),d=d.slice(),o=b-r,o){for(_=o<0,_?(e=d,o=-o,s=T.length):(e=T,r=b,s=d.length),n=Math.max(Math.ceil(u/re),s)+2,o>n&&(o=n,e.length=1),e.reverse(),n=o;n--;)e.push(0);e.reverse()}else{for(n=d.length,s=T.length,_=n<s,_&&(s=n),n=0;n<s;n++)if(d[n]!=T[n]){_=d[n]<T[n];break}o=0}for(_&&(e=d,d=T,T=e,t.s=-t.s),s=d.length,n=T.length-s;n>0;--n)d[s++]=0;for(n=T.length;n>o;){if(d[--n]<T[n]){for(i=n;i&&d[--i]===0;)d[i]=$t-1;--d[i],d[n]+=$t}d[n]-=T[n]}for(;d[--s]===0;)d.pop();for(;d[0]===0;d.shift())--r;return d[0]?(t.d=d,t.e=Yi(d,r),ie?J(t,u,l):t):new A(l===3?-0:0)};q.modulo=q.mod=function(t){var e,r=this,n=r.constructor;return t=new n(t),!r.d||!t.s||t.d&&!t.d[0]?new n(NaN):!t.d||r.d&&!r.d[0]?J(new n(r),n.precision,n.rounding):(ie=!1,n.modulo==9?(e=Te(r,t.abs(),0,3,1),e.s*=t.s):e=Te(r,t,0,n.modulo,1),e=e.times(t),ie=!0,r.minus(e))};q.naturalExponential=q.exp=function(){return ea(this)};q.naturalLogarithm=q.ln=function(){return pr(this)};q.negated=q.neg=function(){var t=new this.constructor(this);return t.s=-t.s,J(t)};q.plus=q.add=function(t){var e,r,n,i,o,s,u,l,d,b,_=this,T=_.constructor;if(t=new T(t),!_.d||!t.d)return!_.s||!t.s?t=new T(NaN):_.d||(t=new T(t.d||_.s===t.s?_:NaN)),t;if(_.s!=t.s)return t.s=-t.s,_.minus(t);if(d=_.d,b=t.d,u=T.precision,l=T.rounding,!d[0]||!b[0])return b[0]||(t=new T(_)),ie?J(t,u,l):t;if(o=xt(_.e/re),n=xt(t.e/re),d=d.slice(),i=o-n,i){for(i<0?(r=d,i=-i,s=b.length):(r=b,n=o,s=d.length),o=Math.ceil(u/re),s=o>s?o+1:s+1,i>s&&(i=s,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(s=d.length,i=b.length,s-i<0&&(i=s,r=b,b=d,d=r),e=0;i;)e=(d[--i]=d[i]+b[i]+e)/$t|0,d[i]%=$t;for(e&&(d.unshift(e),++n),s=d.length;d[--s]==0;)d.pop();return t.d=d,t.e=Yi(d,n),ie?J(t,u,l):t};q.precision=q.sd=function(t){var e,r=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(mr+t);return r.d?(e=Rc(r.d),t&&r.e+1>e&&(e=r.e+1)):e=NaN,e};q.round=function(){var t=this,e=t.constructor;return J(new e(t),t.e+1,e.rounding)};q.sine=q.sin=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=wm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or>2?r.neg():r,t,e,!0)):new n(NaN)};q.squareRoot=q.sqrt=function(){var t,e,r,n,i,o,s=this,u=s.d,l=s.e,d=s.s,b=s.constructor;if(d!==1||!u||!u[0])return new b(!d||d<0&&(!u||u[0])?NaN:u?s:1/0);for(ie=!1,d=Math.sqrt(+s),d==0||d==1/0?(e=gt(u),(e.length+l)%2==0&&(e+="0"),d=Math.sqrt(e),l=xt((l+1)/2)-(l<0||l%2),d==1/0?e="5e"+l:(e=d.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),n=new b(e)):n=new b(d.toString()),r=(l=b.precision)+3;;)if(o=n,n=o.plus(Te(s,o,r+2,1)).times(.5),gt(o.d).slice(0,r)===(e=gt(n.d)).slice(0,r))if(e=e.slice(r-3,r+1),e=="9999"||!i&&e=="4999"){if(!i&&(J(o,l+1,0),o.times(o).eq(s))){n=o;break}r+=4,i=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(J(n,l+1,1),t=!n.times(n).eq(s));break}return ie=!0,J(n,l,b.rounding,t)};q.tangent=q.tan=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+10,n.rounding=1,r=r.sin(),r.s=1,r=Te(r,new n(1).minus(r.times(r)).sqrt(),t+10,0),n.precision=t,n.rounding=e,J(or==2||or==4?r.neg():r,t,e,!0)):new n(NaN)};q.times=q.mul=function(t){var e,r,n,i,o,s,u,l,d,b=this,_=b.constructor,T=b.d,x=(t=new _(t)).d;if(t.s*=b.s,!T||!T[0]||!x||!x[0])return new _(!t.s||T&&!T[0]&&!x||x&&!x[0]&&!T?NaN:!T||!x?t.s/0:t.s*0);for(r=xt(b.e/re)+xt(t.e/re),l=T.length,d=x.length,l<d&&(o=T,T=x,x=o,s=l,l=d,d=s),o=[],s=l+d,n=s;n--;)o.push(0);for(n=d;--n>=0;){for(e=0,i=l+n;i>n;)u=o[i]+x[n]*T[i-n-1]+e,o[i--]=u%$t|0,e=u/$t|0;o[i]=(o[i]+e)%$t|0}for(;!o[--s];)o.pop();return e?++r:o.shift(),t.d=o,t.e=Yi(o,r),ie?J(t,_.precision,_.rounding):t};q.toBinary=function(t,e){return ra(this,2,t,e)};q.toDecimalPlaces=q.toDP=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(Ct(t,0,gr),e===void 0?e=n.rounding:Ct(e,0,8),J(r,t+r.e+1,e))};q.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,!0):(Ct(t,0,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t+1,e),r=Yt(n,!0,t+1)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?r=Yt(i):(Ct(t,0,gr),e===void 0?e=o.rounding:Ct(e,0,8),n=J(new o(i),t+i.e+1,e),r=Yt(n,!1,t+n.e+1)),i.isNeg()&&!i.isZero()?"-"+r:r};q.toFraction=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.d,I=x.constructor;if(!A)return new I(x);if(d=r=new I(1),n=l=new I(0),e=new I(n),o=e.e=Rc(A)-x.e-1,s=o%re,e.d[0]=ft(10,s<0?re+s:s),t==null)t=o>0?e:d;else{if(u=new I(t),!u.isInt()||u.lt(d))throw Error(mr+u);t=u.gt(e)?o>0?e:d:u}for(ie=!1,u=new I(gt(A)),b=I.precision,I.precision=o=A.length*re*2;_=Te(u,e,0,1,1),i=r.plus(_.times(n)),i.cmp(t)!=1;)r=n,n=i,i=d,d=l.plus(_.times(i)),l=i,i=e,e=u.minus(_.times(i)),u=i;return i=Te(t.minus(r),n,0,1,1),l=l.plus(i.times(d)),r=r.plus(i.times(n)),l.s=d.s=x.s,T=Te(d,n,o,1).minus(x).abs().cmp(Te(l,r,o,1).minus(x).abs())<1?[d,n]:[l,r],I.precision=b,ie=!0,T};q.toHexadecimal=q.toHex=function(t,e){return ra(this,16,t,e)};q.toNearest=function(t,e){var r=this,n=r.constructor;if(r=new n(r),t==null){if(!r.d)return r;t=new n(1),e=n.rounding}else{if(t=new n(t),e===void 0?e=n.rounding:Ct(e,0,8),!r.d)return t.s?r:t;if(!t.d)return t.s&&(t.s=r.s),t}return t.d[0]?(ie=!1,r=Te(r,t,0,e,1).times(t),ie=!0,J(r)):(t.s=r.s,r=t),r};q.toNumber=function(){return+this};q.toOctal=function(t,e){return ra(this,8,t,e)};q.toPower=q.pow=function(t){var e,r,n,i,o,s,u=this,l=u.constructor,d=+(t=new l(t));if(!u.d||!t.d||!u.d[0]||!t.d[0])return new l(ft(+u,d));if(u=new l(u),u.eq(1))return u;if(n=l.precision,o=l.rounding,t.eq(1))return J(u,n,o);if(e=xt(t.e/re),e>=t.d.length-1&&(r=d<0?-d:d)<=hm)return i=jc(l,u,r,n),t.s<0?new l(1).div(i):J(i,n,o);if(s=u.s,s<0){if(e<t.d.length-1)return new l(NaN);if(t.d[e]&1||(s=1),u.e==0&&u.d[0]==1&&u.d.length==1)return u.s=s,u}return r=ft(+u,d),e=r==0||!isFinite(r)?xt(d*(Math.log("0."+gt(u.d))/Math.LN10+u.e+1)):new l(r+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(ie=!1,l.rounding=u.s=1,r=Math.min(12,(e+"").length),i=ea(t.times(pr(u,n+r)),n),i.d&&(i=J(i,n+5,1),$n(i.d,n,o)&&(e=n+10,i=J(ea(t.times(pr(u,e+r)),e),e+5,1),+gt(i.d).slice(n+1,n+15)+1==1e14&&(i=J(i,n+1,0)))),i.s=s,ie=!0,l.rounding=o,J(i,n,o))};q.toPrecision=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,n.e<=i.toExpNeg||n.e>=i.toExpPos):(Ct(t,1,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t,e),r=Yt(n,t<=n.e||n.e<=i.toExpNeg,t)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toSignificantDigits=q.toSD=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(Ct(t,1,gr),e===void 0?e=n.rounding:Ct(e,0,8)),J(new n(r),t,e)};q.toString=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+r:r};q.truncated=q.trunc=function(){return J(new this.constructor(this),this.e+1,1)};q.valueOf=q.toJSON=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+r:r};function gt(t){var e,r,n,i=t.length-1,o="",s=t[0];if(i>0){for(o+=s,e=1;e<i;e++)n=t[e]+"",r=re-n.length,r&&(o+=hr(r)),o+=n;s=t[e],n=s+"",r=re-n.length,r&&(o+=hr(r))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Ct(t,e,r){if(t!==~~t||t<e||t>r)throw Error(mr+t)}function $n(t,e,r,n){var i,o,s,u;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=re,i=0):(i=Math.ceil((e+1)/re),e%=re),o=ft(10,re-e),u=t[i]%o|0,n==null?e<3?(e==0?u=u/100|0:e==1&&(u=u/10|0),s=r<4&&u==99999||r>3&&u==49999||u==5e4||u==0):s=(r<4&&u+1==o||r>3&&u+1==o/2)&&(t[i+1]/o/100|0)==ft(10,e-2)-1||(u==o/2||u==0)&&(t[i+1]/o/100|0)==0:e<4?(e==0?u=u/1e3|0:e==1?u=u/100|0:e==2&&(u=u/10|0),s=(n||r<4)&&u==9999||!n&&r>3&&u==4999):s=((n||r<4)&&u+1==o||!n&&r>3&&u+1==o/2)&&(t[i+1]/o/1e3|0)==ft(10,e-3)-1,s}function Hi(t,e,r){for(var n,i=[0],o,s=0,u=t.length;s<u;){for(o=i.length;o--;)i[o]*=e;for(i[0]+=Xs.indexOf(t.charAt(s++)),n=0;n<i.length;n++)i[n]>r-1&&(i[n+1]===void 0&&(i[n+1]=0),i[n+1]+=i[n]/r|0,i[n]%=r)}return i.reverse()}function mm(t,e){var r,n,i;if(e.isZero())return e;n=e.d.length,n<32?(r=Math.ceil(n/3),i=(1/Qi(4,r)).toString()):(r=16,i="2.3283064365386962890625e-10"),t.precision+=r,e=dn(t,1,e.times(i),new t(1));for(var o=r;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=r,e}var Te=function(){function t(n,i,o){var s,u=0,l=n.length;for(n=n.slice();l--;)s=n[l]*i+u,n[l]=s%o|0,u=s/o|0;return u&&n.unshift(u),n}function e(n,i,o,s){var u,l;if(o!=s)l=o>s?1:-1;else for(u=l=0;u<o;u++)if(n[u]!=i[u]){l=n[u]>i[u]?1:-1;break}return l}function r(n,i,o,s){for(var u=0;o--;)n[o]-=u,u=n[o]<i[o]?1:0,n[o]=u*s+n[o]-i[o];for(;!n[0]&&n.length>1;)n.shift()}return function(n,i,o,s,u,l){var d,b,_,T,x,A,I,C,E,P,D,L,H,W,K,F,U,N,j,S,k=n.constructor,a=n.s==i.s?1:-1,c=n.d,m=i.d;if(!c||!c[0]||!m||!m[0])return new k(!n.s||!i.s||(c?m&&c[0]==m[0]:!m)?NaN:c&&c[0]==0||!m?a*0:a/0);for(l?(x=1,b=n.e-i.e):(l=$t,x=re,b=xt(n.e/x)-xt(i.e/x)),j=m.length,U=c.length,E=new k(a),P=E.d=[],_=0;m[_]==(c[_]||0);_++);if(m[_]>(c[_]||0)&&b--,o==null?(W=o=k.precision,s=k.rounding):u?W=o+(n.e-i.e)+1:W=o,W<0)P.push(1),A=!0;else{if(W=W/x+2|0,_=0,j==1){for(T=0,m=m[0],W++;(_<U||T)&&W--;_++)K=T*l+(c[_]||0),P[_]=K/m|0,T=K%m|0;A=T||_<U}else{for(T=l/(m[0]+1)|0,T>1&&(m=t(m,T,l),c=t(c,T,l),j=m.length,U=c.length),F=j,D=c.slice(0,j),L=D.length;L<j;)D[L++]=0;S=m.slice(),S.unshift(0),N=m[0],m[1]>=l/2&&++N;do T=0,d=e(m,D,j,L),d<0?(H=D[0],j!=L&&(H=H*l+(D[1]||0)),T=H/N|0,T>1?(T>=l&&(T=l-1),I=t(m,T,l),C=I.length,L=D.length,d=e(I,D,C,L),d==1&&(T--,r(I,j<C?S:m,C,l))):(T==0&&(d=T=1),I=m.slice()),C=I.length,C<L&&I.unshift(0),r(D,I,L,l),d==-1&&(L=D.length,d=e(m,D,j,L),d<1&&(T++,r(D,j<L?S:m,L,l))),L=D.length):d===0&&(T++,D=[0]),P[_++]=T,d&&D[0]?D[L++]=c[F]||0:(D=[c[F]],L=1);while((F++<U||D[0]!==void 0)&&W--);A=D[0]!==void 0}P[0]||P.shift()}if(x==1)E.e=b,Ec=A;else{for(_=1,T=P[0];T>=10;T/=10)_++;E.e=_+b*x-1,J(E,u?o+E.e+1:o,s,A)}return E}}();function J(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor;e:if(e!=null){if(_=t.d,!_)return t;for(i=1,u=_[0];u>=10;u/=10)i++;if(o=e-i,o<0)o+=re,s=e,b=_[T=0],l=b/ft(10,i-s-1)%10|0;else if(T=Math.ceil((o+1)/re),u=_.length,T>=u)if(n){for(;u++<=T;)_.push(0);b=l=0,i=1,o%=re,s=o-re+1}else break e;else{for(b=u=_[T],i=1;u>=10;u/=10)i++;o%=re,s=o-re+i,l=s<0?0:b/ft(10,i-s-1)%10|0}if(n=n||e<0||_[T+1]!==void 0||(s<0?b:b%ft(10,i-s-1)),d=r<4?(l||n)&&(r==0||r==(t.s<0?3:2)):l>5||l==5&&(r==4||n||r==6&&(o>0?s>0?b/ft(10,i-s):0:_[T-1])%10&1||r==(t.s<0?8:7)),e<1||!_[0])return _.length=0,d?(e-=t.e+1,_[0]=ft(10,(re-e%re)%re),t.e=-e||0):_[0]=t.e=0,t;if(o==0?(_.length=T,u=1,T--):(_.length=T+1,u=ft(10,re-o),_[T]=s>0?(b/ft(10,i-s)%ft(10,s)|0)*u:0),d)for(;;)if(T==0){for(o=1,s=_[0];s>=10;s/=10)o++;for(s=_[0]+=u,u=1;s>=10;s/=10)u++;o!=u&&(t.e++,_[0]==$t&&(_[0]=1));break}else{if(_[T]+=u,_[T]!=$t)break;_[T--]=0,u=1}for(o=_.length;_[--o]===0;)_.pop()}return ie&&(t.e>x.maxE?(t.d=null,t.e=NaN):t.e<x.minE&&(t.e=0,t.d=[0])),t}function Yt(t,e,r){if(!t.isFinite())return qc(t);var n,i=t.e,o=gt(t.d),s=o.length;return e?(r&&(n=r-s)>0?o=o.charAt(0)+"."+o.slice(1)+hr(n):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):i<0?(o="0."+hr(-i-1)+o,r&&(n=r-s)>0&&(o+=hr(n))):i>=s?(o+=hr(i+1-s),r&&(n=r-i-1)>0&&(o=o+"."+hr(n))):((n=i+1)<s&&(o=o.slice(0,n)+"."+o.slice(n)),r&&(n=r-s)>0&&(i+1===s&&(o+="."),o+=hr(n))),o}function Yi(t,e){var r=t[0];for(e*=re;r>=10;r/=10)e++;return e}function Ji(t,e,r){if(e>pm)throw ie=!0,r&&(t.precision=r),Error(Pc);return J(new t(Zi),e,1,!0)}function Ut(t,e,r){if(e>Qs)throw Error(Pc);return J(new t(Ki),e,r,!0)}function Rc(t){var e=t.length-1,r=e*re+1;if(e=t[e],e){for(;e%10==0;e/=10)r--;for(e=t[0];e>=10;e/=10)r++}return r}function hr(t){for(var e="";t--;)e+="0";return e}function jc(t,e,r,n){var i,o=new t(1),s=Math.ceil(n/re+4);for(ie=!1;;){if(r%2&&(o=o.times(e),Oc(o.d,s)&&(i=!0)),r=xt(r/2),r===0){r=o.d.length-1,i&&o.d[r]===0&&++o.d[r];break}e=e.times(e),Oc(e.d,s)}return ie=!0,o}function Cc(t){return t.d[t.d.length-1]&1}function Fc(t,e,r){for(var n,i=new t(e[0]),o=0;++o<e.length;)if(n=new t(e[o]),n.s)i[r](n)&&(i=n);else{i=n;break}return i}function ea(t,e){var r,n,i,o,s,u,l,d=0,b=0,_=0,T=t.constructor,x=T.rounding,A=T.precision;if(!t.d||!t.d[0]||t.e>17)return new T(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(ie=!1,l=A):l=e,u=new T(.03125);t.e>-2;)t=t.times(u),_+=5;for(n=Math.log(ft(2,_))/Math.LN10*2+5|0,l+=n,r=o=s=new T(1),T.precision=l;;){if(o=J(o.times(t),l,1),r=r.times(++b),u=s.plus(Te(o,r,l,1)),gt(u.d).slice(0,l)===gt(s.d).slice(0,l)){for(i=_;i--;)s=J(s.times(s),l,1);if(e==null)if(d<3&&$n(s.d,l-n,x,d))T.precision=l+=10,r=o=u=new T(1),b=0,d++;else return J(s,T.precision=A,x,ie=!0);else return T.precision=A,s}s=u}}function pr(t,e){var r,n,i,o,s,u,l,d,b,_,T,x=1,A=10,I=t,C=I.d,E=I.constructor,P=E.rounding,D=E.precision;if(I.s<0||!C||!C[0]||!I.e&&C[0]==1&&C.length==1)return new E(C&&!C[0]?-1/0:I.s!=1?NaN:C?0:I);if(e==null?(ie=!1,b=D):b=e,E.precision=b+=A,r=gt(C),n=r.charAt(0),Math.abs(o=I.e)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)I=I.times(t),r=gt(I.d),n=r.charAt(0),x++;o=I.e,n>1?(I=new E("0."+r),o++):I=new E(n+"."+r.slice(1))}else return d=Ji(E,b+2,D).times(o+""),I=pr(new E(n+"."+r.slice(1)),b-A).plus(d),E.precision=D,e==null?J(I,D,P,ie=!0):I;for(_=I,l=s=I=Te(I.minus(1),I.plus(1),b,1),T=J(I.times(I),b,1),i=3;;){if(s=J(s.times(T),b,1),d=l.plus(Te(s,new E(i),b,1)),gt(d.d).slice(0,b)===gt(l.d).slice(0,b))if(l=l.times(2),o!==0&&(l=l.plus(Ji(E,b+2,D).times(o+""))),l=Te(l,new E(x),b,1),e==null)if($n(l.d,b-A,P,u))E.precision=b+=A,d=s=I=Te(_.minus(1),_.plus(1),b,1),T=J(I.times(I),b,1),i=u=1;else return J(l,E.precision=D,P,ie=!0);else return E.precision=D,l;l=d,i+=2}}function qc(t){return String(t.s*t.s/0)}function ta(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;n++);for(i=e.length;e.charCodeAt(i-1)===48;--i);if(e=e.slice(n,i),e){if(i-=n,t.e=r=r-n-1,t.d=[],n=(r+1)%re,r<0&&(n+=re),n<i){for(n&&t.d.push(+e.slice(0,n)),i-=re;n<i;)t.d.push(+e.slice(n,n+=re));e=e.slice(n),n=re-e.length}else n-=i;for(;n--;)e+="0";t.d.push(+e),ie&&(t.e>t.constructor.maxE?(t.d=null,t.e=NaN):t.e<t.constructor.minE&&(t.e=0,t.d=[0]))}else t.e=0,t.d=[0];return t}function gm(t,e){var r,n,i,o,s,u,l,d,b;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Nc.test(e))return ta(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(dm.test(e))r=16,e=e.toLowerCase();else if(lm.test(e))r=2;else if(fm.test(e))r=8;else throw Error(mr+e);for(o=e.search(/p/i),o>0?(l=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,n=t.constructor,s&&(e=e.replace(".",""),u=e.length,o=u-o,i=jc(n,new n(r),o,o*2)),d=Hi(e,r,$t),b=d.length-1,o=b;d[o]===0;--o)d.pop();return o<0?new n(t.s*0):(t.e=Yi(d,b),t.d=d,ie=!1,s&&(t=Te(t,i,u*4)),l&&(t=t.times(Math.abs(l)<54?ft(2,l):Gn.pow(2,l))),ie=!0,t)}function wm(t,e){var r,n=e.d.length;if(n<3)return e.isZero()?e:dn(t,2,e,e);r=1.4*Math.sqrt(n),r=r>16?16:r|0,e=e.times(1/Qi(5,r)),e=dn(t,2,e,e);for(var i,o=new t(5),s=new t(16),u=new t(20);r--;)i=e.times(e),e=e.times(o.plus(i.times(s.times(i).minus(u))));return e}function dn(t,e,r,n,i){var o,s,u,l,d=1,b=t.precision,_=Math.ceil(b/re);for(ie=!1,l=r.times(r),u=new t(n);;){if(s=Te(u.times(l),new t(e++*e++),b,1),u=i?n.plus(s):n.minus(s),n=Te(s.times(l),new t(e++*e++),b,1),s=u.plus(n),s.d[_]!==void 0){for(o=_;s.d[o]===u.d[o]&&o--;);if(o==-1)break}o=u,u=n,n=s,s=o,d++}return ie=!0,s.d.length=_+1,s}function Qi(t,e){for(var r=t;--e;)r*=t;return r}function Lc(t,e){var r,n=e.s<0,i=Ut(t,t.precision,1),o=i.times(.5);if(e=e.abs(),e.lte(o))return or=n?4:1,e;if(r=e.divToInt(i),r.isZero())or=n?3:2;else{if(e=e.minus(r.times(i)),e.lte(o))return or=Cc(r)?n?2:3:n?4:1,e;or=Cc(r)?n?1:4:n?3:2}return e.minus(i).abs()}function ra(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor,A=r!==void 0;if(A?(Ct(r,1,gr),n===void 0?n=x.rounding:Ct(n,0,8)):(r=x.precision,n=x.rounding),!t.isFinite())b=qc(t);else{for(b=Yt(t),s=b.indexOf("."),A?(i=2,e==16?r=r*4-3:e==8&&(r=r*3-2)):i=e,s>=0&&(b=b.replace(".",""),T=new x(1),T.e=b.length-s,T.d=Hi(Yt(T),10,i),T.e=T.d.length),_=Hi(b,10,i),o=l=_.length;_[--l]==0;)_.pop();if(!_[0])b=A?"0p+0":"0";else{if(s<0?o--:(t=new x(t),t.d=_,t.e=o,t=Te(t,T,r,n,0,i),_=t.d,o=t.e,d=Ec),s=_[r],u=i/2,d=d||_[r+1]!==void 0,d=n<4?(s!==void 0||d)&&(n===0||n===(t.s<0?3:2)):s>u||s===u&&(n===4||d||n===6&&_[r-1]&1||n===(t.s<0?8:7)),_.length=r,d)for(;++_[--r]>i-1;)_[r]=0,r||(++o,_.unshift(1));for(l=_.length;!_[l-1];--l);for(s=0,b="";s<l;s++)b+=Xs.charAt(_[s]);if(A){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)b+="0";for(_=Hi(b,i,e),l=_.length;!_[l-1];--l);for(s=1,b="1.";s<l;s++)b+=Xs.charAt(_[s])}else b=b.charAt(0)+"."+b.slice(1);b=b+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)b="0"+b;b="0."+b}else if(++o>l)for(o-=l;o--;)b+="0";else o<l&&(b=b.slice(0,o)+"."+b.slice(o))}b=(e==16?"0x":e==2?"0b":e==8?"0o":"")+b}return t.s<0?"-"+b:b}function Oc(t,e){if(t.length>e)return t.length=e,!0}function ym(t){return new this(t).abs()}function bm(t){return new this(t).acos()}function _m(t){return new this(t).acosh()}function vm(t,e){return new this(t).plus(e)}function Tm(t){return new this(t).asin()}function Sm(t){return new this(t).asinh()}function xm(t){return new this(t).atan()}function km(t){return new this(t).atanh()}function Am(t,e){t=new this(t),e=new this(e);var r,n=this.precision,i=this.rounding,o=n+4;return!t.s||!e.s?r=new this(NaN):!t.d&&!e.d?(r=Ut(this,o,1).times(e.s>0?.25:.75),r.s=t.s):!e.d||t.isZero()?(r=e.s<0?Ut(this,n,i):new this(0),r.s=t.s):!t.d||e.isZero()?(r=Ut(this,o,1).times(.5),r.s=t.s):e.s<0?(this.precision=o,this.rounding=1,r=this.atan(Te(t,e,o,1)),e=Ut(this,o,1),this.precision=n,this.rounding=i,r=t.s<0?r.minus(e):r.plus(e)):r=this.atan(Te(t,e,o,1)),r}function Im(t){return new this(t).cbrt()}function Cm(t){return J(t=new this(t),t.e+1,2)}function Om(t,e,r){return new this(t).clamp(e,r)}function Mm(t){if(!t||typeof t!="object")throw Error(Xi+"Object expected");var e,r,n,i=t.defaults===!0,o=["precision",1,gr,"rounding",0,8,"toExpNeg",-ln,0,"toExpPos",0,ln,"maxE",0,ln,"minE",-ln,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(r=o[e],i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(xt(n)===n&&n>=o[e+1]&&n<=o[e+2])this[r]=n;else throw Error(mr+r+": "+n);if(r="crypto",i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[r]=!0;else throw Error(Dc);else this[r]=!1;else throw Error(mr+r+": "+n);return this}function Em(t){return new this(t).cos()}function Pm(t){return new this(t).cosh()}function Uc(t){var e,r,n;function i(o){var s,u,l,d=this;if(!(d instanceof i))return new i(o);if(d.constructor=i,Mc(o)){d.s=o.s,ie?!o.d||o.e>i.maxE?(d.e=NaN,d.d=null):o.e<i.minE?(d.e=0,d.d=[0]):(d.e=o.e,d.d=o.d.slice()):(d.e=o.e,d.d=o.d?o.d.slice():o.d);return}if(l=typeof o,l==="number"){if(o===0){d.s=1/o<0?-1:1,d.e=0,d.d=[0];return}if(o<0?(o=-o,d.s=-1):d.s=1,o===~~o&&o<1e7){for(s=0,u=o;u>=10;u/=10)s++;ie?s>i.maxE?(d.e=NaN,d.d=null):s<i.minE?(d.e=0,d.d=[0]):(d.e=s,d.d=[o]):(d.e=s,d.d=[o]);return}else if(o*0!==0){o||(d.s=NaN),d.e=NaN,d.d=null;return}return ta(d,o.toString())}else if(l!=="string")throw Error(mr+o);return(u=o.charCodeAt(0))===45?(o=o.slice(1),d.s=-1):(u===43&&(o=o.slice(1)),d.s=1),Nc.test(o)?ta(d,o):gm(d,o)}if(i.prototype=q,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Mm,i.clone=Uc,i.isDecimal=Mc,i.abs=ym,i.acos=bm,i.acosh=_m,i.add=vm,i.asin=Tm,i.asinh=Sm,i.atan=xm,i.atanh=km,i.atan2=Am,i.cbrt=Im,i.ceil=Cm,i.clamp=Om,i.cos=Em,i.cosh=Pm,i.div=Dm,i.exp=Bm,i.floor=Nm,i.hypot=Rm,i.ln=jm,i.log=Fm,i.log10=Lm,i.log2=qm,i.max=Um,i.min=$m,i.mod=Gm,i.mul=Vm,i.pow=zm,i.random=Wm,i.round=Hm,i.sign=Zm,i.sin=Km,i.sinh=Jm,i.sqrt=Xm,i.sub=Ym,i.sum=Qm,i.tan=eg,i.tanh=tg,i.trunc=rg,t===void 0&&(t={}),t&&t.defaults!==!0)for(n=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<n.length;)t.hasOwnProperty(r=n[e++])||(t[r]=this[r]);return i.config(t),i}function Dm(t,e){return new this(t).div(e)}function Bm(t){return new this(t).exp()}function Nm(t){return J(t=new this(t),t.e+1,3)}function Rm(){var t,e,r=new this(0);for(ie=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)r.d&&(r=r.plus(e.times(e)));else{if(e.s)return ie=!0,new this(1/0);r=e}return ie=!0,r.sqrt()}function Mc(t){return t instanceof Gn||t&&t.toStringTag===Bc||!1}function jm(t){return new this(t).ln()}function Fm(t,e){return new this(t).log(e)}function qm(t){return new this(t).log(2)}function Lm(t){return new this(t).log(10)}function Um(){return Fc(this,arguments,"lt")}function $m(){return Fc(this,arguments,"gt")}function Gm(t,e){return new this(t).mod(e)}function Vm(t,e){return new this(t).mul(e)}function zm(t,e){return new this(t).pow(e)}function Wm(t){var e,r,n,i,o=0,s=new this(1),u=[];if(t===void 0?t=this.precision:Ct(t,1,gr),n=Math.ceil(t/re),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(n));o<n;)i=e[o],i>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:u[o++]=i%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(n*=4);o<n;)i=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(e,o):(u.push(i%1e7),o+=4);o=n/4}else throw Error(Dc);else for(;o<n;)u[o++]=Math.random()*1e7|0;for(n=u[--o],t%=re,n&&t&&(i=ft(10,re-t),u[o]=(n/i|0)*i);u[o]===0;o--)u.pop();if(o<0)r=0,u=[0];else{for(r=-1;u[0]===0;r-=re)u.shift();for(n=1,i=u[0];i>=10;i/=10)n++;n<re&&(r-=re-n)}return s.e=r,s.d=u,s}function Hm(t){return J(t=new this(t),t.e+1,this.rounding)}function Zm(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function Km(t){return new this(t).sin()}function Jm(t){return new this(t).sinh()}function Xm(t){return new this(t).sqrt()}function Ym(t,e){return new this(t).sub(e)}function Qm(){var t=0,e=arguments,r=new this(e[t]);for(ie=!1;r.s&&++t<e.length;)r=r.plus(e[t]);return ie=!0,J(r,this.precision,this.rounding)}function eg(t){return new this(t).tan()}function tg(t){return new this(t).tanh()}function rg(t){return J(t=new this(t),t.e+1,1)}q[Symbol.for("nodejs.util.inspect.custom")]=q.toString;q[Symbol.toStringTag]="Decimal";var Gn=q.constructor=Uc(Ys);Zi=new Gn(Zi);Ki=new Gn(Ki);var $=Gn;var Ll=de(we(),1),Kn=de(we(),1);var ee=de(we(),1),ye=de(we(),1),Ul=de(we(),1),To=require("@mysten/sui.js/utils"),r0=de(we(),1),n0=de(we(),1),o0=de(we(),1);var qr=de(we(),1),Hn=de(we(),1);var Lr=require("@mysten/sui.js/transactions"),w0=require("@mysten/sui.js/utils"),y0=require("@mysten/sui.js/transactions"),bt=de(we(),1),po=require("@mysten/sui.js/transactions"),ga=de(we(),1),Ur=require("@mysten/sui.js/transactions"),Xl=require("@mysten/sui.js/utils"),Se=de(we(),1),mo=require("@mysten/sui.js/transactions"),Et=de(we(),1),Wr=de(hl(),1),Yl=require("@mysten/sui.js/transactions"),$r=de(we(),1);var wa=require("@mysten/sui.js/transactions");var bl="3.7.7",lg=bl,pn=typeof Buffer=="function",pl=typeof TextDecoder=="function"?new TextDecoder:void 0,ml=typeof TextEncoder=="function"?new TextEncoder:void 0,dg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Vn=Array.prototype.slice.call(dg),io=(t=>{let e={};return t.forEach((r,n)=>e[r]=n),e})(Vn),fg=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,wt=String.fromCharCode.bind(String),gl=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),_l=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),vl=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Tl=t=>{let e,r,n,i,o="",s=t.length%3;for(let u=0;u<t.length;){if((r=t.charCodeAt(u++))>255||(n=t.charCodeAt(u++))>255||(i=t.charCodeAt(u++))>255)throw new TypeError("invalid character found");e=r<<16|n<<8|i,o+=Vn[e>>18&63]+Vn[e>>12&63]+Vn[e>>6&63]+Vn[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},aa=typeof btoa=="function"?t=>btoa(t):pn?t=>Buffer.from(t,"binary").toString("base64"):Tl,oa=pn?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let n=0,i=t.length;n<i;n+=4096)r.push(wt.apply(null,t.subarray(n,n+4096)));return aa(r.join(""))},oo=(t,e=!1)=>e?_l(oa(t)):oa(t),hg=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?wt(192|e>>>6)+wt(128|e&63):wt(224|e>>>12&15)+wt(128|e>>>6&63)+wt(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return wt(240|e>>>18&7)+wt(128|e>>>12&63)+wt(128|e>>>6&63)+wt(128|e&63)}},pg=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Sl=t=>t.replace(pg,hg),wl=pn?t=>Buffer.from(t,"utf8").toString("base64"):ml?t=>oa(ml.encode(t)):t=>aa(Sl(t)),hn=(t,e=!1)=>e?_l(wl(t)):wl(t),yl=t=>hn(t,!0),mg=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,gg=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return wt((r>>>10)+55296)+wt((r&1023)+56320);case 3:return wt((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return wt((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},xl=t=>t.replace(mg,gg),kl=t=>{if(t=t.replace(/\s+/g,""),!fg.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r="",n,i;for(let o=0;o<t.length;)e=io[t.charAt(o++)]<<18|io[t.charAt(o++)]<<12|(n=io[t.charAt(o++)])<<6|(i=io[t.charAt(o++)]),r+=n===64?wt(e>>16&255):i===64?wt(e>>16&255,e>>8&255):wt(e>>16&255,e>>8&255,e&255);return r},ua=typeof atob=="function"?t=>atob(vl(t)):pn?t=>Buffer.from(t,"base64").toString("binary"):kl,Al=pn?t=>gl(Buffer.from(t,"base64")):t=>gl(ua(t).split("").map(e=>e.charCodeAt(0))),Il=t=>Al(Cl(t)),wg=pn?t=>Buffer.from(t,"base64").toString("utf8"):pl?t=>pl.decode(Al(t)):t=>xl(ua(t)),Cl=t=>vl(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),sa=t=>wg(Cl(t)),yg=t=>{if(typeof t!="string")return!1;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},Ol=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Ml=function(){let t=(e,r)=>Object.defineProperty(String.prototype,e,Ol(r));t("fromBase64",function(){return sa(this)}),t("toBase64",function(e){return hn(this,e)}),t("toBase64URI",function(){return hn(this,!0)}),t("toBase64URL",function(){return hn(this,!0)}),t("toUint8Array",function(){return Il(this)})},El=function(){let t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,Ol(r));t("toBase64",function(e){return oo(this,e)}),t("toBase64URI",function(){return oo(this,!0)}),t("toBase64URL",function(){return oo(this,!0)})},bg=()=>{Ml(),El()},mn={version:bl,VERSION:lg,atob:ua,atobPolyfill:kl,btoa:aa,btoaPolyfill:Tl,fromBase64:sa,toBase64:hn,encode:hn,encodeURI:yl,encodeURL:yl,utob:Sl,btou:xl,decode:sa,isValid:yg,fromUint8Array:oo,toUint8Array:Il,extendString:Ml,extendUint8Array:El,extendBuiltins:bg};var ya=require("@mysten/sui.js/transactions"),Ql=require("@mysten/sui.js/utils"),Gt=de(we(),1);var so,_g=new Uint8Array(16);function ca(){if(!so&&(so=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!so))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return so(_g)}var yt=[];for(let t=0;t<256;++t)yt.push((t+256).toString(16).slice(1));function Pl(t,e=0){return yt[t[e+0]]+yt[t[e+1]]+yt[t[e+2]]+yt[t[e+3]]+"-"+yt[t[e+4]]+yt[t[e+5]]+"-"+yt[t[e+6]]+yt[t[e+7]]+"-"+yt[t[e+8]]+yt[t[e+9]]+"-"+yt[t[e+10]]+yt[t[e+11]]+yt[t[e+12]]+yt[t[e+13]]+yt[t[e+14]]+yt[t[e+15]]}var vg=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),la={randomUUID:vg};function Tg(t,e,r){if(la.randomUUID&&!e&&!t)return la.randomUUID();t=t||{};let n=t.random||(t.rng||ca)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Pl(n)}var ao=Tg;var go=require("@mysten/sui.js/utils"),ed=require("@mysten/sui.js/transactions"),td=require("@mysten/sui.js/client"),rd=require("@mysten/sui.js/bcs");var Sg=Object.defineProperty,xg=(t,e,r)=>e in t?Sg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kg=(t,e,r)=>(xg(t,typeof e!="symbol"?e+"":e,r),r),yo=5*60*1e3,Oe=24*60*60*1e3;function er(t){return Date.parse(new Date().toString())+t}var Zn=class{overdueTime;value;constructor(t,e=0){this.overdueTime=e,this.value=t}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};$.config({precision:64,rounding:$.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var _t=$,V=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof V&&t.errorCode===e}},Y=new ct.default(0),Qt=new ct.default(1),bo=new ct.default(2),uv=bo.pow(new ct.default(128)),_n=bo.pow(new ct.default(64)).sub(Qt),Cg=bo.pow(new ct.default(128)).sub(Qt),fe=class{static toX64_BN(t){return t.mul(new ct.default(2).pow(new ct.default(64)))}static toX64_Decimal(t){return t.mul(_t.pow(2,64))}static toX64(t){return new ct.default(t.mul(_t.pow(2,64)).floor().toFixed())}static fromX64(t){return new _t(t.toString()).mul(_t.pow(2,-64))}static fromX64_Decimal(t){return t.mul(_t.pow(2,-64))}static fromX64_BN(t){return t.div(new ct.default(2).pow(new ct.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(_n).gt(Y)&&(e=e.add(Qt)),e}static divRoundUp(t,e){return t.mod(e).eq(Y)?t.div(e):t.div(e).add(new ct.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(Cg):t.sub(e)}static checkUnsignedSub(t,e){let r=t.sub(e);if(r.isNeg())throw new V("Unsigned integer sub overflow","UnsignedIntegerOverflow");return r}static checkMul(t,e,r){let n=t.mul(e);if(this.isOverflow(n,r))throw new V("Multiplication overflow","MultiplicationOverflow");return n}static checkMulDivFloor(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivCeil(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).add(r.sub(Qt)).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivRound(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e.add(r.shrn(1))).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulShiftRight(t,e,r,n){let i=t.mul(e).div(new ct.default(2).pow(new ct.default(r)));if(this.isOverflow(i,n))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return i}static checkMulShiftRight64RoundUpIf(t,e,r,n){let i=t.mul(e),s=n&&i.and(_n).gt(Y)?i.shrn(64).add(Qt):i.shrn(64);if(this.isOverflow(s,r))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return s}static checkMulShiftLeft(t,e,r,n){let i=t.mul(e).shln(r);if(this.isOverflow(i,n))throw new V("Multiplication shift left overflow","MulShiftLeftOverflow");return i}static checkDivRoundUpIf(t,e,r){if(e.eq(Y))throw new V("Devide by zero","DivideByZero");return r?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(bo.pow(new ct.default(e)))}static sign(t){return t.testn(127)?1:0}static is_neg(t){return this.sign(t)===1}static abs_u128(t){return t.gt(Y)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new ct.default("ffffffffffffffffffffffffffffffff",16))}static neg(t){return this.is_neg(t)?t.abs():this.neg_from(t)}static abs(t){return this.sign(t)===0?t:this.u128_neg(t.sub(new ct.default(1)))}static neg_from(t){return t.eq(Y)?t:this.u128_neg(t).add(new ct.default(1)).or(new ct.default(1).shln(127))}};function Og(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new wr.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new wr.default(t.fee_growth_global_a),feeGrowthGlobalB:new wr.default(t.fee_growth_global_b),feeProtocolCoinA:new wr.default(t.fee_protocol_coin_a),feeProtocolCoinB:new wr.default(t.fee_protocol_coin_b),feeRate:new wr.default(t.fee_rate),liquidity:new wr.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var _o="79226673515401279992447579055";var vo="4295048016",yn=new Ll.default(1e6),Ce="0x0000000000000000000000000000000000000000000000000000000000000006",Mg="partner",fo="pool_script",Gr="pool_script_v2",Wn="router",da="router_with_partner",Vr="fetcher_script",Eg="expect_swap",Dl="utils";var fa="custodian_v2",Pg="clob_v2",Dg="endpoints_v2";function be(t){if(t.config===void 0)throw new V(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var Bg=14,Ng="59543866431248",Rg="184467440737095516",jg="15793534762490258745",Fg=443636;function qg(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}function ue(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}function Lg(t){let e;return t&1?e=new ee.default("79232123823359799118286999567"):e=new ee.default("79228162514264337593543950336"),t&2&&(e=ue(e.mul(new ee.default("79236085330515764027303304731")),96,256)),t&4&&(e=ue(e.mul(new ee.default("79244008939048815603706035061")),96,256)),t&8&&(e=ue(e.mul(new ee.default("79259858533276714757314932305")),96,256)),t&16&&(e=ue(e.mul(new ee.default("79291567232598584799939703904")),96,256)),t&32&&(e=ue(e.mul(new ee.default("79355022692464371645785046466")),96,256)),t&64&&(e=ue(e.mul(new ee.default("79482085999252804386437311141")),96,256)),t&128&&(e=ue(e.mul(new ee.default("79736823300114093921829183326")),96,256)),t&256&&(e=ue(e.mul(new ee.default("80248749790819932309965073892")),96,256)),t&512&&(e=ue(e.mul(new ee.default("81282483887344747381513967011")),96,256)),t&1024&&(e=ue(e.mul(new ee.default("83390072131320151908154831281")),96,256)),t&2048&&(e=ue(e.mul(new ee.default("87770609709833776024991924138")),96,256)),t&4096&&(e=ue(e.mul(new ee.default("97234110755111693312479820773")),96,256)),t&8192&&(e=ue(e.mul(new ee.default("119332217159966728226237229890")),96,256)),t&16384&&(e=ue(e.mul(new ee.default("179736315981702064433883588727")),96,256)),t&32768&&(e=ue(e.mul(new ee.default("407748233172238350107850275304")),96,256)),t&65536&&(e=ue(e.mul(new ee.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=ue(e.mul(new ee.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=ue(e.mul(new ee.default("38992368544603139932233054999993551")),96,256)),ue(e,32,256)}function Ug(t){let e=Math.abs(t),r;return e&1?r=new ee.default("18445821805675392311"):r=new ee.default("18446744073709551616"),e&2&&(r=ue(r.mul(new ee.default("18444899583751176498")),64,256)),e&4&&(r=ue(r.mul(new ee.default("18443055278223354162")),64,256)),e&8&&(r=ue(r.mul(new ee.default("18439367220385604838")),64,256)),e&16&&(r=ue(r.mul(new ee.default("18431993317065449817")),64,256)),e&32&&(r=ue(r.mul(new ee.default("18417254355718160513")),64,256)),e&64&&(r=ue(r.mul(new ee.default("18387811781193591352")),64,256)),e&128&&(r=ue(r.mul(new ee.default("18329067761203520168")),64,256)),e&256&&(r=ue(r.mul(new ee.default("18212142134806087854")),64,256)),e&512&&(r=ue(r.mul(new ee.default("17980523815641551639")),64,256)),e&1024&&(r=ue(r.mul(new ee.default("17526086738831147013")),64,256)),e&2048&&(r=ue(r.mul(new ee.default("16651378430235024244")),64,256)),e&4096&&(r=ue(r.mul(new ee.default("15030750278693429944")),64,256)),e&8192&&(r=ue(r.mul(new ee.default("12247334978882834399")),64,256)),e&16384&&(r=ue(r.mul(new ee.default("8131365268884726200")),64,256)),e&32768&&(r=ue(r.mul(new ee.default("3584323654723342297")),64,256)),e&65536&&(r=ue(r.mul(new ee.default("696457651847595233")),64,256)),e&131072&&(r=ue(r.mul(new ee.default("26294789957452057")),64,256)),e&262144&&(r=ue(r.mul(new ee.default("37481735321082")),64,256)),r}var ke=class{static priceToSqrtPriceX64(t,e,r){return fe.toX64(t.mul(_t.pow(10,r-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,r){return fe.fromX64(t).pow(2).mul(_t.pow(10,e-r))}static tickIndexToSqrtPriceX64(t){return t>0?new ee.default(Lg(t)):new ee.default(Ug(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ee.default(_o))||t.lt(new ee.default(vo)))throw new V("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,r=new ee.default(e-64),n=qg(r,32,128),i=new ee.default("8000000000000000","hex"),o=0,s=new ee.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new ee.default(0))&&o<Bg;){u=u.mul(u);let A=u.shrn(127);u=u.shrn(63+A.toNumber()),s=s.add(i.mul(A)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new ee.default(Ng)),_=ue(b.sub(new ee.default(Rg)),64,128).toNumber(),T=ue(b.add(new ee.default(jg)),64,128).toNumber();return _===T?_:ke.tickIndexToSqrtPriceX64(T).lte(t)?T:_}static tickIndexToPrice(t,e,r){return ke.sqrtPriceX64ToPrice(ke.tickIndexToSqrtPriceX64(t),e,r)}static priceToTickIndex(t,e,r){return ke.sqrtPriceX64ToTickIndex(ke.priceToSqrtPriceX64(t,e,r))}static priceToInitializableTickIndex(t,e,r,n){return ke.getInitializableTickIndex(ke.priceToTickIndex(t,e,r),n)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)-e}};function $g(t){return vt(t).add(vt(Fg))}var lv=new Kn.default(365),dv=new Kn.default(24),fv=new Kn.default(3600),hv=new Kn.default(.5);var yr=class{static getDefaultSqrtPriceLimit(t){return new Ul.default(t?vo:_o)}static getDefaultOtherAmountThreshold(t){return t?Y:_n}};function $l(t,e,r,n){if(r.eq(Y))return t;let i=fe.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=fe.checkMul(t,r,256);if(!n&&o.lte(s))throw new V("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let u=n?fe.checkDivRoundUpIf(i,o.add(s),!0):fe.checkDivRoundUpIf(i,o.sub(s),!0);if(u.lt(new ye.default(vo)))throw new V("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(u.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return u}function Gl(t,e,r,n){let i=fe.checkDivRoundUpIf(r.shln(64),e,!n),o=n?t.add(i):t.sub(i);if(o.lt(new ye.default(vo))||o.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function Gg(t,e,r,n){return n?$l(t,e,r,!0):Gl(t,e,r,!0)}function Vg(t,e,r,n){return n?Gl(t,e,r,!1):$l(t,e,r,!1)}function Bl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n){let s=new ye.default(r).mul(new ye.default(i)).shln(64),u=e.mul(t),l=s.div(u);o=s.mod(u).eq(Y)?l:l.add(Qt)}else{let s=new ye.default(r).mul(new ye.default(i));o=s.and(_n).gt(Y)?s.shrn(64).add(Qt):s.shrn(64)}return o}function Nl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n)o=r.mul(i).shrn(64);else{let s=r.mul(i).shln(64),u=e.mul(t);o=s.div(u)}return o}function zg(t,e,r,n,i,o){if(r===Y)return{amountIn:Y,amountOut:Y,nextSqrtPrice:e,feeAmount:Y};let s=t.gte(e),u,l,d,b;if(o){let _=fe.checkMulDivFloor(n,fe.checkUnsignedSub(yn,i),yn,64),T=Bl(t,e,r,s);T.gt(_)?(u=_,b=fe.checkUnsignedSub(n,_),d=Gg(t,r,_,s)):(u=T,b=fe.checkMulDivCeil(u,i,yn.sub(i),64),d=e),l=Nl(t,d,r,s)}else{let _=Nl(t,e,r,s);_.gt(n)?(l=n,d=Vg(t,r,n,s)):(l=_,d=e),u=Bl(t,d,r,s),b=fe.checkMulDivCeil(u,i,yn.sub(i),64)}return{amountIn:u,amountOut:l,nextSqrtPrice:d,feeAmount:b}}function Wg(t,e,r,n,i){let o=r,s=n.liquidity,{currentSqrtPrice:u}=n,l={amountIn:Y,amountOut:Y,feeAmount:Y,refAmount:Y,nextSqrtPrice:Y,crossTickNum:0},d,b,_=yr.getDefaultSqrtPriceLimit(t);for(let T of i){if(t&&n.currentTickIndex<T.index||!t&&n.currentTickIndex>=T.index||T===null)continue;t&&_.gt(T.sqrtPrice)||!t&&_.lt(T.sqrtPrice)?d=_:d=T.sqrtPrice;let x=zg(u,d,s,o,n.feeRate,e);if(x.amountIn.eq(Y)||(o=e?o.sub(x.amountIn.add(x.feeAmount)):o.sub(x.amountOut)),l.amountIn=l.amountIn.add(x.amountIn),l.amountOut=l.amountOut.add(x.amountOut),l.feeAmount=l.feeAmount.add(x.feeAmount),x.nextSqrtPrice.eq(T.sqrtPrice)?(b=T.liquidityNet.mul(new ye.default(-1)),t?fe.is_neg(b)?s=s.add(new ye.default(Vt(BigInt(b.toString()),128))):s=s.add(b):fe.is_neg(b)?s=s.sub(new ye.default(Vt(BigInt(b.toString()),128))):s=s.sub(b),u=T.sqrtPrice):u=x.nextSqrtPrice,l.crossTickNum+=1,o.eq(Y))break}return l.amountIn=l.amountIn.add(l.feeAmount),l.nextSqrtPrice=u,l}function uo(t,e,r){let n=ye.default.min(t,e),i=ye.default.max(t,e),o=fe.fromX64_BN(r.mul(i).mul(n)),s=i.sub(n);return o.div(s)}function co(t,e,r){let n=ye.default.min(t,e),o=ye.default.max(t,e).sub(n);return r.shln(64).div(o)}var ho=class{static updateFeeRate(t,e,r,n,i){let o=fe.checkMulDivCeil(e,new ye.default(n),yn,64),s=r===0?Y:fe.checkMulDivFloor(e,new ye.default(r),yn,64),u=e.mul(o).mul(s);if(i?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),u.eq(Y)||t.liquidity.eq(Y))return{refFee:s,clmm:t};let l=u.shln(64).div(t.liquidity);return i?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(l):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(l),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,r,n,i){let o=new _t(t.toString()),s=new _t(e.toString()),u=new _t(r.toString()),l=new _t(n.toString()),d,b;return e.lt(r)?(d=fe.toX64_Decimal(o).mul(l.sub(u)).div(u.mul(l)),b=new _t(0)):e.lt(n)?(d=fe.toX64_Decimal(o).mul(l.sub(s)).div(s.mul(l)),b=fe.fromX64_Decimal(o.mul(s.sub(u)))):(d=new _t(0),b=fe.fromX64_Decimal(o.mul(l.sub(u)))),i?{coinA:new ye.default(d.ceil().toString()),coinB:new ye.default(b.ceil().toString())}:{coinA:new ye.default(d.floor().toString()),coinB:new ye.default(b.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,r,n,i,o,s){let u=ke.sqrtPriceX64ToTickIndex(s),l=ke.tickIndexToSqrtPriceX64(t),d=ke.tickIndexToSqrtPriceX64(e),b;if(u<t){if(!n)throw new V("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");b=uo(l,d,r)}else if(u>e){if(n)throw new V("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");b=co(d,l,r)}else n?b=uo(s,d,r):b=co(s,l,r);let _=ho.getCoinAmountFromLiquidity(b,s,l,d,i),T=i?vt(_.coinA.toString()).mul(1+o).toString():vt(_.coinA.toString()).mul(1-o).toString(),x=i?vt(_.coinB.toString()).mul(1+o).toString():vt(_.coinB.toString()).mul(1-o).toString();return{coinAmountA:_.coinA,coinAmountB:_.coinB,tokenMaxA:i?new ye.default(_t.ceil(T).toString()):new ye.default(_t.floor(T).toString()),tokenMaxB:i?new ye.default(_t.ceil(x).toString()):new ye.default(_t.floor(x).toString()),liquidityAmount:b,fix_amount_a:n}}static estimateLiquidityFromcoinAmounts(t,e,r,n){if(e>r)throw new V("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let i=ke.sqrtPriceX64ToTickIndex(t),o=ke.tickIndexToSqrtPriceX64(e),s=ke.tickIndexToSqrtPriceX64(r);if(i<e)return uo(o,s,n.coinA);if(i>=r)return co(s,o,n.coinB);let u=uo(t,s,n.coinA),l=co(t,o,n.coinB);return ye.default.min(u,l)}static estCoinAmountsFromTotalAmount(t,e,r,n,i,o){let{ratioA:s,ratioB:u}=ho.calculateDepositRatioFixTokenA(t,e,r),l=vt(n).mul(s).div(i),d=vt(n).mul(u).div(o);return{amountA:l,amountB:d}}static calculateDepositRatioFixTokenA(t,e,r){let n=new ye.default(1e8),{coinAmountB:i}=ho.estLiquidityAndcoinAmountFromOneAmounts(t,e,n,!0,!0,0,r),o=ke.sqrtPriceX64ToPrice(r,0,0),s=vt(n.toString()).mul(o),u=s.add(i.toString()),l=s.div(u),d=vt(i.toString()).div(u);return{ratioA:l,ratioB:d}}};function Hg(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var Zg=0,Vl=1,Kg=2;function Rl(t,e){return t===e?Zg:t<e?Vl:Kg}function Jg(t,e){let r=0,n=t.length<=e.length?t.length:e.length,i=Rl(t.length,e.length);for(;r<n;){let o=Rl(t.charCodeAt(r),e.charCodeAt(r));if(r+=1,o!==0)return o}return i}function jl(t,e){return Jg(t,e)===Vl}function Fl(t,...e){let r=Array.isArray(e[e.length-1])?e.pop():[],i=[t,...e].filter(Boolean).join("::");return r&&r.length&&(i+=`<${r.join(", ")}>`),i}function se(t){try{let e=t.replace(/\s/g,""),n=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){e=e.slice(0,e.indexOf("<"));let l={...se(e),type_arguments:n.map(d=>se(d).source_address)};return l.type_arguments=l.type_arguments.map(d=>Ie.isSuiCoin(d)?d:se(d).source_address),l.source_address=Fl(l.full_address,l.type_arguments),l}let i=e.split("::"),s={full_address:e,address:e===Wl||e===t0?"0x2":(0,To.normalizeSuiObjectId)(i[0]),module:i[1],name:i[2],type_arguments:[],source_address:""};return s.full_address=`${s.address}::${s.module}::${s.name}`,s.source_address=Fl(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function sr(t){return se(t).source_address}function Xg(t){return t.toLowerCase().startsWith("0x")?(0,To.normalizeSuiObjectId)(t):t}var Yg=(t,e=!0)=>{let r=t.split("::"),n=r.shift(),i=(0,To.normalizeSuiObjectId)(n);return e&&(i=Hg(i)),`${i}::${r.join("::")}`};function zl(t){for(let e in t){let r=typeof t[e];if(r==="object")zl(t[e]);else if(r==="string"){let n=t[e];n&&!n.includes("::")&&(t[e]=Xg(n))}}}var Qg="0x2::coin::Coin",e0=/^0x2::coin::Coin<(.+)>$/;var Wl="0x2::sui::SUI",t0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie=class{static getCoinTypeArg(t){let e=t.type.match(e0);return e?e[1]:null}static isSUI(t){let e=Ie.getCoinTypeArg(t);return e?Ie.getCoinSymbol(e)==="SUI":!1}static getCoinSymbol(t){return t.substring(t.lastIndexOf(":")+1)}static getBalance(t){return BigInt(t.fields.balance)}static totalBalance(t,e){let r=BigInt(0);return t.forEach(n=>{e===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(t){return t.fields.id.id}static getCoinTypeFromArg(t){return`${Qg}<${t}>`}static getFaucetCoins(t){let{events:e}=t,r=[];return e?.forEach(n=>{let{type:i}=n;if(se(i).name==="InitEvent"){let o=n.parsedJson;r.push({transactionModule:n.transactionModule,suplyID:o.suplyID,decimals:o.decimals})}}),r}static getCoinAssets(t,e){let r=[];return e.forEach(n=>{sr(n.coinAddress)===sr(t)&&r.push(n)}),r}static isSuiCoin(t){return se(t).full_address===Wl}static selectCoinObjectIdGreaterThanOrEqual(t,e,r=[]){let n=Ie.selectCoinAssetGreaterThanOrEqual(t,e,r),i=n.selectedCoins.map(u=>u.coinObjectId),o=n.remainingCoins,s=n.selectedCoins.map(u=>u.balance.toString());return{objectArray:i,remainCoins:o,amountArray:s}}static selectCoinAssetGreaterThanOrEqual(t,e,r=[]){let n=Ie.sortByBalance(t.filter(l=>!r.includes(l.coinObjectId))),i=Ie.calculateTotalBalance(n);if(i<e)return{selectedCoins:[],remainingCoins:n};if(i===e)return{selectedCoins:n,remainingCoins:[]};let o=BigInt(0),s=[],u=[...n];for(;o<i;){let l=e-o,d=u.findIndex(_=>_.balance>=l);if(d!==-1){s.push(u[d]),u.splice(d,1);break}let b=u.pop();b.balance>0&&(s.push(b),o+=b.balance)}return{selectedCoins:Ie.sortByBalance(s),remainingCoins:Ie.sortByBalance(u)}}static sortByBalance(t){return t.sort((e,r)=>e.balance<r.balance?-1:e.balance>r.balance?1:0)}static sortByBalanceDes(t){return t.sort((e,r)=>e.balance>r.balance?-1:e.balance<r.balance?0:1)}static calculateTotalBalance(t){return t.reduce((e,r)=>e+r.balance,BigInt(0))}};function i0(t,{numerator:e,denominator:r},n){return n?t.mul(r.add(e)).div(r):t.mul(r).div(r.add(e))}function vt(t){return $.isDecimal(t)?t:new $(t===void 0?0:t)}function Jn(t){return t.data}function Hl(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let{error:e}=t;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Zl(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function s0(t){if("reference"in t)return t.reference;let e=Jn(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Hl(t)}function bn(t){return"objectId"in t?t.objectId:s0(t)?.objectId??Zl(t)}function a0(t){return t.data!==void 0}function u0(t){return t.content!==void 0}function Kl(t){let e="data"in t?Jn(t):t;if(!(!e||!u0(e)||e.content.dataType!=="moveObject"))return e.content}function ba(t){return Kl(t)?.type}function c0(t){let e=a0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":ba(t):e?.type}function _a(t){return Jn(t)?.previousTransaction}function l0(t){return Jn(t)?.owner}function d0(t){let e=Jn(t)?.display;return e||{data:null,error:null}}function br(t){let e=Kl(t)?.fields;if(e)return"fields"in e?e.fields:e}function Vt(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function zr(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function f0(t,e,r){let n=se(t).name,i=se(e).name;return`${n}-${i}[${r}]`}function ha(t){let e=ba(t),r=se(e),n=br(t);if(n==null)throw new V(`Pool id ${bn(t)} not exists.`,"InvalidPoolObject");let i=[];n.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:u}=s.fields,l=fe.fromX64(new Rt.default(u)),d=Math.floor(l.toNumber()*60*60*24);i.push({emissions_per_second:u,coinAddress:se(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:d})});let o={poolAddress:bn(t),poolType:e,coinTypeA:r.type_arguments[0],coinTypeB:r.type_arguments[1],coinAmountA:n.coin_a,coinAmountB:n.coin_b,current_sqrt_price:n.current_sqrt_price,current_tick_index:zr(BigInt(n.current_tick_index.fields.bits)),fee_growth_global_a:n.fee_growth_global_a,fee_growth_global_b:n.fee_growth_global_b,fee_protocol_coin_a:n.fee_protocol_coin_a,fee_protocol_coin_b:n.fee_protocol_coin_b,fee_rate:n.fee_rate,is_pause:n.is_pause,liquidity:n.liquidity,position_manager:{positions_handle:n.position_manager.fields.positions.fields.id.id,size:n.position_manager.fields.positions.fields.size},rewarder_infos:i,rewarder_last_updated_time:n.rewarder_manager.fields.last_updated_time,tickSpacing:n.tick_spacing,ticks_handle:n.tick_manager.fields.ticks.fields.id.id,uri:n.url,index:Number(n.index),name:""};return o.name=f0(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function h0(t){let e=d0(t).data,r={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(r.creator=e.creator,r.description=e.description,r.image_url=e.image_url,r.link=e.link,r.name=e.name,r.project_url=e.project_url),r}function pa(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Position not exists. Get Position error:${t.error}`,"InvalidPositionObject");let e={creator:"",description:"",image_url:"",link:"",name:"",project_url:""},r={...e,pos_object_id:"",owner:"",type:"",coin_type_a:"",coin_type_b:"",liquidity:"",tick_lower_index:0,tick_upper_index:0,index:0,pool:"",reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"},n=br(t);if(n){let s=ba(t),u=l0(t);"nft"in n?(n=n.nft.fields,e.description=n.description,e.name=n.name,e.link=n.url):e=h0(t),r={...e,pos_object_id:n.id.id,owner:u.AddressOwner,type:s,coin_type_a:n.coin_type_a.fields.name,coin_type_b:n.coin_type_b.fields.name,liquidity:n.liquidity,tick_lower_index:zr(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:zr(BigInt(n.tick_upper_index.fields.bits)),index:n.index,pool:n.pool,reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"}}let i=Hl(t);i&&(r.pos_object_id=i.objectId,r.position_status="Deleted");let o=Zl(t);return o&&(r.pos_object_id=o,r.position_status="NotExists"),r}function Jl(t){let e={reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0"};t="fields"in t?t.fields:t,t.rewards.forEach((o,s)=>{let{amount_owned:u,growth_inside:l}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=u,e.reward_growth_inside_0=l):s===1?(e.reward_amount_owed_1=u,e.reward_growth_inside_1=l):s===2&&(e.reward_amount_owed_2=u,e.reward_growth_inside_2=l)});let r="fields"in t.tick_lower_index?t.tick_lower_index.fields.bits:t.tick_lower_index.bits,n="fields"in t.tick_upper_index?t.tick_upper_index.fields.bits:t.tick_upper_index.bits;return{liquidity:t.liquidity,tick_lower_index:zr(BigInt(r)),tick_upper_index:zr(BigInt(n)),...e,fee_growth_inside_a:t.fee_growth_inside_a,fee_owed_a:t.fee_owned_a,fee_growth_inside_b:t.fee_growth_inside_b,fee_owed_b:t.fee_owned_b,pos_object_id:t.position_id}}function ma(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let r=br(t).value.fields.value.fields;return{objectId:bn(t),index:zr(BigInt(r.index.fields.bits)),sqrtPrice:new Rt.default(r.sqrt_price),liquidityNet:new Rt.default(r.liquidity_net.fields.bits),liquidityGross:new Rt.default(r.liquidity_gross),feeGrowthOutsideA:new Rt.default(r.fee_growth_outside_a),feeGrowthOutsideB:new Rt.default(r.fee_growth_outside_b),rewardersGrowthOutside:r.rewards_growth_outside}}function p0(t){if(!t||!t.index||!t.sqrt_price||!t.liquidity_net||!t.liquidity_gross||!t.fee_growth_outside_a||!t.fee_growth_outside_b)throw new V("Invalid tick fields.","InvalidTickFields");let e=zr(BigInt(t.index.bits)),r=new Rt.default(t.sqrt_price),n=new Rt.default(t.liquidity_net.bits),i=new Rt.default(t.liquidity_gross),o=new Rt.default(t.fee_growth_outside_a),s=new Rt.default(t.fee_growth_outside_b),u=t.rewards_growth_outside||[];return{objectId:"",index:e,sqrtPrice:r,liquidityNet:n,liquidityGross:i,feeGrowthOutsideA:o,feeGrowthOutsideB:s,rewardersGrowthOutside:u}}function m0(t,e,r,n,i,o){let s=t.rewarder_infos,u=[];for(let l=0;l<s.length;l+=1){let d=o[l];e!==null&&(t.current_tick_index<n?d=o[l].sub(new qr.default(e.rewardersGrowthOutside[l])):d=e.rewardersGrowthOutside[l]);let b=new qr.default(0);r!==null&&(t.current_tick_index>=i?b=o[l].sub(new qr.default(r.rewardersGrowthOutside[l])):b=r.rewardersGrowthOutside[l]);let _=fe.subUnderflowU128(fe.subUnderflowU128(new qr.default(o[l]),new qr.default(d)),new qr.default(b));u.push(_)}return u}function wo(t){let e=Ie.isSuiCoin(t.coinTypeA),r=Ie.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:r}}function g0(t,e){return $.ceil(vt(t).div(1+e)).toString()}var X=class{static createCollectRewarderAndFeeParams(t,e,r,n,i,o){i===void 0&&(i=[...n]),o===void 0&&(o=[...n]);let s=sr(r.coinTypeA),u=sr(r.coinTypeB);if(r.collect_fee){let d=X.buildCoinForAmount(e,i,BigInt(0),s,!1);i=d.remainCoins;let b=X.buildCoinForAmount(e,o,BigInt(0),u,!1);o=b.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:r.pool_id,pos_id:r.pos_id,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB},e,d.targetCoin,b.targetCoin)}let l=[];return r.rewarder_coin_types.forEach(d=>{switch(sr(d)){case s:l.push(X.buildCoinForAmount(e,i,BigInt(0),d,!1).targetCoin);break;case u:l.push(X.buildCoinForAmount(e,o,BigInt(0),d,!1).targetCoin);break;default:l.push(X.buildCoinForAmount(e,n,BigInt(0),d,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(r,e,l),e}static async adjustTransactionForGas(t,e,r,n){n.setSender(t.senderAddress);let i=Ie.selectCoinAssetGreaterThanOrEqual(e,r).selectedCoins;if(i.length===0)throw new V("Insufficient balance","InsufficientBalance");let o=Ie.calculateTotalBalance(e);if(o-r>1e9)return{fixAmount:r};let s=await t.fullClient.calculationTxGas(n);if(Ie.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),i.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(s)+BigInt(500);if(o-r<l){if(r-=l,r<0)throw new V("gas Insufficient balance","InsufficientBalance");let d=new Lr.TransactionBlock;return{fixAmount:r,newTx:d}}}return{fixAmount:r}}static async buildAddLiquidityFixTokenForGas(t,e,r,n){let i=await X.buildAddLiquidityFixToken(t,e,r),{isAdjustCoinA:o}=wo(r),s=o?r.amount_a:r.amount_b,u=await X.adjustTransactionForGas(t,Ie.getCoinAssets(o?r.coinTypeA:r.coinTypeB,e),BigInt(s),i),{fixAmount:l}=u,{newTx:d}=u;if(d!==void 0){let b,_;if(o)r.amount_a=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,l.toString(),r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);else return r.amount_b=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,l.toString(),r.slippage,r.coinTypeB,e,!1),r=X.fixAddLiquidityFixTokenParams(r,n.slippage,n.curSqrtPrice),i=await X.buildAddLiquidityFixTokenArgs(d,t,e,r,b,_),i}return i}static async buildAddLiquidityFixToken(t,e,r){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=new Lr.TransactionBlock,i=X.buildAddLiquidityFixTokenCoinInput(n,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),o=X.buildAddLiquidityFixTokenCoinInput(n,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);return n=X.buildAddLiquidityFixTokenArgs(n,t,e,r,i,o),n}static buildAddLiquidityFixTokenCoinInput(t,e,r,n,i,o,s=!0){return e?X.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(g0(r,n)),amountFirst:BigInt(r)},i,s):X.buildCoinForAmount(t,o,BigInt(r),i,s)}static fixAddLiquidityFixTokenParams(t,e,r){let n=t.fix_amount_a?t.amount_a:t.amount_b,i=ho.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new Hn.default(n),t.fix_amount_a,!0,e,r);return t.amount_a=t.fix_amount_a?t.amount_a:i.tokenMaxA.toNumber(),t.amount_b=t.fix_amount_a?i.tokenMaxB.toNumber():t.amount_b,t}static buildAddLiquidityFixTokenArgs(t,e,r,n,i,o){let s=[n.coinTypeA,n.coinTypeB],u=n.is_open?"open_position_with_liquidity_by_fix_coin":"add_liquidity_by_fix_coin",{clmm_pool:l,integrate:d}=e.sdkOptions;n.is_open||(t=X.createCollectRewarderAndFeeParams(e,t,n,r,i.remainCoins,o.remainCoins));let b=be(l),_=n.is_open?[t.object(b.global_config_id),t.object(n.pool_id),t.pure(Vt(BigInt(n.tick_lower)).toString()),t.pure(Vt(BigInt(n.tick_upper)).toString()),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)]:[t.object(b.global_config_id),t.object(n.pool_id),t.object(n.pos_id),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)];return t.moveCall({target:`${d.published_at}::${Gr}::${u}`,typeArguments:s,arguments:_}),t}static async buildSwapTransactionForGas(t,e,r,n){let i=X.buildSwapTransaction(t,e,r);i.setSender(t.senderAddress);let o=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:s,newTx:u}=o;if(u!==void 0){u.setSender(t.senderAddress),e.by_amount_in?e.amount=s.toString():e.amount_limit=s.toString(),e=await X.fixSwapParams(t,e,n);let l=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),d=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);i=X.buildSwapTransactionArgs(u,e,t.sdkOptions,l,d)}return i}static buildSwapTransaction(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return n=X.buildSwapTransactionArgs(n,e,t.sdkOptions,i,o),n}static buildSwapTransactionArgs(t,e,r,n,i){let{clmm_pool:o,integrate:s}=r,u=yr.getDefaultSqrtPriceLimit(e.a2b),l=[e.coinTypeA,e.coinTypeB],{global_config_id:d}=be(o);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=e.swap_partner!==void 0,_=b?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",T=b?[t.pure(d),t.pure(e.pool_id),t.pure(e.swap_partner),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)]:[t.pure(d),t.pure(e.pool_id),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)];return t.moveCall({target:`${s.published_at}::${Gr}::${_}`,typeArguments:l,arguments:T}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,r,n){let{tx:i,coinABs:o}=X.buildSwapTransactionWithoutTransferCoins(t,e,r);i.setSender(t.senderAddress);let s=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:u,newTx:l}=s;if(l!==void 0){l.setSender(t.senderAddress),e.by_amount_in?e.amount=u.toString():e.amount_limit=u.toString(),e=await X.fixSwapParams(t,e,n);let d=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),b=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),_=X.buildSwapTransactionWithoutTransferCoinArgs(t,l,e,t.sdkOptions,d,b);i=_.tx,o=_.txRes}return{tx:i,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=X.buildSwapTransactionWithoutTransferCoinArgs(t,n,e,t.sdkOptions,i,o);return{tx:s.tx,coinABs:s.txRes}}static buildSwapTransactionWithoutTransferCoinArgs(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=n,l=yr.getDefaultSqrtPriceLimit(r.a2b),{global_config_id:d}=be(s);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=r.swap_partner!==void 0,_=b?"swap_with_partner":"swap",T=b?da:Wn,x=b?[e.pure(d),e.pure(r.pool_id),e.pure(r.swap_partner),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)]:[e.pure(d),e.pure(r.pool_id),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)],A=[r.coinTypeA,r.coinTypeB],I=e.moveCall({target:`${u.published_at}::${T}::${_}`,typeArguments:A,arguments:x});if(r.by_amount_in){let C=r.a2b?r.coinTypeB:r.coinTypeA,E=r.a2b?I[1]:I[0],P=Number(r.amount_limit);this.checkCoinThreshold(t,r.by_amount_in,e,E,P,C)}return{tx:e,txRes:I}}static async fixSwapParams(t,e,r){let{currentPool:n}=r;try{let i=await t.Swap.preswap({decimalsA:r.decimalsA,decimalsB:r.decimalsB,a2b:e.a2b,byAmountIn:e.by_amount_in,amount:e.amount,pool:n,currentSqrtPrice:n.current_sqrt_price,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB}),o=r.byAmountIn?i.estimatedAmountOut:i.estimatedAmountIn,s=i0(o,r.slippage,!r.byAmountIn);e.amount_limit=s.toString()}catch(i){console.log("fixSwapParams",i)}return e}static async syncBuildCoinInputForAmount(t,e,r,n,i=!0){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let o=await t.getOwnerCoinAssets(t.senderAddress,n);return X.buildCoinForAmount(e,o,r,n,i).targetCoin}static buildCoinForAmount(t,e,r,n,i=!0,o=!1){let s=Ie.getCoinAssets(n,e);if(r===BigInt(0)&&s.length===0)return X.buildZeroValueCoin(e,t,n,i);let u=Ie.calculateTotalBalance(s);if(u<r)throw new V(`The amount(${u}) is Insufficient balance for ${n} , expect ${r} `,"InsufficientBalance");return X.buildCoin(t,e,s,r,n,i,o)}static buildCoin(t,e,r,n,i,o=!0,s=!1){if(Ie.isSuiCoin(i)){if(o){let P=t.splitCoins(t.gas,[t.pure(n.toString())]);return{targetCoin:t.makeMoveVec({objects:[P]}),remainCoins:e,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(n===0n&&r.length>1){let P=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.object(P.objectArray[0]),remainCoins:P.remainCoins,tragetCoinAmount:P.amountArray[0],isMintZeroCoin:!1}}let C=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.splitCoins(t.gas,[t.pure(n.toString())]),remainCoins:C.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let u=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n),l=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),d=u.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:d.map(C=>t.object(C))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),isMintZeroCoin:!1};let[b,..._]=d,T=t.object(b),x=T,A=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),I;return _.length>0&&t.mergeCoins(T,_.map(C=>t.object(C))),s&&Number(l)>Number(n)&&(x=t.splitCoins(T,[t.pure(n.toString())]),A=n.toString(),I=T),{targetCoin:x,remainCoins:u.remainCoins,originalSplitedCoin:I,tragetCoinAmount:A,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,r,n=!0){let i=X.callMintZeroValueCoin(e,r),o;return n?o=e.makeMoveVec({objects:[i]}):o=i,{targetCoin:o,remainCoins:t,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(t,e,r,n,i=!0){let o=Ie.getCoinAssets(n,e);if(r.amountFirst===BigInt(0))return o.length>0?X.buildCoin(t,[...e],[...o],r.amountFirst,n,i):X.buildZeroValueCoin(e,t,n,i);let s=Ie.calculateTotalBalance(o);if(s>=r.amountFirst)return X.buildCoin(t,[...e],[...o],r.amountFirst,n,i);if(s<r.amountSecond)throw new V(`The amount(${s}) is Insufficient balance for ${n} , expect ${r.amountSecond} `,"InsufficientBalance");return X.buildCoin(t,[...e],[...o],r.amountSecond,n,i)}static async buildRouterSwapTransaction(t,e,r,n,i){let o=new Lr.TransactionBlock;return e.paths.length>1&&(e.partner=""),o=await this.buildRouterBasePathTx(t,e,r,n,o,i),o}static async buildRouterBasePathTx(t,e,r,n,i,o){let s=e.paths.filter(D=>D&&D.poolAddress),u=Number(s.reduce((D,L)=>D.add(L.amountIn),Y).toString()),l=Number(s.reduce((D,L)=>D.add(L.amountOut),Y).toString()),d=Math.round(r?Number(l.toString())*(1-e.priceSlippagePoint):Number(u.toString())*(1+e.priceSlippagePoint)),b=e.paths[0].coinType[0],_=e.paths[0].coinType[e.paths[0].coinType.length-1],T=X.buildCoinForAmount(i,n,BigInt(r?u:d),b,!1,!0),x=T.originalSplitedCoin!==void 0,A=X.buildCoinForAmount(i,n,0n,_,!1),I=await this.buildRouterBasePathReturnCoins(t,e,r,T,A,i),C=[],{toCoin:E,fromCoin:P}=I;if(i=I.tx,A.isMintZeroCoin?C.push({coinType:_,coin:E}):A.originalSplitedCoin!==void 0?i.mergeCoins(A.originalSplitedCoin,[E]):i.mergeCoins(A.targetCoin,[E]),x){let D=T?.originalSplitedCoin;i.mergeCoins(D,[P])}else C.push({coinType:b,coin:P});for(let D=0;D<C.length;D++)this.buildTransferCoin(t,i,C[D].coin,C[D].coinType,o);return i}static async buildRouterBasePathReturnCoins(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=t.sdkOptions,l=be(s).global_config_id,d=e.paths.filter(D=>D&&D.poolAddress),b=Number(d.reduce((D,L)=>D.add(L.amountIn),Y).toString()),_=Number(d.reduce((D,L)=>D.add(L.amountOut),Y).toString()),T=Math.round(r?Number(_.toString())*(1-e.priceSlippagePoint):Number(b.toString())*(1+e.priceSlippagePoint)),x=e.paths[0].coinType[0],A=e.paths[0].coinType[e.paths[0].coinType.length-1],I=n.targetCoin,C;i.isMintZeroCoin||i.originalSplitedCoin!==void 0?C=i.targetCoin:C=X.callMintZeroValueCoin(o,A);let E=e.partner==="",P=E?Wn:da;for(let D of d)if(D.poolAddress.length===1){let L=D.a2b[0],H={amount:Number(D.amountIn.toString()),amountLimit:T,poolCoinA:D.a2b[0]?x:A,poolCoinB:D.a2b[0]?A:x},W=E?"swap":"swap_with_partner",K=L?I:C,F=L?C:I,U=r?D.amountIn.toString():D.amountOut.toString(),N=yr.getDefaultSqrtPriceLimit(L).toString(),j=E?[o.object(l),o.object(D.poolAddress[0]),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.pure(e.partner),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)],S=[H.poolCoinA,H.poolCoinB],k=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${P}::${W}`,typeArguments:S,arguments:j});I=L?k[0]:k[1],C=L?k[1]:k[0]}else{let L=r?D.amountIn:D.rawAmountLimit[0],H=r?0:D.amountOut,W="";D.a2b[0]?D.a2b[1]?W="swap_ab_bc":W="swap_ab_cb":D.a2b[1]?W="swap_ba_bc":W="swap_ba_cb",E||(W=`${W}_with_partner`);let K=yr.getDefaultSqrtPriceLimit(D.a2b[0]),F=yr.getDefaultSqrtPriceLimit(D.a2b[1]),U=E?[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),o.pure(e.partner),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)],N=[D.coinType[0],D.coinType[1],D.coinType[2]],j=o.moveCall({target:`${u.published_at}::${P}::${W}`,typeArguments:N,arguments:U});I=j[0],C=j[1]}return this.checkCoinThreshold(t,r,o,C,T,A),{fromCoin:I,toCoin:C,tx:o}}static async buildAggregatorSwapReturnCoins(t,e,r,n,i,o,s,u){if(u==null){if(t.senderAddress.length===0)throw Error("recipient and this config sdk senderAddress all not set");u=t.senderAddress}e.splitPaths.length>1&&(i="");let l,d,b=e.splitPaths.some(_=>_.basePaths.some(T=>T.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!b){let _=[];for(let A of e.splitPaths){let I=[],C=[],E=[],P=[];for(let L=0;L<A.basePaths.length;L+=1){let H=A.basePaths[L];I.push(H.direction),C.push(H.poolAddress),E.push(new Hn.default(H.inputAmount.toString())),L===0?P.push(H.fromCoin,H.toCoin):P.push(H.toCoin)}let D={amountIn:new Hn.default(A.inputAmount.toString()),amountOut:new Hn.default(A.outputAmount.toString()),poolAddress:C,a2b:I,rawAmountLimit:E,isExceed:!1,coinType:P};_.push(D)}let T={paths:_,partner:i,priceSlippagePoint:o},x=await this.buildRouterBasePathReturnCoins(t,T,e.byAmountIn,r,n,s);l=x.fromCoin,d=x.toCoin,s=x.tx}else{let _=Math.round(e.outputAmount*(1-o));l=r.targetCoin,n.isMintZeroCoin||n.originalSplitedCoin!==void 0?d=n.targetCoin:d=X.callMintZeroValueCoin(s,e.toCoin);let T=!1,x;if(b){let[A,I]=ql.createAccountCap(u,t.sdkOptions,s);s=I,x=A,T=!0}for(let A=0;A<e.splitPaths.length;A+=1){let I=e.splitPaths[A],C;for(let E=0;E<I.basePaths.length;E+=1){let P=I.basePaths[E];if(P.label==="Deepbook")if(E===0)if(I.basePaths.length===1){let D=this.buildDeepbookBasePathTx(t,P,s,x,l,d,!1);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildDeepbookBasePathTx(t,P,s,x,l,C,!1);l=D.from,C=D.to}else{let D=this.buildDeepbookBasePathTx(t,P,s,x,C,d,!0);C=D.from,d=D.to}if(P.label==="Cetus")if(E===0)if(I.basePaths.length===1){let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,d,!1,i);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,C,!1,i);l=D.from,C=D.to}else{let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,C,d,!0,i);C=D.from,d=D.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::send_coin`,typeArguments:[P.fromCoin],arguments:[C,s.pure(u)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,d,_,e.toCoin),T&&(s=ql.deleteAccountCapByObject(x,t.sdkOptions,s))}return{fromCoin:l,toCoin:d,tx:s}}static async buildAggregatorSwapTransaction(t,e,r,n,i,o){let s=new Lr.TransactionBlock,u=e.byAmountIn?Math.round(e.outputAmount*(1-i)):Math.round(e.inputAmount*(1+i)),l=X.buildCoinForAmount(s,r,e.byAmountIn?BigInt(e.inputAmount):BigInt(u),e.fromCoin,!1,!0),d=l.originalSplitedCoin!=null,b=X.buildCoinForAmount(s,r,0n,e.toCoin,!1),_=await this.buildAggregatorSwapReturnCoins(t,e,l,b,n,i,s,o),{fromCoin:T,toCoin:x}=_;s=_.tx;let A=[];if(b.isMintZeroCoin?A.push({coinType:e.toCoin,coin:x}):b.originalSplitedCoin!=null?s.mergeCoins(b.originalSplitedCoin,[x]):s.mergeCoins(b.targetCoin,[x]),d){let I=l.originalSplitedCoin;s.mergeCoins(I,[T])}else A.push({coinType:e.fromCoin,coin:T});for(let I=0;I<A.length;I++)this.buildTransferCoin(t,s,A[I].coin,A[I].coinType,o);return s}static checkCoinThreshold(t,e,r,n,i,o){e&&r.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Wn}::check_coin_threshold`,typeArguments:[o],arguments:[n,r.pure(i)]})}static buildDeepbookBasePathTx(t,e,r,n,i,o,s){let u=e.direction?i:o,l=e.direction?o:i,d=[r.object(e.poolAddress),n,r.pure(e.inputAmount),r.pure(0),r.pure(e.direction),u,l,r.pure(s),r.object(Ce)],b=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],_=r.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:b,arguments:d});return i=e.direction?_[0]:_[1],o=e.direction?_[1]:_[0],{from:i,to:o,tx:r}}static buildClmmBasePathTx(t,e,r,n,i,o,s,u){let{clmm_pool:l,integrate:d}=t.sdkOptions,b=be(l).global_config_id,_=e.direction?i:o,T=e.direction?o:i,x=u==="",A=x?Wn:da,I=x?"swap":"swap_with_partner",C=n?e.inputAmount.toString():e.outputAmount.toString(),E=yr.getDefaultSqrtPriceLimit(e.direction),P=x?[r.object(b),r.object(e.poolAddress),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)]:[r.object(b),r.object(e.poolAddress),r.pure(u),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)],D=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],L=r.moveCall({target:`${d.published_at}::${A}::${I}`,typeArguments:D,arguments:P});return _=L[0],T=L[1],i=e.direction?_:T,o=e.direction?T:_,{from:i,to:o,tx:r}}static buildCoinTypePair(t,e){let r=[];if(t.length===2){let n=[];n.push(t[0],t[1]),r.push(n)}else{let n=[];n.push(t[0],t[t.length-1]),r.push(n);for(let i=1;i<t.length-1;i+=1){if(e[i-1]===0)continue;let o=[];o.push(t[0],t[i],t[t.length-1]),r.push(o)}}return r}static buildTransferCoinToSender(t,e,r,n){e.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::transfer_coin_to_sender`,typeArguments:[n],arguments:[r]})}static buildTransferCoin(t,e,r,n,i){i!=null?e.transferObjects([r],e.pure(i)):X.buildTransferCoinToSender(t,e,r,n)}},Pe=X;kg(Pe,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function kt(t){return!(!t.startsWith("0x")||t.length!==66)}var gn=new bt.default(1e9),ql=class{static createAccountCap(t,e,r,n=!1){if(t.length===0)throw Error("this config sdk senderAddress is empty");let{deepbook:i}=e,[o]=r.moveCall({target:`${i.published_at}::${Pg}::create_account`,typeArguments:[],arguments:[]});return n&&r.transferObjects([o],r.pure(t)),[o,r]}static deleteAccountCap(t,e,r){let{deepbook:n}=e,i=[r.pure(t)];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static deleteAccountCapByObject(t,e,r){let{deepbook:n}=e,i=[t];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static async getAccountCap(t){let e=await t.fullClient.getOwnedObjectsByPage(t.senderAddress,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{MoveModule:{package:t.sdkOptions.deepbook.package_id,module:fa}}});return e.data.length===0?"":e.data[0].data.objectId}static async getPools(t){let e=t.sdkOptions.deepbook.package_id,r=[];try{(await t.fullClient.queryEventsByPage({MoveEventType:`${e}::clob_v2::PoolCreated`})).data.forEach(i=>{let o=i.parsedJson;o&&r.push({poolID:o.pool_id,tickSize:Number(o.tick_size),lotSize:Number(o.lot_size),takerFeeRate:Number(o.taker_fee_rate),makerRebateRate:Number(o.maker_rebate_rate),baseAsset:o.base_asset.name,quoteAsset:o.quote_asset.name})})}catch(n){console.log("getPoolImmutables",n)}return r}static async getPoolAsks(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>se(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async getPoolBids(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>se(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async preSwap(t,e,r,n){let i=!1,o=Y,s=new bt.default(n),u=Y,l=new bt.default(n);if(r){let d=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0),d=d.sort((b,_)=>_.price-b.price);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].quantity),T=new bt.default(d[b].price),x=_.mul(new bt.default(T)).mul(new bt.default(e.takerFeeRate)).div(gn).div(gn);if(s.gt(_))s=s.sub(_),o=o.add(_.mul(T).div(gn).sub(x)),u=u.add(x);else{let A=s.mul(new bt.default(d[b].price)).div(gn),I=A.mul(new bt.default(e.takerFeeRate)).div(gn);o=o.add(A.sub(I)),s=s.sub(s),u=u.add(I)}if(s.eq(Y))break}}else{let d=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].price).mul(new bt.default(d[b].quantity)).div(new bt.default(1e9)),T=_.mul(new bt.default(e.takerFeeRate)).div(gn),x=_.add(T);if(s.gt(_))o=o.add(new bt.default(d[b].quantity)),s=s.sub(x),u=u.add(T);else{let A=new bt.default(d[b].quantity).div(new bt.default(e.lotSize)),I=x.div(A),C=s.div(I);o=o.add(C.muln(e.lotSize)),s=s.sub(C.mul(I)),u=u.add(C.div(A).mul(T))}if(s.eq(Y))break}}return{poolAddress:e.poolID,estimatedAmountIn:l.sub(s).toNumber(),estimatedAmountOut:o.toNumber(),estimatedFeeAmount:u,isExceed:i,amount:Number(n),aToB:r,byAmountIn:!0}}static async simulateSwap(t,e,r,n,i,o){let{deepbook_endpoint_v2:s}=t.sdkOptions,u=new po.TransactionBlock,l=await this.getAccountCap(t),d;if(l===""){let H=this.createAccountCap(t.senderAddress,t.sdkOptions,u),W=H[0];u=H[1],d=W}else d=u.pure(l);let b=await t.getOwnerCoinAssets(t.senderAddress),T=Pe.buildCoinForAmount(u,b,BigInt(o),r,!1)?.targetCoin,A=Pe.buildCoinForAmount(u,b,BigInt(o),n,!1)?.targetCoin,I=[r,n],C=[u.pure(e),d,u.pure(o),u.pure(0),u.pure(i),T,A,u.pure(Ce)];u.moveCall({target:`${s.published_at}::${Dg}::swap`,arguments:C,typeArguments:I});let{simulationAccount:E}=t.sdkOptions,D=(await t.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:E.address})).events?.filter(H=>se(H.type).name==="DeepbookSwapEvent");if(D.length===0)return null;let L=D[0].parsedJson;return{poolAddress:L.pool,estimatedAmountIn:L.amount_in,estimatedAmountOut:L.amount_out,aToB:L.atob}}},b0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPositionList(t,e="all"){let r={data:[],hasNextPage:!0},n=await this._sdk.fullClient.getDynamicFieldsByPage(t,e);r.hasNextPage=n.hasNextPage,r.nextCursor=n.nextCursor;let i=n.data.map(s=>{if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getPositionList get position objects error: ${s.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");return s.name.value}),o=await this._sdk.Position.getSipmlePositionList(i);return r.data=o,r}async getPoolImmutables(t=[],e=0,r=100,n=!1){let{package_id:i}=this._sdk.sdkOptions.clmm_pool,o=`${i}_getInitPoolEvent`,s=this.getCache(o,n),u=[],l=[];if(s!==void 0&&u.push(...s),u.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${i}::factory::CreatePoolEvent`})).data.forEach(_=>{let T=_.parsedJson;T&&u.push({poolAddress:T.pool_id,tickSpacing:T.tick_spacing,coinTypeA:se(T.coin_type_a).full_address,coinTypeB:se(T.coin_type_b).full_address})}),this.updateCache(o,u,Oe)}catch(b){console.log("getPoolImmutables",b)}let d=t.length>0;for(let b=0;b<u.length;b+=1){let _=u[b];d&&!t.includes(_.poolAddress)||!d&&(b<e||b>=e+r)||l.push(_)}return l}async getPools(t=[],e=0,r=100){let n=[],i=[];t.length>0?i=[...t]:(await this.getPoolImmutables([],e,r,!1)).forEach(u=>i.push(u.poolAddress));let o=await this._sdk.fullClient.batchGetObjects(i,{showContent:!0,showType:!0});for(let s of o){if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let u=ha(s);n.push(u);let l=`${u.poolAddress}_getPoolObject`;this.updateCache(l,u,Oe)}return n}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:r}=this._sdk.sdkOptions.clmm_pool,n=[],i={data:[],hasNextPage:!1},o=t==="all",s=`${r}_getPoolImmutables`;if(o){let u=this.getCache(s,e);u&&n.push(...u)}if(n.length===0)try{let u=`${r}::factory::CreatePoolEvent`,l=await this._sdk.fullClient.queryEventsByPage({MoveEventType:u},t);i.hasNextPage=l.hasNextPage,i.nextCursor=l.nextCursor,l.data.forEach(d=>{let b=d.parsedJson;if(b){let _={poolAddress:b.pool_id,tickSpacing:b.tick_spacing,coinTypeA:se(b.coin_type_a).full_address,coinTypeB:se(b.coin_type_b).full_address};n.push(_)}})}catch(u){console.log("getPoolImmutables",u)}return i.data=n,o&&this.updateCache(`${r}_getPoolImmutables`,n,Oe),i}async getPoolsWithPage(t=[]){let e=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutablesWithPage()).data.forEach(o=>r.push(o.poolAddress));let n=await this._sdk.fullClient.batchGetObjects(r,{showContent:!0,showType:!0});for(let i of n){if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPoolWithPages error code: ${i.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=ha(i);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,Oe)}return e}async getPool(t,e=!0){let r=`${t}_getPoolObject`,n=this.getCache(r,e);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPool error code: ${i.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=ha(i);return this.updateCache(r,o),o}async creatPoolsTransactionPayload(t){for(let r of t)if(jl((0,zn.normalizeSuiAddress)(r.coinTypeA),(0,zn.normalizeSuiAddress)(r.coinTypeB))){let n=r.coinTypeB;r.coinTypeB=r.coinTypeA,r.coinTypeA=n}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(jl((0,zn.normalizeSuiAddress)(t.coinTypeA),(0,zn.normalizeSuiAddress)(t.coinTypeB))){let e=t.coinTypeB;t.coinTypeB=t.coinTypeA,t.coinTypeA=e}return"fix_amount_a"in t?await this.creatPoolAndAddLiquidity(t):await this.creatPool([t])}async getClmmConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.clmm_pool,r=`${e}_getInitEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=(await this._sdk.fullClient.queryEventsByPage({Transaction:o})).data,u={pools_id:"",global_config_id:"",global_vault_id:"",admin_cap_id:""};return s.length>0&&(s.forEach(l=>{let d=l.parsedJson;if(l.type)switch(se(l.type).full_address){case`${e}::config::InitConfigEvent`:u.global_config_id=d.global_config_id,u.admin_cap_id=d.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:u.pools_id=d.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:u.global_vault_id=d.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:u.partners_id=d.partners_id;break;default:break}}),this.updateCache(r,u,Oe)),u}async getSuiTransactionResponse(t,e=!1){let r=`${t}_getSuiTransactionResponse`,n=this.getCache(r,e);if(n!==void 0)return n;let i;try{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,i,Oe),i}async creatPool(t){let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id;return t.forEach(u=>{let l=[e.object(o),e.object(s),e.pure(u.tick_spacing.toString()),e.pure(u.initialize_sqrt_price),e.pure(u.uri),e.object(Ce)];e.moveCall({target:`${r.published_at}::${fo}::create_pool`,typeArguments:[u.coinTypeA,u.coinTypeB],arguments:l})}),e}async creatPoolAndAddLiquidity(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id,u=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),l=Pe.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,u,!1),d=Pe.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,u,!1),b=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),l.targetCoin,d.targetCoin,e.pure(Vt(BigInt(t.tick_lower)).toString()),e.pure(Vt(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(Ce)];return e.moveCall({target:`${r.published_at}::${Gr}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:b}),e}async fetchTicks(t){let e=[],r=[];for(;;){let i=await this.getTicks({pool_id:t.pool_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,start:r,limit:512});if(e=[...e,...i],i.length<512)break;r=[i[i.length-1].index]}return e}async getTicks(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[t.coinTypeA,t.coinTypeB],o=new wn.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Vr}::fetch_ticks`,arguments:s,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let u=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address});if(u.error!=null)throw new V(`getTicks error code: ${u.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return u.events?.forEach(l=>{se(l.type).name==="FetchTicksResultEvent"&&l.parsedJson.ticks.forEach(d=>{n.push(p0(d))})}),n}async fetchPositionRewardList(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[],o=512;for(;;){let s=[t.coinTypeA,t.coinTypeB],u=new wn.TransactionBlock,l=[u.object(t.pool_id),u.pure(i,"u64"),u.pure(o.toString(),"u64")];if(u.moveCall({target:`${e.published_at}::${Vr}::fetch_positions`,arguments:l,typeArguments:s}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let d=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:r.address});if(d.error!=null)throw new V(`fetch position reward error code: ${d.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let b=[];if(d?.events?.forEach(_=>{se(_.type).name==="FetchPositionsEvent"&&_.parsedJson.positions.forEach(T=>{let x=Jl(T);b.push(x)})}),n.push(...b),b.length<o)break;i=[b[b.length-1].pos_object_id]}return n}async fetchTicksByRpc(t){let e=[],r=null,n=512;for(;;){let i=[],o=await this.sdk.fullClient.getDynamicFields({parentId:t,cursor:r,limit:n});if(r=o.nextCursor,o.data.forEach(s=>{se(s.objectType).module==="skip_list"&&i.push(s.objectId)}),e=[...e,...await this.getTicksByRpc(i)],r===null||o.data.length<n)break}return e}async getTicksByRpc(t){let e=[],r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0,showType:!0});for(let n of r){if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${n.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let i=ma(n);i!=null&&e.push(i)}return e}async getTickDataByIndex(t,e){let r={type:"u64",value:Vt(BigInt($g(e).toString())).toString()},n=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:r});if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`get tick by index: ${e} error: ${n.error}`,"InvalidTickIndex");return ma(n)}async getTickDataByObjectId(t){let e=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0}});if(e.error!=null||e.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return ma(e)}async getPartnerRefFeeAmount(t){let e=await this._sdk.fullClient.batchGetObjects([t],{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0});if(e[0].error!=null||e[0].data?.content?.dataType!=="moveObject")throw new V(`get partner by object id: ${t} error: ${e[0].error}`,"NotFoundPartnerObject");let r=e[0].data.content.fields.balances,n=await this._sdk.fullClient.getDynamicFieldsByPage(r.fields.id.id),i=[];n.data.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`when getPartnerRefFeeAmount get partner object error: ${u.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");i.push(u.objectId)});let o=[];return(await this._sdk.fullClient.batchGetObjects(i,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`get coin by object id: ${u.data.objectId} error: ${u.error}`,"InvalidParnterRefFeeFields");let l={coinAddress:u.data.content.fields.name,coinObjectId:u.data.objectId,balance:BigInt(u.data.content.fields.value)};o.push(l)}),o}async claimPartnerRefFeePayload(t,e,r){let n=new wn.TransactionBlock,{clmm_pool:i}=this.sdk.sdkOptions,{global_config_id:o}=be(i),s=[r],u=[n.object(o),n.object(t),n.object(e)];return n.moveCall({target:`${i.published_at}::${Mg}::claim_ref_fee`,arguments:u,typeArguments:s}),n}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},_0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildPositionType(){return`${this._sdk.sdkOptions.clmm_pool.package_id}::position::Position`}async getPositionList(t,e=[]){let r=[],n=await this._sdk.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.clmm_pool.package_id}}),i=e.length>0;for(let o of n.data)if(se(o.data.type).full_address===this.buildPositionType()){let u=pa(o),l=`${u.pos_object_id}_getPositionList`;this.updateCache(l,u,Oe),i?e.includes(u.pool)&&r.push(u):r.push(u)}return r}async getPosition(t,e,r=!0){let n=await this.getSimplePosition(e);return r&&(n=await this.updatePositionRewarders(t,n)),n}async getPositionById(t,e=!0){let r=await this.getSimplePosition(t);if(e){let n=await this._sdk.Pool.getPool(r.pool,!1);return await this.updatePositionRewarders(n.position_manager.positions_handle,r)}return r}async getSimplePosition(t){let e=`${t}_getPositionList`,r=this.getSimplePositionByCache(t);if(r===void 0){let n=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0,showType:!0,showDisplay:!0,showOwner:!0}});r=pa(n),this.updateCache(e,r,Oe)}return r}getSimplePositionByCache(t){let e=`${t}_getPositionList`;return this.getCache(e)}async getSipmlePositionList(t){let e=[],r=[];return t.forEach(n=>{let i=this.getSimplePositionByCache(n);i?e.push(i):r.push(n)}),r.length>0&&(await this._sdk.fullClient.batchGetObjects(r,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(i=>{let o=pa(i);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,Oe)}),e}async updatePositionRewarders(t,e){let r=await this.getPositionRewarders(t,e.pos_object_id);return{...e,...r}}async getPositionRewarders(t,e){try{let r=await this._sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=br(r.data).value.fields.value;return Jl(i)}catch(r){console.log(r);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new Ur.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(l=>se(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new ga.default(d.fee_owned_a),feeOwedB:new ga.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async createAddLiquidityFixTokenPayload(t,e){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t=t,t.fix_amount_a&&n||!t.fix_amount_a&&i)return await Pe.buildAddLiquidityFixTokenForGas(this._sdk,r,t,e)}return Pe.buildAddLiquidityFixToken(this._sdk,r,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:r}=this._sdk.sdkOptions;if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let n=Vt(BigInt(t.tick_lower)).toString(),i=Vt(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new Ur.TransactionBlock,u=!(0,Xl.isValidSuiObjectId)(t.pos_id),l=BigInt(t.max_amount_a),d=BigInt(t.max_amount_b),b=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),_=Pe.buildCoinForAmount(s,b,l,t.coinTypeA,!1),T=Pe.buildCoinForAmount(s,b,d,t.coinTypeB,!1);return u?s.moveCall({target:`${e.published_at}::${Gr}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.pure(n),s.pure(i),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]}):(s=Pe.createCollectRewarderAndFeeParams(this._sdk,s,t,b,_.remainCoins,T.remainCoins),s.moveCall({target:`${e.published_at}::${Gr}::add_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.object(t.pos_id),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]})),s}async removeLiquidityTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n="remove_liquidity",i=new Ur.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);i=Pe.createCollectRewarderAndFeeParams(this._sdk,i,t,s);let u=[i.object(be(e).global_config_id),i.object(t.pool_id),i.object(t.pos_id),i.pure(t.delta_liquidity),i.pure(t.min_amount_a),i.pure(t.min_amount_b),i.object(Ce)];return i.moveCall({target:`${r.published_at}::${fo}::${n}`,typeArguments:o,arguments:u}),i}async closePositionTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return n=Pe.createCollectRewarderAndFeeParams(this._sdk,n,t,o),n.moveCall({target:`${r.published_at}::${fo}::close_position`,typeArguments:i,arguments:[n.object(be(e).global_config_id),n.object(t.pool_id),n.object(t.pos_id),n.pure(t.min_amount_a),n.pure(t.min_amount_b),n.object(Ce)]}),n}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=Vt(BigInt(t.tick_lower)).toString(),s=Vt(BigInt(t.tick_upper)).toString(),u=[n.pure(be(e).global_config_id),n.pure(t.pool_id),n.pure(o),n.pure(s)];return n.moveCall({target:`${r.published_at}::${fo}::open_position`,typeArguments:i,arguments:u}),n}async collectFeeTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),r=new Ur.TransactionBlock,n=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeA,!1),i=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeB,!1);return this.createCollectFeePaylod(t,r,n.targetCoin,i.targetCoin),r}createCollectFeePaylod(t,e,r,n){let{clmm_pool:i,integrate:o}=this.sdk.sdkOptions,s=[t.coinTypeA,t.coinTypeB],u=[e.object(be(i).global_config_id),e.object(t.pool_id),e.object(t.pos_id),r,n];return e.moveCall({target:`${o.published_at}::${Gr}::collect_fee`,typeArguments:s,arguments:u}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.fullClient.devInspectTransactionBlock({transactionBlock:e,sender:this._sdk.senderAddress});for(let n of r.events)if(se(n.type).name==="CollectFeeEvent"){let i=n.parsedJson;return{feeOwedA:i.amount_a,feeOwedB:i.amount_b}}return{feeOwedA:"0",feeOwedB:"0"}}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},v0=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[Y,Y,Y]}get sdk(){return this._sdk}async emissionsEveryDay(t){let r=(await this.sdk.Pool.getPool(t)).rewarder_infos;if(!r)return null;let n=[];for(let i of r){let o=fe.fromX64(new Se.default(i.emissions_per_second));n.push({emissions:Math.floor(o.toNumber()*60*60*24),coin_address:i.coinAddress})}return n}async updatePoolRewarder(t,e){let r=await this.sdk.Pool.getPool(t),n=r.rewarder_last_updated_time;if(r.rewarder_last_updated_time=e.toString(),Number(r.liquidity)===0||e.eq(new Se.default(n)))return r;let i=e.div(new Se.default(1e3)).sub(new Se.default(n)).add(new Se.default(15)),o=r.rewarder_infos;for(let s=0;s<o.length;s+=1){let u=o[s],l=fe.checkMulDivFloor(i,new Se.default(u.emissions_per_second),new Se.default(r.liquidity),128);this.growthGlobal[s]=new Se.default(u.growth_global).add(new Se.default(l))}return r}async posRewardersAmount(t,e,r){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(t,new Se.default(n)),o=await this.sdk.Position.getPositionRewarders(e,r);if(o===void 0)return[];let s=i.ticks_handle,u=await this.sdk.Pool.getTickDataByIndex(s,o.tick_lower_index),l=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(i,o,u,l)}async poolRewardersAmount(t,e){let r=Date.parse(new Date().toString()),n=await this.updatePoolRewarder(e,new Se.default(r)),i=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(n.ticks_handle,i),s=[Y,Y,Y];for(let u=0;u<i.length;u+=1){let l=await this.posRewardersAmountInternal(n,i[u],o[0][u],o[1][u]);for(let d=0;d<3;d+=1)s[d]=s[d].add(l[d].amount_owed)}return s}posRewardersAmountInternal(t,e,r,n){let i=e.tick_lower_index,o=e.tick_upper_index,s=m0(t,r,n,i,o,this.growthGlobal),u=[],l=[];if(s.length>0){let d=fe.subUnderflowU128(s[0],new Se.default(e.reward_growth_inside_0));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[0]),l.push({amount_owed:new Se.default(e.reward_amount_owed_0).add(b),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let d=fe.subUnderflowU128(s[1],new Se.default(e.reward_growth_inside_1));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[1]),l.push({amount_owed:new Se.default(e.reward_amount_owed_1).add(b),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let d=fe.subUnderflowU128(s[2],new Se.default(e.reward_growth_inside_2));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[2]),l.push({amount_owed:new Se.default(e.reward_amount_owed_2).add(b),coin_address:t.rewarder_infos[2].coinAddress})}return l}async batchFetchPositionRewarders(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB,rewarderInfo:o.rewarder_infos})}let r={};if(e.length>0){let n=await this.fetchPosRewardersAmount(e);for(let i of n)r[i.positionId]=i.rewarderAmountOwed;return r}return r}async fetchPositionRewarders(t,e){let r={poolAddress:t.poolAddress,positionId:e,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,rewarderInfo:t.rewarder_infos};return(await this.fetchPosRewardersAmount([r]))[0].rewarderAmountOwed}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(l=>se(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new Se.default(d.fee_owned_a),feeOwedB:new Se.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId),i.object(Ce)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_rewards`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V(`this config simulationAccount: ${n.address} is not set right`,"InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(l=>se(l.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new V("valueData.length !== params.pools.length");let u=[];for(let l=0;l<s.length;l+=1){let d={poolAddress:t[l].poolAddress,positionId:t[l].positionId,rewarderAmountOwed:[]};for(let b=0;b<t[l].rewarderInfo.length;b+=1)d.rewarderAmountOwed.push({amount_owed:new Se.default(s[l].parsedJson.data[b]),coin_address:t[l].rewarderInfo[b].coinAddress});u.push(d)}return u}async fetchPoolRewardersAmount(t,e){let r=await this.sdk.Pool.getPool(e),n=await this.sdk.Position.getPositionList(t,[e]),i=[];for(let u of n)i.push({poolAddress:r.poolAddress,positionId:u.pos_object_id,rewarderInfo:r.rewarder_infos,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB});let o=await this.fetchPosRewardersAmount(i),s=[Y,Y,Y];if(o!=null)for(let u of o)for(let l=0;l<u.rewarderAmountOwed.length;l+=1)s[l]=s[l].add(u.rewarderAmountOwed[l].amount_owed);return s}async getPoolLowerAndUpperTicks(t,e){let r=[],n=[];for(let i of e){let o=await this.sdk.Pool.getTickDataByIndex(t,i.tick_lower_index),s=await this.sdk.Pool.getTickDataByIndex(t,i.tick_upper_index);r.push(o),n.push(s)}return[r,n]}async collectRewarderTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),r=new mo.TransactionBlock;return r=Pe.createCollectRewarderAndFeeParams(this._sdk,r,t,e),r}createCollectRewarderPaylod(t,e,r){let{clmm_pool:n,integrate:i}=this.sdk.sdkOptions,o=be(n),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((u,l)=>{e&&e.moveCall({target:`${i.published_at}::${Gr}::collect_reward`,typeArguments:[...s,u],arguments:[e.object(o.global_config_id),e.object(t.pool_id),e.object(t.pos_id),e.object(o.global_vault_id),r[l],e.object(Ce)]})}),e}};function lo(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var T0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new Wr.Graph(!1),this._coinAddressMap=new Map,this.poolAddressMap=new Map,this._sdk=t,this.getPoolAddressMapAndDirection=this.getPoolAddressMapAndDirection.bind(this),this.setCoinList=this.setCoinList.bind(this),this.loadGraph=this.loadGraph.bind(this),this.addCoinProvider=this.addCoinProvider.bind(this),this.addPathProvider=this.addPathProvider.bind(this),this.preRouterSwapA2B2C=this.preRouterSwapA2B2C.bind(this),this.price=this.price.bind(this),this.getPoolWithTVL=this.getPoolWithTVL.bind(this)}get sdk(){return this._sdk}getPoolAddressMapAndDirection(t,e){let{pair:r,reversePair:n}=lo(t,e),i=this.poolAddressMap.get(r);if(i!=null)return{addressMap:i,direction:!0};if(i=this.poolAddressMap.get(n),i!=null)return{addressMap:i,direction:!1}}setCoinList(){this.coinProviders.coins.forEach(t=>{this._coinAddressMap.set(t.address,t)})}loadGraph(t,e){this.addCoinProvider(t),this.addPathProvider(e),this.setCoinList(),this.pathProviders.forEach(r=>{let{paths:n}=r;n.forEach(i=>{let o=this.graph.getVertexByKey(i.base)??new Wr.GraphVertex(i.base),s=this.graph.getVertexByKey(i.quote)??new Wr.GraphVertex(i.quote);this.graph.addEdge(new Wr.GraphEdge(o,s));let u=this._coinAddressMap.get(i.base),l=this._coinAddressMap.get(i.quote);if(u!=null&&l!=null){let d=lo(i.base,i.quote).pair;this.poolAddressMap.set(d,i.addressMap)}})})}addPathProvider(t){for(let e=0;e<t.paths.length;e+=1){let{base:r,quote:n}=t.paths[e];r.localeCompare(n)<0&&(t.paths[e].base=n,t.paths[e].quote=r),r==="0x2::sui::SUI"&&(t.paths[e].base=n,t.paths[e].quote=r),n==="0x2::sui::SUI"&&(t.paths[e].base=r,t.paths[e].quote=n)}return this.pathProviders.push(t),this}addCoinProvider(t){return this.coinProviders=t,this}tokenInfo(t){return this._coinAddressMap.get(t)}getFeeRate(t,e,r){let n=lo(t,e).pair,i=this.poolAddressMap.get(n);if(i!=null){for(let[u,l]of i.entries())if(l===r)return u*100}let o=lo(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[u,l]of s.entries())if(l===r)return u*100}return 0}async price(t,e,r,n,i,o,s){let u=this.tokenInfo(t),l=this.tokenInfo(e);if(u===void 0||l===void 0)throw new V("From/To coin is undefined","InvalidCoin");let d=this.graph.getVertexByKey(u.address),b=this.graph.getVertexByKey(l.address),_=this.graph.findAllPath(d,b),T=Array.from(_);if(T.length===0)throw new V("No find valid path in coin graph","NotFoundPath");let x=[];for(let N=0;N<T.length;N+=1){let j=T[N];if(j.length>3)continue;let S=[],k=[],a=[],c=[];for(let m=0;m<j.length-1;m+=1){let y=j[m].value.toString(),p=j[m+1].value.toString(),h=this.getPoolAddressMapAndDirection(y,p),w=h?.addressMap,g=h?.direction;w!=null&&g!=null&&(k.push(g),S.push(y),S.push(p),w.forEach(f=>{m===0?a.push(f):c.push(f)}))}for(let m of a)if(c.length>0)for(let y of c){let p={stepNums:2,poolAB:m,poolBC:y,a2b:k[0],b2c:k[1],amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:S[3]};x.push(p)}else{let y={stepNums:1,poolAB:m,poolBC:void 0,a2b:k[0],b2c:void 0,amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:void 0};x.push(y)}}let A=x.filter(N=>N.stepNums===1),I=x.filter(N=>N.stepNums!==1),C=[];try{C=await this.getPoolWithTVL()}catch{C=[]}if(C.length>0){let N=new Map(C.map(j=>[j.poolAddress,j]));I.sort((j,S)=>{let k=0,a=0;if(N.has(j.poolAB)&&N.has(j.poolBC)){let c=N.get(j.poolAB),m=N.get(j.poolBC);k=Math.min(c.tvl,m.tvl)}if(N.has(S.poolAB)&&N.has(S.poolBC)){let c=N.get(S.poolAB),m=N.get(S.poolBC);a=Math.min(c.tvl,m.tvl)}return a-k})}if(x=[...A,...I],x.length===0){if(s!=null){let N=await this.sdk.Swap.preSwapWithMultiPool(s),j={amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),poolAddress:[N.poolAddress],a2b:[N.aToB],rawAmountLimit:n?[N.estimatedAmountOut]:[N.estimatedAmountIn],isExceed:N.isExceed,coinType:[t,e]},S={paths:[j],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),paths:[j],a2b:N.aToB,b2c:void 0,byAmountIn:n,isExceed:N.isExceed,targetSqrtPrice:[N.estimatedEndSqrtPrice],currentSqrtPrice:[N.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:S}}throw new V("No parameters available for service downgrade","NoDowngradeNeedParams")}let E=await this.preRouterSwapA2B2C(x.slice(0,16));if(E==null){if(s!=null){let j=await this.sdk.Swap.preSwapWithMultiPool(s),S={amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),poolAddress:[j.poolAddress],a2b:[j.aToB],rawAmountLimit:n?[j.estimatedAmountOut]:[j.estimatedAmountIn],isExceed:j.isExceed,coinType:[t,e]},k={paths:[S],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),paths:[S],a2b:j.aToB,b2c:void 0,byAmountIn:n,isExceed:j.isExceed,targetSqrtPrice:[j.estimatedEndSqrtPrice],currentSqrtPrice:[j.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:k}}return{amountIn:Y,amountOut:Y,paths:[],a2b:!1,b2c:!1,byAmountIn:n,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let P=E.index,D=x[P].poolBC!=null?[x[P].poolAB,x[P].poolBC]:[x[P].poolAB],L=n?[E.amountMedium,E.amountOut]:[E.amountIn,E.amountMedium],H=[];H.push(x[P].a2b),E.stepNum>1&&H.push(x[P].b2c);let W=[];W.push(x[P].coinTypeA),W.push(x[P].coinTypeB),E.stepNum>1&&W.push(x[P].coinTypeC);let K={amountIn:E.amountIn,amountOut:E.amountOut,poolAddress:D,a2b:H,rawAmountLimit:L,isExceed:E.isExceed,coinType:W},F={paths:[K],partner:o,priceSlippagePoint:i};return{amountIn:E.amountIn,amountOut:E.amountOut,paths:[K],a2b:x[P].a2b,b2c:E.stepNum>1?x[P].b2c:void 0,byAmountIn:n,isExceed:E.isExceed,targetSqrtPrice:E.targetSqrtPrice,currentSqrtPrice:E.currentSqrtPrice,coinTypeA:x[P].coinTypeA,coinTypeB:x[P].coinTypeB,coinTypeC:E.stepNum>1?x[P].coinTypeC:void 0,createTxParams:F}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new Yl.TransactionBlock;for(let _ of t)if(_.stepNums>1){let T=[n.object(_.poolAB),n.object(_.poolBC),n.pure(_.a2b),n.pure(_.b2c),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=[];_.a2b?x.push(_.coinTypeA,_.coinTypeB):x.push(_.coinTypeB,_.coinTypeA),_.b2c?x.push(_.coinTypeB,_.coinTypeC):x.push(_.coinTypeC,_.coinTypeB),n.moveCall({target:`${e.published_at}::${Wn}::calculate_router_swap_result`,typeArguments:x,arguments:T})}else{let T=[n.pure(_.poolAB),n.pure(_.a2b),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=_.a2b?[_.coinTypeA,_.coinTypeB]:[_.coinTypeB,_.coinTypeA];n.moveCall({target:`${e.published_at}::${Eg}::get_expect_swap_result`,arguments:T,typeArguments:x})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address})).events?.filter(_=>se(_.type).name==="CalculatedRouterSwapResultEvent"||se(_.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?Y:_n,u=0;for(let _=0;_<o.length;_+=1)if(!o[_].parsedJson.data.is_exceed)if(t[0].byAmountIn){let T=new Et.default(o[_].parsedJson.data.amount_out);T.gt(s)&&(u=_,s=T)}else{let T=t[_].stepNums>1?new Et.default(o[_].parsedJson.data.amount_in):new Et.default(o[_].parsedJson.data.amount_in).add(new Et.default(o[_].parsedJson.data.fee_amount));T.lt(s)&&(u=_,s=T)}let l=[],d=[];return t[u].stepNums>1?(d.push(o[u].parsedJson.data.target_sqrt_price_ab,o[u].parsedJson.data.target_sqrt_price_cd),l.push(o[u].parsedJson.data.current_sqrt_price_ab,o[u].parsedJson.data.current_sqrt_price_cd)):(d.push(o[u].parsedJson.data.after_sqrt_price),l.push(o[u].parsedJson.current_sqrt_price)),{index:u,amountIn:t[0].byAmountIn?t[u].amount:s,amountMedium:o[u].parsedJson.data.amount_medium,amountOut:t[0].byAmountIn?s:t[u].amount,targetSqrtPrice:d,currentSqrtPrice:l,isExceed:o[u].parsedJson.data.is_exceed,stepNum:t[u].stepNums}}async getPoolWithTVL(){let t=[],{swapCountUrl:e}=this._sdk.sdkOptions;if(!e)return t;let r;try{r=await fetch(e)}catch{throw new V(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let n;try{n=await r.json()}catch{throw new V(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(n.code!==200)throw new V(`Failed to get pool list from ${e}. Statu code is ${n.code}.`,"InvalidSwapCountUrl");let{pools:i}=n.data;for(let o of i)t.push({poolAddress:o.swap_account,tvl:Number(o.tvl_in_usd)});return t}};var S0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n>0){let i=r.basePaths[0],o=i.label==="Cetus"?new $(i.feeRate).div(10**6):new $(i.feeRate).div(10**9),s=vt(i.inputAmount).div(10**i.fromDecimal).mul(o);if(e=e.add(s),n>1){let u=r.basePaths[1],l=i.direction?i.currentPrice:new $(1).div(i.currentPrice),d=u.direction?u.currentPrice:new $(1).div(u.currentPrice),b=u.label==="Cetus"?new $(u.feeRate).div(10**6):new $(u.feeRate).div(10**9),T=vt(u.outputAmount).div(10**u.toDecimal).mul(b).div(l.mul(d));e=e.add(T)}}}),e.toString()}calculateSwapPriceImpact(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n===1){let i=r.basePaths[0],o=vt(i.outputAmount).div(10**i.toDecimal),s=vt(i.inputAmount).div(10**i.fromDecimal),u=o.div(s),l=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice);e=e.add(this.calculateSingleImpact(u,l))}if(n===2){let i=r.basePaths[0],o=r.basePaths[1],s=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice),u=o.direction?new $(o.currentPrice):new $(1).div(o.currentPrice),l=s.mul(u),d=new $(o.outputAmount).div(10**o.toDecimal),b=new $(i.inputAmount).div(10**i.fromDecimal),_=d.div(b);e=e.add(this.calculateSingleImpact(_,l))}}),e.toString()}calculateSingleImpact=(t,e)=>e.minus(t).div(e).mul(100);async preSwapWithMultiPool(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB];for(let d=0;d<t.poolAddresses.length;d+=1){let b=[n.pure(t.poolAddresses[d]),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:b,typeArguments:i})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(o.error!=null)throw new V(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(d=>se(d.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new V("valueData.length !== params.pools.length","ParamsLengthNotEqual");let u=t.byAmountIn?Y:_n,l=0;for(let d=0;d<s.length;d+=1)if(!s[d].parsedJson.data.is_exceed)if(t.byAmountIn){let b=new $r.default(s[d].parsedJson.data.amount_out);b.gt(u)&&(l=d,u=b)}else{let b=new $r.default(s[d].parsedJson.data.amount_out);b.lt(u)&&(l=d,u=b)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[l],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[l].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=[n.pure(t.pool.poolAddress),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];if(n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:o,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let s=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(s.error!=null)throw new V(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let u=s.events?.filter(l=>se(l.type).name==="CalculatedSwapResultEvent");return u.length===0?null:this.transformSwapData(t,u[0].parsedJson.data)}transformSwapData(t,e){let r=e.amount_in&&e.fee_amount?new $r.default(e.amount_in).add(new $r.default(e.fee_amount)).toString():"";return{poolAddress:t.pool.poolAddress,currentSqrtPrice:t.currentSqrtPrice,estimatedAmountIn:r,estimatedAmountOut:e.amount_out,estimatedEndSqrtPrice:e.after_sqrt_price,estimatedFeeAmount:e.fee_amount,isExceed:e.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}transformSwapWithMultiPoolData(t,e){let{data:r}=e,n=r.amount_in&&r.fee_amount?new $r.default(r.amount_in).add(new $r.default(r.fee_amount)).toString():"";return{poolAddress:t.poolAddress,estimatedAmountIn:n,estimatedAmountOut:r.amount_out,estimatedEndSqrtPrice:r.after_sqrt_price,estimatedStartSqrtPrice:e.current_sqrt_price,estimatedFeeAmount:r.fee_amount,isExceed:r.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}calculateRates(t){let{currentPool:e}=t,r=Og(e),n;t.a2b?n=t.swapTicks.sort((_,T)=>T.index-_.index):n=t.swapTicks.sort((_,T)=>_.index-T.index);let i=Wg(t.a2b,t.byAmountIn,t.amount,r,n),o=!1;t.byAmountIn?o=i.amountIn.lt(t.amount):o=i.amountOut.lt(t.amount);let s=yr.getDefaultSqrtPriceLimit(t.a2b);t.a2b&&i.nextSqrtPrice.lt(s)&&(o=!0),!t.a2b&&i.nextSqrtPrice.gt(s)&&(o=!0);let u=0;i.crossTickNum>6&&i.crossTickNum<40&&(u=22e3*(i.crossTickNum-6)),i.crossTickNum>40&&(o=!0);let l=ke.sqrtPriceX64ToPrice(r.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),d=ke.sqrtPriceX64ToPrice(i.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),b=Math.abs(l-d)/l*100;return{estimatedAmountIn:i.amountIn,estimatedAmountOut:i.amountOut,estimatedEndSqrtPrice:i.nextSqrtPrice,estimatedFeeAmount:i.feeAmount,isExceed:o,extraComputeLimit:u,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn,priceImpactPct:b}}async createSwapTransactionPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionForGas(this._sdk,t,r,e)}return Pe.buildSwapTransaction(this.sdk,t,r)}async createSwapTransactionWithoutTransferCoinsPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,r,e)}return Pe.buildSwapTransactionWithoutTransferCoins(this.sdk,t,r)}},x0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getAllRegisteredTokenList(t=!1){return await this.factchTokenList("",t)}async getOwnerTokenList(t="",e=!1){return await this.factchTokenList(t,e)}async getAllRegisteredPoolList(t=!1){return await this.factchPoolList("",t)}async getOwnerPoolList(t="",e=!1){return await this.factchPoolList(t,e)}async getWarpPoolList(t=!1){return await this.factchWarpPoolList("","",t)}async getOwnerWarpPoolList(t="",e="",r=!1){return await this.factchWarpPoolList(t,e,r)}async getTokenListByCoinTypes(t){let e={},n=this.getCache("getAllRegisteredTokenList");if(n!==void 0){let o=n;for(let s of t)for(let u of o)if(sr(s)===sr(u.address)){e[s]=u;continue}}let i=t.filter(o=>e[o]===void 0);for(let o of i){let s=`${o}_metadata`,u=this.getCache(s);if(u!==void 0)e[o]=u;else{let l=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(l){let d={id:l.id,name:l.name,symbol:l.symbol,official_symbol:l.symbol,coingecko_id:"",decimals:l.decimals,project_url:"",logo_url:l.iconUrl,address:o};e[o]=d,this.updateCache(s,d,Oe)}}}return e}async factchTokenList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredTokenList",e);if(o!==void 0)return o;let s=t.length>0,u=512,l=0,d=[];if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;_.moveCall({target:`${n.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[_.pure(b.coin_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.coin_registry_id),_.pure(l),_.pure(u)]});let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{se(A.type).full_address===`${n.published_at}::coin_list::FetchCoinListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!1))})}),d=[...d,...x],x.length<u)break;l=d.length}return d}async factchPoolList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredPoolList",e);if(o!==void 0)return o;let s=[],u=512,l=0,d=t.length>0;if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;if(_.moveCall({target:`${n.published_at}::lp_list::${d?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:d?[_.pure(b.pool_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.pool_registry_id),_.pure(l),_.pure(u)]}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{se(A.type).full_address===`${n.published_at}::lp_list::FetchPoolListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!0))})}),s=[...s,...x],x.length<u)break;l=s.length}return s}async factchWarpPoolList(t="",e="",r=!1){let n=await this.factchPoolList(t,r);if(n.length===0)return[];let i=await this.factchTokenList(e,r),o=[];for(let s of n){for(let u of i)u.address===s.coin_a_address&&(s.coinA=u),u.address===s.coin_b_address&&(s.coinB=u);o.push(s)}return o}async getTokenConfigEvent(t=!1){let e=this._sdk.sdkOptions.token.package_id,r=`${e}_getTokenConfigEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_registry_id:"",pool_registry_id:"",coin_list_owner:"",pool_list_owner:""};return s.data.length>0&&s.data.forEach(l=>{let d=se(l.type);if(l.transactionModule==="coin_list")switch(d.name){case"InitListEvent":u.coin_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent":u.coin_registry_id=l.parsedJson.registry_id;break;default:break}else if(l.transactionModule==="lp_list")switch(d.name){case"InitListEvent<address>":u.pool_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent<address>":u.pool_registry_id=l.parsedJson.registry_id;break;default:break}}),u.coin_registry_id.length>0&&this.updateCache(r,u,Oe),u}transformData(t,e){let r={...t};if(e)try{r.coin_a_address=se(r.coin_a_address).full_address,r.coin_b_address=se(r.coin_b_address).full_address}catch{}else r.address=se(r.address).full_address;if(t.extensions){let n=t.extensions.contents;for(let i of n){let{key:o}=i,{value:s}=i;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}o==="pyth_id"&&(s=(0,Ql.normalizeSuiObjectId)(s)),r[o]=s}delete r.extensions}return r}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},k0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculatePrice(t,e,r,n,i){let o=n?e:r,s=n?r:e;return i==="Cetus"?ke.sqrtPriceX64ToPrice(t,o,s):new $(t.toString()).div(new $(10).pow(new $(s+9-o)))}parseJsonResult(t){return{isExceed:t.is_exceed,isTimeout:t.is_timeout,inputAmount:t.input_amount,outputAmount:t.output_amount,fromCoin:t.from_coin,toCoin:t.to_coin,byAmountIn:t.by_amount_in,splitPaths:t.split_paths.map(r=>({pathIndex:r.path_index,lastQuoteOutput:r.last_quote_output,percent:r.percent,basePaths:r.best_path.map(i=>({direction:i.direction,label:i.label,poolAddress:i.provider,fromCoin:i.from_coin,toCoin:i.to_coin,outputAmount:i.output_amount,inputAmount:i.input_amount,feeRate:i.fee_rate,currentSqrtPrice:new Gt.default(i.current_sqrt_price.toString()),afterSqrtPrice:i.label==="Cetus"?new Gt.default(i.after_sqrt_price.toString()):Y,fromDecimal:i.from_decimal,toDecimal:i.to_decimal,currentPrice:this.calculatePrice(new Gt.default(i.current_sqrt_price.toString()),i.from_decimal,i.to_decimal,i.direction,i.label)})),inputAmount:r.input_amount,outputAmount:r.output_amount}))}}async fetchWithTimeout(t,e,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let o=await fetch(t,{...e,signal:n.signal});return clearTimeout(i),o}catch{return null}}async fetchAndParseData(t,e){try{let n=await this.fetchWithTimeout(t,e,1500);return n.status===200?this.parseJsonResult(await n.json()):null}catch{return null}}async getBestRouter(t,e,r,n,i,o,s,u,l=!1,d=!1,b=[]){let _=null,T="v2",x={},A=this.sdk.sdkOptions.aggregatorUrl;if(b.length>0){let I=new URL(A);A=`${I.protocol}//${I.hostname}/router_with_lp_changes`,x={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:r,by_amount_in:n,order_split:l,external_router:d,sender_address:"None",request_id:encodeURIComponent(ao()),lp_changes:b})}}else A=`
4
4
  ${A}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(r)}&by_amount_in=${encodeURIComponent(n)}&order_split=${encodeURIComponent(l)}&external_router=${encodeURIComponent(d)}&sender_address=''&request_id=${encodeURIComponent(ao())}
5
- `;if(_=await this.fetchAndParseData(A,x),_?.isTimeout||_==null){let I=await this.sdk.Router.price(t,e,new Gt.default(r),n,i,o,u),C=[];for(let P of I.paths){let D=[];if(P.poolAddress.length>1){let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W},U=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,N=this.sdk.Router.tokenInfo(P.coinType[2]).decimals,j=P.a2b[1]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),U,N):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),N,U),S={direction:P.a2b[1],label:"Cetus",poolAddress:P.poolAddress[1],fromCoin:P.coinType[1],toCoin:P.coinType[2],feeRate:this.sdk.Router.getFeeRate(P.coinType[1],P.coinType[2],P.poolAddress[1]),outputAmount:P.amountOut.toString(),inputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),currentSqrtPrice:I.currentSqrtPrice[1],currentPrice:j,fromDecimal:U,toDecimal:N};D.push(F,S)}else{let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:P.amountOut.toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W};D.push(F)}let L={percent:Number(P.amountIn)/Number(I.amountIn)*100,inputAmount:Number(P.amountIn.toString()),outputAmount:Number(P.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:D};C.push(L)}let E={isExceed:I.isExceed,isTimeout:!0,inputAmount:Number(I.amountIn.toString()),outputAmount:Number(I.amountOut.toString()),fromCoin:I.coinTypeA,toCoin:I.coinTypeC!=null?I.coinTypeC:I.coinTypeB,byAmountIn:I.byAmountIn,splitPaths:C};T="v1",_=E}return{result:_,version:T}}},A0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=be(this.sdk.sdkOptions.cetus_config),r=`${e}_getCoinConfigs`,n=this.getCache(r),i=n?[...n,...t]:t;this.updateCache(r,i,Oe)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n);if(i!==void 0){let s=i;for(let u of t)for(let l of s)if(sr(u)===sr(l.address)){e[u]=l;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let u=`${s}_metadata`,l=this.getCache(u);if(l!==void 0)e[s]=l;else{let d=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(d){let b={id:d.id,pyth_id:"",name:d.name,symbol:d.symbol,official_symbol:d.symbol,coingecko_id:"",decimals:d.decimals,project_url:"",logo_url:d.iconUrl,address:s};e[s]=b,this.updateCache(u,b,Oe)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildCoinConfig(d,e);this.updateCache(`${r}_${b.address}_getCoinConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getCoinConfig(t,e=!1,r=!0){let{coin_list_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${n}_${t}_getCoinConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"0x1::type_name::TypeName",value:{name:Yg(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfig get object error: ${s.error}, please check the rpc and contracts address config.`,"InvalidConfig");let u=this.buildCoinConfig(s,r);return this.updateCache(i,u,Oe),u}buildCoinConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.address=ae(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=(0,go.normalizeSuiObjectId)(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,e),delete n.coin_type,n}async getClmmPoolConfigs(t=!1,e=!0){let{clmm_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getClmmPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getClmmPoolsConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildClmmPoolConfig(d,e);this.updateCache(`${b.pool_address}_getClmmPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getClmmPoolConfig(t,e=!1,r=!0){let{clmm_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getClmmPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildClmmPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildClmmPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e),n}async getLaunchpadPoolConfigs(t=!1,e=!0){let{launchpad_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getLaunchpadPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildLaunchpadPoolConfig(d,e);this.updateCache(`${b.pool_address}_getLaunchpadPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getLaunchpadPoolConfig(t,e=!1,r=!0){let{launchpad_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getLaunchpadPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildLaunchpadPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildLaunchpadPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e);let i=[];r.social_media.fields.contents.forEach(o=>{i.push({name:o.fields.value.fields.name,link:o.fields.value.fields.link})}),n.social_media=i;try{n.regulation=decodeURIComponent(mn.decode(n.regulation).replace(/%/g,"%25"))}catch{n.regulation=mn.decode(n.regulation)}return n}transformExtensions(t,e,r=!0){let n=[];for(let i of e){let{key:o}=i.fields,{value:s}=i.fields;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}r&&(t[o]=s),n.push({key:o,value:s})}delete t.extension_fields,r||(t.extensions=n)}async getCetusConfig(t=!1){let e=this._sdk.sdkOptions.cetus_config.package_id,r=`${e}_getCetusConfig`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_list_id:"",launchpad_pools_id:"",clmm_pools_id:"",admin_cap_id:"",global_config_id:"",coin_list_handle:"",launchpad_pools_handle:"",clmm_pools_handle:""};if(s.data.length>0)for(let l of s.data)switch(ae(l.type).name){case"InitCoinListEvent":u.coin_list_id=l.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":u.launchpad_pools_id=l.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":u.clmm_pools_id=l.parsedJson.pools_id;break;case"InitConfigEvent":u.global_config_id=l.parsedJson.global_config_id,u.admin_cap_id=l.parsedJson.admin_cap_id;break;default:break}return u=await this.getCetusConfigHandle(u),u.clmm_pools_id.length>0&&this.updateCache(r,u,Oe),u}async getCetusConfigHandle(t){let e=[t.clmm_pools_id,t.coin_list_id,t.launchpad_pools_id];return(await this._sdk.fullClient.multiGetObjects({ids:e,options:{showContent:!0}})).forEach(n=>{if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`when getCetusConfigHandle get objects error: ${n.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let i=br(n),o=c0(n);switch(ae(o).name){case"ClmmPools":t.clmm_pools_handle=i.pools.fields.id.id;break;case"CoinList":t.coin_list_handle=i.coins.fields.id.id;break;case"LaunchpadPools":t.launchpad_pools_handle=i.pools.fields.id.id;break;default:break}}),t}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){try{let r=this._cache[t];if(!r)return;if(e||!r.isValid()){delete this._cache[t];return}return r.value}catch(r){console.error(`Error accessing cache for key ${t}:`,r);return}}},I0=class extends td.SuiClient{async queryEventsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.queryEvents({query:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async getOwnedObjectsByPage(t,e,r="all"){let n=[],i=!0,o=r==="all",s=o?null:r.cursor;do{let u=await this.getOwnedObjects({owner:t,...e,cursor:s,limit:o?null:r.limit});u.data?(n=[...n,...u.data],i=u.hasNextPage,s=u.nextCursor):i=!1}while(o&&i);return{data:n,nextCursor:s,hasNextPage:i}}async getDynamicFieldsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.getDynamicFields({parentId:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async batchGetObjects(t,e,r=50){let n=[];try{for(let i=0;i<Math.ceil(t.length/r);i++){let o=await this.multiGetObjects({ids:t.slice(i*r,r*(i+1)),options:e});n=[...n,...o]}}catch(i){console.log(i)}return n}async calculationTxGas(t){let{sender:e}=t.blockData;if(e===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:t,sender:e}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(t,e){try{return await this.signAndExecuteTransactionBlock({transactionBlock:e,signer:t,options:{showEffects:!0,showEvents:!0}})}catch(r){console.log("error: ",r)}}async sendSimulationTransaction(t,e,r=!0){try{if(r)return await this.devInspectTransactionBlock({transactionBlock:t,sender:e});let i={ProgrammableTransaction:{inputs:t.blockData.inputs.map(l=>{let{type:d,value:b}=l;return d==="object"?ed.Inputs.SharedObjectRef({objectId:b,initialSharedVersion:0,mutable:!0}):b}),transactions:t.blockData.transactions}},o=rd.bcs.TransactionKind.serialize(i,{maxSize:131072}).toBytes(),s=Js(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(n){console.log("devInspectTransactionBlock error",n)}}},nd=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new I0({url:t.fullRpcUrl}),this._swap=new S0(this),this._pool=new b0(this),this._position=new _0(this),this._rewarder=new v0(this),this._router=new T0(this),this._router_v2=new k0(this),this._token=new x0(this),this._config=new A0(this),zl(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(t){this._senderAddress=t}get Swap(){return this._swap}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}get Pool(){return this._pool}get Position(){return this._position}get Rewarder(){return this._rewarder}get Router(){return this._router}get RouterV2(){return this._router_v2}get CetusConfig(){return this._config}get Token(){return this._token}async getOwnerCoinAssets(t,e,r=!0){let n=[],i=null,o=`${this.sdkOptions.fullRpcUrl}_${t}_${e}_getOwnerCoinAssets`,s=this.getCache(o,r);if(s)return s;for(;;){let u=await(e?this.fullClient.getCoins({owner:t,coinType:e,cursor:i}):this.fullClient.getAllCoins({owner:t,cursor:i}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&n.push({coinAddress:ae(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),i=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,n,30*1e3),n}async getOwnerCoinBalances(t,e){let r=[];return e?r=[await this.fullClient.getBalance({owner:t,coinType:e})]:r=[...await this.fullClient.getAllBalances({owner:t})],r}updateCache(t,e,r=Oe){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}};var fh=require("@msafe/sui3-utils"),Oh=require("@mysten/sui.js/client"),dr=de(require("axios"),1),on=require("@mysten/sui.js/utils"),Ln=require("@mysten/sui.js/utils");var ar=class extends Error{},So=class extends ar{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},xo=class extends ar{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},ko=class extends ar{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},zt=class extends ar{},vn=class extends ar{constructor(e){super(`Invalid unit ${e}`)}},lt=class extends ar{},Wt=class extends ar{constructor(){super("Zone is an abstract class")}};var z="numeric",Ht="short",Pt="long",_r={year:z,month:z,day:z},Xn={year:z,month:Ht,day:z},va={year:z,month:Ht,day:z,weekday:Ht},Yn={year:z,month:Pt,day:z},Qn={year:z,month:Pt,day:z,weekday:Pt},ei={hour:z,minute:z},ti={hour:z,minute:z,second:z},ri={hour:z,minute:z,second:z,timeZoneName:Ht},ni={hour:z,minute:z,second:z,timeZoneName:Pt},ii={hour:z,minute:z,hourCycle:"h23"},oi={hour:z,minute:z,second:z,hourCycle:"h23"},si={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Ht},ai={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Pt},ui={year:z,month:z,day:z,hour:z,minute:z},ci={year:z,month:z,day:z,hour:z,minute:z,second:z},li={year:z,month:Ht,day:z,hour:z,minute:z},di={year:z,month:Ht,day:z,hour:z,minute:z,second:z},Ta={year:z,month:Ht,day:z,weekday:Ht,hour:z,minute:z},fi={year:z,month:Pt,day:z,hour:z,minute:z,timeZoneName:Ht},hi={year:z,month:Pt,day:z,hour:z,minute:z,second:z,timeZoneName:Ht},pi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,timeZoneName:Pt},mi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,second:z,timeZoneName:Pt};var Ot=class{get type(){throw new Wt}get name(){throw new Wt}get ianaName(){return this.name}get isUniversal(){throw new Wt}offsetName(e,r){throw new Wt}formatOffset(e,r){throw new Wt}offset(e){throw new Wt}equals(e){throw new Wt}get isValid(){throw new Wt}};var Sa=null,vr=class t extends Ot{static get instance(){return Sa===null&&(Sa=new t),Sa}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Oo={};function C0(t){return Oo[t]||(Oo[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Oo[t]}var O0={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function M0(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,o,s,u,l,d,b]=n;return[s,i,o,u,l,d,b]}function E0(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:o,value:s}=r[i],u=O0[o];o==="era"?n[u]=s:ne(u)||(n[u]=parseInt(s,10))}return n}var Co={},At=class t extends Ot{static create(e){return Co[e]||(Co[e]=new t(e)),Co[e]}static resetCache(){Co={},Oo={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n,this.name)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=C0(this.name),[i,o,s,u,l,d,b]=n.formatToParts?E0(n,r):M0(n,r);u==="BC"&&(i=-Math.abs(i)+1);let T=Tn({year:i,month:o,day:s,hour:l===24?0:l,minute:d,second:b,millisecond:0}),x=+r,A=x%1e3;return x-=A>=0?A:1e3+A,(T-x)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var id={};function P0(t,e={}){let r=JSON.stringify([t,e]),n=id[r];return n||(n=new Intl.ListFormat(t,e),id[r]=n),n}var xa={};function ka(t,e={}){let r=JSON.stringify([t,e]),n=xa[r];return n||(n=new Intl.DateTimeFormat(t,e),xa[r]=n),n}var Aa={};function D0(t,e={}){let r=JSON.stringify([t,e]),n=Aa[r];return n||(n=new Intl.NumberFormat(t,e),Aa[r]=n),n}var Ia={};function B0(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),o=Ia[i];return o||(o=new Intl.RelativeTimeFormat(t,e),Ia[i]=o),o}var gi=null;function N0(){return gi||(gi=new Intl.DateTimeFormat().resolvedOptions().locale,gi)}var od={};function R0(t){let e=od[t];if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,od[t]=e}return e}function j0(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=ka(t).resolvedOptions(),i=t}catch{let l=t.substring(0,r);n=ka(l).resolvedOptions(),i=l}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function F0(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function q0(t){let e=[];for(let r=1;r<=12;r++){let n=le.utc(2009,r,1);e.push(t(n))}return e}function L0(t){let e=[];for(let r=1;r<=7;r++){let n=le.utc(2016,11,13+r);e.push(t(n))}return e}function Mo(t,e,r,n){let i=t.listingMode();return i==="error"?null:i==="en"?r(e):n(e)}function U0(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var Ca=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!r||Object.keys(s).length>0){let u={useGrouping:!1,...n};n.padTo>0&&(u.minimumIntegerDigits=n.padTo),this.inf=D0(e,u)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):Sn(e,3);return Ee(r,this.padTo)}}},Oa=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),u=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&At.create(u).valid?(i=u,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=ka(r,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Ma=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&Eo()&&(this.rtf=B0(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):sd(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},$0={firstDay:1,minimalDays:4,weekend:[6,7]},ge=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,i,o=!1){let s=e||he.defaultLocale,u=s||(o?"en-US":N0()),l=r||he.defaultNumberingSystem,d=n||he.defaultOutputCalendar,b=wi(i)||he.defaultWeekSettings;return new t(u,l,d,b,s)}static resetCache(){gi=null,xa={},Aa={},Ia={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:i}={}){return t.create(e,r,n,i)}constructor(e,r,n,i,o){let[s,u,l]=j0(e);this.locale=s,this.numberingSystem=r||u||null,this.outputCalendar=n||l||null,this.weekSettings=i,this.intl=F0(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=o,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=U0(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,wi(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return Mo(this,e,Ea,()=>{let n=r?{month:e,day:"numeric"}:{month:e},i=r?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=q0(o=>this.extract(o,n,"month"))),this.monthsCache[i][e]})}weekdays(e,r=!1){return Mo(this,e,Pa,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=r?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=L0(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return Mo(this,void 0,()=>Da,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[le.utc(2016,11,13,9),le.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Mo(this,e,Ba,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[le.utc(-40,1,1),le.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),o=i.formatToParts(),s=o.find(u=>u.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new Ca(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Oa(e,this.intl,r)}relFormatter(e={}){return new Ma(this.intl,this.isEnglish(),e)}listFormatter(e={}){return P0(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Po()?R0(this.locale):$0}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var Ra=null,ht=class t extends Ot{static get utcInstance(){return Ra===null&&(Ra=new t(0)),Ra}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(Hr(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Tr(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Tr(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return Tr(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var xn=class extends Ot{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Zt(t,e){let r;if(ne(t)||t===null)return e;if(t instanceof Ot)return t;if(ad(t)){let n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?vr.instance:n==="utc"||n==="gmt"?ht.utcInstance:ht.parseSpecifier(n)||At.create(t)}else return tr(t)?ht.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new xn(t)}var ud=()=>Date.now(),cd="system",ld=null,dd=null,fd=null,hd=60,pd,md=null,he=class{static get now(){return ud}static set now(e){ud=e}static set defaultZone(e){cd=e}static get defaultZone(){return Zt(cd,vr.instance)}static get defaultLocale(){return ld}static set defaultLocale(e){ld=e}static get defaultNumberingSystem(){return dd}static set defaultNumberingSystem(e){dd=e}static get defaultOutputCalendar(){return fd}static set defaultOutputCalendar(e){fd=e}static get defaultWeekSettings(){return md}static set defaultWeekSettings(e){md=wi(e)}static get twoDigitCutoffYear(){return hd}static set twoDigitCutoffYear(e){hd=e%100}static get throwOnInvalid(){return pd}static set throwOnInvalid(e){pd=e}static resetCaches(){ge.resetCache(),At.resetCache()}};var pt=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var gd=[0,31,59,90,120,151,181,212,243,273,304,334],wd=[0,31,60,91,121,152,182,213,244,274,305,335];function jt(t,e){return new pt("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Do(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function yd(t,e,r){return r+(Kr(t)?wd:gd)[e-1]}function bd(t,e){let r=Kr(t)?wd:gd,n=r.findIndex(o=>o<e),i=e-r[n];return{month:n+1,day:i}}function Bo(t,e){return(t-e+7)%7+1}function yi(t,e=4,r=1){let{year:n,month:i,day:o}=t,s=yd(n,i,o),u=Bo(Do(n,i,o),r),l=Math.floor((s-u+14-e)/7),d;return l<1?(d=n-1,l=Zr(d,e,r)):l>Zr(n,e,r)?(d=n+1,l=1):d=n,{weekYear:d,weekNumber:l,weekday:u,..._i(t)}}function ja(t,e=4,r=1){let{weekYear:n,weekNumber:i,weekday:o}=t,s=Bo(Do(n,1,e),r),u=Sr(n),l=i*7+o-s-7+e,d;l<1?(d=n-1,l+=Sr(d)):l>u?(d=n+1,l-=Sr(n)):d=n;let{month:b,day:_}=bd(d,l);return{year:d,month:b,day:_,..._i(t)}}function No(t){let{year:e,month:r,day:n}=t,i=yd(e,r,n);return{year:e,ordinal:i,..._i(t)}}function Fa(t){let{year:e,ordinal:r}=t,{month:n,day:i}=bd(e,r);return{year:e,month:n,day:i,..._i(t)}}function qa(t,e){if(!ne(t.localWeekday)||!ne(t.localWeekNumber)||!ne(t.localWeekYear)){if(!ne(t.weekday)||!ne(t.weekNumber)||!ne(t.weekYear))throw new zt("Cannot mix locale-based week fields with ISO-based week fields");return ne(t.localWeekday)||(t.weekday=t.localWeekday),ne(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),ne(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function _d(t,e=4,r=1){let n=bi(t.weekYear),i=Dt(t.weekNumber,1,Zr(t.weekYear,e,r)),o=Dt(t.weekday,1,7);return n?i?o?!1:jt("weekday",t.weekday):jt("week",t.weekNumber):jt("weekYear",t.weekYear)}function vd(t){let e=bi(t.year),r=Dt(t.ordinal,1,Sr(t.year));return e?r?!1:jt("ordinal",t.ordinal):jt("year",t.year)}function La(t){let e=bi(t.year),r=Dt(t.month,1,12),n=Dt(t.day,1,kn(t.year,t.month));return e?r?n?!1:jt("day",t.day):jt("month",t.month):jt("year",t.year)}function Ua(t){let{hour:e,minute:r,second:n,millisecond:i}=t,o=Dt(e,0,23)||e===24&&r===0&&n===0&&i===0,s=Dt(r,0,59),u=Dt(n,0,59),l=Dt(i,0,999);return o?s?u?l?!1:jt("millisecond",i):jt("second",n):jt("minute",r):jt("hour",e)}function ne(t){return typeof t>"u"}function tr(t){return typeof t=="number"}function bi(t){return typeof t=="number"&&t%1===0}function ad(t){return typeof t=="string"}function Sd(t){return Object.prototype.toString.call(t)==="[object Date]"}function Eo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Po(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xd(t){return Array.isArray(t)?t:[t]}function $a(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let o=[e(i),i];return n&&r(n[0],o[0])===n[0]?n:o},null)[1]}function kd(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function xr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wi(t){if(t==null)return null;if(typeof t!="object")throw new lt("Week settings must be an object");if(!Dt(t.firstDay,1,7)||!Dt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Dt(e,1,7)))throw new lt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Dt(t,e,r){return bi(t)&&t>=e&&t<=r}function G0(t,e){return t-e*Math.floor(t/e)}function Ee(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function ur(t){if(!(ne(t)||t===null||t===""))return parseInt(t,10)}function kr(t){if(!(ne(t)||t===null||t===""))return parseFloat(t)}function vi(t){if(!(ne(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function Sn(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function Kr(t){return t%4===0&&(t%100!==0||t%400===0)}function Sr(t){return Kr(t)?366:365}function kn(t,e){let r=G0(e-1,12)+1,n=t+(e-r)/12;return r===2?Kr(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function Tn(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Td(t,e,r){return-Bo(Do(t,1,e),r)+e-1}function Zr(t,e=4,r=1){let n=Td(t,e,r),i=Td(t+1,e,r);return(Sr(t)-n+i)/7}function Ti(t){return t>99?t:t>he.twoDigitCutoffYear?1900+t:2e3+t}function Io(t,e,r,n=null){let i=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},u=new Intl.DateTimeFormat(r,s).formatToParts(i).find(l=>l.type.toLowerCase()==="timezonename");return u?u.value:null}function Hr(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function Ga(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new lt(`Invalid unit value ${t}`);return e}function An(t,e){let r={};for(let n in t)if(xr(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=Ga(i)}return r}function Tr(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Ee(r,2)}:${Ee(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Ee(r,2)}${Ee(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function _i(t){return kd(t,["hour","minute","second","millisecond"])}var V0=["January","February","March","April","May","June","July","August","September","October","November","December"],Va=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],z0=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ea(t){switch(t){case"narrow":return[...z0];case"short":return[...Va];case"long":return[...V0];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var za=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Wa=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],W0=["M","T","W","T","F","S","S"];function Pa(t){switch(t){case"narrow":return[...W0];case"short":return[...Wa];case"long":return[...za];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Da=["AM","PM"],H0=["Before Christ","Anno Domini"],Z0=["BC","AD"],K0=["B","A"];function Ba(t){switch(t){case"narrow":return[...K0];case"short":return[...Z0];case"long":return[...H0];default:return null}}function Ad(t){return Da[t.hour<12?0:1]}function Id(t,e){return Pa(e)[t.weekday-1]}function Cd(t,e){return Ea(e)[t.month-1]}function Od(t,e){return Ba(e)[t.year<0?0:1]}function sd(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&o){let _=t==="days";switch(e){case 1:return _?"tomorrow":`next ${i[t][0]}`;case-1:return _?"yesterday":`last ${i[t][0]}`;case 0:return _?"today":`this ${i[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,u=Math.abs(e),l=u===1,d=i[t],b=n?l?d[1]:d[2]||d[1]:l?i[t][0]:t;return s?`${u} ${b} ago`:`in ${u} ${b}`}function Md(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var J0={D:_r,DD:Xn,DDD:Yn,DDDD:Qn,t:ei,tt:ti,ttt:ri,tttt:ni,T:ii,TT:oi,TTT:si,TTTT:ai,f:ui,ff:li,fff:fi,ffff:pi,F:ci,FF:di,FFF:hi,FFFF:mi},mt=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let u=e.charAt(s);u==="'"?(n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),r=null,n="",i=!i):i||u===r?n+=u:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=u,r=u)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return J0[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return Ee(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(x,A)=>this.loc.extract(e,x,A),s=x=>e.isOffsetFixed&&e.offset===0&&x.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,x.format):"",u=()=>n?Ad(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(x,A)=>n?Cd(e,x):o(A?{month:x}:{month:x,day:"numeric"},"month"),d=(x,A)=>n?Id(e,x):o(A?{weekday:x}:{weekday:x,month:"long",day:"numeric"},"weekday"),b=x=>{let A=t.macroTokenToFormatOpts(x);return A?this.formatWithSystemDefault(e,A):x},_=x=>n?Od(e,x):o({era:x},"era"),T=x=>{switch(x){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return d("short",!0);case"cccc":return d("long",!0);case"ccccc":return d("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return d("short",!1);case"EEEE":return d("long",!1);case"EEEEE":return d("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return _("short");case"GG":return _("long");case"GGGGG":return _("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return b(x)}};return Md(t.parseFormat(r),T)}formatDurationFromString(e,r){let n=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=l=>d=>{let b=n(d);return b?this.num(l.get(b),d.length):d},o=t.parseFormat(r),s=o.reduce((l,{literal:d,val:b})=>d?l:l.concat(b),[]),u=e.shiftTo(...s.map(n).filter(l=>l));return Md(o,i(u))}};var Pd=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Cn(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function On(...t){return e=>t.reduce(([r,n,i],o)=>{let[s,u,l]=o(e,i);return[{...r,...s},u||n,l]},[{},null,1]).slice(0,2)}function Mn(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function Dd(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=ur(e[r+i]);return[n,null,r+i]}}var Bd=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,X0=`(?:${Bd.source}?(?:\\[(${Pd.source})\\])?)?`,Ha=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Nd=RegExp(`${Ha.source}${X0}`),Za=RegExp(`(?:T${Nd.source})?`),Y0=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Q0=/(\d{4})-?W(\d\d)(?:-?(\d))?/,ew=/(\d{4})-?(\d{3})/,tw=Dd("weekYear","weekNumber","weekDay"),rw=Dd("year","ordinal"),nw=/(\d{4})-(\d\d)-(\d\d)/,Rd=RegExp(`${Ha.source} ?(?:${Bd.source}|(${Pd.source}))?`),iw=RegExp(`(?: ${Rd.source})?`);function In(t,e,r){let n=t[e];return ne(n)?r:ur(n)}function ow(t,e){return[{year:In(t,e),month:In(t,e+1,1),day:In(t,e+2,1)},null,e+3]}function En(t,e){return[{hours:In(t,e,0),minutes:In(t,e+1,0),seconds:In(t,e+2,0),milliseconds:vi(t[e+3])},null,e+4]}function Si(t,e){let r=!t[e]&&!t[e+1],n=Hr(t[e+1],t[e+2]),i=r?null:ht.instance(n);return[{},i,e+3]}function xi(t,e){let r=t[e]?At.create(t[e]):null;return[{},r,e+1]}var sw=RegExp(`^T?${Ha.source}$`),aw=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function uw(t){let[e,r,n,i,o,s,u,l,d]=t,b=e[0]==="-",_=l&&l[0]==="-",T=(x,A=!1)=>x!==void 0&&(A||x&&b)?-x:x;return[{years:T(kr(r)),months:T(kr(n)),weeks:T(kr(i)),days:T(kr(o)),hours:T(kr(s)),minutes:T(kr(u)),seconds:T(kr(l),l==="-0"),milliseconds:T(vi(d),_)}]}var cw={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Ka(t,e,r,n,i,o,s){let u={year:e.length===2?Ti(ur(e)):ur(e),month:Va.indexOf(r)+1,day:ur(n),hour:ur(i),minute:ur(o)};return s&&(u.second=ur(s)),t&&(u.weekday=t.length>3?za.indexOf(t)+1:Wa.indexOf(t)+1),u}var lw=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function dw(t){let[,e,r,n,i,o,s,u,l,d,b,_]=t,T=Ka(e,i,n,r,o,s,u),x;return l?x=cw[l]:d?x=0:x=Hr(b,_),[T,new ht(x)]}function fw(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var hw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,pw=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,mw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Ed(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,i,n,r,o,s,u),ht.utcInstance]}function gw(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,u,r,n,i,o,s),ht.utcInstance]}var ww=Cn(Y0,Za),yw=Cn(Q0,Za),bw=Cn(ew,Za),_w=Cn(Nd),jd=On(ow,En,Si,xi),vw=On(tw,En,Si,xi),Tw=On(rw,En,Si,xi),Sw=On(En,Si,xi);function Fd(t){return Mn(t,[ww,jd],[yw,vw],[bw,Tw],[_w,Sw])}function qd(t){return Mn(fw(t),[lw,dw])}function Ld(t){return Mn(t,[hw,Ed],[pw,Ed],[mw,gw])}function Ud(t){return Mn(t,[aw,uw])}var xw=On(En);function $d(t){return Mn(t,[sw,xw])}var kw=Cn(nw,iw),Aw=Cn(Rd),Iw=On(En,Si,xi);function Gd(t){return Mn(t,[kw,jd],[Aw,Iw])}var Vd="Invalid Duration",Wd={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Cw={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Wd},Ft=146097/400,Pn=146097/4800,Ow={years:{quarters:4,months:12,weeks:Ft/7,days:Ft,hours:Ft*24,minutes:Ft*24*60,seconds:Ft*24*60*60,milliseconds:Ft*24*60*60*1e3},quarters:{months:3,weeks:Ft/28,days:Ft/4,hours:Ft*24/4,minutes:Ft*24*60/4,seconds:Ft*24*60*60/4,milliseconds:Ft*24*60*60*1e3/4},months:{weeks:Pn/7,days:Pn,hours:Pn*24,minutes:Pn*24*60,seconds:Pn*24*60*60,milliseconds:Pn*24*60*60*1e3},...Wd},Jr=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Mw=Jr.slice(0).reverse();function Ar(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new _e(n)}function Hd(t,e){let r=e.milliseconds??0;for(let n of Mw.slice(1))e[n]&&(r+=e[n]*t[n].milliseconds);return r}function zd(t,e){let r=Hd(t,e)<0?-1:1;Jr.reduceRight((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]*r,s=t[i][n],u=Math.floor(o/s);e[i]+=u*r,e[n]-=u*s*r}return i},null),Jr.reduce((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*t[n][i]}return i},null)}function Ew(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var _e=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?Ow:Cw;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||ge.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new lt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:An(e,t.normalizeUnit),loc:ge.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(tr(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new lt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Ud(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=$d(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Duration is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new ko(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new vn(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?mt.create(this.loc,n).formatDurationFromString(this,e):Vd}toHuman(e={}){if(!this.isValid)return Vd;let r=Jr.map(n=>{let i=this.values[n];return ne(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Sn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},le.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Hd(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of Jr)(xr(r.values,i)||xr(this.values,i))&&(n[i]=r.get(i)+this.get(i));return Ar(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=Ga(e(this.values[n],n));return Ar(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...An(e,t.normalizeUnit)};return Ar(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return Ar(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return zd(this.matrix,e),Ar(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Ew(this.normalize().shiftToAll().toObject());return Ar(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let r={},n={},i=this.toObject(),o;for(let s of Jr)if(e.indexOf(s)>=0){o=s;let u=0;for(let d in n)u+=this.matrix[d][s]*n[d],n[d]=0;tr(i[s])&&(u+=i[s]);let l=Math.trunc(u);r[s]=l,n[s]=(u*1e3-l*1e3)/1e3}else tr(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(r[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return zd(this.matrix,r),Ar(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Ar(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of Jr)if(!r(this.values[n],e.values[n]))return!1;return!0}};var Dn="Invalid Interval";function Pw(t,e){return!t||!t.isValid?cr.invalid("missing or invalid start"):!e||!e.isValid?cr.invalid("missing or invalid end"):e<t?cr.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var cr=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Interval is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new xo(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=Bn(e),i=Bn(r),o=Pw(n,i);return o??new t({start:n,end:i})}static after(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=le.fromISO(n,r),s=o.isValid}catch{s=!1}let u,l;try{u=le.fromISO(i,r),l=u.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(o,u);if(s){let d=_e.fromISO(i,r);if(d.isValid)return t.after(o,d)}else if(l){let d=_e.fromISO(n,r);if(d.isValid)return t.before(u,d)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),i;return r?.useLocaleWeeks?i=this.end.reconfigure({locale:n.locale}):i=this.end,i=i.startOf(e,r),Math.floor(i.diff(n,e).get(e))+(i.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(Bn).filter(s=>this.contains(s)).sort((s,u)=>s.toMillis()-u.toMillis()),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=r[o]||this.e,u=+s>+this.e?this.e:s;n.push(t.fromDateTimes(i,u)),i=u,o+=1}return n}splitBy(e){let r=_e.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let u=this.start.plus(r.mapUnits(l=>l*i));o=+u>+this.e?this.e:u,s.push(t.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],o=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...o),u=s.sort((l,d)=>l.time-d.time);for(let l of u)n+=l.type==="s"?1:-1,n===1?r=l.time:(r&&+r!=+l.time&&i.push(t.fromDateTimes(r,l.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Dn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.s.loc.clone(r),e).formatInterval(this):Dn}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Dn}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Dn}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Dn}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Dn}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):_e.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var lr=class{static hasDST(e=he.defaultZone){let r=le.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return At.isValidZone(e)}static normalizeZone(e){return Zt(e,he.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ge.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return ge.create(r,null,"gregory").eras(e)}static features(){return{relative:Eo(),localeWeek:Po()}}};function Zd(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(_e.fromMillis(n).as("days"))}function Dw(t,e,r){let n=[["years",(l,d)=>d.year-l.year],["quarters",(l,d)=>d.quarter-l.quarter+(d.year-l.year)*4],["months",(l,d)=>d.month-l.month+(d.year-l.year)*12],["weeks",(l,d)=>{let b=Zd(l,d);return(b-b%7)/7}],["days",Zd]],i={},o=t,s,u;for(let[l,d]of n)r.indexOf(l)>=0&&(s=l,i[l]=d(t,e),u=o.plus(i),u>e?(i[l]--,t=o.plus(i),t>e&&(u=t,i[l]--,t=o.plus(i))):t=u);return[t,i,u,s]}function Kd(t,e,r,n){let[i,o,s,u]=Dw(t,e,r),l=e-i,d=r.filter(_=>["hours","minutes","seconds","milliseconds"].indexOf(_)>=0);d.length===0&&(s<e&&(s=i.plus({[u]:1})),s!==i&&(o[u]=(o[u]||0)+l/(s-i)));let b=_e.fromObject(o,n);return d.length>0?_e.fromMillis(l,n).shiftTo(...d).plus(b):b}var Ja={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Jd={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Bw=Ja.hanidec.replace(/[\[|\]]/g,"").split("");function Xd(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(Ja.hanidec)!==-1)e+=Bw.indexOf(t[r]);else for(let i in Jd){let[o,s]=Jd[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}function qt({numberingSystem:t},e=""){return new RegExp(`${Ja[t||"latn"]}${e}`)}var Nw="missing Intl.DateTimeFormat.formatToParts support";function pe(t,e=r=>r){return{regex:t,deser:([r])=>e(Xd(r))}}var Rw="\xA0",ef=`[ ${Rw}]`,tf=new RegExp(ef,"g");function jw(t){return t.replace(/\./g,"\\.?").replace(tf,ef)}function Yd(t){return t.replace(/\./g,"").replace(tf," ").toLowerCase()}function Kt(t,e){return t===null?null:{regex:RegExp(t.map(jw).join("|")),deser:([r])=>t.findIndex(n=>Yd(r)===Yd(n))+e}}function Qd(t,e){return{regex:t,deser:([,r,n])=>Hr(r,n),groups:e}}function Ro(t){return{regex:t,deser:([e])=>e}}function Fw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function qw(t,e){let r=qt(e),n=qt(e,"{2}"),i=qt(e,"{3}"),o=qt(e,"{4}"),s=qt(e,"{6}"),u=qt(e,"{1,2}"),l=qt(e,"{1,3}"),d=qt(e,"{1,6}"),b=qt(e,"{1,9}"),_=qt(e,"{2,4}"),T=qt(e,"{4,6}"),x=C=>({regex:RegExp(Fw(C.val)),deser:([E])=>E,literal:!0}),I=(C=>{if(t.literal)return x(C);switch(C.val){case"G":return Kt(e.eras("short"),0);case"GG":return Kt(e.eras("long"),0);case"y":return pe(d);case"yy":return pe(_,Ti);case"yyyy":return pe(o);case"yyyyy":return pe(T);case"yyyyyy":return pe(s);case"M":return pe(u);case"MM":return pe(n);case"MMM":return Kt(e.months("short",!0),1);case"MMMM":return Kt(e.months("long",!0),1);case"L":return pe(u);case"LL":return pe(n);case"LLL":return Kt(e.months("short",!1),1);case"LLLL":return Kt(e.months("long",!1),1);case"d":return pe(u);case"dd":return pe(n);case"o":return pe(l);case"ooo":return pe(i);case"HH":return pe(n);case"H":return pe(u);case"hh":return pe(n);case"h":return pe(u);case"mm":return pe(n);case"m":return pe(u);case"q":return pe(u);case"qq":return pe(n);case"s":return pe(u);case"ss":return pe(n);case"S":return pe(l);case"SSS":return pe(i);case"u":return Ro(b);case"uu":return Ro(u);case"uuu":return pe(r);case"a":return Kt(e.meridiems(),0);case"kkkk":return pe(o);case"kk":return pe(_,Ti);case"W":return pe(u);case"WW":return pe(n);case"E":case"c":return pe(r);case"EEE":return Kt(e.weekdays("short",!1),1);case"EEEE":return Kt(e.weekdays("long",!1),1);case"ccc":return Kt(e.weekdays("short",!0),1);case"cccc":return Kt(e.weekdays("long",!0),1);case"Z":case"ZZ":return Qd(new RegExp(`([+-]${u.source})(?::(${n.source}))?`),2);case"ZZZ":return Qd(new RegExp(`([+-]${u.source})(${n.source})?`),2);case"z":return Ro(/[a-z_+-/]{1,256}?/i);case" ":return Ro(/[^\S\n\r]/);default:return x(C)}})(t)||{invalidReason:Nw};return I.token=t,I}var Lw={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Uw(t,e,r){let{type:n,value:i}=t;if(n==="literal"){let l=/^\s+$/.test(i);return{literal:!l,val:l?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=r.hour12?"hour12":"hour24");let u=Lw[s];if(typeof u=="object"&&(u=u[o]),u)return{literal:!1,val:u}}function $w(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function Gw(t,e,r){let n=t.match(e);if(n){let i={},o=1;for(let s in r)if(xr(r,s)){let u=r[s],l=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(n.slice(o,o+l))),o+=l}return[n,i]}else return[n,{}]}function Vw(t){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return ne(t.z)||(r=At.create(t.z)),ne(t.Z)||(r||(r=new ht(t.Z)),n=t.Z),ne(t.q)||(t.M=(t.q-1)*3+1),ne(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),ne(t.u)||(t.S=vi(t.u)),[Object.keys(t).reduce((o,s)=>{let u=e(s);return u&&(o[u]=t[s]),o},{}),r,n]}var Xa=null;function zw(){return Xa||(Xa=le.fromMillis(1555555555555)),Xa}function Ww(t,e){if(t.literal)return t;let r=mt.macroTokenToFormatOpts(t.val),n=eu(r,e);return n==null||n.includes(void 0)?t:n}function Ya(t,e){return Array.prototype.concat(...t.map(r=>Ww(r,e)))}function Qa(t,e,r){let n=Ya(mt.parseFormat(r),t),i=n.map(s=>qw(s,t)),o=i.find(s=>s.invalidReason);if(o)return{input:e,tokens:n,invalidReason:o.invalidReason};{let[s,u]=$w(i),l=RegExp(s,"i"),[d,b]=Gw(e,l,u),[_,T,x]=b?Vw(b):[null,null,void 0];if(xr(b,"a")&&xr(b,"H"))throw new zt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:l,rawMatches:d,matches:b,result:_,zone:T,specificOffset:x}}}function rf(t,e,r){let{result:n,zone:i,specificOffset:o,invalidReason:s}=Qa(t,e,r);return[n,i,o,s]}function eu(t,e){if(!t)return null;let n=mt.create(e,t).dtFormatter(zw()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>Uw(s,t,o))}var tu="Invalid DateTime",nf=864e13;function jo(t){return new pt("unsupported zone",`the zone "${t.name}" is not supported`)}function ru(t){return t.weekData===null&&(t.weekData=yi(t.c)),t.weekData}function nu(t){return t.localWeekData===null&&(t.localWeekData=yi(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Xr(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new le({...r,...e,old:r})}function df(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=r.offset(n);return i===o?[n,i]:[t-Math.min(i,o)*60*1e3,Math.max(i,o)]}function Fo(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Lo(t,e,r){return df(Tn(t),e,r)}function of(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:n,month:i,day:Math.min(t.c.day,kn(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=_e.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=Tn(o),[l,d]=df(u,r,t.zone);return s!==0&&(l+=s,d=t.zone.offset(l)),{ts:l,o:d}}function ki(t,e,r,n,i,o){let{setZone:s,zone:u}=r;if(t&&Object.keys(t).length!==0||e){let l=e||u,d=le.fromObject(t,{...r,zone:l,specificOffset:o});return s?d:d.setZone(u)}else return le.invalid(new pt("unparsable",`the input "${i}" can't be parsed as ${n}`))}function qo(t,e,r=!0){return t.isValid?mt.create(ge.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function iu(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=Ee(t.c.year,r?6:4),e?(n+="-",n+=Ee(t.c.month),n+="-",n+=Ee(t.c.day)):(n+=Ee(t.c.month),n+=Ee(t.c.day)),n}function sf(t,e,r,n,i,o){let s=Ee(t.c.hour);return e?(s+=":",s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=":")):s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=Ee(t.c.second),(t.c.millisecond!==0||!n)&&(s+=".",s+=Ee(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Ee(Math.trunc(-t.o/60)),s+=":",s+=Ee(Math.trunc(-t.o%60))):(s+="+",s+=Ee(Math.trunc(t.o/60)),s+=":",s+=Ee(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var ff={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Hw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Zw={ordinal:1,hour:0,minute:0,second:0,millisecond:0},hf=["year","month","day","hour","minute","second","millisecond"],Kw=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Jw=["year","ordinal","hour","minute","second","millisecond"];function Xw(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new vn(t);return e}function af(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Xw(t)}}function uf(t,e){let r=Zt(e.zone,he.defaultZone),n=ge.fromObject(e),i=he.now(),o,s;if(ne(t.year))o=i;else{for(let d of hf)ne(t[d])&&(t[d]=ff[d]);let u=La(t)||Ua(t);if(u)return le.invalid(u);let l=r.offset(i);[o,s]=Lo(t,l,r)}return new le({ts:o,zone:r,loc:n,o:s})}function cf(t,e,r){let n=ne(r.round)?!0:r.round,i=(s,u)=>(s=Sn(s,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(s,u)),o=s=>r.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(r.unit)return i(o(r.unit),r.unit);for(let s of r.units){let u=o(s);if(Math.abs(u)>=1)return i(u,s)}return i(t>e?-0:0,r.units[r.units.length-1])}function lf(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var le=class t{constructor(e){let r=e.zone||he.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new pt("invalid input"):null)||(r.isValid?null:jo(r));this.ts=ne(e.ts)?he.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,o]=[e.old.c,e.old.o];else{let u=r.offset(this.ts);i=Fo(this.ts,u),n=Number.isNaN(i.year)?new pt("invalid input"):null,i=n?null:i,o=n?null:u}this._zone=r,this.loc=e.loc||ge.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static utc(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return e.zone=ht.utcInstance,uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static fromJSDate(e,r={}){let n=Sd(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Zt(r.zone,he.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:ge.fromObject(r)}):t.invalid(jo(i))}static fromMillis(e,r={}){if(tr(e))return e<-nf||e>nf?t.invalid("Timestamp out of range"):new t({ts:e,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(tr(e))return new t({ts:e*1e3,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Zt(r.zone,he.defaultZone);if(!n.isValid)return t.invalid(jo(n));let i=ge.fromObject(r),o=An(e,af),{minDaysInFirstWeek:s,startOfWeek:u}=qa(o,i),l=he.now(),d=ne(r.specificOffset)?n.offset(l):r.specificOffset,b=!ne(o.ordinal),_=!ne(o.year),T=!ne(o.month)||!ne(o.day),x=_||T,A=o.weekYear||o.weekNumber;if((x||b)&&A)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(T&&b)throw new zt("Can't mix ordinal dates with month/day");let I=A||o.weekday&&!x,C,E,P=Fo(l,d);I?(C=Kw,E=Hw,P=yi(P,s,u)):b?(C=Jw,E=Zw,P=No(P)):(C=hf,E=ff);let D=!1;for(let N of C){let j=o[N];ne(j)?D?o[N]=E[N]:o[N]=P[N]:D=!0}let L=I?_d(o,s,u):b?vd(o):La(o),H=L||Ua(o);if(H)return t.invalid(H);let W=I?ja(o,s,u):b?Fa(o):o,[K,F]=Lo(W,d,n),U=new t({ts:K,zone:n,o:F,loc:i});return o.weekday&&x&&e.weekday!==U.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${U.toISO()}`):U}static fromISO(e,r={}){let[n,i]=Fd(e);return ki(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=qd(e);return ki(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Ld(e);return ki(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(ne(e)||ne(r))throw new lt("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[u,l,d,b]=rf(s,e,r);return b?t.invalid(b):ki(u,l,n,`format ${r}`,e,d)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=Gd(e);return ki(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the DateTime is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new So(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=eu(e,ge.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return Ya(mt.parseFormat(e),ge.fromObject(r)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?ru(this).weekYear:NaN}get weekNumber(){return this.isValid?ru(this).weekNumber:NaN}get weekday(){return this.isValid?ru(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?nu(this).weekday:NaN}get localWeekNumber(){return this.isValid?nu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?nu(this).weekYear:NaN}get ordinal(){return this.isValid?No(this.c).ordinal:NaN}get monthShort(){return this.isValid?lr.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?lr.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?lr.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?lr.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=Tn(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*r),u=this.zone.offset(n-o*r);if(s===u)return[this];let l=n-s*r,d=n-u*r,b=Fo(l,s),_=Fo(d,u);return b.hour===_.hour&&b.minute===_.minute&&b.second===_.second&&b.millisecond===_.millisecond?[Xr(this,{ts:l}),Xr(this,{ts:d})]:[this]}get isInLeapYear(){return Kr(this.year)}get daysInMonth(){return kn(this.year,this.month)}get daysInYear(){return this.isValid?Sr(this.year):NaN}get weeksInWeekYear(){return this.isValid?Zr(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Zr(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=mt.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(ht.instance(e),r)}toLocal(){return this.setZone(he.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Zt(e,he.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let o=e.offset(this.ts),s=this.toObject();[i]=Lo(s,o,e)}return Xr(this,{ts:i,zone:e})}else return t.invalid(jo(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return Xr(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=An(e,af),{minDaysInFirstWeek:n,startOfWeek:i}=qa(r,this.loc),o=!ne(r.weekYear)||!ne(r.weekNumber)||!ne(r.weekday),s=!ne(r.ordinal),u=!ne(r.year),l=!ne(r.month)||!ne(r.day),d=u||l,b=r.weekYear||r.weekNumber;if((d||s)&&b)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new zt("Can't mix ordinal dates with month/day");let _;o?_=ja({...yi(this.c,n,i),...r},n,i):ne(r.ordinal)?(_={...this.toObject(),...r},ne(r.day)&&(_.day=Math.min(kn(_.year,_.month),_.day))):_=Fa({...No(this.c),...r});let[T,x]=Lo(_,this.o,this.zone);return Xr(this,{ts:T,o:x})}plus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e);return Xr(this,of(this,r))}minus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e).negate();return Xr(this,of(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},i=_e.normalizeUnit(e);switch(i){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(i==="weeks")if(r){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(n.weekNumber=this.weekNumber-1),n.weekday=o}else n.weekday=1;if(i==="quarters"){let o=Math.ceil(this.month/3);n.month=(o-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?mt.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):tu}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.loc.clone(r),e).formatDateTime(this):tu}toLocaleParts(e={}){return this.isValid?mt.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",u=iu(this,s);return u+="T",u+=sf(this,s,r,n,i,o),u}toISODate({format:e="extended"}={}){return this.isValid?iu(this,e==="extended"):null}toISOWeekDate(){return qo(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(i?"T":"")+sf(this,s==="extended",r,e,n,o):null}toRFC2822(){return qo(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return qo(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?iu(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),qo(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():tu}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return _e.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=xd(r).map(_e.normalizeUnit),s=e.valueOf()>this.valueOf(),u=s?this:e,l=s?e:this,d=Kd(u,l,o,i);return s?d.negate():d}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?cr.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let i=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(r,n)<=i&&i<=o.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),cf(r,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?cf(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new lt("min requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new lt("max requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return Qa(s,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return _r}static get DATE_MED(){return Xn}static get DATE_MED_WITH_WEEKDAY(){return va}static get DATE_FULL(){return Yn}static get DATE_HUGE(){return Qn}static get TIME_SIMPLE(){return ei}static get TIME_WITH_SECONDS(){return ti}static get TIME_WITH_SHORT_OFFSET(){return ri}static get TIME_WITH_LONG_OFFSET(){return ni}static get TIME_24_SIMPLE(){return ii}static get TIME_24_WITH_SECONDS(){return oi}static get TIME_24_WITH_SHORT_OFFSET(){return si}static get TIME_24_WITH_LONG_OFFSET(){return ai}static get DATETIME_SHORT(){return ui}static get DATETIME_SHORT_WITH_SECONDS(){return ci}static get DATETIME_MED(){return li}static get DATETIME_MED_WITH_SECONDS(){return di}static get DATETIME_MED_WITH_WEEKDAY(){return Ta}static get DATETIME_FULL(){return fi}static get DATETIME_FULL_WITH_SECONDS(){return hi}static get DATETIME_HUGE(){return pi}static get DATETIME_HUGE_WITH_SECONDS(){return mi}};function Bn(t){if(le.isDateTime(t))return t;if(t&&t.valueOf&&tr(t.valueOf()))return le.fromJSDate(t);if(t&&typeof t=="object")return le.fromObject(t);throw new lt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Pi=require("@mysten/sui.js/transactions"),ku=require("@mysten/sui.js/transactions"),Bi=require("@mysten/sui.js/utils"),Au=require("buffer"),Dh=require("@mysten/sui.js/utils"),Ru=require("@mysten/sui.js/bcs"),Ni=require("@mysten/sui.js/utils");var pf=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var Ou=require("@mysten/sui.js/transactions"),Rr=require("@mysten/sui.js/utils");var Di=require("@mysten/sui.js/transactions"),Ri=require("@mysten/sui.js/utils");var Kh=de(Wi(),1),Jh=require("@msafe/sui3-utils"),Xh=require("@msafe/sui3-utils"),Yh=require("@msafe/sui3-utils"),Du=require("@mysten/sui.js/bcs"),Dr=require("@mysten/sui.js/utils"),ep=require("@msafe/sui3-utils"),qn=require("@msafe/sui3-utils"),tp=require("@msafe/sui3-utils"),np=require("@msafe/sui3-utils"),op=require("@msafe/sui3-utils"),sp=require("@mysten/sui.js/transactions"),up=require("@msafe/sui3-utils"),Fn=require("@msafe/sui3-utils"),Bu=require("@mysten/sui.js/bcs"),Br=require("@mysten/sui.js/utils"),cp=require("@mysten/sui.js/transactions"),dp=require("@mysten/sui.js/transactions"),hp=require("@mysten/sui.js/transactions"),gp=require("@mysten/sui.js/transactions"),yp=require("@mysten/sui.js/transactions"),ls=require("@msafe/sui3-utils"),_p=require("@mysten/sui.js/transactions"),ds=require("@mysten/sui.js/utils"),$T=de(Wi(),1),vp=require("@msafe/sui3-utils"),Tp=require("@msafe/sui3-utils"),Nu=require("@mysten/sui.js/bcs"),Nr=require("@mysten/sui.js/utils");var vy=de(we(),1);var tn=require("@mysten/sui.js/client"),Ef=require("@mysten/sui.js/keypairs/ed25519");function mf(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Yw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function ou(t,...e){if(!Yw(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function su(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gf(t,e){ou(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Uo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Go=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Jt=(t,e)=>t<<32-e|t>>>e,ey=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ey)throw new Error("Non little-endian hardware is not supported");function ty(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function au(t){if(typeof t=="string"&&(t=ty(t)),!Qw(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var $o=class{clone(){return this._cloneInto()}},X2={}.toString;function wf(t){let e=n=>t().update(au(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yf(t=32){if(Uo&&typeof Uo.getRandomValues=="function")return Uo.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ry(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),u=Number(r&o),l=n?4:0,d=n?0:4;t.setUint32(e+l,s,n),t.setUint32(e+d,u,n)}var Vo=class extends $o{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){su(this);let{view:r,buffer:n,blockLen:i}=this;e=au(e);let o=e.length;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let l=Go(e);for(;i<=o-s;s+=i)this.process(l,s);continue}n.set(e.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){su(this),gf(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let _=s;_<i;_++)r[_]=0;ry(n,i-8,BigInt(this.length*8),o),this.process(n,0);let u=Go(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=l/4,b=this.get();if(d>b.length)throw new Error("_sha2: outputLen bigger than state");for(let _=0;_<d;_++)u.setUint32(4*_,b[_],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:u}=this;return e.length=i,e.pos=u,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var ny=(t,e,r)=>t&e^~t&r,iy=(t,e,r)=>t&e^t&r^e&r,oy=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ir=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=new Uint32Array(64),uu=class extends Vo{constructor(){super(64,32,8,!1),this.A=Ir[0]|0,this.B=Ir[1]|0,this.C=Ir[2]|0,this.D=Ir[3]|0,this.E=Ir[4]|0,this.F=Ir[5]|0,this.G=Ir[6]|0,this.H=Ir[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:u,H:l}=this;return[e,r,n,i,o,s,u,l]}set(e,r,n,i,o,s,u,l){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=u|0,this.H=l|0}process(e,r){for(let _=0;_<16;_++,r+=4)Cr[_]=e.getUint32(r,!1);for(let _=16;_<64;_++){let T=Cr[_-15],x=Cr[_-2],A=Jt(T,7)^Jt(T,18)^T>>>3,I=Jt(x,17)^Jt(x,19)^x>>>10;Cr[_]=I+Cr[_-7]+A+Cr[_-16]|0}let{A:n,B:i,C:o,D:s,E:u,F:l,G:d,H:b}=this;for(let _=0;_<64;_++){let T=Jt(u,6)^Jt(u,11)^Jt(u,25),x=b+T+ny(u,l,d)+oy[_]+Cr[_]|0,I=(Jt(n,2)^Jt(n,13)^Jt(n,22))+iy(n,i,o)|0;b=d,d=l,l=u,u=s+x|0,s=o,o=i,i=n,n=x+I|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,u=u+this.E|0,l=l+this.F|0,d=d+this.G|0,b=b+this.H|0,this.set(n,i,o,s,u,l,d,b)}roundClean(){Cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var bf=wf(()=>new uu);function Yr(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function zo(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function sy(...t){let e=o=>o,r=(o,s)=>u=>o(s(u)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function ay(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function uy(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function cy(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function cu(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],o=Array.from(t);for(o.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,u=!0;for(let l=n;l<o.length;l++){let d=o[l],b=e*s+d;if(!Number.isSafeInteger(b)||e*s/e!==s||b-d!==e*s)throw new Error("convertRadix: carry overflow");s=b%r;let _=Math.floor(b/r);if(o[l]=_,!Number.isSafeInteger(_)||_*r+s!==b)throw new Error("convertRadix: carry overflow");if(u)_?u=!1:n=l;else continue}if(i.push(s),u)break}for(let s=0;s<t.length-1&&t[s]===0;s++)i.push(0);return i.reverse()}var _f=(t,e)=>e?_f(e,t%e):t,Wo=(t,e)=>t+(e-_f(t,e));function lu(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Wo(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Wo(e,r)}`);let i=0,o=0,s=2**r-1,u=[];for(let l of t){if(l>=2**e)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(i=i<<e|l,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)u.push((i>>o-r&s)>>>0);i&=2**o-1}if(i=i<<r-o&s,!n&&o>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&u.push(i>>>0),u}function ly(t){return{encode:e=>{if(!zo(e))throw new Error("radix.encode input should be Uint8Array");return cu(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(cu(e,t,2**8))}}}function dy(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Wo(8,t)>32||Wo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!zo(r))throw new Error("radix2.encode input should be Uint8Array");return lu(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(lu(r,t,8,e))}}}function fy(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!zo(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!zo(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),o=r.slice(-t);for(let s=0;s<t;s++)if(i[s]!==o[s])throw new Error("Invalid checksum");return n}}}var Ai={alphabet:ay,chain:sy,checksum:fy,convertRadix:cu,convertRadix2:lu,radix:ly,radix2:dy,join:uy,padding:cy};var hy=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function py(t){ou(t,16,20,24,28,32)}function vf(t,e=128){if(mf(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return wy(yf(e/8),t)}var my=t=>{let e=8-t.length/4;return new Uint8Array([bf(t)[0]>>e<<e])};function gy(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),Ai.chain(Ai.checksum(1,my),Ai.radix2(11,!0),Ai.alphabet(t))}function wy(t,e){return py(t),gy(e).encode(t).join(hy(e)?"\u3000":" ")}var Tf=`abandon
5
+ `;if(_=await this.fetchAndParseData(A,x),_?.isTimeout||_==null){let I=await this.sdk.Router.price(t,e,new Gt.default(r),n,i,o,u),C=[];for(let P of I.paths){let D=[];if(P.poolAddress.length>1){let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W},U=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,N=this.sdk.Router.tokenInfo(P.coinType[2]).decimals,j=P.a2b[1]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),U,N):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),N,U),S={direction:P.a2b[1],label:"Cetus",poolAddress:P.poolAddress[1],fromCoin:P.coinType[1],toCoin:P.coinType[2],feeRate:this.sdk.Router.getFeeRate(P.coinType[1],P.coinType[2],P.poolAddress[1]),outputAmount:P.amountOut.toString(),inputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),currentSqrtPrice:I.currentSqrtPrice[1],currentPrice:j,fromDecimal:U,toDecimal:N};D.push(F,S)}else{let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:P.amountOut.toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W};D.push(F)}let L={percent:Number(P.amountIn)/Number(I.amountIn)*100,inputAmount:Number(P.amountIn.toString()),outputAmount:Number(P.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:D};C.push(L)}let E={isExceed:I.isExceed,isTimeout:!0,inputAmount:Number(I.amountIn.toString()),outputAmount:Number(I.amountOut.toString()),fromCoin:I.coinTypeA,toCoin:I.coinTypeC!=null?I.coinTypeC:I.coinTypeB,byAmountIn:I.byAmountIn,splitPaths:C};T="v1",_=E}return{result:_,version:T}}},A0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=be(this.sdk.sdkOptions.cetus_config),r=`${e}_getCoinConfigs`,n=this.getCache(r),i=n?[...n,...t]:t;this.updateCache(r,i,Oe)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n);if(i!==void 0){let s=i;for(let u of t)for(let l of s)if(sr(u)===sr(l.address)){e[u]=l;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let u=`${s}_metadata`,l=this.getCache(u);if(l!==void 0)e[s]=l;else{let d=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(d){let b={id:d.id,pyth_id:"",name:d.name,symbol:d.symbol,official_symbol:d.symbol,coingecko_id:"",decimals:d.decimals,project_url:"",logo_url:d.iconUrl,address:s};e[s]=b,this.updateCache(u,b,Oe)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildCoinConfig(d,e);this.updateCache(`${r}_${b.address}_getCoinConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getCoinConfig(t,e=!1,r=!0){let{coin_list_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${n}_${t}_getCoinConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"0x1::type_name::TypeName",value:{name:Yg(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfig get object error: ${s.error}, please check the rpc and contracts address config.`,"InvalidConfig");let u=this.buildCoinConfig(s,r);return this.updateCache(i,u,Oe),u}buildCoinConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.address=se(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=(0,go.normalizeSuiObjectId)(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,e),delete n.coin_type,n}async getClmmPoolConfigs(t=!1,e=!0){let{clmm_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getClmmPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getClmmPoolsConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildClmmPoolConfig(d,e);this.updateCache(`${b.pool_address}_getClmmPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getClmmPoolConfig(t,e=!1,r=!0){let{clmm_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getClmmPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildClmmPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildClmmPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e),n}async getLaunchpadPoolConfigs(t=!1,e=!0){let{launchpad_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getLaunchpadPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildLaunchpadPoolConfig(d,e);this.updateCache(`${b.pool_address}_getLaunchpadPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getLaunchpadPoolConfig(t,e=!1,r=!0){let{launchpad_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getLaunchpadPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildLaunchpadPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildLaunchpadPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e);let i=[];r.social_media.fields.contents.forEach(o=>{i.push({name:o.fields.value.fields.name,link:o.fields.value.fields.link})}),n.social_media=i;try{n.regulation=decodeURIComponent(mn.decode(n.regulation).replace(/%/g,"%25"))}catch{n.regulation=mn.decode(n.regulation)}return n}transformExtensions(t,e,r=!0){let n=[];for(let i of e){let{key:o}=i.fields,{value:s}=i.fields;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}r&&(t[o]=s),n.push({key:o,value:s})}delete t.extension_fields,r||(t.extensions=n)}async getCetusConfig(t=!1){let e=this._sdk.sdkOptions.cetus_config.package_id,r=`${e}_getCetusConfig`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_list_id:"",launchpad_pools_id:"",clmm_pools_id:"",admin_cap_id:"",global_config_id:"",coin_list_handle:"",launchpad_pools_handle:"",clmm_pools_handle:""};if(s.data.length>0)for(let l of s.data)switch(se(l.type).name){case"InitCoinListEvent":u.coin_list_id=l.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":u.launchpad_pools_id=l.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":u.clmm_pools_id=l.parsedJson.pools_id;break;case"InitConfigEvent":u.global_config_id=l.parsedJson.global_config_id,u.admin_cap_id=l.parsedJson.admin_cap_id;break;default:break}return u=await this.getCetusConfigHandle(u),u.clmm_pools_id.length>0&&this.updateCache(r,u,Oe),u}async getCetusConfigHandle(t){let e=[t.clmm_pools_id,t.coin_list_id,t.launchpad_pools_id];return(await this._sdk.fullClient.multiGetObjects({ids:e,options:{showContent:!0}})).forEach(n=>{if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`when getCetusConfigHandle get objects error: ${n.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let i=br(n),o=c0(n);switch(se(o).name){case"ClmmPools":t.clmm_pools_handle=i.pools.fields.id.id;break;case"CoinList":t.coin_list_handle=i.coins.fields.id.id;break;case"LaunchpadPools":t.launchpad_pools_handle=i.pools.fields.id.id;break;default:break}}),t}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){try{let r=this._cache[t];if(!r)return;if(e||!r.isValid()){delete this._cache[t];return}return r.value}catch(r){console.error(`Error accessing cache for key ${t}:`,r);return}}},I0=class extends td.SuiClient{async queryEventsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.queryEvents({query:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async getOwnedObjectsByPage(t,e,r="all"){let n=[],i=!0,o=r==="all",s=o?null:r.cursor;do{let u=await this.getOwnedObjects({owner:t,...e,cursor:s,limit:o?null:r.limit});u.data?(n=[...n,...u.data],i=u.hasNextPage,s=u.nextCursor):i=!1}while(o&&i);return{data:n,nextCursor:s,hasNextPage:i}}async getDynamicFieldsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.getDynamicFields({parentId:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async batchGetObjects(t,e,r=50){let n=[];try{for(let i=0;i<Math.ceil(t.length/r);i++){let o=await this.multiGetObjects({ids:t.slice(i*r,r*(i+1)),options:e});n=[...n,...o]}}catch(i){console.log(i)}return n}async calculationTxGas(t){let{sender:e}=t.blockData;if(e===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:t,sender:e}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(t,e){try{return await this.signAndExecuteTransactionBlock({transactionBlock:e,signer:t,options:{showEffects:!0,showEvents:!0}})}catch(r){console.log("error: ",r)}}async sendSimulationTransaction(t,e,r=!0){try{if(r)return await this.devInspectTransactionBlock({transactionBlock:t,sender:e});let i={ProgrammableTransaction:{inputs:t.blockData.inputs.map(l=>{let{type:d,value:b}=l;return d==="object"?ed.Inputs.SharedObjectRef({objectId:b,initialSharedVersion:0,mutable:!0}):b}),transactions:t.blockData.transactions}},o=rd.bcs.TransactionKind.serialize(i,{maxSize:131072}).toBytes(),s=Js(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(n){console.log("devInspectTransactionBlock error",n)}}},nd=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new I0({url:t.fullRpcUrl}),this._swap=new S0(this),this._pool=new b0(this),this._position=new _0(this),this._rewarder=new v0(this),this._router=new T0(this),this._router_v2=new k0(this),this._token=new x0(this),this._config=new A0(this),zl(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(t){this._senderAddress=t}get Swap(){return this._swap}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}get Pool(){return this._pool}get Position(){return this._position}get Rewarder(){return this._rewarder}get Router(){return this._router}get RouterV2(){return this._router_v2}get CetusConfig(){return this._config}get Token(){return this._token}async getOwnerCoinAssets(t,e,r=!0){let n=[],i=null,o=`${this.sdkOptions.fullRpcUrl}_${t}_${e}_getOwnerCoinAssets`,s=this.getCache(o,r);if(s)return s;for(;;){let u=await(e?this.fullClient.getCoins({owner:t,coinType:e,cursor:i}):this.fullClient.getAllCoins({owner:t,cursor:i}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&n.push({coinAddress:se(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),i=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,n,30*1e3),n}async getOwnerCoinBalances(t,e){let r=[];return e?r=[await this.fullClient.getBalance({owner:t,coinType:e})]:r=[...await this.fullClient.getAllBalances({owner:t})],r}updateCache(t,e,r=Oe){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}};var fh=require("@msafe/sui3-utils"),Oh=require("@mysten/sui.js/client"),dr=de(require("axios"),1),on=require("@mysten/sui.js/utils"),Ln=require("@mysten/sui.js/utils");var ar=class extends Error{},So=class extends ar{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},xo=class extends ar{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},ko=class extends ar{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},zt=class extends ar{},vn=class extends ar{constructor(e){super(`Invalid unit ${e}`)}},lt=class extends ar{},Wt=class extends ar{constructor(){super("Zone is an abstract class")}};var z="numeric",Ht="short",Pt="long",_r={year:z,month:z,day:z},Xn={year:z,month:Ht,day:z},va={year:z,month:Ht,day:z,weekday:Ht},Yn={year:z,month:Pt,day:z},Qn={year:z,month:Pt,day:z,weekday:Pt},ei={hour:z,minute:z},ti={hour:z,minute:z,second:z},ri={hour:z,minute:z,second:z,timeZoneName:Ht},ni={hour:z,minute:z,second:z,timeZoneName:Pt},ii={hour:z,minute:z,hourCycle:"h23"},oi={hour:z,minute:z,second:z,hourCycle:"h23"},si={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Ht},ai={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Pt},ui={year:z,month:z,day:z,hour:z,minute:z},ci={year:z,month:z,day:z,hour:z,minute:z,second:z},li={year:z,month:Ht,day:z,hour:z,minute:z},di={year:z,month:Ht,day:z,hour:z,minute:z,second:z},Ta={year:z,month:Ht,day:z,weekday:Ht,hour:z,minute:z},fi={year:z,month:Pt,day:z,hour:z,minute:z,timeZoneName:Ht},hi={year:z,month:Pt,day:z,hour:z,minute:z,second:z,timeZoneName:Ht},pi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,timeZoneName:Pt},mi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,second:z,timeZoneName:Pt};var Ot=class{get type(){throw new Wt}get name(){throw new Wt}get ianaName(){return this.name}get isUniversal(){throw new Wt}offsetName(e,r){throw new Wt}formatOffset(e,r){throw new Wt}offset(e){throw new Wt}equals(e){throw new Wt}get isValid(){throw new Wt}};var Sa=null,vr=class t extends Ot{static get instance(){return Sa===null&&(Sa=new t),Sa}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Oo={};function C0(t){return Oo[t]||(Oo[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Oo[t]}var O0={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function M0(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,o,s,u,l,d,b]=n;return[s,i,o,u,l,d,b]}function E0(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:o,value:s}=r[i],u=O0[o];o==="era"?n[u]=s:ne(u)||(n[u]=parseInt(s,10))}return n}var Co={},At=class t extends Ot{static create(e){return Co[e]||(Co[e]=new t(e)),Co[e]}static resetCache(){Co={},Oo={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n,this.name)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=C0(this.name),[i,o,s,u,l,d,b]=n.formatToParts?E0(n,r):M0(n,r);u==="BC"&&(i=-Math.abs(i)+1);let T=Tn({year:i,month:o,day:s,hour:l===24?0:l,minute:d,second:b,millisecond:0}),x=+r,A=x%1e3;return x-=A>=0?A:1e3+A,(T-x)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var id={};function P0(t,e={}){let r=JSON.stringify([t,e]),n=id[r];return n||(n=new Intl.ListFormat(t,e),id[r]=n),n}var xa={};function ka(t,e={}){let r=JSON.stringify([t,e]),n=xa[r];return n||(n=new Intl.DateTimeFormat(t,e),xa[r]=n),n}var Aa={};function D0(t,e={}){let r=JSON.stringify([t,e]),n=Aa[r];return n||(n=new Intl.NumberFormat(t,e),Aa[r]=n),n}var Ia={};function B0(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),o=Ia[i];return o||(o=new Intl.RelativeTimeFormat(t,e),Ia[i]=o),o}var gi=null;function N0(){return gi||(gi=new Intl.DateTimeFormat().resolvedOptions().locale,gi)}var od={};function R0(t){let e=od[t];if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,od[t]=e}return e}function j0(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=ka(t).resolvedOptions(),i=t}catch{let l=t.substring(0,r);n=ka(l).resolvedOptions(),i=l}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function F0(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function q0(t){let e=[];for(let r=1;r<=12;r++){let n=le.utc(2009,r,1);e.push(t(n))}return e}function L0(t){let e=[];for(let r=1;r<=7;r++){let n=le.utc(2016,11,13+r);e.push(t(n))}return e}function Mo(t,e,r,n){let i=t.listingMode();return i==="error"?null:i==="en"?r(e):n(e)}function U0(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var Ca=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!r||Object.keys(s).length>0){let u={useGrouping:!1,...n};n.padTo>0&&(u.minimumIntegerDigits=n.padTo),this.inf=D0(e,u)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):Sn(e,3);return Ee(r,this.padTo)}}},Oa=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),u=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&At.create(u).valid?(i=u,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=ka(r,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Ma=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&Eo()&&(this.rtf=B0(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):sd(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},$0={firstDay:1,minimalDays:4,weekend:[6,7]},ge=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,i,o=!1){let s=e||he.defaultLocale,u=s||(o?"en-US":N0()),l=r||he.defaultNumberingSystem,d=n||he.defaultOutputCalendar,b=wi(i)||he.defaultWeekSettings;return new t(u,l,d,b,s)}static resetCache(){gi=null,xa={},Aa={},Ia={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:i}={}){return t.create(e,r,n,i)}constructor(e,r,n,i,o){let[s,u,l]=j0(e);this.locale=s,this.numberingSystem=r||u||null,this.outputCalendar=n||l||null,this.weekSettings=i,this.intl=F0(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=o,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=U0(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,wi(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return Mo(this,e,Ea,()=>{let n=r?{month:e,day:"numeric"}:{month:e},i=r?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=q0(o=>this.extract(o,n,"month"))),this.monthsCache[i][e]})}weekdays(e,r=!1){return Mo(this,e,Pa,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=r?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=L0(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return Mo(this,void 0,()=>Da,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[le.utc(2016,11,13,9),le.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Mo(this,e,Ba,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[le.utc(-40,1,1),le.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),o=i.formatToParts(),s=o.find(u=>u.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new Ca(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Oa(e,this.intl,r)}relFormatter(e={}){return new Ma(this.intl,this.isEnglish(),e)}listFormatter(e={}){return P0(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Po()?R0(this.locale):$0}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var Ra=null,ht=class t extends Ot{static get utcInstance(){return Ra===null&&(Ra=new t(0)),Ra}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(Hr(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Tr(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Tr(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return Tr(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var xn=class extends Ot{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Zt(t,e){let r;if(ne(t)||t===null)return e;if(t instanceof Ot)return t;if(ad(t)){let n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?vr.instance:n==="utc"||n==="gmt"?ht.utcInstance:ht.parseSpecifier(n)||At.create(t)}else return tr(t)?ht.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new xn(t)}var ud=()=>Date.now(),cd="system",ld=null,dd=null,fd=null,hd=60,pd,md=null,he=class{static get now(){return ud}static set now(e){ud=e}static set defaultZone(e){cd=e}static get defaultZone(){return Zt(cd,vr.instance)}static get defaultLocale(){return ld}static set defaultLocale(e){ld=e}static get defaultNumberingSystem(){return dd}static set defaultNumberingSystem(e){dd=e}static get defaultOutputCalendar(){return fd}static set defaultOutputCalendar(e){fd=e}static get defaultWeekSettings(){return md}static set defaultWeekSettings(e){md=wi(e)}static get twoDigitCutoffYear(){return hd}static set twoDigitCutoffYear(e){hd=e%100}static get throwOnInvalid(){return pd}static set throwOnInvalid(e){pd=e}static resetCaches(){ge.resetCache(),At.resetCache()}};var pt=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var gd=[0,31,59,90,120,151,181,212,243,273,304,334],wd=[0,31,60,91,121,152,182,213,244,274,305,335];function jt(t,e){return new pt("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Do(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function yd(t,e,r){return r+(Kr(t)?wd:gd)[e-1]}function bd(t,e){let r=Kr(t)?wd:gd,n=r.findIndex(o=>o<e),i=e-r[n];return{month:n+1,day:i}}function Bo(t,e){return(t-e+7)%7+1}function yi(t,e=4,r=1){let{year:n,month:i,day:o}=t,s=yd(n,i,o),u=Bo(Do(n,i,o),r),l=Math.floor((s-u+14-e)/7),d;return l<1?(d=n-1,l=Zr(d,e,r)):l>Zr(n,e,r)?(d=n+1,l=1):d=n,{weekYear:d,weekNumber:l,weekday:u,..._i(t)}}function ja(t,e=4,r=1){let{weekYear:n,weekNumber:i,weekday:o}=t,s=Bo(Do(n,1,e),r),u=Sr(n),l=i*7+o-s-7+e,d;l<1?(d=n-1,l+=Sr(d)):l>u?(d=n+1,l-=Sr(n)):d=n;let{month:b,day:_}=bd(d,l);return{year:d,month:b,day:_,..._i(t)}}function No(t){let{year:e,month:r,day:n}=t,i=yd(e,r,n);return{year:e,ordinal:i,..._i(t)}}function Fa(t){let{year:e,ordinal:r}=t,{month:n,day:i}=bd(e,r);return{year:e,month:n,day:i,..._i(t)}}function qa(t,e){if(!ne(t.localWeekday)||!ne(t.localWeekNumber)||!ne(t.localWeekYear)){if(!ne(t.weekday)||!ne(t.weekNumber)||!ne(t.weekYear))throw new zt("Cannot mix locale-based week fields with ISO-based week fields");return ne(t.localWeekday)||(t.weekday=t.localWeekday),ne(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),ne(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function _d(t,e=4,r=1){let n=bi(t.weekYear),i=Dt(t.weekNumber,1,Zr(t.weekYear,e,r)),o=Dt(t.weekday,1,7);return n?i?o?!1:jt("weekday",t.weekday):jt("week",t.weekNumber):jt("weekYear",t.weekYear)}function vd(t){let e=bi(t.year),r=Dt(t.ordinal,1,Sr(t.year));return e?r?!1:jt("ordinal",t.ordinal):jt("year",t.year)}function La(t){let e=bi(t.year),r=Dt(t.month,1,12),n=Dt(t.day,1,kn(t.year,t.month));return e?r?n?!1:jt("day",t.day):jt("month",t.month):jt("year",t.year)}function Ua(t){let{hour:e,minute:r,second:n,millisecond:i}=t,o=Dt(e,0,23)||e===24&&r===0&&n===0&&i===0,s=Dt(r,0,59),u=Dt(n,0,59),l=Dt(i,0,999);return o?s?u?l?!1:jt("millisecond",i):jt("second",n):jt("minute",r):jt("hour",e)}function ne(t){return typeof t>"u"}function tr(t){return typeof t=="number"}function bi(t){return typeof t=="number"&&t%1===0}function ad(t){return typeof t=="string"}function Sd(t){return Object.prototype.toString.call(t)==="[object Date]"}function Eo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Po(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xd(t){return Array.isArray(t)?t:[t]}function $a(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let o=[e(i),i];return n&&r(n[0],o[0])===n[0]?n:o},null)[1]}function kd(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function xr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wi(t){if(t==null)return null;if(typeof t!="object")throw new lt("Week settings must be an object");if(!Dt(t.firstDay,1,7)||!Dt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Dt(e,1,7)))throw new lt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Dt(t,e,r){return bi(t)&&t>=e&&t<=r}function G0(t,e){return t-e*Math.floor(t/e)}function Ee(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function ur(t){if(!(ne(t)||t===null||t===""))return parseInt(t,10)}function kr(t){if(!(ne(t)||t===null||t===""))return parseFloat(t)}function vi(t){if(!(ne(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function Sn(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function Kr(t){return t%4===0&&(t%100!==0||t%400===0)}function Sr(t){return Kr(t)?366:365}function kn(t,e){let r=G0(e-1,12)+1,n=t+(e-r)/12;return r===2?Kr(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function Tn(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Td(t,e,r){return-Bo(Do(t,1,e),r)+e-1}function Zr(t,e=4,r=1){let n=Td(t,e,r),i=Td(t+1,e,r);return(Sr(t)-n+i)/7}function Ti(t){return t>99?t:t>he.twoDigitCutoffYear?1900+t:2e3+t}function Io(t,e,r,n=null){let i=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},u=new Intl.DateTimeFormat(r,s).formatToParts(i).find(l=>l.type.toLowerCase()==="timezonename");return u?u.value:null}function Hr(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function Ga(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new lt(`Invalid unit value ${t}`);return e}function An(t,e){let r={};for(let n in t)if(xr(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=Ga(i)}return r}function Tr(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Ee(r,2)}:${Ee(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Ee(r,2)}${Ee(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function _i(t){return kd(t,["hour","minute","second","millisecond"])}var V0=["January","February","March","April","May","June","July","August","September","October","November","December"],Va=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],z0=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ea(t){switch(t){case"narrow":return[...z0];case"short":return[...Va];case"long":return[...V0];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var za=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Wa=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],W0=["M","T","W","T","F","S","S"];function Pa(t){switch(t){case"narrow":return[...W0];case"short":return[...Wa];case"long":return[...za];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Da=["AM","PM"],H0=["Before Christ","Anno Domini"],Z0=["BC","AD"],K0=["B","A"];function Ba(t){switch(t){case"narrow":return[...K0];case"short":return[...Z0];case"long":return[...H0];default:return null}}function Ad(t){return Da[t.hour<12?0:1]}function Id(t,e){return Pa(e)[t.weekday-1]}function Cd(t,e){return Ea(e)[t.month-1]}function Od(t,e){return Ba(e)[t.year<0?0:1]}function sd(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&o){let _=t==="days";switch(e){case 1:return _?"tomorrow":`next ${i[t][0]}`;case-1:return _?"yesterday":`last ${i[t][0]}`;case 0:return _?"today":`this ${i[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,u=Math.abs(e),l=u===1,d=i[t],b=n?l?d[1]:d[2]||d[1]:l?i[t][0]:t;return s?`${u} ${b} ago`:`in ${u} ${b}`}function Md(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var J0={D:_r,DD:Xn,DDD:Yn,DDDD:Qn,t:ei,tt:ti,ttt:ri,tttt:ni,T:ii,TT:oi,TTT:si,TTTT:ai,f:ui,ff:li,fff:fi,ffff:pi,F:ci,FF:di,FFF:hi,FFFF:mi},mt=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let u=e.charAt(s);u==="'"?(n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),r=null,n="",i=!i):i||u===r?n+=u:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=u,r=u)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return J0[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return Ee(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(x,A)=>this.loc.extract(e,x,A),s=x=>e.isOffsetFixed&&e.offset===0&&x.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,x.format):"",u=()=>n?Ad(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(x,A)=>n?Cd(e,x):o(A?{month:x}:{month:x,day:"numeric"},"month"),d=(x,A)=>n?Id(e,x):o(A?{weekday:x}:{weekday:x,month:"long",day:"numeric"},"weekday"),b=x=>{let A=t.macroTokenToFormatOpts(x);return A?this.formatWithSystemDefault(e,A):x},_=x=>n?Od(e,x):o({era:x},"era"),T=x=>{switch(x){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return d("short",!0);case"cccc":return d("long",!0);case"ccccc":return d("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return d("short",!1);case"EEEE":return d("long",!1);case"EEEEE":return d("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return _("short");case"GG":return _("long");case"GGGGG":return _("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return b(x)}};return Md(t.parseFormat(r),T)}formatDurationFromString(e,r){let n=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=l=>d=>{let b=n(d);return b?this.num(l.get(b),d.length):d},o=t.parseFormat(r),s=o.reduce((l,{literal:d,val:b})=>d?l:l.concat(b),[]),u=e.shiftTo(...s.map(n).filter(l=>l));return Md(o,i(u))}};var Pd=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Cn(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function On(...t){return e=>t.reduce(([r,n,i],o)=>{let[s,u,l]=o(e,i);return[{...r,...s},u||n,l]},[{},null,1]).slice(0,2)}function Mn(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function Dd(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=ur(e[r+i]);return[n,null,r+i]}}var Bd=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,X0=`(?:${Bd.source}?(?:\\[(${Pd.source})\\])?)?`,Ha=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Nd=RegExp(`${Ha.source}${X0}`),Za=RegExp(`(?:T${Nd.source})?`),Y0=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Q0=/(\d{4})-?W(\d\d)(?:-?(\d))?/,ew=/(\d{4})-?(\d{3})/,tw=Dd("weekYear","weekNumber","weekDay"),rw=Dd("year","ordinal"),nw=/(\d{4})-(\d\d)-(\d\d)/,Rd=RegExp(`${Ha.source} ?(?:${Bd.source}|(${Pd.source}))?`),iw=RegExp(`(?: ${Rd.source})?`);function In(t,e,r){let n=t[e];return ne(n)?r:ur(n)}function ow(t,e){return[{year:In(t,e),month:In(t,e+1,1),day:In(t,e+2,1)},null,e+3]}function En(t,e){return[{hours:In(t,e,0),minutes:In(t,e+1,0),seconds:In(t,e+2,0),milliseconds:vi(t[e+3])},null,e+4]}function Si(t,e){let r=!t[e]&&!t[e+1],n=Hr(t[e+1],t[e+2]),i=r?null:ht.instance(n);return[{},i,e+3]}function xi(t,e){let r=t[e]?At.create(t[e]):null;return[{},r,e+1]}var sw=RegExp(`^T?${Ha.source}$`),aw=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function uw(t){let[e,r,n,i,o,s,u,l,d]=t,b=e[0]==="-",_=l&&l[0]==="-",T=(x,A=!1)=>x!==void 0&&(A||x&&b)?-x:x;return[{years:T(kr(r)),months:T(kr(n)),weeks:T(kr(i)),days:T(kr(o)),hours:T(kr(s)),minutes:T(kr(u)),seconds:T(kr(l),l==="-0"),milliseconds:T(vi(d),_)}]}var cw={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Ka(t,e,r,n,i,o,s){let u={year:e.length===2?Ti(ur(e)):ur(e),month:Va.indexOf(r)+1,day:ur(n),hour:ur(i),minute:ur(o)};return s&&(u.second=ur(s)),t&&(u.weekday=t.length>3?za.indexOf(t)+1:Wa.indexOf(t)+1),u}var lw=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function dw(t){let[,e,r,n,i,o,s,u,l,d,b,_]=t,T=Ka(e,i,n,r,o,s,u),x;return l?x=cw[l]:d?x=0:x=Hr(b,_),[T,new ht(x)]}function fw(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var hw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,pw=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,mw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Ed(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,i,n,r,o,s,u),ht.utcInstance]}function gw(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,u,r,n,i,o,s),ht.utcInstance]}var ww=Cn(Y0,Za),yw=Cn(Q0,Za),bw=Cn(ew,Za),_w=Cn(Nd),jd=On(ow,En,Si,xi),vw=On(tw,En,Si,xi),Tw=On(rw,En,Si,xi),Sw=On(En,Si,xi);function Fd(t){return Mn(t,[ww,jd],[yw,vw],[bw,Tw],[_w,Sw])}function qd(t){return Mn(fw(t),[lw,dw])}function Ld(t){return Mn(t,[hw,Ed],[pw,Ed],[mw,gw])}function Ud(t){return Mn(t,[aw,uw])}var xw=On(En);function $d(t){return Mn(t,[sw,xw])}var kw=Cn(nw,iw),Aw=Cn(Rd),Iw=On(En,Si,xi);function Gd(t){return Mn(t,[kw,jd],[Aw,Iw])}var Vd="Invalid Duration",Wd={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Cw={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Wd},Ft=146097/400,Pn=146097/4800,Ow={years:{quarters:4,months:12,weeks:Ft/7,days:Ft,hours:Ft*24,minutes:Ft*24*60,seconds:Ft*24*60*60,milliseconds:Ft*24*60*60*1e3},quarters:{months:3,weeks:Ft/28,days:Ft/4,hours:Ft*24/4,minutes:Ft*24*60/4,seconds:Ft*24*60*60/4,milliseconds:Ft*24*60*60*1e3/4},months:{weeks:Pn/7,days:Pn,hours:Pn*24,minutes:Pn*24*60,seconds:Pn*24*60*60,milliseconds:Pn*24*60*60*1e3},...Wd},Jr=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Mw=Jr.slice(0).reverse();function Ar(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new _e(n)}function Hd(t,e){let r=e.milliseconds??0;for(let n of Mw.slice(1))e[n]&&(r+=e[n]*t[n].milliseconds);return r}function zd(t,e){let r=Hd(t,e)<0?-1:1;Jr.reduceRight((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]*r,s=t[i][n],u=Math.floor(o/s);e[i]+=u*r,e[n]-=u*s*r}return i},null),Jr.reduce((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*t[n][i]}return i},null)}function Ew(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var _e=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?Ow:Cw;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||ge.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new lt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:An(e,t.normalizeUnit),loc:ge.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(tr(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new lt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Ud(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=$d(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Duration is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new ko(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new vn(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?mt.create(this.loc,n).formatDurationFromString(this,e):Vd}toHuman(e={}){if(!this.isValid)return Vd;let r=Jr.map(n=>{let i=this.values[n];return ne(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Sn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},le.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Hd(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of Jr)(xr(r.values,i)||xr(this.values,i))&&(n[i]=r.get(i)+this.get(i));return Ar(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=Ga(e(this.values[n],n));return Ar(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...An(e,t.normalizeUnit)};return Ar(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return Ar(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return zd(this.matrix,e),Ar(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Ew(this.normalize().shiftToAll().toObject());return Ar(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let r={},n={},i=this.toObject(),o;for(let s of Jr)if(e.indexOf(s)>=0){o=s;let u=0;for(let d in n)u+=this.matrix[d][s]*n[d],n[d]=0;tr(i[s])&&(u+=i[s]);let l=Math.trunc(u);r[s]=l,n[s]=(u*1e3-l*1e3)/1e3}else tr(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(r[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return zd(this.matrix,r),Ar(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Ar(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of Jr)if(!r(this.values[n],e.values[n]))return!1;return!0}};var Dn="Invalid Interval";function Pw(t,e){return!t||!t.isValid?cr.invalid("missing or invalid start"):!e||!e.isValid?cr.invalid("missing or invalid end"):e<t?cr.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var cr=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Interval is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new xo(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=Bn(e),i=Bn(r),o=Pw(n,i);return o??new t({start:n,end:i})}static after(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=le.fromISO(n,r),s=o.isValid}catch{s=!1}let u,l;try{u=le.fromISO(i,r),l=u.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(o,u);if(s){let d=_e.fromISO(i,r);if(d.isValid)return t.after(o,d)}else if(l){let d=_e.fromISO(n,r);if(d.isValid)return t.before(u,d)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),i;return r?.useLocaleWeeks?i=this.end.reconfigure({locale:n.locale}):i=this.end,i=i.startOf(e,r),Math.floor(i.diff(n,e).get(e))+(i.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(Bn).filter(s=>this.contains(s)).sort((s,u)=>s.toMillis()-u.toMillis()),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=r[o]||this.e,u=+s>+this.e?this.e:s;n.push(t.fromDateTimes(i,u)),i=u,o+=1}return n}splitBy(e){let r=_e.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let u=this.start.plus(r.mapUnits(l=>l*i));o=+u>+this.e?this.e:u,s.push(t.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],o=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...o),u=s.sort((l,d)=>l.time-d.time);for(let l of u)n+=l.type==="s"?1:-1,n===1?r=l.time:(r&&+r!=+l.time&&i.push(t.fromDateTimes(r,l.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Dn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.s.loc.clone(r),e).formatInterval(this):Dn}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Dn}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Dn}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Dn}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Dn}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):_e.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var lr=class{static hasDST(e=he.defaultZone){let r=le.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return At.isValidZone(e)}static normalizeZone(e){return Zt(e,he.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ge.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return ge.create(r,null,"gregory").eras(e)}static features(){return{relative:Eo(),localeWeek:Po()}}};function Zd(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(_e.fromMillis(n).as("days"))}function Dw(t,e,r){let n=[["years",(l,d)=>d.year-l.year],["quarters",(l,d)=>d.quarter-l.quarter+(d.year-l.year)*4],["months",(l,d)=>d.month-l.month+(d.year-l.year)*12],["weeks",(l,d)=>{let b=Zd(l,d);return(b-b%7)/7}],["days",Zd]],i={},o=t,s,u;for(let[l,d]of n)r.indexOf(l)>=0&&(s=l,i[l]=d(t,e),u=o.plus(i),u>e?(i[l]--,t=o.plus(i),t>e&&(u=t,i[l]--,t=o.plus(i))):t=u);return[t,i,u,s]}function Kd(t,e,r,n){let[i,o,s,u]=Dw(t,e,r),l=e-i,d=r.filter(_=>["hours","minutes","seconds","milliseconds"].indexOf(_)>=0);d.length===0&&(s<e&&(s=i.plus({[u]:1})),s!==i&&(o[u]=(o[u]||0)+l/(s-i)));let b=_e.fromObject(o,n);return d.length>0?_e.fromMillis(l,n).shiftTo(...d).plus(b):b}var Ja={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Jd={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Bw=Ja.hanidec.replace(/[\[|\]]/g,"").split("");function Xd(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(Ja.hanidec)!==-1)e+=Bw.indexOf(t[r]);else for(let i in Jd){let[o,s]=Jd[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}function qt({numberingSystem:t},e=""){return new RegExp(`${Ja[t||"latn"]}${e}`)}var Nw="missing Intl.DateTimeFormat.formatToParts support";function pe(t,e=r=>r){return{regex:t,deser:([r])=>e(Xd(r))}}var Rw="\xA0",ef=`[ ${Rw}]`,tf=new RegExp(ef,"g");function jw(t){return t.replace(/\./g,"\\.?").replace(tf,ef)}function Yd(t){return t.replace(/\./g,"").replace(tf," ").toLowerCase()}function Kt(t,e){return t===null?null:{regex:RegExp(t.map(jw).join("|")),deser:([r])=>t.findIndex(n=>Yd(r)===Yd(n))+e}}function Qd(t,e){return{regex:t,deser:([,r,n])=>Hr(r,n),groups:e}}function Ro(t){return{regex:t,deser:([e])=>e}}function Fw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function qw(t,e){let r=qt(e),n=qt(e,"{2}"),i=qt(e,"{3}"),o=qt(e,"{4}"),s=qt(e,"{6}"),u=qt(e,"{1,2}"),l=qt(e,"{1,3}"),d=qt(e,"{1,6}"),b=qt(e,"{1,9}"),_=qt(e,"{2,4}"),T=qt(e,"{4,6}"),x=C=>({regex:RegExp(Fw(C.val)),deser:([E])=>E,literal:!0}),I=(C=>{if(t.literal)return x(C);switch(C.val){case"G":return Kt(e.eras("short"),0);case"GG":return Kt(e.eras("long"),0);case"y":return pe(d);case"yy":return pe(_,Ti);case"yyyy":return pe(o);case"yyyyy":return pe(T);case"yyyyyy":return pe(s);case"M":return pe(u);case"MM":return pe(n);case"MMM":return Kt(e.months("short",!0),1);case"MMMM":return Kt(e.months("long",!0),1);case"L":return pe(u);case"LL":return pe(n);case"LLL":return Kt(e.months("short",!1),1);case"LLLL":return Kt(e.months("long",!1),1);case"d":return pe(u);case"dd":return pe(n);case"o":return pe(l);case"ooo":return pe(i);case"HH":return pe(n);case"H":return pe(u);case"hh":return pe(n);case"h":return pe(u);case"mm":return pe(n);case"m":return pe(u);case"q":return pe(u);case"qq":return pe(n);case"s":return pe(u);case"ss":return pe(n);case"S":return pe(l);case"SSS":return pe(i);case"u":return Ro(b);case"uu":return Ro(u);case"uuu":return pe(r);case"a":return Kt(e.meridiems(),0);case"kkkk":return pe(o);case"kk":return pe(_,Ti);case"W":return pe(u);case"WW":return pe(n);case"E":case"c":return pe(r);case"EEE":return Kt(e.weekdays("short",!1),1);case"EEEE":return Kt(e.weekdays("long",!1),1);case"ccc":return Kt(e.weekdays("short",!0),1);case"cccc":return Kt(e.weekdays("long",!0),1);case"Z":case"ZZ":return Qd(new RegExp(`([+-]${u.source})(?::(${n.source}))?`),2);case"ZZZ":return Qd(new RegExp(`([+-]${u.source})(${n.source})?`),2);case"z":return Ro(/[a-z_+-/]{1,256}?/i);case" ":return Ro(/[^\S\n\r]/);default:return x(C)}})(t)||{invalidReason:Nw};return I.token=t,I}var Lw={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Uw(t,e,r){let{type:n,value:i}=t;if(n==="literal"){let l=/^\s+$/.test(i);return{literal:!l,val:l?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=r.hour12?"hour12":"hour24");let u=Lw[s];if(typeof u=="object"&&(u=u[o]),u)return{literal:!1,val:u}}function $w(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function Gw(t,e,r){let n=t.match(e);if(n){let i={},o=1;for(let s in r)if(xr(r,s)){let u=r[s],l=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(n.slice(o,o+l))),o+=l}return[n,i]}else return[n,{}]}function Vw(t){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return ne(t.z)||(r=At.create(t.z)),ne(t.Z)||(r||(r=new ht(t.Z)),n=t.Z),ne(t.q)||(t.M=(t.q-1)*3+1),ne(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),ne(t.u)||(t.S=vi(t.u)),[Object.keys(t).reduce((o,s)=>{let u=e(s);return u&&(o[u]=t[s]),o},{}),r,n]}var Xa=null;function zw(){return Xa||(Xa=le.fromMillis(1555555555555)),Xa}function Ww(t,e){if(t.literal)return t;let r=mt.macroTokenToFormatOpts(t.val),n=eu(r,e);return n==null||n.includes(void 0)?t:n}function Ya(t,e){return Array.prototype.concat(...t.map(r=>Ww(r,e)))}function Qa(t,e,r){let n=Ya(mt.parseFormat(r),t),i=n.map(s=>qw(s,t)),o=i.find(s=>s.invalidReason);if(o)return{input:e,tokens:n,invalidReason:o.invalidReason};{let[s,u]=$w(i),l=RegExp(s,"i"),[d,b]=Gw(e,l,u),[_,T,x]=b?Vw(b):[null,null,void 0];if(xr(b,"a")&&xr(b,"H"))throw new zt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:l,rawMatches:d,matches:b,result:_,zone:T,specificOffset:x}}}function rf(t,e,r){let{result:n,zone:i,specificOffset:o,invalidReason:s}=Qa(t,e,r);return[n,i,o,s]}function eu(t,e){if(!t)return null;let n=mt.create(e,t).dtFormatter(zw()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>Uw(s,t,o))}var tu="Invalid DateTime",nf=864e13;function jo(t){return new pt("unsupported zone",`the zone "${t.name}" is not supported`)}function ru(t){return t.weekData===null&&(t.weekData=yi(t.c)),t.weekData}function nu(t){return t.localWeekData===null&&(t.localWeekData=yi(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Xr(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new le({...r,...e,old:r})}function df(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=r.offset(n);return i===o?[n,i]:[t-Math.min(i,o)*60*1e3,Math.max(i,o)]}function Fo(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Lo(t,e,r){return df(Tn(t),e,r)}function of(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:n,month:i,day:Math.min(t.c.day,kn(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=_e.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=Tn(o),[l,d]=df(u,r,t.zone);return s!==0&&(l+=s,d=t.zone.offset(l)),{ts:l,o:d}}function ki(t,e,r,n,i,o){let{setZone:s,zone:u}=r;if(t&&Object.keys(t).length!==0||e){let l=e||u,d=le.fromObject(t,{...r,zone:l,specificOffset:o});return s?d:d.setZone(u)}else return le.invalid(new pt("unparsable",`the input "${i}" can't be parsed as ${n}`))}function qo(t,e,r=!0){return t.isValid?mt.create(ge.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function iu(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=Ee(t.c.year,r?6:4),e?(n+="-",n+=Ee(t.c.month),n+="-",n+=Ee(t.c.day)):(n+=Ee(t.c.month),n+=Ee(t.c.day)),n}function sf(t,e,r,n,i,o){let s=Ee(t.c.hour);return e?(s+=":",s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=":")):s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=Ee(t.c.second),(t.c.millisecond!==0||!n)&&(s+=".",s+=Ee(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Ee(Math.trunc(-t.o/60)),s+=":",s+=Ee(Math.trunc(-t.o%60))):(s+="+",s+=Ee(Math.trunc(t.o/60)),s+=":",s+=Ee(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var ff={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Hw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Zw={ordinal:1,hour:0,minute:0,second:0,millisecond:0},hf=["year","month","day","hour","minute","second","millisecond"],Kw=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Jw=["year","ordinal","hour","minute","second","millisecond"];function Xw(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new vn(t);return e}function af(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Xw(t)}}function uf(t,e){let r=Zt(e.zone,he.defaultZone),n=ge.fromObject(e),i=he.now(),o,s;if(ne(t.year))o=i;else{for(let d of hf)ne(t[d])&&(t[d]=ff[d]);let u=La(t)||Ua(t);if(u)return le.invalid(u);let l=r.offset(i);[o,s]=Lo(t,l,r)}return new le({ts:o,zone:r,loc:n,o:s})}function cf(t,e,r){let n=ne(r.round)?!0:r.round,i=(s,u)=>(s=Sn(s,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(s,u)),o=s=>r.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(r.unit)return i(o(r.unit),r.unit);for(let s of r.units){let u=o(s);if(Math.abs(u)>=1)return i(u,s)}return i(t>e?-0:0,r.units[r.units.length-1])}function lf(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var le=class t{constructor(e){let r=e.zone||he.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new pt("invalid input"):null)||(r.isValid?null:jo(r));this.ts=ne(e.ts)?he.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,o]=[e.old.c,e.old.o];else{let u=r.offset(this.ts);i=Fo(this.ts,u),n=Number.isNaN(i.year)?new pt("invalid input"):null,i=n?null:i,o=n?null:u}this._zone=r,this.loc=e.loc||ge.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static utc(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return e.zone=ht.utcInstance,uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static fromJSDate(e,r={}){let n=Sd(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Zt(r.zone,he.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:ge.fromObject(r)}):t.invalid(jo(i))}static fromMillis(e,r={}){if(tr(e))return e<-nf||e>nf?t.invalid("Timestamp out of range"):new t({ts:e,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(tr(e))return new t({ts:e*1e3,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Zt(r.zone,he.defaultZone);if(!n.isValid)return t.invalid(jo(n));let i=ge.fromObject(r),o=An(e,af),{minDaysInFirstWeek:s,startOfWeek:u}=qa(o,i),l=he.now(),d=ne(r.specificOffset)?n.offset(l):r.specificOffset,b=!ne(o.ordinal),_=!ne(o.year),T=!ne(o.month)||!ne(o.day),x=_||T,A=o.weekYear||o.weekNumber;if((x||b)&&A)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(T&&b)throw new zt("Can't mix ordinal dates with month/day");let I=A||o.weekday&&!x,C,E,P=Fo(l,d);I?(C=Kw,E=Hw,P=yi(P,s,u)):b?(C=Jw,E=Zw,P=No(P)):(C=hf,E=ff);let D=!1;for(let N of C){let j=o[N];ne(j)?D?o[N]=E[N]:o[N]=P[N]:D=!0}let L=I?_d(o,s,u):b?vd(o):La(o),H=L||Ua(o);if(H)return t.invalid(H);let W=I?ja(o,s,u):b?Fa(o):o,[K,F]=Lo(W,d,n),U=new t({ts:K,zone:n,o:F,loc:i});return o.weekday&&x&&e.weekday!==U.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${U.toISO()}`):U}static fromISO(e,r={}){let[n,i]=Fd(e);return ki(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=qd(e);return ki(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Ld(e);return ki(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(ne(e)||ne(r))throw new lt("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[u,l,d,b]=rf(s,e,r);return b?t.invalid(b):ki(u,l,n,`format ${r}`,e,d)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=Gd(e);return ki(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the DateTime is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new So(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=eu(e,ge.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return Ya(mt.parseFormat(e),ge.fromObject(r)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?ru(this).weekYear:NaN}get weekNumber(){return this.isValid?ru(this).weekNumber:NaN}get weekday(){return this.isValid?ru(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?nu(this).weekday:NaN}get localWeekNumber(){return this.isValid?nu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?nu(this).weekYear:NaN}get ordinal(){return this.isValid?No(this.c).ordinal:NaN}get monthShort(){return this.isValid?lr.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?lr.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?lr.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?lr.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=Tn(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*r),u=this.zone.offset(n-o*r);if(s===u)return[this];let l=n-s*r,d=n-u*r,b=Fo(l,s),_=Fo(d,u);return b.hour===_.hour&&b.minute===_.minute&&b.second===_.second&&b.millisecond===_.millisecond?[Xr(this,{ts:l}),Xr(this,{ts:d})]:[this]}get isInLeapYear(){return Kr(this.year)}get daysInMonth(){return kn(this.year,this.month)}get daysInYear(){return this.isValid?Sr(this.year):NaN}get weeksInWeekYear(){return this.isValid?Zr(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Zr(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=mt.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(ht.instance(e),r)}toLocal(){return this.setZone(he.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Zt(e,he.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let o=e.offset(this.ts),s=this.toObject();[i]=Lo(s,o,e)}return Xr(this,{ts:i,zone:e})}else return t.invalid(jo(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return Xr(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=An(e,af),{minDaysInFirstWeek:n,startOfWeek:i}=qa(r,this.loc),o=!ne(r.weekYear)||!ne(r.weekNumber)||!ne(r.weekday),s=!ne(r.ordinal),u=!ne(r.year),l=!ne(r.month)||!ne(r.day),d=u||l,b=r.weekYear||r.weekNumber;if((d||s)&&b)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new zt("Can't mix ordinal dates with month/day");let _;o?_=ja({...yi(this.c,n,i),...r},n,i):ne(r.ordinal)?(_={...this.toObject(),...r},ne(r.day)&&(_.day=Math.min(kn(_.year,_.month),_.day))):_=Fa({...No(this.c),...r});let[T,x]=Lo(_,this.o,this.zone);return Xr(this,{ts:T,o:x})}plus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e);return Xr(this,of(this,r))}minus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e).negate();return Xr(this,of(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},i=_e.normalizeUnit(e);switch(i){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(i==="weeks")if(r){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(n.weekNumber=this.weekNumber-1),n.weekday=o}else n.weekday=1;if(i==="quarters"){let o=Math.ceil(this.month/3);n.month=(o-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?mt.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):tu}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.loc.clone(r),e).formatDateTime(this):tu}toLocaleParts(e={}){return this.isValid?mt.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",u=iu(this,s);return u+="T",u+=sf(this,s,r,n,i,o),u}toISODate({format:e="extended"}={}){return this.isValid?iu(this,e==="extended"):null}toISOWeekDate(){return qo(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(i?"T":"")+sf(this,s==="extended",r,e,n,o):null}toRFC2822(){return qo(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return qo(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?iu(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),qo(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():tu}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return _e.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=xd(r).map(_e.normalizeUnit),s=e.valueOf()>this.valueOf(),u=s?this:e,l=s?e:this,d=Kd(u,l,o,i);return s?d.negate():d}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?cr.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let i=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(r,n)<=i&&i<=o.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),cf(r,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?cf(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new lt("min requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new lt("max requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return Qa(s,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return _r}static get DATE_MED(){return Xn}static get DATE_MED_WITH_WEEKDAY(){return va}static get DATE_FULL(){return Yn}static get DATE_HUGE(){return Qn}static get TIME_SIMPLE(){return ei}static get TIME_WITH_SECONDS(){return ti}static get TIME_WITH_SHORT_OFFSET(){return ri}static get TIME_WITH_LONG_OFFSET(){return ni}static get TIME_24_SIMPLE(){return ii}static get TIME_24_WITH_SECONDS(){return oi}static get TIME_24_WITH_SHORT_OFFSET(){return si}static get TIME_24_WITH_LONG_OFFSET(){return ai}static get DATETIME_SHORT(){return ui}static get DATETIME_SHORT_WITH_SECONDS(){return ci}static get DATETIME_MED(){return li}static get DATETIME_MED_WITH_SECONDS(){return di}static get DATETIME_MED_WITH_WEEKDAY(){return Ta}static get DATETIME_FULL(){return fi}static get DATETIME_FULL_WITH_SECONDS(){return hi}static get DATETIME_HUGE(){return pi}static get DATETIME_HUGE_WITH_SECONDS(){return mi}};function Bn(t){if(le.isDateTime(t))return t;if(t&&t.valueOf&&tr(t.valueOf()))return le.fromJSDate(t);if(t&&typeof t=="object")return le.fromObject(t);throw new lt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Pi=require("@mysten/sui.js/transactions"),ku=require("@mysten/sui.js/transactions"),Bi=require("@mysten/sui.js/utils"),Au=require("buffer"),Dh=require("@mysten/sui.js/utils"),Ru=require("@mysten/sui.js/bcs"),Ni=require("@mysten/sui.js/utils");var pf=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var Ou=require("@mysten/sui.js/transactions"),Rr=require("@mysten/sui.js/utils");var Di=require("@mysten/sui.js/transactions"),Ri=require("@mysten/sui.js/utils");var Kh=de(Wi(),1),Jh=require("@msafe/sui3-utils"),Xh=require("@msafe/sui3-utils"),Yh=require("@msafe/sui3-utils"),Du=require("@mysten/sui.js/bcs"),Dr=require("@mysten/sui.js/utils"),ep=require("@msafe/sui3-utils"),qn=require("@msafe/sui3-utils"),tp=require("@msafe/sui3-utils"),np=require("@msafe/sui3-utils"),op=require("@msafe/sui3-utils"),sp=require("@mysten/sui.js/transactions"),up=require("@msafe/sui3-utils"),Fn=require("@msafe/sui3-utils"),Bu=require("@mysten/sui.js/bcs"),Br=require("@mysten/sui.js/utils"),cp=require("@mysten/sui.js/transactions"),dp=require("@mysten/sui.js/transactions"),hp=require("@mysten/sui.js/transactions"),gp=require("@mysten/sui.js/transactions"),yp=require("@mysten/sui.js/transactions"),ls=require("@msafe/sui3-utils"),_p=require("@mysten/sui.js/transactions"),ds=require("@mysten/sui.js/utils"),$T=de(Wi(),1),vp=require("@msafe/sui3-utils"),Tp=require("@msafe/sui3-utils"),Nu=require("@mysten/sui.js/bcs"),Nr=require("@mysten/sui.js/utils");var vy=de(we(),1);var tn=require("@mysten/sui.js/client"),Ef=require("@mysten/sui.js/keypairs/ed25519");function mf(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Yw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function ou(t,...e){if(!Yw(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function su(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gf(t,e){ou(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Uo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Go=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Jt=(t,e)=>t<<32-e|t>>>e,ey=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ey)throw new Error("Non little-endian hardware is not supported");function ty(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function au(t){if(typeof t=="string"&&(t=ty(t)),!Qw(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var $o=class{clone(){return this._cloneInto()}},X2={}.toString;function wf(t){let e=n=>t().update(au(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yf(t=32){if(Uo&&typeof Uo.getRandomValues=="function")return Uo.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ry(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),u=Number(r&o),l=n?4:0,d=n?0:4;t.setUint32(e+l,s,n),t.setUint32(e+d,u,n)}var Vo=class extends $o{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){su(this);let{view:r,buffer:n,blockLen:i}=this;e=au(e);let o=e.length;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let l=Go(e);for(;i<=o-s;s+=i)this.process(l,s);continue}n.set(e.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){su(this),gf(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let _=s;_<i;_++)r[_]=0;ry(n,i-8,BigInt(this.length*8),o),this.process(n,0);let u=Go(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=l/4,b=this.get();if(d>b.length)throw new Error("_sha2: outputLen bigger than state");for(let _=0;_<d;_++)u.setUint32(4*_,b[_],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:u}=this;return e.length=i,e.pos=u,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var ny=(t,e,r)=>t&e^~t&r,iy=(t,e,r)=>t&e^t&r^e&r,oy=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ir=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=new Uint32Array(64),uu=class extends Vo{constructor(){super(64,32,8,!1),this.A=Ir[0]|0,this.B=Ir[1]|0,this.C=Ir[2]|0,this.D=Ir[3]|0,this.E=Ir[4]|0,this.F=Ir[5]|0,this.G=Ir[6]|0,this.H=Ir[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:u,H:l}=this;return[e,r,n,i,o,s,u,l]}set(e,r,n,i,o,s,u,l){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=u|0,this.H=l|0}process(e,r){for(let _=0;_<16;_++,r+=4)Cr[_]=e.getUint32(r,!1);for(let _=16;_<64;_++){let T=Cr[_-15],x=Cr[_-2],A=Jt(T,7)^Jt(T,18)^T>>>3,I=Jt(x,17)^Jt(x,19)^x>>>10;Cr[_]=I+Cr[_-7]+A+Cr[_-16]|0}let{A:n,B:i,C:o,D:s,E:u,F:l,G:d,H:b}=this;for(let _=0;_<64;_++){let T=Jt(u,6)^Jt(u,11)^Jt(u,25),x=b+T+ny(u,l,d)+oy[_]+Cr[_]|0,I=(Jt(n,2)^Jt(n,13)^Jt(n,22))+iy(n,i,o)|0;b=d,d=l,l=u,u=s+x|0,s=o,o=i,i=n,n=x+I|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,u=u+this.E|0,l=l+this.F|0,d=d+this.G|0,b=b+this.H|0,this.set(n,i,o,s,u,l,d,b)}roundClean(){Cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var bf=wf(()=>new uu);function Yr(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function zo(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function sy(...t){let e=o=>o,r=(o,s)=>u=>o(s(u)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function ay(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function uy(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function cy(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function cu(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],o=Array.from(t);for(o.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,u=!0;for(let l=n;l<o.length;l++){let d=o[l],b=e*s+d;if(!Number.isSafeInteger(b)||e*s/e!==s||b-d!==e*s)throw new Error("convertRadix: carry overflow");s=b%r;let _=Math.floor(b/r);if(o[l]=_,!Number.isSafeInteger(_)||_*r+s!==b)throw new Error("convertRadix: carry overflow");if(u)_?u=!1:n=l;else continue}if(i.push(s),u)break}for(let s=0;s<t.length-1&&t[s]===0;s++)i.push(0);return i.reverse()}var _f=(t,e)=>e?_f(e,t%e):t,Wo=(t,e)=>t+(e-_f(t,e));function lu(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Wo(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Wo(e,r)}`);let i=0,o=0,s=2**r-1,u=[];for(let l of t){if(l>=2**e)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(i=i<<e|l,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)u.push((i>>o-r&s)>>>0);i&=2**o-1}if(i=i<<r-o&s,!n&&o>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&u.push(i>>>0),u}function ly(t){return{encode:e=>{if(!zo(e))throw new Error("radix.encode input should be Uint8Array");return cu(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(cu(e,t,2**8))}}}function dy(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Wo(8,t)>32||Wo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!zo(r))throw new Error("radix2.encode input should be Uint8Array");return lu(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(lu(r,t,8,e))}}}function fy(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!zo(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!zo(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),o=r.slice(-t);for(let s=0;s<t;s++)if(i[s]!==o[s])throw new Error("Invalid checksum");return n}}}var Ai={alphabet:ay,chain:sy,checksum:fy,convertRadix:cu,convertRadix2:lu,radix:ly,radix2:dy,join:uy,padding:cy};var hy=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function py(t){ou(t,16,20,24,28,32)}function vf(t,e=128){if(mf(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return wy(yf(e/8),t)}var my=t=>{let e=8-t.length/4;return new Uint8Array([bf(t)[0]>>e<<e])};function gy(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),Ai.chain(Ai.checksum(1,my),Ai.radix2(11,!0),Ai.alphabet(t))}function wy(t,e){return py(t),gy(e).encode(t).join(hy(e)?"\u3000":" ")}var Tf=`abandon
6
6
  ability
7
7
  able
8
8
  about
@@ -2050,7 +2050,7 @@ zebra
2050
2050
  zero
2051
2051
  zone
2052
2052
  zoo`.split(`
2053
- `);var Ii=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,du=typeof process=="object"&&process?process:{},kf=(t,e,r,n)=>{typeof du.emitWarning=="function"?du.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Ho=globalThis.AbortController,Sf=globalThis.AbortSignal;if(typeof Ho>"u"){Sf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Ho=class{constructor(){e()}signal=new Sf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=du.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yy=t=>!xf.has(t),pT=Symbol("type"),Or=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Af=t=>Or(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Nn:null:null,Nn=class extends Array{constructor(e){super(e),this.fill(0)}},fu=class t{heap;length;static#u=!1;static create(e){let r=Af(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zo=class t{#u;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#i;#r;#e;#c;#f;#a;#o;#g;#s;#T;#S;#w;#b;#k;#l;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#w,sizes:e.#T,keyMap:e.#i,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,o)=>e.#P(r,n,i,o),moveToTail:r=>e.#C(r),indexes:r=>e.#_(r),rindexes:r=>e.#v(r),isStale:r=>e.#h(r)}}get max(){return this.#u}get maxSize(){return this.#d}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:u,allowStale:l,dispose:d,disposeAfter:b,noDisposeOnSet:_,noUpdateTTL:T,maxSize:x=0,maxEntrySize:A=0,sizeCalculation:I,fetchMethod:C,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:D,allowStaleOnFetchAbort:L,ignoreFetchAbort:H}=e;if(r!==0&&!Or(r))throw new TypeError("max option must be a nonnegative integer");let W=r?Af(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#u=r,this.#d=x,this.maxEntrySize=A||this.#d,this.sizeCalculation=I,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(C!==void 0&&typeof C!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=C,this.#k=!!C,this.#i=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new W(r),this.#f=new W(r),this.#a=0,this.#o=0,this.#g=fu.create(r),this.#n=0,this.#m=0,typeof d=="function"&&(this.#y=d),typeof b=="function"?(this.#p=b,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!T,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!D,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#d!==0&&!Or(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Or(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!u,this.ttlResolution=Or(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Or(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#u===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#d){let K="LRU_CACHE_UNBOUNDED";yy(K)&&(xf.add(K),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,t))}}getRemainingTTL(e){return this.#i.has(e)?1/0:0}#D(){let e=new Nn(this.#u),r=new Nn(this.#u);this.#w=e,this.#S=r,this.#B=(o,s,u=Ii.now())=>{if(r[o]=s!==0?u:0,e[o]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#h(o)&&this.delete(this.#r[o])},s+1);l.unref&&l.unref()}},this.#A=o=>{r[o]=e[o]!==0?Ii.now():0},this.#x=(o,s)=>{if(e[s]){let u=e[s],l=r[s];o.ttl=u,o.start=l,o.now=n||i();let d=o.now-l;o.remainingTTL=u-d}};let n=0,i=()=>{let o=Ii.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#i.get(o);if(s===void 0)return 0;let u=e[s],l=r[s];if(u===0||l===0)return 1/0;let d=(n||i())-l;return u-d},this.#h=o=>e[o]!==0&&r[o]!==0&&(n||i())-r[o]>e[o]}#A=()=>{};#x=()=>{};#B=()=>{};#h=()=>!1;#F(){let e=new Nn(this.#u);this.#m=0,this.#T=e,this.#I=r=>{this.#m-=e[r],e[r]=0},this.#N=(r,n,i,o)=>{if(this.#t(n))return 0;if(!Or(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(n,r),!Or(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#d){let o=this.#d-e[r];for(;this.#m>o;)this.#E(!0)}this.#m+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#m)}}#I=e=>{};#M=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#o;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#v({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#o));)r=this.#c[r]}#R(e){return e!==void 0&&this.#i.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#_()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#v()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#_())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#v()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#v({allowStale:!0}))this.#h(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#_({allowStale:!0})){let n=this.#r[r],i=this.#e[r],o=this.#t(i)?i.__staleWhileFetching:i;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#w&&this.#S){s.ttl=this.#w[r];let u=Ii.now()-this.#S[r];s.start=Math.floor(Date.now()-u)}this.#T&&(s.size=this.#T[r]),e.unshift([n,s])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ii.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:l}=n,{noUpdateTTL:d=this.noUpdateTTL}=n,b=this.#N(e,r,n.size||0,u);if(this.maxEntrySize&&b>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let _=this.#n===0?void 0:this.#i.get(e);if(_===void 0)_=this.#n===0?this.#o:this.#g.length!==0?this.#g.pop():this.#n===this.#u?this.#E(!1):this.#n,this.#r[_]=e,this.#e[_]=r,this.#i.set(e,_),this.#c[this.#o]=_,this.#f[_]=this.#o,this.#o=_,this.#n++,this.#M(_,b,l),l&&(l.set="add"),d=!1;else{this.#C(_);let T=this.#e[_];if(r!==T){if(this.#k&&this.#t(T)?T.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(T,e,"set"),this.#l&&this.#s?.push([T,e,"set"])),this.#I(_),this.#M(_,b,l),this.#e[_]=r,l){l.set="replace";let x=T&&this.#t(T)?T.__staleWhileFetching:T;x!==void 0&&(l.oldValue=x)}}else l&&(l.set="update")}if(i!==0&&!this.#w&&this.#D(),this.#w&&(d||this.#B(_,i,o),l&&this.#x(l,_)),!s&&this.#l&&this.#s){let T=this.#s,x;for(;x=T?.shift();)this.#p?.(...x)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}}#E(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#k&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,n,"evict"),this.#l&&this.#s?.push([i,n,"evict"])),this.#I(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#g.push(r)),this.#n===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#c[r],this.#i.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,o=this.#i.get(e);if(o!==void 0){let s=this.#e[o];if(this.#t(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#h(o))i&&(i.has="stale",this.#x(i,o));else return n&&this.#A(o),i&&(i.has="hit",this.#x(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#i.get(e);if(i!==void 0&&(n||!this.#h(i))){let o=this.#e[i];return this.#t(o)?o.__staleWhileFetching:o}}#P(e,r,n,i){let o=r===void 0?void 0:this.#e[r];if(this.#t(o))return o;let s=new Ho,{signal:u}=n;u?.addEventListener("abort",()=>s.abort(u.reason),{signal:s.signal});let l={signal:s.signal,options:n,context:i},d=(I,C=!1)=>{let{aborted:E}=s.signal,P=n.ignoreFetchAbort&&I!==void 0;if(n.status&&(E&&!C?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,P&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),E&&!P&&!C)return _(s.signal.reason);let D=x;return this.#e[r]===x&&(I===void 0?D.__staleWhileFetching?this.#e[r]=D.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,I,l.options))),I},b=I=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=I),_(I)),_=I=>{let{aborted:C}=s.signal,E=C&&n.allowStaleOnFetchAbort,P=E||n.allowStaleOnFetchRejection,D=P||n.noDeleteOnFetchRejection,L=x;if(this.#e[r]===x&&(!D||L.__staleWhileFetching===void 0?this.delete(e):E||(this.#e[r]=L.__staleWhileFetching)),P)return n.status&&L.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw I},T=(I,C)=>{let E=this.#O?.(e,o,l);E&&E instanceof Promise&&E.then(P=>I(P),C),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(I(),n.allowStaleOnFetchAbort&&(I=P=>d(P,!0)))})};n.status&&(n.status.fetchDispatched=!0);let x=new Promise(T).then(d,b),A=Object.assign(x,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,A,{...l.options,status:void 0}),r=this.#i.get(e)):this.#e[r]=A,A}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Ho}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:l=0,sizeCalculation:d=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:T=this.allowStaleOnFetchRejection,ignoreFetchAbort:x=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:I,forceRefresh:C=!1,status:E,signal:P}=r;if(!this.#k)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:E});let D={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:u,size:l,sizeCalculation:d,noUpdateTTL:b,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:A,ignoreFetchAbort:x,status:E,signal:P},L=this.#i.get(e);if(L===void 0){E&&(E.fetch="miss");let H=this.#P(e,L,D,I);return H.__returned=H}else{let H=this.#e[L];if(this.#t(H)){let N=n&&H.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=!0)),N?H.__staleWhileFetching:H.__returned=H}let W=this.#h(L);if(!C&&!W)return E&&(E.fetch="hit"),this.#C(L),i&&this.#A(L),E&&this.#x(E,L),H;let K=this.#P(e,L,D,I),U=K.__staleWhileFetching!==void 0&&n;return E&&(E.fetch=W?"stale":"refresh",U&&W&&(E.returnedStale=!0)),U?K.__staleWhileFetching:K.__returned=K}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=r,u=this.#i.get(e);if(u!==void 0){let l=this.#e[u],d=this.#t(l);return s&&this.#x(s,u),this.#h(u)?(s&&(s.get="stale"),d?(s&&n&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?l.__staleWhileFetching:void 0):(o||this.delete(e),s&&n&&(s.returnedStale=!0),n?l:void 0)):(s&&(s.get="hit"),d?l.__staleWhileFetching:(this.#C(u),i&&this.#A(u),l))}else s&&(s.get="miss")}#j(e,r){this.#f[r]=e,this.#c[e]=r}#C(e){e!==this.#o&&(e===this.#a?this.#a=this.#c[e]:this.#j(this.#f[e],this.#c[e]),this.#j(this.#o,e),this.#o=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#i.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#I(n);let i=this.#e[n];this.#t(i)?i.__abortController.abort(new Error("deleted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,e,"delete"),this.#l&&this.#s?.push([i,e,"delete"])),this.#i.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#o?this.#o=this.#f[n]:n===this.#a?this.#a=this.#c[n]:(this.#c[this.#f[n]]=this.#c[n],this.#f[this.#c[n]]=this.#f[n]),this.#n--,this.#g.push(n)}}if(this.#l&&this.#s?.length){let n=this.#s,i;for(;i=n?.shift();)this.#p?.(...i)}return r}clear(){for(let e of this.#v({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#b&&this.#y?.(r,n,"delete"),this.#l&&this.#s?.push([r,n,"delete"])}}if(this.#i.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#w&&this.#S&&(this.#w.fill(0),this.#S.fill(0)),this.#T&&this.#T.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#m=0,this.#n=0,this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}};var Q=de(we(),1);var Yo=de(If(),1),Qr=require("@mysten/sui.js/utils"),en=require("@mysten/sui.js/transactions");var Ci=de(we(),1),Nf=require("@mysten/sui.js/transactions"),Mt=de(we(),1);var Mr=de(we(),1),Lt=de(we(),1);var Ei=de(we(),1);var Rf=require("@mysten/sui.js/utils"),Qo=require("@mysten/sui.js/transactions"),es=require("@mysten/sui.js/utils");var yu=de(we(),1),by=Object.defineProperty,_y=(t,e,r)=>e in t?by(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e,r)=>(_y(t,typeof e!="symbol"?e+"":e,r),r);var Ko=443636,Jo=-443636,mu="79226673515401279992447579055",gu="4295048016",Ty=14,Sy="59543866431248",xy="184467440737095516",ky="15793534762490258745",Ay=class{generateMnemonic(t=24){return vf(Tf,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let r=this.getDerivePath(e);return Ef.Ed25519Keypair.deriveKeypair(t,r)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:r=!1,addressIndex:n=0}=t;return`m/44'/784'/${e}'/${r?1:0}'/${n}'`}},Mi=class{constructor(t){this.sdk=t,rr(this,"_lru"),rr(this,"_fetching",{})}async getCacheOrSet(t,e,r=0){var n;let i=this._lru||(this._lru=new Zo({max:100}));if(i.has(t))return i.get(t);let s=await((n=this._fetching)[t]||(n[t]=e()));return delete this._fetching[t],i.set(t,s,{ttl:r}),s}get provider(){return this.sdk.provider}get math(){return this.sdk.math}get account(){return this.sdk.account}get network(){return this.sdk.network}get contract(){return this.sdk.contract}get nft(){return this.sdk.nft}get coin(){return this.sdk.coin}get trade(){return this.sdk.trade}get pool(){return this.sdk.pool}};function Iy(t){if("reference"in t)return t.reference;let e=bu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Df(t)}function rs(t){var e,r;return"objectId"in t?t.objectId:(r=(e=Iy(t))==null?void 0:e.objectId)!=null?r:Bf(t)}function nr(t){var e;return"fields"in t?t.fields:(e=Pf(t))==null?void 0:e.fields}function Pf(t){let e="data"in t?bu(t):t;if(!(!e||!Cy(e)||e.content.dataType!=="moveObject"))return e.content}function Cy(t){return t.content!==void 0}function bu(t){return t.data}function Df(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let e=t.error;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Bf(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Oy(t){return t.data!==void 0}function My(t){var e;let r=Oy(t)?t.data:t;return!r?.type&&"data"in t?((e=r?.content)==null?void 0:e.dataType)==="package"?"package":ts(t):r?.type}function ts(t){var e;return(e=Pf(t))==null?void 0:e.type}function Ey(t){var e;return(e=bu(t))==null?void 0:e.owner}var Oi=async(t,e,r)=>{let i=e.length;if(i>50){let o=[],s=0,u=Math.ceil(i/50);for(s;s<u;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:r}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:r})},Py=class extends Mi{async getConfig(){return(await this.fetchJSON())[this.network].contract}getFees(){return this.getCacheOrSet("fees",async()=>{let e=(await this.fetchJSON())[this.network].fee;return(await Oi(this.provider,Object.values(e),{showContent:!0})).map(n=>{let i=nr(n),o=rs(n),s=ts(n);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:i.fee,tickSpacing:i.tick_spacing}})})}fetchJSON(){return this.getCacheOrSet("contract-json",async()=>await(await fetch("https://s3.amazonaws.com/app.turbos.finance/sdk/contract.json?t="+Date.now(),{method:"GET"})).json())}},Cf=new Q.default(2).pow(new Q.default(128)),Dy=class{priceToSqrtPriceX64(t,e,r){return new Q.default(new $(t).mul($.pow(10,r-e)).sqrt().mul($.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,r){return new $(t.toString()).mul($.pow(2,-64)).pow(2).mul($.pow(10,e-r))}priceToTickIndex(t,e,r){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,r))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Q.default(mu))||t.lt(new Q.default(gu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,r=new Q.default(e-64),n=this.signedShiftLeft(r,32,128),i=new Q.default("8000000000000000","hex"),o=0,s=new Q.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new Q.default(0))&&o<Ty;){u=u.mul(u);let x=u.shrn(127);u=u.shrn(63+x.toNumber()),s=s.add(i.mul(x)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new Q.default(Sy)),_=this.signedShiftRight(b.sub(new Q.default(xy)),64,128).toNumber(),T=this.signedShiftRight(b.add(new Q.default(ky)),64,128).toNumber();return _==T?_:this.tickIndexToSqrtPriceX64(T).lte(t)?T:_}tickIndexToSqrtPriceX64(t){return t>0?new Q.default(this.tickIndexToSqrtPricePositive(t)):new Q.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,r){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,r)}toX64_Decimal(t){return t.mul($.pow(2,64))}fromX64_Decimal(t){return t.mul($.pow(2,-64))}scaleDown(t,e){return new $(t).div($.pow(10,e)).toString()}scaleUp(t,e){return new $(t).mul($.pow(10,e)).toString()}bitsToNumber(t,e=32){return Yo.default.toNumber(Yo.default.asIntN(e,Yo.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Cf).sub(e).mod(Cf)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Q.default("79232123823359799118286999567"):e=new Q.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Q.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Q.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Q.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Q.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Q.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Q.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Q.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Q.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Q.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Q.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Q.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Q.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Q.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Q.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Q.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Q.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Q.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Q.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),r;return e&1?r=new Q.default("18445821805675392311"):r=new Q.default("18446744073709551616"),e&2&&(r=this.signedShiftRight(r.mul(new Q.default("18444899583751176498")),64,256)),e&4&&(r=this.signedShiftRight(r.mul(new Q.default("18443055278223354162")),64,256)),e&8&&(r=this.signedShiftRight(r.mul(new Q.default("18439367220385604838")),64,256)),e&16&&(r=this.signedShiftRight(r.mul(new Q.default("18431993317065449817")),64,256)),e&32&&(r=this.signedShiftRight(r.mul(new Q.default("18417254355718160513")),64,256)),e&64&&(r=this.signedShiftRight(r.mul(new Q.default("18387811781193591352")),64,256)),e&128&&(r=this.signedShiftRight(r.mul(new Q.default("18329067761203520168")),64,256)),e&256&&(r=this.signedShiftRight(r.mul(new Q.default("18212142134806087854")),64,256)),e&512&&(r=this.signedShiftRight(r.mul(new Q.default("17980523815641551639")),64,256)),e&1024&&(r=this.signedShiftRight(r.mul(new Q.default("17526086738831147013")),64,256)),e&2048&&(r=this.signedShiftRight(r.mul(new Q.default("16651378430235024244")),64,256)),e&4096&&(r=this.signedShiftRight(r.mul(new Q.default("15030750278693429944")),64,256)),e&8192&&(r=this.signedShiftRight(r.mul(new Q.default("12247334978882834399")),64,256)),e&16384&&(r=this.signedShiftRight(r.mul(new Q.default("8131365268884726200")),64,256)),e&32768&&(r=this.signedShiftRight(r.mul(new Q.default("3584323654723342297")),64,256)),e&65536&&(r=this.signedShiftRight(r.mul(new Q.default("696457651847595233")),64,256)),e&131072&&(r=this.signedShiftRight(r.mul(new Q.default("26294789957452057")),64,256)),e&262144&&(r=this.signedShiftRight(r.mul(new Q.default("37481735321082")),64,256)),r}signedShiftLeft(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}signedShiftRight(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}},wu=(t,e)=>{let r=rs(t);if(Df(t))throw new Error(`${e}(${r}) had been deleted`);if(Bf(t))throw new Error(`${e}(${r}) is not found`);return!0},Rn=60*1e3,By=class extends Mi{async getPools(t=!1){let e=await this.contract.getConfig(),r=[],n;do n=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:n?.nextCursor,limit:15}),r.push(...n.data.map(u=>u.objectId));while(n.hasNextPage);if(!r.length)return[];let o=(await Oi(this.provider,r,{showContent:!0})).map(u=>nr(u).value.fields.pool_id);if(!o.length)return[];let s=await Oi(this.provider,o,{showContent:!0});return t||(s=s.filter(u=>nr(u).unlocked)),s.map(u=>this.parsePool(u))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:r,tickLower:n,tickUpper:i,sqrtPrice:o,slippage:s,coinTypeA:u,coinTypeB:l}=t,d=await this.contract.getConfig(),b=new $(t.amountA),_=new $(t.amountB),[T,x]=await Promise.all([this.coin.selectTradeCoins(r,u,b),this.coin.selectTradeCoins(r,l,_)]),A=t.txb||new en.TransactionBlock,I=T.length>0?this.coin.convertTradeCoins(A,T,u,b):[this.coin.zero(u,A)],C=x.length>0?this.coin.convertTradeCoins(A,x,l,_):[this.coin.zero(l,A)];return A.moveCall({target:`${d.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[u,l,e.type],arguments:[A.object(d.PoolConfig),A.object(e.objectId),A.pure(o,"u128"),A.object(d.Positions),A.makeMoveVec({objects:I}),A.makeMoveVec({objects:C}),A.pure(Math.abs(n).toFixed(0),"u32"),A.pure(n<0,"bool"),A.pure(Math.abs(i).toFixed(0),"u32"),A.pure(i<0,"bool"),A.pure(b.toFixed(0),"u64"),A.pure(_.toFixed(0),"u64"),A.pure(this.getMinimumAmountBySlippage(b,s),"u64"),A.pure(this.getMinimumAmountBySlippage(_,s),"u64"),A.pure(r,"address"),A.pure(Date.now()+Rn,"u64"),A.object(Qr.SUI_CLOCK_OBJECT_ID),A.object(d.Versioned)]}),A}async addLiquidity(t){let{address:e,tickLower:r,tickUpper:n,slippage:i,pool:o}=t,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(o),[l,d]=u,[b,_]=await Promise.all([this.coin.getMetadata(l),this.coin.getMetadata(d)]);if(!b||!_)throw new Error("Invalid coin type");let T=new $(t.amountA),x=new $(t.amountB),[A,I]=await Promise.all([this.coin.selectTradeCoins(e,l,T),this.coin.selectTradeCoins(e,d,x)]),C=t.txb||new en.TransactionBlock,E=A.length>0?this.coin.convertTradeCoins(C,A,l,T):[this.coin.zero(l,C)],P=I.length>0?this.coin.convertTradeCoins(C,I,d,x):[this.coin.zero(d,C)];return C.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:u,arguments:[C.object(o),C.object(s.Positions),C.makeMoveVec({objects:E}),C.makeMoveVec({objects:P}),C.pure(Math.abs(r).toFixed(0),"u32"),C.pure(r<0,"bool"),C.pure(Math.abs(n).toFixed(0),"u32"),C.pure(n<0,"bool"),C.pure(T.toFixed(0),"u64"),C.pure(x.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(T,i),"u64"),C.pure(this.getMinimumAmountBySlippage(x,i),"u64"),C.pure(e,"address"),C.pure(Date.now()+Rn,"u64"),C.object(Qr.SUI_CLOCK_OBJECT_ID),C.object(s.Versioned)]}),C}async increaseLiquidity(t){let{pool:e,slippage:r,address:n,nft:i}=t,o=await this.contract.getConfig(),s=new $(t.amountA),u=new $(t.amountB),l=await this.getPoolTypeArguments(e),[d,b]=l,[_,T]=await Promise.all([this.coin.selectTradeCoins(n,d,s),this.coin.selectTradeCoins(n,b,u)]),x=t.txb||new en.TransactionBlock,A=_.length>0?this.coin.convertTradeCoins(x,_,d,s):[this.coin.zero(d,x)],I=T.length>0?this.coin.convertTradeCoins(x,T,b,u):[this.coin.zero(b,x)];return x.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:l,arguments:[x.object(e),x.object(o.Positions),x.makeMoveVec({objects:A}),x.makeMoveVec({objects:I}),x.object(i),x.pure(s.toFixed(0),"u64"),x.pure(u.toFixed(0),"u64"),x.pure(this.getMinimumAmountBySlippage(s,r),"u64"),x.pure(this.getMinimumAmountBySlippage(u,r),"u64"),x.pure(Date.now()+Rn*3,"u64"),x.object(Qr.SUI_CLOCK_OBJECT_ID),x.object(o.Versioned)]}),x}async decreaseLiquidity(t){let{slippage:e,nft:r,pool:n,decreaseLiquidity:i}=t,o=new $(t.amountA),s=new $(t.amountB),u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(n),d=t.txb||new en.TransactionBlock;return d.moveCall({target:`${u.PackageId}::position_manager::decrease_liquidity`,typeArguments:l,arguments:[d.object(n),d.object(u.Positions),d.object(r),d.pure(new Ci.default(i).toString(),"u128"),d.pure(this.getMinimumAmountBySlippage(o,e),"u64"),d.pure(this.getMinimumAmountBySlippage(s,e),"u64"),d.pure(Date.now()+Rn*3,"u64"),d.object(Qr.SUI_CLOCK_OBJECT_ID),d.object(u.Versioned)]}),d}async removeLiquidity(t){let e=await this.decreaseLiquidity(t);return e=await this.collectFee({txb:e,...t}),e=await this.collectReward({txb:e,...t}),e=await this.nft.burn({txb:e,nft:t.nft,pool:t.pool}),e}async collectFee(t){let{pool:e,nft:r,address:n,collectAmountA:i,collectAmountB:o}=t,s=t.txb||new en.TransactionBlock;if(Number(i)===0&&Number(o)===0)return s;let u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(e);return s.moveCall({target:`${u.PackageId}::position_manager::collect`,typeArguments:l,arguments:[s.object(e),s.object(u.Positions),s.object(r),s.pure(i,"u64"),s.pure(o,"u64"),s.pure(n),s.pure(Date.now()+Rn*3,"u64"),s.object(Qr.SUI_CLOCK_OBJECT_ID),s.object(u.Versioned)]}),s}async collectReward(t){let{pool:e,nft:r,rewardAmounts:n,address:i}=t,o=t.txb||new en.TransactionBlock,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((d,b)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...u,d.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(r),o.object(d.fields.vault),o.pure(b,"u64"),o.pure(n[b],"u64"),o.pure(i),o.pure(Date.now()+Rn*3,"u64"),o.object(Qr.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new $((t.liquidity||new Ci.default(1e8)).toString()),r=new $(t.currentSqrtPrice.toString()),n=new $(t.lowerSqrtPrice.toString()),i=new $(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(n)).div(n.mul(i)),s=new $(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(r)).div(r.mul(i)),s=this.math.fromX64_Decimal(e.mul(r.sub(n)))):(o=new $(0),s=this.math.fromX64_Decimal(e.mul(i.sub(n))));let u=t.ceil!==!1?"ceil":"floor";return[new Ci.default(o[u]().toString()),new Ci.default(s[u]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var r;let n=((r=t.replace(">","").split("<")[1])==null?void 0:r.split(/,\s*/))||[];if(e!==void 0&&e!==n.length)throw new Error("Invalid pool type");return n}async getFixedLiquidity(t){var e,r;let{coinTypeA:n,coinTypeB:i,amountA:o,amountB:s}=t,[u,l]=await Promise.all([this.coin.getMetadata(n),this.coin.getMetadata(i)]),d=new $(this.math.scaleDown(o,u.decimals)).mul((e=t.priceA)!=null?e:1),b=new $(this.math.scaleDown(s,l.decimals)).mul((r=t.priceB)!=null?r:1);return{liquidityA:d.toString(),liquidityB:b.toString(),liquidity:d.plus(b).toString()}}parsePool(t){let e=nr(t),r=rs(t),n=My(t),i=this.parsePoolType(n,3);return this.getCacheOrSet("pool-type-"+r,async()=>i),{...e,objectId:r,type:n,types:i}}getMinimumAmountBySlippage(t,e){let r=new $(t),n=new $(1).minus(new $(e).div(100));if(n.lte(0)||n.gt(1))throw new Error("invalid slippage range");return r.mul(n).toFixed(0)}},Ny=(t,e)=>{let{pool:r,position:n,tickLowerDetail:i,tickUpperDetail:o}=e,s=new Mr.default(r.fee_growth_global_a),u=new Mr.default(n.fee_growth_inside_a),l=new Mr.default(n.tokens_owed_a),d=new Mr.default(r.fee_growth_global_b),b=new Mr.default(n.fee_growth_inside_b),_=new Mr.default(n.tokens_owed_b),T=new Mr.default(n.liquidity),x,A,I,C,E=t.bitsToNumber(r.tick_current_index.fields.bits),P=t.bitsToNumber(n.tick_lower_index.fields.bits),D=t.bitsToNumber(n.tick_upper_index.fields.bits);E<P?(x=t.subUnderflowU128(s,i.feeGrowthOutsideA),A=t.subUnderflowU128(d,i.feeGrowthOutsideB)):(x=i.feeGrowthOutsideA,A=i.feeGrowthOutsideB),E<D?(I=o.feeGrowthOutsideA,C=o.feeGrowthOutsideB):(I=t.subUnderflowU128(s,o.feeGrowthOutsideA),C=t.subUnderflowU128(d,o.feeGrowthOutsideB));let L=t.subUnderflowU128(t.subUnderflowU128(s,x),I),H=t.subUnderflowU128(t.subUnderflowU128(d,A),C),W=t.subUnderflowU128(L,u).mul(T).shrn(64),K=t.subUnderflowU128(H,b).mul(T).shrn(64);return{feeOwedA:l.add(W).toString(),feeOwedB:_.add(K).toString()}},Of=new Ei.default(0),Mf=new Ei.default(1),Ry=new Ei.default(2),jy={mul(t,e,r){let n=t.mul(e);if(this.isOverLimit(n,r))throw new Error(`Mul result higher than u${r}`);return n},mulDiv(t,e,r,n){return this.mulDivRoundUpIf(t,e,r,!1,n)},mulDivRoundUpIf(t,e,r,n,i){if(r.eq(Of))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,i),s=o.div(r);return n&&o.mod(r).gt(Of)?s.add(Mf):s},isOverLimit(t,e){let r=Ry.pow(new Ei.default(e)).sub(Mf);return t.gt(r)}},Fy=(t,e)=>{var r,n,i,o;let{pool:s,position:u,tickLowerDetail:l,tickUpperDetail:d,timeStampInSeconds:b}=e,_=new Lt.default(new $(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),x=(b??new Lt.default(Date.now()).div(new Lt.default(1e3))).sub(new Lt.default(_)),A=[],I=new Lt.default(s.liquidity),C=new Lt.default(u.liquidity);for(let E=0;E<3;++E){let P=s.reward_infos[E],D={emissionsPerSecondX64:new Lt.default(P?P.fields.emissions_per_second:"0"),growthGlobalX64:new Lt.default(P?P.fields.growth_global:"0")},L={growthInsideCheckpoint:new Lt.default((n=(r=u.reward_infos[E])==null?void 0:r.fields.reward_growth_inside)!=null?n:"0"),amountOwed:new Lt.default((o=(i=u.reward_infos[E])==null?void 0:i.fields.amount_owed)!=null?o:"0")},H=D.growthGlobalX64;if(!I.isZero()){let S=jy.mulDiv(x,D.emissionsPerSecondX64,I,128);H=D.growthGlobalX64.add(S)}let W=l.rewardGrowthsOutside[E],K=d.rewardGrowthsOutside[E],F=H;l.initialized&&(F=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_lower_index.fields.bits)?t.subUnderflowU128(H,W):W);let U=new Lt.default(0);d.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_upper_index.fields.bits)?K:t.subUnderflowU128(H,K));let N=t.subUnderflowU128(t.subUnderflowU128(H,F),U),j=L.amountOwed.shln(64);A[E]=j.add(t.subUnderflowU128(N,L.growthInsideCheckpoint).mul(C)).shrn(64).toString()}return A},qy=class extends Mi{async getOwner(t){let e=await this.getObject(t),r=Ey(e);if(!(!r||typeof r=="string")){if("ObjectOwner"in r)return r.ObjectOwner;if("AddressOwner"in r)return r.AddressOwner}}async getFields(t){let e=await this.getObject(t);return nr(e)}async getPositionFields(t){let e=await this.contract.getConfig(),r=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return nr(r)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"position"),nr(e)}async getPositionTick(t,e){let r=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),n=nr(r);if(n)return{tickIndex:this.math.bitsToNumber(n.name.fields.bits),initialized:n.value.fields.initialized,liquidityNet:new Mt.default(this.math.bitsToNumber(n.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Mt.default(n.value.fields.liquidity_gross),feeGrowthOutsideA:new Mt.default(n.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Mt.default(n.value.fields.fee_growth_outside_b),rewardGrowthsOutside:n.value.fields.reward_growths_outside.map(i=>new Mt.default(i))}}async getPositionAPR(t){let{poolId:e,getPrice:r,fees24h:n,tickLower:i,tickUpper:o}=t,s=await this.pool.getPool(e),u=this.math.bitsToNumber(s.tick_current_index.fields.bits),[l,d,b,_]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),r(s.types[0]),r(s.types[1])]);if(!b||!_||i>=o||u<i||u>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:T,minTokenB:x}=this.getRemoveLiquidityQuote(s,i,o),A=new $(this.math.scaleDown(T.toString(),l.decimals)).mul(b),I=new $(this.math.scaleDown(x.toString(),d.decimals)).mul(_),C=A.add(I),E=C.isZero()?new $(0):new $(n).mul(365).div(C).mul(100),P=new $(0);return await Promise.all(s.reward_infos.map(async D=>{let{emissions_per_second:L}=D.fields,H=this.coin.formatCoinType(D.fields.vault_coin_type),[W,K]=await Promise.all([r(H),this.coin.getMetadata(H)]);!L||L==="0"||!W||(P=P.add(new $(new Mt.default(L).shrn(64).toString()).div(10**K.decimals).mul(31536e3).mul(W).div(C).mul(100)))})),{fees:E.toString(),rewards:P.toString(),total:E.plus(P).toString()}}getRemoveLiquidityQuote(t,e,r){let n=new Mt.default(0),i=new Mt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),u=this.math.tickIndexToSqrtPriceX64(r);if(o<e){let d=this.getTokenAFromLiquidity(i,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:n}}if(o<r){let d=new Mt.default(t.sqrt_price),b=this.getTokenAFromLiquidity(i,d,u),_=this.getTokenBFromLiquidity(i,s,d);return{minTokenA:this.adjustForSlippage(b),minTokenB:this.adjustForSlippage(_)}}let l=this.getTokenBFromLiquidity(i,s,u);return{minTokenA:n,minTokenB:this.adjustForSlippage(l)}}adjustForSlippage(t){let e={numerator:new Mt.default(0),denominator:new Mt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,r){let n=t.mul(r.sub(e)).shln(64),i=r.mul(e);return n.div(i)}getTokenBFromLiquidity(t,e,r){return t.mul(r.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:r}=t,n=t.txb||new Nf.TransactionBlock,i=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return n.moveCall({target:`${i.PackageId}::position_manager::burn`,typeArguments:o,arguments:[n.object(i.Positions),n.object(r),n.object(i.Versioned)]}),n}async getPositionLiquidityUSD(t){let{position:e,poolId:r,priceA:n,priceB:i}=t,o=await this.pool.getPool(r),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Mt.default(o.sqrt_price),lowerSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_lower_index.fields.bits)),upperSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_upper_index.fields.bits)),liquidity:new Mt.default(e.liquidity===void 0?1e8:e.liquidity)}),[u,l]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),d=new $(s[0].toString()).div(10**u.decimals).mul(n||0),b=new $(s[1].toString()).div(10**l.decimals).mul(i||0);return d.plus(b).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:r}=t,[n,i,o]=await Promise.all([this.pool.getPool(r),this.nft.getPositionTick(r,e.tick_lower_index),this.nft.getPositionTick(r,e.tick_upper_index)]),s={...t,pool:n,tickLowerDetail:i,tickUpperDetail:o},[u,l]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:d,...b}=u,{unclaimedRewards:_,...T}=l;return{fees:u.unclaimedFees.toString(),rewards:_.toString(),total:d.plus(_).toString(),fields:{...b,...T}}}async getUnclaimedFees(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,[s,u,l,d]=await Promise.all([this.coin.getMetadata(r.types[0]),this.coin.getMetadata(r.types[1]),n(r.types[0]),n(r.types[1])]),b=Ny(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),_=this.math.scaleDown(b.feeOwedA,s.decimals),T=this.math.scaleDown(b.feeOwedB,u.decimals);function x(C,E){return new $(1e6).mul($.pow(10,E)).lt(C)}x(_,s.decimals)&&(_="0",b.feeOwedA="0"),x(T,u.decimals)&&(T="0",b.feeOwedB="0");let A=l===void 0?new $(0):new $(l).mul(_),I=d===void 0?new $(0):new $(d).mul(T);return{unclaimedFees:A.plus(I),scaledFeeOwedA:_,scaledFeeOwedB:T,...b}}async getUnclaimedRewards(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,s=Fy(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),u=[...s],l=r.reward_infos.map(T=>this.coin.formatCoinType(T.fields.vault_coin_type)),d=await Promise.all([...r.reward_infos.map((T,x)=>this.coin.getMetadata(l[x]))]),b=await Promise.all(r.reward_infos.map((T,x)=>n(l[x])));d.forEach((T,x)=>{u[x]=this.math.scaleDown(u[x],T.decimals)});let _=new $(0);return r.reward_infos.some((T,x)=>{let A=b[x];return A?(_=_.plus(new $(A).mul(u[x])),!1):(_=_.plus(1),!0)}),{unclaimedRewards:_,collectRewards:s,scaledCollectRewards:u}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return wu(e,"nft"),e})}},Ly=class extends Mi{isSUI(t){return(0,Rf.normalizeSuiAddress)(t)==="0x000000000000000000000000000000000000000000000000000002::sui::sui"}async getMetadata(t){return this.getCacheOrSet(`coin-metadata-${t}`,async()=>{let e=await this.provider.getCoinMetadata({coinType:t});if(!e)throw new Error(`Coin "${t}" is not found`);return e})}async selectTradeCoins(t,e,r){if(r.eq(0))return[];let n=[],i=[],o=new $(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),n.push(...s.data);while(s.hasNextPage);n.sort((u,l)=>Number(l.balance)-Number(u.balance));for(let u of n)if(i.push(u.coinObjectId),o=o.add(u.balance),o.gte(r))break;return i}convertTradeCoins(t,e,r,n){return this.isSUI(r)?[t.splitCoins(t.gas,[t.pure(n.toNumber())])[0]]:e.map(i=>t.object(i))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let n=t.replace(/^0x/i,"");return n=n.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&n.length<64&&t!=="2::sui:SUI"?"0".repeat(64-n.length):"")+n}},Uy=60*1e3,Xo=100,$y=class extends Mi{async swap(t){let{coinTypeA:e,coinTypeB:r,address:n,amountSpecifiedIsInput:i,slippage:o}=t,s=new $(t.amountA),u=new $(t.amountB),l=await this.contract.getConfig(),d=await Promise.all(t.routes.map(async I=>{let C=await this.pool.getPoolTypeArguments(I.pool),[E,P]=await Promise.all([this.coin.getMetadata(C[0]),this.coin.getMetadata(C[1])]);return{...I,coinA:E,coinB:P,typeArguments:C}})),b=await this.coin.selectTradeCoins(n,e,s),{functionName:_,typeArguments:T}=this.getFunctionNameAndTypeArguments(d.map(({typeArguments:I})=>I),e,r),x=d.map(({nextTickIndex:I,coinA:C,coinB:E,a2b:P})=>{let D=this.math.tickIndexToPrice(I,C.decimals,E.decimals);return this.sqrtPriceWithSlippage(D,o,P,C.decimals,E.decimals)}),A=t.txb||new Qo.TransactionBlock;return A.moveCall({target:`${l.PackageId}::swap_router::${_}`,typeArguments:T,arguments:[...d.map(({pool:I})=>A.object(I)),A.makeMoveVec({objects:this.coin.convertTradeCoins(A,b,e,s)}),A.pure((i?s:u).toFixed(0),"u64"),A.pure(this.amountOutWithSlippage(i?u:s,o,i),"u64"),...x.map(I=>A.pure(I,"u128")),A.pure(i,"bool"),A.pure(n,"address"),A.pure(Date.now()+Uy*3,"u64"),A.object(es.SUI_CLOCK_OBJECT_ID),A.object(l.Versioned)]}),A}async computeSwapResult(t){let{pools:e,amountSpecified:r,amountSpecifiedIsInput:n,address:i,tickStep:o}=t,s=await this.contract.getConfig(),u=e.map(_=>_.pool),l=await Oi(this.provider,u,{showContent:!0}),d=new Qo.TransactionBlock;l.map(async _=>{let T=nr(_),x=e.find(P=>P.pool===T.id.id),A=this.math.bitsToNumber(T.tick_current_index.fields.bits),I=A-T.tick_spacing*(o||Xo),C=A+T.tick_spacing*(o||Xo);I=I<Jo?Jo:I,C=C>Ko?Ko:C;let E=this.pool.parsePoolType(ts(_));d.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:E,arguments:[d.object(T.id.id),d.pure(x.a2b,"bool"),d.pure(new $(r).toFixed(0),"u128"),d.pure(n,"bool"),d.pure(this.math.tickIndexToSqrtPriceX64(x.a2b?I:C).toString(),"u128"),d.object(es.SUI_CLOCK_OBJECT_ID),d.object(s.Versioned)]})});let b=await this.provider.devInspectTransactionBlock({transactionBlock:d,sender:i});if(b.error)throw new Error(b.error);return b.events.map(_=>_.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:r,address:n,tickStep:i}=t,o=await this.contract.getConfig(),s=e.map(b=>b.pool),u=await Oi(this.provider,Array.from(new Set(s)),{showContent:!0}),l=new Qo.TransactionBlock;e.forEach(async b=>{let _=u.find(E=>rs(E)===b.pool),T=nr(_),x=this.math.bitsToNumber(T.tick_current_index.fields.bits),A=x-T.tick_spacing*(i||Xo),I=x+T.tick_spacing*(i||Xo);A=A<Jo?Jo:A,I=I>Ko?Ko:I;let C=this.pool.parsePoolType(ts(_));l.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:C,arguments:[l.object(T.id.id),l.pure(b.a2b,"bool"),l.pure(new $(b.amountSpecified).toFixed(0),"u128"),l.pure(r,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(b.a2b?A:I).toString(),"u128"),l.object(es.SUI_CLOCK_OBJECT_ID),l.object(o.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:n});if(d.error)throw new Error(d.error);return d.events.map(b=>b.parsedJson)}getFunctionNameAndTypeArguments(t,e,r){let n=[],i=["swap"];if(t.length===1)n=t[0],e===n[0]?i.push("a","b"):i.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(i.push("a","b"),n.push(o[0],o[2],o[1])):(i.push("b","a"),n.push(o[1],o[2],o[0])),n.push(s[2],r),r===s[0]?i.push("c","b"):i.push("b","c")}return{functionName:i.join("_"),typeArguments:n}}amountOutWithSlippage(t,e,r){if(r){let i=new $(100).minus(e).div(100);return new $(t).mul(i).toFixed(0)}let n=new $(100).plus(e).div(100);return new $(t).mul(n).toFixed(0)}sqrtPriceWithSlippage(t,e,r,n,i){let o=new $(t).mul(r?new $(100).minus(e).div(100):new $(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,n,i);return s.lt(new yu.BN(gu))?gu:s.gt(new yu.BN(mu))?mu:s.toString()}},It=class{constructor(t,e){this.network=t,rr(this,"pool"),rr(this,"contract"),rr(this,"math",new Dy),rr(this,"account",new Ay),rr(this,"coin"),rr(this,"nft"),rr(this,"trade"),rr(this,"provider"),this.provider=e?e instanceof tn.SuiClient?e:new tn.SuiClient(e):new tn.SuiClient({url:t==="mainnet"?(0,tn.getFullnodeUrl)("mainnet"):(0,tn.getFullnodeUrl)("testnet")}),this.contract=new Py(this),this.pool=new By(this),this.nft=new qy(this),this.coin=new Ly(this),this.trade=new $y(this)}};var Gy=Object.defineProperty,uh=(t,e)=>{for(var r in e)Gy(t,r,{get:e[r],enumerable:!0})},St=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,lh.default)(this.data))}},Vy={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},_u=new nd(Vy),zy=async(t,e,r,n,i)=>{console.log("getSwapRouterTxb account2: ",n),console.log("getSwapRouterTxb suiClient: ",i),_u.senderAddress=r;let o=await _u.getOwnerCoinAssets(r);return await Pe.buildAggregatorSwapTransaction(_u,t,o,"",e)},Wy=class dh extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r,suiClient:n}=e,{payloadParams:i}=this.data,o=await zy(i?.createTxParams,i?.slippage,i?.account,r,n);return console.log("Swap intention build txb: ",o),o}static fromData(e){return new dh(e)}},Hy=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{payloadParams:e,action:r}=t;return{txType:ch.TransactionType.Other,txSubType:`Cetus${r}`,intentionData:{payloadParams:e,action:r}}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"CetusSwap":n=Wy.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},hh={};uh(hh,{contractId:()=>gh,default:()=>Zy,feeObjId:()=>bh,roleObjId:()=>wh,status:()=>mh,transaction:()=>ph,upgradeCapObjId:()=>_h,vaultObjId:()=>yh});var ph="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",mh="success",gh="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",wh="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yh="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",bh="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_h="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zy={transaction:ph,status:mh,contractId:gh,roleObjId:wh,vaultObjId:yh,feeObjId:bh,upgradeCapObjId:_h},vh={};uh(vh,{contractId:()=>xh,default:()=>Ky,feeObjId:()=>Ih,roleObjId:()=>kh,status:()=>Sh,transaction:()=>Th,upgradeCapObjId:()=>Ch,vaultObjId:()=>Ah});var Th="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sh="success",xh="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",kh="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ah="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Ih="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ch="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ky={transaction:Th,status:Sh,contractId:xh,roleObjId:kh,vaultObjId:Ah,feeObjId:Ih,upgradeCapObjId:Ch},Jy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Xy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Yy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",eb="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tb="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",rb="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",nb="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",jf=hh,Ff=vh,ib=new Map([["dev",{env:"dev",rpc:{url:Jy},backend:{url:eb},contract:jf}],["stg",{env:"stg",rpc:{url:Xy},backend:{url:tb},contract:jf}],["prev",{env:"prev",rpc:{url:Yy},backend:{url:rb},contract:Ff}],["prod",{env:"prod",rpc:{url:Qy},backend:{url:nb},contract:Ff}]]);function ob(t,e){let r=ib.get(t);if(!r)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(r.rpc=e.rpc),e&&e.backend&&(r.backend=e.backend),e&&e.contract&&(r.contract=e.contract),r}var Nt=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:i}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=i}},sb=class extends Nt{constructor(){super(11,"Backend is not specified")}},ab=class extends Nt{constructor(){super(1,"Wallet not connected")}},vu=class extends Nt{constructor(t,e){super(10,t,{context:e})}},ub=class nn{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof dr.AxiosError)throw new vu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new vu(e.data.code)}throw new vu(e.status.toString())}async getIncomingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{recipient:e,...r});return nn.parseResponseData(n)}async getOutgoingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{sender:e,...r});return nn.parseResponseData(n)}async getStreamHistory(e){let r=await dr.default.post(`${this.apiURL}/stream-events`,e),n=nn.parseResponseData(r);return n.data.forEach(i=>{let o=i;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),n}async getAllCoinTypes(e){let r=await dr.default.post(`${this.apiURL}/stream-info`,{address:e});return nn.parseResponseData(r)}async getAllRecipients(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:r});return nn.parseResponseData(n)}async getAllSenders(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:r});return nn.parseResponseData(n)}},Mh=class Eh{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Oh.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new ub(e.backend.url))}static new(e,r){let n=ob(e,r);return new Eh(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new sb;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new ab;return this.signer}async walletAddress(){return this.wallet.address()}},qf=50n,Tu=10000n,cb=25n,Lf=100000000n,rn=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Uf=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},as=class Ph{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(r,n){if(n in r)return Reflect.get(r,n);let i=s=>new Ph(r.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield i(s),s++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}moveArg(){return this.result}},$f=class extends Nt{constructor(t,e){super(3,t,{context:e})}},lb=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="address")throw new $f("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Dh.normalizeSuiAddress)(Au.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new $f("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Au.Buffer.from(r).readBigInt64LE()}},Bt=class extends Nt{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}},Bh={groupId:"string",name:"string"},db=64;function fb(t){return Nh(t),Ru.bcs.ser(Bh,t).toString("base64")}function Iu(t){let e=Ru.bcs.de(Bh,t,"base64");return Nh(e),e}function Nh(t){if(!Gf(t.name))throw new Bt("Invalid metadata: Name contains unknown character");if(!Gf(t.groupId))throw new Bt("Invalid metadata: Group ID contains unknown character");if(t.name.length>db)throw new Bt("Invalid metadata: Name exceed max length 64")}function Gf(t){return/^[\x00-\x7F]+$/.test(t)}function Rh(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}function jn(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}var jh="txn.gas";function hb(){return pf()}var Cu=class Fh{constructor(e,r,n){this.globals=e,this.feeContract=r,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:fb({name:e.name,groupId:hb()}),coinType:(0,Bi.normalizeStructTag)(e.coinType),recipients:e.recipients.map(r=>({address:r.address,cliffAmount:r.cliffAmount,amountPerEpoch:r.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let r=new ku.TransactionBlock,n=this.calculateFeesInternal(e),i=this.getCreateStreamCoinRequests(e,n),o=await this.wallet.requestCoins(i),s=await this.addMergeCoins(r,o[0]),u;i.length>1?u=await this.addMergeCoins(r,o[1]):u=s;for(let l=0;l<e.recipients.length;l++){let d=e.recipients[l],b=this.amountForRecipient(d,e.numberEpoch),_=this.getStreamFeeLocal(b),[T]=r.splitCoins(s,[r.pure(b+_,"u64")]),[x]=r.splitCoins(u,[r.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(r,{paymentCoin:new as(T),flatFeeCoin:new as(x),metadata:e.metadata,recipient:d.address,timeStart:e.startTime,cliff:d.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return r}calculateCreateStreamFees(e){let r=Fh.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(r)}feeParams(){return{createFeePercent:{numerator:qf,denominator:Tu},claimFeePercent:{numerator:cb,denominator:Tu},flatFeePerStream:Lf}}async addMergeCoins(e,r){let n;return r.mergedCoins&&r.mergedCoins.length?(e.mergeCoins(e.object(r.primaryCoin),r.mergedCoins.map(i=>e.object(i))),n=e.object(r.primaryCoin)):r.primaryCoin===jh?n=e.gas:n=e.object(r.primaryCoin),n}getCreateStreamCoinRequests(e,r){let n=e.coinType;return Rh(n,Bi.SUI_TYPE_ARG)?[{coinType:n,amount:r.totalAmount+r.streamFeeAmount+r.flatFeeAmount}]:[{coinType:n,amount:r.totalAmount+r.streamFeeAmount},{coinType:Bi.SUI_TYPE_ARG,amount:r.flatFeeAmount}]}calculateFeesInternal(e){let r=e.recipients.reduce((n,i)=>{let o=this.amountForRecipient(i,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:n.totalAmount+o,streamFeeAmount:n.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...r}}amountForRecipient(e,r){return BigInt(e.amountPerEpoch)*BigInt(r)+BigInt(e.cliffAmount)}get flatSuiFee(){return Lf}getStreamFeeLocal(e){return e*qf/Tu}async getStreamFeeRemote(e){let r=this.feeContract.streamingFee(new ku.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:r});return new lb(n).getU64()}get wallet(){return this.globals.wallet}},pb="0x0000000000000000000000000000000000000000000000000000000000000006",qh=class{constructor(t,e,r){this.moduleName=t,this.config=e,this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Ou.Transactions.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof Uf?n.moveArgs(t):n instanceof rn?n.moveArg(t):n instanceof as?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(Ou.Transactions.MoveCall({target:e,arguments:r.map(i=>i instanceof Uf?i.moveArgs(t):i instanceof rn?i.moveArg(t):i instanceof as?i.moveArg():t.pure(i)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new rn(t):t}vaultObject(){return new rn(this.config.vaultObjId)}roleObject(){return new rn(this.config.roleObjId)}feeObject(){return new rn(this.config.feeObjId)}clockObject(){return new rn(pb)}},Lh=class Er extends qh{constructor(e,r){super(Er.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_fee,arguments:[n,i,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_flat_fee,arguments:[n,i,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_claim_fee,arguments:[n,i,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:Er.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:Er.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},cs=class Tt extends qh{constructor(e,r){super(Tt.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let n=this.feeObject(),i=this.vaultObject(),o=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.create_stream,arguments:[n,i,o,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:Tt.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.cancel_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),i=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream_by_proxy,arguments:[n,i,o,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream_by_proxy}`}},Uh=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lh(e,t),this.streamContract=new cs(e,t)}feeContract;streamContract;async createStreams(t){let e=Cu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new Pi.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}},mb=class extends Nt{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},gb=1e3,wb=class{constructor(t){this.globals=t,this.coinMetaHelper=new yb(t.suiClient),this.createStreamHelper=new Uh(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mb(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(_e.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:_e.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:(0,Ln.normalizeStructTag)(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,i)=>({...n,coinType:(0,Ln.normalizeStructTag)(n.coinType),coinMeta:r[i]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new Bt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Bt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<gb)throw new Bt("Interval shall be at least 1 second","interval",t.interval)}},yb=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ln.normalizeStructTag)(t||Ln.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},bb=class extends Nt{constructor(){super(7,"Connected wallet is not creator")}},Vf=class extends Nt{constructor(){super(8,"Connected wallet is not recipient")}},zf=class extends Nt{constructor(t,e){super(6,t,{context:e})}},Xt=class extends Nt{constructor(t,e={}){super(0,t,e)}},_b=class extends Nt{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},vb=(1n<<64n)-1n,us=1e3;function Wf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return le.fromMillis(r*us)}function Hf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return _e.fromMillis(r*us)}var ju=class Pr{constructor(e,r,n){this.globals=e,this.streamId=r,this.rawData=n,this.streamContract=new cs(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,r){let n=await Pr.fetchStreamData(e,r);return new Pr(e,r,n)}static fromObjectData(e,r,n){let i=Pr.parseRawStreamData(r,n);return new Pr(e,r,i)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await Pr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Xt("Object Id does not align");this.rawData=Pr.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new bb;let e=new Di.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let e=new Di.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let r=new Di.TransactionBlock;return this.streamContract.setAutoClaim(r,{streamId:this.streamId,coinType:this.coinType,enabled:e}),r}async claimByProxy(){let e=new Di.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Ri.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Hf(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Iu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Iu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Wf(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,r=e.epochInterval*e.totalEpoch;return Hf(r)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Wf((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===vb?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=le.now().toMillis(),r=this.timeStart.toMillis();if(e<r)return-1n;let n=Math.floor((e-r)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,r){let n=await e.suiClient.getObject({id:r,options:{showContent:!0,showType:!0}});return Pr.parseRawStreamData(r,n)}static parseRawStreamData(e,r){if(r.error)throw r.error.code==="notExists"?new _b(e):new zf(`get stream data: ${r.error.code}`,{streamId:e,...r.error});let n=r.data.content;if(n.dataType!=="moveObject")throw new zf("Unexpected object type",{gotType:n.dataType});let{typeParams:i}=(0,Ri.parseStructTag)(n.type),o=(0,Ri.normalizeStructTag)(i[0]),s=n.fields,u=s.config.fields,l=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}},Su=class extends Nt{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Tb(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sb=class{constructor(t){this.requester=t,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},$h=class{constructor(t){this.requester=t,this.pager=new Sb(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},xb=25;async function Zf(t,e,r){let n=new Gh(e),i=new Vh(t,n,r);return await Tb(i)}var Gh=class{constructor(t){this.ids=t,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Vh=class extends $h{constructor(t,e,r){super(new kb(t,e,r)),this.suiClient=t,this.idIter=e,this.options=r}},kb=class{constructor(t,e,r){this.suiClient=t,this.stringIter=e,this.options=r,this.filter=r?.filter,this.pageSize=r?.pageSize||xb,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&t.push(n)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:n}=this;r=e.filter(i=>n?.(i))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}},Ab=class ns{constructor(e,r){if(this.globals=e,this.streams=r,r.length===0)throw new Su("stream size 0");let n=r.map(i=>i.groupId);if(new Set(n).size!==1)throw new Bt("Stream does not have same group ID")}type="StreamGroup";static async new(e,r){let n=await Zf(e.suiClient,r);return n.forEach(i=>{if(!i)throw new Xt("stream group object data undefined")}),ns.newFromObjectResponse(e,r,n)}static async newFromObjectResponse(e,r,n){let i=await ns.parseGroupStreams(e,r,n);return new ns(e,i)}static checkStreamGroup(e){let r=e.map(o=>o.groupCommonInfo),n=r[0],i=!0;return r.forEach(o=>{Ib(n,o)||(i=!1)}),i}async refresh(){let e=await Zf(this.globals.suiClient,this.streams.map(r=>r.streamId));this.streams.forEach((r,n)=>{r.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,r)=>e+r.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,r)=>e+r.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,r)=>r.nextReleaseAmount===null?e:e+r.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,r)=>e+r.totalAmount,0n),streamed:this.streams.reduce((e,r)=>e+r.streamedAmount,0n),claimed:this.streams.reduce((e,r)=>e+r.claimedAmount,0n),claimable:this.streams.reduce((e,r)=>e+r.claimable,0n),canceled:this.streams.reduce((e,r)=>e+r.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,r,n){let i=n.map((o,s)=>ju.fromObjectData(e,r[s],o)).filter(o=>!!o);if(new Set(i.map(o=>o.groupId)).size!==1)throw new Su("Not same group ID");if(!this.checkStreamGroup(i))throw new Su("Not same stream settings");return i}};function Ib(t,e){return t.name===e.name&&t.groupId===e.groupId&&t.creator===e.creator&&t.start.toMillis()===e.start.toMillis()&&t.interval.toMillis()===e.interval.toMillis()&&t.steps===e.steps&&t.cancelable===e.cancelable}var Kf=class Mu{constructor(e,r){this.it=e,this.pageSize=r}static async newIncoming(e){let r=await Jf.newIncoming(e);return new Mu(r,e.pageSize)}static async newOutgoing(e){let r=await Jf.newOutgoing(e);return new Mu(r,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Jf=class Eu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let r=await Xf.newIncomingQuery(e);return new Eu(r)}static async newOutgoing(e){let r=await Xf.newOutgoingQuery(e);return new Eu(r)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let r=await this.requester.doNextRequest();if(r===null)throw new Xt("No more results");return r}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Xt("No more results");return e}},Xf=class Pu{constructor(e,r,n,i){this.globals=e,this.recipient=r,this.groupRefs=n,this.query=i,this.current=0;let o=new Gh(n.flat().map(s=>s.streamId));this.objectIter=new Vh(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let r=Pb(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,r)).filter(s=>(0,Rr.normalizeSuiAddress)(s.recipient)===(0,Rr.normalizeSuiAddress)(n)),o=Yf(i);return new Pu(e.globals,n,o,e.query)}static async newOutgoingQuery(e){let r=Db(e.query),n=await e.globals.walletAddress(),i=await e.globals.backend.getOutgoingStreams(n,r),o=Yf(i);return new Pu(e.globals,n,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let r=await Mb(this.globals,e[0].streamId,this.objectIter);return this.current++,zh(r,this.query)?r:this.doNextRequest()}if(e.length>1){let r=await Eb(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Ob(r,this.query)?r:this.doNextRequest()}throw new Xt("Stream group with no stream")}};function Yf(t){let e=new Map;return t.forEach(r=>{let n=e.get(r.groupId);n?(n.push(r),e.set(r.groupId,n)):e.set(r.groupId,[r])}),Array.from(e.values()).sort((r,n)=>le.fromISO(n[0].createDate).toMillis()-le.fromISO(r[0].createDate).toMillis())}function zh(t,e){if(e===void 0)return!0;let r=Cb(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return r&&n}return r}function Cb(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function Ob(t,e){if(!e)return!0;let r=!1;return t.streams.forEach(n=>{zh(n,e)&&(r=!0)}),r}async function Mb(t,e,r){let n=await Wh(r,e);return ju.fromObjectData(t,e,n)}async function Eb(t,e,r){let n=[];for(;n.length<e.length;){let i=await Wh(r,e[n.length]);n.push(i)}return Ab.newFromObjectResponse(t,e,n)}async function Wh(t,e){if(!await t.hasNext())throw new Xt("object iterator has been consumed");let r=await t.next();if(!r||r.error||r.data===void 0||r.data===null)throw new Xt("object iterator undefined response",{cause:r?.error});if(r?.data?.objectId!==e)throw new Xt("stream id not aligned");return r}function Pb(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),sender:Zh(t?.sender)}}function Db(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),recipient:Zh(t?.recipient)}}function Fu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,r)=>{let n=Fu(r);return!e||e===n?n:"all"},void 0):Bb(t)}function Bb(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Bt("Unknown stream filtered status")}}function Hh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeStructTag)(e)):void 0:(0,Rr.normalizeStructTag)(t)}function Zh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeSuiAddress)(e)):void 0:(0,Rr.normalizeSuiAddress)(t)}var Nb=class extends Nt{constructor(t,e,r){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:r}}),this.coinType=t,this.requestAmount=e,this.gotAmount=r}},Rb=25;async function jb(t,e,r,n="0x2::sui::SUI",i=Rb){let o=new Fb(t,e,n,i),s=BigInt(0),u=[];for(;await o.hasNext()&&s<r;){let l=await o.next();l&&(u.push(l),s+=BigInt(l.balance))}if(s<r)throw new Nb(n,r,s);return u}var Fb=class extends $h{constructor(t,e,r,n){super(new qb(t,e,r,n)),this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n}},qb=class{constructor(t,e,r,n){if(this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n,n<=0)throw new Xt("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}},Lb=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ub=class{constructor(t){this.account=t}async address(){return this.account.address}},$b=class{constructor(t,e){this.singleWallet=t,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(Rh(t.coinType,on.SUI_TYPE_ARG))return{primaryCoin:jh};if(t.amount<=0)throw new Bt("Invalid coin request","coinAmount",t.amount);let e=await jb(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new Xt("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Gb=class{globals;helper;constructor(t,e){this.globals=Mh.new(t,e),this.helper=new wb(this.globals)}connectSingleWallet(t){let e=new $b(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Lb(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ju.new(this.globals,t)}async getIncomingStreams(t,e=10){return Kf.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Kf.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(e=>(0,on.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}get wallet(){return this.globals.wallet}builder(){return new Uh(this.globals)}},Vb=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Kh.default)(this.data))}},ji=class extends Vb{application="mpay";getClient(t,e){let r=new Gb(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ub(e)),r}},Qf=class extends ji{constructor(t){super(t),this.data=t}txType=fh.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).cancel()}},eh=class extends ji{constructor(t){super(t),this.data=t}txType=Jh.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claimByProxy()}},th=class extends ji{constructor(t){super(t),this.data=t}txType=Xh.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claim()}},rh=class extends ji{constructor(t){super(t),this.data=t}txType=Yh.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:r}=t;return this.getClient(e,r).createStream(this.data)}},Qh=class is{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return is.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return is.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return BigInt(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Dr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return is.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Dr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Dr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Dr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Dr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Dr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},zb=class{constructor(t,e){this.globals=t,this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&jn(e.target,this.contract.createStreamTarget));if(t.length===0)throw new Xt("No create stream transactions");return t.map(e=>new Qh(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=Iu(e),i=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),b=t.decodeInputBool(11),_=t.typeArg(0);return{name:r,groupId:n,recipient:i,timeStart:o,cliff:s,epochInterval:u,totalEpoch:l,amountPerEpoch:d,cancelable:b,coinType:_}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new Bt("Stream group not have common info");let e=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:e,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new cs(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lh(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}},Wb=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new cs(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(t=>t.kind==="MoveCall"&&jn(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new zb(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let t=this.transactions[0];return new Qh(t,this.txb)}},nh=class extends ji{constructor(t){super(t),this.data=t}txType=ep.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Hb=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,n=Mh.new(e==="sui:mainnet"?"prod":"dev"),i=new Wb(n,r).decode(),o;switch(i.type){case"CreateStream":o=new rh(i.info);break;case"SetAutoClaim":o=new nh({streamId:i.streamId,enabled:i.enabled});break;case"Claim":o=new th({streamId:i.streamId});break;case"ClaimByProxy":o=new eh({streamId:i.streamId});break;case"Cancel":o=new Qf({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,r;switch(t.txSubType){case"CreateStream":r=new rh(e);break;case"Claim":r=new th(e);break;case"ClaimByProxy":r=new eh(e);break;case"SetAutoClaim":r=new nh(e);break;case"Cancel":r=new Qf(e);break;default:throw new Error("not implemented")}return r.build({...t})}},Zb=class rp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,tp.buildCoinTransferTxb)(r,this.data,n.address)}static fromData(e){return new rp(e)}},Kb=class ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,np.buildObjectTransferTxb)(r,this.data,n.address)}static fromData(e){return new ip(e)}},Jb=class ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=sp.TransactionBlock.from(this.data.content);if(!(0,op.isSameAddress)(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ap(e)}},Xb=class{application;constructor(){this.application=qn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case qn.TransactionSubTypes.assets.coin.send:n=Zb.fromData(t.intentionData);break;case qn.TransactionSubTypes.assets.object.send:n=Kb.fromData(t.intentionData);break;case qn.TransactionSubTypes.others.plain:n=Jb.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},Yb={ProtocolPackage:"0x7c9b90b3fda0fa4aa8ee88ae6c4a0b83c773f74936b5354448cb94662e94442d",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},oe=Yb,Qb=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${oe.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${oe.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${oe.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${oe.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${oe.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(oe.pool).find(r=>r.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${oe.ProtocolPackage}::incentive_v2::claim_reward`){let r=new ih(e,this.txb),n=r.decodeInputU8(4),i=r.decodeInputU8(5),o=this.findPoolByAssetId(n),s=[...e.typeArguments];t.push({coinType:o.coinType,option:i,typeArguments:s})}}),console.log("decode claims",t),{txType:Fn.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(oe.ProtocolPackage));return new ih(t,this.txb)}},ih=class os{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return os.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return os.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Br.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return os.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Br.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Br.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Br.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Br.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Br.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function oh(t,e,r,n){return t.moveCall({target:`${oe.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(oe.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(oe.Incentive),t.object(oe.IncentiveV2)],typeArguments:[e.type]}),t}function e_(t,e,r){return t.moveCall({target:`${oe.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(oe.PriceOracle),t.object(oe.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(oe.Incentive),t.object(oe.IncentiveV2)],typeArguments:[e.type]}),t}function t_(t,e,r){return t.moveCall({target:`${oe.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(oe.PriceOracle),t.object(oe.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(oe.IncentiveV2)],typeArguments:[e.type]}),t}function sh(t,e,r,n){return t.moveCall({target:`${oe.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(oe.PriceOracle),t.object(oe.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(oe.IncentiveV2)],typeArguments:[e.type]}),t}function r_(t,e,r,n){let i=Object.values(oe.pool).find(o=>n.includes(o.type));return t.moveCall({target:`${oe.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(oe.IncentiveV2),t.object(i.fondPoolId),t.object(oe.StorageId),t.pure(e.assetId),t.pure(r)],typeArguments:n}),t}var n_=class lp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new cp.TransactionBlock;return e.forEach(n=>{let{coinType:i,option:o,typeArguments:s}=n,u=oe.pool[i];if(console.log("build",this.data),!u)throw new Error(`${i} not support, please use ${Object.keys(oe.pool).join(", ")}.`);if(!u.fondPoolId)throw new Error(`${i} not support claim reward.`);r_(r,u,o,s)}),r}static fromData(e){return new lp(e)}},i_=class fp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new dp.TransactionBlock;console.log("build",this.data);let i=oe.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(oe.pool).join(", ")}.`);return t_(n,i,r)}static fromData(e){return new fp(e)}};async function pp(t,e,r){let n=await t.getCoins({owner:e,coinType:r});return console.log("getTokenObjs",e,n),n}var o_=class mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new hp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return oh(s,oe.pool.sui,b,o)}let u=oe.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(oe.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return oh(s,u,s.object(d),o)}static fromData(e){return new mp(e)}},s_=class wp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new gp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return sh(s,oe.pool.sui,b,o)}let u=oe.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(oe.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return sh(s,u,s.object(d),o)}static fromData(e){return new wp(e)}},a_=class bp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new yp.TransactionBlock;console.log("build",this.data);let i=oe.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(oe.pool).join(", ")}.`);return e_(n,i,r)}static fromData(e){return new bp(e)}},u_=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,r=new Qb(e).decode();return{txType:up.TransactionType.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=o_.fromData(t.intentionData);break;case"EntryBorrow":n=i_.fromData(t.intentionData);break;case"EntryRepay":n=s_.fromData(t.intentionData);break;case"EntryWithdraw":n=a_.fromData(t.intentionData);break;case"ClaimReward":n=n_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},c_=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},l_="msafe-plain-tx",d_=ls.TransactionSubTypes.others.plain,f_=class{application;constructor(){this.application=l_}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ls.TransactionType.Other,txSubType:d_,intentionData:{content:(0,ds.toHEX)(n)}}}async build(t){let{suiClient:e,account:r}=t,n=_p.TransactionBlock.from((0,ds.fromHEX)(t.intentionData.content)),i=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(i.effects.status.status!=="success")throw new Error(i.effects.status.error);return n}},xu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},h_=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){let t=this.helper.decodeInputString(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(8),n=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),o=this.helper.decodeInputU32(6);return{txType:Tp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:n,tickLower:i,tickUpper:o}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(""));return new p_(t,this.txb)}},p_=class ss{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return ss.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return ss.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU32(e){let r=this.decodePureArg(e,"u32");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Nr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return ss.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Nr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Nr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Nr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Nr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Nr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},m_=class Sp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,tickLower:l,tickUpper:d,txb:b}=this.data;return r.pool.addLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,tickLower:l,tickUpper:d,txb:b})}static fromData(e){return new Sp(e)}},g_=class xp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,nft:i,txb:o}=this.data;return r.nft.burn({pool:n,nft:i,txb:o})}static fromData(e){return new xp(e)}},w_=class kp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,collectAmountA:s,collectAmountB:u,txb:l}=this.data;return r.pool.collectFee({pool:n,address:i,collectAmountA:s,collectAmountB:u,nft:o,txb:l})}static fromData(e){return new kp(e)}},y_=class Ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,rewardAmounts:s,txb:u}=this.data;return r.pool.collectReward({pool:n,address:i,rewardAmounts:s,nft:o,txb:u})}static fromData(e){return new Ap(e)}},b_=class Ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{fee:n,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,amountA:_,amountB:T,txb:x}=this.data;return r.pool.createPool({fee:n,amountA:_,amountB:T,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,txb:x})}static fromData(e){return new Ip(e)}},__=class Cp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,txb:b}=this.data;return r.pool.decreaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,decreaseLiquidity:d,txb:b})}static fromData(e){return new Cp(e)}},v_=class Op extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,txb:d}=this.data;return r.pool.increaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,txb:d})}static fromData(e){return new Op(e)}},T_=class Mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x}=this.data;return r.pool.removeLiquidity({pool:n,decreaseLiquidity:d,nft:l,amountA:o,amountB:s,slippage:u,address:i,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x})}static fromData(e){return new Mp(e)}},ah=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=new h_(e).decode();return{txType:vp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r,network:n}=t,i;switch(t.txSubType){case"CreatePool":i=b_.fromData(t.intentionData);break;case"AddLiquidity":i=m_.fromData(t.intentionData);break;case"IncreaseLiquidity":i=v_.fromData(t.intentionData);break;case"DecreaseLiquidity":i=__.fromData(t.intentionData);break;case"RemoveLiquidity":i=T_.fromData(t.intentionData);break;case"CollectFee":i=w_.fromData(t.intentionData);break;case"CollectReward":i=y_.fromData(t.intentionData);break;case"Burn":i=g_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:r,network:n})}},fs=new c_([new Xb,new u_,new ah,new Hb,new f_,new Hy,new ah]);var me=require("@msafe/sui3-utils"),Hu=require("@mysten/sui.js/transactions"),bs=require("@mysten/sui.js/utils");var Ep=require("@mysten/sui.js/transactions"),S_=1000n,x_=120n,k_=100n,A_={multiplier:{numerator:x_,denominator:k_}};var hs=class{constructor(e){this.globals=e}async simulate(e,r=A_){let n=this.copyTransactionBlock(e.txb),{suiClient:i}=this.globals,o=await this.getGasPrice(r);n.setGasPrice(o);let s=await i.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:u}=s.effects,l=this.toGasBudget(u,o),d=s.effects.status.status==="success",b;return d||(b=s.effects.status.error),{success:d,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:u,gasBudget:l,simulationError:b}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let r=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(r,e)}toGasBudget(e,r){let{computationCost:n,storageCost:i}=e,o=S_*r,s=BigInt(n)+o,u=s+BigInt(i);return u>s?u:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,r){if(this.isFixedValue(r))return r.fixedVal;if(this.isMultiplier(r)){let{multiplier:n}=r;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ep.TransactionBlock.from(e.serialize())}};var qu=require("buffer");function ps(t){return qu.Buffer.from(t,"utf-8")}function I_(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ms(t){return Uint8Array.from(qu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ws=require("@mysten/sui.js/verify");var jr=require("@mysten/sui.js/utils");var gs=require("@mysten/sui.js/utils"),Fi=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let r=(0,gs.normalizeStructTag)(e);if(this._coinMetaReg.has(r))return this._coinMetaReg.get(r);let n=await this.queryCoinMeta(r);return n&&this._coinMetaReg.set(r,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Lu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,qi=class t{static isCoin(e){return e?(0,gs.normalizeStructTag)(e).match(Lu)!=null:!1}static getCoinType(e){let[,r]=(0,gs.normalizeStructTag)(e).match(Lu)??[];return r||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:r}=e.content?.fields;if(r!==void 0)return BigInt(r)}};var fr=class{static normalizeSuiAddress(e){return(0,jr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,jr.normalizeStructTag)(e)}static isSuiAddressEqual(e,r){return(0,jr.normalizeSuiAddress)(e)===(0,jr.normalizeSuiAddress)(r)}static isSuiStructEqual(e,r){return(0,jr.normalizeStructTag)(e)===(0,jr.normalizeStructTag)(r)}static isCoinObjectType(e){return qi.isCoin(e)}};function Uu(t,e){return t.startsWith(e)?t:e+t}var $u=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ws.verifyTransactionBlock)(e.message,e.signature):(0,ws.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let r=ps(e.messageStr);return this.getPublicKeyFromSignature({message:r,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let r=await t.getPublicKeyFromSignature(e);return fr.isSuiAddressEqual(r.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let r=ps(e.messageStr);return this.verifySignature({message:r,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Pp=require("@msafe/sui3-utils"),Dp=require("@mysten/sui.js/cryptography"),Bp=require("@mysten/sui.js/multisig");var C_="0x2::sui::SUI";async function Gu(t,e){let r;try{r=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(r.data.length===0||!r.data[0].transaction?.txSignatures)return;let i=r.data[0].transaction?.txSignatures;for(let o=0;o!==i.length;o++){let s=i[o],u=O_(s,e);if(u)return u}}function O_(t,e){let r=(0,Dp.parseSerializedSignature)(t);switch(r.signatureScheme){case"MultiSig":{let n=new Bp.MultiSigPublicKey(r.multisig.multisig_pk).toSuiAddress();if(fr.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(fr.isSuiAddressEqual(r.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Pp.PublicKeySerde.de({publicKeyEncoded:r.publicKey,schema:r.signatureScheme});return fr.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function M_(t){let e=!0,r,n=[];for(;e;){let i=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:r});n.push(...i.data),e=i.hasNextPage,r=i.nextCursor}return n}var Np=25;async function Rp(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Vu=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ys=class{constructor(e){this.requester=e;this.pager=new Vu(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function jp(t,e,r){let n=new zu(t,e,r);return await Rp(n)}var zu=class extends ys{constructor(r,n,i){super(new Wu(r,n,i));this.provider=r;this.owner=n;this.options=i}},Wu=class{constructor(e,r,n){this.provider=e;this.owner=r;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Np,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let r;if(this.filter){let{filter:n}=this;r=e.data.filter(i=>n?.(i))}else r=e.data;return{data:r.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var sn=class t{constructor(e,r){this.globals=e;this.info=r;this.multiSig=new me.MultiSigAccount({threshold:r.threshold,ownersWithWeight:r.owners,creationNonce:r.creationNonce}),this.coinHelper=new Fi(this.suiClient),this.simulator=new hs(e)}multiSig;coinHelper;simulator;static async New(e,r){let n=await e.backend.getMSafeAccountInfo(r);if(new t(e,n).address!==r)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async r=>{let n=await this.coinHelper.getCoinMeta(r.coinType),i=r.lockedBalance.number?BigInt(r.totalBalance)-BigInt(r.lockedBalance.number):BigInt(r.totalBalance);return{type:(0,bs.normalizeStructTag)(r.coinType),balance:BigInt(i),metadata:n}}))}async ownedObjects(e){let r={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return jp(this.suiClient,this.address,r)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let r=e.pending,n=e.reject;return{application:r.application,txType:r.txType,txSubType:r.txSubType,createdAt:r.createdAt,creator:r.creator,digest:r.digest,intention:r.intention,sequenceNumber:r.sequenceNumber,payload:r.payload,votes:r.votes,approvalWeight:this.calculateWeightFromVotes(r.votes),msafeAddress:r.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let r=me.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:r});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let i=await n.build({client:this.globals.suiClient}),o=await n.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,bs.toHEX)(i),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async proposeCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async simulateObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async proposeObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async simulatePlainPayloadIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async proposePlainPayloadIntention(e){let r=await this.nextSequenceNumber(),n=Hu.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,me.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async voteForTransaction(e,r){let n=ms(r),i=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:i.signature})}async proposePendingTransaction(e){let r=new Hu.TransactionBlock,n=await r.build({client:this.suiClient}),i=await r.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:i,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let r=e.payload,n=(0,me.buildRejectTxb)(this.address,r);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let r=await this.pendingTransaction();if(!r||r.rejectDigest!=="")throw new Error("Already rejected");let n=r.payload,i=(0,me.buildRejectTxb)(this.address,n),o=await i.getDigest({client:this.suiClient}),s=await i.build({client:this.suiClient}),u=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:u.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,r=!1){let n=r?e.rejectVotes:e.votes,i=r?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(n.map(l=>[l.userAddress,l.signature]));for(let l=0;l<this.info.owners.length;l++){let d=this.info.owners[l],b=s.get(d.address);b&&o.push(b)}let u=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ms(i),signature:u,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(r=>r.userAddress))}calculateWeight(e){let r=0;for(let n=0;n<e.length;n++){let i=this.info.owners.find(o=>(0,me.isSameAddress)(o.address,e[n]));i&&(r+=i.weight)}return r}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Fp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/utils");var _s=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let r=this.knownPublicKeys.get(e);if(r)return r;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let r=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];r[o]=this.knownPublicKeys.get(s)}let n=r.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(n.length===0)return r;let i=await this.globals.backend.getPublicKeyBatch(n.map(o=>e[o]));for(let o=0;o<n.length;o++){let s=n[o];r[s]=i[o]}for(let o=0;o<r.length;o++)r[o]===void 0&&(r[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)r[o]&&this.knownPublicKeys.set(e[o],r[o]);return r}addPublicKey(e,r){if(!(0,Fp.isSameAddress)(e,r.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,qp.normalizeSuiAddress)(e),r)}async _getPublicKey(e){let r=await this.getPublicKeyFromBackend(e);if(r)return r;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Gu(this.globals.suiClient,e)}};var vs=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Wp=require("@mysten/sui.js/client");var Ui=require("@msafe/sui3-utils"),Li=de(require("axios"),1);var Ts=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let r=await this.post("/auth/login",e);return this._token=r.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let r={userAddressList:e};return(await this.get("/user/public-keys",{params:r,headers:this.headers()})).data?.map(i=>i?Ui.PublicKeySerde.de(i):void 0)}async getMSafeAccountInfo(e){let r={msafeAddress:e},n=await this.get("/msafe",{params:r,headers:this.headers()});return t.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let r={status:e.status??Ui.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:r,headers:this.headers()});return{data:n.data.data.map(t.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let r=e;await this.post("/msafe/status",r,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(r=>({address:r.address,weight:r.weight,publicKey:Ui.PublicKeySerde.de({publicKeyEncoded:r.publicKeyEncoded,schema:r.schema})}))}}async get(e,r){let n=this.getFullUrl(e);try{return await Li.default.get(n,r)}catch(i){throw Ss.fromError(i)??i}}async post(e,r,n){let i=this.getFullUrl(e);try{return await Li.default.post(i,r,{...n,transformRequest:this.getTransformRequest()})}catch(o){throw Ss.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Uu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:r}=Li.default.defaults;return r?r instanceof Array?e=r:e=[r]:e=[],[n=>JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ss=class t extends Error{constructor(r){super();this.e=r;Error.captureStackTrace(this,this.constructor)}name;static fromError(r){if(Li.default.isAxiosError(r)&&r?.response?.data&&"message"in r.response.data)return new t(r)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Lp=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Lp||{}),xs="https://fullnode.testnet.sui.io",Zu="https://fullnode.mainnet.sui.io",Ku="http://127.0.0.1:3000",Ju="http://127.0.0.1:3001",Up="https://sui-dev.m-safe.link",$p="http://13.56.226.148:81",Gp="https://sui-preview.m-safe.link",Vp="https://sui.m-safe.link",zp=new Map([["unit",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["local",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["dev",{suiClient:{url:xs},backend:{url:Up},syncingURL:$p,network:"sui:testnet"}],["prev",{suiClient:{url:Zu},backend:{url:Gp},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Zu},backend:{url:Vp},syncingURL:"",network:"sui:mainnet"}]]);function Xu(t,e){let r=zp.get(t);if(!r)throw new Error("Unknown environment");return e?.suiClient?.url&&(r.suiClient.url=e.suiClient.url),e?.backend?.url&&(r.backend.url=e.backend.url),r}var $i=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,r){let n=Xu(e,r),i=new Wp.SuiClient(n.suiClient),o=new Ts(n.backend.url);return new t({backend:o,suiClient:i,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var ks=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,r){let n=await $i.New(e,r);return new t(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let r=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(r),r}async authSign(e){let r=As.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:r});return this.backend.authSign({address:await e.address(),message:r,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:As.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new sn(this.globals,e)}async getMSafeAccountFromAddress(e){let r=await this.backend.getMSafeAccountInfo(e);return new sn(this.globals,r)}get creationHelper(){return this._creationHelper||(this._creationHelper=new un(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _s(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new cn(this.globals)}get Invitation(){return new zi(this.globals)}get Report(){return new vs(this.globals)}async walletAddress(){return this.wallet.address()}};
2053
+ `);var Ii=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,du=typeof process=="object"&&process?process:{},kf=(t,e,r,n)=>{typeof du.emitWarning=="function"?du.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Ho=globalThis.AbortController,Sf=globalThis.AbortSignal;if(typeof Ho>"u"){Sf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Ho=class{constructor(){e()}signal=new Sf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=du.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yy=t=>!xf.has(t),pT=Symbol("type"),Or=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Af=t=>Or(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Nn:null:null,Nn=class extends Array{constructor(e){super(e),this.fill(0)}},fu=class t{heap;length;static#u=!1;static create(e){let r=Af(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zo=class t{#u;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#i;#r;#e;#c;#f;#a;#o;#g;#s;#T;#S;#w;#b;#k;#l;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#w,sizes:e.#T,keyMap:e.#i,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,o)=>e.#P(r,n,i,o),moveToTail:r=>e.#C(r),indexes:r=>e.#_(r),rindexes:r=>e.#v(r),isStale:r=>e.#h(r)}}get max(){return this.#u}get maxSize(){return this.#d}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:u,allowStale:l,dispose:d,disposeAfter:b,noDisposeOnSet:_,noUpdateTTL:T,maxSize:x=0,maxEntrySize:A=0,sizeCalculation:I,fetchMethod:C,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:D,allowStaleOnFetchAbort:L,ignoreFetchAbort:H}=e;if(r!==0&&!Or(r))throw new TypeError("max option must be a nonnegative integer");let W=r?Af(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#u=r,this.#d=x,this.maxEntrySize=A||this.#d,this.sizeCalculation=I,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(C!==void 0&&typeof C!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=C,this.#k=!!C,this.#i=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new W(r),this.#f=new W(r),this.#a=0,this.#o=0,this.#g=fu.create(r),this.#n=0,this.#m=0,typeof d=="function"&&(this.#y=d),typeof b=="function"?(this.#p=b,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!T,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!D,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#d!==0&&!Or(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Or(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!u,this.ttlResolution=Or(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Or(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#u===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#d){let K="LRU_CACHE_UNBOUNDED";yy(K)&&(xf.add(K),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,t))}}getRemainingTTL(e){return this.#i.has(e)?1/0:0}#D(){let e=new Nn(this.#u),r=new Nn(this.#u);this.#w=e,this.#S=r,this.#B=(o,s,u=Ii.now())=>{if(r[o]=s!==0?u:0,e[o]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#h(o)&&this.delete(this.#r[o])},s+1);l.unref&&l.unref()}},this.#A=o=>{r[o]=e[o]!==0?Ii.now():0},this.#x=(o,s)=>{if(e[s]){let u=e[s],l=r[s];o.ttl=u,o.start=l,o.now=n||i();let d=o.now-l;o.remainingTTL=u-d}};let n=0,i=()=>{let o=Ii.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#i.get(o);if(s===void 0)return 0;let u=e[s],l=r[s];if(u===0||l===0)return 1/0;let d=(n||i())-l;return u-d},this.#h=o=>e[o]!==0&&r[o]!==0&&(n||i())-r[o]>e[o]}#A=()=>{};#x=()=>{};#B=()=>{};#h=()=>!1;#F(){let e=new Nn(this.#u);this.#m=0,this.#T=e,this.#I=r=>{this.#m-=e[r],e[r]=0},this.#N=(r,n,i,o)=>{if(this.#t(n))return 0;if(!Or(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(n,r),!Or(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#d){let o=this.#d-e[r];for(;this.#m>o;)this.#E(!0)}this.#m+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#m)}}#I=e=>{};#M=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#o;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#v({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#o));)r=this.#c[r]}#R(e){return e!==void 0&&this.#i.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#_()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#v()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#_())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#v()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#v({allowStale:!0}))this.#h(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#_({allowStale:!0})){let n=this.#r[r],i=this.#e[r],o=this.#t(i)?i.__staleWhileFetching:i;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#w&&this.#S){s.ttl=this.#w[r];let u=Ii.now()-this.#S[r];s.start=Math.floor(Date.now()-u)}this.#T&&(s.size=this.#T[r]),e.unshift([n,s])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ii.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:l}=n,{noUpdateTTL:d=this.noUpdateTTL}=n,b=this.#N(e,r,n.size||0,u);if(this.maxEntrySize&&b>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let _=this.#n===0?void 0:this.#i.get(e);if(_===void 0)_=this.#n===0?this.#o:this.#g.length!==0?this.#g.pop():this.#n===this.#u?this.#E(!1):this.#n,this.#r[_]=e,this.#e[_]=r,this.#i.set(e,_),this.#c[this.#o]=_,this.#f[_]=this.#o,this.#o=_,this.#n++,this.#M(_,b,l),l&&(l.set="add"),d=!1;else{this.#C(_);let T=this.#e[_];if(r!==T){if(this.#k&&this.#t(T)?T.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(T,e,"set"),this.#l&&this.#s?.push([T,e,"set"])),this.#I(_),this.#M(_,b,l),this.#e[_]=r,l){l.set="replace";let x=T&&this.#t(T)?T.__staleWhileFetching:T;x!==void 0&&(l.oldValue=x)}}else l&&(l.set="update")}if(i!==0&&!this.#w&&this.#D(),this.#w&&(d||this.#B(_,i,o),l&&this.#x(l,_)),!s&&this.#l&&this.#s){let T=this.#s,x;for(;x=T?.shift();)this.#p?.(...x)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}}#E(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#k&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,n,"evict"),this.#l&&this.#s?.push([i,n,"evict"])),this.#I(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#g.push(r)),this.#n===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#c[r],this.#i.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,o=this.#i.get(e);if(o!==void 0){let s=this.#e[o];if(this.#t(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#h(o))i&&(i.has="stale",this.#x(i,o));else return n&&this.#A(o),i&&(i.has="hit",this.#x(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#i.get(e);if(i!==void 0&&(n||!this.#h(i))){let o=this.#e[i];return this.#t(o)?o.__staleWhileFetching:o}}#P(e,r,n,i){let o=r===void 0?void 0:this.#e[r];if(this.#t(o))return o;let s=new Ho,{signal:u}=n;u?.addEventListener("abort",()=>s.abort(u.reason),{signal:s.signal});let l={signal:s.signal,options:n,context:i},d=(I,C=!1)=>{let{aborted:E}=s.signal,P=n.ignoreFetchAbort&&I!==void 0;if(n.status&&(E&&!C?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,P&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),E&&!P&&!C)return _(s.signal.reason);let D=x;return this.#e[r]===x&&(I===void 0?D.__staleWhileFetching?this.#e[r]=D.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,I,l.options))),I},b=I=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=I),_(I)),_=I=>{let{aborted:C}=s.signal,E=C&&n.allowStaleOnFetchAbort,P=E||n.allowStaleOnFetchRejection,D=P||n.noDeleteOnFetchRejection,L=x;if(this.#e[r]===x&&(!D||L.__staleWhileFetching===void 0?this.delete(e):E||(this.#e[r]=L.__staleWhileFetching)),P)return n.status&&L.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw I},T=(I,C)=>{let E=this.#O?.(e,o,l);E&&E instanceof Promise&&E.then(P=>I(P),C),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(I(),n.allowStaleOnFetchAbort&&(I=P=>d(P,!0)))})};n.status&&(n.status.fetchDispatched=!0);let x=new Promise(T).then(d,b),A=Object.assign(x,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,A,{...l.options,status:void 0}),r=this.#i.get(e)):this.#e[r]=A,A}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Ho}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:l=0,sizeCalculation:d=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:T=this.allowStaleOnFetchRejection,ignoreFetchAbort:x=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:I,forceRefresh:C=!1,status:E,signal:P}=r;if(!this.#k)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:E});let D={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:u,size:l,sizeCalculation:d,noUpdateTTL:b,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:A,ignoreFetchAbort:x,status:E,signal:P},L=this.#i.get(e);if(L===void 0){E&&(E.fetch="miss");let H=this.#P(e,L,D,I);return H.__returned=H}else{let H=this.#e[L];if(this.#t(H)){let N=n&&H.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=!0)),N?H.__staleWhileFetching:H.__returned=H}let W=this.#h(L);if(!C&&!W)return E&&(E.fetch="hit"),this.#C(L),i&&this.#A(L),E&&this.#x(E,L),H;let K=this.#P(e,L,D,I),U=K.__staleWhileFetching!==void 0&&n;return E&&(E.fetch=W?"stale":"refresh",U&&W&&(E.returnedStale=!0)),U?K.__staleWhileFetching:K.__returned=K}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=r,u=this.#i.get(e);if(u!==void 0){let l=this.#e[u],d=this.#t(l);return s&&this.#x(s,u),this.#h(u)?(s&&(s.get="stale"),d?(s&&n&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?l.__staleWhileFetching:void 0):(o||this.delete(e),s&&n&&(s.returnedStale=!0),n?l:void 0)):(s&&(s.get="hit"),d?l.__staleWhileFetching:(this.#C(u),i&&this.#A(u),l))}else s&&(s.get="miss")}#j(e,r){this.#f[r]=e,this.#c[e]=r}#C(e){e!==this.#o&&(e===this.#a?this.#a=this.#c[e]:this.#j(this.#f[e],this.#c[e]),this.#j(this.#o,e),this.#o=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#i.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#I(n);let i=this.#e[n];this.#t(i)?i.__abortController.abort(new Error("deleted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,e,"delete"),this.#l&&this.#s?.push([i,e,"delete"])),this.#i.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#o?this.#o=this.#f[n]:n===this.#a?this.#a=this.#c[n]:(this.#c[this.#f[n]]=this.#c[n],this.#f[this.#c[n]]=this.#f[n]),this.#n--,this.#g.push(n)}}if(this.#l&&this.#s?.length){let n=this.#s,i;for(;i=n?.shift();)this.#p?.(...i)}return r}clear(){for(let e of this.#v({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#b&&this.#y?.(r,n,"delete"),this.#l&&this.#s?.push([r,n,"delete"])}}if(this.#i.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#w&&this.#S&&(this.#w.fill(0),this.#S.fill(0)),this.#T&&this.#T.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#m=0,this.#n=0,this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}};var Q=de(we(),1);var Yo=de(If(),1),Qr=require("@mysten/sui.js/utils"),en=require("@mysten/sui.js/transactions");var Ci=de(we(),1),Nf=require("@mysten/sui.js/transactions"),Mt=de(we(),1);var Mr=de(we(),1),Lt=de(we(),1);var Ei=de(we(),1);var Rf=require("@mysten/sui.js/utils"),Qo=require("@mysten/sui.js/transactions"),es=require("@mysten/sui.js/utils");var yu=de(we(),1),by=Object.defineProperty,_y=(t,e,r)=>e in t?by(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e,r)=>(_y(t,typeof e!="symbol"?e+"":e,r),r);var Ko=443636,Jo=-443636,mu="79226673515401279992447579055",gu="4295048016",Ty=14,Sy="59543866431248",xy="184467440737095516",ky="15793534762490258745",Ay=class{generateMnemonic(t=24){return vf(Tf,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let r=this.getDerivePath(e);return Ef.Ed25519Keypair.deriveKeypair(t,r)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:r=!1,addressIndex:n=0}=t;return`m/44'/784'/${e}'/${r?1:0}'/${n}'`}},Mi=class{constructor(t){this.sdk=t,rr(this,"_lru"),rr(this,"_fetching",{})}async getCacheOrSet(t,e,r=0){var n;let i=this._lru||(this._lru=new Zo({max:100}));if(i.has(t))return i.get(t);let s=await((n=this._fetching)[t]||(n[t]=e()));return delete this._fetching[t],i.set(t,s,{ttl:r}),s}get provider(){return this.sdk.provider}get math(){return this.sdk.math}get account(){return this.sdk.account}get network(){return this.sdk.network}get contract(){return this.sdk.contract}get nft(){return this.sdk.nft}get coin(){return this.sdk.coin}get trade(){return this.sdk.trade}get pool(){return this.sdk.pool}};function Iy(t){if("reference"in t)return t.reference;let e=bu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Df(t)}function rs(t){var e,r;return"objectId"in t?t.objectId:(r=(e=Iy(t))==null?void 0:e.objectId)!=null?r:Bf(t)}function nr(t){var e;return"fields"in t?t.fields:(e=Pf(t))==null?void 0:e.fields}function Pf(t){let e="data"in t?bu(t):t;if(!(!e||!Cy(e)||e.content.dataType!=="moveObject"))return e.content}function Cy(t){return t.content!==void 0}function bu(t){return t.data}function Df(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let e=t.error;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Bf(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Oy(t){return t.data!==void 0}function My(t){var e;let r=Oy(t)?t.data:t;return!r?.type&&"data"in t?((e=r?.content)==null?void 0:e.dataType)==="package"?"package":ts(t):r?.type}function ts(t){var e;return(e=Pf(t))==null?void 0:e.type}function Ey(t){var e;return(e=bu(t))==null?void 0:e.owner}var Oi=async(t,e,r)=>{let i=e.length;if(i>50){let o=[],s=0,u=Math.ceil(i/50);for(s;s<u;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:r}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:r})},Py=class extends Mi{async getConfig(){return(await this.fetchJSON())[this.network].contract}getFees(){return this.getCacheOrSet("fees",async()=>{let e=(await this.fetchJSON())[this.network].fee;return(await Oi(this.provider,Object.values(e),{showContent:!0})).map(n=>{let i=nr(n),o=rs(n),s=ts(n);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:i.fee,tickSpacing:i.tick_spacing}})})}fetchJSON(){return this.getCacheOrSet("contract-json",async()=>await(await fetch("https://s3.amazonaws.com/app.turbos.finance/sdk/contract.json?t="+Date.now(),{method:"GET"})).json())}},Cf=new Q.default(2).pow(new Q.default(128)),Dy=class{priceToSqrtPriceX64(t,e,r){return new Q.default(new $(t).mul($.pow(10,r-e)).sqrt().mul($.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,r){return new $(t.toString()).mul($.pow(2,-64)).pow(2).mul($.pow(10,e-r))}priceToTickIndex(t,e,r){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,r))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Q.default(mu))||t.lt(new Q.default(gu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,r=new Q.default(e-64),n=this.signedShiftLeft(r,32,128),i=new Q.default("8000000000000000","hex"),o=0,s=new Q.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new Q.default(0))&&o<Ty;){u=u.mul(u);let x=u.shrn(127);u=u.shrn(63+x.toNumber()),s=s.add(i.mul(x)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new Q.default(Sy)),_=this.signedShiftRight(b.sub(new Q.default(xy)),64,128).toNumber(),T=this.signedShiftRight(b.add(new Q.default(ky)),64,128).toNumber();return _==T?_:this.tickIndexToSqrtPriceX64(T).lte(t)?T:_}tickIndexToSqrtPriceX64(t){return t>0?new Q.default(this.tickIndexToSqrtPricePositive(t)):new Q.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,r){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,r)}toX64_Decimal(t){return t.mul($.pow(2,64))}fromX64_Decimal(t){return t.mul($.pow(2,-64))}scaleDown(t,e){return new $(t).div($.pow(10,e)).toString()}scaleUp(t,e){return new $(t).mul($.pow(10,e)).toString()}bitsToNumber(t,e=32){return Yo.default.toNumber(Yo.default.asIntN(e,Yo.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Cf).sub(e).mod(Cf)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Q.default("79232123823359799118286999567"):e=new Q.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Q.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Q.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Q.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Q.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Q.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Q.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Q.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Q.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Q.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Q.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Q.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Q.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Q.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Q.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Q.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Q.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Q.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Q.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),r;return e&1?r=new Q.default("18445821805675392311"):r=new Q.default("18446744073709551616"),e&2&&(r=this.signedShiftRight(r.mul(new Q.default("18444899583751176498")),64,256)),e&4&&(r=this.signedShiftRight(r.mul(new Q.default("18443055278223354162")),64,256)),e&8&&(r=this.signedShiftRight(r.mul(new Q.default("18439367220385604838")),64,256)),e&16&&(r=this.signedShiftRight(r.mul(new Q.default("18431993317065449817")),64,256)),e&32&&(r=this.signedShiftRight(r.mul(new Q.default("18417254355718160513")),64,256)),e&64&&(r=this.signedShiftRight(r.mul(new Q.default("18387811781193591352")),64,256)),e&128&&(r=this.signedShiftRight(r.mul(new Q.default("18329067761203520168")),64,256)),e&256&&(r=this.signedShiftRight(r.mul(new Q.default("18212142134806087854")),64,256)),e&512&&(r=this.signedShiftRight(r.mul(new Q.default("17980523815641551639")),64,256)),e&1024&&(r=this.signedShiftRight(r.mul(new Q.default("17526086738831147013")),64,256)),e&2048&&(r=this.signedShiftRight(r.mul(new Q.default("16651378430235024244")),64,256)),e&4096&&(r=this.signedShiftRight(r.mul(new Q.default("15030750278693429944")),64,256)),e&8192&&(r=this.signedShiftRight(r.mul(new Q.default("12247334978882834399")),64,256)),e&16384&&(r=this.signedShiftRight(r.mul(new Q.default("8131365268884726200")),64,256)),e&32768&&(r=this.signedShiftRight(r.mul(new Q.default("3584323654723342297")),64,256)),e&65536&&(r=this.signedShiftRight(r.mul(new Q.default("696457651847595233")),64,256)),e&131072&&(r=this.signedShiftRight(r.mul(new Q.default("26294789957452057")),64,256)),e&262144&&(r=this.signedShiftRight(r.mul(new Q.default("37481735321082")),64,256)),r}signedShiftLeft(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}signedShiftRight(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}},wu=(t,e)=>{let r=rs(t);if(Df(t))throw new Error(`${e}(${r}) had been deleted`);if(Bf(t))throw new Error(`${e}(${r}) is not found`);return!0},Rn=60*1e3,By=class extends Mi{async getPools(t=!1){let e=await this.contract.getConfig(),r=[],n;do n=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:n?.nextCursor,limit:15}),r.push(...n.data.map(u=>u.objectId));while(n.hasNextPage);if(!r.length)return[];let o=(await Oi(this.provider,r,{showContent:!0})).map(u=>nr(u).value.fields.pool_id);if(!o.length)return[];let s=await Oi(this.provider,o,{showContent:!0});return t||(s=s.filter(u=>nr(u).unlocked)),s.map(u=>this.parsePool(u))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:r,tickLower:n,tickUpper:i,sqrtPrice:o,slippage:s,coinTypeA:u,coinTypeB:l}=t,d=await this.contract.getConfig(),b=new $(t.amountA),_=new $(t.amountB),[T,x]=await Promise.all([this.coin.selectTradeCoins(r,u,b),this.coin.selectTradeCoins(r,l,_)]),A=t.txb||new en.TransactionBlock,I=T.length>0?this.coin.convertTradeCoins(A,T,u,b):[this.coin.zero(u,A)],C=x.length>0?this.coin.convertTradeCoins(A,x,l,_):[this.coin.zero(l,A)];return A.moveCall({target:`${d.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[u,l,e.type],arguments:[A.object(d.PoolConfig),A.object(e.objectId),A.pure(o,"u128"),A.object(d.Positions),A.makeMoveVec({objects:I}),A.makeMoveVec({objects:C}),A.pure(Math.abs(n).toFixed(0),"u32"),A.pure(n<0,"bool"),A.pure(Math.abs(i).toFixed(0),"u32"),A.pure(i<0,"bool"),A.pure(b.toFixed(0),"u64"),A.pure(_.toFixed(0),"u64"),A.pure(this.getMinimumAmountBySlippage(b,s),"u64"),A.pure(this.getMinimumAmountBySlippage(_,s),"u64"),A.pure(r,"address"),A.pure(Date.now()+Rn,"u64"),A.object(Qr.SUI_CLOCK_OBJECT_ID),A.object(d.Versioned)]}),A}async addLiquidity(t){let{address:e,tickLower:r,tickUpper:n,slippage:i,pool:o}=t,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(o),[l,d]=u,[b,_]=await Promise.all([this.coin.getMetadata(l),this.coin.getMetadata(d)]);if(!b||!_)throw new Error("Invalid coin type");let T=new $(t.amountA),x=new $(t.amountB),[A,I]=await Promise.all([this.coin.selectTradeCoins(e,l,T),this.coin.selectTradeCoins(e,d,x)]),C=t.txb||new en.TransactionBlock,E=A.length>0?this.coin.convertTradeCoins(C,A,l,T):[this.coin.zero(l,C)],P=I.length>0?this.coin.convertTradeCoins(C,I,d,x):[this.coin.zero(d,C)];return C.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:u,arguments:[C.object(o),C.object(s.Positions),C.makeMoveVec({objects:E}),C.makeMoveVec({objects:P}),C.pure(Math.abs(r).toFixed(0),"u32"),C.pure(r<0,"bool"),C.pure(Math.abs(n).toFixed(0),"u32"),C.pure(n<0,"bool"),C.pure(T.toFixed(0),"u64"),C.pure(x.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(T,i),"u64"),C.pure(this.getMinimumAmountBySlippage(x,i),"u64"),C.pure(e,"address"),C.pure(Date.now()+Rn,"u64"),C.object(Qr.SUI_CLOCK_OBJECT_ID),C.object(s.Versioned)]}),C}async increaseLiquidity(t){let{pool:e,slippage:r,address:n,nft:i}=t,o=await this.contract.getConfig(),s=new $(t.amountA),u=new $(t.amountB),l=await this.getPoolTypeArguments(e),[d,b]=l,[_,T]=await Promise.all([this.coin.selectTradeCoins(n,d,s),this.coin.selectTradeCoins(n,b,u)]),x=t.txb||new en.TransactionBlock,A=_.length>0?this.coin.convertTradeCoins(x,_,d,s):[this.coin.zero(d,x)],I=T.length>0?this.coin.convertTradeCoins(x,T,b,u):[this.coin.zero(b,x)];return x.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:l,arguments:[x.object(e),x.object(o.Positions),x.makeMoveVec({objects:A}),x.makeMoveVec({objects:I}),x.object(i),x.pure(s.toFixed(0),"u64"),x.pure(u.toFixed(0),"u64"),x.pure(this.getMinimumAmountBySlippage(s,r),"u64"),x.pure(this.getMinimumAmountBySlippage(u,r),"u64"),x.pure(Date.now()+Rn*3,"u64"),x.object(Qr.SUI_CLOCK_OBJECT_ID),x.object(o.Versioned)]}),x}async decreaseLiquidity(t){let{slippage:e,nft:r,pool:n,decreaseLiquidity:i}=t,o=new $(t.amountA),s=new $(t.amountB),u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(n),d=t.txb||new en.TransactionBlock;return d.moveCall({target:`${u.PackageId}::position_manager::decrease_liquidity`,typeArguments:l,arguments:[d.object(n),d.object(u.Positions),d.object(r),d.pure(new Ci.default(i).toString(),"u128"),d.pure(this.getMinimumAmountBySlippage(o,e),"u64"),d.pure(this.getMinimumAmountBySlippage(s,e),"u64"),d.pure(Date.now()+Rn*3,"u64"),d.object(Qr.SUI_CLOCK_OBJECT_ID),d.object(u.Versioned)]}),d}async removeLiquidity(t){let e=await this.decreaseLiquidity(t);return e=await this.collectFee({txb:e,...t}),e=await this.collectReward({txb:e,...t}),e=await this.nft.burn({txb:e,nft:t.nft,pool:t.pool}),e}async collectFee(t){let{pool:e,nft:r,address:n,collectAmountA:i,collectAmountB:o}=t,s=t.txb||new en.TransactionBlock;if(Number(i)===0&&Number(o)===0)return s;let u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(e);return s.moveCall({target:`${u.PackageId}::position_manager::collect`,typeArguments:l,arguments:[s.object(e),s.object(u.Positions),s.object(r),s.pure(i,"u64"),s.pure(o,"u64"),s.pure(n),s.pure(Date.now()+Rn*3,"u64"),s.object(Qr.SUI_CLOCK_OBJECT_ID),s.object(u.Versioned)]}),s}async collectReward(t){let{pool:e,nft:r,rewardAmounts:n,address:i}=t,o=t.txb||new en.TransactionBlock,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((d,b)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...u,d.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(r),o.object(d.fields.vault),o.pure(b,"u64"),o.pure(n[b],"u64"),o.pure(i),o.pure(Date.now()+Rn*3,"u64"),o.object(Qr.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new $((t.liquidity||new Ci.default(1e8)).toString()),r=new $(t.currentSqrtPrice.toString()),n=new $(t.lowerSqrtPrice.toString()),i=new $(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(n)).div(n.mul(i)),s=new $(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(r)).div(r.mul(i)),s=this.math.fromX64_Decimal(e.mul(r.sub(n)))):(o=new $(0),s=this.math.fromX64_Decimal(e.mul(i.sub(n))));let u=t.ceil!==!1?"ceil":"floor";return[new Ci.default(o[u]().toString()),new Ci.default(s[u]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var r;let n=((r=t.replace(">","").split("<")[1])==null?void 0:r.split(/,\s*/))||[];if(e!==void 0&&e!==n.length)throw new Error("Invalid pool type");return n}async getFixedLiquidity(t){var e,r;let{coinTypeA:n,coinTypeB:i,amountA:o,amountB:s}=t,[u,l]=await Promise.all([this.coin.getMetadata(n),this.coin.getMetadata(i)]),d=new $(this.math.scaleDown(o,u.decimals)).mul((e=t.priceA)!=null?e:1),b=new $(this.math.scaleDown(s,l.decimals)).mul((r=t.priceB)!=null?r:1);return{liquidityA:d.toString(),liquidityB:b.toString(),liquidity:d.plus(b).toString()}}parsePool(t){let e=nr(t),r=rs(t),n=My(t),i=this.parsePoolType(n,3);return this.getCacheOrSet("pool-type-"+r,async()=>i),{...e,objectId:r,type:n,types:i}}getMinimumAmountBySlippage(t,e){let r=new $(t),n=new $(1).minus(new $(e).div(100));if(n.lte(0)||n.gt(1))throw new Error("invalid slippage range");return r.mul(n).toFixed(0)}},Ny=(t,e)=>{let{pool:r,position:n,tickLowerDetail:i,tickUpperDetail:o}=e,s=new Mr.default(r.fee_growth_global_a),u=new Mr.default(n.fee_growth_inside_a),l=new Mr.default(n.tokens_owed_a),d=new Mr.default(r.fee_growth_global_b),b=new Mr.default(n.fee_growth_inside_b),_=new Mr.default(n.tokens_owed_b),T=new Mr.default(n.liquidity),x,A,I,C,E=t.bitsToNumber(r.tick_current_index.fields.bits),P=t.bitsToNumber(n.tick_lower_index.fields.bits),D=t.bitsToNumber(n.tick_upper_index.fields.bits);E<P?(x=t.subUnderflowU128(s,i.feeGrowthOutsideA),A=t.subUnderflowU128(d,i.feeGrowthOutsideB)):(x=i.feeGrowthOutsideA,A=i.feeGrowthOutsideB),E<D?(I=o.feeGrowthOutsideA,C=o.feeGrowthOutsideB):(I=t.subUnderflowU128(s,o.feeGrowthOutsideA),C=t.subUnderflowU128(d,o.feeGrowthOutsideB));let L=t.subUnderflowU128(t.subUnderflowU128(s,x),I),H=t.subUnderflowU128(t.subUnderflowU128(d,A),C),W=t.subUnderflowU128(L,u).mul(T).shrn(64),K=t.subUnderflowU128(H,b).mul(T).shrn(64);return{feeOwedA:l.add(W).toString(),feeOwedB:_.add(K).toString()}},Of=new Ei.default(0),Mf=new Ei.default(1),Ry=new Ei.default(2),jy={mul(t,e,r){let n=t.mul(e);if(this.isOverLimit(n,r))throw new Error(`Mul result higher than u${r}`);return n},mulDiv(t,e,r,n){return this.mulDivRoundUpIf(t,e,r,!1,n)},mulDivRoundUpIf(t,e,r,n,i){if(r.eq(Of))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,i),s=o.div(r);return n&&o.mod(r).gt(Of)?s.add(Mf):s},isOverLimit(t,e){let r=Ry.pow(new Ei.default(e)).sub(Mf);return t.gt(r)}},Fy=(t,e)=>{var r,n,i,o;let{pool:s,position:u,tickLowerDetail:l,tickUpperDetail:d,timeStampInSeconds:b}=e,_=new Lt.default(new $(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),x=(b??new Lt.default(Date.now()).div(new Lt.default(1e3))).sub(new Lt.default(_)),A=[],I=new Lt.default(s.liquidity),C=new Lt.default(u.liquidity);for(let E=0;E<3;++E){let P=s.reward_infos[E],D={emissionsPerSecondX64:new Lt.default(P?P.fields.emissions_per_second:"0"),growthGlobalX64:new Lt.default(P?P.fields.growth_global:"0")},L={growthInsideCheckpoint:new Lt.default((n=(r=u.reward_infos[E])==null?void 0:r.fields.reward_growth_inside)!=null?n:"0"),amountOwed:new Lt.default((o=(i=u.reward_infos[E])==null?void 0:i.fields.amount_owed)!=null?o:"0")},H=D.growthGlobalX64;if(!I.isZero()){let S=jy.mulDiv(x,D.emissionsPerSecondX64,I,128);H=D.growthGlobalX64.add(S)}let W=l.rewardGrowthsOutside[E],K=d.rewardGrowthsOutside[E],F=H;l.initialized&&(F=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_lower_index.fields.bits)?t.subUnderflowU128(H,W):W);let U=new Lt.default(0);d.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_upper_index.fields.bits)?K:t.subUnderflowU128(H,K));let N=t.subUnderflowU128(t.subUnderflowU128(H,F),U),j=L.amountOwed.shln(64);A[E]=j.add(t.subUnderflowU128(N,L.growthInsideCheckpoint).mul(C)).shrn(64).toString()}return A},qy=class extends Mi{async getOwner(t){let e=await this.getObject(t),r=Ey(e);if(!(!r||typeof r=="string")){if("ObjectOwner"in r)return r.ObjectOwner;if("AddressOwner"in r)return r.AddressOwner}}async getFields(t){let e=await this.getObject(t);return nr(e)}async getPositionFields(t){let e=await this.contract.getConfig(),r=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return nr(r)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"position"),nr(e)}async getPositionTick(t,e){let r=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),n=nr(r);if(n)return{tickIndex:this.math.bitsToNumber(n.name.fields.bits),initialized:n.value.fields.initialized,liquidityNet:new Mt.default(this.math.bitsToNumber(n.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Mt.default(n.value.fields.liquidity_gross),feeGrowthOutsideA:new Mt.default(n.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Mt.default(n.value.fields.fee_growth_outside_b),rewardGrowthsOutside:n.value.fields.reward_growths_outside.map(i=>new Mt.default(i))}}async getPositionAPR(t){let{poolId:e,getPrice:r,fees24h:n,tickLower:i,tickUpper:o}=t,s=await this.pool.getPool(e),u=this.math.bitsToNumber(s.tick_current_index.fields.bits),[l,d,b,_]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),r(s.types[0]),r(s.types[1])]);if(!b||!_||i>=o||u<i||u>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:T,minTokenB:x}=this.getRemoveLiquidityQuote(s,i,o),A=new $(this.math.scaleDown(T.toString(),l.decimals)).mul(b),I=new $(this.math.scaleDown(x.toString(),d.decimals)).mul(_),C=A.add(I),E=C.isZero()?new $(0):new $(n).mul(365).div(C).mul(100),P=new $(0);return await Promise.all(s.reward_infos.map(async D=>{let{emissions_per_second:L}=D.fields,H=this.coin.formatCoinType(D.fields.vault_coin_type),[W,K]=await Promise.all([r(H),this.coin.getMetadata(H)]);!L||L==="0"||!W||(P=P.add(new $(new Mt.default(L).shrn(64).toString()).div(10**K.decimals).mul(31536e3).mul(W).div(C).mul(100)))})),{fees:E.toString(),rewards:P.toString(),total:E.plus(P).toString()}}getRemoveLiquidityQuote(t,e,r){let n=new Mt.default(0),i=new Mt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),u=this.math.tickIndexToSqrtPriceX64(r);if(o<e){let d=this.getTokenAFromLiquidity(i,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:n}}if(o<r){let d=new Mt.default(t.sqrt_price),b=this.getTokenAFromLiquidity(i,d,u),_=this.getTokenBFromLiquidity(i,s,d);return{minTokenA:this.adjustForSlippage(b),minTokenB:this.adjustForSlippage(_)}}let l=this.getTokenBFromLiquidity(i,s,u);return{minTokenA:n,minTokenB:this.adjustForSlippage(l)}}adjustForSlippage(t){let e={numerator:new Mt.default(0),denominator:new Mt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,r){let n=t.mul(r.sub(e)).shln(64),i=r.mul(e);return n.div(i)}getTokenBFromLiquidity(t,e,r){return t.mul(r.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:r}=t,n=t.txb||new Nf.TransactionBlock,i=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return n.moveCall({target:`${i.PackageId}::position_manager::burn`,typeArguments:o,arguments:[n.object(i.Positions),n.object(r),n.object(i.Versioned)]}),n}async getPositionLiquidityUSD(t){let{position:e,poolId:r,priceA:n,priceB:i}=t,o=await this.pool.getPool(r),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Mt.default(o.sqrt_price),lowerSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_lower_index.fields.bits)),upperSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_upper_index.fields.bits)),liquidity:new Mt.default(e.liquidity===void 0?1e8:e.liquidity)}),[u,l]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),d=new $(s[0].toString()).div(10**u.decimals).mul(n||0),b=new $(s[1].toString()).div(10**l.decimals).mul(i||0);return d.plus(b).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:r}=t,[n,i,o]=await Promise.all([this.pool.getPool(r),this.nft.getPositionTick(r,e.tick_lower_index),this.nft.getPositionTick(r,e.tick_upper_index)]),s={...t,pool:n,tickLowerDetail:i,tickUpperDetail:o},[u,l]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:d,...b}=u,{unclaimedRewards:_,...T}=l;return{fees:u.unclaimedFees.toString(),rewards:_.toString(),total:d.plus(_).toString(),fields:{...b,...T}}}async getUnclaimedFees(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,[s,u,l,d]=await Promise.all([this.coin.getMetadata(r.types[0]),this.coin.getMetadata(r.types[1]),n(r.types[0]),n(r.types[1])]),b=Ny(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),_=this.math.scaleDown(b.feeOwedA,s.decimals),T=this.math.scaleDown(b.feeOwedB,u.decimals);function x(C,E){return new $(1e6).mul($.pow(10,E)).lt(C)}x(_,s.decimals)&&(_="0",b.feeOwedA="0"),x(T,u.decimals)&&(T="0",b.feeOwedB="0");let A=l===void 0?new $(0):new $(l).mul(_),I=d===void 0?new $(0):new $(d).mul(T);return{unclaimedFees:A.plus(I),scaledFeeOwedA:_,scaledFeeOwedB:T,...b}}async getUnclaimedRewards(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,s=Fy(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),u=[...s],l=r.reward_infos.map(T=>this.coin.formatCoinType(T.fields.vault_coin_type)),d=await Promise.all([...r.reward_infos.map((T,x)=>this.coin.getMetadata(l[x]))]),b=await Promise.all(r.reward_infos.map((T,x)=>n(l[x])));d.forEach((T,x)=>{u[x]=this.math.scaleDown(u[x],T.decimals)});let _=new $(0);return r.reward_infos.some((T,x)=>{let A=b[x];return A?(_=_.plus(new $(A).mul(u[x])),!1):(_=_.plus(1),!0)}),{unclaimedRewards:_,collectRewards:s,scaledCollectRewards:u}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return wu(e,"nft"),e})}},Ly=class extends Mi{isSUI(t){return(0,Rf.normalizeSuiAddress)(t)==="0x000000000000000000000000000000000000000000000000000002::sui::sui"}async getMetadata(t){return this.getCacheOrSet(`coin-metadata-${t}`,async()=>{let e=await this.provider.getCoinMetadata({coinType:t});if(!e)throw new Error(`Coin "${t}" is not found`);return e})}async selectTradeCoins(t,e,r){if(r.eq(0))return[];let n=[],i=[],o=new $(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),n.push(...s.data);while(s.hasNextPage);n.sort((u,l)=>Number(l.balance)-Number(u.balance));for(let u of n)if(i.push(u.coinObjectId),o=o.add(u.balance),o.gte(r))break;return i}convertTradeCoins(t,e,r,n){return this.isSUI(r)?[t.splitCoins(t.gas,[t.pure(n.toNumber())])[0]]:e.map(i=>t.object(i))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let n=t.replace(/^0x/i,"");return n=n.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&n.length<64&&t!=="2::sui:SUI"?"0".repeat(64-n.length):"")+n}},Uy=60*1e3,Xo=100,$y=class extends Mi{async swap(t){let{coinTypeA:e,coinTypeB:r,address:n,amountSpecifiedIsInput:i,slippage:o}=t,s=new $(t.amountA),u=new $(t.amountB),l=await this.contract.getConfig(),d=await Promise.all(t.routes.map(async I=>{let C=await this.pool.getPoolTypeArguments(I.pool),[E,P]=await Promise.all([this.coin.getMetadata(C[0]),this.coin.getMetadata(C[1])]);return{...I,coinA:E,coinB:P,typeArguments:C}})),b=await this.coin.selectTradeCoins(n,e,s),{functionName:_,typeArguments:T}=this.getFunctionNameAndTypeArguments(d.map(({typeArguments:I})=>I),e,r),x=d.map(({nextTickIndex:I,coinA:C,coinB:E,a2b:P})=>{let D=this.math.tickIndexToPrice(I,C.decimals,E.decimals);return this.sqrtPriceWithSlippage(D,o,P,C.decimals,E.decimals)}),A=t.txb||new Qo.TransactionBlock;return A.moveCall({target:`${l.PackageId}::swap_router::${_}`,typeArguments:T,arguments:[...d.map(({pool:I})=>A.object(I)),A.makeMoveVec({objects:this.coin.convertTradeCoins(A,b,e,s)}),A.pure((i?s:u).toFixed(0),"u64"),A.pure(this.amountOutWithSlippage(i?u:s,o,i),"u64"),...x.map(I=>A.pure(I,"u128")),A.pure(i,"bool"),A.pure(n,"address"),A.pure(Date.now()+Uy*3,"u64"),A.object(es.SUI_CLOCK_OBJECT_ID),A.object(l.Versioned)]}),A}async computeSwapResult(t){let{pools:e,amountSpecified:r,amountSpecifiedIsInput:n,address:i,tickStep:o}=t,s=await this.contract.getConfig(),u=e.map(_=>_.pool),l=await Oi(this.provider,u,{showContent:!0}),d=new Qo.TransactionBlock;l.map(async _=>{let T=nr(_),x=e.find(P=>P.pool===T.id.id),A=this.math.bitsToNumber(T.tick_current_index.fields.bits),I=A-T.tick_spacing*(o||Xo),C=A+T.tick_spacing*(o||Xo);I=I<Jo?Jo:I,C=C>Ko?Ko:C;let E=this.pool.parsePoolType(ts(_));d.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:E,arguments:[d.object(T.id.id),d.pure(x.a2b,"bool"),d.pure(new $(r).toFixed(0),"u128"),d.pure(n,"bool"),d.pure(this.math.tickIndexToSqrtPriceX64(x.a2b?I:C).toString(),"u128"),d.object(es.SUI_CLOCK_OBJECT_ID),d.object(s.Versioned)]})});let b=await this.provider.devInspectTransactionBlock({transactionBlock:d,sender:i});if(b.error)throw new Error(b.error);return b.events.map(_=>_.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:r,address:n,tickStep:i}=t,o=await this.contract.getConfig(),s=e.map(b=>b.pool),u=await Oi(this.provider,Array.from(new Set(s)),{showContent:!0}),l=new Qo.TransactionBlock;e.forEach(async b=>{let _=u.find(E=>rs(E)===b.pool),T=nr(_),x=this.math.bitsToNumber(T.tick_current_index.fields.bits),A=x-T.tick_spacing*(i||Xo),I=x+T.tick_spacing*(i||Xo);A=A<Jo?Jo:A,I=I>Ko?Ko:I;let C=this.pool.parsePoolType(ts(_));l.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:C,arguments:[l.object(T.id.id),l.pure(b.a2b,"bool"),l.pure(new $(b.amountSpecified).toFixed(0),"u128"),l.pure(r,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(b.a2b?A:I).toString(),"u128"),l.object(es.SUI_CLOCK_OBJECT_ID),l.object(o.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:n});if(d.error)throw new Error(d.error);return d.events.map(b=>b.parsedJson)}getFunctionNameAndTypeArguments(t,e,r){let n=[],i=["swap"];if(t.length===1)n=t[0],e===n[0]?i.push("a","b"):i.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(i.push("a","b"),n.push(o[0],o[2],o[1])):(i.push("b","a"),n.push(o[1],o[2],o[0])),n.push(s[2],r),r===s[0]?i.push("c","b"):i.push("b","c")}return{functionName:i.join("_"),typeArguments:n}}amountOutWithSlippage(t,e,r){if(r){let i=new $(100).minus(e).div(100);return new $(t).mul(i).toFixed(0)}let n=new $(100).plus(e).div(100);return new $(t).mul(n).toFixed(0)}sqrtPriceWithSlippage(t,e,r,n,i){let o=new $(t).mul(r?new $(100).minus(e).div(100):new $(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,n,i);return s.lt(new yu.BN(gu))?gu:s.gt(new yu.BN(mu))?mu:s.toString()}},It=class{constructor(t,e){this.network=t,rr(this,"pool"),rr(this,"contract"),rr(this,"math",new Dy),rr(this,"account",new Ay),rr(this,"coin"),rr(this,"nft"),rr(this,"trade"),rr(this,"provider"),this.provider=e?e instanceof tn.SuiClient?e:new tn.SuiClient(e):new tn.SuiClient({url:t==="mainnet"?(0,tn.getFullnodeUrl)("mainnet"):(0,tn.getFullnodeUrl)("testnet")}),this.contract=new Py(this),this.pool=new By(this),this.nft=new qy(this),this.coin=new Ly(this),this.trade=new $y(this)}};var Gy=Object.defineProperty,uh=(t,e)=>{for(var r in e)Gy(t,r,{get:e[r],enumerable:!0})},St=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,lh.default)(this.data))}},Vy={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},_u=new nd(Vy),zy=async(t,e,r,n,i)=>{console.log("getSwapRouterTxb account2: ",n),console.log("getSwapRouterTxb suiClient: ",i),_u.senderAddress=r;let o=await _u.getOwnerCoinAssets(r);return await Pe.buildAggregatorSwapTransaction(_u,t,o,"",e)},Wy=class dh extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r,suiClient:n}=e,{payloadParams:i}=this.data,o=await zy(i?.createTxParams,i?.slippage,i?.account,r,n);return console.log("Swap intention build txb: ",o),o}static fromData(e){return new dh(e)}},Hy=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{payloadParams:e,action:r}=t;return{txType:ch.TransactionType.Other,txSubType:`Cetus${r}`,intentionData:{payloadParams:e,action:r}}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"CetusSwap":n=Wy.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},hh={};uh(hh,{contractId:()=>gh,default:()=>Zy,feeObjId:()=>bh,roleObjId:()=>wh,status:()=>mh,transaction:()=>ph,upgradeCapObjId:()=>_h,vaultObjId:()=>yh});var ph="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",mh="success",gh="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",wh="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yh="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",bh="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_h="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zy={transaction:ph,status:mh,contractId:gh,roleObjId:wh,vaultObjId:yh,feeObjId:bh,upgradeCapObjId:_h},vh={};uh(vh,{contractId:()=>xh,default:()=>Ky,feeObjId:()=>Ih,roleObjId:()=>kh,status:()=>Sh,transaction:()=>Th,upgradeCapObjId:()=>Ch,vaultObjId:()=>Ah});var Th="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sh="success",xh="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",kh="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ah="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Ih="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ch="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ky={transaction:Th,status:Sh,contractId:xh,roleObjId:kh,vaultObjId:Ah,feeObjId:Ih,upgradeCapObjId:Ch},Jy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Xy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Yy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",eb="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tb="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",rb="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",nb="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",jf=hh,Ff=vh,ib=new Map([["dev",{env:"dev",rpc:{url:Jy},backend:{url:eb},contract:jf}],["stg",{env:"stg",rpc:{url:Xy},backend:{url:tb},contract:jf}],["prev",{env:"prev",rpc:{url:Yy},backend:{url:rb},contract:Ff}],["prod",{env:"prod",rpc:{url:Qy},backend:{url:nb},contract:Ff}]]);function ob(t,e){let r=ib.get(t);if(!r)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(r.rpc=e.rpc),e&&e.backend&&(r.backend=e.backend),e&&e.contract&&(r.contract=e.contract),r}var Nt=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:i}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=i}},sb=class extends Nt{constructor(){super(11,"Backend is not specified")}},ab=class extends Nt{constructor(){super(1,"Wallet not connected")}},vu=class extends Nt{constructor(t,e){super(10,t,{context:e})}},ub=class nn{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof dr.AxiosError)throw new vu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new vu(e.data.code)}throw new vu(e.status.toString())}async getIncomingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{recipient:e,...r});return nn.parseResponseData(n)}async getOutgoingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{sender:e,...r});return nn.parseResponseData(n)}async getStreamHistory(e){let r=await dr.default.post(`${this.apiURL}/stream-events`,e),n=nn.parseResponseData(r);return n.data.forEach(i=>{let o=i;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),n}async getAllCoinTypes(e){let r=await dr.default.post(`${this.apiURL}/stream-info`,{address:e});return nn.parseResponseData(r)}async getAllRecipients(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:r});return nn.parseResponseData(n)}async getAllSenders(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:r});return nn.parseResponseData(n)}},Mh=class Eh{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Oh.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new ub(e.backend.url))}static new(e,r){let n=ob(e,r);return new Eh(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new sb;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new ab;return this.signer}async walletAddress(){return this.wallet.address()}},qf=50n,Tu=10000n,cb=25n,Lf=100000000n,rn=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Uf=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},as=class Ph{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(r,n){if(n in r)return Reflect.get(r,n);let i=s=>new Ph(r.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield i(s),s++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}moveArg(){return this.result}},$f=class extends Nt{constructor(t,e){super(3,t,{context:e})}},lb=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="address")throw new $f("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Dh.normalizeSuiAddress)(Au.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new $f("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Au.Buffer.from(r).readBigInt64LE()}},Bt=class extends Nt{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}},Bh={groupId:"string",name:"string"},db=64;function fb(t){return Nh(t),Ru.bcs.ser(Bh,t).toString("base64")}function Iu(t){let e=Ru.bcs.de(Bh,t,"base64");return Nh(e),e}function Nh(t){if(!Gf(t.name))throw new Bt("Invalid metadata: Name contains unknown character");if(!Gf(t.groupId))throw new Bt("Invalid metadata: Group ID contains unknown character");if(t.name.length>db)throw new Bt("Invalid metadata: Name exceed max length 64")}function Gf(t){return/^[\x00-\x7F]+$/.test(t)}function Rh(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}function jn(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}var jh="txn.gas";function hb(){return pf()}var Cu=class Fh{constructor(e,r,n){this.globals=e,this.feeContract=r,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:fb({name:e.name,groupId:hb()}),coinType:(0,Bi.normalizeStructTag)(e.coinType),recipients:e.recipients.map(r=>({address:r.address,cliffAmount:r.cliffAmount,amountPerEpoch:r.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let r=new ku.TransactionBlock,n=this.calculateFeesInternal(e),i=this.getCreateStreamCoinRequests(e,n),o=await this.wallet.requestCoins(i),s=await this.addMergeCoins(r,o[0]),u;i.length>1?u=await this.addMergeCoins(r,o[1]):u=s;for(let l=0;l<e.recipients.length;l++){let d=e.recipients[l],b=this.amountForRecipient(d,e.numberEpoch),_=this.getStreamFeeLocal(b),[T]=r.splitCoins(s,[r.pure(b+_,"u64")]),[x]=r.splitCoins(u,[r.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(r,{paymentCoin:new as(T),flatFeeCoin:new as(x),metadata:e.metadata,recipient:d.address,timeStart:e.startTime,cliff:d.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return r}calculateCreateStreamFees(e){let r=Fh.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(r)}feeParams(){return{createFeePercent:{numerator:qf,denominator:Tu},claimFeePercent:{numerator:cb,denominator:Tu},flatFeePerStream:Lf}}async addMergeCoins(e,r){let n;return r.mergedCoins&&r.mergedCoins.length?(e.mergeCoins(e.object(r.primaryCoin),r.mergedCoins.map(i=>e.object(i))),n=e.object(r.primaryCoin)):r.primaryCoin===jh?n=e.gas:n=e.object(r.primaryCoin),n}getCreateStreamCoinRequests(e,r){let n=e.coinType;return Rh(n,Bi.SUI_TYPE_ARG)?[{coinType:n,amount:r.totalAmount+r.streamFeeAmount+r.flatFeeAmount}]:[{coinType:n,amount:r.totalAmount+r.streamFeeAmount},{coinType:Bi.SUI_TYPE_ARG,amount:r.flatFeeAmount}]}calculateFeesInternal(e){let r=e.recipients.reduce((n,i)=>{let o=this.amountForRecipient(i,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:n.totalAmount+o,streamFeeAmount:n.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...r}}amountForRecipient(e,r){return BigInt(e.amountPerEpoch)*BigInt(r)+BigInt(e.cliffAmount)}get flatSuiFee(){return Lf}getStreamFeeLocal(e){return e*qf/Tu}async getStreamFeeRemote(e){let r=this.feeContract.streamingFee(new ku.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:r});return new lb(n).getU64()}get wallet(){return this.globals.wallet}},pb="0x0000000000000000000000000000000000000000000000000000000000000006",qh=class{constructor(t,e,r){this.moduleName=t,this.config=e,this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Ou.Transactions.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof Uf?n.moveArgs(t):n instanceof rn?n.moveArg(t):n instanceof as?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(Ou.Transactions.MoveCall({target:e,arguments:r.map(i=>i instanceof Uf?i.moveArgs(t):i instanceof rn?i.moveArg(t):i instanceof as?i.moveArg():t.pure(i)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new rn(t):t}vaultObject(){return new rn(this.config.vaultObjId)}roleObject(){return new rn(this.config.roleObjId)}feeObject(){return new rn(this.config.feeObjId)}clockObject(){return new rn(pb)}},Lh=class Er extends qh{constructor(e,r){super(Er.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_fee,arguments:[n,i,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_flat_fee,arguments:[n,i,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_claim_fee,arguments:[n,i,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:Er.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:Er.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},cs=class Tt extends qh{constructor(e,r){super(Tt.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let n=this.feeObject(),i=this.vaultObject(),o=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.create_stream,arguments:[n,i,o,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:Tt.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.cancel_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),i=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream_by_proxy,arguments:[n,i,o,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream_by_proxy}`}},Uh=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lh(e,t),this.streamContract=new cs(e,t)}feeContract;streamContract;async createStreams(t){let e=Cu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new Pi.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}},mb=class extends Nt{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},gb=1e3,wb=class{constructor(t){this.globals=t,this.coinMetaHelper=new yb(t.suiClient),this.createStreamHelper=new Uh(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mb(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(_e.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:_e.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:(0,Ln.normalizeStructTag)(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,i)=>({...n,coinType:(0,Ln.normalizeStructTag)(n.coinType),coinMeta:r[i]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new Bt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Bt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<gb)throw new Bt("Interval shall be at least 1 second","interval",t.interval)}},yb=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ln.normalizeStructTag)(t||Ln.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},bb=class extends Nt{constructor(){super(7,"Connected wallet is not creator")}},Vf=class extends Nt{constructor(){super(8,"Connected wallet is not recipient")}},zf=class extends Nt{constructor(t,e){super(6,t,{context:e})}},Xt=class extends Nt{constructor(t,e={}){super(0,t,e)}},_b=class extends Nt{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},vb=(1n<<64n)-1n,us=1e3;function Wf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return le.fromMillis(r*us)}function Hf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return _e.fromMillis(r*us)}var ju=class Pr{constructor(e,r,n){this.globals=e,this.streamId=r,this.rawData=n,this.streamContract=new cs(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,r){let n=await Pr.fetchStreamData(e,r);return new Pr(e,r,n)}static fromObjectData(e,r,n){let i=Pr.parseRawStreamData(r,n);return new Pr(e,r,i)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await Pr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Xt("Object Id does not align");this.rawData=Pr.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new bb;let e=new Di.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let e=new Di.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let r=new Di.TransactionBlock;return this.streamContract.setAutoClaim(r,{streamId:this.streamId,coinType:this.coinType,enabled:e}),r}async claimByProxy(){let e=new Di.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Ri.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Hf(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Iu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Iu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Wf(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,r=e.epochInterval*e.totalEpoch;return Hf(r)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Wf((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===vb?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=le.now().toMillis(),r=this.timeStart.toMillis();if(e<r)return-1n;let n=Math.floor((e-r)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,r){let n=await e.suiClient.getObject({id:r,options:{showContent:!0,showType:!0}});return Pr.parseRawStreamData(r,n)}static parseRawStreamData(e,r){if(r.error)throw r.error.code==="notExists"?new _b(e):new zf(`get stream data: ${r.error.code}`,{streamId:e,...r.error});let n=r.data.content;if(n.dataType!=="moveObject")throw new zf("Unexpected object type",{gotType:n.dataType});let{typeParams:i}=(0,Ri.parseStructTag)(n.type),o=(0,Ri.normalizeStructTag)(i[0]),s=n.fields,u=s.config.fields,l=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}},Su=class extends Nt{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Tb(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sb=class{constructor(t){this.requester=t,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},$h=class{constructor(t){this.requester=t,this.pager=new Sb(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},xb=25;async function Zf(t,e,r){let n=new Gh(e),i=new Vh(t,n,r);return await Tb(i)}var Gh=class{constructor(t){this.ids=t,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Vh=class extends $h{constructor(t,e,r){super(new kb(t,e,r)),this.suiClient=t,this.idIter=e,this.options=r}},kb=class{constructor(t,e,r){this.suiClient=t,this.stringIter=e,this.options=r,this.filter=r?.filter,this.pageSize=r?.pageSize||xb,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&t.push(n)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:n}=this;r=e.filter(i=>n?.(i))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}},Ab=class ns{constructor(e,r){if(this.globals=e,this.streams=r,r.length===0)throw new Su("stream size 0");let n=r.map(i=>i.groupId);if(new Set(n).size!==1)throw new Bt("Stream does not have same group ID")}type="StreamGroup";static async new(e,r){let n=await Zf(e.suiClient,r);return n.forEach(i=>{if(!i)throw new Xt("stream group object data undefined")}),ns.newFromObjectResponse(e,r,n)}static async newFromObjectResponse(e,r,n){let i=await ns.parseGroupStreams(e,r,n);return new ns(e,i)}static checkStreamGroup(e){let r=e.map(o=>o.groupCommonInfo),n=r[0],i=!0;return r.forEach(o=>{Ib(n,o)||(i=!1)}),i}async refresh(){let e=await Zf(this.globals.suiClient,this.streams.map(r=>r.streamId));this.streams.forEach((r,n)=>{r.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,r)=>e+r.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,r)=>e+r.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,r)=>r.nextReleaseAmount===null?e:e+r.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,r)=>e+r.totalAmount,0n),streamed:this.streams.reduce((e,r)=>e+r.streamedAmount,0n),claimed:this.streams.reduce((e,r)=>e+r.claimedAmount,0n),claimable:this.streams.reduce((e,r)=>e+r.claimable,0n),canceled:this.streams.reduce((e,r)=>e+r.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,r,n){let i=n.map((o,s)=>ju.fromObjectData(e,r[s],o)).filter(o=>!!o);if(new Set(i.map(o=>o.groupId)).size!==1)throw new Su("Not same group ID");if(!this.checkStreamGroup(i))throw new Su("Not same stream settings");return i}};function Ib(t,e){return t.name===e.name&&t.groupId===e.groupId&&t.creator===e.creator&&t.start.toMillis()===e.start.toMillis()&&t.interval.toMillis()===e.interval.toMillis()&&t.steps===e.steps&&t.cancelable===e.cancelable}var Kf=class Mu{constructor(e,r){this.it=e,this.pageSize=r}static async newIncoming(e){let r=await Jf.newIncoming(e);return new Mu(r,e.pageSize)}static async newOutgoing(e){let r=await Jf.newOutgoing(e);return new Mu(r,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Jf=class Eu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let r=await Xf.newIncomingQuery(e);return new Eu(r)}static async newOutgoing(e){let r=await Xf.newOutgoingQuery(e);return new Eu(r)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let r=await this.requester.doNextRequest();if(r===null)throw new Xt("No more results");return r}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Xt("No more results");return e}},Xf=class Pu{constructor(e,r,n,i){this.globals=e,this.recipient=r,this.groupRefs=n,this.query=i,this.current=0;let o=new Gh(n.flat().map(s=>s.streamId));this.objectIter=new Vh(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let r=Pb(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,r)).filter(s=>(0,Rr.normalizeSuiAddress)(s.recipient)===(0,Rr.normalizeSuiAddress)(n)),o=Yf(i);return new Pu(e.globals,n,o,e.query)}static async newOutgoingQuery(e){let r=Db(e.query),n=await e.globals.walletAddress(),i=await e.globals.backend.getOutgoingStreams(n,r),o=Yf(i);return new Pu(e.globals,n,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let r=await Mb(this.globals,e[0].streamId,this.objectIter);return this.current++,zh(r,this.query)?r:this.doNextRequest()}if(e.length>1){let r=await Eb(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Ob(r,this.query)?r:this.doNextRequest()}throw new Xt("Stream group with no stream")}};function Yf(t){let e=new Map;return t.forEach(r=>{let n=e.get(r.groupId);n?(n.push(r),e.set(r.groupId,n)):e.set(r.groupId,[r])}),Array.from(e.values()).sort((r,n)=>le.fromISO(n[0].createDate).toMillis()-le.fromISO(r[0].createDate).toMillis())}function zh(t,e){if(e===void 0)return!0;let r=Cb(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return r&&n}return r}function Cb(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function Ob(t,e){if(!e)return!0;let r=!1;return t.streams.forEach(n=>{zh(n,e)&&(r=!0)}),r}async function Mb(t,e,r){let n=await Wh(r,e);return ju.fromObjectData(t,e,n)}async function Eb(t,e,r){let n=[];for(;n.length<e.length;){let i=await Wh(r,e[n.length]);n.push(i)}return Ab.newFromObjectResponse(t,e,n)}async function Wh(t,e){if(!await t.hasNext())throw new Xt("object iterator has been consumed");let r=await t.next();if(!r||r.error||r.data===void 0||r.data===null)throw new Xt("object iterator undefined response",{cause:r?.error});if(r?.data?.objectId!==e)throw new Xt("stream id not aligned");return r}function Pb(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),sender:Zh(t?.sender)}}function Db(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),recipient:Zh(t?.recipient)}}function Fu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,r)=>{let n=Fu(r);return!e||e===n?n:"all"},void 0):Bb(t)}function Bb(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Bt("Unknown stream filtered status")}}function Hh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeStructTag)(e)):void 0:(0,Rr.normalizeStructTag)(t)}function Zh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeSuiAddress)(e)):void 0:(0,Rr.normalizeSuiAddress)(t)}var Nb=class extends Nt{constructor(t,e,r){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:r}}),this.coinType=t,this.requestAmount=e,this.gotAmount=r}},Rb=25;async function jb(t,e,r,n="0x2::sui::SUI",i=Rb){let o=new Fb(t,e,n,i),s=BigInt(0),u=[];for(;await o.hasNext()&&s<r;){let l=await o.next();l&&(u.push(l),s+=BigInt(l.balance))}if(s<r)throw new Nb(n,r,s);return u}var Fb=class extends $h{constructor(t,e,r,n){super(new qb(t,e,r,n)),this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n}},qb=class{constructor(t,e,r,n){if(this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n,n<=0)throw new Xt("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}},Lb=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ub=class{constructor(t){this.account=t}async address(){return this.account.address}},$b=class{constructor(t,e){this.singleWallet=t,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(Rh(t.coinType,on.SUI_TYPE_ARG))return{primaryCoin:jh};if(t.amount<=0)throw new Bt("Invalid coin request","coinAmount",t.amount);let e=await jb(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new Xt("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Gb=class{globals;helper;constructor(t,e){this.globals=Mh.new(t,e),this.helper=new wb(this.globals)}connectSingleWallet(t){let e=new $b(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Lb(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ju.new(this.globals,t)}async getIncomingStreams(t,e=10){return Kf.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Kf.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(e=>(0,on.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}get wallet(){return this.globals.wallet}builder(){return new Uh(this.globals)}},Vb=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Kh.default)(this.data))}},ji=class extends Vb{application="mpay";getClient(t,e){let r=new Gb(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ub(e)),r}},Qf=class extends ji{constructor(t){super(t),this.data=t}txType=fh.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).cancel()}},eh=class extends ji{constructor(t){super(t),this.data=t}txType=Jh.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claimByProxy()}},th=class extends ji{constructor(t){super(t),this.data=t}txType=Xh.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claim()}},rh=class extends ji{constructor(t){super(t),this.data=t}txType=Yh.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:r}=t;return this.getClient(e,r).createStream(this.data)}},Qh=class is{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return is.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return is.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return BigInt(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Dr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return is.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Dr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Dr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Dr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Dr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Dr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},zb=class{constructor(t,e){this.globals=t,this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&jn(e.target,this.contract.createStreamTarget));if(t.length===0)throw new Xt("No create stream transactions");return t.map(e=>new Qh(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=Iu(e),i=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),b=t.decodeInputBool(11),_=t.typeArg(0);return{name:r,groupId:n,recipient:i,timeStart:o,cliff:s,epochInterval:u,totalEpoch:l,amountPerEpoch:d,cancelable:b,coinType:_}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new Bt("Stream group not have common info");let e=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:e,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new cs(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lh(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}},Wb=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new cs(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(t=>t.kind==="MoveCall"&&jn(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new zb(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let t=this.transactions[0];return new Qh(t,this.txb)}},nh=class extends ji{constructor(t){super(t),this.data=t}txType=ep.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Hb=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,n=Mh.new(e==="sui:mainnet"?"prod":"dev"),i=new Wb(n,r).decode(),o;switch(i.type){case"CreateStream":o=new rh(i.info);break;case"SetAutoClaim":o=new nh({streamId:i.streamId,enabled:i.enabled});break;case"Claim":o=new th({streamId:i.streamId});break;case"ClaimByProxy":o=new eh({streamId:i.streamId});break;case"Cancel":o=new Qf({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,r;switch(t.txSubType){case"CreateStream":r=new rh(e);break;case"Claim":r=new th(e);break;case"ClaimByProxy":r=new eh(e);break;case"SetAutoClaim":r=new nh(e);break;case"Cancel":r=new Qf(e);break;default:throw new Error("not implemented")}return r.build({...t})}},Zb=class rp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,tp.buildCoinTransferTxb)(r,this.data,n.address)}static fromData(e){return new rp(e)}},Kb=class ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,np.buildObjectTransferTxb)(r,this.data,n.address)}static fromData(e){return new ip(e)}},Jb=class ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=sp.TransactionBlock.from(this.data.content);if(!(0,op.isSameAddress)(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ap(e)}},Xb=class{application;constructor(){this.application=qn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case qn.TransactionSubTypes.assets.coin.send:n=Zb.fromData(t.intentionData);break;case qn.TransactionSubTypes.assets.object.send:n=Kb.fromData(t.intentionData);break;case qn.TransactionSubTypes.others.plain:n=Jb.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},Yb={ProtocolPackage:"0x7c9b90b3fda0fa4aa8ee88ae6c4a0b83c773f74936b5354448cb94662e94442d",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},ce=Yb,Qb=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ce.pool).find(r=>r.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${ce.ProtocolPackage}::incentive_v2::claim_reward`){let r=new ih(e,this.txb),n=r.decodeInputU8(4),i=r.decodeInputU8(5),o=r.decodeSharedObjectId(2),s=this.findPoolByAssetId(n),u=[...e.typeArguments];t.push({coinType:s.coinType,option:i,typeArguments:u,assetId:n,poolId:o})}}),console.log("decode claims",t),{txType:Fn.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ce.ProtocolPackage));return new ih(t,this.txb)}},ih=class os{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return os.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return os.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Br.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return os.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Br.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Br.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Br.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Br.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Br.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function oh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function e_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function t_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function sh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function r_(t,e,r,n,i){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ce.IncentiveV2),t.object(r),t.object(ce.StorageId),t.pure(e),t.pure(n)],typeArguments:i}),t}var n_=class lp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new cp.TransactionBlock;return e.forEach(n=>{let{assetId:i,poolId:o,option:s,typeArguments:u}=n;r_(r,i,o,s,u)}),r}static fromData(e){return new lp(e)}},i_=class fp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new dp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return t_(n,i,r)}static fromData(e){return new fp(e)}};async function pp(t,e,r){let n=await t.getCoins({owner:e,coinType:r});return console.log("getTokenObjs",e,n),n}var o_=class mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new hp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return oh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return oh(s,u,s.object(d),o)}static fromData(e){return new mp(e)}},s_=class wp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new gp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return sh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return sh(s,u,s.object(d),o)}static fromData(e){return new wp(e)}},a_=class bp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new yp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return e_(n,i,r)}static fromData(e){return new bp(e)}},u_=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,r=new Qb(e).decode();return{txType:up.TransactionType.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=o_.fromData(t.intentionData);break;case"EntryBorrow":n=i_.fromData(t.intentionData);break;case"EntryRepay":n=s_.fromData(t.intentionData);break;case"EntryWithdraw":n=a_.fromData(t.intentionData);break;case"ClaimReward":n=n_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},c_=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},l_="msafe-plain-tx",d_=ls.TransactionSubTypes.others.plain,f_=class{application;constructor(){this.application=l_}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ls.TransactionType.Other,txSubType:d_,intentionData:{content:(0,ds.toHEX)(n)}}}async build(t){let{suiClient:e,account:r}=t,n=_p.TransactionBlock.from((0,ds.fromHEX)(t.intentionData.content)),i=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(i.effects.status.status!=="success")throw new Error(i.effects.status.error);return n}},xu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},h_=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){let t=this.helper.decodeInputString(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(8),n=this.helper.decodeInputU64(9),i=this.helper.decodeInputU32(4),o=this.helper.decodeInputU32(6);return{txType:Tp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:n,tickLower:i,tickUpper:o}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(""));return new p_(t,this.txb)}},p_=class ss{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return ss.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return ss.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU32(e){let r=this.decodePureArg(e,"u32");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Nr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return ss.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Nr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Nr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Nr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Nr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Nr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},m_=class Sp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,tickLower:l,tickUpper:d,txb:b}=this.data;return r.pool.addLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,tickLower:l,tickUpper:d,txb:b})}static fromData(e){return new Sp(e)}},g_=class xp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,nft:i,txb:o}=this.data;return r.nft.burn({pool:n,nft:i,txb:o})}static fromData(e){return new xp(e)}},w_=class kp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,collectAmountA:s,collectAmountB:u,txb:l}=this.data;return r.pool.collectFee({pool:n,address:i,collectAmountA:s,collectAmountB:u,nft:o,txb:l})}static fromData(e){return new kp(e)}},y_=class Ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,rewardAmounts:s,txb:u}=this.data;return r.pool.collectReward({pool:n,address:i,rewardAmounts:s,nft:o,txb:u})}static fromData(e){return new Ap(e)}},b_=class Ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{fee:n,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,amountA:_,amountB:T,txb:x}=this.data;return r.pool.createPool({fee:n,amountA:_,amountB:T,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,txb:x})}static fromData(e){return new Ip(e)}},__=class Cp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,txb:b}=this.data;return r.pool.decreaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,decreaseLiquidity:d,txb:b})}static fromData(e){return new Cp(e)}},v_=class Op extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,txb:d}=this.data;return r.pool.increaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,txb:d})}static fromData(e){return new Op(e)}},T_=class Mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x}=this.data;return r.pool.removeLiquidity({pool:n,decreaseLiquidity:d,nft:l,amountA:o,amountB:s,slippage:u,address:i,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x})}static fromData(e){return new Mp(e)}},ah=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=new h_(e).decode();return{txType:vp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r,network:n}=t,i;switch(t.txSubType){case"CreatePool":i=b_.fromData(t.intentionData);break;case"AddLiquidity":i=m_.fromData(t.intentionData);break;case"IncreaseLiquidity":i=v_.fromData(t.intentionData);break;case"DecreaseLiquidity":i=__.fromData(t.intentionData);break;case"RemoveLiquidity":i=T_.fromData(t.intentionData);break;case"CollectFee":i=w_.fromData(t.intentionData);break;case"CollectReward":i=y_.fromData(t.intentionData);break;case"Burn":i=g_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:r,network:n})}},fs=new c_([new Xb,new u_,new ah,new Hb,new f_,new Hy,new ah]);var me=require("@msafe/sui3-utils"),Hu=require("@mysten/sui.js/transactions"),bs=require("@mysten/sui.js/utils");var Ep=require("@mysten/sui.js/transactions"),S_=1000n,x_=120n,k_=100n,A_={multiplier:{numerator:x_,denominator:k_}};var hs=class{constructor(e){this.globals=e}async simulate(e,r=A_){let n=this.copyTransactionBlock(e.txb),{suiClient:i}=this.globals,o=await this.getGasPrice(r);n.setGasPrice(o);let s=await i.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:u}=s.effects,l=this.toGasBudget(u,o),d=s.effects.status.status==="success",b;return d||(b=s.effects.status.error),{success:d,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:u,gasBudget:l,simulationError:b}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let r=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(r,e)}toGasBudget(e,r){let{computationCost:n,storageCost:i}=e,o=S_*r,s=BigInt(n)+o,u=s+BigInt(i);return u>s?u:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,r){if(this.isFixedValue(r))return r.fixedVal;if(this.isMultiplier(r)){let{multiplier:n}=r;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ep.TransactionBlock.from(e.serialize())}};var qu=require("buffer");function ps(t){return qu.Buffer.from(t,"utf-8")}function I_(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ms(t){return Uint8Array.from(qu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ws=require("@mysten/sui.js/verify");var jr=require("@mysten/sui.js/utils");var gs=require("@mysten/sui.js/utils"),Fi=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let r=(0,gs.normalizeStructTag)(e);if(this._coinMetaReg.has(r))return this._coinMetaReg.get(r);let n=await this.queryCoinMeta(r);return n&&this._coinMetaReg.set(r,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Lu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,qi=class t{static isCoin(e){return e?(0,gs.normalizeStructTag)(e).match(Lu)!=null:!1}static getCoinType(e){let[,r]=(0,gs.normalizeStructTag)(e).match(Lu)??[];return r||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:r}=e.content?.fields;if(r!==void 0)return BigInt(r)}};var fr=class{static normalizeSuiAddress(e){return(0,jr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,jr.normalizeStructTag)(e)}static isSuiAddressEqual(e,r){return(0,jr.normalizeSuiAddress)(e)===(0,jr.normalizeSuiAddress)(r)}static isSuiStructEqual(e,r){return(0,jr.normalizeStructTag)(e)===(0,jr.normalizeStructTag)(r)}static isCoinObjectType(e){return qi.isCoin(e)}};function Uu(t,e){return t.startsWith(e)?t:e+t}var $u=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ws.verifyTransactionBlock)(e.message,e.signature):(0,ws.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let r=ps(e.messageStr);return this.getPublicKeyFromSignature({message:r,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let r=await t.getPublicKeyFromSignature(e);return fr.isSuiAddressEqual(r.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let r=ps(e.messageStr);return this.verifySignature({message:r,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Pp=require("@msafe/sui3-utils"),Dp=require("@mysten/sui.js/cryptography"),Bp=require("@mysten/sui.js/multisig");var C_="0x2::sui::SUI";async function Gu(t,e){let r;try{r=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(r.data.length===0||!r.data[0].transaction?.txSignatures)return;let i=r.data[0].transaction?.txSignatures;for(let o=0;o!==i.length;o++){let s=i[o],u=O_(s,e);if(u)return u}}function O_(t,e){let r=(0,Dp.parseSerializedSignature)(t);switch(r.signatureScheme){case"MultiSig":{let n=new Bp.MultiSigPublicKey(r.multisig.multisig_pk).toSuiAddress();if(fr.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(fr.isSuiAddressEqual(r.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Pp.PublicKeySerde.de({publicKeyEncoded:r.publicKey,schema:r.signatureScheme});return fr.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function M_(t){let e=!0,r,n=[];for(;e;){let i=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:r});n.push(...i.data),e=i.hasNextPage,r=i.nextCursor}return n}var Np=25;async function Rp(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Vu=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ys=class{constructor(e){this.requester=e;this.pager=new Vu(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function jp(t,e,r){let n=new zu(t,e,r);return await Rp(n)}var zu=class extends ys{constructor(r,n,i){super(new Wu(r,n,i));this.provider=r;this.owner=n;this.options=i}},Wu=class{constructor(e,r,n){this.provider=e;this.owner=r;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Np,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let r;if(this.filter){let{filter:n}=this;r=e.data.filter(i=>n?.(i))}else r=e.data;return{data:r.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var sn=class t{constructor(e,r){this.globals=e;this.info=r;this.multiSig=new me.MultiSigAccount({threshold:r.threshold,ownersWithWeight:r.owners,creationNonce:r.creationNonce}),this.coinHelper=new Fi(this.suiClient),this.simulator=new hs(e)}multiSig;coinHelper;simulator;static async New(e,r){let n=await e.backend.getMSafeAccountInfo(r);if(new t(e,n).address!==r)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async r=>{let n=await this.coinHelper.getCoinMeta(r.coinType),i=r.lockedBalance.number?BigInt(r.totalBalance)-BigInt(r.lockedBalance.number):BigInt(r.totalBalance);return{type:(0,bs.normalizeStructTag)(r.coinType),balance:BigInt(i),metadata:n}}))}async ownedObjects(e){let r={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return jp(this.suiClient,this.address,r)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let r=e.pending,n=e.reject;return{application:r.application,txType:r.txType,txSubType:r.txSubType,createdAt:r.createdAt,creator:r.creator,digest:r.digest,intention:r.intention,sequenceNumber:r.sequenceNumber,payload:r.payload,votes:r.votes,approvalWeight:this.calculateWeightFromVotes(r.votes),msafeAddress:r.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let r=me.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:r});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let i=await n.build({client:this.globals.suiClient}),o=await n.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,bs.toHEX)(i),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async proposeCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async simulateObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async proposeObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async simulatePlainPayloadIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async proposePlainPayloadIntention(e){let r=await this.nextSequenceNumber(),n=Hu.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,me.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async voteForTransaction(e,r){let n=ms(r),i=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:i.signature})}async proposePendingTransaction(e){let r=new Hu.TransactionBlock,n=await r.build({client:this.suiClient}),i=await r.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:i,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let r=e.payload,n=(0,me.buildRejectTxb)(this.address,r);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let r=await this.pendingTransaction();if(!r||r.rejectDigest!=="")throw new Error("Already rejected");let n=r.payload,i=(0,me.buildRejectTxb)(this.address,n),o=await i.getDigest({client:this.suiClient}),s=await i.build({client:this.suiClient}),u=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:u.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,r=!1){let n=r?e.rejectVotes:e.votes,i=r?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(n.map(l=>[l.userAddress,l.signature]));for(let l=0;l<this.info.owners.length;l++){let d=this.info.owners[l],b=s.get(d.address);b&&o.push(b)}let u=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ms(i),signature:u,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(r=>r.userAddress))}calculateWeight(e){let r=0;for(let n=0;n<e.length;n++){let i=this.info.owners.find(o=>(0,me.isSameAddress)(o.address,e[n]));i&&(r+=i.weight)}return r}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Fp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/utils");var _s=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let r=this.knownPublicKeys.get(e);if(r)return r;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let r=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];r[o]=this.knownPublicKeys.get(s)}let n=r.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(n.length===0)return r;let i=await this.globals.backend.getPublicKeyBatch(n.map(o=>e[o]));for(let o=0;o<n.length;o++){let s=n[o];r[s]=i[o]}for(let o=0;o<r.length;o++)r[o]===void 0&&(r[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)r[o]&&this.knownPublicKeys.set(e[o],r[o]);return r}addPublicKey(e,r){if(!(0,Fp.isSameAddress)(e,r.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,qp.normalizeSuiAddress)(e),r)}async _getPublicKey(e){let r=await this.getPublicKeyFromBackend(e);if(r)return r;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Gu(this.globals.suiClient,e)}};var vs=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Wp=require("@mysten/sui.js/client");var Ui=require("@msafe/sui3-utils"),Li=de(require("axios"),1);var Ts=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let r=await this.post("/auth/login",e);return this._token=r.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let r={userAddressList:e};return(await this.get("/user/public-keys",{params:r,headers:this.headers()})).data?.map(i=>i?Ui.PublicKeySerde.de(i):void 0)}async getMSafeAccountInfo(e){let r={msafeAddress:e},n=await this.get("/msafe",{params:r,headers:this.headers()});return t.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let r={status:e.status??Ui.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:r,headers:this.headers()});return{data:n.data.data.map(t.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let r=e;await this.post("/msafe/status",r,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(r=>({address:r.address,weight:r.weight,publicKey:Ui.PublicKeySerde.de({publicKeyEncoded:r.publicKeyEncoded,schema:r.schema})}))}}async get(e,r){let n=this.getFullUrl(e);try{return await Li.default.get(n,r)}catch(i){throw Ss.fromError(i)??i}}async post(e,r,n){let i=this.getFullUrl(e);try{return await Li.default.post(i,r,{...n,transformRequest:this.getTransformRequest()})}catch(o){throw Ss.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Uu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:r}=Li.default.defaults;return r?r instanceof Array?e=r:e=[r]:e=[],[n=>JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ss=class t extends Error{constructor(r){super();this.e=r;Error.captureStackTrace(this,this.constructor)}name;static fromError(r){if(Li.default.isAxiosError(r)&&r?.response?.data&&"message"in r.response.data)return new t(r)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Lp=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Lp||{}),xs="https://fullnode.testnet.sui.io",Zu="https://fullnode.mainnet.sui.io",Ku="http://127.0.0.1:3000",Ju="http://127.0.0.1:3001",Up="https://sui-dev.m-safe.link",$p="http://13.56.226.148:81",Gp="https://sui-preview.m-safe.link",Vp="https://sui.m-safe.link",zp=new Map([["unit",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["local",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["dev",{suiClient:{url:xs},backend:{url:Up},syncingURL:$p,network:"sui:testnet"}],["prev",{suiClient:{url:Zu},backend:{url:Gp},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Zu},backend:{url:Vp},syncingURL:"",network:"sui:mainnet"}]]);function Xu(t,e){let r=zp.get(t);if(!r)throw new Error("Unknown environment");return e?.suiClient?.url&&(r.suiClient.url=e.suiClient.url),e?.backend?.url&&(r.backend.url=e.backend.url),r}var $i=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,r){let n=Xu(e,r),i=new Wp.SuiClient(n.suiClient),o=new Ts(n.backend.url);return new t({backend:o,suiClient:i,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var ks=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,r){let n=await $i.New(e,r);return new t(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let r=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(r),r}async authSign(e){let r=As.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:r});return this.backend.authSign({address:await e.address(),message:r,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:As.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new sn(this.globals,e)}async getMSafeAccountFromAddress(e){let r=await this.backend.getMSafeAccountInfo(e);return new sn(this.globals,r)}get creationHelper(){return this._creationHelper||(this._creationHelper=new un(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _s(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new cn(this.globals)}get Invitation(){return new zi(this.globals)}get Report(){return new vs(this.globals)}async walletAddress(){return this.wallet.address()}};
2054
2054
  /*! Bundled license information:
2055
2055
 
2056
2056
  @syntsugar/cc-graph/dist/index.umd.js: