@msafe/sui3-sdk 0.0.49-pre-96f409f.0 → 0.0.49-pre-cf75f5e.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 Cg=Object.create;var Ro=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var xg=Object.getPrototypeOf,Ig=Object.prototype.hasOwnProperty;var Og=(t,e)=>()=>(t&&(e=t(t=0)),e);var yi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wl=(t,e)=>{for(var n in e)Ro(t,n,{get:e[n],enumerable:!0})},bl=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ag(e))!Ig.call(t,r)&&r!==n&&Ro(t,r,{get:()=>e[r],enumerable:!(i=Sg(e,r))||i.enumerable});return t};var ge=(t,e,n)=>(n=t!=null?Cg(xg(t)):{},bl(e||!t||!t.__esModule?Ro(n,"default",{value:t,enumerable:!0}):n,t)),vl=t=>bl(Ro({},"__esModule",{value:!0}),t);var Cl=yi((ck,Tl)=>{"use strict";Tl.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Al=yi((uk,Sl)=>{"use strict";var Va=Cl();Sl.exports=(t,e={})=>{if(!Va(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:n}=e,i=[],r=[],o=a=>{let u=i.indexOf(a);if(u!==-1)return r[u];let l=[];return i.push(a),r.push(l),l.push(...a.map(h=>Array.isArray(h)?o(h):Va(h)?s(h):h)),l},s=a=>{let u=i.indexOf(a);if(u!==-1)return r[u];let l={},h=Object.keys(a).sort(e.compare);i.push(a),r.push(l);for(let w of h){let v=a[w],T;n&&Array.isArray(v)?T=o(v):T=n&&Va(v)?s(v):v,Object.defineProperty(l,w,{...Object.getOwnPropertyDescriptor(a,w),value:T})}return l};return Array.isArray(t)?n?o(t):t.slice():s(t)}});var Ol=yi((lk,Il)=>{"use strict";var Pg=Object.prototype.toString;Il.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var n=typeof e;if(n==="boolean")return"boolean";if(n==="string")return"string";if(n==="number")return"number";if(n==="symbol")return"symbol";if(n==="function")return jg(e)?"generatorfunction":"function";if(Dg(e))return"array";if(Rg(e))return"buffer";if(Fg(e))return"arguments";if(Mg(e))return"date";if(Eg(e))return"error";if(Bg(e))return"regexp";switch(xl(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(Ng(e))return"generator";switch(n=Pg.call(e),n){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 n.slice(8,-1).toLowerCase().replace(/\s/g,"")};function xl(t){return typeof t.constructor=="function"?t.constructor.name:null}function Dg(t){return Array.isArray?Array.isArray(t):t instanceof Array}function Eg(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function Mg(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function Bg(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function jg(t,e){return xl(t)==="GeneratorFunction"}function Ng(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function Fg(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 Rg(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Lo=yi((dk,Ml)=>{"use strict";var qg=Al(),Ga=Ol(),Pl=(t,e)=>!e||Ga(e)!=="array"?!1:e.indexOf(t)>-1,Lg=(t,e)=>qg(t,{compare:e}),Dl=(t,e)=>{let n=e&&e.compareFunction;return t.slice().sort(n)};function El(t,e){let n=e&&e.compareFunction,i=Lg(t,n);return Object.keys(t).forEach(function(r){let o=i[r],s=Ga(o);if(s==="object"){(!e||!Pl(r,e.ignoreObjectAtKeys))&&(i[r]=El(o,e));return}s==="array"&&(!e||!Pl(r,e.ignoreArrayAtKeys))&&(i[r]=Dl(o,e))}),i}var Er=(t,e)=>{let n=Ga(t);return Er[n]?Er[n](t,e):t};Er.array=Dl;Er.object=El;Ml.exports=Er});var ke=yi((Bl,Wa)=>{"use strict";(function(t,e){"use strict";function n(A,c){if(!A)throw new Error(c||"Assertion failed")}function i(A,c){A.super_=c;var d=function(){};d.prototype=c.prototype,A.prototype=new d,A.prototype.constructor=A}function r(A,c,d){if(r.isBN(A))return A;this.negative=0,this.words=null,this.length=0,this.red=null,A!==null&&((c==="le"||c==="be")&&(d=c,c=10),this._init(A||0,c||10,d||"be"))}typeof t=="object"?t.exports=r:e.BN=r,r.BN=r,r.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=require("buffer").Buffer}catch{}r.isBN=function(c){return c instanceof r?!0:c!==null&&typeof c=="object"&&c.constructor.wordSize===r.wordSize&&Array.isArray(c.words)},r.max=function(c,d){return c.cmp(d)>0?c:d},r.min=function(c,d){return c.cmp(d)<0?c:d},r.prototype._init=function(c,d,g){if(typeof c=="number")return this._initNumber(c,d,g);if(typeof c=="object")return this._initArray(c,d,g);d==="hex"&&(d=16),n(d===(d|0)&&d>=2&&d<=36),c=c.toString().replace(/\s+/g,"");var b=0;c[0]==="-"&&(b++,this.negative=1),b<c.length&&(d===16?this._parseHex(c,b,g):(this._parseBase(c,d,b),g==="le"&&this._initArray(this.toArray(),d,g)))},r.prototype._initNumber=function(c,d,g){c<0&&(this.negative=1,c=-c),c<67108864?(this.words=[c&67108863],this.length=1):c<4503599627370496?(this.words=[c&67108863,c/67108864&67108863],this.length=2):(n(c<9007199254740992),this.words=[c&67108863,c/67108864&67108863,1],this.length=3),g==="le"&&this._initArray(this.toArray(),d,g)},r.prototype._initArray=function(c,d,g){if(n(typeof c.length=="number"),c.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(c.length/3),this.words=new Array(this.length);for(var b=0;b<this.length;b++)this.words[b]=0;var p,m,y=0;if(g==="be")for(b=c.length-1,p=0;b>=0;b-=3)m=c[b]|c[b-1]<<8|c[b-2]<<16,this.words[p]|=m<<y&67108863,this.words[p+1]=m>>>26-y&67108863,y+=24,y>=26&&(y-=26,p++);else if(g==="le")for(b=0,p=0;b<c.length;b+=3)m=c[b]|c[b+1]<<8|c[b+2]<<16,this.words[p]|=m<<y&67108863,this.words[p+1]=m>>>26-y&67108863,y+=24,y>=26&&(y-=26,p++);return this._strip()};function s(A,c){var d=A.charCodeAt(c);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;n(!1,"Invalid character in "+A)}function a(A,c,d){var g=s(A,d);return d-1>=c&&(g|=s(A,d-1)<<4),g}r.prototype._parseHex=function(c,d,g){this.length=Math.ceil((c.length-d)/6),this.words=new Array(this.length);for(var b=0;b<this.length;b++)this.words[b]=0;var p=0,m=0,y;if(g==="be")for(b=c.length-1;b>=d;b-=2)y=a(c,d,b)<<p,this.words[m]|=y&67108863,p>=18?(p-=18,m+=1,this.words[m]|=y>>>26):p+=8;else{var _=c.length-d;for(b=_%2===0?d+1:d;b<c.length;b+=2)y=a(c,d,b)<<p,this.words[m]|=y&67108863,p>=18?(p-=18,m+=1,this.words[m]|=y>>>26):p+=8}this._strip()};function u(A,c,d,g){for(var b=0,p=0,m=Math.min(A.length,d),y=c;y<m;y++){var _=A.charCodeAt(y)-48;b*=g,_>=49?p=_-49+10:_>=17?p=_-17+10:p=_,n(_>=0&&p<g,"Invalid character"),b+=p}return b}r.prototype._parseBase=function(c,d,g){this.words=[0],this.length=1;for(var b=0,p=1;p<=67108863;p*=d)b++;b--,p=p/d|0;for(var m=c.length-g,y=m%b,_=Math.min(m,m-y)+g,f=0,k=g;k<_;k+=b)f=u(c,k,k+b,d),this.imuln(p),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f);if(y!==0){var M=1;for(f=u(c,k,c.length,d),k=0;k<y;k++)M*=d;this.imuln(M),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f)}this._strip()},r.prototype.copy=function(c){c.words=new Array(this.length);for(var d=0;d<this.length;d++)c.words[d]=this.words[d];c.length=this.length,c.negative=this.negative,c.red=this.red};function l(A,c){A.words=c.words,A.length=c.length,A.negative=c.negative,A.red=c.red}if(r.prototype._move=function(c){l(c,this)},r.prototype.clone=function(){var c=new r(null);return this.copy(c),c},r.prototype._expand=function(c){for(;this.length<c;)this.words[this.length++]=0;return this},r.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},r.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{r.prototype[Symbol.for("nodejs.util.inspect.custom")]=h}catch{r.prototype.inspect=h}else r.prototype.inspect=h;function h(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],v=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];r.prototype.toString=function(c,d){c=c||10,d=d|0||1;var g;if(c===16||c==="hex"){g="";for(var b=0,p=0,m=0;m<this.length;m++){var y=this.words[m],_=((y<<b|p)&16777215).toString(16);p=y>>>24-b&16777215,b+=2,b>=26&&(b-=26,m--),p!==0||m!==this.length-1?g=w[6-_.length]+_+g:g=_+g}for(p!==0&&(g=p.toString(16)+g);g.length%d!==0;)g="0"+g;return this.negative!==0&&(g="-"+g),g}if(c===(c|0)&&c>=2&&c<=36){var f=v[c],k=T[c];g="";var M=this.clone();for(M.negative=0;!M.isZero();){var j=M.modrn(k).toString(c);M=M.idivn(k),M.isZero()?g=j+g:g=w[f-j.length]+j+g}for(this.isZero()&&(g="0"+g);g.length%d!==0;)g="0"+g;return this.negative!==0&&(g="-"+g),g}n(!1,"Base should be between 2 and 36")},r.prototype.toNumber=function(){var c=this.words[0];return this.length===2?c+=this.words[1]*67108864:this.length===3&&this.words[2]===1?c+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-c:c},r.prototype.toJSON=function(){return this.toString(16,2)},o&&(r.prototype.toBuffer=function(c,d){return this.toArrayLike(o,c,d)}),r.prototype.toArray=function(c,d){return this.toArrayLike(Array,c,d)};var I=function(c,d){return c.allocUnsafe?c.allocUnsafe(d):new c(d)};r.prototype.toArrayLike=function(c,d,g){this._strip();var b=this.byteLength(),p=g||Math.max(1,b);n(b<=p,"byte array longer than desired length"),n(p>0,"Requested array length <= 0");var m=I(c,p),y=d==="le"?"LE":"BE";return this["_toArrayLike"+y](m,b),m},r.prototype._toArrayLikeLE=function(c,d){for(var g=0,b=0,p=0,m=0;p<this.length;p++){var y=this.words[p]<<m|b;c[g++]=y&255,g<c.length&&(c[g++]=y>>8&255),g<c.length&&(c[g++]=y>>16&255),m===6?(g<c.length&&(c[g++]=y>>24&255),b=0,m=0):(b=y>>>24,m+=2)}if(g<c.length)for(c[g++]=b;g<c.length;)c[g++]=0},r.prototype._toArrayLikeBE=function(c,d){for(var g=c.length-1,b=0,p=0,m=0;p<this.length;p++){var y=this.words[p]<<m|b;c[g--]=y&255,g>=0&&(c[g--]=y>>8&255),g>=0&&(c[g--]=y>>16&255),m===6?(g>=0&&(c[g--]=y>>24&255),b=0,m=0):(b=y>>>24,m+=2)}if(g>=0)for(c[g--]=b;g>=0;)c[g--]=0},Math.clz32?r.prototype._countBits=function(c){return 32-Math.clz32(c)}:r.prototype._countBits=function(c){var d=c,g=0;return d>=4096&&(g+=13,d>>>=13),d>=64&&(g+=7,d>>>=7),d>=8&&(g+=4,d>>>=4),d>=2&&(g+=2,d>>>=2),g+d},r.prototype._zeroBits=function(c){if(c===0)return 26;var d=c,g=0;return d&8191||(g+=13,d>>>=13),d&127||(g+=7,d>>>=7),d&15||(g+=4,d>>>=4),d&3||(g+=2,d>>>=2),d&1||g++,g},r.prototype.bitLength=function(){var c=this.words[this.length-1],d=this._countBits(c);return(this.length-1)*26+d};function x(A){for(var c=new Array(A.bitLength()),d=0;d<c.length;d++){var g=d/26|0,b=d%26;c[d]=A.words[g]>>>b&1}return c}r.prototype.zeroBits=function(){if(this.isZero())return 0;for(var c=0,d=0;d<this.length;d++){var g=this._zeroBits(this.words[d]);if(c+=g,g!==26)break}return c},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(c){return this.negative!==0?this.abs().inotn(c).iaddn(1):this.clone()},r.prototype.fromTwos=function(c){return this.testn(c-1)?this.notn(c).iaddn(1).ineg():this.clone()},r.prototype.isNeg=function(){return this.negative!==0},r.prototype.neg=function(){return this.clone().ineg()},r.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},r.prototype.iuor=function(c){for(;this.length<c.length;)this.words[this.length++]=0;for(var d=0;d<c.length;d++)this.words[d]=this.words[d]|c.words[d];return this._strip()},r.prototype.ior=function(c){return n((this.negative|c.negative)===0),this.iuor(c)},r.prototype.or=function(c){return this.length>c.length?this.clone().ior(c):c.clone().ior(this)},r.prototype.uor=function(c){return this.length>c.length?this.clone().iuor(c):c.clone().iuor(this)},r.prototype.iuand=function(c){var d;this.length>c.length?d=c:d=this;for(var g=0;g<d.length;g++)this.words[g]=this.words[g]&c.words[g];return this.length=d.length,this._strip()},r.prototype.iand=function(c){return n((this.negative|c.negative)===0),this.iuand(c)},r.prototype.and=function(c){return this.length>c.length?this.clone().iand(c):c.clone().iand(this)},r.prototype.uand=function(c){return this.length>c.length?this.clone().iuand(c):c.clone().iuand(this)},r.prototype.iuxor=function(c){var d,g;this.length>c.length?(d=this,g=c):(d=c,g=this);for(var b=0;b<g.length;b++)this.words[b]=d.words[b]^g.words[b];if(this!==d)for(;b<d.length;b++)this.words[b]=d.words[b];return this.length=d.length,this._strip()},r.prototype.ixor=function(c){return n((this.negative|c.negative)===0),this.iuxor(c)},r.prototype.xor=function(c){return this.length>c.length?this.clone().ixor(c):c.clone().ixor(this)},r.prototype.uxor=function(c){return this.length>c.length?this.clone().iuxor(c):c.clone().iuxor(this)},r.prototype.inotn=function(c){n(typeof c=="number"&&c>=0);var d=Math.ceil(c/26)|0,g=c%26;this._expand(d),g>0&&d--;for(var b=0;b<d;b++)this.words[b]=~this.words[b]&67108863;return g>0&&(this.words[b]=~this.words[b]&67108863>>26-g),this._strip()},r.prototype.notn=function(c){return this.clone().inotn(c)},r.prototype.setn=function(c,d){n(typeof c=="number"&&c>=0);var g=c/26|0,b=c%26;return this._expand(g+1),d?this.words[g]=this.words[g]|1<<b:this.words[g]=this.words[g]&~(1<<b),this._strip()},r.prototype.iadd=function(c){var d;if(this.negative!==0&&c.negative===0)return this.negative=0,d=this.isub(c),this.negative^=1,this._normSign();if(this.negative===0&&c.negative!==0)return c.negative=0,d=this.isub(c),c.negative=1,d._normSign();var g,b;this.length>c.length?(g=this,b=c):(g=c,b=this);for(var p=0,m=0;m<b.length;m++)d=(g.words[m]|0)+(b.words[m]|0)+p,this.words[m]=d&67108863,p=d>>>26;for(;p!==0&&m<g.length;m++)d=(g.words[m]|0)+p,this.words[m]=d&67108863,p=d>>>26;if(this.length=g.length,p!==0)this.words[this.length]=p,this.length++;else if(g!==this)for(;m<g.length;m++)this.words[m]=g.words[m];return this},r.prototype.add=function(c){var d;return c.negative!==0&&this.negative===0?(c.negative=0,d=this.sub(c),c.negative^=1,d):c.negative===0&&this.negative!==0?(this.negative=0,d=c.sub(this),this.negative=1,d):this.length>c.length?this.clone().iadd(c):c.clone().iadd(this)},r.prototype.isub=function(c){if(c.negative!==0){c.negative=0;var d=this.iadd(c);return c.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(c),this.negative=1,this._normSign();var g=this.cmp(c);if(g===0)return this.negative=0,this.length=1,this.words[0]=0,this;var b,p;g>0?(b=this,p=c):(b=c,p=this);for(var m=0,y=0;y<p.length;y++)d=(b.words[y]|0)-(p.words[y]|0)+m,m=d>>26,this.words[y]=d&67108863;for(;m!==0&&y<b.length;y++)d=(b.words[y]|0)+m,m=d>>26,this.words[y]=d&67108863;if(m===0&&y<b.length&&b!==this)for(;y<b.length;y++)this.words[y]=b.words[y];return this.length=Math.max(this.length,y),b!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(c){return this.clone().isub(c)};function P(A,c,d){d.negative=c.negative^A.negative;var g=A.length+c.length|0;d.length=g,g=g-1|0;var b=A.words[0]|0,p=c.words[0]|0,m=b*p,y=m&67108863,_=m/67108864|0;d.words[0]=y;for(var f=1;f<g;f++){for(var k=_>>>26,M=_&67108863,j=Math.min(f,c.length-1),L=Math.max(0,f-A.length+1);L<=j;L++){var R=f-L|0;b=A.words[R]|0,p=c.words[L]|0,m=b*p+M,k+=m/67108864|0,M=m&67108863}d.words[f]=M|0,_=k|0}return _!==0?d.words[f]=_|0:d.length--,d._strip()}var O=function(c,d,g){var b=c.words,p=d.words,m=g.words,y=0,_,f,k,M=b[0]|0,j=M&8191,L=M>>>13,R=b[1]|0,W=R&8191,ne=R>>>13,me=b[2]|0,ue=me&8191,pe=me>>>13,vt=b[3]|0,De=vt&8191,je=vt>>>13,Ki=b[4]|0,Ne=Ki&8191,Fe=Ki>>>13,Fo=b[5]|0,Ke=Fo&8191,ze=Fo>>>13,ol=b[6]|0,Ve=ol&8191,Ge=ol>>>13,sl=b[7]|0,We=sl&8191,He=sl>>>13,al=b[8]|0,Ze=al&8191,Xe=al>>>13,cl=b[9]|0,Je=cl&8191,Ye=cl>>>13,ul=p[0]|0,Qe=ul&8191,et=ul>>>13,ll=p[1]|0,tt=ll&8191,nt=ll>>>13,dl=p[2]|0,it=dl&8191,rt=dl>>>13,fl=p[3]|0,ot=fl&8191,st=fl>>>13,hl=p[4]|0,at=hl&8191,ct=hl>>>13,ml=p[5]|0,ut=ml&8191,lt=ml>>>13,pl=p[6]|0,dt=pl&8191,ft=pl>>>13,gl=p[7]|0,ht=gl&8191,mt=gl>>>13,_l=p[8]|0,pt=_l&8191,gt=_l>>>13,yl=p[9]|0,_t=yl&8191,yt=yl>>>13;g.negative=c.negative^d.negative,g.length=19,_=Math.imul(j,Qe),f=Math.imul(j,et),f=f+Math.imul(L,Qe)|0,k=Math.imul(L,et);var Aa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,_=Math.imul(W,Qe),f=Math.imul(W,et),f=f+Math.imul(ne,Qe)|0,k=Math.imul(ne,et),_=_+Math.imul(j,tt)|0,f=f+Math.imul(j,nt)|0,f=f+Math.imul(L,tt)|0,k=k+Math.imul(L,nt)|0;var xa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(xa>>>26)|0,xa&=67108863,_=Math.imul(ue,Qe),f=Math.imul(ue,et),f=f+Math.imul(pe,Qe)|0,k=Math.imul(pe,et),_=_+Math.imul(W,tt)|0,f=f+Math.imul(W,nt)|0,f=f+Math.imul(ne,tt)|0,k=k+Math.imul(ne,nt)|0,_=_+Math.imul(j,it)|0,f=f+Math.imul(j,rt)|0,f=f+Math.imul(L,it)|0,k=k+Math.imul(L,rt)|0;var Ia=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ia>>>26)|0,Ia&=67108863,_=Math.imul(De,Qe),f=Math.imul(De,et),f=f+Math.imul(je,Qe)|0,k=Math.imul(je,et),_=_+Math.imul(ue,tt)|0,f=f+Math.imul(ue,nt)|0,f=f+Math.imul(pe,tt)|0,k=k+Math.imul(pe,nt)|0,_=_+Math.imul(W,it)|0,f=f+Math.imul(W,rt)|0,f=f+Math.imul(ne,it)|0,k=k+Math.imul(ne,rt)|0,_=_+Math.imul(j,ot)|0,f=f+Math.imul(j,st)|0,f=f+Math.imul(L,ot)|0,k=k+Math.imul(L,st)|0;var Oa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Oa>>>26)|0,Oa&=67108863,_=Math.imul(Ne,Qe),f=Math.imul(Ne,et),f=f+Math.imul(Fe,Qe)|0,k=Math.imul(Fe,et),_=_+Math.imul(De,tt)|0,f=f+Math.imul(De,nt)|0,f=f+Math.imul(je,tt)|0,k=k+Math.imul(je,nt)|0,_=_+Math.imul(ue,it)|0,f=f+Math.imul(ue,rt)|0,f=f+Math.imul(pe,it)|0,k=k+Math.imul(pe,rt)|0,_=_+Math.imul(W,ot)|0,f=f+Math.imul(W,st)|0,f=f+Math.imul(ne,ot)|0,k=k+Math.imul(ne,st)|0,_=_+Math.imul(j,at)|0,f=f+Math.imul(j,ct)|0,f=f+Math.imul(L,at)|0,k=k+Math.imul(L,ct)|0;var Pa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Pa>>>26)|0,Pa&=67108863,_=Math.imul(Ke,Qe),f=Math.imul(Ke,et),f=f+Math.imul(ze,Qe)|0,k=Math.imul(ze,et),_=_+Math.imul(Ne,tt)|0,f=f+Math.imul(Ne,nt)|0,f=f+Math.imul(Fe,tt)|0,k=k+Math.imul(Fe,nt)|0,_=_+Math.imul(De,it)|0,f=f+Math.imul(De,rt)|0,f=f+Math.imul(je,it)|0,k=k+Math.imul(je,rt)|0,_=_+Math.imul(ue,ot)|0,f=f+Math.imul(ue,st)|0,f=f+Math.imul(pe,ot)|0,k=k+Math.imul(pe,st)|0,_=_+Math.imul(W,at)|0,f=f+Math.imul(W,ct)|0,f=f+Math.imul(ne,at)|0,k=k+Math.imul(ne,ct)|0,_=_+Math.imul(j,ut)|0,f=f+Math.imul(j,lt)|0,f=f+Math.imul(L,ut)|0,k=k+Math.imul(L,lt)|0;var Da=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Da>>>26)|0,Da&=67108863,_=Math.imul(Ve,Qe),f=Math.imul(Ve,et),f=f+Math.imul(Ge,Qe)|0,k=Math.imul(Ge,et),_=_+Math.imul(Ke,tt)|0,f=f+Math.imul(Ke,nt)|0,f=f+Math.imul(ze,tt)|0,k=k+Math.imul(ze,nt)|0,_=_+Math.imul(Ne,it)|0,f=f+Math.imul(Ne,rt)|0,f=f+Math.imul(Fe,it)|0,k=k+Math.imul(Fe,rt)|0,_=_+Math.imul(De,ot)|0,f=f+Math.imul(De,st)|0,f=f+Math.imul(je,ot)|0,k=k+Math.imul(je,st)|0,_=_+Math.imul(ue,at)|0,f=f+Math.imul(ue,ct)|0,f=f+Math.imul(pe,at)|0,k=k+Math.imul(pe,ct)|0,_=_+Math.imul(W,ut)|0,f=f+Math.imul(W,lt)|0,f=f+Math.imul(ne,ut)|0,k=k+Math.imul(ne,lt)|0,_=_+Math.imul(j,dt)|0,f=f+Math.imul(j,ft)|0,f=f+Math.imul(L,dt)|0,k=k+Math.imul(L,ft)|0;var Ea=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,_=Math.imul(We,Qe),f=Math.imul(We,et),f=f+Math.imul(He,Qe)|0,k=Math.imul(He,et),_=_+Math.imul(Ve,tt)|0,f=f+Math.imul(Ve,nt)|0,f=f+Math.imul(Ge,tt)|0,k=k+Math.imul(Ge,nt)|0,_=_+Math.imul(Ke,it)|0,f=f+Math.imul(Ke,rt)|0,f=f+Math.imul(ze,it)|0,k=k+Math.imul(ze,rt)|0,_=_+Math.imul(Ne,ot)|0,f=f+Math.imul(Ne,st)|0,f=f+Math.imul(Fe,ot)|0,k=k+Math.imul(Fe,st)|0,_=_+Math.imul(De,at)|0,f=f+Math.imul(De,ct)|0,f=f+Math.imul(je,at)|0,k=k+Math.imul(je,ct)|0,_=_+Math.imul(ue,ut)|0,f=f+Math.imul(ue,lt)|0,f=f+Math.imul(pe,ut)|0,k=k+Math.imul(pe,lt)|0,_=_+Math.imul(W,dt)|0,f=f+Math.imul(W,ft)|0,f=f+Math.imul(ne,dt)|0,k=k+Math.imul(ne,ft)|0,_=_+Math.imul(j,ht)|0,f=f+Math.imul(j,mt)|0,f=f+Math.imul(L,ht)|0,k=k+Math.imul(L,mt)|0;var Ma=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ma>>>26)|0,Ma&=67108863,_=Math.imul(Ze,Qe),f=Math.imul(Ze,et),f=f+Math.imul(Xe,Qe)|0,k=Math.imul(Xe,et),_=_+Math.imul(We,tt)|0,f=f+Math.imul(We,nt)|0,f=f+Math.imul(He,tt)|0,k=k+Math.imul(He,nt)|0,_=_+Math.imul(Ve,it)|0,f=f+Math.imul(Ve,rt)|0,f=f+Math.imul(Ge,it)|0,k=k+Math.imul(Ge,rt)|0,_=_+Math.imul(Ke,ot)|0,f=f+Math.imul(Ke,st)|0,f=f+Math.imul(ze,ot)|0,k=k+Math.imul(ze,st)|0,_=_+Math.imul(Ne,at)|0,f=f+Math.imul(Ne,ct)|0,f=f+Math.imul(Fe,at)|0,k=k+Math.imul(Fe,ct)|0,_=_+Math.imul(De,ut)|0,f=f+Math.imul(De,lt)|0,f=f+Math.imul(je,ut)|0,k=k+Math.imul(je,lt)|0,_=_+Math.imul(ue,dt)|0,f=f+Math.imul(ue,ft)|0,f=f+Math.imul(pe,dt)|0,k=k+Math.imul(pe,ft)|0,_=_+Math.imul(W,ht)|0,f=f+Math.imul(W,mt)|0,f=f+Math.imul(ne,ht)|0,k=k+Math.imul(ne,mt)|0,_=_+Math.imul(j,pt)|0,f=f+Math.imul(j,gt)|0,f=f+Math.imul(L,pt)|0,k=k+Math.imul(L,gt)|0;var Ba=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ba>>>26)|0,Ba&=67108863,_=Math.imul(Je,Qe),f=Math.imul(Je,et),f=f+Math.imul(Ye,Qe)|0,k=Math.imul(Ye,et),_=_+Math.imul(Ze,tt)|0,f=f+Math.imul(Ze,nt)|0,f=f+Math.imul(Xe,tt)|0,k=k+Math.imul(Xe,nt)|0,_=_+Math.imul(We,it)|0,f=f+Math.imul(We,rt)|0,f=f+Math.imul(He,it)|0,k=k+Math.imul(He,rt)|0,_=_+Math.imul(Ve,ot)|0,f=f+Math.imul(Ve,st)|0,f=f+Math.imul(Ge,ot)|0,k=k+Math.imul(Ge,st)|0,_=_+Math.imul(Ke,at)|0,f=f+Math.imul(Ke,ct)|0,f=f+Math.imul(ze,at)|0,k=k+Math.imul(ze,ct)|0,_=_+Math.imul(Ne,ut)|0,f=f+Math.imul(Ne,lt)|0,f=f+Math.imul(Fe,ut)|0,k=k+Math.imul(Fe,lt)|0,_=_+Math.imul(De,dt)|0,f=f+Math.imul(De,ft)|0,f=f+Math.imul(je,dt)|0,k=k+Math.imul(je,ft)|0,_=_+Math.imul(ue,ht)|0,f=f+Math.imul(ue,mt)|0,f=f+Math.imul(pe,ht)|0,k=k+Math.imul(pe,mt)|0,_=_+Math.imul(W,pt)|0,f=f+Math.imul(W,gt)|0,f=f+Math.imul(ne,pt)|0,k=k+Math.imul(ne,gt)|0,_=_+Math.imul(j,_t)|0,f=f+Math.imul(j,yt)|0,f=f+Math.imul(L,_t)|0,k=k+Math.imul(L,yt)|0;var ja=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(ja>>>26)|0,ja&=67108863,_=Math.imul(Je,tt),f=Math.imul(Je,nt),f=f+Math.imul(Ye,tt)|0,k=Math.imul(Ye,nt),_=_+Math.imul(Ze,it)|0,f=f+Math.imul(Ze,rt)|0,f=f+Math.imul(Xe,it)|0,k=k+Math.imul(Xe,rt)|0,_=_+Math.imul(We,ot)|0,f=f+Math.imul(We,st)|0,f=f+Math.imul(He,ot)|0,k=k+Math.imul(He,st)|0,_=_+Math.imul(Ve,at)|0,f=f+Math.imul(Ve,ct)|0,f=f+Math.imul(Ge,at)|0,k=k+Math.imul(Ge,ct)|0,_=_+Math.imul(Ke,ut)|0,f=f+Math.imul(Ke,lt)|0,f=f+Math.imul(ze,ut)|0,k=k+Math.imul(ze,lt)|0,_=_+Math.imul(Ne,dt)|0,f=f+Math.imul(Ne,ft)|0,f=f+Math.imul(Fe,dt)|0,k=k+Math.imul(Fe,ft)|0,_=_+Math.imul(De,ht)|0,f=f+Math.imul(De,mt)|0,f=f+Math.imul(je,ht)|0,k=k+Math.imul(je,mt)|0,_=_+Math.imul(ue,pt)|0,f=f+Math.imul(ue,gt)|0,f=f+Math.imul(pe,pt)|0,k=k+Math.imul(pe,gt)|0,_=_+Math.imul(W,_t)|0,f=f+Math.imul(W,yt)|0,f=f+Math.imul(ne,_t)|0,k=k+Math.imul(ne,yt)|0;var Na=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Na>>>26)|0,Na&=67108863,_=Math.imul(Je,it),f=Math.imul(Je,rt),f=f+Math.imul(Ye,it)|0,k=Math.imul(Ye,rt),_=_+Math.imul(Ze,ot)|0,f=f+Math.imul(Ze,st)|0,f=f+Math.imul(Xe,ot)|0,k=k+Math.imul(Xe,st)|0,_=_+Math.imul(We,at)|0,f=f+Math.imul(We,ct)|0,f=f+Math.imul(He,at)|0,k=k+Math.imul(He,ct)|0,_=_+Math.imul(Ve,ut)|0,f=f+Math.imul(Ve,lt)|0,f=f+Math.imul(Ge,ut)|0,k=k+Math.imul(Ge,lt)|0,_=_+Math.imul(Ke,dt)|0,f=f+Math.imul(Ke,ft)|0,f=f+Math.imul(ze,dt)|0,k=k+Math.imul(ze,ft)|0,_=_+Math.imul(Ne,ht)|0,f=f+Math.imul(Ne,mt)|0,f=f+Math.imul(Fe,ht)|0,k=k+Math.imul(Fe,mt)|0,_=_+Math.imul(De,pt)|0,f=f+Math.imul(De,gt)|0,f=f+Math.imul(je,pt)|0,k=k+Math.imul(je,gt)|0,_=_+Math.imul(ue,_t)|0,f=f+Math.imul(ue,yt)|0,f=f+Math.imul(pe,_t)|0,k=k+Math.imul(pe,yt)|0;var Fa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Fa>>>26)|0,Fa&=67108863,_=Math.imul(Je,ot),f=Math.imul(Je,st),f=f+Math.imul(Ye,ot)|0,k=Math.imul(Ye,st),_=_+Math.imul(Ze,at)|0,f=f+Math.imul(Ze,ct)|0,f=f+Math.imul(Xe,at)|0,k=k+Math.imul(Xe,ct)|0,_=_+Math.imul(We,ut)|0,f=f+Math.imul(We,lt)|0,f=f+Math.imul(He,ut)|0,k=k+Math.imul(He,lt)|0,_=_+Math.imul(Ve,dt)|0,f=f+Math.imul(Ve,ft)|0,f=f+Math.imul(Ge,dt)|0,k=k+Math.imul(Ge,ft)|0,_=_+Math.imul(Ke,ht)|0,f=f+Math.imul(Ke,mt)|0,f=f+Math.imul(ze,ht)|0,k=k+Math.imul(ze,mt)|0,_=_+Math.imul(Ne,pt)|0,f=f+Math.imul(Ne,gt)|0,f=f+Math.imul(Fe,pt)|0,k=k+Math.imul(Fe,gt)|0,_=_+Math.imul(De,_t)|0,f=f+Math.imul(De,yt)|0,f=f+Math.imul(je,_t)|0,k=k+Math.imul(je,yt)|0;var Ra=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ra>>>26)|0,Ra&=67108863,_=Math.imul(Je,at),f=Math.imul(Je,ct),f=f+Math.imul(Ye,at)|0,k=Math.imul(Ye,ct),_=_+Math.imul(Ze,ut)|0,f=f+Math.imul(Ze,lt)|0,f=f+Math.imul(Xe,ut)|0,k=k+Math.imul(Xe,lt)|0,_=_+Math.imul(We,dt)|0,f=f+Math.imul(We,ft)|0,f=f+Math.imul(He,dt)|0,k=k+Math.imul(He,ft)|0,_=_+Math.imul(Ve,ht)|0,f=f+Math.imul(Ve,mt)|0,f=f+Math.imul(Ge,ht)|0,k=k+Math.imul(Ge,mt)|0,_=_+Math.imul(Ke,pt)|0,f=f+Math.imul(Ke,gt)|0,f=f+Math.imul(ze,pt)|0,k=k+Math.imul(ze,gt)|0,_=_+Math.imul(Ne,_t)|0,f=f+Math.imul(Ne,yt)|0,f=f+Math.imul(Fe,_t)|0,k=k+Math.imul(Fe,yt)|0;var qa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(qa>>>26)|0,qa&=67108863,_=Math.imul(Je,ut),f=Math.imul(Je,lt),f=f+Math.imul(Ye,ut)|0,k=Math.imul(Ye,lt),_=_+Math.imul(Ze,dt)|0,f=f+Math.imul(Ze,ft)|0,f=f+Math.imul(Xe,dt)|0,k=k+Math.imul(Xe,ft)|0,_=_+Math.imul(We,ht)|0,f=f+Math.imul(We,mt)|0,f=f+Math.imul(He,ht)|0,k=k+Math.imul(He,mt)|0,_=_+Math.imul(Ve,pt)|0,f=f+Math.imul(Ve,gt)|0,f=f+Math.imul(Ge,pt)|0,k=k+Math.imul(Ge,gt)|0,_=_+Math.imul(Ke,_t)|0,f=f+Math.imul(Ke,yt)|0,f=f+Math.imul(ze,_t)|0,k=k+Math.imul(ze,yt)|0;var La=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(La>>>26)|0,La&=67108863,_=Math.imul(Je,dt),f=Math.imul(Je,ft),f=f+Math.imul(Ye,dt)|0,k=Math.imul(Ye,ft),_=_+Math.imul(Ze,ht)|0,f=f+Math.imul(Ze,mt)|0,f=f+Math.imul(Xe,ht)|0,k=k+Math.imul(Xe,mt)|0,_=_+Math.imul(We,pt)|0,f=f+Math.imul(We,gt)|0,f=f+Math.imul(He,pt)|0,k=k+Math.imul(He,gt)|0,_=_+Math.imul(Ve,_t)|0,f=f+Math.imul(Ve,yt)|0,f=f+Math.imul(Ge,_t)|0,k=k+Math.imul(Ge,yt)|0;var $a=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+($a>>>26)|0,$a&=67108863,_=Math.imul(Je,ht),f=Math.imul(Je,mt),f=f+Math.imul(Ye,ht)|0,k=Math.imul(Ye,mt),_=_+Math.imul(Ze,pt)|0,f=f+Math.imul(Ze,gt)|0,f=f+Math.imul(Xe,pt)|0,k=k+Math.imul(Xe,gt)|0,_=_+Math.imul(We,_t)|0,f=f+Math.imul(We,yt)|0,f=f+Math.imul(He,_t)|0,k=k+Math.imul(He,yt)|0;var Ua=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ua>>>26)|0,Ua&=67108863,_=Math.imul(Je,pt),f=Math.imul(Je,gt),f=f+Math.imul(Ye,pt)|0,k=Math.imul(Ye,gt),_=_+Math.imul(Ze,_t)|0,f=f+Math.imul(Ze,yt)|0,f=f+Math.imul(Xe,_t)|0,k=k+Math.imul(Xe,yt)|0;var Ka=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ka>>>26)|0,Ka&=67108863,_=Math.imul(Je,_t),f=Math.imul(Je,yt),f=f+Math.imul(Ye,_t)|0,k=Math.imul(Ye,yt);var za=(y+_|0)+((f&8191)<<13)|0;return y=(k+(f>>>13)|0)+(za>>>26)|0,za&=67108863,m[0]=Aa,m[1]=xa,m[2]=Ia,m[3]=Oa,m[4]=Pa,m[5]=Da,m[6]=Ea,m[7]=Ma,m[8]=Ba,m[9]=ja,m[10]=Na,m[11]=Fa,m[12]=Ra,m[13]=qa,m[14]=La,m[15]=$a,m[16]=Ua,m[17]=Ka,m[18]=za,y!==0&&(m[19]=y,g.length++),g};Math.imul||(O=P);function E(A,c,d){d.negative=c.negative^A.negative,d.length=A.length+c.length;for(var g=0,b=0,p=0;p<d.length-1;p++){var m=b;b=0;for(var y=g&67108863,_=Math.min(p,c.length-1),f=Math.max(0,p-A.length+1);f<=_;f++){var k=p-f,M=A.words[k]|0,j=c.words[f]|0,L=M*j,R=L&67108863;m=m+(L/67108864|0)|0,R=R+y|0,y=R&67108863,m=m+(R>>>26)|0,b+=m>>>26,m&=67108863}d.words[p]=y,g=m,m=b}return g!==0?d.words[p]=g:d.length--,d._strip()}function B(A,c,d){return E(A,c,d)}r.prototype.mulTo=function(c,d){var g,b=this.length+c.length;return this.length===10&&c.length===10?g=O(this,c,d):b<63?g=P(this,c,d):b<1024?g=E(this,c,d):g=B(this,c,d),g};function $(A,c){this.x=A,this.y=c}$.prototype.makeRBT=function(c){for(var d=new Array(c),g=r.prototype._countBits(c)-1,b=0;b<c;b++)d[b]=this.revBin(b,g,c);return d},$.prototype.revBin=function(c,d,g){if(c===0||c===g-1)return c;for(var b=0,p=0;p<d;p++)b|=(c&1)<<d-p-1,c>>=1;return b},$.prototype.permute=function(c,d,g,b,p,m){for(var y=0;y<m;y++)b[y]=d[c[y]],p[y]=g[c[y]]},$.prototype.transform=function(c,d,g,b,p,m){this.permute(m,c,d,g,b,p);for(var y=1;y<p;y<<=1)for(var _=y<<1,f=Math.cos(2*Math.PI/_),k=Math.sin(2*Math.PI/_),M=0;M<p;M+=_)for(var j=f,L=k,R=0;R<y;R++){var W=g[M+R],ne=b[M+R],me=g[M+R+y],ue=b[M+R+y],pe=j*me-L*ue;ue=j*ue+L*me,me=pe,g[M+R]=W+me,b[M+R]=ne+ue,g[M+R+y]=W-me,b[M+R+y]=ne-ue,R!==_&&(pe=f*j-k*L,L=f*L+k*j,j=pe)}},$.prototype.guessLen13b=function(c,d){var g=Math.max(d,c)|1,b=g&1,p=0;for(g=g/2|0;g;g=g>>>1)p++;return 1<<p+1+b},$.prototype.conjugate=function(c,d,g){if(!(g<=1))for(var b=0;b<g/2;b++){var p=c[b];c[b]=c[g-b-1],c[g-b-1]=p,p=d[b],d[b]=-d[g-b-1],d[g-b-1]=-p}},$.prototype.normalize13b=function(c,d){for(var g=0,b=0;b<d/2;b++){var p=Math.round(c[2*b+1]/d)*8192+Math.round(c[2*b]/d)+g;c[b]=p&67108863,p<67108864?g=0:g=p/67108864|0}return c},$.prototype.convert13b=function(c,d,g,b){for(var p=0,m=0;m<d;m++)p=p+(c[m]|0),g[2*m]=p&8191,p=p>>>13,g[2*m+1]=p&8191,p=p>>>13;for(m=2*d;m<b;++m)g[m]=0;n(p===0),n((p&-8192)===0)},$.prototype.stub=function(c){for(var d=new Array(c),g=0;g<c;g++)d[g]=0;return d},$.prototype.mulp=function(c,d,g){var b=2*this.guessLen13b(c.length,d.length),p=this.makeRBT(b),m=this.stub(b),y=new Array(b),_=new Array(b),f=new Array(b),k=new Array(b),M=new Array(b),j=new Array(b),L=g.words;L.length=b,this.convert13b(c.words,c.length,y,b),this.convert13b(d.words,d.length,k,b),this.transform(y,m,_,f,b,p),this.transform(k,m,M,j,b,p);for(var R=0;R<b;R++){var W=_[R]*M[R]-f[R]*j[R];f[R]=_[R]*j[R]+f[R]*M[R],_[R]=W}return this.conjugate(_,f,b),this.transform(_,f,L,m,b,p),this.conjugate(L,m,b),this.normalize13b(L,b),g.negative=c.negative^d.negative,g.length=c.length+d.length,g._strip()},r.prototype.mul=function(c){var d=new r(null);return d.words=new Array(this.length+c.length),this.mulTo(c,d)},r.prototype.mulf=function(c){var d=new r(null);return d.words=new Array(this.length+c.length),B(this,c,d)},r.prototype.imul=function(c){return this.clone().mulTo(c,this)},r.prototype.imuln=function(c){var d=c<0;d&&(c=-c),n(typeof c=="number"),n(c<67108864);for(var g=0,b=0;b<this.length;b++){var p=(this.words[b]|0)*c,m=(p&67108863)+(g&67108863);g>>=26,g+=p/67108864|0,g+=m>>>26,this.words[b]=m&67108863}return g!==0&&(this.words[b]=g,this.length++),d?this.ineg():this},r.prototype.muln=function(c){return this.clone().imuln(c)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(c){var d=x(c);if(d.length===0)return new r(1);for(var g=this,b=0;b<d.length&&d[b]===0;b++,g=g.sqr());if(++b<d.length)for(var p=g.sqr();b<d.length;b++,p=p.sqr())d[b]!==0&&(g=g.mul(p));return g},r.prototype.iushln=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26,b=67108863>>>26-d<<26-d,p;if(d!==0){var m=0;for(p=0;p<this.length;p++){var y=this.words[p]&b,_=(this.words[p]|0)-y<<d;this.words[p]=_|m,m=y>>>26-d}m&&(this.words[p]=m,this.length++)}if(g!==0){for(p=this.length-1;p>=0;p--)this.words[p+g]=this.words[p];for(p=0;p<g;p++)this.words[p]=0;this.length+=g}return this._strip()},r.prototype.ishln=function(c){return n(this.negative===0),this.iushln(c)},r.prototype.iushrn=function(c,d,g){n(typeof c=="number"&&c>=0);var b;d?b=(d-d%26)/26:b=0;var p=c%26,m=Math.min((c-p)/26,this.length),y=67108863^67108863>>>p<<p,_=g;if(b-=m,b=Math.max(0,b),_){for(var f=0;f<m;f++)_.words[f]=this.words[f];_.length=m}if(m!==0)if(this.length>m)for(this.length-=m,f=0;f<this.length;f++)this.words[f]=this.words[f+m];else this.words[0]=0,this.length=1;var k=0;for(f=this.length-1;f>=0&&(k!==0||f>=b);f--){var M=this.words[f]|0;this.words[f]=k<<26-p|M>>>p,k=M&y}return _&&k!==0&&(_.words[_.length++]=k),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(c,d,g){return n(this.negative===0),this.iushrn(c,d,g)},r.prototype.shln=function(c){return this.clone().ishln(c)},r.prototype.ushln=function(c){return this.clone().iushln(c)},r.prototype.shrn=function(c){return this.clone().ishrn(c)},r.prototype.ushrn=function(c){return this.clone().iushrn(c)},r.prototype.testn=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26,b=1<<d;if(this.length<=g)return!1;var p=this.words[g];return!!(p&b)},r.prototype.imaskn=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=g)return this;if(d!==0&&g++,this.length=Math.min(g,this.length),d!==0){var b=67108863^67108863>>>d<<d;this.words[this.length-1]&=b}return this._strip()},r.prototype.maskn=function(c){return this.clone().imaskn(c)},r.prototype.iaddn=function(c){return n(typeof c=="number"),n(c<67108864),c<0?this.isubn(-c):this.negative!==0?this.length===1&&(this.words[0]|0)<=c?(this.words[0]=c-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(c),this.negative=1,this):this._iaddn(c)},r.prototype._iaddn=function(c){this.words[0]+=c;for(var d=0;d<this.length&&this.words[d]>=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},r.prototype.isubn=function(c){if(n(typeof c=="number"),n(c<67108864),c<0)return this.iaddn(-c);if(this.negative!==0)return this.negative=0,this.iaddn(c),this.negative=1,this;if(this.words[0]-=c,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d<this.length&&this.words[d]<0;d++)this.words[d]+=67108864,this.words[d+1]-=1;return this._strip()},r.prototype.addn=function(c){return this.clone().iaddn(c)},r.prototype.subn=function(c){return this.clone().isubn(c)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(c,d,g){var b=c.length+g,p;this._expand(b);var m,y=0;for(p=0;p<c.length;p++){m=(this.words[p+g]|0)+y;var _=(c.words[p]|0)*d;m-=_&67108863,y=(m>>26)-(_/67108864|0),this.words[p+g]=m&67108863}for(;p<this.length-g;p++)m=(this.words[p+g]|0)+y,y=m>>26,this.words[p+g]=m&67108863;if(y===0)return this._strip();for(n(y===-1),y=0,p=0;p<this.length;p++)m=-(this.words[p]|0)+y,y=m>>26,this.words[p]=m&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(c,d){var g=this.length-c.length,b=this.clone(),p=c,m=p.words[p.length-1]|0,y=this._countBits(m);g=26-y,g!==0&&(p=p.ushln(g),b.iushln(g),m=p.words[p.length-1]|0);var _=b.length-p.length,f;if(d!=="mod"){f=new r(null),f.length=_+1,f.words=new Array(f.length);for(var k=0;k<f.length;k++)f.words[k]=0}var M=b.clone()._ishlnsubmul(p,1,_);M.negative===0&&(b=M,f&&(f.words[_]=1));for(var j=_-1;j>=0;j--){var L=(b.words[p.length+j]|0)*67108864+(b.words[p.length+j-1]|0);for(L=Math.min(L/m|0,67108863),b._ishlnsubmul(p,L,j);b.negative!==0;)L--,b.negative=0,b._ishlnsubmul(p,1,j),b.isZero()||(b.negative^=1);f&&(f.words[j]=L)}return f&&f._strip(),b._strip(),d!=="div"&&g!==0&&b.iushrn(g),{div:f||null,mod:b}},r.prototype.divmod=function(c,d,g){if(n(!c.isZero()),this.isZero())return{div:new r(0),mod:new r(0)};var b,p,m;return this.negative!==0&&c.negative===0?(m=this.neg().divmod(c,d),d!=="mod"&&(b=m.div.neg()),d!=="div"&&(p=m.mod.neg(),g&&p.negative!==0&&p.iadd(c)),{div:b,mod:p}):this.negative===0&&c.negative!==0?(m=this.divmod(c.neg(),d),d!=="mod"&&(b=m.div.neg()),{div:b,mod:m.mod}):this.negative&c.negative?(m=this.neg().divmod(c.neg(),d),d!=="div"&&(p=m.mod.neg(),g&&p.negative!==0&&p.isub(c)),{div:m.div,mod:p}):c.length>this.length||this.cmp(c)<0?{div:new r(0),mod:this}:c.length===1?d==="div"?{div:this.divn(c.words[0]),mod:null}:d==="mod"?{div:null,mod:new r(this.modrn(c.words[0]))}:{div:this.divn(c.words[0]),mod:new r(this.modrn(c.words[0]))}:this._wordDiv(c,d)},r.prototype.div=function(c){return this.divmod(c,"div",!1).div},r.prototype.mod=function(c){return this.divmod(c,"mod",!1).mod},r.prototype.umod=function(c){return this.divmod(c,"mod",!0).mod},r.prototype.divRound=function(c){var d=this.divmod(c);if(d.mod.isZero())return d.div;var g=d.div.negative!==0?d.mod.isub(c):d.mod,b=c.ushrn(1),p=c.andln(1),m=g.cmp(b);return m<0||p===1&&m===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},r.prototype.modrn=function(c){var d=c<0;d&&(c=-c),n(c<=67108863);for(var g=(1<<26)%c,b=0,p=this.length-1;p>=0;p--)b=(g*b+(this.words[p]|0))%c;return d?-b:b},r.prototype.modn=function(c){return this.modrn(c)},r.prototype.idivn=function(c){var d=c<0;d&&(c=-c),n(c<=67108863);for(var g=0,b=this.length-1;b>=0;b--){var p=(this.words[b]|0)+g*67108864;this.words[b]=p/c|0,g=p%c}return this._strip(),d?this.ineg():this},r.prototype.divn=function(c){return this.clone().idivn(c)},r.prototype.egcd=function(c){n(c.negative===0),n(!c.isZero());var d=this,g=c.clone();d.negative!==0?d=d.umod(c):d=d.clone();for(var b=new r(1),p=new r(0),m=new r(0),y=new r(1),_=0;d.isEven()&&g.isEven();)d.iushrn(1),g.iushrn(1),++_;for(var f=g.clone(),k=d.clone();!d.isZero();){for(var M=0,j=1;!(d.words[0]&j)&&M<26;++M,j<<=1);if(M>0)for(d.iushrn(M);M-- >0;)(b.isOdd()||p.isOdd())&&(b.iadd(f),p.isub(k)),b.iushrn(1),p.iushrn(1);for(var L=0,R=1;!(g.words[0]&R)&&L<26;++L,R<<=1);if(L>0)for(g.iushrn(L);L-- >0;)(m.isOdd()||y.isOdd())&&(m.iadd(f),y.isub(k)),m.iushrn(1),y.iushrn(1);d.cmp(g)>=0?(d.isub(g),b.isub(m),p.isub(y)):(g.isub(d),m.isub(b),y.isub(p))}return{a:m,b:y,gcd:g.iushln(_)}},r.prototype._invmp=function(c){n(c.negative===0),n(!c.isZero());var d=this,g=c.clone();d.negative!==0?d=d.umod(c):d=d.clone();for(var b=new r(1),p=new r(0),m=g.clone();d.cmpn(1)>0&&g.cmpn(1)>0;){for(var y=0,_=1;!(d.words[0]&_)&&y<26;++y,_<<=1);if(y>0)for(d.iushrn(y);y-- >0;)b.isOdd()&&b.iadd(m),b.iushrn(1);for(var f=0,k=1;!(g.words[0]&k)&&f<26;++f,k<<=1);if(f>0)for(g.iushrn(f);f-- >0;)p.isOdd()&&p.iadd(m),p.iushrn(1);d.cmp(g)>=0?(d.isub(g),b.isub(p)):(g.isub(d),p.isub(b))}var M;return d.cmpn(1)===0?M=b:M=p,M.cmpn(0)<0&&M.iadd(c),M},r.prototype.gcd=function(c){if(this.isZero())return c.abs();if(c.isZero())return this.abs();var d=this.clone(),g=c.clone();d.negative=0,g.negative=0;for(var b=0;d.isEven()&&g.isEven();b++)d.iushrn(1),g.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;g.isEven();)g.iushrn(1);var p=d.cmp(g);if(p<0){var m=d;d=g,g=m}else if(p===0||g.cmpn(1)===0)break;d.isub(g)}while(!0);return g.iushln(b)},r.prototype.invm=function(c){return this.egcd(c).a.umod(c)},r.prototype.isEven=function(){return(this.words[0]&1)===0},r.prototype.isOdd=function(){return(this.words[0]&1)===1},r.prototype.andln=function(c){return this.words[0]&c},r.prototype.bincn=function(c){n(typeof c=="number");var d=c%26,g=(c-d)/26,b=1<<d;if(this.length<=g)return this._expand(g+1),this.words[g]|=b,this;for(var p=b,m=g;p!==0&&m<this.length;m++){var y=this.words[m]|0;y+=p,p=y>>>26,y&=67108863,this.words[m]=y}return p!==0&&(this.words[m]=p,this.length++),this},r.prototype.isZero=function(){return this.length===1&&this.words[0]===0},r.prototype.cmpn=function(c){var d=c<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var g;if(this.length>1)g=1;else{d&&(c=-c),n(c<=67108863,"Number is too big");var b=this.words[0]|0;g=b===c?0:b<c?-1:1}return this.negative!==0?-g|0:g},r.prototype.cmp=function(c){if(this.negative!==0&&c.negative===0)return-1;if(this.negative===0&&c.negative!==0)return 1;var d=this.ucmp(c);return this.negative!==0?-d|0:d},r.prototype.ucmp=function(c){if(this.length>c.length)return 1;if(this.length<c.length)return-1;for(var d=0,g=this.length-1;g>=0;g--){var b=this.words[g]|0,p=c.words[g]|0;if(b!==p){b<p?d=-1:b>p&&(d=1);break}}return d},r.prototype.gtn=function(c){return this.cmpn(c)===1},r.prototype.gt=function(c){return this.cmp(c)===1},r.prototype.gten=function(c){return this.cmpn(c)>=0},r.prototype.gte=function(c){return this.cmp(c)>=0},r.prototype.ltn=function(c){return this.cmpn(c)===-1},r.prototype.lt=function(c){return this.cmp(c)===-1},r.prototype.lten=function(c){return this.cmpn(c)<=0},r.prototype.lte=function(c){return this.cmp(c)<=0},r.prototype.eqn=function(c){return this.cmpn(c)===0},r.prototype.eq=function(c){return this.cmp(c)===0},r.red=function(c){return new K(c)},r.prototype.toRed=function(c){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),c.convertTo(this)._forceRed(c)},r.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(c){return this.red=c,this},r.prototype.forceRed=function(c){return n(!this.red,"Already a number in reduction context"),this._forceRed(c)},r.prototype.redAdd=function(c){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,c)},r.prototype.redIAdd=function(c){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,c)},r.prototype.redSub=function(c){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,c)},r.prototype.redISub=function(c){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,c)},r.prototype.redShl=function(c){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,c)},r.prototype.redMul=function(c){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.mul(this,c)},r.prototype.redIMul=function(c){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.imul(this,c)},r.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},r.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},r.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},r.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},r.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},r.prototype.redPow=function(c){return n(this.red&&!c.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,c)};var Z={k256:null,p224:null,p192:null,p25519:null};function H(A,c){this.name=A,this.p=new r(c,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var c=new r(null);return c.words=new Array(Math.ceil(this.n/13)),c},H.prototype.ireduce=function(c){var d=c,g;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),g=d.bitLength();while(g>this.n);var b=g<this.n?-1:d.ucmp(this.p);return b===0?(d.words[0]=0,d.length=1):b>0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},H.prototype.split=function(c,d){c.iushrn(this.n,0,d)},H.prototype.imulK=function(c){return c.imul(this.k)};function te(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(te,H),te.prototype.split=function(c,d){for(var g=4194303,b=Math.min(c.length,9),p=0;p<b;p++)d.words[p]=c.words[p];if(d.length=b,c.length<=9){c.words[0]=0,c.length=1;return}var m=c.words[9];for(d.words[d.length++]=m&g,p=10;p<c.length;p++){var y=c.words[p]|0;c.words[p-10]=(y&g)<<4|m>>>22,m=y}m>>>=22,c.words[p-10]=m,m===0&&c.length>10?c.length-=10:c.length-=9},te.prototype.imulK=function(c){c.words[c.length]=0,c.words[c.length+1]=0,c.length+=2;for(var d=0,g=0;g<c.length;g++){var b=c.words[g]|0;d+=b*977,c.words[g]=d&67108863,d=b*64+(d/67108864|0)}return c.words[c.length-1]===0&&(c.length--,c.words[c.length-1]===0&&c.length--),c};function U(){H.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i(U,H);function V(){H.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(V,H);function F(){H.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(F,H),F.prototype.imulK=function(c){for(var d=0,g=0;g<c.length;g++){var b=(c.words[g]|0)*19+d,p=b&67108863;b>>>=26,c.words[g]=p,d=b}return d!==0&&(c.words[c.length++]=d),c},r._prime=function(c){if(Z[c])return Z[c];var d;if(c==="k256")d=new te;else if(c==="p224")d=new U;else if(c==="p192")d=new V;else if(c==="p25519")d=new F;else throw new Error("Unknown prime "+c);return Z[c]=d,d};function K(A){if(typeof A=="string"){var c=r._prime(A);this.m=c.p,this.prime=c}else n(A.gtn(1),"modulus must be greater than 1"),this.m=A,this.prime=null}K.prototype._verify1=function(c){n(c.negative===0,"red works only with positives"),n(c.red,"red works only with red numbers")},K.prototype._verify2=function(c,d){n((c.negative|d.negative)===0,"red works only with positives"),n(c.red&&c.red===d.red,"red works only with red numbers")},K.prototype.imod=function(c){return this.prime?this.prime.ireduce(c)._forceRed(this):(l(c,c.umod(this.m)._forceRed(this)),c)},K.prototype.neg=function(c){return c.isZero()?c.clone():this.m.sub(c)._forceRed(this)},K.prototype.add=function(c,d){this._verify2(c,d);var g=c.add(d);return g.cmp(this.m)>=0&&g.isub(this.m),g._forceRed(this)},K.prototype.iadd=function(c,d){this._verify2(c,d);var g=c.iadd(d);return g.cmp(this.m)>=0&&g.isub(this.m),g},K.prototype.sub=function(c,d){this._verify2(c,d);var g=c.sub(d);return g.cmpn(0)<0&&g.iadd(this.m),g._forceRed(this)},K.prototype.isub=function(c,d){this._verify2(c,d);var g=c.isub(d);return g.cmpn(0)<0&&g.iadd(this.m),g},K.prototype.shl=function(c,d){return this._verify1(c),this.imod(c.ushln(d))},K.prototype.imul=function(c,d){return this._verify2(c,d),this.imod(c.imul(d))},K.prototype.mul=function(c,d){return this._verify2(c,d),this.imod(c.mul(d))},K.prototype.isqr=function(c){return this.imul(c,c.clone())},K.prototype.sqr=function(c){return this.mul(c,c)},K.prototype.sqrt=function(c){if(c.isZero())return c.clone();var d=this.m.andln(3);if(n(d%2===1),d===3){var g=this.m.add(new r(1)).iushrn(2);return this.pow(c,g)}for(var b=this.m.subn(1),p=0;!b.isZero()&&b.andln(1)===0;)p++,b.iushrn(1);n(!b.isZero());var m=new r(1).toRed(this),y=m.redNeg(),_=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new r(2*f*f).toRed(this);this.pow(f,_).cmp(y)!==0;)f.redIAdd(y);for(var k=this.pow(f,b),M=this.pow(c,b.addn(1).iushrn(1)),j=this.pow(c,b),L=p;j.cmp(m)!==0;){for(var R=j,W=0;R.cmp(m)!==0;W++)R=R.redSqr();n(W<L);var ne=this.pow(k,new r(1).iushln(L-W-1));M=M.redMul(ne),k=ne.redSqr(),j=j.redMul(k),L=W}return M},K.prototype.invm=function(c){var d=c._invmp(this.m);return d.negative!==0?(d.negative=0,this.imod(d).redNeg()):this.imod(d)},K.prototype.pow=function(c,d){if(d.isZero())return new r(1).toRed(this);if(d.cmpn(1)===0)return c.clone();var g=4,b=new Array(1<<g);b[0]=new r(1).toRed(this),b[1]=c;for(var p=2;p<b.length;p++)b[p]=this.mul(b[p-1],c);var m=b[0],y=0,_=0,f=d.bitLength()%26;for(f===0&&(f=26),p=d.length-1;p>=0;p--){for(var k=d.words[p],M=f-1;M>=0;M--){var j=k>>M&1;if(m!==b[0]&&(m=this.sqr(m)),j===0&&y===0){_=0;continue}y<<=1,y|=j,_++,!(_!==g&&(p!==0||M!==0))&&(m=this.mul(m,b[y]),_=0,y=0)}f=26}return m},K.prototype.convertTo=function(c){var d=c.umod(this.m);return d===c?d.clone():d},K.prototype.convertFrom=function(c){var d=c.clone();return d.red=null,d},r.mont=function(c){return new C(c)};function C(A){K.call(this,A),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new r(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(C,K),C.prototype.convertTo=function(c){return this.imod(c.ushln(this.shift))},C.prototype.convertFrom=function(c){var d=this.imod(c.mul(this.rinv));return d.red=null,d},C.prototype.imul=function(c,d){if(c.isZero()||d.isZero())return c.words[0]=0,c.length=1,c;var g=c.imul(d),b=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=g.isub(b).iushrn(this.shift),m=p;return p.cmp(this.m)>=0?m=p.isub(this.m):p.cmpn(0)<0&&(m=p.iadd(this.m)),m._forceRed(this)},C.prototype.mul=function(c,d){if(c.isZero()||d.isZero())return new r(0)._forceRed(this);var g=c.mul(d),b=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=g.isub(b).iushrn(this.shift),m=p;return p.cmp(this.m)>=0?m=p.isub(this.m):p.cmpn(0)<0&&(m=p.iadd(this.m)),m._forceRed(this)},C.prototype.invm=function(c){var d=this.imod(c._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(typeof Wa>"u"||Wa,Bl)});var _d={};wl(_d,{__addDisposableResource:()=>pd,__assign:()=>Ho,__asyncDelegator:()=>ad,__asyncGenerator:()=>sd,__asyncValues:()=>cd,__await:()=>Hi,__awaiter:()=>ed,__classPrivateFieldGet:()=>fd,__classPrivateFieldIn:()=>md,__classPrivateFieldSet:()=>hd,__createBinding:()=>Xo,__decorate:()=>Jl,__disposeResources:()=>gd,__esDecorate:()=>B_,__exportStar:()=>nd,__extends:()=>Zl,__generator:()=>td,__importDefault:()=>dd,__importStar:()=>ld,__makeTemplateObject:()=>ud,__metadata:()=>Ql,__param:()=>Yl,__propKey:()=>N_,__read:()=>ic,__rest:()=>Xl,__runInitializers:()=>j_,__setFunctionName:()=>F_,__spread:()=>id,__spreadArray:()=>od,__spreadArrays:()=>rd,__values:()=>Zo,default:()=>L_});function Zl(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");nc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Xl(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function Jl(t,e,n,i){var r=arguments.length,o=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,n):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,i);else for(var a=t.length-1;a>=0;a--)(s=t[a])&&(o=(r<3?s(o):r>3?s(e,n,o):s(e,n))||o);return r>3&&o&&Object.defineProperty(e,n,o),o}function Yl(t,e){return function(n,i){e(n,i,t)}}function B_(t,e,n,i,r,o){function s(O){if(O!==void 0&&typeof O!="function")throw new TypeError("Function expected");return O}for(var a=i.kind,u=a==="getter"?"get":a==="setter"?"set":"value",l=!e&&t?i.static?t:t.prototype:null,h=e||(l?Object.getOwnPropertyDescriptor(l,i.name):{}),w,v=!1,T=n.length-1;T>=0;T--){var I={};for(var x in i)I[x]=x==="access"?{}:i[x];for(var x in i.access)I.access[x]=i.access[x];I.addInitializer=function(O){if(v)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(O||null))};var P=(0,n[T])(a==="accessor"?{get:h.get,set:h.set}:h[u],I);if(a==="accessor"){if(P===void 0)continue;if(P===null||typeof P!="object")throw new TypeError("Object expected");(w=s(P.get))&&(h.get=w),(w=s(P.set))&&(h.set=w),(w=s(P.init))&&r.unshift(w)}else(w=s(P))&&(a==="field"?r.unshift(w):h[u]=w)}l&&Object.defineProperty(l,i.name,h),v=!0}function j_(t,e,n){for(var i=arguments.length>2,r=0;r<e.length;r++)n=i?e[r].call(t,n):e[r].call(t);return i?n:void 0}function N_(t){return typeof t=="symbol"?t:"".concat(t)}function F_(t,e,n){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function Ql(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ed(t,e,n,i){function r(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(h){try{l(i.next(h))}catch(w){s(w)}}function u(h){try{l(i.throw(h))}catch(w){s(w)}}function l(h){h.done?o(h.value):r(h.value).then(a,u)}l((i=i.apply(t,e||[])).next())})}function td(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},i,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(l){return function(h){return u([l,h])}}function u(l){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,l[0]&&(n=0)),n;)try{if(i=1,r&&(o=l[0]&2?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,r=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){n.label=l[1];break}if(l[0]===6&&n.label<o[1]){n.label=o[1],o=l;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(l);break}o[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(h){l=[6,h],r=0}finally{i=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function nd(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Xo(e,t,n)}function Zo(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ic(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var i=n.call(t),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o}function id(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ic(arguments[e]));return t}function rd(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var i=Array(t),r=0,e=0;e<n;e++)for(var o=arguments[e],s=0,a=o.length;s<a;s++,r++)i[r]=o[s];return i}function od(t,e,n){if(n||arguments.length===2)for(var i=0,r=e.length,o;i<r;i++)(o||!(i in e))&&(o||(o=Array.prototype.slice.call(e,0,i)),o[i]=e[i]);return t.concat(o||Array.prototype.slice.call(e))}function Hi(t){return this instanceof Hi?(this.v=t,this):new Hi(t)}function sd(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(v){i[v]&&(r[v]=function(T){return new Promise(function(I,x){o.push([v,T,I,x])>1||a(v,T)})})}function a(v,T){try{u(i[v](T))}catch(I){w(o[0][3],I)}}function u(v){v.value instanceof Hi?Promise.resolve(v.value.v).then(l,h):w(o[0][2],v)}function l(v){a("next",v)}function h(v){a("throw",v)}function w(v,T){v(T),o.shift(),o.length&&a(o[0][0],o[0][1])}}function ad(t){var e,n;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,o){e[r]=t[r]?function(s){return(n=!n)?{value:Hi(t[r](s)),done:!1}:o?o(s):s}:o}}function cd(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Zo=="function"?Zo(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(o){n[o]=t[o]&&function(s){return new Promise(function(a,u){s=t[o](s),r(a,u,s.done,s.value)})}}function r(o,s,a,u){Promise.resolve(u).then(function(l){o({value:l,done:a})},s)}}function ud(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ld(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Xo(e,t,n);return R_(e,t),e}function dd(t){return t&&t.__esModule?t:{default:t}}function fd(t,e,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(t):i?i.value:e.get(t)}function hd(t,e,n,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(t,n):r?r.value=n:e.set(t,n),n}function md(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 pd(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose]}if(typeof i!="function")throw new TypeError("Object not disposable.");t.stack.push({value:e,dispose:i,async:n})}else n&&t.stack.push({async:!0});return e}function gd(t){function e(i){t.error=t.hasError?new q_(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}function n(){for(;t.stack.length;){var i=t.stack.pop();try{var r=i.dispose&&i.dispose.call(i.value);if(i.async)return Promise.resolve(r).then(n,function(o){return e(o),n()})}catch(o){e(o)}}if(t.hasError)throw t.error}return n()}var nc,Ho,Xo,R_,q_,L_,yd=Og(()=>{"use strict";nc=function(t,e){return nc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},nc(t,e)};Ho=function(){return Ho=Object.assign||function(e){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Ho.apply(this,arguments)};Xo=Object.create?function(t,e,n,i){i===void 0&&(i=n);var r=Object.getOwnPropertyDescriptor(e,n);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,r)}:function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]};R_=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};q_=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var i=new Error(n);return i.name="SuppressedError",i.error=t,i.suppressed=e,i};L_={__extends:Zl,__assign:Ho,__rest:Xl,__decorate:Jl,__param:Yl,__metadata:Ql,__awaiter:ed,__generator:td,__createBinding:Xo,__exportStar:nd,__values:Zo,__read:ic,__spread:id,__spreadArrays:rd,__spreadArray:od,__await:Hi,__asyncGenerator:sd,__asyncDelegator:ad,__asyncValues:cd,__makeTemplateObject:ud,__importStar:ld,__importDefault:dd,__classPrivateFieldGet:fd,__classPrivateFieldSet:hd,__classPrivateFieldIn:md,__addDisposableResource:pd,__disposeResources:gd}});var bd=yi((Jo,wd)=>{"use strict";(function(t,e){typeof Jo=="object"&&typeof wd<"u"?e(Jo,(yd(),vl(_d))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(Jo,function(t,e){"use strict";var n=function(){function p(m,y,_){_===void 0&&(_=0),this.startVertex=m,this.endVertex=y,this.weight=_}return p.prototype.getKey=function(){var m=this.startVertex.getKey(),y=this.endVertex.getKey();return m+"_"+y},p.prototype.reverse=function(){var m=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=m,this},p.prototype.clone=function(){return new p(this.startVertex,this.endVertex,this.weight)},p.prototype.toString=function(){return this.getKey()},p}();function i(p,m,y){if(y===void 0&&(y="cc-graph"),!p)throw new Error((y?"["+y+"]":"")+" Invariant failed: "+m)}function r(p,m){m===void 0&&(m=!0);var y=typeof p<"u"&&p!==null;return m?y&&p!=="undefined"&&p!=="null":y}var o=function(){function p(m){i(r(m),"Graph vertex must have a value"),this.value=m,this.edges=new Map}return p.prototype.addEdge=function(m){return this.edges.set(m.getKey(),m),this},p.prototype.deleteEdge=function(m){this.edges.delete(m.getKey())},p.prototype.getNeighbors=function(){var m=this,y=this.getEdges(),_=function(f){return f.startVertex===m?f.endVertex:f.startVertex};return y.map(_)},p.prototype.getEdges=function(){return Array.from(this.edges.values())},p.prototype.getDegree=function(){return this.getEdges().length},p.prototype.hasEdge=function(m){var y=this.getEdges().find(function(_){return _===m});return!!y},p.prototype.hasNeighbor=function(m){var y=this.getEdges().find(function(_){return _.startVertex===m||_.endVertex===m});return!!y},p.prototype.findEdge=function(m){var y=function(f){return f.startVertex===m||f.endVertex===m},_=this.getEdges().find(y);return _||null},p.prototype.getKey=function(){return this.value},p.prototype.deleteAllEdges=function(){var m=this;return this.getEdges().forEach(function(y){return m.deleteEdge(y)}),this},p.prototype.toString=function(m){return m?m(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 a=function(){function p(m){this.compare=m||p.defaultCompareFunction}return p.defaultCompareFunction=function(m,y){return m===y?s.EQUAL:m<y?s.LESS:s.GREATER},p.prototype.equal=function(m,y){return this.compare(m,y)===s.EQUAL},p.prototype.lessThan=function(m,y){return this.compare(m,y)===s.LESS},p.prototype.greaterThan=function(m,y){return this.compare(m,y)===s.GREATER},p.prototype.lessThanOrEqual=function(m,y){return this.lessThan(m,y)||this.equal(m,y)},p.prototype.greaterThanOrEqual=function(m,y){return this.greaterThan(m,y)||this.equal(m,y)},p.prototype.reverse=function(){var m=this.compare;this.compare=function(y,_){return m(_,y)}},p}(),u=function(){function p(m){this.value=m,this.next=null}return p}(),l=function(){function p(m){this.value=m,this.next=null,this.prev=null}return p}();var h=function(p,m){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,_){y.__proto__=_}||function(y,_){for(var f in _)_.hasOwnProperty(f)&&(y[f]=_[f])},h(p,m)};function w(p,m){h(p,m);function y(){this.constructor=p}p.prototype=m===null?Object.create(m):(y.prototype=m.prototype,new y)}function v(p,m){var y={label:0,sent:function(){if(k[0]&1)throw k[1];return k[1]},trys:[],ops:[]},_,f,k,M;return M={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(M[Symbol.iterator]=function(){return this}),M;function j(R){return function(W){return L([R,W])}}function L(R){if(_)throw new TypeError("Generator is already executing.");for(;y;)try{if(_=1,f&&(k=R[0]&2?f.return:R[0]?f.throw||((k=f.return)&&k.call(f),0):f.next)&&!(k=k.call(f,R[1])).done)return k;switch(f=0,k&&(R=[R[0]&2,k.value]),R[0]){case 0:case 1:k=R;break;case 4:return y.label++,{value:R[1],done:!1};case 5:y.label++,f=R[1],R=[0];continue;case 7:R=y.ops.pop(),y.trys.pop();continue;default:if(k=y.trys,!(k=k.length>0&&k[k.length-1])&&(R[0]===6||R[0]===2)){y=0;continue}if(R[0]===3&&(!k||R[1]>k[0]&&R[1]<k[3])){y.label=R[1];break}if(R[0]===6&&y.label<k[1]){y.label=k[1],k=R;break}if(k&&y.label<k[2]){y.label=k[2],y.ops.push(R);break}k[2]&&y.ops.pop(),y.trys.pop();continue}R=m.call(p,y)}catch(W){R=[6,W],f=0}finally{_=k=0}if(R[0]&5)throw R[1];return{value:R[0]?R[1]:void 0,done:!0}}}function T(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function I(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(T(arguments[m]));return p}var x="obfuse error occur";function P(p,m){if(!p)throw new Error("[linked-list] "+(m||x))}var O=-1,E=function(){function p(){for(var m=this,y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];this._head=null,this._tail=null,this._length=0,this.compare=new a,y.length>0&&y.forEach(function(f){m.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 m=!1,y=1;if(!this._head)return 0;for(var _=this._head,f=this._head;f.next&&f.next.next;)if(f=f.next.next,_=_.next,_===f){m=!0;break}if(m){for(f=f.next;_!==f;)y++,f=f.next;return y}else return 0},enumerable:!0,configurable:!0}),p.prototype.getNode=function(m){var y=this._length;P(y>0&&m>=0&&m<y,"[linked-list] index "+m+" out of scope of list, which length is "+y);for(var _=this._head,f=0;f<m;)_=_.next,f++;return _},p.prototype.get=function(m){var y=this.getNode(m);return y?y.value:null},p.prototype.find=function(m){var y=m.value,_=m.callback;if(!this._head)return null;for(var f=this._head;f;){if(_&&_(f.value)||y!==void 0&&this.compare.equal(f.value,y))return f;f=f.next}return null},p.prototype.indexOf=function(m){if(!this._head)return O;for(var y=this._head,_=-1;y.next;){if(_++,this.compare.equal(y.value,m))return _;y=y.next}return y===this._tail&&this.compare.equal(y.value,m)&&(_+=1),_},p.prototype.first=function(m){P(m>=0,"[linked-list] param 'num' ("+m+") should not less than 0");for(var y=this.iterator(),_=[],f=Math.min(m,this.length),k=0;k<f;k++){var M=y.next();_.push(M.value)}return _},p.prototype.toArray=function(){return I(this)},p.prototype.isEmpty=function(){return this._head===null},p.prototype.iterator=function(){var m;return v(this,function(y){switch(y.label){case 0:m=this._head,y.label=1;case 1:return m?[4,m.value]:[3,3];case 2:return y.sent(),m=m.next,[3,1];case 3:return[2]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p}(),B=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return p.apply(this,I(y))||this}return m.prototype.append=function(y){var _=new u(y);return this._tail?(this._tail.next=_,this._tail=_):this._head=this._tail=_,this._length++,!0},m.prototype.prepend=function(y){var _=new u(y);return this._head?(_.next=this._head,this._head=_):this._head=this._tail=_,this._length++,!0},m.prototype.remove=function(y){var _=this._head;if(_){if(this.compare.equal(_.value,y))return _.next?(this._head=_.next,_.next=null):this._head=this._tail=null,this._length--,y;for(var f=_;;){if(this.compare.equal(_.value,y))return _.next?f.next=_.next:(this._tail=f,this._tail.next=null),_.next=null,this._length--,y;if(_.next)f=_,_=_.next;else return}}},m.prototype.removeHead=function(){var y=this._head;if(y)return this._head.next?(this._head=y.next,y.next=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.removeTail=function(){var y=this._tail;if(y){if(!this._head.next)this._head=null,this._tail=null;else{for(var _=this._head;_.next!==y;)_=_.next;_.next=null,this._tail=_}return this._length--,y.value}},m.prototype.reverse=function(){if(this._head){var y=this._head,_=null,f;for(this._tail=this._head;y!==null;)f=y.next,y.next=_,_=y,y=f;this._head=_}},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(E),$=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.iterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,y===this._head&&(y=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=p.prototype[y].apply(this,_);return this.cyclization(),k},m.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},m.prototype.append=function(y){return this.mapToNormalListFn("append",y)},m.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},m.prototype.find=function(y){return this.mapToNormalListFn("find",y)},m.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},m.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(y){P(y>=0,"[linked-list] param 'num' ("+y+") should not less than 0");for(var _=this.circleIterator(),f=[],k=0;k<y;k++){var M=_.next();f.push(M.value)}return f},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(B),Z=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},m.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}($),H=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return p.apply(this,I(y))||this}return m.prototype.append=function(y){var _=new l(y);return this._tail?(this._tail.next=_,_.prev=this._tail,this._tail=_):this._head=this._tail=_,this._length++,!0},m.prototype.prepend=function(y){var _=new l(y);return this._head?(_.next=this._head,this._head.prev=_,this._head=_):this._head=this._tail=_,this._length++,!0},m.prototype.remove=function(y){var _=this._head;if(_){if(this.compare.equal(_.value,y))return _.next?(this._head=_.next,this._head.prev=null,_.next=_.prev=null):this._head=this._tail=null,this._length--,y;for(;;){if(this.compare.equal(_.value,y))return _.next?(_.prev.next=_.next,_.next.prev=_.prev,_.next=_.prev=null):(_.prev.next=null,this._tail=_.prev,_.next=_.prev=null),this._length--,_.value;if(_.next)_=_.next;else return}}},m.prototype.removeHead=function(){var y=this._head;if(y)return this._head.next?(y.next.prev=null,this._head=y.next,y.next=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.removeTail=function(){var y=this._tail;if(y)return this._head.next?(y.prev.next=null,this._tail=y.prev,y.next=y.prev=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.reverse=function(){if(this._head){var y=this._head,_=null,f;for(this._tail=this._head;y!==null;)f=y.next,y.next=_,y.prev=f,_=y,y=f;this._head=_}},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(E),te=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.iterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,y===this._head&&(y=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=p.prototype[y].apply(this,_);return this.cyclization(),k},m.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},m.prototype.append=function(y){return this.mapToNormalListFn("append",y)},m.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},m.prototype.find=function(y){return this.mapToNormalListFn("find",y)},m.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},m.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(y){P(y>=0,"[linked-list] param 'num' ("+y+") should not less than 0");for(var _=this.circleIterator(),f=[],k=0;k<y;k++){var M=_.next();f.push(M.value)}return f},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(H),U=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},m.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(te);function V(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function F(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(V(arguments[m]));return p}var K=function(){function p(){for(var m=[],y=0;y<arguments.length;y++)m[y]=arguments[y];this.queue=new(B.bind.apply(B,F([void 0],m)))}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(m){return this.queue.append(m)},p.prototype.dequeue=function(){var m=this.queue.removeHead();return typeof m<"u"?m:void 0},p.prototype.toArray=function(){return this.queue.toArray()},p}();function C(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function A(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(C(arguments[m]));return p}var c=function(){function p(){for(var m=[],y=0;y<arguments.length;y++)m[y]=arguments[y];this.stack=new(B.bind.apply(B,A([void 0],m)))}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(m){return this.stack.append(m)},p.prototype.pop=function(){var m=this.stack.removeTail();return typeof m<"u"?m:void 0},p.prototype.popBottom=function(){var m=this.stack.removeHead();return typeof m<"u"?m:void 0},p.prototype.toArray=function(){return this.stack.toArray()},p}();function d(p,m,y,_){if(p){m.push(p),_.set(p.getKey(),!0);var f=p.getNeighbors().filter(function(k){return!_.get(k.getKey())});y.push(f)}}function g(p,m,y){var _=p.pop();_&&y.set(_.getKey(),!1),m.pop()}var b=function(){function p(m){m===void 0&&(m=!1),this.vertices={},this.edges={},this.isDirected=m}return p.prototype.addVertex=function(m){return this.vertices[m.getKey()]=m,this},p.prototype.getVertexByKey=function(m){return this.vertices[m]},p.prototype.getNeighbors=function(m){return m.getNeighbors()},p.prototype.getAllVertices=function(){return Object.values(this.vertices)},p.prototype.getAllEdges=function(){return Object.values(this.edges)},p.prototype.addEdge=function(m,y){if(y===void 0&&(y=!1),this.edges[m.getKey()]){if(y)return this;i(!1,"Edge has already been added before")}var _=this.getVertexByKey(m.startVertex.getKey()),f=this.getVertexByKey(m.endVertex.getKey());if(_||(this.addVertex(m.startVertex),_=this.getVertexByKey(m.startVertex.getKey())),f||(this.addVertex(m.endVertex),f=this.getVertexByKey(m.endVertex.getKey())),this.edges[m.getKey()]=m,this.isDirected)_.addEdge(m);else{_.addEdge(m);var k=m.clone();f.addEdge(k.reverse())}return this},p.prototype.deleteEdge=function(m,y){if(y===void 0&&(y=!1),!this.edges[m.getKey()]){if(y)return this;i(!1,"Edge not found in graph")}delete this.edges[m.getKey()];var _=this.getVertexByKey(m.startVertex.getKey()),f=this.getVertexByKey(m.endVertex.getKey());return _.deleteEdge(m),f.deleteEdge(m),this},p.prototype.findEdge=function(m,y){var _=this.getVertexByKey(m.getKey());return _?_.findEdge(y):null},p.prototype.getWeight=function(){return this.getAllEdges().reduce(function(m,y){return m+y.weight},0)},p.prototype.reverse=function(){var m=this;return this.getAllEdges().forEach(function(y){m.deleteEdge(y),y.reverse(),m.addEdge(y)}),this},p.prototype.getVerticesIndices=function(){var m={};return this.getAllVertices().forEach(function(y,_){m[y.getKey()]=_}),m},p.prototype.getAdjacencyMatrix=function(){var m=this,y=this.getAllVertices(),_=this.getVerticesIndices(),f=Array(y.length).fill(null).map(function(){return Array(y.length).fill(1/0)});return y.forEach(function(k,M){k.getNeighbors().forEach(function(j){var L=_[j.getKey()],R=m.findEdge(k,j);R&&(f[M][L]=R.weight)})}),f},p.prototype.toString=function(){return Object.keys(this.vertices).toString()},p.prototype.bfs=function(m){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new K,_.enqueue(m),k.label=1;case 1:return _.isEmpty()?[3,4]:(f=_.dequeue(),f&&!y.has(f.getKey())?[4,f]:[3,3]);case 2:k.sent(),y.set(f.getKey(),f),f.getNeighbors().forEach(function(M){return _.enqueue(M)}),k.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.dfs=function(m){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new c,_.push(m),k.label=1;case 1:return _.isEmpty()?[3,4]:(f=_.pop(),f&&!y.has(f.getKey())?[4,f]:[3,3]);case 2:k.sent(),y.set(f.getKey(),f),f.getNeighbors().forEach(function(M){return _.push(M)}),k.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.findAllPath=function(m,y){var _,f,k,M,j,L,R;return e.__generator(this,function(W){switch(W.label){case 0:return _=[],m!==y?[3,2]:(_.push(m),[4,_]);case 1:return W.sent(),[2];case 2:f=new Map,k=new c,M=new c,d(m,k,M,f),W.label=3;case 3:if(k.isEmpty())return[3,6];if(j=M.pop(),j&&j.length)L=j.shift(),M.push(j),L&&d(L,k,M,f);else return M.push(j),g(k,M,f),[3,3];return R=k.peek,R!==y?[3,5]:[4,k.toArray()];case 4:W.sent(),g(k,M,f),W.label=5;case 5:return[3,3];case 6:return[2]}})},p}();t.GraphEdge=n,t.GraphVertex=o,t.Graph=b,Object.defineProperty(t,"__esModule",{value:!0})})});var qh=yi((bu,vu)=>{"use strict";(function(t,e){typeof bu=="object"&&typeof vu<"u"?vu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(bu,function(){"use strict";var t=Math.imul,e=Math.clz32;function n(U){"@babel/helpers - typeof";return n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(V){return typeof V}:function(V){return V&&typeof Symbol=="function"&&V.constructor===Symbol&&V!==Symbol.prototype?"symbol":typeof V},n(U)}function i(U,V){if(!(U instanceof V))throw new TypeError("Cannot call a class as a function")}function r(U,V){for(var F,K=0;K<V.length;K++)F=V[K],F.enumerable=F.enumerable||!1,F.configurable=!0,"value"in F&&(F.writable=!0),Object.defineProperty(U,F.key,F)}function o(U,V,F){return V&&r(U.prototype,V),F&&r(U,F),Object.defineProperty(U,"prototype",{writable:!1}),U}function s(U,V){if(typeof V!="function"&&V!==null)throw new TypeError("Super expression must either be null or a function");U.prototype=Object.create(V&&V.prototype,{constructor:{value:U,writable:!0,configurable:!0}}),Object.defineProperty(U,"prototype",{writable:!1}),V&&u(U,V)}function a(U){return a=Object.setPrototypeOf?Object.getPrototypeOf:function(V){return V.__proto__||Object.getPrototypeOf(V)},a(U)}function u(U,V){return u=Object.setPrototypeOf||function(F,K){return F.__proto__=K,F},u(U,V)}function l(){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 h(){return h=l()?Reflect.construct:function(U,V,F){var K=[null];K.push.apply(K,V);var C=Function.bind.apply(U,K),A=new C;return F&&u(A,F.prototype),A},h.apply(null,arguments)}function w(U){return Function.toString.call(U).indexOf("[native code]")!==-1}function v(U){var V=typeof Map=="function"?new Map:void 0;return v=function(F){function K(){return h(F,arguments,a(this).constructor)}if(F===null||!w(F))return F;if(typeof F!="function")throw new TypeError("Super expression must either be null or a function");if(typeof V<"u"){if(V.has(F))return V.get(F);V.set(F,K)}return K.prototype=Object.create(F.prototype,{constructor:{value:K,enumerable:!1,writable:!0,configurable:!0}}),u(K,F)},v(U)}function T(U){if(U===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return U}function I(U,V){if(V&&(typeof V=="object"||typeof V=="function"))return V;if(V!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return T(U)}function x(U){var V=l();return function(){var F,K=a(U);if(V){var C=a(this).constructor;F=Reflect.construct(K,arguments,C)}else F=K.apply(this,arguments);return I(this,F)}}function P(U,V){return O(U)||E(U,V)||B(U,V)||Z()}function O(U){if(Array.isArray(U))return U}function E(U,V){var F=U==null?null:typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(F!=null){var K,C,A=[],c=!0,d=!1;try{for(F=F.call(U);!(c=(K=F.next()).done)&&(A.push(K.value),!(V&&A.length===V));c=!0);}catch(g){d=!0,C=g}finally{try{c||F.return==null||F.return()}finally{if(d)throw C}}return A}}function B(U,V){if(U){if(typeof U=="string")return $(U,V);var F=Object.prototype.toString.call(U).slice(8,-1);return F==="Object"&&U.constructor&&(F=U.constructor.name),F==="Map"||F==="Set"?Array.from(U):F==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(F)?$(U,V):void 0}}function $(U,V){(V==null||V>U.length)&&(V=U.length);for(var F=0,K=Array(V);F<V;F++)K[F]=U[F];return K}function Z(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1
+ "use strict";var Sg=Object.create;var Lo=Object.defineProperty;var Ag=Object.getOwnPropertyDescriptor;var xg=Object.getOwnPropertyNames;var Ig=Object.getPrototypeOf,Og=Object.prototype.hasOwnProperty;var Pg=(t,e)=>()=>(t&&(e=t(t=0)),e);var yi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),bl=(t,e)=>{for(var n in e)Lo(t,n,{get:e[n],enumerable:!0})},vl=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xg(e))!Og.call(t,r)&&r!==n&&Lo(t,r,{get:()=>e[r],enumerable:!(i=Ag(e,r))||i.enumerable});return t};var ge=(t,e,n)=>(n=t!=null?Sg(Ig(t)):{},vl(e||!t||!t.__esModule?Lo(n,"default",{value:t,enumerable:!0}):n,t)),kl=t=>vl(Lo({},"__esModule",{value:!0}),t);var Sl=yi((ck,Cl)=>{"use strict";Cl.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var xl=yi((uk,Al)=>{"use strict";var Wa=Sl();Al.exports=(t,e={})=>{if(!Wa(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:n}=e,i=[],r=[],o=a=>{let u=i.indexOf(a);if(u!==-1)return r[u];let l=[];return i.push(a),r.push(l),l.push(...a.map(h=>Array.isArray(h)?o(h):Wa(h)?s(h):h)),l},s=a=>{let u=i.indexOf(a);if(u!==-1)return r[u];let l={},h=Object.keys(a).sort(e.compare);i.push(a),r.push(l);for(let w of h){let v=a[w],T;n&&Array.isArray(v)?T=o(v):T=n&&Wa(v)?s(v):v,Object.defineProperty(l,w,{...Object.getOwnPropertyDescriptor(a,w),value:T})}return l};return Array.isArray(t)?n?o(t):t.slice():s(t)}});var Pl=yi((lk,Ol)=>{"use strict";var Dg=Object.prototype.toString;Ol.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var n=typeof e;if(n==="boolean")return"boolean";if(n==="string")return"string";if(n==="number")return"number";if(n==="symbol")return"symbol";if(n==="function")return Ng(e)?"generatorfunction":"function";if(Eg(e))return"array";if(qg(e))return"buffer";if(Rg(e))return"arguments";if(Bg(e))return"date";if(Mg(e))return"error";if(jg(e))return"regexp";switch(Il(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(Fg(e))return"generator";switch(n=Dg.call(e),n){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 n.slice(8,-1).toLowerCase().replace(/\s/g,"")};function Il(t){return typeof t.constructor=="function"?t.constructor.name:null}function Eg(t){return Array.isArray?Array.isArray(t):t instanceof Array}function Mg(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function Bg(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function jg(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function Ng(t,e){return Il(t)==="GeneratorFunction"}function Fg(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function Rg(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 qg(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Uo=yi((dk,Bl)=>{"use strict";var Lg=xl(),Ha=Pl(),Dl=(t,e)=>!e||Ha(e)!=="array"?!1:e.indexOf(t)>-1,$g=(t,e)=>Lg(t,{compare:e}),El=(t,e)=>{let n=e&&e.compareFunction;return t.slice().sort(n)};function Ml(t,e){let n=e&&e.compareFunction,i=$g(t,n);return Object.keys(t).forEach(function(r){let o=i[r],s=Ha(o);if(s==="object"){(!e||!Dl(r,e.ignoreObjectAtKeys))&&(i[r]=Ml(o,e));return}s==="array"&&(!e||!Dl(r,e.ignoreArrayAtKeys))&&(i[r]=El(o,e))}),i}var Br=(t,e)=>{let n=Ha(t);return Br[n]?Br[n](t,e):t};Br.array=El;Br.object=Ml;Bl.exports=Br});var ke=yi((jl,Za)=>{"use strict";(function(t,e){"use strict";function n(A,c){if(!A)throw new Error(c||"Assertion failed")}function i(A,c){A.super_=c;var d=function(){};d.prototype=c.prototype,A.prototype=new d,A.prototype.constructor=A}function r(A,c,d){if(r.isBN(A))return A;this.negative=0,this.words=null,this.length=0,this.red=null,A!==null&&((c==="le"||c==="be")&&(d=c,c=10),this._init(A||0,c||10,d||"be"))}typeof t=="object"?t.exports=r:e.BN=r,r.BN=r,r.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=require("buffer").Buffer}catch{}r.isBN=function(c){return c instanceof r?!0:c!==null&&typeof c=="object"&&c.constructor.wordSize===r.wordSize&&Array.isArray(c.words)},r.max=function(c,d){return c.cmp(d)>0?c:d},r.min=function(c,d){return c.cmp(d)<0?c:d},r.prototype._init=function(c,d,g){if(typeof c=="number")return this._initNumber(c,d,g);if(typeof c=="object")return this._initArray(c,d,g);d==="hex"&&(d=16),n(d===(d|0)&&d>=2&&d<=36),c=c.toString().replace(/\s+/g,"");var b=0;c[0]==="-"&&(b++,this.negative=1),b<c.length&&(d===16?this._parseHex(c,b,g):(this._parseBase(c,d,b),g==="le"&&this._initArray(this.toArray(),d,g)))},r.prototype._initNumber=function(c,d,g){c<0&&(this.negative=1,c=-c),c<67108864?(this.words=[c&67108863],this.length=1):c<4503599627370496?(this.words=[c&67108863,c/67108864&67108863],this.length=2):(n(c<9007199254740992),this.words=[c&67108863,c/67108864&67108863,1],this.length=3),g==="le"&&this._initArray(this.toArray(),d,g)},r.prototype._initArray=function(c,d,g){if(n(typeof c.length=="number"),c.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(c.length/3),this.words=new Array(this.length);for(var b=0;b<this.length;b++)this.words[b]=0;var p,m,y=0;if(g==="be")for(b=c.length-1,p=0;b>=0;b-=3)m=c[b]|c[b-1]<<8|c[b-2]<<16,this.words[p]|=m<<y&67108863,this.words[p+1]=m>>>26-y&67108863,y+=24,y>=26&&(y-=26,p++);else if(g==="le")for(b=0,p=0;b<c.length;b+=3)m=c[b]|c[b+1]<<8|c[b+2]<<16,this.words[p]|=m<<y&67108863,this.words[p+1]=m>>>26-y&67108863,y+=24,y>=26&&(y-=26,p++);return this._strip()};function s(A,c){var d=A.charCodeAt(c);if(d>=48&&d<=57)return d-48;if(d>=65&&d<=70)return d-55;if(d>=97&&d<=102)return d-87;n(!1,"Invalid character in "+A)}function a(A,c,d){var g=s(A,d);return d-1>=c&&(g|=s(A,d-1)<<4),g}r.prototype._parseHex=function(c,d,g){this.length=Math.ceil((c.length-d)/6),this.words=new Array(this.length);for(var b=0;b<this.length;b++)this.words[b]=0;var p=0,m=0,y;if(g==="be")for(b=c.length-1;b>=d;b-=2)y=a(c,d,b)<<p,this.words[m]|=y&67108863,p>=18?(p-=18,m+=1,this.words[m]|=y>>>26):p+=8;else{var _=c.length-d;for(b=_%2===0?d+1:d;b<c.length;b+=2)y=a(c,d,b)<<p,this.words[m]|=y&67108863,p>=18?(p-=18,m+=1,this.words[m]|=y>>>26):p+=8}this._strip()};function u(A,c,d,g){for(var b=0,p=0,m=Math.min(A.length,d),y=c;y<m;y++){var _=A.charCodeAt(y)-48;b*=g,_>=49?p=_-49+10:_>=17?p=_-17+10:p=_,n(_>=0&&p<g,"Invalid character"),b+=p}return b}r.prototype._parseBase=function(c,d,g){this.words=[0],this.length=1;for(var b=0,p=1;p<=67108863;p*=d)b++;b--,p=p/d|0;for(var m=c.length-g,y=m%b,_=Math.min(m,m-y)+g,f=0,k=g;k<_;k+=b)f=u(c,k,k+b,d),this.imuln(p),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f);if(y!==0){var M=1;for(f=u(c,k,c.length,d),k=0;k<y;k++)M*=d;this.imuln(M),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f)}this._strip()},r.prototype.copy=function(c){c.words=new Array(this.length);for(var d=0;d<this.length;d++)c.words[d]=this.words[d];c.length=this.length,c.negative=this.negative,c.red=this.red};function l(A,c){A.words=c.words,A.length=c.length,A.negative=c.negative,A.red=c.red}if(r.prototype._move=function(c){l(c,this)},r.prototype.clone=function(){var c=new r(null);return this.copy(c),c},r.prototype._expand=function(c){for(;this.length<c;)this.words[this.length++]=0;return this},r.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},r.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{r.prototype[Symbol.for("nodejs.util.inspect.custom")]=h}catch{r.prototype.inspect=h}else r.prototype.inspect=h;function h(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],v=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];r.prototype.toString=function(c,d){c=c||10,d=d|0||1;var g;if(c===16||c==="hex"){g="";for(var b=0,p=0,m=0;m<this.length;m++){var y=this.words[m],_=((y<<b|p)&16777215).toString(16);p=y>>>24-b&16777215,b+=2,b>=26&&(b-=26,m--),p!==0||m!==this.length-1?g=w[6-_.length]+_+g:g=_+g}for(p!==0&&(g=p.toString(16)+g);g.length%d!==0;)g="0"+g;return this.negative!==0&&(g="-"+g),g}if(c===(c|0)&&c>=2&&c<=36){var f=v[c],k=T[c];g="";var M=this.clone();for(M.negative=0;!M.isZero();){var j=M.modrn(k).toString(c);M=M.idivn(k),M.isZero()?g=j+g:g=w[f-j.length]+j+g}for(this.isZero()&&(g="0"+g);g.length%d!==0;)g="0"+g;return this.negative!==0&&(g="-"+g),g}n(!1,"Base should be between 2 and 36")},r.prototype.toNumber=function(){var c=this.words[0];return this.length===2?c+=this.words[1]*67108864:this.length===3&&this.words[2]===1?c+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-c:c},r.prototype.toJSON=function(){return this.toString(16,2)},o&&(r.prototype.toBuffer=function(c,d){return this.toArrayLike(o,c,d)}),r.prototype.toArray=function(c,d){return this.toArrayLike(Array,c,d)};var I=function(c,d){return c.allocUnsafe?c.allocUnsafe(d):new c(d)};r.prototype.toArrayLike=function(c,d,g){this._strip();var b=this.byteLength(),p=g||Math.max(1,b);n(b<=p,"byte array longer than desired length"),n(p>0,"Requested array length <= 0");var m=I(c,p),y=d==="le"?"LE":"BE";return this["_toArrayLike"+y](m,b),m},r.prototype._toArrayLikeLE=function(c,d){for(var g=0,b=0,p=0,m=0;p<this.length;p++){var y=this.words[p]<<m|b;c[g++]=y&255,g<c.length&&(c[g++]=y>>8&255),g<c.length&&(c[g++]=y>>16&255),m===6?(g<c.length&&(c[g++]=y>>24&255),b=0,m=0):(b=y>>>24,m+=2)}if(g<c.length)for(c[g++]=b;g<c.length;)c[g++]=0},r.prototype._toArrayLikeBE=function(c,d){for(var g=c.length-1,b=0,p=0,m=0;p<this.length;p++){var y=this.words[p]<<m|b;c[g--]=y&255,g>=0&&(c[g--]=y>>8&255),g>=0&&(c[g--]=y>>16&255),m===6?(g>=0&&(c[g--]=y>>24&255),b=0,m=0):(b=y>>>24,m+=2)}if(g>=0)for(c[g--]=b;g>=0;)c[g--]=0},Math.clz32?r.prototype._countBits=function(c){return 32-Math.clz32(c)}:r.prototype._countBits=function(c){var d=c,g=0;return d>=4096&&(g+=13,d>>>=13),d>=64&&(g+=7,d>>>=7),d>=8&&(g+=4,d>>>=4),d>=2&&(g+=2,d>>>=2),g+d},r.prototype._zeroBits=function(c){if(c===0)return 26;var d=c,g=0;return d&8191||(g+=13,d>>>=13),d&127||(g+=7,d>>>=7),d&15||(g+=4,d>>>=4),d&3||(g+=2,d>>>=2),d&1||g++,g},r.prototype.bitLength=function(){var c=this.words[this.length-1],d=this._countBits(c);return(this.length-1)*26+d};function x(A){for(var c=new Array(A.bitLength()),d=0;d<c.length;d++){var g=d/26|0,b=d%26;c[d]=A.words[g]>>>b&1}return c}r.prototype.zeroBits=function(){if(this.isZero())return 0;for(var c=0,d=0;d<this.length;d++){var g=this._zeroBits(this.words[d]);if(c+=g,g!==26)break}return c},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(c){return this.negative!==0?this.abs().inotn(c).iaddn(1):this.clone()},r.prototype.fromTwos=function(c){return this.testn(c-1)?this.notn(c).iaddn(1).ineg():this.clone()},r.prototype.isNeg=function(){return this.negative!==0},r.prototype.neg=function(){return this.clone().ineg()},r.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},r.prototype.iuor=function(c){for(;this.length<c.length;)this.words[this.length++]=0;for(var d=0;d<c.length;d++)this.words[d]=this.words[d]|c.words[d];return this._strip()},r.prototype.ior=function(c){return n((this.negative|c.negative)===0),this.iuor(c)},r.prototype.or=function(c){return this.length>c.length?this.clone().ior(c):c.clone().ior(this)},r.prototype.uor=function(c){return this.length>c.length?this.clone().iuor(c):c.clone().iuor(this)},r.prototype.iuand=function(c){var d;this.length>c.length?d=c:d=this;for(var g=0;g<d.length;g++)this.words[g]=this.words[g]&c.words[g];return this.length=d.length,this._strip()},r.prototype.iand=function(c){return n((this.negative|c.negative)===0),this.iuand(c)},r.prototype.and=function(c){return this.length>c.length?this.clone().iand(c):c.clone().iand(this)},r.prototype.uand=function(c){return this.length>c.length?this.clone().iuand(c):c.clone().iuand(this)},r.prototype.iuxor=function(c){var d,g;this.length>c.length?(d=this,g=c):(d=c,g=this);for(var b=0;b<g.length;b++)this.words[b]=d.words[b]^g.words[b];if(this!==d)for(;b<d.length;b++)this.words[b]=d.words[b];return this.length=d.length,this._strip()},r.prototype.ixor=function(c){return n((this.negative|c.negative)===0),this.iuxor(c)},r.prototype.xor=function(c){return this.length>c.length?this.clone().ixor(c):c.clone().ixor(this)},r.prototype.uxor=function(c){return this.length>c.length?this.clone().iuxor(c):c.clone().iuxor(this)},r.prototype.inotn=function(c){n(typeof c=="number"&&c>=0);var d=Math.ceil(c/26)|0,g=c%26;this._expand(d),g>0&&d--;for(var b=0;b<d;b++)this.words[b]=~this.words[b]&67108863;return g>0&&(this.words[b]=~this.words[b]&67108863>>26-g),this._strip()},r.prototype.notn=function(c){return this.clone().inotn(c)},r.prototype.setn=function(c,d){n(typeof c=="number"&&c>=0);var g=c/26|0,b=c%26;return this._expand(g+1),d?this.words[g]=this.words[g]|1<<b:this.words[g]=this.words[g]&~(1<<b),this._strip()},r.prototype.iadd=function(c){var d;if(this.negative!==0&&c.negative===0)return this.negative=0,d=this.isub(c),this.negative^=1,this._normSign();if(this.negative===0&&c.negative!==0)return c.negative=0,d=this.isub(c),c.negative=1,d._normSign();var g,b;this.length>c.length?(g=this,b=c):(g=c,b=this);for(var p=0,m=0;m<b.length;m++)d=(g.words[m]|0)+(b.words[m]|0)+p,this.words[m]=d&67108863,p=d>>>26;for(;p!==0&&m<g.length;m++)d=(g.words[m]|0)+p,this.words[m]=d&67108863,p=d>>>26;if(this.length=g.length,p!==0)this.words[this.length]=p,this.length++;else if(g!==this)for(;m<g.length;m++)this.words[m]=g.words[m];return this},r.prototype.add=function(c){var d;return c.negative!==0&&this.negative===0?(c.negative=0,d=this.sub(c),c.negative^=1,d):c.negative===0&&this.negative!==0?(this.negative=0,d=c.sub(this),this.negative=1,d):this.length>c.length?this.clone().iadd(c):c.clone().iadd(this)},r.prototype.isub=function(c){if(c.negative!==0){c.negative=0;var d=this.iadd(c);return c.negative=1,d._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(c),this.negative=1,this._normSign();var g=this.cmp(c);if(g===0)return this.negative=0,this.length=1,this.words[0]=0,this;var b,p;g>0?(b=this,p=c):(b=c,p=this);for(var m=0,y=0;y<p.length;y++)d=(b.words[y]|0)-(p.words[y]|0)+m,m=d>>26,this.words[y]=d&67108863;for(;m!==0&&y<b.length;y++)d=(b.words[y]|0)+m,m=d>>26,this.words[y]=d&67108863;if(m===0&&y<b.length&&b!==this)for(;y<b.length;y++)this.words[y]=b.words[y];return this.length=Math.max(this.length,y),b!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(c){return this.clone().isub(c)};function P(A,c,d){d.negative=c.negative^A.negative;var g=A.length+c.length|0;d.length=g,g=g-1|0;var b=A.words[0]|0,p=c.words[0]|0,m=b*p,y=m&67108863,_=m/67108864|0;d.words[0]=y;for(var f=1;f<g;f++){for(var k=_>>>26,M=_&67108863,j=Math.min(f,c.length-1),L=Math.max(0,f-A.length+1);L<=j;L++){var R=f-L|0;b=A.words[R]|0,p=c.words[L]|0,m=b*p+M,k+=m/67108864|0,M=m&67108863}d.words[f]=M|0,_=k|0}return _!==0?d.words[f]=_|0:d.length--,d._strip()}var O=function(c,d,g){var b=c.words,p=d.words,m=g.words,y=0,_,f,k,M=b[0]|0,j=M&8191,L=M>>>13,R=b[1]|0,W=R&8191,ne=R>>>13,me=b[2]|0,ue=me&8191,pe=me>>>13,vt=b[3]|0,De=vt&8191,je=vt>>>13,zi=b[4]|0,Ne=zi&8191,Fe=zi>>>13,qo=b[5]|0,Ke=qo&8191,ze=qo>>>13,sl=b[6]|0,Ve=sl&8191,Ge=sl>>>13,al=b[7]|0,We=al&8191,He=al>>>13,cl=b[8]|0,Ze=cl&8191,Xe=cl>>>13,ul=b[9]|0,Je=ul&8191,Ye=ul>>>13,ll=p[0]|0,Qe=ll&8191,et=ll>>>13,dl=p[1]|0,tt=dl&8191,nt=dl>>>13,fl=p[2]|0,it=fl&8191,rt=fl>>>13,hl=p[3]|0,ot=hl&8191,st=hl>>>13,ml=p[4]|0,at=ml&8191,ct=ml>>>13,pl=p[5]|0,ut=pl&8191,lt=pl>>>13,gl=p[6]|0,dt=gl&8191,ft=gl>>>13,_l=p[7]|0,ht=_l&8191,mt=_l>>>13,yl=p[8]|0,pt=yl&8191,gt=yl>>>13,wl=p[9]|0,_t=wl&8191,yt=wl>>>13;g.negative=c.negative^d.negative,g.length=19,_=Math.imul(j,Qe),f=Math.imul(j,et),f=f+Math.imul(L,Qe)|0,k=Math.imul(L,et);var Ia=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ia>>>26)|0,Ia&=67108863,_=Math.imul(W,Qe),f=Math.imul(W,et),f=f+Math.imul(ne,Qe)|0,k=Math.imul(ne,et),_=_+Math.imul(j,tt)|0,f=f+Math.imul(j,nt)|0,f=f+Math.imul(L,tt)|0,k=k+Math.imul(L,nt)|0;var Oa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Oa>>>26)|0,Oa&=67108863,_=Math.imul(ue,Qe),f=Math.imul(ue,et),f=f+Math.imul(pe,Qe)|0,k=Math.imul(pe,et),_=_+Math.imul(W,tt)|0,f=f+Math.imul(W,nt)|0,f=f+Math.imul(ne,tt)|0,k=k+Math.imul(ne,nt)|0,_=_+Math.imul(j,it)|0,f=f+Math.imul(j,rt)|0,f=f+Math.imul(L,it)|0,k=k+Math.imul(L,rt)|0;var Pa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Pa>>>26)|0,Pa&=67108863,_=Math.imul(De,Qe),f=Math.imul(De,et),f=f+Math.imul(je,Qe)|0,k=Math.imul(je,et),_=_+Math.imul(ue,tt)|0,f=f+Math.imul(ue,nt)|0,f=f+Math.imul(pe,tt)|0,k=k+Math.imul(pe,nt)|0,_=_+Math.imul(W,it)|0,f=f+Math.imul(W,rt)|0,f=f+Math.imul(ne,it)|0,k=k+Math.imul(ne,rt)|0,_=_+Math.imul(j,ot)|0,f=f+Math.imul(j,st)|0,f=f+Math.imul(L,ot)|0,k=k+Math.imul(L,st)|0;var Da=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Da>>>26)|0,Da&=67108863,_=Math.imul(Ne,Qe),f=Math.imul(Ne,et),f=f+Math.imul(Fe,Qe)|0,k=Math.imul(Fe,et),_=_+Math.imul(De,tt)|0,f=f+Math.imul(De,nt)|0,f=f+Math.imul(je,tt)|0,k=k+Math.imul(je,nt)|0,_=_+Math.imul(ue,it)|0,f=f+Math.imul(ue,rt)|0,f=f+Math.imul(pe,it)|0,k=k+Math.imul(pe,rt)|0,_=_+Math.imul(W,ot)|0,f=f+Math.imul(W,st)|0,f=f+Math.imul(ne,ot)|0,k=k+Math.imul(ne,st)|0,_=_+Math.imul(j,at)|0,f=f+Math.imul(j,ct)|0,f=f+Math.imul(L,at)|0,k=k+Math.imul(L,ct)|0;var Ea=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,_=Math.imul(Ke,Qe),f=Math.imul(Ke,et),f=f+Math.imul(ze,Qe)|0,k=Math.imul(ze,et),_=_+Math.imul(Ne,tt)|0,f=f+Math.imul(Ne,nt)|0,f=f+Math.imul(Fe,tt)|0,k=k+Math.imul(Fe,nt)|0,_=_+Math.imul(De,it)|0,f=f+Math.imul(De,rt)|0,f=f+Math.imul(je,it)|0,k=k+Math.imul(je,rt)|0,_=_+Math.imul(ue,ot)|0,f=f+Math.imul(ue,st)|0,f=f+Math.imul(pe,ot)|0,k=k+Math.imul(pe,st)|0,_=_+Math.imul(W,at)|0,f=f+Math.imul(W,ct)|0,f=f+Math.imul(ne,at)|0,k=k+Math.imul(ne,ct)|0,_=_+Math.imul(j,ut)|0,f=f+Math.imul(j,lt)|0,f=f+Math.imul(L,ut)|0,k=k+Math.imul(L,lt)|0;var Ma=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ma>>>26)|0,Ma&=67108863,_=Math.imul(Ve,Qe),f=Math.imul(Ve,et),f=f+Math.imul(Ge,Qe)|0,k=Math.imul(Ge,et),_=_+Math.imul(Ke,tt)|0,f=f+Math.imul(Ke,nt)|0,f=f+Math.imul(ze,tt)|0,k=k+Math.imul(ze,nt)|0,_=_+Math.imul(Ne,it)|0,f=f+Math.imul(Ne,rt)|0,f=f+Math.imul(Fe,it)|0,k=k+Math.imul(Fe,rt)|0,_=_+Math.imul(De,ot)|0,f=f+Math.imul(De,st)|0,f=f+Math.imul(je,ot)|0,k=k+Math.imul(je,st)|0,_=_+Math.imul(ue,at)|0,f=f+Math.imul(ue,ct)|0,f=f+Math.imul(pe,at)|0,k=k+Math.imul(pe,ct)|0,_=_+Math.imul(W,ut)|0,f=f+Math.imul(W,lt)|0,f=f+Math.imul(ne,ut)|0,k=k+Math.imul(ne,lt)|0,_=_+Math.imul(j,dt)|0,f=f+Math.imul(j,ft)|0,f=f+Math.imul(L,dt)|0,k=k+Math.imul(L,ft)|0;var Ba=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ba>>>26)|0,Ba&=67108863,_=Math.imul(We,Qe),f=Math.imul(We,et),f=f+Math.imul(He,Qe)|0,k=Math.imul(He,et),_=_+Math.imul(Ve,tt)|0,f=f+Math.imul(Ve,nt)|0,f=f+Math.imul(Ge,tt)|0,k=k+Math.imul(Ge,nt)|0,_=_+Math.imul(Ke,it)|0,f=f+Math.imul(Ke,rt)|0,f=f+Math.imul(ze,it)|0,k=k+Math.imul(ze,rt)|0,_=_+Math.imul(Ne,ot)|0,f=f+Math.imul(Ne,st)|0,f=f+Math.imul(Fe,ot)|0,k=k+Math.imul(Fe,st)|0,_=_+Math.imul(De,at)|0,f=f+Math.imul(De,ct)|0,f=f+Math.imul(je,at)|0,k=k+Math.imul(je,ct)|0,_=_+Math.imul(ue,ut)|0,f=f+Math.imul(ue,lt)|0,f=f+Math.imul(pe,ut)|0,k=k+Math.imul(pe,lt)|0,_=_+Math.imul(W,dt)|0,f=f+Math.imul(W,ft)|0,f=f+Math.imul(ne,dt)|0,k=k+Math.imul(ne,ft)|0,_=_+Math.imul(j,ht)|0,f=f+Math.imul(j,mt)|0,f=f+Math.imul(L,ht)|0,k=k+Math.imul(L,mt)|0;var ja=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(ja>>>26)|0,ja&=67108863,_=Math.imul(Ze,Qe),f=Math.imul(Ze,et),f=f+Math.imul(Xe,Qe)|0,k=Math.imul(Xe,et),_=_+Math.imul(We,tt)|0,f=f+Math.imul(We,nt)|0,f=f+Math.imul(He,tt)|0,k=k+Math.imul(He,nt)|0,_=_+Math.imul(Ve,it)|0,f=f+Math.imul(Ve,rt)|0,f=f+Math.imul(Ge,it)|0,k=k+Math.imul(Ge,rt)|0,_=_+Math.imul(Ke,ot)|0,f=f+Math.imul(Ke,st)|0,f=f+Math.imul(ze,ot)|0,k=k+Math.imul(ze,st)|0,_=_+Math.imul(Ne,at)|0,f=f+Math.imul(Ne,ct)|0,f=f+Math.imul(Fe,at)|0,k=k+Math.imul(Fe,ct)|0,_=_+Math.imul(De,ut)|0,f=f+Math.imul(De,lt)|0,f=f+Math.imul(je,ut)|0,k=k+Math.imul(je,lt)|0,_=_+Math.imul(ue,dt)|0,f=f+Math.imul(ue,ft)|0,f=f+Math.imul(pe,dt)|0,k=k+Math.imul(pe,ft)|0,_=_+Math.imul(W,ht)|0,f=f+Math.imul(W,mt)|0,f=f+Math.imul(ne,ht)|0,k=k+Math.imul(ne,mt)|0,_=_+Math.imul(j,pt)|0,f=f+Math.imul(j,gt)|0,f=f+Math.imul(L,pt)|0,k=k+Math.imul(L,gt)|0;var Na=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Na>>>26)|0,Na&=67108863,_=Math.imul(Je,Qe),f=Math.imul(Je,et),f=f+Math.imul(Ye,Qe)|0,k=Math.imul(Ye,et),_=_+Math.imul(Ze,tt)|0,f=f+Math.imul(Ze,nt)|0,f=f+Math.imul(Xe,tt)|0,k=k+Math.imul(Xe,nt)|0,_=_+Math.imul(We,it)|0,f=f+Math.imul(We,rt)|0,f=f+Math.imul(He,it)|0,k=k+Math.imul(He,rt)|0,_=_+Math.imul(Ve,ot)|0,f=f+Math.imul(Ve,st)|0,f=f+Math.imul(Ge,ot)|0,k=k+Math.imul(Ge,st)|0,_=_+Math.imul(Ke,at)|0,f=f+Math.imul(Ke,ct)|0,f=f+Math.imul(ze,at)|0,k=k+Math.imul(ze,ct)|0,_=_+Math.imul(Ne,ut)|0,f=f+Math.imul(Ne,lt)|0,f=f+Math.imul(Fe,ut)|0,k=k+Math.imul(Fe,lt)|0,_=_+Math.imul(De,dt)|0,f=f+Math.imul(De,ft)|0,f=f+Math.imul(je,dt)|0,k=k+Math.imul(je,ft)|0,_=_+Math.imul(ue,ht)|0,f=f+Math.imul(ue,mt)|0,f=f+Math.imul(pe,ht)|0,k=k+Math.imul(pe,mt)|0,_=_+Math.imul(W,pt)|0,f=f+Math.imul(W,gt)|0,f=f+Math.imul(ne,pt)|0,k=k+Math.imul(ne,gt)|0,_=_+Math.imul(j,_t)|0,f=f+Math.imul(j,yt)|0,f=f+Math.imul(L,_t)|0,k=k+Math.imul(L,yt)|0;var Fa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Fa>>>26)|0,Fa&=67108863,_=Math.imul(Je,tt),f=Math.imul(Je,nt),f=f+Math.imul(Ye,tt)|0,k=Math.imul(Ye,nt),_=_+Math.imul(Ze,it)|0,f=f+Math.imul(Ze,rt)|0,f=f+Math.imul(Xe,it)|0,k=k+Math.imul(Xe,rt)|0,_=_+Math.imul(We,ot)|0,f=f+Math.imul(We,st)|0,f=f+Math.imul(He,ot)|0,k=k+Math.imul(He,st)|0,_=_+Math.imul(Ve,at)|0,f=f+Math.imul(Ve,ct)|0,f=f+Math.imul(Ge,at)|0,k=k+Math.imul(Ge,ct)|0,_=_+Math.imul(Ke,ut)|0,f=f+Math.imul(Ke,lt)|0,f=f+Math.imul(ze,ut)|0,k=k+Math.imul(ze,lt)|0,_=_+Math.imul(Ne,dt)|0,f=f+Math.imul(Ne,ft)|0,f=f+Math.imul(Fe,dt)|0,k=k+Math.imul(Fe,ft)|0,_=_+Math.imul(De,ht)|0,f=f+Math.imul(De,mt)|0,f=f+Math.imul(je,ht)|0,k=k+Math.imul(je,mt)|0,_=_+Math.imul(ue,pt)|0,f=f+Math.imul(ue,gt)|0,f=f+Math.imul(pe,pt)|0,k=k+Math.imul(pe,gt)|0,_=_+Math.imul(W,_t)|0,f=f+Math.imul(W,yt)|0,f=f+Math.imul(ne,_t)|0,k=k+Math.imul(ne,yt)|0;var Ra=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ra>>>26)|0,Ra&=67108863,_=Math.imul(Je,it),f=Math.imul(Je,rt),f=f+Math.imul(Ye,it)|0,k=Math.imul(Ye,rt),_=_+Math.imul(Ze,ot)|0,f=f+Math.imul(Ze,st)|0,f=f+Math.imul(Xe,ot)|0,k=k+Math.imul(Xe,st)|0,_=_+Math.imul(We,at)|0,f=f+Math.imul(We,ct)|0,f=f+Math.imul(He,at)|0,k=k+Math.imul(He,ct)|0,_=_+Math.imul(Ve,ut)|0,f=f+Math.imul(Ve,lt)|0,f=f+Math.imul(Ge,ut)|0,k=k+Math.imul(Ge,lt)|0,_=_+Math.imul(Ke,dt)|0,f=f+Math.imul(Ke,ft)|0,f=f+Math.imul(ze,dt)|0,k=k+Math.imul(ze,ft)|0,_=_+Math.imul(Ne,ht)|0,f=f+Math.imul(Ne,mt)|0,f=f+Math.imul(Fe,ht)|0,k=k+Math.imul(Fe,mt)|0,_=_+Math.imul(De,pt)|0,f=f+Math.imul(De,gt)|0,f=f+Math.imul(je,pt)|0,k=k+Math.imul(je,gt)|0,_=_+Math.imul(ue,_t)|0,f=f+Math.imul(ue,yt)|0,f=f+Math.imul(pe,_t)|0,k=k+Math.imul(pe,yt)|0;var qa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(qa>>>26)|0,qa&=67108863,_=Math.imul(Je,ot),f=Math.imul(Je,st),f=f+Math.imul(Ye,ot)|0,k=Math.imul(Ye,st),_=_+Math.imul(Ze,at)|0,f=f+Math.imul(Ze,ct)|0,f=f+Math.imul(Xe,at)|0,k=k+Math.imul(Xe,ct)|0,_=_+Math.imul(We,ut)|0,f=f+Math.imul(We,lt)|0,f=f+Math.imul(He,ut)|0,k=k+Math.imul(He,lt)|0,_=_+Math.imul(Ve,dt)|0,f=f+Math.imul(Ve,ft)|0,f=f+Math.imul(Ge,dt)|0,k=k+Math.imul(Ge,ft)|0,_=_+Math.imul(Ke,ht)|0,f=f+Math.imul(Ke,mt)|0,f=f+Math.imul(ze,ht)|0,k=k+Math.imul(ze,mt)|0,_=_+Math.imul(Ne,pt)|0,f=f+Math.imul(Ne,gt)|0,f=f+Math.imul(Fe,pt)|0,k=k+Math.imul(Fe,gt)|0,_=_+Math.imul(De,_t)|0,f=f+Math.imul(De,yt)|0,f=f+Math.imul(je,_t)|0,k=k+Math.imul(je,yt)|0;var La=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(La>>>26)|0,La&=67108863,_=Math.imul(Je,at),f=Math.imul(Je,ct),f=f+Math.imul(Ye,at)|0,k=Math.imul(Ye,ct),_=_+Math.imul(Ze,ut)|0,f=f+Math.imul(Ze,lt)|0,f=f+Math.imul(Xe,ut)|0,k=k+Math.imul(Xe,lt)|0,_=_+Math.imul(We,dt)|0,f=f+Math.imul(We,ft)|0,f=f+Math.imul(He,dt)|0,k=k+Math.imul(He,ft)|0,_=_+Math.imul(Ve,ht)|0,f=f+Math.imul(Ve,mt)|0,f=f+Math.imul(Ge,ht)|0,k=k+Math.imul(Ge,mt)|0,_=_+Math.imul(Ke,pt)|0,f=f+Math.imul(Ke,gt)|0,f=f+Math.imul(ze,pt)|0,k=k+Math.imul(ze,gt)|0,_=_+Math.imul(Ne,_t)|0,f=f+Math.imul(Ne,yt)|0,f=f+Math.imul(Fe,_t)|0,k=k+Math.imul(Fe,yt)|0;var $a=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+($a>>>26)|0,$a&=67108863,_=Math.imul(Je,ut),f=Math.imul(Je,lt),f=f+Math.imul(Ye,ut)|0,k=Math.imul(Ye,lt),_=_+Math.imul(Ze,dt)|0,f=f+Math.imul(Ze,ft)|0,f=f+Math.imul(Xe,dt)|0,k=k+Math.imul(Xe,ft)|0,_=_+Math.imul(We,ht)|0,f=f+Math.imul(We,mt)|0,f=f+Math.imul(He,ht)|0,k=k+Math.imul(He,mt)|0,_=_+Math.imul(Ve,pt)|0,f=f+Math.imul(Ve,gt)|0,f=f+Math.imul(Ge,pt)|0,k=k+Math.imul(Ge,gt)|0,_=_+Math.imul(Ke,_t)|0,f=f+Math.imul(Ke,yt)|0,f=f+Math.imul(ze,_t)|0,k=k+Math.imul(ze,yt)|0;var Ua=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ua>>>26)|0,Ua&=67108863,_=Math.imul(Je,dt),f=Math.imul(Je,ft),f=f+Math.imul(Ye,dt)|0,k=Math.imul(Ye,ft),_=_+Math.imul(Ze,ht)|0,f=f+Math.imul(Ze,mt)|0,f=f+Math.imul(Xe,ht)|0,k=k+Math.imul(Xe,mt)|0,_=_+Math.imul(We,pt)|0,f=f+Math.imul(We,gt)|0,f=f+Math.imul(He,pt)|0,k=k+Math.imul(He,gt)|0,_=_+Math.imul(Ve,_t)|0,f=f+Math.imul(Ve,yt)|0,f=f+Math.imul(Ge,_t)|0,k=k+Math.imul(Ge,yt)|0;var Ka=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ka>>>26)|0,Ka&=67108863,_=Math.imul(Je,ht),f=Math.imul(Je,mt),f=f+Math.imul(Ye,ht)|0,k=Math.imul(Ye,mt),_=_+Math.imul(Ze,pt)|0,f=f+Math.imul(Ze,gt)|0,f=f+Math.imul(Xe,pt)|0,k=k+Math.imul(Xe,gt)|0,_=_+Math.imul(We,_t)|0,f=f+Math.imul(We,yt)|0,f=f+Math.imul(He,_t)|0,k=k+Math.imul(He,yt)|0;var za=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(za>>>26)|0,za&=67108863,_=Math.imul(Je,pt),f=Math.imul(Je,gt),f=f+Math.imul(Ye,pt)|0,k=Math.imul(Ye,gt),_=_+Math.imul(Ze,_t)|0,f=f+Math.imul(Ze,yt)|0,f=f+Math.imul(Xe,_t)|0,k=k+Math.imul(Xe,yt)|0;var Va=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Va>>>26)|0,Va&=67108863,_=Math.imul(Je,_t),f=Math.imul(Je,yt),f=f+Math.imul(Ye,_t)|0,k=Math.imul(Ye,yt);var Ga=(y+_|0)+((f&8191)<<13)|0;return y=(k+(f>>>13)|0)+(Ga>>>26)|0,Ga&=67108863,m[0]=Ia,m[1]=Oa,m[2]=Pa,m[3]=Da,m[4]=Ea,m[5]=Ma,m[6]=Ba,m[7]=ja,m[8]=Na,m[9]=Fa,m[10]=Ra,m[11]=qa,m[12]=La,m[13]=$a,m[14]=Ua,m[15]=Ka,m[16]=za,m[17]=Va,m[18]=Ga,y!==0&&(m[19]=y,g.length++),g};Math.imul||(O=P);function E(A,c,d){d.negative=c.negative^A.negative,d.length=A.length+c.length;for(var g=0,b=0,p=0;p<d.length-1;p++){var m=b;b=0;for(var y=g&67108863,_=Math.min(p,c.length-1),f=Math.max(0,p-A.length+1);f<=_;f++){var k=p-f,M=A.words[k]|0,j=c.words[f]|0,L=M*j,R=L&67108863;m=m+(L/67108864|0)|0,R=R+y|0,y=R&67108863,m=m+(R>>>26)|0,b+=m>>>26,m&=67108863}d.words[p]=y,g=m,m=b}return g!==0?d.words[p]=g:d.length--,d._strip()}function B(A,c,d){return E(A,c,d)}r.prototype.mulTo=function(c,d){var g,b=this.length+c.length;return this.length===10&&c.length===10?g=O(this,c,d):b<63?g=P(this,c,d):b<1024?g=E(this,c,d):g=B(this,c,d),g};function $(A,c){this.x=A,this.y=c}$.prototype.makeRBT=function(c){for(var d=new Array(c),g=r.prototype._countBits(c)-1,b=0;b<c;b++)d[b]=this.revBin(b,g,c);return d},$.prototype.revBin=function(c,d,g){if(c===0||c===g-1)return c;for(var b=0,p=0;p<d;p++)b|=(c&1)<<d-p-1,c>>=1;return b},$.prototype.permute=function(c,d,g,b,p,m){for(var y=0;y<m;y++)b[y]=d[c[y]],p[y]=g[c[y]]},$.prototype.transform=function(c,d,g,b,p,m){this.permute(m,c,d,g,b,p);for(var y=1;y<p;y<<=1)for(var _=y<<1,f=Math.cos(2*Math.PI/_),k=Math.sin(2*Math.PI/_),M=0;M<p;M+=_)for(var j=f,L=k,R=0;R<y;R++){var W=g[M+R],ne=b[M+R],me=g[M+R+y],ue=b[M+R+y],pe=j*me-L*ue;ue=j*ue+L*me,me=pe,g[M+R]=W+me,b[M+R]=ne+ue,g[M+R+y]=W-me,b[M+R+y]=ne-ue,R!==_&&(pe=f*j-k*L,L=f*L+k*j,j=pe)}},$.prototype.guessLen13b=function(c,d){var g=Math.max(d,c)|1,b=g&1,p=0;for(g=g/2|0;g;g=g>>>1)p++;return 1<<p+1+b},$.prototype.conjugate=function(c,d,g){if(!(g<=1))for(var b=0;b<g/2;b++){var p=c[b];c[b]=c[g-b-1],c[g-b-1]=p,p=d[b],d[b]=-d[g-b-1],d[g-b-1]=-p}},$.prototype.normalize13b=function(c,d){for(var g=0,b=0;b<d/2;b++){var p=Math.round(c[2*b+1]/d)*8192+Math.round(c[2*b]/d)+g;c[b]=p&67108863,p<67108864?g=0:g=p/67108864|0}return c},$.prototype.convert13b=function(c,d,g,b){for(var p=0,m=0;m<d;m++)p=p+(c[m]|0),g[2*m]=p&8191,p=p>>>13,g[2*m+1]=p&8191,p=p>>>13;for(m=2*d;m<b;++m)g[m]=0;n(p===0),n((p&-8192)===0)},$.prototype.stub=function(c){for(var d=new Array(c),g=0;g<c;g++)d[g]=0;return d},$.prototype.mulp=function(c,d,g){var b=2*this.guessLen13b(c.length,d.length),p=this.makeRBT(b),m=this.stub(b),y=new Array(b),_=new Array(b),f=new Array(b),k=new Array(b),M=new Array(b),j=new Array(b),L=g.words;L.length=b,this.convert13b(c.words,c.length,y,b),this.convert13b(d.words,d.length,k,b),this.transform(y,m,_,f,b,p),this.transform(k,m,M,j,b,p);for(var R=0;R<b;R++){var W=_[R]*M[R]-f[R]*j[R];f[R]=_[R]*j[R]+f[R]*M[R],_[R]=W}return this.conjugate(_,f,b),this.transform(_,f,L,m,b,p),this.conjugate(L,m,b),this.normalize13b(L,b),g.negative=c.negative^d.negative,g.length=c.length+d.length,g._strip()},r.prototype.mul=function(c){var d=new r(null);return d.words=new Array(this.length+c.length),this.mulTo(c,d)},r.prototype.mulf=function(c){var d=new r(null);return d.words=new Array(this.length+c.length),B(this,c,d)},r.prototype.imul=function(c){return this.clone().mulTo(c,this)},r.prototype.imuln=function(c){var d=c<0;d&&(c=-c),n(typeof c=="number"),n(c<67108864);for(var g=0,b=0;b<this.length;b++){var p=(this.words[b]|0)*c,m=(p&67108863)+(g&67108863);g>>=26,g+=p/67108864|0,g+=m>>>26,this.words[b]=m&67108863}return g!==0&&(this.words[b]=g,this.length++),d?this.ineg():this},r.prototype.muln=function(c){return this.clone().imuln(c)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(c){var d=x(c);if(d.length===0)return new r(1);for(var g=this,b=0;b<d.length&&d[b]===0;b++,g=g.sqr());if(++b<d.length)for(var p=g.sqr();b<d.length;b++,p=p.sqr())d[b]!==0&&(g=g.mul(p));return g},r.prototype.iushln=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26,b=67108863>>>26-d<<26-d,p;if(d!==0){var m=0;for(p=0;p<this.length;p++){var y=this.words[p]&b,_=(this.words[p]|0)-y<<d;this.words[p]=_|m,m=y>>>26-d}m&&(this.words[p]=m,this.length++)}if(g!==0){for(p=this.length-1;p>=0;p--)this.words[p+g]=this.words[p];for(p=0;p<g;p++)this.words[p]=0;this.length+=g}return this._strip()},r.prototype.ishln=function(c){return n(this.negative===0),this.iushln(c)},r.prototype.iushrn=function(c,d,g){n(typeof c=="number"&&c>=0);var b;d?b=(d-d%26)/26:b=0;var p=c%26,m=Math.min((c-p)/26,this.length),y=67108863^67108863>>>p<<p,_=g;if(b-=m,b=Math.max(0,b),_){for(var f=0;f<m;f++)_.words[f]=this.words[f];_.length=m}if(m!==0)if(this.length>m)for(this.length-=m,f=0;f<this.length;f++)this.words[f]=this.words[f+m];else this.words[0]=0,this.length=1;var k=0;for(f=this.length-1;f>=0&&(k!==0||f>=b);f--){var M=this.words[f]|0;this.words[f]=k<<26-p|M>>>p,k=M&y}return _&&k!==0&&(_.words[_.length++]=k),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(c,d,g){return n(this.negative===0),this.iushrn(c,d,g)},r.prototype.shln=function(c){return this.clone().ishln(c)},r.prototype.ushln=function(c){return this.clone().iushln(c)},r.prototype.shrn=function(c){return this.clone().ishrn(c)},r.prototype.ushrn=function(c){return this.clone().iushrn(c)},r.prototype.testn=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26,b=1<<d;if(this.length<=g)return!1;var p=this.words[g];return!!(p&b)},r.prototype.imaskn=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=g)return this;if(d!==0&&g++,this.length=Math.min(g,this.length),d!==0){var b=67108863^67108863>>>d<<d;this.words[this.length-1]&=b}return this._strip()},r.prototype.maskn=function(c){return this.clone().imaskn(c)},r.prototype.iaddn=function(c){return n(typeof c=="number"),n(c<67108864),c<0?this.isubn(-c):this.negative!==0?this.length===1&&(this.words[0]|0)<=c?(this.words[0]=c-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(c),this.negative=1,this):this._iaddn(c)},r.prototype._iaddn=function(c){this.words[0]+=c;for(var d=0;d<this.length&&this.words[d]>=67108864;d++)this.words[d]-=67108864,d===this.length-1?this.words[d+1]=1:this.words[d+1]++;return this.length=Math.max(this.length,d+1),this},r.prototype.isubn=function(c){if(n(typeof c=="number"),n(c<67108864),c<0)return this.iaddn(-c);if(this.negative!==0)return this.negative=0,this.iaddn(c),this.negative=1,this;if(this.words[0]-=c,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var d=0;d<this.length&&this.words[d]<0;d++)this.words[d]+=67108864,this.words[d+1]-=1;return this._strip()},r.prototype.addn=function(c){return this.clone().iaddn(c)},r.prototype.subn=function(c){return this.clone().isubn(c)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(c,d,g){var b=c.length+g,p;this._expand(b);var m,y=0;for(p=0;p<c.length;p++){m=(this.words[p+g]|0)+y;var _=(c.words[p]|0)*d;m-=_&67108863,y=(m>>26)-(_/67108864|0),this.words[p+g]=m&67108863}for(;p<this.length-g;p++)m=(this.words[p+g]|0)+y,y=m>>26,this.words[p+g]=m&67108863;if(y===0)return this._strip();for(n(y===-1),y=0,p=0;p<this.length;p++)m=-(this.words[p]|0)+y,y=m>>26,this.words[p]=m&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(c,d){var g=this.length-c.length,b=this.clone(),p=c,m=p.words[p.length-1]|0,y=this._countBits(m);g=26-y,g!==0&&(p=p.ushln(g),b.iushln(g),m=p.words[p.length-1]|0);var _=b.length-p.length,f;if(d!=="mod"){f=new r(null),f.length=_+1,f.words=new Array(f.length);for(var k=0;k<f.length;k++)f.words[k]=0}var M=b.clone()._ishlnsubmul(p,1,_);M.negative===0&&(b=M,f&&(f.words[_]=1));for(var j=_-1;j>=0;j--){var L=(b.words[p.length+j]|0)*67108864+(b.words[p.length+j-1]|0);for(L=Math.min(L/m|0,67108863),b._ishlnsubmul(p,L,j);b.negative!==0;)L--,b.negative=0,b._ishlnsubmul(p,1,j),b.isZero()||(b.negative^=1);f&&(f.words[j]=L)}return f&&f._strip(),b._strip(),d!=="div"&&g!==0&&b.iushrn(g),{div:f||null,mod:b}},r.prototype.divmod=function(c,d,g){if(n(!c.isZero()),this.isZero())return{div:new r(0),mod:new r(0)};var b,p,m;return this.negative!==0&&c.negative===0?(m=this.neg().divmod(c,d),d!=="mod"&&(b=m.div.neg()),d!=="div"&&(p=m.mod.neg(),g&&p.negative!==0&&p.iadd(c)),{div:b,mod:p}):this.negative===0&&c.negative!==0?(m=this.divmod(c.neg(),d),d!=="mod"&&(b=m.div.neg()),{div:b,mod:m.mod}):this.negative&c.negative?(m=this.neg().divmod(c.neg(),d),d!=="div"&&(p=m.mod.neg(),g&&p.negative!==0&&p.isub(c)),{div:m.div,mod:p}):c.length>this.length||this.cmp(c)<0?{div:new r(0),mod:this}:c.length===1?d==="div"?{div:this.divn(c.words[0]),mod:null}:d==="mod"?{div:null,mod:new r(this.modrn(c.words[0]))}:{div:this.divn(c.words[0]),mod:new r(this.modrn(c.words[0]))}:this._wordDiv(c,d)},r.prototype.div=function(c){return this.divmod(c,"div",!1).div},r.prototype.mod=function(c){return this.divmod(c,"mod",!1).mod},r.prototype.umod=function(c){return this.divmod(c,"mod",!0).mod},r.prototype.divRound=function(c){var d=this.divmod(c);if(d.mod.isZero())return d.div;var g=d.div.negative!==0?d.mod.isub(c):d.mod,b=c.ushrn(1),p=c.andln(1),m=g.cmp(b);return m<0||p===1&&m===0?d.div:d.div.negative!==0?d.div.isubn(1):d.div.iaddn(1)},r.prototype.modrn=function(c){var d=c<0;d&&(c=-c),n(c<=67108863);for(var g=(1<<26)%c,b=0,p=this.length-1;p>=0;p--)b=(g*b+(this.words[p]|0))%c;return d?-b:b},r.prototype.modn=function(c){return this.modrn(c)},r.prototype.idivn=function(c){var d=c<0;d&&(c=-c),n(c<=67108863);for(var g=0,b=this.length-1;b>=0;b--){var p=(this.words[b]|0)+g*67108864;this.words[b]=p/c|0,g=p%c}return this._strip(),d?this.ineg():this},r.prototype.divn=function(c){return this.clone().idivn(c)},r.prototype.egcd=function(c){n(c.negative===0),n(!c.isZero());var d=this,g=c.clone();d.negative!==0?d=d.umod(c):d=d.clone();for(var b=new r(1),p=new r(0),m=new r(0),y=new r(1),_=0;d.isEven()&&g.isEven();)d.iushrn(1),g.iushrn(1),++_;for(var f=g.clone(),k=d.clone();!d.isZero();){for(var M=0,j=1;!(d.words[0]&j)&&M<26;++M,j<<=1);if(M>0)for(d.iushrn(M);M-- >0;)(b.isOdd()||p.isOdd())&&(b.iadd(f),p.isub(k)),b.iushrn(1),p.iushrn(1);for(var L=0,R=1;!(g.words[0]&R)&&L<26;++L,R<<=1);if(L>0)for(g.iushrn(L);L-- >0;)(m.isOdd()||y.isOdd())&&(m.iadd(f),y.isub(k)),m.iushrn(1),y.iushrn(1);d.cmp(g)>=0?(d.isub(g),b.isub(m),p.isub(y)):(g.isub(d),m.isub(b),y.isub(p))}return{a:m,b:y,gcd:g.iushln(_)}},r.prototype._invmp=function(c){n(c.negative===0),n(!c.isZero());var d=this,g=c.clone();d.negative!==0?d=d.umod(c):d=d.clone();for(var b=new r(1),p=new r(0),m=g.clone();d.cmpn(1)>0&&g.cmpn(1)>0;){for(var y=0,_=1;!(d.words[0]&_)&&y<26;++y,_<<=1);if(y>0)for(d.iushrn(y);y-- >0;)b.isOdd()&&b.iadd(m),b.iushrn(1);for(var f=0,k=1;!(g.words[0]&k)&&f<26;++f,k<<=1);if(f>0)for(g.iushrn(f);f-- >0;)p.isOdd()&&p.iadd(m),p.iushrn(1);d.cmp(g)>=0?(d.isub(g),b.isub(p)):(g.isub(d),p.isub(b))}var M;return d.cmpn(1)===0?M=b:M=p,M.cmpn(0)<0&&M.iadd(c),M},r.prototype.gcd=function(c){if(this.isZero())return c.abs();if(c.isZero())return this.abs();var d=this.clone(),g=c.clone();d.negative=0,g.negative=0;for(var b=0;d.isEven()&&g.isEven();b++)d.iushrn(1),g.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;g.isEven();)g.iushrn(1);var p=d.cmp(g);if(p<0){var m=d;d=g,g=m}else if(p===0||g.cmpn(1)===0)break;d.isub(g)}while(!0);return g.iushln(b)},r.prototype.invm=function(c){return this.egcd(c).a.umod(c)},r.prototype.isEven=function(){return(this.words[0]&1)===0},r.prototype.isOdd=function(){return(this.words[0]&1)===1},r.prototype.andln=function(c){return this.words[0]&c},r.prototype.bincn=function(c){n(typeof c=="number");var d=c%26,g=(c-d)/26,b=1<<d;if(this.length<=g)return this._expand(g+1),this.words[g]|=b,this;for(var p=b,m=g;p!==0&&m<this.length;m++){var y=this.words[m]|0;y+=p,p=y>>>26,y&=67108863,this.words[m]=y}return p!==0&&(this.words[m]=p,this.length++),this},r.prototype.isZero=function(){return this.length===1&&this.words[0]===0},r.prototype.cmpn=function(c){var d=c<0;if(this.negative!==0&&!d)return-1;if(this.negative===0&&d)return 1;this._strip();var g;if(this.length>1)g=1;else{d&&(c=-c),n(c<=67108863,"Number is too big");var b=this.words[0]|0;g=b===c?0:b<c?-1:1}return this.negative!==0?-g|0:g},r.prototype.cmp=function(c){if(this.negative!==0&&c.negative===0)return-1;if(this.negative===0&&c.negative!==0)return 1;var d=this.ucmp(c);return this.negative!==0?-d|0:d},r.prototype.ucmp=function(c){if(this.length>c.length)return 1;if(this.length<c.length)return-1;for(var d=0,g=this.length-1;g>=0;g--){var b=this.words[g]|0,p=c.words[g]|0;if(b!==p){b<p?d=-1:b>p&&(d=1);break}}return d},r.prototype.gtn=function(c){return this.cmpn(c)===1},r.prototype.gt=function(c){return this.cmp(c)===1},r.prototype.gten=function(c){return this.cmpn(c)>=0},r.prototype.gte=function(c){return this.cmp(c)>=0},r.prototype.ltn=function(c){return this.cmpn(c)===-1},r.prototype.lt=function(c){return this.cmp(c)===-1},r.prototype.lten=function(c){return this.cmpn(c)<=0},r.prototype.lte=function(c){return this.cmp(c)<=0},r.prototype.eqn=function(c){return this.cmpn(c)===0},r.prototype.eq=function(c){return this.cmp(c)===0},r.red=function(c){return new K(c)},r.prototype.toRed=function(c){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),c.convertTo(this)._forceRed(c)},r.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(c){return this.red=c,this},r.prototype.forceRed=function(c){return n(!this.red,"Already a number in reduction context"),this._forceRed(c)},r.prototype.redAdd=function(c){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,c)},r.prototype.redIAdd=function(c){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,c)},r.prototype.redSub=function(c){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,c)},r.prototype.redISub=function(c){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,c)},r.prototype.redShl=function(c){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,c)},r.prototype.redMul=function(c){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.mul(this,c)},r.prototype.redIMul=function(c){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,c),this.red.imul(this,c)},r.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},r.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},r.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},r.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},r.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},r.prototype.redPow=function(c){return n(this.red&&!c.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,c)};var Z={k256:null,p224:null,p192:null,p25519:null};function H(A,c){this.name=A,this.p=new r(c,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var c=new r(null);return c.words=new Array(Math.ceil(this.n/13)),c},H.prototype.ireduce=function(c){var d=c,g;do this.split(d,this.tmp),d=this.imulK(d),d=d.iadd(this.tmp),g=d.bitLength();while(g>this.n);var b=g<this.n?-1:d.ucmp(this.p);return b===0?(d.words[0]=0,d.length=1):b>0?d.isub(this.p):d.strip!==void 0?d.strip():d._strip(),d},H.prototype.split=function(c,d){c.iushrn(this.n,0,d)},H.prototype.imulK=function(c){return c.imul(this.k)};function te(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(te,H),te.prototype.split=function(c,d){for(var g=4194303,b=Math.min(c.length,9),p=0;p<b;p++)d.words[p]=c.words[p];if(d.length=b,c.length<=9){c.words[0]=0,c.length=1;return}var m=c.words[9];for(d.words[d.length++]=m&g,p=10;p<c.length;p++){var y=c.words[p]|0;c.words[p-10]=(y&g)<<4|m>>>22,m=y}m>>>=22,c.words[p-10]=m,m===0&&c.length>10?c.length-=10:c.length-=9},te.prototype.imulK=function(c){c.words[c.length]=0,c.words[c.length+1]=0,c.length+=2;for(var d=0,g=0;g<c.length;g++){var b=c.words[g]|0;d+=b*977,c.words[g]=d&67108863,d=b*64+(d/67108864|0)}return c.words[c.length-1]===0&&(c.length--,c.words[c.length-1]===0&&c.length--),c};function U(){H.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i(U,H);function V(){H.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(V,H);function F(){H.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(F,H),F.prototype.imulK=function(c){for(var d=0,g=0;g<c.length;g++){var b=(c.words[g]|0)*19+d,p=b&67108863;b>>>=26,c.words[g]=p,d=b}return d!==0&&(c.words[c.length++]=d),c},r._prime=function(c){if(Z[c])return Z[c];var d;if(c==="k256")d=new te;else if(c==="p224")d=new U;else if(c==="p192")d=new V;else if(c==="p25519")d=new F;else throw new Error("Unknown prime "+c);return Z[c]=d,d};function K(A){if(typeof A=="string"){var c=r._prime(A);this.m=c.p,this.prime=c}else n(A.gtn(1),"modulus must be greater than 1"),this.m=A,this.prime=null}K.prototype._verify1=function(c){n(c.negative===0,"red works only with positives"),n(c.red,"red works only with red numbers")},K.prototype._verify2=function(c,d){n((c.negative|d.negative)===0,"red works only with positives"),n(c.red&&c.red===d.red,"red works only with red numbers")},K.prototype.imod=function(c){return this.prime?this.prime.ireduce(c)._forceRed(this):(l(c,c.umod(this.m)._forceRed(this)),c)},K.prototype.neg=function(c){return c.isZero()?c.clone():this.m.sub(c)._forceRed(this)},K.prototype.add=function(c,d){this._verify2(c,d);var g=c.add(d);return g.cmp(this.m)>=0&&g.isub(this.m),g._forceRed(this)},K.prototype.iadd=function(c,d){this._verify2(c,d);var g=c.iadd(d);return g.cmp(this.m)>=0&&g.isub(this.m),g},K.prototype.sub=function(c,d){this._verify2(c,d);var g=c.sub(d);return g.cmpn(0)<0&&g.iadd(this.m),g._forceRed(this)},K.prototype.isub=function(c,d){this._verify2(c,d);var g=c.isub(d);return g.cmpn(0)<0&&g.iadd(this.m),g},K.prototype.shl=function(c,d){return this._verify1(c),this.imod(c.ushln(d))},K.prototype.imul=function(c,d){return this._verify2(c,d),this.imod(c.imul(d))},K.prototype.mul=function(c,d){return this._verify2(c,d),this.imod(c.mul(d))},K.prototype.isqr=function(c){return this.imul(c,c.clone())},K.prototype.sqr=function(c){return this.mul(c,c)},K.prototype.sqrt=function(c){if(c.isZero())return c.clone();var d=this.m.andln(3);if(n(d%2===1),d===3){var g=this.m.add(new r(1)).iushrn(2);return this.pow(c,g)}for(var b=this.m.subn(1),p=0;!b.isZero()&&b.andln(1)===0;)p++,b.iushrn(1);n(!b.isZero());var m=new r(1).toRed(this),y=m.redNeg(),_=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new r(2*f*f).toRed(this);this.pow(f,_).cmp(y)!==0;)f.redIAdd(y);for(var k=this.pow(f,b),M=this.pow(c,b.addn(1).iushrn(1)),j=this.pow(c,b),L=p;j.cmp(m)!==0;){for(var R=j,W=0;R.cmp(m)!==0;W++)R=R.redSqr();n(W<L);var ne=this.pow(k,new r(1).iushln(L-W-1));M=M.redMul(ne),k=ne.redSqr(),j=j.redMul(k),L=W}return M},K.prototype.invm=function(c){var d=c._invmp(this.m);return d.negative!==0?(d.negative=0,this.imod(d).redNeg()):this.imod(d)},K.prototype.pow=function(c,d){if(d.isZero())return new r(1).toRed(this);if(d.cmpn(1)===0)return c.clone();var g=4,b=new Array(1<<g);b[0]=new r(1).toRed(this),b[1]=c;for(var p=2;p<b.length;p++)b[p]=this.mul(b[p-1],c);var m=b[0],y=0,_=0,f=d.bitLength()%26;for(f===0&&(f=26),p=d.length-1;p>=0;p--){for(var k=d.words[p],M=f-1;M>=0;M--){var j=k>>M&1;if(m!==b[0]&&(m=this.sqr(m)),j===0&&y===0){_=0;continue}y<<=1,y|=j,_++,!(_!==g&&(p!==0||M!==0))&&(m=this.mul(m,b[y]),_=0,y=0)}f=26}return m},K.prototype.convertTo=function(c){var d=c.umod(this.m);return d===c?d.clone():d},K.prototype.convertFrom=function(c){var d=c.clone();return d.red=null,d},r.mont=function(c){return new C(c)};function C(A){K.call(this,A),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new r(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(C,K),C.prototype.convertTo=function(c){return this.imod(c.ushln(this.shift))},C.prototype.convertFrom=function(c){var d=this.imod(c.mul(this.rinv));return d.red=null,d},C.prototype.imul=function(c,d){if(c.isZero()||d.isZero())return c.words[0]=0,c.length=1,c;var g=c.imul(d),b=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=g.isub(b).iushrn(this.shift),m=p;return p.cmp(this.m)>=0?m=p.isub(this.m):p.cmpn(0)<0&&(m=p.iadd(this.m)),m._forceRed(this)},C.prototype.mul=function(c,d){if(c.isZero()||d.isZero())return new r(0)._forceRed(this);var g=c.mul(d),b=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=g.isub(b).iushrn(this.shift),m=p;return p.cmp(this.m)>=0?m=p.isub(this.m):p.cmpn(0)<0&&(m=p.iadd(this.m)),m._forceRed(this)},C.prototype.invm=function(c){var d=this.imod(c._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(typeof Za>"u"||Za,jl)});var yd={};bl(yd,{__addDisposableResource:()=>gd,__assign:()=>Xo,__asyncDelegator:()=>cd,__asyncGenerator:()=>ad,__asyncValues:()=>ud,__await:()=>Zi,__awaiter:()=>td,__classPrivateFieldGet:()=>hd,__classPrivateFieldIn:()=>pd,__classPrivateFieldSet:()=>md,__createBinding:()=>Yo,__decorate:()=>Yl,__disposeResources:()=>_d,__esDecorate:()=>j_,__exportStar:()=>id,__extends:()=>Xl,__generator:()=>nd,__importDefault:()=>fd,__importStar:()=>dd,__makeTemplateObject:()=>ld,__metadata:()=>ed,__param:()=>Ql,__propKey:()=>F_,__read:()=>oc,__rest:()=>Jl,__runInitializers:()=>N_,__setFunctionName:()=>R_,__spread:()=>rd,__spreadArray:()=>sd,__spreadArrays:()=>od,__values:()=>Jo,default:()=>$_});function Xl(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");rc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Jl(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n}function Yl(t,e,n,i){var r=arguments.length,o=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,n):i,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,i);else for(var a=t.length-1;a>=0;a--)(s=t[a])&&(o=(r<3?s(o):r>3?s(e,n,o):s(e,n))||o);return r>3&&o&&Object.defineProperty(e,n,o),o}function Ql(t,e){return function(n,i){e(n,i,t)}}function j_(t,e,n,i,r,o){function s(O){if(O!==void 0&&typeof O!="function")throw new TypeError("Function expected");return O}for(var a=i.kind,u=a==="getter"?"get":a==="setter"?"set":"value",l=!e&&t?i.static?t:t.prototype:null,h=e||(l?Object.getOwnPropertyDescriptor(l,i.name):{}),w,v=!1,T=n.length-1;T>=0;T--){var I={};for(var x in i)I[x]=x==="access"?{}:i[x];for(var x in i.access)I.access[x]=i.access[x];I.addInitializer=function(O){if(v)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(O||null))};var P=(0,n[T])(a==="accessor"?{get:h.get,set:h.set}:h[u],I);if(a==="accessor"){if(P===void 0)continue;if(P===null||typeof P!="object")throw new TypeError("Object expected");(w=s(P.get))&&(h.get=w),(w=s(P.set))&&(h.set=w),(w=s(P.init))&&r.unshift(w)}else(w=s(P))&&(a==="field"?r.unshift(w):h[u]=w)}l&&Object.defineProperty(l,i.name,h),v=!0}function N_(t,e,n){for(var i=arguments.length>2,r=0;r<e.length;r++)n=i?e[r].call(t,n):e[r].call(t);return i?n:void 0}function F_(t){return typeof t=="symbol"?t:"".concat(t)}function R_(t,e,n){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function ed(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function td(t,e,n,i){function r(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(h){try{l(i.next(h))}catch(w){s(w)}}function u(h){try{l(i.throw(h))}catch(w){s(w)}}function l(h){h.done?o(h.value):r(h.value).then(a,u)}l((i=i.apply(t,e||[])).next())})}function nd(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},i,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(l){return function(h){return u([l,h])}}function u(l){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,l[0]&&(n=0)),n;)try{if(i=1,r&&(o=l[0]&2?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,r=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){n.label=l[1];break}if(l[0]===6&&n.label<o[1]){n.label=o[1],o=l;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(l);break}o[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(h){l=[6,h],r=0}finally{i=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function id(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Yo(e,t,n)}function Jo(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function oc(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var i=n.call(t),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(s)throw s.error}}return o}function rd(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(oc(arguments[e]));return t}function od(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var i=Array(t),r=0,e=0;e<n;e++)for(var o=arguments[e],s=0,a=o.length;s<a;s++,r++)i[r]=o[s];return i}function sd(t,e,n){if(n||arguments.length===2)for(var i=0,r=e.length,o;i<r;i++)(o||!(i in e))&&(o||(o=Array.prototype.slice.call(e,0,i)),o[i]=e[i]);return t.concat(o||Array.prototype.slice.call(e))}function Zi(t){return this instanceof Zi?(this.v=t,this):new Zi(t)}function ad(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(v){i[v]&&(r[v]=function(T){return new Promise(function(I,x){o.push([v,T,I,x])>1||a(v,T)})})}function a(v,T){try{u(i[v](T))}catch(I){w(o[0][3],I)}}function u(v){v.value instanceof Zi?Promise.resolve(v.value.v).then(l,h):w(o[0][2],v)}function l(v){a("next",v)}function h(v){a("throw",v)}function w(v,T){v(T),o.shift(),o.length&&a(o[0][0],o[0][1])}}function cd(t){var e,n;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,o){e[r]=t[r]?function(s){return(n=!n)?{value:Zi(t[r](s)),done:!1}:o?o(s):s}:o}}function ud(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Jo=="function"?Jo(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(o){n[o]=t[o]&&function(s){return new Promise(function(a,u){s=t[o](s),r(a,u,s.done,s.value)})}}function r(o,s,a,u){Promise.resolve(u).then(function(l){o({value:l,done:a})},s)}}function ld(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function dd(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Yo(e,t,n);return q_(e,t),e}function fd(t){return t&&t.__esModule?t:{default:t}}function hd(t,e,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(t):i?i.value:e.get(t)}function md(t,e,n,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(t,n):r?r.value=n:e.set(t,n),n}function pd(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 gd(t,e,n){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose]}if(typeof i!="function")throw new TypeError("Object not disposable.");t.stack.push({value:e,dispose:i,async:n})}else n&&t.stack.push({async:!0});return e}function _d(t){function e(i){t.error=t.hasError?new L_(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}function n(){for(;t.stack.length;){var i=t.stack.pop();try{var r=i.dispose&&i.dispose.call(i.value);if(i.async)return Promise.resolve(r).then(n,function(o){return e(o),n()})}catch(o){e(o)}}if(t.hasError)throw t.error}return n()}var rc,Xo,Yo,q_,L_,$_,wd=Pg(()=>{"use strict";rc=function(t,e){return rc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},rc(t,e)};Xo=function(){return Xo=Object.assign||function(e){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Xo.apply(this,arguments)};Yo=Object.create?function(t,e,n,i){i===void 0&&(i=n);var r=Object.getOwnPropertyDescriptor(e,n);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,r)}:function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]};q_=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};L_=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var i=new Error(n);return i.name="SuppressedError",i.error=t,i.suppressed=e,i};$_={__extends:Xl,__assign:Xo,__rest:Jl,__decorate:Yl,__param:Ql,__metadata:ed,__awaiter:td,__generator:nd,__createBinding:Yo,__exportStar:id,__values:Jo,__read:oc,__spread:rd,__spreadArrays:od,__spreadArray:sd,__await:Zi,__asyncGenerator:ad,__asyncDelegator:cd,__asyncValues:ud,__makeTemplateObject:ld,__importStar:dd,__importDefault:fd,__classPrivateFieldGet:hd,__classPrivateFieldSet:md,__classPrivateFieldIn:pd,__addDisposableResource:gd,__disposeResources:_d}});var vd=yi((Qo,bd)=>{"use strict";(function(t,e){typeof Qo=="object"&&typeof bd<"u"?e(Qo,(wd(),kl(yd))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(Qo,function(t,e){"use strict";var n=function(){function p(m,y,_){_===void 0&&(_=0),this.startVertex=m,this.endVertex=y,this.weight=_}return p.prototype.getKey=function(){var m=this.startVertex.getKey(),y=this.endVertex.getKey();return m+"_"+y},p.prototype.reverse=function(){var m=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=m,this},p.prototype.clone=function(){return new p(this.startVertex,this.endVertex,this.weight)},p.prototype.toString=function(){return this.getKey()},p}();function i(p,m,y){if(y===void 0&&(y="cc-graph"),!p)throw new Error((y?"["+y+"]":"")+" Invariant failed: "+m)}function r(p,m){m===void 0&&(m=!0);var y=typeof p<"u"&&p!==null;return m?y&&p!=="undefined"&&p!=="null":y}var o=function(){function p(m){i(r(m),"Graph vertex must have a value"),this.value=m,this.edges=new Map}return p.prototype.addEdge=function(m){return this.edges.set(m.getKey(),m),this},p.prototype.deleteEdge=function(m){this.edges.delete(m.getKey())},p.prototype.getNeighbors=function(){var m=this,y=this.getEdges(),_=function(f){return f.startVertex===m?f.endVertex:f.startVertex};return y.map(_)},p.prototype.getEdges=function(){return Array.from(this.edges.values())},p.prototype.getDegree=function(){return this.getEdges().length},p.prototype.hasEdge=function(m){var y=this.getEdges().find(function(_){return _===m});return!!y},p.prototype.hasNeighbor=function(m){var y=this.getEdges().find(function(_){return _.startVertex===m||_.endVertex===m});return!!y},p.prototype.findEdge=function(m){var y=function(f){return f.startVertex===m||f.endVertex===m},_=this.getEdges().find(y);return _||null},p.prototype.getKey=function(){return this.value},p.prototype.deleteAllEdges=function(){var m=this;return this.getEdges().forEach(function(y){return m.deleteEdge(y)}),this},p.prototype.toString=function(m){return m?m(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 a=function(){function p(m){this.compare=m||p.defaultCompareFunction}return p.defaultCompareFunction=function(m,y){return m===y?s.EQUAL:m<y?s.LESS:s.GREATER},p.prototype.equal=function(m,y){return this.compare(m,y)===s.EQUAL},p.prototype.lessThan=function(m,y){return this.compare(m,y)===s.LESS},p.prototype.greaterThan=function(m,y){return this.compare(m,y)===s.GREATER},p.prototype.lessThanOrEqual=function(m,y){return this.lessThan(m,y)||this.equal(m,y)},p.prototype.greaterThanOrEqual=function(m,y){return this.greaterThan(m,y)||this.equal(m,y)},p.prototype.reverse=function(){var m=this.compare;this.compare=function(y,_){return m(_,y)}},p}(),u=function(){function p(m){this.value=m,this.next=null}return p}(),l=function(){function p(m){this.value=m,this.next=null,this.prev=null}return p}();var h=function(p,m){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,_){y.__proto__=_}||function(y,_){for(var f in _)_.hasOwnProperty(f)&&(y[f]=_[f])},h(p,m)};function w(p,m){h(p,m);function y(){this.constructor=p}p.prototype=m===null?Object.create(m):(y.prototype=m.prototype,new y)}function v(p,m){var y={label:0,sent:function(){if(k[0]&1)throw k[1];return k[1]},trys:[],ops:[]},_,f,k,M;return M={next:j(0),throw:j(1),return:j(2)},typeof Symbol=="function"&&(M[Symbol.iterator]=function(){return this}),M;function j(R){return function(W){return L([R,W])}}function L(R){if(_)throw new TypeError("Generator is already executing.");for(;y;)try{if(_=1,f&&(k=R[0]&2?f.return:R[0]?f.throw||((k=f.return)&&k.call(f),0):f.next)&&!(k=k.call(f,R[1])).done)return k;switch(f=0,k&&(R=[R[0]&2,k.value]),R[0]){case 0:case 1:k=R;break;case 4:return y.label++,{value:R[1],done:!1};case 5:y.label++,f=R[1],R=[0];continue;case 7:R=y.ops.pop(),y.trys.pop();continue;default:if(k=y.trys,!(k=k.length>0&&k[k.length-1])&&(R[0]===6||R[0]===2)){y=0;continue}if(R[0]===3&&(!k||R[1]>k[0]&&R[1]<k[3])){y.label=R[1];break}if(R[0]===6&&y.label<k[1]){y.label=k[1],k=R;break}if(k&&y.label<k[2]){y.label=k[2],y.ops.push(R);break}k[2]&&y.ops.pop(),y.trys.pop();continue}R=m.call(p,y)}catch(W){R=[6,W],f=0}finally{_=k=0}if(R[0]&5)throw R[1];return{value:R[0]?R[1]:void 0,done:!0}}}function T(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function I(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(T(arguments[m]));return p}var x="obfuse error occur";function P(p,m){if(!p)throw new Error("[linked-list] "+(m||x))}var O=-1,E=function(){function p(){for(var m=this,y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];this._head=null,this._tail=null,this._length=0,this.compare=new a,y.length>0&&y.forEach(function(f){m.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 m=!1,y=1;if(!this._head)return 0;for(var _=this._head,f=this._head;f.next&&f.next.next;)if(f=f.next.next,_=_.next,_===f){m=!0;break}if(m){for(f=f.next;_!==f;)y++,f=f.next;return y}else return 0},enumerable:!0,configurable:!0}),p.prototype.getNode=function(m){var y=this._length;P(y>0&&m>=0&&m<y,"[linked-list] index "+m+" out of scope of list, which length is "+y);for(var _=this._head,f=0;f<m;)_=_.next,f++;return _},p.prototype.get=function(m){var y=this.getNode(m);return y?y.value:null},p.prototype.find=function(m){var y=m.value,_=m.callback;if(!this._head)return null;for(var f=this._head;f;){if(_&&_(f.value)||y!==void 0&&this.compare.equal(f.value,y))return f;f=f.next}return null},p.prototype.indexOf=function(m){if(!this._head)return O;for(var y=this._head,_=-1;y.next;){if(_++,this.compare.equal(y.value,m))return _;y=y.next}return y===this._tail&&this.compare.equal(y.value,m)&&(_+=1),_},p.prototype.first=function(m){P(m>=0,"[linked-list] param 'num' ("+m+") should not less than 0");for(var y=this.iterator(),_=[],f=Math.min(m,this.length),k=0;k<f;k++){var M=y.next();_.push(M.value)}return _},p.prototype.toArray=function(){return I(this)},p.prototype.isEmpty=function(){return this._head===null},p.prototype.iterator=function(){var m;return v(this,function(y){switch(y.label){case 0:m=this._head,y.label=1;case 1:return m?[4,m.value]:[3,3];case 2:return y.sent(),m=m.next,[3,1];case 3:return[2]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p}(),B=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return p.apply(this,I(y))||this}return m.prototype.append=function(y){var _=new u(y);return this._tail?(this._tail.next=_,this._tail=_):this._head=this._tail=_,this._length++,!0},m.prototype.prepend=function(y){var _=new u(y);return this._head?(_.next=this._head,this._head=_):this._head=this._tail=_,this._length++,!0},m.prototype.remove=function(y){var _=this._head;if(_){if(this.compare.equal(_.value,y))return _.next?(this._head=_.next,_.next=null):this._head=this._tail=null,this._length--,y;for(var f=_;;){if(this.compare.equal(_.value,y))return _.next?f.next=_.next:(this._tail=f,this._tail.next=null),_.next=null,this._length--,y;if(_.next)f=_,_=_.next;else return}}},m.prototype.removeHead=function(){var y=this._head;if(y)return this._head.next?(this._head=y.next,y.next=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.removeTail=function(){var y=this._tail;if(y){if(!this._head.next)this._head=null,this._tail=null;else{for(var _=this._head;_.next!==y;)_=_.next;_.next=null,this._tail=_}return this._length--,y.value}},m.prototype.reverse=function(){if(this._head){var y=this._head,_=null,f;for(this._tail=this._head;y!==null;)f=y.next,y.next=_,_=y,y=f;this._head=_}},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(E),$=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.iterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,y===this._head&&(y=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=p.prototype[y].apply(this,_);return this.cyclization(),k},m.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},m.prototype.append=function(y){return this.mapToNormalListFn("append",y)},m.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},m.prototype.find=function(y){return this.mapToNormalListFn("find",y)},m.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},m.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(y){P(y>=0,"[linked-list] param 'num' ("+y+") should not less than 0");for(var _=this.circleIterator(),f=[],k=0;k<y;k++){var M=_.next();f.push(M.value)}return f},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(B),Z=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},m.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}($),H=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return p.apply(this,I(y))||this}return m.prototype.append=function(y){var _=new l(y);return this._tail?(this._tail.next=_,_.prev=this._tail,this._tail=_):this._head=this._tail=_,this._length++,!0},m.prototype.prepend=function(y){var _=new l(y);return this._head?(_.next=this._head,this._head.prev=_,this._head=_):this._head=this._tail=_,this._length++,!0},m.prototype.remove=function(y){var _=this._head;if(_){if(this.compare.equal(_.value,y))return _.next?(this._head=_.next,this._head.prev=null,_.next=_.prev=null):this._head=this._tail=null,this._length--,y;for(;;){if(this.compare.equal(_.value,y))return _.next?(_.prev.next=_.next,_.next.prev=_.prev,_.next=_.prev=null):(_.prev.next=null,this._tail=_.prev,_.next=_.prev=null),this._length--,_.value;if(_.next)_=_.next;else return}}},m.prototype.removeHead=function(){var y=this._head;if(y)return this._head.next?(y.next.prev=null,this._head=y.next,y.next=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.removeTail=function(){var y=this._tail;if(y)return this._head.next?(y.prev.next=null,this._tail=y.prev,y.next=y.prev=null):(this._head=null,this._tail=null),this._length--,y.value},m.prototype.reverse=function(){if(this._head){var y=this._head,_=null,f;for(this._tail=this._head;y!==null;)f=y.next,y.next=_,y.prev=f,_=y,y=f;this._head=_}},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(E),te=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.iterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,y===this._head&&(y=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var y;return v(this,function(_){switch(_.label){case 0:y=this._head,_.label=1;case 1:return y?[4,y.value]:[3,3];case 2:return _.sent(),y=y.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=p.prototype[y].apply(this,_);return this.cyclization(),k},m.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},m.prototype.append=function(y){return this.mapToNormalListFn("append",y)},m.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},m.prototype.find=function(y){return this.mapToNormalListFn("find",y)},m.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},m.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(y){P(y>=0,"[linked-list] param 'num' ("+y+") should not less than 0");for(var _=this.circleIterator(),f=[],k=0;k<y;k++){var M=_.next();f.push(M.value)}return f},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(H),U=function(p){w(m,p);function m(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=p.apply(this,I(y))||this;return f.cyclization(),f}return m.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},m.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},m.prototype.clone=function(){var y=this.toArray();return new(m.bind.apply(m,I([void 0],y)))},m}(te);function V(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function F(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(V(arguments[m]));return p}var K=function(){function p(){for(var m=[],y=0;y<arguments.length;y++)m[y]=arguments[y];this.queue=new(B.bind.apply(B,F([void 0],m)))}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(m){return this.queue.append(m)},p.prototype.dequeue=function(){var m=this.queue.removeHead();return typeof m<"u"?m:void 0},p.prototype.toArray=function(){return this.queue.toArray()},p}();function C(p,m){var y=typeof Symbol=="function"&&p[Symbol.iterator];if(!y)return p;var _=y.call(p),f,k=[],M;try{for(;(m===void 0||m-- >0)&&!(f=_.next()).done;)k.push(f.value)}catch(j){M={error:j}}finally{try{f&&!f.done&&(y=_.return)&&y.call(_)}finally{if(M)throw M.error}}return k}function A(){for(var p=[],m=0;m<arguments.length;m++)p=p.concat(C(arguments[m]));return p}var c=function(){function p(){for(var m=[],y=0;y<arguments.length;y++)m[y]=arguments[y];this.stack=new(B.bind.apply(B,A([void 0],m)))}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(m){return this.stack.append(m)},p.prototype.pop=function(){var m=this.stack.removeTail();return typeof m<"u"?m:void 0},p.prototype.popBottom=function(){var m=this.stack.removeHead();return typeof m<"u"?m:void 0},p.prototype.toArray=function(){return this.stack.toArray()},p}();function d(p,m,y,_){if(p){m.push(p),_.set(p.getKey(),!0);var f=p.getNeighbors().filter(function(k){return!_.get(k.getKey())});y.push(f)}}function g(p,m,y){var _=p.pop();_&&y.set(_.getKey(),!1),m.pop()}var b=function(){function p(m){m===void 0&&(m=!1),this.vertices={},this.edges={},this.isDirected=m}return p.prototype.addVertex=function(m){return this.vertices[m.getKey()]=m,this},p.prototype.getVertexByKey=function(m){return this.vertices[m]},p.prototype.getNeighbors=function(m){return m.getNeighbors()},p.prototype.getAllVertices=function(){return Object.values(this.vertices)},p.prototype.getAllEdges=function(){return Object.values(this.edges)},p.prototype.addEdge=function(m,y){if(y===void 0&&(y=!1),this.edges[m.getKey()]){if(y)return this;i(!1,"Edge has already been added before")}var _=this.getVertexByKey(m.startVertex.getKey()),f=this.getVertexByKey(m.endVertex.getKey());if(_||(this.addVertex(m.startVertex),_=this.getVertexByKey(m.startVertex.getKey())),f||(this.addVertex(m.endVertex),f=this.getVertexByKey(m.endVertex.getKey())),this.edges[m.getKey()]=m,this.isDirected)_.addEdge(m);else{_.addEdge(m);var k=m.clone();f.addEdge(k.reverse())}return this},p.prototype.deleteEdge=function(m,y){if(y===void 0&&(y=!1),!this.edges[m.getKey()]){if(y)return this;i(!1,"Edge not found in graph")}delete this.edges[m.getKey()];var _=this.getVertexByKey(m.startVertex.getKey()),f=this.getVertexByKey(m.endVertex.getKey());return _.deleteEdge(m),f.deleteEdge(m),this},p.prototype.findEdge=function(m,y){var _=this.getVertexByKey(m.getKey());return _?_.findEdge(y):null},p.prototype.getWeight=function(){return this.getAllEdges().reduce(function(m,y){return m+y.weight},0)},p.prototype.reverse=function(){var m=this;return this.getAllEdges().forEach(function(y){m.deleteEdge(y),y.reverse(),m.addEdge(y)}),this},p.prototype.getVerticesIndices=function(){var m={};return this.getAllVertices().forEach(function(y,_){m[y.getKey()]=_}),m},p.prototype.getAdjacencyMatrix=function(){var m=this,y=this.getAllVertices(),_=this.getVerticesIndices(),f=Array(y.length).fill(null).map(function(){return Array(y.length).fill(1/0)});return y.forEach(function(k,M){k.getNeighbors().forEach(function(j){var L=_[j.getKey()],R=m.findEdge(k,j);R&&(f[M][L]=R.weight)})}),f},p.prototype.toString=function(){return Object.keys(this.vertices).toString()},p.prototype.bfs=function(m){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new K,_.enqueue(m),k.label=1;case 1:return _.isEmpty()?[3,4]:(f=_.dequeue(),f&&!y.has(f.getKey())?[4,f]:[3,3]);case 2:k.sent(),y.set(f.getKey(),f),f.getNeighbors().forEach(function(M){return _.enqueue(M)}),k.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.dfs=function(m){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new c,_.push(m),k.label=1;case 1:return _.isEmpty()?[3,4]:(f=_.pop(),f&&!y.has(f.getKey())?[4,f]:[3,3]);case 2:k.sent(),y.set(f.getKey(),f),f.getNeighbors().forEach(function(M){return _.push(M)}),k.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.findAllPath=function(m,y){var _,f,k,M,j,L,R;return e.__generator(this,function(W){switch(W.label){case 0:return _=[],m!==y?[3,2]:(_.push(m),[4,_]);case 1:return W.sent(),[2];case 2:f=new Map,k=new c,M=new c,d(m,k,M,f),W.label=3;case 3:if(k.isEmpty())return[3,6];if(j=M.pop(),j&&j.length)L=j.shift(),M.push(j),L&&d(L,k,M,f);else return M.push(j),g(k,M,f),[3,3];return R=k.peek,R!==y?[3,5]:[4,k.toArray()];case 4:W.sent(),g(k,M,f),W.label=5;case 5:return[3,3];case 6:return[2]}})},p}();t.GraphEdge=n,t.GraphVertex=o,t.Graph=b,Object.defineProperty(t,"__esModule",{value:!0})})});var Lh=yi((ku,Tu)=>{"use strict";(function(t,e){typeof ku=="object"&&typeof Tu<"u"?Tu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(ku,function(){"use strict";var t=Math.imul,e=Math.clz32;function n(U){"@babel/helpers - typeof";return n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(V){return typeof V}:function(V){return V&&typeof Symbol=="function"&&V.constructor===Symbol&&V!==Symbol.prototype?"symbol":typeof V},n(U)}function i(U,V){if(!(U instanceof V))throw new TypeError("Cannot call a class as a function")}function r(U,V){for(var F,K=0;K<V.length;K++)F=V[K],F.enumerable=F.enumerable||!1,F.configurable=!0,"value"in F&&(F.writable=!0),Object.defineProperty(U,F.key,F)}function o(U,V,F){return V&&r(U.prototype,V),F&&r(U,F),Object.defineProperty(U,"prototype",{writable:!1}),U}function s(U,V){if(typeof V!="function"&&V!==null)throw new TypeError("Super expression must either be null or a function");U.prototype=Object.create(V&&V.prototype,{constructor:{value:U,writable:!0,configurable:!0}}),Object.defineProperty(U,"prototype",{writable:!1}),V&&u(U,V)}function a(U){return a=Object.setPrototypeOf?Object.getPrototypeOf:function(V){return V.__proto__||Object.getPrototypeOf(V)},a(U)}function u(U,V){return u=Object.setPrototypeOf||function(F,K){return F.__proto__=K,F},u(U,V)}function l(){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 h(){return h=l()?Reflect.construct:function(U,V,F){var K=[null];K.push.apply(K,V);var C=Function.bind.apply(U,K),A=new C;return F&&u(A,F.prototype),A},h.apply(null,arguments)}function w(U){return Function.toString.call(U).indexOf("[native code]")!==-1}function v(U){var V=typeof Map=="function"?new Map:void 0;return v=function(F){function K(){return h(F,arguments,a(this).constructor)}if(F===null||!w(F))return F;if(typeof F!="function")throw new TypeError("Super expression must either be null or a function");if(typeof V<"u"){if(V.has(F))return V.get(F);V.set(F,K)}return K.prototype=Object.create(F.prototype,{constructor:{value:K,enumerable:!1,writable:!0,configurable:!0}}),u(K,F)},v(U)}function T(U){if(U===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return U}function I(U,V){if(V&&(typeof V=="object"||typeof V=="function"))return V;if(V!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return T(U)}function x(U){var V=l();return function(){var F,K=a(U);if(V){var C=a(this).constructor;F=Reflect.construct(K,arguments,C)}else F=K.apply(this,arguments);return I(this,F)}}function P(U,V){return O(U)||E(U,V)||B(U,V)||Z()}function O(U){if(Array.isArray(U))return U}function E(U,V){var F=U==null?null:typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(F!=null){var K,C,A=[],c=!0,d=!1;try{for(F=F.call(U);!(c=(K=F.next()).done)&&(A.push(K.value),!(V&&A.length===V));c=!0);}catch(g){d=!0,C=g}finally{try{c||F.return==null||F.return()}finally{if(d)throw C}}return A}}function B(U,V){if(U){if(typeof U=="string")return $(U,V);var F=Object.prototype.toString.call(U).slice(8,-1);return F==="Object"&&U.constructor&&(F=U.constructor.name),F==="Map"||F==="Set"?Array.from(U):F==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(F)?$(U,V):void 0}}function $(U,V){(V==null||V>U.length)&&(V=U.length);for(var F=0,K=Array(V);F<V;F++)K[F]=U[F];return K}function Z(){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 H(U,V){var F=typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(!F){if(Array.isArray(U)||(F=B(U))||V&&U&&typeof U.length=="number"){F&&(U=F);var K=0,C=function(){};return{s:C,n:function(){return K>=U.length?{done:!0}:{done:!1,value:U[K++]}},e:function(g){throw g},f:C}}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 A,c=!0,d=!1;return{s:function(){F=F.call(U)},n:function(){var g=F.next();return c=g.done,g},e:function(g){d=!0,A=g},f:function(){try{c||F.return==null||F.return()}finally{if(d)throw A}}}}var te=function(U){var V=Math.abs,F=Math.max,K=Math.floor;function C(c,d){var g;if(i(this,C),g=A.call(this,c),g.sign=d,Object.setPrototypeOf(T(g),C.prototype),c>C.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return g}s(C,U);var A=x(C);return o(C,[{key:"toDebugString",value:function(){var c,d=["BigInt["],g=H(this);try{for(g.s();!(c=g.n()).done;){var b=c.value;d.push((b&&(b>>>0).toString(16))+", ")}}catch(p){g.e(p)}finally{g.f()}return d.push("]"),d.join("")}},{key:"toString",value:function(){var c=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>c||36<c)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":c&c-1?C.__toStringGeneric(this,c,!1):C.__toStringBasePowerOfTwo(this,c)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var c=new C(this.length,this.sign),d=0;d<this.length;d++)c[d]=this[d];return c}},{key:"__trim",value:function(){for(var c=this.length,d=this[c-1];d===0;)c--,d=this[c-1],this.pop();return c===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var c=0;c<this.length;c++)this[c]=0}},{key:"__clzmsd",value:function(){return C.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(c,d,g){g>this.length&&(g=this.length);for(var b=32767&c,p=c>>>15,m=0,y=d,_=0;_<g;_++){var f=this.__digit(_),k=32767&f,M=f>>>15,j=C.__imul(k,b),L=C.__imul(k,p),R=C.__imul(M,b),W=C.__imul(M,p),ne=y+j+m;m=ne>>>30,ne&=1073741823,ne+=((32767&L)<<15)+((32767&R)<<15),m+=ne>>>30,y=W+(L>>>15)+(R>>>15),this.__setDigit(_,1073741823&ne)}if(m!==0||y!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(c,d,g){for(var b,p=0,m=0;m<g;m++)b=this.__halfDigit(d+m)+c.__halfDigit(m)+p,p=b>>>15,this.__setHalfDigit(d+m,32767&b);return p}},{key:"__inplaceSub",value:function(c,d,g){var b=0;if(1&d){d>>=1;for(var p=this.__digit(d),m=32767&p,y=0;y<g-1>>>1;y++){var _=c.__digit(y),f=(p>>>15)-(32767&_)-b;b=1&f>>>15,this.__setDigit(d+y,(32767&f)<<15|32767&m),p=this.__digit(d+y+1),m=(32767&p)-(_>>>15)-b,b=1&m>>>15}var k=c.__digit(y),M=(p>>>15)-(32767&k)-b;if(b=1&M>>>15,this.__setDigit(d+y,(32767&M)<<15|32767&m),d+y+1>=this.length)throw new RangeError("out of bounds");!(1&g)&&(p=this.__digit(d+y+1),m=(32767&p)-(k>>>15)-b,b=1&m>>>15,this.__setDigit(d+c.length,1073709056&p|32767&m))}else{d>>=1;for(var j=0;j<c.length-1;j++){var L=this.__digit(d+j),R=c.__digit(j),W=(32767&L)-(32767&R)-b;b=1&W>>>15;var ne=(L>>>15)-(R>>>15)-b;b=1&ne>>>15,this.__setDigit(d+j,(32767&ne)<<15|32767&W)}var me=this.__digit(d+j),ue=c.__digit(j),pe=(32767&me)-(32767&ue)-b;b=1&pe>>>15;var vt=0;!(1&g)&&(vt=(me>>>15)-(ue>>>15)-b,b=1&vt>>>15),this.__setDigit(d+j,(32767&vt)<<15|32767&pe)}return b}},{key:"__inplaceRightShift",value:function(c){if(c!==0){for(var d,g=this.__digit(0)>>>c,b=this.length-1,p=0;p<b;p++)d=this.__digit(p+1),this.__setDigit(p,1073741823&d<<30-c|g),g=d>>>c;this.__setDigit(b,g)}}},{key:"__digit",value:function(c){return this[c]}},{key:"__unsignedDigit",value:function(c){return this[c]>>>0}},{key:"__setDigit",value:function(c,d){this[c]=0|d}},{key:"__setDigitGrow",value:function(c,d){this[c]=0|d}},{key:"__halfDigitLength",value:function(){var c=this.length;return 32767>=this.__unsignedDigit(c-1)?2*c-1:2*c}},{key:"__halfDigit",value:function(c){return 32767&this[c>>>1]>>>15*(1&c)}},{key:"__setHalfDigit",value:function(c,d){var g=c>>>1,b=this.__digit(g),p=1&c?32767&b|d<<15:1073709056&b|32767&d;this.__setDigit(g,p)}}],[{key:"BigInt",value:function(c){var d=Number.isFinite;if(typeof c=="number"){if(c===0)return C.__zero();if(C.__isOneDigitInt(c))return 0>c?C.__oneDigit(-c,!0):C.__oneDigit(c,!1);if(!d(c)||K(c)!==c)throw new RangeError("The number "+c+" cannot be converted to BigInt because it is not an integer");return C.__fromDouble(c)}if(typeof c=="string"){var g=C.__fromString(c);if(g===null)throw new SyntaxError("Cannot convert "+c+" to a BigInt");return g}if(typeof c=="boolean")return c===!0?C.__oneDigit(1,!1):C.__zero();if(n(c)==="object"){if(c.constructor===C)return c;var b=C.__toPrimitive(c);return C.BigInt(b)}throw new TypeError("Cannot convert "+c+" to a BigInt")}},{key:"toNumber",value:function(c){var d=c.length;if(d===0)return 0;if(d===1){var g=c.__unsignedDigit(0);return c.sign?-g:g}var b=c.__digit(d-1),p=C.__clz30(b),m=30*d-p;if(1024<m)return c.sign?-1/0:1/0;var y=m-1,_=b,f=d-1,k=p+3,M=k===32?0:_<<k;M>>>=12;var j=k-12,L=12<=k?0:_<<20+k,R=20+k;for(0<j&&0<f&&(f--,_=c.__digit(f),M|=_>>>30-j,L=_<<j+2,R=j+2);0<R&&0<f;)f--,_=c.__digit(f),L|=30<=R?_<<R-30:_>>>30-R,R-=30;var W=C.__decideRounding(c,R,f,_);if((W===1||W===0&&(1&L)==1)&&(L=L+1>>>0,L===0&&(M++,M>>>20!=0&&(M=0,y++,1023<y))))return c.sign?-1/0:1/0;var ne=c.sign?-2147483648:0;return y=y+1023<<20,C.__kBitConversionInts[1]=ne|y|M,C.__kBitConversionInts[0]=L,C.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(c){if(c.length===0)return c;var d=c.__copy();return d.sign=!c.sign,d}},{key:"bitwiseNot",value:function(c){return c.sign?C.__absoluteSubOne(c).__trim():C.__absoluteAddOne(c,!0)}},{key:"exponentiate",value:function(c,d){if(d.sign)throw new RangeError("Exponent must be positive");if(d.length===0)return C.__oneDigit(1,!1);if(c.length===0)return c;if(c.length===1&&c.__digit(0)===1)return c.sign&&!(1&d.__digit(0))?C.unaryMinus(c):c;if(1<d.length)throw new RangeError("BigInt too big");var g=d.__unsignedDigit(0);if(g===1)return c;if(g>=C.__kMaxLengthBits)throw new RangeError("BigInt too big");if(c.length===1&&c.__digit(0)===2){var b=1+(0|g/30),p=c.sign&&(1&g)!=0,m=new C(b,p);m.__initializeDigits();var y=1<<g%30;return m.__setDigit(b-1,y),m}var _=null,f=c;for(1&g&&(_=c),g>>=1;g!==0;g>>=1)f=C.multiply(f,f),1&g&&(_===null?_=f:_=C.multiply(_,f));return _}},{key:"multiply",value:function(c,d){if(c.length===0)return c;if(d.length===0)return d;var g=c.length+d.length;30<=c.__clzmsd()+d.__clzmsd()&&g--;var b=new C(g,c.sign!==d.sign);b.__initializeDigits();for(var p=0;p<c.length;p++)C.__multiplyAccumulate(d,c.__digit(p),b,p);return b.__trim()}},{key:"divide",value:function(c,d){if(d.length===0)throw new RangeError("Division by zero");if(0>C.__absoluteCompare(c,d))return C.__zero();var g,b=c.sign!==d.sign,p=d.__unsignedDigit(0);if(d.length===1&&32767>=p){if(p===1)return b===c.sign?c:C.unaryMinus(c);g=C.__absoluteDivSmall(c,p,null)}else g=C.__absoluteDivLarge(c,d,!0,!1);return g.sign=b,g.__trim()}},{key:"remainder",value:function(d,g){if(g.length===0)throw new RangeError("Division by zero");if(0>C.__absoluteCompare(d,g))return d;var b=g.__unsignedDigit(0);if(g.length===1&&32767>=b){if(b===1)return C.__zero();var p=C.__absoluteModSmall(d,b);return p===0?C.__zero():C.__oneDigit(p,d.sign)}var m=C.__absoluteDivLarge(d,g,!1,!0);return m.sign=d.sign,m.__trim()}},{key:"add",value:function(c,d){var g=c.sign;return g===d.sign?C.__absoluteAdd(c,d,g):0<=C.__absoluteCompare(c,d)?C.__absoluteSub(c,d,g):C.__absoluteSub(d,c,!g)}},{key:"subtract",value:function(c,d){var g=c.sign;return g===d.sign?0<=C.__absoluteCompare(c,d)?C.__absoluteSub(c,d,g):C.__absoluteSub(d,c,!g):C.__absoluteAdd(c,d,g)}},{key:"leftShift",value:function(c,d){return d.length===0||c.length===0?c:d.sign?C.__rightShiftByAbsolute(c,d):C.__leftShiftByAbsolute(c,d)}},{key:"signedRightShift",value:function(c,d){return d.length===0||c.length===0?c:d.sign?C.__leftShiftByAbsolute(c,d):C.__rightShiftByAbsolute(c,d)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(c,d){return 0>C.__compareToBigInt(c,d)}},{key:"lessThanOrEqual",value:function(c,d){return 0>=C.__compareToBigInt(c,d)}},{key:"greaterThan",value:function(c,d){return 0<C.__compareToBigInt(c,d)}},{key:"greaterThanOrEqual",value:function(c,d){return 0<=C.__compareToBigInt(c,d)}},{key:"equal",value:function(c,d){if(c.sign!==d.sign||c.length!==d.length)return!1;for(var g=0;g<c.length;g++)if(c.__digit(g)!==d.__digit(g))return!1;return!0}},{key:"notEqual",value:function(c,d){return!C.equal(c,d)}},{key:"bitwiseAnd",value:function(c,d){if(!c.sign&&!d.sign)return C.__absoluteAnd(c,d).__trim();if(c.sign&&d.sign){var g=F(c.length,d.length)+1,b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return b=C.__absoluteOr(b,p,b),C.__absoluteAddOne(b,!0,b).__trim()}if(c.sign){var m=[d,c];c=m[0],d=m[1]}return C.__absoluteAndNot(c,C.__absoluteSubOne(d)).__trim()}},{key:"bitwiseXor",value:function(c,d){if(!c.sign&&!d.sign)return C.__absoluteXor(c,d).__trim();if(c.sign&&d.sign){var g=F(c.length,d.length),b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return C.__absoluteXor(b,p,b).__trim()}var m=F(c.length,d.length)+1;if(c.sign){var y=[d,c];c=y[0],d=y[1]}var _=C.__absoluteSubOne(d,m);return _=C.__absoluteXor(_,c,_),C.__absoluteAddOne(_,!0,_).__trim()}},{key:"bitwiseOr",value:function(c,d){var g=F(c.length,d.length);if(!c.sign&&!d.sign)return C.__absoluteOr(c,d).__trim();if(c.sign&&d.sign){var b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return b=C.__absoluteAnd(b,p,b),C.__absoluteAddOne(b,!0,b).__trim()}if(c.sign){var m=[d,c];c=m[0],d=m[1]}var y=C.__absoluteSubOne(d,g);return y=C.__absoluteAndNot(y,c,y),C.__absoluteAddOne(y,!0,y).__trim()}},{key:"asIntN",value:function(c,d){if(d.length===0)return d;if(c=K(c),0>c)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(c===0)return C.__zero();if(c>=C.__kMaxLengthBits)return d;var g=0|(c+29)/30;if(d.length<g)return d;var b=d.__unsignedDigit(g-1),p=1<<(c-1)%30;if(d.length===g&&b<p)return d;if((b&p)!==p)return C.__truncateToNBits(c,d);if(!d.sign)return C.__truncateAndSubFromPowerOfTwo(c,d,!0);if(!(b&p-1)){for(var m=g-2;0<=m;m--)if(d.__digit(m)!==0)return C.__truncateAndSubFromPowerOfTwo(c,d,!1);return d.length===g&&b===p?d:C.__truncateToNBits(c,d)}return C.__truncateAndSubFromPowerOfTwo(c,d,!1)}},{key:"asUintN",value:function(c,d){if(d.length===0)return d;if(c=K(c),0>c)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(c===0)return C.__zero();if(d.sign){if(c>C.__kMaxLengthBits)throw new RangeError("BigInt too big");return C.__truncateAndSubFromPowerOfTwo(c,d,!1)}if(c>=C.__kMaxLengthBits)return d;var g=0|(c+29)/30;if(d.length<g)return d;var b=c%30;if(d.length==g){if(b===0)return d;var p=d.__digit(g-1);if(!(p>>>b))return d}return C.__truncateToNBits(c,d)}},{key:"ADD",value:function(c,d){if(c=C.__toPrimitive(c),d=C.__toPrimitive(d),typeof c=="string")return typeof d!="string"&&(d=d.toString()),c+d;if(typeof d=="string")return c.toString()+d;if(c=C.__toNumeric(c),d=C.__toNumeric(d),C.__isBigInt(c)&&C.__isBigInt(d))return C.add(c,d);if(typeof c=="number"&&typeof d=="number")return c+d;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(c,d){return C.__compare(c,d,0)}},{key:"LE",value:function(c,d){return C.__compare(c,d,1)}},{key:"GT",value:function(c,d){return C.__compare(c,d,2)}},{key:"GE",value:function(c,d){return C.__compare(c,d,3)}},{key:"EQ",value:function(c,d){for(;;){if(C.__isBigInt(c))return C.__isBigInt(d)?C.equal(c,d):C.EQ(d,c);if(typeof c=="number"){if(C.__isBigInt(d))return C.__equalToNumber(d,c);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(typeof c=="string"){if(C.__isBigInt(d))return c=C.__fromString(c),c!==null&&C.equal(c,d);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(typeof c=="boolean"){if(C.__isBigInt(d))return C.__equalToNumber(d,+c);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(n(c)==="symbol"){if(C.__isBigInt(d))return!1;if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(n(c)==="object"){if(n(d)==="object"&&d.constructor!==C)return c==d;c=C.__toPrimitive(c)}else return c==d}}},{key:"NE",value:function(c,d){return!C.EQ(c,d)}},{key:"DataViewGetBigInt64",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return C.asIntN(64,C.DataViewGetBigUint64(c,d,g))}},{key:"DataViewGetBigUint64",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0&&arguments[2],b=g?[4,0]:[0,4],p=P(b,2),m=p[0],y=p[1],_=c.getUint32(d+m,g),f=c.getUint32(d+y,g),k=new C(3,!1);return k.__setDigit(0,1073741823&f),k.__setDigit(1,(268435455&_)<<2|f>>>30),k.__setDigit(2,_>>>28),k.__trim()}},{key:"DataViewSetBigInt64",value:function(c,d,g){var b=3<arguments.length&&arguments[3]!==void 0&&arguments[3];C.DataViewSetBigUint64(c,d,g,b)}},{key:"DataViewSetBigUint64",value:function(c,d,g){var b=3<arguments.length&&arguments[3]!==void 0&&arguments[3];g=C.asUintN(64,g);var p=0,m=0;if(0<g.length&&(m=g.__digit(0),1<g.length)){var y=g.__digit(1);m|=y<<30,p=y>>>2,2<g.length&&(p|=g.__digit(2)<<28)}var _=b?[4,0]:[0,4],f=P(_,2),k=f[0],M=f[1];c.setUint32(d+k,p,b),c.setUint32(d+M,m,b)}},{key:"__zero",value:function(){return new C(0,!1)}},{key:"__oneDigit",value:function(c,d){var g=new C(1,d);return g.__setDigit(0,c),g}},{key:"__decideRounding",value:function(c,d,g,b){if(0<d)return-1;var p;if(0>d)p=-d-1;else{if(g===0)return-1;g--,b=c.__digit(g),p=29}var m=1<<p;if(!(b&m))return-1;if(m-=1,(b&m)!=0)return 1;for(;0<g;)if(g--,c.__digit(g)!==0)return 1;return 0}},{key:"__fromDouble",value:function(c){C.__kBitConversionDouble[0]=c;var d,g=2047&C.__kBitConversionInts[1]>>>20,b=g-1023,p=(0|b/30)+1,m=new C(p,0>c),y=1048575&C.__kBitConversionInts[1]|1048576,_=C.__kBitConversionInts[0],f=20,k=b%30,M=0;if(k<f){var j=f-k;M=j+32,d=y>>>j,y=y<<32-j|_>>>j,_<<=32-j}else if(k===f)M=32,d=y,y=_,_=0;else{var L=k-f;M=32-L,d=y<<L|_>>>32-L,y=_<<L,_=0}m.__setDigit(p-1,d);for(var R=p-2;0<=R;R--)0<M?(M-=30,d=y>>>2,y=y<<30|_>>>2,_<<=30):d=0,m.__setDigit(R,d);return m.__trim()}},{key:"__isWhitespace",value:function(c){return 13>=c&&9<=c||(159>=c?c==32:131071>=c?c==160||c==5760:196607>=c?(c&=131071,10>=c||c==40||c==41||c==47||c==95||c==4096):c==65279)}},{key:"__fromString",value:function(c){var d=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,g=0,b=c.length,p=0;if(p===b)return C.__zero();for(var m=c.charCodeAt(p);C.__isWhitespace(m);){if(++p===b)return C.__zero();m=c.charCodeAt(p)}if(m===43){if(++p===b)return null;m=c.charCodeAt(p),g=1}else if(m===45){if(++p===b)return null;m=c.charCodeAt(p),g=-1}if(d===0){if(d=10,m===48){if(++p===b)return C.__zero();if(m=c.charCodeAt(p),m===88||m===120){if(d=16,++p===b)return null;m=c.charCodeAt(p)}else if(m===79||m===111){if(d=8,++p===b)return null;m=c.charCodeAt(p)}else if(m===66||m===98){if(d=2,++p===b)return null;m=c.charCodeAt(p)}}}else if(d===16&&m===48){if(++p===b)return C.__zero();if(m=c.charCodeAt(p),m===88||m===120){if(++p===b)return null;m=c.charCodeAt(p)}}if(g!==0&&d!==10)return null;for(;m===48;){if(++p===b)return C.__zero();m=c.charCodeAt(p)}var y=b-p,_=C.__kMaxBitsPerChar[d],f=C.__kBitsPerCharTableMultiplier-1;if(y>1073741824/_)return null;var k=_*y+f>>>C.__kBitsPerCharTableShift,M=new C(0|(k+29)/30,!1),j=10>d?d:10,L=10<d?d-10:0;if(d&d-1){M.__initializeDigits();var vt=!1,De=0;do{for(var je,Ki=0,Ne=1;;){if(je=void 0,m-48>>>0<j)je=m-48;else if((32|m)-97>>>0<L)je=(32|m)-87;else{vt=!0;break}var Fe=Ne*d;if(1073741823<Fe)break;if(Ne=Fe,Ki=Ki*d+je,De++,++p===b){vt=!0;break}m=c.charCodeAt(p)}f=30*C.__kBitsPerCharTableMultiplier-1;var Fo=0|(_*De+f>>>C.__kBitsPerCharTableShift)/30;M.__inplaceMultiplyAdd(Ne,Ki,Fo)}while(!vt)}else{_>>=C.__kBitsPerCharTableShift;var R=[],W=[],ne=!1;do{for(var me,ue=0,pe=0;;){if(me=void 0,m-48>>>0<j)me=m-48;else if((32|m)-97>>>0<L)me=(32|m)-87;else{ne=!0;break}if(pe+=_,ue=ue<<_|me,++p===b){ne=!0;break}if(m=c.charCodeAt(p),30<pe+_)break}R.push(ue),W.push(pe)}while(!ne);C.__fillFromParts(M,R,W)}if(p!==b){if(!C.__isWhitespace(m))return null;for(p++;p<b;p++)if(m=c.charCodeAt(p),!C.__isWhitespace(m))return null}return M.sign=g===-1,M.__trim()}},{key:"__fillFromParts",value:function(c,d,g){for(var b=0,p=0,m=0,y=d.length-1;0<=y;y--){var _=d[y],f=g[y];p|=_<<m,m+=f,m===30?(c.__setDigit(b++,p),m=0,p=0):30<m&&(c.__setDigit(b++,1073741823&p),m-=30,p=_>>>f-m)}if(p!==0){if(b>=c.length)throw new Error("implementation bug");c.__setDigit(b++,p)}for(;b<c.length;b++)c.__setDigit(b,0)}},{key:"__toStringBasePowerOfTwo",value:function(c,d){var g=c.length,b=d-1;b=(85&b>>>1)+(85&b),b=(51&b>>>2)+(51&b),b=(15&b>>>4)+(15&b);var p=b,m=d-1,y=c.__digit(g-1),_=C.__clz30(y),f=0|(30*g-_+p-1)/p;if(c.sign&&f++,268435456<f)throw new Error("string too long");for(var k=Array(f),M=f-1,j=0,L=0,R=0;R<g-1;R++){var W=c.__digit(R),ne=(j|W<<L)&m;k[M--]=C.__kConversionChars[ne];var me=p-L;for(j=W>>>me,L=30-me;L>=p;)k[M--]=C.__kConversionChars[j&m],j>>>=p,L-=p}var ue=(j|y<<L)&m;for(k[M--]=C.__kConversionChars[ue],j=y>>>p-L;j!==0;)k[M--]=C.__kConversionChars[j&m],j>>>=p;if(c.sign&&(k[M--]="-"),M!==-1)throw new Error("implementation bug");return k.join("")}},{key:"__toStringGeneric",value:function(c,d,g){var b=c.length;if(b===0)return"";if(b===1){var p=c.__unsignedDigit(0).toString(d);return g===!1&&c.sign&&(p="-"+p),p}var m=30*b-C.__clz30(c.__digit(b-1)),y=C.__kMaxBitsPerChar[d],_=y-1,f=m*C.__kBitsPerCharTableMultiplier;f+=_-1,f=0|f/_;var k,M,j=f+1>>1,L=C.exponentiate(C.__oneDigit(d,!1),C.__oneDigit(j,!1)),R=L.__unsignedDigit(0);if(L.length===1&&32767>=R){k=new C(c.length,!1),k.__initializeDigits();for(var W,ne=0,me=2*c.length-1;0<=me;me--)W=ne<<15|c.__halfDigit(me),k.__setHalfDigit(me,0|W/R),ne=0|W%R;M=ne.toString(d)}else{var ue=C.__absoluteDivLarge(c,L,!0,!0);k=ue.quotient;var pe=ue.remainder.__trim();M=C.__toStringGeneric(pe,d,!0)}k.__trim();for(var vt=C.__toStringGeneric(k,d,!0);M.length<j;)M="0"+M;return g===!1&&c.sign&&(vt="-"+vt),vt+M}},{key:"__unequalSign",value:function(c){return c?-1:1}},{key:"__absoluteGreater",value:function(c){return c?-1:1}},{key:"__absoluteLess",value:function(c){return c?1:-1}},{key:"__compareToBigInt",value:function(c,d){var g=c.sign;if(g!==d.sign)return C.__unequalSign(g);var b=C.__absoluteCompare(c,d);return 0<b?C.__absoluteGreater(g):0>b?C.__absoluteLess(g):0}},{key:"__compareToNumber",value:function(c,d){if(C.__isOneDigitInt(d)){var g=c.sign,b=0>d;if(g!==b)return C.__unequalSign(g);if(c.length===0){if(b)throw new Error("implementation bug");return d===0?0:-1}if(1<c.length)return C.__absoluteGreater(g);var p=V(d),m=c.__unsignedDigit(0);return m>p?C.__absoluteGreater(g):m<p?C.__absoluteLess(g):0}return C.__compareToDouble(c,d)}},{key:"__compareToDouble",value:function(c,d){if(d!==d)return d;if(d===1/0)return-1;if(d===-1/0)return 1;var g=c.sign;if(g!==0>d)return C.__unequalSign(g);if(d===0)throw new Error("implementation bug: should be handled elsewhere");if(c.length===0)return-1;C.__kBitConversionDouble[0]=d;var b=2047&C.__kBitConversionInts[1]>>>20;if(b==2047)throw new Error("implementation bug: handled elsewhere");var p=b-1023;if(0>p)return C.__absoluteGreater(g);var m=c.length,y=c.__digit(m-1),_=C.__clz30(y),f=30*m-_,k=p+1;if(f<k)return C.__absoluteLess(g);if(f>k)return C.__absoluteGreater(g);var M=1048576|1048575&C.__kBitConversionInts[1],j=C.__kBitConversionInts[0],L=20,R=29-_;if(R!==(0|(f-1)%30))throw new Error("implementation bug");var W,ne=0;if(R<L){var me=L-R;ne=me+32,W=M>>>me,M=M<<32-me|j>>>me,j<<=32-me}else if(R===L)ne=32,W=M,M=j,j=0;else{var ue=R-L;ne=32-ue,W=M<<ue|j>>>32-ue,M=j<<ue,j=0}if(y>>>=0,W>>>=0,y>W)return C.__absoluteGreater(g);if(y<W)return C.__absoluteLess(g);for(var pe=m-2;0<=pe;pe--){0<ne?(ne-=30,W=M>>>2,M=M<<30|j>>>2,j<<=30):W=0;var vt=c.__unsignedDigit(pe);if(vt>W)return C.__absoluteGreater(g);if(vt<W)return C.__absoluteLess(g)}if(M!==0||j!==0){if(ne===0)throw new Error("implementation bug");return C.__absoluteLess(g)}return 0}},{key:"__equalToNumber",value:function(c,d){return C.__isOneDigitInt(d)?d===0?c.length===0:c.length===1&&c.sign===0>d&&c.__unsignedDigit(0)===V(d):C.__compareToDouble(c,d)===0}},{key:"__comparisonResultToBool",value:function(c,d){return d===0?0>c:d===1?0>=c:d===2?0<c:d===3?0<=c:void 0}},{key:"__compare",value:function(c,d,g){if(c=C.__toPrimitive(c),d=C.__toPrimitive(d),typeof c=="string"&&typeof d=="string")switch(g){case 0:return c<d;case 1:return c<=d;case 2:return c>d;case 3:return c>=d}if(C.__isBigInt(c)&&typeof d=="string")return d=C.__fromString(d),d!==null&&C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(typeof c=="string"&&C.__isBigInt(d))return c=C.__fromString(c),c!==null&&C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(c=C.__toNumeric(c),d=C.__toNumeric(d),C.__isBigInt(c)){if(C.__isBigInt(d))return C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(typeof d!="number")throw new Error("implementation bug");return C.__comparisonResultToBool(C.__compareToNumber(c,d),g)}if(typeof c!="number")throw new Error("implementation bug");if(C.__isBigInt(d))return C.__comparisonResultToBool(C.__compareToNumber(d,c),2^g);if(typeof d!="number")throw new Error("implementation bug");return g===0?c<d:g===1?c<=d:g===2?c>d:g===3?c>=d:void 0}},{key:"__absoluteAdd",value:function(c,d,g){if(c.length<d.length)return C.__absoluteAdd(d,c,g);if(c.length===0)return c;if(d.length===0)return c.sign===g?c:C.unaryMinus(c);var b=c.length;(c.__clzmsd()===0||d.length===c.length&&d.__clzmsd()===0)&&b++;for(var p,m=new C(b,g),y=0,_=0;_<d.length;_++)p=c.__digit(_)+d.__digit(_)+y,y=p>>>30,m.__setDigit(_,1073741823&p);for(;_<c.length;_++){var f=c.__digit(_)+y;y=f>>>30,m.__setDigit(_,1073741823&f)}return _<m.length&&m.__setDigit(_,y),m.__trim()}},{key:"__absoluteSub",value:function(c,d,g){if(c.length===0)return c;if(d.length===0)return c.sign===g?c:C.unaryMinus(c);for(var b,p=new C(c.length,g),m=0,y=0;y<d.length;y++)b=c.__digit(y)-d.__digit(y)-m,m=1&b>>>30,p.__setDigit(y,1073741823&b);for(;y<c.length;y++){var _=c.__digit(y)-m;m=1&_>>>30,p.__setDigit(y,1073741823&_)}return p.__trim()}},{key:"__absoluteAddOne",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length;g===null?g=new C(b,d):g.sign=d;for(var p,m=1,y=0;y<b;y++)p=c.__digit(y)+m,m=p>>>30,g.__setDigit(y,1073741823&p);return m!==0&&g.__setDigitGrow(b,1),g}},{key:"__absoluteSubOne",value:function(c,d){var g=c.length;d=d||g;for(var b,p=new C(d,!1),m=1,y=0;y<g;y++)b=c.__digit(y)-m,m=1&b>>>30,p.__setDigit(y,1073741823&b);if(m!==0)throw new Error("implementation bug");for(var _=g;_<d;_++)p.__setDigit(_,0);return p}},{key:"__absoluteAnd",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=m;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)&d.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteAndNot",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;b<p&&(m=b);var y=b;g===null?g=new C(y,!1):y=g.length;for(var _=0;_<m;_++)g.__setDigit(_,c.__digit(_)&~d.__digit(_));for(;_<b;_++)g.__setDigit(_,c.__digit(_));for(;_<y;_++)g.__setDigit(_,0);return g}},{key:"__absoluteOr",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=b;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)|d.__digit(k));for(;k<b;k++)g.__setDigit(k,c.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteXor",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=b;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)^d.__digit(k));for(;k<b;k++)g.__setDigit(k,c.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteCompare",value:function(c,d){var g=c.length-d.length;if(g!=0)return g;for(var b=c.length-1;0<=b&&c.__digit(b)===d.__digit(b);)b--;return 0>b?0:c.__unsignedDigit(b)>d.__unsignedDigit(b)?1:-1}},{key:"__multiplyAccumulate",value:function(c,d,g,b){if(d!==0){for(var p=32767&d,m=d>>>15,y=0,_=0,f=0;f<c.length;f++,b++){var k=g.__digit(b),M=c.__digit(f),j=32767&M,L=M>>>15,R=C.__imul(j,p),W=C.__imul(j,m),ne=C.__imul(L,p),me=C.__imul(L,m);k+=_+R+y,y=k>>>30,k&=1073741823,k+=((32767&W)<<15)+((32767&ne)<<15),y+=k>>>30,_=me+(W>>>15)+(ne>>>15),g.__setDigit(b,1073741823&k)}for(;y!==0||_!==0;b++){var ue=g.__digit(b);ue+=y+_,_=0,y=ue>>>30,g.__setDigit(b,1073741823&ue)}}}},{key:"__internalMultiplyAdd",value:function(c,d,g,b,p){for(var m=g,y=0,_=0;_<b;_++){var f=c.__digit(_),k=C.__imul(32767&f,d),M=C.__imul(f>>>15,d),j=k+((32767&M)<<15)+y+m;m=j>>>30,y=M>>>15,p.__setDigit(_,1073741823&j)}if(p.length>b)for(p.__setDigit(b++,m+y);b<p.length;)p.__setDigit(b++,0);else if(m+y!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;g===null&&(g=new C(c.length,!1));for(var b=0,p=2*c.length-1;0<=p;p-=2){var m=(b<<15|c.__halfDigit(p))>>>0,y=0|m/d;b=0|m%d,m=(b<<15|c.__halfDigit(p-1))>>>0;var _=0|m/d;b=0|m%d,g.__setDigit(p>>>1,y<<15|_)}return g}},{key:"__absoluteModSmall",value:function(c,d){for(var g,b=0,p=2*c.length-1;0<=p;p--)g=(b<<15|c.__halfDigit(p))>>>0,b=0|g%d;return b}},{key:"__absoluteDivLarge",value:function(c,d,g,b){var p=d.__halfDigitLength(),m=d.length,y=c.__halfDigitLength()-p,_=null;g&&(_=new C(y+2>>>1,!1),_.__initializeDigits());var f=new C(p+2>>>1,!1);f.__initializeDigits();var k=C.__clz15(d.__halfDigit(p-1));0<k&&(d=C.__specialLeftShift(d,k,0));for(var M=C.__specialLeftShift(c,k,1),j=d.__halfDigit(p-1),L=0,R=y;0<=R;R--){var W=32767,ne=M.__halfDigit(R+p);if(ne!==j){var me=(ne<<15|M.__halfDigit(R+p-1))>>>0;W=0|me/j;for(var ue=0|me%j,pe=d.__halfDigit(p-2),vt=M.__halfDigit(R+p-2);C.__imul(W,pe)>>>0>(ue<<16|vt)>>>0&&(W--,ue+=j,!(32767<ue)););}C.__internalMultiplyAdd(d,W,0,m,f);var De=M.__inplaceSub(f,R,p+1);De!==0&&(De=M.__inplaceAdd(d,R,p),M.__setHalfDigit(R+p,32767&M.__halfDigit(R+p)+De),W--),g&&(1&R?L=W<<15:_.__setDigit(R>>>1,L|W))}if(b)return M.__inplaceRightShift(k),g?{quotient:_,remainder:M}:M;if(g)return _;throw new Error("unreachable")}},{key:"__clz15",value:function(c){return C.__clz30(c)-15}},{key:"__specialLeftShift",value:function(c,d,g){var b=c.length,p=new C(b+g,!1);if(d===0){for(var m=0;m<b;m++)p.__setDigit(m,c.__digit(m));return 0<g&&p.__setDigit(b,0),p}for(var y,_=0,f=0;f<b;f++)y=c.__digit(f),p.__setDigit(f,1073741823&y<<d|_),_=y>>>30-d;return 0<g&&p.__setDigit(b,_),p}},{key:"__leftShiftByAbsolute",value:function(c,d){var g=C.__toShiftAmount(d);if(0>g)throw new RangeError("BigInt too big");var b=0|g/30,p=g%30,m=c.length,y=p!==0&&c.__digit(m-1)>>>30-p!=0,_=m+b+(y?1:0),f=new C(_,c.sign);if(p===0){for(var k=0;k<b;k++)f.__setDigit(k,0);for(;k<_;k++)f.__setDigit(k,c.__digit(k-b))}else{for(var M=0,j=0;j<b;j++)f.__setDigit(j,0);for(var L,R=0;R<m;R++)L=c.__digit(R),f.__setDigit(R+b,1073741823&L<<p|M),M=L>>>30-p;if(y)f.__setDigit(m+b,M);else if(M!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(c,d){var g=c.length,b=c.sign,p=C.__toShiftAmount(d);if(0>p)return C.__rightShiftByMaximum(b);var m=0|p/30,y=p%30,_=g-m;if(0>=_)return C.__rightShiftByMaximum(b);var f=!1;if(b){if(c.__digit(m)&(1<<y)-1)f=!0;else for(var k=0;k<m;k++)if(c.__digit(k)!==0){f=!0;break}}if(f&&y===0){var M=c.__digit(g-1);!~M&&_++}var j=new C(_,b);if(y===0){j.__setDigit(_-1,0);for(var L=m;L<g;L++)j.__setDigit(L-m,c.__digit(L))}else{for(var R,W=c.__digit(m)>>>y,ne=g-m-1,me=0;me<ne;me++)R=c.__digit(me+m+1),j.__setDigit(me,1073741823&R<<30-y|W),W=R>>>y;j.__setDigit(ne,W)}return f&&(j=C.__absoluteAddOne(j,!0,j)),j.__trim()}},{key:"__rightShiftByMaximum",value:function(c){return c?C.__oneDigit(1,!0):C.__zero()}},{key:"__toShiftAmount",value:function(c){if(1<c.length)return-1;var d=c.__unsignedDigit(0);return d>C.__kMaxLengthBits?-1:d}},{key:"__toPrimitive",value:function(c){var d=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(n(c)!=="object"||c.constructor===C)return c;if(typeof Symbol<"u"&&n(Symbol.toPrimitive)==="symbol"){var g=c[Symbol.toPrimitive];if(g){var b=g(d);if(n(b)!=="object")return b;throw new TypeError("Cannot convert object to primitive value")}}var p=c.valueOf;if(p){var m=p.call(c);if(n(m)!=="object")return m}var y=c.toString;if(y){var _=y.call(c);if(n(_)!=="object")return _}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(c){return C.__isBigInt(c)?c:+c}},{key:"__isBigInt",value:function(c){return n(c)==="object"&&c!==null&&c.constructor===C}},{key:"__truncateToNBits",value:function(c,d){for(var g=0|(c+29)/30,b=new C(g,d.sign),p=g-1,m=0;m<p;m++)b.__setDigit(m,d.__digit(m));var y=d.__digit(p);if(c%30!=0){var _=32-c%30;y=y<<_>>>_}return b.__setDigit(p,y),b.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(c,d,g){for(var b=Math.min,p,m=0|(c+29)/30,y=new C(m,g),_=0,f=m-1,k=0,M=b(f,d.length);_<M;_++)p=0-d.__digit(_)-k,k=1&p>>>30,y.__setDigit(_,1073741823&p);for(;_<f;_++)y.__setDigit(_,0|1073741823&-k);var j,L=f<d.length?d.__digit(f):0,R=c%30;if(R===0)j=0-L-k,j&=1073741823;else{var W=32-R;L=L<<W>>>W;var ne=1<<32-W;j=ne-L-k,j&=ne-1}return y.__setDigit(f,j),y.__trim()}},{key:"__digitPow",value:function(c,d){for(var g=1;0<d;)1&d&&(g*=c),d>>>=1,c*=c;return g}},{key:"__isOneDigitInt",value:function(c){return(1073741823&c)===c}}]),C}(v(Array));return te.__kMaxLength=33554432,te.__kMaxLengthBits=te.__kMaxLength<<5,te.__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],te.__kBitsPerCharTableShift=5,te.__kBitsPerCharTableMultiplier=1<<te.__kBitsPerCharTableShift,te.__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"],te.__kBitConversionBuffer=new ArrayBuffer(8),te.__kBitConversionDouble=new Float64Array(te.__kBitConversionBuffer),te.__kBitConversionInts=new Int32Array(te.__kBitConversionBuffer),te.__clz30=e?function(U){return e(U)-2}:function(U){var V=Math.LN2,F=Math.log;return U===0?30:0|29-(0|F(U>>>0)/V)},te.__imul=t||function(U,V){return 0|U*V},te})});var Y1={};wl(Y1,{AddressBookSDK:()=>Vi,COIN_TYPE_ARG_REGEX:()=>Wu,Coin:()=>Mo,CoinHelper:()=>Eo,CreateHelper:()=>zi,DEV_API_URL:()=>yg,DEV_SYNCING_URL:()=>wg,ENV_CONFIGS:()=>kg,Formatter:()=>Vn,HexToUint8Array:()=>ma,LOCAL_API_URL:()=>nl,LOCAL_SYNCING_URL:()=>il,MAINNET_RPC_URL:()=>tl,MSafeAccount:()=>Ui,MSafeClient:()=>Ca,MSafeEnv:()=>_g,MSafeGlobals:()=>No,PREV_API_URL:()=>bg,PROD_API_URL:()=>vg,SUI_COIN:()=>Z1,SignatureVerifier:()=>Zu,TESTNET_RPC_URL:()=>Ta,Uint8ArrayToHex:()=>H1,addPrefix:()=>Hu,getAllCoins:()=>J1,getMSafeConfig:()=>rl,getPublicKeyFromChain:()=>Xu,stringToBuffer:()=>ha});module.exports=vl(Y1);var Mn=require("@msafe/sui3-utils"),zi=class{constructor(e,n){this.globals=e;this.pkHelper=n}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let n=await this.reduceCreationInfoToRawConfig(e);return new Mn.MultiSigAccount(n).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,n){let i=Mn.PublicKeySerde.de(n);if(!(0,Mn.isSameAddress)(e,i.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,i)}async submitMSafeCreation(e){let n=await this.validateCreateInfo(e),i=Mn.SigningMessageHelper.createMSafeMessage(n),r=await this.globals.wallet.signPersonalMessage({messageStr:i});return await this.submitToBackend(e,r.signature),n}async reduceCreationInfoToRawConfig(e){let n=await this.getPublicKeyBatch(e.owners.map(i=>i.address));return n.forEach((i,r)=>{if(i===void 0)throw new Error(`Unknown public key for address: ${e.owners[r].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((i,r)=>({publicKey:n[r],weight:i.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,n){let i=await this.pkHelper.getPublicKeyBatch(e.owners.map(r=>r.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((r,o)=>({address:r.address,weight:r.weight,...Mn.PublicKeySerde.ser(i[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:n})}};var Sa=require("@msafe/sui3-utils");var kl=require("@msafe/sui3-utils"),Vi=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let n=kl.SigningMessageHelper.updateAddressBookMessage(e),i=await this.globals.wallet.signPersonalMessage({messageStr:n});return this.globals.backend.updateAddressBook({updates:e,signature:i.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var qo=class{constructor(e){this.globals=e}async getMSafeByStatus(e,n){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:n})}async updateMSafeStatus(e,n){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:n})}};var vm=require("@msafe/sui3-utils"),km=ge(Lo(),1);var Nr=require("@mysten/sui.js/utils"),Qi=require("@mysten/sui.js/transactions"),rn=ge(ke(),1);var Ha=8192;function Za(t){if(t.length<Ha)return btoa(String.fromCharCode(...t));let e="";for(var n=0;n<t.length;n+=Ha){let i=t.slice(n,n+Ha);e+=String.fromCharCode(...i)}return btoa(e)}var i0=require("@mysten/sui.js/keypairs/ed25519"),r0=require("@mysten/sui.js/keypairs/secp256k1"),Xn=ge(ke(),1),wt=ge(ke(),1);var Gi=9e15,Zn=1e9,Xa="0123456789abcdef",Uo="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ko="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ja={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Gi,maxE:Gi,crypto:!1},Rl,Bn,fe=!0,Vo="[DecimalError] ",Hn=Vo+"Invalid argument: ",ql=Vo+"Precision limit exceeded",Ll=Vo+"crypto unavailable",$l="[object Decimal]",jt=Math.floor,kt=Math.pow,$g=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Ug=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Kg=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Ul=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,fn=1e7,le=7,zg=9007199254740991,Vg=Uo.length-1,Ya=Ko.length-1,z={toStringTag:$l};z.absoluteValue=z.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),oe(t)};z.ceil=function(){return oe(new this.constructor(this),this.e+1,2)};z.clampedTo=z.clamp=function(t,e){var n,i=this,r=i.constructor;if(t=new r(t),e=new r(e),!t.s||!e.s)return new r(NaN);if(t.gt(e))throw Error(Hn+e);return n=i.cmp(t),n<0?t:i.cmp(e)>0?e:new r(i)};z.comparedTo=z.cmp=function(t){var e,n,i,r,o=this,s=o.d,a=(t=new o.constructor(t)).d,u=o.s,l=t.s;if(!s||!a)return!u||!l?NaN:u!==l?u:s===a?0:!s^u<0?1:-1;if(!s[0]||!a[0])return s[0]?u:a[0]?-l:0;if(u!==l)return u;if(o.e!==t.e)return o.e>t.e^u<0?1:-1;for(i=s.length,r=a.length,e=0,n=i<r?i:r;e<n;++e)if(s[e]!==a[e])return s[e]>a[e]^u<0?1:-1;return i===r?0:i>r^u<0?1:-1};z.cosine=z.cos=function(){var t,e,n=this,i=n.constructor;return n.d?n.d[0]?(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+le,i.rounding=1,n=Gg(i,Wl(i,n)),i.precision=t,i.rounding=e,oe(Bn==2||Bn==3?n.neg():n,t,e,!0)):new i(1):new i(NaN)};z.cubeRoot=z.cbrt=function(){var t,e,n,i,r,o,s,a,u,l,h=this,w=h.constructor;if(!h.isFinite()||h.isZero())return new w(h);for(fe=!1,o=h.s*kt(h.s*h,1/3),!o||Math.abs(o)==1/0?(n=xt(h.d),t=h.e,(o=(t-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=kt(n,1/3),t=jt((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?n="5e"+t:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+t),i=new w(n),i.s=h.s):i=new w(o.toString()),s=(t=w.precision)+3;;)if(a=i,u=a.times(a).times(a),l=u.plus(h),i=Ee(l.plus(h).times(a),l.plus(u),s+2,1),xt(a.d).slice(0,s)===(n=xt(i.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!r&&n=="4999"){if(!r&&(oe(a,t+1,0),a.times(a).times(a).eq(h))){i=a;break}s+=4,r=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(oe(i,t+1,1),e=!i.times(i).times(i).eq(h));break}return fe=!0,oe(i,t,w.rounding,e)};z.decimalPlaces=z.dp=function(){var t,e=this.d,n=NaN;if(e){if(t=e.length-1,n=(t-jt(this.e/le))*le,t=e[t],t)for(;t%10==0;t/=10)n--;n<0&&(n=0)}return n};z.dividedBy=z.div=function(t){return Ee(this,new this.constructor(t))};z.dividedToIntegerBy=z.divToInt=function(t){var e=this,n=e.constructor;return oe(Ee(e,new n(t),0,1,1),n.precision,n.rounding)};z.equals=z.eq=function(t){return this.cmp(t)===0};z.floor=function(){return oe(new this.constructor(this),this.e+1,3)};z.greaterThan=z.gt=function(t){return this.cmp(t)>0};z.greaterThanOrEqualTo=z.gte=function(t){var e=this.cmp(t);return e==1||e===0};z.hyperbolicCosine=z.cosh=function(){var t,e,n,i,r,o=this,s=o.constructor,a=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return a;n=s.precision,i=s.rounding,s.precision=n+Math.max(o.e,o.sd())+4,s.rounding=1,r=o.d.length,r<32?(t=Math.ceil(r/3),e=(1/Wo(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=Wi(s,1,o.times(e),new s(1),!0);for(var u,l=t,h=new s(8);l--;)u=o.times(o),o=a.minus(u.times(h.minus(u.times(h))));return oe(o,s.precision=n,s.rounding=i,!0)};z.hyperbolicSine=z.sinh=function(){var t,e,n,i,r=this,o=r.constructor;if(!r.isFinite()||r.isZero())return new o(r);if(e=o.precision,n=o.rounding,o.precision=e+Math.max(r.e,r.sd())+4,o.rounding=1,i=r.d.length,i<3)r=Wi(o,2,r,r,!0);else{t=1.4*Math.sqrt(i),t=t>16?16:t|0,r=r.times(1/Wo(5,t)),r=Wi(o,2,r,r,!0);for(var s,a=new o(5),u=new o(16),l=new o(20);t--;)s=r.times(r),r=r.times(a.plus(s.times(u.times(s).plus(l))))}return o.precision=e,o.rounding=n,oe(r,e,n,!0)};z.hyperbolicTangent=z.tanh=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+7,i.rounding=1,Ee(n.sinh(),n.cosh(),i.precision=t,i.rounding=e)):new i(n.s)};z.inverseCosine=z.acos=function(){var t,e=this,n=e.constructor,i=e.abs().cmp(1),r=n.precision,o=n.rounding;return i!==-1?i===0?e.isNeg()?dn(n,r,o):new n(0):new n(NaN):e.isZero()?dn(n,r+4,o).times(.5):(n.precision=r+6,n.rounding=1,e=e.asin(),t=dn(n,r+4,o).times(.5),n.precision=r,n.rounding=o,t.minus(e))};z.inverseHyperbolicCosine=z.acosh=function(){var t,e,n=this,i=n.constructor;return n.lte(1)?new i(n.eq(1)?0:NaN):n.isFinite()?(t=i.precision,e=i.rounding,i.precision=t+Math.max(Math.abs(n.e),n.sd())+4,i.rounding=1,fe=!1,n=n.times(n).minus(1).sqrt().plus(n),fe=!0,i.precision=t,i.rounding=e,n.ln()):new i(n)};z.inverseHyperbolicSine=z.asinh=function(){var t,e,n=this,i=n.constructor;return!n.isFinite()||n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+2*Math.max(Math.abs(n.e),n.sd())+6,i.rounding=1,fe=!1,n=n.times(n).plus(1).sqrt().plus(n),fe=!0,i.precision=t,i.rounding=e,n.ln())};z.inverseHyperbolicTangent=z.atanh=function(){var t,e,n,i,r=this,o=r.constructor;return r.isFinite()?r.e>=0?new o(r.abs().eq(1)?r.s/0:r.isZero()?r:NaN):(t=o.precision,e=o.rounding,i=r.sd(),Math.max(i,t)<2*-r.e-1?oe(new o(r),t,e,!0):(o.precision=n=i-r.e,r=Ee(r.plus(1),new o(1).minus(r),n+t,1),o.precision=t+4,o.rounding=1,r=r.ln(),o.precision=t,o.rounding=e,r.times(.5))):new o(NaN)};z.inverseSine=z.asin=function(){var t,e,n,i,r=this,o=r.constructor;return r.isZero()?new o(r):(e=r.abs().cmp(1),n=o.precision,i=o.rounding,e!==-1?e===0?(t=dn(o,n+4,i).times(.5),t.s=r.s,t):new o(NaN):(o.precision=n+6,o.rounding=1,r=r.div(new o(1).minus(r.times(r)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=i,r.times(2)))};z.inverseTangent=z.atan=function(){var t,e,n,i,r,o,s,a,u,l=this,h=l.constructor,w=h.precision,v=h.rounding;if(l.isFinite()){if(l.isZero())return new h(l);if(l.abs().eq(1)&&w+4<=Ya)return s=dn(h,w+4,v).times(.25),s.s=l.s,s}else{if(!l.s)return new h(NaN);if(w+4<=Ya)return s=dn(h,w+4,v).times(.5),s.s=l.s,s}for(h.precision=a=w+10,h.rounding=1,n=Math.min(28,a/le+2|0),t=n;t;--t)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(fe=!1,e=Math.ceil(a/le),i=1,u=l.times(l),s=new h(l),r=l;t!==-1;)if(r=r.times(u),o=s.minus(r.div(i+=2)),r=r.times(u),s=o.plus(r.div(i+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return n&&(s=s.times(2<<n-1)),fe=!0,oe(s,h.precision=w,h.rounding=v,!0)};z.isFinite=function(){return!!this.d};z.isInteger=z.isInt=function(){return!!this.d&&jt(this.e/le)>this.d.length-2};z.isNaN=function(){return!this.s};z.isNegative=z.isNeg=function(){return this.s<0};z.isPositive=z.isPos=function(){return this.s>0};z.isZero=function(){return!!this.d&&this.d[0]===0};z.lessThan=z.lt=function(t){return this.cmp(t)<0};z.lessThanOrEqualTo=z.lte=function(t){return this.cmp(t)<1};z.logarithm=z.log=function(t){var e,n,i,r,o,s,a,u,l=this,h=l.constructor,w=h.precision,v=h.rounding,T=5;if(t==null)t=new h(10),e=!0;else{if(t=new h(t),n=t.d,t.s<0||!n||!n[0]||t.eq(1))return new h(NaN);e=t.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new h(n&&!n[0]?-1/0:l.s!=1?NaN:n?0:1/0);if(e)if(n.length>1)o=!0;else{for(r=n[0];r%10===0;)r/=10;o=r!==1}if(fe=!1,a=w+T,s=Wn(l,a),i=e?zo(h,a+10):Wn(t,a),u=Ee(s,i,a,1),Mr(u.d,r=w,v))do if(a+=10,s=Wn(l,a),i=e?zo(h,a+10):Wn(t,a),u=Ee(s,i,a,1),!o){+xt(u.d).slice(r+1,r+15)+1==1e14&&(u=oe(u,w+1,0));break}while(Mr(u.d,r+=10,v));return fe=!0,oe(u,w,v)};z.minus=z.sub=function(t){var e,n,i,r,o,s,a,u,l,h,w,v,T=this,I=T.constructor;if(t=new I(t),!T.d||!t.d)return!T.s||!t.s?t=new I(NaN):T.d?t.s=-t.s:t=new I(t.d||T.s!==t.s?T:NaN),t;if(T.s!=t.s)return t.s=-t.s,T.plus(t);if(l=T.d,v=t.d,a=I.precision,u=I.rounding,!l[0]||!v[0]){if(v[0])t.s=-t.s;else if(l[0])t=new I(T);else return new I(u===3?-0:0);return fe?oe(t,a,u):t}if(n=jt(t.e/le),h=jt(T.e/le),l=l.slice(),o=h-n,o){for(w=o<0,w?(e=l,o=-o,s=v.length):(e=v,n=h,s=l.length),i=Math.max(Math.ceil(a/le),s)+2,o>i&&(o=i,e.length=1),e.reverse(),i=o;i--;)e.push(0);e.reverse()}else{for(i=l.length,s=v.length,w=i<s,w&&(s=i),i=0;i<s;i++)if(l[i]!=v[i]){w=l[i]<v[i];break}o=0}for(w&&(e=l,l=v,v=e,t.s=-t.s),s=l.length,i=v.length-s;i>0;--i)l[s++]=0;for(i=v.length;i>o;){if(l[--i]<v[i]){for(r=i;r&&l[--r]===0;)l[r]=fn-1;--l[r],l[i]+=fn}l[i]-=v[i]}for(;l[--s]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(t.d=l,t.e=Go(l,n),fe?oe(t,a,u):t):new I(u===3?-0:0)};z.modulo=z.mod=function(t){var e,n=this,i=n.constructor;return t=new i(t),!n.d||!t.s||t.d&&!t.d[0]?new i(NaN):!t.d||n.d&&!n.d[0]?oe(new i(n),i.precision,i.rounding):(fe=!1,i.modulo==9?(e=Ee(n,t.abs(),0,3,1),e.s*=t.s):e=Ee(n,t,0,i.modulo,1),e=e.times(t),fe=!0,n.minus(e))};z.naturalExponential=z.exp=function(){return Qa(this)};z.naturalLogarithm=z.ln=function(){return Wn(this)};z.negated=z.neg=function(){var t=new this.constructor(this);return t.s=-t.s,oe(t)};z.plus=z.add=function(t){var e,n,i,r,o,s,a,u,l,h,w=this,v=w.constructor;if(t=new v(t),!w.d||!t.d)return!w.s||!t.s?t=new v(NaN):w.d||(t=new v(t.d||w.s===t.s?w:NaN)),t;if(w.s!=t.s)return t.s=-t.s,w.minus(t);if(l=w.d,h=t.d,a=v.precision,u=v.rounding,!l[0]||!h[0])return h[0]||(t=new v(w)),fe?oe(t,a,u):t;if(o=jt(w.e/le),i=jt(t.e/le),l=l.slice(),r=o-i,r){for(r<0?(n=l,r=-r,s=h.length):(n=h,i=o,s=l.length),o=Math.ceil(a/le),s=o>s?o+1:s+1,r>s&&(r=s,n.length=1),n.reverse();r--;)n.push(0);n.reverse()}for(s=l.length,r=h.length,s-r<0&&(r=s,n=h,h=l,l=n),e=0;r;)e=(l[--r]=l[r]+h[r]+e)/fn|0,l[r]%=fn;for(e&&(l.unshift(e),++i),s=l.length;l[--s]==0;)l.pop();return t.d=l,t.e=Go(l,i),fe?oe(t,a,u):t};z.precision=z.sd=function(t){var e,n=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Hn+t);return n.d?(e=Kl(n.d),t&&n.e+1>e&&(e=n.e+1)):e=NaN,e};z.round=function(){var t=this,e=t.constructor;return oe(new e(t),t.e+1,e.rounding)};z.sine=z.sin=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+le,i.rounding=1,n=Hg(i,Wl(i,n)),i.precision=t,i.rounding=e,oe(Bn>2?n.neg():n,t,e,!0)):new i(NaN)};z.squareRoot=z.sqrt=function(){var t,e,n,i,r,o,s=this,a=s.d,u=s.e,l=s.s,h=s.constructor;if(l!==1||!a||!a[0])return new h(!l||l<0&&(!a||a[0])?NaN:a?s:1/0);for(fe=!1,l=Math.sqrt(+s),l==0||l==1/0?(e=xt(a),(e.length+u)%2==0&&(e+="0"),l=Math.sqrt(e),u=jt((u+1)/2)-(u<0||u%2),l==1/0?e="5e"+u:(e=l.toExponential(),e=e.slice(0,e.indexOf("e")+1)+u),i=new h(e)):i=new h(l.toString()),n=(u=h.precision)+3;;)if(o=i,i=o.plus(Ee(s,o,n+2,1)).times(.5),xt(o.d).slice(0,n)===(e=xt(i.d)).slice(0,n))if(e=e.slice(n-3,n+1),e=="9999"||!r&&e=="4999"){if(!r&&(oe(o,u+1,0),o.times(o).eq(s))){i=o;break}n+=4,r=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(oe(i,u+1,1),t=!i.times(i).eq(s));break}return fe=!0,oe(i,u,h.rounding,t)};z.tangent=z.tan=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+10,i.rounding=1,n=n.sin(),n.s=1,n=Ee(n,new i(1).minus(n.times(n)).sqrt(),t+10,0),i.precision=t,i.rounding=e,oe(Bn==2||Bn==4?n.neg():n,t,e,!0)):new i(NaN)};z.times=z.mul=function(t){var e,n,i,r,o,s,a,u,l,h=this,w=h.constructor,v=h.d,T=(t=new w(t)).d;if(t.s*=h.s,!v||!v[0]||!T||!T[0])return new w(!t.s||v&&!v[0]&&!T||T&&!T[0]&&!v?NaN:!v||!T?t.s/0:t.s*0);for(n=jt(h.e/le)+jt(t.e/le),u=v.length,l=T.length,u<l&&(o=v,v=T,T=o,s=u,u=l,l=s),o=[],s=u+l,i=s;i--;)o.push(0);for(i=l;--i>=0;){for(e=0,r=u+i;r>i;)a=o[r]+T[i]*v[r-i-1]+e,o[r--]=a%fn|0,e=a/fn|0;o[r]=(o[r]+e)%fn|0}for(;!o[--s];)o.pop();return e?++n:o.shift(),t.d=o,t.e=Go(o,n),fe?oe(t,w.precision,w.rounding):t};z.toBinary=function(t,e){return tc(this,2,t,e)};z.toDecimalPlaces=z.toDP=function(t,e){var n=this,i=n.constructor;return n=new i(n),t===void 0?n:(Kt(t,0,Zn),e===void 0?e=i.rounding:Kt(e,0,8),oe(n,t+n.e+1,e))};z.toExponential=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Tn(i,!0):(Kt(t,0,Zn),e===void 0?e=r.rounding:Kt(e,0,8),i=oe(new r(i),t+1,e),n=Tn(i,!0,t+1)),i.isNeg()&&!i.isZero()?"-"+n:n};z.toFixed=function(t,e){var n,i,r=this,o=r.constructor;return t===void 0?n=Tn(r):(Kt(t,0,Zn),e===void 0?e=o.rounding:Kt(e,0,8),i=oe(new o(r),t+r.e+1,e),n=Tn(i,!1,t+i.e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};z.toFraction=function(t){var e,n,i,r,o,s,a,u,l,h,w,v,T=this,I=T.d,x=T.constructor;if(!I)return new x(T);if(l=n=new x(1),i=u=new x(0),e=new x(i),o=e.e=Kl(I)-T.e-1,s=o%le,e.d[0]=kt(10,s<0?le+s:s),t==null)t=o>0?e:l;else{if(a=new x(t),!a.isInt()||a.lt(l))throw Error(Hn+a);t=a.gt(e)?o>0?e:l:a}for(fe=!1,a=new x(xt(I)),h=x.precision,x.precision=o=I.length*le*2;w=Ee(a,e,0,1,1),r=n.plus(w.times(i)),r.cmp(t)!=1;)n=i,i=r,r=l,l=u.plus(w.times(r)),u=r,r=e,e=a.minus(w.times(r)),a=r;return r=Ee(t.minus(n),i,0,1,1),u=u.plus(r.times(l)),n=n.plus(r.times(i)),u.s=l.s=T.s,v=Ee(l,i,o,1).minus(T).abs().cmp(Ee(u,n,o,1).minus(T).abs())<1?[l,i]:[u,n],x.precision=h,fe=!0,v};z.toHexadecimal=z.toHex=function(t,e){return tc(this,16,t,e)};z.toNearest=function(t,e){var n=this,i=n.constructor;if(n=new i(n),t==null){if(!n.d)return n;t=new i(1),e=i.rounding}else{if(t=new i(t),e===void 0?e=i.rounding:Kt(e,0,8),!n.d)return t.s?n:t;if(!t.d)return t.s&&(t.s=n.s),t}return t.d[0]?(fe=!1,n=Ee(n,t,0,e,1).times(t),fe=!0,oe(n)):(t.s=n.s,n=t),n};z.toNumber=function(){return+this};z.toOctal=function(t,e){return tc(this,8,t,e)};z.toPower=z.pow=function(t){var e,n,i,r,o,s,a=this,u=a.constructor,l=+(t=new u(t));if(!a.d||!t.d||!a.d[0]||!t.d[0])return new u(kt(+a,l));if(a=new u(a),a.eq(1))return a;if(i=u.precision,o=u.rounding,t.eq(1))return oe(a,i,o);if(e=jt(t.e/le),e>=t.d.length-1&&(n=l<0?-l:l)<=zg)return r=zl(u,a,n,i),t.s<0?new u(1).div(r):oe(r,i,o);if(s=a.s,s<0){if(e<t.d.length-1)return new u(NaN);if(t.d[e]&1||(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return n=kt(+a,l),e=n==0||!isFinite(n)?jt(l*(Math.log("0."+xt(a.d))/Math.LN10+a.e+1)):new u(n+"").e,e>u.maxE+1||e<u.minE-1?new u(e>0?s/0:0):(fe=!1,u.rounding=a.s=1,n=Math.min(12,(e+"").length),r=Qa(t.times(Wn(a,i+n)),i),r.d&&(r=oe(r,i+5,1),Mr(r.d,i,o)&&(e=i+10,r=oe(Qa(t.times(Wn(a,e+n)),e),e+5,1),+xt(r.d).slice(i+1,i+15)+1==1e14&&(r=oe(r,i+1,0)))),r.s=s,fe=!0,u.rounding=o,oe(r,i,o))};z.toPrecision=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Tn(i,i.e<=r.toExpNeg||i.e>=r.toExpPos):(Kt(t,1,Zn),e===void 0?e=r.rounding:Kt(e,0,8),i=oe(new r(i),t,e),n=Tn(i,t<=i.e||i.e<=r.toExpNeg,t)),i.isNeg()&&!i.isZero()?"-"+n:n};z.toSignificantDigits=z.toSD=function(t,e){var n=this,i=n.constructor;return t===void 0?(t=i.precision,e=i.rounding):(Kt(t,1,Zn),e===void 0?e=i.rounding:Kt(e,0,8)),oe(new i(n),t,e)};z.toString=function(){var t=this,e=t.constructor,n=Tn(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+n:n};z.truncated=z.trunc=function(){return oe(new this.constructor(this),this.e+1,1)};z.valueOf=z.toJSON=function(){var t=this,e=t.constructor,n=Tn(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+n:n};function xt(t){var e,n,i,r=t.length-1,o="",s=t[0];if(r>0){for(o+=s,e=1;e<r;e++)i=t[e]+"",n=le-i.length,n&&(o+=Gn(n)),o+=i;s=t[e],i=s+"",n=le-i.length,n&&(o+=Gn(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Kt(t,e,n){if(t!==~~t||t<e||t>n)throw Error(Hn+t)}function Mr(t,e,n,i){var r,o,s,a;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=le,r=0):(r=Math.ceil((e+1)/le),e%=le),o=kt(10,le-e),a=t[r]%o|0,i==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=n<4&&a==99999||n>3&&a==49999||a==5e4||a==0):s=(n<4&&a+1==o||n>3&&a+1==o/2)&&(t[r+1]/o/100|0)==kt(10,e-2)-1||(a==o/2||a==0)&&(t[r+1]/o/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(i||n<4)&&a==9999||!i&&n>3&&a==4999):s=((i||n<4)&&a+1==o||!i&&n>3&&a+1==o/2)&&(t[r+1]/o/1e3|0)==kt(10,e-3)-1,s}function $o(t,e,n){for(var i,r=[0],o,s=0,a=t.length;s<a;){for(o=r.length;o--;)r[o]*=e;for(r[0]+=Xa.indexOf(t.charAt(s++)),i=0;i<r.length;i++)r[i]>n-1&&(r[i+1]===void 0&&(r[i+1]=0),r[i+1]+=r[i]/n|0,r[i]%=n)}return r.reverse()}function Gg(t,e){var n,i,r;if(e.isZero())return e;i=e.d.length,i<32?(n=Math.ceil(i/3),r=(1/Wo(4,n)).toString()):(n=16,r="2.3283064365386962890625e-10"),t.precision+=n,e=Wi(t,1,e.times(r),new t(1));for(var o=n;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=n,e}var Ee=function(){function t(i,r,o){var s,a=0,u=i.length;for(i=i.slice();u--;)s=i[u]*r+a,i[u]=s%o|0,a=s/o|0;return a&&i.unshift(a),i}function e(i,r,o,s){var a,u;if(o!=s)u=o>s?1:-1;else for(a=u=0;a<o;a++)if(i[a]!=r[a]){u=i[a]>r[a]?1:-1;break}return u}function n(i,r,o,s){for(var a=0;o--;)i[o]-=a,a=i[o]<r[o]?1:0,i[o]=a*s+i[o]-r[o];for(;!i[0]&&i.length>1;)i.shift()}return function(i,r,o,s,a,u){var l,h,w,v,T,I,x,P,O,E,B,$,Z,H,te,U,V,F,K,C,A=i.constructor,c=i.s==r.s?1:-1,d=i.d,g=r.d;if(!d||!d[0]||!g||!g[0])return new A(!i.s||!r.s||(d?g&&d[0]==g[0]:!g)?NaN:d&&d[0]==0||!g?c*0:c/0);for(u?(T=1,h=i.e-r.e):(u=fn,T=le,h=jt(i.e/T)-jt(r.e/T)),K=g.length,V=d.length,O=new A(c),E=O.d=[],w=0;g[w]==(d[w]||0);w++);if(g[w]>(d[w]||0)&&h--,o==null?(H=o=A.precision,s=A.rounding):a?H=o+(i.e-r.e)+1:H=o,H<0)E.push(1),I=!0;else{if(H=H/T+2|0,w=0,K==1){for(v=0,g=g[0],H++;(w<V||v)&&H--;w++)te=v*u+(d[w]||0),E[w]=te/g|0,v=te%g|0;I=v||w<V}else{for(v=u/(g[0]+1)|0,v>1&&(g=t(g,v,u),d=t(d,v,u),K=g.length,V=d.length),U=K,B=d.slice(0,K),$=B.length;$<K;)B[$++]=0;C=g.slice(),C.unshift(0),F=g[0],g[1]>=u/2&&++F;do v=0,l=e(g,B,K,$),l<0?(Z=B[0],K!=$&&(Z=Z*u+(B[1]||0)),v=Z/F|0,v>1?(v>=u&&(v=u-1),x=t(g,v,u),P=x.length,$=B.length,l=e(x,B,P,$),l==1&&(v--,n(x,K<P?C:g,P,u))):(v==0&&(l=v=1),x=g.slice()),P=x.length,P<$&&x.unshift(0),n(B,x,$,u),l==-1&&($=B.length,l=e(g,B,K,$),l<1&&(v++,n(B,K<$?C:g,$,u))),$=B.length):l===0&&(v++,B=[0]),E[w++]=v,l&&B[0]?B[$++]=d[U]||0:(B=[d[U]],$=1);while((U++<V||B[0]!==void 0)&&H--);I=B[0]!==void 0}E[0]||E.shift()}if(T==1)O.e=h,Rl=I;else{for(w=1,v=E[0];v>=10;v/=10)w++;O.e=w+h*T-1,oe(O,a?o+O.e+1:o,s,I)}return O}}();function oe(t,e,n,i){var r,o,s,a,u,l,h,w,v,T=t.constructor;e:if(e!=null){if(w=t.d,!w)return t;for(r=1,a=w[0];a>=10;a/=10)r++;if(o=e-r,o<0)o+=le,s=e,h=w[v=0],u=h/kt(10,r-s-1)%10|0;else if(v=Math.ceil((o+1)/le),a=w.length,v>=a)if(i){for(;a++<=v;)w.push(0);h=u=0,r=1,o%=le,s=o-le+1}else break e;else{for(h=a=w[v],r=1;a>=10;a/=10)r++;o%=le,s=o-le+r,u=s<0?0:h/kt(10,r-s-1)%10|0}if(i=i||e<0||w[v+1]!==void 0||(s<0?h:h%kt(10,r-s-1)),l=n<4?(u||i)&&(n==0||n==(t.s<0?3:2)):u>5||u==5&&(n==4||i||n==6&&(o>0?s>0?h/kt(10,r-s):0:w[v-1])%10&1||n==(t.s<0?8:7)),e<1||!w[0])return w.length=0,l?(e-=t.e+1,w[0]=kt(10,(le-e%le)%le),t.e=-e||0):w[0]=t.e=0,t;if(o==0?(w.length=v,a=1,v--):(w.length=v+1,a=kt(10,le-o),w[v]=s>0?(h/kt(10,r-s)%kt(10,s)|0)*a:0),l)for(;;)if(v==0){for(o=1,s=w[0];s>=10;s/=10)o++;for(s=w[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(t.e++,w[0]==fn&&(w[0]=1));break}else{if(w[v]+=a,w[v]!=fn)break;w[v--]=0,a=1}for(o=w.length;w[--o]===0;)w.pop()}return fe&&(t.e>T.maxE?(t.d=null,t.e=NaN):t.e<T.minE&&(t.e=0,t.d=[0])),t}function Tn(t,e,n){if(!t.isFinite())return Gl(t);var i,r=t.e,o=xt(t.d),s=o.length;return e?(n&&(i=n-s)>0?o=o.charAt(0)+"."+o.slice(1)+Gn(i):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):r<0?(o="0."+Gn(-r-1)+o,n&&(i=n-s)>0&&(o+=Gn(i))):r>=s?(o+=Gn(r+1-s),n&&(i=n-r-1)>0&&(o=o+"."+Gn(i))):((i=r+1)<s&&(o=o.slice(0,i)+"."+o.slice(i)),n&&(i=n-s)>0&&(r+1===s&&(o+="."),o+=Gn(i))),o}function Go(t,e){var n=t[0];for(e*=le;n>=10;n/=10)e++;return e}function zo(t,e,n){if(e>Vg)throw fe=!0,n&&(t.precision=n),Error(ql);return oe(new t(Uo),e,1,!0)}function dn(t,e,n){if(e>Ya)throw Error(ql);return oe(new t(Ko),e,n,!0)}function Kl(t){var e=t.length-1,n=e*le+1;if(e=t[e],e){for(;e%10==0;e/=10)n--;for(e=t[0];e>=10;e/=10)n++}return n}function Gn(t){for(var e="";t--;)e+="0";return e}function zl(t,e,n,i){var r,o=new t(1),s=Math.ceil(i/le+4);for(fe=!1;;){if(n%2&&(o=o.times(e),Nl(o.d,s)&&(r=!0)),n=jt(n/2),n===0){n=o.d.length-1,r&&o.d[n]===0&&++o.d[n];break}e=e.times(e),Nl(e.d,s)}return fe=!0,o}function jl(t){return t.d[t.d.length-1]&1}function Vl(t,e,n){for(var i,r=new t(e[0]),o=0;++o<e.length;)if(i=new t(e[o]),i.s)r[n](i)&&(r=i);else{r=i;break}return r}function Qa(t,e){var n,i,r,o,s,a,u,l=0,h=0,w=0,v=t.constructor,T=v.rounding,I=v.precision;if(!t.d||!t.d[0]||t.e>17)return new v(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(fe=!1,u=I):u=e,a=new v(.03125);t.e>-2;)t=t.times(a),w+=5;for(i=Math.log(kt(2,w))/Math.LN10*2+5|0,u+=i,n=o=s=new v(1),v.precision=u;;){if(o=oe(o.times(t),u,1),n=n.times(++h),a=s.plus(Ee(o,n,u,1)),xt(a.d).slice(0,u)===xt(s.d).slice(0,u)){for(r=w;r--;)s=oe(s.times(s),u,1);if(e==null)if(l<3&&Mr(s.d,u-i,T,l))v.precision=u+=10,n=o=a=new v(1),h=0,l++;else return oe(s,v.precision=I,T,fe=!0);else return v.precision=I,s}s=a}}function Wn(t,e){var n,i,r,o,s,a,u,l,h,w,v,T=1,I=10,x=t,P=x.d,O=x.constructor,E=O.rounding,B=O.precision;if(x.s<0||!P||!P[0]||!x.e&&P[0]==1&&P.length==1)return new O(P&&!P[0]?-1/0:x.s!=1?NaN:P?0:x);if(e==null?(fe=!1,h=B):h=e,O.precision=h+=I,n=xt(P),i=n.charAt(0),Math.abs(o=x.e)<15e14){for(;i<7&&i!=1||i==1&&n.charAt(1)>3;)x=x.times(t),n=xt(x.d),i=n.charAt(0),T++;o=x.e,i>1?(x=new O("0."+n),o++):x=new O(i+"."+n.slice(1))}else return l=zo(O,h+2,B).times(o+""),x=Wn(new O(i+"."+n.slice(1)),h-I).plus(l),O.precision=B,e==null?oe(x,B,E,fe=!0):x;for(w=x,u=s=x=Ee(x.minus(1),x.plus(1),h,1),v=oe(x.times(x),h,1),r=3;;){if(s=oe(s.times(v),h,1),l=u.plus(Ee(s,new O(r),h,1)),xt(l.d).slice(0,h)===xt(u.d).slice(0,h))if(u=u.times(2),o!==0&&(u=u.plus(zo(O,h+2,B).times(o+""))),u=Ee(u,new O(T),h,1),e==null)if(Mr(u.d,h-I,E,a))O.precision=h+=I,l=s=x=Ee(w.minus(1),w.plus(1),h,1),v=oe(x.times(x),h,1),r=a=1;else return oe(u,O.precision=B,E,fe=!0);else return O.precision=B,u;u=l,r+=2}}function Gl(t){return String(t.s*t.s/0)}function ec(t,e){var n,i,r;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(i=e.search(/e/i))>0?(n<0&&(n=i),n+=+e.slice(i+1),e=e.substring(0,i)):n<0&&(n=e.length),i=0;e.charCodeAt(i)===48;i++);for(r=e.length;e.charCodeAt(r-1)===48;--r);if(e=e.slice(i,r),e){if(r-=i,t.e=n=n-i-1,t.d=[],i=(n+1)%le,n<0&&(i+=le),i<r){for(i&&t.d.push(+e.slice(0,i)),r-=le;i<r;)t.d.push(+e.slice(i,i+=le));e=e.slice(i),i=le-e.length}else i-=r;for(;i--;)e+="0";t.d.push(+e),fe&&(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 Wg(t,e){var n,i,r,o,s,a,u,l,h;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Ul.test(e))return ec(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(Ug.test(e))n=16,e=e.toLowerCase();else if($g.test(e))n=2;else if(Kg.test(e))n=8;else throw Error(Hn+e);for(o=e.search(/p/i),o>0?(u=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,i=t.constructor,s&&(e=e.replace(".",""),a=e.length,o=a-o,r=zl(i,new i(n),o,o*2)),l=$o(e,n,fn),h=l.length-1,o=h;l[o]===0;--o)l.pop();return o<0?new i(t.s*0):(t.e=Go(l,h),t.d=l,fe=!1,s&&(t=Ee(t,r,a*4)),u&&(t=t.times(Math.abs(u)<54?kt(2,u):Br.pow(2,u))),fe=!0,t)}function Hg(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Wi(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/Wo(5,n)),e=Wi(t,2,e,e);for(var r,o=new t(5),s=new t(16),a=new t(20);n--;)r=e.times(e),e=e.times(o.plus(r.times(s.times(r).minus(a))));return e}function Wi(t,e,n,i,r){var o,s,a,u,l=1,h=t.precision,w=Math.ceil(h/le);for(fe=!1,u=n.times(n),a=new t(i);;){if(s=Ee(a.times(u),new t(e++*e++),h,1),a=r?i.plus(s):i.minus(s),i=Ee(s.times(u),new t(e++*e++),h,1),s=a.plus(i),s.d[w]!==void 0){for(o=w;s.d[o]===a.d[o]&&o--;);if(o==-1)break}o=a,a=i,i=s,s=o,l++}return fe=!0,s.d.length=w+1,s}function Wo(t,e){for(var n=t;--e;)n*=t;return n}function Wl(t,e){var n,i=e.s<0,r=dn(t,t.precision,1),o=r.times(.5);if(e=e.abs(),e.lte(o))return Bn=i?4:1,e;if(n=e.divToInt(r),n.isZero())Bn=i?3:2;else{if(e=e.minus(n.times(r)),e.lte(o))return Bn=jl(n)?i?2:3:i?4:1,e;Bn=jl(n)?i?1:4:i?3:2}return e.minus(r).abs()}function tc(t,e,n,i){var r,o,s,a,u,l,h,w,v,T=t.constructor,I=n!==void 0;if(I?(Kt(n,1,Zn),i===void 0?i=T.rounding:Kt(i,0,8)):(n=T.precision,i=T.rounding),!t.isFinite())h=Gl(t);else{for(h=Tn(t),s=h.indexOf("."),I?(r=2,e==16?n=n*4-3:e==8&&(n=n*3-2)):r=e,s>=0&&(h=h.replace(".",""),v=new T(1),v.e=h.length-s,v.d=$o(Tn(v),10,r),v.e=v.d.length),w=$o(h,10,r),o=u=w.length;w[--u]==0;)w.pop();if(!w[0])h=I?"0p+0":"0";else{if(s<0?o--:(t=new T(t),t.d=w,t.e=o,t=Ee(t,v,n,i,0,r),w=t.d,o=t.e,l=Rl),s=w[n],a=r/2,l=l||w[n+1]!==void 0,l=i<4?(s!==void 0||l)&&(i===0||i===(t.s<0?3:2)):s>a||s===a&&(i===4||l||i===6&&w[n-1]&1||i===(t.s<0?8:7)),w.length=n,l)for(;++w[--n]>r-1;)w[n]=0,n||(++o,w.unshift(1));for(u=w.length;!w[u-1];--u);for(s=0,h="";s<u;s++)h+=Xa.charAt(w[s]);if(I){if(u>1)if(e==16||e==8){for(s=e==16?4:3,--u;u%s;u++)h+="0";for(w=$o(h,r,e),u=w.length;!w[u-1];--u);for(s=1,h="1.";s<u;s++)h+=Xa.charAt(w[s])}else h=h.charAt(0)+"."+h.slice(1);h=h+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)h="0"+h;h="0."+h}else if(++o>u)for(o-=u;o--;)h+="0";else o<u&&(h=h.slice(0,o)+"."+h.slice(o))}h=(e==16?"0x":e==2?"0b":e==8?"0o":"")+h}return t.s<0?"-"+h:h}function Nl(t,e){if(t.length>e)return t.length=e,!0}function Zg(t){return new this(t).abs()}function Xg(t){return new this(t).acos()}function Jg(t){return new this(t).acosh()}function Yg(t,e){return new this(t).plus(e)}function Qg(t){return new this(t).asin()}function e_(t){return new this(t).asinh()}function t_(t){return new this(t).atan()}function n_(t){return new this(t).atanh()}function i_(t,e){t=new this(t),e=new this(e);var n,i=this.precision,r=this.rounding,o=i+4;return!t.s||!e.s?n=new this(NaN):!t.d&&!e.d?(n=dn(this,o,1).times(e.s>0?.25:.75),n.s=t.s):!e.d||t.isZero()?(n=e.s<0?dn(this,i,r):new this(0),n.s=t.s):!t.d||e.isZero()?(n=dn(this,o,1).times(.5),n.s=t.s):e.s<0?(this.precision=o,this.rounding=1,n=this.atan(Ee(t,e,o,1)),e=dn(this,o,1),this.precision=i,this.rounding=r,n=t.s<0?n.minus(e):n.plus(e)):n=this.atan(Ee(t,e,o,1)),n}function r_(t){return new this(t).cbrt()}function o_(t){return oe(t=new this(t),t.e+1,2)}function s_(t,e,n){return new this(t).clamp(e,n)}function a_(t){if(!t||typeof t!="object")throw Error(Vo+"Object expected");var e,n,i,r=t.defaults===!0,o=["precision",1,Zn,"rounding",0,8,"toExpNeg",-Gi,0,"toExpPos",0,Gi,"maxE",0,Gi,"minE",-Gi,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(n=o[e],r&&(this[n]=Ja[n]),(i=t[n])!==void 0)if(jt(i)===i&&i>=o[e+1]&&i<=o[e+2])this[n]=i;else throw Error(Hn+n+": "+i);if(n="crypto",r&&(this[n]=Ja[n]),(i=t[n])!==void 0)if(i===!0||i===!1||i===0||i===1)if(i)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(Ll);else this[n]=!1;else throw Error(Hn+n+": "+i);return this}function c_(t){return new this(t).cos()}function u_(t){return new this(t).cosh()}function Hl(t){var e,n,i;function r(o){var s,a,u,l=this;if(!(l instanceof r))return new r(o);if(l.constructor=r,Fl(o)){l.s=o.s,fe?!o.d||o.e>r.maxE?(l.e=NaN,l.d=null):o.e<r.minE?(l.e=0,l.d=[0]):(l.e=o.e,l.d=o.d.slice()):(l.e=o.e,l.d=o.d?o.d.slice():o.d);return}if(u=typeof o,u==="number"){if(o===0){l.s=1/o<0?-1:1,l.e=0,l.d=[0];return}if(o<0?(o=-o,l.s=-1):l.s=1,o===~~o&&o<1e7){for(s=0,a=o;a>=10;a/=10)s++;fe?s>r.maxE?(l.e=NaN,l.d=null):s<r.minE?(l.e=0,l.d=[0]):(l.e=s,l.d=[o]):(l.e=s,l.d=[o]);return}else if(o*0!==0){o||(l.s=NaN),l.e=NaN,l.d=null;return}return ec(l,o.toString())}else if(u!=="string")throw Error(Hn+o);return(a=o.charCodeAt(0))===45?(o=o.slice(1),l.s=-1):(a===43&&(o=o.slice(1)),l.s=1),Ul.test(o)?ec(l,o):Wg(l,o)}if(r.prototype=z,r.ROUND_UP=0,r.ROUND_DOWN=1,r.ROUND_CEIL=2,r.ROUND_FLOOR=3,r.ROUND_HALF_UP=4,r.ROUND_HALF_DOWN=5,r.ROUND_HALF_EVEN=6,r.ROUND_HALF_CEIL=7,r.ROUND_HALF_FLOOR=8,r.EUCLID=9,r.config=r.set=a_,r.clone=Hl,r.isDecimal=Fl,r.abs=Zg,r.acos=Xg,r.acosh=Jg,r.add=Yg,r.asin=Qg,r.asinh=e_,r.atan=t_,r.atanh=n_,r.atan2=i_,r.cbrt=r_,r.ceil=o_,r.clamp=s_,r.cos=c_,r.cosh=u_,r.div=l_,r.exp=d_,r.floor=f_,r.hypot=h_,r.ln=m_,r.log=p_,r.log10=__,r.log2=g_,r.max=y_,r.min=w_,r.mod=b_,r.mul=v_,r.pow=k_,r.random=T_,r.round=C_,r.sign=S_,r.sin=A_,r.sinh=x_,r.sqrt=I_,r.sub=O_,r.sum=P_,r.tan=D_,r.tanh=E_,r.trunc=M_,t===void 0&&(t={}),t&&t.defaults!==!0)for(i=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<i.length;)t.hasOwnProperty(n=i[e++])||(t[n]=this[n]);return r.config(t),r}function l_(t,e){return new this(t).div(e)}function d_(t){return new this(t).exp()}function f_(t){return oe(t=new this(t),t.e+1,3)}function h_(){var t,e,n=new this(0);for(fe=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)n.d&&(n=n.plus(e.times(e)));else{if(e.s)return fe=!0,new this(1/0);n=e}return fe=!0,n.sqrt()}function Fl(t){return t instanceof Br||t&&t.toStringTag===$l||!1}function m_(t){return new this(t).ln()}function p_(t,e){return new this(t).log(e)}function g_(t){return new this(t).log(2)}function __(t){return new this(t).log(10)}function y_(){return Vl(this,arguments,"lt")}function w_(){return Vl(this,arguments,"gt")}function b_(t,e){return new this(t).mod(e)}function v_(t,e){return new this(t).mul(e)}function k_(t,e){return new this(t).pow(e)}function T_(t){var e,n,i,r,o=0,s=new this(1),a=[];if(t===void 0?t=this.precision:Kt(t,1,Zn),i=Math.ceil(t/le),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(i));o<i;)r=e[o],r>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:a[o++]=r%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(i*=4);o<i;)r=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),r>=214e7?crypto.randomBytes(4).copy(e,o):(a.push(r%1e7),o+=4);o=i/4}else throw Error(Ll);else for(;o<i;)a[o++]=Math.random()*1e7|0;for(i=a[--o],t%=le,i&&t&&(r=kt(10,le-t),a[o]=(i/r|0)*r);a[o]===0;o--)a.pop();if(o<0)n=0,a=[0];else{for(n=-1;a[0]===0;n-=le)a.shift();for(i=1,r=a[0];r>=10;r/=10)i++;i<le&&(n-=le-i)}return s.e=n,s.d=a,s}function C_(t){return oe(t=new this(t),t.e+1,this.rounding)}function S_(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function A_(t){return new this(t).sin()}function x_(t){return new this(t).sinh()}function I_(t){return new this(t).sqrt()}function O_(t,e){return new this(t).sub(e)}function P_(){var t=0,e=arguments,n=new this(e[t]);for(fe=!1;n.s&&++t<e.length;)n=n.plus(e[t]);return fe=!0,oe(n,this.precision,this.rounding)}function D_(t){return new this(t).tan()}function E_(t){return new this(t).tanh()}function M_(t){return oe(t=new this(t),t.e+1,1)}z[Symbol.for("nodejs.util.inspect.custom")]=z.toString;z[Symbol.toStringTag]="Decimal";var Br=z.constructor=Hl(Ja);Uo=new Br(Uo);Ko=new Br(Ko);var N=Br;var Vd=ge(ke(),1),Rr=ge(ke(),1);var ce=ge(ke(),1),Ie=ge(ke(),1),Hd=ge(ke(),1),hs=require("@mysten/sui.js/utils"),E0=ge(ke(),1),mc=ge(ke(),1),M0=ge(ke(),1);var wi=ge(ke(),1),Fr=ge(ke(),1);var bi=require("@mysten/sui.js/transactions"),K0=require("@mysten/sui.js/utils"),z0=require("@mysten/sui.js/transactions"),Pt=ge(ke(),1),os=require("@mysten/sui.js/transactions"),gc=ge(ke(),1),vi=require("@mysten/sui.js/transactions"),rf=require("@mysten/sui.js/utils"),Me=ge(ke(),1),ss=require("@mysten/sui.js/transactions"),Ht=ge(ke(),1),Ti=ge(bd(),1),of=require("@mysten/sui.js/transactions"),ki=ge(ke(),1);var _c=require("@mysten/sui.js/transactions");var Ad="3.7.7",$_=Ad,Xi=typeof Buffer=="function",vd=typeof TextDecoder=="function"?new TextDecoder:void 0,kd=typeof TextEncoder=="function"?new TextEncoder:void 0,U_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",jr=Array.prototype.slice.call(U_),Yo=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(jr),K_=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,It=String.fromCharCode.bind(String),Td=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),xd=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Id=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Od=t=>{let e,n,i,r,o="",s=t.length%3;for(let a=0;a<t.length;){if((n=t.charCodeAt(a++))>255||(i=t.charCodeAt(a++))>255||(r=t.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=n<<16|i<<8|r,o+=jr[e>>18&63]+jr[e>>12&63]+jr[e>>6&63]+jr[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},sc=typeof btoa=="function"?t=>btoa(t):Xi?t=>Buffer.from(t,"binary").toString("base64"):Od,rc=Xi?t=>Buffer.from(t).toString("base64"):t=>{let n=[];for(let i=0,r=t.length;i<r;i+=4096)n.push(It.apply(null,t.subarray(i,i+4096)));return sc(n.join(""))},Qo=(t,e=!1)=>e?xd(rc(t)):rc(t),z_=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?It(192|e>>>6)+It(128|e&63):It(224|e>>>12&15)+It(128|e>>>6&63)+It(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return It(240|e>>>18&7)+It(128|e>>>12&63)+It(128|e>>>6&63)+It(128|e&63)}},V_=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Pd=t=>t.replace(V_,z_),Cd=Xi?t=>Buffer.from(t,"utf8").toString("base64"):kd?t=>rc(kd.encode(t)):t=>sc(Pd(t)),Zi=(t,e=!1)=>e?xd(Cd(t)):Cd(t),Sd=t=>Zi(t,!0),G_=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,W_=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),n=e-65536;return It((n>>>10)+55296)+It((n&1023)+56320);case 3:return It((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return It((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Dd=t=>t.replace(G_,W_),Ed=t=>{if(t=t.replace(/\s+/g,""),!K_.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,n="",i,r;for(let o=0;o<t.length;)e=Yo[t.charAt(o++)]<<18|Yo[t.charAt(o++)]<<12|(i=Yo[t.charAt(o++)])<<6|(r=Yo[t.charAt(o++)]),n+=i===64?It(e>>16&255):r===64?It(e>>16&255,e>>8&255):It(e>>16&255,e>>8&255,e&255);return n},ac=typeof atob=="function"?t=>atob(Id(t)):Xi?t=>Buffer.from(t,"base64").toString("binary"):Ed,Md=Xi?t=>Td(Buffer.from(t,"base64")):t=>Td(ac(t).split("").map(e=>e.charCodeAt(0))),Bd=t=>Md(jd(t)),H_=Xi?t=>Buffer.from(t,"base64").toString("utf8"):vd?t=>vd.decode(Md(t)):t=>Dd(ac(t)),jd=t=>Id(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),oc=t=>H_(jd(t)),Z_=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)},Nd=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Fd=function(){let t=(e,n)=>Object.defineProperty(String.prototype,e,Nd(n));t("fromBase64",function(){return oc(this)}),t("toBase64",function(e){return Zi(this,e)}),t("toBase64URI",function(){return Zi(this,!0)}),t("toBase64URL",function(){return Zi(this,!0)}),t("toUint8Array",function(){return Bd(this)})},Rd=function(){let t=(e,n)=>Object.defineProperty(Uint8Array.prototype,e,Nd(n));t("toBase64",function(e){return Qo(this,e)}),t("toBase64URI",function(){return Qo(this,!0)}),t("toBase64URL",function(){return Qo(this,!0)})},X_=()=>{Fd(),Rd()},Ji={version:Ad,VERSION:$_,atob:ac,atobPolyfill:Ed,btoa:sc,btoaPolyfill:Od,fromBase64:oc,toBase64:Zi,encode:Zi,encodeURI:Sd,encodeURL:Sd,utob:Pd,btou:Dd,decode:oc,isValid:Z_,fromUint8Array:Qo,toUint8Array:Bd,extendString:Fd,extendUint8Array:Rd,extendBuiltins:X_};var yc=require("@mysten/sui.js/transactions"),sf=require("@mysten/sui.js/utils"),hn=ge(ke(),1);var es,J_=new Uint8Array(16);function cc(){if(!es&&(es=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!es))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return es(J_)}var Ot=[];for(let t=0;t<256;++t)Ot.push((t+256).toString(16).slice(1));function qd(t,e=0){return Ot[t[e+0]]+Ot[t[e+1]]+Ot[t[e+2]]+Ot[t[e+3]]+"-"+Ot[t[e+4]]+Ot[t[e+5]]+"-"+Ot[t[e+6]]+Ot[t[e+7]]+"-"+Ot[t[e+8]]+Ot[t[e+9]]+"-"+Ot[t[e+10]]+Ot[t[e+11]]+Ot[t[e+12]]+Ot[t[e+13]]+Ot[t[e+14]]+Ot[t[e+15]]}var Y_=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),uc={randomUUID:Y_};function Q_(t,e,n){if(uc.randomUUID&&!e&&!t)return uc.randomUUID();t=t||{};let i=t.random||(t.rng||cc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=i[r];return e}return qd(i)}var ts=Q_;var as=require("@mysten/sui.js/utils"),af=require("@mysten/sui.js/transactions"),cf=require("@mysten/sui.js/client"),uf=require("@mysten/sui.js/bcs");var e0=Object.defineProperty,t0=(t,e,n)=>e in t?e0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,n0=(t,e,n)=>(t0(t,typeof e!="symbol"?e+"":e,n),n),Ue=5*60*1e3,X=24*60*60*1e3;function he(t){return Date.parse(new Date().toString())+t}var Be=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)}};N.config({precision:64,rounding:N.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var Dt=N,J=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof J&&t.errorCode===e}},ie=new wt.default(0),Cn=new wt.default(1),ls=new wt.default(2),Ok=ls.pow(new wt.default(128)),nr=ls.pow(new wt.default(64)).sub(Cn),o0=ls.pow(new wt.default(128)).sub(Cn),Te=class{static toX64_BN(t){return t.mul(new wt.default(2).pow(new wt.default(64)))}static toX64_Decimal(t){return t.mul(Dt.pow(2,64))}static toX64(t){return new wt.default(t.mul(Dt.pow(2,64)).floor().toFixed())}static fromX64(t){return new Dt(t.toString()).mul(Dt.pow(2,-64))}static fromX64_Decimal(t){return t.mul(Dt.pow(2,-64))}static fromX64_BN(t){return t.div(new wt.default(2).pow(new wt.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(nr).gt(ie)&&(e=e.add(Cn)),e}static divRoundUp(t,e){return t.mod(e).eq(ie)?t.div(e):t.div(e).add(new wt.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(o0):t.sub(e)}static checkUnsignedSub(t,e){let n=t.sub(e);if(n.isNeg())throw new J("Unsigned integer sub overflow","UnsignedIntegerOverflow");return n}static checkMul(t,e,n){let i=t.mul(e);if(this.isOverflow(i,n))throw new J("Multiplication overflow","MultiplicationOverflow");return i}static checkMulDivFloor(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivCeil(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e).add(n.sub(Cn)).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivRound(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e.add(n.shrn(1))).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulShiftRight(t,e,n,i){let r=t.mul(e).div(new wt.default(2).pow(new wt.default(n)));if(this.isOverflow(r,i))throw new J("Multiplication shift right overflow","MulShiftRightOverflow");return r}static checkMulShiftRight64RoundUpIf(t,e,n,i){let r=t.mul(e),s=i&&r.and(nr).gt(ie)?r.shrn(64).add(Cn):r.shrn(64);if(this.isOverflow(s,n))throw new J("Multiplication shift right overflow","MulShiftRightOverflow");return s}static checkMulShiftLeft(t,e,n,i){let r=t.mul(e).shln(n);if(this.isOverflow(r,i))throw new J("Multiplication shift left overflow","MulShiftLeftOverflow");return r}static checkDivRoundUpIf(t,e,n){if(e.eq(ie))throw new J("Devide by zero","DivideByZero");return n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(ls.pow(new wt.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(ie)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new wt.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 wt.default(1)))}static neg_from(t){return t.eq(ie)?t:this.u128_neg(t).add(new wt.default(1)).or(new wt.default(1).shln(127))}};function s0(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new Xn.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new Xn.default(t.fee_growth_global_a),feeGrowthGlobalB:new Xn.default(t.fee_growth_global_b),feeProtocolCoinA:new Xn.default(t.fee_protocol_coin_a),feeProtocolCoinB:new Xn.default(t.fee_protocol_coin_b),feeRate:new Xn.default(t.fee_rate),liquidity:new Xn.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var Gd=443636,Wd=-443636,ds="79226673515401279992447579055";var fs="4295048016",er=new Vd.default(1e6),G="0x0000000000000000000000000000000000000000000000000000000000000006",a0="partner",tr="pool_script",jn="pool_script_v2",Jn="router",lc="router_with_partner",zt="fetcher_script",c0="expect_swap",Ld="utils";var dc="custodian_v2",u0="clob_v2",l0="endpoints_v2";var wc=(t=>(t.Deleted="Deleted",t.Exists="Exists",t.NotExists="NotExists",t))(wc||{});function D(t){if(t.config===void 0)throw new J(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var d0=14,f0="59543866431248",h0="184467440737095516",m0="15793534762490258745",p0=443636;function g0(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}function _e(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}function _0(t){let e;return t&1?e=new ce.default("79232123823359799118286999567"):e=new ce.default("79228162514264337593543950336"),t&2&&(e=_e(e.mul(new ce.default("79236085330515764027303304731")),96,256)),t&4&&(e=_e(e.mul(new ce.default("79244008939048815603706035061")),96,256)),t&8&&(e=_e(e.mul(new ce.default("79259858533276714757314932305")),96,256)),t&16&&(e=_e(e.mul(new ce.default("79291567232598584799939703904")),96,256)),t&32&&(e=_e(e.mul(new ce.default("79355022692464371645785046466")),96,256)),t&64&&(e=_e(e.mul(new ce.default("79482085999252804386437311141")),96,256)),t&128&&(e=_e(e.mul(new ce.default("79736823300114093921829183326")),96,256)),t&256&&(e=_e(e.mul(new ce.default("80248749790819932309965073892")),96,256)),t&512&&(e=_e(e.mul(new ce.default("81282483887344747381513967011")),96,256)),t&1024&&(e=_e(e.mul(new ce.default("83390072131320151908154831281")),96,256)),t&2048&&(e=_e(e.mul(new ce.default("87770609709833776024991924138")),96,256)),t&4096&&(e=_e(e.mul(new ce.default("97234110755111693312479820773")),96,256)),t&8192&&(e=_e(e.mul(new ce.default("119332217159966728226237229890")),96,256)),t&16384&&(e=_e(e.mul(new ce.default("179736315981702064433883588727")),96,256)),t&32768&&(e=_e(e.mul(new ce.default("407748233172238350107850275304")),96,256)),t&65536&&(e=_e(e.mul(new ce.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=_e(e.mul(new ce.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=_e(e.mul(new ce.default("38992368544603139932233054999993551")),96,256)),_e(e,32,256)}function y0(t){let e=Math.abs(t),n;return e&1?n=new ce.default("18445821805675392311"):n=new ce.default("18446744073709551616"),e&2&&(n=_e(n.mul(new ce.default("18444899583751176498")),64,256)),e&4&&(n=_e(n.mul(new ce.default("18443055278223354162")),64,256)),e&8&&(n=_e(n.mul(new ce.default("18439367220385604838")),64,256)),e&16&&(n=_e(n.mul(new ce.default("18431993317065449817")),64,256)),e&32&&(n=_e(n.mul(new ce.default("18417254355718160513")),64,256)),e&64&&(n=_e(n.mul(new ce.default("18387811781193591352")),64,256)),e&128&&(n=_e(n.mul(new ce.default("18329067761203520168")),64,256)),e&256&&(n=_e(n.mul(new ce.default("18212142134806087854")),64,256)),e&512&&(n=_e(n.mul(new ce.default("17980523815641551639")),64,256)),e&1024&&(n=_e(n.mul(new ce.default("17526086738831147013")),64,256)),e&2048&&(n=_e(n.mul(new ce.default("16651378430235024244")),64,256)),e&4096&&(n=_e(n.mul(new ce.default("15030750278693429944")),64,256)),e&8192&&(n=_e(n.mul(new ce.default("12247334978882834399")),64,256)),e&16384&&(n=_e(n.mul(new ce.default("8131365268884726200")),64,256)),e&32768&&(n=_e(n.mul(new ce.default("3584323654723342297")),64,256)),e&65536&&(n=_e(n.mul(new ce.default("696457651847595233")),64,256)),e&131072&&(n=_e(n.mul(new ce.default("26294789957452057")),64,256)),e&262144&&(n=_e(n.mul(new ce.default("37481735321082")),64,256)),n}var ee=class{static priceToSqrtPriceX64(t,e,n){return Te.toX64(t.mul(Dt.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return Te.fromX64(t).pow(2).mul(Dt.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new ce.default(_0(t)):new ce.default(y0(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ce.default(ds))||t.lt(new ce.default(fs)))throw new J("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,n=new ce.default(e-64),i=g0(n,32,128),r=new ce.default("8000000000000000","hex"),o=0,s=new ce.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ce.default(0))&&o<d0;){a=a.mul(a);let I=a.shrn(127);a=a.shrn(63+I.toNumber()),s=s.add(r.mul(I)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ce.default(f0)),w=_e(h.sub(new ce.default(h0)),64,128).toNumber(),v=_e(h.add(new ce.default(m0)),64,128).toNumber();return w===v?w:ee.tickIndexToSqrtPriceX64(v).lte(t)?v:w}static tickIndexToPrice(t,e,n){return ee.sqrtPriceX64ToPrice(ee.tickIndexToSqrtPriceX64(t),e,n)}static priceToTickIndex(t,e,n){return ee.sqrtPriceX64ToTickIndex(ee.priceToSqrtPriceX64(t,e,n))}static priceToInitializableTickIndex(t,e,n,i){return ee.getInitializableTickIndex(ee.priceToTickIndex(t,e,n),i)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ee.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ee.getInitializableTickIndex(t,e)-e}};function w0(t){return S(t).add(S(p0))}var Dk=new Rr.default(365),Ek=new Rr.default(24),Mk=new Rr.default(3600),Bk=new Rr.default(.5);var mn=class{static getDefaultSqrtPriceLimit(t){return new Hd.default(t?fs:ds)}static getDefaultOtherAmountThreshold(t){return t?ie:nr}};function Zd(t,e,n,i){if(n.eq(ie))return t;let r=Te.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=Te.checkMul(t,n,256);if(!i&&o.lte(s))throw new J("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let a=i?Te.checkDivRoundUpIf(r,o.add(s),!0):Te.checkDivRoundUpIf(r,o.sub(s),!0);if(a.lt(new Ie.default(fs)))throw new J("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(a.gt(new Ie.default(ds)))throw new J("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return a}function Xd(t,e,n,i){let r=Te.checkDivRoundUpIf(n.shln(64),e,!i),o=i?t.add(r):t.sub(r);if(o.lt(new Ie.default(fs))||o.gt(new Ie.default(ds)))throw new J("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function b0(t,e,n,i){return i?Zd(t,e,n,!0):Xd(t,e,n,!0)}function v0(t,e,n,i){return i?Xd(t,e,n,!1):Zd(t,e,n,!1)}function $d(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(ie)||r.eq(ie))return ie;let o;if(i){let s=new Ie.default(n).mul(new Ie.default(r)).shln(64),a=e.mul(t),u=s.div(a);o=s.mod(a).eq(ie)?u:u.add(Cn)}else{let s=new Ie.default(n).mul(new Ie.default(r));o=s.and(nr).gt(ie)?s.shrn(64).add(Cn):s.shrn(64)}return o}function Ud(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(ie)||r.eq(ie))return ie;let o;if(i)o=n.mul(r).shrn(64);else{let s=n.mul(r).shln(64),a=e.mul(t);o=s.div(a)}return o}function k0(t,e,n,i,r,o){if(n===ie)return{amountIn:ie,amountOut:ie,nextSqrtPrice:e,feeAmount:ie};let s=t.gte(e),a,u,l,h;if(o){let w=Te.checkMulDivFloor(i,Te.checkUnsignedSub(er,r),er,64),v=$d(t,e,n,s);v.gt(w)?(a=w,h=Te.checkUnsignedSub(i,w),l=b0(t,n,w,s)):(a=v,h=Te.checkMulDivCeil(a,r,er.sub(r),64),l=e),u=Ud(t,l,n,s)}else{let w=Ud(t,e,n,s);w.gt(i)?(u=i,l=v0(t,n,i,s)):(u=w,l=e),a=$d(t,l,n,s),h=Te.checkMulDivCeil(a,r,er.sub(r),64)}return{amountIn:a,amountOut:u,nextSqrtPrice:l,feeAmount:h}}function T0(t,e,n,i,r){let o=n,s=i.liquidity,{currentSqrtPrice:a}=i,u={amountIn:ie,amountOut:ie,feeAmount:ie,refAmount:ie,nextSqrtPrice:ie,crossTickNum:0},l,h,w=mn.getDefaultSqrtPriceLimit(t);for(let v of r){if(t&&i.currentTickIndex<v.index||!t&&i.currentTickIndex>=v.index||v===null)continue;t&&w.gt(v.sqrtPrice)||!t&&w.lt(v.sqrtPrice)?l=w:l=v.sqrtPrice;let T=k0(a,l,s,o,i.feeRate,e);if(T.amountIn.eq(ie)||(o=e?o.sub(T.amountIn.add(T.feeAmount)):o.sub(T.amountOut)),u.amountIn=u.amountIn.add(T.amountIn),u.amountOut=u.amountOut.add(T.amountOut),u.feeAmount=u.feeAmount.add(T.feeAmount),T.nextSqrtPrice.eq(v.sqrtPrice)?(h=v.liquidityNet.mul(new Ie.default(-1)),t?Te.is_neg(h)?s=s.add(new Ie.default(Tt(BigInt(h.toString()),128))):s=s.add(h):Te.is_neg(h)?s=s.sub(new Ie.default(Tt(BigInt(h.toString()),128))):s=s.sub(h),a=v.sqrtPrice):a=T.nextSqrtPrice,u.crossTickNum+=1,o.eq(ie))break}return u.amountIn=u.amountIn.add(u.feeAmount),u.nextSqrtPrice=a,u}function ns(t,e,n){let i=Ie.default.min(t,e),r=Ie.default.max(t,e),o=Te.fromX64_BN(n.mul(r).mul(i)),s=r.sub(i);return o.div(s)}function is(t,e,n){let i=Ie.default.min(t,e),o=Ie.default.max(t,e).sub(i);return n.shln(64).div(o)}var $e=class{static updateFeeRate(t,e,n,i,r){let o=Te.checkMulDivCeil(e,new Ie.default(i),er,64),s=n===0?ie:Te.checkMulDivFloor(e,new Ie.default(n),er,64),a=e.mul(o).mul(s);if(r?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),a.eq(ie)||t.liquidity.eq(ie))return{refFee:s,clmm:t};let u=a.shln(64).div(t.liquidity);return r?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(u):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(u),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,n,i,r){let o=new Dt(t.toString()),s=new Dt(e.toString()),a=new Dt(n.toString()),u=new Dt(i.toString()),l,h;return e.lt(n)?(l=Te.toX64_Decimal(o).mul(u.sub(a)).div(a.mul(u)),h=new Dt(0)):e.lt(i)?(l=Te.toX64_Decimal(o).mul(u.sub(s)).div(s.mul(u)),h=Te.fromX64_Decimal(o.mul(s.sub(a)))):(l=new Dt(0),h=Te.fromX64_Decimal(o.mul(u.sub(a)))),r?{coinA:new Ie.default(l.ceil().toString()),coinB:new Ie.default(h.ceil().toString())}:{coinA:new Ie.default(l.floor().toString()),coinB:new Ie.default(h.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,n,i,r,o,s){let a=ee.sqrtPriceX64ToTickIndex(s),u=ee.tickIndexToSqrtPriceX64(t),l=ee.tickIndexToSqrtPriceX64(e),h;if(a<t){if(!i)throw new J("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");h=ns(u,l,n)}else if(a>e){if(i)throw new J("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");h=is(l,u,n)}else i?h=ns(s,l,n):h=is(s,u,n);let w=$e.getCoinAmountFromLiquidity(h,s,u,l,r),v=r?S(w.coinA.toString()).mul(1+o).toString():S(w.coinA.toString()).mul(1-o).toString(),T=r?S(w.coinB.toString()).mul(1+o).toString():S(w.coinB.toString()).mul(1-o).toString();return{coinAmountA:w.coinA,coinAmountB:w.coinB,tokenMaxA:r?new Ie.default(Dt.ceil(v).toString()):new Ie.default(Dt.floor(v).toString()),tokenMaxB:r?new Ie.default(Dt.ceil(T).toString()):new Ie.default(Dt.floor(T).toString()),liquidityAmount:h,fix_amount_a:i}}static estimateLiquidityFromcoinAmounts(t,e,n,i){if(e>n)throw new J("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let r=ee.sqrtPriceX64ToTickIndex(t),o=ee.tickIndexToSqrtPriceX64(e),s=ee.tickIndexToSqrtPriceX64(n);if(r<e)return ns(o,s,i.coinA);if(r>=n)return is(s,o,i.coinB);let a=ns(t,s,i.coinA),u=is(t,o,i.coinB);return Ie.default.min(a,u)}static estCoinAmountsFromTotalAmount(t,e,n,i,r,o){let{ratioA:s,ratioB:a}=$e.calculateDepositRatioFixTokenA(t,e,n),u=S(i).mul(s).div(r),l=S(i).mul(a).div(o);return{amountA:u,amountB:l}}static calculateDepositRatioFixTokenA(t,e,n){let i=new Ie.default(1e8),{coinAmountB:r}=$e.estLiquidityAndcoinAmountFromOneAmounts(t,e,i,!0,!0,0,n),o=ee.sqrtPriceX64ToPrice(n,0,0),s=S(i.toString()).mul(o),a=s.add(r.toString()),u=s.div(a),l=S(r.toString()).div(a);return{ratioA:u,ratioB:l}}};function bc(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var C0=0,Jd=1,S0=2;function Kd(t,e){return t===e?C0:t<e?Jd:S0}function A0(t,e){let n=0,i=t.length<=e.length?t.length:e.length,r=Kd(t.length,e.length);for(;n<i;){let o=Kd(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,o!==0)return o}return r}function cs(t,e){return A0(t,e)===Jd}function ir(t,...e){let n=Array.isArray(e[e.length-1])?e.pop():[],r=[t,...e].filter(Boolean).join("::");return n&&n.length&&(r+=`<${n.join(", ")}>`),r}function q(t){try{let e=t.replace(/\s/g,""),i=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(i){e=e.slice(0,e.indexOf("<"));let u={...q(e),type_arguments:i.map(l=>q(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>we.isSuiCoin(l)?l:q(l).source_address),u.source_address=ir(u.full_address,u.type_arguments),u}let r=e.split("::"),s={full_address:e,address:e===qr||e===D0?"0x2":(0,hs.normalizeSuiObjectId)(r[0]),module:r[1],name:r[2],type_arguments:[],source_address:""};return s.full_address=`${s.address}::${s.module}::${s.name}`,s.source_address=ir(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function Et(t){return q(t).source_address}function x0(t){return t.toLowerCase().startsWith("0x")?(0,hs.normalizeSuiObjectId)(t):t}var I0=(t,e=!0)=>{let n=t.split("::"),i=n.shift(),r=(0,hs.normalizeSuiObjectId)(i);return e&&(r=bc(r)),`${r}::${n.join("::")}`};function ms(t){for(let e in t){let n=typeof t[e];if(n==="object")ms(t[e]);else if(n==="string"){let i=t[e];i&&!i.includes("::")&&(t[e]=x0(i))}}}var O0="0x2::coin::Coin",P0=/^0x2::coin::Coin<(.+)>$/;var qr="0x2::sui::SUI",D0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var we=class{static getCoinTypeArg(t){let e=t.type.match(P0);return e?e[1]:null}static isSUI(t){let e=we.getCoinTypeArg(t);return e?we.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 n=BigInt(0);return t.forEach(i=>{e===i.coinAddress&&(n+=BigInt(i.balance))}),n}static getID(t){return t.fields.id.id}static getCoinTypeFromArg(t){return`${O0}<${t}>`}static getFaucetCoins(t){let{events:e}=t,n=[];return e?.forEach(i=>{let{type:r}=i;if(q(r).name==="InitEvent"){let o=i.parsedJson;n.push({transactionModule:i.transactionModule,suplyID:o.suplyID,decimals:o.decimals})}}),n}static getCoinAssets(t,e){let n=[];return e.forEach(i=>{Et(i.coinAddress)===Et(t)&&n.push(i)}),n}static isSuiCoin(t){return q(t).full_address===qr}static selectCoinObjectIdGreaterThanOrEqual(t,e,n=[]){let i=we.selectCoinAssetGreaterThanOrEqual(t,e,n),r=i.selectedCoins.map(a=>a.coinObjectId),o=i.remainingCoins,s=i.selectedCoins.map(a=>a.balance.toString());return{objectArray:r,remainCoins:o,amountArray:s}}static selectCoinAssetGreaterThanOrEqual(t,e,n=[]){let i=we.sortByBalance(t.filter(u=>!n.includes(u.coinObjectId))),r=we.calculateTotalBalance(i);if(r<e)return{selectedCoins:[],remainingCoins:i};if(r===e)return{selectedCoins:i,remainingCoins:[]};let o=BigInt(0),s=[],a=[...i];for(;o<r;){let u=e-o,l=a.findIndex(w=>w.balance>=u);if(l!==-1){s.push(a[l]),a.splice(l,1);break}let h=a.pop();h.balance>0&&(s.push(h),o+=h.balance)}return{selectedCoins:we.sortByBalance(s),remainingCoins:we.sortByBalance(a)}}static sortByBalance(t){return t.sort((e,n)=>e.balance<n.balance?-1:e.balance>n.balance?1:0)}static sortByBalanceDes(t){return t.sort((e,n)=>e.balance>n.balance?-1:e.balance<n.balance?0:1)}static calculateTotalBalance(t){return t.reduce((e,n)=>e+n.balance,BigInt(0))}};var rr=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return rr.fromFraction(t.toDecimalPlaces(1).mul(10).toNumber(),1e3)}static fromFraction(t,e){let n=typeof t=="number"?new mc.default(t.toString()):t,i=typeof e=="number"?new mc.default(e.toString()):e;return new rr(n,i)}};function pc(t,{numerator:e,denominator:n},i){return i?t.mul(n.add(e)).div(n):t.mul(n).div(n.add(e))}function ps(t,e,n){return{tokenMaxA:pc(t.coinA,e,n),tokenMaxB:pc(t.coinB,e,n)}}function S(t){return N.isDecimal(t)?t:new N(t===void 0?0:t)}function B0(t){return S(10).pow(S(t).abs())}function Lr(t){return t.data}function Yd(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 Qd(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function j0(t){if("reference"in t)return t.reference;let e=Lr(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Yd(t)}function Lt(t){return"objectId"in t?t.objectId:j0(t)?.objectId??Qd(t)}function N0(t){return t.data!==void 0}function F0(t){return t.content!==void 0}function ef(t){let e="data"in t?Lr(t):t;if(!(!e||!F0(e)||e.content.dataType!=="moveObject"))return e.content}function Mt(t){return ef(t)?.type}function pn(t){let e=N0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":Mt(t):e?.type}function Ci(t){return Lr(t)?.previousTransaction}function or(t){return Lr(t)?.owner}function R0(t){let e=Lr(t)?.display;return e||{data:null,error:null}}function Q(t){let e=ef(t)?.fields;if(e)return"fields"in e?e.fields:e}function tf(t,e){let n=B0(S(e));return Number(S(t).mul(n))}function Tt(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function Re(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function q0(t,e,n){let i=q(t).name,r=q(e).name;return`${i}-${r}[${n}]`}function fc(t){let e=Mt(t),n=q(e),i=Q(t);if(i==null)throw new J(`Pool id ${Lt(t)} not exists.`,"InvalidPoolObject");let r=[];i.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:a}=s.fields,u=Te.fromX64(new rn.default(a)),l=Math.floor(u.toNumber()*60*60*24);r.push({emissions_per_second:a,coinAddress:q(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:l})});let o={poolAddress:Lt(t),poolType:e,coinTypeA:n.type_arguments[0],coinTypeB:n.type_arguments[1],coinAmountA:i.coin_a,coinAmountB:i.coin_b,current_sqrt_price:i.current_sqrt_price,current_tick_index:Re(BigInt(i.current_tick_index.fields.bits)),fee_growth_global_a:i.fee_growth_global_a,fee_growth_global_b:i.fee_growth_global_b,fee_protocol_coin_a:i.fee_protocol_coin_a,fee_protocol_coin_b:i.fee_protocol_coin_b,fee_rate:i.fee_rate,is_pause:i.is_pause,liquidity:i.liquidity,position_manager:{positions_handle:i.position_manager.fields.positions.fields.id.id,size:i.position_manager.fields.positions.fields.size},rewarder_infos:r,rewarder_last_updated_time:i.rewarder_manager.fields.last_updated_time,tickSpacing:i.tick_spacing,ticks_handle:i.tick_manager.fields.ticks.fields.id.id,uri:i.url,index:Number(i.index),name:""};return o.name=q0(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function Si(t){let e=R0(t).data,n={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(n.creator=e.creator,n.description=e.description,n.image_url=e.image_url,n.link=e.link,n.name=e.name,n.project_url=e.project_url),n}function Nn(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new J(`Position not exists. Get Position error:${t.error}`,"InvalidPositionObject");let e={creator:"",description:"",image_url:"",link:"",name:"",project_url:""},n={...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"},i=Q(t);if(i){let s=Mt(t),a=or(t);"nft"in i?(i=i.nft.fields,e.description=i.description,e.name=i.name,e.link=i.url):e=Si(t),n={...e,pos_object_id:i.id.id,owner:a.AddressOwner,type:s,coin_type_a:i.coin_type_a.fields.name,coin_type_b:i.coin_type_b.fields.name,liquidity:i.liquidity,tick_lower_index:Re(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(i.tick_upper_index.fields.bits)),index:i.index,pool:i.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 r=Yd(t);r&&(n.pos_object_id=r.objectId,n.position_status="Deleted");let o=Qd(t);return o&&(n.pos_object_id=o,n.position_status="NotExists"),n}function nf(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:a,growth_inside:u}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=a,e.reward_growth_inside_0=u):s===1?(e.reward_amount_owed_1=a,e.reward_growth_inside_1=u):s===2&&(e.reward_amount_owed_2=a,e.reward_growth_inside_2=u)});let n="fields"in t.tick_lower_index?t.tick_lower_index.fields.bits:t.tick_lower_index.bits,i="fields"in t.tick_upper_index?t.tick_upper_index.fields.bits:t.tick_upper_index.bits;return{liquidity:t.liquidity,tick_lower_index:Re(BigInt(n)),tick_upper_index:Re(BigInt(i)),...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 hc(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new J(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let n=Q(t).value.fields.value.fields;return{objectId:Lt(t),index:Re(BigInt(n.index.fields.bits)),sqrtPrice:new rn.default(n.sqrt_price),liquidityNet:new rn.default(n.liquidity_net.fields.bits),liquidityGross:new rn.default(n.liquidity_gross),feeGrowthOutsideA:new rn.default(n.fee_growth_outside_a),feeGrowthOutsideB:new rn.default(n.fee_growth_outside_b),rewardersGrowthOutside:n.rewards_growth_outside}}function L0(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 J("Invalid tick fields.","InvalidTickFields");let e=Re(BigInt(t.index.bits)),n=new rn.default(t.sqrt_price),i=new rn.default(t.liquidity_net.bits),r=new rn.default(t.liquidity_gross),o=new rn.default(t.fee_growth_outside_a),s=new rn.default(t.fee_growth_outside_b),a=t.rewards_growth_outside||[];return{objectId:"",index:e,sqrtPrice:n,liquidityNet:i,liquidityGross:r,feeGrowthOutsideA:o,feeGrowthOutsideB:s,rewardersGrowthOutside:a}}function $0(t,e,n,i,r,o){let s=t.rewarder_infos,a=[];for(let u=0;u<s.length;u+=1){let l=o[u];e!==null&&(t.current_tick_index<i?l=o[u].sub(new wi.default(e.rewardersGrowthOutside[u])):l=e.rewardersGrowthOutside[u]);let h=new wi.default(0);n!==null&&(t.current_tick_index>=r?h=o[u].sub(new wi.default(n.rewardersGrowthOutside[u])):h=n.rewardersGrowthOutside[u]);let w=Te.subUnderflowU128(Te.subUnderflowU128(new wi.default(o[u]),new wi.default(l)),new wi.default(h));a.push(w)}return a}function us(t){let e=we.isSuiCoin(t.coinTypeA),n=we.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:n}}function U0(t,e){return N.ceil(S(t).div(1+e)).toString()}var se=class{static createCollectRewarderAndFeeParams(t,e,n,i,r,o){r===void 0&&(r=[...i]),o===void 0&&(o=[...i]);let s=Et(n.coinTypeA),a=Et(n.coinTypeB);if(n.collect_fee){let l=se.buildCoinForAmount(e,r,BigInt(0),s,!1);r=l.remainCoins;let h=se.buildCoinForAmount(e,o,BigInt(0),a,!1);o=h.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:n.pool_id,pos_id:n.pos_id,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB},e,l.targetCoin,h.targetCoin)}let u=[];return n.rewarder_coin_types.forEach(l=>{switch(Et(l)){case s:u.push(se.buildCoinForAmount(e,r,BigInt(0),l,!1).targetCoin);break;case a:u.push(se.buildCoinForAmount(e,o,BigInt(0),l,!1).targetCoin);break;default:u.push(se.buildCoinForAmount(e,i,BigInt(0),l,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(n,e,u),e}static async adjustTransactionForGas(t,e,n,i){i.setSender(t.senderAddress);let r=we.selectCoinAssetGreaterThanOrEqual(e,n).selectedCoins;if(r.length===0)throw new J("Insufficient balance","InsufficientBalance");let o=we.calculateTotalBalance(e);if(o-n>1e9)return{fixAmount:n};let s=await t.fullClient.calculationTxGas(i);if(we.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),r.map(u=>u.coinObjectId)).selectedCoins.length===0){let u=BigInt(s)+BigInt(500);if(o-n<u){if(n-=u,n<0)throw new J("gas Insufficient balance","InsufficientBalance");let l=new bi.TransactionBlock;return{fixAmount:n,newTx:l}}}return{fixAmount:n}}static async buildAddLiquidityFixTokenForGas(t,e,n,i){let r=await se.buildAddLiquidityFixToken(t,e,n),{isAdjustCoinA:o}=us(n),s=o?n.amount_a:n.amount_b,a=await se.adjustTransactionForGas(t,we.getCoinAssets(o?n.coinTypeA:n.coinTypeB,e),BigInt(s),r),{fixAmount:u}=a,{newTx:l}=a;if(l!==void 0){let h,w;if(o)n.amount_a=Number(u),h=se.buildAddLiquidityFixTokenCoinInput(l,!n.fix_amount_a,u.toString(),n.slippage,n.coinTypeA,e,!1),w=se.buildAddLiquidityFixTokenCoinInput(l,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);else return n.amount_b=Number(u),h=se.buildAddLiquidityFixTokenCoinInput(l,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),w=se.buildAddLiquidityFixTokenCoinInput(l,n.fix_amount_a,u.toString(),n.slippage,n.coinTypeB,e,!1),n=se.fixAddLiquidityFixTokenParams(n,i.slippage,i.curSqrtPrice),r=await se.buildAddLiquidityFixTokenArgs(l,t,e,n,h,w),r}return r}static async buildAddLiquidityFixToken(t,e,n){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let i=new bi.TransactionBlock,r=se.buildAddLiquidityFixTokenCoinInput(i,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),o=se.buildAddLiquidityFixTokenCoinInput(i,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);return i=se.buildAddLiquidityFixTokenArgs(i,t,e,n,r,o),i}static buildAddLiquidityFixTokenCoinInput(t,e,n,i,r,o,s=!0){return e?se.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(U0(n,i)),amountFirst:BigInt(n)},r,s):se.buildCoinForAmount(t,o,BigInt(n),r,s)}static fixAddLiquidityFixTokenParams(t,e,n){let i=t.fix_amount_a?t.amount_a:t.amount_b,r=$e.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new Fr.default(i),t.fix_amount_a,!0,e,n);return t.amount_a=t.fix_amount_a?t.amount_a:r.tokenMaxA.toNumber(),t.amount_b=t.fix_amount_a?r.tokenMaxB.toNumber():t.amount_b,t}static buildAddLiquidityFixTokenArgs(t,e,n,i,r,o){let s=[i.coinTypeA,i.coinTypeB],a=i.is_open?"open_position_with_liquidity_by_fix_coin":"add_liquidity_by_fix_coin",{clmm_pool:u,integrate:l}=e.sdkOptions;i.is_open||(t=se.createCollectRewarderAndFeeParams(e,t,i,n,r.remainCoins,o.remainCoins));let h=D(u),w=i.is_open?[t.object(h.global_config_id),t.object(i.pool_id),t.pure(Tt(BigInt(i.tick_lower)).toString()),t.pure(Tt(BigInt(i.tick_upper)).toString()),r.targetCoin,o.targetCoin,t.pure(i.amount_a),t.pure(i.amount_b),t.pure(i.fix_amount_a),t.object(G)]:[t.object(h.global_config_id),t.object(i.pool_id),t.object(i.pos_id),r.targetCoin,o.targetCoin,t.pure(i.amount_a),t.pure(i.amount_b),t.pure(i.fix_amount_a),t.object(G)];return t.moveCall({target:`${l.published_at}::${jn}::${a}`,typeArguments:s,arguments:w}),t}static async buildSwapTransactionForGas(t,e,n,i){let r=se.buildSwapTransaction(t,e,n);r.setSender(t.senderAddress);let o=await se.adjustTransactionForGas(t,we.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:s,newTx:a}=o;if(a!==void 0){a.setSender(t.senderAddress),e.by_amount_in?e.amount=s.toString():e.amount_limit=s.toString(),e=await se.fixSwapParams(t,e,i);let u=se.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),l=se.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);r=se.buildSwapTransactionArgs(a,e,t.sdkOptions,u,l)}return r}static buildSwapTransaction(t,e,n){let i=new bi.TransactionBlock;i.setSender(t.senderAddress);let r=se.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=se.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return i=se.buildSwapTransactionArgs(i,e,t.sdkOptions,r,o),i}static buildSwapTransactionArgs(t,e,n,i,r){let{clmm_pool:o,integrate:s}=n,a=mn.getDefaultSqrtPriceLimit(e.a2b),u=[e.coinTypeA,e.coinTypeB],{global_config_id:l}=D(o);if(l===void 0)throw Error("clmm.config.global_config_id is undefined");let h=e.swap_partner!==void 0,w=h?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",v=h?[t.pure(l),t.pure(e.pool_id),t.pure(e.swap_partner),i.targetCoin,r.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(a.toString()),t.pure(G)]:[t.pure(l),t.pure(e.pool_id),i.targetCoin,r.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(a.toString()),t.pure(G)];return t.moveCall({target:`${s.published_at}::${jn}::${w}`,typeArguments:u,arguments:v}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,n,i){let{tx:r,coinABs:o}=se.buildSwapTransactionWithoutTransferCoins(t,e,n);r.setSender(t.senderAddress);let s=await se.adjustTransactionForGas(t,we.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:a,newTx:u}=s;if(u!==void 0){u.setSender(t.senderAddress),e.by_amount_in?e.amount=a.toString():e.amount_limit=a.toString(),e=await se.fixSwapParams(t,e,i);let l=se.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),h=se.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),w=se.buildSwapTransactionWithoutTransferCoinArgs(t,u,e,t.sdkOptions,l,h);r=w.tx,o=w.txRes}return{tx:r,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,n){let i=new bi.TransactionBlock;i.setSender(t.senderAddress);let r=se.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=se.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=se.buildSwapTransactionWithoutTransferCoinArgs(t,i,e,t.sdkOptions,r,o);return{tx:s.tx,coinABs:s.txRes}}static buildSwapTransactionWithoutTransferCoinArgs(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=i,u=mn.getDefaultSqrtPriceLimit(n.a2b),{global_config_id:l}=D(s);if(l===void 0)throw Error("clmm.config.global_config_id is undefined");let h=n.swap_partner!==void 0,w=h?"swap_with_partner":"swap",v=h?lc:Jn,T=h?[e.pure(l),e.pure(n.pool_id),e.pure(n.swap_partner),r.targetCoin,o.targetCoin,e.pure(n.a2b),e.pure(n.by_amount_in),e.pure(n.amount),e.pure(u.toString()),e.pure(!1),e.pure(G)]:[e.pure(l),e.pure(n.pool_id),r.targetCoin,o.targetCoin,e.pure(n.a2b),e.pure(n.by_amount_in),e.pure(n.amount),e.pure(u.toString()),e.pure(!1),e.pure(G)],I=[n.coinTypeA,n.coinTypeB],x=e.moveCall({target:`${a.published_at}::${v}::${w}`,typeArguments:I,arguments:T});if(n.by_amount_in){let P=n.a2b?n.coinTypeB:n.coinTypeA,O=n.a2b?x[1]:x[0],E=Number(n.amount_limit);this.checkCoinThreshold(t,n.by_amount_in,e,O,E,P)}return{tx:e,txRes:x}}static async fixSwapParams(t,e,n){let{currentPool:i}=n;try{let r=await t.Swap.preswap({decimalsA:n.decimalsA,decimalsB:n.decimalsB,a2b:e.a2b,byAmountIn:e.by_amount_in,amount:e.amount,pool:i,currentSqrtPrice:i.current_sqrt_price,coinTypeA:i.coinTypeA,coinTypeB:i.coinTypeB}),o=n.byAmountIn?r.estimatedAmountOut:r.estimatedAmountIn,s=pc(o,n.slippage,!n.byAmountIn);e.amount_limit=s.toString()}catch(r){console.log("fixSwapParams",r)}return e}static async syncBuildCoinInputForAmount(t,e,n,i,r=!0){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let o=await t.getOwnerCoinAssets(t.senderAddress,i);return se.buildCoinForAmount(e,o,n,i,r).targetCoin}static buildCoinForAmount(t,e,n,i,r=!0,o=!1){let s=we.getCoinAssets(i,e);if(n===BigInt(0)&&s.length===0)return se.buildZeroValueCoin(e,t,i,r);let a=we.calculateTotalBalance(s);if(a<n)throw new J(`The amount(${a}) is Insufficient balance for ${i} , expect ${n} `,"InsufficientBalance");return se.buildCoin(t,e,s,n,i,r,o)}static buildCoin(t,e,n,i,r,o=!0,s=!1){if(we.isSuiCoin(r)){if(o){let E=t.splitCoins(t.gas,[t.pure(i.toString())]);return{targetCoin:t.makeMoveVec({objects:[E]}),remainCoins:e,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(i===0n&&n.length>1){let E=we.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.object(E.objectArray[0]),remainCoins:E.remainCoins,tragetCoinAmount:E.amountArray[0],isMintZeroCoin:!1}}let P=we.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.splitCoins(t.gas,[t.pure(i.toString())]),remainCoins:P.remainCoins,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let a=we.selectCoinObjectIdGreaterThanOrEqual(n,i),u=a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),l=a.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:l.map(P=>t.object(P))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),isMintZeroCoin:!1};let[h,...w]=l,v=t.object(h),T=v,I=a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),x;return w.length>0&&t.mergeCoins(v,w.map(P=>t.object(P))),s&&Number(u)>Number(i)&&(T=t.splitCoins(v,[t.pure(i.toString())]),I=i.toString(),x=v),{targetCoin:T,remainCoins:a.remainCoins,originalSplitedCoin:x,tragetCoinAmount:I,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,n,i=!0){let r=se.callMintZeroValueCoin(e,n),o;return i?o=e.makeMoveVec({objects:[r]}):o=r,{targetCoin:o,remainCoins:t,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(t,e,n,i,r=!0){let o=we.getCoinAssets(i,e);if(n.amountFirst===BigInt(0))return o.length>0?se.buildCoin(t,[...e],[...o],n.amountFirst,i,r):se.buildZeroValueCoin(e,t,i,r);let s=we.calculateTotalBalance(o);if(s>=n.amountFirst)return se.buildCoin(t,[...e],[...o],n.amountFirst,i,r);if(s<n.amountSecond)throw new J(`The amount(${s}) is Insufficient balance for ${i} , expect ${n.amountSecond} `,"InsufficientBalance");return se.buildCoin(t,[...e],[...o],n.amountSecond,i,r)}static async buildRouterSwapTransaction(t,e,n,i,r){let o=new bi.TransactionBlock;return e.paths.length>1&&(e.partner=""),o=await this.buildRouterBasePathTx(t,e,n,i,o,r),o}static async buildRouterBasePathTx(t,e,n,i,r,o){let s=e.paths.filter(B=>B&&B.poolAddress),a=Number(s.reduce((B,$)=>B.add($.amountIn),ie).toString()),u=Number(s.reduce((B,$)=>B.add($.amountOut),ie).toString()),l=Math.round(n?Number(u.toString())*(1-e.priceSlippagePoint):Number(a.toString())*(1+e.priceSlippagePoint)),h=e.paths[0].coinType[0],w=e.paths[0].coinType[e.paths[0].coinType.length-1],v=se.buildCoinForAmount(r,i,BigInt(n?a:l),h,!1,!0),T=v.originalSplitedCoin!==void 0,I=se.buildCoinForAmount(r,i,0n,w,!1),x=await this.buildRouterBasePathReturnCoins(t,e,n,v,I,r),P=[],{toCoin:O,fromCoin:E}=x;if(r=x.tx,I.isMintZeroCoin?P.push({coinType:w,coin:O}):I.originalSplitedCoin!==void 0?r.mergeCoins(I.originalSplitedCoin,[O]):r.mergeCoins(I.targetCoin,[O]),T){let B=v?.originalSplitedCoin;r.mergeCoins(B,[E])}else P.push({coinType:h,coin:E});for(let B=0;B<P.length;B++)this.buildTransferCoin(t,r,P[B].coin,P[B].coinType,o);return r}static async buildRouterBasePathReturnCoins(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=t.sdkOptions,u=D(s).global_config_id,l=e.paths.filter(B=>B&&B.poolAddress),h=Number(l.reduce((B,$)=>B.add($.amountIn),ie).toString()),w=Number(l.reduce((B,$)=>B.add($.amountOut),ie).toString()),v=Math.round(n?Number(w.toString())*(1-e.priceSlippagePoint):Number(h.toString())*(1+e.priceSlippagePoint)),T=e.paths[0].coinType[0],I=e.paths[0].coinType[e.paths[0].coinType.length-1],x=i.targetCoin,P;r.isMintZeroCoin||r.originalSplitedCoin!==void 0?P=r.targetCoin:P=se.callMintZeroValueCoin(o,I);let O=e.partner==="",E=O?Jn:lc;for(let B of l)if(B.poolAddress.length===1){let $=B.a2b[0],Z={amount:Number(B.amountIn.toString()),amountLimit:v,poolCoinA:B.a2b[0]?T:I,poolCoinB:B.a2b[0]?I:T},H=O?"swap":"swap_with_partner",te=$?x:P,U=$?P:x,V=n?B.amountIn.toString():B.amountOut.toString(),F=mn.getDefaultSqrtPriceLimit($).toString(),K=O?[o.object(u),o.object(B.poolAddress[0]),te,U,o.pure($),o.pure(n),o.pure(V),o.pure(F),o.pure(!1),o.object(G)]:[o.object(u),o.object(B.poolAddress[0]),o.pure(e.partner),te,U,o.pure($),o.pure(n),o.pure(V),o.pure(F),o.pure(!1),o.object(G)],C=[Z.poolCoinA,Z.poolCoinB],A=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${E}::${H}`,typeArguments:C,arguments:K});x=$?A[0]:A[1],P=$?A[1]:A[0]}else{let $=n?B.amountIn:B.rawAmountLimit[0],Z=n?0:B.amountOut,H="";B.a2b[0]?B.a2b[1]?H="swap_ab_bc":H="swap_ab_cb":B.a2b[1]?H="swap_ba_bc":H="swap_ba_cb",O||(H=`${H}_with_partner`);let te=mn.getDefaultSqrtPriceLimit(B.a2b[0]),U=mn.getDefaultSqrtPriceLimit(B.a2b[1]),V=O?[o.object(u),o.object(B.poolAddress[0]),o.object(B.poolAddress[1]),x,P,o.pure(n),o.pure($.toString()),o.pure(Z.toString()),o.pure(te.toString()),o.pure(U.toString()),o.object(G)]:[o.object(u),o.object(B.poolAddress[0]),o.object(B.poolAddress[1]),o.pure(e.partner),x,P,o.pure(n),o.pure($.toString()),o.pure(Z.toString()),o.pure(te.toString()),o.pure(U.toString()),o.object(G)],F=[B.coinType[0],B.coinType[1],B.coinType[2]],K=o.moveCall({target:`${a.published_at}::${E}::${H}`,typeArguments:F,arguments:V});x=K[0],P=K[1]}return this.checkCoinThreshold(t,n,o,P,v,I),{fromCoin:x,toCoin:P,tx:o}}static async buildAggregatorSwapReturnCoins(t,e,n,i,r,o,s,a){if(a==null){if(t.senderAddress.length===0)throw Error("recipient and this config sdk senderAddress all not set");a=t.senderAddress}e.splitPaths.length>1&&(r="");let u,l,h=e.splitPaths.some(w=>w.basePaths.some(v=>v.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!h){let w=[];for(let I of e.splitPaths){let x=[],P=[],O=[],E=[];for(let $=0;$<I.basePaths.length;$+=1){let Z=I.basePaths[$];x.push(Z.direction),P.push(Z.poolAddress),O.push(new Fr.default(Z.inputAmount.toString())),$===0?E.push(Z.fromCoin,Z.toCoin):E.push(Z.toCoin)}let B={amountIn:new Fr.default(I.inputAmount.toString()),amountOut:new Fr.default(I.outputAmount.toString()),poolAddress:P,a2b:x,rawAmountLimit:O,isExceed:!1,coinType:E};w.push(B)}let v={paths:w,partner:r,priceSlippagePoint:o},T=await this.buildRouterBasePathReturnCoins(t,v,e.byAmountIn,n,i,s);u=T.fromCoin,l=T.toCoin,s=T.tx}else{let w=Math.round(e.outputAmount*(1-o));u=n.targetCoin,i.isMintZeroCoin||i.originalSplitedCoin!==void 0?l=i.targetCoin:l=se.callMintZeroValueCoin(s,e.toCoin);let v=!1,T;if(h){let[I,x]=zd.createAccountCap(a,t.sdkOptions,s);s=x,T=I,v=!0}for(let I=0;I<e.splitPaths.length;I+=1){let x=e.splitPaths[I],P;for(let O=0;O<x.basePaths.length;O+=1){let E=x.basePaths[O];if(E.label==="Deepbook")if(O===0)if(x.basePaths.length===1){let B=this.buildDeepbookBasePathTx(t,E,s,T,u,l,!1);u=B.from,l=B.to}else{P=se.callMintZeroValueCoin(s,E.toCoin);let B=this.buildDeepbookBasePathTx(t,E,s,T,u,P,!1);u=B.from,P=B.to}else{let B=this.buildDeepbookBasePathTx(t,E,s,T,P,l,!0);P=B.from,l=B.to}if(E.label==="Cetus")if(O===0)if(x.basePaths.length===1){let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,u,l,!1,r);u=B.from,l=B.to}else{P=se.callMintZeroValueCoin(s,E.toCoin);let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,u,P,!1,r);u=B.from,P=B.to}else{let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,P,l,!0,r);P=B.from,l=B.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Ld}::send_coin`,typeArguments:[E.fromCoin],arguments:[P,s.pure(a)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,l,w,e.toCoin),v&&(s=zd.deleteAccountCapByObject(T,t.sdkOptions,s))}return{fromCoin:u,toCoin:l,tx:s}}static async buildAggregatorSwapTransaction(t,e,n,i,r,o){let s=new bi.TransactionBlock,a=e.byAmountIn?Math.round(e.outputAmount*(1-r)):Math.round(e.inputAmount*(1+r)),u=se.buildCoinForAmount(s,n,e.byAmountIn?BigInt(e.inputAmount):BigInt(a),e.fromCoin,!1,!0),l=u.originalSplitedCoin!=null,h=se.buildCoinForAmount(s,n,0n,e.toCoin,!1),w=await this.buildAggregatorSwapReturnCoins(t,e,u,h,i,r,s,o),{fromCoin:v,toCoin:T}=w;s=w.tx;let I=[];if(h.isMintZeroCoin?I.push({coinType:e.toCoin,coin:T}):h.originalSplitedCoin!=null?s.mergeCoins(h.originalSplitedCoin,[T]):s.mergeCoins(h.targetCoin,[T]),l){let x=u.originalSplitedCoin;s.mergeCoins(x,[v])}else I.push({coinType:e.fromCoin,coin:v});for(let x=0;x<I.length;x++)this.buildTransferCoin(t,s,I[x].coin,I[x].coinType,o);return s}static checkCoinThreshold(t,e,n,i,r,o){e&&n.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Jn}::check_coin_threshold`,typeArguments:[o],arguments:[i,n.pure(r)]})}static buildDeepbookBasePathTx(t,e,n,i,r,o,s){let a=e.direction?r:o,u=e.direction?o:r,l=[n.object(e.poolAddress),i,n.pure(e.inputAmount),n.pure(0),n.pure(e.direction),a,u,n.pure(s),n.object(G)],h=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],w=n.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:h,arguments:l});return r=e.direction?w[0]:w[1],o=e.direction?w[1]:w[0],{from:r,to:o,tx:n}}static buildClmmBasePathTx(t,e,n,i,r,o,s,a){let{clmm_pool:u,integrate:l}=t.sdkOptions,h=D(u).global_config_id,w=e.direction?r:o,v=e.direction?o:r,T=a==="",I=T?Jn:lc,x=T?"swap":"swap_with_partner",P=i?e.inputAmount.toString():e.outputAmount.toString(),O=mn.getDefaultSqrtPriceLimit(e.direction),E=T?[n.object(h),n.object(e.poolAddress),w,v,n.pure(e.direction),n.pure(i),n.pure(P),n.pure(O.toString()),n.pure(s),n.object(G)]:[n.object(h),n.object(e.poolAddress),n.pure(a),w,v,n.pure(e.direction),n.pure(i),n.pure(P),n.pure(O.toString()),n.pure(s),n.object(G)],B=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],$=n.moveCall({target:`${l.published_at}::${I}::${x}`,typeArguments:B,arguments:E});return w=$[0],v=$[1],r=e.direction?w:v,o=e.direction?v:w,{from:r,to:o,tx:n}}static buildCoinTypePair(t,e){let n=[];if(t.length===2){let i=[];i.push(t[0],t[1]),n.push(i)}else{let i=[];i.push(t[0],t[t.length-1]),n.push(i);for(let r=1;r<t.length-1;r+=1){if(e[r-1]===0)continue;let o=[];o.push(t[0],t[r],t[t.length-1]),n.push(o)}}return n}static buildTransferCoinToSender(t,e,n,i){e.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Ld}::transfer_coin_to_sender`,typeArguments:[i],arguments:[n]})}static buildTransferCoin(t,e,n,i,r){r!=null?e.transferObjects([n],e.pure(r)):se.buildTransferCoinToSender(t,e,n,i)}},re=se;n0(re,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function Nt(t){return!(!t.startsWith("0x")||t.length!==66)}var Yi=new Pt.default(1e9),zd=class{static createAccountCap(t,e,n,i=!1){if(t.length===0)throw Error("this config sdk senderAddress is empty");let{deepbook:r}=e,[o]=n.moveCall({target:`${r.published_at}::${u0}::create_account`,typeArguments:[],arguments:[]});return i&&n.transferObjects([o],n.pure(t)),[o,n]}static deleteAccountCap(t,e,n){let{deepbook:i}=e,r=[n.pure(t)];return n.moveCall({target:`${i.published_at}::${dc}::delete_account_cap`,typeArguments:[],arguments:r}),n}static deleteAccountCapByObject(t,e,n){let{deepbook:i}=e,r=[t];return n.moveCall({target:`${i.published_at}::${dc}::delete_account_cap`,typeArguments:[],arguments:r}),n}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:dc}}});return e.data.length===0?"":e.data[0].data.objectId}static async getPools(t){let e=t.sdkOptions.deepbook.package_id,n=[];try{(await t.fullClient.queryEventsByPage({MoveEventType:`${e}::clob_v2::PoolCreated`})).data.forEach(r=>{let o=r.parsedJson;o&&n.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(i){console.log("getPoolImmutables",i)}return n}static async getPoolAsks(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new os.TransactionBlock,a=[],u=[n,i],l=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(G)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:l,typeArguments:u});let w=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(w.length===0)return a;for(let v=0;v<w[0].parsedJson.depths.length;v++){let T=w[0].parsedJson.price[v],I=w[0].parsedJson.depths[v],x={price:parseInt(T,10),quantity:parseInt(I,10)};a.push(x)}return a}static async getPoolBids(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new os.TransactionBlock,a=[],u=[n,i],l=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(G)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:l,typeArguments:u});let w=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(w.length===0)return a;for(let v=0;v<w[0].parsedJson.depths.length;v++){let T=w[0].parsedJson.price[v],I=w[0].parsedJson.depths[v],x={price:parseInt(T,10),quantity:parseInt(I,10)};a.push(x)}return a}static async preSwap(t,e,n,i){let r=!1,o=ie,s=new Pt.default(i),a=ie,u=new Pt.default(i);if(n){let l=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);l===null&&(r=!0),l=l.sort((h,w)=>w.price-h.price);for(let h=0;h<l.length;h+=1){let w=new Pt.default(l[h].quantity),v=new Pt.default(l[h].price),T=w.mul(new Pt.default(v)).mul(new Pt.default(e.takerFeeRate)).div(Yi).div(Yi);if(s.gt(w))s=s.sub(w),o=o.add(w.mul(v).div(Yi).sub(T)),a=a.add(T);else{let I=s.mul(new Pt.default(l[h].price)).div(Yi),x=I.mul(new Pt.default(e.takerFeeRate)).div(Yi);o=o.add(I.sub(x)),s=s.sub(s),a=a.add(x)}if(s.eq(ie))break}}else{let l=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);l===null&&(r=!0);for(let h=0;h<l.length;h+=1){let w=new Pt.default(l[h].price).mul(new Pt.default(l[h].quantity)).div(new Pt.default(1e9)),v=w.mul(new Pt.default(e.takerFeeRate)).div(Yi),T=w.add(v);if(s.gt(w))o=o.add(new Pt.default(l[h].quantity)),s=s.sub(T),a=a.add(v);else{let I=new Pt.default(l[h].quantity).div(new Pt.default(e.lotSize)),x=T.div(I),P=s.div(x);o=o.add(P.muln(e.lotSize)),s=s.sub(P.mul(x)),a=a.add(P.div(I).mul(v))}if(s.eq(ie))break}}return{poolAddress:e.poolID,estimatedAmountIn:u.sub(s).toNumber(),estimatedAmountOut:o.toNumber(),estimatedFeeAmount:a,isExceed:r,amount:Number(i),aToB:n,byAmountIn:!0}}static async simulateSwap(t,e,n,i,r,o){let{deepbook_endpoint_v2:s}=t.sdkOptions,a=new os.TransactionBlock,u=await this.getAccountCap(t),l;if(u===""){let Z=this.createAccountCap(t.senderAddress,t.sdkOptions,a),H=Z[0];a=Z[1],l=H}else l=a.pure(u);let h=await t.getOwnerCoinAssets(t.senderAddress),v=re.buildCoinForAmount(a,h,BigInt(o),n,!1)?.targetCoin,I=re.buildCoinForAmount(a,h,BigInt(o),i,!1)?.targetCoin,x=[n,i],P=[a.pure(e),l,a.pure(o),a.pure(0),a.pure(r),v,I,a.pure(G)];a.moveCall({target:`${s.published_at}::${l0}::swap`,arguments:P,typeArguments:x});let{simulationAccount:O}=t.sdkOptions,B=(await t.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:O.address})).events?.filter(Z=>q(Z.type).name==="DeepbookSwapEvent");if(B.length===0)return null;let $=B[0].parsedJson;return{poolAddress:$.pool,estimatedAmountIn:$.amount_in,estimatedAmountOut:$.amount_out,aToB:$.atob}}},V0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPositionList(t,e="all"){let n={data:[],hasNextPage:!0},i=await this._sdk.fullClient.getDynamicFieldsByPage(t,e);n.hasNextPage=i.hasNextPage,n.nextCursor=i.nextCursor;let r=i.data.map(s=>{if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`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(r);return n.data=o,n}async getPoolImmutables(t=[],e=0,n=100,i=!1){let{package_id:r}=this._sdk.sdkOptions.clmm_pool,o=`${r}_getInitPoolEvent`,s=this.getCache(o,i),a=[],u=[];if(s!==void 0&&a.push(...s),a.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`})).data.forEach(w=>{let v=w.parsedJson;v&&a.push({poolAddress:v.pool_id,tickSpacing:v.tick_spacing,coinTypeA:q(v.coin_type_a).full_address,coinTypeB:q(v.coin_type_b).full_address})}),this.updateCache(o,a,X)}catch(h){console.log("getPoolImmutables",h)}let l=t.length>0;for(let h=0;h<a.length;h+=1){let w=a[h];l&&!t.includes(w.poolAddress)||!l&&(h<e||h>=e+n)||u.push(w)}return u}async getPools(t=[],e=0,n=100){let i=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutables([],e,n,!1)).forEach(a=>r.push(a.poolAddress));let o=await this._sdk.fullClient.batchGetObjects(r,{showContent:!0,showType:!0});for(let s of o){if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let a=fc(s);i.push(a);let u=`${a.poolAddress}_getPoolObject`;this.updateCache(u,a,X)}return i}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.clmm_pool,i=[],r={data:[],hasNextPage:!1},o=t==="all",s=`${n}_getPoolImmutables`;if(o){let a=this.getCache(s,e);a&&i.push(...a)}if(i.length===0)try{let a=`${n}::factory::CreatePoolEvent`,u=await this._sdk.fullClient.queryEventsByPage({MoveEventType:a},t);r.hasNextPage=u.hasNextPage,r.nextCursor=u.nextCursor,u.data.forEach(l=>{let h=l.parsedJson;if(h){let w={poolAddress:h.pool_id,tickSpacing:h.tick_spacing,coinTypeA:q(h.coin_type_a).full_address,coinTypeB:q(h.coin_type_b).full_address};i.push(w)}})}catch(a){console.log("getPoolImmutables",a)}return r.data=i,o&&this.updateCache(`${n}_getPoolImmutables`,i,X),r}async getPoolsWithPage(t=[]){let e=[],n=[];t.length>0?n=[...t]:(await this.getPoolImmutablesWithPage()).data.forEach(o=>n.push(o.poolAddress));let i=await this._sdk.fullClient.batchGetObjects(n,{showContent:!0,showType:!0});for(let r of i){if(r.error!=null||r.data?.content?.dataType!=="moveObject")throw new J(`getPoolWithPages error code: ${r.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=fc(r);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,X)}return e}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(r.error!=null||r.data?.content?.dataType!=="moveObject")throw new J(`getPool error code: ${r.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=fc(r);return this.updateCache(n,o),o}async creatPoolsTransactionPayload(t){for(let n of t)if(cs((0,Nr.normalizeSuiAddress)(n.coinTypeA),(0,Nr.normalizeSuiAddress)(n.coinTypeB))){let i=n.coinTypeB;n.coinTypeB=n.coinTypeA,n.coinTypeA=i}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(cs((0,Nr.normalizeSuiAddress)(t.coinTypeA),(0,Nr.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,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.fullClient.queryEventsByPage({Transaction:o})).data,a={pools_id:"",global_config_id:"",global_vault_id:"",admin_cap_id:""};return s.length>0&&(s.forEach(u=>{let l=u.parsedJson;if(u.type)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.global_config_id=l.global_config_id,a.admin_cap_id=l.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:a.global_vault_id=l.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:a.partners_id=l.partners_id;break;default:break}}),this.updateCache(n,a,X)),a}async getSuiTransactionResponse(t,e=!1){let n=`${t}_getSuiTransactionResponse`,i=this.getCache(n,e);if(i!==void 0)return i;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(n,r,X),r}async creatPool(t){let e=new Qi.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=D(i),o=r.global_config_id,s=r.pools_id;return t.forEach(a=>{let u=[e.object(o),e.object(s),e.pure(a.tick_spacing.toString()),e.pure(a.initialize_sqrt_price),e.pure(a.uri),e.object(G)];e.moveCall({target:`${n.published_at}::${tr}::create_pool`,typeArguments:[a.coinTypeA,a.coinTypeB],arguments:u})}),e}async creatPoolAndAddLiquidity(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new Qi.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=D(i),o=r.global_config_id,s=r.pools_id,a=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),u=re.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,a,!1),l=re.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,a,!1),h=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),u.targetCoin,l.targetCoin,e.pure(Tt(BigInt(t.tick_lower)).toString()),e.pure(Tt(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(G)];return e.moveCall({target:`${n.published_at}::${jn}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:h}),e}async fetchTicks(t){let e=[],n=[];for(;;){let r=await this.getTicks({pool_id:t.pool_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,start:n,limit:512});if(e=[...e,...r],r.length<512)break;n=[r[r.length-1].index]}return e}async getTicks(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=[],r=[t.coinTypeA,t.coinTypeB],o=new Qi.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${zt}::fetch_ticks`,arguments:s,typeArguments:r}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let a=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:n.address});if(a.error!=null)throw new J(`getTicks error code: ${a.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return a.events?.forEach(u=>{q(u.type).name==="FetchTicksResultEvent"&&u.parsedJson.ticks.forEach(l=>{i.push(L0(l))})}),i}async fetchPositionRewardList(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=[],r=[],o=512;for(;;){let s=[t.coinTypeA,t.coinTypeB],a=new Qi.TransactionBlock,u=[a.object(t.pool_id),a.pure(r,"u64"),a.pure(o.toString(),"u64")];if(a.moveCall({target:`${e.published_at}::${zt}::fetch_positions`,arguments:u,typeArguments:s}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let l=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:n.address});if(l.error!=null)throw new J(`fetch position reward error code: ${l.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let h=[];if(l?.events?.forEach(w=>{q(w.type).name==="FetchPositionsEvent"&&w.parsedJson.positions.forEach(v=>{let T=nf(v);h.push(T)})}),i.push(...h),h.length<o)break;r=[h[h.length-1].pos_object_id]}return i}async fetchTicksByRpc(t){let e=[],n=null,i=512;for(;;){let r=[],o=await this.sdk.fullClient.getDynamicFields({parentId:t,cursor:n,limit:i});if(n=o.nextCursor,o.data.forEach(s=>{q(s.objectType).module==="skip_list"&&r.push(s.objectId)}),e=[...e,...await this.getTicksByRpc(r)],n===null||o.data.length<i)break}return e}async getTicksByRpc(t){let e=[],n=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0,showType:!0});for(let i of n){if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`getTicksByRpc error code: ${i.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let r=hc(i);r!=null&&e.push(r)}return e}async getTickDataByIndex(t,e){let n={type:"u64",value:Tt(BigInt(w0(e).toString())).toString()},i=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:n});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`get tick by index: ${e} error: ${i.error}`,"InvalidTickIndex");return hc(i)}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 J(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return hc(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 J(`get partner by object id: ${t} error: ${e[0].error}`,"NotFoundPartnerObject");let n=e[0].data.content.fields.balances,i=await this._sdk.fullClient.getDynamicFieldsByPage(n.fields.id.id),r=[];i.data.forEach(a=>{if(a.error!=null||a.data?.content?.dataType!=="moveObject")throw new J(`when getPartnerRefFeeAmount get partner object error: ${a.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");r.push(a.objectId)});let o=[];return(await this._sdk.fullClient.batchGetObjects(r,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(a=>{if(a.error!=null||a.data?.content?.dataType!=="moveObject")throw new J(`get coin by object id: ${a.data.objectId} error: ${a.error}`,"InvalidParnterRefFeeFields");let u={coinAddress:a.data.content.fields.name,coinObjectId:a.data.objectId,balance:BigInt(a.data.content.fields.value)};o.push(u)}),o}async claimPartnerRefFeePayload(t,e,n){let i=new Qi.TransactionBlock,{clmm_pool:r}=this.sdk.sdkOptions,{global_config_id:o}=D(r),s=[n],a=[i.object(o),i.object(t),i.object(e)];return i.moveCall({target:`${r.published_at}::${a0}::claim_ref_fee`,arguments:a,typeArguments:s}),i}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},G0=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 n=[],i=await this._sdk.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.clmm_pool.package_id}}),r=e.length>0;for(let o of i.data)if(q(o.data.type).full_address===this.buildPositionType()){let a=Nn(o),u=`${a.pos_object_id}_getPositionList`;this.updateCache(u,a,X),r?e.includes(a.pool)&&n.push(a):n.push(a)}return n}async getPosition(t,e,n=!0){let i=await this.getSimplePosition(e);return n&&(i=await this.updatePositionRewarders(t,i)),i}async getPositionById(t,e=!0){let n=await this.getSimplePosition(t);if(e){let i=await this._sdk.Pool.getPool(n.pool,!1);return await this.updatePositionRewarders(i.position_manager.positions_handle,n)}return n}async getSimplePosition(t){let e=`${t}_getPositionList`,n=this.getSimplePositionByCache(t);if(n===void 0){let i=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0,showType:!0,showDisplay:!0,showOwner:!0}});n=Nn(i),this.updateCache(e,n,X)}return n}getSimplePositionByCache(t){let e=`${t}_getPositionList`;return this.getCache(e)}async getSipmlePositionList(t){let e=[],n=[];return t.forEach(i=>{let r=this.getSimplePositionByCache(i);r?e.push(r):n.push(i)}),n.length>0&&(await this._sdk.fullClient.batchGetObjects(n,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(r=>{let o=Nn(r);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,X)}),e}async updatePositionRewarders(t,e){let n=await this.getPositionRewarders(t,e.pos_object_id);return{...e,...n}}async getPositionRewarders(t,e){try{let n=await this._sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),r=Q(n.data).value.fields.value;return nf(r)}catch(n){console.log(n);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new vi.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l})}if(!Nt(i.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address});if(o.error!=null)throw new J(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(u=>q(u.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let u=0;u<s.length;u+=1){let{parsedJson:l}=s[u],h={feeOwedA:new gc.default(l.fee_owned_a),feeOwedB:new gc.default(l.fee_owned_b),position_id:l.position_id};a.push(h)}return a}async batchFetchPositionFees(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let n={};if(e.length>0){let i=await this.fetchPosFeeAmount(e);for(let r of i)n[r.position_id]=r;return n}return n}async createAddLiquidityFixTokenPayload(t,e){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=us(t);if(t=t,t.fix_amount_a&&i||!t.fix_amount_a&&r)return await re.buildAddLiquidityFixTokenForGas(this._sdk,n,t,e)}return re.buildAddLiquidityFixToken(this._sdk,n,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:n}=this._sdk.sdkOptions;if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let i=Tt(BigInt(t.tick_lower)).toString(),r=Tt(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new vi.TransactionBlock,a=!(0,rf.isValidSuiObjectId)(t.pos_id),u=BigInt(t.max_amount_a),l=BigInt(t.max_amount_b),h=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),w=re.buildCoinForAmount(s,h,u,t.coinTypeA,!1),v=re.buildCoinForAmount(s,h,l,t.coinTypeB,!1);return a?s.moveCall({target:`${e.published_at}::${jn}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(D(n).global_config_id),s.object(t.pool_id),s.pure(i),s.pure(r),w.targetCoin,v.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(G)]}):(s=re.createCollectRewarderAndFeeParams(this._sdk,s,t,h,w.remainCoins,v.remainCoins),s.moveCall({target:`${e.published_at}::${jn}::add_liquidity`,typeArguments:o,arguments:[s.object(D(n).global_config_id),s.object(t.pool_id),s.object(t.pos_id),w.targetCoin,v.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(G)]})),s}async removeLiquidityTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i="remove_liquidity",r=new vi.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);r=re.createCollectRewarderAndFeeParams(this._sdk,r,t,s);let a=[r.object(D(e).global_config_id),r.object(t.pool_id),r.object(t.pos_id),r.pure(t.delta_liquidity),r.pure(t.min_amount_a),r.pure(t.min_amount_b),r.object(G)];return r.moveCall({target:`${n.published_at}::${tr}::${i}`,typeArguments:o,arguments:a}),r}async closePositionTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new vi.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return i=re.createCollectRewarderAndFeeParams(this._sdk,i,t,o),i.moveCall({target:`${n.published_at}::${tr}::close_position`,typeArguments:r,arguments:[i.object(D(e).global_config_id),i.object(t.pool_id),i.object(t.pos_id),i.pure(t.min_amount_a),i.pure(t.min_amount_b),i.object(G)]}),i}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new vi.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=Tt(BigInt(t.tick_lower)).toString(),s=Tt(BigInt(t.tick_upper)).toString(),a=[i.pure(D(e).global_config_id),i.pure(t.pool_id),i.pure(o),i.pure(s)];return i.moveCall({target:`${n.published_at}::${tr}::open_position`,typeArguments:r,arguments:a}),i}async collectFeeTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),n=new vi.TransactionBlock,i=re.buildCoinForAmount(n,e,BigInt(0),t.coinTypeA,!1),r=re.buildCoinForAmount(n,e,BigInt(0),t.coinTypeB,!1);return this.createCollectFeePaylod(t,n,i.targetCoin,r.targetCoin),n}createCollectFeePaylod(t,e,n,i){let{clmm_pool:r,integrate:o}=this.sdk.sdkOptions,s=[t.coinTypeA,t.coinTypeB],a=[e.object(D(r).global_config_id),e.object(t.pool_id),e.object(t.pos_id),n,i];return e.moveCall({target:`${o.published_at}::${jn}::collect_fee`,typeArguments:s,arguments:a}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let n=await this._sdk.fullClient.devInspectTransactionBlock({transactionBlock:e,sender:this._sdk.senderAddress});for(let i of n.events)if(q(i.type).name==="CollectFeeEvent"){let r=i.parsedJson;return{feeOwedA:r.amount_a,feeOwedB:r.amount_b}}return{feeOwedA:"0",feeOwedB:"0"}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},W0=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[ie,ie,ie]}get sdk(){return this._sdk}async emissionsEveryDay(t){let n=(await this.sdk.Pool.getPool(t)).rewarder_infos;if(!n)return null;let i=[];for(let r of n){let o=Te.fromX64(new Me.default(r.emissions_per_second));i.push({emissions:Math.floor(o.toNumber()*60*60*24),coin_address:r.coinAddress})}return i}async updatePoolRewarder(t,e){let n=await this.sdk.Pool.getPool(t),i=n.rewarder_last_updated_time;if(n.rewarder_last_updated_time=e.toString(),Number(n.liquidity)===0||e.eq(new Me.default(i)))return n;let r=e.div(new Me.default(1e3)).sub(new Me.default(i)).add(new Me.default(15)),o=n.rewarder_infos;for(let s=0;s<o.length;s+=1){let a=o[s],u=Te.checkMulDivFloor(r,new Me.default(a.emissions_per_second),new Me.default(n.liquidity),128);this.growthGlobal[s]=new Me.default(a.growth_global).add(new Me.default(u))}return n}async posRewardersAmount(t,e,n){let i=Date.parse(new Date().toString()),r=await this.updatePoolRewarder(t,new Me.default(i)),o=await this.sdk.Position.getPositionRewarders(e,n);if(o===void 0)return[];let s=r.ticks_handle,a=await this.sdk.Pool.getTickDataByIndex(s,o.tick_lower_index),u=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(r,o,a,u)}async poolRewardersAmount(t,e){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(e,new Me.default(n)),r=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(i.ticks_handle,r),s=[ie,ie,ie];for(let a=0;a<r.length;a+=1){let u=await this.posRewardersAmountInternal(i,r[a],o[0][a],o[1][a]);for(let l=0;l<3;l+=1)s[l]=s[l].add(u[l].amount_owed)}return s}posRewardersAmountInternal(t,e,n,i){let r=e.tick_lower_index,o=e.tick_upper_index,s=$0(t,n,i,r,o,this.growthGlobal),a=[],u=[];if(s.length>0){let l=Te.subUnderflowU128(s[0],new Me.default(e.reward_growth_inside_0));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[0]),u.push({amount_owed:new Me.default(e.reward_amount_owed_0).add(h),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let l=Te.subUnderflowU128(s[1],new Me.default(e.reward_growth_inside_1));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[1]),u.push({amount_owed:new Me.default(e.reward_amount_owed_1).add(h),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let l=Te.subUnderflowU128(s[2],new Me.default(e.reward_growth_inside_2));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[2]),u.push({amount_owed:new Me.default(e.reward_amount_owed_2).add(h),coin_address:t.rewarder_infos[2].coinAddress})}return u}async batchFetchPositionRewarders(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB,rewarderInfo:o.rewarder_infos})}let n={};if(e.length>0){let i=await this.fetchPosRewardersAmount(e);for(let r of i)n[r.positionId]=r.rewarderAmountOwed;return n}return n}async fetchPositionRewarders(t,e){let n={poolAddress:t.poolAddress,positionId:e,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,rewarderInfo:t.rewarder_infos};return(await this.fetchPosRewardersAmount([n]))[0].rewarderAmountOwed}async batchFetchPositionFees(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let n={};if(e.length>0){let i=await this.fetchPosFeeAmount(e);for(let r of i)n[r.position_id]=r;return n}return n}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new ss.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address})).events?.filter(u=>q(u.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let u=0;u<s.length;u+=1){let{parsedJson:l}=s[u],h={feeOwedA:new Me.default(l.fee_owned_a),feeOwedB:new Me.default(l.fee_owned_b),position_id:l.position_id};a.push(h)}return a}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new ss.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId),r.object(G)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_rewards`,arguments:h,typeArguments:l})}if(!Nt(i.address))throw new J(`this config simulationAccount: ${i.address} is not set right`,"InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address});if(o.error!=null)throw new J(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(u=>q(u.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new J("valueData.length !== params.pools.length");let a=[];for(let u=0;u<s.length;u+=1){let l={poolAddress:t[u].poolAddress,positionId:t[u].positionId,rewarderAmountOwed:[]};for(let h=0;h<t[u].rewarderInfo.length;h+=1)l.rewarderAmountOwed.push({amount_owed:new Me.default(s[u].parsedJson.data[h]),coin_address:t[u].rewarderInfo[h].coinAddress});a.push(l)}return a}async fetchPoolRewardersAmount(t,e){let n=await this.sdk.Pool.getPool(e),i=await this.sdk.Position.getPositionList(t,[e]),r=[];for(let a of i)r.push({poolAddress:n.poolAddress,positionId:a.pos_object_id,rewarderInfo:n.rewarder_infos,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB});let o=await this.fetchPosRewardersAmount(r),s=[ie,ie,ie];if(o!=null)for(let a of o)for(let u=0;u<a.rewarderAmountOwed.length;u+=1)s[u]=s[u].add(a.rewarderAmountOwed[u].amount_owed);return s}async getPoolLowerAndUpperTicks(t,e){let n=[],i=[];for(let r of e){let o=await this.sdk.Pool.getTickDataByIndex(t,r.tick_lower_index),s=await this.sdk.Pool.getTickDataByIndex(t,r.tick_upper_index);n.push(o),i.push(s)}return[n,i]}async collectRewarderTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),n=new ss.TransactionBlock;return n=re.createCollectRewarderAndFeeParams(this._sdk,n,t,e),n}createCollectRewarderPaylod(t,e,n){let{clmm_pool:i,integrate:r}=this.sdk.sdkOptions,o=D(i),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((a,u)=>{e&&e.moveCall({target:`${r.published_at}::${jn}::collect_reward`,typeArguments:[...s,a],arguments:[e.object(o.global_config_id),e.object(t.pool_id),e.object(t.pos_id),e.object(o.global_vault_id),n[u],e.object(G)]})}),e}};function rs(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var H0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new Ti.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:n,reversePair:i}=rs(t,e),r=this.poolAddressMap.get(n);if(r!=null)return{addressMap:r,direction:!0};if(r=this.poolAddressMap.get(i),r!=null)return{addressMap:r,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(n=>{let{paths:i}=n;i.forEach(r=>{let o=this.graph.getVertexByKey(r.base)??new Ti.GraphVertex(r.base),s=this.graph.getVertexByKey(r.quote)??new Ti.GraphVertex(r.quote);this.graph.addEdge(new Ti.GraphEdge(o,s));let a=this._coinAddressMap.get(r.base),u=this._coinAddressMap.get(r.quote);if(a!=null&&u!=null){let l=rs(r.base,r.quote).pair;this.poolAddressMap.set(l,r.addressMap)}})})}addPathProvider(t){for(let e=0;e<t.paths.length;e+=1){let{base:n,quote:i}=t.paths[e];n.localeCompare(i)<0&&(t.paths[e].base=i,t.paths[e].quote=n),n==="0x2::sui::SUI"&&(t.paths[e].base=i,t.paths[e].quote=n),i==="0x2::sui::SUI"&&(t.paths[e].base=n,t.paths[e].quote=i)}return this.pathProviders.push(t),this}addCoinProvider(t){return this.coinProviders=t,this}tokenInfo(t){return this._coinAddressMap.get(t)}getFeeRate(t,e,n){let i=rs(t,e).pair,r=this.poolAddressMap.get(i);if(r!=null){for(let[a,u]of r.entries())if(u===n)return a*100}let o=rs(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[a,u]of s.entries())if(u===n)return a*100}return 0}async price(t,e,n,i,r,o,s){let a=this.tokenInfo(t),u=this.tokenInfo(e);if(a===void 0||u===void 0)throw new J("From/To coin is undefined","InvalidCoin");let l=this.graph.getVertexByKey(a.address),h=this.graph.getVertexByKey(u.address),w=this.graph.findAllPath(l,h),v=Array.from(w);if(v.length===0)throw new J("No find valid path in coin graph","NotFoundPath");let T=[];for(let F=0;F<v.length;F+=1){let K=v[F];if(K.length>3)continue;let C=[],A=[],c=[],d=[];for(let g=0;g<K.length-1;g+=1){let b=K[g].value.toString(),p=K[g+1].value.toString(),m=this.getPoolAddressMapAndDirection(b,p),y=m?.addressMap,_=m?.direction;y!=null&&_!=null&&(A.push(_),C.push(b),C.push(p),y.forEach(f=>{g===0?c.push(f):d.push(f)}))}for(let g of c)if(d.length>0)for(let b of d){let p={stepNums:2,poolAB:g,poolBC:b,a2b:A[0],b2c:A[1],amount:n,byAmountIn:i,coinTypeA:C[0],coinTypeB:C[1],coinTypeC:C[3]};T.push(p)}else{let b={stepNums:1,poolAB:g,poolBC:void 0,a2b:A[0],b2c:void 0,amount:n,byAmountIn:i,coinTypeA:C[0],coinTypeB:C[1],coinTypeC:void 0};T.push(b)}}let I=T.filter(F=>F.stepNums===1),x=T.filter(F=>F.stepNums!==1),P=[];try{P=await this.getPoolWithTVL()}catch{P=[]}if(P.length>0){let F=new Map(P.map(K=>[K.poolAddress,K]));x.sort((K,C)=>{let A=0,c=0;if(F.has(K.poolAB)&&F.has(K.poolBC)){let d=F.get(K.poolAB),g=F.get(K.poolBC);A=Math.min(d.tvl,g.tvl)}if(F.has(C.poolAB)&&F.has(C.poolBC)){let d=F.get(C.poolAB),g=F.get(C.poolBC);c=Math.min(d.tvl,g.tvl)}return c-A})}if(T=[...I,...x],T.length===0){if(s!=null){let F=await this.sdk.Swap.preSwapWithMultiPool(s),K={amountIn:new Ht.default(F.estimatedAmountIn),amountOut:new Ht.default(F.estimatedAmountOut),poolAddress:[F.poolAddress],a2b:[F.aToB],rawAmountLimit:i?[F.estimatedAmountOut]:[F.estimatedAmountIn],isExceed:F.isExceed,coinType:[t,e]},C={paths:[K],partner:o,priceSlippagePoint:r};return{amountIn:new Ht.default(F.estimatedAmountIn),amountOut:new Ht.default(F.estimatedAmountOut),paths:[K],a2b:F.aToB,b2c:void 0,byAmountIn:i,isExceed:F.isExceed,targetSqrtPrice:[F.estimatedEndSqrtPrice],currentSqrtPrice:[F.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:C}}throw new J("No parameters available for service downgrade","NoDowngradeNeedParams")}let O=await this.preRouterSwapA2B2C(T.slice(0,16));if(O==null){if(s!=null){let K=await this.sdk.Swap.preSwapWithMultiPool(s),C={amountIn:new Ht.default(K.estimatedAmountIn),amountOut:new Ht.default(K.estimatedAmountOut),poolAddress:[K.poolAddress],a2b:[K.aToB],rawAmountLimit:i?[K.estimatedAmountOut]:[K.estimatedAmountIn],isExceed:K.isExceed,coinType:[t,e]},A={paths:[C],partner:o,priceSlippagePoint:r};return{amountIn:new Ht.default(K.estimatedAmountIn),amountOut:new Ht.default(K.estimatedAmountOut),paths:[C],a2b:K.aToB,b2c:void 0,byAmountIn:i,isExceed:K.isExceed,targetSqrtPrice:[K.estimatedEndSqrtPrice],currentSqrtPrice:[K.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:A}}return{amountIn:ie,amountOut:ie,paths:[],a2b:!1,b2c:!1,byAmountIn:i,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let E=O.index,B=T[E].poolBC!=null?[T[E].poolAB,T[E].poolBC]:[T[E].poolAB],$=i?[O.amountMedium,O.amountOut]:[O.amountIn,O.amountMedium],Z=[];Z.push(T[E].a2b),O.stepNum>1&&Z.push(T[E].b2c);let H=[];H.push(T[E].coinTypeA),H.push(T[E].coinTypeB),O.stepNum>1&&H.push(T[E].coinTypeC);let te={amountIn:O.amountIn,amountOut:O.amountOut,poolAddress:B,a2b:Z,rawAmountLimit:$,isExceed:O.isExceed,coinType:H},U={paths:[te],partner:o,priceSlippagePoint:r};return{amountIn:O.amountIn,amountOut:O.amountOut,paths:[te],a2b:T[E].a2b,b2c:O.stepNum>1?T[E].b2c:void 0,byAmountIn:i,isExceed:O.isExceed,targetSqrtPrice:O.targetSqrtPrice,currentSqrtPrice:O.currentSqrtPrice,coinTypeA:T[E].coinTypeA,coinTypeB:T[E].coinTypeB,coinTypeC:O.stepNum>1?T[E].coinTypeC:void 0,createTxParams:U}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new of.TransactionBlock;for(let w of t)if(w.stepNums>1){let v=[i.object(w.poolAB),i.object(w.poolBC),i.pure(w.a2b),i.pure(w.b2c),i.pure(w.byAmountIn),i.pure(w.amount.toString())],T=[];w.a2b?T.push(w.coinTypeA,w.coinTypeB):T.push(w.coinTypeB,w.coinTypeA),w.b2c?T.push(w.coinTypeB,w.coinTypeC):T.push(w.coinTypeC,w.coinTypeB),i.moveCall({target:`${e.published_at}::${Jn}::calculate_router_swap_result`,typeArguments:T,arguments:v})}else{let v=[i.pure(w.poolAB),i.pure(w.a2b),i.pure(w.byAmountIn),i.pure(w.amount.toString())],T=w.a2b?[w.coinTypeA,w.coinTypeB]:[w.coinTypeB,w.coinTypeA];i.moveCall({target:`${e.published_at}::${c0}::get_expect_swap_result`,arguments:v,typeArguments:T})}if(!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(w=>q(w.type).name==="CalculatedRouterSwapResultEvent"||q(w.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?ie:nr,a=0;for(let w=0;w<o.length;w+=1)if(!o[w].parsedJson.data.is_exceed)if(t[0].byAmountIn){let v=new Ht.default(o[w].parsedJson.data.amount_out);v.gt(s)&&(a=w,s=v)}else{let v=t[w].stepNums>1?new Ht.default(o[w].parsedJson.data.amount_in):new Ht.default(o[w].parsedJson.data.amount_in).add(new Ht.default(o[w].parsedJson.data.fee_amount));v.lt(s)&&(a=w,s=v)}let u=[],l=[];return t[a].stepNums>1?(l.push(o[a].parsedJson.data.target_sqrt_price_ab,o[a].parsedJson.data.target_sqrt_price_cd),u.push(o[a].parsedJson.data.current_sqrt_price_ab,o[a].parsedJson.data.current_sqrt_price_cd)):(l.push(o[a].parsedJson.data.after_sqrt_price),u.push(o[a].parsedJson.current_sqrt_price)),{index:a,amountIn:t[0].byAmountIn?t[a].amount:s,amountMedium:o[a].parsedJson.data.amount_medium,amountOut:t[0].byAmountIn?s:t[a].amount,targetSqrtPrice:l,currentSqrtPrice:u,isExceed:o[a].parsedJson.data.is_exceed,stepNum:t[a].stepNums}}async getPoolWithTVL(){let t=[],{swapCountUrl:e}=this._sdk.sdkOptions;if(!e)return t;let n;try{n=await fetch(e)}catch{throw new J(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let i;try{i=await n.json()}catch{throw new J(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(i.code!==200)throw new J(`Failed to get pool list from ${e}. Statu code is ${i.code}.`,"InvalidSwapCountUrl");let{pools:r}=i.data;for(let o of r)t.push({poolAddress:o.swap_account,tvl:Number(o.tvl_in_usd)});return t}};var Z0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=S(0);return t.forEach(n=>{let i=n.basePaths.length;if(i>0){let r=n.basePaths[0],o=r.label==="Cetus"?new N(r.feeRate).div(10**6):new N(r.feeRate).div(10**9),s=S(r.inputAmount).div(10**r.fromDecimal).mul(o);if(e=e.add(s),i>1){let a=n.basePaths[1],u=r.direction?r.currentPrice:new N(1).div(r.currentPrice),l=a.direction?a.currentPrice:new N(1).div(a.currentPrice),h=a.label==="Cetus"?new N(a.feeRate).div(10**6):new N(a.feeRate).div(10**9),v=S(a.outputAmount).div(10**a.toDecimal).mul(h).div(u.mul(l));e=e.add(v)}}}),e.toString()}calculateSwapPriceImpact(t){let e=S(0);return t.forEach(n=>{let i=n.basePaths.length;if(i===1){let r=n.basePaths[0],o=S(r.outputAmount).div(10**r.toDecimal),s=S(r.inputAmount).div(10**r.fromDecimal),a=o.div(s),u=r.direction?new N(r.currentPrice):new N(1).div(r.currentPrice);e=e.add(this.calculateSingleImpact(a,u))}if(i===2){let r=n.basePaths[0],o=n.basePaths[1],s=r.direction?new N(r.currentPrice):new N(1).div(r.currentPrice),a=o.direction?new N(o.currentPrice):new N(1).div(o.currentPrice),u=s.mul(a),l=new N(o.outputAmount).div(10**o.toDecimal),h=new N(r.inputAmount).div(10**r.fromDecimal),w=l.div(h);e=e.add(this.calculateSingleImpact(w,u))}}),e.toString()}calculateSingleImpact=(t,e)=>e.minus(t).div(e).mul(100);async preSwapWithMultiPool(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new _c.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];for(let l=0;l<t.poolAddresses.length;l+=1){let h=[i.pure(t.poolAddresses[l]),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:h,typeArguments:r})}if(!Nt(n.address))throw new J("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 J(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(l=>q(l.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new J("valueData.length !== params.pools.length","ParamsLengthNotEqual");let a=t.byAmountIn?ie:nr,u=0;for(let l=0;l<s.length;l+=1)if(!s[l].parsedJson.data.is_exceed)if(t.byAmountIn){let h=new ki.default(s[l].parsedJson.data.amount_out);h.gt(a)&&(u=l,a=h)}else{let h=new ki.default(s[l].parsedJson.data.amount_out);h.lt(a)&&(u=l,a=h)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[u],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[u].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new _c.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=[i.pure(t.pool.poolAddress),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];if(i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:o,typeArguments:r}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let s=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(s.error!=null)throw new J(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let a=s.events?.filter(u=>q(u.type).name==="CalculatedSwapResultEvent");return a.length===0?null:this.transformSwapData(t,a[0].parsedJson.data)}transformSwapData(t,e){let n=e.amount_in&&e.fee_amount?new ki.default(e.amount_in).add(new ki.default(e.fee_amount)).toString():"";return{poolAddress:t.pool.poolAddress,currentSqrtPrice:t.currentSqrtPrice,estimatedAmountIn:n,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:n}=e,i=n.amount_in&&n.fee_amount?new ki.default(n.amount_in).add(new ki.default(n.fee_amount)).toString():"";return{poolAddress:t.poolAddress,estimatedAmountIn:i,estimatedAmountOut:n.amount_out,estimatedEndSqrtPrice:n.after_sqrt_price,estimatedStartSqrtPrice:e.current_sqrt_price,estimatedFeeAmount:n.fee_amount,isExceed:n.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}calculateRates(t){let{currentPool:e}=t,n=s0(e),i;t.a2b?i=t.swapTicks.sort((w,v)=>v.index-w.index):i=t.swapTicks.sort((w,v)=>w.index-v.index);let r=T0(t.a2b,t.byAmountIn,t.amount,n,i),o=!1;t.byAmountIn?o=r.amountIn.lt(t.amount):o=r.amountOut.lt(t.amount);let s=mn.getDefaultSqrtPriceLimit(t.a2b);t.a2b&&r.nextSqrtPrice.lt(s)&&(o=!0),!t.a2b&&r.nextSqrtPrice.gt(s)&&(o=!0);let a=0;r.crossTickNum>6&&r.crossTickNum<40&&(a=22e3*(r.crossTickNum-6)),r.crossTickNum>40&&(o=!0);let u=ee.sqrtPriceX64ToPrice(n.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),l=ee.sqrtPriceX64ToPrice(r.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),h=Math.abs(u-l)/u*100;return{estimatedAmountIn:r.amountIn,estimatedAmountOut:r.amountOut,estimatedEndSqrtPrice:r.nextSqrtPrice,estimatedFeeAmount:r.feeAmount,isExceed:o,extraComputeLimit:a,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn,priceImpactPct:h}}async createSwapTransactionPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=us(t);if(t.a2b&&i||!t.a2b&&r)return await re.buildSwapTransactionForGas(this._sdk,t,n,e)}return re.buildSwapTransaction(this.sdk,t,n)}async createSwapTransactionWithoutTransferCoinsPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=us(t);if(t.a2b&&i||!t.a2b&&r)return await re.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,n,e)}return re.buildSwapTransactionWithoutTransferCoins(this.sdk,t,n)}},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="",n=!1){return await this.factchWarpPoolList(t,e,n)}async getTokenListByCoinTypes(t){let e={},i=this.getCache("getAllRegisteredTokenList");if(i!==void 0){let o=i;for(let s of t)for(let a of o)if(Et(s)===Et(a.address)){e[s]=a;continue}}let r=t.filter(o=>e[o]===void 0);for(let o of r){let s=`${o}_metadata`,a=this.getCache(s);if(a!==void 0)e[o]=a;else{let u=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(u){let l={id:u.id,name:u.name,symbol:u.symbol,official_symbol:u.symbol,coingecko_id:"",decimals:u.decimals,project_url:"",logo_url:u.iconUrl,address:o};e[o]=l,this.updateCache(s,l,X)}}}return e}async factchTokenList(t="",e=!1){let{simulationAccount:n,token:i}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredTokenList",e);if(o!==void 0)return o;let s=t.length>0,a=512,u=0,l=[];if(i===void 0)throw Error("please config token ofsdkOptions");let h=D(i);for(;;){let w=new yc.TransactionBlock;w.moveCall({target:`${i.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[w.pure(h.coin_registry_id),w.pure(t),w.pure(u),w.pure(a)]:[w.pure(h.coin_registry_id),w.pure(u),w.pure(a)]});let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:w,sender:n.address}),T=[];if(v.events?.forEach(I=>{q(I.type).full_address===`${i.published_at}::coin_list::FetchCoinListEvent`&&I.parsedJson.full_list.value_list.forEach(P=>{T.push(this.transformData(P,!1))})}),l=[...l,...T],T.length<a)break;u=l.length}return l}async factchPoolList(t="",e=!1){let{simulationAccount:n,token:i}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredPoolList",e);if(o!==void 0)return o;let s=[],a=512,u=0,l=t.length>0;if(i===void 0)throw Error("please config token ofsdkOptions");let h=D(i);for(;;){let w=new yc.TransactionBlock;if(w.moveCall({target:`${i.published_at}::lp_list::${l?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:l?[w.pure(h.pool_registry_id),w.pure(t),w.pure(u),w.pure(a)]:[w.pure(h.pool_registry_id),w.pure(u),w.pure(a)]}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:w,sender:n.address}),T=[];if(v.events?.forEach(I=>{q(I.type).full_address===`${i.published_at}::lp_list::FetchPoolListEvent`&&I.parsedJson.full_list.value_list.forEach(P=>{T.push(this.transformData(P,!0))})}),s=[...s,...T],T.length<a)break;u=s.length}return s}async factchWarpPoolList(t="",e="",n=!1){let i=await this.factchPoolList(t,n);if(i.length===0)return[];let r=await this.factchTokenList(e,n),o=[];for(let s of i){for(let a of r)a.address===s.coin_a_address&&(s.coinA=a),a.address===s.coin_b_address&&(s.coinB=a);o.push(s)}return o}async getTokenConfigEvent(t=!1){let e=this._sdk.sdkOptions.token.package_id,n=`${e}_getTokenConfigEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),a={coin_registry_id:"",pool_registry_id:"",coin_list_owner:"",pool_list_owner:""};return s.data.length>0&&s.data.forEach(u=>{let l=q(u.type);if(u.transactionModule==="coin_list")switch(l.name){case"InitListEvent":a.coin_list_owner=u.parsedJson.list_id;break;case"InitRegistryEvent":a.coin_registry_id=u.parsedJson.registry_id;break;default:break}else if(u.transactionModule==="lp_list")switch(l.name){case"InitListEvent<address>":a.pool_list_owner=u.parsedJson.list_id;break;case"InitRegistryEvent<address>":a.pool_registry_id=u.parsedJson.registry_id;break;default:break}}),a.coin_registry_id.length>0&&this.updateCache(n,a,X),a}transformData(t,e){let n={...t};if(e)try{n.coin_a_address=q(n.coin_a_address).full_address,n.coin_b_address=q(n.coin_b_address).full_address}catch{}else n.address=q(n.address).full_address;if(t.extensions){let i=t.extensions.contents;for(let r of i){let{key:o}=r,{value:s}=r;if(o==="labels")try{s=JSON.parse(decodeURIComponent(Ji.decode(s)))}catch{}o==="pyth_id"&&(s=(0,sf.normalizeSuiObjectId)(s)),n[o]=s}delete n.extensions}return n}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},J0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculatePrice(t,e,n,i,r){let o=i?e:n,s=i?n:e;return r==="Cetus"?ee.sqrtPriceX64ToPrice(t,o,s):new N(t.toString()).div(new N(10).pow(new N(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(n=>({pathIndex:n.path_index,lastQuoteOutput:n.last_quote_output,percent:n.percent,basePaths:n.best_path.map(r=>({direction:r.direction,label:r.label,poolAddress:r.provider,fromCoin:r.from_coin,toCoin:r.to_coin,outputAmount:r.output_amount,inputAmount:r.input_amount,feeRate:r.fee_rate,currentSqrtPrice:new hn.default(r.current_sqrt_price.toString()),afterSqrtPrice:r.label==="Cetus"?new hn.default(r.after_sqrt_price.toString()):ie,fromDecimal:r.from_decimal,toDecimal:r.to_decimal,currentPrice:this.calculatePrice(new hn.default(r.current_sqrt_price.toString()),r.from_decimal,r.to_decimal,r.direction,r.label)})),inputAmount:n.input_amount,outputAmount:n.output_amount}))}}async fetchWithTimeout(t,e,n){let i=new AbortController,r=setTimeout(()=>i.abort(),n);try{let o=await fetch(t,{...e,signal:i.signal});return clearTimeout(r),o}catch{return null}}async fetchAndParseData(t,e){try{let i=await this.fetchWithTimeout(t,e,1500);return i.status===200?this.parseJsonResult(await i.json()):null}catch{return null}}async getBestRouter(t,e,n,i,r,o,s,a,u=!1,l=!1,h=[]){let w=null,v="v2",T={},I=this.sdk.sdkOptions.aggregatorUrl;if(h.length>0){let x=new URL(I);I=`${x.protocol}//${x.hostname}/router_with_lp_changes`,T={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:n,by_amount_in:i,order_split:u,external_router:l,sender_address:"None",request_id:encodeURIComponent(ts()),lp_changes:h})}}else I=`
4
- ${I}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(n)}&by_amount_in=${encodeURIComponent(i)}&order_split=${encodeURIComponent(u)}&external_router=${encodeURIComponent(l)}&sender_address=''&request_id=${encodeURIComponent(ts())}
5
- `;if(w=await this.fetchAndParseData(I,T),w?.isTimeout||w==null){let x=await this.sdk.Router.price(t,e,new hn.default(n),i,r,o,a),P=[];for(let E of x.paths){let B=[];if(E.poolAddress.length>1){let Z=this.sdk.Router.tokenInfo(E.coinType[0]).decimals,H=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,te=E.a2b[0]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),H,Z),U={direction:E.a2b[0],label:"Cetus",poolAddress:E.poolAddress[0],fromCoin:E.coinType[0],toCoin:E.coinType[1],feeRate:this.sdk.Router.getFeeRate(E.coinType[0],E.coinType[1],E.poolAddress[0]),outputAmount:x.byAmountIn?E.rawAmountLimit[0].toString():E.rawAmountLimit[1].toString(),inputAmount:E.amountIn.toString(),currentSqrtPrice:x.currentSqrtPrice[0],currentPrice:te,fromDecimal:Z,toDecimal:H},V=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,F=this.sdk.Router.tokenInfo(E.coinType[2]).decimals,K=E.a2b[1]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),V,F):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),F,V),C={direction:E.a2b[1],label:"Cetus",poolAddress:E.poolAddress[1],fromCoin:E.coinType[1],toCoin:E.coinType[2],feeRate:this.sdk.Router.getFeeRate(E.coinType[1],E.coinType[2],E.poolAddress[1]),outputAmount:E.amountOut.toString(),inputAmount:x.byAmountIn?E.rawAmountLimit[0].toString():E.rawAmountLimit[1].toString(),currentSqrtPrice:x.currentSqrtPrice[1],currentPrice:K,fromDecimal:V,toDecimal:F};B.push(U,C)}else{let Z=this.sdk.Router.tokenInfo(E.coinType[0]).decimals,H=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,te=E.a2b[0]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),H,Z),U={direction:E.a2b[0],label:"Cetus",poolAddress:E.poolAddress[0],fromCoin:E.coinType[0],toCoin:E.coinType[1],feeRate:this.sdk.Router.getFeeRate(E.coinType[0],E.coinType[1],E.poolAddress[0]),outputAmount:E.amountOut.toString(),inputAmount:E.amountIn.toString(),currentSqrtPrice:x.currentSqrtPrice[0],currentPrice:te,fromDecimal:Z,toDecimal:H};B.push(U)}let $={percent:Number(E.amountIn)/Number(x.amountIn)*100,inputAmount:Number(E.amountIn.toString()),outputAmount:Number(E.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:B};P.push($)}let O={isExceed:x.isExceed,isTimeout:!0,inputAmount:Number(x.amountIn.toString()),outputAmount:Number(x.amountOut.toString()),fromCoin:x.coinTypeA,toCoin:x.coinTypeC!=null?x.coinTypeC:x.coinTypeB,byAmountIn:x.byAmountIn,splitPaths:P};v="v1",w=O}return{result:w,version:v}}},Y0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=D(this.sdk.sdkOptions.cetus_config),n=`${e}_getCoinConfigs`,i=this.getCache(n),r=i?[...i,...t]:t;this.updateCache(n,r,X)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getCoinConfigs`,r=this.getCache(i);if(r!==void 0){let s=r;for(let a of t)for(let u of s)if(Et(a)===Et(u.address)){e[a]=u;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let a=`${s}_metadata`,u=this.getCache(a);if(u!==void 0)e[s]=u;else{let l=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(l){let h={id:l.id,pyth_id:"",name:l.name,symbol:l.symbol,official_symbol:l.symbol,coingecko_id:"",decimals:l.decimals,project_url:"",logo_url:l.iconUrl,address:s};e[s]=h,this.updateCache(a,h,X)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getCoinConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildCoinConfig(l,e);this.updateCache(`${n}_${h.address}_getCoinConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getCoinConfig(t,e=!1,n=!0){let{coin_list_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${i}_${t}_getCoinConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"0x1::type_name::TypeName",value:{name:I0(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfig get object error: ${s.error}, please check the rpc and contracts address config.`,"InvalidConfig");let a=this.buildCoinConfig(s,n);return this.updateCache(r,a,X),a}buildCoinConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};return i.id=Lt(t),i.address=q(n.coin_type.fields.name).full_address,n.pyth_id&&(i.pyth_id=(0,as.normalizeSuiObjectId)(n.pyth_id)),this.transformExtensions(i,n.extension_fields.fields.contents,e),delete i.coin_type,i}async getClmmPoolConfigs(t=!1,e=!0){let{clmm_pools_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getClmmPoolConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getClmmPoolsConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildClmmPoolConfig(l,e);this.updateCache(`${h.pool_address}_getClmmPoolConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getClmmPoolConfig(t,e=!1,n=!0){let{clmm_pools_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${t}_getClmmPoolConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"address",value:t}}),a=this.buildClmmPoolConfig(s,n);return this.updateCache(r,a,X),a}buildClmmPoolConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};return i.id=Lt(t),i.pool_address=(0,as.normalizeSuiObjectId)(n.pool_address),this.transformExtensions(i,n.extension_fields.fields.contents,e),i}async getLaunchpadPoolConfigs(t=!1,e=!0){let{launchpad_pools_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getLaunchpadPoolConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildLaunchpadPoolConfig(l,e);this.updateCache(`${h.pool_address}_getLaunchpadPoolConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getLaunchpadPoolConfig(t,e=!1,n=!0){let{launchpad_pools_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${t}_getLaunchpadPoolConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"address",value:t}}),a=this.buildLaunchpadPoolConfig(s,n);return this.updateCache(r,a,X),a}buildLaunchpadPoolConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};i.id=Lt(t),i.pool_address=(0,as.normalizeSuiObjectId)(n.pool_address),this.transformExtensions(i,n.extension_fields.fields.contents,e);let r=[];n.social_media.fields.contents.forEach(o=>{r.push({name:o.fields.value.fields.name,link:o.fields.value.fields.link})}),i.social_media=r;try{i.regulation=decodeURIComponent(Ji.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=Ji.decode(i.regulation)}return i}transformExtensions(t,e,n=!0){let i=[];for(let r of e){let{key:o}=r.fields,{value:s}=r.fields;if(o==="labels")try{s=JSON.parse(decodeURIComponent(Ji.decode(s)))}catch{}n&&(t[o]=s),i.push({key:o,value:s})}delete t.extension_fields,n||(t.extensions=i)}async getCetusConfig(t=!1){let e=this._sdk.sdkOptions.cetus_config.package_id,n=`${e}_getCetusConfig`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),a={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 u of s.data)switch(q(u.type).name){case"InitCoinListEvent":a.coin_list_id=u.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":a.launchpad_pools_id=u.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":a.clmm_pools_id=u.parsedJson.pools_id;break;case"InitConfigEvent":a.global_config_id=u.parsedJson.global_config_id,a.admin_cap_id=u.parsedJson.admin_cap_id;break;default:break}return a=await this.getCetusConfigHandle(a),a.clmm_pools_id.length>0&&this.updateCache(n,a,X),a}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(i=>{if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`when getCetusConfigHandle get objects error: ${i.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let r=Q(i),o=pn(i);switch(q(o).name){case"ClmmPools":t.clmm_pools_handle=r.pools.fields.id.id;break;case"CoinList":t.coin_list_handle=r.coins.fields.id.id;break;case"LaunchpadPools":t.launchpad_pools_handle=r.pools.fields.id.id;break;default:break}}),t}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){try{let n=this._cache[t];if(!n)return;if(e||!n.isValid()){delete this._cache[t];return}return n.value}catch(n){console.error(`Error accessing cache for key ${t}:`,n);return}}},Q0=class extends cf.SuiClient{async queryEventsByPage(t,e="all"){let n=[],i=!0,r=e==="all",o=r?null:e.cursor;do{let s=await this.queryEvents({query:t,cursor:o,limit:r?null:e.limit});s.data?(n=[...n,...s.data],i=s.hasNextPage,o=s.nextCursor):i=!1}while(r&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getOwnedObjectsByPage(t,e,n="all"){let i=[],r=!0,o=n==="all",s=o?null:n.cursor;do{let a=await this.getOwnedObjects({owner:t,...e,cursor:s,limit:o?null:n.limit});a.data?(i=[...i,...a.data],r=a.hasNextPage,s=a.nextCursor):r=!1}while(o&&r);return{data:i,nextCursor:s,hasNextPage:r}}async getDynamicFieldsByPage(t,e="all"){let n=[],i=!0,r=e==="all",o=r?null:e.cursor;do{let s=await this.getDynamicFields({parentId:t,cursor:o,limit:r?null:e.limit});s.data?(n=[...n,...s.data],i=s.hasNextPage,o=s.nextCursor):i=!1}while(r&&i);return{data:n,nextCursor:o,hasNextPage:i}}async batchGetObjects(t,e,n=50){let i=[];try{for(let r=0;r<Math.ceil(t.length/n);r++){let o=await this.multiGetObjects({ids:t.slice(r*n,n*(r+1)),options:e});i=[...i,...o]}}catch(r){console.log(r)}return i}async calculationTxGas(t){let{sender:e}=t.blockData;if(e===void 0)throw Error("sdk sender is empty");let n=await this.devInspectTransactionBlock({transactionBlock:t,sender:e}),{gasUsed:i}=n.effects;return Number(i.computationCost)+Number(i.storageCost)-Number(i.storageRebate)}async sendTransaction(t,e){try{return await this.signAndExecuteTransactionBlock({transactionBlock:e,signer:t,options:{showEffects:!0,showEvents:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(t,e,n=!0){try{if(n)return await this.devInspectTransactionBlock({transactionBlock:t,sender:e});let r={ProgrammableTransaction:{inputs:t.blockData.inputs.map(u=>{let{type:l,value:h}=u;return l==="object"?af.Inputs.SharedObjectRef({objectId:h,initialSharedVersion:0,mutable:!0}):h}),transactions:t.blockData.transactions}},o=uf.bcs.TransactionKind.serialize(r,{maxSize:131072}).toBytes(),s=Za(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(i){console.log("devInspectTransactionBlock error",i)}}},sr=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new Q0({url:t.fullRpcUrl}),this._swap=new Z0(this),this._pool=new V0(this),this._position=new G0(this),this._rewarder=new W0(this),this._router=new H0(this),this._router_v2=new J0(this),this._token=new X0(this),this._config=new Y0(this),ms(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,n=!0){let i=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${t}_${e}_getOwnerCoinAssets`,s=this.getCache(o,n);if(s)return s;for(;;){let a=await(e?this.fullClient.getCoins({owner:t,coinType:e,cursor:r}):this.fullClient.getAllCoins({owner:t,cursor:r}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&i.push({coinAddress:q(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),r=a.nextCursor,!a.hasNextPage)break}return this.updateCache(o,i,30*1e3),i}async getOwnerCoinBalances(t,e){let n=[];return e?n=[await this.fullClient.getBalance({owner:t,coinType:e})]:n=[...await this.fullClient.getAllBalances({owner:t})],n}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}};var ff=require("@mysten/sui.js/utils");var ws=require("@mysten/sui.js/transactions");var Zt=require("@mysten/sui.js/transactions"),dr=require("@mysten/sui.js/utils"),Kr=ge(ke(),1);var hf=require("@mysten/sui.js/utils");var Cc=require("@mysten/sui.js/transactions");var Fn=require("@mysten/sui.js/transactions");var xn=require("@mysten/sui.js/utils"),Xt=require("@mysten/sui.js/transactions");var Sc=require("@mysten/sui.js/utils");var uy=require("@mysten/sui.js/utils");var qe=ge(ke(),1);var gf=ge(ke(),1);var Ac=ge(ke(),1);var Rn=require("@mysten/sui.js/transactions"),Ai=require("@mysten/sui.js/transactions");var xi=require("@mysten/sui.js/transactions");var Oe=ge(ke(),1);var xc=require("@mysten/sui.js/bcs"),$r=require("@mysten/sui.js/utils"),bs=require("@mysten/sui.js/transactions");var Jt=require("@mysten/sui.js/transactions"),vc="router",lr=1e4,Yn=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:q(e.clmm_pool_id).address,booster_type:q(e.booster_type.fields.name).source_address,pool_id:q(e.pool_id).address,coinTypeA:q(e.coin_type_a.fields.name).source_address,coinTypeB:q(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=Q(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({lock_day:Number(r.fields.key),multiplier:Number(S(r.fields.value).div(lr))})}),{basic_percent:Number(S(e.basic_percent).div(lr)),balances:{balances_handle:e.balances.fields.id.id,size:e.balances.fields.size},config:n,lock_positions:{lock_positions_handle:e.lock_positions.fields.id.id,size:e.lock_positions.fields.size},is_open:e.is_open,index:Number(e.index),pool_id:Lt(t)}}static buildLockNFT(t){let e=q(Lt(t)).address;return{lock_clmm_position:Nn(t),locked_nft_id:e}}static buildLockPositionInfo(t){let e=Q(t),{value:n}=e.value.fields;return{type:n.type,position_id:n.fields.position_id,start_time:Number(n.fields.start_time),lock_period:Number(n.fields.lock_period),end_time:Number(n.fields.end_time),growth_rewarder:n.fields.growth_rewarder,rewarder_owned:n.fields.rewarder_owned,is_settled:n.fields.is_settled}}static isLocked(t){return t.end_time>Date.parse(new Date().toString())/1e3}},ey=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=!1){let{booster:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n,t),r=[];if(i!==void 0)r.push(...i);else{let o=[];(await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(D(e).booster_pool_handle)).data?.forEach(u=>{o.push(u.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let u of a){let l=Q(u);if(l){let h=Yn.buildPoolImmutables(l);this.updateCache(`${h.pool_id}_getPoolImmutable`,h,X),r.push(h)}}}return this.updateCache(n,r,X),r}async getPoolImmutable(t){let{booster:e}=this._sdk.sdkOptions,n=`${t}_getPoolImmutable`,i=this.getCache(n);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(e).booster_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=Q(r),s=Yn.buildPoolImmutables(o);return this.updateCache(n,s,X),s}async getPools(){let t=[],n=(await this.getPoolImmutables()).map(r=>r.pool_id),i=await this._sdk.ClmmSDK.fullClient.batchGetObjects(n,{showType:!0,showContent:!0});for(let r of i){let o=Yn.buildPoolState(r);if(o){let s={...await this.getPoolImmutable(o.pool_id),...o};t.push(s);let a=`${s.pool_id}_getPoolObject`;this.updateCache(a,s,X)}}return t}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e),r=await this.getPoolImmutable(t);if(i!==void 0)return{...r,...i};let o=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),s=Yn.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,X),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=Q(e);return n?n.list.fields.id.id:""}async getBoosterInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.booster,e=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitEvent`}))?.data,n={booster_config_id:"",booster_pool_handle:""};return e.length>0&&e.forEach(i=>{let r=i.parsedJson;r&&(n.booster_config_id=r.config_id)}),n.booster_pool_handle=await this.getPoolHandleId(n.booster_config_id),n}async getOwnerBoosterPositions(t,e,n){let{booster:i}=this.sdk.sdkOptions,r=[],o=[],s=`${i.package_id}::lock_nft::LockNFT<${this._sdk.ClmmSDK.Position.buildPositionType()}>`,a=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showOwner:!0},filter:{StructType:s}});for(let l of a.data)if(q(Mt(l)).source_address===s&&l.data){let w=Yn.buildLockNFT(l);this.updateCache(`${w.locked_nft_id}_getBoosterPositionById`,w,X),w&&(e===void 0||e===w.lock_clmm_position.pool)&&r.push(w)}let u=await this.getLockPositionInfos(n,r.map(l=>l.locked_nft_id));for(let l of r)for(let h of u)if(l.lock_clmm_position.pos_object_id===h.position_id){o.push({...l,...h});break}return o}async getBoosterPosition(t,e){let n=`${e}_getBoosterPositionById`,i=this.getCache(n),r;if(i!==void 0)r=i;else{let s=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0,showOwner:!0}});r=Yn.buildLockNFT(s),this.updateCache(n,r,X)}let o=await this.getLockPositionInfo(t,e);return{...r,...o}}async getLockPositionInfos(t,e=[]){let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(t),i=[],r=[];return n.data?.forEach(o=>{e.length>0?e.includes(o.name.value)&&i.push(o.objectId):i.push(o.objectId)}),i.length>0&&(await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showContent:!0})).forEach(s=>{let a=Yn.buildLockPositionInfo(s);a&&r.push(a)}),r}async getLockPositionInfo(t,e){let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}});return Yn.buildLockPositionInfo(n)}calculateXCetusRewarder(t,e,n){let i=e.basic_percent,r="0";t.forEach(a=>{a.coin_address===e.booster_type&&(console.log("find ",e.booster_type),r=a.amount_owed.toString())}),n.is_settled||e.config.forEach(a=>{a.lock_day===n.lock_period&&(i=a.multiplier)});let o=S(r).sub(n.growth_rewarder).mul(i);return S(n.rewarder_owned).add(o).toString()}lockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new ws.TransactionBlock;return i.moveCall({target:`${e.published_at}::${vc}::lock_position`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[i.pure(D(e).booster_config_id),i.pure(D(n).global_config_id),i.pure(t.booster_pool_id),i.pure(t.clmm_pool_id),i.pure(t.clmm_position_id),i.pure(t.lock_day),i.pure(G)]}),i}canceLockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,n=new ws.TransactionBlock;return n.moveCall({target:`${e.published_at}::${vc}::cancel_lock`,typeArguments:[t.booster_type],arguments:[n.pure(D(e).booster_config_id),n.pure(t.booster_pool_id),n.pure(t.lock_nft_id),n.pure(G)]}),n}redeemPayload(t){let{booster:e,xcetus:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions,r=new ws.TransactionBlock,o=D(n);return r.moveCall({target:`${e.published_at}::${vc}::redeem`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[r.pure(D(e).booster_config_id),r.pure(D(i).global_config_id),r.pure(t.booster_pool_id),r.pure(t.lock_nft_id),r.pure(t.clmm_pool_id),r.pure(o.lock_manager_id),r.pure(o.xcetus_manager_id),r.pure(t.ve_nft_id),r.pure(G)]}),r}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Vt="router",mf=1e9;var An=class{static priceRealToFix(t,e,n){let i=S(e-n).toNumber();return Number(S(t).div(S(10).pow(S(i))).toString())}static priceFixToReal(t,e,n){let i=S(e-n).toNumber();return Number(S(t).mul(S(10).pow(S(i))).toString())}static raiseTotalAmount(t,e,n){let i=S(e-n).abs().toNumber();return e>n?Number(S(t.total_supply).mul(t.current_price).div(S(10).pow(S(i))).toString()):Number(S(t.total_supply).mul(t.current_price).mul(S(10).pow(S(i))).toString())}static buildLaunchPadPool(t){let e=Mt(t),n=q(e),i=Q(t),r={coin_type_sale:n.type_arguments[0],coin_type_raise:n.type_arguments[1],pool_address:(0,hf.normalizeSuiObjectId)(Lt(t)),is_settle:i.is_settle,current_price:S(i.initialize_price).div(S(mf)).toString(),price:i.initialize_price,min_price:"0",max_price:"0",sale_coin_amount:i.sale_coin,raise_coin_amount:i.raise_coin,total_purchase_amount:i.reality_raise_total,total_supply:i.sale_total,min_purchase:i.min_purchase,max_purchase:i.max_purchase,complete_raise_limit:i.least_raise_amount,softcap:i.softcap,max_raise_amount:i.hardcap,sale_decimals:0,raise_decimals:0,liquidity_injection_ratio:Number(i.liquidity_rate)/1e4,is_cancel:i.is_cancel,duration_summary:{start_time:Number(i.duration_manager.fields.start_time),end_time:0,settle_end_time:0,purchase_duration:Number(i.duration_manager.fields.activity_duration),settle_duration:Number(i.duration_manager.fields.settle_duration),lock_up_duration:Number(i.duration_manager.fields.locked_duration)},white_summary:{white_handle:i.white_list.fields.users.fields.id.id,protection_hard_cap:i.white_list.fields.hard_cap_total,protection_limit_used:i.white_list.fields.purchase_total,size:Number(i.white_list.fields.users.fields.size)},unused_sale:i.unused_sale,harvest_raise:i.harvest_raise,tick_spacing:Number(i.tick_spacing),owner:i.recipient,purchase_summary:{purchase_handle:i.purchase_list.fields.id.id,size:Number(i.purchase_list.fields.size)},pool_status:"Failed"};return An.updatePoolStatus(r),r}static updatePoolStatus(t){let e=Number(S(Date.now()/1e3).toFixed(0)),{duration_summary:n}=t,i=n.start_time+n.purchase_duration,r=i+n.settle_duration;if(n.end_time=i,n.settle_end_time=r,t.is_settle)t.pool_status="Ended";else if(t.is_cancel)t.pool_status="Canceled";else if(e<n.start_time)t.pool_status="Upcoming";else if(e>n.start_time&&e<i)t.pool_status="Live";else if(e>i&&e<r){let o=t.raise_coin_amount;Number(o)<Number(t.complete_raise_limit)?t.pool_status="Failed":t.pool_status="Settle"}return t}static async calculatePoolPrice(t,e){let n=await t.ClmmSDK.CetusConfig.getTokenListByCoinTypes([e.coin_type_sale,e.coin_type_raise]),i=n[e.coin_type_sale].decimals,r=n[e.coin_type_raise].decimals;e.min_price=this.priceFixToReal(Number(S(e.softcap).div(S(e.total_supply))),i,r).toString(),e.max_price=this.priceFixToReal(Number(S(e.max_raise_amount).div(S(e.total_supply))),i,r).toString(),e.current_price=this.priceFixToReal(Number(e.current_price),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r}static async getWithdrawRaise(t){return t.pool_status==="Ended"?t.harvest_raise:"0"}static async getWithdrawSale(t){return t.pool_status==="Ended"?t.unused_sale:t.sale_coin_amount}static async getHistoryWithdrawRaise(t,e){if(e.pool_status==="Ended"){if(S(e.harvest_raise).equals(S(0))){let i=await t.Launchpad.getSettleEvent(e.pool_address);i&&(e.harvest_raise=i.unused_raise)}let n=(0,Kr.min)(new Kr.default(e.total_purchase_amount),new Kr.default(e.max_raise_amount));return S(n.toString()).mul(1-e.liquidity_injection_ratio).toString()}return"0"}static async getHistoryWithdrawSale(t,e){if(e.pool_status==="Ended"){let n=await t.Launchpad.getSettleEvent(e.pool_address);return n&&(e.unused_sale=n.unused_sale),e.unused_sale}return"0"}static async getOverrecruitReverseAmount(t,e){let n=await t.Launchpad.getPurchaseMarks(t.ClmmSDK.senderAddress,[e.pool_address],!1);if(n.length>0){let i=n[0].purchased_raise_amount,r=(await t.Launchpad.getPurchaseAmount(e.white_summary.white_handle,t.ClmmSDK.senderAddress)).safe_purchased_amount,{protection_limit_used:o}=e.white_summary;return S(i).sub(r).div(S(e.total_purchase_amount).sub(o)).mul(S(e.total_purchase_amount).sub(e.max_raise_amount)).toString()}return"0"}static async getCanPurchaseAmount(t,e){let n=await An.getOverrecruitReverseAmount(t,e),i=await t.Launchpad.getPurchaseMarks(t.ClmmSDK.senderAddress,[e.pool_address],!1);if(i){let r=i[0].purchased_raise_amount;S(r).sub(n).div(e.current_price)}return"0"}},ty=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=[],e=0,n=100,i=!1){let{package_id:r}=this._sdk.sdkOptions.launchpad;if(r===void 0)throw Error("sdk.sdkOptions.launchpad is undefined");let o=`${r}_getPoolImmutables`,s=this.getCache(o,i),a=[],u=[];if(s!==void 0&&a.push(...s),a.length===0)try{((await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`}))?.data).forEach(w=>{let v=w.parsedJson;v&&a.push({pool_address:v.pool_id,coin_type_sale:q(v.sale_coin.name).full_address,coin_type_raise:q(v.raise_coin.name).full_address})}),this.updateCache(o,a,X)}catch(h){console.log("getPoolImmutables",h)}let l=t.length>0;for(let h=0;h<a.length;h+=1){let w=a[h];if(!(l&&!t.includes(w.pool_address))){if(!l){let v=h;if(v<e||v>=e+n)continue}u.push(w)}}return u}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.launchpad,i=`${n}_getPoolImmutables`,r=[],o={data:[],hasNextPage:!1},s=t==="all";if(s){let a=this.getCache(i,e);a&&r.push(...a)}if(r.length===0)try{let a=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n}::factory::CreatePoolEvent`},t);o.hasNextPage=a.hasNextPage,o.nextCursor=a.nextCursor,a.data.forEach(u=>{let l=u.parsedJson;l&&r.push({pool_address:l.pool_id,coin_type_sale:q(l.sale_coin.name).full_address,coin_type_raise:q(l.raise_coin.name).full_address})})}catch(a){console.log("getPoolImmutables",a)}return o.data=r,s&&this.updateCache(i,r,X),o}async getPools(t=[],e=0,n=100){let i=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutables([],e,n,!1)).forEach(a=>{r.push(a.pool_address)});let o=await this._sdk.ClmmSDK.fullClient.batchGetObjects(r,{showType:!0,showContent:!0});for(let s of o){let a=An.buildLaunchPadPool(s);await An.calculatePoolPrice(this._sdk,a),i.push(a);let u=`${a.pool_address}_getPoolObject`;this.updateCache(u,a,X)}return i}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0){let s=i;return An.updatePoolStatus(s),s}let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=An.buildLaunchPadPool(r);return await An.calculatePoolPrice(this._sdk,o),this.updateCache(n,o),o}async getInitConfig(t=!1){let e=this._sdk.sdkOptions.launchpad.package_id,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({Transaction:o}))?.data,a={pools_id:"",admin_cap_id:"",config_cap_id:""};return s.length>0&&(s.forEach(u=>{let l=u.parsedJson;if(l)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=l.admin_cap_id,a.config_cap_id=l.config_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;default:break}}),this.updateCache(n,a,X)),a}async getLockNFT(t,e=!1){let n=`${t}_getLockNFT`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(!r.error)return Nn(r)}async getLockNFTList(t){let{package_id:e}=this._sdk.ClmmSDK.sdkOptions.clmm_pool,{sdkOptions:n}=this._sdk,i=[];try{let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n.launchpad.package_id}::lock::LockNFTEvent`}))?.data;for(let o of r){let s=o.parsedJson;if(s){let a={locked_time:Number(s.locked_time),end_lock_time:Number(s.end_lock_time),nft_type:s.nft_type_name.name,lock_nft_id:s.lock_nft_id,recipient:s.recipient};if(t===a.recipient&&`${e}`===q(a.nft_type).address){let u=await this.getLockNFT(a.lock_nft_id);if(u){let l=q(u.coin_type_a).full_address,h=q(u.coin_type_b).full_address;i.push({...u,coin_type_a:l,coin_type_b:h,...a})}}}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPoolTransactionPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=D(e);if(this.assertLuanchpadConfig(),this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let i=An.priceRealToFix(Number(t.initialize_price),t.sale_decimals,t.raise_decimals),r=new Zt.TransactionBlock,o=S(t.total_supply).add(S(t.total_supply).mul(S(t.liquidity_rate))).toNumber(),s=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,r,BigInt(o),t.coin_type_sale),a=[r.pure(n.admin_cap_id),r.pure(n.config_cap_id),r.pure(n.pools_id),r.pure((0,dr.normalizeSuiAddress)(t.recipient)),r.pure((i*mf).toString()),s,r.pure(t.total_supply.toString()),r.pure(t.min_purchase.toString()),r.pure(t.max_purchase.toString()),r.pure(t.least_raise_amount.toString()),r.pure(t.hardcap.toString()),r.pure((t.liquidity_rate*1e3).toString()),r.pure(t.start_time.toString()),r.pure(t.activity_duration.toString()),r.pure(t.settle_duration.toString()),r.pure(t.locked_duration.toString()),r.pure(t.tick_spacing.toString()),r.pure(G)],u=[t.coin_type_sale,t.coin_type_raise];return r.moveCall({target:`${e.published_at}::${Vt}::create_launch_pool`,typeArguments:u,arguments:a}),r}async creatPurchasePayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=new Zt.TransactionBlock,i=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.purchase_amount),t.coin_type_raise),r=(await this.getPurchaseMarks(this._sdk.ClmmSDK.senderAddress,[t.pool_address],!1))[0],o=[t.coin_type_sale,t.coin_type_raise],s;return r?s=[n.pure(t.pool_address),n.pure(D(e).config_cap_id),n.pure(r.id),i,n.pure(t.purchase_amount.toString()),n.pure(G)]:s=[n.pure(t.pool_address),n.pure(D(e).config_cap_id),i,n.pure(t.purchase_amount.toString()),n.pure(G)],n.moveCall({target:`${e.published_at}::${Vt}::${r===void 0?"create_and_purchase":"purchase"}`,typeArguments:o,arguments:s}),n}async creatClaimPayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=(await this.getPurchaseMarks(this._sdk.ClmmSDK.senderAddress,[t.pool_address],!1))[0],i=new Zt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure(t.pool_address),i.pure(D(e).config_cap_id),i.pure(n?.id),i.pure(G)];return i.moveCall({target:`${e.published_at}::${Vt}::claim`,typeArguments:r,arguments:o}),i}async creatSettlePayload(t){let{launchpad:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");this.assertLuanchpadConfig();let i=D(n),{clmm_args:r}=t,o=new Zt.TransactionBlock;o.setSender(this.sdk.ClmmSDK.senderAddress);let s=[t.coin_type_sale,t.coin_type_raise];if(r){let a=r.opposite?ee.priceToSqrtPriceX64(S(1).div(r.current_price),r.raise_decimals,r.sale_decimals).toString():ee.priceToSqrtPriceX64(S(r.current_price),r.sale_decimals,r.raise_decimals).toString(),u=BigInt(a)<BigInt(r.clmm_sqrt_price),l=r.opposite?u?t.coin_type_raise:t.coin_type_sale:u?t.coin_type_sale:t.coin_type_raise,h=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,l),w=we.calculateTotalBalance(h);we.isSuiCoin(l)&&(w-=BigInt(2e8));let T=re.buildCoinForAmount(o,h,w,l).targetCoin,I=r.opposite?u?"settle_with_reverse_clmm_only_with_a":"settle_with_reverse_clmm_only_with_b":u?"settle_only_with_a":"settle_only_with_b",x=[o.pure(t.pool_address),o.pure(D(e).config_cap_id),o.pure(r.clmm_pool_address),o.pure(i.global_config_id),o.pure(a),T,o.pure(G)];o.moveCall({target:`${e.published_at}::${Vt}::${I}`,typeArguments:s,arguments:x})}else o.moveCall({target:`${e.published_at}::${Vt}::settle`,typeArguments:s,arguments:[o.pure(t.pool_address),o.pure(D(e).config_cap_id),o.pure(G)]});return o}creatWithdrawPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object(t.pool_address),n.object(D(e).config_cap_id),n.object(G)];return t.sale_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Vt}::withdraw_sale`,typeArguments:i,arguments:r}),t.raise_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Vt}::withdraw_raise`,typeArguments:i,arguments:r}),n}addUserToWhitelisPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.object(r),n.pure(t.safe_limit_amount),n.object(G)];n.moveCall({target:`${e.published_at}::${Vt}::add_user_to_whitelist`,typeArguments:i,arguments:o})}),n}updateWhitelistCapPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.safe_limit_amount>0&&n.moveCall({target:`${e.published_at}::${Vt}::update_whitelist_member_safe_limit_amount`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.pure(t.white_list_member),n.pure(t.safe_limit_amount),n.object(G)]}),t.hard_cap_total>0&&n.moveCall({target:`${e.published_at}::${Vt}::update_whitelist_hard_cap_total`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.pure(t.hard_cap_total),n.object(G)]}),n}creatRemoveWhitelistPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.object(r),n.object(G)];n.moveCall({target:`${e.published_at}::${Vt}::remove_user_from_whitelist`,typeArguments:i,arguments:o})}),n}creatCancelPoolPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::cancel`,typeArguments:i,arguments:r}),n}updateRecipientPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(t.new_recipient),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::update_recipient_address`,typeArguments:i,arguments:r}),n}updatePoolDuractionPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(t.activity_duration),n.pure(t.settle_duration),n.pure(t.lock_duration),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::update_pool_duration`,typeArguments:i,arguments:r}),n}creatUnlockNftPayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(D(e)===void 0)throw Error("getPackagerConfigs(launchpad) is null");let n=new Zt.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft),n.pure(G)];return n.moveCall({target:`${e.published_at}::lock::unlock_nft`,typeArguments:i,arguments:r}),n}async isAdminCap(t){let{launchpad:e}=this._sdk.sdkOptions;if(D(e)===void 0)throw Error("launchpad config is empty");let n=`${t}_isAdminCap`,i=this.getCache(n);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:D(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=pn(r),s=or(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,dr.normalizeSuiAddress)(s.AddressOwner)===(0,dr.normalizeSuiAddress)(t)),this.updateCache(n,a,X),a}async isWhiteListUser(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n});return!!(i&&i.data)}catch{return!1}}async getPurchaseAmount(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n}),r=Q(i);if(console.log(r),r)return r?.value?.fields}catch{}return{safe_limit_amount:"0",safe_purchased_amount:"0"}}async getPurchaseMarks(t,e=[],n=!0){let{launchpad:i}=this._sdk.sdkOptions,r=`${e}_getPurchaseMark`,o=this.getCache(r,n);if(!n&&o!==void 0)return o;let s=null,a=[];for(;;){let u=await this._sdk.ClmmSDK.fullClient.getOwnedObjects({owner:t,options:{showType:!0,showContent:!0,showDisplay:!0},cursor:s});for(let l of u.data){let{fields:h}=l.data.content;if(q(Mt(l)).source_address===`${i.package_id}::pool::PurchaseMark`){console.log("fields: ",h);let v={id:h.id.id,pool_id:q(h.pool_id).address,purchased_raise_amount:h.purchase_total,obtain_sale_amount:h.obtain_sale_amount,used_raise_amount:h.used_raise_amount};e.length>0?e.includes(v.pool_id)&&a.push(v):a.push(v)}}if(u.hasNextPage)s=u.nextCursor;else break}return this.updateCache(r,a,X),a}async getSettleEvent(t){let{launchpad:e}=this._sdk.sdkOptions,n=`${t}_getPurchaseMark`,i=this.getCache(n);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e.package_id}::pool::SettleEvent`});for(let o of r.data){let s=o.parsedJson;if(t===(0,dr.normalizeSuiObjectId)(s.pool_id)){let a={pool_id:s.pool_id,settle_price:s.settle_price,unused_sale:s.unused_sale,unused_raise:s.unused_raise,white_purchase_total:s.white_purchase_total};return this.updateCache(n,a,X),a}}}buildLaunchpadCoinType(t,e){return ir(this._sdk.sdkOptions.launchpad.package_id,"pool","PoolLiquidityCoin",[t,e])}assertLuanchpadConfig(){let{launchpad:t}=this.sdk.sdkOptions;if(D(t)===void 0)throw Error("sdk getPackagerConfigs(launchpad) is null")}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Qn=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:q(e.clmm_pool_id).address,bonus_type:q(e.bonus_type.fields.name).source_address,pool_id:q(e.pool_id).address,coinTypeA:q(e.coin_type_a.fields.name).source_address,coinTypeB:q(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=Q(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({rate:Number(S(r.fields.key).div(lr)),multiplier:Number(S(r.fields.value).div(lr))})}),{balance:e.balance,config:n,is_open:e.is_open,index:Number(e.index),start_time:Number(e.start_time),interval_day:Number(e.interval_day),minimum_percent_to_reward:Number(S(e.minimum_percent_to_reward).div(lr)),rewarders:{rewarder_handle:e.rewarders.fields.id.id,size:Number(e.rewarders.fields.size)},whale_nfts:{whale_nfts_handle:e.whale_nfts.fields.id.id,size:Number(e.whale_nfts.fields.size)},points:{point_handle:e.points.fields.id.id,size:Number(e.points.fields.size)}}}static buildMarkerPositions(t){let{contents:e}=t.value.fields.value.fields,n=[],i=t.id.id;return e.forEach(r=>{let{key:o,value:s}=r.fields,a={id:o,period_id:i,bonus_num:s.fields.bonus_num,point:s.fields.point,is_burn:s.fields.is_burn,point_after_multiplier:s.fields.point_after_multiplier,percent:Number(S(s.fields.percent).div(lr)),fee_share_rate:0,is_redeemed:s.fields.is_redeemed};n.push(a)}),n}static buildPoolBonusInfo(t){let{fields:e,type:n}=t.value.fields.value;return{type:n,time:Number(e.time),settle_time:Number(e.settle_time),settled_num:e.settled_num,is_settled:e.is_settled,basis_bonus:e.basis_bonus,total_bonus:e.total_bonus,is_vacant:e.is_vacant,redeemed_num:e.redeemed_num}}static getBonusPercent(t,e){let n=0;for(let i of t)e>=i.rate&&i.rate>n&&(n=i.multiplier);return n}},lf="router",ny=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=!1){let{maker_bonus:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n,t),r=[];if(i!==void 0)r.push(...i);else{let o=[];(await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(D(e).maker_pool_handle)).data?.forEach(u=>{o.push(u.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let u of a){let l=Q(u);l&&r.push(Qn.buildPoolImmutables(l))}}return r}async getPoolImmutable(t){let{maker_bonus:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n);if(i!==void 0){let s=i.filter(a=>t===a.pool_id);if(s.length>0)return s[0]}let r=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(e).maker_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=Q(r);return Qn.buildPoolImmutables(o)}async getPools(){let t=[],e=await this.getPoolImmutables(),n=e.map(o=>o.pool_id),i=await this._sdk.ClmmSDK.fullClient.batchGetObjects(n,{showType:!0,showContent:!0}),r=0;for(let o of i){let s=Qn.buildPoolState(o);if(s){let a={...e[r],...s};t.push(a);let u=`${a.pool_id}_getPoolObject`;this.updateCache(u,a,X)}r+=1}return t}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e),r=await this.getPoolImmutable(t);if(i!==void 0)return i;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),s=Qn.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,X),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=Q(e);return n?n.list.fields.id.id:""}async getMakerPoolPeriods(t,e=!1){let n=[],i=`${t.pool_id}_getMakerPoolPeriods`,r=this.getCache(i,e);return r!==void 0?r:((await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(t.whale_nfts.whale_nfts_handle)).data.forEach(s=>{let a={id:s.objectId,start_time:0,end_time:0,period:Number(s.name.value)};a.start_time=Number(S(t.start_time).add(S(t.interval_day).mul(24*3600).mul(a.period)).toFixed(0,N.ROUND_DOWN)),a.end_time=Number(S(a.start_time).add(S(t.interval_day).mul(24*3600)).toFixed(0,N.ROUND_DOWN)),n.push(a)}),this.updateCache(i,n,X),n)}async getMakerBonusInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.maker_bonus,e=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitEvent`}))?.data,n={maker_config_id:"",maker_pool_handle:""};return e.length>0&&e.forEach(i=>{let r=i.parsedJson;r&&(n.maker_config_id=r.config_id)}),n.maker_pool_handle=await this.getPoolHandleId(n.maker_config_id),n}async getPoolMarkerPositionList(t,e,n=!1){let i={},r=[];n||e.forEach(o=>{let s=`${t}_${o.period}_getPoolMarkerPositionList`,a=this.getCache(s);a!==void 0?i[o.period]=a:(i[o.period]=[],r.push(o))});try{r.length>0&&(await this._sdk.ClmmSDK.fullClient.batchGetObjects(r.map(a=>a.id),{showContent:!0})).forEach(a=>{let u=Q(a),l=Qn.buildMarkerPositions(u);if(l.length>0){let{period_id:h}=l[0],w=e.filter(v=>v.id===h)[0];i[w.period]=l}});let o=[];for(let s in i)i[s].forEach(u=>{o.push(u)});if(o.length>0){let s=await this._sdk.ClmmSDK.Position.getSipmlePositionList(o.map(a=>a.id));for(let a of o)for(let u of s)if(a.id===u.pos_object_id){a.clmm_position=u;break}}}catch(o){console.log(o)}for(let o in i){let s=`${t}_${o}_getPoolMarkerPositionList`;this.updateCache(s,i[o],X)}return i}async updateXCetusRewarderAndFee(t,e,n){let i=await this.calculateTotalPointsAfterMultiper(t,n);for(let r of e)await this.calculateXCetusRewarder(t,r,n.period,i);return e}async calculateXCetusRewarder(t,e,n,i){let r=await this.getPoolBonusInfo(t.rewarders.rewarder_handle,n),{fee_share_rate:o}=this.calculateFeeShareRate(t,e,i),s=S(o).mul(r.total_bonus);return e.is_redeemed?e.bonus_num="0":e.bonus_num=s.toString(),e.bonus_num}calculateFeeShareRate(t,e,n){let i=Qn.getBonusPercent(t.config,e.percent),r=S(e.point).mul(i),o=S(r).div(n);return e.point_after_multiplier=r.toString(),e.fee_share_rate=Number(o),{fee_share_rate:Number(o),points_after_multiper:r.toString()}}async calculateTotalPointsAfterMultiper(t,e){let n=await this.getPoolMarkerPositionList(t.whale_nfts.whale_nfts_handle,[e]),i=S(0),r=n[e.period];for(let o of r){let s=Qn.getBonusPercent(t.config,o.percent),a=S(o.point).mul(s);i=i.add(a)}return i.toString()}async calculateAllXCetusRewarder(t){let e=this._sdk.ClmmSDK.senderAddress,n=S(0),i=[];for(let r of t){let o=await this._sdk.MakerModule.getMakerPoolPeriods(r),s=await this._sdk.MakerModule.getPoolMarkerPositionList(r.whale_nfts.whale_nfts_handle,o),a=[];for(let u of o){let l=s[u.period].filter(h=>e.length===0?!1:h.clmm_position?.owner===e);l.length>0&&(await this._sdk.MakerModule.updateXCetusRewarderAndFee(r,l,u),l.forEach(h=>{h.clmm_position?.position_status===wc.Exists&&S(h.bonus_num).greaterThan(0)&&(n=n.add(h.bonus_num),a.includes(h.clmm_position.pos_object_id)||a.push(h.clmm_position.pos_object_id))}))}i.push({bonus_type:r.bonus_type,pool_id:r.pool_id,nft_ids:a})}return{claimtotal:n,claimRecord:i}}async getPoolBonusInfo(t,e,n=!1){let i=`${t}_${e}_getPoolBonusInfo`,r=this.getCache(i,n);if(r!==void 0)return r;let o=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:e.toString()}}),s=Q(o),a=Qn.buildPoolBonusInfo(s);return this.updateCache(i,a,Ue),a}claimPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Cc.TransactionBlock;return i.moveCall({target:`${e.published_at}::${lf}::claim`,typeArguments:[t.bonus_type],arguments:[i.pure(D(e).maker_config_id),i.pure(t.market_pool_id),i.pure(t.position_nft_id),i.pure(t.phase),i.pure(D(n).lock_manager_id),i.pure(D(n).xcetus_manager_id),i.pure(t.ve_nft_id)]}),i}claimAllPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Cc.TransactionBlock;return t.whale_nfts.forEach(r=>{r.nft_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::${lf}::claim_all`,typeArguments:[r.bonus_type],arguments:[i.object(D(e).maker_config_id),i.object(r.pool_id),i.object(o),i.object(D(n).lock_manager_id),i.object(D(n).xcetus_manager_id),i.object(t.ve_nft_id)]})})}),i}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},ar="router",kc="router",Ur=24*3600,vs=1e3,sn=1e11,Ii=class{static buildVeNFTDividendInfo(t){let e={id:t.id.id,ve_nft_id:t.name,rewards:[]};return t.value.fields.value.fields.dividends.fields.contents.forEach(n=>{let i=[];n.fields.value.fields.contents.forEach(r=>{i.push({coin_type:q(r.fields.key.fields.name).source_address,amount:r.fields.value})}),e.rewards.push({period:Number(n.fields.key),rewards:i})}),e}static buildDividendManager(t){let e={id:t.id.id,dividends:{id:t.dividends.fields.id.id,size:t.dividends.fields.size},venft_dividends:{id:t.venft_dividends.fields.id.id,size:t.venft_dividends.fields.size},bonus_types:[],start_time:Number(t.start_time),interval_day:Number(t.interval_day),balances:{id:t.balances.fields.id.id,size:t.balances.fields.size},is_open:t.is_open};return t.bonus_types.forEach(n=>{e.bonus_types.push(q(n.fields.name).source_address)}),e}static buildLockUpManager(t){return{id:t.id.id,balance:t.balance,treasury_manager:t.treasury_manager,extra_treasury:t.extra_treasury,lock_infos:{lock_handle_id:t.lock_infos.fields.id.id,size:Number(t.lock_infos.fields.size)},type_name:Et(t.type_name.fields.name),min_lock_day:Number(t.min_lock_day),max_lock_day:Number(t.max_lock_day),package_version:Number(t.package_version),max_percent_numerator:Number(t.max_percent_numerator),min_percent_numerator:Number(t.min_percent_numerator)}}static buildLockCetus(t){let e=t.fields,n={id:e.id.id,type:q(t.type).source_address,locked_start_time:Number(e.locked_start_time),locked_until_time:Number(e.locked_until_time),cetus_amount:e.balance,xcetus_amount:"0",lock_day:0};return n.lock_day=(n.locked_until_time-n.locked_start_time)/Ur,n}static getAvailableXCetus(t,e){let n=S(0);return e.forEach(i=>{n=n.add(i.xcetus_amount)}),S(t.xcetus_balance).sub(n).toString()}static getWaitUnLockCetuss(t){return t.filter(e=>!Ii.isLocked(e))}static getLockingCetuss(t){return t.filter(e=>Ii.isLocked(e))}static isLocked(t){return t.locked_until_time>Date.parse(new Date().toString())/1e3}static buildDividendRewardTypeList(t){let e=new Set;return t.forEach(n=>{n.rewards.forEach(i=>{e.add(i.coin_type)})}),Array.from(e)}static getNextStartTime(t){let e=Date.now()/1e3,{start_time:n,interval_day:i}=t,r=Math.ceil((e-n)/(i*Ur));return n+r*i*Ur}},iy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getOwnerVeNFT(t,e=!0){let{xcetus:n}=this.sdk.sdkOptions,i=`${t}_getLockUpManagerEvent`,r=this.getCache(i,e);if(r!==void 0)return r;let o,s=`${n.package_id}::xcetus::VeNFT`;return(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0},filter:{StructType:s}})).data.forEach(u=>{let l=q(Mt(u)).source_address;if(l===s&&u.data&&u.data.content){let{fields:h}=u.data.content;o={...Si(u),id:h.id.id,index:h.index,type:l,xcetus_balance:h.xcetus_balance},this.updateCache(i,o,X)}}),o}async getOwnerLockCetuss(t){let{xcetus:e}=this.sdk.sdkOptions,n=[],i=`${e.package_id}::lock_coin::LockedCoin<${this.buileCetusCoinType()}>`,r=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0},filter:{StructType:i}});for(let o of r.data)if(q(Mt(o)).source_address===i&&o.data){let a=Ii.buildLockCetus(o.data.content);a.xcetus_amount=await this.getXCetusAmount(a.id),n.push(a)}return n}async getLockCetus(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(e.data?.content){let n=Ii.buildLockCetus(e.data.content);return n.xcetus_amount=await this.getXCetusAmount(n.id),n}}async getOwnerCetusCoins(t){return await this._sdk.ClmmSDK.getOwnerCoinAssets(t,this.buileCetusCoinType())}mintVeNFTPayload(){let{xcetus:t}=this.sdk.sdkOptions,e=new Fn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${ar}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xcetus_manager_id)]}),e}async convertPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock,i=this.buileCetusCoinType(),r=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${ar}::mint_and_convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xcetus_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${ar}::convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xcetus_manager_id),r,n.pure(t.amount),n.pure(t.venft_id)]}),n}redeemLockPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ar}::redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(G)]}),n}redeemPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ar}::redeem`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}redeemDividendPayload(t,e){let{xcetus:n,xcetus_dividends:i}=this.sdk.sdkOptions,r=new Fn.TransactionBlock;return e.forEach(o=>{r.moveCall({target:`${n.published_at}::${kc}::redeem`,typeArguments:[o],arguments:[r.object(D(i).dividend_manager_id),r.object(t)]})}),r}redeemDividendV2Payload(t,e,n){let{xcetus_dividends:i}=this.sdk.sdkOptions,r=new Fn.TransactionBlock;return e.filter(s=>n.includes(s)).length>0&&(r=this.redeemDividendXTokenPayload(t,r)),e.forEach(s=>{n.includes(s)||r.moveCall({target:`${i.published_at}::${kc}::redeem_v2`,typeArguments:[s],arguments:[r.object(D(i).dividend_manager_id),r.object(t),r.object(G)]})}),r}redeemDividendXTokenPayload(t,e){let{xcetus_dividends:n,xcetus:i}=this.sdk.sdkOptions,{xcetus_manager_id:r,lock_manager_id:o}=D(i),{dividend_manager_id:s}=D(n);return e=e===void 0?new Fn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${kc}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(G)]}),e}buileCetusCoinType(){return`${this.sdk.sdkOptions.cetus_faucet.package_id}::cetus::CETUS`}buileXTokenCoinType(t=this._sdk.sdkOptions.xcetus.package_id,e="xcetus",n="XCETUS"){return`${t}::${e}::${n}`}cancelRedeemPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ar}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}async getInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.xcetus,e=`${t}_getInitFactoryEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::xcetus::InitEvent`}))?.data,r={xcetus_manager_id:"",lock_manager_id:"",lock_handle_id:""};i.length>0&&i.forEach(s=>{let a=s.parsedJson;a&&(r.xcetus_manager_id=a.xcetus_manager)});let o=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::locking::InitializeEvent`}))?.data;return o.length>0&&o.forEach(s=>{let a=s.parsedJson;a&&(r.lock_manager_id=a.lock_manager)}),r.lock_manager_id.length>0&&(r.lock_handle_id=(await this.getLockUpManager(r.lock_manager_id)).lock_infos.lock_handle_id),this.updateCache(e,r,X),r}async getLockUpManager(t=D(this.sdk.sdkOptions.xcetus).lock_manager_id,e=!1){let n=`${t}_getLockUpManager`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Ii.buildLockUpManager(Q(r));return this.updateCache(n,o,X),o}async getDividendConfigs(){let{package_id:t}=this.sdk.sdkOptions.xcetus_dividends,e=`${t}_getDividendManagerEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::dividend::InitEvent`}))?.data,r={dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""};return i.length>0&&i.forEach(o=>{let s=o.parsedJson;s&&(r.dividend_manager_id=s.manager_id,r.dividend_admin_id=s.admin_id,r.dividend_settle_id=s.settle_id,this.updateCache(e,r,X))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=D(this._sdk.sdkOptions.xcetus_dividends),n=`${e}_getDividendManager`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s=Ii.buildDividendManager(o);return this.updateCache(n,s,X),s}async getXcetusManager(t=!0){let{xcetus_manager_id:e}=D(this._sdk.sdkOptions.xcetus),n=`${e}_getXcetusManager`,i=this.getCache(n,t);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s={id:o.id.id,index:Number(o.index),has_venft:{handle:o.has_venft.fields.id.id,size:o.has_venft.fields.size},nfts:{handle:o.nfts.fields.id.id,size:o.nfts.fields.size},total_locked:o.total_locked,treasury:o.treasury.fields.total_supply.fields.value};return this.updateCache(n,s),s}async getVeNFTDividendInfo(t,e){try{let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);return Ii.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(D(this._sdk.sdkOptions.xcetus).lock_manager_id),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(vs)).div(sn);return{amountOut:S(r).mul(S(t)).round().toString(),percent:r.toString()}}async reverseRedeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(D(this._sdk.sdkOptions.xcetus).lock_manager_id),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(vs)).div(sn);return{amountOut:S(t).div(r).toFixed(0,N.ROUND_UP),percent:r.toString()}}async getXCetusAmount(t){let{lock_handle_id:e}=D(this._sdk.sdkOptions.xcetus),n=`${t}_getXCetusAmount`,i=this.getCache(n);if(i!==void 0)return i;try{let r=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:e,name:{type:"0x2::object::ID",value:t}}),o=Q(r);if(o){let{xcetus_amount:s}=o.value.fields.value.fields;return this.updateCache(n,s,X),s}}catch{}return"0"}async getVeNftAmount(t,e){try{let n=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);if(i){let{lock_amount:r,xcetus_amount:o}=i.value.fields.value.fields;return{lock_amount:r,xcetus_amount:o}}}catch{}return{lock_amount:"0",xcetus_amount:"0"}}async getPhaseDividendInfo(t,e=!1){let i=(await this.getDividendManager()).dividends.id,r=`${i}_${t}_getPhaseDividendInfo`,o=this._sdk.getCache(r,e);if(o)return o;try{let s=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:i,name:{type:"u64",value:t}}),a=Q(s),u=a.value.fields.value.fields,l=u.redeemed_num.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),h=u.bonus_types.map(T=>T.fields.name),w=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:Lt(s),phase:a.name,settled_num:u.settled_num,register_time:u.register_time,redeemed_num:l,is_settled:u.is_settled,bonus_types:h,bonus:w,phase_end_time:""};return this.updateCache(r,v),v}catch{}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},ry="factory",on="oversubscribe_pool",pf=1e6,ur=1e18;var cr="router",Tc="router",gs="router";var df={curve:{strategy:3,both_side:{div_width:10,ratios:[.333333,.266666,.2,.133333,.066666]},one_side:{div_width:5,ratios:[.333333,.266666,.2,.133333,.066666]}},bidAsk:{strategy:4,both_side:{div_width:10,ratios:[.172413793,.137931034,.103448276,.068965517,.034482759,.068965517,.103448276,.137931034,.172413793]},one_side:{div_width:5,ratios:[.066666667,.13333333,.2,.266666667,.333333333]}}};function oy(t){return"master_address"in t}var sy="router",ay="vaults",cy=1e4;var $t=class{static buildIdoPoolImmutables(t){return{pool_address:(0,Sc.normalizeSuiObjectId)(t.pool_id),coin_type_sale:q(t.sale_coin_type.name).full_address,coin_type_raise:q(t.raise_coin_type.name).full_address,tick_spacing:Number(t.tick_spacing),total_supply:t.total_supply,min_purchase:t.min_purchase_amount,max_purchase:t.max_purchase_amount}}static buildIdoPool(t){let e=Mt(t),n=q(e),i=Q(t);console.log("fields:",i);let r={pool_address:(0,Sc.normalizeSuiObjectId)(i.id.id),coin_type_sale:n.type_arguments[0],coin_type_raise:n.type_arguments[1],tick_spacing:Number(i.tick_spacing),total_supply:i.total_supply,min_purchase:i.min_purchase_amount,max_purchase:i.max_purchase_amount},o={start_time:Number(i.duration_manager.fields.start_time),lock_up_duration:Number(i.duration_manager.fields.lock_up_duration),purchase_duration:Number(i.duration_manager.fields.purchase_duration),end_time:0};o.end_time=o.start_time+o.purchase_duration;let s={complete_raise_limit:i.complete_raise_limit,liquidity_injection_ratio:S(i.liquidity_injection_ratio).div(pf).toNumber(),current_sqrt_price_min:i.current_sqrt_price_min,current_sqrt_price_max:i.current_sqrt_price_max,owner:i.owner,sale_coin_amount:i.sale_coin,raise_coin_amount:i.raise_coin,price:i.price,current_price:i.price,duration_summary:o,is_cancelled:i.is_cancelled,is_liquidity_injected:i.is_liquidity_injected,liquidity_used_raise_amount:i.liquidity_used_raise_amount,liquidity_used_sale_amount:i.liquidity_used_sale_amount,purchase_summary:{size:Number(i.purchase_manager.fields.purchases.fields.size),purchase_handle:i.purchase_manager.fields.purchases.fields.id.id},total_purchase_amount:i.total_purchase_amount,white_summary:{white_list_id:i.white_list.fields.id.id,protection_limit_used:i.white_list.fields.protection_limit_used,protection_hard_cap:i.white_list.fields.protection_hard_cap,white_handle:i.white_list.fields.addresses.fields.id.id,size:Number(i.white_list.fields.addresses.fields.size)},pool_status:"Upcoming",max_raise_amount:"",sale_decimals:0,raise_decimals:0,is_withdrawn:i.is_withdrawn};return $t.updatePoolStatus(s),{...r,...s}}static is_init_period(t){return Number(S(Date.now()/1e3).toFixed(0))<t.start_time}static is_purchase_period(t){let e=Number(S(Date.now()/1e3).toFixed(0));return e>=t.start_time&&e<=t.start_time+t.purchase_duration}static is_claim_period(t){let e=Number(S(Date.now()/1e3).toFixed(0)),n=t.start_time+t.purchase_duration;return e>n}static is_can_inject_liquidity(t){return!t.is_cancelled&&t.liquidity_injection_ratio!==0&&$t.is_claim_period(t.duration_summary)&&!t.is_liquidity_injected}static is_can_withdraw(t){return t.is_withdrawn?!1:$t.is_sale_failed(t)?!0:(t.liquidity_injection_ratio===0||t.is_liquidity_injected)&&$t.is_claim_period(t.duration_summary)}static is_sale_failed(t){return!!(t.is_cancelled||$t.is_claim_period(t.duration_summary)&&S(t.total_purchase_amount).lessThan(t.complete_raise_limit))}static buildPurchaseInfo(t){return{...t.value.fields.value.fields,owner:t.name}}static calculateRedeemAmount(t,e){let n,i;if($t.is_sale_failed(t))n="0",i="0";else if(e.is_redeemed)n=e.obtained_sale_amount,i=e.used_raise_amount;else if(S(t.total_purchase_amount).lessThanOrEqualTo(t.max_raise_amount))n=S(e.purchased_raise_amount).mul(ur).div(t.price).toString(),i=e.purchased_raise_amount;else{let o=$t.redeemForSaleOversubcribeV2(t,e);n=o.user_obtained_sale_amount,i=o.user_used_raise_amount_ceil}n=N.floor(n);let r=N.floor(S(e.purchased_raise_amount).sub(i).toString());return{obtained_sale_amount:n,refunded_raise_amount:r}}static calculateWithdrawAmount(t){let e,n,i=S(t.total_supply).mul(t.liquidity_injection_ratio);if($t.is_sale_failed(t))e="0",n=S(i).add(t.total_supply);else{let{max_raise_amount:r}=t;S(t.total_purchase_amount).greaterThanOrEqualTo(r)?(e=S(r).sub(t.liquidity_used_raise_amount).toString(),n="0"):(e=S(t.total_purchase_amount).sub(t.liquidity_used_raise_amount),n=S(t.total_supply).add(i).sub(t.liquidity_used_sale_amount).sub($t.get_sold_amount(t)))}return{obtained_raise_amount:N.floor(e).toString(),refunded_sale_amount:N.ceil(n).toString()}}static get_sold_amount(t){return S(t.total_purchase_amount).greaterThanOrEqualTo(t.max_raise_amount)?t.total_supply:S(t.total_purchase_amount).mul(ur).div(t.price)}static redeemForSaleOversubcribe(t,e){let n=e.protection_raise_amount,i=S(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=S(r).sub(o),a=S(t.total_purchase_amount).sub(o),u=N.ceil(i.mul(s).div(a).add(n)),l=N.floor(i.mul(s).div(a).add(n));return{user_obtained_sale_amount:N.floor(S(t.total_supply).mul(l).div(r)),user_used_raise_amount_ceil:u}}static redeemForSaleOversubcribeV2(t,e){let n=e.protection_raise_amount,i=S(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=S(r).sub(o),a=S(t.total_purchase_amount).sub(o),u=S(n).mul(a).add(S(i).mul(s)).mul(ur).div(S(a).mul(t.price)),l=N.ceil(u.mul(t.price).div(ur));return{user_obtained_sale_amount:u,user_used_raise_amount_ceil:l}}static raiseTotalAmount(t){let e=S(t.sale_decimals-t.raise_decimals).abs().toNumber();return t.sale_decimals>t.raise_decimals?S(t.total_supply).mul(t.current_price).div(S(10).pow(S(e))).toString():S(t.total_supply).mul(t.current_price).mul(S(10).pow(S(e))).toString()}static updatePoolStatus(t){let e=Number(S(Date.now()/1e3).toFixed(0)),n=t.duration_summary,i=n.start_time+n.purchase_duration;t.is_cancelled?t.pool_status="Canceled":e<n.start_time?t.pool_status="Upcoming":e>n.start_time&&e<i?t.pool_status="Live":S(t.total_purchase_amount).lessThan(t.complete_raise_limit)?t.pool_status="Failed":t.pool_status="Ended"}static async calculatePoolUiPrice(t,e){let n=await t.ClmmSDK.CetusConfig.getTokenListByCoinTypes([e.coin_type_sale,e.coin_type_raise]),i=n[e.coin_type_sale].decimals,r=n[e.coin_type_raise].decimals;e.current_price=An.priceFixToReal(Number(S(e.price).div(S(ur)).toString()),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r,e.max_raise_amount=this.raiseTotalAmount(e)}};var Oi=class{static buildVeNFTDividendInfo(t){let e={id:t.id.id,ve_nft_id:t.name,rewards:[]};return t.value.fields.value.fields.dividends.fields.contents.forEach(n=>{let i=[];n.fields.value.fields.contents.forEach(r=>{i.push({coin_type:q(r.fields.key.fields.name).source_address,amount:r.fields.value})}),e.rewards.push({period:Number(n.fields.key),rewards:i})}),e}static buildDividendManager(t){let e={id:t.id.id,dividends:{id:t.dividends.fields.id.id,size:t.dividends.fields.size},venft_dividends:{id:t.venft_dividends.fields.id.id,size:t.venft_dividends.fields.size},bonus_types:[],start_time:Number(t.start_time),interval_day:Number(t.interval_day),balances:{id:t.balances.fields.id.id,size:t.balances.fields.size},is_open:t.is_open};return t.bonus_types.forEach(n=>{e.bonus_types.push(q(n.fields.name).source_address)}),e}static buildLockUpManager(t){return{id:t.id.id,balance:t.balance,treasury_manager:t.treasury_manager,extra_treasury:t.extra_treasury,lock_infos:{lock_handle_id:t.lock_infos.fields.id.id,size:Number(t.lock_infos.fields.size)},type_name:Et(t.type_name.fields.name),min_lock_day:Number(t.min_lock_day),max_lock_day:Number(t.max_lock_day),package_version:Number(t.package_version),max_percent_numerator:Number(t.max_percent_numerator),min_percent_numerator:Number(t.min_percent_numerator)}}static buildLockToken(t){let e=t.fields,n={id:e.id.id,type:q(t.type).source_address,locked_start_time:Number(e.locked_start_time),locked_until_time:Number(e.locked_until_time),token_amount:e.balance,xtoken_amount:"0",lock_day:0};return n.lock_day=(n.locked_until_time-n.locked_start_time)/Ur,n}static getAvailableXToken(t,e){let n=S(0);return e.forEach(i=>{n=n.add(i.xtoken_amount)}),S(t.xtoken_balance).sub(n).toString()}static getWaitUnLockTokens(t){return t.filter(e=>!Oi.isLocked(e))}static getLockingTokens(t){return t.filter(e=>Oi.isLocked(e))}static buildDividendRewardTypeList(t){let e=new Set;return t.forEach(n=>{n.rewards.forEach(i=>{e.add(i.coin_type)})}),Array.from(e)}static isLocked(t){return t.locked_until_time>Date.parse(new Date().toString())/1e3}static getNextStartTime(t,e=Ur){let n=Date.now()/1e3,{start_time:i,interval_day:r}=t,o=Math.ceil((n-i)/(r*e));return i+o*r*e}},qn=class{static getDefaultStrategyConfig(t){let e;switch(t){case 4:e=df.bidAsk;break;default:e=df.curve;break}return e}static geTickIndexRange(t,e,n,i){let r,o;switch(t=ee.getInitializableTickIndex(t,e),i){case"left":t>0?(o=S(t).sub(e).toNumber(),r=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber()):(o=S(t).sub(e).toNumber(),r=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber());break;case"right":t>0?(o=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber(),r=S(t).add(e).toNumber()):(o=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber(),r=S(t).add(e).toNumber());break;default:t>0?(r=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber(),o=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber()):(r=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber(),o=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber());break}if(r=ee.getInitializableTickIndex(r,e),o=ee.getInitializableTickIndex(o,e),r<Wd)throw Error("Tick lower value is below the minimum allowed value.");if(o>Gd)throw Error("Tick upper value is above the maximum allowed value.");return{tick_lower:r,tick_upper:o}}static getCreateLiquidityBins(t,e){let n=[];switch(e){case 4:n=qn.getCreateBidAskLiquidityBins(t);break;default:n=qn.getCreateCurveLiquidityBins(t);break}return n}static getCreateBidAskLiquidityBins(t){let e=S(Math.floor(S(t.tick_upper).sub(t.tick_lower).div(t.div_width).toNumber())).abs(),n=[],i=t.ratios,r,o;for(let s=0;s<i.length;s++){let a,u;t.tick_upper<=t.curr_tick?(u=S(t.tick_upper).sub(e.mul(s)).toNumber(),a=S(u).sub(e).toNumber()):t.tick_lower>=t.curr_tick?(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(t.tick_lower).add(e.mul(s+1)).toNumber()):s===4?(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(a).add(e.mul(2)).toNumber()):s>4?(a=S(t.tick_lower).add(e.mul(s+1)).toNumber(),u=S(a).add(e).toNumber()):(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(a).add(e).toNumber()),r=ee.getInitializableTickIndex(a,t.tick_spacing),o=ee.getInitializableTickIndex(u,t.tick_spacing),n.push({tick_lower:r,tick_upper:o,ratio:i[s],liquidity:"0"})}return n}static getCreateCurveLiquidityBins(t){let e=S(Math.floor(S(t.tick_upper).sub(t.tick_lower).div(t.div_width).toNumber())).abs(),n=[],i=t.ratios;for(let r=0;r<i.length;r++){let o,s;t.tick_upper<=t.curr_tick?(s=t.tick_upper,o=S(t.tick_upper).sub(e.mul(r+1)).toNumber()):t.tick_lower>=t.curr_tick?(o=t.tick_lower,s=S(o).add(e.mul(r+1)).toNumber()):(o=S(t.curr_tick).sub(e.mul(r+1)).toNumber(),s=S(t.curr_tick).add(e.mul(r+1)).toNumber()),n.push({tick_lower:ee.getInitializableTickIndex(o,t.tick_spacing),tick_upper:ee.getInitializableTickIndex(s,t.tick_spacing),ratio:i[r],liquidity:"0"})}return n}static calculateAddLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick)),n=qn.calculateCoinRatios(t.curr_tick,t.liquidity_bins),i=t.liquidity_bins.map((r,o)=>{let s=n[o],a=S(t.coin_amount).mul(t.fix_amount_a?s.coinRatioA:s.coinRatioB).toFixed(0).toString();try{return{...$e.estLiquidityAndcoinAmountFromOneAmounts(r.tick_lower,r.tick_upper,new qe.default(a),t.fix_amount_a,!0,t.slippage,e),...r}}catch{return{coinAmountA:new qe.default(0),coinAmountB:new qe.default(0),tokenMaxA:new qe.default(0),tokenMaxB:new qe.default(0),liquidityAmount:new qe.default(0),fix_amount_a:!t.fix_amount_a,...r}}});return qn.fixLiquidityInputs(e,t.slippage,i,!0)}static fixLiquidityInputs(t,e,n,i){let r=n.filter(s=>s.liquidityAmount.gt(ie));if(r.length===0)return[];let o=r[0];return n.map(s=>{if(s.liquidityAmount.eq(ie)){let a=S(o.liquidityAmount.toString()).mul(s.ratio).div(o.ratio).toFixed(0),u=ee.tickIndexToSqrtPriceX64(s.tick_lower),l=ee.tickIndexToSqrtPriceX64(s.tick_upper),h=$e.getCoinAmountFromLiquidity(new qe.default(a.toString()),t,u,l,!1);return{coinAmountA:h.coinA,coinAmountB:h.coinB,liquidityAmount:new qe.default(a.toString()),fix_amount_a:s.fix_amount_a,...ps(h,rr.fromDecimal(S(e).mul(100)),i)}}return s})}static calculateCoinRatios(t,e){let n=new qe.default(ee.tickIndexToSqrtPriceX64(t)),i=[],r=S(0),o=S(0),s=e.map(l=>{let h=S(tf(100,6).toString()).mul(l.ratio).toFixed(0).toString(),w=ee.tickIndexToSqrtPriceX64(l.tick_lower),v=ee.tickIndexToSqrtPriceX64(l.tick_upper),T=$e.getCoinAmountFromLiquidity(new qe.default(h),n,w,v,!0);return r=r.add(T.coinA.toString()),o=o.add(T.coinB.toString()),{...T,liquidity:h}}),a=[],u=[];return s.forEach((l,h)=>{let w={coinRatioA:r.eq(S(0))?0:S(l.coinA.toString()).div(r).toNumber(),coinRatioB:o.eq(S(0))?0:S(l.coinB.toString()).div(o).toNumber(),liquiditys:l.liquidity,tick_lower:e[h].tick_lower,tick_upper:e[h].tick_upper};i.push(w),a.push(r.eq(S(0))?0:S(l.coinA.toString()).div(r).toNumber()),u.push(o.eq(S(0))?0:S(l.coinB.toString()).div(o).toNumber())}),i}static calculateCloseMasterLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick));return t.positions.map(i=>{let r=new qe.default(i.liquidity),o=ee.tickIndexToSqrtPriceX64(i.tick_lower_index),s=ee.tickIndexToSqrtPriceX64(i.tick_upper_index),a=$e.getCoinAmountFromLiquidity(r,e,o,s,!1),u=rr.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:l,tokenMaxB:h}=ps(a,u,!1);return{coinAmountA:a.coinA,coinAmountB:a.coinB,tokenMaxA:l,tokenMaxB:h,liquidityAmount:r,fix_amount_a:!1}})}static calculateRemoveMasterLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick)),{fix_token:n}=t;if(n){let r=t.positions.map((a,u)=>({tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,ratio:t.ratios[u]})),o=qn.calculateCoinRatios(t.curr_tick,r),s=t.positions.map((a,u)=>{let l=o[u],h=S(n.coin_amount).mul(n.fix_amount_a?l.coinRatioA:l.coinRatioB).toFixed(0).toString();try{let w=$e.estLiquidityAndcoinAmountFromOneAmounts(a.tick_lower_index,a.tick_upper_index,new qe.default(h),n.fix_amount_a,!1,t.slippage,e);return{...w,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:w.liquidityAmount.toString(),ratio:t.ratios[u]}}catch{return{coinAmountA:new qe.default(0),coinAmountB:new qe.default(0),tokenMaxA:new qe.default(0),tokenMaxB:new qe.default(0),liquidityAmount:new qe.default(0),fix_amount_a:!n.fix_amount_a,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:"0",ratio:t.ratios[u]}}});return qn.fixLiquidityInputs(e,t.slippage,s,!1)}return t.positions.map((r,o)=>{let s=t.ratios[o],a=S(t.liquidity).mul(s).toFixed(0);S(a).greaterThan(r.liquidity)&&(a=r.liquidity);let u=ee.tickIndexToSqrtPriceX64(r.tick_lower_index),l=ee.tickIndexToSqrtPriceX64(r.tick_upper_index),h=$e.getCoinAmountFromLiquidity(new qe.default(a),e,u,l,!1),w=rr.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:v,tokenMaxB:T}=ps(h,w,!1);return{coinAmountA:h.coinA,coinAmountB:h.coinB,tokenMaxA:v,tokenMaxB:T,liquidityAmount:new qe.default(a),fix_amount_a:!1}})}static buildMasterPosition(t){return{coin_type_a:q(t.coin_type_a.fields.name).full_address,coin_type_b:q(t.coin_type_b.fields.name).full_address,description:t.description,id:t.id.id,index:t.index,liquidity:t.liquidity,name:t.name,pool:t.pool,tick_lower_index:Re(BigInt(t.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(t.tick_upper_index.fields.bits)),url:t.url}}static buildMasterNFT(t){let e=Q(t);if(e){let n={id:e.id.id,pool_id:e.pool_id,index:Number(e.index),strategy:Number(e.strategy),tick_lower_index:Re(BigInt(e.tick_lower_index)),tick_upper_index:Re(BigInt(e.tick_upper_index)),positions:[],...Si(t)};return n.positions=e.positions.map(i=>qn.buildMasterPosition(i.fields)),n}}},Sn=class{static generateNextTickRange(t,e,n){let i=t-e/2,r=t+e/2;return{new_tick_lower:Sn.getValidTickIndex(i,n),new_tick_upper:Sn.getValidTickIndex(r,n)}}static calculateDepositRatio(t,e,n){let i=ee.sqrtPriceX64ToTickIndex(n);if(i<t)return{ratioA:new N(1),ratioB:new N(0)};if(i>e)return{ratioA:new N(0),ratioB:new N(1)};let r=new gf.default(1e8),{coinAmountB:o}=$e.estLiquidityAndcoinAmountFromOneAmounts(t,e,r,!0,!0,0,n),s=ee.sqrtPriceX64ToPrice(n,0,0),a=S(r.toString()).mul(s),u=a.add(o.toString()),l=a.div(u),h=S(o.toString()).div(u);return{ratioA:l,ratioB:h}}static getValidTickIndex(t,e){if(t%e===0)return t;let n;if(t>0?n=t-t%e+e:t<0?n=t+Math.abs(t)%e-e:n=t,n%e!==0)throw new Error("Assertion failed: res % tickSpacing == 0");if(Math.abs(n)<Math.abs(t))throw new Error("Assertion failed: res.abs() >= tickIndex");return n}static get_lp_amount_by_liquidity(t,e){return t.total_supply==="0"?"0":S(t.total_supply).mul(e).div(t.liquidity).toFixed(0,N.ROUND_DOWN).toString()}static get_share_liquidity_by_amount(t,e){return t.total_supply==="0"?"0":S(e).mul(t.liquidity).div(t.total_supply).toFixed(0,N.ROUND_DOWN).toString()}static get_protocol_fee_amount(t,e){return S(e).mul(t.protocol_fee_rate).div(cy).toFixed(0,N.ROUND_CEIL)}static buildFramsPositionNFT(t){let e=t.clmm_postion.fields;return{id:t.id.id,url:e.url,pool_id:t.pool_id,coinTypeA:q(e.coin_type_a.fields.name).full_address,coinTypeB:q(e.coin_type_b.fields.name).full_address,description:e.description,name:e.name,liquidity:e.liquidity,clmm_position_id:e.id.id,clmm_pool_id:e.pool,tick_lower_index:Re(BigInt(e.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(e.tick_upper_index.fields.bits)),rewards:[]}}static buildPool(t){let e=Q(t),n=pn(t),{positions:i}=e;if(e&&i.length>0){let r=Sn.buildFramsPositionNFT(i[0].fields);return{id:e.id.id,pool_id:e.pool,protocol_fee_rate:e.protocol_fee_rate,is_pause:e.is_pause,harvest_assets:{harvest_assets_handle:e.harvest_assets.fields.id.id,size:Number(e.harvest_assets.fields.size)},lp_token_type:q(n).type_arguments[0],total_supply:e.lp_token_treasury.fields.total_supply.fields.value,liquidity:e.liquidity,max_quota:e.max_quota,status:e.status===1?"STATUS_RUNNING":"STATUS_REBALANCING",quota_based_type:e.quota_based_type.fields.name,position:r}}}},_s=class{static calculatePositionShare(t,e,n,i,r,o,s){if(e<=r||t>=o)return"0";let a=0;t<r?a=r:a=t;let u=0;e<o?u=e:u=o;let l=ee.tickIndexToSqrtPriceX64(a),h=ee.tickIndexToSqrtPriceX64(u),{coinA:w,coinB:v}=$e.getCoinAmountFromLiquidity(new Ac.default(n),new Ac.default(s),l,h,!0);return S(w.toString()).mul(i).div(1e12).add(v.toString()).toString()}static buildFramsPool(t){let e=Q(t);if(e)try{let n=[];return e.rewarders.forEach(r=>{n.push({reward_coin:q(r.fields.name).full_address,last_reward_time:"",emission_per_second:"",total_allocate_point:"",allocate_point:""})}),{id:e.id.id,clmm_pool_id:e.clmm_pool_id,effective_tick_lower:Re(BigInt(e.effective_tick_lower.fields.bits)),effective_tick_upper:Re(BigInt(e.effective_tick_upper.fields.bits)),total_share:e.total_share,rewarders:n,positions:{positions_handle:e.positions.fields.id.id,size:e.positions.fields.size},sqrt_price:e.sqrt_price}}catch(n){console.log(n)}}static buildFramsPositionNFT(t){let e=Q(t);if(e){let n=e.clmm_postion.fields;return{id:e.id.id,url:n.url,pool_id:e.pool_id,coinTypeA:q(n.coin_type_a.fields.name).full_address,coinTypeB:q(n.coin_type_b.fields.name).full_address,description:n.description,name:n.name,liquidity:n.liquidity,clmm_position_id:n.id.id,clmm_pool_id:n.pool,tick_lower_index:Re(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(n.tick_upper_index.fields.bits)),rewards:[]}}}},ly=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.ido,i=`${n}_getPoolImmutables`,r=this.getCache(i,e),o={data:[],hasNextPage:!1},s=[];if(r!==void 0&&s.push(...r),s.length===0)try{let a=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n}::oversubscribe_pool::CreatePoolEvent`},t);a.data.forEach(u=>{let l=u.parsedJson;if(l){let h=$t.buildIdoPoolImmutables(l);s.push(h)}}),o.hasNextPage=a.hasNextPage,o.nextCursor=a.nextCursor,this.updateCache(i,s,X)}catch(a){console.log("getPoolImmutables",a)}return o.data=s,o}async getPools(t=[],e=!1){let n=[],i=[];t.length>0?i=[...t]:(await this.getPoolImmutables("all",e)).data.forEach(s=>{i.push(s.pool_address)});let r=await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showType:!0,showContent:!0});for(let o of r){let s=$t.buildIdoPool(o);await $t.calculatePoolUiPrice(this._sdk,s),n.push(s);let a=`${s.pool_address}_getPoolObject`;this.updateCache(a,s,X)}return n}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=$t.buildIdoPool(r);return await $t.calculatePoolUiPrice(this._sdk,o),this.updateCache(n,o),o}async getIdoConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.ido,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({Transaction:o}))?.data,a={pools_id:"",admin_cap_id:"",package_version_id:""};return s.length>0&&(s.forEach(u=>{console.log("item: ",u);let l=u.parsedJson;if(l)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=l.admin_cap_id,a.package_version_id=l.package_version_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;default:break}}),this.updateCache(n,a,X)),a}async getPurchaseInfo(t,e,n=!0){let i=`${t}_${e}_getPurchaseInfo`,r=this.getCache(i,n);if(r)return r;try{let o=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"address",value:e}}),s=$t.buildPurchaseInfo(Q(o));return this.updateCache(i,s,Ue),s}catch{return}}async getLockNFT(t,e=!1){let n=`${t}_getLockNFT`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(!r.error)return Nn(r)}async getLockNFTList(t){let{clmm_pool:e}=this._sdk.ClmmSDK.sdkOptions,{ido:n}=this._sdk.sdkOptions,i=[];try{let r=(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{filter:{StructType:`${n.package_id}::lock::LockedNFT<${e.package_id}::position::Position>`},options:{showContent:!0}}))?.data;for(let o of r){let s=Q(o);if(s){let a=s.nft.fields,u={locked_at:Number(s.locked_at),lock_duration:Number(s.lock_duration),lock_nft_id:s.id.id,type:s.nft.type,...a};u.end_lock_time=u.locked_at+u.lock_duration,u.coin_type_a=q(a.coin_type_a.fields.name).full_address,u.coin_type_b=q(a.coin_type_b.fields.name).full_address,u.id=a.id.id,u.tick_lower_index=Re(BigInt(a.tick_lower_index.fields.bits)),u.tick_upper_index=Re(BigInt(a.tick_upper_index.fields.bits)),i.push(u)}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPool(t){let{ido:e}=this.sdk.sdkOptions;cs((0,xn.normalizeSuiAddress)(t.coin_type_sale),(0,xn.normalizeSuiAddress)(t.coin_type_raise))&&(t.price_min=S(1).div(t.price_max).toNumber(),t.price_max=S(1).div(t.price_min).toNumber());let i=An.priceRealToFix(Number(t.price),t.sale_decimals,t.raise_decimals),r=ee.priceToSqrtPriceX64(S(t.price_min),t.sale_decimals,t.raise_decimals).toString(),o=ee.priceToSqrtPriceX64(S(t.price_max),t.sale_decimals,t.raise_decimals).toString(),s=new Xt.TransactionBlock,a=S(t.total_supply).add(S(t.total_supply).mul(S(t.liquidity_injection_ratio))).toNumber(),u=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.coin_type_sale),l=re.buildCoinForAmount(s,u,BigInt(a),t.coin_type_sale,!1),h=[s.pure(D(e).admin_cap_id),s.pure(D(e).package_version_id),s.pure(D(e).pools_id),s.pure((0,xn.normalizeSuiAddress)(t.owner)),s.pure(S(i).mul(ur).toString()),s.pure(t.total_supply),s.pure(t.complete_raise_limit),s.pure(t.min_purchase_amount),s.pure(t.max_purchase_amount),s.pure(t.start_time),s.pure(t.purchase_duration),s.pure(t.lock_up_duration),s.pure((t.liquidity_injection_ratio*pf).toString()),s.pure(r),s.pure(o),s.pure(t.tick_spacing.toString()),l.targetCoin,s.pure(t.protection_hard_cap.toString()),s.pure(G)],w=[t.coin_type_sale,t.coin_type_raise];return s.moveCall({target:`${e.published_at}::${ry}::create_oversubscribe_pool`,typeArguments:w,arguments:h}),s}async creatPurchasePayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=await this.getPurchaseInfo(t.purchase_handle,this._sdk.ClmmSDK.senderAddress,!1),r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.coin_type_raise),o=re.buildCoinForAmount(n,r,BigInt(t.raise_amount),t.coin_type_raise,!1),s=[t.coin_type_sale,t.coin_type_raise],a,u;return i?(u="purchase",a=[n.object(D(e).package_version_id),n.object(t.pool_address),n.object(i.purchase_certificate_id),n.pure(t.raise_amount.toString()),o.targetCoin,n.pure(G)]):(u="create_certificate_and_purchase",a=[n.object(D(e).package_version_id),n.object(t.pool_address),n.pure(t.raise_amount.toString()),o.targetCoin,n.pure(G)]),n.moveCall({target:`${e.published_at}::${on}::${u}`,typeArguments:s,arguments:a}),n}async redeemPayload(t){let{ido:e}=this.sdk.sdkOptions,n=await this.getPurchaseInfo(t.purchase_handle,this._sdk.ClmmSDK.senderAddress,!1);if(n===void 0)throw Error("get purchase certificate fail");let i=new Xt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure(D(e).package_version_id),i.pure(t.pool_address),i.pure(n.purchase_certificate_id),i.pure(G)];return i.moveCall({target:`${e.published_at}::${on}::redeem`,typeArguments:r,arguments:o}),i}injectLiquidityPayload(t){let{ido:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new Xt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=t.is_reverse?"inject_liquidity_with_reverse_clmm_pool":"inject_liquidity_with_forward_clmm_pool",s=[i.pure(D(e).package_version_id),i.pure(t.pool_address),i.pure(D(n).global_config_id),i.pure(t.clmm_pool_address),i.pure(G)];return i.moveCall({target:`${e.published_at}::${on}::${o}`,typeArguments:r,arguments:s}),i}unPauseInjectLiquidity(t){let{ido:e}=this.sdk.sdkOptions,{integrate:n,clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions,r=new Xt.TransactionBlock;r.moveCall({target:`${n.published_at}::${tr}::unpause_pool`,typeArguments:[t.coin_type_a,t.coin_type_b],arguments:[r.object(D(i).global_config_id),r.object(t.clmm_pool_address)]});let o=[t.coin_type_sale,t.coin_type_raise],s=t.is_reverse?"inject_liquidity_with_reverse_clmm_pool":"inject_liquidity_with_forward_clmm_pool",a=[r.object(D(e).package_version_id),r.object(t.pool_address),r.object(D(i).global_config_id),r.object(t.clmm_pool_address),r.object(G)];return r.moveCall({target:`${e.published_at}::${on}::${s}`,typeArguments:o,arguments:a}),r}async findClmmPoolForLiquidity(t){let e=null,n=!1,i=await this.sdk.ClmmSDK.Pool.getPoolImmutables();for(let r of i){if(r.coinTypeA===t.coin_type_sale&&r.coinTypeB===t.coin_type_raise&&Number(r.tickSpacing)===t.tick_spacing){e=await this._sdk.ClmmSDK.Pool.getPool(r.poolAddress);break}if(r.coinTypeA===t.coin_type_raise&&r.coinTypeB===t.coin_type_sale&&Number(r.tickSpacing)===t.tick_spacing){e=await this._sdk.ClmmSDK.Pool.getPool(r.poolAddress),n=!0;break}}return e&&(S(e.current_sqrt_price).lessThanOrEqualTo(t.current_sqrt_price_min)||S(e.current_sqrt_price).greaterThanOrEqualTo(t.current_sqrt_price_max))?(console.log("clmmPool: ",e.poolAddress),{is_reverse:n,clmmPool:null}):{is_reverse:n,clmmPool:e}}withdrawPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object(D(e).package_version_id),n.object(t.pool_address),n.object(G)];return n.moveCall({target:`${e.published_at}::${on}::withdraw`,typeArguments:i,arguments:r}),n}updateWhitelistCapPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.add_whites&&t.add_whites.addresses.length>0&&n.moveCall({target:`${e.published_at}::${on}::add_white_listed_addresses`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.add_whites.addresses.map(r=>n.object((0,xn.normalizeSuiObjectId)(r)))}),n.pure(t.add_whites.protection_limit),n.object(G)]}),t.remove_whites&&t.remove_whites.length>0&&n.moveCall({target:`${e.published_at}::${on}::remove_white_listed_addresses`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.remove_whites.map(r=>n.object((0,xn.normalizeSuiObjectId)(r)))}),n.object(G)]}),t.update_whites&&t.update_whites.forEach(r=>{n.moveCall({target:`${e.published_at}::${on}::update_white_listed_address`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.object(r.address),n.pure(r.protection_limit),n.object(G)]})}),n}creatCancelPoolPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).package_version_id),n.pure(t.pool_address),n.pure(G)];return n.moveCall({target:`${e.published_at}::${on}::cancel`,typeArguments:i,arguments:r}),n}updatePoolOwnerPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.object(t.new_owner),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_pool_owner`,typeArguments:i,arguments:r}),e}updatePoolDuractionPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.pure(t.start_time),e.pure(t.purchase_duration),e.pure(t.lock_duration),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_pool_duration`,typeArguments:i,arguments:r}),e}updateProtectionHardCapPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.pure(t.protection_hard_cap),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_protection_hard_cap`,typeArguments:i,arguments:r}),e}unlockNftPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft_id),n.pure(G)];return n.moveCall({target:`${e.published_at}::lock::unlock_nft`,typeArguments:i,arguments:r}),n}async isAdminCap(t){let{ido:e}=this._sdk.sdkOptions,n=`${e.package_id}_${t}_isAdminCap`,i=this.getCache(n);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:D(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=pn(r),s=or(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,xn.normalizeSuiAddress)(s.AddressOwner)===(0,xn.normalizeSuiAddress)(t)),this.updateCache(n,a,X),a}async getWhiteProtectionLimit(t,e,n=!0){let i=`${t}_${e}_getWhiteProtectionLimit`,r=this._sdk.getCache(i,n);if(r)return r;try{let o=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"address",value:e}});if(o&&o.data){let s=Q(o);return this._sdk.updateCache(i,s.value),s.value}return}catch{return}}async getWhiteList(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n}),r=Q(i);if(console.log(r),r)return r?.value?.fields}catch{}return{safe_limit_amount:"0",safe_purchased_amount:"0"}}async getAdminAddress(){let{ido:t}=this._sdk.sdkOptions,e=`${D(t).admin_cap_id}_getAdminAddress`,n=this.getCache(e);if(n)return n;let i=await this._sdk.ClmmSDK.fullClient.getObject({id:D(t).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(i);let r=pn(i),o=or(i);if(o&&r&&q(r).source_address===`${t.package_id}::config::AdminCap`){let a=(0,xn.normalizeSuiAddress)(o.AddressOwner);return this.updateCache(e,a,X),a}return""}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},dy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getOwnerVeNFT(t,e=!0){let{xtoken:n}=this.sdk.sdkOptions,i=`${t}_getLockUpManagerEvent`,r=this.getCache(i,e);if(r!==void 0)return r;let o,s=`${n.package_id}::xtoken::VeNFT`;return(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0},filter:{StructType:s}})).data.forEach(u=>{let l=q(Mt(u)).source_address;if(l===s&&u.data&&u.data.content){let{fields:h}=u.data.content;o={...Si(u),id:h.id.id,index:h.index,type:l,xtoken_balance:h.xtoken_balance},this.updateCache(i,o,X)}}),o}async getOwnerLockTokens(t){let{xtoken:e}=this.sdk.sdkOptions,n=[],i=`${e.package_id}::lock_coin::LockedCoin<${this.buileTokenCoinType()}>`,r=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0},filter:{StructType:i}});for(let o of r.data)if(q(Mt(o)).source_address===i&&o.data){let a=Oi.buildLockToken(o.data.content),u=await this.getLockXToken(a.id);u&&(a.xtoken_amount=u.xtoken_amount),n.push(a)}return n}async getLockToken(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(e.data?.content){let n=Oi.buildLockToken(e.data.content),i=await this.getLockXToken(n.id);return i&&(n.xtoken_amount=i.xtoken_amount),n}}async getOwnerTokenCoins(t){return await this._sdk.ClmmSDK.getOwnerCoinAssets(t,this.buileTokenCoinType())}mintVeNFTPayload(){let{xtoken:t}=this.sdk.sdkOptions,e=new Rn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${cr}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xtoken_manager_id)]}),e}async convertPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock,i=this.buileTokenCoinType(),r=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${cr}::mint_and_convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xtoken_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${cr}::convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xtoken_manager_id),r,n.pure(t.amount),n.pure(t.venft_id)]}),n}redeemLockPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(G)]}),n}redeemPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::redeem`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}redeemDividendPayload(t,e){let{xtoken_dividends:n}=this.sdk.sdkOptions,i=new Rn.TransactionBlock;return e.forEach(r=>{i.moveCall({target:`${n.published_at}::${Tc}::redeem`,typeArguments:[r],arguments:[i.object(D(n).dividend_manager_id),i.object(t)]})}),i}redeemDividendV2Payload(t,e,n){let{xtoken_dividends:i}=this.sdk.sdkOptions,r=new Rn.TransactionBlock;return e.filter(s=>n.includes(s)).length>0&&(r=this.redeemDividendXTokenPayload(t,r)),e.forEach(s=>{n.includes(s)||r.moveCall({target:`${i.published_at}::${Tc}::redeem_v2`,typeArguments:[s],arguments:[r.object(D(i).dividend_manager_id),r.object(t),r.object(G)]})}),r}redeemDividendXTokenPayload(t,e){let{xtoken_dividends:n,xtoken:i}=this.sdk.sdkOptions,{xtoken_manager_id:r,lock_manager_id:o}=D(i),{dividend_manager_id:s}=D(n);return e=e===void 0?new Rn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${Tc}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(G)]}),e}buileTokenCoinType(){return`${this.sdk.sdkOptions.token_faucet.package_id}::token::TOKEN`}buileXTokenCoinType(t=this._sdk.sdkOptions.xtoken.package_id,e="xtoken",n="XTOKEN"){return`${t}::${e}::${n}`}cancelRedeemPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}async getInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.xtoken,e=`${t}_getInitFactoryEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::xtoken::InitEvent`}))?.data,r={xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""};i.length>0&&i.forEach(s=>{let a=s.parsedJson;a&&(r.xtoken_manager_id=a.xtoken_manager)});let o=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::locking::InitializeEvent`}))?.data;return o.length>0&&o.forEach(s=>{let a=s.parsedJson;a&&(r.lock_manager_id=a.lock_manager)}),r.lock_handle_id=(await this.getLockUpManager(r.lock_manager_id)).lock_infos.lock_handle_id,this.updateCache(e,r,X),r}async getLockUpManager(t=D(this.sdk.sdkOptions.xtoken).lock_manager_id,e=!1){let n=`${t}_getLockUpManagerEvent`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Oi.buildLockUpManager(Q(r));return this.updateCache(n,o,X),o}async getLockInfoHandle(t){let e=`${t}_getLockInfoHandle`,n=this.getCache(e);if(n!==void 0)return n;let i="",r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Q(r);return o&&(i=o.lock_infos.fields.id.id,this.updateCache(e,i,X)),i}async getDividendConfigs(){let{package_id:t}=this.sdk.sdkOptions.xtoken_dividends,e=`${t}_getDividendManagerEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::dividend::InitEvent`}))?.data,r={dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""};return i.length>0&&i.forEach(o=>{let s=o.parsedJson;s&&(r.dividend_manager_id=s.manager_id,r.dividend_admin_id=s.admin_id,r.dividend_settle_id=s.settle_id,this.updateCache(e,r,X))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=D(this.sdk.sdkOptions.xtoken_dividends),n=`${e}_getDividendManager`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s=Oi.buildDividendManager(o);return this.updateCache(n,s,X),s}async getXcetusManager(t=!0){let{xtoken_manager_id:e}=D(this.sdk.sdkOptions.xtoken),n=`${e}_getXcetusManager`,i=this.getCache(n,t);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s={id:o.id.id,index:Number(o.index),has_venft:{handle:o.has_venft.fields.id.id,size:o.has_venft.fields.size},nfts:{handle:o.nfts.fields.id.id,size:o.nfts.fields.size},total_locked:o.total_locked,treasury:o.treasury.fields.total_supply.fields.value};return this.updateCache(n,s),s}async getVeNFTDividendInfo(t,e){try{let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);return Oi.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(vs)).div(sn);return{amountOut:S(r).mul(S(t)).round().toString(),percent:r.toString()}}async reverseRedeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(vs)).div(sn);return{amountOut:S(t).div(r).toFixed(0,N.ROUND_UP),percent:r.toString()}}async getLockXToken(t){let{lock_handle_id:e}=D(this._sdk.sdkOptions.xtoken),n=`${t}_getXTokenAmount`,i=this.getCache(n);if(i)return i;try{let r=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:e,name:{type:"0x2::object::ID",value:t}}),o=Q(r);if(o){let s=o.value.fields.value.fields;return this.updateCache(n,s,X),s}}catch{}}async getVeNftAmount(t,e){try{let n=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);if(i){let{lock_amount:r,xtoken_amount:o}=i.value.fields.value.fields;return{lock_amount:r,xtoken_amount:o}}}catch{}return{lock_amount:"0",xtoken_amount:"0"}}async getPhaseDividendInfo(t,e=!1){let i=(await this.getDividendManager()).dividends.id,r=`${i}_${t}_getPhaseDividendInfo`,o=this._sdk.getCache(r,e);if(o)return o;try{let s=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:i,name:{type:"u64",value:t}}),a=Q(s),u=a.value.fields.value.fields,l=u.redeemed_num.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),h=u.bonus_types.map(T=>T.fields.name),w=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:Lt(s),phase:a.name,settled_num:u.settled_num,register_time:u.register_time,redeemed_num:l,is_settled:u.is_settled,bonus_types:h,bonus:w,phase_end_time:""};return this.updateCache(r,v),v}catch{}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},fy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async addMasterLiquidity(t){let{liquidity_stratefy:e}=this._sdk.sdkOptions,{clmm_pool:n}=this._sdk.ClmmSDK.sdkOptions,i=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),r=S(0),o=S(0),s=[],a=[],u=[],l=[],h=[];t.liquidity_bins.forEach((x,P)=>{let O=t.amounts_a[P],E=t.amounts_b[P],B=t.bins_fix_amount_a[P];r=r.add(O),o=o.add(E),s.push(O),a.push(E),u.push(Tt(BigInt(x.tick_lower)).toString()),l.push(Tt(BigInt(x.tick_upper)).toString()),h.push(B)});let w=[t.coinTypeA,t.coinTypeB],v=new Ai.TransactionBlock,T=re.buildAddLiquidityFixTokenCoinInput(v,!t.fix_amount_a,r.toString(),t.slippage,t.coinTypeA,i,!1)?.targetCoin,I=re.buildAddLiquidityFixTokenCoinInput(v,t.fix_amount_a,o.toString(),t.slippage,t.coinTypeB,i,!1)?.targetCoin;return oy(t)?v.moveCall({target:`${e.published_at}::router::increase_liquidity`,typeArguments:w,arguments:[v.object(D(e).master_manger_id),v.object(t.master_address),v.object(D(n).global_config_id),v.object(t.pool_address),T,I,v.pure(s.map(x=>v.pure(x,"u64"))),v.pure(a.map(x=>v.pure(x,"u64"))),v.pure(h.map(x=>v.pure(x,"bool"))),v.object(G)]}):v.moveCall({target:`${e.published_at}::router::create_master_liquidity`,typeArguments:w,arguments:[v.object(D(e).master_manger_id),v.object(D(n).global_config_id),v.object(t.pool_address),T,I,v.pure(u.map(x=>v.pure(x,"u32"))),v.pure(l.map(x=>v.pure(x,"u32"))),v.pure(s.map(x=>v.pure(x,"u64"))),v.pure(a.map(x=>v.pure(x,"u64"))),v.pure(h.map(x=>v.pure(x,"bool"))),v.pure(t.strategy),v.pure(Tt(BigInt(t.tick_lower)).toString()),v.pure(Tt(BigInt(t.tick_upper)).toString()),v.object(G)]}),v}buildMasterNFTType(){return`${this._sdk.sdkOptions.liquidity_stratefy.package_id}::master_liquidity::MasterLiquidity`}async getMasterNFTList(t,e=[]){let n=[],i=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.liquidity_stratefy.package_id}}),r=e.length>0;for(let o of i.data)if(q(o.data.type).full_address===this.buildMasterNFTType()){let a=qn.buildMasterNFT(o);if(a){let u=`${a.id}_masterNFT`;this.updateCache(u,a,X),r?e.includes(a.pool_id)&&n.push(a):n.push(a)}}return n}async getMasterNFT(t,e=!1){let n="$masterId}_masterNFT",i=this.getCache(n,e);if(i)return i;try{let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(q(r.data.type).full_address===this.buildMasterNFTType()){let s=qn.buildMasterNFT(r);return s&&this.updateCache(n,s,X),s}}catch(r){console.log(r)}}async fetchMasterPositionInfos(t){let e={},{clmm_pool:n,integrate:i,simulationAccount:r}=this.sdk.ClmmSDK.sdkOptions,o=new Ai.TransactionBlock;return t.forEach(a=>{a.position_ids.forEach(u=>{let l=[a.coinTypeA,a.coinTypeB],h=[o.object(D(n).global_config_id),o.object(a.pool_id),o.object(u)];o.moveCall({target:`${i.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l}),o.moveCall({target:`${i.published_at}::${zt}::fetch_position_rewards`,arguments:[...h,o.object(G)],typeArguments:l})})}),(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address})).events?.forEach(a=>{let{parsedJson:u}=a,{position_id:l}=u,h=e[l];switch(h===void 0&&(h={position_id:l,feeOwedA:"0",feeOwedB:"0",rewarders:[]},e[l]=h),q(a.type).name){case"FetchPositionFeesEvent":h.feeOwedA=u.fee_owned_a,h.feeOwedB=u.fee_owned_b;break;case"FetchPositionRewardsEvent":h.rewarders=u.data;break}}),e}async getLiquidityStrategyConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.liquidity_stratefy,n=`${e}_getLiquidityStrategyConfigst`,i=this.getCache(n,t);if(i!==void 0)return i;let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::master_liquidity::MasterLiquidityManagerCreatedEvent`})).data,o={master_manger_id:"",master_liquidity_handle:""};if(r.length>0){for(let s of r){let a=s.parsedJson;o.master_manger_id=a.id;let u=await this._sdk.ClmmSDK.fullClient.getObject({id:a.id,options:{showContent:!0}}),l=Q(u);o.master_liquidity_handle=l.position_maps.fields.id.id;break}this.updateCache(n,o,X)}return o}removeMasterLiquidity(t){let{clmm_pool:e}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:n}=this.sdk.sdkOptions,i=new Ai.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];this.collectReward({coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collect_fee:!1,rewarder_coin_types:t.rewarder_coin_types,master_address:t.master_address,pool_address:t.pool_address},i);let o=[i.object(D(n).master_manger_id),i.object(t.pool_address),i.object(t.master_address),i.object(D(e).global_config_id),i.pure(t.delta_liquidities.map(s=>i.pure(s,"u128"))),i.pure(t.min_amounts_a.map(s=>i.pure(s,"u64"))),i.pure(t.min_amounts_b.map(s=>i.pure(s,"u64"))),i.object(G)];return i.moveCall({target:`${n.published_at}::${gs}::remove_liquidity`,typeArguments:r,arguments:o}),i}closeMasterLiquidity(t){let{clmm_pool:e}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:n}=this.sdk.sdkOptions,i=new Ai.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];return this.collectReward({coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collect_fee:!1,rewarder_coin_types:t.rewarder_coin_types,master_address:t.master_address,pool_address:t.pool_address},i),i.moveCall({target:`${n.published_at}::${gs}::close_master_liquidity`,typeArguments:r,arguments:[i.object(D(n).master_manger_id),i.object(t.master_address),i.object(D(e).global_config_id),i.object(t.pool_address),i.pure(t.min_amounts_a.map(o=>i.pure(o,"u64"))),i.pure(t.min_amounts_b.map(o=>i.pure(o,"u64"))),i.object(G)]}),i}collectFee(t,e){let{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:i}=this.sdk.sdkOptions;e=e===void 0?new Ai.TransactionBlock:e;let r=[t.coinTypeA,t.coinTypeB],o=[e.object(D(i).master_manger_id),e.object(t.master_address),e.object(D(n).global_config_id),e.object(t.pool_address)];return e.moveCall({target:`${i.published_at}::${gs}::collect_fee`,typeArguments:r,arguments:o}),e}collectReward(t,e){let{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:i}=this.sdk.sdkOptions;return e=e===void 0?new Ai.TransactionBlock:e,t.collect_fee&&this.collectFee({...t},e),t.rewarder_coin_types.forEach(r=>{let o=[t.coinTypeA,t.coinTypeB,r];if(e){let s=[e.object(D(i).master_manger_id),e.object(t.master_address),e.object(D(n).global_config_id),e.object(t.pool_address),e.object(D(n).global_vault_id),e.object(G)];e.moveCall({target:`${i.published_at}::${gs}::collect_reward`,typeArguments:o,arguments:s})}}),e}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},hy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildCoinInput(t,e,n,i,r){let{selectedCoins:o,remainingCoins:s}=we.selectCoinAssetGreaterThanOrEqual(e,BigInt(i)),a=we.calculateTotalBalance(o);if(a<BigInt(i))throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${i} `);let u=a-BigInt(i),l;if(we.isSuiCoin(n))l=t.splitCoins(t.gas,[t.pure(i)]);else{let[h,...w]=o.map(v=>v.coinObjectId);l=t.object(h),w.length>0?r?t.mergeCoins(l,[...w.map(v=>t.object(v)),r]):t.mergeCoins(l,[...w.map(v=>t.object(v))]):r&&t.mergeCoins(l,[r])}return{selectedUnusedAmount:u,coinInput:l,remainingCoins:s}}async deposit(t){console.log("1110 deposit \u53C2\u6570: ",{params:t});let{vaults:e,frams:n}=this._sdk.sdkOptions,{clmm_pool:i}=this._sdk.ClmmSDK.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress()),o=new xi.TransactionBlock,s,a;if(t.swapParams){let w=await this.handleDepositSwap(t,o,r);s=w.primaryCoinAInputs,a=w.primaryCoinBInputs}else s=re.buildAddLiquidityFixTokenCoinInput(o,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,r,!1)?.targetCoin,a=re.buildAddLiquidityFixTokenCoinInput(o,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,r,!1)?.targetCoin;let u=D(e),l=D(n),h=D(i);return o.moveCall({target:`${e.published_at}::${sy}::deposit`,typeArguments:[t.coinTypeA,t.coinTypeB,t.lp_token_type],arguments:[o.object(u.vaults_manager_id),o.object(t.vault_id),o.object(l.rewarder_manager_id),o.object(l.global_config_id),o.object(t.farming_pool),o.object(h.global_config_id),o.object(t.clmm_pool),s,a,o.pure(t.amount_a),o.pure(t.amount_b),o.pure(t.fix_amount_a),o.object(G)]}),o}async handleDepositSwap(t,e,n){let{clmm_pool:i,integrate:r}=this._sdk.ClmmSDK.sdkOptions,{swap_amount:o,a2b:s,route_obj:a,staking_id:u}=t.swapParams,l=s?t.coinTypeA:t.coinTypeB,h=re.buildCoinForAmount(e,n,BigInt(o),l,!1),w=BigInt(h.tragetCoinAmount)-BigInt(o),v=[];if(u){let O=this.requestStakeCoin(u,e,h.targetCoin),E=re.buildCoinForAmount(e,h.remainCoins,BigInt(0),l,!1).targetCoin;v=s?[E,O]:[O,E]}else if(a){let O=re.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),E=await re.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,a,h,O,"",t.slippage,e);v=s?[E.fromCoin,E.toCoin]:[E.toCoin,E.fromCoin],console.log("swapCoinInputTo.isMintZeroCoin: ",O),!O.isMintZeroCoin&&O.originalSplitedCoin===void 0&&e.transferObjects([O.targetCoin],e.pure(this._sdk.getVerifySenderAddress()))}else{let O=re.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),E=mn.getDefaultSqrtPriceLimit(s).toString();v=e.moveCall({target:`${r.published_at}::${Jn}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(D(i).global_config_id),e.object(t.clmm_pool),s?h.targetCoin:O.targetCoin,s?O.targetCoin:h.targetCoin,e.pure(s),e.pure(!0),e.pure(o),e.pure(E),e.pure(!1),e.object(G)]})}let T,I,x=v[0],P=v[1];if(s){let O=BigInt(t.amount_a)-w;we.isSuiCoin(l)?(e.transferObjects([x],e.pure(this._sdk.getVerifySenderAddress())),T=e.splitCoins(e.gas,[e.pure(t.amount_a)])):O>0n?T=this.buildCoinInput(e,h.remainCoins,l,O,x).coinInput:T=x,I=P}else{T=x;let O=BigInt(t.amount_b)-w;we.isSuiCoin(l)?(e.transferObjects([P],e.pure(this._sdk.getVerifySenderAddress())),I=e.splitCoins(e.gas,[e.pure(t.amount_b)])):O>0n?I=this.buildCoinInput(e,h.remainCoins,l,O,P).coinInput:I=P}return{primaryCoinAInputs:T,primaryCoinBInputs:I}}async remove(t){console.log({params:t});let{vaults:e,frams:n}=this.sdk.sdkOptions,{clmm_pool:i,integrate:r}=this._sdk.ClmmSDK.sdkOptions,o=new xi.TransactionBlock,s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),t.lp_token_type),a=re.buildCoinForAmount(o,s,BigInt(t.lp_token_amount),t.lp_token_type,!1).targetCoin,u=D(e),l=D(n),h=D(i),w=[t.coinTypeA,t.coinTypeB,t.lp_token_type],v=o.moveCall({target:`${e.published_at}::${ay}::remove`,typeArguments:w,arguments:[o.object(u.vaults_manager_id),o.object(t.vault_id),o.object(l.rewarder_manager_id),o.object(l.global_config_id),o.object(t.farming_pool),o.object(h.global_config_id),o.object(t.clmm_pool),a,o.pure(t.lp_token_amount),o.pure(t.min_amount_a),o.pure(t.min_amount_b),o.object(G)]}),T=v[0],I=v[1];if(t.swapParams){let{a2b:x,swap_amount:P,route_obj:O}=t.swapParams;if(O){let E={targetCoin:x?T:I,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},B={targetCoin:x?I:T,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},$=await re.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,O,E,B,"",t.slippage,o),Z=x?[$.fromCoin,$.toCoin]:[$.toCoin,$.fromCoin];x?o.mergeCoins(Z[1],[I]):o.mergeCoins(Z[0],[T]),o.transferObjects([...Z],o.pure(this._sdk.getVerifySenderAddress()))}else{let E=mn.getDefaultSqrtPriceLimit(x).toString(),B=o.moveCall({target:`${r.published_at}::${Jn}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[o.object(D(i).global_config_id),o.object(t.clmm_pool),T,I,o.pure(x),o.pure(!0),o.pure(P),o.pure(E),o.pure(!0),o.object(G)]});o.transferObjects([B[0],B[1]],o.pure(this._sdk.getVerifySenderAddress()))}}else o.transferObjects([T,I],o.pure(this._sdk.getVerifySenderAddress()));return o}async getVaultList(t="all"){let{vaults:e}=this._sdk.sdkOptions,n=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e.package_id}::vaults::CreateEvent`},t),i=n.data.map(s=>s.parsedJson.id),r=await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}),o=[];return r.forEach(s=>{let a=Sn.buildPool(s);a&&(a.staking_id=this.findHaedalStakeId(a.position.coinTypeA,a.position.coinTypeB),this.savePoolToCache(a),o.push(a))}),n.data=o,n}findHaedalStakeId(t,e){let{haedal:n}=this._sdk.sdkOptions,{support_stakings:i}=D(n);return i.length===0?void 0:i.filter(o=>{let s=q(o.from_coin_type).full_address,a=q(o.to_coin_type).full_address,u=q(t).full_address,l=q(e).full_address;return u===s&&l===a||u===a&&l===s})[0]?.staking_id||void 0}savePoolToCache(t){let e=`${t.id}_mirrorPool`;this.updateCache(e,t,X)}readPoolFromCache(t,e=!1){let n=`${t}_mirrorPool`;return this.getCache(n,e)}async calculateMaxAvailable(t){let{integrate:e,simulationAccount:n}=this.sdk.ClmmSDK.sdkOptions,i=new xi.TransactionBlock,r=ee.tickIndexToSqrtPriceX64(t.lowerTick),o=ee.tickIndexToSqrtPriceX64(t.upperTick),s=new Oe.default(t.curSqrtPrice),a=$e.getCoinAmountFromLiquidity(new Oe.default(t.input_amount),s,r,o,!1),u=[t.coinTypeA,t.coinTypeB];i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!0),i.pure(!0),i.pure(a.coinA.toString())],typeArguments:u}),i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!1),i.pure(!0),i.pure(a.coinB.toString())],typeArguments:u});let h=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(x=>q(x.type).name==="CalculatedSwapResultEvent");if(h.length===0)return null;let w=h[0].parsedJson.data,v=h[1].parsedJson.data,T=S(a.coinB.toString()).add(w.amount_out),I=S(a.coinA.toString()).add(v.amount_out);return{maxAmountB:T,maxAmountA:I}}async calculateRemoveSwapAmount(t,e){let n=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice)),i=t.fix_amount_a?n.ratioA:n.ratioB;console.log({fixRatio:i});let r=S(t.receive_amount).mul(i),o,s;if(t.removeLiquidity){let x=ee.tickIndexToSqrtPriceX64(t.lowerTick),P=ee.tickIndexToSqrtPriceX64(t.upperTick),O=$e.getCoinAmountFromLiquidity(new Oe.default(t.removeLiquidity),new Oe.default(t.curSqrtPrice),x,P,!1);s=t.removeLiquidity,o=t.fix_amount_a?O.coinB.toString():O.coinA.toString(),r=t.fix_amount_a?S(O.coinA.toString()):S(O.coinB.toString())}else{let x=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new Oe.default(r.toFixed(0)),t.fix_amount_a,!1,.2,new Oe.default(t.curSqrtPrice));s=x.liquidityAmount.toString(),o=t.fix_amount_a?x.coinAmountB.toString():x.coinAmountA.toString()}console.log({fixAmount:r,otherSideAmount:o});let a=!t.fix_amount_a,u=await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,S(o),t.coinTypeA,t.coinTypeB,!0,t.priceSplitPoint,t.use_route,[{pool_id:t.clmm_pool,tick_lower:t.lowerTick,tick_upper:t.upperTick,delta_liquidity:Number(s),is_increase:!1}]);console.log({data:u,range:e});let l=r.add(u.amount_out),h=S(t.receive_amount),w=h.sub(l);if(console.log(`\u5B9E\u9645\u5F97\u5230: ${l.toString()} , \u671F\u671B\u5F97\u5230: ${t.receive_amount}, \u5269\u4F59: ${w.toString()} `),(!t.removeLiquidity||t.removeLiquidity&&e)&&w.abs().greaterThan(h.mul(.01))){let x=l.lessThan(h),P,O;e?x?(P=S(s),O=e.right):(P=e.left,O=S(s)):(P=x?S(s):S(0),O=x?S(t.maxLiquidity):S(s));let E=S(P).add(O).div(2).toFixed(0);if(console.log({left:P.toString(),right:O.toString(),midLiquidity:E.toString()}),!e||e&&e.count<15&&P<O)return await this.calculateRemoveSwapAmount({...t,removeLiquidity:E},{left:P,right:O,count:e?e.count+1:0})}let v=u.amount_in&&u.fee_amount?new Oe.default(u.amount_in).add(new Oe.default(u.fee_amount)).toString():u.amount_in,T=u.amount_out,{is_exceed:I}=u;return{swapInAmount:v,swapOutAmount:T,liquidity:s,is_exceed:I,routeObj:u.route_obj,request_id:t.request_id}}async calculateHaedalDepositFixSui(t){let e=t.inputSuiAmount.mul(t.remainRate),n=t.inputSuiAmount.sub(t.swapSuiAmount),i=t.exchangeRate?t.exchangeRate:await this.getExchangeRateForHaedal(t.staking_id,t.shouldRequestStake,Number(t.swapSuiAmount.toFixed(0))),r=t.swapSuiAmount.div(i).toFixed(0);console.log({swapAmount:t.swapSuiAmount.toString(),hasuiAmount:r.toString(),leftSuiAmount:t.leftSuiAmount.toString(),rightSuiAmount:t.rightSuiAmount.toString(),exchangeRate:i});let o=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new Oe.default(r.toString()),!t.fixCoinA,!0,0,new Oe.default(t.curSqrtPrice)),s=t.fixCoinA?o.coinAmountA.toString():o.coinAmountB.toString(),a=S(n).sub(s);return console.log({useSuiAmount:s.toString(),hasuiAmount:r.toString(),remainSui:n.toString(),remainSuiLimit:e.toString(),actRemainSui:a.toString(),rebalanceCount:t.rebalanceCount}),a.greaterThanOrEqualTo(0)&&a.lessThanOrEqualTo(e)||t.rebalanceCount>12||t.leftSuiAmount.greaterThanOrEqualTo(t.rightSuiAmount)?{swapInAmount:t.swapSuiAmount.toFixed(0),swapOutAmount:r,afterSqrtPrice:t.curSqrtPrice,fixAmountA:!t.fixCoinA,is_exceed:!0,request_id:"",staking_id:t.staking_id}:a.lessThan(0)?await this.calculateHaedalDepositFixSui({...t,rightSuiAmount:t.swapSuiAmount,swapSuiAmount:t.swapSuiAmount.add(t.leftSuiAmount).div(2),exchangeRate:i,rebalanceCount:t.rebalanceCount+1}):a.greaterThan(e)?await this.calculateHaedalDepositFixSui({...t,leftSuiAmount:t.swapSuiAmount,swapSuiAmount:t.swapSuiAmount.add(t.rightSuiAmount).div(2),exchangeRate:i,rebalanceCount:t.rebalanceCount+1}):null}async calculateDepositSwapAmount(t,e=!1){let n=ee.sqrtPriceX64ToTickIndex(new Oe.default(t.curSqrtPrice)),{ratioA:i,ratioB:r}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:n,adjustBestAmount:e});let o=S(t.input_amount).mul(t.fix_amount_a?i:r),s=S(t.input_amount).sub(o);console.log("1110 ",{fixAmount:o.toString(),swapAmount:s.toString()});let a=t.fix_amount_a;if(s.toFixed(0)==="0")return null;if(t.staking_id){if(we.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||we.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let H=await this.calculateHaedalDepositFixSui({inputSuiAmount:S(t.input_amount),swapSuiAmount:s,lowerTick:t.lowerTick,upperTick:t.upperTick,curSqrtPrice:t.curSqrtPrice,remainRate:t.remainRate?t.remainRate:.01,fixCoinA:t.fix_amount_a,rebalanceCount:0,shouldRequestStake:t.shouldRequestStake,leftSuiAmount:a?new N(s.toFixed(0)):new N(0),rightSuiAmount:a?new N(t.input_amount):new N(s.toFixed(0)),staking_id:t.staking_id});return H?{...H,request_id:t.request_id}:null}throw Error("Only support fix sui")}let u=n<t.lowerTick||n>t.upperTick,l={clmm_pool:t.clmm_pool,curSqrtPrice:t.curSqrtPrice,a2b:a,amount_a:a?new N(t.input_amount):new N(0),amount_b:a?new N(0):new N(t.input_amount),amount_left:a?new N(s.toFixed(0)):new N(0),amount_right:a?new N(t.input_amount):new N(s.toFixed(0)),lowerTick:t.lowerTick,upperTick:t.upperTick,tick_spacing:2,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,useRoute:t.use_route,remainRate:t.remainRate?t.remainRate:.01,priceSplitPoint:t.priceSplitPoint},h=e&&n<=t.upperTick,w=h?await this.calculateRebalance(l):await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,s,t.coinTypeA,t.coinTypeB,!0,t.priceSplitPoint,t.use_route),v=w.after_sqrt_price,T=ee.sqrtPriceX64ToTickIndex(new Oe.default(v));console.log("1110 \u9996\u6B21\u8BA1\u7B97 \u7ED3\u679C: ",{...w,currentTick:T},null,2);let I=T<t.lowerTick||T>t.upperTick;if(u!==I&&!h&&T<=t.upperTick){console.log("1110 \u533A\u95F4\u53D1\u751F\u53D8\u5316, \u518D\u6B21\u8FDB\u884Cswap: ");let{ratioA:H,ratioB:te}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(v));console.log("1110 ",{newAfterRatioA:H,newAfterRatioB:te}),s=S(t.input_amount).sub(S(t.input_amount).mul(t.fix_amount_a?H:te)),l.amount_left=a?new N(s.toFixed(0)):new N(0),l.amount_right=a?new N(t.input_amount):new N(s.toFixed(0)),w=await this.calculateRebalance(l),v=w.after_sqrt_price;let U=ee.sqrtPriceX64ToTickIndex(new Oe.default(v));console.log("1110 \u518D\u6B21\u8BA1\u7B97\u53D8\u5316\u540E: ",{lowerTick:t.lowerTick,upperTick:t.upperTick,currentTick:U,afterSqrtPrice:v})}let{ratioA:x,ratioB:P}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(v));console.log("1110 1",{afterRatioA:x,afterRatioB:P,data:w});let O=P.div(x).sub(r.div(i)).greaterThan("0"),E=w.amount_in&&w.fee_amount?new Oe.default(w.amount_in).add(new Oe.default(w.fee_amount)).toString():w.amount_in,B=w.amount_out,{is_exceed:$}=w;if(T<t.lowerTick)O=!0;else if(T>t.upperTick)O=!1;else{let H=O===a?new Oe.default(S(t.input_amount).sub(E).toString()):new Oe.default(B),te=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,H,O,!0,0,new Oe.default(v)),U=te.coinAmountA,V=te.coinAmountB,F=S(t.fix_amount_a?U.toString():V.toString()).add(E);console.log("1110 \u5B9E\u9645\u6D88\u8017:",{preAmountTotal:F.toString(),fixAmountA:O}),F.greaterThanOrEqualTo(t.input_amount)&&(O=!O)}let Z={swapInAmount:E,swapOutAmount:B,afterSqrtPrice:v,is_exceed:$,fixAmountA:O,routeObj:w.route_obj,request_id:t.request_id,use_Haedal_stake:!1};return console.log(Z),Z}async calculateHaedalDepositSwapAmount(t){let e=ee.sqrtPriceX64ToTickIndex(new Oe.default(t.curSqrtPrice)),{ratioA:n,ratioB:i}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:e});let r=S(t.input_amount).mul(t.fix_amount_a?n:i),o=S(t.input_amount).sub(r);console.log("1110 ",{fixAmount:r.toString(),swapAmount:o.toString()});let s=t.fix_amount_a;if(o.toFixed(0)==="0")return null;if(t.staking_id){if(we.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||we.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let a=await this.calculateHaedalDepositFixSui({inputSuiAmount:S(t.input_amount),swapSuiAmount:o,lowerTick:t.lowerTick,upperTick:t.upperTick,curSqrtPrice:t.curSqrtPrice,remainRate:t.remainRate?t.remainRate:.01,fixCoinA:t.fix_amount_a,rebalanceCount:0,shouldRequestStake:t.shouldRequestStake,leftSuiAmount:s?new N(o.toFixed(0)):new N(0),rightSuiAmount:s?new N(t.input_amount):new N(o.toFixed(0)),staking_id:t.staking_id});return a?{...a,request_id:t.request_id}:null}throw Error("Only support fix sui")}return null}async calculateRebalance(t){let{clmm_pool:e,a2b:n,curSqrtPrice:i,amount_a:r,amount_b:o,lowerTick:s,upperTick:a,amount_left:u,amount_right:l,coinTypeA:h,coinTypeB:w,useRoute:v,priceSplitPoint:T,remainRate:I}=t,x=async(P,O,E)=>{let B=P.plus(O).div(2),$=await this.clmmPreSwap(e,i,n,B,h,w,!0,T,v);if($.amount_out==="0")return $;if($.after_sqrt_price||($.after_sqrt_price=t.curSqrtPrice),$.is_exceed)return O=B,x(P,O,E+1);let Z=n?r.sub($.amount_in):r.add($.amount_out),H=n?o.add($.amount_out):o.sub($.amount_in),te=ee.sqrtPriceX64ToTickIndex(new Oe.default($.after_sqrt_price)),U=$e.estLiquidityAndcoinAmountFromOneAmounts(s,a,new Oe.default(Z.toString()),!0,!0,1,new Oe.default($.after_sqrt_price)),V=new N(U.coinAmountA.toString()),F=new N(U.coinAmountB.toString());if(console.log("1110 swap\u9012\u5F52\u8BA1\u7B97 ",{preRes:$,left:P.toString(),right:O.toString(),mid:B.toString(),afterPoolTickIndex:te,afterA:Z.toString(),afterB:H.toString(),usedA:V.toString(),usedB:toString(),count:E}),V.toString()!==Z.toString())throw new Error("usedA does not match afterA");if(H.lessThan(F))n?P=B:O=B;else{n?O=B:P=B;let K=H.sub(F),C=H.mul(I);if(console.log("1110 \u5269\u4F59\u672A\u4F7F\u7528amount ",{remainingB:K.toString(),maxRemainingB:C.toString(),remainRate:I,count:E}),C.sub(K).greaterThanOrEqualTo(0))return console.log("break"),{...$,remainingB:K}}return P.greaterThan(O)||O.sub(P).lessThan(10)?$:x(P,O,E+1)};return u.greaterThanOrEqualTo(l)?x(new N(0),u,0):x(u,l,0)}async clmmPreSwap(t,e,n,i,r,o,s,a,u,l){if(u)try{let O=await this._sdk.ClmmSDK.RouterV2.getBestRouter(n?r:o,n?o:r,Number(i.toFixed(0)),s,a,"",void 0,void 0,!0,!1,l);if(!O.result)throw new Error("route unavailable");let{result:E}=O,B=e;return E.splitPaths.forEach($=>{let Z=$.basePaths.find(H=>H.poolAddress.toLowerCase()===t.toLowerCase());Z&&(B=Z.afterSqrtPrice.toString())}),{amount_in:E.inputAmount.toString(),amount_out:E.outputAmount.toString(),after_sqrt_price:B,is_exceed:E.isExceed,route_obj:E}}catch{throw new Error("route unavailable")}let{integrate:h,simulationAccount:w}=this.sdk.ClmmSDK.sdkOptions,v=new xi.TransactionBlock,T=[r,o],I=[v.pure(t),v.pure(n),v.pure(s),v.pure(i.toFixed(0))];v.moveCall({target:`${h.published_at}::${zt}::calculate_swap_result`,arguments:I,typeArguments:T});let P=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:v,sender:w.address})).events?.filter(O=>q(O.type).name==="CalculatedSwapResultEvent");return P.length===0?null:P[0].parsedJson.data}async getVault(t,e=!1){let n=this.readPoolFromCache(t,e);if(n)return n;try{let i=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}}),r=Sn.buildPool(i);if(r)return r.staking_id=this.findHaedalStakeId(r.position.coinTypeA,r.position.coinTypeB),this.savePoolToCache(r),r}catch(i){console.log(i)}}async getVaultsConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.vaults,n=`${e}_getMirrorPoolConfigs`,i=this.getCache(n,t);if(i!==void 0)return i;let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::vaults::InitEvent`})).data,o={admin_cap_id:"",vaults_manager_id:"",vaults_pool_handle:""};if(r.length>0){for(let s of r){let a=s.parsedJson;o.admin_cap_id=a.admin_cap_id,o.vaults_manager_id=a.manager_id;let u=await this._sdk.ClmmSDK.fullClient.getObject({id:o.vaults_manager_id,options:{showContent:!0}}),l=Q(u);o.vaults_pool_handle=l.vault_to_pool_maps.fields.id.id;break}this.updateCache(n,o,X)}return o}async getExchangeRateForHaedal(t,e,n){let{haedal:i}=this._sdk.sdkOptions,{simulationAccount:r}=this._sdk.ClmmSDK.sdkOptions;try{let o=new xi.TransactionBlock;e?await this.requestStake(t,n||1e9,o):o.moveCall({target:`${i.published_at}::staking::get_exchange_rate`,typeArguments:[],arguments:[o.object(t)]});let s=await this._sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:e?this._sdk.ClmmSDK.senderAddress:r.address});if(console.log("getExchangeRateForHaedal res: ",s),e){let l=s.events.find(T=>T.type.includes("UserStaked")),{sui_amount:h,st_amount:w}=l.parsedJson,v=S(h).div(w).toString();return console.log({st_amount:w,sui_amount:h,rate:v}),v}let a=s.results[0].returnValues[0][0],u=xc.bcs.de("u64",Uint8Array.from(a))/1e6;return console.log("rate ",xc.bcs.de("u64",Uint8Array.from(a))),u.toString()}catch(o){console.log("getExchangeRateForHaedal",o)}return"0"}requestStakeCoin(t,e,n){let{haedal:i}=this._sdk.sdkOptions;return e.moveCall({target:`${i.published_at}::staking::request_stake_coin`,typeArguments:[],arguments:[e.object((0,$r.normalizeSuiObjectId)("0x5")),e.object(t),n,e.pure((0,$r.normalizeSuiObjectId)("0x0"))]})}async requestStake(t,e,n){let{haedal:i}=this._sdk.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),qr);n=n||new xi.TransactionBlock;let o;if(e>95e10){let[s,...a]=r;a.length>0&&n.mergeCoins(n.object(s.coinObjectId),a.map(u=>n.object(u.coinObjectId))),o=n.splitCoins(n.object(s.coinObjectId),[e])}else o=re.buildCoinForAmount(n,r,BigInt(e),qr,!1,!0).targetCoin;return n.moveCall({target:`${i.published_at}::interface::request_stake`,typeArguments:[],arguments:[n.object((0,$r.normalizeSuiObjectId)("0x5")),n.object(t),o,n.pure((0,$r.normalizeSuiObjectId)("0x0"))]}),n}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},ys=class{static buildOrderLimitEvent(t){let{events:e}=t,n=[];return e&&e.forEach(i=>{let r=q(i.type).name;if(r==="OrderPlacedEvent"||r==="OrderCanceledEvent"||r==="FlashLoanEvent"){let o={digest:t.digest,type:r,timestampMs:t.timestampMs,parsedJson:i.parsedJson};n.push(o)}}),n}static buildLimitOrderInfo(t){let e=Q(t),n=pn(t);if(e&&n)try{let i=q(n),r={pay_coin_type:i.type_arguments[0],target_coin_type:i.type_arguments[1],balance:e.balance,canceled_ts:e.canceled_ts==="18446744073709551615"?0:Number(e.canceled_ts),id:e.id.id,obtained_amount:e.obtained_amount,owner:e.owner,rate:e.rate,expire_ts:Number(e.expire_ts),total_pay_amount:e.total_pay_amount,status:"Running",created_ts:Number(e.created_ts)};if(r.canceled_ts===0)r.status="Running";else if(Number(r.obtained_amount)===0)r.status="Cancelled";else{let o=S(r.total_pay_amount).mul(1e20).div(r.rate).toFixed(0);r.obtained_amount===o?r.status="Completed":r.status="Cancelled"}return r}catch(i){console.log(i)}}static calculateFormatRate(t,e,n){let i=20+e-n;return S(t).mul(S(10).pow(i)).toString()}static calculateRate(t,e,n){let i=20+e-n;return Number(t)/10**i}},my=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getLimitOrderTokenList(){let{limit_order:t}=this._sdk.sdkOptions,{token_list_handle:e}=D(t),{fullClient:n}=this._sdk.ClmmSDK,r=(await n.getDynamicFieldsByPage(e)).data.map(s=>s.objectId);return(await n.batchGetObjects(r,{showContent:!0})).map(s=>{let{fields:a}=s.data.content;return{coin_type:q(a.name.fields.name).full_address,min_trade_amount:Number(a.value)}})}async getLimitOrderPoolList(){let{limit_order:t}=this._sdk.sdkOptions,{rate_orders_indexer_handle:e}=D(t),{fullClient:n}=this._sdk.ClmmSDK,r=(await n.getDynamicFieldsByPage(e)).data.map(s=>s.objectId);return(await n.batchGetObjects(r,{showContent:!0})).map(s=>{let{fields:a}=s.data.content.fields.value,u={pay_coin_type:q(a.pay_coin.fields.name).full_address,target_coin_type:q(a.target_coin.fields.name).full_address,indexer_id:a.indexer_id};return this._sdk.updateCache(`${u.pay_coin_type}_${u.target_coin_type}`,u.indexer_id),u})}async getPoolIndexerId(t,e){let n=this._sdk.getCache(`${t}_${e}`);try{if(n===void 0){let r=(await this.getLimitOrderPoolList()).filter(o=>o.pay_coin_type===t&&o.target_coin_type===e);if(r.length>0)return r[0].indexer_id}}catch{}return n}async getOwnerLimitOrderList(t,e){let{fullClient:n}=this._sdk.ClmmSDK,i={data:[],hasNextPage:!1};try{let r=await this.getUserIndexerHandle(t);if(!r)return i;let o=await n.getDynamicFieldsByPage(r,e);i.hasNextPage=o.hasNextPage,i.nextCursor=o.nextCursor;let s=o.data.map(l=>l.name.value),u=(await n.batchGetObjects(s,{showContent:!0})).map(l=>ys.buildLimitOrderInfo(l)).filter(l=>l!==void 0);i.data=u}catch(r){console.error("Error in getOwnerLimitOrderList:",r)}return i}async getLimitOrderConfigs(){let{package_id:t}=this._sdk.sdkOptions.limit_order,e={rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""},n=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::limit_order::InitEvent`})).data;if(n.length>0){let r=n[0].parsedJson;e.rate_orders_indexer_id=r.rate_orders_indexer_id,e.user_orders_indexer_id=r.user_orders_indexer_id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.rate_orders_indexer_id,options:{showContent:!0}});e.rate_orders_indexer_handle=Q(o).list.fields.id.id;let s=await this._sdk.ClmmSDK.fullClient.getObject({id:e.user_orders_indexer_id,options:{showContent:!0}});e.user_orders_indexer_handle=Q(s).indexer.fields.id.id}let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitFactoryEvent`})).data;if(i.length>0){let r=i[0].parsedJson;e.global_config_id=r.global_config_id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.global_config_id,options:{showContent:!0}}),s=Q(o);e.token_list_handle=s.token_white_list.fields.id.id}return e}async getLimitOrder(t){let{fullClient:e}=this._sdk.ClmmSDK;try{let n=await e.getObject({id:t,options:{showContent:!0}});return ys.buildLimitOrderInfo(n)}catch(n){console.error("Error in getLimitOrder:",n);return}}async getLimitOrderLogs(t){let{fullClient:e}=this._sdk.ClmmSDK;try{let n=await e.queryTransactionBlocks({filter:{ChangedObject:t},options:{showEvents:!0}}),i=[];return n.data.forEach(r=>{i.push(...ys.buildOrderLimitEvent(r))}),i}catch(n){return console.error("Error in getLimitOrderLogs:",n),[]}}buildRateOrdersIndexerType(t){let{limit_order:e}=this._sdk.sdkOptions;return ir(`${e.package_id}::limit_order::RateOrdersIndexer`,[t.pay_coin_type,t.target_coin_type])}async placeLimitOrder(t){let{limit_order:e}=this._sdk.sdkOptions,{user_orders_indexer_id:n,global_config_id:i,rate_orders_indexer_id:r}=D(e),o=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.pay_coin_type),s=new bs.TransactionBlock,a=await this.getPoolIndexerId(t.pay_coin_type,t.target_coin_type),u=re.buildCoinForAmount(s,o,BigInt(t.pay_coin_amount),t.pay_coin_type,!1,!0);return s.moveCall({target:`${e.published_at}::limit_order::${a===void 0?"create_indexer_and_place_limit_order":"place_limit_order"}`,typeArguments:[t.pay_coin_type,t.target_coin_type],arguments:[s.object(i),a===void 0?s.object(r):s.object(a),s.object(n),u.targetCoin,s.pure(ys.calculateFormatRate(t.rate,t.pay_decimal,t.target_decimal)),s.pure(t.expired_ts),s.object(G)]}),s}async cancelOrdersByOwner(t){let{limit_order:e}=this._sdk.sdkOptions,{global_config_id:n}=D(e),i=new bs.TransactionBlock,r=await this.getPoolIndexerId(t.pay_coin_type,t.target_coin_type);if(r===void 0)throw Error("not found indexerId");return t.order_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::limit_order::cancel_order_by_owner`,typeArguments:[t.pay_coin_type,t.target_coin_type],arguments:[i.object(n),i.object(r),i.object(o),i.object(G)]})}),i}async getUserIndexerHandle(t){let{fullClient:e}=this._sdk.ClmmSDK,{limit_order:n}=this._sdk.sdkOptions,i=this.getUserIndexerHandleByCache(t);if(i===void 0){let r=new bs.TransactionBlock;r.moveCall({target:`${n.published_at}::limit_order::get_orders_indexer_by_owner`,typeArguments:[],arguments:[r.pure(t),r.object(D(n).user_orders_indexer_id)]}),i=(await e.devInspectTransactionBlock({transactionBlock:r,sender:this._sdk.ClmmSDK.sdkOptions.simulationAccount.address})).events[0].parsedJson.orders_table_id,i&&this.saveUserIndexerHandleByCache(t,i)}return i}getUserIndexerHandleByCache(t){let e=`getUserIndexerHandleByCache_${t}`;return this.getCache(e)}saveUserIndexerHandleByCache(t,e){let n=`getUserIndexerHandleByCache_${t}`;return this.updateCache(n,e)}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},py=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getFramsPoolList(t="all"){let{package_id:e}=this._sdk.sdkOptions.frams,n={data:[],hasNextPage:!1};try{let i=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::pool::CreatePoolEvent`},t),r=i.data.map(o=>o.parsedJson.pool_id);if(n.hasNextPage=i.hasNextPage,n.nextCursor=i.nextCursor,r.length>0){let o=await this._sdk.ClmmSDK.fullClient.batchGetObjects(r,{showType:!0,showContent:!0});for(let s of o){let a=_s.buildFramsPool(s);a&&(a.rewarders=await this.getFramsRewarderConfig(a.clmm_pool_id,a.rewarders.map(u=>u.reward_coin)),n.data.push(a),this.updateCache(a.id,a))}}}catch(i){console.log("getFramsPoolList error ",i)}return n}async getFramsPool(t,e=!1){let n=this.getCache(t,e);if(n)return n;let i=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}}),r=_s.buildFramsPool(i.data);return r&&(r.rewarders=await this.getFramsRewarderConfig(r.clmm_pool_id,r.rewarders.map(o=>o.reward_coin)),this.updateCache(r.id,r)),r}async getFramsRewarderConfig(t,e,n=!1){let{frams:i}=this._sdk.sdkOptions,r=[];for(let o of e){let s=`getFramsRewarderConfig_${o}_${t}`,a=this.getCache(s,n);if(a)r.push(a);else try{let u=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(i).rewarder_manager_handle,name:{type:"0x1::type_name::TypeName",value:bc(o)}}),{fields:l}=u.data.content.fields.value.fields.value,h={reward_coin:o,last_reward_time:l.last_reward_time,emission_per_second:l.emission_per_second,total_allocate_point:l.total_allocate_point,allocate_point:""},w=l.pools.fields.id.id,v=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:w,name:{type:"0x2::object::ID",value:t}}),{allocate_point:T}=v.data.content.fields.value.fields.value.fields;h.allocate_point=T,this.updateCache(s,h),r.push(h)}catch(u){console.log(u)}}return r}async getOwnedFramsPositionNFTList(t,e=[],n=!1,i=!0,r="all"){let{package_id:o}=this._sdk.sdkOptions.frams,s={data:[],hasNextPage:!1},a={},u=[],l=e.length>0,h=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{filter:{StructType:`${o}::pool::WrappedPositionNFT`},options:{showContent:!0}},r);s.hasNextPage=h.hasNextPage,s.nextCursor=h.nextCursor;for(let w of h.data){let v=_s.buildFramsPositionNFT(w);if(v)if(l){if(e.includes(v.pool_id)){u.push(v);let T=a[v.pool_id];T?T.push(v):T=[v],a[v.pool_id]=T}}else u.push(v)}if(n&&u.length>0){let w=await this.calculateFarmingRewards(u.map(v=>({pool_id:v.pool_id,position_nft_id:v.id,clmm_pool_id:v.clmm_pool_id})),i);l?(a={},u.forEach(v=>{w[v.id]&&(v.rewards=w[v.id]);let I=a[v.pool_id];I?I.push(v):I=[v],a[v.pool_id]=I})):u.forEach(v=>{w[v.id]&&(v.rewards=w[v.id])})}return l?a:(s.data=u,s)}async getFramsPositionNFT(t,e=!0){let n=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),i=_s.buildFramsPositionNFT(n);if(e&&i){let r=await this.calculateFarmingRewards([{pool_id:i.pool_id,position_nft_id:i.id}]);r[i.id]&&(i.rewards=r[i.id])}return i}async calculateFarmingRewards(t,e=!0){let{frams:n}=this._sdk.sdkOptions,i=new Jt.TransactionBlock,{rewarder_manager_id:r,global_config_id:o}=D(n);t.forEach(a=>{i.moveCall({target:`${n.published_at}::router::accumulated_position_rewards`,typeArguments:[],arguments:[i.object(o),i.object(r),i.object(a.pool_id),i.pure(a.position_nft_id,"address"),i.object(G)]})});let s={};try{let a=await this._sdk.ClmmSDK.fullClient.sendSimulationTransaction(i,this._sdk.ClmmSDK.senderAddress,e);console.log({simulateRes:a});let u=a?.events?.filter(l=>q(l.type).name==="AccumulatedPositionRewardsEvent");if(u&&u.length>0)for(let l=0;l<u.length;l+=1){let{parsedJson:h}=u[l],w=[];h.rewards.contents.forEach(v=>{w.push({rewarder_type:q(v.key.name).full_address,rewarder_amount:v.value})}),s[h.wrapped_position_id]=w}}catch(a){console.log(a)}return s}depositPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new Jt.TransactionBlock;let{global_config_id:i,rewarder_manager_id:r}=D(n);return e.moveCall({target:`${n.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(i),e.object(r),e.object(t.pool_id),e.object(t.clmm_position_id),e.object(G)]}),e}async withdrawPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{global_config_id:i,rewarder_manager_id:r}=D(n);return e=e||new Jt.TransactionBlock,e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id},e),e.moveCall({target:`${n.published_at}::router::withdraw`,typeArguments:[],arguments:[e.object(i),e.object(r),e.object(t.pool_id),e.object(t.position_nft_id),e.object(G)]}),e}async batchHarvestPayload(t,e){e=e||new Jt.TransactionBlock;for(let n of t)await this.harvestPayload(n,e);return e}async harvestPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new Jt.TransactionBlock;let i=await this.getFramsPool(t.pool_id,!1);if(i===void 0)throw Error(`not found ${t.pool_id}`);let{global_config_id:r,rewarder_manager_id:o}=D(n);if("collect_fee"in t&&(t.collect_fee||t.clmm_rewarder_types.length>0)){let a=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,a)}return i.rewarders.forEach(a=>{e&&e.moveCall({target:`${n.published_at}::router::harvest`,typeArguments:[a.reward_coin],arguments:[e.object(r),e.object(o),e.object(t.pool_id),e.object(t.position_nft_id),e.object(G)]})}),e}async claimFeeAndClmmReward(t){let e=new Jt.TransactionBlock,n=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);return await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,n),e}async openPositionAddLiquidityStakePaylod(t){let e=new Jt.TransactionBlock,{clmm_pool:n,integrate:i}=this._sdk.ClmmSDK.sdkOptions,r=D(n),o=e.moveCall({target:`${n.published_at}::pool::open_position`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(t.clmm_pool_id),e.pure(Tt(BigInt(t.tick_lower)).toString()),e.pure(Tt(BigInt(t.tick_upper)).toString())]}),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_b),t.coinTypeB,!1);e.moveCall({target:`${i.published_at}::${jn}::add_liquidity_by_fix_coin`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(t.clmm_pool_id),o,a.targetCoin,u.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(G)]});let{frams:l}=this.sdk.sdkOptions,{global_config_id:h,rewarder_manager_id:w}=D(l);return e.moveCall({target:`${l.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(h),e.object(w),e.object(t.pool_id),o,e.object(G)]}),e}async addLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_limit_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_limit_b),t.coinTypeB,!1);if(t.collect_rewarder&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.collect_fee||t.clmm_rewarder_types.length>0){let l=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,l,a.remainCoins,u.remainCoins)}return e.moveCall({target:`${n.published_at}::router::add_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),a.targetCoin,u.targetCoin,e.pure(t.amount_limit_a),e.pure(t.amount_limit_b),e.pure(t.delta_liquidity),e.object(G)]}),e}async addLiquidityFixCoinPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_b),t.coinTypeB,!1);if(t.collect_rewarder&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.collect_fee||t.clmm_rewarder_types.length>0){let l=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,l,a.remainCoins,u.remainCoins)}return e.moveCall({target:`${n.published_at}::router::add_liquidity_fix_coin`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),a.targetCoin,u.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(G)]}),e}async removeLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i);if(t.collect_rewarder&&(!t.unstake||t.close_position)&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.clmm_rewarder_types.length>0){let s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:!1,clmm_rewarder_types:t.clmm_rewarder_types},e,s)}if(t.close_position){if(t.clmm_position_id===void 0)throw Error("close_position need clmm_position_id");e.moveCall({target:`${n.published_at}::router::close_position`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(o.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.pure(t.min_amount_a),e.pure(t.min_amount_b),e.object(G)]})}else e.moveCall({target:`${n.published_at}::router::remove_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.pure(t.delta_liquidity),e.pure(t.min_amount_a),e.pure(t.min_amount_b),e.object(G)]}),t.unstake&&this.withdrawPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id});return e}async buildCollectRewarderAndFeeParams(t,e,n,i,r){i===void 0&&(i=[...n]),r===void 0&&(r=[...n]);let o=Et(t.coinTypeA),s=Et(t.coinTypeB);t.collectFee&&this.collectFeePayload({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},e);let a=[];return t.clmm_rewarder_types.forEach(u=>{switch(Et(u)){case o:a.push(re.buildCoinForAmount(e,i,BigInt(0),u,!1).targetCoin);break;case s:a.push(re.buildCoinForAmount(e,r,BigInt(0),u,!1).targetCoin);break;default:a.push(re.buildCoinForAmount(e,n,BigInt(0),u,!1).targetCoin);break}}),this.collectClmmRewardPayload({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,clmm_rewarder_types:t.clmm_rewarder_types,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,reward_coins:a},e),e}collectFeePayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i);return e.moveCall({target:`${n.published_at}::router::collect_fee`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id)]}),e}async collectClmmRewardPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=t.reward_coins;if(t.clmm_rewarder_types.length>0&&r===void 0){r=[];let a=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);t.clmm_rewarder_types.forEach(u=>{r.push(re.buildCoinForAmount(e,a,BigInt(0),u,!1).targetCoin)})}let o=D(n),s=D(i);return t.clmm_rewarder_types?.forEach((a,u)=>{e&&e.moveCall({target:`${n.published_at}::router::collect_clmm_reward`,typeArguments:[a,t.coinTypeA,t.coinTypeB],arguments:[e.object(o.global_config_id),e.object(s.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.object(s.global_vault_id),r[u],e.object(G)]})}),e}async getFrarmsConfigs(){let{package_id:t}=this._sdk.sdkOptions.frams,e={global_config_id:"",rewarder_manager_id:"",rewarder_manager_handle:""},n=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitConfigEvent`})).data;if(n.length>0){let r=n[0].parsedJson;e.global_config_id=r.global_config_id,e.admin_cap_id=r.admin_cap_id}let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::rewarder::InitRewarderManagerEvent`})).data;if(i.length>0){let r=i[0].parsedJson;e.rewarder_manager_id=r.id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.rewarder_manager_id,options:{showContent:!0}});e.rewarder_manager_handle=o.data.content.fields.rewarders.fields.id.id}return e}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Ut=class{_cache={};_sdkOptions;_launchpad;_ido;_xcetusModule;_xtokenModule;_boosterModule;_makerModule;_clmmSDK;_liquidityStrategy;_vaults;_limitOrder;_farmsModule;constructor(t,e){this._sdkOptions=t,this._clmmSDK=e,this._launchpad=new ty(this),this._ido=new ly(this),this._xcetusModule=new iy(this),this._xtokenModule=new dy(this),this._boosterModule=new ey(this),this._makerModule=new ny(this),this._vaults=new hy(this),this._limitOrder=new my(this),this._farmsModule=new py(this),this._liquidityStrategy=new fy(this),ms(this._sdkOptions)}get ClmmSDK(){return this._clmmSDK}get sdkOptions(){return this._sdkOptions}get Launchpad(){return this._launchpad}get Ido(){return this._ido}get XToken(){return this._xtokenModule}get XCetusModule(){return this._xcetusModule}get BoosterModule(){return this._boosterModule}get MakerModule(){return this._makerModule}get LiquidityStrategy(){return this._liquidityStrategy}get Vaults(){return this._vaults}get LimitOrder(){return this._limitOrder}get Farms(){return this._farmsModule}getVerifySenderAddress(){let{senderAddress:t}=this.ClmmSDK;if(t.length===0||!(0,ff.isValidSuiAddress)(t))throw Error("this clmm config sdk senderAddess is illegal");return t}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}};var Km=require("@msafe/sui3-utils"),sp=require("@mysten/sui.js/client"),zn=ge(require("axios"),1),$i=require("@mysten/sui.js/utils"),Ao=require("@mysten/sui.js/transactions"),Du=require("@mysten/sui.js/transactions"),Io=require("@mysten/sui.js/utils"),Eu=require("buffer"),lp=require("@mysten/sui.js/utils"),Ku=require("@mysten/sui.js/bcs"),Oo=require("@mysten/sui.js/utils");var _f=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");var ju=require("@mysten/sui.js/transactions"),xo=require("@mysten/sui.js/transactions"),Po=require("@mysten/sui.js/utils");var Ln=class extends Error{},ks=class extends Ln{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Ts=class extends Ln{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Cs=class extends Ln{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},gn=class extends Ln{},fr=class extends Ln{constructor(e){super(`Invalid unit ${e}`)}},bt=class extends Ln{},_n=class extends Ln{constructor(){super("Zone is an abstract class")}};var Y="numeric",yn="short",Yt="long",ei={year:Y,month:Y,day:Y},zr={year:Y,month:yn,day:Y},Ic={year:Y,month:yn,day:Y,weekday:yn},Vr={year:Y,month:Yt,day:Y},Gr={year:Y,month:Yt,day:Y,weekday:Yt},Wr={hour:Y,minute:Y},Hr={hour:Y,minute:Y,second:Y},Zr={hour:Y,minute:Y,second:Y,timeZoneName:yn},Xr={hour:Y,minute:Y,second:Y,timeZoneName:Yt},Jr={hour:Y,minute:Y,hourCycle:"h23"},Yr={hour:Y,minute:Y,second:Y,hourCycle:"h23"},Qr={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:yn},eo={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:Yt},to={year:Y,month:Y,day:Y,hour:Y,minute:Y},no={year:Y,month:Y,day:Y,hour:Y,minute:Y,second:Y},io={year:Y,month:yn,day:Y,hour:Y,minute:Y},ro={year:Y,month:yn,day:Y,hour:Y,minute:Y,second:Y},Oc={year:Y,month:yn,day:Y,weekday:yn,hour:Y,minute:Y},oo={year:Y,month:Yt,day:Y,hour:Y,minute:Y,timeZoneName:yn},so={year:Y,month:Yt,day:Y,hour:Y,minute:Y,second:Y,timeZoneName:yn},ao={year:Y,month:Yt,day:Y,weekday:Yt,hour:Y,minute:Y,timeZoneName:Yt},co={year:Y,month:Yt,day:Y,weekday:Yt,hour:Y,minute:Y,second:Y,timeZoneName:Yt};var Gt=class{get type(){throw new _n}get name(){throw new _n}get ianaName(){return this.name}get isUniversal(){throw new _n}offsetName(e,n){throw new _n}formatOffset(e,n){throw new _n}offset(e){throw new _n}equals(e){throw new _n}get isValid(){throw new _n}};var Pc=null,ti=class t extends Gt{static get instance(){return Pc===null&&(Pc=new t),Pc}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:i}){return As(e,n,i)}formatOffset(e,n){return ni(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Is={};function gy(t){return Is[t]||(Is[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"})),Is[t]}var _y={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function yy(t,e){let n=t.format(e).replace(/\u200E/g,""),i=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,o,s,a,u,l,h]=i;return[s,r,o,a,u,l,h]}function wy(t,e){let n=t.formatToParts(e),i=[];for(let r=0;r<n.length;r++){let{type:o,value:s}=n[r],a=_y[o];o==="era"?i[a]=s:de(a)||(i[a]=parseInt(s,10))}return i}var xs={},Ft=class t extends Gt{static create(e){return xs[e]||(xs[e]=new t(e)),xs[e]}static resetCache(){xs={},Is={}}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:n,locale:i}){return As(e,n,i,this.name)}formatOffset(e,n){return ni(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let i=gy(this.name),[r,o,s,a,u,l,h]=i.formatToParts?wy(i,n):yy(i,n);a==="BC"&&(r=-Math.abs(r)+1);let v=hr({year:r,month:o,day:s,hour:u===24?0:u,minute:l,second:h,millisecond:0}),T=+n,I=T%1e3;return T-=I>=0?I:1e3+I,(v-T)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var yf={};function by(t,e={}){let n=JSON.stringify([t,e]),i=yf[n];return i||(i=new Intl.ListFormat(t,e),yf[n]=i),i}var Dc={};function Ec(t,e={}){let n=JSON.stringify([t,e]),i=Dc[n];return i||(i=new Intl.DateTimeFormat(t,e),Dc[n]=i),i}var Mc={};function vy(t,e={}){let n=JSON.stringify([t,e]),i=Mc[n];return i||(i=new Intl.NumberFormat(t,e),Mc[n]=i),i}var Bc={};function ky(t,e={}){let{base:n,...i}=e,r=JSON.stringify([t,i]),o=Bc[r];return o||(o=new Intl.RelativeTimeFormat(t,e),Bc[r]=o),o}var uo=null;function Ty(){return uo||(uo=new Intl.DateTimeFormat().resolvedOptions().locale,uo)}var wf={};function Cy(t){let e=wf[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,wf[t]=e}return e}function Sy(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let n=t.indexOf("-u-");if(n===-1)return[t];{let i,r;try{i=Ec(t).resolvedOptions(),r=t}catch{let u=t.substring(0,n);i=Ec(u).resolvedOptions(),r=u}let{numberingSystem:o,calendar:s}=i;return[r,o,s]}}function Ay(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function xy(t){let e=[];for(let n=1;n<=12;n++){let i=be.utc(2009,n,1);e.push(t(i))}return e}function Iy(t){let e=[];for(let n=1;n<=7;n++){let i=be.utc(2016,11,13+n);e.push(t(i))}return e}function Os(t,e,n,i){let r=t.listingMode();return r==="error"?null:r==="en"?n(e):i(e)}function Oy(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 jc=class{constructor(e,n,i){this.padTo=i.padTo||0,this.floor=i.floor||!1;let{padTo:r,floor:o,...s}=i;if(!n||Object.keys(s).length>0){let a={useGrouping:!1,...i};i.padTo>0&&(a.minimumIntegerDigits=i.padTo),this.inf=vy(e,a)}}format(e){if(this.inf){let n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{let n=this.floor?Math.floor(e):mr(e,3);return Le(n,this.padTo)}}},Nc=class{constructor(e,n,i){this.opts=i,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Ft.create(a).valid?(r=a,this.dt=e):(r="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,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||r,this.dtf=Ec(n,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(n=>{if(n.type==="timeZoneName"){let i=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:i}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Fc=class{constructor(e,n,i){this.opts={style:"long",...i},!n&&Ps()&&(this.rtf=ky(e,i))}format(e,n){return this.rtf?this.rtf.format(e,n):bf(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},Py={firstDay:1,minimalDays:4,weekend:[6,7]},xe=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,i,r,o=!1){let s=e||Ce.defaultLocale,a=s||(o?"en-US":Ty()),u=n||Ce.defaultNumberingSystem,l=i||Ce.defaultOutputCalendar,h=lo(r)||Ce.defaultWeekSettings;return new t(a,u,l,h,s)}static resetCache(){uo=null,Dc={},Mc={},Bc={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:i,weekSettings:r}={}){return t.create(e,n,i,r)}constructor(e,n,i,r,o){let[s,a,u]=Sy(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=i||u||null,this.weekSettings=r,this.intl=Ay(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=Oy(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"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,lo(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,n=!1){return Os(this,e,Rc,()=>{let i=n?{month:e,day:"numeric"}:{month:e},r=n?"format":"standalone";return this.monthsCache[r][e]||(this.monthsCache[r][e]=xy(o=>this.extract(o,i,"month"))),this.monthsCache[r][e]})}weekdays(e,n=!1){return Os(this,e,qc,()=>{let i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Iy(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return Os(this,void 0,()=>Lc,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[be.utc(2016,11,13,9),be.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Os(this,e,$c,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[be.utc(-40,1,1),be.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,n,i){let r=this.dtFormatter(e,n),o=r.formatToParts(),s=o.find(a=>a.type.toLowerCase()===i);return s?s.value:null}numberFormatter(e={}){return new jc(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Nc(e,this.intl,n)}relFormatter(e={}){return new Fc(this.intl,this.isEnglish(),e)}listFormatter(e={}){return by(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:Ds()?Cy(this.locale):Py}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 Kc=null,Ct=class t extends Gt{static get utcInstance(){return Kc===null&&(Kc=new t(0)),Kc}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(Pi(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ni(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ni(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ni(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var pr=class extends Gt{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 wn(t,e){let n;if(de(t)||t===null)return e;if(t instanceof Gt)return t;if(vf(t)){let i=t.toLowerCase();return i==="default"?e:i==="local"||i==="system"?ti.instance:i==="utc"||i==="gmt"?Ct.utcInstance:Ct.parseSpecifier(i)||Ft.create(t)}else return In(t)?Ct.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new pr(t)}var kf=()=>Date.now(),Tf="system",Cf=null,Sf=null,Af=null,xf=60,If,Of=null,Ce=class{static get now(){return kf}static set now(e){kf=e}static set defaultZone(e){Tf=e}static get defaultZone(){return wn(Tf,ti.instance)}static get defaultLocale(){return Cf}static set defaultLocale(e){Cf=e}static get defaultNumberingSystem(){return Sf}static set defaultNumberingSystem(e){Sf=e}static get defaultOutputCalendar(){return Af}static set defaultOutputCalendar(e){Af=e}static get defaultWeekSettings(){return Of}static set defaultWeekSettings(e){Of=lo(e)}static get twoDigitCutoffYear(){return xf}static set twoDigitCutoffYear(e){xf=e%100}static get throwOnInvalid(){return If}static set throwOnInvalid(e){If=e}static resetCaches(){xe.resetCache(),Ft.resetCache()}};var St=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var Pf=[0,31,59,90,120,151,181,212,243,273,304,334],Df=[0,31,60,91,121,152,182,213,244,274,305,335];function an(t,e){return new St("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Es(t,e,n){let i=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&i.setUTCFullYear(i.getUTCFullYear()-1900);let r=i.getUTCDay();return r===0?7:r}function Ef(t,e,n){return n+(Ei(t)?Df:Pf)[e-1]}function Mf(t,e){let n=Ei(t)?Df:Pf,i=n.findIndex(o=>o<e),r=e-n[i];return{month:i+1,day:r}}function Ms(t,e){return(t-e+7)%7+1}function fo(t,e=4,n=1){let{year:i,month:r,day:o}=t,s=Ef(i,r,o),a=Ms(Es(i,r,o),n),u=Math.floor((s-a+14-e)/7),l;return u<1?(l=i-1,u=Di(l,e,n)):u>Di(i,e,n)?(l=i+1,u=1):l=i,{weekYear:l,weekNumber:u,weekday:a,...mo(t)}}function zc(t,e=4,n=1){let{weekYear:i,weekNumber:r,weekday:o}=t,s=Ms(Es(i,1,e),n),a=ii(i),u=r*7+o-s-7+e,l;u<1?(l=i-1,u+=ii(l)):u>a?(l=i+1,u-=ii(i)):l=i;let{month:h,day:w}=Mf(l,u);return{year:l,month:h,day:w,...mo(t)}}function Bs(t){let{year:e,month:n,day:i}=t,r=Ef(e,n,i);return{year:e,ordinal:r,...mo(t)}}function Vc(t){let{year:e,ordinal:n}=t,{month:i,day:r}=Mf(e,n);return{year:e,month:i,day:r,...mo(t)}}function Gc(t,e){if(!de(t.localWeekday)||!de(t.localWeekNumber)||!de(t.localWeekYear)){if(!de(t.weekday)||!de(t.weekNumber)||!de(t.weekYear))throw new gn("Cannot mix locale-based week fields with ISO-based week fields");return de(t.localWeekday)||(t.weekday=t.localWeekday),de(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),de(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 Bf(t,e=4,n=1){let i=ho(t.weekYear),r=Qt(t.weekNumber,1,Di(t.weekYear,e,n)),o=Qt(t.weekday,1,7);return i?r?o?!1:an("weekday",t.weekday):an("week",t.weekNumber):an("weekYear",t.weekYear)}function jf(t){let e=ho(t.year),n=Qt(t.ordinal,1,ii(t.year));return e?n?!1:an("ordinal",t.ordinal):an("year",t.year)}function Wc(t){let e=ho(t.year),n=Qt(t.month,1,12),i=Qt(t.day,1,gr(t.year,t.month));return e?n?i?!1:an("day",t.day):an("month",t.month):an("year",t.year)}function Hc(t){let{hour:e,minute:n,second:i,millisecond:r}=t,o=Qt(e,0,23)||e===24&&n===0&&i===0&&r===0,s=Qt(n,0,59),a=Qt(i,0,59),u=Qt(r,0,999);return o?s?a?u?!1:an("millisecond",r):an("second",i):an("minute",n):an("hour",e)}function de(t){return typeof t>"u"}function In(t){return typeof t=="number"}function ho(t){return typeof t=="number"&&t%1===0}function vf(t){return typeof t=="string"}function Ff(t){return Object.prototype.toString.call(t)==="[object Date]"}function Ps(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ds(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Rf(t){return Array.isArray(t)?t:[t]}function Zc(t,e,n){if(t.length!==0)return t.reduce((i,r)=>{let o=[e(r),r];return i&&n(i[0],o[0])===i[0]?i:o},null)[1]}function qf(t,e){return e.reduce((n,i)=>(n[i]=t[i],n),{})}function ri(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function lo(t){if(t==null)return null;if(typeof t!="object")throw new bt("Week settings must be an object");if(!Qt(t.firstDay,1,7)||!Qt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Qt(e,1,7)))throw new bt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Qt(t,e,n){return ho(t)&&t>=e&&t<=n}function Dy(t,e){return t-e*Math.floor(t/e)}function Le(t,e=2){let n=t<0,i;return n?i="-"+(""+-t).padStart(e,"0"):i=(""+t).padStart(e,"0"),i}function $n(t){if(!(de(t)||t===null||t===""))return parseInt(t,10)}function oi(t){if(!(de(t)||t===null||t===""))return parseFloat(t)}function po(t){if(!(de(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function mr(t,e,n=!1){let i=10**e;return(n?Math.trunc:Math.round)(t*i)/i}function Ei(t){return t%4===0&&(t%100!==0||t%400===0)}function ii(t){return Ei(t)?366:365}function gr(t,e){let n=Dy(e-1,12)+1,i=t+(e-n)/12;return n===2?Ei(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function hr(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 Nf(t,e,n){return-Ms(Es(t,1,e),n)+e-1}function Di(t,e=4,n=1){let i=Nf(t,e,n),r=Nf(t+1,e,n);return(ii(t)-i+r)/7}function go(t){return t>99?t:t>Ce.twoDigitCutoffYear?1900+t:2e3+t}function As(t,e,n,i=null){let r=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};i&&(o.timeZone=i);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(n,s).formatToParts(r).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function Pi(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);let i=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-i:i;return n*60+r}function Xc(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new bt(`Invalid unit value ${t}`);return e}function _r(t,e){let n={};for(let i in t)if(ri(t,i)){let r=t[i];if(r==null)continue;n[e(i)]=Xc(r)}return n}function ni(t,e){let n=Math.trunc(Math.abs(t/60)),i=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${Le(n,2)}:${Le(i,2)}`;case"narrow":return`${r}${n}${i>0?`:${i}`:""}`;case"techie":return`${r}${Le(n,2)}${Le(i,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function mo(t){return qf(t,["hour","minute","second","millisecond"])}var Ey=["January","February","March","April","May","June","July","August","September","October","November","December"],Jc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],My=["J","F","M","A","M","J","J","A","S","O","N","D"];function Rc(t){switch(t){case"narrow":return[...My];case"short":return[...Jc];case"long":return[...Ey];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 Yc=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Qc=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],By=["M","T","W","T","F","S","S"];function qc(t){switch(t){case"narrow":return[...By];case"short":return[...Qc];case"long":return[...Yc];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Lc=["AM","PM"],jy=["Before Christ","Anno Domini"],Ny=["BC","AD"],Fy=["B","A"];function $c(t){switch(t){case"narrow":return[...Fy];case"short":return[...Ny];case"long":return[...jy];default:return null}}function Lf(t){return Lc[t.hour<12?0:1]}function $f(t,e){return qc(e)[t.weekday-1]}function Uf(t,e){return Rc(e)[t.month-1]}function Kf(t,e){return $c(e)[t.year<0?0:1]}function bf(t,e,n="always",i=!1){let r={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(n==="auto"&&o){let w=t==="days";switch(e){case 1:return w?"tomorrow":`next ${r[t][0]}`;case-1:return w?"yesterday":`last ${r[t][0]}`;case 0:return w?"today":`this ${r[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=r[t],h=i?u?l[1]:l[2]||l[1]:u?r[t][0]:t;return s?`${a} ${h} ago`:`in ${a} ${h}`}function zf(t,e){let n="";for(let i of t)i.literal?n+=i.val:n+=e(i.val);return n}var Ry={D:ei,DD:zr,DDD:Vr,DDDD:Gr,t:Wr,tt:Hr,ttt:Zr,tttt:Xr,T:Jr,TT:Yr,TTT:Qr,TTTT:eo,f:to,ff:io,fff:oo,ffff:ao,F:no,FF:ro,FFF:so,FFFF:co},At=class t{static create(e,n={}){return new t(e,n)}static parseFormat(e){let n=null,i="",r=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(i.length>0&&o.push({literal:r||/^\s+$/.test(i),val:i}),n=null,i="",r=!r):r||a===n?i+=a:(i.length>0&&o.push({literal:/^\s+$/.test(i),val:i}),i=a,n=a)}return i.length>0&&o.push({literal:r||/^\s+$/.test(i),val:i}),o}static macroTokenToFormatOpts(e){return Ry[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Le(e,n);let i={...this.opts};return n>0&&(i.padTo=n),this.loc.numberFormatter(i).format(e)}formatDateTimeFromString(e,n){let i=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(T,I)=>this.loc.extract(e,T,I),s=T=>e.isOffsetFixed&&e.offset===0&&T.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,T.format):"",a=()=>i?Lf(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(T,I)=>i?Uf(e,T):o(I?{month:T}:{month:T,day:"numeric"},"month"),l=(T,I)=>i?$f(e,T):o(I?{weekday:T}:{weekday:T,month:"long",day:"numeric"},"weekday"),h=T=>{let I=t.macroTokenToFormatOpts(T);return I?this.formatWithSystemDefault(e,I):T},w=T=>i?Kf(e,T):o({era:T},"era"),v=T=>{switch(T){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 a();case"d":return r?o({day:"numeric"},"day"):this.num(e.day);case"dd":return r?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return r?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return r?o({month:"numeric"},"month"):this.num(e.month);case"MM":return r?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return r?o({year:"numeric"},"year"):this.num(e.year);case"yy":return r?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return w("short");case"GG":return w("long");case"GGGGG":return w("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 h(T)}};return zf(t.parseFormat(n),v)}formatDurationFromString(e,n){let i=u=>{switch(u[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}},r=u=>l=>{let h=i(l);return h?this.num(u.get(h),l.length):l},o=t.parseFormat(n),s=o.reduce((u,{literal:l,val:h})=>l?u:u.concat(h),[]),a=e.shiftTo(...s.map(i).filter(u=>u));return zf(o,r(a))}};var Gf=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wr(...t){let e=t.reduce((n,i)=>n+i.source,"");return RegExp(`^${e}$`)}function br(...t){return e=>t.reduce(([n,i,r],o)=>{let[s,a,u]=o(e,r);return[{...n,...s},a||i,u]},[{},null,1]).slice(0,2)}function vr(t,...e){if(t==null)return[null,null];for(let[n,i]of e){let r=n.exec(t);if(r)return i(r)}return[null,null]}function Wf(...t){return(e,n)=>{let i={},r;for(r=0;r<t.length;r++)i[t[r]]=$n(e[n+r]);return[i,null,n+r]}}var Hf=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,qy=`(?:${Hf.source}?(?:\\[(${Gf.source})\\])?)?`,eu=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Zf=RegExp(`${eu.source}${qy}`),tu=RegExp(`(?:T${Zf.source})?`),Ly=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,$y=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Uy=/(\d{4})-?(\d{3})/,Ky=Wf("weekYear","weekNumber","weekDay"),zy=Wf("year","ordinal"),Vy=/(\d{4})-(\d\d)-(\d\d)/,Xf=RegExp(`${eu.source} ?(?:${Hf.source}|(${Gf.source}))?`),Gy=RegExp(`(?: ${Xf.source})?`);function yr(t,e,n){let i=t[e];return de(i)?n:$n(i)}function Wy(t,e){return[{year:yr(t,e),month:yr(t,e+1,1),day:yr(t,e+2,1)},null,e+3]}function kr(t,e){return[{hours:yr(t,e,0),minutes:yr(t,e+1,0),seconds:yr(t,e+2,0),milliseconds:po(t[e+3])},null,e+4]}function _o(t,e){let n=!t[e]&&!t[e+1],i=Pi(t[e+1],t[e+2]),r=n?null:Ct.instance(i);return[{},r,e+3]}function yo(t,e){let n=t[e]?Ft.create(t[e]):null;return[{},n,e+1]}var Hy=RegExp(`^T?${eu.source}$`),Zy=/^-?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 Xy(t){let[e,n,i,r,o,s,a,u,l]=t,h=e[0]==="-",w=u&&u[0]==="-",v=(T,I=!1)=>T!==void 0&&(I||T&&h)?-T:T;return[{years:v(oi(n)),months:v(oi(i)),weeks:v(oi(r)),days:v(oi(o)),hours:v(oi(s)),minutes:v(oi(a)),seconds:v(oi(u),u==="-0"),milliseconds:v(po(l),w)}]}var Jy={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 nu(t,e,n,i,r,o,s){let a={year:e.length===2?go($n(e)):$n(e),month:Jc.indexOf(n)+1,day:$n(i),hour:$n(r),minute:$n(o)};return s&&(a.second=$n(s)),t&&(a.weekday=t.length>3?Yc.indexOf(t)+1:Qc.indexOf(t)+1),a}var Yy=/^(?:(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 Qy(t){let[,e,n,i,r,o,s,a,u,l,h,w]=t,v=nu(e,r,i,n,o,s,a),T;return u?T=Jy[u]:l?T=0:T=Pi(h,w),[v,new Ct(T)]}function ew(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var tw=/^(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$/,nw=/^(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$/,iw=/^(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 Vf(t){let[,e,n,i,r,o,s,a]=t;return[nu(e,r,i,n,o,s,a),Ct.utcInstance]}function rw(t){let[,e,n,i,r,o,s,a]=t;return[nu(e,a,n,i,r,o,s),Ct.utcInstance]}var ow=wr(Ly,tu),sw=wr($y,tu),aw=wr(Uy,tu),cw=wr(Zf),Jf=br(Wy,kr,_o,yo),uw=br(Ky,kr,_o,yo),lw=br(zy,kr,_o,yo),dw=br(kr,_o,yo);function Yf(t){return vr(t,[ow,Jf],[sw,uw],[aw,lw],[cw,dw])}function Qf(t){return vr(ew(t),[Yy,Qy])}function eh(t){return vr(t,[tw,Vf],[nw,Vf],[iw,rw])}function th(t){return vr(t,[Zy,Xy])}var fw=br(kr);function nh(t){return vr(t,[Hy,fw])}var hw=wr(Vy,Gy),mw=wr(Xf),pw=br(kr,_o,yo);function ih(t){return vr(t,[hw,Jf],[mw,pw])}var rh="Invalid Duration",sh={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}},gw={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},...sh},cn=146097/400,Tr=146097/4800,_w={years:{quarters:4,months:12,weeks:cn/7,days:cn,hours:cn*24,minutes:cn*24*60,seconds:cn*24*60*60,milliseconds:cn*24*60*60*1e3},quarters:{months:3,weeks:cn/28,days:cn/4,hours:cn*24/4,minutes:cn*24*60/4,seconds:cn*24*60*60/4,milliseconds:cn*24*60*60*1e3/4},months:{weeks:Tr/7,days:Tr,hours:Tr*24,minutes:Tr*24*60,seconds:Tr*24*60*60,milliseconds:Tr*24*60*60*1e3},...sh},Mi=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],yw=Mi.slice(0).reverse();function si(t,e,n=!1){let i={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new Pe(i)}function ah(t,e){let n=e.milliseconds??0;for(let i of yw.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function oh(t,e){let n=ah(t,e)<0?-1:1;Mi.reduceRight((i,r)=>{if(de(e[r]))return i;if(i){let o=e[i]*n,s=t[r][i],a=Math.floor(o/s);e[r]+=a*n,e[i]-=a*s*n}return r},null),Mi.reduce((i,r)=>{if(de(e[r]))return i;if(i){let o=e[i]%1;e[i]-=o,e[r]+=o*t[i][r]}return r},null)}function ww(t){let e={};for(let[n,i]of Object.entries(t))i!==0&&(e[n]=i);return e}var Pe=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,i=n?_w:gw;e.matrix&&(i=e.matrix),this.values=e.values,this.loc=e.loc||xe.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=i,this.isLuxonDuration=!0}static fromMillis(e,n){return t.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new bt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:_r(e,t.normalizeUnit),loc:xe.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(In(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new bt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[i]=th(e);return i?t.fromObject(i,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){let[i]=nh(e);return i?t.fromObject(i,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the Duration is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new Cs(i);return new t({invalid:i})}static normalizeUnit(e){let n={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(!n)throw new fr(e);return n}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,n={}){let i={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?At.create(this.loc,i).formatDurationFromString(this,e):rh}toHuman(e={}){if(!this.isValid)return rh;let n=Mi.map(i=>{let r=this.values[i];return de(r)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:i.slice(0,-1)}).format(r)}).filter(i=>i);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}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+=mr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},be.fromMillis(n,{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?ah(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e),i={};for(let r of Mi)(ri(n.values,r)||ri(this.values,r))&&(i[r]=n.get(r)+this.get(r));return si(this,{values:i},!0)}minus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let n={};for(let i of Object.keys(this.values))n[i]=Xc(e(this.values[i],i));return si(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,..._r(e,t.normalizeUnit)};return si(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:i,matrix:r}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:i};return si(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return oh(this.matrix,e),si(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=ww(this.normalize().shiftToAll().toObject());return si(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 n={},i={},r=this.toObject(),o;for(let s of Mi)if(e.indexOf(s)>=0){o=s;let a=0;for(let l in i)a+=this.matrix[l][s]*i[l],i[l]=0;In(r[s])&&(a+=r[s]);let u=Math.trunc(a);n[s]=u,i[s]=(a*1e3-u*1e3)/1e3}else In(r[s])&&(i[s]=r[s]);for(let s in i)i[s]!==0&&(n[o]+=s===o?i[s]:i[s]/this.matrix[o][s]);return oh(this.matrix,n),si(this,{values:n},!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 n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return si(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 n(i,r){return i===void 0||i===0?r===void 0||r===0:i===r}for(let i of Mi)if(!n(this.values[i],e.values[i]))return!1;return!0}};var Cr="Invalid Interval";function bw(t,e){return!t||!t.isValid?Un.invalid("missing or invalid start"):!e||!e.isValid?Un.invalid("missing or invalid end"):e<t?Un.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 Un=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the Interval is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new Ts(i);return new t({invalid:i})}static fromDateTimes(e,n){let i=Sr(e),r=Sr(n),o=bw(i,r);return o??new t({start:i,end:r})}static after(e,n){let i=Pe.fromDurationLike(n),r=Sr(e);return t.fromDateTimes(r,r.plus(i))}static before(e,n){let i=Pe.fromDurationLike(n),r=Sr(e);return t.fromDateTimes(r.minus(i),r)}static fromISO(e,n){let[i,r]=(e||"").split("/",2);if(i&&r){let o,s;try{o=be.fromISO(i,n),s=o.isValid}catch{s=!1}let a,u;try{a=be.fromISO(r,n),u=a.isValid}catch{u=!1}if(s&&u)return t.fromDateTimes(o,a);if(s){let l=Pe.fromISO(r,n);if(l.isValid)return t.after(o,l)}else if(u){let l=Pe.fromISO(i,n);if(l.isValid)return t.before(a,l)}}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",n){if(!this.isValid)return NaN;let i=this.start.startOf(e,n),r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:i.locale}):r=this.end,r=r.startOf(e,n),Math.floor(r.diff(i,e).get(e))+(r.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:n}={}){return this.isValid?t.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];let n=e.map(Sr).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),i=[],{s:r}=this,o=0;for(;r<this.e;){let s=n[o]||this.e,a=+s>+this.e?this.e:s;i.push(t.fromDateTimes(r,a)),r=a,o+=1}return i}splitBy(e){let n=Pe.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:i}=this,r=1,o,s=[];for(;i<this.e;){let a=this.start.plus(n.mapUnits(u=>u*r));o=+a>+this.e?this.e:a,s.push(t.fromDateTimes(i,o)),i=o,r+=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 n=this.s>e.s?this.s:e.s,i=this.e<e.e?this.e:e.e;return n>=i?null:t.fromDateTimes(n,i)}union(e){if(!this.isValid)return this;let n=this.s<e.s?this.s:e.s,i=this.e>e.e?this.e:e.e;return t.fromDateTimes(n,i)}static merge(e){let[n,i]=e.sort((r,o)=>r.s-o.s).reduce(([r,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[r,o.union(s)]:[r.concat([o]),s]:[r,s],[[],null]);return i&&n.push(i),n}static xor(e){let n=null,i=0,r=[],o=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((u,l)=>u.time-l.time);for(let u of a)i+=u.type==="s"?1:-1,i===1?n=u.time:(n&&+n!=+u.time&&r.push(t.fromDateTimes(n,u.time)),n=null);return t.merge(r)}difference(...e){return t.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Cr}[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=ei,n={}){return this.isValid?At.create(this.s.loc.clone(n),e).formatInterval(this):Cr}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Cr}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Cr}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Cr}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:Cr}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):Pe.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var Kn=class{static hasDST(e=Ce.defaultZone){let n=be.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Ft.isValidZone(e)}static normalizeZone(e){return wn(e,Ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||xe.create(n,i,o)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||xe.create(n,i,o)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||xe.create(n,i,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||xe.create(n,i,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return xe.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return xe.create(n,null,"gregory").eras(e)}static features(){return{relative:Ps(),localeWeek:Ds()}}};function ch(t,e){let n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),i=n(e)-n(t);return Math.floor(Pe.fromMillis(i).as("days"))}function vw(t,e,n){let i=[["years",(u,l)=>l.year-u.year],["quarters",(u,l)=>l.quarter-u.quarter+(l.year-u.year)*4],["months",(u,l)=>l.month-u.month+(l.year-u.year)*12],["weeks",(u,l)=>{let h=ch(u,l);return(h-h%7)/7}],["days",ch]],r={},o=t,s,a;for(let[u,l]of i)n.indexOf(u)>=0&&(s=u,r[u]=l(t,e),a=o.plus(r),a>e?(r[u]--,t=o.plus(r),t>e&&(a=t,r[u]--,t=o.plus(r))):t=a);return[t,r,a,s]}function uh(t,e,n,i){let[r,o,s,a]=vw(t,e,n),u=e-r,l=n.filter(w=>["hours","minutes","seconds","milliseconds"].indexOf(w)>=0);l.length===0&&(s<e&&(s=r.plus({[a]:1})),s!==r&&(o[a]=(o[a]||0)+u/(s-r)));let h=Pe.fromObject(o,i);return l.length>0?Pe.fromMillis(u,i).shiftTo(...l).plus(h):h}var iu={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"},lh={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]},kw=iu.hanidec.replace(/[\[|\]]/g,"").split("");function dh(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(t[n].search(iu.hanidec)!==-1)e+=kw.indexOf(t[n]);else for(let r in lh){let[o,s]=lh[r];i>=o&&i<=s&&(e+=i-o)}}return parseInt(e,10)}else return e}function un({numberingSystem:t},e=""){return new RegExp(`${iu[t||"latn"]}${e}`)}var Tw="missing Intl.DateTimeFormat.formatToParts support";function Se(t,e=n=>n){return{regex:t,deser:([n])=>e(dh(n))}}var Cw="\xA0",mh=`[ ${Cw}]`,ph=new RegExp(mh,"g");function Sw(t){return t.replace(/\./g,"\\.?").replace(ph,mh)}function fh(t){return t.replace(/\./g,"").replace(ph," ").toLowerCase()}function bn(t,e){return t===null?null:{regex:RegExp(t.map(Sw).join("|")),deser:([n])=>t.findIndex(i=>fh(n)===fh(i))+e}}function hh(t,e){return{regex:t,deser:([,n,i])=>Pi(n,i),groups:e}}function js(t){return{regex:t,deser:([e])=>e}}function Aw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function xw(t,e){let n=un(e),i=un(e,"{2}"),r=un(e,"{3}"),o=un(e,"{4}"),s=un(e,"{6}"),a=un(e,"{1,2}"),u=un(e,"{1,3}"),l=un(e,"{1,6}"),h=un(e,"{1,9}"),w=un(e,"{2,4}"),v=un(e,"{4,6}"),T=P=>({regex:RegExp(Aw(P.val)),deser:([O])=>O,literal:!0}),x=(P=>{if(t.literal)return T(P);switch(P.val){case"G":return bn(e.eras("short"),0);case"GG":return bn(e.eras("long"),0);case"y":return Se(l);case"yy":return Se(w,go);case"yyyy":return Se(o);case"yyyyy":return Se(v);case"yyyyyy":return Se(s);case"M":return Se(a);case"MM":return Se(i);case"MMM":return bn(e.months("short",!0),1);case"MMMM":return bn(e.months("long",!0),1);case"L":return Se(a);case"LL":return Se(i);case"LLL":return bn(e.months("short",!1),1);case"LLLL":return bn(e.months("long",!1),1);case"d":return Se(a);case"dd":return Se(i);case"o":return Se(u);case"ooo":return Se(r);case"HH":return Se(i);case"H":return Se(a);case"hh":return Se(i);case"h":return Se(a);case"mm":return Se(i);case"m":return Se(a);case"q":return Se(a);case"qq":return Se(i);case"s":return Se(a);case"ss":return Se(i);case"S":return Se(u);case"SSS":return Se(r);case"u":return js(h);case"uu":return js(a);case"uuu":return Se(n);case"a":return bn(e.meridiems(),0);case"kkkk":return Se(o);case"kk":return Se(w,go);case"W":return Se(a);case"WW":return Se(i);case"E":case"c":return Se(n);case"EEE":return bn(e.weekdays("short",!1),1);case"EEEE":return bn(e.weekdays("long",!1),1);case"ccc":return bn(e.weekdays("short",!0),1);case"cccc":return bn(e.weekdays("long",!0),1);case"Z":case"ZZ":return hh(new RegExp(`([+-]${a.source})(?::(${i.source}))?`),2);case"ZZZ":return hh(new RegExp(`([+-]${a.source})(${i.source})?`),2);case"z":return js(/[a-z_+-/]{1,256}?/i);case" ":return js(/[^\S\n\r]/);default:return T(P)}})(t)||{invalidReason:Tw};return x.token=t,x}var Iw={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 Ow(t,e,n){let{type:i,value:r}=t;if(i==="literal"){let u=/^\s+$/.test(r);return{literal:!u,val:u?" ":r}}let o=e[i],s=i;i==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=n.hour12?"hour12":"hour24");let a=Iw[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Pw(t){return[`^${t.map(n=>n.regex).reduce((n,i)=>`${n}(${i.source})`,"")}$`,t]}function Dw(t,e,n){let i=t.match(e);if(i){let r={},o=1;for(let s in n)if(ri(n,s)){let a=n[s],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(i.slice(o,o+u))),o+=u}return[i,r]}else return[i,{}]}function Ew(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}},n=null,i;return de(t.z)||(n=Ft.create(t.z)),de(t.Z)||(n||(n=new Ct(t.Z)),i=t.Z),de(t.q)||(t.M=(t.q-1)*3+1),de(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),de(t.u)||(t.S=po(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),n,i]}var ru=null;function Mw(){return ru||(ru=be.fromMillis(1555555555555)),ru}function Bw(t,e){if(t.literal)return t;let n=At.macroTokenToFormatOpts(t.val),i=au(n,e);return i==null||i.includes(void 0)?t:i}function ou(t,e){return Array.prototype.concat(...t.map(n=>Bw(n,e)))}function su(t,e,n){let i=ou(At.parseFormat(n),t),r=i.map(s=>xw(s,t)),o=r.find(s=>s.invalidReason);if(o)return{input:e,tokens:i,invalidReason:o.invalidReason};{let[s,a]=Pw(r),u=RegExp(s,"i"),[l,h]=Dw(e,u,a),[w,v,T]=h?Ew(h):[null,null,void 0];if(ri(h,"a")&&ri(h,"H"))throw new gn("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:i,regex:u,rawMatches:l,matches:h,result:w,zone:v,specificOffset:T}}}function gh(t,e,n){let{result:i,zone:r,specificOffset:o,invalidReason:s}=su(t,e,n);return[i,r,o,s]}function au(t,e){if(!t)return null;let i=At.create(e,t).dtFormatter(Mw()),r=i.formatToParts(),o=i.resolvedOptions();return r.map(s=>Ow(s,t,o))}var cu="Invalid DateTime",_h=864e13;function Ns(t){return new St("unsupported zone",`the zone "${t.name}" is not supported`)}function uu(t){return t.weekData===null&&(t.weekData=fo(t.c)),t.weekData}function lu(t){return t.localWeekData===null&&(t.localWeekData=fo(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Bi(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new be({...n,...e,old:n})}function Ch(t,e,n){let i=t-e*60*1e3,r=n.offset(i);if(e===r)return[i,e];i-=(r-e)*60*1e3;let o=n.offset(i);return r===o?[i,r]:[t-Math.min(r,o)*60*1e3,Math.max(r,o)]}function Fs(t,e){t+=e*60*1e3;let n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function qs(t,e,n){return Ch(hr(t),e,n)}function yh(t,e){let n=t.o,i=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:i,month:r,day:Math.min(t.c.day,gr(i,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=Pe.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"),a=hr(o),[u,l]=Ch(a,n,t.zone);return s!==0&&(u+=s,l=t.zone.offset(u)),{ts:u,o:l}}function wo(t,e,n,i,r,o){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let u=e||a,l=be.fromObject(t,{...n,zone:u,specificOffset:o});return s?l:l.setZone(a)}else return be.invalid(new St("unparsable",`the input "${r}" can't be parsed as ${i}`))}function Rs(t,e,n=!0){return t.isValid?At.create(xe.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function du(t,e){let n=t.c.year>9999||t.c.year<0,i="";return n&&t.c.year>=0&&(i+="+"),i+=Le(t.c.year,n?6:4),e?(i+="-",i+=Le(t.c.month),i+="-",i+=Le(t.c.day)):(i+=Le(t.c.month),i+=Le(t.c.day)),i}function wh(t,e,n,i,r,o){let s=Le(t.c.hour);return e?(s+=":",s+=Le(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=Le(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=Le(t.c.second),(t.c.millisecond!==0||!i)&&(s+=".",s+=Le(t.c.millisecond,3))),r&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Le(Math.trunc(-t.o/60)),s+=":",s+=Le(Math.trunc(-t.o%60))):(s+="+",s+=Le(Math.trunc(t.o/60)),s+=":",s+=Le(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var Sh={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},jw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Nw={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Ah=["year","month","day","hour","minute","second","millisecond"],Fw=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Rw=["year","ordinal","hour","minute","second","millisecond"];function qw(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 fr(t);return e}function bh(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return qw(t)}}function vh(t,e){let n=wn(e.zone,Ce.defaultZone),i=xe.fromObject(e),r=Ce.now(),o,s;if(de(t.year))o=r;else{for(let l of Ah)de(t[l])&&(t[l]=Sh[l]);let a=Wc(t)||Hc(t);if(a)return be.invalid(a);let u=n.offset(r);[o,s]=qs(t,u,n)}return new be({ts:o,zone:n,loc:i,o:s})}function kh(t,e,n){let i=de(n.round)?!0:n.round,r=(s,a)=>(s=mr(s,i||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(s,a)),o=s=>n.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(n.unit)return r(o(n.unit),n.unit);for(let s of n.units){let a=o(s);if(Math.abs(a)>=1)return r(a,s)}return r(t>e?-0:0,n.units[n.units.length-1])}function Th(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}var be=class t{constructor(e){let n=e.zone||Ce.defaultZone,i=e.invalid||(Number.isNaN(e.ts)?new St("invalid input"):null)||(n.isValid?null:Ns(n));this.ts=de(e.ts)?Ce.now():e.ts;let r=null,o=null;if(!i)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,o]=[e.old.c,e.old.o];else{let a=n.offset(this.ts);r=Fs(this.ts,a),i=Number.isNaN(r.year)?new St("invalid input"):null,r=i?null:r,o=i?null:a}this._zone=n,this.loc=e.loc||xe.create(),this.invalid=i,this.weekData=null,this.localWeekData=null,this.c=r,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,n]=Th(arguments),[i,r,o,s,a,u,l]=n;return vh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static utc(){let[e,n]=Th(arguments),[i,r,o,s,a,u,l]=n;return e.zone=Ct.utcInstance,vh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,n={}){let i=Ff(e)?e.valueOf():NaN;if(Number.isNaN(i))return t.invalid("invalid input");let r=wn(n.zone,Ce.defaultZone);return r.isValid?new t({ts:i,zone:r,loc:xe.fromObject(n)}):t.invalid(Ns(r))}static fromMillis(e,n={}){if(In(e))return e<-_h||e>_h?t.invalid("Timestamp out of range"):new t({ts:e,zone:wn(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new bt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(In(e))return new t({ts:e*1e3,zone:wn(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new bt("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let i=wn(n.zone,Ce.defaultZone);if(!i.isValid)return t.invalid(Ns(i));let r=xe.fromObject(n),o=_r(e,bh),{minDaysInFirstWeek:s,startOfWeek:a}=Gc(o,r),u=Ce.now(),l=de(n.specificOffset)?i.offset(u):n.specificOffset,h=!de(o.ordinal),w=!de(o.year),v=!de(o.month)||!de(o.day),T=w||v,I=o.weekYear||o.weekNumber;if((T||h)&&I)throw new gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(v&&h)throw new gn("Can't mix ordinal dates with month/day");let x=I||o.weekday&&!T,P,O,E=Fs(u,l);x?(P=Fw,O=jw,E=fo(E,s,a)):h?(P=Rw,O=Nw,E=Bs(E)):(P=Ah,O=Sh);let B=!1;for(let F of P){let K=o[F];de(K)?B?o[F]=O[F]:o[F]=E[F]:B=!0}let $=x?Bf(o,s,a):h?jf(o):Wc(o),Z=$||Hc(o);if(Z)return t.invalid(Z);let H=x?zc(o,s,a):h?Vc(o):o,[te,U]=qs(H,l,i),V=new t({ts:te,zone:i,o:U,loc:r});return o.weekday&&T&&e.weekday!==V.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${V.toISO()}`):V}static fromISO(e,n={}){let[i,r]=Yf(e);return wo(i,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[i,r]=Qf(e);return wo(i,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[i,r]=eh(e);return wo(i,r,n,"HTTP",n)}static fromFormat(e,n,i={}){if(de(e)||de(n))throw new bt("fromFormat requires an input string and a format");let{locale:r=null,numberingSystem:o=null}=i,s=xe.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0}),[a,u,l,h]=gh(s,e,n);return h?t.invalid(h):wo(a,u,i,`format ${n}`,e,l)}static fromString(e,n,i={}){return t.fromFormat(e,n,i)}static fromSQL(e,n={}){let[i,r]=ih(e);return wo(i,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the DateTime is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new ks(i);return new t({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let i=au(e,xe.fromObject(n));return i?i.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return ou(At.parseFormat(e),xe.fromObject(n)).map(r=>r.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?uu(this).weekYear:NaN}get weekNumber(){return this.isValid?uu(this).weekNumber:NaN}get weekday(){return this.isValid?uu(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?lu(this).weekday:NaN}get localWeekNumber(){return this.isValid?lu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?lu(this).weekYear:NaN}get ordinal(){return this.isValid?Bs(this.c).ordinal:NaN}get monthShort(){return this.isValid?Kn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Kn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Kn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Kn.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,n=6e4,i=hr(this.c),r=this.zone.offset(i-e),o=this.zone.offset(i+e),s=this.zone.offset(i-r*n),a=this.zone.offset(i-o*n);if(s===a)return[this];let u=i-s*n,l=i-a*n,h=Fs(u,s),w=Fs(l,a);return h.hour===w.hour&&h.minute===w.minute&&h.second===w.second&&h.millisecond===w.millisecond?[Bi(this,{ts:u}),Bi(this,{ts:l})]:[this]}get isInLeapYear(){return Ei(this.year)}get daysInMonth(){return gr(this.year,this.month)}get daysInYear(){return this.isValid?ii(this.year):NaN}get weeksInWeekYear(){return this.isValid?Di(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Di(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:i,calendar:r}=At.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:i,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(Ct.instance(e),n)}toLocal(){return this.setZone(Ce.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:i=!1}={}){if(e=wn(e,Ce.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||i){let o=e.offset(this.ts),s=this.toObject();[r]=qs(s,o,e)}return Bi(this,{ts:r,zone:e})}else return t.invalid(Ns(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:i}={}){let r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:i});return Bi(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=_r(e,bh),{minDaysInFirstWeek:i,startOfWeek:r}=Gc(n,this.loc),o=!de(n.weekYear)||!de(n.weekNumber)||!de(n.weekday),s=!de(n.ordinal),a=!de(n.year),u=!de(n.month)||!de(n.day),l=a||u,h=n.weekYear||n.weekNumber;if((l||s)&&h)throw new gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&s)throw new gn("Can't mix ordinal dates with month/day");let w;o?w=zc({...fo(this.c,i,r),...n},i,r):de(n.ordinal)?(w={...this.toObject(),...n},de(n.day)&&(w.day=Math.min(gr(w.year,w.month),w.day))):w=Vc({...Bs(this.c),...n});let[v,T]=qs(w,this.o,this.zone);return Bi(this,{ts:v,o:T})}plus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e);return Bi(this,yh(this,n))}minus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e).negate();return Bi(this,yh(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let i={},r=Pe.normalizeUnit(e);switch(r){case"years":i.month=1;case"quarters":case"months":i.day=1;case"weeks":case"days":i.hour=0;case"hours":i.minute=0;case"minutes":i.second=0;case"seconds":i.millisecond=0;break;case"milliseconds":break}if(r==="weeks")if(n){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(i.weekNumber=this.weekNumber-1),i.weekday=o}else i.weekday=1;if(r==="quarters"){let o=Math.ceil(this.month/3);i.month=(o-1)*3+1}return this.set(i)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?At.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):cu}toLocaleString(e=ei,n={}){return this.isValid?At.create(this.loc.clone(n),e).formatDateTime(this):cu}toLocaleParts(e={}){return this.isValid?At.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:i=!1,includeOffset:r=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=du(this,s);return a+="T",a+=wh(this,s,n,i,r,o),a}toISODate({format:e="extended"}={}){return this.isValid?du(this,e==="extended"):null}toISOWeekDate(){return Rs(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:i=!0,includePrefix:r=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(r?"T":"")+wh(this,s==="extended",n,e,i,o):null}toRFC2822(){return Rs(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Rs(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?du(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:i=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(i&&(r+=" "),n?r+="z":e&&(r+="ZZ")),Rs(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():cu}[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 n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",i={}){if(!this.isValid||!e.isValid)return Pe.invalid("created by diffing an invalid DateTime");let r={locale:this.locale,numberingSystem:this.numberingSystem,...i},o=Rf(n).map(Pe.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,u=s?e:this,l=uh(a,u,o,r);return s?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?Un.fromDateTimes(this,e):this}hasSame(e,n,i){if(!this.isValid)return!1;let r=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(n,i)<=r&&r<=o.endOf(n,i)}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 n=e.base||t.fromObject({},{zone:this.zone}),i=e.padding?this<n?-e.padding:e.padding:0,r=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(r=e.unit,o=void 0),kh(n,this.plus(i),{...e,numeric:"always",units:r,unit:o})}toRelativeCalendar(e={}){return this.isValid?kh(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 bt("min requires all arguments be DateTimes");return Zc(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new bt("max requires all arguments be DateTimes");return Zc(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,i={}){let{locale:r=null,numberingSystem:o=null}=i,s=xe.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0});return su(s,e,n)}static fromStringExplain(e,n,i={}){return t.fromFormatExplain(e,n,i)}static get DATE_SHORT(){return ei}static get DATE_MED(){return zr}static get DATE_MED_WITH_WEEKDAY(){return Ic}static get DATE_FULL(){return Vr}static get DATE_HUGE(){return Gr}static get TIME_SIMPLE(){return Wr}static get TIME_WITH_SECONDS(){return Hr}static get TIME_WITH_SHORT_OFFSET(){return Zr}static get TIME_WITH_LONG_OFFSET(){return Xr}static get TIME_24_SIMPLE(){return Jr}static get TIME_24_WITH_SECONDS(){return Yr}static get TIME_24_WITH_SHORT_OFFSET(){return Qr}static get TIME_24_WITH_LONG_OFFSET(){return eo}static get DATETIME_SHORT(){return to}static get DATETIME_SHORT_WITH_SECONDS(){return no}static get DATETIME_MED(){return io}static get DATETIME_MED_WITH_SECONDS(){return ro}static get DATETIME_MED_WITH_WEEKDAY(){return Oc}static get DATETIME_FULL(){return oo}static get DATETIME_FULL_WITH_SECONDS(){return so}static get DATETIME_HUGE(){return ao}static get DATETIME_HUGE_WITH_SECONDS(){return co}};function Sr(t){if(be.isDateTime(t))return t;if(t&&t.valueOf&&In(t.valueOf()))return be.fromJSDate(t);if(t&&typeof t=="object")return be.fromObject(t);throw new bt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Dr=require("@mysten/sui.js/utils");var gi=require("@mysten/sui.js/utils");var Ap=ge(Lo(),1),xp=require("@msafe/sui3-utils"),Ip=require("@msafe/sui3-utils"),Op=require("@msafe/sui3-utils"),qu=require("@mysten/sui.js/bcs"),hi=require("@mysten/sui.js/utils"),Dp=require("@msafe/sui3-utils"),Pr=require("@msafe/sui3-utils"),Ep=require("@msafe/sui3-utils"),Bp=require("@msafe/sui3-utils"),Np=require("@msafe/sui3-utils"),Fp=require("@mysten/sui.js/transactions"),qp=require("@msafe/sui3-utils"),Or=require("@msafe/sui3-utils"),Lu=require("@mysten/sui.js/bcs"),mi=require("@mysten/sui.js/utils"),Lp=require("@mysten/sui.js/transactions"),Up=require("@mysten/sui.js/transactions"),zp=require("@mysten/sui.js/transactions"),Wp=require("@mysten/sui.js/transactions"),Zp=require("@mysten/sui.js/transactions"),ua=require("@msafe/sui3-utils"),Jp=require("@mysten/sui.js/transactions"),la=require("@mysten/sui.js/utils"),lx=ge(Lo(),1),Yp=require("@msafe/sui3-utils"),Qp=require("@msafe/sui3-utils"),$u=require("@mysten/sui.js/bcs"),pi=require("@mysten/sui.js/utils");var ub=ge(ke(),1);var Ri=require("@mysten/sui.js/client"),Kh=require("@mysten/sui.js/keypairs/ed25519");function xh(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Lw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function fu(t,...e){if(!Lw(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 hu(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 Ih(t,e){fu(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Ls=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $w(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Us=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),vn=(t,e)=>t<<32-e|t>>>e,Uw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Uw)throw new Error("Non little-endian hardware is not supported");function Kw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function mu(t){if(typeof t=="string"&&(t=Kw(t)),!$w(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var $s=class{clone(){return this._cloneInto()}},pA={}.toString;function Oh(t){let e=i=>t().update(mu(i)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Ph(t=32){if(Ls&&typeof Ls.getRandomValues=="function")return Ls.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function zw(t,e,n,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,i);let r=BigInt(32),o=BigInt(4294967295),s=Number(n>>r&o),a=Number(n&o),u=i?4:0,l=i?0:4;t.setUint32(e+u,s,i),t.setUint32(e+l,a,i)}var Ks=class extends $s{constructor(e,n,i,r){super(),this.blockLen=e,this.outputLen=n,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Us(this.buffer)}update(e){hu(this);let{view:n,buffer:i,blockLen:r}=this;e=mu(e);let o=e.length;for(let s=0;s<o;){let a=Math.min(r-this.pos,o-s);if(a===r){let u=Us(e);for(;r<=o-s;s+=r)this.process(u,s);continue}i.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){hu(this),Ih(e,this),this.finished=!0;let{buffer:n,view:i,blockLen:r,isLE:o}=this,{pos:s}=this;n[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>r-s&&(this.process(i,0),s=0);for(let w=s;w<r;w++)n[w]=0;zw(i,r-8,BigInt(this.length*8),o),this.process(i,0);let a=Us(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=u/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let w=0;w<l;w++)a.setUint32(4*w,h[w],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let i=e.slice(0,n);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:i,length:r,finished:o,destroyed:s,pos:a}=this;return e.length=r,e.pos=a,e.finished=o,e.destroyed=s,r%n&&e.buffer.set(i),e}};var Vw=(t,e,n)=>t&e^~t&n,Gw=(t,e,n)=>t&e^t&n^e&n,Ww=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]),ai=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ci=new Uint32Array(64),pu=class extends Ks{constructor(){super(64,32,8,!1),this.A=ai[0]|0,this.B=ai[1]|0,this.C=ai[2]|0,this.D=ai[3]|0,this.E=ai[4]|0,this.F=ai[5]|0,this.G=ai[6]|0,this.H=ai[7]|0}get(){let{A:e,B:n,C:i,D:r,E:o,F:s,G:a,H:u}=this;return[e,n,i,r,o,s,a,u]}set(e,n,i,r,o,s,a,u){this.A=e|0,this.B=n|0,this.C=i|0,this.D=r|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=u|0}process(e,n){for(let w=0;w<16;w++,n+=4)ci[w]=e.getUint32(n,!1);for(let w=16;w<64;w++){let v=ci[w-15],T=ci[w-2],I=vn(v,7)^vn(v,18)^v>>>3,x=vn(T,17)^vn(T,19)^T>>>10;ci[w]=x+ci[w-7]+I+ci[w-16]|0}let{A:i,B:r,C:o,D:s,E:a,F:u,G:l,H:h}=this;for(let w=0;w<64;w++){let v=vn(a,6)^vn(a,11)^vn(a,25),T=h+v+Vw(a,u,l)+Ww[w]+ci[w]|0,x=(vn(i,2)^vn(i,13)^vn(i,22))+Gw(i,r,o)|0;h=l,l=u,u=a,a=s+T|0,s=o,o=r,r=i,i=T+x|0}i=i+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,u=u+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(i,r,o,s,a,u,l,h)}roundClean(){ci.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Dh=Oh(()=>new pu);function ji(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function zs(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Hw(...t){let e=o=>o,n=(o,s)=>a=>o(s(a)),i=t.map(o=>o.encode).reduceRight(n,e),r=t.map(o=>o.decode).reduce(n,e);return{encode:i,decode:r}}function Zw(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(n=>{if(n<0||n>=t.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${t.length})`);return t[n]})},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(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);let i=t.indexOf(n);if(i===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return i})}}}function Xw(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 n of e)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function Jw(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.encode: non-string input=${i}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.decode: non-string input=${r}`);let i=n.length;if(i*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;i>0&&n[i-1]===e;i--)if(!((i-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,i)}}}function gu(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let i=0,r=[],o=Array.from(t);for(o.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,a=!0;for(let u=i;u<o.length;u++){let l=o[u],h=e*s+l;if(!Number.isSafeInteger(h)||e*s/e!==s||h-l!==e*s)throw new Error("convertRadix: carry overflow");s=h%n;let w=Math.floor(h/n);if(o[u]=w,!Number.isSafeInteger(w)||w*n+s!==h)throw new Error("convertRadix: carry overflow");if(a)w?a=!1:i=u;else continue}if(r.push(s),a)break}for(let s=0;s<t.length-1&&t[s]===0;s++)r.push(0);return r.reverse()}var Eh=(t,e)=>e?Eh(e,t%e):t,Vs=(t,e)=>t+(e-Eh(t,e));function _u(t,e,n,i){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(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Vs(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Vs(e,n)}`);let r=0,o=0,s=2**n-1,a=[];for(let u of t){if(u>=2**e)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(r=r<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=n;o-=n)a.push((r>>o-n&s)>>>0);r&=2**o-1}if(r=r<<n-o&s,!i&&o>=e)throw new Error("Excess padding");if(!i&&r)throw new Error(`Non-zero padding: ${r}`);return i&&o>0&&a.push(r>>>0),a}function Yw(t){return{encode:e=>{if(!zs(e))throw new Error("radix.encode input should be Uint8Array");return gu(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(gu(e,t,2**8))}}}function Qw(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Vs(8,t)>32||Vs(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!zs(n))throw new Error("radix2.encode input should be Uint8Array");return _u(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(_u(n,t,8,e))}}}function eb(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(n){if(!zs(n))throw new Error("checksum.encode: input should be Uint8Array");let i=e(n).slice(0,t),r=new Uint8Array(n.length+t);return r.set(n),r.set(i,n.length),r},decode(n){if(!zs(n))throw new Error("checksum.decode: input should be Uint8Array");let i=n.slice(0,-t),r=e(i).slice(0,t),o=n.slice(-t);for(let s=0;s<t;s++)if(r[s]!==o[s])throw new Error("Invalid checksum");return i}}}var bo={alphabet:Zw,chain:Hw,checksum:eb,convertRadix:gu,convertRadix2:_u,radix:Yw,radix2:Qw,join:Xw,padding:Jw};var tb=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function nb(t){fu(t,16,20,24,28,32)}function Mh(t,e=128){if(xh(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return ob(Ph(e/8),t)}var ib=t=>{let e=8-t.length/4;return new Uint8Array([Dh(t)[0]>>e<<e])};function rb(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}`)}),bo.chain(bo.checksum(1,ib),bo.radix2(11,!0),bo.alphabet(t))}function ob(t,e){return nb(t),rb(e).encode(t).join(tb(e)?"\u3000":" ")}var Bh=`abandon
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var A,c=!0,d=!1;return{s:function(){F=F.call(U)},n:function(){var g=F.next();return c=g.done,g},e:function(g){d=!0,A=g},f:function(){try{c||F.return==null||F.return()}finally{if(d)throw A}}}}var te=function(U){var V=Math.abs,F=Math.max,K=Math.floor;function C(c,d){var g;if(i(this,C),g=A.call(this,c),g.sign=d,Object.setPrototypeOf(T(g),C.prototype),c>C.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return g}s(C,U);var A=x(C);return o(C,[{key:"toDebugString",value:function(){var c,d=["BigInt["],g=H(this);try{for(g.s();!(c=g.n()).done;){var b=c.value;d.push((b&&(b>>>0).toString(16))+", ")}}catch(p){g.e(p)}finally{g.f()}return d.push("]"),d.join("")}},{key:"toString",value:function(){var c=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>c||36<c)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":c&c-1?C.__toStringGeneric(this,c,!1):C.__toStringBasePowerOfTwo(this,c)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var c=new C(this.length,this.sign),d=0;d<this.length;d++)c[d]=this[d];return c}},{key:"__trim",value:function(){for(var c=this.length,d=this[c-1];d===0;)c--,d=this[c-1],this.pop();return c===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var c=0;c<this.length;c++)this[c]=0}},{key:"__clzmsd",value:function(){return C.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(c,d,g){g>this.length&&(g=this.length);for(var b=32767&c,p=c>>>15,m=0,y=d,_=0;_<g;_++){var f=this.__digit(_),k=32767&f,M=f>>>15,j=C.__imul(k,b),L=C.__imul(k,p),R=C.__imul(M,b),W=C.__imul(M,p),ne=y+j+m;m=ne>>>30,ne&=1073741823,ne+=((32767&L)<<15)+((32767&R)<<15),m+=ne>>>30,y=W+(L>>>15)+(R>>>15),this.__setDigit(_,1073741823&ne)}if(m!==0||y!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(c,d,g){for(var b,p=0,m=0;m<g;m++)b=this.__halfDigit(d+m)+c.__halfDigit(m)+p,p=b>>>15,this.__setHalfDigit(d+m,32767&b);return p}},{key:"__inplaceSub",value:function(c,d,g){var b=0;if(1&d){d>>=1;for(var p=this.__digit(d),m=32767&p,y=0;y<g-1>>>1;y++){var _=c.__digit(y),f=(p>>>15)-(32767&_)-b;b=1&f>>>15,this.__setDigit(d+y,(32767&f)<<15|32767&m),p=this.__digit(d+y+1),m=(32767&p)-(_>>>15)-b,b=1&m>>>15}var k=c.__digit(y),M=(p>>>15)-(32767&k)-b;if(b=1&M>>>15,this.__setDigit(d+y,(32767&M)<<15|32767&m),d+y+1>=this.length)throw new RangeError("out of bounds");!(1&g)&&(p=this.__digit(d+y+1),m=(32767&p)-(k>>>15)-b,b=1&m>>>15,this.__setDigit(d+c.length,1073709056&p|32767&m))}else{d>>=1;for(var j=0;j<c.length-1;j++){var L=this.__digit(d+j),R=c.__digit(j),W=(32767&L)-(32767&R)-b;b=1&W>>>15;var ne=(L>>>15)-(R>>>15)-b;b=1&ne>>>15,this.__setDigit(d+j,(32767&ne)<<15|32767&W)}var me=this.__digit(d+j),ue=c.__digit(j),pe=(32767&me)-(32767&ue)-b;b=1&pe>>>15;var vt=0;!(1&g)&&(vt=(me>>>15)-(ue>>>15)-b,b=1&vt>>>15),this.__setDigit(d+j,(32767&vt)<<15|32767&pe)}return b}},{key:"__inplaceRightShift",value:function(c){if(c!==0){for(var d,g=this.__digit(0)>>>c,b=this.length-1,p=0;p<b;p++)d=this.__digit(p+1),this.__setDigit(p,1073741823&d<<30-c|g),g=d>>>c;this.__setDigit(b,g)}}},{key:"__digit",value:function(c){return this[c]}},{key:"__unsignedDigit",value:function(c){return this[c]>>>0}},{key:"__setDigit",value:function(c,d){this[c]=0|d}},{key:"__setDigitGrow",value:function(c,d){this[c]=0|d}},{key:"__halfDigitLength",value:function(){var c=this.length;return 32767>=this.__unsignedDigit(c-1)?2*c-1:2*c}},{key:"__halfDigit",value:function(c){return 32767&this[c>>>1]>>>15*(1&c)}},{key:"__setHalfDigit",value:function(c,d){var g=c>>>1,b=this.__digit(g),p=1&c?32767&b|d<<15:1073709056&b|32767&d;this.__setDigit(g,p)}}],[{key:"BigInt",value:function(c){var d=Number.isFinite;if(typeof c=="number"){if(c===0)return C.__zero();if(C.__isOneDigitInt(c))return 0>c?C.__oneDigit(-c,!0):C.__oneDigit(c,!1);if(!d(c)||K(c)!==c)throw new RangeError("The number "+c+" cannot be converted to BigInt because it is not an integer");return C.__fromDouble(c)}if(typeof c=="string"){var g=C.__fromString(c);if(g===null)throw new SyntaxError("Cannot convert "+c+" to a BigInt");return g}if(typeof c=="boolean")return c===!0?C.__oneDigit(1,!1):C.__zero();if(n(c)==="object"){if(c.constructor===C)return c;var b=C.__toPrimitive(c);return C.BigInt(b)}throw new TypeError("Cannot convert "+c+" to a BigInt")}},{key:"toNumber",value:function(c){var d=c.length;if(d===0)return 0;if(d===1){var g=c.__unsignedDigit(0);return c.sign?-g:g}var b=c.__digit(d-1),p=C.__clz30(b),m=30*d-p;if(1024<m)return c.sign?-1/0:1/0;var y=m-1,_=b,f=d-1,k=p+3,M=k===32?0:_<<k;M>>>=12;var j=k-12,L=12<=k?0:_<<20+k,R=20+k;for(0<j&&0<f&&(f--,_=c.__digit(f),M|=_>>>30-j,L=_<<j+2,R=j+2);0<R&&0<f;)f--,_=c.__digit(f),L|=30<=R?_<<R-30:_>>>30-R,R-=30;var W=C.__decideRounding(c,R,f,_);if((W===1||W===0&&(1&L)==1)&&(L=L+1>>>0,L===0&&(M++,M>>>20!=0&&(M=0,y++,1023<y))))return c.sign?-1/0:1/0;var ne=c.sign?-2147483648:0;return y=y+1023<<20,C.__kBitConversionInts[1]=ne|y|M,C.__kBitConversionInts[0]=L,C.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(c){if(c.length===0)return c;var d=c.__copy();return d.sign=!c.sign,d}},{key:"bitwiseNot",value:function(c){return c.sign?C.__absoluteSubOne(c).__trim():C.__absoluteAddOne(c,!0)}},{key:"exponentiate",value:function(c,d){if(d.sign)throw new RangeError("Exponent must be positive");if(d.length===0)return C.__oneDigit(1,!1);if(c.length===0)return c;if(c.length===1&&c.__digit(0)===1)return c.sign&&!(1&d.__digit(0))?C.unaryMinus(c):c;if(1<d.length)throw new RangeError("BigInt too big");var g=d.__unsignedDigit(0);if(g===1)return c;if(g>=C.__kMaxLengthBits)throw new RangeError("BigInt too big");if(c.length===1&&c.__digit(0)===2){var b=1+(0|g/30),p=c.sign&&(1&g)!=0,m=new C(b,p);m.__initializeDigits();var y=1<<g%30;return m.__setDigit(b-1,y),m}var _=null,f=c;for(1&g&&(_=c),g>>=1;g!==0;g>>=1)f=C.multiply(f,f),1&g&&(_===null?_=f:_=C.multiply(_,f));return _}},{key:"multiply",value:function(c,d){if(c.length===0)return c;if(d.length===0)return d;var g=c.length+d.length;30<=c.__clzmsd()+d.__clzmsd()&&g--;var b=new C(g,c.sign!==d.sign);b.__initializeDigits();for(var p=0;p<c.length;p++)C.__multiplyAccumulate(d,c.__digit(p),b,p);return b.__trim()}},{key:"divide",value:function(c,d){if(d.length===0)throw new RangeError("Division by zero");if(0>C.__absoluteCompare(c,d))return C.__zero();var g,b=c.sign!==d.sign,p=d.__unsignedDigit(0);if(d.length===1&&32767>=p){if(p===1)return b===c.sign?c:C.unaryMinus(c);g=C.__absoluteDivSmall(c,p,null)}else g=C.__absoluteDivLarge(c,d,!0,!1);return g.sign=b,g.__trim()}},{key:"remainder",value:function(d,g){if(g.length===0)throw new RangeError("Division by zero");if(0>C.__absoluteCompare(d,g))return d;var b=g.__unsignedDigit(0);if(g.length===1&&32767>=b){if(b===1)return C.__zero();var p=C.__absoluteModSmall(d,b);return p===0?C.__zero():C.__oneDigit(p,d.sign)}var m=C.__absoluteDivLarge(d,g,!1,!0);return m.sign=d.sign,m.__trim()}},{key:"add",value:function(c,d){var g=c.sign;return g===d.sign?C.__absoluteAdd(c,d,g):0<=C.__absoluteCompare(c,d)?C.__absoluteSub(c,d,g):C.__absoluteSub(d,c,!g)}},{key:"subtract",value:function(c,d){var g=c.sign;return g===d.sign?0<=C.__absoluteCompare(c,d)?C.__absoluteSub(c,d,g):C.__absoluteSub(d,c,!g):C.__absoluteAdd(c,d,g)}},{key:"leftShift",value:function(c,d){return d.length===0||c.length===0?c:d.sign?C.__rightShiftByAbsolute(c,d):C.__leftShiftByAbsolute(c,d)}},{key:"signedRightShift",value:function(c,d){return d.length===0||c.length===0?c:d.sign?C.__leftShiftByAbsolute(c,d):C.__rightShiftByAbsolute(c,d)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(c,d){return 0>C.__compareToBigInt(c,d)}},{key:"lessThanOrEqual",value:function(c,d){return 0>=C.__compareToBigInt(c,d)}},{key:"greaterThan",value:function(c,d){return 0<C.__compareToBigInt(c,d)}},{key:"greaterThanOrEqual",value:function(c,d){return 0<=C.__compareToBigInt(c,d)}},{key:"equal",value:function(c,d){if(c.sign!==d.sign||c.length!==d.length)return!1;for(var g=0;g<c.length;g++)if(c.__digit(g)!==d.__digit(g))return!1;return!0}},{key:"notEqual",value:function(c,d){return!C.equal(c,d)}},{key:"bitwiseAnd",value:function(c,d){if(!c.sign&&!d.sign)return C.__absoluteAnd(c,d).__trim();if(c.sign&&d.sign){var g=F(c.length,d.length)+1,b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return b=C.__absoluteOr(b,p,b),C.__absoluteAddOne(b,!0,b).__trim()}if(c.sign){var m=[d,c];c=m[0],d=m[1]}return C.__absoluteAndNot(c,C.__absoluteSubOne(d)).__trim()}},{key:"bitwiseXor",value:function(c,d){if(!c.sign&&!d.sign)return C.__absoluteXor(c,d).__trim();if(c.sign&&d.sign){var g=F(c.length,d.length),b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return C.__absoluteXor(b,p,b).__trim()}var m=F(c.length,d.length)+1;if(c.sign){var y=[d,c];c=y[0],d=y[1]}var _=C.__absoluteSubOne(d,m);return _=C.__absoluteXor(_,c,_),C.__absoluteAddOne(_,!0,_).__trim()}},{key:"bitwiseOr",value:function(c,d){var g=F(c.length,d.length);if(!c.sign&&!d.sign)return C.__absoluteOr(c,d).__trim();if(c.sign&&d.sign){var b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return b=C.__absoluteAnd(b,p,b),C.__absoluteAddOne(b,!0,b).__trim()}if(c.sign){var m=[d,c];c=m[0],d=m[1]}var y=C.__absoluteSubOne(d,g);return y=C.__absoluteAndNot(y,c,y),C.__absoluteAddOne(y,!0,y).__trim()}},{key:"asIntN",value:function(c,d){if(d.length===0)return d;if(c=K(c),0>c)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(c===0)return C.__zero();if(c>=C.__kMaxLengthBits)return d;var g=0|(c+29)/30;if(d.length<g)return d;var b=d.__unsignedDigit(g-1),p=1<<(c-1)%30;if(d.length===g&&b<p)return d;if((b&p)!==p)return C.__truncateToNBits(c,d);if(!d.sign)return C.__truncateAndSubFromPowerOfTwo(c,d,!0);if(!(b&p-1)){for(var m=g-2;0<=m;m--)if(d.__digit(m)!==0)return C.__truncateAndSubFromPowerOfTwo(c,d,!1);return d.length===g&&b===p?d:C.__truncateToNBits(c,d)}return C.__truncateAndSubFromPowerOfTwo(c,d,!1)}},{key:"asUintN",value:function(c,d){if(d.length===0)return d;if(c=K(c),0>c)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(c===0)return C.__zero();if(d.sign){if(c>C.__kMaxLengthBits)throw new RangeError("BigInt too big");return C.__truncateAndSubFromPowerOfTwo(c,d,!1)}if(c>=C.__kMaxLengthBits)return d;var g=0|(c+29)/30;if(d.length<g)return d;var b=c%30;if(d.length==g){if(b===0)return d;var p=d.__digit(g-1);if(!(p>>>b))return d}return C.__truncateToNBits(c,d)}},{key:"ADD",value:function(c,d){if(c=C.__toPrimitive(c),d=C.__toPrimitive(d),typeof c=="string")return typeof d!="string"&&(d=d.toString()),c+d;if(typeof d=="string")return c.toString()+d;if(c=C.__toNumeric(c),d=C.__toNumeric(d),C.__isBigInt(c)&&C.__isBigInt(d))return C.add(c,d);if(typeof c=="number"&&typeof d=="number")return c+d;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(c,d){return C.__compare(c,d,0)}},{key:"LE",value:function(c,d){return C.__compare(c,d,1)}},{key:"GT",value:function(c,d){return C.__compare(c,d,2)}},{key:"GE",value:function(c,d){return C.__compare(c,d,3)}},{key:"EQ",value:function(c,d){for(;;){if(C.__isBigInt(c))return C.__isBigInt(d)?C.equal(c,d):C.EQ(d,c);if(typeof c=="number"){if(C.__isBigInt(d))return C.__equalToNumber(d,c);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(typeof c=="string"){if(C.__isBigInt(d))return c=C.__fromString(c),c!==null&&C.equal(c,d);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(typeof c=="boolean"){if(C.__isBigInt(d))return C.__equalToNumber(d,+c);if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(n(c)==="symbol"){if(C.__isBigInt(d))return!1;if(n(d)!=="object")return c==d;d=C.__toPrimitive(d)}else if(n(c)==="object"){if(n(d)==="object"&&d.constructor!==C)return c==d;c=C.__toPrimitive(c)}else return c==d}}},{key:"NE",value:function(c,d){return!C.EQ(c,d)}},{key:"DataViewGetBigInt64",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return C.asIntN(64,C.DataViewGetBigUint64(c,d,g))}},{key:"DataViewGetBigUint64",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0&&arguments[2],b=g?[4,0]:[0,4],p=P(b,2),m=p[0],y=p[1],_=c.getUint32(d+m,g),f=c.getUint32(d+y,g),k=new C(3,!1);return k.__setDigit(0,1073741823&f),k.__setDigit(1,(268435455&_)<<2|f>>>30),k.__setDigit(2,_>>>28),k.__trim()}},{key:"DataViewSetBigInt64",value:function(c,d,g){var b=3<arguments.length&&arguments[3]!==void 0&&arguments[3];C.DataViewSetBigUint64(c,d,g,b)}},{key:"DataViewSetBigUint64",value:function(c,d,g){var b=3<arguments.length&&arguments[3]!==void 0&&arguments[3];g=C.asUintN(64,g);var p=0,m=0;if(0<g.length&&(m=g.__digit(0),1<g.length)){var y=g.__digit(1);m|=y<<30,p=y>>>2,2<g.length&&(p|=g.__digit(2)<<28)}var _=b?[4,0]:[0,4],f=P(_,2),k=f[0],M=f[1];c.setUint32(d+k,p,b),c.setUint32(d+M,m,b)}},{key:"__zero",value:function(){return new C(0,!1)}},{key:"__oneDigit",value:function(c,d){var g=new C(1,d);return g.__setDigit(0,c),g}},{key:"__decideRounding",value:function(c,d,g,b){if(0<d)return-1;var p;if(0>d)p=-d-1;else{if(g===0)return-1;g--,b=c.__digit(g),p=29}var m=1<<p;if(!(b&m))return-1;if(m-=1,(b&m)!=0)return 1;for(;0<g;)if(g--,c.__digit(g)!==0)return 1;return 0}},{key:"__fromDouble",value:function(c){C.__kBitConversionDouble[0]=c;var d,g=2047&C.__kBitConversionInts[1]>>>20,b=g-1023,p=(0|b/30)+1,m=new C(p,0>c),y=1048575&C.__kBitConversionInts[1]|1048576,_=C.__kBitConversionInts[0],f=20,k=b%30,M=0;if(k<f){var j=f-k;M=j+32,d=y>>>j,y=y<<32-j|_>>>j,_<<=32-j}else if(k===f)M=32,d=y,y=_,_=0;else{var L=k-f;M=32-L,d=y<<L|_>>>32-L,y=_<<L,_=0}m.__setDigit(p-1,d);for(var R=p-2;0<=R;R--)0<M?(M-=30,d=y>>>2,y=y<<30|_>>>2,_<<=30):d=0,m.__setDigit(R,d);return m.__trim()}},{key:"__isWhitespace",value:function(c){return 13>=c&&9<=c||(159>=c?c==32:131071>=c?c==160||c==5760:196607>=c?(c&=131071,10>=c||c==40||c==41||c==47||c==95||c==4096):c==65279)}},{key:"__fromString",value:function(c){var d=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,g=0,b=c.length,p=0;if(p===b)return C.__zero();for(var m=c.charCodeAt(p);C.__isWhitespace(m);){if(++p===b)return C.__zero();m=c.charCodeAt(p)}if(m===43){if(++p===b)return null;m=c.charCodeAt(p),g=1}else if(m===45){if(++p===b)return null;m=c.charCodeAt(p),g=-1}if(d===0){if(d=10,m===48){if(++p===b)return C.__zero();if(m=c.charCodeAt(p),m===88||m===120){if(d=16,++p===b)return null;m=c.charCodeAt(p)}else if(m===79||m===111){if(d=8,++p===b)return null;m=c.charCodeAt(p)}else if(m===66||m===98){if(d=2,++p===b)return null;m=c.charCodeAt(p)}}}else if(d===16&&m===48){if(++p===b)return C.__zero();if(m=c.charCodeAt(p),m===88||m===120){if(++p===b)return null;m=c.charCodeAt(p)}}if(g!==0&&d!==10)return null;for(;m===48;){if(++p===b)return C.__zero();m=c.charCodeAt(p)}var y=b-p,_=C.__kMaxBitsPerChar[d],f=C.__kBitsPerCharTableMultiplier-1;if(y>1073741824/_)return null;var k=_*y+f>>>C.__kBitsPerCharTableShift,M=new C(0|(k+29)/30,!1),j=10>d?d:10,L=10<d?d-10:0;if(d&d-1){M.__initializeDigits();var vt=!1,De=0;do{for(var je,zi=0,Ne=1;;){if(je=void 0,m-48>>>0<j)je=m-48;else if((32|m)-97>>>0<L)je=(32|m)-87;else{vt=!0;break}var Fe=Ne*d;if(1073741823<Fe)break;if(Ne=Fe,zi=zi*d+je,De++,++p===b){vt=!0;break}m=c.charCodeAt(p)}f=30*C.__kBitsPerCharTableMultiplier-1;var qo=0|(_*De+f>>>C.__kBitsPerCharTableShift)/30;M.__inplaceMultiplyAdd(Ne,zi,qo)}while(!vt)}else{_>>=C.__kBitsPerCharTableShift;var R=[],W=[],ne=!1;do{for(var me,ue=0,pe=0;;){if(me=void 0,m-48>>>0<j)me=m-48;else if((32|m)-97>>>0<L)me=(32|m)-87;else{ne=!0;break}if(pe+=_,ue=ue<<_|me,++p===b){ne=!0;break}if(m=c.charCodeAt(p),30<pe+_)break}R.push(ue),W.push(pe)}while(!ne);C.__fillFromParts(M,R,W)}if(p!==b){if(!C.__isWhitespace(m))return null;for(p++;p<b;p++)if(m=c.charCodeAt(p),!C.__isWhitespace(m))return null}return M.sign=g===-1,M.__trim()}},{key:"__fillFromParts",value:function(c,d,g){for(var b=0,p=0,m=0,y=d.length-1;0<=y;y--){var _=d[y],f=g[y];p|=_<<m,m+=f,m===30?(c.__setDigit(b++,p),m=0,p=0):30<m&&(c.__setDigit(b++,1073741823&p),m-=30,p=_>>>f-m)}if(p!==0){if(b>=c.length)throw new Error("implementation bug");c.__setDigit(b++,p)}for(;b<c.length;b++)c.__setDigit(b,0)}},{key:"__toStringBasePowerOfTwo",value:function(c,d){var g=c.length,b=d-1;b=(85&b>>>1)+(85&b),b=(51&b>>>2)+(51&b),b=(15&b>>>4)+(15&b);var p=b,m=d-1,y=c.__digit(g-1),_=C.__clz30(y),f=0|(30*g-_+p-1)/p;if(c.sign&&f++,268435456<f)throw new Error("string too long");for(var k=Array(f),M=f-1,j=0,L=0,R=0;R<g-1;R++){var W=c.__digit(R),ne=(j|W<<L)&m;k[M--]=C.__kConversionChars[ne];var me=p-L;for(j=W>>>me,L=30-me;L>=p;)k[M--]=C.__kConversionChars[j&m],j>>>=p,L-=p}var ue=(j|y<<L)&m;for(k[M--]=C.__kConversionChars[ue],j=y>>>p-L;j!==0;)k[M--]=C.__kConversionChars[j&m],j>>>=p;if(c.sign&&(k[M--]="-"),M!==-1)throw new Error("implementation bug");return k.join("")}},{key:"__toStringGeneric",value:function(c,d,g){var b=c.length;if(b===0)return"";if(b===1){var p=c.__unsignedDigit(0).toString(d);return g===!1&&c.sign&&(p="-"+p),p}var m=30*b-C.__clz30(c.__digit(b-1)),y=C.__kMaxBitsPerChar[d],_=y-1,f=m*C.__kBitsPerCharTableMultiplier;f+=_-1,f=0|f/_;var k,M,j=f+1>>1,L=C.exponentiate(C.__oneDigit(d,!1),C.__oneDigit(j,!1)),R=L.__unsignedDigit(0);if(L.length===1&&32767>=R){k=new C(c.length,!1),k.__initializeDigits();for(var W,ne=0,me=2*c.length-1;0<=me;me--)W=ne<<15|c.__halfDigit(me),k.__setHalfDigit(me,0|W/R),ne=0|W%R;M=ne.toString(d)}else{var ue=C.__absoluteDivLarge(c,L,!0,!0);k=ue.quotient;var pe=ue.remainder.__trim();M=C.__toStringGeneric(pe,d,!0)}k.__trim();for(var vt=C.__toStringGeneric(k,d,!0);M.length<j;)M="0"+M;return g===!1&&c.sign&&(vt="-"+vt),vt+M}},{key:"__unequalSign",value:function(c){return c?-1:1}},{key:"__absoluteGreater",value:function(c){return c?-1:1}},{key:"__absoluteLess",value:function(c){return c?1:-1}},{key:"__compareToBigInt",value:function(c,d){var g=c.sign;if(g!==d.sign)return C.__unequalSign(g);var b=C.__absoluteCompare(c,d);return 0<b?C.__absoluteGreater(g):0>b?C.__absoluteLess(g):0}},{key:"__compareToNumber",value:function(c,d){if(C.__isOneDigitInt(d)){var g=c.sign,b=0>d;if(g!==b)return C.__unequalSign(g);if(c.length===0){if(b)throw new Error("implementation bug");return d===0?0:-1}if(1<c.length)return C.__absoluteGreater(g);var p=V(d),m=c.__unsignedDigit(0);return m>p?C.__absoluteGreater(g):m<p?C.__absoluteLess(g):0}return C.__compareToDouble(c,d)}},{key:"__compareToDouble",value:function(c,d){if(d!==d)return d;if(d===1/0)return-1;if(d===-1/0)return 1;var g=c.sign;if(g!==0>d)return C.__unequalSign(g);if(d===0)throw new Error("implementation bug: should be handled elsewhere");if(c.length===0)return-1;C.__kBitConversionDouble[0]=d;var b=2047&C.__kBitConversionInts[1]>>>20;if(b==2047)throw new Error("implementation bug: handled elsewhere");var p=b-1023;if(0>p)return C.__absoluteGreater(g);var m=c.length,y=c.__digit(m-1),_=C.__clz30(y),f=30*m-_,k=p+1;if(f<k)return C.__absoluteLess(g);if(f>k)return C.__absoluteGreater(g);var M=1048576|1048575&C.__kBitConversionInts[1],j=C.__kBitConversionInts[0],L=20,R=29-_;if(R!==(0|(f-1)%30))throw new Error("implementation bug");var W,ne=0;if(R<L){var me=L-R;ne=me+32,W=M>>>me,M=M<<32-me|j>>>me,j<<=32-me}else if(R===L)ne=32,W=M,M=j,j=0;else{var ue=R-L;ne=32-ue,W=M<<ue|j>>>32-ue,M=j<<ue,j=0}if(y>>>=0,W>>>=0,y>W)return C.__absoluteGreater(g);if(y<W)return C.__absoluteLess(g);for(var pe=m-2;0<=pe;pe--){0<ne?(ne-=30,W=M>>>2,M=M<<30|j>>>2,j<<=30):W=0;var vt=c.__unsignedDigit(pe);if(vt>W)return C.__absoluteGreater(g);if(vt<W)return C.__absoluteLess(g)}if(M!==0||j!==0){if(ne===0)throw new Error("implementation bug");return C.__absoluteLess(g)}return 0}},{key:"__equalToNumber",value:function(c,d){return C.__isOneDigitInt(d)?d===0?c.length===0:c.length===1&&c.sign===0>d&&c.__unsignedDigit(0)===V(d):C.__compareToDouble(c,d)===0}},{key:"__comparisonResultToBool",value:function(c,d){return d===0?0>c:d===1?0>=c:d===2?0<c:d===3?0<=c:void 0}},{key:"__compare",value:function(c,d,g){if(c=C.__toPrimitive(c),d=C.__toPrimitive(d),typeof c=="string"&&typeof d=="string")switch(g){case 0:return c<d;case 1:return c<=d;case 2:return c>d;case 3:return c>=d}if(C.__isBigInt(c)&&typeof d=="string")return d=C.__fromString(d),d!==null&&C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(typeof c=="string"&&C.__isBigInt(d))return c=C.__fromString(c),c!==null&&C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(c=C.__toNumeric(c),d=C.__toNumeric(d),C.__isBigInt(c)){if(C.__isBigInt(d))return C.__comparisonResultToBool(C.__compareToBigInt(c,d),g);if(typeof d!="number")throw new Error("implementation bug");return C.__comparisonResultToBool(C.__compareToNumber(c,d),g)}if(typeof c!="number")throw new Error("implementation bug");if(C.__isBigInt(d))return C.__comparisonResultToBool(C.__compareToNumber(d,c),2^g);if(typeof d!="number")throw new Error("implementation bug");return g===0?c<d:g===1?c<=d:g===2?c>d:g===3?c>=d:void 0}},{key:"__absoluteAdd",value:function(c,d,g){if(c.length<d.length)return C.__absoluteAdd(d,c,g);if(c.length===0)return c;if(d.length===0)return c.sign===g?c:C.unaryMinus(c);var b=c.length;(c.__clzmsd()===0||d.length===c.length&&d.__clzmsd()===0)&&b++;for(var p,m=new C(b,g),y=0,_=0;_<d.length;_++)p=c.__digit(_)+d.__digit(_)+y,y=p>>>30,m.__setDigit(_,1073741823&p);for(;_<c.length;_++){var f=c.__digit(_)+y;y=f>>>30,m.__setDigit(_,1073741823&f)}return _<m.length&&m.__setDigit(_,y),m.__trim()}},{key:"__absoluteSub",value:function(c,d,g){if(c.length===0)return c;if(d.length===0)return c.sign===g?c:C.unaryMinus(c);for(var b,p=new C(c.length,g),m=0,y=0;y<d.length;y++)b=c.__digit(y)-d.__digit(y)-m,m=1&b>>>30,p.__setDigit(y,1073741823&b);for(;y<c.length;y++){var _=c.__digit(y)-m;m=1&_>>>30,p.__setDigit(y,1073741823&_)}return p.__trim()}},{key:"__absoluteAddOne",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length;g===null?g=new C(b,d):g.sign=d;for(var p,m=1,y=0;y<b;y++)p=c.__digit(y)+m,m=p>>>30,g.__setDigit(y,1073741823&p);return m!==0&&g.__setDigitGrow(b,1),g}},{key:"__absoluteSubOne",value:function(c,d){var g=c.length;d=d||g;for(var b,p=new C(d,!1),m=1,y=0;y<g;y++)b=c.__digit(y)-m,m=1&b>>>30,p.__setDigit(y,1073741823&b);if(m!==0)throw new Error("implementation bug");for(var _=g;_<d;_++)p.__setDigit(_,0);return p}},{key:"__absoluteAnd",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=m;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)&d.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteAndNot",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;b<p&&(m=b);var y=b;g===null?g=new C(y,!1):y=g.length;for(var _=0;_<m;_++)g.__setDigit(_,c.__digit(_)&~d.__digit(_));for(;_<b;_++)g.__setDigit(_,c.__digit(_));for(;_<y;_++)g.__setDigit(_,0);return g}},{key:"__absoluteOr",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=b;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)|d.__digit(k));for(;k<b;k++)g.__setDigit(k,c.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteXor",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,b=c.length,p=d.length,m=p;if(b<p){m=b;var y=c,_=b;c=d,b=p,d=y,p=_}var f=b;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<m;k++)g.__setDigit(k,c.__digit(k)^d.__digit(k));for(;k<b;k++)g.__setDigit(k,c.__digit(k));for(;k<f;k++)g.__setDigit(k,0);return g}},{key:"__absoluteCompare",value:function(c,d){var g=c.length-d.length;if(g!=0)return g;for(var b=c.length-1;0<=b&&c.__digit(b)===d.__digit(b);)b--;return 0>b?0:c.__unsignedDigit(b)>d.__unsignedDigit(b)?1:-1}},{key:"__multiplyAccumulate",value:function(c,d,g,b){if(d!==0){for(var p=32767&d,m=d>>>15,y=0,_=0,f=0;f<c.length;f++,b++){var k=g.__digit(b),M=c.__digit(f),j=32767&M,L=M>>>15,R=C.__imul(j,p),W=C.__imul(j,m),ne=C.__imul(L,p),me=C.__imul(L,m);k+=_+R+y,y=k>>>30,k&=1073741823,k+=((32767&W)<<15)+((32767&ne)<<15),y+=k>>>30,_=me+(W>>>15)+(ne>>>15),g.__setDigit(b,1073741823&k)}for(;y!==0||_!==0;b++){var ue=g.__digit(b);ue+=y+_,_=0,y=ue>>>30,g.__setDigit(b,1073741823&ue)}}}},{key:"__internalMultiplyAdd",value:function(c,d,g,b,p){for(var m=g,y=0,_=0;_<b;_++){var f=c.__digit(_),k=C.__imul(32767&f,d),M=C.__imul(f>>>15,d),j=k+((32767&M)<<15)+y+m;m=j>>>30,y=M>>>15,p.__setDigit(_,1073741823&j)}if(p.length>b)for(p.__setDigit(b++,m+y);b<p.length;)p.__setDigit(b++,0);else if(m+y!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;g===null&&(g=new C(c.length,!1));for(var b=0,p=2*c.length-1;0<=p;p-=2){var m=(b<<15|c.__halfDigit(p))>>>0,y=0|m/d;b=0|m%d,m=(b<<15|c.__halfDigit(p-1))>>>0;var _=0|m/d;b=0|m%d,g.__setDigit(p>>>1,y<<15|_)}return g}},{key:"__absoluteModSmall",value:function(c,d){for(var g,b=0,p=2*c.length-1;0<=p;p--)g=(b<<15|c.__halfDigit(p))>>>0,b=0|g%d;return b}},{key:"__absoluteDivLarge",value:function(c,d,g,b){var p=d.__halfDigitLength(),m=d.length,y=c.__halfDigitLength()-p,_=null;g&&(_=new C(y+2>>>1,!1),_.__initializeDigits());var f=new C(p+2>>>1,!1);f.__initializeDigits();var k=C.__clz15(d.__halfDigit(p-1));0<k&&(d=C.__specialLeftShift(d,k,0));for(var M=C.__specialLeftShift(c,k,1),j=d.__halfDigit(p-1),L=0,R=y;0<=R;R--){var W=32767,ne=M.__halfDigit(R+p);if(ne!==j){var me=(ne<<15|M.__halfDigit(R+p-1))>>>0;W=0|me/j;for(var ue=0|me%j,pe=d.__halfDigit(p-2),vt=M.__halfDigit(R+p-2);C.__imul(W,pe)>>>0>(ue<<16|vt)>>>0&&(W--,ue+=j,!(32767<ue)););}C.__internalMultiplyAdd(d,W,0,m,f);var De=M.__inplaceSub(f,R,p+1);De!==0&&(De=M.__inplaceAdd(d,R,p),M.__setHalfDigit(R+p,32767&M.__halfDigit(R+p)+De),W--),g&&(1&R?L=W<<15:_.__setDigit(R>>>1,L|W))}if(b)return M.__inplaceRightShift(k),g?{quotient:_,remainder:M}:M;if(g)return _;throw new Error("unreachable")}},{key:"__clz15",value:function(c){return C.__clz30(c)-15}},{key:"__specialLeftShift",value:function(c,d,g){var b=c.length,p=new C(b+g,!1);if(d===0){for(var m=0;m<b;m++)p.__setDigit(m,c.__digit(m));return 0<g&&p.__setDigit(b,0),p}for(var y,_=0,f=0;f<b;f++)y=c.__digit(f),p.__setDigit(f,1073741823&y<<d|_),_=y>>>30-d;return 0<g&&p.__setDigit(b,_),p}},{key:"__leftShiftByAbsolute",value:function(c,d){var g=C.__toShiftAmount(d);if(0>g)throw new RangeError("BigInt too big");var b=0|g/30,p=g%30,m=c.length,y=p!==0&&c.__digit(m-1)>>>30-p!=0,_=m+b+(y?1:0),f=new C(_,c.sign);if(p===0){for(var k=0;k<b;k++)f.__setDigit(k,0);for(;k<_;k++)f.__setDigit(k,c.__digit(k-b))}else{for(var M=0,j=0;j<b;j++)f.__setDigit(j,0);for(var L,R=0;R<m;R++)L=c.__digit(R),f.__setDigit(R+b,1073741823&L<<p|M),M=L>>>30-p;if(y)f.__setDigit(m+b,M);else if(M!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(c,d){var g=c.length,b=c.sign,p=C.__toShiftAmount(d);if(0>p)return C.__rightShiftByMaximum(b);var m=0|p/30,y=p%30,_=g-m;if(0>=_)return C.__rightShiftByMaximum(b);var f=!1;if(b){if(c.__digit(m)&(1<<y)-1)f=!0;else for(var k=0;k<m;k++)if(c.__digit(k)!==0){f=!0;break}}if(f&&y===0){var M=c.__digit(g-1);!~M&&_++}var j=new C(_,b);if(y===0){j.__setDigit(_-1,0);for(var L=m;L<g;L++)j.__setDigit(L-m,c.__digit(L))}else{for(var R,W=c.__digit(m)>>>y,ne=g-m-1,me=0;me<ne;me++)R=c.__digit(me+m+1),j.__setDigit(me,1073741823&R<<30-y|W),W=R>>>y;j.__setDigit(ne,W)}return f&&(j=C.__absoluteAddOne(j,!0,j)),j.__trim()}},{key:"__rightShiftByMaximum",value:function(c){return c?C.__oneDigit(1,!0):C.__zero()}},{key:"__toShiftAmount",value:function(c){if(1<c.length)return-1;var d=c.__unsignedDigit(0);return d>C.__kMaxLengthBits?-1:d}},{key:"__toPrimitive",value:function(c){var d=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(n(c)!=="object"||c.constructor===C)return c;if(typeof Symbol<"u"&&n(Symbol.toPrimitive)==="symbol"){var g=c[Symbol.toPrimitive];if(g){var b=g(d);if(n(b)!=="object")return b;throw new TypeError("Cannot convert object to primitive value")}}var p=c.valueOf;if(p){var m=p.call(c);if(n(m)!=="object")return m}var y=c.toString;if(y){var _=y.call(c);if(n(_)!=="object")return _}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(c){return C.__isBigInt(c)?c:+c}},{key:"__isBigInt",value:function(c){return n(c)==="object"&&c!==null&&c.constructor===C}},{key:"__truncateToNBits",value:function(c,d){for(var g=0|(c+29)/30,b=new C(g,d.sign),p=g-1,m=0;m<p;m++)b.__setDigit(m,d.__digit(m));var y=d.__digit(p);if(c%30!=0){var _=32-c%30;y=y<<_>>>_}return b.__setDigit(p,y),b.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(c,d,g){for(var b=Math.min,p,m=0|(c+29)/30,y=new C(m,g),_=0,f=m-1,k=0,M=b(f,d.length);_<M;_++)p=0-d.__digit(_)-k,k=1&p>>>30,y.__setDigit(_,1073741823&p);for(;_<f;_++)y.__setDigit(_,0|1073741823&-k);var j,L=f<d.length?d.__digit(f):0,R=c%30;if(R===0)j=0-L-k,j&=1073741823;else{var W=32-R;L=L<<W>>>W;var ne=1<<32-W;j=ne-L-k,j&=ne-1}return y.__setDigit(f,j),y.__trim()}},{key:"__digitPow",value:function(c,d){for(var g=1;0<d;)1&d&&(g*=c),d>>>=1,c*=c;return g}},{key:"__isOneDigitInt",value:function(c){return(1073741823&c)===c}}]),C}(v(Array));return te.__kMaxLength=33554432,te.__kMaxLengthBits=te.__kMaxLength<<5,te.__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],te.__kBitsPerCharTableShift=5,te.__kBitsPerCharTableMultiplier=1<<te.__kBitsPerCharTableShift,te.__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"],te.__kBitConversionBuffer=new ArrayBuffer(8),te.__kBitConversionDouble=new Float64Array(te.__kBitConversionBuffer),te.__kBitConversionInts=new Int32Array(te.__kBitConversionBuffer),te.__clz30=e?function(U){return e(U)-2}:function(U){var V=Math.LN2,F=Math.log;return U===0?30:0|29-(0|F(U>>>0)/V)},te.__imul=t||function(U,V){return 0|U*V},te})});var Y1={};bl(Y1,{AddressBookSDK:()=>Gi,COIN_TYPE_ARG_REGEX:()=>Hu,Coin:()=>jo,CoinHelper:()=>Bo,CreateHelper:()=>Vi,DEV_API_URL:()=>wg,DEV_SYNCING_URL:()=>bg,ENV_CONFIGS:()=>Tg,Formatter:()=>Vn,HexToUint8Array:()=>ga,LOCAL_API_URL:()=>il,LOCAL_SYNCING_URL:()=>rl,MAINNET_RPC_URL:()=>nl,MSafeAccount:()=>Ki,MSafeClient:()=>Aa,MSafeEnv:()=>yg,MSafeGlobals:()=>Ro,PREV_API_URL:()=>vg,PROD_API_URL:()=>kg,SUI_COIN:()=>Z1,SignatureVerifier:()=>Xu,TESTNET_RPC_URL:()=>Sa,Uint8ArrayToHex:()=>H1,addPrefix:()=>Zu,getAllCoins:()=>J1,getMSafeConfig:()=>ol,getPublicKeyFromChain:()=>Ju,stringToBuffer:()=>pa});module.exports=kl(Y1);var Mn=require("@msafe/sui3-utils"),Vi=class{constructor(e,n){this.globals=e;this.pkHelper=n}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let n=await this.reduceCreationInfoToRawConfig(e);return new Mn.MultiSigAccount(n).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,n){let i=Mn.PublicKeySerde.de(n);if(!(0,Mn.isSameAddress)(e,i.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,i)}async submitMSafeCreation(e){let n=await this.validateCreateInfo(e),i=Mn.SigningMessageHelper.createMSafeMessage(n),r=await this.globals.wallet.signPersonalMessage({messageStr:i});return await this.submitToBackend(e,r.signature),n}async reduceCreationInfoToRawConfig(e){let n=await this.getPublicKeyBatch(e.owners.map(i=>i.address));return n.forEach((i,r)=>{if(i===void 0)throw new Error(`Unknown public key for address: ${e.owners[r].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((i,r)=>({publicKey:n[r],weight:i.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,n){let i=await this.pkHelper.getPublicKeyBatch(e.owners.map(r=>r.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((r,o)=>({address:r.address,weight:r.weight,...Mn.PublicKeySerde.ser(i[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:n})}};var xa=require("@msafe/sui3-utils");var Tl=require("@msafe/sui3-utils"),Gi=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let n=Tl.SigningMessageHelper.updateAddressBookMessage(e),i=await this.globals.wallet.signPersonalMessage({messageStr:n});return this.globals.backend.updateAddressBook({updates:e,signature:i.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var $o=class{constructor(e){this.globals=e}async getMSafeByStatus(e,n){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:n})}async updateMSafeStatus(e,n){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:n})}};var Tm=require("@msafe/sui3-utils"),Cm=ge(Uo(),1);var Rr=require("@mysten/sui.js/utils"),er=require("@mysten/sui.js/transactions"),rn=ge(ke(),1);var Xa=8192;function Ja(t){if(t.length<Xa)return btoa(String.fromCharCode(...t));let e="";for(var n=0;n<t.length;n+=Xa){let i=t.slice(n,n+Xa);e+=String.fromCharCode(...i)}return btoa(e)}var r0=require("@mysten/sui.js/keypairs/ed25519"),o0=require("@mysten/sui.js/keypairs/secp256k1"),Xn=ge(ke(),1),wt=ge(ke(),1);var Wi=9e15,Zn=1e9,Ya="0123456789abcdef",zo="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Vo="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Qa={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Wi,maxE:Wi,crypto:!1},ql,Bn,fe=!0,Wo="[DecimalError] ",Hn=Wo+"Invalid argument: ",Ll=Wo+"Precision limit exceeded",$l=Wo+"crypto unavailable",Ul="[object Decimal]",jt=Math.floor,kt=Math.pow,Ug=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Kg=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,zg=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Kl=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,fn=1e7,le=7,Vg=9007199254740991,Gg=zo.length-1,ec=Vo.length-1,z={toStringTag:Ul};z.absoluteValue=z.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),oe(t)};z.ceil=function(){return oe(new this.constructor(this),this.e+1,2)};z.clampedTo=z.clamp=function(t,e){var n,i=this,r=i.constructor;if(t=new r(t),e=new r(e),!t.s||!e.s)return new r(NaN);if(t.gt(e))throw Error(Hn+e);return n=i.cmp(t),n<0?t:i.cmp(e)>0?e:new r(i)};z.comparedTo=z.cmp=function(t){var e,n,i,r,o=this,s=o.d,a=(t=new o.constructor(t)).d,u=o.s,l=t.s;if(!s||!a)return!u||!l?NaN:u!==l?u:s===a?0:!s^u<0?1:-1;if(!s[0]||!a[0])return s[0]?u:a[0]?-l:0;if(u!==l)return u;if(o.e!==t.e)return o.e>t.e^u<0?1:-1;for(i=s.length,r=a.length,e=0,n=i<r?i:r;e<n;++e)if(s[e]!==a[e])return s[e]>a[e]^u<0?1:-1;return i===r?0:i>r^u<0?1:-1};z.cosine=z.cos=function(){var t,e,n=this,i=n.constructor;return n.d?n.d[0]?(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+le,i.rounding=1,n=Wg(i,Hl(i,n)),i.precision=t,i.rounding=e,oe(Bn==2||Bn==3?n.neg():n,t,e,!0)):new i(1):new i(NaN)};z.cubeRoot=z.cbrt=function(){var t,e,n,i,r,o,s,a,u,l,h=this,w=h.constructor;if(!h.isFinite()||h.isZero())return new w(h);for(fe=!1,o=h.s*kt(h.s*h,1/3),!o||Math.abs(o)==1/0?(n=xt(h.d),t=h.e,(o=(t-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=kt(n,1/3),t=jt((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?n="5e"+t:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+t),i=new w(n),i.s=h.s):i=new w(o.toString()),s=(t=w.precision)+3;;)if(a=i,u=a.times(a).times(a),l=u.plus(h),i=Ee(l.plus(h).times(a),l.plus(u),s+2,1),xt(a.d).slice(0,s)===(n=xt(i.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!r&&n=="4999"){if(!r&&(oe(a,t+1,0),a.times(a).times(a).eq(h))){i=a;break}s+=4,r=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(oe(i,t+1,1),e=!i.times(i).times(i).eq(h));break}return fe=!0,oe(i,t,w.rounding,e)};z.decimalPlaces=z.dp=function(){var t,e=this.d,n=NaN;if(e){if(t=e.length-1,n=(t-jt(this.e/le))*le,t=e[t],t)for(;t%10==0;t/=10)n--;n<0&&(n=0)}return n};z.dividedBy=z.div=function(t){return Ee(this,new this.constructor(t))};z.dividedToIntegerBy=z.divToInt=function(t){var e=this,n=e.constructor;return oe(Ee(e,new n(t),0,1,1),n.precision,n.rounding)};z.equals=z.eq=function(t){return this.cmp(t)===0};z.floor=function(){return oe(new this.constructor(this),this.e+1,3)};z.greaterThan=z.gt=function(t){return this.cmp(t)>0};z.greaterThanOrEqualTo=z.gte=function(t){var e=this.cmp(t);return e==1||e===0};z.hyperbolicCosine=z.cosh=function(){var t,e,n,i,r,o=this,s=o.constructor,a=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return a;n=s.precision,i=s.rounding,s.precision=n+Math.max(o.e,o.sd())+4,s.rounding=1,r=o.d.length,r<32?(t=Math.ceil(r/3),e=(1/Zo(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=Hi(s,1,o.times(e),new s(1),!0);for(var u,l=t,h=new s(8);l--;)u=o.times(o),o=a.minus(u.times(h.minus(u.times(h))));return oe(o,s.precision=n,s.rounding=i,!0)};z.hyperbolicSine=z.sinh=function(){var t,e,n,i,r=this,o=r.constructor;if(!r.isFinite()||r.isZero())return new o(r);if(e=o.precision,n=o.rounding,o.precision=e+Math.max(r.e,r.sd())+4,o.rounding=1,i=r.d.length,i<3)r=Hi(o,2,r,r,!0);else{t=1.4*Math.sqrt(i),t=t>16?16:t|0,r=r.times(1/Zo(5,t)),r=Hi(o,2,r,r,!0);for(var s,a=new o(5),u=new o(16),l=new o(20);t--;)s=r.times(r),r=r.times(a.plus(s.times(u.times(s).plus(l))))}return o.precision=e,o.rounding=n,oe(r,e,n,!0)};z.hyperbolicTangent=z.tanh=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+7,i.rounding=1,Ee(n.sinh(),n.cosh(),i.precision=t,i.rounding=e)):new i(n.s)};z.inverseCosine=z.acos=function(){var t,e=this,n=e.constructor,i=e.abs().cmp(1),r=n.precision,o=n.rounding;return i!==-1?i===0?e.isNeg()?dn(n,r,o):new n(0):new n(NaN):e.isZero()?dn(n,r+4,o).times(.5):(n.precision=r+6,n.rounding=1,e=e.asin(),t=dn(n,r+4,o).times(.5),n.precision=r,n.rounding=o,t.minus(e))};z.inverseHyperbolicCosine=z.acosh=function(){var t,e,n=this,i=n.constructor;return n.lte(1)?new i(n.eq(1)?0:NaN):n.isFinite()?(t=i.precision,e=i.rounding,i.precision=t+Math.max(Math.abs(n.e),n.sd())+4,i.rounding=1,fe=!1,n=n.times(n).minus(1).sqrt().plus(n),fe=!0,i.precision=t,i.rounding=e,n.ln()):new i(n)};z.inverseHyperbolicSine=z.asinh=function(){var t,e,n=this,i=n.constructor;return!n.isFinite()||n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+2*Math.max(Math.abs(n.e),n.sd())+6,i.rounding=1,fe=!1,n=n.times(n).plus(1).sqrt().plus(n),fe=!0,i.precision=t,i.rounding=e,n.ln())};z.inverseHyperbolicTangent=z.atanh=function(){var t,e,n,i,r=this,o=r.constructor;return r.isFinite()?r.e>=0?new o(r.abs().eq(1)?r.s/0:r.isZero()?r:NaN):(t=o.precision,e=o.rounding,i=r.sd(),Math.max(i,t)<2*-r.e-1?oe(new o(r),t,e,!0):(o.precision=n=i-r.e,r=Ee(r.plus(1),new o(1).minus(r),n+t,1),o.precision=t+4,o.rounding=1,r=r.ln(),o.precision=t,o.rounding=e,r.times(.5))):new o(NaN)};z.inverseSine=z.asin=function(){var t,e,n,i,r=this,o=r.constructor;return r.isZero()?new o(r):(e=r.abs().cmp(1),n=o.precision,i=o.rounding,e!==-1?e===0?(t=dn(o,n+4,i).times(.5),t.s=r.s,t):new o(NaN):(o.precision=n+6,o.rounding=1,r=r.div(new o(1).minus(r.times(r)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=i,r.times(2)))};z.inverseTangent=z.atan=function(){var t,e,n,i,r,o,s,a,u,l=this,h=l.constructor,w=h.precision,v=h.rounding;if(l.isFinite()){if(l.isZero())return new h(l);if(l.abs().eq(1)&&w+4<=ec)return s=dn(h,w+4,v).times(.25),s.s=l.s,s}else{if(!l.s)return new h(NaN);if(w+4<=ec)return s=dn(h,w+4,v).times(.5),s.s=l.s,s}for(h.precision=a=w+10,h.rounding=1,n=Math.min(28,a/le+2|0),t=n;t;--t)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(fe=!1,e=Math.ceil(a/le),i=1,u=l.times(l),s=new h(l),r=l;t!==-1;)if(r=r.times(u),o=s.minus(r.div(i+=2)),r=r.times(u),s=o.plus(r.div(i+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return n&&(s=s.times(2<<n-1)),fe=!0,oe(s,h.precision=w,h.rounding=v,!0)};z.isFinite=function(){return!!this.d};z.isInteger=z.isInt=function(){return!!this.d&&jt(this.e/le)>this.d.length-2};z.isNaN=function(){return!this.s};z.isNegative=z.isNeg=function(){return this.s<0};z.isPositive=z.isPos=function(){return this.s>0};z.isZero=function(){return!!this.d&&this.d[0]===0};z.lessThan=z.lt=function(t){return this.cmp(t)<0};z.lessThanOrEqualTo=z.lte=function(t){return this.cmp(t)<1};z.logarithm=z.log=function(t){var e,n,i,r,o,s,a,u,l=this,h=l.constructor,w=h.precision,v=h.rounding,T=5;if(t==null)t=new h(10),e=!0;else{if(t=new h(t),n=t.d,t.s<0||!n||!n[0]||t.eq(1))return new h(NaN);e=t.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new h(n&&!n[0]?-1/0:l.s!=1?NaN:n?0:1/0);if(e)if(n.length>1)o=!0;else{for(r=n[0];r%10===0;)r/=10;o=r!==1}if(fe=!1,a=w+T,s=Wn(l,a),i=e?Go(h,a+10):Wn(t,a),u=Ee(s,i,a,1),jr(u.d,r=w,v))do if(a+=10,s=Wn(l,a),i=e?Go(h,a+10):Wn(t,a),u=Ee(s,i,a,1),!o){+xt(u.d).slice(r+1,r+15)+1==1e14&&(u=oe(u,w+1,0));break}while(jr(u.d,r+=10,v));return fe=!0,oe(u,w,v)};z.minus=z.sub=function(t){var e,n,i,r,o,s,a,u,l,h,w,v,T=this,I=T.constructor;if(t=new I(t),!T.d||!t.d)return!T.s||!t.s?t=new I(NaN):T.d?t.s=-t.s:t=new I(t.d||T.s!==t.s?T:NaN),t;if(T.s!=t.s)return t.s=-t.s,T.plus(t);if(l=T.d,v=t.d,a=I.precision,u=I.rounding,!l[0]||!v[0]){if(v[0])t.s=-t.s;else if(l[0])t=new I(T);else return new I(u===3?-0:0);return fe?oe(t,a,u):t}if(n=jt(t.e/le),h=jt(T.e/le),l=l.slice(),o=h-n,o){for(w=o<0,w?(e=l,o=-o,s=v.length):(e=v,n=h,s=l.length),i=Math.max(Math.ceil(a/le),s)+2,o>i&&(o=i,e.length=1),e.reverse(),i=o;i--;)e.push(0);e.reverse()}else{for(i=l.length,s=v.length,w=i<s,w&&(s=i),i=0;i<s;i++)if(l[i]!=v[i]){w=l[i]<v[i];break}o=0}for(w&&(e=l,l=v,v=e,t.s=-t.s),s=l.length,i=v.length-s;i>0;--i)l[s++]=0;for(i=v.length;i>o;){if(l[--i]<v[i]){for(r=i;r&&l[--r]===0;)l[r]=fn-1;--l[r],l[i]+=fn}l[i]-=v[i]}for(;l[--s]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(t.d=l,t.e=Ho(l,n),fe?oe(t,a,u):t):new I(u===3?-0:0)};z.modulo=z.mod=function(t){var e,n=this,i=n.constructor;return t=new i(t),!n.d||!t.s||t.d&&!t.d[0]?new i(NaN):!t.d||n.d&&!n.d[0]?oe(new i(n),i.precision,i.rounding):(fe=!1,i.modulo==9?(e=Ee(n,t.abs(),0,3,1),e.s*=t.s):e=Ee(n,t,0,i.modulo,1),e=e.times(t),fe=!0,n.minus(e))};z.naturalExponential=z.exp=function(){return tc(this)};z.naturalLogarithm=z.ln=function(){return Wn(this)};z.negated=z.neg=function(){var t=new this.constructor(this);return t.s=-t.s,oe(t)};z.plus=z.add=function(t){var e,n,i,r,o,s,a,u,l,h,w=this,v=w.constructor;if(t=new v(t),!w.d||!t.d)return!w.s||!t.s?t=new v(NaN):w.d||(t=new v(t.d||w.s===t.s?w:NaN)),t;if(w.s!=t.s)return t.s=-t.s,w.minus(t);if(l=w.d,h=t.d,a=v.precision,u=v.rounding,!l[0]||!h[0])return h[0]||(t=new v(w)),fe?oe(t,a,u):t;if(o=jt(w.e/le),i=jt(t.e/le),l=l.slice(),r=o-i,r){for(r<0?(n=l,r=-r,s=h.length):(n=h,i=o,s=l.length),o=Math.ceil(a/le),s=o>s?o+1:s+1,r>s&&(r=s,n.length=1),n.reverse();r--;)n.push(0);n.reverse()}for(s=l.length,r=h.length,s-r<0&&(r=s,n=h,h=l,l=n),e=0;r;)e=(l[--r]=l[r]+h[r]+e)/fn|0,l[r]%=fn;for(e&&(l.unshift(e),++i),s=l.length;l[--s]==0;)l.pop();return t.d=l,t.e=Ho(l,i),fe?oe(t,a,u):t};z.precision=z.sd=function(t){var e,n=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Hn+t);return n.d?(e=zl(n.d),t&&n.e+1>e&&(e=n.e+1)):e=NaN,e};z.round=function(){var t=this,e=t.constructor;return oe(new e(t),t.e+1,e.rounding)};z.sine=z.sin=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+Math.max(n.e,n.sd())+le,i.rounding=1,n=Zg(i,Hl(i,n)),i.precision=t,i.rounding=e,oe(Bn>2?n.neg():n,t,e,!0)):new i(NaN)};z.squareRoot=z.sqrt=function(){var t,e,n,i,r,o,s=this,a=s.d,u=s.e,l=s.s,h=s.constructor;if(l!==1||!a||!a[0])return new h(!l||l<0&&(!a||a[0])?NaN:a?s:1/0);for(fe=!1,l=Math.sqrt(+s),l==0||l==1/0?(e=xt(a),(e.length+u)%2==0&&(e+="0"),l=Math.sqrt(e),u=jt((u+1)/2)-(u<0||u%2),l==1/0?e="5e"+u:(e=l.toExponential(),e=e.slice(0,e.indexOf("e")+1)+u),i=new h(e)):i=new h(l.toString()),n=(u=h.precision)+3;;)if(o=i,i=o.plus(Ee(s,o,n+2,1)).times(.5),xt(o.d).slice(0,n)===(e=xt(i.d)).slice(0,n))if(e=e.slice(n-3,n+1),e=="9999"||!r&&e=="4999"){if(!r&&(oe(o,u+1,0),o.times(o).eq(s))){i=o;break}n+=4,r=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(oe(i,u+1,1),t=!i.times(i).eq(s));break}return fe=!0,oe(i,u,h.rounding,t)};z.tangent=z.tan=function(){var t,e,n=this,i=n.constructor;return n.isFinite()?n.isZero()?new i(n):(t=i.precision,e=i.rounding,i.precision=t+10,i.rounding=1,n=n.sin(),n.s=1,n=Ee(n,new i(1).minus(n.times(n)).sqrt(),t+10,0),i.precision=t,i.rounding=e,oe(Bn==2||Bn==4?n.neg():n,t,e,!0)):new i(NaN)};z.times=z.mul=function(t){var e,n,i,r,o,s,a,u,l,h=this,w=h.constructor,v=h.d,T=(t=new w(t)).d;if(t.s*=h.s,!v||!v[0]||!T||!T[0])return new w(!t.s||v&&!v[0]&&!T||T&&!T[0]&&!v?NaN:!v||!T?t.s/0:t.s*0);for(n=jt(h.e/le)+jt(t.e/le),u=v.length,l=T.length,u<l&&(o=v,v=T,T=o,s=u,u=l,l=s),o=[],s=u+l,i=s;i--;)o.push(0);for(i=l;--i>=0;){for(e=0,r=u+i;r>i;)a=o[r]+T[i]*v[r-i-1]+e,o[r--]=a%fn|0,e=a/fn|0;o[r]=(o[r]+e)%fn|0}for(;!o[--s];)o.pop();return e?++n:o.shift(),t.d=o,t.e=Ho(o,n),fe?oe(t,w.precision,w.rounding):t};z.toBinary=function(t,e){return ic(this,2,t,e)};z.toDecimalPlaces=z.toDP=function(t,e){var n=this,i=n.constructor;return n=new i(n),t===void 0?n:(Kt(t,0,Zn),e===void 0?e=i.rounding:Kt(e,0,8),oe(n,t+n.e+1,e))};z.toExponential=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Tn(i,!0):(Kt(t,0,Zn),e===void 0?e=r.rounding:Kt(e,0,8),i=oe(new r(i),t+1,e),n=Tn(i,!0,t+1)),i.isNeg()&&!i.isZero()?"-"+n:n};z.toFixed=function(t,e){var n,i,r=this,o=r.constructor;return t===void 0?n=Tn(r):(Kt(t,0,Zn),e===void 0?e=o.rounding:Kt(e,0,8),i=oe(new o(r),t+r.e+1,e),n=Tn(i,!1,t+i.e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};z.toFraction=function(t){var e,n,i,r,o,s,a,u,l,h,w,v,T=this,I=T.d,x=T.constructor;if(!I)return new x(T);if(l=n=new x(1),i=u=new x(0),e=new x(i),o=e.e=zl(I)-T.e-1,s=o%le,e.d[0]=kt(10,s<0?le+s:s),t==null)t=o>0?e:l;else{if(a=new x(t),!a.isInt()||a.lt(l))throw Error(Hn+a);t=a.gt(e)?o>0?e:l:a}for(fe=!1,a=new x(xt(I)),h=x.precision,x.precision=o=I.length*le*2;w=Ee(a,e,0,1,1),r=n.plus(w.times(i)),r.cmp(t)!=1;)n=i,i=r,r=l,l=u.plus(w.times(r)),u=r,r=e,e=a.minus(w.times(r)),a=r;return r=Ee(t.minus(n),i,0,1,1),u=u.plus(r.times(l)),n=n.plus(r.times(i)),u.s=l.s=T.s,v=Ee(l,i,o,1).minus(T).abs().cmp(Ee(u,n,o,1).minus(T).abs())<1?[l,i]:[u,n],x.precision=h,fe=!0,v};z.toHexadecimal=z.toHex=function(t,e){return ic(this,16,t,e)};z.toNearest=function(t,e){var n=this,i=n.constructor;if(n=new i(n),t==null){if(!n.d)return n;t=new i(1),e=i.rounding}else{if(t=new i(t),e===void 0?e=i.rounding:Kt(e,0,8),!n.d)return t.s?n:t;if(!t.d)return t.s&&(t.s=n.s),t}return t.d[0]?(fe=!1,n=Ee(n,t,0,e,1).times(t),fe=!0,oe(n)):(t.s=n.s,n=t),n};z.toNumber=function(){return+this};z.toOctal=function(t,e){return ic(this,8,t,e)};z.toPower=z.pow=function(t){var e,n,i,r,o,s,a=this,u=a.constructor,l=+(t=new u(t));if(!a.d||!t.d||!a.d[0]||!t.d[0])return new u(kt(+a,l));if(a=new u(a),a.eq(1))return a;if(i=u.precision,o=u.rounding,t.eq(1))return oe(a,i,o);if(e=jt(t.e/le),e>=t.d.length-1&&(n=l<0?-l:l)<=Vg)return r=Vl(u,a,n,i),t.s<0?new u(1).div(r):oe(r,i,o);if(s=a.s,s<0){if(e<t.d.length-1)return new u(NaN);if(t.d[e]&1||(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return n=kt(+a,l),e=n==0||!isFinite(n)?jt(l*(Math.log("0."+xt(a.d))/Math.LN10+a.e+1)):new u(n+"").e,e>u.maxE+1||e<u.minE-1?new u(e>0?s/0:0):(fe=!1,u.rounding=a.s=1,n=Math.min(12,(e+"").length),r=tc(t.times(Wn(a,i+n)),i),r.d&&(r=oe(r,i+5,1),jr(r.d,i,o)&&(e=i+10,r=oe(tc(t.times(Wn(a,e+n)),e),e+5,1),+xt(r.d).slice(i+1,i+15)+1==1e14&&(r=oe(r,i+1,0)))),r.s=s,fe=!0,u.rounding=o,oe(r,i,o))};z.toPrecision=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Tn(i,i.e<=r.toExpNeg||i.e>=r.toExpPos):(Kt(t,1,Zn),e===void 0?e=r.rounding:Kt(e,0,8),i=oe(new r(i),t,e),n=Tn(i,t<=i.e||i.e<=r.toExpNeg,t)),i.isNeg()&&!i.isZero()?"-"+n:n};z.toSignificantDigits=z.toSD=function(t,e){var n=this,i=n.constructor;return t===void 0?(t=i.precision,e=i.rounding):(Kt(t,1,Zn),e===void 0?e=i.rounding:Kt(e,0,8)),oe(new i(n),t,e)};z.toString=function(){var t=this,e=t.constructor,n=Tn(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+n:n};z.truncated=z.trunc=function(){return oe(new this.constructor(this),this.e+1,1)};z.valueOf=z.toJSON=function(){var t=this,e=t.constructor,n=Tn(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+n:n};function xt(t){var e,n,i,r=t.length-1,o="",s=t[0];if(r>0){for(o+=s,e=1;e<r;e++)i=t[e]+"",n=le-i.length,n&&(o+=Gn(n)),o+=i;s=t[e],i=s+"",n=le-i.length,n&&(o+=Gn(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Kt(t,e,n){if(t!==~~t||t<e||t>n)throw Error(Hn+t)}function jr(t,e,n,i){var r,o,s,a;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=le,r=0):(r=Math.ceil((e+1)/le),e%=le),o=kt(10,le-e),a=t[r]%o|0,i==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=n<4&&a==99999||n>3&&a==49999||a==5e4||a==0):s=(n<4&&a+1==o||n>3&&a+1==o/2)&&(t[r+1]/o/100|0)==kt(10,e-2)-1||(a==o/2||a==0)&&(t[r+1]/o/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(i||n<4)&&a==9999||!i&&n>3&&a==4999):s=((i||n<4)&&a+1==o||!i&&n>3&&a+1==o/2)&&(t[r+1]/o/1e3|0)==kt(10,e-3)-1,s}function Ko(t,e,n){for(var i,r=[0],o,s=0,a=t.length;s<a;){for(o=r.length;o--;)r[o]*=e;for(r[0]+=Ya.indexOf(t.charAt(s++)),i=0;i<r.length;i++)r[i]>n-1&&(r[i+1]===void 0&&(r[i+1]=0),r[i+1]+=r[i]/n|0,r[i]%=n)}return r.reverse()}function Wg(t,e){var n,i,r;if(e.isZero())return e;i=e.d.length,i<32?(n=Math.ceil(i/3),r=(1/Zo(4,n)).toString()):(n=16,r="2.3283064365386962890625e-10"),t.precision+=n,e=Hi(t,1,e.times(r),new t(1));for(var o=n;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=n,e}var Ee=function(){function t(i,r,o){var s,a=0,u=i.length;for(i=i.slice();u--;)s=i[u]*r+a,i[u]=s%o|0,a=s/o|0;return a&&i.unshift(a),i}function e(i,r,o,s){var a,u;if(o!=s)u=o>s?1:-1;else for(a=u=0;a<o;a++)if(i[a]!=r[a]){u=i[a]>r[a]?1:-1;break}return u}function n(i,r,o,s){for(var a=0;o--;)i[o]-=a,a=i[o]<r[o]?1:0,i[o]=a*s+i[o]-r[o];for(;!i[0]&&i.length>1;)i.shift()}return function(i,r,o,s,a,u){var l,h,w,v,T,I,x,P,O,E,B,$,Z,H,te,U,V,F,K,C,A=i.constructor,c=i.s==r.s?1:-1,d=i.d,g=r.d;if(!d||!d[0]||!g||!g[0])return new A(!i.s||!r.s||(d?g&&d[0]==g[0]:!g)?NaN:d&&d[0]==0||!g?c*0:c/0);for(u?(T=1,h=i.e-r.e):(u=fn,T=le,h=jt(i.e/T)-jt(r.e/T)),K=g.length,V=d.length,O=new A(c),E=O.d=[],w=0;g[w]==(d[w]||0);w++);if(g[w]>(d[w]||0)&&h--,o==null?(H=o=A.precision,s=A.rounding):a?H=o+(i.e-r.e)+1:H=o,H<0)E.push(1),I=!0;else{if(H=H/T+2|0,w=0,K==1){for(v=0,g=g[0],H++;(w<V||v)&&H--;w++)te=v*u+(d[w]||0),E[w]=te/g|0,v=te%g|0;I=v||w<V}else{for(v=u/(g[0]+1)|0,v>1&&(g=t(g,v,u),d=t(d,v,u),K=g.length,V=d.length),U=K,B=d.slice(0,K),$=B.length;$<K;)B[$++]=0;C=g.slice(),C.unshift(0),F=g[0],g[1]>=u/2&&++F;do v=0,l=e(g,B,K,$),l<0?(Z=B[0],K!=$&&(Z=Z*u+(B[1]||0)),v=Z/F|0,v>1?(v>=u&&(v=u-1),x=t(g,v,u),P=x.length,$=B.length,l=e(x,B,P,$),l==1&&(v--,n(x,K<P?C:g,P,u))):(v==0&&(l=v=1),x=g.slice()),P=x.length,P<$&&x.unshift(0),n(B,x,$,u),l==-1&&($=B.length,l=e(g,B,K,$),l<1&&(v++,n(B,K<$?C:g,$,u))),$=B.length):l===0&&(v++,B=[0]),E[w++]=v,l&&B[0]?B[$++]=d[U]||0:(B=[d[U]],$=1);while((U++<V||B[0]!==void 0)&&H--);I=B[0]!==void 0}E[0]||E.shift()}if(T==1)O.e=h,ql=I;else{for(w=1,v=E[0];v>=10;v/=10)w++;O.e=w+h*T-1,oe(O,a?o+O.e+1:o,s,I)}return O}}();function oe(t,e,n,i){var r,o,s,a,u,l,h,w,v,T=t.constructor;e:if(e!=null){if(w=t.d,!w)return t;for(r=1,a=w[0];a>=10;a/=10)r++;if(o=e-r,o<0)o+=le,s=e,h=w[v=0],u=h/kt(10,r-s-1)%10|0;else if(v=Math.ceil((o+1)/le),a=w.length,v>=a)if(i){for(;a++<=v;)w.push(0);h=u=0,r=1,o%=le,s=o-le+1}else break e;else{for(h=a=w[v],r=1;a>=10;a/=10)r++;o%=le,s=o-le+r,u=s<0?0:h/kt(10,r-s-1)%10|0}if(i=i||e<0||w[v+1]!==void 0||(s<0?h:h%kt(10,r-s-1)),l=n<4?(u||i)&&(n==0||n==(t.s<0?3:2)):u>5||u==5&&(n==4||i||n==6&&(o>0?s>0?h/kt(10,r-s):0:w[v-1])%10&1||n==(t.s<0?8:7)),e<1||!w[0])return w.length=0,l?(e-=t.e+1,w[0]=kt(10,(le-e%le)%le),t.e=-e||0):w[0]=t.e=0,t;if(o==0?(w.length=v,a=1,v--):(w.length=v+1,a=kt(10,le-o),w[v]=s>0?(h/kt(10,r-s)%kt(10,s)|0)*a:0),l)for(;;)if(v==0){for(o=1,s=w[0];s>=10;s/=10)o++;for(s=w[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(t.e++,w[0]==fn&&(w[0]=1));break}else{if(w[v]+=a,w[v]!=fn)break;w[v--]=0,a=1}for(o=w.length;w[--o]===0;)w.pop()}return fe&&(t.e>T.maxE?(t.d=null,t.e=NaN):t.e<T.minE&&(t.e=0,t.d=[0])),t}function Tn(t,e,n){if(!t.isFinite())return Wl(t);var i,r=t.e,o=xt(t.d),s=o.length;return e?(n&&(i=n-s)>0?o=o.charAt(0)+"."+o.slice(1)+Gn(i):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):r<0?(o="0."+Gn(-r-1)+o,n&&(i=n-s)>0&&(o+=Gn(i))):r>=s?(o+=Gn(r+1-s),n&&(i=n-r-1)>0&&(o=o+"."+Gn(i))):((i=r+1)<s&&(o=o.slice(0,i)+"."+o.slice(i)),n&&(i=n-s)>0&&(r+1===s&&(o+="."),o+=Gn(i))),o}function Ho(t,e){var n=t[0];for(e*=le;n>=10;n/=10)e++;return e}function Go(t,e,n){if(e>Gg)throw fe=!0,n&&(t.precision=n),Error(Ll);return oe(new t(zo),e,1,!0)}function dn(t,e,n){if(e>ec)throw Error(Ll);return oe(new t(Vo),e,n,!0)}function zl(t){var e=t.length-1,n=e*le+1;if(e=t[e],e){for(;e%10==0;e/=10)n--;for(e=t[0];e>=10;e/=10)n++}return n}function Gn(t){for(var e="";t--;)e+="0";return e}function Vl(t,e,n,i){var r,o=new t(1),s=Math.ceil(i/le+4);for(fe=!1;;){if(n%2&&(o=o.times(e),Fl(o.d,s)&&(r=!0)),n=jt(n/2),n===0){n=o.d.length-1,r&&o.d[n]===0&&++o.d[n];break}e=e.times(e),Fl(e.d,s)}return fe=!0,o}function Nl(t){return t.d[t.d.length-1]&1}function Gl(t,e,n){for(var i,r=new t(e[0]),o=0;++o<e.length;)if(i=new t(e[o]),i.s)r[n](i)&&(r=i);else{r=i;break}return r}function tc(t,e){var n,i,r,o,s,a,u,l=0,h=0,w=0,v=t.constructor,T=v.rounding,I=v.precision;if(!t.d||!t.d[0]||t.e>17)return new v(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(fe=!1,u=I):u=e,a=new v(.03125);t.e>-2;)t=t.times(a),w+=5;for(i=Math.log(kt(2,w))/Math.LN10*2+5|0,u+=i,n=o=s=new v(1),v.precision=u;;){if(o=oe(o.times(t),u,1),n=n.times(++h),a=s.plus(Ee(o,n,u,1)),xt(a.d).slice(0,u)===xt(s.d).slice(0,u)){for(r=w;r--;)s=oe(s.times(s),u,1);if(e==null)if(l<3&&jr(s.d,u-i,T,l))v.precision=u+=10,n=o=a=new v(1),h=0,l++;else return oe(s,v.precision=I,T,fe=!0);else return v.precision=I,s}s=a}}function Wn(t,e){var n,i,r,o,s,a,u,l,h,w,v,T=1,I=10,x=t,P=x.d,O=x.constructor,E=O.rounding,B=O.precision;if(x.s<0||!P||!P[0]||!x.e&&P[0]==1&&P.length==1)return new O(P&&!P[0]?-1/0:x.s!=1?NaN:P?0:x);if(e==null?(fe=!1,h=B):h=e,O.precision=h+=I,n=xt(P),i=n.charAt(0),Math.abs(o=x.e)<15e14){for(;i<7&&i!=1||i==1&&n.charAt(1)>3;)x=x.times(t),n=xt(x.d),i=n.charAt(0),T++;o=x.e,i>1?(x=new O("0."+n),o++):x=new O(i+"."+n.slice(1))}else return l=Go(O,h+2,B).times(o+""),x=Wn(new O(i+"."+n.slice(1)),h-I).plus(l),O.precision=B,e==null?oe(x,B,E,fe=!0):x;for(w=x,u=s=x=Ee(x.minus(1),x.plus(1),h,1),v=oe(x.times(x),h,1),r=3;;){if(s=oe(s.times(v),h,1),l=u.plus(Ee(s,new O(r),h,1)),xt(l.d).slice(0,h)===xt(u.d).slice(0,h))if(u=u.times(2),o!==0&&(u=u.plus(Go(O,h+2,B).times(o+""))),u=Ee(u,new O(T),h,1),e==null)if(jr(u.d,h-I,E,a))O.precision=h+=I,l=s=x=Ee(w.minus(1),w.plus(1),h,1),v=oe(x.times(x),h,1),r=a=1;else return oe(u,O.precision=B,E,fe=!0);else return O.precision=B,u;u=l,r+=2}}function Wl(t){return String(t.s*t.s/0)}function nc(t,e){var n,i,r;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(i=e.search(/e/i))>0?(n<0&&(n=i),n+=+e.slice(i+1),e=e.substring(0,i)):n<0&&(n=e.length),i=0;e.charCodeAt(i)===48;i++);for(r=e.length;e.charCodeAt(r-1)===48;--r);if(e=e.slice(i,r),e){if(r-=i,t.e=n=n-i-1,t.d=[],i=(n+1)%le,n<0&&(i+=le),i<r){for(i&&t.d.push(+e.slice(0,i)),r-=le;i<r;)t.d.push(+e.slice(i,i+=le));e=e.slice(i),i=le-e.length}else i-=r;for(;i--;)e+="0";t.d.push(+e),fe&&(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 Hg(t,e){var n,i,r,o,s,a,u,l,h;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Kl.test(e))return nc(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(Kg.test(e))n=16,e=e.toLowerCase();else if(Ug.test(e))n=2;else if(zg.test(e))n=8;else throw Error(Hn+e);for(o=e.search(/p/i),o>0?(u=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,i=t.constructor,s&&(e=e.replace(".",""),a=e.length,o=a-o,r=Vl(i,new i(n),o,o*2)),l=Ko(e,n,fn),h=l.length-1,o=h;l[o]===0;--o)l.pop();return o<0?new i(t.s*0):(t.e=Ho(l,h),t.d=l,fe=!1,s&&(t=Ee(t,r,a*4)),u&&(t=t.times(Math.abs(u)<54?kt(2,u):Nr.pow(2,u))),fe=!0,t)}function Zg(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Hi(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/Zo(5,n)),e=Hi(t,2,e,e);for(var r,o=new t(5),s=new t(16),a=new t(20);n--;)r=e.times(e),e=e.times(o.plus(r.times(s.times(r).minus(a))));return e}function Hi(t,e,n,i,r){var o,s,a,u,l=1,h=t.precision,w=Math.ceil(h/le);for(fe=!1,u=n.times(n),a=new t(i);;){if(s=Ee(a.times(u),new t(e++*e++),h,1),a=r?i.plus(s):i.minus(s),i=Ee(s.times(u),new t(e++*e++),h,1),s=a.plus(i),s.d[w]!==void 0){for(o=w;s.d[o]===a.d[o]&&o--;);if(o==-1)break}o=a,a=i,i=s,s=o,l++}return fe=!0,s.d.length=w+1,s}function Zo(t,e){for(var n=t;--e;)n*=t;return n}function Hl(t,e){var n,i=e.s<0,r=dn(t,t.precision,1),o=r.times(.5);if(e=e.abs(),e.lte(o))return Bn=i?4:1,e;if(n=e.divToInt(r),n.isZero())Bn=i?3:2;else{if(e=e.minus(n.times(r)),e.lte(o))return Bn=Nl(n)?i?2:3:i?4:1,e;Bn=Nl(n)?i?1:4:i?3:2}return e.minus(r).abs()}function ic(t,e,n,i){var r,o,s,a,u,l,h,w,v,T=t.constructor,I=n!==void 0;if(I?(Kt(n,1,Zn),i===void 0?i=T.rounding:Kt(i,0,8)):(n=T.precision,i=T.rounding),!t.isFinite())h=Wl(t);else{for(h=Tn(t),s=h.indexOf("."),I?(r=2,e==16?n=n*4-3:e==8&&(n=n*3-2)):r=e,s>=0&&(h=h.replace(".",""),v=new T(1),v.e=h.length-s,v.d=Ko(Tn(v),10,r),v.e=v.d.length),w=Ko(h,10,r),o=u=w.length;w[--u]==0;)w.pop();if(!w[0])h=I?"0p+0":"0";else{if(s<0?o--:(t=new T(t),t.d=w,t.e=o,t=Ee(t,v,n,i,0,r),w=t.d,o=t.e,l=ql),s=w[n],a=r/2,l=l||w[n+1]!==void 0,l=i<4?(s!==void 0||l)&&(i===0||i===(t.s<0?3:2)):s>a||s===a&&(i===4||l||i===6&&w[n-1]&1||i===(t.s<0?8:7)),w.length=n,l)for(;++w[--n]>r-1;)w[n]=0,n||(++o,w.unshift(1));for(u=w.length;!w[u-1];--u);for(s=0,h="";s<u;s++)h+=Ya.charAt(w[s]);if(I){if(u>1)if(e==16||e==8){for(s=e==16?4:3,--u;u%s;u++)h+="0";for(w=Ko(h,r,e),u=w.length;!w[u-1];--u);for(s=1,h="1.";s<u;s++)h+=Ya.charAt(w[s])}else h=h.charAt(0)+"."+h.slice(1);h=h+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)h="0"+h;h="0."+h}else if(++o>u)for(o-=u;o--;)h+="0";else o<u&&(h=h.slice(0,o)+"."+h.slice(o))}h=(e==16?"0x":e==2?"0b":e==8?"0o":"")+h}return t.s<0?"-"+h:h}function Fl(t,e){if(t.length>e)return t.length=e,!0}function Xg(t){return new this(t).abs()}function Jg(t){return new this(t).acos()}function Yg(t){return new this(t).acosh()}function Qg(t,e){return new this(t).plus(e)}function e_(t){return new this(t).asin()}function t_(t){return new this(t).asinh()}function n_(t){return new this(t).atan()}function i_(t){return new this(t).atanh()}function r_(t,e){t=new this(t),e=new this(e);var n,i=this.precision,r=this.rounding,o=i+4;return!t.s||!e.s?n=new this(NaN):!t.d&&!e.d?(n=dn(this,o,1).times(e.s>0?.25:.75),n.s=t.s):!e.d||t.isZero()?(n=e.s<0?dn(this,i,r):new this(0),n.s=t.s):!t.d||e.isZero()?(n=dn(this,o,1).times(.5),n.s=t.s):e.s<0?(this.precision=o,this.rounding=1,n=this.atan(Ee(t,e,o,1)),e=dn(this,o,1),this.precision=i,this.rounding=r,n=t.s<0?n.minus(e):n.plus(e)):n=this.atan(Ee(t,e,o,1)),n}function o_(t){return new this(t).cbrt()}function s_(t){return oe(t=new this(t),t.e+1,2)}function a_(t,e,n){return new this(t).clamp(e,n)}function c_(t){if(!t||typeof t!="object")throw Error(Wo+"Object expected");var e,n,i,r=t.defaults===!0,o=["precision",1,Zn,"rounding",0,8,"toExpNeg",-Wi,0,"toExpPos",0,Wi,"maxE",0,Wi,"minE",-Wi,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(n=o[e],r&&(this[n]=Qa[n]),(i=t[n])!==void 0)if(jt(i)===i&&i>=o[e+1]&&i<=o[e+2])this[n]=i;else throw Error(Hn+n+": "+i);if(n="crypto",r&&(this[n]=Qa[n]),(i=t[n])!==void 0)if(i===!0||i===!1||i===0||i===1)if(i)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error($l);else this[n]=!1;else throw Error(Hn+n+": "+i);return this}function u_(t){return new this(t).cos()}function l_(t){return new this(t).cosh()}function Zl(t){var e,n,i;function r(o){var s,a,u,l=this;if(!(l instanceof r))return new r(o);if(l.constructor=r,Rl(o)){l.s=o.s,fe?!o.d||o.e>r.maxE?(l.e=NaN,l.d=null):o.e<r.minE?(l.e=0,l.d=[0]):(l.e=o.e,l.d=o.d.slice()):(l.e=o.e,l.d=o.d?o.d.slice():o.d);return}if(u=typeof o,u==="number"){if(o===0){l.s=1/o<0?-1:1,l.e=0,l.d=[0];return}if(o<0?(o=-o,l.s=-1):l.s=1,o===~~o&&o<1e7){for(s=0,a=o;a>=10;a/=10)s++;fe?s>r.maxE?(l.e=NaN,l.d=null):s<r.minE?(l.e=0,l.d=[0]):(l.e=s,l.d=[o]):(l.e=s,l.d=[o]);return}else if(o*0!==0){o||(l.s=NaN),l.e=NaN,l.d=null;return}return nc(l,o.toString())}else if(u!=="string")throw Error(Hn+o);return(a=o.charCodeAt(0))===45?(o=o.slice(1),l.s=-1):(a===43&&(o=o.slice(1)),l.s=1),Kl.test(o)?nc(l,o):Hg(l,o)}if(r.prototype=z,r.ROUND_UP=0,r.ROUND_DOWN=1,r.ROUND_CEIL=2,r.ROUND_FLOOR=3,r.ROUND_HALF_UP=4,r.ROUND_HALF_DOWN=5,r.ROUND_HALF_EVEN=6,r.ROUND_HALF_CEIL=7,r.ROUND_HALF_FLOOR=8,r.EUCLID=9,r.config=r.set=c_,r.clone=Zl,r.isDecimal=Rl,r.abs=Xg,r.acos=Jg,r.acosh=Yg,r.add=Qg,r.asin=e_,r.asinh=t_,r.atan=n_,r.atanh=i_,r.atan2=r_,r.cbrt=o_,r.ceil=s_,r.clamp=a_,r.cos=u_,r.cosh=l_,r.div=d_,r.exp=f_,r.floor=h_,r.hypot=m_,r.ln=p_,r.log=g_,r.log10=y_,r.log2=__,r.max=w_,r.min=b_,r.mod=v_,r.mul=k_,r.pow=T_,r.random=C_,r.round=S_,r.sign=A_,r.sin=x_,r.sinh=I_,r.sqrt=O_,r.sub=P_,r.sum=D_,r.tan=E_,r.tanh=M_,r.trunc=B_,t===void 0&&(t={}),t&&t.defaults!==!0)for(i=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<i.length;)t.hasOwnProperty(n=i[e++])||(t[n]=this[n]);return r.config(t),r}function d_(t,e){return new this(t).div(e)}function f_(t){return new this(t).exp()}function h_(t){return oe(t=new this(t),t.e+1,3)}function m_(){var t,e,n=new this(0);for(fe=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)n.d&&(n=n.plus(e.times(e)));else{if(e.s)return fe=!0,new this(1/0);n=e}return fe=!0,n.sqrt()}function Rl(t){return t instanceof Nr||t&&t.toStringTag===Ul||!1}function p_(t){return new this(t).ln()}function g_(t,e){return new this(t).log(e)}function __(t){return new this(t).log(2)}function y_(t){return new this(t).log(10)}function w_(){return Gl(this,arguments,"lt")}function b_(){return Gl(this,arguments,"gt")}function v_(t,e){return new this(t).mod(e)}function k_(t,e){return new this(t).mul(e)}function T_(t,e){return new this(t).pow(e)}function C_(t){var e,n,i,r,o=0,s=new this(1),a=[];if(t===void 0?t=this.precision:Kt(t,1,Zn),i=Math.ceil(t/le),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(i));o<i;)r=e[o],r>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:a[o++]=r%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(i*=4);o<i;)r=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),r>=214e7?crypto.randomBytes(4).copy(e,o):(a.push(r%1e7),o+=4);o=i/4}else throw Error($l);else for(;o<i;)a[o++]=Math.random()*1e7|0;for(i=a[--o],t%=le,i&&t&&(r=kt(10,le-t),a[o]=(i/r|0)*r);a[o]===0;o--)a.pop();if(o<0)n=0,a=[0];else{for(n=-1;a[0]===0;n-=le)a.shift();for(i=1,r=a[0];r>=10;r/=10)i++;i<le&&(n-=le-i)}return s.e=n,s.d=a,s}function S_(t){return oe(t=new this(t),t.e+1,this.rounding)}function A_(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function x_(t){return new this(t).sin()}function I_(t){return new this(t).sinh()}function O_(t){return new this(t).sqrt()}function P_(t,e){return new this(t).sub(e)}function D_(){var t=0,e=arguments,n=new this(e[t]);for(fe=!1;n.s&&++t<e.length;)n=n.plus(e[t]);return fe=!0,oe(n,this.precision,this.rounding)}function E_(t){return new this(t).tan()}function M_(t){return new this(t).tanh()}function B_(t){return oe(t=new this(t),t.e+1,1)}z[Symbol.for("nodejs.util.inspect.custom")]=z.toString;z[Symbol.toStringTag]="Decimal";var Nr=z.constructor=Zl(Qa);zo=new Nr(zo);Vo=new Nr(Vo);var N=Nr;var Gd=ge(ke(),1),Lr=ge(ke(),1);var ce=ge(ke(),1),Ie=ge(ke(),1),Zd=ge(ke(),1),ps=require("@mysten/sui.js/utils"),M0=ge(ke(),1),gc=ge(ke(),1),B0=ge(ke(),1);var wi=ge(ke(),1),qr=ge(ke(),1);var bi=require("@mysten/sui.js/transactions"),z0=require("@mysten/sui.js/utils"),V0=require("@mysten/sui.js/transactions"),Pt=ge(ke(),1),as=require("@mysten/sui.js/transactions"),yc=ge(ke(),1),vi=require("@mysten/sui.js/transactions"),of=require("@mysten/sui.js/utils"),Me=ge(ke(),1),cs=require("@mysten/sui.js/transactions"),Ht=ge(ke(),1),Ti=ge(vd(),1),sf=require("@mysten/sui.js/transactions"),ki=ge(ke(),1);var wc=require("@mysten/sui.js/transactions");var xd="3.7.7",U_=xd,Ji=typeof Buffer=="function",kd=typeof TextDecoder=="function"?new TextDecoder:void 0,Td=typeof TextEncoder=="function"?new TextEncoder:void 0,K_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Fr=Array.prototype.slice.call(K_),es=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(Fr),z_=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,It=String.fromCharCode.bind(String),Cd=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),Id=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Od=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Pd=t=>{let e,n,i,r,o="",s=t.length%3;for(let a=0;a<t.length;){if((n=t.charCodeAt(a++))>255||(i=t.charCodeAt(a++))>255||(r=t.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=n<<16|i<<8|r,o+=Fr[e>>18&63]+Fr[e>>12&63]+Fr[e>>6&63]+Fr[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},cc=typeof btoa=="function"?t=>btoa(t):Ji?t=>Buffer.from(t,"binary").toString("base64"):Pd,sc=Ji?t=>Buffer.from(t).toString("base64"):t=>{let n=[];for(let i=0,r=t.length;i<r;i+=4096)n.push(It.apply(null,t.subarray(i,i+4096)));return cc(n.join(""))},ts=(t,e=!1)=>e?Id(sc(t)):sc(t),V_=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?It(192|e>>>6)+It(128|e&63):It(224|e>>>12&15)+It(128|e>>>6&63)+It(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return It(240|e>>>18&7)+It(128|e>>>12&63)+It(128|e>>>6&63)+It(128|e&63)}},G_=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Dd=t=>t.replace(G_,V_),Sd=Ji?t=>Buffer.from(t,"utf8").toString("base64"):Td?t=>sc(Td.encode(t)):t=>cc(Dd(t)),Xi=(t,e=!1)=>e?Id(Sd(t)):Sd(t),Ad=t=>Xi(t,!0),W_=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,H_=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),n=e-65536;return It((n>>>10)+55296)+It((n&1023)+56320);case 3:return It((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return It((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Ed=t=>t.replace(W_,H_),Md=t=>{if(t=t.replace(/\s+/g,""),!z_.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,n="",i,r;for(let o=0;o<t.length;)e=es[t.charAt(o++)]<<18|es[t.charAt(o++)]<<12|(i=es[t.charAt(o++)])<<6|(r=es[t.charAt(o++)]),n+=i===64?It(e>>16&255):r===64?It(e>>16&255,e>>8&255):It(e>>16&255,e>>8&255,e&255);return n},uc=typeof atob=="function"?t=>atob(Od(t)):Ji?t=>Buffer.from(t,"base64").toString("binary"):Md,Bd=Ji?t=>Cd(Buffer.from(t,"base64")):t=>Cd(uc(t).split("").map(e=>e.charCodeAt(0))),jd=t=>Bd(Nd(t)),Z_=Ji?t=>Buffer.from(t,"base64").toString("utf8"):kd?t=>kd.decode(Bd(t)):t=>Ed(uc(t)),Nd=t=>Od(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),ac=t=>Z_(Nd(t)),X_=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)},Fd=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Rd=function(){let t=(e,n)=>Object.defineProperty(String.prototype,e,Fd(n));t("fromBase64",function(){return ac(this)}),t("toBase64",function(e){return Xi(this,e)}),t("toBase64URI",function(){return Xi(this,!0)}),t("toBase64URL",function(){return Xi(this,!0)}),t("toUint8Array",function(){return jd(this)})},qd=function(){let t=(e,n)=>Object.defineProperty(Uint8Array.prototype,e,Fd(n));t("toBase64",function(e){return ts(this,e)}),t("toBase64URI",function(){return ts(this,!0)}),t("toBase64URL",function(){return ts(this,!0)})},J_=()=>{Rd(),qd()},Yi={version:xd,VERSION:U_,atob:uc,atobPolyfill:Md,btoa:cc,btoaPolyfill:Pd,fromBase64:ac,toBase64:Xi,encode:Xi,encodeURI:Ad,encodeURL:Ad,utob:Dd,btou:Ed,decode:ac,isValid:X_,fromUint8Array:ts,toUint8Array:jd,extendString:Rd,extendUint8Array:qd,extendBuiltins:J_};var bc=require("@mysten/sui.js/transactions"),af=require("@mysten/sui.js/utils"),hn=ge(ke(),1);var ns,Y_=new Uint8Array(16);function lc(){if(!ns&&(ns=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ns))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ns(Y_)}var Ot=[];for(let t=0;t<256;++t)Ot.push((t+256).toString(16).slice(1));function Ld(t,e=0){return Ot[t[e+0]]+Ot[t[e+1]]+Ot[t[e+2]]+Ot[t[e+3]]+"-"+Ot[t[e+4]]+Ot[t[e+5]]+"-"+Ot[t[e+6]]+Ot[t[e+7]]+"-"+Ot[t[e+8]]+Ot[t[e+9]]+"-"+Ot[t[e+10]]+Ot[t[e+11]]+Ot[t[e+12]]+Ot[t[e+13]]+Ot[t[e+14]]+Ot[t[e+15]]}var Q_=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dc={randomUUID:Q_};function e0(t,e,n){if(dc.randomUUID&&!e&&!t)return dc.randomUUID();t=t||{};let i=t.random||(t.rng||lc)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=i[r];return e}return Ld(i)}var is=e0;var us=require("@mysten/sui.js/utils"),cf=require("@mysten/sui.js/transactions"),uf=require("@mysten/sui.js/client"),lf=require("@mysten/sui.js/bcs");var t0=Object.defineProperty,n0=(t,e,n)=>e in t?t0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,i0=(t,e,n)=>(n0(t,typeof e!="symbol"?e+"":e,n),n),Ue=5*60*1e3,X=24*60*60*1e3;function he(t){return Date.parse(new Date().toString())+t}var Be=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)}};N.config({precision:64,rounding:N.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var Dt=N,J=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof J&&t.errorCode===e}},ie=new wt.default(0),Cn=new wt.default(1),fs=new wt.default(2),Ok=fs.pow(new wt.default(128)),ir=fs.pow(new wt.default(64)).sub(Cn),s0=fs.pow(new wt.default(128)).sub(Cn),Te=class{static toX64_BN(t){return t.mul(new wt.default(2).pow(new wt.default(64)))}static toX64_Decimal(t){return t.mul(Dt.pow(2,64))}static toX64(t){return new wt.default(t.mul(Dt.pow(2,64)).floor().toFixed())}static fromX64(t){return new Dt(t.toString()).mul(Dt.pow(2,-64))}static fromX64_Decimal(t){return t.mul(Dt.pow(2,-64))}static fromX64_BN(t){return t.div(new wt.default(2).pow(new wt.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(ir).gt(ie)&&(e=e.add(Cn)),e}static divRoundUp(t,e){return t.mod(e).eq(ie)?t.div(e):t.div(e).add(new wt.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(s0):t.sub(e)}static checkUnsignedSub(t,e){let n=t.sub(e);if(n.isNeg())throw new J("Unsigned integer sub overflow","UnsignedIntegerOverflow");return n}static checkMul(t,e,n){let i=t.mul(e);if(this.isOverflow(i,n))throw new J("Multiplication overflow","MultiplicationOverflow");return i}static checkMulDivFloor(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivCeil(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e).add(n.sub(Cn)).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivRound(t,e,n,i){if(n.eq(ie))throw new J("Devide by zero","DivideByZero");let r=t.mul(e.add(n.shrn(1))).div(n);if(this.isOverflow(r,i))throw new J("Multiplication div overflow","MulDivOverflow");return r}static checkMulShiftRight(t,e,n,i){let r=t.mul(e).div(new wt.default(2).pow(new wt.default(n)));if(this.isOverflow(r,i))throw new J("Multiplication shift right overflow","MulShiftRightOverflow");return r}static checkMulShiftRight64RoundUpIf(t,e,n,i){let r=t.mul(e),s=i&&r.and(ir).gt(ie)?r.shrn(64).add(Cn):r.shrn(64);if(this.isOverflow(s,n))throw new J("Multiplication shift right overflow","MulShiftRightOverflow");return s}static checkMulShiftLeft(t,e,n,i){let r=t.mul(e).shln(n);if(this.isOverflow(r,i))throw new J("Multiplication shift left overflow","MulShiftLeftOverflow");return r}static checkDivRoundUpIf(t,e,n){if(e.eq(ie))throw new J("Devide by zero","DivideByZero");return n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(fs.pow(new wt.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(ie)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new wt.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 wt.default(1)))}static neg_from(t){return t.eq(ie)?t:this.u128_neg(t).add(new wt.default(1)).or(new wt.default(1).shln(127))}};function a0(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new Xn.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new Xn.default(t.fee_growth_global_a),feeGrowthGlobalB:new Xn.default(t.fee_growth_global_b),feeProtocolCoinA:new Xn.default(t.fee_protocol_coin_a),feeProtocolCoinB:new Xn.default(t.fee_protocol_coin_b),feeRate:new Xn.default(t.fee_rate),liquidity:new Xn.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var Wd=443636,Hd=-443636,hs="79226673515401279992447579055";var ms="4295048016",tr=new Gd.default(1e6),G="0x0000000000000000000000000000000000000000000000000000000000000006",c0="partner",nr="pool_script",jn="pool_script_v2",Jn="router",fc="router_with_partner",zt="fetcher_script",u0="expect_swap",$d="utils";var hc="custodian_v2",l0="clob_v2",d0="endpoints_v2";var vc=(t=>(t.Deleted="Deleted",t.Exists="Exists",t.NotExists="NotExists",t))(vc||{});function D(t){if(t.config===void 0)throw new J(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var f0=14,h0="59543866431248",m0="184467440737095516",p0="15793534762490258745",g0=443636;function _0(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}function _e(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}function y0(t){let e;return t&1?e=new ce.default("79232123823359799118286999567"):e=new ce.default("79228162514264337593543950336"),t&2&&(e=_e(e.mul(new ce.default("79236085330515764027303304731")),96,256)),t&4&&(e=_e(e.mul(new ce.default("79244008939048815603706035061")),96,256)),t&8&&(e=_e(e.mul(new ce.default("79259858533276714757314932305")),96,256)),t&16&&(e=_e(e.mul(new ce.default("79291567232598584799939703904")),96,256)),t&32&&(e=_e(e.mul(new ce.default("79355022692464371645785046466")),96,256)),t&64&&(e=_e(e.mul(new ce.default("79482085999252804386437311141")),96,256)),t&128&&(e=_e(e.mul(new ce.default("79736823300114093921829183326")),96,256)),t&256&&(e=_e(e.mul(new ce.default("80248749790819932309965073892")),96,256)),t&512&&(e=_e(e.mul(new ce.default("81282483887344747381513967011")),96,256)),t&1024&&(e=_e(e.mul(new ce.default("83390072131320151908154831281")),96,256)),t&2048&&(e=_e(e.mul(new ce.default("87770609709833776024991924138")),96,256)),t&4096&&(e=_e(e.mul(new ce.default("97234110755111693312479820773")),96,256)),t&8192&&(e=_e(e.mul(new ce.default("119332217159966728226237229890")),96,256)),t&16384&&(e=_e(e.mul(new ce.default("179736315981702064433883588727")),96,256)),t&32768&&(e=_e(e.mul(new ce.default("407748233172238350107850275304")),96,256)),t&65536&&(e=_e(e.mul(new ce.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=_e(e.mul(new ce.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=_e(e.mul(new ce.default("38992368544603139932233054999993551")),96,256)),_e(e,32,256)}function w0(t){let e=Math.abs(t),n;return e&1?n=new ce.default("18445821805675392311"):n=new ce.default("18446744073709551616"),e&2&&(n=_e(n.mul(new ce.default("18444899583751176498")),64,256)),e&4&&(n=_e(n.mul(new ce.default("18443055278223354162")),64,256)),e&8&&(n=_e(n.mul(new ce.default("18439367220385604838")),64,256)),e&16&&(n=_e(n.mul(new ce.default("18431993317065449817")),64,256)),e&32&&(n=_e(n.mul(new ce.default("18417254355718160513")),64,256)),e&64&&(n=_e(n.mul(new ce.default("18387811781193591352")),64,256)),e&128&&(n=_e(n.mul(new ce.default("18329067761203520168")),64,256)),e&256&&(n=_e(n.mul(new ce.default("18212142134806087854")),64,256)),e&512&&(n=_e(n.mul(new ce.default("17980523815641551639")),64,256)),e&1024&&(n=_e(n.mul(new ce.default("17526086738831147013")),64,256)),e&2048&&(n=_e(n.mul(new ce.default("16651378430235024244")),64,256)),e&4096&&(n=_e(n.mul(new ce.default("15030750278693429944")),64,256)),e&8192&&(n=_e(n.mul(new ce.default("12247334978882834399")),64,256)),e&16384&&(n=_e(n.mul(new ce.default("8131365268884726200")),64,256)),e&32768&&(n=_e(n.mul(new ce.default("3584323654723342297")),64,256)),e&65536&&(n=_e(n.mul(new ce.default("696457651847595233")),64,256)),e&131072&&(n=_e(n.mul(new ce.default("26294789957452057")),64,256)),e&262144&&(n=_e(n.mul(new ce.default("37481735321082")),64,256)),n}var ee=class{static priceToSqrtPriceX64(t,e,n){return Te.toX64(t.mul(Dt.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return Te.fromX64(t).pow(2).mul(Dt.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new ce.default(y0(t)):new ce.default(w0(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ce.default(hs))||t.lt(new ce.default(ms)))throw new J("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,n=new ce.default(e-64),i=_0(n,32,128),r=new ce.default("8000000000000000","hex"),o=0,s=new ce.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ce.default(0))&&o<f0;){a=a.mul(a);let I=a.shrn(127);a=a.shrn(63+I.toNumber()),s=s.add(r.mul(I)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ce.default(h0)),w=_e(h.sub(new ce.default(m0)),64,128).toNumber(),v=_e(h.add(new ce.default(p0)),64,128).toNumber();return w===v?w:ee.tickIndexToSqrtPriceX64(v).lte(t)?v:w}static tickIndexToPrice(t,e,n){return ee.sqrtPriceX64ToPrice(ee.tickIndexToSqrtPriceX64(t),e,n)}static priceToTickIndex(t,e,n){return ee.sqrtPriceX64ToTickIndex(ee.priceToSqrtPriceX64(t,e,n))}static priceToInitializableTickIndex(t,e,n,i){return ee.getInitializableTickIndex(ee.priceToTickIndex(t,e,n),i)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ee.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ee.getInitializableTickIndex(t,e)-e}};function b0(t){return S(t).add(S(g0))}var Dk=new Lr.default(365),Ek=new Lr.default(24),Mk=new Lr.default(3600),Bk=new Lr.default(.5);var mn=class{static getDefaultSqrtPriceLimit(t){return new Zd.default(t?ms:hs)}static getDefaultOtherAmountThreshold(t){return t?ie:ir}};function Xd(t,e,n,i){if(n.eq(ie))return t;let r=Te.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=Te.checkMul(t,n,256);if(!i&&o.lte(s))throw new J("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let a=i?Te.checkDivRoundUpIf(r,o.add(s),!0):Te.checkDivRoundUpIf(r,o.sub(s),!0);if(a.lt(new Ie.default(ms)))throw new J("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(a.gt(new Ie.default(hs)))throw new J("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return a}function Jd(t,e,n,i){let r=Te.checkDivRoundUpIf(n.shln(64),e,!i),o=i?t.add(r):t.sub(r);if(o.lt(new Ie.default(ms))||o.gt(new Ie.default(hs)))throw new J("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function v0(t,e,n,i){return i?Xd(t,e,n,!0):Jd(t,e,n,!0)}function k0(t,e,n,i){return i?Jd(t,e,n,!1):Xd(t,e,n,!1)}function Ud(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(ie)||r.eq(ie))return ie;let o;if(i){let s=new Ie.default(n).mul(new Ie.default(r)).shln(64),a=e.mul(t),u=s.div(a);o=s.mod(a).eq(ie)?u:u.add(Cn)}else{let s=new Ie.default(n).mul(new Ie.default(r));o=s.and(ir).gt(ie)?s.shrn(64).add(Cn):s.shrn(64)}return o}function Kd(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(ie)||r.eq(ie))return ie;let o;if(i)o=n.mul(r).shrn(64);else{let s=n.mul(r).shln(64),a=e.mul(t);o=s.div(a)}return o}function T0(t,e,n,i,r,o){if(n===ie)return{amountIn:ie,amountOut:ie,nextSqrtPrice:e,feeAmount:ie};let s=t.gte(e),a,u,l,h;if(o){let w=Te.checkMulDivFloor(i,Te.checkUnsignedSub(tr,r),tr,64),v=Ud(t,e,n,s);v.gt(w)?(a=w,h=Te.checkUnsignedSub(i,w),l=v0(t,n,w,s)):(a=v,h=Te.checkMulDivCeil(a,r,tr.sub(r),64),l=e),u=Kd(t,l,n,s)}else{let w=Kd(t,e,n,s);w.gt(i)?(u=i,l=k0(t,n,i,s)):(u=w,l=e),a=Ud(t,l,n,s),h=Te.checkMulDivCeil(a,r,tr.sub(r),64)}return{amountIn:a,amountOut:u,nextSqrtPrice:l,feeAmount:h}}function C0(t,e,n,i,r){let o=n,s=i.liquidity,{currentSqrtPrice:a}=i,u={amountIn:ie,amountOut:ie,feeAmount:ie,refAmount:ie,nextSqrtPrice:ie,crossTickNum:0},l,h,w=mn.getDefaultSqrtPriceLimit(t);for(let v of r){if(t&&i.currentTickIndex<v.index||!t&&i.currentTickIndex>=v.index||v===null)continue;t&&w.gt(v.sqrtPrice)||!t&&w.lt(v.sqrtPrice)?l=w:l=v.sqrtPrice;let T=T0(a,l,s,o,i.feeRate,e);if(T.amountIn.eq(ie)||(o=e?o.sub(T.amountIn.add(T.feeAmount)):o.sub(T.amountOut)),u.amountIn=u.amountIn.add(T.amountIn),u.amountOut=u.amountOut.add(T.amountOut),u.feeAmount=u.feeAmount.add(T.feeAmount),T.nextSqrtPrice.eq(v.sqrtPrice)?(h=v.liquidityNet.mul(new Ie.default(-1)),t?Te.is_neg(h)?s=s.add(new Ie.default(Tt(BigInt(h.toString()),128))):s=s.add(h):Te.is_neg(h)?s=s.sub(new Ie.default(Tt(BigInt(h.toString()),128))):s=s.sub(h),a=v.sqrtPrice):a=T.nextSqrtPrice,u.crossTickNum+=1,o.eq(ie))break}return u.amountIn=u.amountIn.add(u.feeAmount),u.nextSqrtPrice=a,u}function rs(t,e,n){let i=Ie.default.min(t,e),r=Ie.default.max(t,e),o=Te.fromX64_BN(n.mul(r).mul(i)),s=r.sub(i);return o.div(s)}function os(t,e,n){let i=Ie.default.min(t,e),o=Ie.default.max(t,e).sub(i);return n.shln(64).div(o)}var $e=class{static updateFeeRate(t,e,n,i,r){let o=Te.checkMulDivCeil(e,new Ie.default(i),tr,64),s=n===0?ie:Te.checkMulDivFloor(e,new Ie.default(n),tr,64),a=e.mul(o).mul(s);if(r?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),a.eq(ie)||t.liquidity.eq(ie))return{refFee:s,clmm:t};let u=a.shln(64).div(t.liquidity);return r?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(u):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(u),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,n,i,r){let o=new Dt(t.toString()),s=new Dt(e.toString()),a=new Dt(n.toString()),u=new Dt(i.toString()),l,h;return e.lt(n)?(l=Te.toX64_Decimal(o).mul(u.sub(a)).div(a.mul(u)),h=new Dt(0)):e.lt(i)?(l=Te.toX64_Decimal(o).mul(u.sub(s)).div(s.mul(u)),h=Te.fromX64_Decimal(o.mul(s.sub(a)))):(l=new Dt(0),h=Te.fromX64_Decimal(o.mul(u.sub(a)))),r?{coinA:new Ie.default(l.ceil().toString()),coinB:new Ie.default(h.ceil().toString())}:{coinA:new Ie.default(l.floor().toString()),coinB:new Ie.default(h.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,n,i,r,o,s){let a=ee.sqrtPriceX64ToTickIndex(s),u=ee.tickIndexToSqrtPriceX64(t),l=ee.tickIndexToSqrtPriceX64(e),h;if(a<t){if(!i)throw new J("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");h=rs(u,l,n)}else if(a>e){if(i)throw new J("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");h=os(l,u,n)}else i?h=rs(s,l,n):h=os(s,u,n);let w=$e.getCoinAmountFromLiquidity(h,s,u,l,r),v=r?S(w.coinA.toString()).mul(1+o).toString():S(w.coinA.toString()).mul(1-o).toString(),T=r?S(w.coinB.toString()).mul(1+o).toString():S(w.coinB.toString()).mul(1-o).toString();return{coinAmountA:w.coinA,coinAmountB:w.coinB,tokenMaxA:r?new Ie.default(Dt.ceil(v).toString()):new Ie.default(Dt.floor(v).toString()),tokenMaxB:r?new Ie.default(Dt.ceil(T).toString()):new Ie.default(Dt.floor(T).toString()),liquidityAmount:h,fix_amount_a:i}}static estimateLiquidityFromcoinAmounts(t,e,n,i){if(e>n)throw new J("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let r=ee.sqrtPriceX64ToTickIndex(t),o=ee.tickIndexToSqrtPriceX64(e),s=ee.tickIndexToSqrtPriceX64(n);if(r<e)return rs(o,s,i.coinA);if(r>=n)return os(s,o,i.coinB);let a=rs(t,s,i.coinA),u=os(t,o,i.coinB);return Ie.default.min(a,u)}static estCoinAmountsFromTotalAmount(t,e,n,i,r,o){let{ratioA:s,ratioB:a}=$e.calculateDepositRatioFixTokenA(t,e,n),u=S(i).mul(s).div(r),l=S(i).mul(a).div(o);return{amountA:u,amountB:l}}static calculateDepositRatioFixTokenA(t,e,n){let i=new Ie.default(1e8),{coinAmountB:r}=$e.estLiquidityAndcoinAmountFromOneAmounts(t,e,i,!0,!0,0,n),o=ee.sqrtPriceX64ToPrice(n,0,0),s=S(i.toString()).mul(o),a=s.add(r.toString()),u=s.div(a),l=S(r.toString()).div(a);return{ratioA:u,ratioB:l}}};function kc(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var S0=0,Yd=1,A0=2;function zd(t,e){return t===e?S0:t<e?Yd:A0}function x0(t,e){let n=0,i=t.length<=e.length?t.length:e.length,r=zd(t.length,e.length);for(;n<i;){let o=zd(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,o!==0)return o}return r}function ls(t,e){return x0(t,e)===Yd}function rr(t,...e){let n=Array.isArray(e[e.length-1])?e.pop():[],r=[t,...e].filter(Boolean).join("::");return n&&n.length&&(r+=`<${n.join(", ")}>`),r}function q(t){try{let e=t.replace(/\s/g,""),i=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(i){e=e.slice(0,e.indexOf("<"));let u={...q(e),type_arguments:i.map(l=>q(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>we.isSuiCoin(l)?l:q(l).source_address),u.source_address=rr(u.full_address,u.type_arguments),u}let r=e.split("::"),s={full_address:e,address:e===$r||e===E0?"0x2":(0,ps.normalizeSuiObjectId)(r[0]),module:r[1],name:r[2],type_arguments:[],source_address:""};return s.full_address=`${s.address}::${s.module}::${s.name}`,s.source_address=rr(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function Et(t){return q(t).source_address}function I0(t){return t.toLowerCase().startsWith("0x")?(0,ps.normalizeSuiObjectId)(t):t}var O0=(t,e=!0)=>{let n=t.split("::"),i=n.shift(),r=(0,ps.normalizeSuiObjectId)(i);return e&&(r=kc(r)),`${r}::${n.join("::")}`};function gs(t){for(let e in t){let n=typeof t[e];if(n==="object")gs(t[e]);else if(n==="string"){let i=t[e];i&&!i.includes("::")&&(t[e]=I0(i))}}}var P0="0x2::coin::Coin",D0=/^0x2::coin::Coin<(.+)>$/;var $r="0x2::sui::SUI",E0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var we=class{static getCoinTypeArg(t){let e=t.type.match(D0);return e?e[1]:null}static isSUI(t){let e=we.getCoinTypeArg(t);return e?we.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 n=BigInt(0);return t.forEach(i=>{e===i.coinAddress&&(n+=BigInt(i.balance))}),n}static getID(t){return t.fields.id.id}static getCoinTypeFromArg(t){return`${P0}<${t}>`}static getFaucetCoins(t){let{events:e}=t,n=[];return e?.forEach(i=>{let{type:r}=i;if(q(r).name==="InitEvent"){let o=i.parsedJson;n.push({transactionModule:i.transactionModule,suplyID:o.suplyID,decimals:o.decimals})}}),n}static getCoinAssets(t,e){let n=[];return e.forEach(i=>{Et(i.coinAddress)===Et(t)&&n.push(i)}),n}static isSuiCoin(t){return q(t).full_address===$r}static selectCoinObjectIdGreaterThanOrEqual(t,e,n=[]){let i=we.selectCoinAssetGreaterThanOrEqual(t,e,n),r=i.selectedCoins.map(a=>a.coinObjectId),o=i.remainingCoins,s=i.selectedCoins.map(a=>a.balance.toString());return{objectArray:r,remainCoins:o,amountArray:s}}static selectCoinAssetGreaterThanOrEqual(t,e,n=[]){let i=we.sortByBalance(t.filter(u=>!n.includes(u.coinObjectId))),r=we.calculateTotalBalance(i);if(r<e)return{selectedCoins:[],remainingCoins:i};if(r===e)return{selectedCoins:i,remainingCoins:[]};let o=BigInt(0),s=[],a=[...i];for(;o<r;){let u=e-o,l=a.findIndex(w=>w.balance>=u);if(l!==-1){s.push(a[l]),a.splice(l,1);break}let h=a.pop();h.balance>0&&(s.push(h),o+=h.balance)}return{selectedCoins:we.sortByBalance(s),remainingCoins:we.sortByBalance(a)}}static sortByBalance(t){return t.sort((e,n)=>e.balance<n.balance?-1:e.balance>n.balance?1:0)}static sortByBalanceDes(t){return t.sort((e,n)=>e.balance>n.balance?-1:e.balance<n.balance?0:1)}static calculateTotalBalance(t){return t.reduce((e,n)=>e+n.balance,BigInt(0))}};var or=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return or.fromFraction(t.toDecimalPlaces(1).mul(10).toNumber(),1e3)}static fromFraction(t,e){let n=typeof t=="number"?new gc.default(t.toString()):t,i=typeof e=="number"?new gc.default(e.toString()):e;return new or(n,i)}};function _c(t,{numerator:e,denominator:n},i){return i?t.mul(n.add(e)).div(n):t.mul(n).div(n.add(e))}function _s(t,e,n){return{tokenMaxA:_c(t.coinA,e,n),tokenMaxB:_c(t.coinB,e,n)}}function S(t){return N.isDecimal(t)?t:new N(t===void 0?0:t)}function j0(t){return S(10).pow(S(t).abs())}function Ur(t){return t.data}function Qd(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 ef(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function N0(t){if("reference"in t)return t.reference;let e=Ur(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Qd(t)}function Lt(t){return"objectId"in t?t.objectId:N0(t)?.objectId??ef(t)}function F0(t){return t.data!==void 0}function R0(t){return t.content!==void 0}function tf(t){let e="data"in t?Ur(t):t;if(!(!e||!R0(e)||e.content.dataType!=="moveObject"))return e.content}function Mt(t){return tf(t)?.type}function pn(t){let e=F0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":Mt(t):e?.type}function Ci(t){return Ur(t)?.previousTransaction}function sr(t){return Ur(t)?.owner}function q0(t){let e=Ur(t)?.display;return e||{data:null,error:null}}function Q(t){let e=tf(t)?.fields;if(e)return"fields"in e?e.fields:e}function nf(t,e){let n=j0(S(e));return Number(S(t).mul(n))}function Tt(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function Re(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function L0(t,e,n){let i=q(t).name,r=q(e).name;return`${i}-${r}[${n}]`}function mc(t){let e=Mt(t),n=q(e),i=Q(t);if(i==null)throw new J(`Pool id ${Lt(t)} not exists.`,"InvalidPoolObject");let r=[];i.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:a}=s.fields,u=Te.fromX64(new rn.default(a)),l=Math.floor(u.toNumber()*60*60*24);r.push({emissions_per_second:a,coinAddress:q(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:l})});let o={poolAddress:Lt(t),poolType:e,coinTypeA:n.type_arguments[0],coinTypeB:n.type_arguments[1],coinAmountA:i.coin_a,coinAmountB:i.coin_b,current_sqrt_price:i.current_sqrt_price,current_tick_index:Re(BigInt(i.current_tick_index.fields.bits)),fee_growth_global_a:i.fee_growth_global_a,fee_growth_global_b:i.fee_growth_global_b,fee_protocol_coin_a:i.fee_protocol_coin_a,fee_protocol_coin_b:i.fee_protocol_coin_b,fee_rate:i.fee_rate,is_pause:i.is_pause,liquidity:i.liquidity,position_manager:{positions_handle:i.position_manager.fields.positions.fields.id.id,size:i.position_manager.fields.positions.fields.size},rewarder_infos:r,rewarder_last_updated_time:i.rewarder_manager.fields.last_updated_time,tickSpacing:i.tick_spacing,ticks_handle:i.tick_manager.fields.ticks.fields.id.id,uri:i.url,index:Number(i.index),name:""};return o.name=L0(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function Si(t){let e=q0(t).data,n={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(n.creator=e.creator,n.description=e.description,n.image_url=e.image_url,n.link=e.link,n.name=e.name,n.project_url=e.project_url),n}function Nn(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new J(`Position not exists. Get Position error:${t.error}`,"InvalidPositionObject");let e={creator:"",description:"",image_url:"",link:"",name:"",project_url:""},n={...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"},i=Q(t);if(i){let s=Mt(t),a=sr(t);"nft"in i?(i=i.nft.fields,e.description=i.description,e.name=i.name,e.link=i.url):e=Si(t),n={...e,pos_object_id:i.id.id,owner:a.AddressOwner,type:s,coin_type_a:i.coin_type_a.fields.name,coin_type_b:i.coin_type_b.fields.name,liquidity:i.liquidity,tick_lower_index:Re(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(i.tick_upper_index.fields.bits)),index:i.index,pool:i.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 r=Qd(t);r&&(n.pos_object_id=r.objectId,n.position_status="Deleted");let o=ef(t);return o&&(n.pos_object_id=o,n.position_status="NotExists"),n}function rf(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:a,growth_inside:u}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=a,e.reward_growth_inside_0=u):s===1?(e.reward_amount_owed_1=a,e.reward_growth_inside_1=u):s===2&&(e.reward_amount_owed_2=a,e.reward_growth_inside_2=u)});let n="fields"in t.tick_lower_index?t.tick_lower_index.fields.bits:t.tick_lower_index.bits,i="fields"in t.tick_upper_index?t.tick_upper_index.fields.bits:t.tick_upper_index.bits;return{liquidity:t.liquidity,tick_lower_index:Re(BigInt(n)),tick_upper_index:Re(BigInt(i)),...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 pc(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new J(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let n=Q(t).value.fields.value.fields;return{objectId:Lt(t),index:Re(BigInt(n.index.fields.bits)),sqrtPrice:new rn.default(n.sqrt_price),liquidityNet:new rn.default(n.liquidity_net.fields.bits),liquidityGross:new rn.default(n.liquidity_gross),feeGrowthOutsideA:new rn.default(n.fee_growth_outside_a),feeGrowthOutsideB:new rn.default(n.fee_growth_outside_b),rewardersGrowthOutside:n.rewards_growth_outside}}function $0(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 J("Invalid tick fields.","InvalidTickFields");let e=Re(BigInt(t.index.bits)),n=new rn.default(t.sqrt_price),i=new rn.default(t.liquidity_net.bits),r=new rn.default(t.liquidity_gross),o=new rn.default(t.fee_growth_outside_a),s=new rn.default(t.fee_growth_outside_b),a=t.rewards_growth_outside||[];return{objectId:"",index:e,sqrtPrice:n,liquidityNet:i,liquidityGross:r,feeGrowthOutsideA:o,feeGrowthOutsideB:s,rewardersGrowthOutside:a}}function U0(t,e,n,i,r,o){let s=t.rewarder_infos,a=[];for(let u=0;u<s.length;u+=1){let l=o[u];e!==null&&(t.current_tick_index<i?l=o[u].sub(new wi.default(e.rewardersGrowthOutside[u])):l=e.rewardersGrowthOutside[u]);let h=new wi.default(0);n!==null&&(t.current_tick_index>=r?h=o[u].sub(new wi.default(n.rewardersGrowthOutside[u])):h=n.rewardersGrowthOutside[u]);let w=Te.subUnderflowU128(Te.subUnderflowU128(new wi.default(o[u]),new wi.default(l)),new wi.default(h));a.push(w)}return a}function ds(t){let e=we.isSuiCoin(t.coinTypeA),n=we.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:n}}function K0(t,e){return N.ceil(S(t).div(1+e)).toString()}var se=class{static createCollectRewarderAndFeeParams(t,e,n,i,r,o){r===void 0&&(r=[...i]),o===void 0&&(o=[...i]);let s=Et(n.coinTypeA),a=Et(n.coinTypeB);if(n.collect_fee){let l=se.buildCoinForAmount(e,r,BigInt(0),s,!1);r=l.remainCoins;let h=se.buildCoinForAmount(e,o,BigInt(0),a,!1);o=h.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:n.pool_id,pos_id:n.pos_id,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB},e,l.targetCoin,h.targetCoin)}let u=[];return n.rewarder_coin_types.forEach(l=>{switch(Et(l)){case s:u.push(se.buildCoinForAmount(e,r,BigInt(0),l,!1).targetCoin);break;case a:u.push(se.buildCoinForAmount(e,o,BigInt(0),l,!1).targetCoin);break;default:u.push(se.buildCoinForAmount(e,i,BigInt(0),l,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(n,e,u),e}static async adjustTransactionForGas(t,e,n,i){i.setSender(t.senderAddress);let r=we.selectCoinAssetGreaterThanOrEqual(e,n).selectedCoins;if(r.length===0)throw new J("Insufficient balance","InsufficientBalance");let o=we.calculateTotalBalance(e);if(o-n>1e9)return{fixAmount:n};let s=await t.fullClient.calculationTxGas(i);if(we.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),r.map(u=>u.coinObjectId)).selectedCoins.length===0){let u=BigInt(s)+BigInt(500);if(o-n<u){if(n-=u,n<0)throw new J("gas Insufficient balance","InsufficientBalance");let l=new bi.TransactionBlock;return{fixAmount:n,newTx:l}}}return{fixAmount:n}}static async buildAddLiquidityFixTokenForGas(t,e,n,i){let r=await se.buildAddLiquidityFixToken(t,e,n),{isAdjustCoinA:o}=ds(n),s=o?n.amount_a:n.amount_b,a=await se.adjustTransactionForGas(t,we.getCoinAssets(o?n.coinTypeA:n.coinTypeB,e),BigInt(s),r),{fixAmount:u}=a,{newTx:l}=a;if(l!==void 0){let h,w;if(o)n.amount_a=Number(u),h=se.buildAddLiquidityFixTokenCoinInput(l,!n.fix_amount_a,u.toString(),n.slippage,n.coinTypeA,e,!1),w=se.buildAddLiquidityFixTokenCoinInput(l,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);else return n.amount_b=Number(u),h=se.buildAddLiquidityFixTokenCoinInput(l,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),w=se.buildAddLiquidityFixTokenCoinInput(l,n.fix_amount_a,u.toString(),n.slippage,n.coinTypeB,e,!1),n=se.fixAddLiquidityFixTokenParams(n,i.slippage,i.curSqrtPrice),r=await se.buildAddLiquidityFixTokenArgs(l,t,e,n,h,w),r}return r}static async buildAddLiquidityFixToken(t,e,n){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let i=new bi.TransactionBlock,r=se.buildAddLiquidityFixTokenCoinInput(i,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),o=se.buildAddLiquidityFixTokenCoinInput(i,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);return i=se.buildAddLiquidityFixTokenArgs(i,t,e,n,r,o),i}static buildAddLiquidityFixTokenCoinInput(t,e,n,i,r,o,s=!0){return e?se.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(K0(n,i)),amountFirst:BigInt(n)},r,s):se.buildCoinForAmount(t,o,BigInt(n),r,s)}static fixAddLiquidityFixTokenParams(t,e,n){let i=t.fix_amount_a?t.amount_a:t.amount_b,r=$e.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new qr.default(i),t.fix_amount_a,!0,e,n);return t.amount_a=t.fix_amount_a?t.amount_a:r.tokenMaxA.toNumber(),t.amount_b=t.fix_amount_a?r.tokenMaxB.toNumber():t.amount_b,t}static buildAddLiquidityFixTokenArgs(t,e,n,i,r,o){let s=[i.coinTypeA,i.coinTypeB],a=i.is_open?"open_position_with_liquidity_by_fix_coin":"add_liquidity_by_fix_coin",{clmm_pool:u,integrate:l}=e.sdkOptions;i.is_open||(t=se.createCollectRewarderAndFeeParams(e,t,i,n,r.remainCoins,o.remainCoins));let h=D(u),w=i.is_open?[t.object(h.global_config_id),t.object(i.pool_id),t.pure(Tt(BigInt(i.tick_lower)).toString()),t.pure(Tt(BigInt(i.tick_upper)).toString()),r.targetCoin,o.targetCoin,t.pure(i.amount_a),t.pure(i.amount_b),t.pure(i.fix_amount_a),t.object(G)]:[t.object(h.global_config_id),t.object(i.pool_id),t.object(i.pos_id),r.targetCoin,o.targetCoin,t.pure(i.amount_a),t.pure(i.amount_b),t.pure(i.fix_amount_a),t.object(G)];return t.moveCall({target:`${l.published_at}::${jn}::${a}`,typeArguments:s,arguments:w}),t}static async buildSwapTransactionForGas(t,e,n,i){let r=se.buildSwapTransaction(t,e,n);r.setSender(t.senderAddress);let o=await se.adjustTransactionForGas(t,we.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:s,newTx:a}=o;if(a!==void 0){a.setSender(t.senderAddress),e.by_amount_in?e.amount=s.toString():e.amount_limit=s.toString(),e=await se.fixSwapParams(t,e,i);let u=se.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),l=se.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);r=se.buildSwapTransactionArgs(a,e,t.sdkOptions,u,l)}return r}static buildSwapTransaction(t,e,n){let i=new bi.TransactionBlock;i.setSender(t.senderAddress);let r=se.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=se.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return i=se.buildSwapTransactionArgs(i,e,t.sdkOptions,r,o),i}static buildSwapTransactionArgs(t,e,n,i,r){let{clmm_pool:o,integrate:s}=n,a=mn.getDefaultSqrtPriceLimit(e.a2b),u=[e.coinTypeA,e.coinTypeB],{global_config_id:l}=D(o);if(l===void 0)throw Error("clmm.config.global_config_id is undefined");let h=e.swap_partner!==void 0,w=h?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",v=h?[t.pure(l),t.pure(e.pool_id),t.pure(e.swap_partner),i.targetCoin,r.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(a.toString()),t.pure(G)]:[t.pure(l),t.pure(e.pool_id),i.targetCoin,r.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(a.toString()),t.pure(G)];return t.moveCall({target:`${s.published_at}::${jn}::${w}`,typeArguments:u,arguments:v}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,n,i){let{tx:r,coinABs:o}=se.buildSwapTransactionWithoutTransferCoins(t,e,n);r.setSender(t.senderAddress);let s=await se.adjustTransactionForGas(t,we.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:a,newTx:u}=s;if(u!==void 0){u.setSender(t.senderAddress),e.by_amount_in?e.amount=a.toString():e.amount_limit=a.toString(),e=await se.fixSwapParams(t,e,i);let l=se.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),h=se.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),w=se.buildSwapTransactionWithoutTransferCoinArgs(t,u,e,t.sdkOptions,l,h);r=w.tx,o=w.txRes}return{tx:r,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,n){let i=new bi.TransactionBlock;i.setSender(t.senderAddress);let r=se.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=se.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=se.buildSwapTransactionWithoutTransferCoinArgs(t,i,e,t.sdkOptions,r,o);return{tx:s.tx,coinABs:s.txRes}}static buildSwapTransactionWithoutTransferCoinArgs(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=i,u=mn.getDefaultSqrtPriceLimit(n.a2b),{global_config_id:l}=D(s);if(l===void 0)throw Error("clmm.config.global_config_id is undefined");let h=n.swap_partner!==void 0,w=h?"swap_with_partner":"swap",v=h?fc:Jn,T=h?[e.pure(l),e.pure(n.pool_id),e.pure(n.swap_partner),r.targetCoin,o.targetCoin,e.pure(n.a2b),e.pure(n.by_amount_in),e.pure(n.amount),e.pure(u.toString()),e.pure(!1),e.pure(G)]:[e.pure(l),e.pure(n.pool_id),r.targetCoin,o.targetCoin,e.pure(n.a2b),e.pure(n.by_amount_in),e.pure(n.amount),e.pure(u.toString()),e.pure(!1),e.pure(G)],I=[n.coinTypeA,n.coinTypeB],x=e.moveCall({target:`${a.published_at}::${v}::${w}`,typeArguments:I,arguments:T});if(n.by_amount_in){let P=n.a2b?n.coinTypeB:n.coinTypeA,O=n.a2b?x[1]:x[0],E=Number(n.amount_limit);this.checkCoinThreshold(t,n.by_amount_in,e,O,E,P)}return{tx:e,txRes:x}}static async fixSwapParams(t,e,n){let{currentPool:i}=n;try{let r=await t.Swap.preswap({decimalsA:n.decimalsA,decimalsB:n.decimalsB,a2b:e.a2b,byAmountIn:e.by_amount_in,amount:e.amount,pool:i,currentSqrtPrice:i.current_sqrt_price,coinTypeA:i.coinTypeA,coinTypeB:i.coinTypeB}),o=n.byAmountIn?r.estimatedAmountOut:r.estimatedAmountIn,s=_c(o,n.slippage,!n.byAmountIn);e.amount_limit=s.toString()}catch(r){console.log("fixSwapParams",r)}return e}static async syncBuildCoinInputForAmount(t,e,n,i,r=!0){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let o=await t.getOwnerCoinAssets(t.senderAddress,i);return se.buildCoinForAmount(e,o,n,i,r).targetCoin}static buildCoinForAmount(t,e,n,i,r=!0,o=!1){let s=we.getCoinAssets(i,e);if(n===BigInt(0)&&s.length===0)return se.buildZeroValueCoin(e,t,i,r);let a=we.calculateTotalBalance(s);if(a<n)throw new J(`The amount(${a}) is Insufficient balance for ${i} , expect ${n} `,"InsufficientBalance");return se.buildCoin(t,e,s,n,i,r,o)}static buildCoin(t,e,n,i,r,o=!0,s=!1){if(we.isSuiCoin(r)){if(o){let E=t.splitCoins(t.gas,[t.pure(i.toString())]);return{targetCoin:t.makeMoveVec({objects:[E]}),remainCoins:e,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(i===0n&&n.length>1){let E=we.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.object(E.objectArray[0]),remainCoins:E.remainCoins,tragetCoinAmount:E.amountArray[0],isMintZeroCoin:!1}}let P=we.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.splitCoins(t.gas,[t.pure(i.toString())]),remainCoins:P.remainCoins,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let a=we.selectCoinObjectIdGreaterThanOrEqual(n,i),u=a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),l=a.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:l.map(P=>t.object(P))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),isMintZeroCoin:!1};let[h,...w]=l,v=t.object(h),T=v,I=a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),x;return w.length>0&&t.mergeCoins(v,w.map(P=>t.object(P))),s&&Number(u)>Number(i)&&(T=t.splitCoins(v,[t.pure(i.toString())]),I=i.toString(),x=v),{targetCoin:T,remainCoins:a.remainCoins,originalSplitedCoin:x,tragetCoinAmount:I,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,n,i=!0){let r=se.callMintZeroValueCoin(e,n),o;return i?o=e.makeMoveVec({objects:[r]}):o=r,{targetCoin:o,remainCoins:t,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(t,e,n,i,r=!0){let o=we.getCoinAssets(i,e);if(n.amountFirst===BigInt(0))return o.length>0?se.buildCoin(t,[...e],[...o],n.amountFirst,i,r):se.buildZeroValueCoin(e,t,i,r);let s=we.calculateTotalBalance(o);if(s>=n.amountFirst)return se.buildCoin(t,[...e],[...o],n.amountFirst,i,r);if(s<n.amountSecond)throw new J(`The amount(${s}) is Insufficient balance for ${i} , expect ${n.amountSecond} `,"InsufficientBalance");return se.buildCoin(t,[...e],[...o],n.amountSecond,i,r)}static async buildRouterSwapTransaction(t,e,n,i,r){let o=new bi.TransactionBlock;return e.paths.length>1&&(e.partner=""),o=await this.buildRouterBasePathTx(t,e,n,i,o,r),o}static async buildRouterBasePathTx(t,e,n,i,r,o){let s=e.paths.filter(B=>B&&B.poolAddress),a=Number(s.reduce((B,$)=>B.add($.amountIn),ie).toString()),u=Number(s.reduce((B,$)=>B.add($.amountOut),ie).toString()),l=Math.round(n?Number(u.toString())*(1-e.priceSlippagePoint):Number(a.toString())*(1+e.priceSlippagePoint)),h=e.paths[0].coinType[0],w=e.paths[0].coinType[e.paths[0].coinType.length-1],v=se.buildCoinForAmount(r,i,BigInt(n?a:l),h,!1,!0),T=v.originalSplitedCoin!==void 0,I=se.buildCoinForAmount(r,i,0n,w,!1),x=await this.buildRouterBasePathReturnCoins(t,e,n,v,I,r),P=[],{toCoin:O,fromCoin:E}=x;if(r=x.tx,I.isMintZeroCoin?P.push({coinType:w,coin:O}):I.originalSplitedCoin!==void 0?r.mergeCoins(I.originalSplitedCoin,[O]):r.mergeCoins(I.targetCoin,[O]),T){let B=v?.originalSplitedCoin;r.mergeCoins(B,[E])}else P.push({coinType:h,coin:E});for(let B=0;B<P.length;B++)this.buildTransferCoin(t,r,P[B].coin,P[B].coinType,o);return r}static async buildRouterBasePathReturnCoins(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=t.sdkOptions,u=D(s).global_config_id,l=e.paths.filter(B=>B&&B.poolAddress),h=Number(l.reduce((B,$)=>B.add($.amountIn),ie).toString()),w=Number(l.reduce((B,$)=>B.add($.amountOut),ie).toString()),v=Math.round(n?Number(w.toString())*(1-e.priceSlippagePoint):Number(h.toString())*(1+e.priceSlippagePoint)),T=e.paths[0].coinType[0],I=e.paths[0].coinType[e.paths[0].coinType.length-1],x=i.targetCoin,P;r.isMintZeroCoin||r.originalSplitedCoin!==void 0?P=r.targetCoin:P=se.callMintZeroValueCoin(o,I);let O=e.partner==="",E=O?Jn:fc;for(let B of l)if(B.poolAddress.length===1){let $=B.a2b[0],Z={amount:Number(B.amountIn.toString()),amountLimit:v,poolCoinA:B.a2b[0]?T:I,poolCoinB:B.a2b[0]?I:T},H=O?"swap":"swap_with_partner",te=$?x:P,U=$?P:x,V=n?B.amountIn.toString():B.amountOut.toString(),F=mn.getDefaultSqrtPriceLimit($).toString(),K=O?[o.object(u),o.object(B.poolAddress[0]),te,U,o.pure($),o.pure(n),o.pure(V),o.pure(F),o.pure(!1),o.object(G)]:[o.object(u),o.object(B.poolAddress[0]),o.pure(e.partner),te,U,o.pure($),o.pure(n),o.pure(V),o.pure(F),o.pure(!1),o.object(G)],C=[Z.poolCoinA,Z.poolCoinB],A=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${E}::${H}`,typeArguments:C,arguments:K});x=$?A[0]:A[1],P=$?A[1]:A[0]}else{let $=n?B.amountIn:B.rawAmountLimit[0],Z=n?0:B.amountOut,H="";B.a2b[0]?B.a2b[1]?H="swap_ab_bc":H="swap_ab_cb":B.a2b[1]?H="swap_ba_bc":H="swap_ba_cb",O||(H=`${H}_with_partner`);let te=mn.getDefaultSqrtPriceLimit(B.a2b[0]),U=mn.getDefaultSqrtPriceLimit(B.a2b[1]),V=O?[o.object(u),o.object(B.poolAddress[0]),o.object(B.poolAddress[1]),x,P,o.pure(n),o.pure($.toString()),o.pure(Z.toString()),o.pure(te.toString()),o.pure(U.toString()),o.object(G)]:[o.object(u),o.object(B.poolAddress[0]),o.object(B.poolAddress[1]),o.pure(e.partner),x,P,o.pure(n),o.pure($.toString()),o.pure(Z.toString()),o.pure(te.toString()),o.pure(U.toString()),o.object(G)],F=[B.coinType[0],B.coinType[1],B.coinType[2]],K=o.moveCall({target:`${a.published_at}::${E}::${H}`,typeArguments:F,arguments:V});x=K[0],P=K[1]}return this.checkCoinThreshold(t,n,o,P,v,I),{fromCoin:x,toCoin:P,tx:o}}static async buildAggregatorSwapReturnCoins(t,e,n,i,r,o,s,a){if(a==null){if(t.senderAddress.length===0)throw Error("recipient and this config sdk senderAddress all not set");a=t.senderAddress}e.splitPaths.length>1&&(r="");let u,l,h=e.splitPaths.some(w=>w.basePaths.some(v=>v.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!h){let w=[];for(let I of e.splitPaths){let x=[],P=[],O=[],E=[];for(let $=0;$<I.basePaths.length;$+=1){let Z=I.basePaths[$];x.push(Z.direction),P.push(Z.poolAddress),O.push(new qr.default(Z.inputAmount.toString())),$===0?E.push(Z.fromCoin,Z.toCoin):E.push(Z.toCoin)}let B={amountIn:new qr.default(I.inputAmount.toString()),amountOut:new qr.default(I.outputAmount.toString()),poolAddress:P,a2b:x,rawAmountLimit:O,isExceed:!1,coinType:E};w.push(B)}let v={paths:w,partner:r,priceSlippagePoint:o},T=await this.buildRouterBasePathReturnCoins(t,v,e.byAmountIn,n,i,s);u=T.fromCoin,l=T.toCoin,s=T.tx}else{let w=Math.round(e.outputAmount*(1-o));u=n.targetCoin,i.isMintZeroCoin||i.originalSplitedCoin!==void 0?l=i.targetCoin:l=se.callMintZeroValueCoin(s,e.toCoin);let v=!1,T;if(h){let[I,x]=Vd.createAccountCap(a,t.sdkOptions,s);s=x,T=I,v=!0}for(let I=0;I<e.splitPaths.length;I+=1){let x=e.splitPaths[I],P;for(let O=0;O<x.basePaths.length;O+=1){let E=x.basePaths[O];if(E.label==="Deepbook")if(O===0)if(x.basePaths.length===1){let B=this.buildDeepbookBasePathTx(t,E,s,T,u,l,!1);u=B.from,l=B.to}else{P=se.callMintZeroValueCoin(s,E.toCoin);let B=this.buildDeepbookBasePathTx(t,E,s,T,u,P,!1);u=B.from,P=B.to}else{let B=this.buildDeepbookBasePathTx(t,E,s,T,P,l,!0);P=B.from,l=B.to}if(E.label==="Cetus")if(O===0)if(x.basePaths.length===1){let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,u,l,!1,r);u=B.from,l=B.to}else{P=se.callMintZeroValueCoin(s,E.toCoin);let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,u,P,!1,r);u=B.from,P=B.to}else{let B=this.buildClmmBasePathTx(t,E,s,e.byAmountIn,P,l,!0,r);P=B.from,l=B.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${$d}::send_coin`,typeArguments:[E.fromCoin],arguments:[P,s.pure(a)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,l,w,e.toCoin),v&&(s=Vd.deleteAccountCapByObject(T,t.sdkOptions,s))}return{fromCoin:u,toCoin:l,tx:s}}static async buildAggregatorSwapTransaction(t,e,n,i,r,o){let s=new bi.TransactionBlock,a=e.byAmountIn?Math.round(e.outputAmount*(1-r)):Math.round(e.inputAmount*(1+r)),u=se.buildCoinForAmount(s,n,e.byAmountIn?BigInt(e.inputAmount):BigInt(a),e.fromCoin,!1,!0),l=u.originalSplitedCoin!=null,h=se.buildCoinForAmount(s,n,0n,e.toCoin,!1),w=await this.buildAggregatorSwapReturnCoins(t,e,u,h,i,r,s,o),{fromCoin:v,toCoin:T}=w;s=w.tx;let I=[];if(h.isMintZeroCoin?I.push({coinType:e.toCoin,coin:T}):h.originalSplitedCoin!=null?s.mergeCoins(h.originalSplitedCoin,[T]):s.mergeCoins(h.targetCoin,[T]),l){let x=u.originalSplitedCoin;s.mergeCoins(x,[v])}else I.push({coinType:e.fromCoin,coin:v});for(let x=0;x<I.length;x++)this.buildTransferCoin(t,s,I[x].coin,I[x].coinType,o);return s}static checkCoinThreshold(t,e,n,i,r,o){e&&n.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Jn}::check_coin_threshold`,typeArguments:[o],arguments:[i,n.pure(r)]})}static buildDeepbookBasePathTx(t,e,n,i,r,o,s){let a=e.direction?r:o,u=e.direction?o:r,l=[n.object(e.poolAddress),i,n.pure(e.inputAmount),n.pure(0),n.pure(e.direction),a,u,n.pure(s),n.object(G)],h=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],w=n.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:h,arguments:l});return r=e.direction?w[0]:w[1],o=e.direction?w[1]:w[0],{from:r,to:o,tx:n}}static buildClmmBasePathTx(t,e,n,i,r,o,s,a){let{clmm_pool:u,integrate:l}=t.sdkOptions,h=D(u).global_config_id,w=e.direction?r:o,v=e.direction?o:r,T=a==="",I=T?Jn:fc,x=T?"swap":"swap_with_partner",P=i?e.inputAmount.toString():e.outputAmount.toString(),O=mn.getDefaultSqrtPriceLimit(e.direction),E=T?[n.object(h),n.object(e.poolAddress),w,v,n.pure(e.direction),n.pure(i),n.pure(P),n.pure(O.toString()),n.pure(s),n.object(G)]:[n.object(h),n.object(e.poolAddress),n.pure(a),w,v,n.pure(e.direction),n.pure(i),n.pure(P),n.pure(O.toString()),n.pure(s),n.object(G)],B=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],$=n.moveCall({target:`${l.published_at}::${I}::${x}`,typeArguments:B,arguments:E});return w=$[0],v=$[1],r=e.direction?w:v,o=e.direction?v:w,{from:r,to:o,tx:n}}static buildCoinTypePair(t,e){let n=[];if(t.length===2){let i=[];i.push(t[0],t[1]),n.push(i)}else{let i=[];i.push(t[0],t[t.length-1]),n.push(i);for(let r=1;r<t.length-1;r+=1){if(e[r-1]===0)continue;let o=[];o.push(t[0],t[r],t[t.length-1]),n.push(o)}}return n}static buildTransferCoinToSender(t,e,n,i){e.moveCall({target:`${t.sdkOptions.integrate.published_at}::${$d}::transfer_coin_to_sender`,typeArguments:[i],arguments:[n]})}static buildTransferCoin(t,e,n,i,r){r!=null?e.transferObjects([n],e.pure(r)):se.buildTransferCoinToSender(t,e,n,i)}},re=se;i0(re,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function Nt(t){return!(!t.startsWith("0x")||t.length!==66)}var Qi=new Pt.default(1e9),Vd=class{static createAccountCap(t,e,n,i=!1){if(t.length===0)throw Error("this config sdk senderAddress is empty");let{deepbook:r}=e,[o]=n.moveCall({target:`${r.published_at}::${l0}::create_account`,typeArguments:[],arguments:[]});return i&&n.transferObjects([o],n.pure(t)),[o,n]}static deleteAccountCap(t,e,n){let{deepbook:i}=e,r=[n.pure(t)];return n.moveCall({target:`${i.published_at}::${hc}::delete_account_cap`,typeArguments:[],arguments:r}),n}static deleteAccountCapByObject(t,e,n){let{deepbook:i}=e,r=[t];return n.moveCall({target:`${i.published_at}::${hc}::delete_account_cap`,typeArguments:[],arguments:r}),n}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:hc}}});return e.data.length===0?"":e.data[0].data.objectId}static async getPools(t){let e=t.sdkOptions.deepbook.package_id,n=[];try{(await t.fullClient.queryEventsByPage({MoveEventType:`${e}::clob_v2::PoolCreated`})).data.forEach(r=>{let o=r.parsedJson;o&&n.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(i){console.log("getPoolImmutables",i)}return n}static async getPoolAsks(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new as.TransactionBlock,a=[],u=[n,i],l=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(G)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:l,typeArguments:u});let w=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(w.length===0)return a;for(let v=0;v<w[0].parsedJson.depths.length;v++){let T=w[0].parsedJson.price[v],I=w[0].parsedJson.depths[v],x={price:parseInt(T,10),quantity:parseInt(I,10)};a.push(x)}return a}static async getPoolBids(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new as.TransactionBlock,a=[],u=[n,i],l=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(G)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:l,typeArguments:u});let w=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(w.length===0)return a;for(let v=0;v<w[0].parsedJson.depths.length;v++){let T=w[0].parsedJson.price[v],I=w[0].parsedJson.depths[v],x={price:parseInt(T,10),quantity:parseInt(I,10)};a.push(x)}return a}static async preSwap(t,e,n,i){let r=!1,o=ie,s=new Pt.default(i),a=ie,u=new Pt.default(i);if(n){let l=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);l===null&&(r=!0),l=l.sort((h,w)=>w.price-h.price);for(let h=0;h<l.length;h+=1){let w=new Pt.default(l[h].quantity),v=new Pt.default(l[h].price),T=w.mul(new Pt.default(v)).mul(new Pt.default(e.takerFeeRate)).div(Qi).div(Qi);if(s.gt(w))s=s.sub(w),o=o.add(w.mul(v).div(Qi).sub(T)),a=a.add(T);else{let I=s.mul(new Pt.default(l[h].price)).div(Qi),x=I.mul(new Pt.default(e.takerFeeRate)).div(Qi);o=o.add(I.sub(x)),s=s.sub(s),a=a.add(x)}if(s.eq(ie))break}}else{let l=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);l===null&&(r=!0);for(let h=0;h<l.length;h+=1){let w=new Pt.default(l[h].price).mul(new Pt.default(l[h].quantity)).div(new Pt.default(1e9)),v=w.mul(new Pt.default(e.takerFeeRate)).div(Qi),T=w.add(v);if(s.gt(w))o=o.add(new Pt.default(l[h].quantity)),s=s.sub(T),a=a.add(v);else{let I=new Pt.default(l[h].quantity).div(new Pt.default(e.lotSize)),x=T.div(I),P=s.div(x);o=o.add(P.muln(e.lotSize)),s=s.sub(P.mul(x)),a=a.add(P.div(I).mul(v))}if(s.eq(ie))break}}return{poolAddress:e.poolID,estimatedAmountIn:u.sub(s).toNumber(),estimatedAmountOut:o.toNumber(),estimatedFeeAmount:a,isExceed:r,amount:Number(i),aToB:n,byAmountIn:!0}}static async simulateSwap(t,e,n,i,r,o){let{deepbook_endpoint_v2:s}=t.sdkOptions,a=new as.TransactionBlock,u=await this.getAccountCap(t),l;if(u===""){let Z=this.createAccountCap(t.senderAddress,t.sdkOptions,a),H=Z[0];a=Z[1],l=H}else l=a.pure(u);let h=await t.getOwnerCoinAssets(t.senderAddress),v=re.buildCoinForAmount(a,h,BigInt(o),n,!1)?.targetCoin,I=re.buildCoinForAmount(a,h,BigInt(o),i,!1)?.targetCoin,x=[n,i],P=[a.pure(e),l,a.pure(o),a.pure(0),a.pure(r),v,I,a.pure(G)];a.moveCall({target:`${s.published_at}::${d0}::swap`,arguments:P,typeArguments:x});let{simulationAccount:O}=t.sdkOptions,B=(await t.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:O.address})).events?.filter(Z=>q(Z.type).name==="DeepbookSwapEvent");if(B.length===0)return null;let $=B[0].parsedJson;return{poolAddress:$.pool,estimatedAmountIn:$.amount_in,estimatedAmountOut:$.amount_out,aToB:$.atob}}},G0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPositionList(t,e="all"){let n={data:[],hasNextPage:!0},i=await this._sdk.fullClient.getDynamicFieldsByPage(t,e);n.hasNextPage=i.hasNextPage,n.nextCursor=i.nextCursor;let r=i.data.map(s=>{if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`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(r);return n.data=o,n}async getPoolImmutables(t=[],e=0,n=100,i=!1){let{package_id:r}=this._sdk.sdkOptions.clmm_pool,o=`${r}_getInitPoolEvent`,s=this.getCache(o,i),a=[],u=[];if(s!==void 0&&a.push(...s),a.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`})).data.forEach(w=>{let v=w.parsedJson;v&&a.push({poolAddress:v.pool_id,tickSpacing:v.tick_spacing,coinTypeA:q(v.coin_type_a).full_address,coinTypeB:q(v.coin_type_b).full_address})}),this.updateCache(o,a,X)}catch(h){console.log("getPoolImmutables",h)}let l=t.length>0;for(let h=0;h<a.length;h+=1){let w=a[h];l&&!t.includes(w.poolAddress)||!l&&(h<e||h>=e+n)||u.push(w)}return u}async getPools(t=[],e=0,n=100){let i=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutables([],e,n,!1)).forEach(a=>r.push(a.poolAddress));let o=await this._sdk.fullClient.batchGetObjects(r,{showContent:!0,showType:!0});for(let s of o){if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let a=mc(s);i.push(a);let u=`${a.poolAddress}_getPoolObject`;this.updateCache(u,a,X)}return i}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.clmm_pool,i=[],r={data:[],hasNextPage:!1},o=t==="all",s=`${n}_getPoolImmutables`;if(o){let a=this.getCache(s,e);a&&i.push(...a)}if(i.length===0)try{let a=`${n}::factory::CreatePoolEvent`,u=await this._sdk.fullClient.queryEventsByPage({MoveEventType:a},t);r.hasNextPage=u.hasNextPage,r.nextCursor=u.nextCursor,u.data.forEach(l=>{let h=l.parsedJson;if(h){let w={poolAddress:h.pool_id,tickSpacing:h.tick_spacing,coinTypeA:q(h.coin_type_a).full_address,coinTypeB:q(h.coin_type_b).full_address};i.push(w)}})}catch(a){console.log("getPoolImmutables",a)}return r.data=i,o&&this.updateCache(`${n}_getPoolImmutables`,i,X),r}async getPoolsWithPage(t=[]){let e=[],n=[];t.length>0?n=[...t]:(await this.getPoolImmutablesWithPage()).data.forEach(o=>n.push(o.poolAddress));let i=await this._sdk.fullClient.batchGetObjects(n,{showContent:!0,showType:!0});for(let r of i){if(r.error!=null||r.data?.content?.dataType!=="moveObject")throw new J(`getPoolWithPages error code: ${r.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=mc(r);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,X)}return e}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(r.error!=null||r.data?.content?.dataType!=="moveObject")throw new J(`getPool error code: ${r.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=mc(r);return this.updateCache(n,o),o}async creatPoolsTransactionPayload(t){for(let n of t)if(ls((0,Rr.normalizeSuiAddress)(n.coinTypeA),(0,Rr.normalizeSuiAddress)(n.coinTypeB))){let i=n.coinTypeB;n.coinTypeB=n.coinTypeA,n.coinTypeA=i}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(ls((0,Rr.normalizeSuiAddress)(t.coinTypeA),(0,Rr.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,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.fullClient.queryEventsByPage({Transaction:o})).data,a={pools_id:"",global_config_id:"",global_vault_id:"",admin_cap_id:""};return s.length>0&&(s.forEach(u=>{let l=u.parsedJson;if(u.type)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.global_config_id=l.global_config_id,a.admin_cap_id=l.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:a.global_vault_id=l.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:a.partners_id=l.partners_id;break;default:break}}),this.updateCache(n,a,X)),a}async getSuiTransactionResponse(t,e=!1){let n=`${t}_getSuiTransactionResponse`,i=this.getCache(n,e);if(i!==void 0)return i;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(n,r,X),r}async creatPool(t){let e=new er.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=D(i),o=r.global_config_id,s=r.pools_id;return t.forEach(a=>{let u=[e.object(o),e.object(s),e.pure(a.tick_spacing.toString()),e.pure(a.initialize_sqrt_price),e.pure(a.uri),e.object(G)];e.moveCall({target:`${n.published_at}::${nr}::create_pool`,typeArguments:[a.coinTypeA,a.coinTypeB],arguments:u})}),e}async creatPoolAndAddLiquidity(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new er.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=D(i),o=r.global_config_id,s=r.pools_id,a=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),u=re.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,a,!1),l=re.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,a,!1),h=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),u.targetCoin,l.targetCoin,e.pure(Tt(BigInt(t.tick_lower)).toString()),e.pure(Tt(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(G)];return e.moveCall({target:`${n.published_at}::${jn}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:h}),e}async fetchTicks(t){let e=[],n=[];for(;;){let r=await this.getTicks({pool_id:t.pool_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,start:n,limit:512});if(e=[...e,...r],r.length<512)break;n=[r[r.length-1].index]}return e}async getTicks(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=[],r=[t.coinTypeA,t.coinTypeB],o=new er.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${zt}::fetch_ticks`,arguments:s,typeArguments:r}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let a=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:n.address});if(a.error!=null)throw new J(`getTicks error code: ${a.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return a.events?.forEach(u=>{q(u.type).name==="FetchTicksResultEvent"&&u.parsedJson.ticks.forEach(l=>{i.push($0(l))})}),i}async fetchPositionRewardList(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=[],r=[],o=512;for(;;){let s=[t.coinTypeA,t.coinTypeB],a=new er.TransactionBlock,u=[a.object(t.pool_id),a.pure(r,"u64"),a.pure(o.toString(),"u64")];if(a.moveCall({target:`${e.published_at}::${zt}::fetch_positions`,arguments:u,typeArguments:s}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let l=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:n.address});if(l.error!=null)throw new J(`fetch position reward error code: ${l.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let h=[];if(l?.events?.forEach(w=>{q(w.type).name==="FetchPositionsEvent"&&w.parsedJson.positions.forEach(v=>{let T=rf(v);h.push(T)})}),i.push(...h),h.length<o)break;r=[h[h.length-1].pos_object_id]}return i}async fetchTicksByRpc(t){let e=[],n=null,i=512;for(;;){let r=[],o=await this.sdk.fullClient.getDynamicFields({parentId:t,cursor:n,limit:i});if(n=o.nextCursor,o.data.forEach(s=>{q(s.objectType).module==="skip_list"&&r.push(s.objectId)}),e=[...e,...await this.getTicksByRpc(r)],n===null||o.data.length<i)break}return e}async getTicksByRpc(t){let e=[],n=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0,showType:!0});for(let i of n){if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`getTicksByRpc error code: ${i.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let r=pc(i);r!=null&&e.push(r)}return e}async getTickDataByIndex(t,e){let n={type:"u64",value:Tt(BigInt(b0(e).toString())).toString()},i=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:n});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`get tick by index: ${e} error: ${i.error}`,"InvalidTickIndex");return pc(i)}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 J(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return pc(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 J(`get partner by object id: ${t} error: ${e[0].error}`,"NotFoundPartnerObject");let n=e[0].data.content.fields.balances,i=await this._sdk.fullClient.getDynamicFieldsByPage(n.fields.id.id),r=[];i.data.forEach(a=>{if(a.error!=null||a.data?.content?.dataType!=="moveObject")throw new J(`when getPartnerRefFeeAmount get partner object error: ${a.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");r.push(a.objectId)});let o=[];return(await this._sdk.fullClient.batchGetObjects(r,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(a=>{if(a.error!=null||a.data?.content?.dataType!=="moveObject")throw new J(`get coin by object id: ${a.data.objectId} error: ${a.error}`,"InvalidParnterRefFeeFields");let u={coinAddress:a.data.content.fields.name,coinObjectId:a.data.objectId,balance:BigInt(a.data.content.fields.value)};o.push(u)}),o}async claimPartnerRefFeePayload(t,e,n){let i=new er.TransactionBlock,{clmm_pool:r}=this.sdk.sdkOptions,{global_config_id:o}=D(r),s=[n],a=[i.object(o),i.object(t),i.object(e)];return i.moveCall({target:`${r.published_at}::${c0}::claim_ref_fee`,arguments:a,typeArguments:s}),i}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},W0=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 n=[],i=await this._sdk.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.clmm_pool.package_id}}),r=e.length>0;for(let o of i.data)if(q(o.data.type).full_address===this.buildPositionType()){let a=Nn(o),u=`${a.pos_object_id}_getPositionList`;this.updateCache(u,a,X),r?e.includes(a.pool)&&n.push(a):n.push(a)}return n}async getPosition(t,e,n=!0){let i=await this.getSimplePosition(e);return n&&(i=await this.updatePositionRewarders(t,i)),i}async getPositionById(t,e=!0){let n=await this.getSimplePosition(t);if(e){let i=await this._sdk.Pool.getPool(n.pool,!1);return await this.updatePositionRewarders(i.position_manager.positions_handle,n)}return n}async getSimplePosition(t){let e=`${t}_getPositionList`,n=this.getSimplePositionByCache(t);if(n===void 0){let i=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0,showType:!0,showDisplay:!0,showOwner:!0}});n=Nn(i),this.updateCache(e,n,X)}return n}getSimplePositionByCache(t){let e=`${t}_getPositionList`;return this.getCache(e)}async getSipmlePositionList(t){let e=[],n=[];return t.forEach(i=>{let r=this.getSimplePositionByCache(i);r?e.push(r):n.push(i)}),n.length>0&&(await this._sdk.fullClient.batchGetObjects(n,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(r=>{let o=Nn(r);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,X)}),e}async updatePositionRewarders(t,e){let n=await this.getPositionRewarders(t,e.pos_object_id);return{...e,...n}}async getPositionRewarders(t,e){try{let n=await this._sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),r=Q(n.data).value.fields.value;return rf(r)}catch(n){console.log(n);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new vi.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l})}if(!Nt(i.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address});if(o.error!=null)throw new J(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(u=>q(u.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let u=0;u<s.length;u+=1){let{parsedJson:l}=s[u],h={feeOwedA:new yc.default(l.fee_owned_a),feeOwedB:new yc.default(l.fee_owned_b),position_id:l.position_id};a.push(h)}return a}async batchFetchPositionFees(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let n={};if(e.length>0){let i=await this.fetchPosFeeAmount(e);for(let r of i)n[r.position_id]=r;return n}return n}async createAddLiquidityFixTokenPayload(t,e){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=ds(t);if(t=t,t.fix_amount_a&&i||!t.fix_amount_a&&r)return await re.buildAddLiquidityFixTokenForGas(this._sdk,n,t,e)}return re.buildAddLiquidityFixToken(this._sdk,n,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:n}=this._sdk.sdkOptions;if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let i=Tt(BigInt(t.tick_lower)).toString(),r=Tt(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new vi.TransactionBlock,a=!(0,of.isValidSuiObjectId)(t.pos_id),u=BigInt(t.max_amount_a),l=BigInt(t.max_amount_b),h=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),w=re.buildCoinForAmount(s,h,u,t.coinTypeA,!1),v=re.buildCoinForAmount(s,h,l,t.coinTypeB,!1);return a?s.moveCall({target:`${e.published_at}::${jn}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(D(n).global_config_id),s.object(t.pool_id),s.pure(i),s.pure(r),w.targetCoin,v.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(G)]}):(s=re.createCollectRewarderAndFeeParams(this._sdk,s,t,h,w.remainCoins,v.remainCoins),s.moveCall({target:`${e.published_at}::${jn}::add_liquidity`,typeArguments:o,arguments:[s.object(D(n).global_config_id),s.object(t.pool_id),s.object(t.pos_id),w.targetCoin,v.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(G)]})),s}async removeLiquidityTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i="remove_liquidity",r=new vi.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);r=re.createCollectRewarderAndFeeParams(this._sdk,r,t,s);let a=[r.object(D(e).global_config_id),r.object(t.pool_id),r.object(t.pos_id),r.pure(t.delta_liquidity),r.pure(t.min_amount_a),r.pure(t.min_amount_b),r.object(G)];return r.moveCall({target:`${n.published_at}::${nr}::${i}`,typeArguments:o,arguments:a}),r}async closePositionTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new vi.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return i=re.createCollectRewarderAndFeeParams(this._sdk,i,t,o),i.moveCall({target:`${n.published_at}::${nr}::close_position`,typeArguments:r,arguments:[i.object(D(e).global_config_id),i.object(t.pool_id),i.object(t.pos_id),i.pure(t.min_amount_a),i.pure(t.min_amount_b),i.object(G)]}),i}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new vi.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=Tt(BigInt(t.tick_lower)).toString(),s=Tt(BigInt(t.tick_upper)).toString(),a=[i.pure(D(e).global_config_id),i.pure(t.pool_id),i.pure(o),i.pure(s)];return i.moveCall({target:`${n.published_at}::${nr}::open_position`,typeArguments:r,arguments:a}),i}async collectFeeTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),n=new vi.TransactionBlock,i=re.buildCoinForAmount(n,e,BigInt(0),t.coinTypeA,!1),r=re.buildCoinForAmount(n,e,BigInt(0),t.coinTypeB,!1);return this.createCollectFeePaylod(t,n,i.targetCoin,r.targetCoin),n}createCollectFeePaylod(t,e,n,i){let{clmm_pool:r,integrate:o}=this.sdk.sdkOptions,s=[t.coinTypeA,t.coinTypeB],a=[e.object(D(r).global_config_id),e.object(t.pool_id),e.object(t.pos_id),n,i];return e.moveCall({target:`${o.published_at}::${jn}::collect_fee`,typeArguments:s,arguments:a}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let n=await this._sdk.fullClient.devInspectTransactionBlock({transactionBlock:e,sender:this._sdk.senderAddress});for(let i of n.events)if(q(i.type).name==="CollectFeeEvent"){let r=i.parsedJson;return{feeOwedA:r.amount_a,feeOwedB:r.amount_b}}return{feeOwedA:"0",feeOwedB:"0"}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},H0=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[ie,ie,ie]}get sdk(){return this._sdk}async emissionsEveryDay(t){let n=(await this.sdk.Pool.getPool(t)).rewarder_infos;if(!n)return null;let i=[];for(let r of n){let o=Te.fromX64(new Me.default(r.emissions_per_second));i.push({emissions:Math.floor(o.toNumber()*60*60*24),coin_address:r.coinAddress})}return i}async updatePoolRewarder(t,e){let n=await this.sdk.Pool.getPool(t),i=n.rewarder_last_updated_time;if(n.rewarder_last_updated_time=e.toString(),Number(n.liquidity)===0||e.eq(new Me.default(i)))return n;let r=e.div(new Me.default(1e3)).sub(new Me.default(i)).add(new Me.default(15)),o=n.rewarder_infos;for(let s=0;s<o.length;s+=1){let a=o[s],u=Te.checkMulDivFloor(r,new Me.default(a.emissions_per_second),new Me.default(n.liquidity),128);this.growthGlobal[s]=new Me.default(a.growth_global).add(new Me.default(u))}return n}async posRewardersAmount(t,e,n){let i=Date.parse(new Date().toString()),r=await this.updatePoolRewarder(t,new Me.default(i)),o=await this.sdk.Position.getPositionRewarders(e,n);if(o===void 0)return[];let s=r.ticks_handle,a=await this.sdk.Pool.getTickDataByIndex(s,o.tick_lower_index),u=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(r,o,a,u)}async poolRewardersAmount(t,e){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(e,new Me.default(n)),r=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(i.ticks_handle,r),s=[ie,ie,ie];for(let a=0;a<r.length;a+=1){let u=await this.posRewardersAmountInternal(i,r[a],o[0][a],o[1][a]);for(let l=0;l<3;l+=1)s[l]=s[l].add(u[l].amount_owed)}return s}posRewardersAmountInternal(t,e,n,i){let r=e.tick_lower_index,o=e.tick_upper_index,s=U0(t,n,i,r,o,this.growthGlobal),a=[],u=[];if(s.length>0){let l=Te.subUnderflowU128(s[0],new Me.default(e.reward_growth_inside_0));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[0]),u.push({amount_owed:new Me.default(e.reward_amount_owed_0).add(h),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let l=Te.subUnderflowU128(s[1],new Me.default(e.reward_growth_inside_1));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[1]),u.push({amount_owed:new Me.default(e.reward_amount_owed_1).add(h),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let l=Te.subUnderflowU128(s[2],new Me.default(e.reward_growth_inside_2));l.gt(new Me.default("3402823669209384634633745948738404"))&&(l=Cn);let h=Te.checkMulShiftRight(new Me.default(e.liquidity),l,64,128);a.push(s[2]),u.push({amount_owed:new Me.default(e.reward_amount_owed_2).add(h),coin_address:t.rewarder_infos[2].coinAddress})}return u}async batchFetchPositionRewarders(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB,rewarderInfo:o.rewarder_infos})}let n={};if(e.length>0){let i=await this.fetchPosRewardersAmount(e);for(let r of i)n[r.positionId]=r.rewarderAmountOwed;return n}return n}async fetchPositionRewarders(t,e){let n={poolAddress:t.poolAddress,positionId:e,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,rewarderInfo:t.rewarder_infos};return(await this.fetchPosRewardersAmount([n]))[0].rewarderAmountOwed}async batchFetchPositionFees(t){let e=[];for(let i of t){let r=await this._sdk.Position.getPositionById(i,!1),o=await this._sdk.Pool.getPool(r.pool,!1);e.push({poolAddress:o.poolAddress,positionId:r.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let n={};if(e.length>0){let i=await this.fetchPosFeeAmount(e);for(let r of i)n[r.position_id]=r;return n}return n}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new cs.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address})).events?.filter(u=>q(u.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let u=0;u<s.length;u+=1){let{parsedJson:l}=s[u],h={feeOwedA:new Me.default(l.fee_owned_a),feeOwedB:new Me.default(l.fee_owned_b),position_id:l.position_id};a.push(h)}return a}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new cs.TransactionBlock;for(let u of t){let l=[u.coinTypeA,u.coinTypeB],h=[r.object(D(e).global_config_id),r.object(u.poolAddress),r.pure(u.positionId),r.object(G)];r.moveCall({target:`${n.published_at}::${zt}::fetch_position_rewards`,arguments:h,typeArguments:l})}if(!Nt(i.address))throw new J(`this config simulationAccount: ${i.address} is not set right`,"InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address});if(o.error!=null)throw new J(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(u=>q(u.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new J("valueData.length !== params.pools.length");let a=[];for(let u=0;u<s.length;u+=1){let l={poolAddress:t[u].poolAddress,positionId:t[u].positionId,rewarderAmountOwed:[]};for(let h=0;h<t[u].rewarderInfo.length;h+=1)l.rewarderAmountOwed.push({amount_owed:new Me.default(s[u].parsedJson.data[h]),coin_address:t[u].rewarderInfo[h].coinAddress});a.push(l)}return a}async fetchPoolRewardersAmount(t,e){let n=await this.sdk.Pool.getPool(e),i=await this.sdk.Position.getPositionList(t,[e]),r=[];for(let a of i)r.push({poolAddress:n.poolAddress,positionId:a.pos_object_id,rewarderInfo:n.rewarder_infos,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB});let o=await this.fetchPosRewardersAmount(r),s=[ie,ie,ie];if(o!=null)for(let a of o)for(let u=0;u<a.rewarderAmountOwed.length;u+=1)s[u]=s[u].add(a.rewarderAmountOwed[u].amount_owed);return s}async getPoolLowerAndUpperTicks(t,e){let n=[],i=[];for(let r of e){let o=await this.sdk.Pool.getTickDataByIndex(t,r.tick_lower_index),s=await this.sdk.Pool.getTickDataByIndex(t,r.tick_upper_index);n.push(o),i.push(s)}return[n,i]}async collectRewarderTransactionPayload(t){if(!Nt(this._sdk.senderAddress))throw new J("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),n=new cs.TransactionBlock;return n=re.createCollectRewarderAndFeeParams(this._sdk,n,t,e),n}createCollectRewarderPaylod(t,e,n){let{clmm_pool:i,integrate:r}=this.sdk.sdkOptions,o=D(i),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((a,u)=>{e&&e.moveCall({target:`${r.published_at}::${jn}::collect_reward`,typeArguments:[...s,a],arguments:[e.object(o.global_config_id),e.object(t.pool_id),e.object(t.pos_id),e.object(o.global_vault_id),n[u],e.object(G)]})}),e}};function ss(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var Z0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new Ti.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:n,reversePair:i}=ss(t,e),r=this.poolAddressMap.get(n);if(r!=null)return{addressMap:r,direction:!0};if(r=this.poolAddressMap.get(i),r!=null)return{addressMap:r,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(n=>{let{paths:i}=n;i.forEach(r=>{let o=this.graph.getVertexByKey(r.base)??new Ti.GraphVertex(r.base),s=this.graph.getVertexByKey(r.quote)??new Ti.GraphVertex(r.quote);this.graph.addEdge(new Ti.GraphEdge(o,s));let a=this._coinAddressMap.get(r.base),u=this._coinAddressMap.get(r.quote);if(a!=null&&u!=null){let l=ss(r.base,r.quote).pair;this.poolAddressMap.set(l,r.addressMap)}})})}addPathProvider(t){for(let e=0;e<t.paths.length;e+=1){let{base:n,quote:i}=t.paths[e];n.localeCompare(i)<0&&(t.paths[e].base=i,t.paths[e].quote=n),n==="0x2::sui::SUI"&&(t.paths[e].base=i,t.paths[e].quote=n),i==="0x2::sui::SUI"&&(t.paths[e].base=n,t.paths[e].quote=i)}return this.pathProviders.push(t),this}addCoinProvider(t){return this.coinProviders=t,this}tokenInfo(t){return this._coinAddressMap.get(t)}getFeeRate(t,e,n){let i=ss(t,e).pair,r=this.poolAddressMap.get(i);if(r!=null){for(let[a,u]of r.entries())if(u===n)return a*100}let o=ss(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[a,u]of s.entries())if(u===n)return a*100}return 0}async price(t,e,n,i,r,o,s){let a=this.tokenInfo(t),u=this.tokenInfo(e);if(a===void 0||u===void 0)throw new J("From/To coin is undefined","InvalidCoin");let l=this.graph.getVertexByKey(a.address),h=this.graph.getVertexByKey(u.address),w=this.graph.findAllPath(l,h),v=Array.from(w);if(v.length===0)throw new J("No find valid path in coin graph","NotFoundPath");let T=[];for(let F=0;F<v.length;F+=1){let K=v[F];if(K.length>3)continue;let C=[],A=[],c=[],d=[];for(let g=0;g<K.length-1;g+=1){let b=K[g].value.toString(),p=K[g+1].value.toString(),m=this.getPoolAddressMapAndDirection(b,p),y=m?.addressMap,_=m?.direction;y!=null&&_!=null&&(A.push(_),C.push(b),C.push(p),y.forEach(f=>{g===0?c.push(f):d.push(f)}))}for(let g of c)if(d.length>0)for(let b of d){let p={stepNums:2,poolAB:g,poolBC:b,a2b:A[0],b2c:A[1],amount:n,byAmountIn:i,coinTypeA:C[0],coinTypeB:C[1],coinTypeC:C[3]};T.push(p)}else{let b={stepNums:1,poolAB:g,poolBC:void 0,a2b:A[0],b2c:void 0,amount:n,byAmountIn:i,coinTypeA:C[0],coinTypeB:C[1],coinTypeC:void 0};T.push(b)}}let I=T.filter(F=>F.stepNums===1),x=T.filter(F=>F.stepNums!==1),P=[];try{P=await this.getPoolWithTVL()}catch{P=[]}if(P.length>0){let F=new Map(P.map(K=>[K.poolAddress,K]));x.sort((K,C)=>{let A=0,c=0;if(F.has(K.poolAB)&&F.has(K.poolBC)){let d=F.get(K.poolAB),g=F.get(K.poolBC);A=Math.min(d.tvl,g.tvl)}if(F.has(C.poolAB)&&F.has(C.poolBC)){let d=F.get(C.poolAB),g=F.get(C.poolBC);c=Math.min(d.tvl,g.tvl)}return c-A})}if(T=[...I,...x],T.length===0){if(s!=null){let F=await this.sdk.Swap.preSwapWithMultiPool(s),K={amountIn:new Ht.default(F.estimatedAmountIn),amountOut:new Ht.default(F.estimatedAmountOut),poolAddress:[F.poolAddress],a2b:[F.aToB],rawAmountLimit:i?[F.estimatedAmountOut]:[F.estimatedAmountIn],isExceed:F.isExceed,coinType:[t,e]},C={paths:[K],partner:o,priceSlippagePoint:r};return{amountIn:new Ht.default(F.estimatedAmountIn),amountOut:new Ht.default(F.estimatedAmountOut),paths:[K],a2b:F.aToB,b2c:void 0,byAmountIn:i,isExceed:F.isExceed,targetSqrtPrice:[F.estimatedEndSqrtPrice],currentSqrtPrice:[F.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:C}}throw new J("No parameters available for service downgrade","NoDowngradeNeedParams")}let O=await this.preRouterSwapA2B2C(T.slice(0,16));if(O==null){if(s!=null){let K=await this.sdk.Swap.preSwapWithMultiPool(s),C={amountIn:new Ht.default(K.estimatedAmountIn),amountOut:new Ht.default(K.estimatedAmountOut),poolAddress:[K.poolAddress],a2b:[K.aToB],rawAmountLimit:i?[K.estimatedAmountOut]:[K.estimatedAmountIn],isExceed:K.isExceed,coinType:[t,e]},A={paths:[C],partner:o,priceSlippagePoint:r};return{amountIn:new Ht.default(K.estimatedAmountIn),amountOut:new Ht.default(K.estimatedAmountOut),paths:[C],a2b:K.aToB,b2c:void 0,byAmountIn:i,isExceed:K.isExceed,targetSqrtPrice:[K.estimatedEndSqrtPrice],currentSqrtPrice:[K.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:A}}return{amountIn:ie,amountOut:ie,paths:[],a2b:!1,b2c:!1,byAmountIn:i,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let E=O.index,B=T[E].poolBC!=null?[T[E].poolAB,T[E].poolBC]:[T[E].poolAB],$=i?[O.amountMedium,O.amountOut]:[O.amountIn,O.amountMedium],Z=[];Z.push(T[E].a2b),O.stepNum>1&&Z.push(T[E].b2c);let H=[];H.push(T[E].coinTypeA),H.push(T[E].coinTypeB),O.stepNum>1&&H.push(T[E].coinTypeC);let te={amountIn:O.amountIn,amountOut:O.amountOut,poolAddress:B,a2b:Z,rawAmountLimit:$,isExceed:O.isExceed,coinType:H},U={paths:[te],partner:o,priceSlippagePoint:r};return{amountIn:O.amountIn,amountOut:O.amountOut,paths:[te],a2b:T[E].a2b,b2c:O.stepNum>1?T[E].b2c:void 0,byAmountIn:i,isExceed:O.isExceed,targetSqrtPrice:O.targetSqrtPrice,currentSqrtPrice:O.currentSqrtPrice,coinTypeA:T[E].coinTypeA,coinTypeB:T[E].coinTypeB,coinTypeC:O.stepNum>1?T[E].coinTypeC:void 0,createTxParams:U}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new sf.TransactionBlock;for(let w of t)if(w.stepNums>1){let v=[i.object(w.poolAB),i.object(w.poolBC),i.pure(w.a2b),i.pure(w.b2c),i.pure(w.byAmountIn),i.pure(w.amount.toString())],T=[];w.a2b?T.push(w.coinTypeA,w.coinTypeB):T.push(w.coinTypeB,w.coinTypeA),w.b2c?T.push(w.coinTypeB,w.coinTypeC):T.push(w.coinTypeC,w.coinTypeB),i.moveCall({target:`${e.published_at}::${Jn}::calculate_router_swap_result`,typeArguments:T,arguments:v})}else{let v=[i.pure(w.poolAB),i.pure(w.a2b),i.pure(w.byAmountIn),i.pure(w.amount.toString())],T=w.a2b?[w.coinTypeA,w.coinTypeB]:[w.coinTypeB,w.coinTypeA];i.moveCall({target:`${e.published_at}::${u0}::get_expect_swap_result`,arguments:v,typeArguments:T})}if(!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(w=>q(w.type).name==="CalculatedRouterSwapResultEvent"||q(w.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?ie:ir,a=0;for(let w=0;w<o.length;w+=1)if(!o[w].parsedJson.data.is_exceed)if(t[0].byAmountIn){let v=new Ht.default(o[w].parsedJson.data.amount_out);v.gt(s)&&(a=w,s=v)}else{let v=t[w].stepNums>1?new Ht.default(o[w].parsedJson.data.amount_in):new Ht.default(o[w].parsedJson.data.amount_in).add(new Ht.default(o[w].parsedJson.data.fee_amount));v.lt(s)&&(a=w,s=v)}let u=[],l=[];return t[a].stepNums>1?(l.push(o[a].parsedJson.data.target_sqrt_price_ab,o[a].parsedJson.data.target_sqrt_price_cd),u.push(o[a].parsedJson.data.current_sqrt_price_ab,o[a].parsedJson.data.current_sqrt_price_cd)):(l.push(o[a].parsedJson.data.after_sqrt_price),u.push(o[a].parsedJson.current_sqrt_price)),{index:a,amountIn:t[0].byAmountIn?t[a].amount:s,amountMedium:o[a].parsedJson.data.amount_medium,amountOut:t[0].byAmountIn?s:t[a].amount,targetSqrtPrice:l,currentSqrtPrice:u,isExceed:o[a].parsedJson.data.is_exceed,stepNum:t[a].stepNums}}async getPoolWithTVL(){let t=[],{swapCountUrl:e}=this._sdk.sdkOptions;if(!e)return t;let n;try{n=await fetch(e)}catch{throw new J(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let i;try{i=await n.json()}catch{throw new J(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(i.code!==200)throw new J(`Failed to get pool list from ${e}. Statu code is ${i.code}.`,"InvalidSwapCountUrl");let{pools:r}=i.data;for(let o of r)t.push({poolAddress:o.swap_account,tvl:Number(o.tvl_in_usd)});return t}};var X0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=S(0);return t.forEach(n=>{let i=n.basePaths.length;if(i>0){let r=n.basePaths[0],o=r.label==="Cetus"?new N(r.feeRate).div(10**6):new N(r.feeRate).div(10**9),s=S(r.inputAmount).div(10**r.fromDecimal).mul(o);if(e=e.add(s),i>1){let a=n.basePaths[1],u=r.direction?r.currentPrice:new N(1).div(r.currentPrice),l=a.direction?a.currentPrice:new N(1).div(a.currentPrice),h=a.label==="Cetus"?new N(a.feeRate).div(10**6):new N(a.feeRate).div(10**9),v=S(a.outputAmount).div(10**a.toDecimal).mul(h).div(u.mul(l));e=e.add(v)}}}),e.toString()}calculateSwapPriceImpact(t){let e=S(0);return t.forEach(n=>{let i=n.basePaths.length;if(i===1){let r=n.basePaths[0],o=S(r.outputAmount).div(10**r.toDecimal),s=S(r.inputAmount).div(10**r.fromDecimal),a=o.div(s),u=r.direction?new N(r.currentPrice):new N(1).div(r.currentPrice);e=e.add(this.calculateSingleImpact(a,u))}if(i===2){let r=n.basePaths[0],o=n.basePaths[1],s=r.direction?new N(r.currentPrice):new N(1).div(r.currentPrice),a=o.direction?new N(o.currentPrice):new N(1).div(o.currentPrice),u=s.mul(a),l=new N(o.outputAmount).div(10**o.toDecimal),h=new N(r.inputAmount).div(10**r.fromDecimal),w=l.div(h);e=e.add(this.calculateSingleImpact(w,u))}}),e.toString()}calculateSingleImpact=(t,e)=>e.minus(t).div(e).mul(100);async preSwapWithMultiPool(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new wc.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];for(let l=0;l<t.poolAddresses.length;l+=1){let h=[i.pure(t.poolAddresses[l]),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:h,typeArguments:r})}if(!Nt(n.address))throw new J("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 J(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(l=>q(l.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new J("valueData.length !== params.pools.length","ParamsLengthNotEqual");let a=t.byAmountIn?ie:ir,u=0;for(let l=0;l<s.length;l+=1)if(!s[l].parsedJson.data.is_exceed)if(t.byAmountIn){let h=new ki.default(s[l].parsedJson.data.amount_out);h.gt(a)&&(u=l,a=h)}else{let h=new ki.default(s[l].parsedJson.data.amount_out);h.lt(a)&&(u=l,a=h)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[u],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[u].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new wc.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=[i.pure(t.pool.poolAddress),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];if(i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:o,typeArguments:r}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let s=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(s.error!=null)throw new J(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let a=s.events?.filter(u=>q(u.type).name==="CalculatedSwapResultEvent");return a.length===0?null:this.transformSwapData(t,a[0].parsedJson.data)}transformSwapData(t,e){let n=e.amount_in&&e.fee_amount?new ki.default(e.amount_in).add(new ki.default(e.fee_amount)).toString():"";return{poolAddress:t.pool.poolAddress,currentSqrtPrice:t.currentSqrtPrice,estimatedAmountIn:n,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:n}=e,i=n.amount_in&&n.fee_amount?new ki.default(n.amount_in).add(new ki.default(n.fee_amount)).toString():"";return{poolAddress:t.poolAddress,estimatedAmountIn:i,estimatedAmountOut:n.amount_out,estimatedEndSqrtPrice:n.after_sqrt_price,estimatedStartSqrtPrice:e.current_sqrt_price,estimatedFeeAmount:n.fee_amount,isExceed:n.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}calculateRates(t){let{currentPool:e}=t,n=a0(e),i;t.a2b?i=t.swapTicks.sort((w,v)=>v.index-w.index):i=t.swapTicks.sort((w,v)=>w.index-v.index);let r=C0(t.a2b,t.byAmountIn,t.amount,n,i),o=!1;t.byAmountIn?o=r.amountIn.lt(t.amount):o=r.amountOut.lt(t.amount);let s=mn.getDefaultSqrtPriceLimit(t.a2b);t.a2b&&r.nextSqrtPrice.lt(s)&&(o=!0),!t.a2b&&r.nextSqrtPrice.gt(s)&&(o=!0);let a=0;r.crossTickNum>6&&r.crossTickNum<40&&(a=22e3*(r.crossTickNum-6)),r.crossTickNum>40&&(o=!0);let u=ee.sqrtPriceX64ToPrice(n.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),l=ee.sqrtPriceX64ToPrice(r.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),h=Math.abs(u-l)/u*100;return{estimatedAmountIn:r.amountIn,estimatedAmountOut:r.amountOut,estimatedEndSqrtPrice:r.nextSqrtPrice,estimatedFeeAmount:r.feeAmount,isExceed:o,extraComputeLimit:a,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn,priceImpactPct:h}}async createSwapTransactionPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=ds(t);if(t.a2b&&i||!t.a2b&&r)return await re.buildSwapTransactionForGas(this._sdk,t,n,e)}return re.buildSwapTransaction(this.sdk,t,n)}async createSwapTransactionWithoutTransferCoinsPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:i,isAdjustCoinB:r}=ds(t);if(t.a2b&&i||!t.a2b&&r)return await re.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,n,e)}return re.buildSwapTransactionWithoutTransferCoins(this.sdk,t,n)}},J0=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="",n=!1){return await this.factchWarpPoolList(t,e,n)}async getTokenListByCoinTypes(t){let e={},i=this.getCache("getAllRegisteredTokenList");if(i!==void 0){let o=i;for(let s of t)for(let a of o)if(Et(s)===Et(a.address)){e[s]=a;continue}}let r=t.filter(o=>e[o]===void 0);for(let o of r){let s=`${o}_metadata`,a=this.getCache(s);if(a!==void 0)e[o]=a;else{let u=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(u){let l={id:u.id,name:u.name,symbol:u.symbol,official_symbol:u.symbol,coingecko_id:"",decimals:u.decimals,project_url:"",logo_url:u.iconUrl,address:o};e[o]=l,this.updateCache(s,l,X)}}}return e}async factchTokenList(t="",e=!1){let{simulationAccount:n,token:i}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredTokenList",e);if(o!==void 0)return o;let s=t.length>0,a=512,u=0,l=[];if(i===void 0)throw Error("please config token ofsdkOptions");let h=D(i);for(;;){let w=new bc.TransactionBlock;w.moveCall({target:`${i.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[w.pure(h.coin_registry_id),w.pure(t),w.pure(u),w.pure(a)]:[w.pure(h.coin_registry_id),w.pure(u),w.pure(a)]});let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:w,sender:n.address}),T=[];if(v.events?.forEach(I=>{q(I.type).full_address===`${i.published_at}::coin_list::FetchCoinListEvent`&&I.parsedJson.full_list.value_list.forEach(P=>{T.push(this.transformData(P,!1))})}),l=[...l,...T],T.length<a)break;u=l.length}return l}async factchPoolList(t="",e=!1){let{simulationAccount:n,token:i}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredPoolList",e);if(o!==void 0)return o;let s=[],a=512,u=0,l=t.length>0;if(i===void 0)throw Error("please config token ofsdkOptions");let h=D(i);for(;;){let w=new bc.TransactionBlock;if(w.moveCall({target:`${i.published_at}::lp_list::${l?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:l?[w.pure(h.pool_registry_id),w.pure(t),w.pure(u),w.pure(a)]:[w.pure(h.pool_registry_id),w.pure(u),w.pure(a)]}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:w,sender:n.address}),T=[];if(v.events?.forEach(I=>{q(I.type).full_address===`${i.published_at}::lp_list::FetchPoolListEvent`&&I.parsedJson.full_list.value_list.forEach(P=>{T.push(this.transformData(P,!0))})}),s=[...s,...T],T.length<a)break;u=s.length}return s}async factchWarpPoolList(t="",e="",n=!1){let i=await this.factchPoolList(t,n);if(i.length===0)return[];let r=await this.factchTokenList(e,n),o=[];for(let s of i){for(let a of r)a.address===s.coin_a_address&&(s.coinA=a),a.address===s.coin_b_address&&(s.coinB=a);o.push(s)}return o}async getTokenConfigEvent(t=!1){let e=this._sdk.sdkOptions.token.package_id,n=`${e}_getTokenConfigEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),a={coin_registry_id:"",pool_registry_id:"",coin_list_owner:"",pool_list_owner:""};return s.data.length>0&&s.data.forEach(u=>{let l=q(u.type);if(u.transactionModule==="coin_list")switch(l.name){case"InitListEvent":a.coin_list_owner=u.parsedJson.list_id;break;case"InitRegistryEvent":a.coin_registry_id=u.parsedJson.registry_id;break;default:break}else if(u.transactionModule==="lp_list")switch(l.name){case"InitListEvent<address>":a.pool_list_owner=u.parsedJson.list_id;break;case"InitRegistryEvent<address>":a.pool_registry_id=u.parsedJson.registry_id;break;default:break}}),a.coin_registry_id.length>0&&this.updateCache(n,a,X),a}transformData(t,e){let n={...t};if(e)try{n.coin_a_address=q(n.coin_a_address).full_address,n.coin_b_address=q(n.coin_b_address).full_address}catch{}else n.address=q(n.address).full_address;if(t.extensions){let i=t.extensions.contents;for(let r of i){let{key:o}=r,{value:s}=r;if(o==="labels")try{s=JSON.parse(decodeURIComponent(Yi.decode(s)))}catch{}o==="pyth_id"&&(s=(0,af.normalizeSuiObjectId)(s)),n[o]=s}delete n.extensions}return n}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},Y0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculatePrice(t,e,n,i,r){let o=i?e:n,s=i?n:e;return r==="Cetus"?ee.sqrtPriceX64ToPrice(t,o,s):new N(t.toString()).div(new N(10).pow(new N(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(n=>({pathIndex:n.path_index,lastQuoteOutput:n.last_quote_output,percent:n.percent,basePaths:n.best_path.map(r=>({direction:r.direction,label:r.label,poolAddress:r.provider,fromCoin:r.from_coin,toCoin:r.to_coin,outputAmount:r.output_amount,inputAmount:r.input_amount,feeRate:r.fee_rate,currentSqrtPrice:new hn.default(r.current_sqrt_price.toString()),afterSqrtPrice:r.label==="Cetus"?new hn.default(r.after_sqrt_price.toString()):ie,fromDecimal:r.from_decimal,toDecimal:r.to_decimal,currentPrice:this.calculatePrice(new hn.default(r.current_sqrt_price.toString()),r.from_decimal,r.to_decimal,r.direction,r.label)})),inputAmount:n.input_amount,outputAmount:n.output_amount}))}}async fetchWithTimeout(t,e,n){let i=new AbortController,r=setTimeout(()=>i.abort(),n);try{let o=await fetch(t,{...e,signal:i.signal});return clearTimeout(r),o}catch{return null}}async fetchAndParseData(t,e){try{let i=await this.fetchWithTimeout(t,e,1500);return i.status===200?this.parseJsonResult(await i.json()):null}catch{return null}}async getBestRouter(t,e,n,i,r,o,s,a,u=!1,l=!1,h=[]){let w=null,v="v2",T={},I=this.sdk.sdkOptions.aggregatorUrl;if(h.length>0){let x=new URL(I);I=`${x.protocol}//${x.hostname}/router_with_lp_changes`,T={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:n,by_amount_in:i,order_split:u,external_router:l,sender_address:"None",request_id:encodeURIComponent(is()),lp_changes:h})}}else I=`
4
+ ${I}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(n)}&by_amount_in=${encodeURIComponent(i)}&order_split=${encodeURIComponent(u)}&external_router=${encodeURIComponent(l)}&sender_address=''&request_id=${encodeURIComponent(is())}
5
+ `;if(w=await this.fetchAndParseData(I,T),w?.isTimeout||w==null){let x=await this.sdk.Router.price(t,e,new hn.default(n),i,r,o,a),P=[];for(let E of x.paths){let B=[];if(E.poolAddress.length>1){let Z=this.sdk.Router.tokenInfo(E.coinType[0]).decimals,H=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,te=E.a2b[0]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),H,Z),U={direction:E.a2b[0],label:"Cetus",poolAddress:E.poolAddress[0],fromCoin:E.coinType[0],toCoin:E.coinType[1],feeRate:this.sdk.Router.getFeeRate(E.coinType[0],E.coinType[1],E.poolAddress[0]),outputAmount:x.byAmountIn?E.rawAmountLimit[0].toString():E.rawAmountLimit[1].toString(),inputAmount:E.amountIn.toString(),currentSqrtPrice:x.currentSqrtPrice[0],currentPrice:te,fromDecimal:Z,toDecimal:H},V=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,F=this.sdk.Router.tokenInfo(E.coinType[2]).decimals,K=E.a2b[1]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),V,F):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),F,V),C={direction:E.a2b[1],label:"Cetus",poolAddress:E.poolAddress[1],fromCoin:E.coinType[1],toCoin:E.coinType[2],feeRate:this.sdk.Router.getFeeRate(E.coinType[1],E.coinType[2],E.poolAddress[1]),outputAmount:E.amountOut.toString(),inputAmount:x.byAmountIn?E.rawAmountLimit[0].toString():E.rawAmountLimit[1].toString(),currentSqrtPrice:x.currentSqrtPrice[1],currentPrice:K,fromDecimal:V,toDecimal:F};B.push(U,C)}else{let Z=this.sdk.Router.tokenInfo(E.coinType[0]).decimals,H=this.sdk.Router.tokenInfo(E.coinType[1]).decimals,te=E.a2b[0]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[0]),H,Z),U={direction:E.a2b[0],label:"Cetus",poolAddress:E.poolAddress[0],fromCoin:E.coinType[0],toCoin:E.coinType[1],feeRate:this.sdk.Router.getFeeRate(E.coinType[0],E.coinType[1],E.poolAddress[0]),outputAmount:E.amountOut.toString(),inputAmount:E.amountIn.toString(),currentSqrtPrice:x.currentSqrtPrice[0],currentPrice:te,fromDecimal:Z,toDecimal:H};B.push(U)}let $={percent:Number(E.amountIn)/Number(x.amountIn)*100,inputAmount:Number(E.amountIn.toString()),outputAmount:Number(E.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:B};P.push($)}let O={isExceed:x.isExceed,isTimeout:!0,inputAmount:Number(x.amountIn.toString()),outputAmount:Number(x.amountOut.toString()),fromCoin:x.coinTypeA,toCoin:x.coinTypeC!=null?x.coinTypeC:x.coinTypeB,byAmountIn:x.byAmountIn,splitPaths:P};v="v1",w=O}return{result:w,version:v}}},Q0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=D(this.sdk.sdkOptions.cetus_config),n=`${e}_getCoinConfigs`,i=this.getCache(n),r=i?[...i,...t]:t;this.updateCache(n,r,X)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getCoinConfigs`,r=this.getCache(i);if(r!==void 0){let s=r;for(let a of t)for(let u of s)if(Et(a)===Et(u.address)){e[a]=u;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let a=`${s}_metadata`,u=this.getCache(a);if(u!==void 0)e[s]=u;else{let l=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(l){let h={id:l.id,pyth_id:"",name:l.name,symbol:l.symbol,official_symbol:l.symbol,coingecko_id:"",decimals:l.decimals,project_url:"",logo_url:l.iconUrl,address:s};e[s]=h,this.updateCache(a,h,X)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getCoinConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildCoinConfig(l,e);this.updateCache(`${n}_${h.address}_getCoinConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getCoinConfig(t,e=!1,n=!0){let{coin_list_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${i}_${t}_getCoinConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"0x1::type_name::TypeName",value:{name:O0(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfig get object error: ${s.error}, please check the rpc and contracts address config.`,"InvalidConfig");let a=this.buildCoinConfig(s,n);return this.updateCache(r,a,X),a}buildCoinConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};return i.id=Lt(t),i.address=q(n.coin_type.fields.name).full_address,n.pyth_id&&(i.pyth_id=(0,us.normalizeSuiObjectId)(n.pyth_id)),this.transformExtensions(i,n.extension_fields.fields.contents,e),delete i.coin_type,i}async getClmmPoolConfigs(t=!1,e=!0){let{clmm_pools_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getClmmPoolConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getClmmPoolsConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildClmmPoolConfig(l,e);this.updateCache(`${h.pool_address}_getClmmPoolConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getClmmPoolConfig(t,e=!1,n=!0){let{clmm_pools_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${t}_getClmmPoolConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"address",value:t}}),a=this.buildClmmPoolConfig(s,n);return this.updateCache(r,a,X),a}buildClmmPoolConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};return i.id=Lt(t),i.pool_address=(0,us.normalizeSuiObjectId)(n.pool_address),this.transformExtensions(i,n.extension_fields.fields.contents,e),i}async getLaunchpadPoolConfigs(t=!1,e=!0){let{launchpad_pools_handle:n}=D(this.sdk.sdkOptions.cetus_config),i=`${n}_getLaunchpadPoolConfigs`,r=this.getCache(i,t);if(r)return r;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),u=[];return a.forEach(l=>{if(l.error!=null||l.data?.content?.dataType!=="moveObject")throw new J(`when getCoinConfigs get objects error: ${l.error}, please check the rpc and contracts address config.`,"InvalidConfig");let h=this.buildLaunchpadPoolConfig(l,e);this.updateCache(`${h.pool_address}_getLaunchpadPoolConfig`,h,X),u.push({...h})}),this.updateCache(i,u,X),u}async getLaunchpadPoolConfig(t,e=!1,n=!0){let{launchpad_pools_handle:i}=D(this.sdk.sdkOptions.cetus_config),r=`${t}_getLaunchpadPoolConfig`,o=this.getCache(r,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:i,name:{type:"address",value:t}}),a=this.buildLaunchpadPoolConfig(s,n);return this.updateCache(r,a,X),a}buildLaunchpadPoolConfig(t,e=!0){let n=Q(t);n=n.value.fields;let i={...n};i.id=Lt(t),i.pool_address=(0,us.normalizeSuiObjectId)(n.pool_address),this.transformExtensions(i,n.extension_fields.fields.contents,e);let r=[];n.social_media.fields.contents.forEach(o=>{r.push({name:o.fields.value.fields.name,link:o.fields.value.fields.link})}),i.social_media=r;try{i.regulation=decodeURIComponent(Yi.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=Yi.decode(i.regulation)}return i}transformExtensions(t,e,n=!0){let i=[];for(let r of e){let{key:o}=r.fields,{value:s}=r.fields;if(o==="labels")try{s=JSON.parse(decodeURIComponent(Yi.decode(s)))}catch{}n&&(t[o]=s),i.push({key:o,value:s})}delete t.extension_fields,n||(t.extensions=i)}async getCetusConfig(t=!1){let e=this._sdk.sdkOptions.cetus_config.package_id,n=`${e}_getCetusConfig`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),a={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 u of s.data)switch(q(u.type).name){case"InitCoinListEvent":a.coin_list_id=u.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":a.launchpad_pools_id=u.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":a.clmm_pools_id=u.parsedJson.pools_id;break;case"InitConfigEvent":a.global_config_id=u.parsedJson.global_config_id,a.admin_cap_id=u.parsedJson.admin_cap_id;break;default:break}return a=await this.getCetusConfigHandle(a),a.clmm_pools_id.length>0&&this.updateCache(n,a,X),a}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(i=>{if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new J(`when getCetusConfigHandle get objects error: ${i.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let r=Q(i),o=pn(i);switch(q(o).name){case"ClmmPools":t.clmm_pools_handle=r.pools.fields.id.id;break;case"CoinList":t.coin_list_handle=r.coins.fields.id.id;break;case"LaunchpadPools":t.launchpad_pools_handle=r.pools.fields.id.id;break;default:break}}),t}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){try{let n=this._cache[t];if(!n)return;if(e||!n.isValid()){delete this._cache[t];return}return n.value}catch(n){console.error(`Error accessing cache for key ${t}:`,n);return}}},ey=class extends uf.SuiClient{async queryEventsByPage(t,e="all"){let n=[],i=!0,r=e==="all",o=r?null:e.cursor;do{let s=await this.queryEvents({query:t,cursor:o,limit:r?null:e.limit});s.data?(n=[...n,...s.data],i=s.hasNextPage,o=s.nextCursor):i=!1}while(r&&i);return{data:n,nextCursor:o,hasNextPage:i}}async getOwnedObjectsByPage(t,e,n="all"){let i=[],r=!0,o=n==="all",s=o?null:n.cursor;do{let a=await this.getOwnedObjects({owner:t,...e,cursor:s,limit:o?null:n.limit});a.data?(i=[...i,...a.data],r=a.hasNextPage,s=a.nextCursor):r=!1}while(o&&r);return{data:i,nextCursor:s,hasNextPage:r}}async getDynamicFieldsByPage(t,e="all"){let n=[],i=!0,r=e==="all",o=r?null:e.cursor;do{let s=await this.getDynamicFields({parentId:t,cursor:o,limit:r?null:e.limit});s.data?(n=[...n,...s.data],i=s.hasNextPage,o=s.nextCursor):i=!1}while(r&&i);return{data:n,nextCursor:o,hasNextPage:i}}async batchGetObjects(t,e,n=50){let i=[];try{for(let r=0;r<Math.ceil(t.length/n);r++){let o=await this.multiGetObjects({ids:t.slice(r*n,n*(r+1)),options:e});i=[...i,...o]}}catch(r){console.log(r)}return i}async calculationTxGas(t){let{sender:e}=t.blockData;if(e===void 0)throw Error("sdk sender is empty");let n=await this.devInspectTransactionBlock({transactionBlock:t,sender:e}),{gasUsed:i}=n.effects;return Number(i.computationCost)+Number(i.storageCost)-Number(i.storageRebate)}async sendTransaction(t,e){try{return await this.signAndExecuteTransactionBlock({transactionBlock:e,signer:t,options:{showEffects:!0,showEvents:!0}})}catch(n){console.log("error: ",n)}}async sendSimulationTransaction(t,e,n=!0){try{if(n)return await this.devInspectTransactionBlock({transactionBlock:t,sender:e});let r={ProgrammableTransaction:{inputs:t.blockData.inputs.map(u=>{let{type:l,value:h}=u;return l==="object"?cf.Inputs.SharedObjectRef({objectId:h,initialSharedVersion:0,mutable:!0}):h}),transactions:t.blockData.transactions}},o=lf.bcs.TransactionKind.serialize(r,{maxSize:131072}).toBytes(),s=Ja(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(i){console.log("devInspectTransactionBlock error",i)}}},ar=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new ey({url:t.fullRpcUrl}),this._swap=new X0(this),this._pool=new G0(this),this._position=new W0(this),this._rewarder=new H0(this),this._router=new Z0(this),this._router_v2=new Y0(this),this._token=new J0(this),this._config=new Q0(this),gs(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,n=!0){let i=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${t}_${e}_getOwnerCoinAssets`,s=this.getCache(o,n);if(s)return s;for(;;){let a=await(e?this.fullClient.getCoins({owner:t,coinType:e,cursor:r}):this.fullClient.getAllCoins({owner:t,cursor:r}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&i.push({coinAddress:q(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),r=a.nextCursor,!a.hasNextPage)break}return this.updateCache(o,i,30*1e3),i}async getOwnerCoinBalances(t,e){let n=[];return e?n=[await this.fullClient.getBalance({owner:t,coinType:e})]:n=[...await this.fullClient.getAllBalances({owner:t})],n}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}};var hf=require("@mysten/sui.js/utils");var vs=require("@mysten/sui.js/transactions");var Zt=require("@mysten/sui.js/transactions"),fr=require("@mysten/sui.js/utils"),Vr=ge(ke(),1);var mf=require("@mysten/sui.js/utils");var Ac=require("@mysten/sui.js/transactions");var Fn=require("@mysten/sui.js/transactions");var xn=require("@mysten/sui.js/utils"),Xt=require("@mysten/sui.js/transactions");var xc=require("@mysten/sui.js/utils");var ly=require("@mysten/sui.js/utils");var qe=ge(ke(),1);var _f=ge(ke(),1);var Ic=ge(ke(),1);var Rn=require("@mysten/sui.js/transactions"),Ai=require("@mysten/sui.js/transactions");var xi=require("@mysten/sui.js/transactions");var Oe=ge(ke(),1);var Oc=require("@mysten/sui.js/bcs"),Kr=require("@mysten/sui.js/utils"),ks=require("@mysten/sui.js/transactions");var Jt=require("@mysten/sui.js/transactions"),Tc="router",dr=1e4,Yn=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:q(e.clmm_pool_id).address,booster_type:q(e.booster_type.fields.name).source_address,pool_id:q(e.pool_id).address,coinTypeA:q(e.coin_type_a.fields.name).source_address,coinTypeB:q(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=Q(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({lock_day:Number(r.fields.key),multiplier:Number(S(r.fields.value).div(dr))})}),{basic_percent:Number(S(e.basic_percent).div(dr)),balances:{balances_handle:e.balances.fields.id.id,size:e.balances.fields.size},config:n,lock_positions:{lock_positions_handle:e.lock_positions.fields.id.id,size:e.lock_positions.fields.size},is_open:e.is_open,index:Number(e.index),pool_id:Lt(t)}}static buildLockNFT(t){let e=q(Lt(t)).address;return{lock_clmm_position:Nn(t),locked_nft_id:e}}static buildLockPositionInfo(t){let e=Q(t),{value:n}=e.value.fields;return{type:n.type,position_id:n.fields.position_id,start_time:Number(n.fields.start_time),lock_period:Number(n.fields.lock_period),end_time:Number(n.fields.end_time),growth_rewarder:n.fields.growth_rewarder,rewarder_owned:n.fields.rewarder_owned,is_settled:n.fields.is_settled}}static isLocked(t){return t.end_time>Date.parse(new Date().toString())/1e3}},ty=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=!1){let{booster:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n,t),r=[];if(i!==void 0)r.push(...i);else{let o=[];(await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(D(e).booster_pool_handle)).data?.forEach(u=>{o.push(u.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let u of a){let l=Q(u);if(l){let h=Yn.buildPoolImmutables(l);this.updateCache(`${h.pool_id}_getPoolImmutable`,h,X),r.push(h)}}}return this.updateCache(n,r,X),r}async getPoolImmutable(t){let{booster:e}=this._sdk.sdkOptions,n=`${t}_getPoolImmutable`,i=this.getCache(n);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(e).booster_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=Q(r),s=Yn.buildPoolImmutables(o);return this.updateCache(n,s,X),s}async getPools(){let t=[],n=(await this.getPoolImmutables()).map(r=>r.pool_id),i=await this._sdk.ClmmSDK.fullClient.batchGetObjects(n,{showType:!0,showContent:!0});for(let r of i){let o=Yn.buildPoolState(r);if(o){let s={...await this.getPoolImmutable(o.pool_id),...o};t.push(s);let a=`${s.pool_id}_getPoolObject`;this.updateCache(a,s,X)}}return t}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e),r=await this.getPoolImmutable(t);if(i!==void 0)return{...r,...i};let o=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),s=Yn.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,X),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=Q(e);return n?n.list.fields.id.id:""}async getBoosterInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.booster,e=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitEvent`}))?.data,n={booster_config_id:"",booster_pool_handle:""};return e.length>0&&e.forEach(i=>{let r=i.parsedJson;r&&(n.booster_config_id=r.config_id)}),n.booster_pool_handle=await this.getPoolHandleId(n.booster_config_id),n}async getOwnerBoosterPositions(t,e,n){let{booster:i}=this.sdk.sdkOptions,r=[],o=[],s=`${i.package_id}::lock_nft::LockNFT<${this._sdk.ClmmSDK.Position.buildPositionType()}>`,a=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showOwner:!0},filter:{StructType:s}});for(let l of a.data)if(q(Mt(l)).source_address===s&&l.data){let w=Yn.buildLockNFT(l);this.updateCache(`${w.locked_nft_id}_getBoosterPositionById`,w,X),w&&(e===void 0||e===w.lock_clmm_position.pool)&&r.push(w)}let u=await this.getLockPositionInfos(n,r.map(l=>l.locked_nft_id));for(let l of r)for(let h of u)if(l.lock_clmm_position.pos_object_id===h.position_id){o.push({...l,...h});break}return o}async getBoosterPosition(t,e){let n=`${e}_getBoosterPositionById`,i=this.getCache(n),r;if(i!==void 0)r=i;else{let s=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0,showOwner:!0}});r=Yn.buildLockNFT(s),this.updateCache(n,r,X)}let o=await this.getLockPositionInfo(t,e);return{...r,...o}}async getLockPositionInfos(t,e=[]){let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(t),i=[],r=[];return n.data?.forEach(o=>{e.length>0?e.includes(o.name.value)&&i.push(o.objectId):i.push(o.objectId)}),i.length>0&&(await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showContent:!0})).forEach(s=>{let a=Yn.buildLockPositionInfo(s);a&&r.push(a)}),r}async getLockPositionInfo(t,e){let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}});return Yn.buildLockPositionInfo(n)}calculateXCetusRewarder(t,e,n){let i=e.basic_percent,r="0";t.forEach(a=>{a.coin_address===e.booster_type&&(console.log("find ",e.booster_type),r=a.amount_owed.toString())}),n.is_settled||e.config.forEach(a=>{a.lock_day===n.lock_period&&(i=a.multiplier)});let o=S(r).sub(n.growth_rewarder).mul(i);return S(n.rewarder_owned).add(o).toString()}lockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new vs.TransactionBlock;return i.moveCall({target:`${e.published_at}::${Tc}::lock_position`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[i.pure(D(e).booster_config_id),i.pure(D(n).global_config_id),i.pure(t.booster_pool_id),i.pure(t.clmm_pool_id),i.pure(t.clmm_position_id),i.pure(t.lock_day),i.pure(G)]}),i}canceLockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,n=new vs.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Tc}::cancel_lock`,typeArguments:[t.booster_type],arguments:[n.pure(D(e).booster_config_id),n.pure(t.booster_pool_id),n.pure(t.lock_nft_id),n.pure(G)]}),n}redeemPayload(t){let{booster:e,xcetus:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions,r=new vs.TransactionBlock,o=D(n);return r.moveCall({target:`${e.published_at}::${Tc}::redeem`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[r.pure(D(e).booster_config_id),r.pure(D(i).global_config_id),r.pure(t.booster_pool_id),r.pure(t.lock_nft_id),r.pure(t.clmm_pool_id),r.pure(o.lock_manager_id),r.pure(o.xcetus_manager_id),r.pure(t.ve_nft_id),r.pure(G)]}),r}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Vt="router",pf=1e9;var An=class{static priceRealToFix(t,e,n){let i=S(e-n).toNumber();return Number(S(t).div(S(10).pow(S(i))).toString())}static priceFixToReal(t,e,n){let i=S(e-n).toNumber();return Number(S(t).mul(S(10).pow(S(i))).toString())}static raiseTotalAmount(t,e,n){let i=S(e-n).abs().toNumber();return e>n?Number(S(t.total_supply).mul(t.current_price).div(S(10).pow(S(i))).toString()):Number(S(t.total_supply).mul(t.current_price).mul(S(10).pow(S(i))).toString())}static buildLaunchPadPool(t){let e=Mt(t),n=q(e),i=Q(t),r={coin_type_sale:n.type_arguments[0],coin_type_raise:n.type_arguments[1],pool_address:(0,mf.normalizeSuiObjectId)(Lt(t)),is_settle:i.is_settle,current_price:S(i.initialize_price).div(S(pf)).toString(),price:i.initialize_price,min_price:"0",max_price:"0",sale_coin_amount:i.sale_coin,raise_coin_amount:i.raise_coin,total_purchase_amount:i.reality_raise_total,total_supply:i.sale_total,min_purchase:i.min_purchase,max_purchase:i.max_purchase,complete_raise_limit:i.least_raise_amount,softcap:i.softcap,max_raise_amount:i.hardcap,sale_decimals:0,raise_decimals:0,liquidity_injection_ratio:Number(i.liquidity_rate)/1e4,is_cancel:i.is_cancel,duration_summary:{start_time:Number(i.duration_manager.fields.start_time),end_time:0,settle_end_time:0,purchase_duration:Number(i.duration_manager.fields.activity_duration),settle_duration:Number(i.duration_manager.fields.settle_duration),lock_up_duration:Number(i.duration_manager.fields.locked_duration)},white_summary:{white_handle:i.white_list.fields.users.fields.id.id,protection_hard_cap:i.white_list.fields.hard_cap_total,protection_limit_used:i.white_list.fields.purchase_total,size:Number(i.white_list.fields.users.fields.size)},unused_sale:i.unused_sale,harvest_raise:i.harvest_raise,tick_spacing:Number(i.tick_spacing),owner:i.recipient,purchase_summary:{purchase_handle:i.purchase_list.fields.id.id,size:Number(i.purchase_list.fields.size)},pool_status:"Failed"};return An.updatePoolStatus(r),r}static updatePoolStatus(t){let e=Number(S(Date.now()/1e3).toFixed(0)),{duration_summary:n}=t,i=n.start_time+n.purchase_duration,r=i+n.settle_duration;if(n.end_time=i,n.settle_end_time=r,t.is_settle)t.pool_status="Ended";else if(t.is_cancel)t.pool_status="Canceled";else if(e<n.start_time)t.pool_status="Upcoming";else if(e>n.start_time&&e<i)t.pool_status="Live";else if(e>i&&e<r){let o=t.raise_coin_amount;Number(o)<Number(t.complete_raise_limit)?t.pool_status="Failed":t.pool_status="Settle"}return t}static async calculatePoolPrice(t,e){let n=await t.ClmmSDK.CetusConfig.getTokenListByCoinTypes([e.coin_type_sale,e.coin_type_raise]),i=n[e.coin_type_sale].decimals,r=n[e.coin_type_raise].decimals;e.min_price=this.priceFixToReal(Number(S(e.softcap).div(S(e.total_supply))),i,r).toString(),e.max_price=this.priceFixToReal(Number(S(e.max_raise_amount).div(S(e.total_supply))),i,r).toString(),e.current_price=this.priceFixToReal(Number(e.current_price),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r}static async getWithdrawRaise(t){return t.pool_status==="Ended"?t.harvest_raise:"0"}static async getWithdrawSale(t){return t.pool_status==="Ended"?t.unused_sale:t.sale_coin_amount}static async getHistoryWithdrawRaise(t,e){if(e.pool_status==="Ended"){if(S(e.harvest_raise).equals(S(0))){let i=await t.Launchpad.getSettleEvent(e.pool_address);i&&(e.harvest_raise=i.unused_raise)}let n=(0,Vr.min)(new Vr.default(e.total_purchase_amount),new Vr.default(e.max_raise_amount));return S(n.toString()).mul(1-e.liquidity_injection_ratio).toString()}return"0"}static async getHistoryWithdrawSale(t,e){if(e.pool_status==="Ended"){let n=await t.Launchpad.getSettleEvent(e.pool_address);return n&&(e.unused_sale=n.unused_sale),e.unused_sale}return"0"}static async getOverrecruitReverseAmount(t,e){let n=await t.Launchpad.getPurchaseMarks(t.ClmmSDK.senderAddress,[e.pool_address],!1);if(n.length>0){let i=n[0].purchased_raise_amount,r=(await t.Launchpad.getPurchaseAmount(e.white_summary.white_handle,t.ClmmSDK.senderAddress)).safe_purchased_amount,{protection_limit_used:o}=e.white_summary;return S(i).sub(r).div(S(e.total_purchase_amount).sub(o)).mul(S(e.total_purchase_amount).sub(e.max_raise_amount)).toString()}return"0"}static async getCanPurchaseAmount(t,e){let n=await An.getOverrecruitReverseAmount(t,e),i=await t.Launchpad.getPurchaseMarks(t.ClmmSDK.senderAddress,[e.pool_address],!1);if(i){let r=i[0].purchased_raise_amount;S(r).sub(n).div(e.current_price)}return"0"}},ny=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=[],e=0,n=100,i=!1){let{package_id:r}=this._sdk.sdkOptions.launchpad;if(r===void 0)throw Error("sdk.sdkOptions.launchpad is undefined");let o=`${r}_getPoolImmutables`,s=this.getCache(o,i),a=[],u=[];if(s!==void 0&&a.push(...s),a.length===0)try{((await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`}))?.data).forEach(w=>{let v=w.parsedJson;v&&a.push({pool_address:v.pool_id,coin_type_sale:q(v.sale_coin.name).full_address,coin_type_raise:q(v.raise_coin.name).full_address})}),this.updateCache(o,a,X)}catch(h){console.log("getPoolImmutables",h)}let l=t.length>0;for(let h=0;h<a.length;h+=1){let w=a[h];if(!(l&&!t.includes(w.pool_address))){if(!l){let v=h;if(v<e||v>=e+n)continue}u.push(w)}}return u}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.launchpad,i=`${n}_getPoolImmutables`,r=[],o={data:[],hasNextPage:!1},s=t==="all";if(s){let a=this.getCache(i,e);a&&r.push(...a)}if(r.length===0)try{let a=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n}::factory::CreatePoolEvent`},t);o.hasNextPage=a.hasNextPage,o.nextCursor=a.nextCursor,a.data.forEach(u=>{let l=u.parsedJson;l&&r.push({pool_address:l.pool_id,coin_type_sale:q(l.sale_coin.name).full_address,coin_type_raise:q(l.raise_coin.name).full_address})})}catch(a){console.log("getPoolImmutables",a)}return o.data=r,s&&this.updateCache(i,r,X),o}async getPools(t=[],e=0,n=100){let i=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutables([],e,n,!1)).forEach(a=>{r.push(a.pool_address)});let o=await this._sdk.ClmmSDK.fullClient.batchGetObjects(r,{showType:!0,showContent:!0});for(let s of o){let a=An.buildLaunchPadPool(s);await An.calculatePoolPrice(this._sdk,a),i.push(a);let u=`${a.pool_address}_getPoolObject`;this.updateCache(u,a,X)}return i}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0){let s=i;return An.updatePoolStatus(s),s}let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=An.buildLaunchPadPool(r);return await An.calculatePoolPrice(this._sdk,o),this.updateCache(n,o),o}async getInitConfig(t=!1){let e=this._sdk.sdkOptions.launchpad.package_id,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({Transaction:o}))?.data,a={pools_id:"",admin_cap_id:"",config_cap_id:""};return s.length>0&&(s.forEach(u=>{let l=u.parsedJson;if(l)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=l.admin_cap_id,a.config_cap_id=l.config_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;default:break}}),this.updateCache(n,a,X)),a}async getLockNFT(t,e=!1){let n=`${t}_getLockNFT`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(!r.error)return Nn(r)}async getLockNFTList(t){let{package_id:e}=this._sdk.ClmmSDK.sdkOptions.clmm_pool,{sdkOptions:n}=this._sdk,i=[];try{let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n.launchpad.package_id}::lock::LockNFTEvent`}))?.data;for(let o of r){let s=o.parsedJson;if(s){let a={locked_time:Number(s.locked_time),end_lock_time:Number(s.end_lock_time),nft_type:s.nft_type_name.name,lock_nft_id:s.lock_nft_id,recipient:s.recipient};if(t===a.recipient&&`${e}`===q(a.nft_type).address){let u=await this.getLockNFT(a.lock_nft_id);if(u){let l=q(u.coin_type_a).full_address,h=q(u.coin_type_b).full_address;i.push({...u,coin_type_a:l,coin_type_b:h,...a})}}}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPoolTransactionPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=D(e);if(this.assertLuanchpadConfig(),this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let i=An.priceRealToFix(Number(t.initialize_price),t.sale_decimals,t.raise_decimals),r=new Zt.TransactionBlock,o=S(t.total_supply).add(S(t.total_supply).mul(S(t.liquidity_rate))).toNumber(),s=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,r,BigInt(o),t.coin_type_sale),a=[r.pure(n.admin_cap_id),r.pure(n.config_cap_id),r.pure(n.pools_id),r.pure((0,fr.normalizeSuiAddress)(t.recipient)),r.pure((i*pf).toString()),s,r.pure(t.total_supply.toString()),r.pure(t.min_purchase.toString()),r.pure(t.max_purchase.toString()),r.pure(t.least_raise_amount.toString()),r.pure(t.hardcap.toString()),r.pure((t.liquidity_rate*1e3).toString()),r.pure(t.start_time.toString()),r.pure(t.activity_duration.toString()),r.pure(t.settle_duration.toString()),r.pure(t.locked_duration.toString()),r.pure(t.tick_spacing.toString()),r.pure(G)],u=[t.coin_type_sale,t.coin_type_raise];return r.moveCall({target:`${e.published_at}::${Vt}::create_launch_pool`,typeArguments:u,arguments:a}),r}async creatPurchasePayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=new Zt.TransactionBlock,i=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.purchase_amount),t.coin_type_raise),r=(await this.getPurchaseMarks(this._sdk.ClmmSDK.senderAddress,[t.pool_address],!1))[0],o=[t.coin_type_sale,t.coin_type_raise],s;return r?s=[n.pure(t.pool_address),n.pure(D(e).config_cap_id),n.pure(r.id),i,n.pure(t.purchase_amount.toString()),n.pure(G)]:s=[n.pure(t.pool_address),n.pure(D(e).config_cap_id),i,n.pure(t.purchase_amount.toString()),n.pure(G)],n.moveCall({target:`${e.published_at}::${Vt}::${r===void 0?"create_and_purchase":"purchase"}`,typeArguments:o,arguments:s}),n}async creatClaimPayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=(await this.getPurchaseMarks(this._sdk.ClmmSDK.senderAddress,[t.pool_address],!1))[0],i=new Zt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure(t.pool_address),i.pure(D(e).config_cap_id),i.pure(n?.id),i.pure(G)];return i.moveCall({target:`${e.published_at}::${Vt}::claim`,typeArguments:r,arguments:o}),i}async creatSettlePayload(t){let{launchpad:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions;if(this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");this.assertLuanchpadConfig();let i=D(n),{clmm_args:r}=t,o=new Zt.TransactionBlock;o.setSender(this.sdk.ClmmSDK.senderAddress);let s=[t.coin_type_sale,t.coin_type_raise];if(r){let a=r.opposite?ee.priceToSqrtPriceX64(S(1).div(r.current_price),r.raise_decimals,r.sale_decimals).toString():ee.priceToSqrtPriceX64(S(r.current_price),r.sale_decimals,r.raise_decimals).toString(),u=BigInt(a)<BigInt(r.clmm_sqrt_price),l=r.opposite?u?t.coin_type_raise:t.coin_type_sale:u?t.coin_type_sale:t.coin_type_raise,h=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,l),w=we.calculateTotalBalance(h);we.isSuiCoin(l)&&(w-=BigInt(2e8));let T=re.buildCoinForAmount(o,h,w,l).targetCoin,I=r.opposite?u?"settle_with_reverse_clmm_only_with_a":"settle_with_reverse_clmm_only_with_b":u?"settle_only_with_a":"settle_only_with_b",x=[o.pure(t.pool_address),o.pure(D(e).config_cap_id),o.pure(r.clmm_pool_address),o.pure(i.global_config_id),o.pure(a),T,o.pure(G)];o.moveCall({target:`${e.published_at}::${Vt}::${I}`,typeArguments:s,arguments:x})}else o.moveCall({target:`${e.published_at}::${Vt}::settle`,typeArguments:s,arguments:[o.pure(t.pool_address),o.pure(D(e).config_cap_id),o.pure(G)]});return o}creatWithdrawPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object(t.pool_address),n.object(D(e).config_cap_id),n.object(G)];return t.sale_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Vt}::withdraw_sale`,typeArguments:i,arguments:r}),t.raise_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Vt}::withdraw_raise`,typeArguments:i,arguments:r}),n}addUserToWhitelisPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.object(r),n.pure(t.safe_limit_amount),n.object(G)];n.moveCall({target:`${e.published_at}::${Vt}::add_user_to_whitelist`,typeArguments:i,arguments:o})}),n}updateWhitelistCapPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.safe_limit_amount>0&&n.moveCall({target:`${e.published_at}::${Vt}::update_whitelist_member_safe_limit_amount`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.pure(t.white_list_member),n.pure(t.safe_limit_amount),n.object(G)]}),t.hard_cap_total>0&&n.moveCall({target:`${e.published_at}::${Vt}::update_whitelist_hard_cap_total`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.pure(t.hard_cap_total),n.object(G)]}),n}creatRemoveWhitelistPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object(D(e).admin_cap_id),n.object(D(e).config_cap_id),n.object(t.pool_address),n.object(r),n.object(G)];n.moveCall({target:`${e.published_at}::${Vt}::remove_user_from_whitelist`,typeArguments:i,arguments:o})}),n}creatCancelPoolPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::cancel`,typeArguments:i,arguments:r}),n}updateRecipientPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(t.new_recipient),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::update_recipient_address`,typeArguments:i,arguments:r}),n}updatePoolDuractionPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Zt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).config_cap_id),n.pure(t.pool_address),n.pure(t.activity_duration),n.pure(t.settle_duration),n.pure(t.lock_duration),n.pure(G)];return n.moveCall({target:`${e.published_at}::${Vt}::update_pool_duration`,typeArguments:i,arguments:r}),n}creatUnlockNftPayload(t){let{launchpad:e}=this.sdk.sdkOptions;if(D(e)===void 0)throw Error("getPackagerConfigs(launchpad) is null");let n=new Zt.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft),n.pure(G)];return n.moveCall({target:`${e.published_at}::lock::unlock_nft`,typeArguments:i,arguments:r}),n}async isAdminCap(t){let{launchpad:e}=this._sdk.sdkOptions;if(D(e)===void 0)throw Error("launchpad config is empty");let n=`${t}_isAdminCap`,i=this.getCache(n);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:D(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=pn(r),s=sr(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,fr.normalizeSuiAddress)(s.AddressOwner)===(0,fr.normalizeSuiAddress)(t)),this.updateCache(n,a,X),a}async isWhiteListUser(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n});return!!(i&&i.data)}catch{return!1}}async getPurchaseAmount(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n}),r=Q(i);if(console.log(r),r)return r?.value?.fields}catch{}return{safe_limit_amount:"0",safe_purchased_amount:"0"}}async getPurchaseMarks(t,e=[],n=!0){let{launchpad:i}=this._sdk.sdkOptions,r=`${e}_getPurchaseMark`,o=this.getCache(r,n);if(!n&&o!==void 0)return o;let s=null,a=[];for(;;){let u=await this._sdk.ClmmSDK.fullClient.getOwnedObjects({owner:t,options:{showType:!0,showContent:!0,showDisplay:!0},cursor:s});for(let l of u.data){let{fields:h}=l.data.content;if(q(Mt(l)).source_address===`${i.package_id}::pool::PurchaseMark`){console.log("fields: ",h);let v={id:h.id.id,pool_id:q(h.pool_id).address,purchased_raise_amount:h.purchase_total,obtain_sale_amount:h.obtain_sale_amount,used_raise_amount:h.used_raise_amount};e.length>0?e.includes(v.pool_id)&&a.push(v):a.push(v)}}if(u.hasNextPage)s=u.nextCursor;else break}return this.updateCache(r,a,X),a}async getSettleEvent(t){let{launchpad:e}=this._sdk.sdkOptions,n=`${t}_getPurchaseMark`,i=this.getCache(n);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e.package_id}::pool::SettleEvent`});for(let o of r.data){let s=o.parsedJson;if(t===(0,fr.normalizeSuiObjectId)(s.pool_id)){let a={pool_id:s.pool_id,settle_price:s.settle_price,unused_sale:s.unused_sale,unused_raise:s.unused_raise,white_purchase_total:s.white_purchase_total};return this.updateCache(n,a,X),a}}}buildLaunchpadCoinType(t,e){return rr(this._sdk.sdkOptions.launchpad.package_id,"pool","PoolLiquidityCoin",[t,e])}assertLuanchpadConfig(){let{launchpad:t}=this.sdk.sdkOptions;if(D(t)===void 0)throw Error("sdk getPackagerConfigs(launchpad) is null")}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Qn=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:q(e.clmm_pool_id).address,bonus_type:q(e.bonus_type.fields.name).source_address,pool_id:q(e.pool_id).address,coinTypeA:q(e.coin_type_a.fields.name).source_address,coinTypeB:q(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=Q(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({rate:Number(S(r.fields.key).div(dr)),multiplier:Number(S(r.fields.value).div(dr))})}),{balance:e.balance,config:n,is_open:e.is_open,index:Number(e.index),start_time:Number(e.start_time),interval_day:Number(e.interval_day),minimum_percent_to_reward:Number(S(e.minimum_percent_to_reward).div(dr)),rewarders:{rewarder_handle:e.rewarders.fields.id.id,size:Number(e.rewarders.fields.size)},whale_nfts:{whale_nfts_handle:e.whale_nfts.fields.id.id,size:Number(e.whale_nfts.fields.size)},points:{point_handle:e.points.fields.id.id,size:Number(e.points.fields.size)}}}static buildMarkerPositions(t){let{contents:e}=t.value.fields.value.fields,n=[],i=t.id.id;return e.forEach(r=>{let{key:o,value:s}=r.fields,a={id:o,period_id:i,bonus_num:s.fields.bonus_num,point:s.fields.point,is_burn:s.fields.is_burn,point_after_multiplier:s.fields.point_after_multiplier,percent:Number(S(s.fields.percent).div(dr)),fee_share_rate:0,is_redeemed:s.fields.is_redeemed};n.push(a)}),n}static buildPoolBonusInfo(t){let{fields:e,type:n}=t.value.fields.value;return{type:n,time:Number(e.time),settle_time:Number(e.settle_time),settled_num:e.settled_num,is_settled:e.is_settled,basis_bonus:e.basis_bonus,total_bonus:e.total_bonus,is_vacant:e.is_vacant,redeemed_num:e.redeemed_num}}static getBonusPercent(t,e){let n=0;for(let i of t)e>=i.rate&&i.rate>n&&(n=i.multiplier);return n}},df="router",iy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t=!1){let{maker_bonus:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n,t),r=[];if(i!==void 0)r.push(...i);else{let o=[];(await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(D(e).maker_pool_handle)).data?.forEach(u=>{o.push(u.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let u of a){let l=Q(u);l&&r.push(Qn.buildPoolImmutables(l))}}return r}async getPoolImmutable(t){let{maker_bonus:e}=this._sdk.sdkOptions,n=`${e.package_id}_getPoolImmutables`,i=this.getCache(n);if(i!==void 0){let s=i.filter(a=>t===a.pool_id);if(s.length>0)return s[0]}let r=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(e).maker_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=Q(r);return Qn.buildPoolImmutables(o)}async getPools(){let t=[],e=await this.getPoolImmutables(),n=e.map(o=>o.pool_id),i=await this._sdk.ClmmSDK.fullClient.batchGetObjects(n,{showType:!0,showContent:!0}),r=0;for(let o of i){let s=Qn.buildPoolState(o);if(s){let a={...e[r],...s};t.push(a);let u=`${a.pool_id}_getPoolObject`;this.updateCache(u,a,X)}r+=1}return t}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e),r=await this.getPoolImmutable(t);if(i!==void 0)return i;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),s=Qn.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,X),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=Q(e);return n?n.list.fields.id.id:""}async getMakerPoolPeriods(t,e=!1){let n=[],i=`${t.pool_id}_getMakerPoolPeriods`,r=this.getCache(i,e);return r!==void 0?r:((await this._sdk.ClmmSDK.fullClient.getDynamicFieldsByPage(t.whale_nfts.whale_nfts_handle)).data.forEach(s=>{let a={id:s.objectId,start_time:0,end_time:0,period:Number(s.name.value)};a.start_time=Number(S(t.start_time).add(S(t.interval_day).mul(24*3600).mul(a.period)).toFixed(0,N.ROUND_DOWN)),a.end_time=Number(S(a.start_time).add(S(t.interval_day).mul(24*3600)).toFixed(0,N.ROUND_DOWN)),n.push(a)}),this.updateCache(i,n,X),n)}async getMakerBonusInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.maker_bonus,e=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitEvent`}))?.data,n={maker_config_id:"",maker_pool_handle:""};return e.length>0&&e.forEach(i=>{let r=i.parsedJson;r&&(n.maker_config_id=r.config_id)}),n.maker_pool_handle=await this.getPoolHandleId(n.maker_config_id),n}async getPoolMarkerPositionList(t,e,n=!1){let i={},r=[];n||e.forEach(o=>{let s=`${t}_${o.period}_getPoolMarkerPositionList`,a=this.getCache(s);a!==void 0?i[o.period]=a:(i[o.period]=[],r.push(o))});try{r.length>0&&(await this._sdk.ClmmSDK.fullClient.batchGetObjects(r.map(a=>a.id),{showContent:!0})).forEach(a=>{let u=Q(a),l=Qn.buildMarkerPositions(u);if(l.length>0){let{period_id:h}=l[0],w=e.filter(v=>v.id===h)[0];i[w.period]=l}});let o=[];for(let s in i)i[s].forEach(u=>{o.push(u)});if(o.length>0){let s=await this._sdk.ClmmSDK.Position.getSipmlePositionList(o.map(a=>a.id));for(let a of o)for(let u of s)if(a.id===u.pos_object_id){a.clmm_position=u;break}}}catch(o){console.log(o)}for(let o in i){let s=`${t}_${o}_getPoolMarkerPositionList`;this.updateCache(s,i[o],X)}return i}async updateXCetusRewarderAndFee(t,e,n){let i=await this.calculateTotalPointsAfterMultiper(t,n);for(let r of e)await this.calculateXCetusRewarder(t,r,n.period,i);return e}async calculateXCetusRewarder(t,e,n,i){let r=await this.getPoolBonusInfo(t.rewarders.rewarder_handle,n),{fee_share_rate:o}=this.calculateFeeShareRate(t,e,i),s=S(o).mul(r.total_bonus);return e.is_redeemed?e.bonus_num="0":e.bonus_num=s.toString(),e.bonus_num}calculateFeeShareRate(t,e,n){let i=Qn.getBonusPercent(t.config,e.percent),r=S(e.point).mul(i),o=S(r).div(n);return e.point_after_multiplier=r.toString(),e.fee_share_rate=Number(o),{fee_share_rate:Number(o),points_after_multiper:r.toString()}}async calculateTotalPointsAfterMultiper(t,e){let n=await this.getPoolMarkerPositionList(t.whale_nfts.whale_nfts_handle,[e]),i=S(0),r=n[e.period];for(let o of r){let s=Qn.getBonusPercent(t.config,o.percent),a=S(o.point).mul(s);i=i.add(a)}return i.toString()}async calculateAllXCetusRewarder(t){let e=this._sdk.ClmmSDK.senderAddress,n=S(0),i=[];for(let r of t){let o=await this._sdk.MakerModule.getMakerPoolPeriods(r),s=await this._sdk.MakerModule.getPoolMarkerPositionList(r.whale_nfts.whale_nfts_handle,o),a=[];for(let u of o){let l=s[u.period].filter(h=>e.length===0?!1:h.clmm_position?.owner===e);l.length>0&&(await this._sdk.MakerModule.updateXCetusRewarderAndFee(r,l,u),l.forEach(h=>{h.clmm_position?.position_status===vc.Exists&&S(h.bonus_num).greaterThan(0)&&(n=n.add(h.bonus_num),a.includes(h.clmm_position.pos_object_id)||a.push(h.clmm_position.pos_object_id))}))}i.push({bonus_type:r.bonus_type,pool_id:r.pool_id,nft_ids:a})}return{claimtotal:n,claimRecord:i}}async getPoolBonusInfo(t,e,n=!1){let i=`${t}_${e}_getPoolBonusInfo`,r=this.getCache(i,n);if(r!==void 0)return r;let o=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:e.toString()}}),s=Q(o),a=Qn.buildPoolBonusInfo(s);return this.updateCache(i,a,Ue),a}claimPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Ac.TransactionBlock;return i.moveCall({target:`${e.published_at}::${df}::claim`,typeArguments:[t.bonus_type],arguments:[i.pure(D(e).maker_config_id),i.pure(t.market_pool_id),i.pure(t.position_nft_id),i.pure(t.phase),i.pure(D(n).lock_manager_id),i.pure(D(n).xcetus_manager_id),i.pure(t.ve_nft_id)]}),i}claimAllPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Ac.TransactionBlock;return t.whale_nfts.forEach(r=>{r.nft_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::${df}::claim_all`,typeArguments:[r.bonus_type],arguments:[i.object(D(e).maker_config_id),i.object(r.pool_id),i.object(o),i.object(D(n).lock_manager_id),i.object(D(n).xcetus_manager_id),i.object(t.ve_nft_id)]})})}),i}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},cr="router",Cc="router",zr=24*3600,Ts=1e3,sn=1e11,Ii=class{static buildVeNFTDividendInfo(t){let e={id:t.id.id,ve_nft_id:t.name,rewards:[]};return t.value.fields.value.fields.dividends.fields.contents.forEach(n=>{let i=[];n.fields.value.fields.contents.forEach(r=>{i.push({coin_type:q(r.fields.key.fields.name).source_address,amount:r.fields.value})}),e.rewards.push({period:Number(n.fields.key),rewards:i})}),e}static buildDividendManager(t){let e={id:t.id.id,dividends:{id:t.dividends.fields.id.id,size:t.dividends.fields.size},venft_dividends:{id:t.venft_dividends.fields.id.id,size:t.venft_dividends.fields.size},bonus_types:[],start_time:Number(t.start_time),interval_day:Number(t.interval_day),balances:{id:t.balances.fields.id.id,size:t.balances.fields.size},is_open:t.is_open};return t.bonus_types.forEach(n=>{e.bonus_types.push(q(n.fields.name).source_address)}),e}static buildLockUpManager(t){return{id:t.id.id,balance:t.balance,treasury_manager:t.treasury_manager,extra_treasury:t.extra_treasury,lock_infos:{lock_handle_id:t.lock_infos.fields.id.id,size:Number(t.lock_infos.fields.size)},type_name:Et(t.type_name.fields.name),min_lock_day:Number(t.min_lock_day),max_lock_day:Number(t.max_lock_day),package_version:Number(t.package_version),max_percent_numerator:Number(t.max_percent_numerator),min_percent_numerator:Number(t.min_percent_numerator)}}static buildLockCetus(t){let e=t.fields,n={id:e.id.id,type:q(t.type).source_address,locked_start_time:Number(e.locked_start_time),locked_until_time:Number(e.locked_until_time),cetus_amount:e.balance,xcetus_amount:"0",lock_day:0};return n.lock_day=(n.locked_until_time-n.locked_start_time)/zr,n}static getAvailableXCetus(t,e){let n=S(0);return e.forEach(i=>{n=n.add(i.xcetus_amount)}),S(t.xcetus_balance).sub(n).toString()}static getWaitUnLockCetuss(t){return t.filter(e=>!Ii.isLocked(e))}static getLockingCetuss(t){return t.filter(e=>Ii.isLocked(e))}static isLocked(t){return t.locked_until_time>Date.parse(new Date().toString())/1e3}static buildDividendRewardTypeList(t){let e=new Set;return t.forEach(n=>{n.rewards.forEach(i=>{e.add(i.coin_type)})}),Array.from(e)}static getNextStartTime(t){let e=Date.now()/1e3,{start_time:n,interval_day:i}=t,r=Math.ceil((e-n)/(i*zr));return n+r*i*zr}},ry=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getOwnerVeNFT(t,e=!0){let{xcetus:n}=this.sdk.sdkOptions,i=`${t}_getLockUpManagerEvent`,r=this.getCache(i,e);if(r!==void 0)return r;let o,s=`${n.package_id}::xcetus::VeNFT`;return(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0},filter:{StructType:s}})).data.forEach(u=>{let l=q(Mt(u)).source_address;if(l===s&&u.data&&u.data.content){let{fields:h}=u.data.content;o={...Si(u),id:h.id.id,index:h.index,type:l,xcetus_balance:h.xcetus_balance},this.updateCache(i,o,X)}}),o}async getOwnerLockCetuss(t){let{xcetus:e}=this.sdk.sdkOptions,n=[],i=`${e.package_id}::lock_coin::LockedCoin<${this.buileCetusCoinType()}>`,r=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0},filter:{StructType:i}});for(let o of r.data)if(q(Mt(o)).source_address===i&&o.data){let a=Ii.buildLockCetus(o.data.content);a.xcetus_amount=await this.getXCetusAmount(a.id),n.push(a)}return n}async getLockCetus(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(e.data?.content){let n=Ii.buildLockCetus(e.data.content);return n.xcetus_amount=await this.getXCetusAmount(n.id),n}}async getOwnerCetusCoins(t){return await this._sdk.ClmmSDK.getOwnerCoinAssets(t,this.buileCetusCoinType())}mintVeNFTPayload(){let{xcetus:t}=this.sdk.sdkOptions,e=new Fn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${cr}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xcetus_manager_id)]}),e}async convertPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock,i=this.buileCetusCoinType(),r=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${cr}::mint_and_convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xcetus_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${cr}::convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xcetus_manager_id),r,n.pure(t.amount),n.pure(t.venft_id)]}),n}redeemLockPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(G)]}),n}redeemPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::redeem`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}redeemDividendPayload(t,e){let{xcetus:n,xcetus_dividends:i}=this.sdk.sdkOptions,r=new Fn.TransactionBlock;return e.forEach(o=>{r.moveCall({target:`${n.published_at}::${Cc}::redeem`,typeArguments:[o],arguments:[r.object(D(i).dividend_manager_id),r.object(t)]})}),r}redeemDividendV2Payload(t,e,n){let{xcetus_dividends:i}=this.sdk.sdkOptions,r=new Fn.TransactionBlock;return e.filter(s=>n.includes(s)).length>0&&(r=this.redeemDividendXTokenPayload(t,r)),e.forEach(s=>{n.includes(s)||r.moveCall({target:`${i.published_at}::${Cc}::redeem_v2`,typeArguments:[s],arguments:[r.object(D(i).dividend_manager_id),r.object(t),r.object(G)]})}),r}redeemDividendXTokenPayload(t,e){let{xcetus_dividends:n,xcetus:i}=this.sdk.sdkOptions,{xcetus_manager_id:r,lock_manager_id:o}=D(i),{dividend_manager_id:s}=D(n);return e=e===void 0?new Fn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${Cc}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(G)]}),e}buileCetusCoinType(){return`${this.sdk.sdkOptions.cetus_faucet.package_id}::cetus::CETUS`}buileXTokenCoinType(t=this._sdk.sdkOptions.xcetus.package_id,e="xcetus",n="XCETUS"){return`${t}::${e}::${n}`}cancelRedeemPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Fn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${cr}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}async getInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.xcetus,e=`${t}_getInitFactoryEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::xcetus::InitEvent`}))?.data,r={xcetus_manager_id:"",lock_manager_id:"",lock_handle_id:""};i.length>0&&i.forEach(s=>{let a=s.parsedJson;a&&(r.xcetus_manager_id=a.xcetus_manager)});let o=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::locking::InitializeEvent`}))?.data;return o.length>0&&o.forEach(s=>{let a=s.parsedJson;a&&(r.lock_manager_id=a.lock_manager)}),r.lock_manager_id.length>0&&(r.lock_handle_id=(await this.getLockUpManager(r.lock_manager_id)).lock_infos.lock_handle_id),this.updateCache(e,r,X),r}async getLockUpManager(t=D(this.sdk.sdkOptions.xcetus).lock_manager_id,e=!1){let n=`${t}_getLockUpManager`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Ii.buildLockUpManager(Q(r));return this.updateCache(n,o,X),o}async getDividendConfigs(){let{package_id:t}=this.sdk.sdkOptions.xcetus_dividends,e=`${t}_getDividendManagerEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::dividend::InitEvent`}))?.data,r={dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""};return i.length>0&&i.forEach(o=>{let s=o.parsedJson;s&&(r.dividend_manager_id=s.manager_id,r.dividend_admin_id=s.admin_id,r.dividend_settle_id=s.settle_id,this.updateCache(e,r,X))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=D(this._sdk.sdkOptions.xcetus_dividends),n=`${e}_getDividendManager`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s=Ii.buildDividendManager(o);return this.updateCache(n,s,X),s}async getXcetusManager(t=!0){let{xcetus_manager_id:e}=D(this._sdk.sdkOptions.xcetus),n=`${e}_getXcetusManager`,i=this.getCache(n,t);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s={id:o.id.id,index:Number(o.index),has_venft:{handle:o.has_venft.fields.id.id,size:o.has_venft.fields.size},nfts:{handle:o.nfts.fields.id.id,size:o.nfts.fields.size},total_locked:o.total_locked,treasury:o.treasury.fields.total_supply.fields.value};return this.updateCache(n,s),s}async getVeNFTDividendInfo(t,e){try{let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);return Ii.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(D(this._sdk.sdkOptions.xcetus).lock_manager_id),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(Ts)).div(sn);return{amountOut:S(r).mul(S(t)).round().toString(),percent:r.toString()}}async reverseRedeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(D(this._sdk.sdkOptions.xcetus).lock_manager_id),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(Ts)).div(sn);return{amountOut:S(t).div(r).toFixed(0,N.ROUND_UP),percent:r.toString()}}async getXCetusAmount(t){let{lock_handle_id:e}=D(this._sdk.sdkOptions.xcetus),n=`${t}_getXCetusAmount`,i=this.getCache(n);if(i!==void 0)return i;try{let r=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:e,name:{type:"0x2::object::ID",value:t}}),o=Q(r);if(o){let{xcetus_amount:s}=o.value.fields.value.fields;return this.updateCache(n,s,X),s}}catch{}return"0"}async getVeNftAmount(t,e){try{let n=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);if(i){let{lock_amount:r,xcetus_amount:o}=i.value.fields.value.fields;return{lock_amount:r,xcetus_amount:o}}}catch{}return{lock_amount:"0",xcetus_amount:"0"}}async getPhaseDividendInfo(t,e=!1){let i=(await this.getDividendManager()).dividends.id,r=`${i}_${t}_getPhaseDividendInfo`,o=this._sdk.getCache(r,e);if(o)return o;try{let s=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:i,name:{type:"u64",value:t}}),a=Q(s),u=a.value.fields.value.fields,l=u.redeemed_num.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),h=u.bonus_types.map(T=>T.fields.name),w=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:Lt(s),phase:a.name,settled_num:u.settled_num,register_time:u.register_time,redeemed_num:l,is_settled:u.is_settled,bonus_types:h,bonus:w,phase_end_time:""};return this.updateCache(r,v),v}catch{}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},oy="factory",on="oversubscribe_pool",gf=1e6,lr=1e18;var ur="router",Sc="router",ys="router";var ff={curve:{strategy:3,both_side:{div_width:10,ratios:[.333333,.266666,.2,.133333,.066666]},one_side:{div_width:5,ratios:[.333333,.266666,.2,.133333,.066666]}},bidAsk:{strategy:4,both_side:{div_width:10,ratios:[.172413793,.137931034,.103448276,.068965517,.034482759,.068965517,.103448276,.137931034,.172413793]},one_side:{div_width:5,ratios:[.066666667,.13333333,.2,.266666667,.333333333]}}};function sy(t){return"master_address"in t}var ay="router",cy="vaults",uy=1e4;var $t=class{static buildIdoPoolImmutables(t){return{pool_address:(0,xc.normalizeSuiObjectId)(t.pool_id),coin_type_sale:q(t.sale_coin_type.name).full_address,coin_type_raise:q(t.raise_coin_type.name).full_address,tick_spacing:Number(t.tick_spacing),total_supply:t.total_supply,min_purchase:t.min_purchase_amount,max_purchase:t.max_purchase_amount}}static buildIdoPool(t){let e=Mt(t),n=q(e),i=Q(t);console.log("fields:",i);let r={pool_address:(0,xc.normalizeSuiObjectId)(i.id.id),coin_type_sale:n.type_arguments[0],coin_type_raise:n.type_arguments[1],tick_spacing:Number(i.tick_spacing),total_supply:i.total_supply,min_purchase:i.min_purchase_amount,max_purchase:i.max_purchase_amount},o={start_time:Number(i.duration_manager.fields.start_time),lock_up_duration:Number(i.duration_manager.fields.lock_up_duration),purchase_duration:Number(i.duration_manager.fields.purchase_duration),end_time:0};o.end_time=o.start_time+o.purchase_duration;let s={complete_raise_limit:i.complete_raise_limit,liquidity_injection_ratio:S(i.liquidity_injection_ratio).div(gf).toNumber(),current_sqrt_price_min:i.current_sqrt_price_min,current_sqrt_price_max:i.current_sqrt_price_max,owner:i.owner,sale_coin_amount:i.sale_coin,raise_coin_amount:i.raise_coin,price:i.price,current_price:i.price,duration_summary:o,is_cancelled:i.is_cancelled,is_liquidity_injected:i.is_liquidity_injected,liquidity_used_raise_amount:i.liquidity_used_raise_amount,liquidity_used_sale_amount:i.liquidity_used_sale_amount,purchase_summary:{size:Number(i.purchase_manager.fields.purchases.fields.size),purchase_handle:i.purchase_manager.fields.purchases.fields.id.id},total_purchase_amount:i.total_purchase_amount,white_summary:{white_list_id:i.white_list.fields.id.id,protection_limit_used:i.white_list.fields.protection_limit_used,protection_hard_cap:i.white_list.fields.protection_hard_cap,white_handle:i.white_list.fields.addresses.fields.id.id,size:Number(i.white_list.fields.addresses.fields.size)},pool_status:"Upcoming",max_raise_amount:"",sale_decimals:0,raise_decimals:0,is_withdrawn:i.is_withdrawn};return $t.updatePoolStatus(s),{...r,...s}}static is_init_period(t){return Number(S(Date.now()/1e3).toFixed(0))<t.start_time}static is_purchase_period(t){let e=Number(S(Date.now()/1e3).toFixed(0));return e>=t.start_time&&e<=t.start_time+t.purchase_duration}static is_claim_period(t){let e=Number(S(Date.now()/1e3).toFixed(0)),n=t.start_time+t.purchase_duration;return e>n}static is_can_inject_liquidity(t){return!t.is_cancelled&&t.liquidity_injection_ratio!==0&&$t.is_claim_period(t.duration_summary)&&!t.is_liquidity_injected}static is_can_withdraw(t){return t.is_withdrawn?!1:$t.is_sale_failed(t)?!0:(t.liquidity_injection_ratio===0||t.is_liquidity_injected)&&$t.is_claim_period(t.duration_summary)}static is_sale_failed(t){return!!(t.is_cancelled||$t.is_claim_period(t.duration_summary)&&S(t.total_purchase_amount).lessThan(t.complete_raise_limit))}static buildPurchaseInfo(t){return{...t.value.fields.value.fields,owner:t.name}}static calculateRedeemAmount(t,e){let n,i;if($t.is_sale_failed(t))n="0",i="0";else if(e.is_redeemed)n=e.obtained_sale_amount,i=e.used_raise_amount;else if(S(t.total_purchase_amount).lessThanOrEqualTo(t.max_raise_amount))n=S(e.purchased_raise_amount).mul(lr).div(t.price).toString(),i=e.purchased_raise_amount;else{let o=$t.redeemForSaleOversubcribeV2(t,e);n=o.user_obtained_sale_amount,i=o.user_used_raise_amount_ceil}n=N.floor(n);let r=N.floor(S(e.purchased_raise_amount).sub(i).toString());return{obtained_sale_amount:n,refunded_raise_amount:r}}static calculateWithdrawAmount(t){let e,n,i=S(t.total_supply).mul(t.liquidity_injection_ratio);if($t.is_sale_failed(t))e="0",n=S(i).add(t.total_supply);else{let{max_raise_amount:r}=t;S(t.total_purchase_amount).greaterThanOrEqualTo(r)?(e=S(r).sub(t.liquidity_used_raise_amount).toString(),n="0"):(e=S(t.total_purchase_amount).sub(t.liquidity_used_raise_amount),n=S(t.total_supply).add(i).sub(t.liquidity_used_sale_amount).sub($t.get_sold_amount(t)))}return{obtained_raise_amount:N.floor(e).toString(),refunded_sale_amount:N.ceil(n).toString()}}static get_sold_amount(t){return S(t.total_purchase_amount).greaterThanOrEqualTo(t.max_raise_amount)?t.total_supply:S(t.total_purchase_amount).mul(lr).div(t.price)}static redeemForSaleOversubcribe(t,e){let n=e.protection_raise_amount,i=S(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=S(r).sub(o),a=S(t.total_purchase_amount).sub(o),u=N.ceil(i.mul(s).div(a).add(n)),l=N.floor(i.mul(s).div(a).add(n));return{user_obtained_sale_amount:N.floor(S(t.total_supply).mul(l).div(r)),user_used_raise_amount_ceil:u}}static redeemForSaleOversubcribeV2(t,e){let n=e.protection_raise_amount,i=S(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=S(r).sub(o),a=S(t.total_purchase_amount).sub(o),u=S(n).mul(a).add(S(i).mul(s)).mul(lr).div(S(a).mul(t.price)),l=N.ceil(u.mul(t.price).div(lr));return{user_obtained_sale_amount:u,user_used_raise_amount_ceil:l}}static raiseTotalAmount(t){let e=S(t.sale_decimals-t.raise_decimals).abs().toNumber();return t.sale_decimals>t.raise_decimals?S(t.total_supply).mul(t.current_price).div(S(10).pow(S(e))).toString():S(t.total_supply).mul(t.current_price).mul(S(10).pow(S(e))).toString()}static updatePoolStatus(t){let e=Number(S(Date.now()/1e3).toFixed(0)),n=t.duration_summary,i=n.start_time+n.purchase_duration;t.is_cancelled?t.pool_status="Canceled":e<n.start_time?t.pool_status="Upcoming":e>n.start_time&&e<i?t.pool_status="Live":S(t.total_purchase_amount).lessThan(t.complete_raise_limit)?t.pool_status="Failed":t.pool_status="Ended"}static async calculatePoolUiPrice(t,e){let n=await t.ClmmSDK.CetusConfig.getTokenListByCoinTypes([e.coin_type_sale,e.coin_type_raise]),i=n[e.coin_type_sale].decimals,r=n[e.coin_type_raise].decimals;e.current_price=An.priceFixToReal(Number(S(e.price).div(S(lr)).toString()),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r,e.max_raise_amount=this.raiseTotalAmount(e)}};var Oi=class{static buildVeNFTDividendInfo(t){let e={id:t.id.id,ve_nft_id:t.name,rewards:[]};return t.value.fields.value.fields.dividends.fields.contents.forEach(n=>{let i=[];n.fields.value.fields.contents.forEach(r=>{i.push({coin_type:q(r.fields.key.fields.name).source_address,amount:r.fields.value})}),e.rewards.push({period:Number(n.fields.key),rewards:i})}),e}static buildDividendManager(t){let e={id:t.id.id,dividends:{id:t.dividends.fields.id.id,size:t.dividends.fields.size},venft_dividends:{id:t.venft_dividends.fields.id.id,size:t.venft_dividends.fields.size},bonus_types:[],start_time:Number(t.start_time),interval_day:Number(t.interval_day),balances:{id:t.balances.fields.id.id,size:t.balances.fields.size},is_open:t.is_open};return t.bonus_types.forEach(n=>{e.bonus_types.push(q(n.fields.name).source_address)}),e}static buildLockUpManager(t){return{id:t.id.id,balance:t.balance,treasury_manager:t.treasury_manager,extra_treasury:t.extra_treasury,lock_infos:{lock_handle_id:t.lock_infos.fields.id.id,size:Number(t.lock_infos.fields.size)},type_name:Et(t.type_name.fields.name),min_lock_day:Number(t.min_lock_day),max_lock_day:Number(t.max_lock_day),package_version:Number(t.package_version),max_percent_numerator:Number(t.max_percent_numerator),min_percent_numerator:Number(t.min_percent_numerator)}}static buildLockToken(t){let e=t.fields,n={id:e.id.id,type:q(t.type).source_address,locked_start_time:Number(e.locked_start_time),locked_until_time:Number(e.locked_until_time),token_amount:e.balance,xtoken_amount:"0",lock_day:0};return n.lock_day=(n.locked_until_time-n.locked_start_time)/zr,n}static getAvailableXToken(t,e){let n=S(0);return e.forEach(i=>{n=n.add(i.xtoken_amount)}),S(t.xtoken_balance).sub(n).toString()}static getWaitUnLockTokens(t){return t.filter(e=>!Oi.isLocked(e))}static getLockingTokens(t){return t.filter(e=>Oi.isLocked(e))}static buildDividendRewardTypeList(t){let e=new Set;return t.forEach(n=>{n.rewards.forEach(i=>{e.add(i.coin_type)})}),Array.from(e)}static isLocked(t){return t.locked_until_time>Date.parse(new Date().toString())/1e3}static getNextStartTime(t,e=zr){let n=Date.now()/1e3,{start_time:i,interval_day:r}=t,o=Math.ceil((n-i)/(r*e));return i+o*r*e}},qn=class{static getDefaultStrategyConfig(t){let e;switch(t){case 4:e=ff.bidAsk;break;default:e=ff.curve;break}return e}static geTickIndexRange(t,e,n,i){let r,o;switch(t=ee.getInitializableTickIndex(t,e),i){case"left":t>0?(o=S(t).sub(e).toNumber(),r=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber()):(o=S(t).sub(e).toNumber(),r=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber());break;case"right":t>0?(o=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber(),r=S(t).add(e).toNumber()):(o=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber(),r=S(t).add(e).toNumber());break;default:t>0?(r=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber(),o=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber()):(r=S(t).mul(S(1).add(n)).toDecimalPlaces(0).toNumber(),o=S(t).mul(S(1).sub(n)).toDecimalPlaces(0).toNumber());break}if(r=ee.getInitializableTickIndex(r,e),o=ee.getInitializableTickIndex(o,e),r<Hd)throw Error("Tick lower value is below the minimum allowed value.");if(o>Wd)throw Error("Tick upper value is above the maximum allowed value.");return{tick_lower:r,tick_upper:o}}static getCreateLiquidityBins(t,e){let n=[];switch(e){case 4:n=qn.getCreateBidAskLiquidityBins(t);break;default:n=qn.getCreateCurveLiquidityBins(t);break}return n}static getCreateBidAskLiquidityBins(t){let e=S(Math.floor(S(t.tick_upper).sub(t.tick_lower).div(t.div_width).toNumber())).abs(),n=[],i=t.ratios,r,o;for(let s=0;s<i.length;s++){let a,u;t.tick_upper<=t.curr_tick?(u=S(t.tick_upper).sub(e.mul(s)).toNumber(),a=S(u).sub(e).toNumber()):t.tick_lower>=t.curr_tick?(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(t.tick_lower).add(e.mul(s+1)).toNumber()):s===4?(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(a).add(e.mul(2)).toNumber()):s>4?(a=S(t.tick_lower).add(e.mul(s+1)).toNumber(),u=S(a).add(e).toNumber()):(a=S(t.tick_lower).add(e.mul(s)).toNumber(),u=S(a).add(e).toNumber()),r=ee.getInitializableTickIndex(a,t.tick_spacing),o=ee.getInitializableTickIndex(u,t.tick_spacing),n.push({tick_lower:r,tick_upper:o,ratio:i[s],liquidity:"0"})}return n}static getCreateCurveLiquidityBins(t){let e=S(Math.floor(S(t.tick_upper).sub(t.tick_lower).div(t.div_width).toNumber())).abs(),n=[],i=t.ratios;for(let r=0;r<i.length;r++){let o,s;t.tick_upper<=t.curr_tick?(s=t.tick_upper,o=S(t.tick_upper).sub(e.mul(r+1)).toNumber()):t.tick_lower>=t.curr_tick?(o=t.tick_lower,s=S(o).add(e.mul(r+1)).toNumber()):(o=S(t.curr_tick).sub(e.mul(r+1)).toNumber(),s=S(t.curr_tick).add(e.mul(r+1)).toNumber()),n.push({tick_lower:ee.getInitializableTickIndex(o,t.tick_spacing),tick_upper:ee.getInitializableTickIndex(s,t.tick_spacing),ratio:i[r],liquidity:"0"})}return n}static calculateAddLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick)),n=qn.calculateCoinRatios(t.curr_tick,t.liquidity_bins),i=t.liquidity_bins.map((r,o)=>{let s=n[o],a=S(t.coin_amount).mul(t.fix_amount_a?s.coinRatioA:s.coinRatioB).toFixed(0).toString();try{return{...$e.estLiquidityAndcoinAmountFromOneAmounts(r.tick_lower,r.tick_upper,new qe.default(a),t.fix_amount_a,!0,t.slippage,e),...r}}catch{return{coinAmountA:new qe.default(0),coinAmountB:new qe.default(0),tokenMaxA:new qe.default(0),tokenMaxB:new qe.default(0),liquidityAmount:new qe.default(0),fix_amount_a:!t.fix_amount_a,...r}}});return qn.fixLiquidityInputs(e,t.slippage,i,!0)}static fixLiquidityInputs(t,e,n,i){let r=n.filter(s=>s.liquidityAmount.gt(ie));if(r.length===0)return[];let o=r[0];return n.map(s=>{if(s.liquidityAmount.eq(ie)){let a=S(o.liquidityAmount.toString()).mul(s.ratio).div(o.ratio).toFixed(0),u=ee.tickIndexToSqrtPriceX64(s.tick_lower),l=ee.tickIndexToSqrtPriceX64(s.tick_upper),h=$e.getCoinAmountFromLiquidity(new qe.default(a.toString()),t,u,l,!1);return{coinAmountA:h.coinA,coinAmountB:h.coinB,liquidityAmount:new qe.default(a.toString()),fix_amount_a:s.fix_amount_a,..._s(h,or.fromDecimal(S(e).mul(100)),i)}}return s})}static calculateCoinRatios(t,e){let n=new qe.default(ee.tickIndexToSqrtPriceX64(t)),i=[],r=S(0),o=S(0),s=e.map(l=>{let h=S(nf(100,6).toString()).mul(l.ratio).toFixed(0).toString(),w=ee.tickIndexToSqrtPriceX64(l.tick_lower),v=ee.tickIndexToSqrtPriceX64(l.tick_upper),T=$e.getCoinAmountFromLiquidity(new qe.default(h),n,w,v,!0);return r=r.add(T.coinA.toString()),o=o.add(T.coinB.toString()),{...T,liquidity:h}}),a=[],u=[];return s.forEach((l,h)=>{let w={coinRatioA:r.eq(S(0))?0:S(l.coinA.toString()).div(r).toNumber(),coinRatioB:o.eq(S(0))?0:S(l.coinB.toString()).div(o).toNumber(),liquiditys:l.liquidity,tick_lower:e[h].tick_lower,tick_upper:e[h].tick_upper};i.push(w),a.push(r.eq(S(0))?0:S(l.coinA.toString()).div(r).toNumber()),u.push(o.eq(S(0))?0:S(l.coinB.toString()).div(o).toNumber())}),i}static calculateCloseMasterLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick));return t.positions.map(i=>{let r=new qe.default(i.liquidity),o=ee.tickIndexToSqrtPriceX64(i.tick_lower_index),s=ee.tickIndexToSqrtPriceX64(i.tick_upper_index),a=$e.getCoinAmountFromLiquidity(r,e,o,s,!1),u=or.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:l,tokenMaxB:h}=_s(a,u,!1);return{coinAmountA:a.coinA,coinAmountB:a.coinB,tokenMaxA:l,tokenMaxB:h,liquidityAmount:r,fix_amount_a:!1}})}static calculateRemoveMasterLiquidityInputs(t){let e=new qe.default(ee.tickIndexToSqrtPriceX64(t.curr_tick)),{fix_token:n}=t;if(n){let r=t.positions.map((a,u)=>({tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,ratio:t.ratios[u]})),o=qn.calculateCoinRatios(t.curr_tick,r),s=t.positions.map((a,u)=>{let l=o[u],h=S(n.coin_amount).mul(n.fix_amount_a?l.coinRatioA:l.coinRatioB).toFixed(0).toString();try{let w=$e.estLiquidityAndcoinAmountFromOneAmounts(a.tick_lower_index,a.tick_upper_index,new qe.default(h),n.fix_amount_a,!1,t.slippage,e);return{...w,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:w.liquidityAmount.toString(),ratio:t.ratios[u]}}catch{return{coinAmountA:new qe.default(0),coinAmountB:new qe.default(0),tokenMaxA:new qe.default(0),tokenMaxB:new qe.default(0),liquidityAmount:new qe.default(0),fix_amount_a:!n.fix_amount_a,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:"0",ratio:t.ratios[u]}}});return qn.fixLiquidityInputs(e,t.slippage,s,!1)}return t.positions.map((r,o)=>{let s=t.ratios[o],a=S(t.liquidity).mul(s).toFixed(0);S(a).greaterThan(r.liquidity)&&(a=r.liquidity);let u=ee.tickIndexToSqrtPriceX64(r.tick_lower_index),l=ee.tickIndexToSqrtPriceX64(r.tick_upper_index),h=$e.getCoinAmountFromLiquidity(new qe.default(a),e,u,l,!1),w=or.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:v,tokenMaxB:T}=_s(h,w,!1);return{coinAmountA:h.coinA,coinAmountB:h.coinB,tokenMaxA:v,tokenMaxB:T,liquidityAmount:new qe.default(a),fix_amount_a:!1}})}static buildMasterPosition(t){return{coin_type_a:q(t.coin_type_a.fields.name).full_address,coin_type_b:q(t.coin_type_b.fields.name).full_address,description:t.description,id:t.id.id,index:t.index,liquidity:t.liquidity,name:t.name,pool:t.pool,tick_lower_index:Re(BigInt(t.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(t.tick_upper_index.fields.bits)),url:t.url}}static buildMasterNFT(t){let e=Q(t);if(e){let n={id:e.id.id,pool_id:e.pool_id,index:Number(e.index),strategy:Number(e.strategy),tick_lower_index:Re(BigInt(e.tick_lower_index)),tick_upper_index:Re(BigInt(e.tick_upper_index)),positions:[],...Si(t)};return n.positions=e.positions.map(i=>qn.buildMasterPosition(i.fields)),n}}},Sn=class{static generateNextTickRange(t,e,n){let i=t-e/2,r=t+e/2;return{new_tick_lower:Sn.getValidTickIndex(i,n),new_tick_upper:Sn.getValidTickIndex(r,n)}}static calculateDepositRatio(t,e,n){let i=ee.sqrtPriceX64ToTickIndex(n);if(i<t)return{ratioA:new N(1),ratioB:new N(0)};if(i>e)return{ratioA:new N(0),ratioB:new N(1)};let r=new _f.default(1e8),{coinAmountB:o}=$e.estLiquidityAndcoinAmountFromOneAmounts(t,e,r,!0,!0,0,n),s=ee.sqrtPriceX64ToPrice(n,0,0),a=S(r.toString()).mul(s),u=a.add(o.toString()),l=a.div(u),h=S(o.toString()).div(u);return{ratioA:l,ratioB:h}}static getValidTickIndex(t,e){if(t%e===0)return t;let n;if(t>0?n=t-t%e+e:t<0?n=t+Math.abs(t)%e-e:n=t,n%e!==0)throw new Error("Assertion failed: res % tickSpacing == 0");if(Math.abs(n)<Math.abs(t))throw new Error("Assertion failed: res.abs() >= tickIndex");return n}static get_lp_amount_by_liquidity(t,e){return t.total_supply==="0"?"0":S(t.total_supply).mul(e).div(t.liquidity).toFixed(0,N.ROUND_DOWN).toString()}static get_share_liquidity_by_amount(t,e){return t.total_supply==="0"?"0":S(e).mul(t.liquidity).div(t.total_supply).toFixed(0,N.ROUND_DOWN).toString()}static get_protocol_fee_amount(t,e){return S(e).mul(t.protocol_fee_rate).div(uy).toFixed(0,N.ROUND_CEIL)}static buildFramsPositionNFT(t){let e=t.clmm_postion.fields;return{id:t.id.id,url:e.url,pool_id:t.pool_id,coinTypeA:q(e.coin_type_a.fields.name).full_address,coinTypeB:q(e.coin_type_b.fields.name).full_address,description:e.description,name:e.name,liquidity:e.liquidity,clmm_position_id:e.id.id,clmm_pool_id:e.pool,tick_lower_index:Re(BigInt(e.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(e.tick_upper_index.fields.bits)),rewards:[]}}static buildPool(t){let e=Q(t),n=pn(t),{positions:i}=e;if(e&&i.length>0){let r=Sn.buildFramsPositionNFT(i[0].fields);return{id:e.id.id,pool_id:e.pool,protocol_fee_rate:e.protocol_fee_rate,is_pause:e.is_pause,harvest_assets:{harvest_assets_handle:e.harvest_assets.fields.id.id,size:Number(e.harvest_assets.fields.size)},lp_token_type:q(n).type_arguments[0],total_supply:e.lp_token_treasury.fields.total_supply.fields.value,liquidity:e.liquidity,max_quota:e.max_quota,status:e.status===1?"STATUS_RUNNING":"STATUS_REBALANCING",quota_based_type:e.quota_based_type.fields.name,position:r}}}},ws=class{static calculatePositionShare(t,e,n,i,r,o,s){if(e<=r||t>=o)return"0";let a=0;t<r?a=r:a=t;let u=0;e<o?u=e:u=o;let l=ee.tickIndexToSqrtPriceX64(a),h=ee.tickIndexToSqrtPriceX64(u),{coinA:w,coinB:v}=$e.getCoinAmountFromLiquidity(new Ic.default(n),new Ic.default(s),l,h,!0);return S(w.toString()).mul(i).div(1e12).add(v.toString()).toString()}static buildFramsPool(t){let e=Q(t);if(e)try{let n=[];return e.rewarders.forEach(r=>{n.push({reward_coin:q(r.fields.name).full_address,last_reward_time:"",emission_per_second:"",total_allocate_point:"",allocate_point:""})}),{id:e.id.id,clmm_pool_id:e.clmm_pool_id,effective_tick_lower:Re(BigInt(e.effective_tick_lower.fields.bits)),effective_tick_upper:Re(BigInt(e.effective_tick_upper.fields.bits)),total_share:e.total_share,rewarders:n,positions:{positions_handle:e.positions.fields.id.id,size:e.positions.fields.size},sqrt_price:e.sqrt_price}}catch(n){console.log(n)}}static buildFramsPositionNFT(t){let e=Q(t);if(e){let n=e.clmm_postion.fields;return{id:e.id.id,url:n.url,pool_id:e.pool_id,coinTypeA:q(n.coin_type_a.fields.name).full_address,coinTypeB:q(n.coin_type_b.fields.name).full_address,description:n.description,name:n.name,liquidity:n.liquidity,clmm_position_id:n.id.id,clmm_pool_id:n.pool,tick_lower_index:Re(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:Re(BigInt(n.tick_upper_index.fields.bits)),rewards:[]}}}},dy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPoolImmutables(t="all",e=!1){let{package_id:n}=this._sdk.sdkOptions.ido,i=`${n}_getPoolImmutables`,r=this.getCache(i,e),o={data:[],hasNextPage:!1},s=[];if(r!==void 0&&s.push(...r),s.length===0)try{let a=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${n}::oversubscribe_pool::CreatePoolEvent`},t);a.data.forEach(u=>{let l=u.parsedJson;if(l){let h=$t.buildIdoPoolImmutables(l);s.push(h)}}),o.hasNextPage=a.hasNextPage,o.nextCursor=a.nextCursor,this.updateCache(i,s,X)}catch(a){console.log("getPoolImmutables",a)}return o.data=s,o}async getPools(t=[],e=!1){let n=[],i=[];t.length>0?i=[...t]:(await this.getPoolImmutables("all",e)).data.forEach(s=>{i.push(s.pool_address)});let r=await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showType:!0,showContent:!0});for(let o of r){let s=$t.buildIdoPool(o);await $t.calculatePoolUiPrice(this._sdk,s),n.push(s);let a=`${s.pool_address}_getPoolObject`;this.updateCache(a,s,X)}return n}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=$t.buildIdoPool(r);return await $t.calculatePoolUiPrice(this._sdk,o),this.updateCache(n,o),o}async getIdoConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.ido,n=`${e}_getInitEvent`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=Ci(r),s=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({Transaction:o}))?.data,a={pools_id:"",admin_cap_id:"",package_version_id:""};return s.length>0&&(s.forEach(u=>{console.log("item: ",u);let l=u.parsedJson;if(l)switch(q(u.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=l.admin_cap_id,a.package_version_id=l.package_version_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=l.pools_id;break;default:break}}),this.updateCache(n,a,X)),a}async getPurchaseInfo(t,e,n=!0){let i=`${t}_${e}_getPurchaseInfo`,r=this.getCache(i,n);if(r)return r;try{let o=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"address",value:e}}),s=$t.buildPurchaseInfo(Q(o));return this.updateCache(i,s,Ue),s}catch{return}}async getLockNFT(t,e=!1){let n=`${t}_getLockNFT`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(!r.error)return Nn(r)}async getLockNFTList(t){let{clmm_pool:e}=this._sdk.ClmmSDK.sdkOptions,{ido:n}=this._sdk.sdkOptions,i=[];try{let r=(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{filter:{StructType:`${n.package_id}::lock::LockedNFT<${e.package_id}::position::Position>`},options:{showContent:!0}}))?.data;for(let o of r){let s=Q(o);if(s){let a=s.nft.fields,u={locked_at:Number(s.locked_at),lock_duration:Number(s.lock_duration),lock_nft_id:s.id.id,type:s.nft.type,...a};u.end_lock_time=u.locked_at+u.lock_duration,u.coin_type_a=q(a.coin_type_a.fields.name).full_address,u.coin_type_b=q(a.coin_type_b.fields.name).full_address,u.id=a.id.id,u.tick_lower_index=Re(BigInt(a.tick_lower_index.fields.bits)),u.tick_upper_index=Re(BigInt(a.tick_upper_index.fields.bits)),i.push(u)}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPool(t){let{ido:e}=this.sdk.sdkOptions;ls((0,xn.normalizeSuiAddress)(t.coin_type_sale),(0,xn.normalizeSuiAddress)(t.coin_type_raise))&&(t.price_min=S(1).div(t.price_max).toNumber(),t.price_max=S(1).div(t.price_min).toNumber());let i=An.priceRealToFix(Number(t.price),t.sale_decimals,t.raise_decimals),r=ee.priceToSqrtPriceX64(S(t.price_min),t.sale_decimals,t.raise_decimals).toString(),o=ee.priceToSqrtPriceX64(S(t.price_max),t.sale_decimals,t.raise_decimals).toString(),s=new Xt.TransactionBlock,a=S(t.total_supply).add(S(t.total_supply).mul(S(t.liquidity_injection_ratio))).toNumber(),u=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.coin_type_sale),l=re.buildCoinForAmount(s,u,BigInt(a),t.coin_type_sale,!1),h=[s.pure(D(e).admin_cap_id),s.pure(D(e).package_version_id),s.pure(D(e).pools_id),s.pure((0,xn.normalizeSuiAddress)(t.owner)),s.pure(S(i).mul(lr).toString()),s.pure(t.total_supply),s.pure(t.complete_raise_limit),s.pure(t.min_purchase_amount),s.pure(t.max_purchase_amount),s.pure(t.start_time),s.pure(t.purchase_duration),s.pure(t.lock_up_duration),s.pure((t.liquidity_injection_ratio*gf).toString()),s.pure(r),s.pure(o),s.pure(t.tick_spacing.toString()),l.targetCoin,s.pure(t.protection_hard_cap.toString()),s.pure(G)],w=[t.coin_type_sale,t.coin_type_raise];return s.moveCall({target:`${e.published_at}::${oy}::create_oversubscribe_pool`,typeArguments:w,arguments:h}),s}async creatPurchasePayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=await this.getPurchaseInfo(t.purchase_handle,this._sdk.ClmmSDK.senderAddress,!1),r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.coin_type_raise),o=re.buildCoinForAmount(n,r,BigInt(t.raise_amount),t.coin_type_raise,!1),s=[t.coin_type_sale,t.coin_type_raise],a,u;return i?(u="purchase",a=[n.object(D(e).package_version_id),n.object(t.pool_address),n.object(i.purchase_certificate_id),n.pure(t.raise_amount.toString()),o.targetCoin,n.pure(G)]):(u="create_certificate_and_purchase",a=[n.object(D(e).package_version_id),n.object(t.pool_address),n.pure(t.raise_amount.toString()),o.targetCoin,n.pure(G)]),n.moveCall({target:`${e.published_at}::${on}::${u}`,typeArguments:s,arguments:a}),n}async redeemPayload(t){let{ido:e}=this.sdk.sdkOptions,n=await this.getPurchaseInfo(t.purchase_handle,this._sdk.ClmmSDK.senderAddress,!1);if(n===void 0)throw Error("get purchase certificate fail");let i=new Xt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure(D(e).package_version_id),i.pure(t.pool_address),i.pure(n.purchase_certificate_id),i.pure(G)];return i.moveCall({target:`${e.published_at}::${on}::redeem`,typeArguments:r,arguments:o}),i}injectLiquidityPayload(t){let{ido:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new Xt.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=t.is_reverse?"inject_liquidity_with_reverse_clmm_pool":"inject_liquidity_with_forward_clmm_pool",s=[i.pure(D(e).package_version_id),i.pure(t.pool_address),i.pure(D(n).global_config_id),i.pure(t.clmm_pool_address),i.pure(G)];return i.moveCall({target:`${e.published_at}::${on}::${o}`,typeArguments:r,arguments:s}),i}unPauseInjectLiquidity(t){let{ido:e}=this.sdk.sdkOptions,{integrate:n,clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions,r=new Xt.TransactionBlock;r.moveCall({target:`${n.published_at}::${nr}::unpause_pool`,typeArguments:[t.coin_type_a,t.coin_type_b],arguments:[r.object(D(i).global_config_id),r.object(t.clmm_pool_address)]});let o=[t.coin_type_sale,t.coin_type_raise],s=t.is_reverse?"inject_liquidity_with_reverse_clmm_pool":"inject_liquidity_with_forward_clmm_pool",a=[r.object(D(e).package_version_id),r.object(t.pool_address),r.object(D(i).global_config_id),r.object(t.clmm_pool_address),r.object(G)];return r.moveCall({target:`${e.published_at}::${on}::${s}`,typeArguments:o,arguments:a}),r}async findClmmPoolForLiquidity(t){let e=null,n=!1,i=await this.sdk.ClmmSDK.Pool.getPoolImmutables();for(let r of i){if(r.coinTypeA===t.coin_type_sale&&r.coinTypeB===t.coin_type_raise&&Number(r.tickSpacing)===t.tick_spacing){e=await this._sdk.ClmmSDK.Pool.getPool(r.poolAddress);break}if(r.coinTypeA===t.coin_type_raise&&r.coinTypeB===t.coin_type_sale&&Number(r.tickSpacing)===t.tick_spacing){e=await this._sdk.ClmmSDK.Pool.getPool(r.poolAddress),n=!0;break}}return e&&(S(e.current_sqrt_price).lessThanOrEqualTo(t.current_sqrt_price_min)||S(e.current_sqrt_price).greaterThanOrEqualTo(t.current_sqrt_price_max))?(console.log("clmmPool: ",e.poolAddress),{is_reverse:n,clmmPool:null}):{is_reverse:n,clmmPool:e}}withdrawPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object(D(e).package_version_id),n.object(t.pool_address),n.object(G)];return n.moveCall({target:`${e.published_at}::${on}::withdraw`,typeArguments:i,arguments:r}),n}updateWhitelistCapPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.add_whites&&t.add_whites.addresses.length>0&&n.moveCall({target:`${e.published_at}::${on}::add_white_listed_addresses`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.add_whites.addresses.map(r=>n.object((0,xn.normalizeSuiObjectId)(r)))}),n.pure(t.add_whites.protection_limit),n.object(G)]}),t.remove_whites&&t.remove_whites.length>0&&n.moveCall({target:`${e.published_at}::${on}::remove_white_listed_addresses`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.remove_whites.map(r=>n.object((0,xn.normalizeSuiObjectId)(r)))}),n.object(G)]}),t.update_whites&&t.update_whites.forEach(r=>{n.moveCall({target:`${e.published_at}::${on}::update_white_listed_address`,typeArguments:i,arguments:[n.object(D(e).admin_cap_id),n.object(D(e).package_version_id),n.object(t.pool_address),n.object(r.address),n.pure(r.protection_limit),n.object(G)]})}),n}creatCancelPoolPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure(D(e).admin_cap_id),n.pure(D(e).package_version_id),n.pure(t.pool_address),n.pure(G)];return n.moveCall({target:`${e.published_at}::${on}::cancel`,typeArguments:i,arguments:r}),n}updatePoolOwnerPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.object(t.new_owner),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_pool_owner`,typeArguments:i,arguments:r}),e}updatePoolDuractionPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.pure(t.start_time),e.pure(t.purchase_duration),e.pure(t.lock_duration),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_pool_duration`,typeArguments:i,arguments:r}),e}updateProtectionHardCapPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Xt.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object(D(n).admin_cap_id),e.object(D(n).package_version_id),e.object(t.pool_address),e.pure(t.protection_hard_cap),e.object(G)];return e.moveCall({target:`${n.published_at}::${on}::update_protection_hard_cap`,typeArguments:i,arguments:r}),e}unlockNftPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Xt.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft_id),n.pure(G)];return n.moveCall({target:`${e.published_at}::lock::unlock_nft`,typeArguments:i,arguments:r}),n}async isAdminCap(t){let{ido:e}=this._sdk.sdkOptions,n=`${e.package_id}_${t}_isAdminCap`,i=this.getCache(n);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:D(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=pn(r),s=sr(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,xn.normalizeSuiAddress)(s.AddressOwner)===(0,xn.normalizeSuiAddress)(t)),this.updateCache(n,a,X),a}async getWhiteProtectionLimit(t,e,n=!0){let i=`${t}_${e}_getWhiteProtectionLimit`,r=this._sdk.getCache(i,n);if(r)return r;try{let o=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"address",value:e}});if(o&&o.data){let s=Q(o);return this._sdk.updateCache(i,s.value),s.value}return}catch{return}}async getWhiteList(t,e){let n={type:"address",value:e};try{let i=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:n}),r=Q(i);if(console.log(r),r)return r?.value?.fields}catch{}return{safe_limit_amount:"0",safe_purchased_amount:"0"}}async getAdminAddress(){let{ido:t}=this._sdk.sdkOptions,e=`${D(t).admin_cap_id}_getAdminAddress`,n=this.getCache(e);if(n)return n;let i=await this._sdk.ClmmSDK.fullClient.getObject({id:D(t).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(i);let r=pn(i),o=sr(i);if(o&&r&&q(r).source_address===`${t.package_id}::config::AdminCap`){let a=(0,xn.normalizeSuiAddress)(o.AddressOwner);return this.updateCache(e,a,X),a}return""}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},fy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getOwnerVeNFT(t,e=!0){let{xtoken:n}=this.sdk.sdkOptions,i=`${t}_getLockUpManagerEvent`,r=this.getCache(i,e);if(r!==void 0)return r;let o,s=`${n.package_id}::xtoken::VeNFT`;return(await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0},filter:{StructType:s}})).data.forEach(u=>{let l=q(Mt(u)).source_address;if(l===s&&u.data&&u.data.content){let{fields:h}=u.data.content;o={...Si(u),id:h.id.id,index:h.index,type:l,xtoken_balance:h.xtoken_balance},this.updateCache(i,o,X)}}),o}async getOwnerLockTokens(t){let{xtoken:e}=this.sdk.sdkOptions,n=[],i=`${e.package_id}::lock_coin::LockedCoin<${this.buileTokenCoinType()}>`,r=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0},filter:{StructType:i}});for(let o of r.data)if(q(Mt(o)).source_address===i&&o.data){let a=Oi.buildLockToken(o.data.content),u=await this.getLockXToken(a.id);u&&(a.xtoken_amount=u.xtoken_amount),n.push(a)}return n}async getLockToken(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(e.data?.content){let n=Oi.buildLockToken(e.data.content),i=await this.getLockXToken(n.id);return i&&(n.xtoken_amount=i.xtoken_amount),n}}async getOwnerTokenCoins(t){return await this._sdk.ClmmSDK.getOwnerCoinAssets(t,this.buileTokenCoinType())}mintVeNFTPayload(){let{xtoken:t}=this.sdk.sdkOptions,e=new Rn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${ur}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xtoken_manager_id)]}),e}async convertPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock,i=this.buileTokenCoinType(),r=await re.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${ur}::mint_and_convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xtoken_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${ur}::convert`,typeArguments:[],arguments:[n.object(D(e).lock_manager_id),n.object(D(e).xtoken_manager_id),r,n.pure(t.amount),n.pure(t.venft_id)]}),n}redeemLockPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ur}::redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(G)]}),n}redeemPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ur}::redeem`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}redeemDividendPayload(t,e){let{xtoken_dividends:n}=this.sdk.sdkOptions,i=new Rn.TransactionBlock;return e.forEach(r=>{i.moveCall({target:`${n.published_at}::${Sc}::redeem`,typeArguments:[r],arguments:[i.object(D(n).dividend_manager_id),i.object(t)]})}),i}redeemDividendV2Payload(t,e,n){let{xtoken_dividends:i}=this.sdk.sdkOptions,r=new Rn.TransactionBlock;return e.filter(s=>n.includes(s)).length>0&&(r=this.redeemDividendXTokenPayload(t,r)),e.forEach(s=>{n.includes(s)||r.moveCall({target:`${i.published_at}::${Sc}::redeem_v2`,typeArguments:[s],arguments:[r.object(D(i).dividend_manager_id),r.object(t),r.object(G)]})}),r}redeemDividendXTokenPayload(t,e){let{xtoken_dividends:n,xtoken:i}=this.sdk.sdkOptions,{xtoken_manager_id:r,lock_manager_id:o}=D(i),{dividend_manager_id:s}=D(n);return e=e===void 0?new Rn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${Sc}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(G)]}),e}buileTokenCoinType(){return`${this.sdk.sdkOptions.token_faucet.package_id}::token::TOKEN`}buileXTokenCoinType(t=this._sdk.sdkOptions.xtoken.package_id,e="xtoken",n="XTOKEN"){return`${t}::${e}::${n}`}cancelRedeemPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Rn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ur}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure(D(e).lock_manager_id),n.pure(D(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(G)]}),n}async getInitConfigs(){let{package_id:t}=this.sdk.sdkOptions.xtoken,e=`${t}_getInitFactoryEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::xtoken::InitEvent`}))?.data,r={xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""};i.length>0&&i.forEach(s=>{let a=s.parsedJson;a&&(r.xtoken_manager_id=a.xtoken_manager)});let o=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::locking::InitializeEvent`}))?.data;return o.length>0&&o.forEach(s=>{let a=s.parsedJson;a&&(r.lock_manager_id=a.lock_manager)}),r.lock_handle_id=(await this.getLockUpManager(r.lock_manager_id)).lock_infos.lock_handle_id,this.updateCache(e,r,X),r}async getLockUpManager(t=D(this.sdk.sdkOptions.xtoken).lock_manager_id,e=!1){let n=`${t}_getLockUpManagerEvent`,i=this.getCache(n,e);if(i!==void 0)return i;let r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Oi.buildLockUpManager(Q(r));return this.updateCache(n,o,X),o}async getLockInfoHandle(t){let e=`${t}_getLockInfoHandle`,n=this.getCache(e);if(n!==void 0)return n;let i="",r=await this.sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),o=Q(r);return o&&(i=o.lock_infos.fields.id.id,this.updateCache(e,i,X)),i}async getDividendConfigs(){let{package_id:t}=this.sdk.sdkOptions.xtoken_dividends,e=`${t}_getDividendManagerEvent`,n=this.getCache(e);if(n!==void 0)return n;let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::dividend::InitEvent`}))?.data,r={dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""};return i.length>0&&i.forEach(o=>{let s=o.parsedJson;s&&(r.dividend_manager_id=s.manager_id,r.dividend_admin_id=s.admin_id,r.dividend_settle_id=s.settle_id,this.updateCache(e,r,X))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=D(this.sdk.sdkOptions.xtoken_dividends),n=`${e}_getDividendManager`,i=this.getCache(n,t);if(i!==void 0)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s=Oi.buildDividendManager(o);return this.updateCache(n,s,X),s}async getXcetusManager(t=!0){let{xtoken_manager_id:e}=D(this.sdk.sdkOptions.xtoken),n=`${e}_getXcetusManager`,i=this.getCache(n,t);if(i)return i;let r=await this._sdk.ClmmSDK.fullClient.getObject({id:e,options:{showContent:!0}}),o=Q(r),s={id:o.id.id,index:Number(o.index),has_venft:{handle:o.has_venft.fields.id.id,size:o.has_venft.fields.size},nfts:{handle:o.nfts.fields.id.id,size:o.nfts.fields.size},total_locked:o.total_locked,treasury:o.treasury.fields.total_supply.fields.value};return this.updateCache(n,s),s}async getVeNFTDividendInfo(t,e){try{let n=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);return Oi.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(Ts)).div(sn);return{amountOut:S(r).mul(S(t)).round().toString(),percent:r.toString()}}async reverseRedeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(),i=S(sn).mul(S(n.max_lock_day).sub(S(e))).mul(S(n.max_percent_numerator).sub(S(n.min_percent_numerator))).div(S(n.max_lock_day).sub(S(n.min_lock_day))),r=S(sn).mul(S(n.max_percent_numerator)).sub(i).div(S(Ts)).div(sn);return{amountOut:S(t).div(r).toFixed(0,N.ROUND_UP),percent:r.toString()}}async getLockXToken(t){let{lock_handle_id:e}=D(this._sdk.sdkOptions.xtoken),n=`${t}_getXTokenAmount`,i=this.getCache(n);if(i)return i;try{let r=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:e,name:{type:"0x2::object::ID",value:t}}),o=Q(r);if(o){let s=o.value.fields.value.fields;return this.updateCache(n,s,X),s}}catch{}}async getVeNftAmount(t,e){try{let n=await this.sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=Q(n);if(i){let{lock_amount:r,xtoken_amount:o}=i.value.fields.value.fields;return{lock_amount:r,xtoken_amount:o}}}catch{}return{lock_amount:"0",xtoken_amount:"0"}}async getPhaseDividendInfo(t,e=!1){let i=(await this.getDividendManager()).dividends.id,r=`${i}_${t}_getPhaseDividendInfo`,o=this._sdk.getCache(r,e);if(o)return o;try{let s=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:i,name:{type:"u64",value:t}}),a=Q(s),u=a.value.fields.value.fields,l=u.redeemed_num.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),h=u.bonus_types.map(T=>T.fields.name),w=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:Lt(s),phase:a.name,settled_num:u.settled_num,register_time:u.register_time,redeemed_num:l,is_settled:u.is_settled,bonus_types:h,bonus:w,phase_end_time:""};return this.updateCache(r,v),v}catch{}}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},hy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async addMasterLiquidity(t){let{liquidity_stratefy:e}=this._sdk.sdkOptions,{clmm_pool:n}=this._sdk.ClmmSDK.sdkOptions,i=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),r=S(0),o=S(0),s=[],a=[],u=[],l=[],h=[];t.liquidity_bins.forEach((x,P)=>{let O=t.amounts_a[P],E=t.amounts_b[P],B=t.bins_fix_amount_a[P];r=r.add(O),o=o.add(E),s.push(O),a.push(E),u.push(Tt(BigInt(x.tick_lower)).toString()),l.push(Tt(BigInt(x.tick_upper)).toString()),h.push(B)});let w=[t.coinTypeA,t.coinTypeB],v=new Ai.TransactionBlock,T=re.buildAddLiquidityFixTokenCoinInput(v,!t.fix_amount_a,r.toString(),t.slippage,t.coinTypeA,i,!1)?.targetCoin,I=re.buildAddLiquidityFixTokenCoinInput(v,t.fix_amount_a,o.toString(),t.slippage,t.coinTypeB,i,!1)?.targetCoin;return sy(t)?v.moveCall({target:`${e.published_at}::router::increase_liquidity`,typeArguments:w,arguments:[v.object(D(e).master_manger_id),v.object(t.master_address),v.object(D(n).global_config_id),v.object(t.pool_address),T,I,v.pure(s.map(x=>v.pure(x,"u64"))),v.pure(a.map(x=>v.pure(x,"u64"))),v.pure(h.map(x=>v.pure(x,"bool"))),v.object(G)]}):v.moveCall({target:`${e.published_at}::router::create_master_liquidity`,typeArguments:w,arguments:[v.object(D(e).master_manger_id),v.object(D(n).global_config_id),v.object(t.pool_address),T,I,v.pure(u.map(x=>v.pure(x,"u32"))),v.pure(l.map(x=>v.pure(x,"u32"))),v.pure(s.map(x=>v.pure(x,"u64"))),v.pure(a.map(x=>v.pure(x,"u64"))),v.pure(h.map(x=>v.pure(x,"bool"))),v.pure(t.strategy),v.pure(Tt(BigInt(t.tick_lower)).toString()),v.pure(Tt(BigInt(t.tick_upper)).toString()),v.object(G)]}),v}buildMasterNFTType(){return`${this._sdk.sdkOptions.liquidity_stratefy.package_id}::master_liquidity::MasterLiquidity`}async getMasterNFTList(t,e=[]){let n=[],i=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.liquidity_stratefy.package_id}}),r=e.length>0;for(let o of i.data)if(q(o.data.type).full_address===this.buildMasterNFTType()){let a=qn.buildMasterNFT(o);if(a){let u=`${a.id}_masterNFT`;this.updateCache(u,a,X),r?e.includes(a.pool_id)&&n.push(a):n.push(a)}}return n}async getMasterNFT(t,e=!1){let n="$masterId}_masterNFT",i=this.getCache(n,e);if(i)return i;try{let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});if(q(r.data.type).full_address===this.buildMasterNFTType()){let s=qn.buildMasterNFT(r);return s&&this.updateCache(n,s,X),s}}catch(r){console.log(r)}}async fetchMasterPositionInfos(t){let e={},{clmm_pool:n,integrate:i,simulationAccount:r}=this.sdk.ClmmSDK.sdkOptions,o=new Ai.TransactionBlock;return t.forEach(a=>{a.position_ids.forEach(u=>{let l=[a.coinTypeA,a.coinTypeB],h=[o.object(D(n).global_config_id),o.object(a.pool_id),o.object(u)];o.moveCall({target:`${i.published_at}::${zt}::fetch_position_fees`,arguments:h,typeArguments:l}),o.moveCall({target:`${i.published_at}::${zt}::fetch_position_rewards`,arguments:[...h,o.object(G)],typeArguments:l})})}),(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address})).events?.forEach(a=>{let{parsedJson:u}=a,{position_id:l}=u,h=e[l];switch(h===void 0&&(h={position_id:l,feeOwedA:"0",feeOwedB:"0",rewarders:[]},e[l]=h),q(a.type).name){case"FetchPositionFeesEvent":h.feeOwedA=u.fee_owned_a,h.feeOwedB=u.fee_owned_b;break;case"FetchPositionRewardsEvent":h.rewarders=u.data;break}}),e}async getLiquidityStrategyConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.liquidity_stratefy,n=`${e}_getLiquidityStrategyConfigst`,i=this.getCache(n,t);if(i!==void 0)return i;let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::master_liquidity::MasterLiquidityManagerCreatedEvent`})).data,o={master_manger_id:"",master_liquidity_handle:""};if(r.length>0){for(let s of r){let a=s.parsedJson;o.master_manger_id=a.id;let u=await this._sdk.ClmmSDK.fullClient.getObject({id:a.id,options:{showContent:!0}}),l=Q(u);o.master_liquidity_handle=l.position_maps.fields.id.id;break}this.updateCache(n,o,X)}return o}removeMasterLiquidity(t){let{clmm_pool:e}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:n}=this.sdk.sdkOptions,i=new Ai.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];this.collectReward({coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collect_fee:!1,rewarder_coin_types:t.rewarder_coin_types,master_address:t.master_address,pool_address:t.pool_address},i);let o=[i.object(D(n).master_manger_id),i.object(t.pool_address),i.object(t.master_address),i.object(D(e).global_config_id),i.pure(t.delta_liquidities.map(s=>i.pure(s,"u128"))),i.pure(t.min_amounts_a.map(s=>i.pure(s,"u64"))),i.pure(t.min_amounts_b.map(s=>i.pure(s,"u64"))),i.object(G)];return i.moveCall({target:`${n.published_at}::${ys}::remove_liquidity`,typeArguments:r,arguments:o}),i}closeMasterLiquidity(t){let{clmm_pool:e}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:n}=this.sdk.sdkOptions,i=new Ai.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];return this.collectReward({coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collect_fee:!1,rewarder_coin_types:t.rewarder_coin_types,master_address:t.master_address,pool_address:t.pool_address},i),i.moveCall({target:`${n.published_at}::${ys}::close_master_liquidity`,typeArguments:r,arguments:[i.object(D(n).master_manger_id),i.object(t.master_address),i.object(D(e).global_config_id),i.object(t.pool_address),i.pure(t.min_amounts_a.map(o=>i.pure(o,"u64"))),i.pure(t.min_amounts_b.map(o=>i.pure(o,"u64"))),i.object(G)]}),i}collectFee(t,e){let{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:i}=this.sdk.sdkOptions;e=e===void 0?new Ai.TransactionBlock:e;let r=[t.coinTypeA,t.coinTypeB],o=[e.object(D(i).master_manger_id),e.object(t.master_address),e.object(D(n).global_config_id),e.object(t.pool_address)];return e.moveCall({target:`${i.published_at}::${ys}::collect_fee`,typeArguments:r,arguments:o}),e}collectReward(t,e){let{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:i}=this.sdk.sdkOptions;return e=e===void 0?new Ai.TransactionBlock:e,t.collect_fee&&this.collectFee({...t},e),t.rewarder_coin_types.forEach(r=>{let o=[t.coinTypeA,t.coinTypeB,r];if(e){let s=[e.object(D(i).master_manger_id),e.object(t.master_address),e.object(D(n).global_config_id),e.object(t.pool_address),e.object(D(n).global_vault_id),e.object(G)];e.moveCall({target:`${i.published_at}::${ys}::collect_reward`,typeArguments:o,arguments:s})}}),e}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},my=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildCoinInput(t,e,n,i,r){let{selectedCoins:o,remainingCoins:s}=we.selectCoinAssetGreaterThanOrEqual(e,BigInt(i)),a=we.calculateTotalBalance(o);if(a<BigInt(i))throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${i} `);let u=a-BigInt(i),l;if(we.isSuiCoin(n))l=t.splitCoins(t.gas,[t.pure(i)]);else{let[h,...w]=o.map(v=>v.coinObjectId);l=t.object(h),w.length>0?r?t.mergeCoins(l,[...w.map(v=>t.object(v)),r]):t.mergeCoins(l,[...w.map(v=>t.object(v))]):r&&t.mergeCoins(l,[r])}return{selectedUnusedAmount:u,coinInput:l,remainingCoins:s}}async deposit(t){console.log("1110 deposit \u53C2\u6570: ",{params:t});let{vaults:e,frams:n}=this._sdk.sdkOptions,{clmm_pool:i}=this._sdk.ClmmSDK.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress()),o=new xi.TransactionBlock,s,a;if(t.swapParams){let w=await this.handleDepositSwap(t,o,r);s=w.primaryCoinAInputs,a=w.primaryCoinBInputs}else s=re.buildAddLiquidityFixTokenCoinInput(o,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,r,!1)?.targetCoin,a=re.buildAddLiquidityFixTokenCoinInput(o,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,r,!1)?.targetCoin;let u=D(e),l=D(n),h=D(i);return o.moveCall({target:`${e.published_at}::${ay}::deposit`,typeArguments:[t.coinTypeA,t.coinTypeB,t.lp_token_type],arguments:[o.object(u.vaults_manager_id),o.object(t.vault_id),o.object(l.rewarder_manager_id),o.object(l.global_config_id),o.object(t.farming_pool),o.object(h.global_config_id),o.object(t.clmm_pool),s,a,o.pure(t.amount_a),o.pure(t.amount_b),o.pure(t.fix_amount_a),o.object(G)]}),o}async handleDepositSwap(t,e,n){let{clmm_pool:i,integrate:r}=this._sdk.ClmmSDK.sdkOptions,{swap_amount:o,a2b:s,route_obj:a,staking_id:u}=t.swapParams,l=s?t.coinTypeA:t.coinTypeB,h=re.buildCoinForAmount(e,n,BigInt(o),l,!1),w=BigInt(h.tragetCoinAmount)-BigInt(o),v=[];if(u){let O=this.requestStakeCoin(u,e,h.targetCoin),E=re.buildCoinForAmount(e,h.remainCoins,BigInt(0),l,!1).targetCoin;v=s?[E,O]:[O,E]}else if(a){let O=re.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),E=await re.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,a,h,O,"",t.slippage,e);v=s?[E.fromCoin,E.toCoin]:[E.toCoin,E.fromCoin],console.log("swapCoinInputTo.isMintZeroCoin: ",O),!O.isMintZeroCoin&&O.originalSplitedCoin===void 0&&e.transferObjects([O.targetCoin],e.pure(this._sdk.getVerifySenderAddress()))}else{let O=re.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),E=mn.getDefaultSqrtPriceLimit(s).toString();v=e.moveCall({target:`${r.published_at}::${Jn}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(D(i).global_config_id),e.object(t.clmm_pool),s?h.targetCoin:O.targetCoin,s?O.targetCoin:h.targetCoin,e.pure(s),e.pure(!0),e.pure(o),e.pure(E),e.pure(!1),e.object(G)]})}let T,I,x=v[0],P=v[1];if(s){let O=BigInt(t.amount_a)-w;we.isSuiCoin(l)?(e.transferObjects([x],e.pure(this._sdk.getVerifySenderAddress())),T=e.splitCoins(e.gas,[e.pure(t.amount_a)])):O>0n?T=this.buildCoinInput(e,h.remainCoins,l,O,x).coinInput:T=x,I=P}else{T=x;let O=BigInt(t.amount_b)-w;we.isSuiCoin(l)?(e.transferObjects([P],e.pure(this._sdk.getVerifySenderAddress())),I=e.splitCoins(e.gas,[e.pure(t.amount_b)])):O>0n?I=this.buildCoinInput(e,h.remainCoins,l,O,P).coinInput:I=P}return{primaryCoinAInputs:T,primaryCoinBInputs:I}}async remove(t){console.log({params:t});let{vaults:e,frams:n}=this.sdk.sdkOptions,{clmm_pool:i,integrate:r}=this._sdk.ClmmSDK.sdkOptions,o=new xi.TransactionBlock,s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),t.lp_token_type),a=re.buildCoinForAmount(o,s,BigInt(t.lp_token_amount),t.lp_token_type,!1).targetCoin,u=D(e),l=D(n),h=D(i),w=[t.coinTypeA,t.coinTypeB,t.lp_token_type],v=o.moveCall({target:`${e.published_at}::${cy}::remove`,typeArguments:w,arguments:[o.object(u.vaults_manager_id),o.object(t.vault_id),o.object(l.rewarder_manager_id),o.object(l.global_config_id),o.object(t.farming_pool),o.object(h.global_config_id),o.object(t.clmm_pool),a,o.pure(t.lp_token_amount),o.pure(t.min_amount_a),o.pure(t.min_amount_b),o.object(G)]}),T=v[0],I=v[1];if(t.swapParams){let{a2b:x,swap_amount:P,route_obj:O}=t.swapParams;if(O){let E={targetCoin:x?T:I,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},B={targetCoin:x?I:T,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},$=await re.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,O,E,B,"",t.slippage,o),Z=x?[$.fromCoin,$.toCoin]:[$.toCoin,$.fromCoin];x?o.mergeCoins(Z[1],[I]):o.mergeCoins(Z[0],[T]),o.transferObjects([...Z],o.pure(this._sdk.getVerifySenderAddress()))}else{let E=mn.getDefaultSqrtPriceLimit(x).toString(),B=o.moveCall({target:`${r.published_at}::${Jn}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[o.object(D(i).global_config_id),o.object(t.clmm_pool),T,I,o.pure(x),o.pure(!0),o.pure(P),o.pure(E),o.pure(!0),o.object(G)]});o.transferObjects([B[0],B[1]],o.pure(this._sdk.getVerifySenderAddress()))}}else o.transferObjects([T,I],o.pure(this._sdk.getVerifySenderAddress()));return o}async getVaultList(t="all"){let{vaults:e}=this._sdk.sdkOptions,n=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e.package_id}::vaults::CreateEvent`},t),i=n.data.map(s=>s.parsedJson.id),r=await this._sdk.ClmmSDK.fullClient.batchGetObjects(i,{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}),o=[];return r.forEach(s=>{let a=Sn.buildPool(s);a&&(a.staking_id=this.findHaedalStakeId(a.position.coinTypeA,a.position.coinTypeB),this.savePoolToCache(a),o.push(a))}),n.data=o,n}findHaedalStakeId(t,e){let{haedal:n}=this._sdk.sdkOptions,{support_stakings:i}=D(n);return i.length===0?void 0:i.filter(o=>{let s=q(o.from_coin_type).full_address,a=q(o.to_coin_type).full_address,u=q(t).full_address,l=q(e).full_address;return u===s&&l===a||u===a&&l===s})[0]?.staking_id||void 0}savePoolToCache(t){let e=`${t.id}_mirrorPool`;this.updateCache(e,t,X)}readPoolFromCache(t,e=!1){let n=`${t}_mirrorPool`;return this.getCache(n,e)}async calculateMaxAvailable(t){let{integrate:e,simulationAccount:n}=this.sdk.ClmmSDK.sdkOptions,i=new xi.TransactionBlock,r=ee.tickIndexToSqrtPriceX64(t.lowerTick),o=ee.tickIndexToSqrtPriceX64(t.upperTick),s=new Oe.default(t.curSqrtPrice),a=$e.getCoinAmountFromLiquidity(new Oe.default(t.input_amount),s,r,o,!1),u=[t.coinTypeA,t.coinTypeB];i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!0),i.pure(!0),i.pure(a.coinA.toString())],typeArguments:u}),i.moveCall({target:`${e.published_at}::${zt}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!1),i.pure(!0),i.pure(a.coinB.toString())],typeArguments:u});let h=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(x=>q(x.type).name==="CalculatedSwapResultEvent");if(h.length===0)return null;let w=h[0].parsedJson.data,v=h[1].parsedJson.data,T=S(a.coinB.toString()).add(w.amount_out),I=S(a.coinA.toString()).add(v.amount_out);return{maxAmountB:T,maxAmountA:I}}async calculateRemoveSwapAmount(t,e){let n=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice)),i=t.fix_amount_a?n.ratioA:n.ratioB;console.log({fixRatio:i});let r=S(t.receive_amount).mul(i),o,s;if(t.removeLiquidity){let x=ee.tickIndexToSqrtPriceX64(t.lowerTick),P=ee.tickIndexToSqrtPriceX64(t.upperTick),O=$e.getCoinAmountFromLiquidity(new Oe.default(t.removeLiquidity),new Oe.default(t.curSqrtPrice),x,P,!1);s=t.removeLiquidity,o=t.fix_amount_a?O.coinB.toString():O.coinA.toString(),r=t.fix_amount_a?S(O.coinA.toString()):S(O.coinB.toString())}else{let x=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new Oe.default(r.toFixed(0)),t.fix_amount_a,!1,.2,new Oe.default(t.curSqrtPrice));s=x.liquidityAmount.toString(),o=t.fix_amount_a?x.coinAmountB.toString():x.coinAmountA.toString()}console.log({fixAmount:r,otherSideAmount:o});let a=!t.fix_amount_a,u=await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,S(o),t.coinTypeA,t.coinTypeB,!0,t.priceSplitPoint,t.use_route,[{pool_id:t.clmm_pool,tick_lower:t.lowerTick,tick_upper:t.upperTick,delta_liquidity:Number(s),is_increase:!1}]);console.log({data:u,range:e});let l=r.add(u.amount_out),h=S(t.receive_amount),w=h.sub(l);if(console.log(`\u5B9E\u9645\u5F97\u5230: ${l.toString()} , \u671F\u671B\u5F97\u5230: ${t.receive_amount}, \u5269\u4F59: ${w.toString()} `),(!t.removeLiquidity||t.removeLiquidity&&e)&&w.abs().greaterThan(h.mul(.01))){let x=l.lessThan(h),P,O;e?x?(P=S(s),O=e.right):(P=e.left,O=S(s)):(P=x?S(s):S(0),O=x?S(t.maxLiquidity):S(s));let E=S(P).add(O).div(2).toFixed(0);if(console.log({left:P.toString(),right:O.toString(),midLiquidity:E.toString()}),!e||e&&e.count<15&&P<O)return await this.calculateRemoveSwapAmount({...t,removeLiquidity:E},{left:P,right:O,count:e?e.count+1:0})}let v=u.amount_in&&u.fee_amount?new Oe.default(u.amount_in).add(new Oe.default(u.fee_amount)).toString():u.amount_in,T=u.amount_out,{is_exceed:I}=u;return{swapInAmount:v,swapOutAmount:T,liquidity:s,is_exceed:I,routeObj:u.route_obj,request_id:t.request_id}}async calculateHaedalDepositFixSui(t){let e=t.inputSuiAmount.mul(t.remainRate),n=t.inputSuiAmount.sub(t.swapSuiAmount),i=t.exchangeRate?t.exchangeRate:await this.getExchangeRateForHaedal(t.staking_id,t.shouldRequestStake,Number(t.swapSuiAmount.toFixed(0))),r=t.swapSuiAmount.div(i).toFixed(0);console.log({swapAmount:t.swapSuiAmount.toString(),hasuiAmount:r.toString(),leftSuiAmount:t.leftSuiAmount.toString(),rightSuiAmount:t.rightSuiAmount.toString(),exchangeRate:i});let o=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new Oe.default(r.toString()),!t.fixCoinA,!0,0,new Oe.default(t.curSqrtPrice)),s=t.fixCoinA?o.coinAmountA.toString():o.coinAmountB.toString(),a=S(n).sub(s);return console.log({useSuiAmount:s.toString(),hasuiAmount:r.toString(),remainSui:n.toString(),remainSuiLimit:e.toString(),actRemainSui:a.toString(),rebalanceCount:t.rebalanceCount}),a.greaterThanOrEqualTo(0)&&a.lessThanOrEqualTo(e)||t.rebalanceCount>12||t.leftSuiAmount.greaterThanOrEqualTo(t.rightSuiAmount)?{swapInAmount:t.swapSuiAmount.toFixed(0),swapOutAmount:r,afterSqrtPrice:t.curSqrtPrice,fixAmountA:!t.fixCoinA,is_exceed:!0,request_id:"",staking_id:t.staking_id}:a.lessThan(0)?await this.calculateHaedalDepositFixSui({...t,rightSuiAmount:t.swapSuiAmount,swapSuiAmount:t.swapSuiAmount.add(t.leftSuiAmount).div(2),exchangeRate:i,rebalanceCount:t.rebalanceCount+1}):a.greaterThan(e)?await this.calculateHaedalDepositFixSui({...t,leftSuiAmount:t.swapSuiAmount,swapSuiAmount:t.swapSuiAmount.add(t.rightSuiAmount).div(2),exchangeRate:i,rebalanceCount:t.rebalanceCount+1}):null}async calculateDepositSwapAmount(t,e=!1){let n=ee.sqrtPriceX64ToTickIndex(new Oe.default(t.curSqrtPrice)),{ratioA:i,ratioB:r}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:n,adjustBestAmount:e});let o=S(t.input_amount).mul(t.fix_amount_a?i:r),s=S(t.input_amount).sub(o);console.log("1110 ",{fixAmount:o.toString(),swapAmount:s.toString()});let a=t.fix_amount_a;if(s.toFixed(0)==="0")return null;if(t.staking_id){if(we.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||we.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let H=await this.calculateHaedalDepositFixSui({inputSuiAmount:S(t.input_amount),swapSuiAmount:s,lowerTick:t.lowerTick,upperTick:t.upperTick,curSqrtPrice:t.curSqrtPrice,remainRate:t.remainRate?t.remainRate:.01,fixCoinA:t.fix_amount_a,rebalanceCount:0,shouldRequestStake:t.shouldRequestStake,leftSuiAmount:a?new N(s.toFixed(0)):new N(0),rightSuiAmount:a?new N(t.input_amount):new N(s.toFixed(0)),staking_id:t.staking_id});return H?{...H,request_id:t.request_id}:null}throw Error("Only support fix sui")}let u=n<t.lowerTick||n>t.upperTick,l={clmm_pool:t.clmm_pool,curSqrtPrice:t.curSqrtPrice,a2b:a,amount_a:a?new N(t.input_amount):new N(0),amount_b:a?new N(0):new N(t.input_amount),amount_left:a?new N(s.toFixed(0)):new N(0),amount_right:a?new N(t.input_amount):new N(s.toFixed(0)),lowerTick:t.lowerTick,upperTick:t.upperTick,tick_spacing:2,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,useRoute:t.use_route,remainRate:t.remainRate?t.remainRate:.01,priceSplitPoint:t.priceSplitPoint},h=e&&n<=t.upperTick,w=h?await this.calculateRebalance(l):await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,s,t.coinTypeA,t.coinTypeB,!0,t.priceSplitPoint,t.use_route),v=w.after_sqrt_price,T=ee.sqrtPriceX64ToTickIndex(new Oe.default(v));console.log("1110 \u9996\u6B21\u8BA1\u7B97 \u7ED3\u679C: ",{...w,currentTick:T},null,2);let I=T<t.lowerTick||T>t.upperTick;if(u!==I&&!h&&T<=t.upperTick){console.log("1110 \u533A\u95F4\u53D1\u751F\u53D8\u5316, \u518D\u6B21\u8FDB\u884Cswap: ");let{ratioA:H,ratioB:te}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(v));console.log("1110 ",{newAfterRatioA:H,newAfterRatioB:te}),s=S(t.input_amount).sub(S(t.input_amount).mul(t.fix_amount_a?H:te)),l.amount_left=a?new N(s.toFixed(0)):new N(0),l.amount_right=a?new N(t.input_amount):new N(s.toFixed(0)),w=await this.calculateRebalance(l),v=w.after_sqrt_price;let U=ee.sqrtPriceX64ToTickIndex(new Oe.default(v));console.log("1110 \u518D\u6B21\u8BA1\u7B97\u53D8\u5316\u540E: ",{lowerTick:t.lowerTick,upperTick:t.upperTick,currentTick:U,afterSqrtPrice:v})}let{ratioA:x,ratioB:P}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(v));console.log("1110 1",{afterRatioA:x,afterRatioB:P,data:w});let O=P.div(x).sub(r.div(i)).greaterThan("0"),E=w.amount_in&&w.fee_amount?new Oe.default(w.amount_in).add(new Oe.default(w.fee_amount)).toString():w.amount_in,B=w.amount_out,{is_exceed:$}=w;if(T<t.lowerTick)O=!0;else if(T>t.upperTick)O=!1;else{let H=O===a?new Oe.default(S(t.input_amount).sub(E).toString()):new Oe.default(B),te=$e.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,H,O,!0,0,new Oe.default(v)),U=te.coinAmountA,V=te.coinAmountB,F=S(t.fix_amount_a?U.toString():V.toString()).add(E);console.log("1110 \u5B9E\u9645\u6D88\u8017:",{preAmountTotal:F.toString(),fixAmountA:O}),F.greaterThanOrEqualTo(t.input_amount)&&(O=!O)}let Z={swapInAmount:E,swapOutAmount:B,afterSqrtPrice:v,is_exceed:$,fixAmountA:O,routeObj:w.route_obj,request_id:t.request_id,use_Haedal_stake:!1};return console.log(Z),Z}async calculateHaedalDepositSwapAmount(t){let e=ee.sqrtPriceX64ToTickIndex(new Oe.default(t.curSqrtPrice)),{ratioA:n,ratioB:i}=Sn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:e});let r=S(t.input_amount).mul(t.fix_amount_a?n:i),o=S(t.input_amount).sub(r);console.log("1110 ",{fixAmount:r.toString(),swapAmount:o.toString()});let s=t.fix_amount_a;if(o.toFixed(0)==="0")return null;if(t.staking_id){if(we.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||we.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let a=await this.calculateHaedalDepositFixSui({inputSuiAmount:S(t.input_amount),swapSuiAmount:o,lowerTick:t.lowerTick,upperTick:t.upperTick,curSqrtPrice:t.curSqrtPrice,remainRate:t.remainRate?t.remainRate:.01,fixCoinA:t.fix_amount_a,rebalanceCount:0,shouldRequestStake:t.shouldRequestStake,leftSuiAmount:s?new N(o.toFixed(0)):new N(0),rightSuiAmount:s?new N(t.input_amount):new N(o.toFixed(0)),staking_id:t.staking_id});return a?{...a,request_id:t.request_id}:null}throw Error("Only support fix sui")}return null}async calculateRebalance(t){let{clmm_pool:e,a2b:n,curSqrtPrice:i,amount_a:r,amount_b:o,lowerTick:s,upperTick:a,amount_left:u,amount_right:l,coinTypeA:h,coinTypeB:w,useRoute:v,priceSplitPoint:T,remainRate:I}=t,x=async(P,O,E)=>{let B=P.plus(O).div(2),$=await this.clmmPreSwap(e,i,n,B,h,w,!0,T,v);if($.amount_out==="0")return $;if($.after_sqrt_price||($.after_sqrt_price=t.curSqrtPrice),$.is_exceed)return O=B,x(P,O,E+1);let Z=n?r.sub($.amount_in):r.add($.amount_out),H=n?o.add($.amount_out):o.sub($.amount_in),te=ee.sqrtPriceX64ToTickIndex(new Oe.default($.after_sqrt_price)),U=$e.estLiquidityAndcoinAmountFromOneAmounts(s,a,new Oe.default(Z.toString()),!0,!0,1,new Oe.default($.after_sqrt_price)),V=new N(U.coinAmountA.toString()),F=new N(U.coinAmountB.toString());if(console.log("1110 swap\u9012\u5F52\u8BA1\u7B97 ",{preRes:$,left:P.toString(),right:O.toString(),mid:B.toString(),afterPoolTickIndex:te,afterA:Z.toString(),afterB:H.toString(),usedA:V.toString(),usedB:toString(),count:E}),V.toString()!==Z.toString())throw new Error("usedA does not match afterA");if(H.lessThan(F))n?P=B:O=B;else{n?O=B:P=B;let K=H.sub(F),C=H.mul(I);if(console.log("1110 \u5269\u4F59\u672A\u4F7F\u7528amount ",{remainingB:K.toString(),maxRemainingB:C.toString(),remainRate:I,count:E}),C.sub(K).greaterThanOrEqualTo(0))return console.log("break"),{...$,remainingB:K}}return P.greaterThan(O)||O.sub(P).lessThan(10)?$:x(P,O,E+1)};return u.greaterThanOrEqualTo(l)?x(new N(0),u,0):x(u,l,0)}async clmmPreSwap(t,e,n,i,r,o,s,a,u,l){if(u)try{let O=await this._sdk.ClmmSDK.RouterV2.getBestRouter(n?r:o,n?o:r,Number(i.toFixed(0)),s,a,"",void 0,void 0,!0,!1,l);if(!O.result)throw new Error("route unavailable");let{result:E}=O,B=e;return E.splitPaths.forEach($=>{let Z=$.basePaths.find(H=>H.poolAddress.toLowerCase()===t.toLowerCase());Z&&(B=Z.afterSqrtPrice.toString())}),{amount_in:E.inputAmount.toString(),amount_out:E.outputAmount.toString(),after_sqrt_price:B,is_exceed:E.isExceed,route_obj:E}}catch{throw new Error("route unavailable")}let{integrate:h,simulationAccount:w}=this.sdk.ClmmSDK.sdkOptions,v=new xi.TransactionBlock,T=[r,o],I=[v.pure(t),v.pure(n),v.pure(s),v.pure(i.toFixed(0))];v.moveCall({target:`${h.published_at}::${zt}::calculate_swap_result`,arguments:I,typeArguments:T});let P=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:v,sender:w.address})).events?.filter(O=>q(O.type).name==="CalculatedSwapResultEvent");return P.length===0?null:P[0].parsedJson.data}async getVault(t,e=!1){let n=this.readPoolFromCache(t,e);if(n)return n;try{let i=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}}),r=Sn.buildPool(i);if(r)return r.staking_id=this.findHaedalStakeId(r.position.coinTypeA,r.position.coinTypeB),this.savePoolToCache(r),r}catch(i){console.log(i)}}async getVaultsConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.vaults,n=`${e}_getMirrorPoolConfigs`,i=this.getCache(n,t);if(i!==void 0)return i;let r=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::vaults::InitEvent`})).data,o={admin_cap_id:"",vaults_manager_id:"",vaults_pool_handle:""};if(r.length>0){for(let s of r){let a=s.parsedJson;o.admin_cap_id=a.admin_cap_id,o.vaults_manager_id=a.manager_id;let u=await this._sdk.ClmmSDK.fullClient.getObject({id:o.vaults_manager_id,options:{showContent:!0}}),l=Q(u);o.vaults_pool_handle=l.vault_to_pool_maps.fields.id.id;break}this.updateCache(n,o,X)}return o}async getExchangeRateForHaedal(t,e,n){let{haedal:i}=this._sdk.sdkOptions,{simulationAccount:r}=this._sdk.ClmmSDK.sdkOptions;try{let o=new xi.TransactionBlock;e?await this.requestStake(t,n||1e9,o):o.moveCall({target:`${i.published_at}::staking::get_exchange_rate`,typeArguments:[],arguments:[o.object(t)]});let s=await this._sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:e?this._sdk.ClmmSDK.senderAddress:r.address});if(console.log("getExchangeRateForHaedal res: ",s),e){let l=s.events.find(T=>T.type.includes("UserStaked")),{sui_amount:h,st_amount:w}=l.parsedJson,v=S(h).div(w).toString();return console.log({st_amount:w,sui_amount:h,rate:v}),v}let a=s.results[0].returnValues[0][0],u=Oc.bcs.de("u64",Uint8Array.from(a))/1e6;return console.log("rate ",Oc.bcs.de("u64",Uint8Array.from(a))),u.toString()}catch(o){console.log("getExchangeRateForHaedal",o)}return"0"}requestStakeCoin(t,e,n){let{haedal:i}=this._sdk.sdkOptions;return e.moveCall({target:`${i.published_at}::staking::request_stake_coin`,typeArguments:[],arguments:[e.object((0,Kr.normalizeSuiObjectId)("0x5")),e.object(t),n,e.pure((0,Kr.normalizeSuiObjectId)("0x0"))]})}async requestStake(t,e,n){let{haedal:i}=this._sdk.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),$r);n=n||new xi.TransactionBlock;let o;if(e>95e10){let[s,...a]=r;a.length>0&&n.mergeCoins(n.object(s.coinObjectId),a.map(u=>n.object(u.coinObjectId))),o=n.splitCoins(n.object(s.coinObjectId),[e])}else o=re.buildCoinForAmount(n,r,BigInt(e),$r,!1,!0).targetCoin;return n.moveCall({target:`${i.published_at}::interface::request_stake`,typeArguments:[],arguments:[n.object((0,Kr.normalizeSuiObjectId)("0x5")),n.object(t),o,n.pure((0,Kr.normalizeSuiObjectId)("0x0"))]}),n}updateCache(t,e,n=Ue){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},bs=class{static buildOrderLimitEvent(t){let{events:e}=t,n=[];return e&&e.forEach(i=>{let r=q(i.type).name;if(r==="OrderPlacedEvent"||r==="OrderCanceledEvent"||r==="FlashLoanEvent"){let o={digest:t.digest,type:r,timestampMs:t.timestampMs,parsedJson:i.parsedJson};n.push(o)}}),n}static buildLimitOrderInfo(t){let e=Q(t),n=pn(t);if(e&&n)try{let i=q(n),r={pay_coin_type:i.type_arguments[0],target_coin_type:i.type_arguments[1],balance:e.balance,canceled_ts:e.canceled_ts==="18446744073709551615"?0:Number(e.canceled_ts),id:e.id.id,obtained_amount:e.obtained_amount,owner:e.owner,rate:e.rate,expire_ts:Number(e.expire_ts),total_pay_amount:e.total_pay_amount,status:"Running",created_ts:Number(e.created_ts)};if(r.canceled_ts===0)r.status="Running";else if(Number(r.obtained_amount)===0)r.status="Cancelled";else{let o=S(r.total_pay_amount).mul(1e20).div(r.rate).toFixed(0);r.obtained_amount===o?r.status="Completed":r.status="Cancelled"}return r}catch(i){console.log(i)}}static calculateFormatRate(t,e,n){let i=20+e-n;return S(t).mul(S(10).pow(i)).toString()}static calculateRate(t,e,n){let i=20+e-n;return Number(t)/10**i}},py=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getLimitOrderTokenList(){let{limit_order:t}=this._sdk.sdkOptions,{token_list_handle:e}=D(t),{fullClient:n}=this._sdk.ClmmSDK,r=(await n.getDynamicFieldsByPage(e)).data.map(s=>s.objectId);return(await n.batchGetObjects(r,{showContent:!0})).map(s=>{let{fields:a}=s.data.content;return{coin_type:q(a.name.fields.name).full_address,min_trade_amount:Number(a.value)}})}async getLimitOrderPoolList(){let{limit_order:t}=this._sdk.sdkOptions,{rate_orders_indexer_handle:e}=D(t),{fullClient:n}=this._sdk.ClmmSDK,r=(await n.getDynamicFieldsByPage(e)).data.map(s=>s.objectId);return(await n.batchGetObjects(r,{showContent:!0})).map(s=>{let{fields:a}=s.data.content.fields.value,u={pay_coin_type:q(a.pay_coin.fields.name).full_address,target_coin_type:q(a.target_coin.fields.name).full_address,indexer_id:a.indexer_id};return this._sdk.updateCache(`${u.pay_coin_type}_${u.target_coin_type}`,u.indexer_id),u})}async getPoolIndexerId(t,e){let n=this._sdk.getCache(`${t}_${e}`);try{if(n===void 0){let r=(await this.getLimitOrderPoolList()).filter(o=>o.pay_coin_type===t&&o.target_coin_type===e);if(r.length>0)return r[0].indexer_id}}catch{}return n}async getOwnerLimitOrderList(t,e){let{fullClient:n}=this._sdk.ClmmSDK,i={data:[],hasNextPage:!1};try{let r=await this.getUserIndexerHandle(t);if(!r)return i;let o=await n.getDynamicFieldsByPage(r,e);i.hasNextPage=o.hasNextPage,i.nextCursor=o.nextCursor;let s=o.data.map(l=>l.name.value),u=(await n.batchGetObjects(s,{showContent:!0})).map(l=>bs.buildLimitOrderInfo(l)).filter(l=>l!==void 0);i.data=u}catch(r){console.error("Error in getOwnerLimitOrderList:",r)}return i}async getLimitOrderConfigs(){let{package_id:t}=this._sdk.sdkOptions.limit_order,e={rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""},n=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::limit_order::InitEvent`})).data;if(n.length>0){let r=n[0].parsedJson;e.rate_orders_indexer_id=r.rate_orders_indexer_id,e.user_orders_indexer_id=r.user_orders_indexer_id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.rate_orders_indexer_id,options:{showContent:!0}});e.rate_orders_indexer_handle=Q(o).list.fields.id.id;let s=await this._sdk.ClmmSDK.fullClient.getObject({id:e.user_orders_indexer_id,options:{showContent:!0}});e.user_orders_indexer_handle=Q(s).indexer.fields.id.id}let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitFactoryEvent`})).data;if(i.length>0){let r=i[0].parsedJson;e.global_config_id=r.global_config_id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.global_config_id,options:{showContent:!0}}),s=Q(o);e.token_list_handle=s.token_white_list.fields.id.id}return e}async getLimitOrder(t){let{fullClient:e}=this._sdk.ClmmSDK;try{let n=await e.getObject({id:t,options:{showContent:!0}});return bs.buildLimitOrderInfo(n)}catch(n){console.error("Error in getLimitOrder:",n);return}}async getLimitOrderLogs(t){let{fullClient:e}=this._sdk.ClmmSDK;try{let n=await e.queryTransactionBlocks({filter:{ChangedObject:t},options:{showEvents:!0}}),i=[];return n.data.forEach(r=>{i.push(...bs.buildOrderLimitEvent(r))}),i}catch(n){return console.error("Error in getLimitOrderLogs:",n),[]}}buildRateOrdersIndexerType(t){let{limit_order:e}=this._sdk.sdkOptions;return rr(`${e.package_id}::limit_order::RateOrdersIndexer`,[t.pay_coin_type,t.target_coin_type])}async placeLimitOrder(t){let{limit_order:e}=this._sdk.sdkOptions,{user_orders_indexer_id:n,global_config_id:i,rate_orders_indexer_id:r}=D(e),o=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.pay_coin_type),s=new ks.TransactionBlock,a=await this.getPoolIndexerId(t.pay_coin_type,t.target_coin_type),u=re.buildCoinForAmount(s,o,BigInt(t.pay_coin_amount),t.pay_coin_type,!1,!0);return s.moveCall({target:`${e.published_at}::limit_order::${a===void 0?"create_indexer_and_place_limit_order":"place_limit_order"}`,typeArguments:[t.pay_coin_type,t.target_coin_type],arguments:[s.object(i),a===void 0?s.object(r):s.object(a),s.object(n),u.targetCoin,s.pure(bs.calculateFormatRate(t.rate,t.pay_decimal,t.target_decimal)),s.pure(t.expired_ts),s.object(G)]}),s}async cancelOrdersByOwner(t){let{limit_order:e}=this._sdk.sdkOptions,{global_config_id:n}=D(e),i=new ks.TransactionBlock,r=await this.getPoolIndexerId(t.pay_coin_type,t.target_coin_type);if(r===void 0)throw Error("not found indexerId");return t.order_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::limit_order::cancel_order_by_owner`,typeArguments:[t.pay_coin_type,t.target_coin_type],arguments:[i.object(n),i.object(r),i.object(o),i.object(G)]})}),i}async getUserIndexerHandle(t){let{fullClient:e}=this._sdk.ClmmSDK,{limit_order:n}=this._sdk.sdkOptions,i=this.getUserIndexerHandleByCache(t);if(i===void 0){let r=new ks.TransactionBlock;r.moveCall({target:`${n.published_at}::limit_order::get_orders_indexer_by_owner`,typeArguments:[],arguments:[r.pure(t),r.object(D(n).user_orders_indexer_id)]}),i=(await e.devInspectTransactionBlock({transactionBlock:r,sender:this._sdk.ClmmSDK.sdkOptions.simulationAccount.address})).events[0].parsedJson.orders_table_id,i&&this.saveUserIndexerHandleByCache(t,i)}return i}getUserIndexerHandleByCache(t){let e=`getUserIndexerHandleByCache_${t}`;return this.getCache(e)}saveUserIndexerHandleByCache(t,e){let n=`getUserIndexerHandleByCache_${t}`;return this.updateCache(n,e)}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}},gy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getFramsPoolList(t="all"){let{package_id:e}=this._sdk.sdkOptions.frams,n={data:[],hasNextPage:!1};try{let i=await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${e}::pool::CreatePoolEvent`},t),r=i.data.map(o=>o.parsedJson.pool_id);if(n.hasNextPage=i.hasNextPage,n.nextCursor=i.nextCursor,r.length>0){let o=await this._sdk.ClmmSDK.fullClient.batchGetObjects(r,{showType:!0,showContent:!0});for(let s of o){let a=ws.buildFramsPool(s);a&&(a.rewarders=await this.getFramsRewarderConfig(a.clmm_pool_id,a.rewarders.map(u=>u.reward_coin)),n.data.push(a),this.updateCache(a.id,a))}}}catch(i){console.log("getFramsPoolList error ",i)}return n}async getFramsPool(t,e=!1){let n=this.getCache(t,e);if(n)return n;let i=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}}),r=ws.buildFramsPool(i.data);return r&&(r.rewarders=await this.getFramsRewarderConfig(r.clmm_pool_id,r.rewarders.map(o=>o.reward_coin)),this.updateCache(r.id,r)),r}async getFramsRewarderConfig(t,e,n=!1){let{frams:i}=this._sdk.sdkOptions,r=[];for(let o of e){let s=`getFramsRewarderConfig_${o}_${t}`,a=this.getCache(s,n);if(a)r.push(a);else try{let u=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:D(i).rewarder_manager_handle,name:{type:"0x1::type_name::TypeName",value:kc(o)}}),{fields:l}=u.data.content.fields.value.fields.value,h={reward_coin:o,last_reward_time:l.last_reward_time,emission_per_second:l.emission_per_second,total_allocate_point:l.total_allocate_point,allocate_point:""},w=l.pools.fields.id.id,v=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:w,name:{type:"0x2::object::ID",value:t}}),{allocate_point:T}=v.data.content.fields.value.fields.value.fields;h.allocate_point=T,this.updateCache(s,h),r.push(h)}catch(u){console.log(u)}}return r}async getOwnedFramsPositionNFTList(t,e=[],n=!1,i=!0,r="all"){let{package_id:o}=this._sdk.sdkOptions.frams,s={data:[],hasNextPage:!1},a={},u=[],l=e.length>0,h=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{filter:{StructType:`${o}::pool::WrappedPositionNFT`},options:{showContent:!0}},r);s.hasNextPage=h.hasNextPage,s.nextCursor=h.nextCursor;for(let w of h.data){let v=ws.buildFramsPositionNFT(w);if(v)if(l){if(e.includes(v.pool_id)){u.push(v);let T=a[v.pool_id];T?T.push(v):T=[v],a[v.pool_id]=T}}else u.push(v)}if(n&&u.length>0){let w=await this.calculateFarmingRewards(u.map(v=>({pool_id:v.pool_id,position_nft_id:v.id,clmm_pool_id:v.clmm_pool_id})),i);l?(a={},u.forEach(v=>{w[v.id]&&(v.rewards=w[v.id]);let I=a[v.pool_id];I?I.push(v):I=[v],a[v.pool_id]=I})):u.forEach(v=>{w[v.id]&&(v.rewards=w[v.id])})}return l?a:(s.data=u,s)}async getFramsPositionNFT(t,e=!0){let n=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),i=ws.buildFramsPositionNFT(n);if(e&&i){let r=await this.calculateFarmingRewards([{pool_id:i.pool_id,position_nft_id:i.id}]);r[i.id]&&(i.rewards=r[i.id])}return i}async calculateFarmingRewards(t,e=!0){let{frams:n}=this._sdk.sdkOptions,i=new Jt.TransactionBlock,{rewarder_manager_id:r,global_config_id:o}=D(n);t.forEach(a=>{i.moveCall({target:`${n.published_at}::router::accumulated_position_rewards`,typeArguments:[],arguments:[i.object(o),i.object(r),i.object(a.pool_id),i.pure(a.position_nft_id,"address"),i.object(G)]})});let s={};try{let a=await this._sdk.ClmmSDK.fullClient.sendSimulationTransaction(i,this._sdk.ClmmSDK.senderAddress,e);console.log({simulateRes:a});let u=a?.events?.filter(l=>q(l.type).name==="AccumulatedPositionRewardsEvent");if(u&&u.length>0)for(let l=0;l<u.length;l+=1){let{parsedJson:h}=u[l],w=[];h.rewards.contents.forEach(v=>{w.push({rewarder_type:q(v.key.name).full_address,rewarder_amount:v.value})}),s[h.wrapped_position_id]=w}}catch(a){console.log(a)}return s}depositPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new Jt.TransactionBlock;let{global_config_id:i,rewarder_manager_id:r}=D(n);return e.moveCall({target:`${n.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(i),e.object(r),e.object(t.pool_id),e.object(t.clmm_position_id),e.object(G)]}),e}async withdrawPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{global_config_id:i,rewarder_manager_id:r}=D(n);return e=e||new Jt.TransactionBlock,e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id},e),e.moveCall({target:`${n.published_at}::router::withdraw`,typeArguments:[],arguments:[e.object(i),e.object(r),e.object(t.pool_id),e.object(t.position_nft_id),e.object(G)]}),e}async batchHarvestPayload(t,e){e=e||new Jt.TransactionBlock;for(let n of t)await this.harvestPayload(n,e);return e}async harvestPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new Jt.TransactionBlock;let i=await this.getFramsPool(t.pool_id,!1);if(i===void 0)throw Error(`not found ${t.pool_id}`);let{global_config_id:r,rewarder_manager_id:o}=D(n);if("collect_fee"in t&&(t.collect_fee||t.clmm_rewarder_types.length>0)){let a=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,a)}return i.rewarders.forEach(a=>{e&&e.moveCall({target:`${n.published_at}::router::harvest`,typeArguments:[a.reward_coin],arguments:[e.object(r),e.object(o),e.object(t.pool_id),e.object(t.position_nft_id),e.object(G)]})}),e}async claimFeeAndClmmReward(t){let e=new Jt.TransactionBlock,n=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);return await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,n),e}async openPositionAddLiquidityStakePaylod(t){let e=new Jt.TransactionBlock,{clmm_pool:n,integrate:i}=this._sdk.ClmmSDK.sdkOptions,r=D(n),o=e.moveCall({target:`${n.published_at}::pool::open_position`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(t.clmm_pool_id),e.pure(Tt(BigInt(t.tick_lower)).toString()),e.pure(Tt(BigInt(t.tick_upper)).toString())]}),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_b),t.coinTypeB,!1);e.moveCall({target:`${i.published_at}::${jn}::add_liquidity_by_fix_coin`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(t.clmm_pool_id),o,a.targetCoin,u.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(G)]});let{frams:l}=this.sdk.sdkOptions,{global_config_id:h,rewarder_manager_id:w}=D(l);return e.moveCall({target:`${l.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(h),e.object(w),e.object(t.pool_id),o,e.object(G)]}),e}async addLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_limit_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_limit_b),t.coinTypeB,!1);if(t.collect_rewarder&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.collect_fee||t.clmm_rewarder_types.length>0){let l=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,l,a.remainCoins,u.remainCoins)}return e.moveCall({target:`${n.published_at}::router::add_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),a.targetCoin,u.targetCoin,e.pure(t.amount_limit_a),e.pure(t.amount_limit_b),e.pure(t.delta_liquidity),e.object(G)]}),e}async addLiquidityFixCoinPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=re.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),u=re.buildCoinForAmount(e,s,BigInt(t.amount_b),t.coinTypeB,!1);if(t.collect_rewarder&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.collect_fee||t.clmm_rewarder_types.length>0){let l=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:t.collect_fee,clmm_rewarder_types:t.clmm_rewarder_types},e,l,a.remainCoins,u.remainCoins)}return e.moveCall({target:`${n.published_at}::router::add_liquidity_fix_coin`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),a.targetCoin,u.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(G)]}),e}async removeLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i);if(t.collect_rewarder&&(!t.unstake||t.close_position)&&(e=await this.harvestPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id,clmm_pool_id:t.clmm_pool_id},e)),t.clmm_rewarder_types.length>0){let s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);e=await this.buildCollectRewarderAndFeeParams({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,collectFee:!1,clmm_rewarder_types:t.clmm_rewarder_types},e,s)}if(t.close_position){if(t.clmm_position_id===void 0)throw Error("close_position need clmm_position_id");e.moveCall({target:`${n.published_at}::router::close_position`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(o.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.pure(t.min_amount_a),e.pure(t.min_amount_b),e.object(G)]})}else e.moveCall({target:`${n.published_at}::router::remove_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(r.rewarder_manager_id),e.object(t.pool_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.pure(t.delta_liquidity),e.pure(t.min_amount_a),e.pure(t.min_amount_b),e.object(G)]}),t.unstake&&this.withdrawPayload({pool_id:t.pool_id,position_nft_id:t.position_nft_id});return e}async buildCollectRewarderAndFeeParams(t,e,n,i,r){i===void 0&&(i=[...n]),r===void 0&&(r=[...n]);let o=Et(t.coinTypeA),s=Et(t.coinTypeB);t.collectFee&&this.collectFeePayload({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},e);let a=[];return t.clmm_rewarder_types.forEach(u=>{switch(Et(u)){case o:a.push(re.buildCoinForAmount(e,i,BigInt(0),u,!1).targetCoin);break;case s:a.push(re.buildCoinForAmount(e,r,BigInt(0),u,!1).targetCoin);break;default:a.push(re.buildCoinForAmount(e,n,BigInt(0),u,!1).targetCoin);break}}),this.collectClmmRewardPayload({clmm_pool_id:t.clmm_pool_id,position_nft_id:t.position_nft_id,clmm_rewarder_types:t.clmm_rewarder_types,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,reward_coins:a},e),e}collectFeePayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=D(n),o=D(i);return e.moveCall({target:`${n.published_at}::router::collect_fee`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(r.global_config_id),e.object(o.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id)]}),e}async collectClmmRewardPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new Jt.TransactionBlock;let r=t.reward_coins;if(t.clmm_rewarder_types.length>0&&r===void 0){r=[];let a=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress);t.clmm_rewarder_types.forEach(u=>{r.push(re.buildCoinForAmount(e,a,BigInt(0),u,!1).targetCoin)})}let o=D(n),s=D(i);return t.clmm_rewarder_types?.forEach((a,u)=>{e&&e.moveCall({target:`${n.published_at}::router::collect_clmm_reward`,typeArguments:[a,t.coinTypeA,t.coinTypeB],arguments:[e.object(o.global_config_id),e.object(s.global_config_id),e.object(t.clmm_pool_id),e.object(t.position_nft_id),e.object(s.global_vault_id),r[u],e.object(G)]})}),e}async getFrarmsConfigs(){let{package_id:t}=this._sdk.sdkOptions.frams,e={global_config_id:"",rewarder_manager_id:"",rewarder_manager_handle:""},n=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::config::InitConfigEvent`})).data;if(n.length>0){let r=n[0].parsedJson;e.global_config_id=r.global_config_id,e.admin_cap_id=r.admin_cap_id}let i=(await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${t}::rewarder::InitRewarderManagerEvent`})).data;if(i.length>0){let r=i[0].parsedJson;e.rewarder_manager_id=r.id;let o=await this._sdk.ClmmSDK.fullClient.getObject({id:e.rewarder_manager_id,options:{showContent:!0}});e.rewarder_manager_handle=o.data.content.fields.rewarders.fields.id.id}return e}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}},Ut=class{_cache={};_sdkOptions;_launchpad;_ido;_xcetusModule;_xtokenModule;_boosterModule;_makerModule;_clmmSDK;_liquidityStrategy;_vaults;_limitOrder;_farmsModule;constructor(t,e){this._sdkOptions=t,this._clmmSDK=e,this._launchpad=new ny(this),this._ido=new dy(this),this._xcetusModule=new ry(this),this._xtokenModule=new fy(this),this._boosterModule=new ty(this),this._makerModule=new iy(this),this._vaults=new my(this),this._limitOrder=new py(this),this._farmsModule=new gy(this),this._liquidityStrategy=new hy(this),gs(this._sdkOptions)}get ClmmSDK(){return this._clmmSDK}get sdkOptions(){return this._sdkOptions}get Launchpad(){return this._launchpad}get Ido(){return this._ido}get XToken(){return this._xtokenModule}get XCetusModule(){return this._xcetusModule}get BoosterModule(){return this._boosterModule}get MakerModule(){return this._makerModule}get LiquidityStrategy(){return this._liquidityStrategy}get Vaults(){return this._vaults}get LimitOrder(){return this._limitOrder}get Farms(){return this._farmsModule}getVerifySenderAddress(){let{senderAddress:t}=this.ClmmSDK;if(t.length===0||!(0,hf.isValidSuiAddress)(t))throw Error("this clmm config sdk senderAddess is illegal");return t}updateCache(t,e,n=X){let i=this._cache[t];i?(i.overdueTime=he(n),i.value=e):i=new Be(e,he(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t];if(!e&&n?.isValid())return n.value;delete this._cache[t]}};var Vm=require("@msafe/sui3-utils"),cp=require("@mysten/sui.js/client"),zn=ge(require("axios"),1),Ui=require("@mysten/sui.js/utils"),Io=require("@mysten/sui.js/transactions"),Eu=require("@mysten/sui.js/transactions"),Po=require("@mysten/sui.js/utils"),Mu=require("buffer"),fp=require("@mysten/sui.js/utils"),zu=require("@mysten/sui.js/bcs"),Do=require("@mysten/sui.js/utils");var yf=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,n)=>(n&=63,n<36?e+=n.toString(36):n<62?e+=(n-26).toString(36).toUpperCase():n>62?e+="-":e+="_",e),"");var Nu=require("@mysten/sui.js/transactions"),Oo=require("@mysten/sui.js/transactions"),Eo=require("@mysten/sui.js/utils");var Ln=class extends Error{},Cs=class extends Ln{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Ss=class extends Ln{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},As=class extends Ln{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},gn=class extends Ln{},hr=class extends Ln{constructor(e){super(`Invalid unit ${e}`)}},bt=class extends Ln{},_n=class extends Ln{constructor(){super("Zone is an abstract class")}};var Y="numeric",yn="short",Yt="long",ei={year:Y,month:Y,day:Y},Gr={year:Y,month:yn,day:Y},Pc={year:Y,month:yn,day:Y,weekday:yn},Wr={year:Y,month:Yt,day:Y},Hr={year:Y,month:Yt,day:Y,weekday:Yt},Zr={hour:Y,minute:Y},Xr={hour:Y,minute:Y,second:Y},Jr={hour:Y,minute:Y,second:Y,timeZoneName:yn},Yr={hour:Y,minute:Y,second:Y,timeZoneName:Yt},Qr={hour:Y,minute:Y,hourCycle:"h23"},eo={hour:Y,minute:Y,second:Y,hourCycle:"h23"},to={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:yn},no={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:Yt},io={year:Y,month:Y,day:Y,hour:Y,minute:Y},ro={year:Y,month:Y,day:Y,hour:Y,minute:Y,second:Y},oo={year:Y,month:yn,day:Y,hour:Y,minute:Y},so={year:Y,month:yn,day:Y,hour:Y,minute:Y,second:Y},Dc={year:Y,month:yn,day:Y,weekday:yn,hour:Y,minute:Y},ao={year:Y,month:Yt,day:Y,hour:Y,minute:Y,timeZoneName:yn},co={year:Y,month:Yt,day:Y,hour:Y,minute:Y,second:Y,timeZoneName:yn},uo={year:Y,month:Yt,day:Y,weekday:Yt,hour:Y,minute:Y,timeZoneName:Yt},lo={year:Y,month:Yt,day:Y,weekday:Yt,hour:Y,minute:Y,second:Y,timeZoneName:Yt};var Gt=class{get type(){throw new _n}get name(){throw new _n}get ianaName(){return this.name}get isUniversal(){throw new _n}offsetName(e,n){throw new _n}formatOffset(e,n){throw new _n}offset(e){throw new _n}equals(e){throw new _n}get isValid(){throw new _n}};var Ec=null,ti=class t extends Gt{static get instance(){return Ec===null&&(Ec=new t),Ec}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:i}){return Is(e,n,i)}formatOffset(e,n){return ni(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Ps={};function _y(t){return Ps[t]||(Ps[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"})),Ps[t]}var yy={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function wy(t,e){let n=t.format(e).replace(/\u200E/g,""),i=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,o,s,a,u,l,h]=i;return[s,r,o,a,u,l,h]}function by(t,e){let n=t.formatToParts(e),i=[];for(let r=0;r<n.length;r++){let{type:o,value:s}=n[r],a=yy[o];o==="era"?i[a]=s:de(a)||(i[a]=parseInt(s,10))}return i}var Os={},Ft=class t extends Gt{static create(e){return Os[e]||(Os[e]=new t(e)),Os[e]}static resetCache(){Os={},Ps={}}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:n,locale:i}){return Is(e,n,i,this.name)}formatOffset(e,n){return ni(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let i=_y(this.name),[r,o,s,a,u,l,h]=i.formatToParts?by(i,n):wy(i,n);a==="BC"&&(r=-Math.abs(r)+1);let v=mr({year:r,month:o,day:s,hour:u===24?0:u,minute:l,second:h,millisecond:0}),T=+n,I=T%1e3;return T-=I>=0?I:1e3+I,(v-T)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var wf={};function vy(t,e={}){let n=JSON.stringify([t,e]),i=wf[n];return i||(i=new Intl.ListFormat(t,e),wf[n]=i),i}var Mc={};function Bc(t,e={}){let n=JSON.stringify([t,e]),i=Mc[n];return i||(i=new Intl.DateTimeFormat(t,e),Mc[n]=i),i}var jc={};function ky(t,e={}){let n=JSON.stringify([t,e]),i=jc[n];return i||(i=new Intl.NumberFormat(t,e),jc[n]=i),i}var Nc={};function Ty(t,e={}){let{base:n,...i}=e,r=JSON.stringify([t,i]),o=Nc[r];return o||(o=new Intl.RelativeTimeFormat(t,e),Nc[r]=o),o}var fo=null;function Cy(){return fo||(fo=new Intl.DateTimeFormat().resolvedOptions().locale,fo)}var bf={};function Sy(t){let e=bf[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,bf[t]=e}return e}function Ay(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let n=t.indexOf("-u-");if(n===-1)return[t];{let i,r;try{i=Bc(t).resolvedOptions(),r=t}catch{let u=t.substring(0,n);i=Bc(u).resolvedOptions(),r=u}let{numberingSystem:o,calendar:s}=i;return[r,o,s]}}function xy(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Iy(t){let e=[];for(let n=1;n<=12;n++){let i=be.utc(2009,n,1);e.push(t(i))}return e}function Oy(t){let e=[];for(let n=1;n<=7;n++){let i=be.utc(2016,11,13+n);e.push(t(i))}return e}function Ds(t,e,n,i){let r=t.listingMode();return r==="error"?null:r==="en"?n(e):i(e)}function Py(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 Fc=class{constructor(e,n,i){this.padTo=i.padTo||0,this.floor=i.floor||!1;let{padTo:r,floor:o,...s}=i;if(!n||Object.keys(s).length>0){let a={useGrouping:!1,...i};i.padTo>0&&(a.minimumIntegerDigits=i.padTo),this.inf=ky(e,a)}}format(e){if(this.inf){let n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{let n=this.floor?Math.floor(e):pr(e,3);return Le(n,this.padTo)}}},Rc=class{constructor(e,n,i){this.opts=i,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Ft.create(a).valid?(r=a,this.dt=e):(r="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,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||r,this.dtf=Bc(n,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(n=>{if(n.type==="timeZoneName"){let i=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:i}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},qc=class{constructor(e,n,i){this.opts={style:"long",...i},!n&&Es()&&(this.rtf=Ty(e,i))}format(e,n){return this.rtf?this.rtf.format(e,n):vf(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},Dy={firstDay:1,minimalDays:4,weekend:[6,7]},xe=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,i,r,o=!1){let s=e||Ce.defaultLocale,a=s||(o?"en-US":Cy()),u=n||Ce.defaultNumberingSystem,l=i||Ce.defaultOutputCalendar,h=ho(r)||Ce.defaultWeekSettings;return new t(a,u,l,h,s)}static resetCache(){fo=null,Mc={},jc={},Nc={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:i,weekSettings:r}={}){return t.create(e,n,i,r)}constructor(e,n,i,r,o){let[s,a,u]=Ay(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=i||u||null,this.weekSettings=r,this.intl=xy(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=Py(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"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,ho(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,n=!1){return Ds(this,e,Lc,()=>{let i=n?{month:e,day:"numeric"}:{month:e},r=n?"format":"standalone";return this.monthsCache[r][e]||(this.monthsCache[r][e]=Iy(o=>this.extract(o,i,"month"))),this.monthsCache[r][e]})}weekdays(e,n=!1){return Ds(this,e,$c,()=>{let i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Oy(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return Ds(this,void 0,()=>Uc,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[be.utc(2016,11,13,9),be.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Ds(this,e,Kc,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[be.utc(-40,1,1),be.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,n,i){let r=this.dtFormatter(e,n),o=r.formatToParts(),s=o.find(a=>a.type.toLowerCase()===i);return s?s.value:null}numberFormatter(e={}){return new Fc(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Rc(e,this.intl,n)}relFormatter(e={}){return new qc(this.intl,this.isEnglish(),e)}listFormatter(e={}){return vy(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:Ms()?Sy(this.locale):Dy}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 Vc=null,Ct=class t extends Gt{static get utcInstance(){return Vc===null&&(Vc=new t(0)),Vc}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(Pi(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ni(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ni(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ni(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var gr=class extends Gt{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 wn(t,e){let n;if(de(t)||t===null)return e;if(t instanceof Gt)return t;if(kf(t)){let i=t.toLowerCase();return i==="default"?e:i==="local"||i==="system"?ti.instance:i==="utc"||i==="gmt"?Ct.utcInstance:Ct.parseSpecifier(i)||Ft.create(t)}else return In(t)?Ct.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new gr(t)}var Tf=()=>Date.now(),Cf="system",Sf=null,Af=null,xf=null,If=60,Of,Pf=null,Ce=class{static get now(){return Tf}static set now(e){Tf=e}static set defaultZone(e){Cf=e}static get defaultZone(){return wn(Cf,ti.instance)}static get defaultLocale(){return Sf}static set defaultLocale(e){Sf=e}static get defaultNumberingSystem(){return Af}static set defaultNumberingSystem(e){Af=e}static get defaultOutputCalendar(){return xf}static set defaultOutputCalendar(e){xf=e}static get defaultWeekSettings(){return Pf}static set defaultWeekSettings(e){Pf=ho(e)}static get twoDigitCutoffYear(){return If}static set twoDigitCutoffYear(e){If=e%100}static get throwOnInvalid(){return Of}static set throwOnInvalid(e){Of=e}static resetCaches(){xe.resetCache(),Ft.resetCache()}};var St=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var Df=[0,31,59,90,120,151,181,212,243,273,304,334],Ef=[0,31,60,91,121,152,182,213,244,274,305,335];function an(t,e){return new St("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Bs(t,e,n){let i=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&i.setUTCFullYear(i.getUTCFullYear()-1900);let r=i.getUTCDay();return r===0?7:r}function Mf(t,e,n){return n+(Ei(t)?Ef:Df)[e-1]}function Bf(t,e){let n=Ei(t)?Ef:Df,i=n.findIndex(o=>o<e),r=e-n[i];return{month:i+1,day:r}}function js(t,e){return(t-e+7)%7+1}function mo(t,e=4,n=1){let{year:i,month:r,day:o}=t,s=Mf(i,r,o),a=js(Bs(i,r,o),n),u=Math.floor((s-a+14-e)/7),l;return u<1?(l=i-1,u=Di(l,e,n)):u>Di(i,e,n)?(l=i+1,u=1):l=i,{weekYear:l,weekNumber:u,weekday:a,...go(t)}}function Gc(t,e=4,n=1){let{weekYear:i,weekNumber:r,weekday:o}=t,s=js(Bs(i,1,e),n),a=ii(i),u=r*7+o-s-7+e,l;u<1?(l=i-1,u+=ii(l)):u>a?(l=i+1,u-=ii(i)):l=i;let{month:h,day:w}=Bf(l,u);return{year:l,month:h,day:w,...go(t)}}function Ns(t){let{year:e,month:n,day:i}=t,r=Mf(e,n,i);return{year:e,ordinal:r,...go(t)}}function Wc(t){let{year:e,ordinal:n}=t,{month:i,day:r}=Bf(e,n);return{year:e,month:i,day:r,...go(t)}}function Hc(t,e){if(!de(t.localWeekday)||!de(t.localWeekNumber)||!de(t.localWeekYear)){if(!de(t.weekday)||!de(t.weekNumber)||!de(t.weekYear))throw new gn("Cannot mix locale-based week fields with ISO-based week fields");return de(t.localWeekday)||(t.weekday=t.localWeekday),de(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),de(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 jf(t,e=4,n=1){let i=po(t.weekYear),r=Qt(t.weekNumber,1,Di(t.weekYear,e,n)),o=Qt(t.weekday,1,7);return i?r?o?!1:an("weekday",t.weekday):an("week",t.weekNumber):an("weekYear",t.weekYear)}function Nf(t){let e=po(t.year),n=Qt(t.ordinal,1,ii(t.year));return e?n?!1:an("ordinal",t.ordinal):an("year",t.year)}function Zc(t){let e=po(t.year),n=Qt(t.month,1,12),i=Qt(t.day,1,_r(t.year,t.month));return e?n?i?!1:an("day",t.day):an("month",t.month):an("year",t.year)}function Xc(t){let{hour:e,minute:n,second:i,millisecond:r}=t,o=Qt(e,0,23)||e===24&&n===0&&i===0&&r===0,s=Qt(n,0,59),a=Qt(i,0,59),u=Qt(r,0,999);return o?s?a?u?!1:an("millisecond",r):an("second",i):an("minute",n):an("hour",e)}function de(t){return typeof t>"u"}function In(t){return typeof t=="number"}function po(t){return typeof t=="number"&&t%1===0}function kf(t){return typeof t=="string"}function Rf(t){return Object.prototype.toString.call(t)==="[object Date]"}function Es(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ms(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function qf(t){return Array.isArray(t)?t:[t]}function Jc(t,e,n){if(t.length!==0)return t.reduce((i,r)=>{let o=[e(r),r];return i&&n(i[0],o[0])===i[0]?i:o},null)[1]}function Lf(t,e){return e.reduce((n,i)=>(n[i]=t[i],n),{})}function ri(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ho(t){if(t==null)return null;if(typeof t!="object")throw new bt("Week settings must be an object");if(!Qt(t.firstDay,1,7)||!Qt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Qt(e,1,7)))throw new bt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Qt(t,e,n){return po(t)&&t>=e&&t<=n}function Ey(t,e){return t-e*Math.floor(t/e)}function Le(t,e=2){let n=t<0,i;return n?i="-"+(""+-t).padStart(e,"0"):i=(""+t).padStart(e,"0"),i}function $n(t){if(!(de(t)||t===null||t===""))return parseInt(t,10)}function oi(t){if(!(de(t)||t===null||t===""))return parseFloat(t)}function _o(t){if(!(de(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function pr(t,e,n=!1){let i=10**e;return(n?Math.trunc:Math.round)(t*i)/i}function Ei(t){return t%4===0&&(t%100!==0||t%400===0)}function ii(t){return Ei(t)?366:365}function _r(t,e){let n=Ey(e-1,12)+1,i=t+(e-n)/12;return n===2?Ei(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function mr(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 Ff(t,e,n){return-js(Bs(t,1,e),n)+e-1}function Di(t,e=4,n=1){let i=Ff(t,e,n),r=Ff(t+1,e,n);return(ii(t)-i+r)/7}function yo(t){return t>99?t:t>Ce.twoDigitCutoffYear?1900+t:2e3+t}function Is(t,e,n,i=null){let r=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};i&&(o.timeZone=i);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(n,s).formatToParts(r).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function Pi(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);let i=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-i:i;return n*60+r}function Yc(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new bt(`Invalid unit value ${t}`);return e}function yr(t,e){let n={};for(let i in t)if(ri(t,i)){let r=t[i];if(r==null)continue;n[e(i)]=Yc(r)}return n}function ni(t,e){let n=Math.trunc(Math.abs(t/60)),i=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${Le(n,2)}:${Le(i,2)}`;case"narrow":return`${r}${n}${i>0?`:${i}`:""}`;case"techie":return`${r}${Le(n,2)}${Le(i,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function go(t){return Lf(t,["hour","minute","second","millisecond"])}var My=["January","February","March","April","May","June","July","August","September","October","November","December"],Qc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],By=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lc(t){switch(t){case"narrow":return[...By];case"short":return[...Qc];case"long":return[...My];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 eu=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],tu=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],jy=["M","T","W","T","F","S","S"];function $c(t){switch(t){case"narrow":return[...jy];case"short":return[...tu];case"long":return[...eu];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Uc=["AM","PM"],Ny=["Before Christ","Anno Domini"],Fy=["BC","AD"],Ry=["B","A"];function Kc(t){switch(t){case"narrow":return[...Ry];case"short":return[...Fy];case"long":return[...Ny];default:return null}}function $f(t){return Uc[t.hour<12?0:1]}function Uf(t,e){return $c(e)[t.weekday-1]}function Kf(t,e){return Lc(e)[t.month-1]}function zf(t,e){return Kc(e)[t.year<0?0:1]}function vf(t,e,n="always",i=!1){let r={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(n==="auto"&&o){let w=t==="days";switch(e){case 1:return w?"tomorrow":`next ${r[t][0]}`;case-1:return w?"yesterday":`last ${r[t][0]}`;case 0:return w?"today":`this ${r[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=r[t],h=i?u?l[1]:l[2]||l[1]:u?r[t][0]:t;return s?`${a} ${h} ago`:`in ${a} ${h}`}function Vf(t,e){let n="";for(let i of t)i.literal?n+=i.val:n+=e(i.val);return n}var qy={D:ei,DD:Gr,DDD:Wr,DDDD:Hr,t:Zr,tt:Xr,ttt:Jr,tttt:Yr,T:Qr,TT:eo,TTT:to,TTTT:no,f:io,ff:oo,fff:ao,ffff:uo,F:ro,FF:so,FFF:co,FFFF:lo},At=class t{static create(e,n={}){return new t(e,n)}static parseFormat(e){let n=null,i="",r=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(i.length>0&&o.push({literal:r||/^\s+$/.test(i),val:i}),n=null,i="",r=!r):r||a===n?i+=a:(i.length>0&&o.push({literal:/^\s+$/.test(i),val:i}),i=a,n=a)}return i.length>0&&o.push({literal:r||/^\s+$/.test(i),val:i}),o}static macroTokenToFormatOpts(e){return qy[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Le(e,n);let i={...this.opts};return n>0&&(i.padTo=n),this.loc.numberFormatter(i).format(e)}formatDateTimeFromString(e,n){let i=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(T,I)=>this.loc.extract(e,T,I),s=T=>e.isOffsetFixed&&e.offset===0&&T.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,T.format):"",a=()=>i?$f(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(T,I)=>i?Kf(e,T):o(I?{month:T}:{month:T,day:"numeric"},"month"),l=(T,I)=>i?Uf(e,T):o(I?{weekday:T}:{weekday:T,month:"long",day:"numeric"},"weekday"),h=T=>{let I=t.macroTokenToFormatOpts(T);return I?this.formatWithSystemDefault(e,I):T},w=T=>i?zf(e,T):o({era:T},"era"),v=T=>{switch(T){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 a();case"d":return r?o({day:"numeric"},"day"):this.num(e.day);case"dd":return r?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return r?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return r?o({month:"numeric"},"month"):this.num(e.month);case"MM":return r?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return r?o({year:"numeric"},"year"):this.num(e.year);case"yy":return r?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return w("short");case"GG":return w("long");case"GGGGG":return w("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 h(T)}};return Vf(t.parseFormat(n),v)}formatDurationFromString(e,n){let i=u=>{switch(u[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}},r=u=>l=>{let h=i(l);return h?this.num(u.get(h),l.length):l},o=t.parseFormat(n),s=o.reduce((u,{literal:l,val:h})=>l?u:u.concat(h),[]),a=e.shiftTo(...s.map(i).filter(u=>u));return Vf(o,r(a))}};var Wf=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function br(...t){let e=t.reduce((n,i)=>n+i.source,"");return RegExp(`^${e}$`)}function vr(...t){return e=>t.reduce(([n,i,r],o)=>{let[s,a,u]=o(e,r);return[{...n,...s},a||i,u]},[{},null,1]).slice(0,2)}function kr(t,...e){if(t==null)return[null,null];for(let[n,i]of e){let r=n.exec(t);if(r)return i(r)}return[null,null]}function Hf(...t){return(e,n)=>{let i={},r;for(r=0;r<t.length;r++)i[t[r]]=$n(e[n+r]);return[i,null,n+r]}}var Zf=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Ly=`(?:${Zf.source}?(?:\\[(${Wf.source})\\])?)?`,nu=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Xf=RegExp(`${nu.source}${Ly}`),iu=RegExp(`(?:T${Xf.source})?`),$y=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Uy=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Ky=/(\d{4})-?(\d{3})/,zy=Hf("weekYear","weekNumber","weekDay"),Vy=Hf("year","ordinal"),Gy=/(\d{4})-(\d\d)-(\d\d)/,Jf=RegExp(`${nu.source} ?(?:${Zf.source}|(${Wf.source}))?`),Wy=RegExp(`(?: ${Jf.source})?`);function wr(t,e,n){let i=t[e];return de(i)?n:$n(i)}function Hy(t,e){return[{year:wr(t,e),month:wr(t,e+1,1),day:wr(t,e+2,1)},null,e+3]}function Tr(t,e){return[{hours:wr(t,e,0),minutes:wr(t,e+1,0),seconds:wr(t,e+2,0),milliseconds:_o(t[e+3])},null,e+4]}function wo(t,e){let n=!t[e]&&!t[e+1],i=Pi(t[e+1],t[e+2]),r=n?null:Ct.instance(i);return[{},r,e+3]}function bo(t,e){let n=t[e]?Ft.create(t[e]):null;return[{},n,e+1]}var Zy=RegExp(`^T?${nu.source}$`),Xy=/^-?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 Jy(t){let[e,n,i,r,o,s,a,u,l]=t,h=e[0]==="-",w=u&&u[0]==="-",v=(T,I=!1)=>T!==void 0&&(I||T&&h)?-T:T;return[{years:v(oi(n)),months:v(oi(i)),weeks:v(oi(r)),days:v(oi(o)),hours:v(oi(s)),minutes:v(oi(a)),seconds:v(oi(u),u==="-0"),milliseconds:v(_o(l),w)}]}var Yy={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 ru(t,e,n,i,r,o,s){let a={year:e.length===2?yo($n(e)):$n(e),month:Qc.indexOf(n)+1,day:$n(i),hour:$n(r),minute:$n(o)};return s&&(a.second=$n(s)),t&&(a.weekday=t.length>3?eu.indexOf(t)+1:tu.indexOf(t)+1),a}var Qy=/^(?:(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 ew(t){let[,e,n,i,r,o,s,a,u,l,h,w]=t,v=ru(e,r,i,n,o,s,a),T;return u?T=Yy[u]:l?T=0:T=Pi(h,w),[v,new Ct(T)]}function tw(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var nw=/^(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$/,iw=/^(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$/,rw=/^(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 Gf(t){let[,e,n,i,r,o,s,a]=t;return[ru(e,r,i,n,o,s,a),Ct.utcInstance]}function ow(t){let[,e,n,i,r,o,s,a]=t;return[ru(e,a,n,i,r,o,s),Ct.utcInstance]}var sw=br($y,iu),aw=br(Uy,iu),cw=br(Ky,iu),uw=br(Xf),Yf=vr(Hy,Tr,wo,bo),lw=vr(zy,Tr,wo,bo),dw=vr(Vy,Tr,wo,bo),fw=vr(Tr,wo,bo);function Qf(t){return kr(t,[sw,Yf],[aw,lw],[cw,dw],[uw,fw])}function eh(t){return kr(tw(t),[Qy,ew])}function th(t){return kr(t,[nw,Gf],[iw,Gf],[rw,ow])}function nh(t){return kr(t,[Xy,Jy])}var hw=vr(Tr);function ih(t){return kr(t,[Zy,hw])}var mw=br(Gy,Wy),pw=br(Jf),gw=vr(Tr,wo,bo);function rh(t){return kr(t,[mw,Yf],[pw,gw])}var oh="Invalid Duration",ah={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}},_w={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},...ah},cn=146097/400,Cr=146097/4800,yw={years:{quarters:4,months:12,weeks:cn/7,days:cn,hours:cn*24,minutes:cn*24*60,seconds:cn*24*60*60,milliseconds:cn*24*60*60*1e3},quarters:{months:3,weeks:cn/28,days:cn/4,hours:cn*24/4,minutes:cn*24*60/4,seconds:cn*24*60*60/4,milliseconds:cn*24*60*60*1e3/4},months:{weeks:Cr/7,days:Cr,hours:Cr*24,minutes:Cr*24*60,seconds:Cr*24*60*60,milliseconds:Cr*24*60*60*1e3},...ah},Mi=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ww=Mi.slice(0).reverse();function si(t,e,n=!1){let i={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new Pe(i)}function ch(t,e){let n=e.milliseconds??0;for(let i of ww.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function sh(t,e){let n=ch(t,e)<0?-1:1;Mi.reduceRight((i,r)=>{if(de(e[r]))return i;if(i){let o=e[i]*n,s=t[r][i],a=Math.floor(o/s);e[r]+=a*n,e[i]-=a*s*n}return r},null),Mi.reduce((i,r)=>{if(de(e[r]))return i;if(i){let o=e[i]%1;e[i]-=o,e[r]+=o*t[i][r]}return r},null)}function bw(t){let e={};for(let[n,i]of Object.entries(t))i!==0&&(e[n]=i);return e}var Pe=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,i=n?yw:_w;e.matrix&&(i=e.matrix),this.values=e.values,this.loc=e.loc||xe.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=i,this.isLuxonDuration=!0}static fromMillis(e,n){return t.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new bt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:yr(e,t.normalizeUnit),loc:xe.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(In(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new bt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[i]=nh(e);return i?t.fromObject(i,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){let[i]=ih(e);return i?t.fromObject(i,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the Duration is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new As(i);return new t({invalid:i})}static normalizeUnit(e){let n={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(!n)throw new hr(e);return n}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,n={}){let i={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?At.create(this.loc,i).formatDurationFromString(this,e):oh}toHuman(e={}){if(!this.isValid)return oh;let n=Mi.map(i=>{let r=this.values[i];return de(r)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:i.slice(0,-1)}).format(r)}).filter(i=>i);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}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+=pr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},be.fromMillis(n,{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?ch(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e),i={};for(let r of Mi)(ri(n.values,r)||ri(this.values,r))&&(i[r]=n.get(r)+this.get(r));return si(this,{values:i},!0)}minus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let n={};for(let i of Object.keys(this.values))n[i]=Yc(e(this.values[i],i));return si(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...yr(e,t.normalizeUnit)};return si(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:i,matrix:r}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:i};return si(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return sh(this.matrix,e),si(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=bw(this.normalize().shiftToAll().toObject());return si(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 n={},i={},r=this.toObject(),o;for(let s of Mi)if(e.indexOf(s)>=0){o=s;let a=0;for(let l in i)a+=this.matrix[l][s]*i[l],i[l]=0;In(r[s])&&(a+=r[s]);let u=Math.trunc(a);n[s]=u,i[s]=(a*1e3-u*1e3)/1e3}else In(r[s])&&(i[s]=r[s]);for(let s in i)i[s]!==0&&(n[o]+=s===o?i[s]:i[s]/this.matrix[o][s]);return sh(this.matrix,n),si(this,{values:n},!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 n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return si(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 n(i,r){return i===void 0||i===0?r===void 0||r===0:i===r}for(let i of Mi)if(!n(this.values[i],e.values[i]))return!1;return!0}};var Sr="Invalid Interval";function vw(t,e){return!t||!t.isValid?Un.invalid("missing or invalid start"):!e||!e.isValid?Un.invalid("missing or invalid end"):e<t?Un.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 Un=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the Interval is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new Ss(i);return new t({invalid:i})}static fromDateTimes(e,n){let i=Ar(e),r=Ar(n),o=vw(i,r);return o??new t({start:i,end:r})}static after(e,n){let i=Pe.fromDurationLike(n),r=Ar(e);return t.fromDateTimes(r,r.plus(i))}static before(e,n){let i=Pe.fromDurationLike(n),r=Ar(e);return t.fromDateTimes(r.minus(i),r)}static fromISO(e,n){let[i,r]=(e||"").split("/",2);if(i&&r){let o,s;try{o=be.fromISO(i,n),s=o.isValid}catch{s=!1}let a,u;try{a=be.fromISO(r,n),u=a.isValid}catch{u=!1}if(s&&u)return t.fromDateTimes(o,a);if(s){let l=Pe.fromISO(r,n);if(l.isValid)return t.after(o,l)}else if(u){let l=Pe.fromISO(i,n);if(l.isValid)return t.before(a,l)}}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",n){if(!this.isValid)return NaN;let i=this.start.startOf(e,n),r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:i.locale}):r=this.end,r=r.startOf(e,n),Math.floor(r.diff(i,e).get(e))+(r.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:n}={}){return this.isValid?t.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];let n=e.map(Ar).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),i=[],{s:r}=this,o=0;for(;r<this.e;){let s=n[o]||this.e,a=+s>+this.e?this.e:s;i.push(t.fromDateTimes(r,a)),r=a,o+=1}return i}splitBy(e){let n=Pe.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:i}=this,r=1,o,s=[];for(;i<this.e;){let a=this.start.plus(n.mapUnits(u=>u*r));o=+a>+this.e?this.e:a,s.push(t.fromDateTimes(i,o)),i=o,r+=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 n=this.s>e.s?this.s:e.s,i=this.e<e.e?this.e:e.e;return n>=i?null:t.fromDateTimes(n,i)}union(e){if(!this.isValid)return this;let n=this.s<e.s?this.s:e.s,i=this.e>e.e?this.e:e.e;return t.fromDateTimes(n,i)}static merge(e){let[n,i]=e.sort((r,o)=>r.s-o.s).reduce(([r,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[r,o.union(s)]:[r.concat([o]),s]:[r,s],[[],null]);return i&&n.push(i),n}static xor(e){let n=null,i=0,r=[],o=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((u,l)=>u.time-l.time);for(let u of a)i+=u.type==="s"?1:-1,i===1?n=u.time:(n&&+n!=+u.time&&r.push(t.fromDateTimes(n,u.time)),n=null);return t.merge(r)}difference(...e){return t.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Sr}[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=ei,n={}){return this.isValid?At.create(this.s.loc.clone(n),e).formatInterval(this):Sr}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Sr}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Sr}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Sr}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:Sr}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):Pe.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var Kn=class{static hasDST(e=Ce.defaultZone){let n=be.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Ft.isValidZone(e)}static normalizeZone(e){return wn(e,Ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||xe.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||xe.create(n,i,o)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||xe.create(n,i,o)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||xe.create(n,i,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||xe.create(n,i,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return xe.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return xe.create(n,null,"gregory").eras(e)}static features(){return{relative:Es(),localeWeek:Ms()}}};function uh(t,e){let n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),i=n(e)-n(t);return Math.floor(Pe.fromMillis(i).as("days"))}function kw(t,e,n){let i=[["years",(u,l)=>l.year-u.year],["quarters",(u,l)=>l.quarter-u.quarter+(l.year-u.year)*4],["months",(u,l)=>l.month-u.month+(l.year-u.year)*12],["weeks",(u,l)=>{let h=uh(u,l);return(h-h%7)/7}],["days",uh]],r={},o=t,s,a;for(let[u,l]of i)n.indexOf(u)>=0&&(s=u,r[u]=l(t,e),a=o.plus(r),a>e?(r[u]--,t=o.plus(r),t>e&&(a=t,r[u]--,t=o.plus(r))):t=a);return[t,r,a,s]}function lh(t,e,n,i){let[r,o,s,a]=kw(t,e,n),u=e-r,l=n.filter(w=>["hours","minutes","seconds","milliseconds"].indexOf(w)>=0);l.length===0&&(s<e&&(s=r.plus({[a]:1})),s!==r&&(o[a]=(o[a]||0)+u/(s-r)));let h=Pe.fromObject(o,i);return l.length>0?Pe.fromMillis(u,i).shiftTo(...l).plus(h):h}var ou={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"},dh={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]},Tw=ou.hanidec.replace(/[\[|\]]/g,"").split("");function fh(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(t[n].search(ou.hanidec)!==-1)e+=Tw.indexOf(t[n]);else for(let r in dh){let[o,s]=dh[r];i>=o&&i<=s&&(e+=i-o)}}return parseInt(e,10)}else return e}function un({numberingSystem:t},e=""){return new RegExp(`${ou[t||"latn"]}${e}`)}var Cw="missing Intl.DateTimeFormat.formatToParts support";function Se(t,e=n=>n){return{regex:t,deser:([n])=>e(fh(n))}}var Sw="\xA0",ph=`[ ${Sw}]`,gh=new RegExp(ph,"g");function Aw(t){return t.replace(/\./g,"\\.?").replace(gh,ph)}function hh(t){return t.replace(/\./g,"").replace(gh," ").toLowerCase()}function bn(t,e){return t===null?null:{regex:RegExp(t.map(Aw).join("|")),deser:([n])=>t.findIndex(i=>hh(n)===hh(i))+e}}function mh(t,e){return{regex:t,deser:([,n,i])=>Pi(n,i),groups:e}}function Fs(t){return{regex:t,deser:([e])=>e}}function xw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Iw(t,e){let n=un(e),i=un(e,"{2}"),r=un(e,"{3}"),o=un(e,"{4}"),s=un(e,"{6}"),a=un(e,"{1,2}"),u=un(e,"{1,3}"),l=un(e,"{1,6}"),h=un(e,"{1,9}"),w=un(e,"{2,4}"),v=un(e,"{4,6}"),T=P=>({regex:RegExp(xw(P.val)),deser:([O])=>O,literal:!0}),x=(P=>{if(t.literal)return T(P);switch(P.val){case"G":return bn(e.eras("short"),0);case"GG":return bn(e.eras("long"),0);case"y":return Se(l);case"yy":return Se(w,yo);case"yyyy":return Se(o);case"yyyyy":return Se(v);case"yyyyyy":return Se(s);case"M":return Se(a);case"MM":return Se(i);case"MMM":return bn(e.months("short",!0),1);case"MMMM":return bn(e.months("long",!0),1);case"L":return Se(a);case"LL":return Se(i);case"LLL":return bn(e.months("short",!1),1);case"LLLL":return bn(e.months("long",!1),1);case"d":return Se(a);case"dd":return Se(i);case"o":return Se(u);case"ooo":return Se(r);case"HH":return Se(i);case"H":return Se(a);case"hh":return Se(i);case"h":return Se(a);case"mm":return Se(i);case"m":return Se(a);case"q":return Se(a);case"qq":return Se(i);case"s":return Se(a);case"ss":return Se(i);case"S":return Se(u);case"SSS":return Se(r);case"u":return Fs(h);case"uu":return Fs(a);case"uuu":return Se(n);case"a":return bn(e.meridiems(),0);case"kkkk":return Se(o);case"kk":return Se(w,yo);case"W":return Se(a);case"WW":return Se(i);case"E":case"c":return Se(n);case"EEE":return bn(e.weekdays("short",!1),1);case"EEEE":return bn(e.weekdays("long",!1),1);case"ccc":return bn(e.weekdays("short",!0),1);case"cccc":return bn(e.weekdays("long",!0),1);case"Z":case"ZZ":return mh(new RegExp(`([+-]${a.source})(?::(${i.source}))?`),2);case"ZZZ":return mh(new RegExp(`([+-]${a.source})(${i.source})?`),2);case"z":return Fs(/[a-z_+-/]{1,256}?/i);case" ":return Fs(/[^\S\n\r]/);default:return T(P)}})(t)||{invalidReason:Cw};return x.token=t,x}var Ow={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 Pw(t,e,n){let{type:i,value:r}=t;if(i==="literal"){let u=/^\s+$/.test(r);return{literal:!u,val:u?" ":r}}let o=e[i],s=i;i==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=n.hour12?"hour12":"hour24");let a=Ow[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Dw(t){return[`^${t.map(n=>n.regex).reduce((n,i)=>`${n}(${i.source})`,"")}$`,t]}function Ew(t,e,n){let i=t.match(e);if(i){let r={},o=1;for(let s in n)if(ri(n,s)){let a=n[s],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(i.slice(o,o+u))),o+=u}return[i,r]}else return[i,{}]}function Mw(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}},n=null,i;return de(t.z)||(n=Ft.create(t.z)),de(t.Z)||(n||(n=new Ct(t.Z)),i=t.Z),de(t.q)||(t.M=(t.q-1)*3+1),de(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),de(t.u)||(t.S=_o(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),n,i]}var su=null;function Bw(){return su||(su=be.fromMillis(1555555555555)),su}function jw(t,e){if(t.literal)return t;let n=At.macroTokenToFormatOpts(t.val),i=uu(n,e);return i==null||i.includes(void 0)?t:i}function au(t,e){return Array.prototype.concat(...t.map(n=>jw(n,e)))}function cu(t,e,n){let i=au(At.parseFormat(n),t),r=i.map(s=>Iw(s,t)),o=r.find(s=>s.invalidReason);if(o)return{input:e,tokens:i,invalidReason:o.invalidReason};{let[s,a]=Dw(r),u=RegExp(s,"i"),[l,h]=Ew(e,u,a),[w,v,T]=h?Mw(h):[null,null,void 0];if(ri(h,"a")&&ri(h,"H"))throw new gn("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:i,regex:u,rawMatches:l,matches:h,result:w,zone:v,specificOffset:T}}}function _h(t,e,n){let{result:i,zone:r,specificOffset:o,invalidReason:s}=cu(t,e,n);return[i,r,o,s]}function uu(t,e){if(!t)return null;let i=At.create(e,t).dtFormatter(Bw()),r=i.formatToParts(),o=i.resolvedOptions();return r.map(s=>Pw(s,t,o))}var lu="Invalid DateTime",yh=864e13;function Rs(t){return new St("unsupported zone",`the zone "${t.name}" is not supported`)}function du(t){return t.weekData===null&&(t.weekData=mo(t.c)),t.weekData}function fu(t){return t.localWeekData===null&&(t.localWeekData=mo(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Bi(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new be({...n,...e,old:n})}function Sh(t,e,n){let i=t-e*60*1e3,r=n.offset(i);if(e===r)return[i,e];i-=(r-e)*60*1e3;let o=n.offset(i);return r===o?[i,r]:[t-Math.min(r,o)*60*1e3,Math.max(r,o)]}function qs(t,e){t+=e*60*1e3;let n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function $s(t,e,n){return Sh(mr(t),e,n)}function wh(t,e){let n=t.o,i=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:i,month:r,day:Math.min(t.c.day,_r(i,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=Pe.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"),a=mr(o),[u,l]=Sh(a,n,t.zone);return s!==0&&(u+=s,l=t.zone.offset(u)),{ts:u,o:l}}function vo(t,e,n,i,r,o){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let u=e||a,l=be.fromObject(t,{...n,zone:u,specificOffset:o});return s?l:l.setZone(a)}else return be.invalid(new St("unparsable",`the input "${r}" can't be parsed as ${i}`))}function Ls(t,e,n=!0){return t.isValid?At.create(xe.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function hu(t,e){let n=t.c.year>9999||t.c.year<0,i="";return n&&t.c.year>=0&&(i+="+"),i+=Le(t.c.year,n?6:4),e?(i+="-",i+=Le(t.c.month),i+="-",i+=Le(t.c.day)):(i+=Le(t.c.month),i+=Le(t.c.day)),i}function bh(t,e,n,i,r,o){let s=Le(t.c.hour);return e?(s+=":",s+=Le(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=Le(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=Le(t.c.second),(t.c.millisecond!==0||!i)&&(s+=".",s+=Le(t.c.millisecond,3))),r&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Le(Math.trunc(-t.o/60)),s+=":",s+=Le(Math.trunc(-t.o%60))):(s+="+",s+=Le(Math.trunc(t.o/60)),s+=":",s+=Le(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var Ah={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Fw={ordinal:1,hour:0,minute:0,second:0,millisecond:0},xh=["year","month","day","hour","minute","second","millisecond"],Rw=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],qw=["year","ordinal","hour","minute","second","millisecond"];function Lw(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 hr(t);return e}function vh(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Lw(t)}}function kh(t,e){let n=wn(e.zone,Ce.defaultZone),i=xe.fromObject(e),r=Ce.now(),o,s;if(de(t.year))o=r;else{for(let l of xh)de(t[l])&&(t[l]=Ah[l]);let a=Zc(t)||Xc(t);if(a)return be.invalid(a);let u=n.offset(r);[o,s]=$s(t,u,n)}return new be({ts:o,zone:n,loc:i,o:s})}function Th(t,e,n){let i=de(n.round)?!0:n.round,r=(s,a)=>(s=pr(s,i||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(s,a)),o=s=>n.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(n.unit)return r(o(n.unit),n.unit);for(let s of n.units){let a=o(s);if(Math.abs(a)>=1)return r(a,s)}return r(t>e?-0:0,n.units[n.units.length-1])}function Ch(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}var be=class t{constructor(e){let n=e.zone||Ce.defaultZone,i=e.invalid||(Number.isNaN(e.ts)?new St("invalid input"):null)||(n.isValid?null:Rs(n));this.ts=de(e.ts)?Ce.now():e.ts;let r=null,o=null;if(!i)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,o]=[e.old.c,e.old.o];else{let a=n.offset(this.ts);r=qs(this.ts,a),i=Number.isNaN(r.year)?new St("invalid input"):null,r=i?null:r,o=i?null:a}this._zone=n,this.loc=e.loc||xe.create(),this.invalid=i,this.weekData=null,this.localWeekData=null,this.c=r,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,n]=Ch(arguments),[i,r,o,s,a,u,l]=n;return kh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static utc(){let[e,n]=Ch(arguments),[i,r,o,s,a,u,l]=n;return e.zone=Ct.utcInstance,kh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,n={}){let i=Rf(e)?e.valueOf():NaN;if(Number.isNaN(i))return t.invalid("invalid input");let r=wn(n.zone,Ce.defaultZone);return r.isValid?new t({ts:i,zone:r,loc:xe.fromObject(n)}):t.invalid(Rs(r))}static fromMillis(e,n={}){if(In(e))return e<-yh||e>yh?t.invalid("Timestamp out of range"):new t({ts:e,zone:wn(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new bt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(In(e))return new t({ts:e*1e3,zone:wn(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new bt("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let i=wn(n.zone,Ce.defaultZone);if(!i.isValid)return t.invalid(Rs(i));let r=xe.fromObject(n),o=yr(e,vh),{minDaysInFirstWeek:s,startOfWeek:a}=Hc(o,r),u=Ce.now(),l=de(n.specificOffset)?i.offset(u):n.specificOffset,h=!de(o.ordinal),w=!de(o.year),v=!de(o.month)||!de(o.day),T=w||v,I=o.weekYear||o.weekNumber;if((T||h)&&I)throw new gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(v&&h)throw new gn("Can't mix ordinal dates with month/day");let x=I||o.weekday&&!T,P,O,E=qs(u,l);x?(P=Rw,O=Nw,E=mo(E,s,a)):h?(P=qw,O=Fw,E=Ns(E)):(P=xh,O=Ah);let B=!1;for(let F of P){let K=o[F];de(K)?B?o[F]=O[F]:o[F]=E[F]:B=!0}let $=x?jf(o,s,a):h?Nf(o):Zc(o),Z=$||Xc(o);if(Z)return t.invalid(Z);let H=x?Gc(o,s,a):h?Wc(o):o,[te,U]=$s(H,l,i),V=new t({ts:te,zone:i,o:U,loc:r});return o.weekday&&T&&e.weekday!==V.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${V.toISO()}`):V}static fromISO(e,n={}){let[i,r]=Qf(e);return vo(i,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[i,r]=eh(e);return vo(i,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[i,r]=th(e);return vo(i,r,n,"HTTP",n)}static fromFormat(e,n,i={}){if(de(e)||de(n))throw new bt("fromFormat requires an input string and a format");let{locale:r=null,numberingSystem:o=null}=i,s=xe.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0}),[a,u,l,h]=_h(s,e,n);return h?t.invalid(h):vo(a,u,i,`format ${n}`,e,l)}static fromString(e,n,i={}){return t.fromFormat(e,n,i)}static fromSQL(e,n={}){let[i,r]=rh(e);return vo(i,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new bt("need to specify a reason the DateTime is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new Cs(i);return new t({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let i=uu(e,xe.fromObject(n));return i?i.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return au(At.parseFormat(e),xe.fromObject(n)).map(r=>r.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?du(this).weekYear:NaN}get weekNumber(){return this.isValid?du(this).weekNumber:NaN}get weekday(){return this.isValid?du(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?fu(this).weekday:NaN}get localWeekNumber(){return this.isValid?fu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?fu(this).weekYear:NaN}get ordinal(){return this.isValid?Ns(this.c).ordinal:NaN}get monthShort(){return this.isValid?Kn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Kn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Kn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Kn.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,n=6e4,i=mr(this.c),r=this.zone.offset(i-e),o=this.zone.offset(i+e),s=this.zone.offset(i-r*n),a=this.zone.offset(i-o*n);if(s===a)return[this];let u=i-s*n,l=i-a*n,h=qs(u,s),w=qs(l,a);return h.hour===w.hour&&h.minute===w.minute&&h.second===w.second&&h.millisecond===w.millisecond?[Bi(this,{ts:u}),Bi(this,{ts:l})]:[this]}get isInLeapYear(){return Ei(this.year)}get daysInMonth(){return _r(this.year,this.month)}get daysInYear(){return this.isValid?ii(this.year):NaN}get weeksInWeekYear(){return this.isValid?Di(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Di(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:i,calendar:r}=At.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:i,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(Ct.instance(e),n)}toLocal(){return this.setZone(Ce.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:i=!1}={}){if(e=wn(e,Ce.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||i){let o=e.offset(this.ts),s=this.toObject();[r]=$s(s,o,e)}return Bi(this,{ts:r,zone:e})}else return t.invalid(Rs(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:i}={}){let r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:i});return Bi(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=yr(e,vh),{minDaysInFirstWeek:i,startOfWeek:r}=Hc(n,this.loc),o=!de(n.weekYear)||!de(n.weekNumber)||!de(n.weekday),s=!de(n.ordinal),a=!de(n.year),u=!de(n.month)||!de(n.day),l=a||u,h=n.weekYear||n.weekNumber;if((l||s)&&h)throw new gn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&s)throw new gn("Can't mix ordinal dates with month/day");let w;o?w=Gc({...mo(this.c,i,r),...n},i,r):de(n.ordinal)?(w={...this.toObject(),...n},de(n.day)&&(w.day=Math.min(_r(w.year,w.month),w.day))):w=Wc({...Ns(this.c),...n});let[v,T]=$s(w,this.o,this.zone);return Bi(this,{ts:v,o:T})}plus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e);return Bi(this,wh(this,n))}minus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e).negate();return Bi(this,wh(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let i={},r=Pe.normalizeUnit(e);switch(r){case"years":i.month=1;case"quarters":case"months":i.day=1;case"weeks":case"days":i.hour=0;case"hours":i.minute=0;case"minutes":i.second=0;case"seconds":i.millisecond=0;break;case"milliseconds":break}if(r==="weeks")if(n){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(i.weekNumber=this.weekNumber-1),i.weekday=o}else i.weekday=1;if(r==="quarters"){let o=Math.ceil(this.month/3);i.month=(o-1)*3+1}return this.set(i)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?At.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):lu}toLocaleString(e=ei,n={}){return this.isValid?At.create(this.loc.clone(n),e).formatDateTime(this):lu}toLocaleParts(e={}){return this.isValid?At.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:i=!1,includeOffset:r=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=hu(this,s);return a+="T",a+=bh(this,s,n,i,r,o),a}toISODate({format:e="extended"}={}){return this.isValid?hu(this,e==="extended"):null}toISOWeekDate(){return Ls(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:i=!0,includePrefix:r=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(r?"T":"")+bh(this,s==="extended",n,e,i,o):null}toRFC2822(){return Ls(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Ls(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?hu(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:i=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(i&&(r+=" "),n?r+="z":e&&(r+="ZZ")),Ls(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():lu}[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 n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",i={}){if(!this.isValid||!e.isValid)return Pe.invalid("created by diffing an invalid DateTime");let r={locale:this.locale,numberingSystem:this.numberingSystem,...i},o=qf(n).map(Pe.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,u=s?e:this,l=lh(a,u,o,r);return s?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?Un.fromDateTimes(this,e):this}hasSame(e,n,i){if(!this.isValid)return!1;let r=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(n,i)<=r&&r<=o.endOf(n,i)}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 n=e.base||t.fromObject({},{zone:this.zone}),i=e.padding?this<n?-e.padding:e.padding:0,r=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(r=e.unit,o=void 0),Th(n,this.plus(i),{...e,numeric:"always",units:r,unit:o})}toRelativeCalendar(e={}){return this.isValid?Th(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 bt("min requires all arguments be DateTimes");return Jc(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new bt("max requires all arguments be DateTimes");return Jc(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,i={}){let{locale:r=null,numberingSystem:o=null}=i,s=xe.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0});return cu(s,e,n)}static fromStringExplain(e,n,i={}){return t.fromFormatExplain(e,n,i)}static get DATE_SHORT(){return ei}static get DATE_MED(){return Gr}static get DATE_MED_WITH_WEEKDAY(){return Pc}static get DATE_FULL(){return Wr}static get DATE_HUGE(){return Hr}static get TIME_SIMPLE(){return Zr}static get TIME_WITH_SECONDS(){return Xr}static get TIME_WITH_SHORT_OFFSET(){return Jr}static get TIME_WITH_LONG_OFFSET(){return Yr}static get TIME_24_SIMPLE(){return Qr}static get TIME_24_WITH_SECONDS(){return eo}static get TIME_24_WITH_SHORT_OFFSET(){return to}static get TIME_24_WITH_LONG_OFFSET(){return no}static get DATETIME_SHORT(){return io}static get DATETIME_SHORT_WITH_SECONDS(){return ro}static get DATETIME_MED(){return oo}static get DATETIME_MED_WITH_SECONDS(){return so}static get DATETIME_MED_WITH_WEEKDAY(){return Dc}static get DATETIME_FULL(){return ao}static get DATETIME_FULL_WITH_SECONDS(){return co}static get DATETIME_HUGE(){return uo}static get DATETIME_HUGE_WITH_SECONDS(){return lo}};function Ar(t){if(be.isDateTime(t))return t;if(t&&t.valueOf&&In(t.valueOf()))return be.fromJSDate(t);if(t&&typeof t=="object")return be.fromObject(t);throw new bt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Mr=require("@mysten/sui.js/utils");var gi=require("@mysten/sui.js/utils");var Ip=ge(Uo(),1),Op=require("@msafe/sui3-utils"),Pp=require("@msafe/sui3-utils"),Dp=require("@msafe/sui3-utils"),Lu=require("@mysten/sui.js/bcs"),hi=require("@mysten/sui.js/utils"),Mp=require("@msafe/sui3-utils"),Er=require("@msafe/sui3-utils"),Bp=require("@msafe/sui3-utils"),Np=require("@msafe/sui3-utils"),Rp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/transactions"),$p=require("@msafe/sui3-utils"),Dr=require("@msafe/sui3-utils"),$u=require("@mysten/sui.js/bcs"),mi=require("@mysten/sui.js/utils"),Up=require("@mysten/sui.js/transactions"),zp=require("@mysten/sui.js/transactions"),Gp=require("@mysten/sui.js/transactions"),Zp=require("@mysten/sui.js/transactions"),Jp=require("@mysten/sui.js/transactions"),da=require("@msafe/sui3-utils"),Qp=require("@mysten/sui.js/transactions"),fa=require("@mysten/sui.js/utils"),lx=ge(Uo(),1),eg=require("@msafe/sui3-utils"),$i=require("@msafe/sui3-utils"),Uu=require("@mysten/sui.js/bcs"),pi=require("@mysten/sui.js/utils");var lb=ge(ke(),1);var Ri=require("@mysten/sui.js/client"),zh=require("@mysten/sui.js/keypairs/ed25519");function Ih(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function $w(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function mu(t,...e){if(!$w(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 pu(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 Oh(t,e){mu(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Us=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Uw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var zs=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),vn=(t,e)=>t<<32-e|t>>>e,Kw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Kw)throw new Error("Non little-endian hardware is not supported");function zw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function gu(t){if(typeof t=="string"&&(t=zw(t)),!Uw(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var Ks=class{clone(){return this._cloneInto()}},pA={}.toString;function Ph(t){let e=i=>t().update(gu(i)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Dh(t=32){if(Us&&typeof Us.getRandomValues=="function")return Us.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Vw(t,e,n,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,i);let r=BigInt(32),o=BigInt(4294967295),s=Number(n>>r&o),a=Number(n&o),u=i?4:0,l=i?0:4;t.setUint32(e+u,s,i),t.setUint32(e+l,a,i)}var Vs=class extends Ks{constructor(e,n,i,r){super(),this.blockLen=e,this.outputLen=n,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=zs(this.buffer)}update(e){pu(this);let{view:n,buffer:i,blockLen:r}=this;e=gu(e);let o=e.length;for(let s=0;s<o;){let a=Math.min(r-this.pos,o-s);if(a===r){let u=zs(e);for(;r<=o-s;s+=r)this.process(u,s);continue}i.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){pu(this),Oh(e,this),this.finished=!0;let{buffer:n,view:i,blockLen:r,isLE:o}=this,{pos:s}=this;n[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>r-s&&(this.process(i,0),s=0);for(let w=s;w<r;w++)n[w]=0;Vw(i,r-8,BigInt(this.length*8),o),this.process(i,0);let a=zs(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=u/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let w=0;w<l;w++)a.setUint32(4*w,h[w],o)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let i=e.slice(0,n);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:i,length:r,finished:o,destroyed:s,pos:a}=this;return e.length=r,e.pos=a,e.finished=o,e.destroyed=s,r%n&&e.buffer.set(i),e}};var Gw=(t,e,n)=>t&e^~t&n,Ww=(t,e,n)=>t&e^t&n^e&n,Hw=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]),ai=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ci=new Uint32Array(64),_u=class extends Vs{constructor(){super(64,32,8,!1),this.A=ai[0]|0,this.B=ai[1]|0,this.C=ai[2]|0,this.D=ai[3]|0,this.E=ai[4]|0,this.F=ai[5]|0,this.G=ai[6]|0,this.H=ai[7]|0}get(){let{A:e,B:n,C:i,D:r,E:o,F:s,G:a,H:u}=this;return[e,n,i,r,o,s,a,u]}set(e,n,i,r,o,s,a,u){this.A=e|0,this.B=n|0,this.C=i|0,this.D=r|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=u|0}process(e,n){for(let w=0;w<16;w++,n+=4)ci[w]=e.getUint32(n,!1);for(let w=16;w<64;w++){let v=ci[w-15],T=ci[w-2],I=vn(v,7)^vn(v,18)^v>>>3,x=vn(T,17)^vn(T,19)^T>>>10;ci[w]=x+ci[w-7]+I+ci[w-16]|0}let{A:i,B:r,C:o,D:s,E:a,F:u,G:l,H:h}=this;for(let w=0;w<64;w++){let v=vn(a,6)^vn(a,11)^vn(a,25),T=h+v+Gw(a,u,l)+Hw[w]+ci[w]|0,x=(vn(i,2)^vn(i,13)^vn(i,22))+Ww(i,r,o)|0;h=l,l=u,u=a,a=s+T|0,s=o,o=r,r=i,i=T+x|0}i=i+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,u=u+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(i,r,o,s,a,u,l,h)}roundClean(){ci.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Eh=Ph(()=>new _u);function ji(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function Gs(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Zw(...t){let e=o=>o,n=(o,s)=>a=>o(s(a)),i=t.map(o=>o.encode).reduceRight(n,e),r=t.map(o=>o.decode).reduce(n,e);return{encode:i,decode:r}}function Xw(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(n=>{if(n<0||n>=t.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${t.length})`);return t[n]})},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(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);let i=t.indexOf(n);if(i===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return i})}}}function Jw(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 n of e)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function Yw(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.encode: non-string input=${i}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.decode: non-string input=${r}`);let i=n.length;if(i*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;i>0&&n[i-1]===e;i--)if(!((i-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,i)}}}function yu(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let i=0,r=[],o=Array.from(t);for(o.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,a=!0;for(let u=i;u<o.length;u++){let l=o[u],h=e*s+l;if(!Number.isSafeInteger(h)||e*s/e!==s||h-l!==e*s)throw new Error("convertRadix: carry overflow");s=h%n;let w=Math.floor(h/n);if(o[u]=w,!Number.isSafeInteger(w)||w*n+s!==h)throw new Error("convertRadix: carry overflow");if(a)w?a=!1:i=u;else continue}if(r.push(s),a)break}for(let s=0;s<t.length-1&&t[s]===0;s++)r.push(0);return r.reverse()}var Mh=(t,e)=>e?Mh(e,t%e):t,Ws=(t,e)=>t+(e-Mh(t,e));function wu(t,e,n,i){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(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Ws(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ws(e,n)}`);let r=0,o=0,s=2**n-1,a=[];for(let u of t){if(u>=2**e)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(r=r<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=n;o-=n)a.push((r>>o-n&s)>>>0);r&=2**o-1}if(r=r<<n-o&s,!i&&o>=e)throw new Error("Excess padding");if(!i&&r)throw new Error(`Non-zero padding: ${r}`);return i&&o>0&&a.push(r>>>0),a}function Qw(t){return{encode:e=>{if(!Gs(e))throw new Error("radix.encode input should be Uint8Array");return yu(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(yu(e,t,2**8))}}}function eb(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ws(8,t)>32||Ws(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Gs(n))throw new Error("radix2.encode input should be Uint8Array");return wu(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(wu(n,t,8,e))}}}function tb(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(n){if(!Gs(n))throw new Error("checksum.encode: input should be Uint8Array");let i=e(n).slice(0,t),r=new Uint8Array(n.length+t);return r.set(n),r.set(i,n.length),r},decode(n){if(!Gs(n))throw new Error("checksum.decode: input should be Uint8Array");let i=n.slice(0,-t),r=e(i).slice(0,t),o=n.slice(-t);for(let s=0;s<t;s++)if(r[s]!==o[s])throw new Error("Invalid checksum");return i}}}var ko={alphabet:Xw,chain:Zw,checksum:tb,convertRadix:yu,convertRadix2:wu,radix:Qw,radix2:eb,join:Jw,padding:Yw};var nb=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function ib(t){mu(t,16,20,24,28,32)}function Bh(t,e=128){if(Ih(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return sb(Dh(e/8),t)}var rb=t=>{let e=8-t.length/4;return new Uint8Array([Eh(t)[0]>>e<<e])};function ob(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}`)}),ko.chain(ko.checksum(1,rb),ko.radix2(11,!0),ko.alphabet(t))}function sb(t,e){return ib(t),ob(e).encode(t).join(nb(e)?"\u3000":" ")}var jh=`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 vo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=new Set,yu=typeof process=="object"&&process?process:{},Fh=(t,e,n,i)=>{typeof yu.emitWarning=="function"?yu.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},Gs=globalThis.AbortController,jh=globalThis.AbortSignal;if(typeof Gs>"u"){jh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},Gs=class{constructor(){e()}signal=new jh;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let r of this.signal._onabort)r(i);this.signal.onabort?.(i)}}};let t=yu.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Fh("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 sb=t=>!Nh.has(t),EA=Symbol("type"),ui=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Rh=t=>ui(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ar:null:null,Ar=class extends Array{constructor(e){super(e),this.fill(0)}},wu=class t{heap;length;static#c=!1;static create(e){let n=Rh(e);if(!n)return[];t.#c=!0;let i=new t(e,n);return t.#c=!1,i}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ws=class t{#c;#d;#y;#m;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#p;#r;#n;#e;#u;#f;#a;#o;#g;#s;#k;#T;#_;#w;#S;#l;static unsafeExposeInternals(e){return{starts:e.#T,ttls:e.#_,sizes:e.#k,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,i,r,o)=>e.#E(n,i,r,o),moveToTail:n=>e.#I(n),indexes:n=>e.#b(n),rindexes:n=>e.#v(n),isStale:n=>e.#h(n)}}get max(){return this.#c}get maxSize(){return this.#d}get calculatedSize(){return this.#p}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#m}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:u,dispose:l,disposeAfter:h,noDisposeOnSet:w,noUpdateTTL:v,maxSize:T=0,maxEntrySize:I=0,sizeCalculation:x,fetchMethod:P,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:$,ignoreFetchAbort:Z}=e;if(n!==0&&!ui(n))throw new TypeError("max option must be a nonnegative integer");let H=n?Rh(n):Array;if(!H)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=T,this.maxEntrySize=I||this.#d,this.sizeCalculation=x,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(P!==void 0&&typeof P!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=P,this.#S=!!P,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new H(n),this.#f=new H(n),this.#a=0,this.#o=0,this.#g=wu.create(n),this.#i=0,this.#p=0,typeof l=="function"&&(this.#y=l),typeof h=="function"?(this.#m=h,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#w=!!this.#y,this.#l=!!this.#m,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!B,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#d!==0&&!ui(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!ui(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#R()}if(this.allowStale=!!u,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=ui(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!ui(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#c===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#d){let te="LRU_CACHE_UNBOUNDED";sb(te)&&(Nh.add(te),Fh("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",te,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#M(){let e=new Ar(this.#c),n=new Ar(this.#c);this.#_=e,this.#T=n,this.#B=(o,s,a=vo.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let u=setTimeout(()=>{this.#h(o)&&this.delete(this.#n[o])},s+1);u.unref&&u.unref()}},this.#A=o=>{n[o]=e[o]!==0?vo.now():0},this.#C=(o,s)=>{if(e[s]){let a=e[s],u=n[s];o.ttl=a,o.start=u,o.now=i||r();let l=o.now-u;o.remainingTTL=a-l}};let i=0,r=()=>{let o=vo.now();if(this.ttlResolution>0){i=o;let s=setTimeout(()=>i=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],u=n[s];if(a===0||u===0)return 1/0;let l=(i||r())-u;return a-l},this.#h=o=>e[o]!==0&&n[o]!==0&&(i||r())-n[o]>e[o]}#A=()=>{};#C=()=>{};#B=()=>{};#h=()=>!1;#R(){let e=new Ar(this.#c);this.#p=0,this.#k=e,this.#x=n=>{this.#p-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!ui(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!ui(r))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 r},this.#P=(n,i,r)=>{if(e[n]=i,this.#d){let o=this.#d-e[n];for(;this.#p>o;)this.#D(!0)}this.#p+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#p)}}#x=e=>{};#P=(e,n,i)=>{};#j=(e,n,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#a));)n=this.#f[n]}*#v({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#N(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#b()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#v()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#b())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,n={}){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&e(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(e,n=this){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}rforEach(e,n=this){for(let i of this.#v()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}purgeStale(){let e=!1;for(let n of this.#v({allowStale:!0}))this.#h(n)&&(this.delete(this.#n[n]),e=!0);return e}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let s={value:o};if(this.#_&&this.#T){s.ttl=this.#_[n];let a=vo.now()-this.#T[n];s.start=Math.floor(Date.now()-a)}this.#k&&(s.size=this.#k[n]),e.unshift([i,s])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let r=Date.now()-i.start;i.start=vo.now()-r}this.set(n,i.value,i)}}set(e,n,i={}){if(n===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:u}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,h=this.#j(e,n,i.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return u&&(u.set="miss",u.maxEntrySizeExceeded=!0),this.delete(e),this;let w=this.#i===0?void 0:this.#r.get(e);if(w===void 0)w=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[w]=e,this.#e[w]=n,this.#r.set(e,w),this.#u[this.#o]=w,this.#f[w]=this.#o,this.#o=w,this.#i++,this.#P(w,h,u),u&&(u.set="add"),l=!1;else{this.#I(w);let v=this.#e[w];if(n!==v){if(this.#S&&this.#t(v)?v.__abortController.abort(new Error("replaced")):s||(this.#w&&this.#y?.(v,e,"set"),this.#l&&this.#s?.push([v,e,"set"])),this.#x(w),this.#P(w,h,u),this.#e[w]=n,u){u.set="replace";let T=v&&this.#t(v)?v.__staleWhileFetching:v;T!==void 0&&(u.oldValue=T)}}else u&&(u.set="update")}if(r!==0&&!this.#_&&this.#M(),this.#_&&(l||this.#B(w,r,o),u&&this.#C(u,w)),!s&&this.#l&&this.#s){let v=this.#s,T;for(;T=v?.shift();)this.#m?.(...T)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#D(!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,n;for(;n=e?.shift();)this.#m?.(...n)}}}#D(e){let n=this.#a,i=this.#n[n],r=this.#e[n];return this.#S&&this.#t(r)?r.__abortController.abort(new Error("evicted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#x(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#g.push(n)),this.#i===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#u[n],this.#r.delete(i),this.#i--,n}has(e,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#r.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))r&&(r.has="stale",this.#C(r,o));else return i&&this.#A(o),r&&(r.has="hit",this.#C(r,o)),!0}else r&&(r.has="miss");return!1}peek(e,n={}){let{allowStale:i=this.allowStale}=n,r=this.#r.get(e);if(r!==void 0&&(i||!this.#h(r))){let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}}#E(e,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let s=new Gs,{signal:a}=i;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let u={signal:s.signal,options:i,context:r},l=(x,P=!1)=>{let{aborted:O}=s.signal,E=i.ignoreFetchAbort&&x!==void 0;if(i.status&&(O&&!P?(i.status.fetchAborted=!0,i.status.fetchError=s.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),O&&!E&&!P)return w(s.signal.reason);let B=T;return this.#e[n]===T&&(x===void 0?B.__staleWhileFetching?this.#e[n]=B.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,x,u.options))),x},h=x=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=x),w(x)),w=x=>{let{aborted:P}=s.signal,O=P&&i.allowStaleOnFetchAbort,E=O||i.allowStaleOnFetchRejection,B=E||i.noDeleteOnFetchRejection,$=T;if(this.#e[n]===T&&(!B||$.__staleWhileFetching===void 0?this.delete(e):O||(this.#e[n]=$.__staleWhileFetching)),E)return i.status&&$.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),$.__staleWhileFetching;if($.__returned===$)throw x},v=(x,P)=>{let O=this.#O?.(e,o,u);O&&O instanceof Promise&&O.then(E=>x(E),P),s.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(),i.allowStaleOnFetchAbort&&(x=E=>l(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let T=new Promise(v).then(l,h),I=Object.assign(T,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,I,{...u.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=I,I}#t(e){if(!this.#S)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Gs}async fetch(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:u=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:v=this.allowStaleOnFetchRejection,ignoreFetchAbort:T=this.ignoreFetchAbort,allowStaleOnFetchAbort:I=this.allowStaleOnFetchAbort,context:x,forceRefresh:P=!1,status:O,signal:E}=n;if(!this.#S)return O&&(O.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:O});let B={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:u,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:I,ignoreFetchAbort:T,status:O,signal:E},$=this.#r.get(e);if($===void 0){O&&(O.fetch="miss");let Z=this.#E(e,$,B,x);return Z.__returned=Z}else{let Z=this.#e[$];if(this.#t(Z)){let F=i&&Z.__staleWhileFetching!==void 0;return O&&(O.fetch="inflight",F&&(O.returnedStale=!0)),F?Z.__staleWhileFetching:Z.__returned=Z}let H=this.#h($);if(!P&&!H)return O&&(O.fetch="hit"),this.#I($),r&&this.#A($),O&&this.#C(O,$),Z;let te=this.#E(e,$,B,x),V=te.__staleWhileFetching!==void 0&&i;return O&&(O.fetch=H?"stale":"refresh",V&&H&&(O.returnedStale=!0)),V?te.__staleWhileFetching:te.__returned=te}}get(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let u=this.#e[a],l=this.#t(u);return s&&this.#C(s,a),this.#h(a)?(s&&(s.get="stale"),l?(s&&i&&u.__staleWhileFetching!==void 0&&(s.returnedStale=!0),i?u.__staleWhileFetching:void 0):(o||this.delete(e),s&&i&&(s.returnedStale=!0),i?u:void 0)):(s&&(s.get="hit"),l?u.__staleWhileFetching:(this.#I(a),r&&this.#A(a),u))}else s&&(s.get="miss")}#F(e,n){this.#f[n]=e,this.#u[e]=n}#I(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#f[e],this.#u[e]),this.#F(this.#o,e),this.#o=e)}delete(e){let n=!1;if(this.#i!==0){let i=this.#r.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.clear();else{this.#x(i);let r=this.#e[i];this.#t(r)?r.__abortController.abort(new Error("deleted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,e,"delete"),this.#l&&this.#s?.push([r,e,"delete"])),this.#r.delete(e),this.#n[i]=void 0,this.#e[i]=void 0,i===this.#o?this.#o=this.#f[i]:i===this.#a?this.#a=this.#u[i]:(this.#u[this.#f[i]]=this.#u[i],this.#f[this.#u[i]]=this.#f[i]),this.#i--,this.#g.push(i)}}if(this.#l&&this.#s?.length){let i=this.#s,r;for(;r=i?.shift();)this.#m?.(...r)}return n}clear(){for(let e of this.#v({allowStale:!0})){let n=this.#e[e];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#n[e];this.#w&&this.#y?.(n,i,"delete"),this.#l&&this.#s?.push([n,i,"delete"])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#_&&this.#T&&(this.#_.fill(0),this.#T.fill(0)),this.#k&&this.#k.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#p=0,this.#i=0,this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#m?.(...n)}}};var ae=ge(ke(),1);var Js=ge(qh(),1),Ni=require("@mysten/sui.js/utils"),Fi=require("@mysten/sui.js/transactions");var ko=ge(ke(),1),Wh=require("@mysten/sui.js/transactions"),Wt=ge(ke(),1);var li=ge(ke(),1),ln=ge(ke(),1);var So=ge(ke(),1);var Hh=require("@mysten/sui.js/utils"),Ys=require("@mysten/sui.js/transactions"),Qs=require("@mysten/sui.js/utils");var Su=ge(ke(),1),ab=Object.defineProperty,cb=(t,e,n)=>e in t?ab(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,On=(t,e,n)=>(cb(t,typeof e!="symbol"?e+"":e,n),n);var Hs=443636,Zs=-443636,ku="79226673515401279992447579055",Tu="4295048016",lb=14,db="59543866431248",fb="184467440737095516",hb="15793534762490258745",mb=class{generateMnemonic(t=24){return Mh(Bh,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return Kh.Ed25519Keypair.deriveKeypair(t,n)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:n=!1,addressIndex:i=0}=t;return`m/44'/784'/${e}'/${n?1:0}'/${i}'`}},Co=class{constructor(t){this.sdk=t,On(this,"_lru"),On(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new Ws({max:100}));if(r.has(t))return r.get(t);let s=await((i=this._fetching)[t]||(i[t]=e()));return delete this._fetching[t],r.set(t,s,{ttl:n}),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 pb(t){if("reference"in t)return t.reference;let e=Au(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Vh(t)}function ta(t){var e,n;return"objectId"in t?t.objectId:(n=(e=pb(t))==null?void 0:e.objectId)!=null?n:Gh(t)}function Pn(t){var e;return"fields"in t?t.fields:(e=zh(t))==null?void 0:e.fields}function zh(t){let e="data"in t?Au(t):t;if(!(!e||!gb(e)||e.content.dataType!=="moveObject"))return e.content}function gb(t){return t.content!==void 0}function Au(t){return t.data}function Vh(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 Gh(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function _b(t){return t.data!==void 0}function yb(t){var e;let n=_b(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":ea(t):n?.type}function ea(t){var e;return(e=zh(t))==null?void 0:e.type}function wb(t){var e;return(e=Au(t))==null?void 0:e.owner}var To=async(t,e,n)=>{let r=e.length;if(r>50){let o=[],s=0,a=Math.ceil(r/50);for(s;s<a;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:n}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:n})},bb=class extends Co{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 To(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=Pn(i),o=ta(i),s=ea(i);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:r.fee,tickSpacing:r.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())}},Lh=new ae.default(2).pow(new ae.default(128)),vb=class{priceToSqrtPriceX64(t,e,n){return new ae.default(new N(t).mul(N.pow(10,n-e)).sqrt().mul(N.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new N(t.toString()).mul(N.pow(2,-64)).pow(2).mul(N.pow(10,e-n))}priceToTickIndex(t,e,n){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,n))}sqrtPriceX64ToTickIndex(t){if(t.gt(new ae.default(ku))||t.lt(new ae.default(Tu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new ae.default(e-64),i=this.signedShiftLeft(n,32,128),r=new ae.default("8000000000000000","hex"),o=0,s=new ae.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ae.default(0))&&o<lb;){a=a.mul(a);let T=a.shrn(127);a=a.shrn(63+T.toNumber()),s=s.add(r.mul(T)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ae.default(db)),w=this.signedShiftRight(h.sub(new ae.default(fb)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(hb)),64,128).toNumber();return w==v?w:this.tickIndexToSqrtPriceX64(v).lte(t)?v:w}tickIndexToSqrtPriceX64(t){return t>0?new ae.default(this.tickIndexToSqrtPricePositive(t)):new ae.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,n){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,n)}toX64_Decimal(t){return t.mul(N.pow(2,64))}fromX64_Decimal(t){return t.mul(N.pow(2,-64))}scaleDown(t,e){return new N(t).div(N.pow(10,e)).toString()}scaleUp(t,e){return new N(t).mul(N.pow(10,e)).toString()}bitsToNumber(t,e=32){return Js.default.toNumber(Js.default.asIntN(e,Js.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Lh).sub(e).mod(Lh)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new ae.default("79232123823359799118286999567"):e=new ae.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new ae.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new ae.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new ae.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new ae.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new ae.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new ae.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new ae.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new ae.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new ae.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new ae.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new ae.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new ae.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new ae.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new ae.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new ae.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new ae.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new ae.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new ae.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),n;return e&1?n=new ae.default("18445821805675392311"):n=new ae.default("18446744073709551616"),e&2&&(n=this.signedShiftRight(n.mul(new ae.default("18444899583751176498")),64,256)),e&4&&(n=this.signedShiftRight(n.mul(new ae.default("18443055278223354162")),64,256)),e&8&&(n=this.signedShiftRight(n.mul(new ae.default("18439367220385604838")),64,256)),e&16&&(n=this.signedShiftRight(n.mul(new ae.default("18431993317065449817")),64,256)),e&32&&(n=this.signedShiftRight(n.mul(new ae.default("18417254355718160513")),64,256)),e&64&&(n=this.signedShiftRight(n.mul(new ae.default("18387811781193591352")),64,256)),e&128&&(n=this.signedShiftRight(n.mul(new ae.default("18329067761203520168")),64,256)),e&256&&(n=this.signedShiftRight(n.mul(new ae.default("18212142134806087854")),64,256)),e&512&&(n=this.signedShiftRight(n.mul(new ae.default("17980523815641551639")),64,256)),e&1024&&(n=this.signedShiftRight(n.mul(new ae.default("17526086738831147013")),64,256)),e&2048&&(n=this.signedShiftRight(n.mul(new ae.default("16651378430235024244")),64,256)),e&4096&&(n=this.signedShiftRight(n.mul(new ae.default("15030750278693429944")),64,256)),e&8192&&(n=this.signedShiftRight(n.mul(new ae.default("12247334978882834399")),64,256)),e&16384&&(n=this.signedShiftRight(n.mul(new ae.default("8131365268884726200")),64,256)),e&32768&&(n=this.signedShiftRight(n.mul(new ae.default("3584323654723342297")),64,256)),e&65536&&(n=this.signedShiftRight(n.mul(new ae.default("696457651847595233")),64,256)),e&131072&&(n=this.signedShiftRight(n.mul(new ae.default("26294789957452057")),64,256)),e&262144&&(n=this.signedShiftRight(n.mul(new ae.default("37481735321082")),64,256)),n}signedShiftLeft(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}signedShiftRight(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}},Cu=(t,e)=>{let n=ta(t);if(Vh(t))throw new Error(`${e}(${n}) had been deleted`);if(Gh(t))throw new Error(`${e}(${n}) is not found`);return!0},xr=60*1e3,kb=class extends Co{async getPools(t=!1){let e=await this.contract.getConfig(),n=[],i;do i=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:i?.nextCursor,limit:15}),n.push(...i.data.map(a=>a.objectId));while(i.hasNextPage);if(!n.length)return[];let o=(await To(this.provider,n,{showContent:!0})).map(a=>Pn(a).value.fields.pool_id);if(!o.length)return[];let s=await To(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>Pn(a).unlocked)),s.map(a=>this.parsePool(a))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Cu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:n,tickLower:i,tickUpper:r,sqrtPrice:o,slippage:s,coinTypeA:a,coinTypeB:u}=t,l=await this.contract.getConfig(),h=new N(t.amountA),w=new N(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,w)]),I=t.txb||new Fi.TransactionBlock,x=v.length>0?this.coin.convertTradeCoins(I,v,a,h):[this.coin.zero(a,I)],P=T.length>0?this.coin.convertTradeCoins(I,T,u,w):[this.coin.zero(u,I)];return I.moveCall({target:`${l.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[a,u,e.type],arguments:[I.object(l.PoolConfig),I.object(e.objectId),I.pure(o,"u128"),I.object(l.Positions),I.makeMoveVec({objects:x}),I.makeMoveVec({objects:P}),I.pure(Math.abs(i).toFixed(0),"u32"),I.pure(i<0,"bool"),I.pure(Math.abs(r).toFixed(0),"u32"),I.pure(r<0,"bool"),I.pure(h.toFixed(0),"u64"),I.pure(w.toFixed(0),"u64"),I.pure(this.getMinimumAmountBySlippage(h,s),"u64"),I.pure(this.getMinimumAmountBySlippage(w,s),"u64"),I.pure(n,"address"),I.pure(Date.now()+xr,"u64"),I.object(Ni.SUI_CLOCK_OBJECT_ID),I.object(l.Versioned)]}),I}async addLiquidity(t){let{address:e,tickLower:n,tickUpper:i,slippage:r,pool:o}=t,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(o),[u,l]=a,[h,w]=await Promise.all([this.coin.getMetadata(u),this.coin.getMetadata(l)]);if(!h||!w)throw new Error("Invalid coin type");let v=new N(t.amountA),T=new N(t.amountB),[I,x]=await Promise.all([this.coin.selectTradeCoins(e,u,v),this.coin.selectTradeCoins(e,l,T)]),P=t.txb||new Fi.TransactionBlock,O=I.length>0?this.coin.convertTradeCoins(P,I,u,v):[this.coin.zero(u,P)],E=x.length>0?this.coin.convertTradeCoins(P,x,l,T):[this.coin.zero(l,P)];return P.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:a,arguments:[P.object(o),P.object(s.Positions),P.makeMoveVec({objects:O}),P.makeMoveVec({objects:E}),P.pure(Math.abs(n).toFixed(0),"u32"),P.pure(n<0,"bool"),P.pure(Math.abs(i).toFixed(0),"u32"),P.pure(i<0,"bool"),P.pure(v.toFixed(0),"u64"),P.pure(T.toFixed(0),"u64"),P.pure(this.getMinimumAmountBySlippage(v,r),"u64"),P.pure(this.getMinimumAmountBySlippage(T,r),"u64"),P.pure(e,"address"),P.pure(Date.now()+xr,"u64"),P.object(Ni.SUI_CLOCK_OBJECT_ID),P.object(s.Versioned)]}),P}async increaseLiquidity(t){let{pool:e,slippage:n,address:i,nft:r}=t,o=await this.contract.getConfig(),s=new N(t.amountA),a=new N(t.amountB),u=await this.getPoolTypeArguments(e),[l,h]=u,[w,v]=await Promise.all([this.coin.selectTradeCoins(i,l,s),this.coin.selectTradeCoins(i,h,a)]),T=t.txb||new Fi.TransactionBlock,I=w.length>0?this.coin.convertTradeCoins(T,w,l,s):[this.coin.zero(l,T)],x=v.length>0?this.coin.convertTradeCoins(T,v,h,a):[this.coin.zero(h,T)];return T.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:u,arguments:[T.object(e),T.object(o.Positions),T.makeMoveVec({objects:I}),T.makeMoveVec({objects:x}),T.object(r),T.pure(s.toFixed(0),"u64"),T.pure(a.toFixed(0),"u64"),T.pure(this.getMinimumAmountBySlippage(s,n),"u64"),T.pure(this.getMinimumAmountBySlippage(a,n),"u64"),T.pure(Date.now()+xr*3,"u64"),T.object(Ni.SUI_CLOCK_OBJECT_ID),T.object(o.Versioned)]}),T}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new N(t.amountA),s=new N(t.amountB),a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(i),l=t.txb||new Fi.TransactionBlock;return l.moveCall({target:`${a.PackageId}::position_manager::decrease_liquidity`,typeArguments:u,arguments:[l.object(i),l.object(a.Positions),l.object(n),l.pure(new ko.default(r).toString(),"u128"),l.pure(this.getMinimumAmountBySlippage(o,e),"u64"),l.pure(this.getMinimumAmountBySlippage(s,e),"u64"),l.pure(Date.now()+xr*3,"u64"),l.object(Ni.SUI_CLOCK_OBJECT_ID),l.object(a.Versioned)]}),l}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:n,address:i,collectAmountA:r,collectAmountB:o}=t,s=t.txb||new Fi.TransactionBlock;if(Number(r)===0&&Number(o)===0)return s;let a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return s.moveCall({target:`${a.PackageId}::position_manager::collect`,typeArguments:u,arguments:[s.object(e),s.object(a.Positions),s.object(n),s.pure(r,"u64"),s.pure(o,"u64"),s.pure(i),s.pure(Date.now()+xr*3,"u64"),s.object(Ni.SUI_CLOCK_OBJECT_ID),s.object(a.Versioned)]}),s}async collectReward(t){let{pool:e,nft:n,rewardAmounts:i,address:r}=t,o=t.txb||new Fi.TransactionBlock,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((l,h)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...a,l.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(n),o.object(l.fields.vault),o.pure(h,"u64"),o.pure(i[h],"u64"),o.pure(r),o.pure(Date.now()+xr*3,"u64"),o.object(Ni.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new N((t.liquidity||new ko.default(1e8)).toString()),n=new N(t.currentSqrtPrice.toString()),i=new N(t.lowerSqrtPrice.toString()),r=new N(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(i)).div(i.mul(r)),s=new N(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(n)).div(n.mul(r)),s=this.math.fromX64_Decimal(e.mul(n.sub(i)))):(o=new N(0),s=this.math.fromX64_Decimal(e.mul(r.sub(i))));let a=t.ceil!==!1?"ceil":"floor";return[new ko.default(o[a]().toString()),new ko.default(s[a]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var n;let i=((n=t.replace(">","").split("<")[1])==null?void 0:n.split(/,\s*/))||[];if(e!==void 0&&e!==i.length)throw new Error("Invalid pool type");return i}async getFixedLiquidity(t){var e,n;let{coinTypeA:i,coinTypeB:r,amountA:o,amountB:s}=t,[a,u]=await Promise.all([this.coin.getMetadata(i),this.coin.getMetadata(r)]),l=new N(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),h=new N(this.math.scaleDown(s,u.decimals)).mul((n=t.priceB)!=null?n:1);return{liquidityA:l.toString(),liquidityB:h.toString(),liquidity:l.plus(h).toString()}}parsePool(t){let e=Pn(t),n=ta(t),i=yb(t),r=this.parsePoolType(i,3);return this.getCacheOrSet("pool-type-"+n,async()=>r),{...e,objectId:n,type:i,types:r}}getMinimumAmountBySlippage(t,e){let n=new N(t),i=new N(1).minus(new N(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},Tb=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new li.default(n.fee_growth_global_a),a=new li.default(i.fee_growth_inside_a),u=new li.default(i.tokens_owed_a),l=new li.default(n.fee_growth_global_b),h=new li.default(i.fee_growth_inside_b),w=new li.default(i.tokens_owed_b),v=new li.default(i.liquidity),T,I,x,P,O=t.bitsToNumber(n.tick_current_index.fields.bits),E=t.bitsToNumber(i.tick_lower_index.fields.bits),B=t.bitsToNumber(i.tick_upper_index.fields.bits);O<E?(T=t.subUnderflowU128(s,r.feeGrowthOutsideA),I=t.subUnderflowU128(l,r.feeGrowthOutsideB)):(T=r.feeGrowthOutsideA,I=r.feeGrowthOutsideB),O<B?(x=o.feeGrowthOutsideA,P=o.feeGrowthOutsideB):(x=t.subUnderflowU128(s,o.feeGrowthOutsideA),P=t.subUnderflowU128(l,o.feeGrowthOutsideB));let $=t.subUnderflowU128(t.subUnderflowU128(s,T),x),Z=t.subUnderflowU128(t.subUnderflowU128(l,I),P),H=t.subUnderflowU128($,a).mul(v).shrn(64),te=t.subUnderflowU128(Z,h).mul(v).shrn(64);return{feeOwedA:u.add(H).toString(),feeOwedB:w.add(te).toString()}},$h=new So.default(0),Uh=new So.default(1),Cb=new So.default(2),Sb={mul(t,e,n){let i=t.mul(e);if(this.isOverLimit(i,n))throw new Error(`Mul result higher than u${n}`);return i},mulDiv(t,e,n,i){return this.mulDivRoundUpIf(t,e,n,!1,i)},mulDivRoundUpIf(t,e,n,i,r){if(n.eq($h))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt($h)?s.add(Uh):s},isOverLimit(t,e){let n=Cb.pow(new So.default(e)).sub(Uh);return t.gt(n)}},Ab=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,w=new ln.default(new N(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),T=(h??new ln.default(Date.now()).div(new ln.default(1e3))).sub(new ln.default(w)),I=[],x=new ln.default(s.liquidity),P=new ln.default(a.liquidity);for(let O=0;O<3;++O){let E=s.reward_infos[O],B={emissionsPerSecondX64:new ln.default(E?E.fields.emissions_per_second:"0"),growthGlobalX64:new ln.default(E?E.fields.growth_global:"0")},$={growthInsideCheckpoint:new ln.default((i=(n=a.reward_infos[O])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new ln.default((o=(r=a.reward_infos[O])==null?void 0:r.fields.amount_owed)!=null?o:"0")},Z=B.growthGlobalX64;if(!x.isZero()){let C=Sb.mulDiv(T,B.emissionsPerSecondX64,x,128);Z=B.growthGlobalX64.add(C)}let H=u.rewardGrowthsOutside[O],te=l.rewardGrowthsOutside[O],U=Z;u.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_lower_index.fields.bits)?t.subUnderflowU128(Z,H):H);let V=new ln.default(0);l.initialized&&(V=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_upper_index.fields.bits)?te:t.subUnderflowU128(Z,te));let F=t.subUnderflowU128(t.subUnderflowU128(Z,U),V),K=$.amountOwed.shln(64);I[O]=K.add(t.subUnderflowU128(F,$.growthInsideCheckpoint).mul(P)).shrn(64).toString()}return I},xb=class extends Co{async getOwner(t){let e=await this.getObject(t),n=wb(e);if(!(!n||typeof n=="string")){if("ObjectOwner"in n)return n.ObjectOwner;if("AddressOwner"in n)return n.AddressOwner}}async getFields(t){let e=await this.getObject(t);return Pn(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return Pn(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Cu(e,"position"),Pn(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=Pn(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new Wt.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Wt.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new Wt.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Wt.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new Wt.default(r))}}async getPositionAPR(t){let{poolId:e,getPrice:n,fees24h:i,tickLower:r,tickUpper:o}=t,s=await this.pool.getPool(e),a=this.math.bitsToNumber(s.tick_current_index.fields.bits),[u,l,h,w]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),n(s.types[0]),n(s.types[1])]);if(!h||!w||r>=o||a<r||a>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:v,minTokenB:T}=this.getRemoveLiquidityQuote(s,r,o),I=new N(this.math.scaleDown(v.toString(),u.decimals)).mul(h),x=new N(this.math.scaleDown(T.toString(),l.decimals)).mul(w),P=I.add(x),O=P.isZero()?new N(0):new N(i).mul(365).div(P).mul(100),E=new N(0);return await Promise.all(s.reward_infos.map(async B=>{let{emissions_per_second:$}=B.fields,Z=this.coin.formatCoinType(B.fields.vault_coin_type),[H,te]=await Promise.all([n(Z),this.coin.getMetadata(Z)]);!$||$==="0"||!H||(E=E.add(new N(new Wt.default($).shrn(64).toString()).div(10**te.decimals).mul(31536e3).mul(H).div(P).mul(100)))})),{fees:O.toString(),rewards:E.toString(),total:O.plus(E).toString()}}getRemoveLiquidityQuote(t,e,n){let i=new Wt.default(0),r=new Wt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),a=this.math.tickIndexToSqrtPriceX64(n);if(o<e){let l=this.getTokenAFromLiquidity(r,s,a);return{minTokenA:this.adjustForSlippage(l),minTokenB:i}}if(o<n){let l=new Wt.default(t.sqrt_price),h=this.getTokenAFromLiquidity(r,l,a),w=this.getTokenBFromLiquidity(r,s,l);return{minTokenA:this.adjustForSlippage(h),minTokenB:this.adjustForSlippage(w)}}let u=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(u)}}adjustForSlippage(t){let e={numerator:new Wt.default(0),denominator:new Wt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,n){let i=t.mul(n.sub(e)).shln(64),r=n.mul(e);return i.div(r)}getTokenBFromLiquidity(t,e,n){return t.mul(n.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:n}=t,i=t.txb||new Wh.TransactionBlock,r=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return i.moveCall({target:`${r.PackageId}::position_manager::burn`,typeArguments:o,arguments:[i.object(r.Positions),i.object(n),i.object(r.Versioned)]}),i}async getPositionLiquidityUSD(t){let{position:e,poolId:n,priceA:i,priceB:r}=t,o=await this.pool.getPool(n),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Wt.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 Wt.default(e.liquidity===void 0?1e8:e.liquidity)}),[a,u]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),l=new N(s[0].toString()).div(10**a.decimals).mul(i||0),h=new N(s[1].toString()).div(10**u.decimals).mul(r||0);return l.plus(h).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:n}=t,[i,r,o]=await Promise.all([this.pool.getPool(n),this.nft.getPositionTick(n,e.tick_lower_index),this.nft.getPositionTick(n,e.tick_upper_index)]),s={...t,pool:i,tickLowerDetail:r,tickUpperDetail:o},[a,u]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:l,...h}=a,{unclaimedRewards:w,...v}=u;return{fees:a.unclaimedFees.toString(),rewards:w.toString(),total:l.plus(w).toString(),fields:{...h,...v}}}async getUnclaimedFees(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,[s,a,u,l]=await Promise.all([this.coin.getMetadata(n.types[0]),this.coin.getMetadata(n.types[1]),i(n.types[0]),i(n.types[1])]),h=Tb(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),w=this.math.scaleDown(h.feeOwedA,s.decimals),v=this.math.scaleDown(h.feeOwedB,a.decimals);function T(P,O){return new N(1e6).mul(N.pow(10,O)).lt(P)}T(w,s.decimals)&&(w="0",h.feeOwedA="0"),T(v,a.decimals)&&(v="0",h.feeOwedB="0");let I=u===void 0?new N(0):new N(u).mul(w),x=l===void 0?new N(0):new N(l).mul(v);return{unclaimedFees:I.plus(x),scaledFeeOwedA:w,scaledFeeOwedB:v,...h}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=Ab(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),a=[...s],u=n.reward_infos.map(v=>this.coin.formatCoinType(v.fields.vault_coin_type)),l=await Promise.all([...n.reward_infos.map((v,T)=>this.coin.getMetadata(u[T]))]),h=await Promise.all(n.reward_infos.map((v,T)=>i(u[T])));l.forEach((v,T)=>{a[T]=this.math.scaleDown(a[T],v.decimals)});let w=new N(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(w=w.plus(new N(I).mul(a[T])),!1):(w=w.plus(1),!0)}),{unclaimedRewards:w,collectRewards:s,scaledCollectRewards:a}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return Cu(e,"nft"),e})}},Ib=class extends Co{isSUI(t){return(0,Hh.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,n){if(n.eq(0))return[];let i=[],r=[],o=new N(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),i.push(...s.data);while(s.hasNextPage);i.sort((a,u)=>Number(u.balance)-Number(a.balance));for(let a of i)if(r.push(a.coinObjectId),o=o.add(a.balance),o.gte(n))break;return r}convertTradeCoins(t,e,n,i){return this.isSUI(n)?[t.splitCoins(t.gas,[t.pure(i.toNumber())])[0]]:e.map(r=>t.object(r))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let i=t.replace(/^0x/i,"");return i=i.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&i.length<64&&t!=="2::sui:SUI"?"0".repeat(64-i.length):"")+i}},Ob=60*1e3,Xs=100,Pb=class extends Co{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new N(t.amountA),a=new N(t.amountB),u=await this.contract.getConfig(),l=await Promise.all(t.routes.map(async x=>{let P=await this.pool.getPoolTypeArguments(x.pool),[O,E]=await Promise.all([this.coin.getMetadata(P[0]),this.coin.getMetadata(P[1])]);return{...x,coinA:O,coinB:E,typeArguments:P}})),h=await this.coin.selectTradeCoins(i,e,s),{functionName:w,typeArguments:v}=this.getFunctionNameAndTypeArguments(l.map(({typeArguments:x})=>x),e,n),T=l.map(({nextTickIndex:x,coinA:P,coinB:O,a2b:E})=>{let B=this.math.tickIndexToPrice(x,P.decimals,O.decimals);return this.sqrtPriceWithSlippage(B,o,E,P.decimals,O.decimals)}),I=t.txb||new Ys.TransactionBlock;return I.moveCall({target:`${u.PackageId}::swap_router::${w}`,typeArguments:v,arguments:[...l.map(({pool:x})=>I.object(x)),I.makeMoveVec({objects:this.coin.convertTradeCoins(I,h,e,s)}),I.pure((r?s:a).toFixed(0),"u64"),I.pure(this.amountOutWithSlippage(r?a:s,o,r),"u64"),...T.map(x=>I.pure(x,"u128")),I.pure(r,"bool"),I.pure(i,"address"),I.pure(Date.now()+Ob*3,"u64"),I.object(Qs.SUI_CLOCK_OBJECT_ID),I.object(u.Versioned)]}),I}async computeSwapResult(t){let{pools:e,amountSpecified:n,amountSpecifiedIsInput:i,address:r,tickStep:o}=t,s=await this.contract.getConfig(),a=e.map(w=>w.pool),u=await To(this.provider,a,{showContent:!0}),l=new Ys.TransactionBlock;u.map(async w=>{let v=Pn(w),T=e.find(E=>E.pool===v.id.id),I=this.math.bitsToNumber(v.tick_current_index.fields.bits),x=I-v.tick_spacing*(o||Xs),P=I+v.tick_spacing*(o||Xs);x=x<Zs?Zs:x,P=P>Hs?Hs:P;let O=this.pool.parsePoolType(ea(w));l.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:O,arguments:[l.object(v.id.id),l.pure(T.a2b,"bool"),l.pure(new N(n).toFixed(0),"u128"),l.pure(i,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(T.a2b?x:P).toString(),"u128"),l.object(Qs.SUI_CLOCK_OBJECT_ID),l.object(s.Versioned)]})});let h=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:r});if(h.error)throw new Error(h.error);return h.events.map(w=>w.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:n,address:i,tickStep:r}=t,o=await this.contract.getConfig(),s=e.map(h=>h.pool),a=await To(this.provider,Array.from(new Set(s)),{showContent:!0}),u=new Ys.TransactionBlock;e.forEach(async h=>{let w=a.find(O=>ta(O)===h.pool),v=Pn(w),T=this.math.bitsToNumber(v.tick_current_index.fields.bits),I=T-v.tick_spacing*(r||Xs),x=T+v.tick_spacing*(r||Xs);I=I<Zs?Zs:I,x=x>Hs?Hs:x;let P=this.pool.parsePoolType(ea(w));u.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:P,arguments:[u.object(v.id.id),u.pure(h.a2b,"bool"),u.pure(new N(h.amountSpecified).toFixed(0),"u128"),u.pure(n,"bool"),u.pure(this.math.tickIndexToSqrtPriceX64(h.a2b?I:x).toString(),"u128"),u.object(Qs.SUI_CLOCK_OBJECT_ID),u.object(o.Versioned)]})});let l=await this.provider.devInspectTransactionBlock({transactionBlock:u,sender:i});if(l.error)throw new Error(l.error);return l.events.map(h=>h.parsedJson)}getFunctionNameAndTypeArguments(t,e,n){let i=[],r=["swap"];if(t.length===1)i=t[0],e===i[0]?r.push("a","b"):r.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(r.push("a","b"),i.push(o[0],o[2],o[1])):(r.push("b","a"),i.push(o[1],o[2],o[0])),i.push(s[2],n),n===s[0]?r.push("c","b"):r.push("b","c")}return{functionName:r.join("_"),typeArguments:i}}amountOutWithSlippage(t,e,n){if(n){let r=new N(100).minus(e).div(100);return new N(t).mul(r).toFixed(0)}let i=new N(100).plus(e).div(100);return new N(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new N(t).mul(n?new N(100).minus(e).div(100):new N(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,i,r);return s.lt(new Su.BN(Tu))?Tu:s.gt(new Su.BN(ku))?ku:s.toString()}},Rt=class{constructor(t,e){this.network=t,On(this,"pool"),On(this,"contract"),On(this,"math",new vb),On(this,"account",new mb),On(this,"coin"),On(this,"nft"),On(this,"trade"),On(this,"provider"),this.provider=e?e instanceof Ri.SuiClient?e:new Ri.SuiClient(e):new Ri.SuiClient({url:t==="mainnet"?(0,Ri.getFullnodeUrl)("mainnet"):(0,Ri.getFullnodeUrl)("testnet")}),this.contract=new bb(this),this.pool=new kb(this),this.nft=new xb(this),this.coin=new Ib(this),this.trade=new Pb(this)}};var Db=Object.defineProperty,bm=(t,e)=>{for(var n in e)Db(t,n,{get:e[n],enumerable:!0})},ve=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,km.default)(this.data))}},Uu={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"},tn={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Dn=new sr(Uu),Eb=async(t,e,n)=>(console.log("getAddLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Mb=async(t,e,n)=>(console.log("getIncreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Bb=async(t,e,n)=>(console.log("getRemoveLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.closePositionTransactionPayload(t?.parameter)),jb=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.removeLiquidityTransactionPayload(t?.parameter)),Nb=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Rewarder.collectRewarderTransactionPayload(t?.parameter)),Fb=class Tm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Eb(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Tm(e)}},Rb=class Cm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Nb(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new Cm(e)}},qb=class Sm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await jb(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Sm(e)}},qt=new sr(Uu),Lb=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.openPositionAddLiquidityStakePaylod(t?.parameter)),$b=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.addLiquidityFixCoinPayload(t?.parameter)),Ub=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.removeLiquidityPayload(t?.parameter)),Kb=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.removeLiquidityPayload(t?.parameter)),zb=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.claimFeeAndClmmReward(t?.parameter)),Am=async(t,e,n)=>(console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.batchHarvestPayload(t?.parameter)),Vb=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.depositPayload(t?.parameter)),Gb=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.withdrawPayload(t?.parameter)),Wb=class xm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Lb(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new xm(e)}},Hb=class Im extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Am(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Im(e)}},Zb=class Om extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await zb(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new Om(e)}},Xb=class Pm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Ub(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Pm(e)}},Jb=class Dm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Am(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new Dm(e)}},Yb=class Em extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await $b(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Em(e)}},Qb=class Mm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Kb(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Mm(e)}},ev=class Bm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Vb(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new Bm(e)}},tv=class jm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Gb(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new jm(e)}},nv=class Nm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Mb(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Nm(e)}},iv=class Fm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Bb(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Fm(e)}},En=new sr(Uu),rv=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.convertPayload(t?.parameter)),ov=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemLockPayload(t?.parameter)),sv=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemDividendV2Payload(t.parameter.venft_id,t.parameter.bonus_types,t.parameter.xTokenType)),av=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.cancelRedeemPayload(t?.parameter)),cv=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemPayload(t?.parameter)),uv=class Rm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await av(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Rm(e)}},lv=class qm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await sv(r,n,i);return console.log("XcetusClaimingStakeRewardsIntention build txb: ",o),o}static fromData(e){return new qm(e)}},dv=class Lm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await rv(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new Lm(e)}},fv=class $m extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await cv(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new $m(e)}},hv=class Um extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await ov(r,n,i);return console.log("XcetusRedeemLockIntention build txb: ",o),o}static fromData(e){return new Um(e)}},mv=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:vm.TransactionType.Other,txSubType:n,intentionData:{txbParams:e,action:n}}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"OpenAndAddLiquidity":i=Fb.fromData(t.intentionData);break;case"IncreaseLiquidity":i=nv.fromData(t.intentionData);break;case"DecreaseLiquidity":i=qb.fromData(t.intentionData);break;case"RemoveLiquidity":i=iv.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=Rb.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=Wb.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=Yb.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=Xb.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=Qb.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=Zb.fromData(t.intentionData);break;case"FarmingHarvest":i=Jb.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=Hb.fromData(t.intentionData);break;case"FarmingStake":i=ev.fromData(t.intentionData);break;case"FarmingUnstake":i=tv.fromData(t.intentionData);break;case"xCETUSConvert":i=dv.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=hv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=lv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=uv.fromData(t.intentionData);break;case"xCETUSRedeem":i=fv.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},zm={};bm(zm,{contractId:()=>Wm,default:()=>pv,feeObjId:()=>Xm,roleObjId:()=>Hm,status:()=>Gm,transaction:()=>Vm,upgradeCapObjId:()=>Jm,vaultObjId:()=>Zm});var Vm="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Gm="success",Wm="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Hm="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Zm="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Xm="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Jm="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",pv={transaction:Vm,status:Gm,contractId:Wm,roleObjId:Hm,vaultObjId:Zm,feeObjId:Xm,upgradeCapObjId:Jm},Ym={};bm(Ym,{contractId:()=>tp,default:()=>gv,feeObjId:()=>rp,roleObjId:()=>np,status:()=>ep,transaction:()=>Qm,upgradeCapObjId:()=>op,vaultObjId:()=>ip});var Qm="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ep="success",tp="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",np="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",ip="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",rp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",op="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",gv={transaction:Qm,status:ep,contractId:tp,roleObjId:np,vaultObjId:ip,feeObjId:rp,upgradeCapObjId:op},_v="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",yv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",wv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",bv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",vv="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",kv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Tv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Cv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Zh=zm,Xh=Ym,Sv=new Map([["dev",{env:"dev",rpc:{url:_v},backend:{url:vv},contract:Zh}],["stg",{env:"stg",rpc:{url:yv},backend:{url:kv},contract:Zh}],["prev",{env:"prev",rpc:{url:wv},backend:{url:Tv},contract:Xh}],["prod",{env:"prod",rpc:{url:bv},backend:{url:Cv},contract:Xh}]]);function Av(t,e){let n=Sv.get(t);if(!n)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(n.rpc=e.rpc),e&&e.backend&&(n.backend=e.backend),e&&e.contract&&(n.contract=e.contract),n}var nn=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:i,context:r}=n;i?super(`[MPay] ${e}: ${i}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}},xv=class extends nn{constructor(){super(11,"Backend is not specified")}},Iv=class extends nn{constructor(){super(1,"Wallet not connected")}},xu=class extends nn{constructor(t,e){super(10,t,{context:e})}},Ov=class Li{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof zn.AxiosError)throw new xu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new xu(e.data.code)}throw new xu(e.status.toString())}async getIncomingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return Li.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{sender:e,...n});return Li.parseResponseData(i)}async getStreamHistory(e){let n=await zn.default.post(`${this.apiURL}/stream-events`,e),i=Li.parseResponseData(n);return i.data.forEach(r=>{let o=r;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}),i}async getAllCoinTypes(e){let n=await zn.default.post(`${this.apiURL}/stream-info`,{address:e});return Li.parseResponseData(n)}async getAllRecipients(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return Li.parseResponseData(i)}async getAllSenders(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return Li.parseResponseData(i)}},ap=class cp{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new sp.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Ov(e.backend.url))}static new(e,n){let i=Av(e,n);return new cp(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new xv;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 Iv;return this.signer}async walletAddress(){return this.wallet.address()}},Jh=50n,Iu=10000n,Pv=25n,Yh=100000000n,qi=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Qh=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},sa=class up{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(n,i){if(i in n)return Reflect.get(n,i);let r=s=>new up(n.result[s]);if(i===Symbol.iterator)return function*(){let s=0;for(;;)yield r(s),s++};if(typeof i=="symbol")return;let o=parseInt(i,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}},em=class extends nn{constructor(t,e){super(3,t,{context:e})}},Dv=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 n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="address")throw new em("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,lp.normalizeSuiAddress)(Eu.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new em("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Eu.Buffer.from(n).readBigInt64LE()}},en=class extends nn{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},dp={groupId:"string",name:"string"},Ev=64;function Mv(t){return fp(t),Ku.bcs.ser(dp,t).toString("base64")}function Mu(t){let e=Ku.bcs.de(dp,t,"base64");return fp(e),e}function fp(t){if(!tm(t.name))throw new en("Invalid metadata: Name contains unknown character");if(!tm(t.groupId))throw new en("Invalid metadata: Group ID contains unknown character");if(t.name.length>Ev)throw new en("Invalid metadata: Name exceed max length 64")}function tm(t){return/^[\x00-\x7F]+$/.test(t)}function hp(t,e){return(0,Oo.normalizeStructTag)(t)===(0,Oo.normalizeStructTag)(e)}function Ir(t,e){return(0,Oo.normalizeStructTag)(t)===(0,Oo.normalizeStructTag)(e)}var mp="txn.gas";function Bv(){return _f()}var Bu=class pp{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:Mv({name:e.name,groupId:Bv()}),coinType:(0,Io.normalizeStructTag)(e.coinType),recipients:e.recipients.map(n=>({address:n.address,cliffAmount:n.cliffAmount,amountPerEpoch:n.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let n=new Du.TransactionBlock,i=this.calculateFeesInternal(e),r=this.getCreateStreamCoinRequests(e,i),o=await this.wallet.requestCoins(r),s=await this.addMergeCoins(n,o[0]),a;r.length>1?a=await this.addMergeCoins(n,o[1]):a=s;for(let u=0;u<e.recipients.length;u++){let l=e.recipients[u],h=this.amountForRecipient(l,e.numberEpoch),w=this.getStreamFeeLocal(h),[v]=n.splitCoins(s,[n.pure(h+w,"u64")]),[T]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new sa(v),flatFeeCoin:new sa(T),metadata:e.metadata,recipient:l.address,timeStart:e.startTime,cliff:l.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return n}calculateCreateStreamFees(e){let n=pp.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Jh,denominator:Iu},claimFeePercent:{numerator:Pv,denominator:Iu},flatFeePerStream:Yh}}async addMergeCoins(e,n){let i;return n.mergedCoins&&n.mergedCoins.length?(e.mergeCoins(e.object(n.primaryCoin),n.mergedCoins.map(r=>e.object(r))),i=e.object(n.primaryCoin)):n.primaryCoin===mp?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return hp(i,Io.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Io.SUI_TYPE_ARG,amount:n.flatFeeAmount}]}calculateFeesInternal(e){let n=e.recipients.reduce((i,r)=>{let o=this.amountForRecipient(r,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:i.totalAmount+o,streamFeeAmount:i.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...n}}amountForRecipient(e,n){return BigInt(e.amountPerEpoch)*BigInt(n)+BigInt(e.cliffAmount)}get flatSuiFee(){return Yh}getStreamFeeLocal(e){return e*Jh/Iu}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new Du.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new Dv(i).getU64()}get wallet(){return this.globals.wallet}},jv="0x0000000000000000000000000000000000000000000000000000000000000006",gp=class{constructor(t,e,n){this.moduleName=t,this.config=e,this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(ju.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof Qh?i.moveArgs(t):i instanceof qi?i.moveArg(t):i instanceof sa?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(ju.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof Qh?r.moveArgs(t):r instanceof qi?r.moveArg(t):r instanceof sa?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new qi(t):t}vaultObject(){return new qi(this.config.vaultObjId)}roleObject(){return new qi(this.config.roleObjId)}feeObject(){return new qi(this.config.feeObjId)}clockObject(){return new qi(jv)}},_p=class di extends gp{constructor(e,n){super(di.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_flat_fee,arguments:[i,r,n],typeArgs:[]})}setClaimFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:di.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:di.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:di.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},ca=class Bt extends gp{constructor(e,n){super(Bt.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.feeObject(),r=this.vaultObject(),o=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),a=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.create_stream,arguments:[i,r,o,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,a],typeArgs:[n.coinType]})}setAutoClaim(e,n){let i=this.makeObject(n.streamId);return this.addContractCall(e,{method:Bt.MethodName.set_auto_claim,arguments:[i,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.cancel_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.claim_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let i=this.makeObject(n.streamId),r=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.claim_stream_by_proxy}`}},yp=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new _p(e,t),this.streamContract=new ca(e,t)}feeContract;streamContract;async createStreams(t){let e=Bu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Bu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new Ao.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Ao.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Ao.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Ao.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},kn=class extends nn{constructor(t,e={}){super(0,t,e)}};async function Nv(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Fv=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)}},wp=class{constructor(t){this.requester=t,this.pager=new Fv(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]}},Rv=class extends nn{constructor(t,e,n){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:n}}),this.coinType=t,this.requestAmount=e,this.gotAmount=n}},qv=25;async function Lv(t,e,n,i="0x2::sui::SUI",r=qv){let o=new $v(t,e,i,r),s=BigInt(0),a=[];for(;await o.hasNext()&&s<n;){let u=await o.next();u&&(a.push(u),s+=BigInt(u.balance))}if(s<n)throw new Rv(i,n,s);return a}var $v=class extends wp{constructor(t,e,n,i){super(new Uv(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},Uv=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new kn("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}}},Kv=class extends nn{constructor(){super(7,"Connected wallet is not creator")}},nm=class extends nn{constructor(){super(8,"Connected wallet is not recipient")}},im=class extends nn{constructor(t,e){super(6,t,{context:e})}},zv=class extends nn{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},Vv=(1n<<64n)-1n,aa=1e3;function rm(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/aa);return be.fromMillis(n*aa)}function om(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/aa);return Pe.fromMillis(n*aa)}var zu=class fi{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new ca(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await fi.fetchStreamData(e,n);return new fi(e,n,i)}static fromObjectData(e,n,i){let r=fi.parseRawStreamData(n,i);return new fi(e,n,r)}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 fi.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new kn("Object Id does not align");this.rawData=fi.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 Kv;let e=new xo.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new nm;let e=new xo.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 nm;let n=new xo.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new xo.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,Po.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 om(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Mu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Mu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return rm(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return om(n)}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:rm((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===Vv?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=be.now().toMillis(),n=this.timeStart.toMillis();if(e<n)return-1n;let i=Math.floor((e-n)/Number(this.rawData.config.epochInterval));return BigInt(i)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(i)}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,n){let i=await e.suiClient.getObject({id:n,options:{showContent:!0,showType:!0}});return fi.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new zv(e):new im(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new im("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Po.parseStructTag)(i.type),o=(0,Po.normalizeStructTag)(r[0]),s=i.fields,a=s.config.fields,u=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(a.amount_per_epoch),cancelable:a.cancelable,cliff:BigInt(a.cliff),creator:a.creator,epochInterval:BigInt(a.epoch_interval),metadata:a.metadata,recipient:a.recipient,timeStart:BigInt(a.time_start),totalEpoch:BigInt(a.total_epoch)},status:{status:u.status,epochCanceled:BigInt(u.epoch_canceled),epochClaimed:BigInt(u.epoch_claimed)}}}},Gv=class extends nn{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},Wv=1e3,Hv=class{constructor(t){this.globals=t,this.coinMetaHelper=new Zv(t.suiClient),this.createStreamHelper=new yp(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Gv(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 en("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,i=(t.totalAmount-n)/t.steps,r={realTotalAmount:i*t.steps+n,cliffAmount:n,amountPerStep:i};return this.validateStreamAmount(r,t.totalAmount),r}calculateTimelineByInterval(t){if(t.steps===0n)throw new en("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new en("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(Pe.fromMillis(Number(e*t.steps))),i={timeStart:t.timeStart,timeEnd:n,interval:Pe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(i),i}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),i=await this.getCoinMeta(e);return{...n,coinType:(0,Dr.normalizeStructTag)(n.coinType),coinMeta:i}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(i=>this.getCoinMeta(i.coinType)));return e.map((i,r)=>({...i,coinType:(0,Dr.normalizeStructTag)(i.coinType),coinMeta:n[r]}))}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 en("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new en("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Wv)throw new en("Interval shall be at least 1 second","interval",t.interval)}},Zv=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Dr.normalizeStructTag)(t||Dr.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},Ou=class extends nn{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}},Xv=25;async function sm(t,e,n){let i=new bp(e),r=new vp(t,i,n);return await Nv(r)}var bp=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]}},vp=class extends wp{constructor(t,e,n){super(new Jv(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},Jv=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||Xv,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&t.push(i)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:i}=this;n=e.filter(r=>i?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}},Yv=class na{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new Ou("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new en("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await sm(e.suiClient,n);return i.forEach(r=>{if(!r)throw new kn("stream group object data undefined")}),na.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await na.parseGroupStreams(e,n,i);return new na(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{Qv(i,o)||(r=!1)}),r}async refresh(){let e=await sm(this.globals.suiClient,this.streams.map(n=>n.streamId));this.streams.forEach((n,i)=>{n.refreshWithData(e[i])})}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,n)=>e+n.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,n)=>e+n.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,n)=>n.nextReleaseAmount===null?e:e+n.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,n)=>e+n.totalAmount,0n),streamed:this.streams.reduce((e,n)=>e+n.streamedAmount,0n),claimed:this.streams.reduce((e,n)=>e+n.claimedAmount,0n),claimable:this.streams.reduce((e,n)=>e+n.claimable,0n),canceled:this.streams.reduce((e,n)=>e+n.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,n,i){let r=i.map((o,s)=>zu.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new Ou("Not same group ID");if(!this.checkStreamGroup(r))throw new Ou("Not same stream settings");return r}};function Qv(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 am=class Nu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await cm.newIncoming(e);return new Nu(n,e.pageSize)}static async newOutgoing(e){let n=await cm.newOutgoing(e);return new Nu(n,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}},cm=class Fu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await um.newIncomingQuery(e);return new Fu(n)}static async newOutgoing(e){let n=await um.newOutgoingQuery(e);return new Fu(n)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let n=await this.requester.doNextRequest();if(n===null)throw new kn("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new kn("No more results");return e}},um=class Ru{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new bp(i.flat().map(s=>s.streamId));this.objectIter=new vp(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=r1(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,gi.normalizeSuiAddress)(s.recipient)===(0,gi.normalizeSuiAddress)(i)),o=lm(r);return new Ru(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=o1(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=lm(r);return new Ru(e.globals,i,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let n=await n1(this.globals,e[0].streamId,this.objectIter);return this.current++,kp(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await i1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,t1(n,this.query)?n:this.doNextRequest()}throw new kn("Stream group with no stream")}};function lm(t){let e=new Map;return t.forEach(n=>{let i=e.get(n.groupId);i?(i.push(n),e.set(n.groupId,i)):e.set(n.groupId,[n])}),Array.from(e.values()).sort((n,i)=>be.fromISO(i[0].createDate).toMillis()-be.fromISO(n[0].createDate).toMillis())}function kp(t,e){if(e===void 0)return!0;let n=e1(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let i=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return n&&i}return n}function e1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function t1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{kp(i,e)&&(n=!0)}),n}async function n1(t,e,n){let i=await Tp(n,e);return zu.fromObjectData(t,e,i)}async function i1(t,e,n){let i=[];for(;i.length<e.length;){let r=await Tp(n,e[i.length]);i.push(r)}return Yv.newFromObjectResponse(t,e,i)}async function Tp(t,e){if(!await t.hasNext())throw new kn("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new kn("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new kn("stream id not aligned");return n}function r1(t){return{status:Vu(t?.status),coinType:Cp(t?.coinType),sender:Sp(t?.sender)}}function o1(t){return{status:Vu(t?.status),coinType:Cp(t?.coinType),recipient:Sp(t?.recipient)}}function Vu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=Vu(n);return!e||e===i?i:"all"},void 0):s1(t)}function s1(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new en("Unknown stream filtered status")}}function Cp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeStructTag)(e)):void 0:(0,gi.normalizeStructTag)(t)}function Sp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeSuiAddress)(e)):void 0:(0,gi.normalizeSuiAddress)(t)}var a1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},c1=class{constructor(t){this.account=t}async address(){return this.account.address}},u1=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(hp(t.coinType,$i.SUI_TYPE_ARG))return{primaryCoin:mp};if(t.amount<=0)throw new en("Invalid coin request","coinAmount",t.amount);let e=await Lv(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new kn("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},l1=class{globals;helper;constructor(t,e){this.globals=ap.new(t,e),this.helper=new Hv(this.globals)}connectSingleWallet(t){let e=new u1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new a1(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return zu.new(this.globals,t)}async getIncomingStreams(t,e=10){return am.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return am.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,$i.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,$i.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,$i.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new yp(this.globals)}},d1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Ap.default)(this.data))}},Do=class extends d1{application="mpay";getClient(t,e){let n=new l1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new c1(e)),n}},dm=class extends Do{constructor(t){super(t),this.data=t}txType=Km.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},fm=class extends Do{constructor(t){super(t),this.data=t}txType=xp.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},hm=class extends Do{constructor(t){super(t),this.data=t}txType=Ip.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},mm=class extends Do{constructor(t){super(t),this.data=t}txType=Op.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Pp=class ia{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return ia.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return ia.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,hi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return ia.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return qu.bcs.de(n,new Uint8Array(i))}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,hi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,hi.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,hi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,hi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return qu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,hi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},f1=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"&&Ir(e.target,this.contract.createStreamTarget));if(t.length===0)throw new kn("No create stream transactions");return t.map(e=>new Pp(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Mu(e),r=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),a=t.decodeInputU64(8),u=t.decodeInputU64(9),l=t.decodeInputU64(10),h=t.decodeInputBool(11),w=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:u,amountPerEpoch:l,cancelable:h,coinType:w}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new en("Stream group not have common info");let e=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 ca(this.globals.envConfig.contract,this.globals)}get feeContract(){return new _p(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Bu(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]}},h1=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new ca(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"&&Ir(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ir(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ir(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ir(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ir(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new f1(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 Pp(t,this.txb)}},pm=class extends Do{constructor(t){super(t),this.data=t}txType=Dp.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},m1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=ap.new(e==="sui:mainnet"?"prod":"dev"),r=new h1(i,n).decode(),o;switch(r.type){case"CreateStream":o=new mm(r.info);break;case"SetAutoClaim":o=new pm({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new hm({streamId:r.streamId});break;case"ClaimByProxy":o=new fm({streamId:r.streamId});break;case"Cancel":o=new dm({streamId:r.streamId});break;default:throw new Error(`Unknown transaction type: ${r}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new mm(e);break;case"Claim":n=new hm(e);break;case"ClaimByProxy":n=new fm(e);break;case"SetAutoClaim":n=new pm(e);break;case"Cancel":n=new dm(e);break;default:throw new Error("not implemented")}return n.build({...t})}},p1=class Mp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Ep.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Mp(e)}},g1=class jp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Bp.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new jp(e)}},_1=class Rp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=Fp.TransactionBlock.from(this.data.content);if(!(0,Np.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new Rp(e)}},y1=class{application;constructor(){this.application=Pr.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case Pr.TransactionSubTypes.assets.coin.send:i=p1.fromData(t.intentionData);break;case Pr.TransactionSubTypes.assets.object.send:i=g1.fromData(t.intentionData);break;case Pr.TransactionSubTypes.others.plain:i=_1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},w1={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"}}},ye=w1,b1=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(`${ye.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ye.pool).find(n=>n.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===`${ye.ProtocolPackage}::incentive_v2::claim_reward`){let n=new gm(e,this.txb),i=n.decodeInputU8(4),r=n.decodeInputU8(5),o=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(i),a=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:a,assetId:i,poolId:o})}}),console.log("decode claims",t),{txType:Or.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Or.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Or.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:Or.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Or.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ye.ProtocolPackage));return new gm(t,this.txb)}},gm=class ra{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return ra.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return ra.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,mi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return ra.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}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,mi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,mi.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,mi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,mi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,mi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function _m(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function v1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function k1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function ym(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function T1(t,e,n,i,r){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ye.IncentiveV2),t.object(n),t.object(ye.StorageId),t.pure(e),t.pure(i)],typeArguments:r}),t}var C1=class $p extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Lp.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;T1(n,r,o,s,a)}),n}static fromData(e){return new $p(e)}},S1=class Kp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new Up.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return k1(i,r,n)}static fromData(e){return new Kp(e)}};async function Vp(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var A1=class Gp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new zp.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return _m(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await Vp(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return _m(s,a,s.object(l),o)}static fromData(e){return new Gp(e)}},x1=class Hp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new Wp.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return ym(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await Vp(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return ym(s,a,s.object(l),o)}static fromData(e){return new Hp(e)}},I1=class Xp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new Zp.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return v1(i,r,n)}static fromData(e){return new Xp(e)}},O1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new b1(e).decode();return{txType:qp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=A1.fromData(t.intentionData);break;case"EntryBorrow":i=S1.fromData(t.intentionData);break;case"EntryRepay":i=x1.fromData(t.intentionData);break;case"EntryWithdraw":i=I1.fromData(t.intentionData);break;case"ClaimReward":i=C1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},P1="msafe-plain-tx",D1=ua.TransactionSubTypes.others.plain,E1=class{application;constructor(){this.application=P1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:ua.TransactionType.Other,txSubType:D1,intentionData:{content:(0,la.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=Jp.TransactionBlock.from((0,la.fromHEX)(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(r.effects.status.status!=="success")throw new Error(r.effects.status.error);return i}},M1=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}},Pu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},B1=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(`${Pu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Pu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Pu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),i=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(5),o=this.helper.decodeInputU32(7);return{txType:Qp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:r,tickUpper:o}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new j1(t,this.txb)}},j1=class oa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return oa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return oa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU32(e){let n=this.decodePureArg(e,"u32");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,pi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return oa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}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,pi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,pi.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,pi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,pi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,pi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},N1=class eg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:u,tickUpper:l,txb:h}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,txb:h})}static fromData(e){return new eg(e)}},F1=class tg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,nft:r,txb:o}=this.data;return n.nft.burn({pool:i,nft:r,txb:o})}static fromData(e){return new tg(e)}},R1=class ng extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,txb:u}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,txb:u})}static fromData(e){return new ng(e)}},q1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,txb:a}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,txb:a})}static fromData(e){return new ig(e)}},L1=class rg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{fee:i,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,amountA:w,amountB:v,txb:T}=this.data;return n.pool.createPool({fee:i,amountA:w,amountB:v,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,txb:T})}static fromData(e){return new rg(e)}},$1=class og extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,txb:h}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,txb:h})}static fromData(e){return new og(e)}},U1=class sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,txb:l}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,txb:l})}static fromData(e){return new sg(e)}},K1=class ag extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:l,nft:u,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T})}static fromData(e){return new ag(e)}},wm=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=new B1(e).decode();return{txType:Yp.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:i}=t,r;switch(t.txSubType){case"CreatePool":r=L1.fromData(t.intentionData);break;case"AddLiquidity":r=N1.fromData(t.intentionData);break;case"IncreaseLiquidity":r=U1.fromData(t.intentionData);break;case"DecreaseLiquidity":r=$1.fromData(t.intentionData);break;case"RemoveLiquidity":r=K1.fromData(t.intentionData);break;case"CollectFee":r=R1.fromData(t.intentionData);break;case"CollectReward":r=q1.fromData(t.intentionData);break;case"Burn":r=F1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},da=new M1([new y1,new O1,new wm,new m1,new E1,new mv,new wm]);var Ae=require("@msafe/sui3-utils"),el=require("@mysten/sui.js/transactions"),ya=require("@mysten/sui.js/utils");var cg=require("@mysten/sui.js/transactions"),z1=1000n,V1=120n,G1=100n,W1={multiplier:{numerator:V1,denominator:G1}};var fa=class{constructor(e){this.globals=e}async simulate(e,n=W1){let i=this.copyTransactionBlock(e.txb),{suiClient:r}=this.globals,o=await this.getGasPrice(n);i.setGasPrice(o);let s=await r.devInspectTransactionBlock({transactionBlock:i,sender:e.sender}),{gasUsed:a}=s.effects,u=this.toGasBudget(a,o),l=s.effects.status.status==="success",h;return l||(h=s.effects.status.error),{success:l,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:a,gasBudget:u,simulationError:h}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let n=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(n,e)}toGasBudget(e,n){let{computationCost:i,storageCost:r}=e,o=z1*n,s=BigInt(i)+o,a=s+BigInt(r);return a>s?a:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,n){if(this.isFixedValue(n))return n.fixedVal;if(this.isMultiplier(n)){let{multiplier:i}=n;return e*i.numerator/i.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return cg.TransactionBlock.from(e.serialize())}};var Gu=require("buffer");function ha(t){return Gu.Buffer.from(t,"utf-8")}function H1(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ma(t){return Uint8Array.from(Gu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ga=require("@mysten/sui.js/verify");var _i=require("@mysten/sui.js/utils");var pa=require("@mysten/sui.js/utils"),Eo=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,pa.normalizeStructTag)(e);if(this._coinMetaReg.has(n))return this._coinMetaReg.get(n);let i=await this.queryCoinMeta(n);return i&&this._coinMetaReg.set(n,i),i}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Wu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Mo=class t{static isCoin(e){return e?(0,pa.normalizeStructTag)(e).match(Wu)!=null:!1}static getCoinType(e){let[,n]=(0,pa.normalizeStructTag)(e).match(Wu)??[];return n||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:n}=e.content?.fields;if(n!==void 0)return BigInt(n)}};var Vn=class{static normalizeSuiAddress(e){return(0,_i.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,_i.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,_i.normalizeSuiAddress)(e)===(0,_i.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,_i.normalizeStructTag)(e)===(0,_i.normalizeStructTag)(n)}static isCoinObjectType(e){return Mo.isCoin(e)}};function Hu(t,e){return t.startsWith(e)?t:e+t}var Zu=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ga.verifyTransactionBlock)(e.message,e.signature):(0,ga.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=ha(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return Vn.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=ha(e.messageStr);return this.verifySignature({message:n,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 ug=require("@msafe/sui3-utils"),lg=require("@mysten/sui.js/cryptography"),dg=require("@mysten/sui.js/multisig");var Z1="0x2::sui::SUI";async function Xu(t,e){let n;try{n=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(n.data.length===0||!n.data[0].transaction?.txSignatures)return;let r=n.data[0].transaction?.txSignatures;for(let o=0;o!==r.length;o++){let s=r[o],a=X1(s,e);if(a)return a}}function X1(t,e){let n=(0,lg.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new dg.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if(Vn.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Vn.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=ug.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return Vn.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function J1(t){let e=!0,n,i=[];for(;e;){let r=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:n});i.push(...r.data),e=r.hasNextPage,n=r.nextCursor}return i}var fg=25;async function hg(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Ju=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)}},_a=class{constructor(e){this.requester=e;this.pager=new Ju(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 mg(t,e,n){let i=new Yu(t,e,n);return await hg(i)}var Yu=class extends _a{constructor(n,i,r){super(new Qu(n,i,r));this.provider=n;this.owner=i;this.options=r}},Qu=class{constructor(e,n,i){this.provider=e;this.owner=n;this.options=i;this.nextCursor=null,this.filter=i?.filter,this.pageSize=i?.pageSize||fg,this.objectOptions=i?.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 n;if(this.filter){let{filter:i}=this;n=e.data.filter(r=>i?.(r))}else n=e.data;return{data:n.map(i=>i.data).filter(i=>i),hasNext:e.hasNextPage}}};var Ui=class t{constructor(e,n){this.globals=e;this.info=n;this.multiSig=new Ae.MultiSigAccount({threshold:n.threshold,ownersWithWeight:n.owners,creationNonce:n.creationNonce}),this.coinHelper=new Eo(this.suiClient),this.simulator=new fa(e)}multiSig;coinHelper;simulator;static async New(e,n){let i=await e.backend.getMSafeAccountInfo(n);if(new t(e,i).address!==n)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 n=>{let i=await this.coinHelper.getCoinMeta(n.coinType),r=n.lockedBalance.number?BigInt(n.totalBalance)-BigInt(n.lockedBalance.number):BigInt(n.totalBalance);return{type:(0,ya.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return mg(this.suiClient,this.address,n)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let n=e.pending,i=e.reject;return{application:n.application,txType:n.txType,txSubType:n.txSubType,createdAt:n.createdAt,creator:n.creator,digest:n.digest,intention:n.intention,sequenceNumber:n.sequenceNumber,payload:n.payload,votes:n.votes,approvalWeight:this.calculateWeightFromVotes(n.votes),msafeAddress:n.msafeAddress,rejectDigest:i?.digest??"",rejectPayload:i?.payload??"",rejectVotes:i?.votes??[],rejectWeight:this.calculateWeightFromVotes(i?.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 n=da.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,sender:this.address})}async proposeIntention(e){let n=Ae.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),i=await this.wallet.signPersonalMessage({messageStr:n});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:i.signature})}async proposeIntentionAndBuildVote(e){let n=da.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});i.setGasPrice(e.gasPrice),i.setGasBudget(e.gasBudget),i.setSender(this.address);let r=await i.build({client:this.globals.suiClient}),o=await i.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:r});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,ya.toHEX)(r),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async proposeCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async simulateObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async proposeObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async simulatePlainPayloadIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async proposePlainPayloadIntention(e){let n=await this.nextSequenceNumber(),i=el.TransactionBlock.from(e.payload);if(!i.blockData.sender||!(0,Ae.isSameAddress)(i.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async voteForTransaction(e,n){let i=ma(n),r=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:r.signature})}async proposePendingTransaction(e){let n=new el.TransactionBlock,i=await n.build({client:this.suiClient}),r=await n.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:r,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let n=e.payload,i=(0,Ae.buildRejectTxb)(this.address,n);return this.simulator.simulate({txb:i,sender:this.address})}async rejectCurrentTx(e){let n=await this.pendingTransaction();if(!n||n.rejectDigest!=="")throw new Error("Already rejected");let i=n.payload,r=(0,Ae.buildRejectTxb)(this.address,i),o=await r.getDigest({client:this.suiClient}),s=await r.build({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:a.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),n=da.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,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,n=!1){let i=n?e.rejectVotes:e.votes,r=n?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(i)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(i.map(u=>[u.userAddress,u.signature]));for(let u=0;u<this.info.owners.length;u++){let l=this.info.owners[u],h=s.get(l.address);h&&o.push(h)}let a=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ma(r),signature:a,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(n=>n.userAddress))}calculateWeight(e){let n=0;for(let i=0;i<e.length;i++){let r=this.info.owners.find(o=>(0,Ae.isSameAddress)(o.address,e[i]));r&&(n+=r.weight)}return n}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 pg=require("@msafe/sui3-utils"),gg=require("@mysten/sui.js/utils");var wa=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let n=this.knownPublicKeys.get(e);if(n)return n;let i=await this._getPublicKey(e);return i&&this.knownPublicKeys.set(e,i),i}async getPublicKeyBatch(e){let n=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];n[o]=this.knownPublicKeys.get(s)}let i=n.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(i.length===0)return n;let r=await this.globals.backend.getPublicKeyBatch(i.map(o=>e[o]));for(let o=0;o<i.length;o++){let s=i[o];n[s]=r[o]}for(let o=0;o<n.length;o++)n[o]===void 0&&(n[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)n[o]&&this.knownPublicKeys.set(e[o],n[o]);return n}addPublicKey(e,n){if(!(0,pg.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,gg.normalizeSuiAddress)(e),n)}async _getPublicKey(e){let n=await this.getPublicKeyFromBackend(e);if(n)return n;let i=await this.getPublicKeyFromChain(e);if(i)return i}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Xu(this.globals.suiClient,e)}};var ba=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Tg=require("@mysten/sui.js/client");var jo=require("@msafe/sui3-utils"),Bo=ge(require("axios"),1);var va=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let n=await this.post("/auth/login",e);return this._token=n.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 n={userAddressList:e};return(await this.get("/user/public-keys",{params:n,headers:this.headers()})).data?.map(r=>r?jo.PublicKeySerde.de(r):void 0)}async getMSafeAccountInfo(e){let n={msafeAddress:e},i=await this.get("/msafe",{params:n,headers:this.headers()});return t.toMSafeConfig(i.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let n={status:e.status??jo.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},i=await this.get("/msafe/owned",{params:n,headers:this.headers()});return{data:i.data.data.map(t.toMSafeConfig),meta:i.data.meta}}async updateMSafeStatus(e){let n=e;await this.post("/msafe/status",n,{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(n=>({address:n.address,weight:n.weight,publicKey:jo.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Bo.default.get(i,n)}catch(r){throw ka.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Bo.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw ka.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Hu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=Bo.default.defaults;return n?n instanceof Array?e=n:e=[n]:e=[],[i=>JSON.parse(JSON.stringify(i,(r,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},ka=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(Bo.default.isAxiosError(n)&&n?.response?.data&&"message"in n.response.data)return new t(n)}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 _g=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(_g||{}),Ta="https://fullnode.testnet.sui.io",tl="https://fullnode.mainnet.sui.io",nl="http://127.0.0.1:3000",il="http://127.0.0.1:3001",yg="https://sui-dev.m-safe.link",wg="http://13.56.226.148:81",bg="https://sui-preview.m-safe.link",vg="https://sui.m-safe.link",kg=new Map([["unit",{suiClient:{url:Ta},backend:{url:nl},syncingURL:il,network:"sui:testnet"}],["local",{suiClient:{url:Ta},backend:{url:nl},syncingURL:il,network:"sui:testnet"}],["dev",{suiClient:{url:Ta},backend:{url:yg},syncingURL:wg,network:"sui:testnet"}],["prev",{suiClient:{url:tl},backend:{url:bg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:tl},backend:{url:vg},syncingURL:"",network:"sui:mainnet"}]]);function rl(t,e){let n=kg.get(t);if(!n)throw new Error("Unknown environment");return e?.suiClient?.url&&(n.suiClient.url=e.suiClient.url),e?.backend?.url&&(n.backend.url=e.backend.url),n}var No=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,n){let i=rl(e,n),r=new Tg.SuiClient(i.suiClient),o=new va(i.backend.url);return new t({backend:o,suiClient:r,config:i})}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 Ca=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await No.New(e,n);return new t(i)}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 n=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(n),n}async authSign(e){let n=Sa.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),i=await e.signPersonalMessage({messageStr:n});return this.backend.authSign({address:await e.address(),message:n,signature:i.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:Sa.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Ui(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new Ui(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new zi(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new wa(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 Vi(this.globals)}get Invitation(){return new qo(this.globals)}get Report(){return new ba(this.globals)}async walletAddress(){return this.wallet.address()}};
2053
+ `);var To=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Fh=new Set,bu=typeof process=="object"&&process?process:{},Rh=(t,e,n,i)=>{typeof bu.emitWarning=="function"?bu.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},Hs=globalThis.AbortController,Nh=globalThis.AbortSignal;if(typeof Hs>"u"){Nh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},Hs=class{constructor(){e()}signal=new Nh;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let r of this.signal._onabort)r(i);this.signal.onabort?.(i)}}};let t=bu.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Rh("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 ab=t=>!Fh.has(t),EA=Symbol("type"),ui=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),qh=t=>ui(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?xr:null:null,xr=class extends Array{constructor(e){super(e),this.fill(0)}},vu=class t{heap;length;static#c=!1;static create(e){let n=qh(e);if(!n)return[];t.#c=!0;let i=new t(e,n);return t.#c=!1,i}constructor(e,n){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zs=class t{#c;#d;#y;#m;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#p;#r;#n;#e;#u;#f;#a;#o;#g;#s;#k;#T;#_;#w;#S;#l;static unsafeExposeInternals(e){return{starts:e.#T,ttls:e.#_,sizes:e.#k,keyMap:e.#r,keyList:e.#n,valList:e.#e,next:e.#u,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:n=>e.#t(n),backgroundFetch:(n,i,r,o)=>e.#E(n,i,r,o),moveToTail:n=>e.#I(n),indexes:n=>e.#b(n),rindexes:n=>e.#v(n),isStale:n=>e.#h(n)}}get max(){return this.#c}get maxSize(){return this.#d}get calculatedSize(){return this.#p}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#m}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:u,dispose:l,disposeAfter:h,noDisposeOnSet:w,noUpdateTTL:v,maxSize:T=0,maxEntrySize:I=0,sizeCalculation:x,fetchMethod:P,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:B,allowStaleOnFetchAbort:$,ignoreFetchAbort:Z}=e;if(n!==0&&!ui(n))throw new TypeError("max option must be a nonnegative integer");let H=n?qh(n):Array;if(!H)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=T,this.maxEntrySize=I||this.#d,this.sizeCalculation=x,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(P!==void 0&&typeof P!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=P,this.#S=!!P,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new H(n),this.#f=new H(n),this.#a=0,this.#o=0,this.#g=vu.create(n),this.#i=0,this.#p=0,typeof l=="function"&&(this.#y=l),typeof h=="function"?(this.#m=h,this.#s=[]):(this.#m=void 0,this.#s=void 0),this.#w=!!this.#y,this.#l=!!this.#m,this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!B,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#d!==0&&!ui(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!ui(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#R()}if(this.allowStale=!!u,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=ui(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!ui(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#c===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#d){let te="LRU_CACHE_UNBOUNDED";ab(te)&&(Fh.add(te),Rh("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",te,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#M(){let e=new xr(this.#c),n=new xr(this.#c);this.#_=e,this.#T=n,this.#B=(o,s,a=To.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let u=setTimeout(()=>{this.#h(o)&&this.delete(this.#n[o])},s+1);u.unref&&u.unref()}},this.#A=o=>{n[o]=e[o]!==0?To.now():0},this.#C=(o,s)=>{if(e[s]){let a=e[s],u=n[s];o.ttl=a,o.start=u,o.now=i||r();let l=o.now-u;o.remainingTTL=a-l}};let i=0,r=()=>{let o=To.now();if(this.ttlResolution>0){i=o;let s=setTimeout(()=>i=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],u=n[s];if(a===0||u===0)return 1/0;let l=(i||r())-u;return a-l},this.#h=o=>e[o]!==0&&n[o]!==0&&(i||r())-n[o]>e[o]}#A=()=>{};#C=()=>{};#B=()=>{};#h=()=>!1;#R(){let e=new xr(this.#c);this.#p=0,this.#k=e,this.#x=n=>{this.#p-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!ui(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!ui(r))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 r},this.#P=(n,i,r)=>{if(e[n]=i,this.#d){let o=this.#d-e[n];for(;this.#p>o;)this.#D(!0)}this.#p+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#p)}}#x=e=>{};#P=(e,n,i)=>{};#j=(e,n,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#a));)n=this.#f[n]}*#v({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#N(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#b()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#v()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#b())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,n={}){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&e(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(e,n=this){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}rforEach(e,n=this){for(let i of this.#v()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}purgeStale(){let e=!1;for(let n of this.#v({allowStale:!0}))this.#h(n)&&(this.delete(this.#n[n]),e=!0);return e}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let s={value:o};if(this.#_&&this.#T){s.ttl=this.#_[n];let a=To.now()-this.#T[n];s.start=Math.floor(Date.now()-a)}this.#k&&(s.size=this.#k[n]),e.unshift([i,s])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let r=Date.now()-i.start;i.start=To.now()-r}this.set(n,i.value,i)}}set(e,n,i={}){if(n===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:u}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,h=this.#j(e,n,i.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return u&&(u.set="miss",u.maxEntrySizeExceeded=!0),this.delete(e),this;let w=this.#i===0?void 0:this.#r.get(e);if(w===void 0)w=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[w]=e,this.#e[w]=n,this.#r.set(e,w),this.#u[this.#o]=w,this.#f[w]=this.#o,this.#o=w,this.#i++,this.#P(w,h,u),u&&(u.set="add"),l=!1;else{this.#I(w);let v=this.#e[w];if(n!==v){if(this.#S&&this.#t(v)?v.__abortController.abort(new Error("replaced")):s||(this.#w&&this.#y?.(v,e,"set"),this.#l&&this.#s?.push([v,e,"set"])),this.#x(w),this.#P(w,h,u),this.#e[w]=n,u){u.set="replace";let T=v&&this.#t(v)?v.__staleWhileFetching:v;T!==void 0&&(u.oldValue=T)}}else u&&(u.set="update")}if(r!==0&&!this.#_&&this.#M(),this.#_&&(l||this.#B(w,r,o),u&&this.#C(u,w)),!s&&this.#l&&this.#s){let v=this.#s,T;for(;T=v?.shift();)this.#m?.(...T)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#D(!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,n;for(;n=e?.shift();)this.#m?.(...n)}}}#D(e){let n=this.#a,i=this.#n[n],r=this.#e[n];return this.#S&&this.#t(r)?r.__abortController.abort(new Error("evicted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#x(n),e&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#g.push(n)),this.#i===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#u[n],this.#r.delete(i),this.#i--,n}has(e,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#r.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))r&&(r.has="stale",this.#C(r,o));else return i&&this.#A(o),r&&(r.has="hit",this.#C(r,o)),!0}else r&&(r.has="miss");return!1}peek(e,n={}){let{allowStale:i=this.allowStale}=n,r=this.#r.get(e);if(r!==void 0&&(i||!this.#h(r))){let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}}#E(e,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let s=new Hs,{signal:a}=i;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let u={signal:s.signal,options:i,context:r},l=(x,P=!1)=>{let{aborted:O}=s.signal,E=i.ignoreFetchAbort&&x!==void 0;if(i.status&&(O&&!P?(i.status.fetchAborted=!0,i.status.fetchError=s.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),O&&!E&&!P)return w(s.signal.reason);let B=T;return this.#e[n]===T&&(x===void 0?B.__staleWhileFetching?this.#e[n]=B.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,x,u.options))),x},h=x=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=x),w(x)),w=x=>{let{aborted:P}=s.signal,O=P&&i.allowStaleOnFetchAbort,E=O||i.allowStaleOnFetchRejection,B=E||i.noDeleteOnFetchRejection,$=T;if(this.#e[n]===T&&(!B||$.__staleWhileFetching===void 0?this.delete(e):O||(this.#e[n]=$.__staleWhileFetching)),E)return i.status&&$.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),$.__staleWhileFetching;if($.__returned===$)throw x},v=(x,P)=>{let O=this.#O?.(e,o,u);O&&O instanceof Promise&&O.then(E=>x(E),P),s.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(x(),i.allowStaleOnFetchAbort&&(x=E=>l(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let T=new Promise(v).then(l,h),I=Object.assign(T,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,I,{...u.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=I,I}#t(e){if(!this.#S)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Hs}async fetch(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:u=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:v=this.allowStaleOnFetchRejection,ignoreFetchAbort:T=this.ignoreFetchAbort,allowStaleOnFetchAbort:I=this.allowStaleOnFetchAbort,context:x,forceRefresh:P=!1,status:O,signal:E}=n;if(!this.#S)return O&&(O.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:O});let B={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:u,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:I,ignoreFetchAbort:T,status:O,signal:E},$=this.#r.get(e);if($===void 0){O&&(O.fetch="miss");let Z=this.#E(e,$,B,x);return Z.__returned=Z}else{let Z=this.#e[$];if(this.#t(Z)){let F=i&&Z.__staleWhileFetching!==void 0;return O&&(O.fetch="inflight",F&&(O.returnedStale=!0)),F?Z.__staleWhileFetching:Z.__returned=Z}let H=this.#h($);if(!P&&!H)return O&&(O.fetch="hit"),this.#I($),r&&this.#A($),O&&this.#C(O,$),Z;let te=this.#E(e,$,B,x),V=te.__staleWhileFetching!==void 0&&i;return O&&(O.fetch=H?"stale":"refresh",V&&H&&(O.returnedStale=!0)),V?te.__staleWhileFetching:te.__returned=te}}get(e,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let u=this.#e[a],l=this.#t(u);return s&&this.#C(s,a),this.#h(a)?(s&&(s.get="stale"),l?(s&&i&&u.__staleWhileFetching!==void 0&&(s.returnedStale=!0),i?u.__staleWhileFetching:void 0):(o||this.delete(e),s&&i&&(s.returnedStale=!0),i?u:void 0)):(s&&(s.get="hit"),l?u.__staleWhileFetching:(this.#I(a),r&&this.#A(a),u))}else s&&(s.get="miss")}#F(e,n){this.#f[n]=e,this.#u[e]=n}#I(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#F(this.#f[e],this.#u[e]),this.#F(this.#o,e),this.#o=e)}delete(e){let n=!1;if(this.#i!==0){let i=this.#r.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.clear();else{this.#x(i);let r=this.#e[i];this.#t(r)?r.__abortController.abort(new Error("deleted")):(this.#w||this.#l)&&(this.#w&&this.#y?.(r,e,"delete"),this.#l&&this.#s?.push([r,e,"delete"])),this.#r.delete(e),this.#n[i]=void 0,this.#e[i]=void 0,i===this.#o?this.#o=this.#f[i]:i===this.#a?this.#a=this.#u[i]:(this.#u[this.#f[i]]=this.#u[i],this.#f[this.#u[i]]=this.#f[i]),this.#i--,this.#g.push(i)}}if(this.#l&&this.#s?.length){let i=this.#s,r;for(;r=i?.shift();)this.#m?.(...r)}return n}clear(){for(let e of this.#v({allowStale:!0})){let n=this.#e[e];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#n[e];this.#w&&this.#y?.(n,i,"delete"),this.#l&&this.#s?.push([n,i,"delete"])}}if(this.#r.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#_&&this.#T&&(this.#_.fill(0),this.#T.fill(0)),this.#k&&this.#k.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#p=0,this.#i=0,this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#m?.(...n)}}};var ae=ge(ke(),1);var Qs=ge(Lh(),1),Ni=require("@mysten/sui.js/utils"),Fi=require("@mysten/sui.js/transactions");var Co=ge(ke(),1),Hh=require("@mysten/sui.js/transactions"),Wt=ge(ke(),1);var li=ge(ke(),1),ln=ge(ke(),1);var xo=ge(ke(),1);var Zh=require("@mysten/sui.js/utils"),ea=require("@mysten/sui.js/transactions"),ta=require("@mysten/sui.js/utils");var xu=ge(ke(),1),cb=Object.defineProperty,ub=(t,e,n)=>e in t?cb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,On=(t,e,n)=>(ub(t,typeof e!="symbol"?e+"":e,n),n);var Xs=443636,Js=-443636,Cu="79226673515401279992447579055",Su="4295048016",db=14,fb="59543866431248",hb="184467440737095516",mb="15793534762490258745",pb=class{generateMnemonic(t=24){return Bh(jh,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return zh.Ed25519Keypair.deriveKeypair(t,n)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:n=!1,addressIndex:i=0}=t;return`m/44'/784'/${e}'/${n?1:0}'/${i}'`}},Ao=class{constructor(t){this.sdk=t,On(this,"_lru"),On(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new Zs({max:100}));if(r.has(t))return r.get(t);let s=await((i=this._fetching)[t]||(i[t]=e()));return delete this._fetching[t],r.set(t,s,{ttl:n}),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 gb(t){if("reference"in t)return t.reference;let e=Iu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Gh(t)}function ia(t){var e,n;return"objectId"in t?t.objectId:(n=(e=gb(t))==null?void 0:e.objectId)!=null?n:Wh(t)}function Pn(t){var e;return"fields"in t?t.fields:(e=Vh(t))==null?void 0:e.fields}function Vh(t){let e="data"in t?Iu(t):t;if(!(!e||!_b(e)||e.content.dataType!=="moveObject"))return e.content}function _b(t){return t.content!==void 0}function Iu(t){return t.data}function Gh(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 Wh(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function yb(t){return t.data!==void 0}function wb(t){var e;let n=yb(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":na(t):n?.type}function na(t){var e;return(e=Vh(t))==null?void 0:e.type}function bb(t){var e;return(e=Iu(t))==null?void 0:e.owner}var So=async(t,e,n)=>{let r=e.length;if(r>50){let o=[],s=0,a=Math.ceil(r/50);for(s;s<a;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:n}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:n})},vb=class extends Ao{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 So(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=Pn(i),o=ia(i),s=na(i);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:r.fee,tickSpacing:r.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())}},$h=new ae.default(2).pow(new ae.default(128)),kb=class{priceToSqrtPriceX64(t,e,n){return new ae.default(new N(t).mul(N.pow(10,n-e)).sqrt().mul(N.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new N(t.toString()).mul(N.pow(2,-64)).pow(2).mul(N.pow(10,e-n))}priceToTickIndex(t,e,n){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,n))}sqrtPriceX64ToTickIndex(t){if(t.gt(new ae.default(Cu))||t.lt(new ae.default(Su)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new ae.default(e-64),i=this.signedShiftLeft(n,32,128),r=new ae.default("8000000000000000","hex"),o=0,s=new ae.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new ae.default(0))&&o<db;){a=a.mul(a);let T=a.shrn(127);a=a.shrn(63+T.toNumber()),s=s.add(r.mul(T)),r=r.shrn(1),o+=1}let u=s.shrn(32),h=i.add(u).mul(new ae.default(fb)),w=this.signedShiftRight(h.sub(new ae.default(hb)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(mb)),64,128).toNumber();return w==v?w:this.tickIndexToSqrtPriceX64(v).lte(t)?v:w}tickIndexToSqrtPriceX64(t){return t>0?new ae.default(this.tickIndexToSqrtPricePositive(t)):new ae.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,n){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,n)}toX64_Decimal(t){return t.mul(N.pow(2,64))}fromX64_Decimal(t){return t.mul(N.pow(2,-64))}scaleDown(t,e){return new N(t).div(N.pow(10,e)).toString()}scaleUp(t,e){return new N(t).mul(N.pow(10,e)).toString()}bitsToNumber(t,e=32){return Qs.default.toNumber(Qs.default.asIntN(e,Qs.default.BigInt(t)))}subUnderflowU128(t,e){return t.add($h).sub(e).mod($h)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new ae.default("79232123823359799118286999567"):e=new ae.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new ae.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new ae.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new ae.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new ae.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new ae.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new ae.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new ae.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new ae.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new ae.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new ae.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new ae.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new ae.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new ae.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new ae.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new ae.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new ae.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new ae.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new ae.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),n;return e&1?n=new ae.default("18445821805675392311"):n=new ae.default("18446744073709551616"),e&2&&(n=this.signedShiftRight(n.mul(new ae.default("18444899583751176498")),64,256)),e&4&&(n=this.signedShiftRight(n.mul(new ae.default("18443055278223354162")),64,256)),e&8&&(n=this.signedShiftRight(n.mul(new ae.default("18439367220385604838")),64,256)),e&16&&(n=this.signedShiftRight(n.mul(new ae.default("18431993317065449817")),64,256)),e&32&&(n=this.signedShiftRight(n.mul(new ae.default("18417254355718160513")),64,256)),e&64&&(n=this.signedShiftRight(n.mul(new ae.default("18387811781193591352")),64,256)),e&128&&(n=this.signedShiftRight(n.mul(new ae.default("18329067761203520168")),64,256)),e&256&&(n=this.signedShiftRight(n.mul(new ae.default("18212142134806087854")),64,256)),e&512&&(n=this.signedShiftRight(n.mul(new ae.default("17980523815641551639")),64,256)),e&1024&&(n=this.signedShiftRight(n.mul(new ae.default("17526086738831147013")),64,256)),e&2048&&(n=this.signedShiftRight(n.mul(new ae.default("16651378430235024244")),64,256)),e&4096&&(n=this.signedShiftRight(n.mul(new ae.default("15030750278693429944")),64,256)),e&8192&&(n=this.signedShiftRight(n.mul(new ae.default("12247334978882834399")),64,256)),e&16384&&(n=this.signedShiftRight(n.mul(new ae.default("8131365268884726200")),64,256)),e&32768&&(n=this.signedShiftRight(n.mul(new ae.default("3584323654723342297")),64,256)),e&65536&&(n=this.signedShiftRight(n.mul(new ae.default("696457651847595233")),64,256)),e&131072&&(n=this.signedShiftRight(n.mul(new ae.default("26294789957452057")),64,256)),e&262144&&(n=this.signedShiftRight(n.mul(new ae.default("37481735321082")),64,256)),n}signedShiftLeft(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}signedShiftRight(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}},Au=(t,e)=>{let n=ia(t);if(Gh(t))throw new Error(`${e}(${n}) had been deleted`);if(Wh(t))throw new Error(`${e}(${n}) is not found`);return!0},Ir=60*1e3,Tb=class extends Ao{async getPools(t=!1){let e=await this.contract.getConfig(),n=[],i;do i=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:i?.nextCursor,limit:15}),n.push(...i.data.map(a=>a.objectId));while(i.hasNextPage);if(!n.length)return[];let o=(await So(this.provider,n,{showContent:!0})).map(a=>Pn(a).value.fields.pool_id);if(!o.length)return[];let s=await So(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>Pn(a).unlocked)),s.map(a=>this.parsePool(a))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:n,tickLower:i,tickUpper:r,sqrtPrice:o,slippage:s,coinTypeA:a,coinTypeB:u}=t,l=await this.contract.getConfig(),h=new N(t.amountA),w=new N(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,w)]),I=t.txb||new Fi.TransactionBlock,x=v.length>0?this.coin.convertTradeCoins(I,v,a,h):[this.coin.zero(a,I)],P=T.length>0?this.coin.convertTradeCoins(I,T,u,w):[this.coin.zero(u,I)];return I.moveCall({target:`${l.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[a,u,e.type],arguments:[I.object(l.PoolConfig),I.object(e.objectId),I.pure(o,"u128"),I.object(l.Positions),I.makeMoveVec({objects:x}),I.makeMoveVec({objects:P}),I.pure(Math.abs(i).toFixed(0),"u32"),I.pure(i<0,"bool"),I.pure(Math.abs(r).toFixed(0),"u32"),I.pure(r<0,"bool"),I.pure(h.toFixed(0),"u64"),I.pure(w.toFixed(0),"u64"),I.pure(this.getMinimumAmountBySlippage(h,s),"u64"),I.pure(this.getMinimumAmountBySlippage(w,s),"u64"),I.pure(n,"address"),I.pure(Date.now()+Ir,"u64"),I.object(Ni.SUI_CLOCK_OBJECT_ID),I.object(l.Versioned)]}),I}async addLiquidity(t){let{address:e,tickLower:n,tickUpper:i,slippage:r,pool:o}=t,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(o),[u,l]=a,[h,w]=await Promise.all([this.coin.getMetadata(u),this.coin.getMetadata(l)]);if(!h||!w)throw new Error("Invalid coin type");let v=new N(t.amountA),T=new N(t.amountB),[I,x]=await Promise.all([this.coin.selectTradeCoins(e,u,v),this.coin.selectTradeCoins(e,l,T)]),P=t.txb||new Fi.TransactionBlock,O=I.length>0?this.coin.convertTradeCoins(P,I,u,v):[this.coin.zero(u,P)],E=x.length>0?this.coin.convertTradeCoins(P,x,l,T):[this.coin.zero(l,P)];return P.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:a,arguments:[P.object(o),P.object(s.Positions),P.makeMoveVec({objects:O}),P.makeMoveVec({objects:E}),P.pure(Math.abs(n).toFixed(0),"u32"),P.pure(n<0,"bool"),P.pure(Math.abs(i).toFixed(0),"u32"),P.pure(i<0,"bool"),P.pure(v.toFixed(0),"u64"),P.pure(T.toFixed(0),"u64"),P.pure(this.getMinimumAmountBySlippage(v,r),"u64"),P.pure(this.getMinimumAmountBySlippage(T,r),"u64"),P.pure(e,"address"),P.pure(Date.now()+Ir,"u64"),P.object(Ni.SUI_CLOCK_OBJECT_ID),P.object(s.Versioned)]}),P}async increaseLiquidity(t){let{pool:e,slippage:n,address:i,nft:r}=t,o=await this.contract.getConfig(),s=new N(t.amountA),a=new N(t.amountB),u=await this.getPoolTypeArguments(e),[l,h]=u,[w,v]=await Promise.all([this.coin.selectTradeCoins(i,l,s),this.coin.selectTradeCoins(i,h,a)]),T=t.txb||new Fi.TransactionBlock,I=w.length>0?this.coin.convertTradeCoins(T,w,l,s):[this.coin.zero(l,T)],x=v.length>0?this.coin.convertTradeCoins(T,v,h,a):[this.coin.zero(h,T)];return T.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:u,arguments:[T.object(e),T.object(o.Positions),T.makeMoveVec({objects:I}),T.makeMoveVec({objects:x}),T.object(r),T.pure(s.toFixed(0),"u64"),T.pure(a.toFixed(0),"u64"),T.pure(this.getMinimumAmountBySlippage(s,n),"u64"),T.pure(this.getMinimumAmountBySlippage(a,n),"u64"),T.pure(Date.now()+Ir*3,"u64"),T.object(Ni.SUI_CLOCK_OBJECT_ID),T.object(o.Versioned)]}),T}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new N(t.amountA),s=new N(t.amountB),a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(i),l=t.txb||new Fi.TransactionBlock;return l.moveCall({target:`${a.PackageId}::position_manager::decrease_liquidity`,typeArguments:u,arguments:[l.object(i),l.object(a.Positions),l.object(n),l.pure(new Co.default(r).toString(),"u128"),l.pure(this.getMinimumAmountBySlippage(o,e),"u64"),l.pure(this.getMinimumAmountBySlippage(s,e),"u64"),l.pure(Date.now()+Ir*3,"u64"),l.object(Ni.SUI_CLOCK_OBJECT_ID),l.object(a.Versioned)]}),l}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:n,address:i,collectAmountA:r,collectAmountB:o}=t,s=t.txb||new Fi.TransactionBlock;if(Number(r)===0&&Number(o)===0)return s;let a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return s.moveCall({target:`${a.PackageId}::position_manager::collect`,typeArguments:u,arguments:[s.object(e),s.object(a.Positions),s.object(n),s.pure(r,"u64"),s.pure(o,"u64"),s.pure(i),s.pure(Date.now()+Ir*3,"u64"),s.object(Ni.SUI_CLOCK_OBJECT_ID),s.object(a.Versioned)]}),s}async collectReward(t){let{pool:e,nft:n,rewardAmounts:i,address:r}=t,o=t.txb||new Fi.TransactionBlock,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((l,h)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...a,l.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(n),o.object(l.fields.vault),o.pure(h,"u64"),o.pure(i[h],"u64"),o.pure(r),o.pure(Date.now()+Ir*3,"u64"),o.object(Ni.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new N((t.liquidity||new Co.default(1e8)).toString()),n=new N(t.currentSqrtPrice.toString()),i=new N(t.lowerSqrtPrice.toString()),r=new N(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(i)).div(i.mul(r)),s=new N(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(r.sub(n)).div(n.mul(r)),s=this.math.fromX64_Decimal(e.mul(n.sub(i)))):(o=new N(0),s=this.math.fromX64_Decimal(e.mul(r.sub(i))));let a=t.ceil!==!1?"ceil":"floor";return[new Co.default(o[a]().toString()),new Co.default(s[a]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var n;let i=((n=t.replace(">","").split("<")[1])==null?void 0:n.split(/,\s*/))||[];if(e!==void 0&&e!==i.length)throw new Error("Invalid pool type");return i}async getFixedLiquidity(t){var e,n;let{coinTypeA:i,coinTypeB:r,amountA:o,amountB:s}=t,[a,u]=await Promise.all([this.coin.getMetadata(i),this.coin.getMetadata(r)]),l=new N(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),h=new N(this.math.scaleDown(s,u.decimals)).mul((n=t.priceB)!=null?n:1);return{liquidityA:l.toString(),liquidityB:h.toString(),liquidity:l.plus(h).toString()}}parsePool(t){let e=Pn(t),n=ia(t),i=wb(t),r=this.parsePoolType(i,3);return this.getCacheOrSet("pool-type-"+n,async()=>r),{...e,objectId:n,type:i,types:r}}getMinimumAmountBySlippage(t,e){let n=new N(t),i=new N(1).minus(new N(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},Cb=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new li.default(n.fee_growth_global_a),a=new li.default(i.fee_growth_inside_a),u=new li.default(i.tokens_owed_a),l=new li.default(n.fee_growth_global_b),h=new li.default(i.fee_growth_inside_b),w=new li.default(i.tokens_owed_b),v=new li.default(i.liquidity),T,I,x,P,O=t.bitsToNumber(n.tick_current_index.fields.bits),E=t.bitsToNumber(i.tick_lower_index.fields.bits),B=t.bitsToNumber(i.tick_upper_index.fields.bits);O<E?(T=t.subUnderflowU128(s,r.feeGrowthOutsideA),I=t.subUnderflowU128(l,r.feeGrowthOutsideB)):(T=r.feeGrowthOutsideA,I=r.feeGrowthOutsideB),O<B?(x=o.feeGrowthOutsideA,P=o.feeGrowthOutsideB):(x=t.subUnderflowU128(s,o.feeGrowthOutsideA),P=t.subUnderflowU128(l,o.feeGrowthOutsideB));let $=t.subUnderflowU128(t.subUnderflowU128(s,T),x),Z=t.subUnderflowU128(t.subUnderflowU128(l,I),P),H=t.subUnderflowU128($,a).mul(v).shrn(64),te=t.subUnderflowU128(Z,h).mul(v).shrn(64);return{feeOwedA:u.add(H).toString(),feeOwedB:w.add(te).toString()}},Uh=new xo.default(0),Kh=new xo.default(1),Sb=new xo.default(2),Ab={mul(t,e,n){let i=t.mul(e);if(this.isOverLimit(i,n))throw new Error(`Mul result higher than u${n}`);return i},mulDiv(t,e,n,i){return this.mulDivRoundUpIf(t,e,n,!1,i)},mulDivRoundUpIf(t,e,n,i,r){if(n.eq(Uh))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt(Uh)?s.add(Kh):s},isOverLimit(t,e){let n=Sb.pow(new xo.default(e)).sub(Kh);return t.gt(n)}},xb=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,w=new ln.default(new N(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),T=(h??new ln.default(Date.now()).div(new ln.default(1e3))).sub(new ln.default(w)),I=[],x=new ln.default(s.liquidity),P=new ln.default(a.liquidity);for(let O=0;O<3;++O){let E=s.reward_infos[O],B={emissionsPerSecondX64:new ln.default(E?E.fields.emissions_per_second:"0"),growthGlobalX64:new ln.default(E?E.fields.growth_global:"0")},$={growthInsideCheckpoint:new ln.default((i=(n=a.reward_infos[O])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new ln.default((o=(r=a.reward_infos[O])==null?void 0:r.fields.amount_owed)!=null?o:"0")},Z=B.growthGlobalX64;if(!x.isZero()){let C=Ab.mulDiv(T,B.emissionsPerSecondX64,x,128);Z=B.growthGlobalX64.add(C)}let H=u.rewardGrowthsOutside[O],te=l.rewardGrowthsOutside[O],U=Z;u.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_lower_index.fields.bits)?t.subUnderflowU128(Z,H):H);let V=new ln.default(0);l.initialized&&(V=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_upper_index.fields.bits)?te:t.subUnderflowU128(Z,te));let F=t.subUnderflowU128(t.subUnderflowU128(Z,U),V),K=$.amountOwed.shln(64);I[O]=K.add(t.subUnderflowU128(F,$.growthInsideCheckpoint).mul(P)).shrn(64).toString()}return I},Ib=class extends Ao{async getOwner(t){let e=await this.getObject(t),n=bb(e);if(!(!n||typeof n=="string")){if("ObjectOwner"in n)return n.ObjectOwner;if("AddressOwner"in n)return n.AddressOwner}}async getFields(t){let e=await this.getObject(t);return Pn(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return Pn(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Au(e,"position"),Pn(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=Pn(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new Wt.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Wt.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new Wt.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Wt.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new Wt.default(r))}}async getPositionAPR(t){let{poolId:e,getPrice:n,fees24h:i,tickLower:r,tickUpper:o}=t,s=await this.pool.getPool(e),a=this.math.bitsToNumber(s.tick_current_index.fields.bits),[u,l,h,w]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),n(s.types[0]),n(s.types[1])]);if(!h||!w||r>=o||a<r||a>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:v,minTokenB:T}=this.getRemoveLiquidityQuote(s,r,o),I=new N(this.math.scaleDown(v.toString(),u.decimals)).mul(h),x=new N(this.math.scaleDown(T.toString(),l.decimals)).mul(w),P=I.add(x),O=P.isZero()?new N(0):new N(i).mul(365).div(P).mul(100),E=new N(0);return await Promise.all(s.reward_infos.map(async B=>{let{emissions_per_second:$}=B.fields,Z=this.coin.formatCoinType(B.fields.vault_coin_type),[H,te]=await Promise.all([n(Z),this.coin.getMetadata(Z)]);!$||$==="0"||!H||(E=E.add(new N(new Wt.default($).shrn(64).toString()).div(10**te.decimals).mul(31536e3).mul(H).div(P).mul(100)))})),{fees:O.toString(),rewards:E.toString(),total:O.plus(E).toString()}}getRemoveLiquidityQuote(t,e,n){let i=new Wt.default(0),r=new Wt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),a=this.math.tickIndexToSqrtPriceX64(n);if(o<e){let l=this.getTokenAFromLiquidity(r,s,a);return{minTokenA:this.adjustForSlippage(l),minTokenB:i}}if(o<n){let l=new Wt.default(t.sqrt_price),h=this.getTokenAFromLiquidity(r,l,a),w=this.getTokenBFromLiquidity(r,s,l);return{minTokenA:this.adjustForSlippage(h),minTokenB:this.adjustForSlippage(w)}}let u=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(u)}}adjustForSlippage(t){let e={numerator:new Wt.default(0),denominator:new Wt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,n){let i=t.mul(n.sub(e)).shln(64),r=n.mul(e);return i.div(r)}getTokenBFromLiquidity(t,e,n){return t.mul(n.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:n}=t,i=t.txb||new Hh.TransactionBlock,r=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return i.moveCall({target:`${r.PackageId}::position_manager::burn`,typeArguments:o,arguments:[i.object(r.Positions),i.object(n),i.object(r.Versioned)]}),i}async getPositionLiquidityUSD(t){let{position:e,poolId:n,priceA:i,priceB:r}=t,o=await this.pool.getPool(n),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Wt.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 Wt.default(e.liquidity===void 0?1e8:e.liquidity)}),[a,u]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),l=new N(s[0].toString()).div(10**a.decimals).mul(i||0),h=new N(s[1].toString()).div(10**u.decimals).mul(r||0);return l.plus(h).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:n}=t,[i,r,o]=await Promise.all([this.pool.getPool(n),this.nft.getPositionTick(n,e.tick_lower_index),this.nft.getPositionTick(n,e.tick_upper_index)]),s={...t,pool:i,tickLowerDetail:r,tickUpperDetail:o},[a,u]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:l,...h}=a,{unclaimedRewards:w,...v}=u;return{fees:a.unclaimedFees.toString(),rewards:w.toString(),total:l.plus(w).toString(),fields:{...h,...v}}}async getUnclaimedFees(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,[s,a,u,l]=await Promise.all([this.coin.getMetadata(n.types[0]),this.coin.getMetadata(n.types[1]),i(n.types[0]),i(n.types[1])]),h=Cb(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),w=this.math.scaleDown(h.feeOwedA,s.decimals),v=this.math.scaleDown(h.feeOwedB,a.decimals);function T(P,O){return new N(1e6).mul(N.pow(10,O)).lt(P)}T(w,s.decimals)&&(w="0",h.feeOwedA="0"),T(v,a.decimals)&&(v="0",h.feeOwedB="0");let I=u===void 0?new N(0):new N(u).mul(w),x=l===void 0?new N(0):new N(l).mul(v);return{unclaimedFees:I.plus(x),scaledFeeOwedA:w,scaledFeeOwedB:v,...h}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=xb(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),a=[...s],u=n.reward_infos.map(v=>this.coin.formatCoinType(v.fields.vault_coin_type)),l=await Promise.all([...n.reward_infos.map((v,T)=>this.coin.getMetadata(u[T]))]),h=await Promise.all(n.reward_infos.map((v,T)=>i(u[T])));l.forEach((v,T)=>{a[T]=this.math.scaleDown(a[T],v.decimals)});let w=new N(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(w=w.plus(new N(I).mul(a[T])),!1):(w=w.plus(1),!0)}),{unclaimedRewards:w,collectRewards:s,scaledCollectRewards:a}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return Au(e,"nft"),e})}},Ob=class extends Ao{isSUI(t){return(0,Zh.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,n){if(n.eq(0))return[];let i=[],r=[],o=new N(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),i.push(...s.data);while(s.hasNextPage);i.sort((a,u)=>Number(u.balance)-Number(a.balance));for(let a of i)if(r.push(a.coinObjectId),o=o.add(a.balance),o.gte(n))break;return r}convertTradeCoins(t,e,n,i){return this.isSUI(n)?[t.splitCoins(t.gas,[t.pure(i.toNumber())])[0]]:e.map(r=>t.object(r))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let i=t.replace(/^0x/i,"");return i=i.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&i.length<64&&t!=="2::sui:SUI"?"0".repeat(64-i.length):"")+i}},Pb=60*1e3,Ys=100,Db=class extends Ao{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new N(t.amountA),a=new N(t.amountB),u=await this.contract.getConfig(),l=await Promise.all(t.routes.map(async x=>{let P=await this.pool.getPoolTypeArguments(x.pool),[O,E]=await Promise.all([this.coin.getMetadata(P[0]),this.coin.getMetadata(P[1])]);return{...x,coinA:O,coinB:E,typeArguments:P}})),h=await this.coin.selectTradeCoins(i,e,s),{functionName:w,typeArguments:v}=this.getFunctionNameAndTypeArguments(l.map(({typeArguments:x})=>x),e,n),T=l.map(({nextTickIndex:x,coinA:P,coinB:O,a2b:E})=>{let B=this.math.tickIndexToPrice(x,P.decimals,O.decimals);return this.sqrtPriceWithSlippage(B,o,E,P.decimals,O.decimals)}),I=t.txb||new ea.TransactionBlock;return I.moveCall({target:`${u.PackageId}::swap_router::${w}`,typeArguments:v,arguments:[...l.map(({pool:x})=>I.object(x)),I.makeMoveVec({objects:this.coin.convertTradeCoins(I,h,e,s)}),I.pure((r?s:a).toFixed(0),"u64"),I.pure(this.amountOutWithSlippage(r?a:s,o,r),"u64"),...T.map(x=>I.pure(x,"u128")),I.pure(r,"bool"),I.pure(i,"address"),I.pure(Date.now()+Pb*3,"u64"),I.object(ta.SUI_CLOCK_OBJECT_ID),I.object(u.Versioned)]}),I}async computeSwapResult(t){let{pools:e,amountSpecified:n,amountSpecifiedIsInput:i,address:r,tickStep:o}=t,s=await this.contract.getConfig(),a=e.map(w=>w.pool),u=await So(this.provider,a,{showContent:!0}),l=new ea.TransactionBlock;u.map(async w=>{let v=Pn(w),T=e.find(E=>E.pool===v.id.id),I=this.math.bitsToNumber(v.tick_current_index.fields.bits),x=I-v.tick_spacing*(o||Ys),P=I+v.tick_spacing*(o||Ys);x=x<Js?Js:x,P=P>Xs?Xs:P;let O=this.pool.parsePoolType(na(w));l.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:O,arguments:[l.object(v.id.id),l.pure(T.a2b,"bool"),l.pure(new N(n).toFixed(0),"u128"),l.pure(i,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(T.a2b?x:P).toString(),"u128"),l.object(ta.SUI_CLOCK_OBJECT_ID),l.object(s.Versioned)]})});let h=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:r});if(h.error)throw new Error(h.error);return h.events.map(w=>w.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:n,address:i,tickStep:r}=t,o=await this.contract.getConfig(),s=e.map(h=>h.pool),a=await So(this.provider,Array.from(new Set(s)),{showContent:!0}),u=new ea.TransactionBlock;e.forEach(async h=>{let w=a.find(O=>ia(O)===h.pool),v=Pn(w),T=this.math.bitsToNumber(v.tick_current_index.fields.bits),I=T-v.tick_spacing*(r||Ys),x=T+v.tick_spacing*(r||Ys);I=I<Js?Js:I,x=x>Xs?Xs:x;let P=this.pool.parsePoolType(na(w));u.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:P,arguments:[u.object(v.id.id),u.pure(h.a2b,"bool"),u.pure(new N(h.amountSpecified).toFixed(0),"u128"),u.pure(n,"bool"),u.pure(this.math.tickIndexToSqrtPriceX64(h.a2b?I:x).toString(),"u128"),u.object(ta.SUI_CLOCK_OBJECT_ID),u.object(o.Versioned)]})});let l=await this.provider.devInspectTransactionBlock({transactionBlock:u,sender:i});if(l.error)throw new Error(l.error);return l.events.map(h=>h.parsedJson)}getFunctionNameAndTypeArguments(t,e,n){let i=[],r=["swap"];if(t.length===1)i=t[0],e===i[0]?r.push("a","b"):r.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(r.push("a","b"),i.push(o[0],o[2],o[1])):(r.push("b","a"),i.push(o[1],o[2],o[0])),i.push(s[2],n),n===s[0]?r.push("c","b"):r.push("b","c")}return{functionName:r.join("_"),typeArguments:i}}amountOutWithSlippage(t,e,n){if(n){let r=new N(100).minus(e).div(100);return new N(t).mul(r).toFixed(0)}let i=new N(100).plus(e).div(100);return new N(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new N(t).mul(n?new N(100).minus(e).div(100):new N(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,i,r);return s.lt(new xu.BN(Su))?Su:s.gt(new xu.BN(Cu))?Cu:s.toString()}},Rt=class{constructor(t,e){this.network=t,On(this,"pool"),On(this,"contract"),On(this,"math",new kb),On(this,"account",new pb),On(this,"coin"),On(this,"nft"),On(this,"trade"),On(this,"provider"),this.provider=e?e instanceof Ri.SuiClient?e:new Ri.SuiClient(e):new Ri.SuiClient({url:t==="mainnet"?(0,Ri.getFullnodeUrl)("mainnet"):(0,Ri.getFullnodeUrl)("testnet")}),this.contract=new vb(this),this.pool=new Tb(this),this.nft=new Ib(this),this.coin=new Ob(this),this.trade=new Db(this)}};var Eb=Object.defineProperty,km=(t,e)=>{for(var n in e)Eb(t,n,{get:e[n],enumerable:!0})},ve=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Cm.default)(this.data))}},Ku={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"},tn={launchpad:{package_id:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",published_at:"0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4",config:{pools_id:"0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3",admin_cap_id:"0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980",config_cap_id:"0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1"}},ido:{package_id:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",published_at:"0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59",config:{pools_id:"0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762",admin_cap_id:"0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce",package_version_id:"0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22"}},xcetus:{package_id:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",published_at:"0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606",config:{xcetus_manager_id:"0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d",lock_manager_id:"0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28",lock_handle_id:"0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49"}},xcetus_dividends:{package_id:"0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10",published_at:"0xcec352932edc6663a118e8d64ed54da6b8107e8719603bf728f80717592cd9e8",version:3,config:{dividend_manager_id:"0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5",dividend_admin_id:"",dividend_settle_id:""}},cetus_faucet:{package_id:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",published_at:"0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b"},xtoken:{package_id:"",published_at:"",config:{xtoken_manager_id:"",lock_manager_id:"",lock_handle_id:""}},xtoken_dividends:{package_id:"",published_at:"",config:{dividend_manager_id:"",dividend_admin_id:"",dividend_settle_id:""}},token_faucet:{package_id:"",published_at:""},booster:{package_id:"",published_at:"",config:{booster_config_id:"",booster_pool_handle:""}},maker_bonus:{package_id:"",published_at:"",config:{maker_config_id:"",maker_pool_handle:""}},liquidity_stratefy:{package_id:"",published_at:"",version:void 0,config:void 0},vaults:{package_id:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",published_at:"0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05",version:1,config:{admin_cap_id:"0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375",vaults_manager_id:"0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6",vaults_pool_handle:"0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd"}},limit_order:{package_id:"",published_at:"",version:1,config:{rate_orders_indexer_id:"",rate_orders_indexer_handle:"",global_config_id:"",token_list_handle:"",user_orders_indexer_id:"",user_orders_indexer_handle:""}},frams:{package_id:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",published_at:"0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526",version:1,config:{global_config_id:"0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e",rewarder_manager_id:"0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5",rewarder_manager_handle:"0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa",admin_cap_id:"0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c"}},haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d",version:1,config:{support_stakings:[{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}]}}},Dn=new ar(Ku),Mb=async(t,e,n)=>(console.log("getAddLiquidityTxb suiClient: ",n),console.log("getAddLiquidityTxb txbParams: ",t),Dn.senderAddress=e.address,await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),Bb=async(t,e,n)=>(console.log("getIncreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,console.log("getIncreaseLiquidityTxb txbParams: ",t),await Dn.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),jb=async(t,e,n)=>(console.log("getRemoveLiquidityTxb txbParams: ",t),console.log("getRemoveLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.closePositionTransactionPayload(t?.parameter)),Nb=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb txbParams: ",t),console.log("getDecreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.removeLiquidityTransactionPayload(t?.parameter)),Fb=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb txbParams: ",t),console.log("getClaimFeeAndMiningTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Rewarder.collectRewarderTransactionPayload(t?.parameter)),Rb=class Sm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("AddLiquidityIntention this.data: ",this.data),console.log("AddLiquidityIntention txbParams: ",r);let o=await Mb(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Sm(e)}},qb=class Am extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("ClaimFeeAndMiningIntention this.data: ",this.data),console.log("ClaimFeeAndMiningIntention txbParams: ",r);let o=await Fb(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new Am(e)}},Lb=class xm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("DecreaseLiquidityIntention this.data: ",this.data),console.log("DecreaseLiquidityIntention txbParams: ",r);let o=await Nb(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new xm(e)}},qt=new ar(Ku),$b=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.openPositionAddLiquidityStakePaylod(t?.parameter)),Ub=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.addLiquidityFixCoinPayload(t?.parameter)),Kb=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.removeLiquidityPayload(t?.parameter)),zb=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.removeLiquidityPayload(t?.parameter)),Vb=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.claimFeeAndClmmReward(t?.parameter)),Im=async(t,e,n)=>(console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.batchHarvestPayload(t?.parameter)),Gb=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.depositPayload(t?.parameter)),Wb=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),qt.senderAddress=e.address,await new Ut(tn,qt).Farms.withdrawPayload(t?.parameter)),Hb=class Om extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingAddLiquidityIntention this.data: ",this.data),console.log("FarmingAddLiquidityIntention txbParams: ",r);let o=await $b(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new Om(e)}},Zb=class Pm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingBatchHarvestIntention this.data: ",this.data),console.log("FarmingBatchHarvestIntention txbParams: ",r);let o=await Im(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Pm(e)}},Xb=class Dm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingClaimFeeAndRewardIntention this.data: ",this.data),console.log("FarmingClaimFeeAndRewardIntention txbParams: ",r);let o=await Vb(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new Dm(e)}},Jb=class Em extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingDecreaseLiquidityIntention this.data: ",this.data),console.log("FarmingDecreaseLiquidityIntention txbParams: ",r);let o=await Kb(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Em(e)}},Yb=class Mm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingHarvestIntention this.data: ",this.data),console.log("FarmingHarvestIntention txbParams: ",r);let o=await Im(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new Mm(e)}},Qb=class Bm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingIncreaseLiquidityIntention this.data: ",this.data),console.log("FarmingIncreaseLiquidityIntention txbParams: ",r);let o=await Ub(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Bm(e)}},ev=class jm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingRemoveLiquidityIntention this.data: ",this.data),console.log("FarmingRemoveLiquidityIntention txbParams: ",r);let o=await zb(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new jm(e)}},tv=class Nm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingStakeIntention this.data: ",this.data),console.log("FarmingStakeIntention txbParams: ",r);let o=await Gb(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new Nm(e)}},nv=class Fm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("FarmingUnstakeIntention this.data: ",this.data),console.log("FarmingUnstakeIntention txbParams: ",r);let o=await Wb(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new Fm(e)}},iv=class Rm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("IncreaseLiquidityIntention this.data: ",this.data),console.log("IncreaseLiquidityIntention txbParams: ",r);let o=await Bb(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Rm(e)}},rv=class qm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("RemoveLiquidityIntention this.data: ",this.data),console.log("RemoveLiquidityIntention txbParams: ",r);let o=await jb(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new qm(e)}},En=new ar(Ku),ov=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.convertPayload(t?.parameter)),sv=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemLockPayload(t?.parameter)),av=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemDividendV2Payload(t.parameter.venft_id,t.parameter.bonus_types,t.parameter.xTokenType)),cv=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.cancelRedeemPayload(t?.parameter)),uv=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Ut(tn,En).XCetusModule.redeemPayload(t?.parameter)),lv=class Lm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusCancelIntention this.data: ",this.data),console.log("XcetusCancelIntention txbParams: ",r);let o=await cv(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Lm(e)}},dv=class $m extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusClaimingStakeRewardsIntention this.data: ",this.data),console.log("XcetusClaimingStakeRewardsIntention txbParams: ",r);let o=await av(r,n,i);return console.log("XcetusClaimingStakeRewardsIntention build txb: ",o),o}static fromData(e){return new $m(e)}},fv=class Um extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusConvertIntention this.data: ",this.data),console.log("XcetusConvertIntention txbParams: ",r);let o=await ov(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new Um(e)}},hv=class Km extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemIntention this.data: ",this.data),console.log("XcetusRedeemIntention txbParams: ",r);let o=await uv(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new Km(e)}},mv=class zm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data;console.log("XcetusRedeemLockIntention this.data: ",this.data),console.log("XcetusRedeemLockIntention txbParams: ",r);let o=await sv(r,n,i);return console.log("XcetusRedeemLockIntention build txb: ",o),o}static fromData(e){return new zm(e)}},pv=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:Tm.TransactionType.Other,txSubType:n,intentionData:{txbParams:e,action:n}}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"OpenAndAddLiquidity":i=Rb.fromData(t.intentionData);break;case"IncreaseLiquidity":i=iv.fromData(t.intentionData);break;case"DecreaseLiquidity":i=Lb.fromData(t.intentionData);break;case"RemoveLiquidity":i=rv.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=qb.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=Hb.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=Qb.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=Jb.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=ev.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=Xb.fromData(t.intentionData);break;case"FarmingHarvest":i=Yb.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=Zb.fromData(t.intentionData);break;case"FarmingStake":i=tv.fromData(t.intentionData);break;case"FarmingUnstake":i=nv.fromData(t.intentionData);break;case"xCETUSConvert":i=fv.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=mv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=dv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=lv.fromData(t.intentionData);break;case"xCETUSRedeem":i=hv.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},Gm={};km(Gm,{contractId:()=>Zm,default:()=>gv,feeObjId:()=>Ym,roleObjId:()=>Xm,status:()=>Hm,transaction:()=>Wm,upgradeCapObjId:()=>Qm,vaultObjId:()=>Jm});var Wm="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Hm="success",Zm="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Xm="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Jm="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Ym="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Qm="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",gv={transaction:Wm,status:Hm,contractId:Zm,roleObjId:Xm,vaultObjId:Jm,feeObjId:Ym,upgradeCapObjId:Qm},ep={};km(ep,{contractId:()=>ip,default:()=>_v,feeObjId:()=>sp,roleObjId:()=>rp,status:()=>np,transaction:()=>tp,upgradeCapObjId:()=>ap,vaultObjId:()=>op});var tp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",np="success",ip="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",rp="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",op="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",sp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",ap="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",_v={transaction:tp,status:np,contractId:ip,roleObjId:rp,vaultObjId:op,feeObjId:sp,upgradeCapObjId:ap},yv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",wv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",bv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",vv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",kv="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Tv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Cv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Sv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Xh=Gm,Jh=ep,Av=new Map([["dev",{env:"dev",rpc:{url:yv},backend:{url:kv},contract:Xh}],["stg",{env:"stg",rpc:{url:wv},backend:{url:Tv},contract:Xh}],["prev",{env:"prev",rpc:{url:bv},backend:{url:Cv},contract:Jh}],["prod",{env:"prod",rpc:{url:vv},backend:{url:Sv},contract:Jh}]]);function xv(t,e){let n=Av.get(t);if(!n)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(n.rpc=e.rpc),e&&e.backend&&(n.backend=e.backend),e&&e.contract&&(n.contract=e.contract),n}var nn=class extends Error{mpayErrorCode;context;constructor(t,e,n={}){let{cause:i,context:r}=n;i?super(`[MPay] ${e}: ${i}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=r}},Iv=class extends nn{constructor(){super(11,"Backend is not specified")}},Ov=class extends nn{constructor(){super(1,"Wallet not connected")}},Ou=class extends nn{constructor(t,e){super(10,t,{context:e})}},Pv=class Li{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof zn.AxiosError)throw new Ou(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Ou(e.data.code)}throw new Ou(e.status.toString())}async getIncomingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return Li.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{sender:e,...n});return Li.parseResponseData(i)}async getStreamHistory(e){let n=await zn.default.post(`${this.apiURL}/stream-events`,e),i=Li.parseResponseData(n);return i.data.forEach(r=>{let o=r;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}),i}async getAllCoinTypes(e){let n=await zn.default.post(`${this.apiURL}/stream-info`,{address:e});return Li.parseResponseData(n)}async getAllRecipients(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return Li.parseResponseData(i)}async getAllSenders(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return Li.parseResponseData(i)}},up=class lp{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new cp.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Pv(e.backend.url))}static new(e,n){let i=xv(e,n);return new lp(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Iv;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 Ov;return this.signer}async walletAddress(){return this.wallet.address()}},Yh=50n,Pu=10000n,Dv=25n,Qh=100000000n,qi=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},em=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ca=class dp{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(n,i){if(i in n)return Reflect.get(n,i);let r=s=>new dp(n.result[s]);if(i===Symbol.iterator)return function*(){let s=0;for(;;)yield r(s),s++};if(typeof i=="symbol")return;let o=parseInt(i,10);if(!(Number.isNaN(o)||o<0))return r(o)}})}moveArg(){return this.result}},tm=class extends nn{constructor(t,e){super(3,t,{context:e})}},Ev=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 n=this.callResult(t);return this.returnValue(n,e)}getAddress(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="address")throw new tm("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,fp.normalizeSuiAddress)(Mu.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new tm("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Mu.Buffer.from(n).readBigInt64LE()}},en=class extends nn{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},hp={groupId:"string",name:"string"},Mv=64;function Bv(t){return mp(t),zu.bcs.ser(hp,t).toString("base64")}function Bu(t){let e=zu.bcs.de(hp,t,"base64");return mp(e),e}function mp(t){if(!nm(t.name))throw new en("Invalid metadata: Name contains unknown character");if(!nm(t.groupId))throw new en("Invalid metadata: Group ID contains unknown character");if(t.name.length>Mv)throw new en("Invalid metadata: Name exceed max length 64")}function nm(t){return/^[\x00-\x7F]+$/.test(t)}function pp(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}function Pr(t,e){return(0,Do.normalizeStructTag)(t)===(0,Do.normalizeStructTag)(e)}var gp="txn.gas";function jv(){return yf()}var ju=class _p{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:Bv({name:e.name,groupId:jv()}),coinType:(0,Po.normalizeStructTag)(e.coinType),recipients:e.recipients.map(n=>({address:n.address,cliffAmount:n.cliffAmount,amountPerEpoch:n.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let n=new Eu.TransactionBlock,i=this.calculateFeesInternal(e),r=this.getCreateStreamCoinRequests(e,i),o=await this.wallet.requestCoins(r),s=await this.addMergeCoins(n,o[0]),a;r.length>1?a=await this.addMergeCoins(n,o[1]):a=s;for(let u=0;u<e.recipients.length;u++){let l=e.recipients[u],h=this.amountForRecipient(l,e.numberEpoch),w=this.getStreamFeeLocal(h),[v]=n.splitCoins(s,[n.pure(h+w,"u64")]),[T]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new ca(v),flatFeeCoin:new ca(T),metadata:e.metadata,recipient:l.address,timeStart:e.startTime,cliff:l.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:l.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return n}calculateCreateStreamFees(e){let n=_p.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Yh,denominator:Pu},claimFeePercent:{numerator:Dv,denominator:Pu},flatFeePerStream:Qh}}async addMergeCoins(e,n){let i;return n.mergedCoins&&n.mergedCoins.length?(e.mergeCoins(e.object(n.primaryCoin),n.mergedCoins.map(r=>e.object(r))),i=e.object(n.primaryCoin)):n.primaryCoin===gp?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return pp(i,Po.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Po.SUI_TYPE_ARG,amount:n.flatFeeAmount}]}calculateFeesInternal(e){let n=e.recipients.reduce((i,r)=>{let o=this.amountForRecipient(r,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:i.totalAmount+o,streamFeeAmount:i.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...n}}amountForRecipient(e,n){return BigInt(e.amountPerEpoch)*BigInt(n)+BigInt(e.cliffAmount)}get flatSuiFee(){return Qh}getStreamFeeLocal(e){return e*Yh/Pu}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new Eu.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new Ev(i).getU64()}get wallet(){return this.globals.wallet}},Nv="0x0000000000000000000000000000000000000000000000000000000000000006",yp=class{constructor(t,e,n){this.moduleName=t,this.config=e,this.globals=n}addContractCall(t,e){let n=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Nu.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof em?i.moveArgs(t):i instanceof qi?i.moveArg(t):i instanceof ca?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(Nu.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof em?r.moveArgs(t):r instanceof qi?r.moveArg(t):r instanceof ca?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new qi(t):t}vaultObject(){return new qi(this.config.vaultObjId)}roleObject(){return new qi(this.config.roleObjId)}feeObject(){return new qi(this.config.feeObjId)}clockObject(){return new qi(Nv)}},wp=class di extends yp{constructor(e,n){super(di.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_streaming_flat_fee,arguments:[i,r,n],typeArgs:[]})}setClaimFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:di.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:di.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:di.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:di.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},la=class Bt extends yp{constructor(e,n){super(Bt.ModuleName,e,n),this.config=e,this.globals=n}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,n){let i=this.feeObject(),r=this.vaultObject(),o=this.makeObject(n.paymentCoin),s=this.makeObject(n.flatFeeCoin),a=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.create_stream,arguments:[i,r,o,s,n.metadata,n.recipient,n.timeStart,n.cliff,n.epochInterval,n.numEpoch,n.amountPerEpoch,n.cancelable,a],typeArgs:[n.coinType]})}setAutoClaim(e,n){let i=this.makeObject(n.streamId);return this.addContractCall(e,{method:Bt.MethodName.set_auto_claim,arguments:[i,n.enabled],typeArgs:[n.coinType]})}cancelStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.cancel_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStream(e,n){let i=this.makeObject(n.streamId),r=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.claim_stream,arguments:[i,r],typeArgs:[n.coinType]})}claimStreamByProxy(e,n){let i=this.makeObject(n.streamId),r=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Bt.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Bt.ModuleName}::${Bt.MethodName.claim_stream_by_proxy}`}},bp=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new wp(e,t),this.streamContract=new la(e,t)}feeContract;streamContract;async createStreams(t){let e=ju.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new ju(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new Io.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Io.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Io.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},kn=class extends nn{constructor(t,e={}){super(0,t,e)}};async function Fv(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Rv=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)}},vp=class{constructor(t){this.requester=t,this.pager=new Rv(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]}},qv=class extends nn{constructor(t,e,n){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:n}}),this.coinType=t,this.requestAmount=e,this.gotAmount=n}},Lv=25;async function $v(t,e,n,i="0x2::sui::SUI",r=Lv){let o=new Uv(t,e,i,r),s=BigInt(0),a=[];for(;await o.hasNext()&&s<n;){let u=await o.next();u&&(a.push(u),s+=BigInt(u.balance))}if(s<n)throw new qv(i,n,s);return a}var Uv=class extends vp{constructor(t,e,n,i){super(new Kv(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},Kv=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new kn("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}}},zv=class extends nn{constructor(){super(7,"Connected wallet is not creator")}},im=class extends nn{constructor(){super(8,"Connected wallet is not recipient")}},rm=class extends nn{constructor(t,e){super(6,t,{context:e})}},Vv=class extends nn{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},Gv=(1n<<64n)-1n,ua=1e3;function om(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return be.fromMillis(n*ua)}function sm(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/ua);return Pe.fromMillis(n*ua)}var Vu=class fi{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new la(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await fi.fetchStreamData(e,n);return new fi(e,n,i)}static fromObjectData(e,n,i){let r=fi.parseRawStreamData(n,i);return new fi(e,n,r)}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 fi.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new kn("Object Id does not align");this.rawData=fi.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 zv;let e=new Oo.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new im;let e=new Oo.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 im;let n=new Oo.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new Oo.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,Eo.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 sm(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Bu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Bu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return om(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return sm(n)}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:om((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===Gv?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=be.now().toMillis(),n=this.timeStart.toMillis();if(e<n)return-1n;let i=Math.floor((e-n)/Number(this.rawData.config.epochInterval));return BigInt(i)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(i)}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,n){let i=await e.suiClient.getObject({id:n,options:{showContent:!0,showType:!0}});return fi.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new Vv(e):new rm(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new rm("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Eo.parseStructTag)(i.type),o=(0,Eo.normalizeStructTag)(r[0]),s=i.fields,a=s.config.fields,u=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(a.amount_per_epoch),cancelable:a.cancelable,cliff:BigInt(a.cliff),creator:a.creator,epochInterval:BigInt(a.epoch_interval),metadata:a.metadata,recipient:a.recipient,timeStart:BigInt(a.time_start),totalEpoch:BigInt(a.total_epoch)},status:{status:u.status,epochCanceled:BigInt(u.epoch_canceled),epochClaimed:BigInt(u.epoch_claimed)}}}},Wv=class extends nn{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},Hv=1e3,Zv=class{constructor(t){this.globals=t,this.coinMetaHelper=new Xv(t.suiClient),this.createStreamHelper=new bp(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new Wv(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 en("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},n=t.totalAmount*e.numerator/e.denominator,i=(t.totalAmount-n)/t.steps,r={realTotalAmount:i*t.steps+n,cliffAmount:n,amountPerStep:i};return this.validateStreamAmount(r,t.totalAmount),r}calculateTimelineByInterval(t){if(t.steps===0n)throw new en("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),n={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(n),n}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new en("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(Pe.fromMillis(Number(e*t.steps))),i={timeStart:t.timeStart,timeEnd:n,interval:Pe.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(i),i}async getBalance(t,e){let n=await this.globals.suiClient.getBalance({owner:t,coinType:e}),i=await this.getCoinMeta(e);return{...n,coinType:(0,Mr.normalizeStructTag)(n.coinType),coinMeta:i}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),n=await Promise.all(e.map(i=>this.getCoinMeta(i.coinType)));return e.map((i,r)=>({...i,coinType:(0,Mr.normalizeStructTag)(i.coinType),coinMeta:n[r]}))}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 en("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new en("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Hv)throw new en("Interval shall be at least 1 second","interval",t.interval)}},Xv=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Mr.normalizeStructTag)(t||Mr.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let n=await this.queryCoinMeta(e);return n&&this.coinMetaReg.set(e,n),n}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},Du=class extends nn{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}},Jv=25;async function am(t,e,n){let i=new kp(e),r=new Tp(t,i,n);return await Fv(r)}var kp=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]}},Tp=class extends vp{constructor(t,e,n){super(new Yv(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},Yv=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||Jv,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let i=await this.stringIter.next();i&&t.push(i)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),n;if(this.filter){let{filter:i}=this;n=e.filter(r=>i?.(r))}else n=e;return{data:n,hasNext:await this.stringIter.hasNext()}}},Qv=class ra{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new Du("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new en("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await am(e.suiClient,n);return i.forEach(r=>{if(!r)throw new kn("stream group object data undefined")}),ra.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await ra.parseGroupStreams(e,n,i);return new ra(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{e1(i,o)||(r=!1)}),r}async refresh(){let e=await am(this.globals.suiClient,this.streams.map(n=>n.streamId));this.streams.forEach((n,i)=>{n.refreshWithData(e[i])})}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,n)=>e+n.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,n)=>e+n.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,n)=>n.nextReleaseAmount===null?e:e+n.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,n)=>e+n.totalAmount,0n),streamed:this.streams.reduce((e,n)=>e+n.streamedAmount,0n),claimed:this.streams.reduce((e,n)=>e+n.claimedAmount,0n),claimable:this.streams.reduce((e,n)=>e+n.claimable,0n),canceled:this.streams.reduce((e,n)=>e+n.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,n,i){let r=i.map((o,s)=>Vu.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new Du("Not same group ID");if(!this.checkStreamGroup(r))throw new Du("Not same stream settings");return r}};function e1(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 cm=class Fu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await um.newIncoming(e);return new Fu(n,e.pageSize)}static async newOutgoing(e){let n=await um.newOutgoing(e);return new Fu(n,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}},um=class Ru{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await lm.newIncomingQuery(e);return new Ru(n)}static async newOutgoing(e){let n=await lm.newOutgoingQuery(e);return new Ru(n)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let n=await this.requester.doNextRequest();if(n===null)throw new kn("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new kn("No more results");return e}},lm=class qu{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new kp(i.flat().map(s=>s.streamId));this.objectIter=new Tp(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=o1(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,gi.normalizeSuiAddress)(s.recipient)===(0,gi.normalizeSuiAddress)(i)),o=dm(r);return new qu(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=s1(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=dm(r);return new qu(e.globals,i,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let n=await i1(this.globals,e[0].streamId,this.objectIter);return this.current++,Cp(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await r1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,n1(n,this.query)?n:this.doNextRequest()}throw new kn("Stream group with no stream")}};function dm(t){let e=new Map;return t.forEach(n=>{let i=e.get(n.groupId);i?(i.push(n),e.set(n.groupId,i)):e.set(n.groupId,[n])}),Array.from(e.values()).sort((n,i)=>be.fromISO(i[0].createDate).toMillis()-be.fromISO(n[0].createDate).toMillis())}function Cp(t,e){if(e===void 0)return!0;let n=t1(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let i=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return n&&i}return n}function t1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function n1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{Cp(i,e)&&(n=!0)}),n}async function i1(t,e,n){let i=await Sp(n,e);return Vu.fromObjectData(t,e,i)}async function r1(t,e,n){let i=[];for(;i.length<e.length;){let r=await Sp(n,e[i.length]);i.push(r)}return Qv.newFromObjectResponse(t,e,i)}async function Sp(t,e){if(!await t.hasNext())throw new kn("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new kn("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new kn("stream id not aligned");return n}function o1(t){return{status:Gu(t?.status),coinType:Ap(t?.coinType),sender:xp(t?.sender)}}function s1(t){return{status:Gu(t?.status),coinType:Ap(t?.coinType),recipient:xp(t?.recipient)}}function Gu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=Gu(n);return!e||e===i?i:"all"},void 0):a1(t)}function a1(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new en("Unknown stream filtered status")}}function Ap(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeStructTag)(e)):void 0:(0,gi.normalizeStructTag)(t)}function xp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeSuiAddress)(e)):void 0:(0,gi.normalizeSuiAddress)(t)}var c1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},u1=class{constructor(t){this.account=t}async address(){return this.account.address}},l1=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(pp(t.coinType,Ui.SUI_TYPE_ARG))return{primaryCoin:gp};if(t.amount<=0)throw new en("Invalid coin request","coinAmount",t.amount);let e=await $v(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new kn("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},d1=class{globals;helper;constructor(t,e){this.globals=up.new(t,e),this.helper=new Zv(this.globals)}connectSingleWallet(t){let e=new l1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new c1(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return Vu.new(this.globals,t)}async getIncomingStreams(t,e=10){return cm.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return cm.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,Ui.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,Ui.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,Ui.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new bp(this.globals)}},f1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Ip.default)(this.data))}},Mo=class extends f1{application="mpay";getClient(t,e){let n=new d1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new u1(e)),n}},fm=class extends Mo{constructor(t){super(t),this.data=t}txType=Vm.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},hm=class extends Mo{constructor(t){super(t),this.data=t}txType=Op.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},mm=class extends Mo{constructor(t){super(t),this.data=t}txType=Pp.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},pm=class extends Mo{constructor(t){super(t),this.data=t}txType=Dp.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Ep=class oa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return oa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return oa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,hi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return oa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}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,hi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,hi.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,hi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,hi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Lu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,hi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},h1=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"&&Pr(e.target,this.contract.createStreamTarget));if(t.length===0)throw new kn("No create stream transactions");return t.map(e=>new Ep(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Bu(e),r=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),a=t.decodeInputU64(8),u=t.decodeInputU64(9),l=t.decodeInputU64(10),h=t.decodeInputBool(11),w=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:u,amountPerEpoch:l,cancelable:h,coinType:w}}aggregateGroupStreamInfo(t){if(new Set(t.map(n=>JSON.stringify({name:n.name,groupId:n.groupId,timeStart:String(n.timeStart),epochInterval:String(n.epochInterval),totalEpoch:String(n.totalEpoch),cancelable:n.cancelable,coinType:n.coinType}))).size!==1)throw new en("Stream group not have common info");let e=t.map(n=>({address:n.recipient,amountPerStep:n.amountPerEpoch,cliffAmount:n.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 la(this.globals.envConfig.contract,this.globals)}get feeContract(){return new wp(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new ju(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]}},m1=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new la(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"&&Pr(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Pr(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new h1(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 Ep(t,this.txb)}},gm=class extends Mo{constructor(t){super(t),this.data=t}txType=Mp.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},p1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=up.new(e==="sui:mainnet"?"prod":"dev"),r=new m1(i,n).decode(),o;switch(r.type){case"CreateStream":o=new pm(r.info);break;case"SetAutoClaim":o=new gm({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new mm({streamId:r.streamId});break;case"ClaimByProxy":o=new hm({streamId:r.streamId});break;case"Cancel":o=new fm({streamId:r.streamId});break;default:throw new Error(`Unknown transaction type: ${r}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,n;switch(t.txSubType){case"CreateStream":n=new pm(e);break;case"Claim":n=new mm(e);break;case"ClaimByProxy":n=new hm(e);break;case"SetAutoClaim":n=new gm(e);break;case"Cancel":n=new fm(e);break;default:throw new Error("not implemented")}return n.build({...t})}},g1=class jp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Bp.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new jp(e)}},_1=class Fp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Np.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new Fp(e)}},y1=class Lp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=qp.TransactionBlock.from(this.data.content);if(!(0,Rp.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new Lp(e)}},w1=class{application;constructor(){this.application=Er.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case Er.TransactionSubTypes.assets.coin.send:i=g1.fromData(t.intentionData);break;case Er.TransactionSubTypes.assets.object.send:i=_1.fromData(t.intentionData);break;case Er.TransactionSubTypes.others.plain:i=y1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},b1={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"}}},ye=b1,v1=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(`${ye.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ye.pool).find(n=>n.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===`${ye.ProtocolPackage}::incentive_v2::claim_reward`){let n=new _m(e,this.txb),i=n.decodeInputU8(4),r=n.decodeInputU8(5),o=n.decodeSharedObjectId(2),s=this.findPoolByAssetId(i),a=[...e.typeArguments];t.push({coinType:s.coinType,option:r,typeArguments:a,assetId:i,poolId:o})}}),console.log("decode claims",t),{txType:Dr.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:n.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),n=this.findPoolByAssetId(t);return{txType:Dr.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ye.ProtocolPackage));return new _m(t,this.txb)}},_m=class sa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return sa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return sa.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,mi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return sa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}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,mi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,mi.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,mi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,mi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return $u.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,mi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function ym(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function k1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.Incentive),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function T1(t,e,n){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function wm(t,e,n,i){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ye.PriceOracle),t.object(ye.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(ye.IncentiveV2)],typeArguments:[e.type]}),t}function C1(t,e,n,i,r){return t.moveCall({target:`${ye.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ye.IncentiveV2),t.object(n),t.object(ye.StorageId),t.pure(e),t.pure(i)],typeArguments:r}),t}var S1=class Kp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Up.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;C1(n,r,o,s,a)}),n}static fromData(e){return new Kp(e)}},A1=class Vp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new zp.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return T1(i,r,n)}static fromData(e){return new Vp(e)}};async function Wp(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var x1=class Hp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new Gp.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return ym(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await Wp(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return ym(s,a,s.object(l),o)}static fromData(e){return new Hp(e)}},I1=class Xp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e,{coinType:r,amount:o}=this.data,s=new Zp.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return wm(s,ye.pool.sui,h,o)}let a=ye.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(ye.pool).join(", ")}.`);let u=await Wp(n,i.address,a.type);if(!u.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let l=u.data[0].coinObjectId;if(u.data.length>=2){let h=1;for(;h<u.data.length;)s.mergeCoins(l,[u.data[h].coinObjectId]),h++}return wm(s,a,s.object(l),o)}static fromData(e){return new Xp(e)}},O1=class Yp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new Jp.TransactionBlock;console.log("build",this.data);let r=ye.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(ye.pool).join(", ")}.`);return k1(i,r,n)}static fromData(e){return new Yp(e)}},P1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new v1(e).decode();return{txType:$p.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=x1.fromData(t.intentionData);break;case"EntryBorrow":i=A1.fromData(t.intentionData);break;case"EntryRepay":i=I1.fromData(t.intentionData);break;case"EntryWithdraw":i=O1.fromData(t.intentionData);break;case"ClaimReward":i=S1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},D1="msafe-plain-tx",E1=da.TransactionSubTypes.others.plain,M1=class{application;constructor(){this.application=D1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:da.TransactionType.Other,txSubType:E1,intentionData:{content:(0,fa.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=Qp.TransactionBlock.from((0,fa.fromHEX)(t.intentionData.content)),r=await e.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(r.effects.status.status!=="success")throw new Error(r.effects.status.error);return i}},B1=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}},Or={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},j1=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(t){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();if(this.isIncreaseLiquidityTransaction())return this.decodeIncreaseLiquidity(t);if(this.isDecreaseLiquidityTransaction())return this.decodeDecreaseLiquidity(t);if(this.isCollectFeeLiquidityTransaction())return this.decodeCollectFeeLiquidity();if(this.isCollectRewardLiquidityTransaction())return this.decodeCollectRewardLiquidity();if(this.isBurnTransaction())return this.decodeCollectRewardLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::collect`)}isCollectRewardLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::collect`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${Or.PackageId}::position_manager::burn`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),i=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(4),o=this.helper.decodeInputU32(6);return{txType:$i.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:r,tickUpper:o}}}decodeIncreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(4),i=this.helper.decodeInputU64(5),r=this.helper.decodeInputU64(6);return{txType:$i.TransactionType.Other,type:"IncreaseLiquidity",intentionData:{pool:e,slippage:5,address:t,amountA:i,amountB:r,nft:n}}}decodeDecreaseLiquidity(t){let e=this.helper.decodeSharedObjectId(0),n=this.helper.decodeSharedObjectId(2),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4),o=this.helper.decodeInputU64(5);return{txType:$i.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:e,decreaseLiquidity:i,nft:n,amountA:r,amountB:o,slippage:3,address:t}}}decodeCollectFeeLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5),i=this.helper.decodeInputU64(3),r=this.helper.decodeInputU64(4);return{txType:$i.TransactionType.Other,type:"CollectFee",intentionData:{pool:t,address:n,collectAmountA:i,collectAmountB:r,nft:e}}}decodeCollectRewardLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2),n=this.helper.decodeInputAddress(5);return{txType:$i.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:[0,0,0],nft:e}}}decodeBurnLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:$i.TransactionType.Other,type:"Burn",intentionData:{pool:t,nft:e}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new bm(t,this.txb)}get helpers(){console.log(this.transactions,"this.transactions");let t=this.transactions.filter(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),t.map(e=>new bm(e,this.txb))}},bm=class aa{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return aa.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return aa.getOwnedObjectId(n)}decodeInputU128(e){let n=this.decodePureArg(e,"u128");return Number(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU32(e){let n=this.decodePureArg(e,"u32");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,pi.normalizeSuiAddress)(n)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,n){let i=this.getInputParam(e);return aa.getPureInputValue(i,n)}getInputParam(e){let n=this.moveCall.arguments[e];if(n.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[n.index]}static getPureInputValue(e,n){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}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,pi.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,pi.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,pi.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,pi.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,n){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 i=e.value.Pure;return Uu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,pi.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},N1=class tg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:u,tickUpper:l,txb:h}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,txb:h})}static fromData(e){return new tg(e)}},F1=class ng extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,nft:r,txb:o}=this.data;return n.nft.burn({pool:i,nft:r,txb:o})}static fromData(e){return new ng(e)}},R1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,txb:u}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,txb:u})}static fromData(e){return new ig(e)}},q1=class rg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,txb:a}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,txb:a})}static fromData(e){return new rg(e)}},L1=class og extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{fee:i,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,amountA:w,amountB:v,txb:T}=this.data;return n.pool.createPool({fee:i,amountA:w,amountB:v,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,txb:T})}static fromData(e){return new og(e)}},$1=class sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,txb:h}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,txb:h})}static fromData(e){return new sg(e)}},U1=class ag extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,txb:l}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,txb:l})}static fromData(e){return new ag(e)}},K1=class cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Rt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:l,nft:u,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:h,collectAmountB:w,rewardAmounts:v,txb:T})}static fromData(e){return new cg(e)}},vm=class{application="turbos";async deserialize(t){let{transactionBlock:e,account:n}=t,i=new j1(e).decode(n.address);return{txType:eg.TransactionType.Other,txSubType:i.type,intentionData:i.intentionData}}async build(t){let{suiClient:e,account:n,network:i}=t,r;switch(t.txSubType){case"CreatePool":r=L1.fromData(t.intentionData);break;case"AddLiquidity":r=N1.fromData(t.intentionData);break;case"IncreaseLiquidity":r=U1.fromData(t.intentionData);break;case"DecreaseLiquidity":r=$1.fromData(t.intentionData);break;case"RemoveLiquidity":r=K1.fromData(t.intentionData);break;case"CollectFee":r=R1.fromData(t.intentionData);break;case"CollectReward":r=q1.fromData(t.intentionData);break;case"Burn":r=F1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},ha=new B1([new w1,new P1,new vm,new p1,new M1,new pv,new vm]);var Ae=require("@msafe/sui3-utils"),tl=require("@mysten/sui.js/transactions"),ba=require("@mysten/sui.js/utils");var ug=require("@mysten/sui.js/transactions"),z1=1000n,V1=120n,G1=100n,W1={multiplier:{numerator:V1,denominator:G1}};var ma=class{constructor(e){this.globals=e}async simulate(e,n=W1){let i=this.copyTransactionBlock(e.txb),{suiClient:r}=this.globals,o=await this.getGasPrice(n);i.setGasPrice(o);let s=await r.devInspectTransactionBlock({transactionBlock:i,sender:e.sender}),{gasUsed:a}=s.effects,u=this.toGasBudget(a,o),l=s.effects.status.status==="success",h;return l||(h=s.effects.status.error),{success:l,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:a,gasBudget:u,simulationError:h}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let n=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(n,e)}toGasBudget(e,n){let{computationCost:i,storageCost:r}=e,o=z1*n,s=BigInt(i)+o,a=s+BigInt(r);return a>s?a:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,n){if(this.isFixedValue(n))return n.fixedVal;if(this.isMultiplier(n)){let{multiplier:i}=n;return e*i.numerator/i.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return ug.TransactionBlock.from(e.serialize())}};var Wu=require("buffer");function pa(t){return Wu.Buffer.from(t,"utf-8")}function H1(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ga(t){return Uint8Array.from(Wu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ya=require("@mysten/sui.js/verify");var _i=require("@mysten/sui.js/utils");var _a=require("@mysten/sui.js/utils"),Bo=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,_a.normalizeStructTag)(e);if(this._coinMetaReg.has(n))return this._coinMetaReg.get(n);let i=await this.queryCoinMeta(n);return i&&this._coinMetaReg.set(n,i),i}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Hu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,jo=class t{static isCoin(e){return e?(0,_a.normalizeStructTag)(e).match(Hu)!=null:!1}static getCoinType(e){let[,n]=(0,_a.normalizeStructTag)(e).match(Hu)??[];return n||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:n}=e.content?.fields;if(n!==void 0)return BigInt(n)}};var Vn=class{static normalizeSuiAddress(e){return(0,_i.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,_i.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,_i.normalizeSuiAddress)(e)===(0,_i.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,_i.normalizeStructTag)(e)===(0,_i.normalizeStructTag)(n)}static isCoinObjectType(e){return jo.isCoin(e)}};function Zu(t,e){return t.startsWith(e)?t:e+t}var Xu=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ya.verifyTransactionBlock)(e.message,e.signature):(0,ya.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=pa(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return Vn.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=pa(e.messageStr);return this.verifySignature({message:n,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 lg=require("@msafe/sui3-utils"),dg=require("@mysten/sui.js/cryptography"),fg=require("@mysten/sui.js/multisig");var Z1="0x2::sui::SUI";async function Ju(t,e){let n;try{n=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(n.data.length===0||!n.data[0].transaction?.txSignatures)return;let r=n.data[0].transaction?.txSignatures;for(let o=0;o!==r.length;o++){let s=r[o],a=X1(s,e);if(a)return a}}function X1(t,e){let n=(0,dg.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new fg.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if(Vn.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Vn.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=lg.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return Vn.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function J1(t){let e=!0,n,i=[];for(;e;){let r=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:n});i.push(...r.data),e=r.hasNextPage,n=r.nextCursor}return i}var hg=25;async function mg(t){let e=[];for(;await t.hasNext();){let n=await t.next();e.push(n)}return e&&Array.isArray(e[0])?e.flat(1):e}var Yu=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)}},wa=class{constructor(e){this.requester=e;this.pager=new Yu(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 pg(t,e,n){let i=new Qu(t,e,n);return await mg(i)}var Qu=class extends wa{constructor(n,i,r){super(new el(n,i,r));this.provider=n;this.owner=i;this.options=r}},el=class{constructor(e,n,i){this.provider=e;this.owner=n;this.options=i;this.nextCursor=null,this.filter=i?.filter,this.pageSize=i?.pageSize||hg,this.objectOptions=i?.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 n;if(this.filter){let{filter:i}=this;n=e.data.filter(r=>i?.(r))}else n=e.data;return{data:n.map(i=>i.data).filter(i=>i),hasNext:e.hasNextPage}}};var Ki=class t{constructor(e,n){this.globals=e;this.info=n;this.multiSig=new Ae.MultiSigAccount({threshold:n.threshold,ownersWithWeight:n.owners,creationNonce:n.creationNonce}),this.coinHelper=new Bo(this.suiClient),this.simulator=new ma(e)}multiSig;coinHelper;simulator;static async New(e,n){let i=await e.backend.getMSafeAccountInfo(n);if(new t(e,i).address!==n)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 n=>{let i=await this.coinHelper.getCoinMeta(n.coinType),r=n.lockedBalance.number?BigInt(n.totalBalance)-BigInt(n.lockedBalance.number):BigInt(n.totalBalance);return{type:(0,ba.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return pg(this.suiClient,this.address,n)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let n=e.pending,i=e.reject;return{application:n.application,txType:n.txType,txSubType:n.txSubType,createdAt:n.createdAt,creator:n.creator,digest:n.digest,intention:n.intention,sequenceNumber:n.sequenceNumber,payload:n.payload,votes:n.votes,approvalWeight:this.calculateWeightFromVotes(n.votes),msafeAddress:n.msafeAddress,rejectDigest:i?.digest??"",rejectPayload:i?.payload??"",rejectVotes:i?.votes??[],rejectWeight:this.calculateWeightFromVotes(i?.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 n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,sender:this.address})}async proposeIntention(e){let n=Ae.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),i=await this.wallet.signPersonalMessage({messageStr:n});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:i.signature})}async proposeIntentionAndBuildVote(e){let n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});i.setGasPrice(e.gasPrice),i.setGasBudget(e.gasBudget),i.setSender(this.address);let r=await i.build({client:this.globals.suiClient}),o=await i.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:r});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,ba.toHEX)(r),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async proposeCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async simulateObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async proposeObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Assets,txSubType:Ae.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async simulatePlainPayloadIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async proposePlainPayloadIntention(e){let n=await this.nextSequenceNumber(),i=tl.TransactionBlock.from(e.payload);if(!i.blockData.sender||!(0,Ae.isSameAddress)(i.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Ae.TransactionDefaultApplication,txType:Ae.TransactionType.Other,txSubType:Ae.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async voteForTransaction(e,n){let i=ga(n),r=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:r.signature})}async proposePendingTransaction(e){let n=new tl.TransactionBlock,i=await n.build({client:this.suiClient}),r=await n.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:r,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let n=e.payload,i=(0,Ae.buildRejectTxb)(this.address,n);return this.simulator.simulate({txb:i,sender:this.address})}async rejectCurrentTx(e){let n=await this.pendingTransaction();if(!n||n.rejectDigest!=="")throw new Error("Already rejected");let i=n.payload,r=(0,Ae.buildRejectTxb)(this.address,i),o=await r.getDigest({client:this.suiClient}),s=await r.build({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:a.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),n=ha.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.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:i,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,n=!1){let i=n?e.rejectVotes:e.votes,r=n?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(i)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(i.map(u=>[u.userAddress,u.signature]));for(let u=0;u<this.info.owners.length;u++){let l=this.info.owners[u],h=s.get(l.address);h&&o.push(h)}let a=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ga(r),signature:a,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(n=>n.userAddress))}calculateWeight(e){let n=0;for(let i=0;i<e.length;i++){let r=this.info.owners.find(o=>(0,Ae.isSameAddress)(o.address,e[i]));r&&(n+=r.weight)}return n}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 gg=require("@msafe/sui3-utils"),_g=require("@mysten/sui.js/utils");var va=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let n=this.knownPublicKeys.get(e);if(n)return n;let i=await this._getPublicKey(e);return i&&this.knownPublicKeys.set(e,i),i}async getPublicKeyBatch(e){let n=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];n[o]=this.knownPublicKeys.get(s)}let i=n.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(i.length===0)return n;let r=await this.globals.backend.getPublicKeyBatch(i.map(o=>e[o]));for(let o=0;o<i.length;o++){let s=i[o];n[s]=r[o]}for(let o=0;o<n.length;o++)n[o]===void 0&&(n[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)n[o]&&this.knownPublicKeys.set(e[o],n[o]);return n}addPublicKey(e,n){if(!(0,gg.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,_g.normalizeSuiAddress)(e),n)}async _getPublicKey(e){let n=await this.getPublicKeyFromBackend(e);if(n)return n;let i=await this.getPublicKeyFromChain(e);if(i)return i}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Ju(this.globals.suiClient,e)}};var ka=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Cg=require("@mysten/sui.js/client");var Fo=require("@msafe/sui3-utils"),No=ge(require("axios"),1);var Ta=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let n=await this.post("/auth/login",e);return this._token=n.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 n={userAddressList:e};return(await this.get("/user/public-keys",{params:n,headers:this.headers()})).data?.map(r=>r?Fo.PublicKeySerde.de(r):void 0)}async getMSafeAccountInfo(e){let n={msafeAddress:e},i=await this.get("/msafe",{params:n,headers:this.headers()});return t.toMSafeConfig(i.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let n={status:e.status??Fo.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},i=await this.get("/msafe/owned",{params:n,headers:this.headers()});return{data:i.data.data.map(t.toMSafeConfig),meta:i.data.meta}}async updateMSafeStatus(e){let n=e;await this.post("/msafe/status",n,{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(n=>({address:n.address,weight:n.weight,publicKey:Fo.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await No.default.get(i,n)}catch(r){throw Ca.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await No.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw Ca.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Zu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=No.default.defaults;return n?n instanceof Array?e=n:e=[n]:e=[],[i=>JSON.parse(JSON.stringify(i,(r,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ca=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(No.default.isAxiosError(n)&&n?.response?.data&&"message"in n.response.data)return new t(n)}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 yg=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(yg||{}),Sa="https://fullnode.testnet.sui.io",nl="https://fullnode.mainnet.sui.io",il="http://127.0.0.1:3000",rl="http://127.0.0.1:3001",wg="https://sui-dev.m-safe.link",bg="http://13.56.226.148:81",vg="https://sui-preview.m-safe.link",kg="https://sui.m-safe.link",Tg=new Map([["unit",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["local",{suiClient:{url:Sa},backend:{url:il},syncingURL:rl,network:"sui:testnet"}],["dev",{suiClient:{url:Sa},backend:{url:wg},syncingURL:bg,network:"sui:testnet"}],["prev",{suiClient:{url:nl},backend:{url:vg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:nl},backend:{url:kg},syncingURL:"",network:"sui:mainnet"}]]);function ol(t,e){let n=Tg.get(t);if(!n)throw new Error("Unknown environment");return e?.suiClient?.url&&(n.suiClient.url=e.suiClient.url),e?.backend?.url&&(n.backend.url=e.backend.url),n}var Ro=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,n){let i=ol(e,n),r=new Cg.SuiClient(i.suiClient),o=new Ta(i.backend.url);return new t({backend:o,suiClient:r,config:i})}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 Aa=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await Ro.New(e,n);return new t(i)}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 n=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(n),n}async authSign(e){let n=xa.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),i=await e.signPersonalMessage({messageStr:n});return this.backend.authSign({address:await e.address(),message:n,signature:i.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:xa.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Ki(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new Ki(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Vi(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new va(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 Gi(this.globals)}get Invitation(){return new $o(this.globals)}get Report(){return new ka(this.globals)}async walletAddress(){return this.wallet.address()}};
2054
2054
  /*! Bundled license information:
2055
2055
 
2056
2056
  @syntsugar/cc-graph/dist/index.umd.js: