@msafe/sui3-sdk 0.0.49-pre-e5a4c1c.0 → 0.0.49-pre-5f42443.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 Ug=Object.create;var Lo=Object.defineProperty;var Kg=Object.getOwnPropertyDescriptor;var zg=Object.getOwnPropertyNames;var Vg=Object.getPrototypeOf,Gg=Object.prototype.hasOwnProperty;var Wg=(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 zg(e))!Gg.call(t,r)&&r!==n&&Lo(t,r,{get:()=>e[r],enumerable:!(i=Kg(e,r))||i.enumerable});return t};var ge=(t,e,n)=>(n=t!=null?Ug(Vg(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((Ik,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((Ok,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((Pk,Ol)=>{"use strict";var Hg=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 Qg(e)?"generatorfunction":"function";if(Zg(e))return"array";if(n_(e))return"buffer";if(t_(e))return"arguments";if(Jg(e))return"date";if(Xg(e))return"error";if(Yg(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(e_(e))return"generator";switch(n=Hg.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 Zg(t){return Array.isArray?Array.isArray(t):t instanceof Array}function Xg(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function Jg(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function Yg(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function Qg(t,e){return Il(t)==="GeneratorFunction"}function e_(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function t_(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 n_(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Uo=yi((Dk,Bl)=>{"use strict";var i_=xl(),Ha=Pl(),Dl=(t,e)=>!e||Ha(e)!=="array"?!1:e.indexOf(t)>-1,r_=(t,e)=>i_(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=r_(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,Vi=b[4]|0,Fe=Vi&8191,Ne=Vi>>>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(Fe,Qe),f=Math.imul(Fe,et),f=f+Math.imul(Ne,Qe)|0,k=Math.imul(Ne,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(Fe,tt)|0,f=f+Math.imul(Fe,nt)|0,f=f+Math.imul(Ne,tt)|0,k=k+Math.imul(Ne,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(Fe,it)|0,f=f+Math.imul(Fe,rt)|0,f=f+Math.imul(Ne,it)|0,k=k+Math.imul(Ne,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(Fe,ot)|0,f=f+Math.imul(Fe,st)|0,f=f+Math.imul(Ne,ot)|0,k=k+Math.imul(Ne,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(Fe,at)|0,f=f+Math.imul(Fe,ct)|0,f=f+Math.imul(Ne,at)|0,k=k+Math.imul(Ne,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 Fa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Fa>>>26)|0,Fa&=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(Fe,ut)|0,f=f+Math.imul(Fe,lt)|0,f=f+Math.imul(Ne,ut)|0,k=k+Math.imul(Ne,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 Na=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Na>>>26)|0,Na&=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(Fe,dt)|0,f=f+Math.imul(Fe,ft)|0,f=f+Math.imul(Ne,dt)|0,k=k+Math.imul(Ne,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(Fe,ht)|0,f=f+Math.imul(Fe,mt)|0,f=f+Math.imul(Ne,ht)|0,k=k+Math.imul(Ne,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(Fe,pt)|0,f=f+Math.imul(Fe,gt)|0,f=f+Math.imul(Ne,pt)|0,k=k+Math.imul(Ne,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(Fe,_t)|0,f=f+Math.imul(Fe,yt)|0,f=f+Math.imul(Ne,_t)|0,k=k+Math.imul(Ne,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]=Fa,m[9]=Na,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 N(){H.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(N,H),N.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 N;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:()=>Xi,__awaiter:()=>td,__classPrivateFieldGet:()=>hd,__classPrivateFieldIn:()=>pd,__classPrivateFieldSet:()=>md,__createBinding:()=>Yo,__decorate:()=>Yl,__disposeResources:()=>_d,__esDecorate:()=>Y_,__exportStar:()=>id,__extends:()=>Xl,__generator:()=>nd,__importDefault:()=>fd,__importStar:()=>dd,__makeTemplateObject:()=>ld,__metadata:()=>ed,__param:()=>Ql,__propKey:()=>e0,__read:()=>oc,__rest:()=>Jl,__runInitializers:()=>Q_,__setFunctionName:()=>t0,__spread:()=>rd,__spreadArray:()=>sd,__spreadArrays:()=>od,__values:()=>Jo,default:()=>r0});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 Y_(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 Q_(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 e0(t){return typeof t=="symbol"?t:"".concat(t)}function t0(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 Xi(t){return this instanceof Xi?(this.v=t,this):new Xi(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 Xi?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:Xi(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 n0(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 i0(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,n0,i0,r0,wd=Wg(()=>{"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]};n0=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};i0=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var i=new Error(n);return i.name="SuppressedError",i.error=t,i.suppressed=e,i};r0={__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:Xi,__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 N(){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,N([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 N,K=0;K<V.length;K++)N=V[K],N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(U,N.key,N)}function o(U,V,N){return V&&r(U.prototype,V),N&&r(U,N),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(N,K){return N.__proto__=K,N},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,N){var K=[null];K.push.apply(K,V);var C=Function.bind.apply(U,K),A=new C;return N&&u(A,N.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(N){function K(){return h(N,arguments,a(this).constructor)}if(N===null||!w(N))return N;if(typeof N!="function")throw new TypeError("Super expression must either be null or a function");if(typeof V<"u"){if(V.has(N))return V.get(N);V.set(N,K)}return K.prototype=Object.create(N.prototype,{constructor:{value:K,enumerable:!1,writable:!0,configurable:!0}}),u(K,N)},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 N,K=a(U);if(V){var C=a(this).constructor;N=Reflect.construct(K,arguments,C)}else N=K.apply(this,arguments);return I(this,N)}}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 N=U==null?null:typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(N!=null){var K,C,A=[],c=!0,d=!1;try{for(N=N.call(U);!(c=(K=N.next()).done)&&(A.push(K.value),!(V&&A.length===V));c=!0);}catch(g){d=!0,C=g}finally{try{c||N.return==null||N.return()}finally{if(d)throw C}}return A}}function B(U,V){if(U){if(typeof U=="string")return $(U,V);var N=Object.prototype.toString.call(U).slice(8,-1);return N==="Object"&&U.constructor&&(N=U.constructor.name),N==="Map"||N==="Set"?Array.from(U):N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N)?$(U,V):void 0}}function $(U,V){(V==null||V>U.length)&&(V=U.length);for(var N=0,K=Array(V);N<V;N++)K[N]=U[N];return K}function Z(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function H(U,V){var N=typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(!N){if(Array.isArray(U)||(N=B(U))||V&&U&&typeof U.length=="number"){N&&(U=N);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(){N=N.call(U)},n:function(){var g=N.next();return c=g.done,g},e:function(g){d=!0,A=g},f:function(){try{c||N.return==null||N.return()}finally{if(d)throw A}}}}var te=function(U){var V=Math.abs,N=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=N(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=N(c.length,d.length),b=C.__absoluteSubOne(c,g),p=C.__absoluteSubOne(d);return C.__absoluteXor(b,p,b).__trim()}var m=N(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=N(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,Vi=0,Fe=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 Ne=Fe*d;if(1073741823<Ne)break;if(Fe=Ne,Vi=Vi*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(Fe,Vi,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,N=Math.log;return U===0?30:0|29-(0|N(U>>>0)/V)},te.__imul=t||function(U,V){return 0|U*V},te})});var yk={};bl(yk,{AddressBookSDK:()=>Wi,COIN_TYPE_ARG_REGEX:()=>Hu,Coin:()=>jo,CoinHelper:()=>Bo,CreateHelper:()=>Gi,DEV_API_URL:()=>Fg,DEV_SYNCING_URL:()=>Ng,ENV_CONFIGS:()=>Lg,Formatter:()=>Vn,HexToUint8Array:()=>ga,LOCAL_API_URL:()=>il,LOCAL_SYNCING_URL:()=>rl,MAINNET_RPC_URL:()=>nl,MSafeAccount:()=>zi,MSafeClient:()=>Aa,MSafeEnv:()=>jg,MSafeGlobals:()=>Ro,PREV_API_URL:()=>Rg,PROD_API_URL:()=>qg,SUI_COIN:()=>pk,SignatureVerifier:()=>Xu,TESTNET_RPC_URL:()=>Sa,Uint8ArrayToHex:()=>mk,addPrefix:()=>Zu,getAllCoins:()=>_k,getMSafeConfig:()=>ol,getPublicKeyFromChain:()=>Ju,stringToBuffer:()=>pa});module.exports=kl(yk);var Mn=require("@msafe/sui3-utils"),Gi=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"),Wi=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 km=require("@msafe/sui3-utils"),Tm=require("@msafe/sui3-utils"),Cm=ge(Uo(),1);var Rr=require("@mysten/sui.js/utils"),tr=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 v0=require("@mysten/sui.js/keypairs/ed25519"),k0=require("@mysten/sui.js/keypairs/secp256k1"),Xn=ge(ke(),1),wt=ge(ke(),1);var Hi=9e15,Zn=1e9,Ya="0123456789abcdef",zo="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Vo="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Qa={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Hi,maxE:Hi,crypto:!1},ql,Bn,fe=!0,Wo="[DecimalError] ",Hn=Wo+"Invalid argument: ",Ll=Wo+"Precision limit exceeded",$l=Wo+"crypto unavailable",Ul="[object Decimal]",Ft=Math.floor,kt=Math.pow,o_=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,s_=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,a_=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Kl=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,fn=1e7,le=7,c_=9007199254740991,u_=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=l_(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=It(h.d),t=h.e,(o=(t-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=kt(n,1/3),t=Ft((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),It(a.d).slice(0,s)===(n=It(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-Ft(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=Zi(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=Zi(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=Zi(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&&Ft(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){+It(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=Ft(t.e/le),h=Ft(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=Ft(w.e/le),i=Ft(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=f_(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=It(a),(e.length+u)%2==0&&(e+="0"),l=Math.sqrt(e),u=Ft((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),It(o.d).slice(0,n)===(e=It(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=Ft(h.e/le)+Ft(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(It(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=Ft(t.e/le),e>=t.d.length-1&&(n=l<0?-l:l)<=c_)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)?Ft(l*(Math.log("0."+It(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),+It(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 It(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 l_(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=Zi(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,N,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=Ft(i.e/T)-Ft(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),N=g[0],g[1]>=u/2&&++N;do v=0,l=e(g,B,K,$),l<0?(Z=B[0],K!=$&&(Z=Z*u+(B[1]||0)),v=Z/N|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=It(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>u_)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),Nl(o.d,s)&&(r=!0)),n=Ft(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 Fl(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)),It(a.d).slice(0,u)===It(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=It(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=It(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)),It(l.d).slice(0,h)===It(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 d_(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(s_.test(e))n=16,e=e.toLowerCase();else if(o_.test(e))n=2;else if(a_.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):Fr.pow(2,u))),fe=!0,t)}function f_(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Zi(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/Zo(5,n)),e=Zi(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 Zi(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=Fl(n)?i?2:3:i?4:1,e;Bn=Fl(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 Nl(t,e){if(t.length>e)return t.length=e,!0}function h_(t){return new this(t).abs()}function m_(t){return new this(t).acos()}function p_(t){return new this(t).acosh()}function g_(t,e){return new this(t).plus(e)}function __(t){return new this(t).asin()}function y_(t){return new this(t).asinh()}function w_(t){return new this(t).atan()}function b_(t){return new this(t).atanh()}function v_(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 k_(t){return new this(t).cbrt()}function T_(t){return oe(t=new this(t),t.e+1,2)}function C_(t,e,n){return new this(t).clamp(e,n)}function S_(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",-Hi,0,"toExpPos",0,Hi,"maxE",0,Hi,"minE",-Hi,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(Ft(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 A_(t){return new this(t).cos()}function x_(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):d_(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=S_,r.clone=Zl,r.isDecimal=Rl,r.abs=h_,r.acos=m_,r.acosh=p_,r.add=g_,r.asin=__,r.asinh=y_,r.atan=w_,r.atanh=b_,r.atan2=v_,r.cbrt=k_,r.ceil=T_,r.clamp=C_,r.cos=A_,r.cosh=x_,r.div=I_,r.exp=O_,r.floor=P_,r.hypot=D_,r.ln=E_,r.log=M_,r.log10=j_,r.log2=B_,r.max=F_,r.min=N_,r.mod=R_,r.mul=q_,r.pow=L_,r.random=$_,r.round=U_,r.sign=K_,r.sin=z_,r.sinh=V_,r.sqrt=G_,r.sub=W_,r.sum=H_,r.tan=Z_,r.tanh=X_,r.trunc=J_,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 I_(t,e){return new this(t).div(e)}function O_(t){return new this(t).exp()}function P_(t){return oe(t=new this(t),t.e+1,3)}function D_(){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 Fr||t&&t.toStringTag===Ul||!1}function E_(t){return new this(t).ln()}function M_(t,e){return new this(t).log(e)}function B_(t){return new this(t).log(2)}function j_(t){return new this(t).log(10)}function F_(){return Gl(this,arguments,"lt")}function N_(){return Gl(this,arguments,"gt")}function R_(t,e){return new this(t).mod(e)}function q_(t,e){return new this(t).mul(e)}function L_(t,e){return new this(t).pow(e)}function $_(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 U_(t){return oe(t=new this(t),t.e+1,this.rounding)}function K_(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function z_(t){return new this(t).sin()}function V_(t){return new this(t).sinh()}function G_(t){return new this(t).sqrt()}function W_(t,e){return new this(t).sub(e)}function H_(){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 Z_(t){return new this(t).tan()}function X_(t){return new this(t).tanh()}function J_(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 Fr=z.constructor=Zl(Qa);zo=new Fr(zo);Vo=new Fr(Vo);var F=Fr;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"),X0=ge(ke(),1),gc=ge(ke(),1),J0=ge(ke(),1);var wi=ge(ke(),1),qr=ge(ke(),1);var bi=require("@mysten/sui.js/transactions"),ay=require("@mysten/sui.js/utils"),cy=require("@mysten/sui.js/transactions"),Dt=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"),Zt=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",o0=xd,Yi=typeof Buffer=="function",kd=typeof TextDecoder=="function"?new TextDecoder:void 0,Td=typeof TextEncoder=="function"?new TextEncoder:void 0,s0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Nr=Array.prototype.slice.call(s0),es=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(Nr),a0=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Ot=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+=Nr[e>>18&63]+Nr[e>>12&63]+Nr[e>>6&63]+Nr[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},cc=typeof btoa=="function"?t=>btoa(t):Yi?t=>Buffer.from(t,"binary").toString("base64"):Pd,sc=Yi?t=>Buffer.from(t).toString("base64"):t=>{let n=[];for(let i=0,r=t.length;i<r;i+=4096)n.push(Ot.apply(null,t.subarray(i,i+4096)));return cc(n.join(""))},ts=(t,e=!1)=>e?Id(sc(t)):sc(t),c0=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?Ot(192|e>>>6)+Ot(128|e&63):Ot(224|e>>>12&15)+Ot(128|e>>>6&63)+Ot(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return Ot(240|e>>>18&7)+Ot(128|e>>>12&63)+Ot(128|e>>>6&63)+Ot(128|e&63)}},u0=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Dd=t=>t.replace(u0,c0),Sd=Yi?t=>Buffer.from(t,"utf8").toString("base64"):Td?t=>sc(Td.encode(t)):t=>cc(Dd(t)),Ji=(t,e=!1)=>e?Id(Sd(t)):Sd(t),Ad=t=>Ji(t,!0),l0=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,d0=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 Ot((n>>>10)+55296)+Ot((n&1023)+56320);case 3:return Ot((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return Ot((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Ed=t=>t.replace(l0,d0),Md=t=>{if(t=t.replace(/\s+/g,""),!a0.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?Ot(e>>16&255):r===64?Ot(e>>16&255,e>>8&255):Ot(e>>16&255,e>>8&255,e&255);return n},uc=typeof atob=="function"?t=>atob(Od(t)):Yi?t=>Buffer.from(t,"base64").toString("binary"):Md,Bd=Yi?t=>Cd(Buffer.from(t,"base64")):t=>Cd(uc(t).split("").map(e=>e.charCodeAt(0))),jd=t=>Bd(Fd(t)),f0=Yi?t=>Buffer.from(t,"base64").toString("utf8"):kd?t=>kd.decode(Bd(t)):t=>Ed(uc(t)),Fd=t=>Od(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),ac=t=>f0(Fd(t)),h0=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}),Rd=function(){let t=(e,n)=>Object.defineProperty(String.prototype,e,Nd(n));t("fromBase64",function(){return ac(this)}),t("toBase64",function(e){return Ji(this,e)}),t("toBase64URI",function(){return Ji(this,!0)}),t("toBase64URL",function(){return Ji(this,!0)}),t("toUint8Array",function(){return jd(this)})},qd=function(){let t=(e,n)=>Object.defineProperty(Uint8Array.prototype,e,Nd(n));t("toBase64",function(e){return ts(this,e)}),t("toBase64URI",function(){return ts(this,!0)}),t("toBase64URL",function(){return ts(this,!0)})},m0=()=>{Rd(),qd()},Qi={version:xd,VERSION:o0,atob:uc,atobPolyfill:Md,btoa:cc,btoaPolyfill:Pd,fromBase64:ac,toBase64:Ji,encode:Ji,encodeURI:Ad,encodeURL:Ad,utob:Dd,btou:Ed,decode:ac,isValid:h0,fromUint8Array:ts,toUint8Array:jd,extendString:Rd,extendUint8Array:qd,extendBuiltins:m0};var bc=require("@mysten/sui.js/transactions"),af=require("@mysten/sui.js/utils"),hn=ge(ke(),1);var ns,p0=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(p0)}var Pt=[];for(let t=0;t<256;++t)Pt.push((t+256).toString(16).slice(1));function Ld(t,e=0){return Pt[t[e+0]]+Pt[t[e+1]]+Pt[t[e+2]]+Pt[t[e+3]]+"-"+Pt[t[e+4]]+Pt[t[e+5]]+"-"+Pt[t[e+6]]+Pt[t[e+7]]+"-"+Pt[t[e+8]]+Pt[t[e+9]]+"-"+Pt[t[e+10]]+Pt[t[e+11]]+Pt[t[e+12]]+Pt[t[e+13]]+Pt[t[e+14]]+Pt[t[e+15]]}var g0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dc={randomUUID:g0};function _0(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=_0;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 y0=Object.defineProperty,w0=(t,e,n)=>e in t?y0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,b0=(t,e,n)=>(w0(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)}};F.config({precision:64,rounding:F.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var Et=F,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),Zk=fs.pow(new wt.default(128)),rr=fs.pow(new wt.default(64)).sub(Cn),T0=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(Et.pow(2,64))}static toX64(t){return new wt.default(t.mul(Et.pow(2,64)).floor().toFixed())}static fromX64(t){return new Et(t.toString()).mul(Et.pow(2,-64))}static fromX64_Decimal(t){return t.mul(Et.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(rr).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(T0):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(rr).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 C0(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",nr=new Gd.default(1e6),G="0x0000000000000000000000000000000000000000000000000000000000000006",S0="partner",ir="pool_script",jn="pool_script_v2",Jn="router",fc="router_with_partner",zt="fetcher_script",A0="expect_swap",$d="utils";var hc="custodian_v2",x0="clob_v2",I0="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 O0=14,P0="59543866431248",D0="184467440737095516",E0="15793534762490258745",M0=443636;function B0(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 j0(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 F0(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(Et.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return Te.fromX64(t).pow(2).mul(Et.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new ce.default(j0(t)):new ce.default(F0(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=B0(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<O0;){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(P0)),w=_e(h.sub(new ce.default(D0)),64,128).toNumber(),v=_e(h.add(new ce.default(E0)),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 N0(t){return S(t).add(S(M0))}var Jk=new Lr.default(365),Yk=new Lr.default(24),Qk=new Lr.default(3600),eT=new Lr.default(.5);var mn=class{static getDefaultSqrtPriceLimit(t){return new Zd.default(t?ms:hs)}static getDefaultOtherAmountThreshold(t){return t?ie:rr}};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 R0(t,e,n,i){return i?Xd(t,e,n,!0):Jd(t,e,n,!0)}function q0(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(rr).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 L0(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(nr,r),nr,64),v=Ud(t,e,n,s);v.gt(w)?(a=w,h=Te.checkUnsignedSub(i,w),l=R0(t,n,w,s)):(a=v,h=Te.checkMulDivCeil(a,r,nr.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=q0(t,n,i,s)):(u=w,l=e),a=Ud(t,l,n,s),h=Te.checkMulDivCeil(a,r,nr.sub(r),64)}return{amountIn:a,amountOut:u,nextSqrtPrice:l,feeAmount:h}}function $0(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=L0(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),nr,64),s=n===0?ie:Te.checkMulDivFloor(e,new Ie.default(n),nr,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 Et(t.toString()),s=new Et(e.toString()),a=new Et(n.toString()),u=new Et(i.toString()),l,h;return e.lt(n)?(l=Te.toX64_Decimal(o).mul(u.sub(a)).div(a.mul(u)),h=new Et(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 Et(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(Et.ceil(v).toString()):new Ie.default(Et.floor(v).toString()),tokenMaxB:r?new Ie.default(Et.ceil(T).toString()):new Ie.default(Et.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 U0=0,Yd=1,K0=2;function zd(t,e){return t===e?U0:t<e?Yd:K0}function z0(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 z0(t,e)===Yd}function or(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=or(u.full_address,u.type_arguments),u}let r=e.split("::"),s={full_address:e,address:e===$r||e===Z0?"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=or(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function Mt(t){return q(t).source_address}function V0(t){return t.toLowerCase().startsWith("0x")?(0,ps.normalizeSuiObjectId)(t):t}var G0=(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]=V0(i))}}}var W0="0x2::coin::Coin",H0=/^0x2::coin::Coin<(.+)>$/;var $r="0x2::sui::SUI",Z0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var we=class{static getCoinTypeArg(t){let e=t.type.match(H0);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`${W0}<${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=>{Mt(i.coinAddress)===Mt(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 sr=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return sr.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 sr(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 F.isDecimal(t)?t:new F(t===void 0?0:t)}function Y0(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 Q0(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 $t(t){return"objectId"in t?t.objectId:Q0(t)?.objectId??ef(t)}function ey(t){return t.data!==void 0}function ty(t){return t.content!==void 0}function tf(t){let e="data"in t?Ur(t):t;if(!(!e||!ty(e)||e.content.dataType!=="moveObject"))return e.content}function Bt(t){return tf(t)?.type}function pn(t){let e=ey(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":Bt(t):e?.type}function Ci(t){return Ur(t)?.previousTransaction}function ar(t){return Ur(t)?.owner}function ny(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=Y0(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 iy(t,e,n){let i=q(t).name,r=q(e).name;return`${i}-${r}[${n}]`}function mc(t){let e=Bt(t),n=q(e),i=Q(t);if(i==null)throw new J(`Pool id ${$t(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:$t(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=iy(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function Si(t){let e=ny(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 Fn(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=Bt(t),a=ar(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:$t(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 ry(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 oy(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 sy(t,e){return F.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=Mt(n.coinTypeA),a=Mt(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(Mt(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(sy(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(),N=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(N),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(N),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)],N=[B.coinType[0],B.coinType[1],B.coinType[2]],K=o.moveCall({target:`${a.published_at}::${E}::${H}`,typeArguments:N,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;b0(re,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function Nt(t){return!(!t.startsWith("0x")||t.length!==66)}var er=new Dt.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}::${x0}::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 Dt.default(i),a=ie,u=new Dt.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 Dt.default(l[h].quantity),v=new Dt.default(l[h].price),T=w.mul(new Dt.default(v)).mul(new Dt.default(e.takerFeeRate)).div(er).div(er);if(s.gt(w))s=s.sub(w),o=o.add(w.mul(v).div(er).sub(T)),a=a.add(T);else{let I=s.mul(new Dt.default(l[h].price)).div(er),x=I.mul(new Dt.default(e.takerFeeRate)).div(er);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 Dt.default(l[h].price).mul(new Dt.default(l[h].quantity)).div(new Dt.default(1e9)),v=w.mul(new Dt.default(e.takerFeeRate)).div(er),T=w.add(v);if(s.gt(w))o=o.add(new Dt.default(l[h].quantity)),s=s.sub(T),a=a.add(v);else{let I=new Dt.default(l[h].quantity).div(new Dt.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}::${I0}::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}}},uy=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 tr.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}::${ir}::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 tr.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 tr.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(ry(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 tr.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(N0(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 tr.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}::${S0}::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]}},ly=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=Fn(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=Fn(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=Fn(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}::${ir}::${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}::${ir}::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}::${ir}::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]}},dy=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=oy(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 fy=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 N=0;N<v.length;N+=1){let K=v[N];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(N=>N.stepNums===1),x=T.filter(N=>N.stepNums!==1),P=[];try{P=await this.getPoolWithTVL()}catch{P=[]}if(P.length>0){let N=new Map(P.map(K=>[K.poolAddress,K]));x.sort((K,C)=>{let A=0,c=0;if(N.has(K.poolAB)&&N.has(K.poolBC)){let d=N.get(K.poolAB),g=N.get(K.poolBC);A=Math.min(d.tvl,g.tvl)}if(N.has(C.poolAB)&&N.has(C.poolBC)){let d=N.get(C.poolAB),g=N.get(C.poolBC);c=Math.min(d.tvl,g.tvl)}return c-A})}if(T=[...I,...x],T.length===0){if(s!=null){let N=await this.sdk.Swap.preSwapWithMultiPool(s),K={amountIn:new Zt.default(N.estimatedAmountIn),amountOut:new Zt.default(N.estimatedAmountOut),poolAddress:[N.poolAddress],a2b:[N.aToB],rawAmountLimit:i?[N.estimatedAmountOut]:[N.estimatedAmountIn],isExceed:N.isExceed,coinType:[t,e]},C={paths:[K],partner:o,priceSlippagePoint:r};return{amountIn:new Zt.default(N.estimatedAmountIn),amountOut:new Zt.default(N.estimatedAmountOut),paths:[K],a2b:N.aToB,b2c:void 0,byAmountIn:i,isExceed:N.isExceed,targetSqrtPrice:[N.estimatedEndSqrtPrice],currentSqrtPrice:[N.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 Zt.default(K.estimatedAmountIn),amountOut:new Zt.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 Zt.default(K.estimatedAmountIn),amountOut:new Zt.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}::${A0}::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:rr,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 Zt.default(o[w].parsedJson.data.amount_out);v.gt(s)&&(a=w,s=v)}else{let v=t[w].stepNums>1?new Zt.default(o[w].parsedJson.data.amount_in):new Zt.default(o[w].parsedJson.data.amount_in).add(new Zt.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 hy=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 F(r.feeRate).div(10**6):new F(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 F(1).div(r.currentPrice),l=a.direction?a.currentPrice:new F(1).div(a.currentPrice),h=a.label==="Cetus"?new F(a.feeRate).div(10**6):new F(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 F(r.currentPrice):new F(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 F(r.currentPrice):new F(1).div(r.currentPrice),a=o.direction?new F(o.currentPrice):new F(1).div(o.currentPrice),u=s.mul(a),l=new F(o.outputAmount).div(10**o.toDecimal),h=new F(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:rr,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=C0(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=$0(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)}},my=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(Mt(s)===Mt(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(Qi.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]}},py=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 F(t.toString()).div(new F(10).pow(new F(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,N=this.sdk.Router.tokenInfo(E.coinType[2]).decimals,K=E.a2b[1]?ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),V,N):ee.sqrtPriceX64ToPrice(new hn.default(x.currentSqrtPrice[1]),N,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:N};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}}},gy=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(Mt(a)===Mt(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:G0(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=$t(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=$t(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=$t(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(Qi.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=Qi.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(Qi.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}}},_y=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)}}},cr=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new _y({url:t.fullRpcUrl}),this._swap=new hy(this),this._pool=new uy(this),this._position=new ly(this),this._rewarder=new dy(this),this._router=new fy(this),this._router_v2=new py(this),this._token=new my(this),this._config=new gy(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 Am=require("@msafe/sui3-utils"),Im=require("@msafe/sui3-utils"),Pm=require("@msafe/sui3-utils");var hf=require("@mysten/sui.js/utils");var vs=require("@mysten/sui.js/transactions");var Xt=require("@mysten/sui.js/transactions"),hr=require("@mysten/sui.js/utils"),Vr=ge(ke(),1);var mf=require("@mysten/sui.js/utils");var Ac=require("@mysten/sui.js/transactions");var Nn=require("@mysten/sui.js/transactions");var xn=require("@mysten/sui.js/utils"),Jt=require("@mysten/sui.js/transactions");var xc=require("@mysten/sui.js/utils");var xy=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 Yt=require("@mysten/sui.js/transactions"),Tc="router",fr=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(fr))})}),{basic_percent:Number(S(e.basic_percent).div(fr)),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:$t(t)}}static buildLockNFT(t){let e=q($t(t)).address;return{lock_clmm_position:Fn(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}},yy=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(Bt(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=Bt(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)($t(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"}},wy=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 Fn(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 Xt.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,hr.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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=ar(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,hr.normalizeSuiAddress)(s.AddressOwner)===(0,hr.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(Bt(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,hr.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 or(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(fr)),multiplier:Number(S(r.fields.value).div(fr))})}),{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(fr)),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(fr)),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",by=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,F.ROUND_DOWN)),a.end_time=Number(S(a.start_time).add(S(t.interval_day).mul(24*3600)).toFixed(0,F.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]}},ur="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:Mt(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}},vy=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(Bt(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(Bt(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 Nn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${ur}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xcetus_manager_id)]}),e}async convertPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Nn.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}::${ur}::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}::${ur}::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 Nn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ur}::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 Nn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${ur}::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 Nn.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 Nn.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 Nn.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 Nn.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).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,F.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:$t(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]}},ky="factory",on="oversubscribe_pool",gf=1e6,dr=1e18;var lr="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 Ty(t){return"master_address"in t}var Cy="router",Sy="vaults",Ay=1e4;var Ut=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=Bt(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 Ut.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&&Ut.is_claim_period(t.duration_summary)&&!t.is_liquidity_injected}static is_can_withdraw(t){return t.is_withdrawn?!1:Ut.is_sale_failed(t)?!0:(t.liquidity_injection_ratio===0||t.is_liquidity_injected)&&Ut.is_claim_period(t.duration_summary)}static is_sale_failed(t){return!!(t.is_cancelled||Ut.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(Ut.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(dr).div(t.price).toString(),i=e.purchased_raise_amount;else{let o=Ut.redeemForSaleOversubcribeV2(t,e);n=o.user_obtained_sale_amount,i=o.user_used_raise_amount_ceil}n=F.floor(n);let r=F.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(Ut.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(Ut.get_sold_amount(t)))}return{obtained_raise_amount:F.floor(e).toString(),refunded_sale_amount:F.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(dr).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=F.ceil(i.mul(s).div(a).add(n)),l=F.floor(i.mul(s).div(a).add(n));return{user_obtained_sale_amount:F.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(dr).div(S(a).mul(t.price)),l=F.ceil(u.mul(t.price).div(dr));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(dr)).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:Mt(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,sr.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=sr.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=sr.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 F(1),ratioB:new F(0)};if(i>e)return{ratioA:new F(0),ratioB:new F(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,F.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,F.ROUND_DOWN).toString()}static get_protocol_fee_amount(t,e){return S(e).mul(t.protocol_fee_rate).div(Ay).toFixed(0,F.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:[]}}}},Iy=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=Ut.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=Ut.buildIdoPool(o);await Ut.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=Ut.buildIdoPool(r);return await Ut.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=Ut.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 Fn(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 Jt.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(dr).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}::${ky}::create_oversubscribe_pool`,typeArguments:w,arguments:h}),s}async creatPurchasePayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Jt.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 Jt.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 Jt.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 Jt.TransactionBlock;r.moveCall({target:`${n.published_at}::${ir}::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 Jt.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 Jt.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 Jt.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 Jt.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 Jt.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 Jt.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 Jt.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=ar(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=ar(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]}},Oy=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(Bt(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(Bt(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}::${lr}::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}::${lr}::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}::${lr}::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}::${lr}::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}::${lr}::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}::${lr}::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,F.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:$t(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]}},Py=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 Ty(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]}},Dy=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}::${Cy}::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}::${Sy}::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 F(s.toFixed(0)):new F(0),rightSuiAmount:a?new F(t.input_amount):new F(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 F(t.input_amount):new F(0),amount_b:a?new F(0):new F(t.input_amount),amount_left:a?new F(s.toFixed(0)):new F(0),amount_right:a?new F(t.input_amount):new F(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 F(s.toFixed(0)):new F(0),l.amount_right=a?new F(t.input_amount):new F(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,N=S(t.fix_amount_a?U.toString():V.toString()).add(E);console.log("1110 \u5B9E\u9645\u6D88\u8017:",{preAmountTotal:N.toString(),fixAmountA:O}),N.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 F(o.toFixed(0)):new F(0),rightSuiAmount:s?new F(t.input_amount):new F(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 F(U.coinAmountA.toString()),N=new F(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(N))n?P=B:O=B;else{n?O=B:P=B;let K=H.sub(N),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 F(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}},Ey=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 or(`${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]}},My=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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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 Yt.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=Mt(t.coinTypeA),s=Mt(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(Mt(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 Yt.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 Yt.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]}},Rt=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 wy(this),this._ido=new Iy(this),this._xcetusModule=new vy(this),this._xtokenModule=new Oy(this),this._boosterModule=new yy(this),this._makerModule=new by(this),this._vaults=new Dy(this),this._limitOrder=new Ey(this),this._farmsModule=new My(this),this._liquidityStrategy=new Py(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 Em=require("@msafe/sui3-utils"),Bm=require("@msafe/sui3-utils"),Fm=require("@msafe/sui3-utils"),Rm=require("@msafe/sui3-utils"),Lm=require("@msafe/sui3-utils"),Um=require("@msafe/sui3-utils"),zm=require("@msafe/sui3-utils"),Gm=require("@msafe/sui3-utils"),Hm=require("@msafe/sui3-utils"),Xm=require("@msafe/sui3-utils"),Ym=require("@msafe/sui3-utils");var ep=require("@msafe/sui3-utils"),np=require("@msafe/sui3-utils"),rp=require("@msafe/sui3-utils"),sp=require("@msafe/sui3-utils"),cp=require("@msafe/sui3-utils"),Sp=require("@mysten/sui.js/client"),zn=ge(require("axios"),1),Ki=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"),Op=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 Fu=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{},mr=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",Qt="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:Qt,day:Y},Hr={year:Y,month:Qt,day:Y,weekday:Qt},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:Qt},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:Qt},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:Qt,day:Y,hour:Y,minute:Y,timeZoneName:yn},co={year:Y,month:Qt,day:Y,hour:Y,minute:Y,second:Y,timeZoneName:yn},uo={year:Y,month:Qt,day:Y,weekday:Qt,hour:Y,minute:Y,timeZoneName:Qt},lo={year:Y,month:Qt,day:Y,weekday:Qt,hour:Y,minute:Y,second:Y,timeZoneName:Qt};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 By(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 jy={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Fy(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 Ny(t,e){let n=t.formatToParts(e),i=[];for(let r=0;r<n.length;r++){let{type:o,value:s}=n[r],a=jy[o];o==="era"?i[a]=s:de(a)||(i[a]=parseInt(s,10))}return i}var Os={},qt=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=By(this.name),[r,o,s,a,u,l,h]=i.formatToParts?Ny(i,n):Fy(i,n);a==="BC"&&(r=-Math.abs(r)+1);let v=pr({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 Ry(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 qy(t,e={}){let n=JSON.stringify([t,e]),i=jc[n];return i||(i=new Intl.NumberFormat(t,e),jc[n]=i),i}var Fc={};function Ly(t,e={}){let{base:n,...i}=e,r=JSON.stringify([t,i]),o=Fc[r];return o||(o=new Intl.RelativeTimeFormat(t,e),Fc[r]=o),o}var fo=null;function $y(){return fo||(fo=new Intl.DateTimeFormat().resolvedOptions().locale,fo)}var bf={};function Uy(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 Ky(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 zy(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Vy(t){let e=[];for(let n=1;n<=12;n++){let i=be.utc(2009,n,1);e.push(t(i))}return e}function Gy(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 Wy(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 Nc=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=qy(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):gr(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&&qt.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=Ly(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):[]}},Hy={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":$y()),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={},Fc={}}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]=Ky(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=i||u||null,this.weekSettings=r,this.intl=zy(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=Wy(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]=Vy(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]=Gy(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 Nc(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 Ry(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()?Uy(this.locale):Hy}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 _r=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)||qt.create(t)}else return In(t)?Ct.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new _r(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(),qt.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 Fs(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=en(t.weekNumber,1,Di(t.weekYear,e,n)),o=en(t.weekday,1,7);return i?r?o?!1:an("weekday",t.weekday):an("week",t.weekNumber):an("weekYear",t.weekYear)}function Ff(t){let e=po(t.year),n=en(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=en(t.month,1,12),i=en(t.day,1,yr(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=en(e,0,23)||e===24&&n===0&&i===0&&r===0,s=en(n,0,59),a=en(i,0,59),u=en(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(!en(t.firstDay,1,7)||!en(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!en(e,1,7)))throw new bt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function en(t,e,n){return po(t)&&t>=e&&t<=n}function Zy(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 gr(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 yr(t,e){let n=Zy(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 pr(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-js(Bs(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 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 wr(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 Xy=["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"],Jy=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lc(t){switch(t){case"narrow":return[...Jy];case"short":return[...Qc];case"long":return[...Xy];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"],Yy=["M","T","W","T","F","S","S"];function $c(t){switch(t){case"narrow":return[...Yy];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"],Qy=["Before Christ","Anno Domini"],ew=["BC","AD"],tw=["B","A"];function Kc(t){switch(t){case"narrow":return[...tw];case"short":return[...ew];case"long":return[...Qy];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 nw={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 nw[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 vr(...t){let e=t.reduce((n,i)=>n+i.source,"");return RegExp(`^${e}$`)}function kr(...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 Tr(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))?)/,iw=`(?:${Zf.source}?(?:\\[(${Wf.source})\\])?)?`,nu=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Xf=RegExp(`${nu.source}${iw}`),iu=RegExp(`(?:T${Xf.source})?`),rw=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,ow=/(\d{4})-?W(\d\d)(?:-?(\d))?/,sw=/(\d{4})-?(\d{3})/,aw=Hf("weekYear","weekNumber","weekDay"),cw=Hf("year","ordinal"),uw=/(\d{4})-(\d\d)-(\d\d)/,Jf=RegExp(`${nu.source} ?(?:${Zf.source}|(${Wf.source}))?`),lw=RegExp(`(?: ${Jf.source})?`);function br(t,e,n){let i=t[e];return de(i)?n:$n(i)}function dw(t,e){return[{year:br(t,e),month:br(t,e+1,1),day:br(t,e+2,1)},null,e+3]}function Cr(t,e){return[{hours:br(t,e,0),minutes:br(t,e+1,0),seconds:br(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]?qt.create(t[e]):null;return[{},n,e+1]}var fw=RegExp(`^T?${nu.source}$`),hw=/^-?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 mw(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 pw={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 gw=/^(?:(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 _w(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=pw[u]:l?T=0:T=Pi(h,w),[v,new Ct(T)]}function yw(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var ww=/^(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$/,bw=/^(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$/,vw=/^(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 kw(t){let[,e,n,i,r,o,s,a]=t;return[ru(e,a,n,i,r,o,s),Ct.utcInstance]}var Tw=vr(rw,iu),Cw=vr(ow,iu),Sw=vr(sw,iu),Aw=vr(Xf),Yf=kr(dw,Cr,wo,bo),xw=kr(aw,Cr,wo,bo),Iw=kr(cw,Cr,wo,bo),Ow=kr(Cr,wo,bo);function Qf(t){return Tr(t,[Tw,Yf],[Cw,xw],[Sw,Iw],[Aw,Ow])}function eh(t){return Tr(yw(t),[gw,_w])}function th(t){return Tr(t,[ww,Gf],[bw,Gf],[vw,kw])}function nh(t){return Tr(t,[hw,mw])}var Pw=kr(Cr);function ih(t){return Tr(t,[fw,Pw])}var Dw=vr(uw,lw),Ew=vr(Jf),Mw=kr(Cr,wo,bo);function rh(t){return Tr(t,[Dw,Yf],[Ew,Mw])}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}},Bw={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,Sr=146097/4800,jw={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:Sr/7,days:Sr,hours:Sr*24,minutes:Sr*24*60,seconds:Sr*24*60*60,milliseconds:Sr*24*60*60*1e3},...ah},Mi=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Fw=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 Fw.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 Nw(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?jw:Bw;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:wr(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 mr(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+=gr(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,...wr(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=Nw(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 Ar="Invalid Interval";function Rw(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=xr(e),r=xr(n),o=Rw(i,r);return o??new t({start:i,end:r})}static after(e,n){let i=Pe.fromDurationLike(n),r=xr(e);return t.fromDateTimes(r,r.plus(i))}static before(e,n){let i=Pe.fromDurationLike(n),r=xr(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(xr).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()})`:Ar}[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):Ar}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ar}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ar}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ar}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:Ar}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 qt.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 qw(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]=qw(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]},Lw=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+=Lw.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 $w="missing Intl.DateTimeFormat.formatToParts support";function Se(t,e=n=>n){return{regex:t,deser:([n])=>e(fh(n))}}var Uw="\xA0",ph=`[ ${Uw}]`,gh=new RegExp(ph,"g");function Kw(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(Kw).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 Ns(t){return{regex:t,deser:([e])=>e}}function zw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Vw(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(zw(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 Ns(h);case"uu":return Ns(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 Ns(/[a-z_+-/]{1,256}?/i);case" ":return Ns(/[^\S\n\r]/);default:return T(P)}})(t)||{invalidReason:$w};return x.token=t,x}var Gw={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 Ww(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=Gw[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Hw(t){return[`^${t.map(n=>n.regex).reduce((n,i)=>`${n}(${i.source})`,"")}$`,t]}function Zw(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 Xw(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=qt.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 Jw(){return su||(su=be.fromMillis(1555555555555)),su}function Yw(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=>Yw(n,e)))}function cu(t,e,n){let i=au(At.parseFormat(n),t),r=i.map(s=>Vw(s,t)),o=r.find(s=>s.invalidReason);if(o)return{input:e,tokens:i,invalidReason:o.invalidReason};{let[s,a]=Hw(r),u=RegExp(s,"i"),[l,h]=Zw(e,u,a),[w,v,T]=h?Xw(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(Jw()),r=i.formatToParts(),o=i.resolvedOptions();return r.map(s=>Ww(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(pr(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,yr(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=pr(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},Qw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},eb={ordinal:1,hour:0,minute:0,second:0,millisecond:0},xh=["year","month","day","hour","minute","second","millisecond"],tb=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],nb=["year","ordinal","hour","minute","second","millisecond"];function ib(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 mr(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 ib(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=gr(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=wr(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=tb,O=Qw,E=mo(E,s,a)):h?(P=nb,O=eb,E=Fs(E)):(P=xh,O=Ah);let B=!1;for(let N of P){let K=o[N];de(K)?B?o[N]=O[N]:o[N]=E[N]:B=!0}let $=x?jf(o,s,a):h?Ff(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?Fs(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=pr(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 yr(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=wr(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(yr(w.year,w.month),w.day))):w=Wc({...Fs(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 xr(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 Vp=ge(Uo(),1),Gp=require("@msafe/sui3-utils"),Wp=require("@msafe/sui3-utils"),Hp=require("@msafe/sui3-utils"),Lu=require("@mysten/sui.js/bcs"),hi=require("@mysten/sui.js/utils"),Xp=require("@msafe/sui3-utils"),Er=require("@msafe/sui3-utils"),Jp=require("@msafe/sui3-utils"),Qp=require("@msafe/sui3-utils"),tg=require("@msafe/sui3-utils"),ng=require("@mysten/sui.js/transactions"),rg=require("@msafe/sui3-utils"),Dr=require("@msafe/sui3-utils"),$u=require("@mysten/sui.js/bcs"),mi=require("@mysten/sui.js/utils"),og=require("@mysten/sui.js/transactions"),ag=require("@mysten/sui.js/transactions"),ug=require("@mysten/sui.js/transactions"),fg=require("@mysten/sui.js/transactions"),mg=require("@mysten/sui.js/transactions"),da=require("@msafe/sui3-utils"),gg=require("@mysten/sui.js/transactions"),fa=require("@mysten/sui.js/utils"),Px=ge(Uo(),1),_g=require("@msafe/sui3-utils"),Ui=require("@msafe/sui3-utils"),Uu=require("@mysten/sui.js/bcs"),pi=require("@mysten/sui.js/utils");var xb=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 rb(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function mu(t,...e){if(!rb(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 ob(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,sb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!sb)throw new Error("Non little-endian hardware is not supported");function ab(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=ab(t)),!ob(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var Ks=class{clone(){return this._cloneInto()}},jA={}.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 cb(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;cb(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 ub=(t,e,n)=>t&e^~t&n,lb=(t,e,n)=>t&e^t&n^e&n,db=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+ub(a,u,l)+db[w]+ci[w]|0,x=(vn(i,2)^vn(i,13)^vn(i,22))+lb(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 fb(...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 hb(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 mb(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 pb(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 gb(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 _b(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 yb(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:hb,chain:fb,checksum:yb,convertRadix:yu,convertRadix2:wu,radix:gb,radix2:_b,join:mb,padding:pb};var wb=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function bb(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 Tb(Dh(e/8),t)}var vb=t=>{let e=8-t.length/4;return new Uint8Array([Eh(t)[0]>>e<<e])};function kb(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,vb),ko.radix2(11,!0),ko.alphabet(t))}function Tb(t,e){return bb(t),kb(e).encode(t).join(wb(e)?"\u3000":" ")}var jh=`abandon
1
+ "use strict";var qg=Object.create;var No=Object.defineProperty;var Lg=Object.getOwnPropertyDescriptor;var $g=Object.getOwnPropertyNames;var Ug=Object.getPrototypeOf,Kg=Object.prototype.hasOwnProperty;var zg=(t,e)=>()=>(t&&(e=t(t=0)),e);var pi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ml=(t,e)=>{for(var n in e)No(t,n,{get:e[n],enumerable:!0})},gl=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $g(e))!Kg.call(t,r)&&r!==n&&No(t,r,{get:()=>e[r],enumerable:!(i=Lg(e,r))||i.enumerable});return t};var ge=(t,e,n)=>(n=t!=null?qg(Ug(t)):{},gl(e||!t||!t.__esModule?No(n,"default",{value:t,enumerable:!0}):n,t)),_l=t=>gl(No({},"__esModule",{value:!0}),t);var wl=pi((Ok,bl)=>{"use strict";bl.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var kl=pi((Pk,vl)=>{"use strict";var Ka=wl();vl.exports=(t,e={})=>{if(!Ka(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):Ka(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 b of h){let v=a[b],T;n&&Array.isArray(v)?T=o(v):T=n&&Ka(v)?s(v):v,Object.defineProperty(l,b,{...Object.getOwnPropertyDescriptor(a,b),value:T})}return l};return Array.isArray(t)?n?o(t):t.slice():s(t)}});var Sl=pi((Dk,Cl)=>{"use strict";var Vg=Object.prototype.toString;Cl.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 Xg(e)?"generatorfunction":"function";if(Gg(e))return"array";if(Qg(e))return"buffer";if(Yg(e))return"arguments";if(Hg(e))return"date";if(Wg(e))return"error";if(Zg(e))return"regexp";switch(Tl(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(Jg(e))return"generator";switch(n=Vg.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 Tl(t){return typeof t.constructor=="function"?t.constructor.name:null}function Gg(t){return Array.isArray?Array.isArray(t):t instanceof Array}function Wg(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function Hg(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function Zg(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function Xg(t,e){return Tl(t)==="GeneratorFunction"}function Jg(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function Yg(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 Ro=pi((Ek,Ol)=>{"use strict";var e_=kl(),za=Sl(),Al=(t,e)=>!e||za(e)!=="array"?!1:e.indexOf(t)>-1,t_=(t,e)=>e_(t,{compare:e}),xl=(t,e)=>{let n=e&&e.compareFunction;return t.slice().sort(n)};function Il(t,e){let n=e&&e.compareFunction,i=t_(t,n);return Object.keys(t).forEach(function(r){let o=i[r],s=za(o);if(s==="object"){(!e||!Al(r,e.ignoreObjectAtKeys))&&(i[r]=Il(o,e));return}s==="array"&&(!e||!Al(r,e.ignoreArrayAtKeys))&&(i[r]=xl(o,e))}),i}var Pr=(t,e)=>{let n=za(t);return Pr[n]?Pr[n](t,e):t};Pr.array=xl;Pr.object=Il;Ol.exports=Pr});var ke=pi((Pl,Va)=>{"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 w=0;c[0]==="-"&&(w++,this.negative=1),w<c.length&&(d===16?this._parseHex(c,w,g):(this._parseBase(c,d,w),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 w=0;w<this.length;w++)this.words[w]=0;var m,p,y=0;if(g==="be")for(w=c.length-1,m=0;w>=0;w-=3)p=c[w]|c[w-1]<<8|c[w-2]<<16,this.words[m]|=p<<y&67108863,this.words[m+1]=p>>>26-y&67108863,y+=24,y>=26&&(y-=26,m++);else if(g==="le")for(w=0,m=0;w<c.length;w+=3)p=c[w]|c[w+1]<<8|c[w+2]<<16,this.words[m]|=p<<y&67108863,this.words[m+1]=p>>>26-y&67108863,y+=24,y>=26&&(y-=26,m++);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 w=0;w<this.length;w++)this.words[w]=0;var m=0,p=0,y;if(g==="be")for(w=c.length-1;w>=d;w-=2)y=a(c,d,w)<<m,this.words[p]|=y&67108863,m>=18?(m-=18,p+=1,this.words[p]|=y>>>26):m+=8;else{var _=c.length-d;for(w=_%2===0?d+1:d;w<c.length;w+=2)y=a(c,d,w)<<m,this.words[p]|=y&67108863,m>=18?(m-=18,p+=1,this.words[p]|=y>>>26):m+=8}this._strip()};function u(A,c,d,g){for(var w=0,m=0,p=Math.min(A.length,d),y=c;y<p;y++){var _=A.charCodeAt(y)-48;w*=g,_>=49?m=_-49+10:_>=17?m=_-17+10:m=_,n(_>=0&&m<g,"Invalid character"),w+=m}return w}r.prototype._parseBase=function(c,d,g){this.words=[0],this.length=1;for(var w=0,m=1;m<=67108863;m*=d)w++;w--,m=m/d|0;for(var p=c.length-g,y=p%w,_=Math.min(p,p-y)+g,f=0,k=g;k<_;k+=w)f=u(c,k,k+w,d),this.imuln(m),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 b=["","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 w=0,m=0,p=0;p<this.length;p++){var y=this.words[p],_=((y<<w|m)&16777215).toString(16);m=y>>>24-w&16777215,w+=2,w>=26&&(w-=26,p--),m!==0||p!==this.length-1?g=b[6-_.length]+_+g:g=_+g}for(m!==0&&(g=m.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=b[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 w=this.byteLength(),m=g||Math.max(1,w);n(w<=m,"byte array longer than desired length"),n(m>0,"Requested array length <= 0");var p=I(c,m),y=d==="le"?"LE":"BE";return this["_toArrayLike"+y](p,w),p},r.prototype._toArrayLikeLE=function(c,d){for(var g=0,w=0,m=0,p=0;m<this.length;m++){var y=this.words[m]<<p|w;c[g++]=y&255,g<c.length&&(c[g++]=y>>8&255),g<c.length&&(c[g++]=y>>16&255),p===6?(g<c.length&&(c[g++]=y>>24&255),w=0,p=0):(w=y>>>24,p+=2)}if(g<c.length)for(c[g++]=w;g<c.length;)c[g++]=0},r.prototype._toArrayLikeBE=function(c,d){for(var g=c.length-1,w=0,m=0,p=0;m<this.length;m++){var y=this.words[m]<<p|w;c[g--]=y&255,g>=0&&(c[g--]=y>>8&255),g>=0&&(c[g--]=y>>16&255),p===6?(g>=0&&(c[g--]=y>>24&255),w=0,p=0):(w=y>>>24,p+=2)}if(g>=0)for(c[g--]=w;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,w=d%26;c[d]=A.words[g]>>>w&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 w=0;w<g.length;w++)this.words[w]=d.words[w]^g.words[w];if(this!==d)for(;w<d.length;w++)this.words[w]=d.words[w];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 w=0;w<d;w++)this.words[w]=~this.words[w]&67108863;return g>0&&(this.words[w]=~this.words[w]&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,w=c%26;return this._expand(g+1),d?this.words[g]=this.words[g]|1<<w:this.words[g]=this.words[g]&~(1<<w),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,w;this.length>c.length?(g=this,w=c):(g=c,w=this);for(var m=0,p=0;p<w.length;p++)d=(g.words[p]|0)+(w.words[p]|0)+m,this.words[p]=d&67108863,m=d>>>26;for(;m!==0&&p<g.length;p++)d=(g.words[p]|0)+m,this.words[p]=d&67108863,m=d>>>26;if(this.length=g.length,m!==0)this.words[this.length]=m,this.length++;else if(g!==this)for(;p<g.length;p++)this.words[p]=g.words[p];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 w,m;g>0?(w=this,m=c):(w=c,m=this);for(var p=0,y=0;y<m.length;y++)d=(w.words[y]|0)-(m.words[y]|0)+p,p=d>>26,this.words[y]=d&67108863;for(;p!==0&&y<w.length;y++)d=(w.words[y]|0)+p,p=d>>26,this.words[y]=d&67108863;if(p===0&&y<w.length&&w!==this)for(;y<w.length;y++)this.words[y]=w.words[y];return this.length=Math.max(this.length,y),w!==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 w=A.words[0]|0,m=c.words[0]|0,p=w*m,y=p&67108863,_=p/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;w=A.words[R]|0,m=c.words[L]|0,p=w*m+M,k+=p/67108864|0,M=p&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 w=c.words,m=d.words,p=g.words,y=0,_,f,k,M=w[0]|0,j=M&8191,L=M>>>13,R=w[1]|0,W=R&8191,ne=R>>>13,pe=w[2]|0,ue=pe&8191,me=pe>>>13,vt=w[3]|0,De=vt&8191,je=vt>>>13,$i=w[4]|0,Ne=$i&8191,Fe=$i>>>13,jo=w[5]|0,Ke=jo&8191,ze=jo>>>13,tl=w[6]|0,Ve=tl&8191,Ge=tl>>>13,nl=w[7]|0,We=nl&8191,He=nl>>>13,il=w[8]|0,Ze=il&8191,Xe=il>>>13,rl=w[9]|0,Je=rl&8191,Ye=rl>>>13,ol=m[0]|0,Qe=ol&8191,et=ol>>>13,sl=m[1]|0,tt=sl&8191,nt=sl>>>13,al=m[2]|0,it=al&8191,rt=al>>>13,cl=m[3]|0,ot=cl&8191,st=cl>>>13,ul=m[4]|0,at=ul&8191,ct=ul>>>13,ll=m[5]|0,ut=ll&8191,lt=ll>>>13,dl=m[6]|0,dt=dl&8191,ft=dl>>>13,fl=m[7]|0,ht=fl&8191,pt=fl>>>13,hl=m[8]|0,mt=hl&8191,gt=hl>>>13,pl=m[9]|0,_t=pl&8191,yt=pl>>>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 Ca=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ca>>>26)|0,Ca&=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 Sa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Sa>>>26)|0,Sa&=67108863,_=Math.imul(ue,Qe),f=Math.imul(ue,et),f=f+Math.imul(me,Qe)|0,k=Math.imul(me,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 Aa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Aa>>>26)|0,Aa&=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(me,tt)|0,k=k+Math.imul(me,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 xa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(xa>>>26)|0,xa&=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(me,it)|0,k=k+Math.imul(me,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 Ia=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ia>>>26)|0,Ia&=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(me,ot)|0,k=k+Math.imul(me,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 Oa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Oa>>>26)|0,Oa&=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(me,at)|0,k=k+Math.imul(me,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 Pa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Pa>>>26)|0,Pa&=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(me,ut)|0,k=k+Math.imul(me,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,pt)|0,f=f+Math.imul(L,ht)|0,k=k+Math.imul(L,pt)|0;var Da=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Da>>>26)|0,Da&=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(me,dt)|0,k=k+Math.imul(me,ft)|0,_=_+Math.imul(W,ht)|0,f=f+Math.imul(W,pt)|0,f=f+Math.imul(ne,ht)|0,k=k+Math.imul(ne,pt)|0,_=_+Math.imul(j,mt)|0,f=f+Math.imul(j,gt)|0,f=f+Math.imul(L,mt)|0,k=k+Math.imul(L,gt)|0;var Ea=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ea>>>26)|0,Ea&=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,pt)|0,f=f+Math.imul(me,ht)|0,k=k+Math.imul(me,pt)|0,_=_+Math.imul(W,mt)|0,f=f+Math.imul(W,gt)|0,f=f+Math.imul(ne,mt)|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 Ma=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ma>>>26)|0,Ma&=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,pt)|0,f=f+Math.imul(je,ht)|0,k=k+Math.imul(je,pt)|0,_=_+Math.imul(ue,mt)|0,f=f+Math.imul(ue,gt)|0,f=f+Math.imul(me,mt)|0,k=k+Math.imul(me,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 Ba=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ba>>>26)|0,Ba&=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,pt)|0,f=f+Math.imul(Fe,ht)|0,k=k+Math.imul(Fe,pt)|0,_=_+Math.imul(De,mt)|0,f=f+Math.imul(De,gt)|0,f=f+Math.imul(je,mt)|0,k=k+Math.imul(je,gt)|0,_=_+Math.imul(ue,_t)|0,f=f+Math.imul(ue,yt)|0,f=f+Math.imul(me,_t)|0,k=k+Math.imul(me,yt)|0;var ja=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(ja>>>26)|0,ja&=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,pt)|0,f=f+Math.imul(ze,ht)|0,k=k+Math.imul(ze,pt)|0,_=_+Math.imul(Ne,mt)|0,f=f+Math.imul(Ne,gt)|0,f=f+Math.imul(Fe,mt)|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 Na=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Na>>>26)|0,Na&=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,pt)|0,f=f+Math.imul(Ge,ht)|0,k=k+Math.imul(Ge,pt)|0,_=_+Math.imul(Ke,mt)|0,f=f+Math.imul(Ke,gt)|0,f=f+Math.imul(ze,mt)|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 Fa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Fa>>>26)|0,Fa&=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,pt)|0,f=f+Math.imul(He,ht)|0,k=k+Math.imul(He,pt)|0,_=_+Math.imul(Ve,mt)|0,f=f+Math.imul(Ve,gt)|0,f=f+Math.imul(Ge,mt)|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 Ra=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(Ra>>>26)|0,Ra&=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,pt)|0,f=f+Math.imul(Xe,ht)|0,k=k+Math.imul(Xe,pt)|0,_=_+Math.imul(We,mt)|0,f=f+Math.imul(We,gt)|0,f=f+Math.imul(He,mt)|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 qa=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(qa>>>26)|0,qa&=67108863,_=Math.imul(Je,ht),f=Math.imul(Je,pt),f=f+Math.imul(Ye,ht)|0,k=Math.imul(Ye,pt),_=_+Math.imul(Ze,mt)|0,f=f+Math.imul(Ze,gt)|0,f=f+Math.imul(Xe,mt)|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 La=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+(La>>>26)|0,La&=67108863,_=Math.imul(Je,mt),f=Math.imul(Je,gt),f=f+Math.imul(Ye,mt)|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 $a=(y+_|0)+((f&8191)<<13)|0;y=(k+(f>>>13)|0)+($a>>>26)|0,$a&=67108863,_=Math.imul(Je,_t),f=Math.imul(Je,yt),f=f+Math.imul(Ye,_t)|0,k=Math.imul(Ye,yt);var Ua=(y+_|0)+((f&8191)<<13)|0;return y=(k+(f>>>13)|0)+(Ua>>>26)|0,Ua&=67108863,p[0]=Ca,p[1]=Sa,p[2]=Aa,p[3]=xa,p[4]=Ia,p[5]=Oa,p[6]=Pa,p[7]=Da,p[8]=Ea,p[9]=Ma,p[10]=Ba,p[11]=ja,p[12]=Na,p[13]=Fa,p[14]=Ra,p[15]=qa,p[16]=La,p[17]=$a,p[18]=Ua,y!==0&&(p[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,w=0,m=0;m<d.length-1;m++){var p=w;w=0;for(var y=g&67108863,_=Math.min(m,c.length-1),f=Math.max(0,m-A.length+1);f<=_;f++){var k=m-f,M=A.words[k]|0,j=c.words[f]|0,L=M*j,R=L&67108863;p=p+(L/67108864|0)|0,R=R+y|0,y=R&67108863,p=p+(R>>>26)|0,w+=p>>>26,p&=67108863}d.words[m]=y,g=p,p=w}return g!==0?d.words[m]=g:d.length--,d._strip()}function B(A,c,d){return E(A,c,d)}r.prototype.mulTo=function(c,d){var g,w=this.length+c.length;return this.length===10&&c.length===10?g=O(this,c,d):w<63?g=P(this,c,d):w<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,w=0;w<c;w++)d[w]=this.revBin(w,g,c);return d},$.prototype.revBin=function(c,d,g){if(c===0||c===g-1)return c;for(var w=0,m=0;m<d;m++)w|=(c&1)<<d-m-1,c>>=1;return w},$.prototype.permute=function(c,d,g,w,m,p){for(var y=0;y<p;y++)w[y]=d[c[y]],m[y]=g[c[y]]},$.prototype.transform=function(c,d,g,w,m,p){this.permute(p,c,d,g,w,m);for(var y=1;y<m;y<<=1)for(var _=y<<1,f=Math.cos(2*Math.PI/_),k=Math.sin(2*Math.PI/_),M=0;M<m;M+=_)for(var j=f,L=k,R=0;R<y;R++){var W=g[M+R],ne=w[M+R],pe=g[M+R+y],ue=w[M+R+y],me=j*pe-L*ue;ue=j*ue+L*pe,pe=me,g[M+R]=W+pe,w[M+R]=ne+ue,g[M+R+y]=W-pe,w[M+R+y]=ne-ue,R!==_&&(me=f*j-k*L,L=f*L+k*j,j=me)}},$.prototype.guessLen13b=function(c,d){var g=Math.max(d,c)|1,w=g&1,m=0;for(g=g/2|0;g;g=g>>>1)m++;return 1<<m+1+w},$.prototype.conjugate=function(c,d,g){if(!(g<=1))for(var w=0;w<g/2;w++){var m=c[w];c[w]=c[g-w-1],c[g-w-1]=m,m=d[w],d[w]=-d[g-w-1],d[g-w-1]=-m}},$.prototype.normalize13b=function(c,d){for(var g=0,w=0;w<d/2;w++){var m=Math.round(c[2*w+1]/d)*8192+Math.round(c[2*w]/d)+g;c[w]=m&67108863,m<67108864?g=0:g=m/67108864|0}return c},$.prototype.convert13b=function(c,d,g,w){for(var m=0,p=0;p<d;p++)m=m+(c[p]|0),g[2*p]=m&8191,m=m>>>13,g[2*p+1]=m&8191,m=m>>>13;for(p=2*d;p<w;++p)g[p]=0;n(m===0),n((m&-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 w=2*this.guessLen13b(c.length,d.length),m=this.makeRBT(w),p=this.stub(w),y=new Array(w),_=new Array(w),f=new Array(w),k=new Array(w),M=new Array(w),j=new Array(w),L=g.words;L.length=w,this.convert13b(c.words,c.length,y,w),this.convert13b(d.words,d.length,k,w),this.transform(y,p,_,f,w,m),this.transform(k,p,M,j,w,m);for(var R=0;R<w;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,w),this.transform(_,f,L,p,w,m),this.conjugate(L,p,w),this.normalize13b(L,w),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,w=0;w<this.length;w++){var m=(this.words[w]|0)*c,p=(m&67108863)+(g&67108863);g>>=26,g+=m/67108864|0,g+=p>>>26,this.words[w]=p&67108863}return g!==0&&(this.words[w]=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,w=0;w<d.length&&d[w]===0;w++,g=g.sqr());if(++w<d.length)for(var m=g.sqr();w<d.length;w++,m=m.sqr())d[w]!==0&&(g=g.mul(m));return g},r.prototype.iushln=function(c){n(typeof c=="number"&&c>=0);var d=c%26,g=(c-d)/26,w=67108863>>>26-d<<26-d,m;if(d!==0){var p=0;for(m=0;m<this.length;m++){var y=this.words[m]&w,_=(this.words[m]|0)-y<<d;this.words[m]=_|p,p=y>>>26-d}p&&(this.words[m]=p,this.length++)}if(g!==0){for(m=this.length-1;m>=0;m--)this.words[m+g]=this.words[m];for(m=0;m<g;m++)this.words[m]=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 w;d?w=(d-d%26)/26:w=0;var m=c%26,p=Math.min((c-m)/26,this.length),y=67108863^67108863>>>m<<m,_=g;if(w-=p,w=Math.max(0,w),_){for(var f=0;f<p;f++)_.words[f]=this.words[f];_.length=p}if(p!==0)if(this.length>p)for(this.length-=p,f=0;f<this.length;f++)this.words[f]=this.words[f+p];else this.words[0]=0,this.length=1;var k=0;for(f=this.length-1;f>=0&&(k!==0||f>=w);f--){var M=this.words[f]|0;this.words[f]=k<<26-m|M>>>m,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,w=1<<d;if(this.length<=g)return!1;var m=this.words[g];return!!(m&w)},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 w=67108863^67108863>>>d<<d;this.words[this.length-1]&=w}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 w=c.length+g,m;this._expand(w);var p,y=0;for(m=0;m<c.length;m++){p=(this.words[m+g]|0)+y;var _=(c.words[m]|0)*d;p-=_&67108863,y=(p>>26)-(_/67108864|0),this.words[m+g]=p&67108863}for(;m<this.length-g;m++)p=(this.words[m+g]|0)+y,y=p>>26,this.words[m+g]=p&67108863;if(y===0)return this._strip();for(n(y===-1),y=0,m=0;m<this.length;m++)p=-(this.words[m]|0)+y,y=p>>26,this.words[m]=p&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(c,d){var g=this.length-c.length,w=this.clone(),m=c,p=m.words[m.length-1]|0,y=this._countBits(p);g=26-y,g!==0&&(m=m.ushln(g),w.iushln(g),p=m.words[m.length-1]|0);var _=w.length-m.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=w.clone()._ishlnsubmul(m,1,_);M.negative===0&&(w=M,f&&(f.words[_]=1));for(var j=_-1;j>=0;j--){var L=(w.words[m.length+j]|0)*67108864+(w.words[m.length+j-1]|0);for(L=Math.min(L/p|0,67108863),w._ishlnsubmul(m,L,j);w.negative!==0;)L--,w.negative=0,w._ishlnsubmul(m,1,j),w.isZero()||(w.negative^=1);f&&(f.words[j]=L)}return f&&f._strip(),w._strip(),d!=="div"&&g!==0&&w.iushrn(g),{div:f||null,mod:w}},r.prototype.divmod=function(c,d,g){if(n(!c.isZero()),this.isZero())return{div:new r(0),mod:new r(0)};var w,m,p;return this.negative!==0&&c.negative===0?(p=this.neg().divmod(c,d),d!=="mod"&&(w=p.div.neg()),d!=="div"&&(m=p.mod.neg(),g&&m.negative!==0&&m.iadd(c)),{div:w,mod:m}):this.negative===0&&c.negative!==0?(p=this.divmod(c.neg(),d),d!=="mod"&&(w=p.div.neg()),{div:w,mod:p.mod}):this.negative&c.negative?(p=this.neg().divmod(c.neg(),d),d!=="div"&&(m=p.mod.neg(),g&&m.negative!==0&&m.isub(c)),{div:p.div,mod:m}):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,w=c.ushrn(1),m=c.andln(1),p=g.cmp(w);return p<0||m===1&&p===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,w=0,m=this.length-1;m>=0;m--)w=(g*w+(this.words[m]|0))%c;return d?-w:w},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,w=this.length-1;w>=0;w--){var m=(this.words[w]|0)+g*67108864;this.words[w]=m/c|0,g=m%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 w=new r(1),m=new r(0),p=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;)(w.isOdd()||m.isOdd())&&(w.iadd(f),m.isub(k)),w.iushrn(1),m.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;)(p.isOdd()||y.isOdd())&&(p.iadd(f),y.isub(k)),p.iushrn(1),y.iushrn(1);d.cmp(g)>=0?(d.isub(g),w.isub(p),m.isub(y)):(g.isub(d),p.isub(w),y.isub(m))}return{a:p,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 w=new r(1),m=new r(0),p=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;)w.isOdd()&&w.iadd(p),w.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;)m.isOdd()&&m.iadd(p),m.iushrn(1);d.cmp(g)>=0?(d.isub(g),w.isub(m)):(g.isub(d),m.isub(w))}var M;return d.cmpn(1)===0?M=w:M=m,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 w=0;d.isEven()&&g.isEven();w++)d.iushrn(1),g.iushrn(1);do{for(;d.isEven();)d.iushrn(1);for(;g.isEven();)g.iushrn(1);var m=d.cmp(g);if(m<0){var p=d;d=g,g=p}else if(m===0||g.cmpn(1)===0)break;d.isub(g)}while(!0);return g.iushln(w)},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,w=1<<d;if(this.length<=g)return this._expand(g+1),this.words[g]|=w,this;for(var m=w,p=g;m!==0&&p<this.length;p++){var y=this.words[p]|0;y+=m,m=y>>>26,y&=67108863,this.words[p]=y}return m!==0&&(this.words[p]=m,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 w=this.words[0]|0;g=w===c?0:w<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 w=this.words[g]|0,m=c.words[g]|0;if(w!==m){w<m?d=-1:w>m&&(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 w=g<this.n?-1:d.ucmp(this.p);return w===0?(d.words[0]=0,d.length=1):w>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,w=Math.min(c.length,9),m=0;m<w;m++)d.words[m]=c.words[m];if(d.length=w,c.length<=9){c.words[0]=0,c.length=1;return}var p=c.words[9];for(d.words[d.length++]=p&g,m=10;m<c.length;m++){var y=c.words[m]|0;c.words[m-10]=(y&g)<<4|p>>>22,p=y}p>>>=22,c.words[m-10]=p,p===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 w=c.words[g]|0;d+=w*977,c.words[g]=d&67108863,d=w*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 w=(c.words[g]|0)*19+d,m=w&67108863;w>>>=26,c.words[g]=m,d=w}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 w=this.m.subn(1),m=0;!w.isZero()&&w.andln(1)===0;)m++,w.iushrn(1);n(!w.isZero());var p=new r(1).toRed(this),y=p.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,w),M=this.pow(c,w.addn(1).iushrn(1)),j=this.pow(c,w),L=m;j.cmp(p)!==0;){for(var R=j,W=0;R.cmp(p)!==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,w=new Array(1<<g);w[0]=new r(1).toRed(this),w[1]=c;for(var m=2;m<w.length;m++)w[m]=this.mul(w[m-1],c);var p=w[0],y=0,_=0,f=d.bitLength()%26;for(f===0&&(f=26),m=d.length-1;m>=0;m--){for(var k=d.words[m],M=f-1;M>=0;M--){var j=k>>M&1;if(p!==w[0]&&(p=this.sqr(p)),j===0&&y===0){_=0;continue}y<<=1,y|=j,_++,!(_!==g&&(m!==0||M!==0))&&(p=this.mul(p,w[y]),_=0,y=0)}f=26}return p},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),w=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),m=g.isub(w).iushrn(this.shift),p=m;return m.cmp(this.m)>=0?p=m.isub(this.m):m.cmpn(0)<0&&(p=m.iadd(this.m)),p._forceRed(this)},C.prototype.mul=function(c,d){if(c.isZero()||d.isZero())return new r(0)._forceRed(this);var g=c.mul(d),w=g.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),m=g.isub(w).iushrn(this.shift),p=m;return m.cmp(this.m)>=0?p=m.isub(this.m):m.cmpn(0)<0&&(p=m.iadd(this.m)),p._forceRed(this)},C.prototype.invm=function(c){var d=this.imod(c._invmp(this.m).mul(this.r2));return d._forceRed(this)}})(typeof Va>"u"||Va,Pl)});var hd={};ml(hd,{__addDisposableResource:()=>dd,__assign:()=>Go,__asyncDelegator:()=>id,__asyncGenerator:()=>nd,__asyncValues:()=>rd,__await:()=>Gi,__awaiter:()=>Xl,__classPrivateFieldGet:()=>cd,__classPrivateFieldIn:()=>ld,__classPrivateFieldSet:()=>ud,__createBinding:()=>Ho,__decorate:()=>Wl,__disposeResources:()=>fd,__esDecorate:()=>Z_,__exportStar:()=>Yl,__extends:()=>Vl,__generator:()=>Jl,__importDefault:()=>ad,__importStar:()=>sd,__makeTemplateObject:()=>od,__metadata:()=>Zl,__param:()=>Hl,__propKey:()=>J_,__read:()=>tc,__rest:()=>Gl,__runInitializers:()=>X_,__setFunctionName:()=>Y_,__spread:()=>Ql,__spreadArray:()=>td,__spreadArrays:()=>ed,__values:()=>Wo,default:()=>t0});function Vl(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ec(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Gl(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 Wl(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 Hl(t,e){return function(n,i){e(n,i,t)}}function Z_(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):{}),b,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");(b=s(P.get))&&(h.get=b),(b=s(P.set))&&(h.set=b),(b=s(P.init))&&r.unshift(b)}else(b=s(P))&&(a==="field"?r.unshift(b):h[u]=b)}l&&Object.defineProperty(l,i.name,h),v=!0}function X_(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 J_(t){return typeof t=="symbol"?t:"".concat(t)}function Y_(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 Zl(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Xl(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(b){s(b)}}function u(h){try{l(i.throw(h))}catch(b){s(b)}}function l(h){h.done?o(h.value):r(h.value).then(a,u)}l((i=i.apply(t,e||[])).next())})}function Jl(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 Yl(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ho(e,t,n)}function Wo(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 tc(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 Ql(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(tc(arguments[e]));return t}function ed(){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 td(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 Gi(t){return this instanceof Gi?(this.v=t,this):new Gi(t)}function nd(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){b(o[0][3],I)}}function u(v){v.value instanceof Gi?Promise.resolve(v.value.v).then(l,h):b(o[0][2],v)}function l(v){a("next",v)}function h(v){a("throw",v)}function b(v,T){v(T),o.shift(),o.length&&a(o[0][0],o[0][1])}}function id(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:Gi(t[r](s)),done:!1}:o?o(s):s}:o}}function rd(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 Wo=="function"?Wo(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 od(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function sd(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)&&Ho(e,t,n);return Q_(e,t),e}function ad(t){return t&&t.__esModule?t:{default:t}}function cd(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 ud(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 ld(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 dd(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 fd(t){function e(i){t.error=t.hasError?new e0(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 ec,Go,Ho,Q_,e0,t0,pd=zg(()=>{"use strict";ec=function(t,e){return ec=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])},ec(t,e)};Go=function(){return Go=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},Go.apply(this,arguments)};Ho=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};e0=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var i=new Error(n);return i.name="SuppressedError",i.error=t,i.suppressed=e,i};t0={__extends:Vl,__assign:Go,__rest:Gl,__decorate:Wl,__param:Hl,__metadata:Zl,__awaiter:Xl,__generator:Jl,__createBinding:Ho,__exportStar:Yl,__values:Wo,__read:tc,__spread:Ql,__spreadArrays:ed,__spreadArray:td,__await:Gi,__asyncGenerator:nd,__asyncDelegator:id,__asyncValues:rd,__makeTemplateObject:od,__importStar:sd,__importDefault:ad,__classPrivateFieldGet:cd,__classPrivateFieldSet:ud,__classPrivateFieldIn:ld,__addDisposableResource:dd,__disposeResources:fd}});var gd=pi((Zo,md)=>{"use strict";(function(t,e){typeof Zo=="object"&&typeof md<"u"?e(Zo,(pd(),_l(hd))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(Zo,function(t,e){"use strict";var n=function(){function m(p,y,_){_===void 0&&(_=0),this.startVertex=p,this.endVertex=y,this.weight=_}return m.prototype.getKey=function(){var p=this.startVertex.getKey(),y=this.endVertex.getKey();return p+"_"+y},m.prototype.reverse=function(){var p=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=p,this},m.prototype.clone=function(){return new m(this.startVertex,this.endVertex,this.weight)},m.prototype.toString=function(){return this.getKey()},m}();function i(m,p,y){if(y===void 0&&(y="cc-graph"),!m)throw new Error((y?"["+y+"]":"")+" Invariant failed: "+p)}function r(m,p){p===void 0&&(p=!0);var y=typeof m<"u"&&m!==null;return p?y&&m!=="undefined"&&m!=="null":y}var o=function(){function m(p){i(r(p),"Graph vertex must have a value"),this.value=p,this.edges=new Map}return m.prototype.addEdge=function(p){return this.edges.set(p.getKey(),p),this},m.prototype.deleteEdge=function(p){this.edges.delete(p.getKey())},m.prototype.getNeighbors=function(){var p=this,y=this.getEdges(),_=function(f){return f.startVertex===p?f.endVertex:f.startVertex};return y.map(_)},m.prototype.getEdges=function(){return Array.from(this.edges.values())},m.prototype.getDegree=function(){return this.getEdges().length},m.prototype.hasEdge=function(p){var y=this.getEdges().find(function(_){return _===p});return!!y},m.prototype.hasNeighbor=function(p){var y=this.getEdges().find(function(_){return _.startVertex===p||_.endVertex===p});return!!y},m.prototype.findEdge=function(p){var y=function(f){return f.startVertex===p||f.endVertex===p},_=this.getEdges().find(y);return _||null},m.prototype.getKey=function(){return this.value},m.prototype.deleteAllEdges=function(){var p=this;return this.getEdges().forEach(function(y){return p.deleteEdge(y)}),this},m.prototype.toString=function(p){return p?p(this.value):""+this.value},m}(),s;(function(m){m[m.EQUAL=0]="EQUAL",m[m.GREATER=1]="GREATER",m[m.LESS=-1]="LESS"})(s||(s={}));var a=function(){function m(p){this.compare=p||m.defaultCompareFunction}return m.defaultCompareFunction=function(p,y){return p===y?s.EQUAL:p<y?s.LESS:s.GREATER},m.prototype.equal=function(p,y){return this.compare(p,y)===s.EQUAL},m.prototype.lessThan=function(p,y){return this.compare(p,y)===s.LESS},m.prototype.greaterThan=function(p,y){return this.compare(p,y)===s.GREATER},m.prototype.lessThanOrEqual=function(p,y){return this.lessThan(p,y)||this.equal(p,y)},m.prototype.greaterThanOrEqual=function(p,y){return this.greaterThan(p,y)||this.equal(p,y)},m.prototype.reverse=function(){var p=this.compare;this.compare=function(y,_){return p(_,y)}},m}(),u=function(){function m(p){this.value=p,this.next=null}return m}(),l=function(){function m(p){this.value=p,this.next=null,this.prev=null}return m}();var h=function(m,p){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,_){y.__proto__=_}||function(y,_){for(var f in _)_.hasOwnProperty(f)&&(y[f]=_[f])},h(m,p)};function b(m,p){h(m,p);function y(){this.constructor=m}m.prototype=p===null?Object.create(p):(y.prototype=p.prototype,new y)}function v(m,p){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=p.call(m,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(m,p){var y=typeof Symbol=="function"&&m[Symbol.iterator];if(!y)return m;var _=y.call(m),f,k=[],M;try{for(;(p===void 0||p-- >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 m=[],p=0;p<arguments.length;p++)m=m.concat(T(arguments[p]));return m}var x="obfuse error occur";function P(m,p){if(!m)throw new Error("[linked-list] "+(p||x))}var O=-1,E=function(){function m(){for(var p=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){p.append(f)})}return Object.defineProperty(m.prototype,"head",{get:function(){return this._head?this._head.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"tail",{get:function(){return this._tail?this._tail.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"loopLength",{get:function(){var p=!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){p=!0;break}if(p){for(f=f.next;_!==f;)y++,f=f.next;return y}else return 0},enumerable:!0,configurable:!0}),m.prototype.getNode=function(p){var y=this._length;P(y>0&&p>=0&&p<y,"[linked-list] index "+p+" out of scope of list, which length is "+y);for(var _=this._head,f=0;f<p;)_=_.next,f++;return _},m.prototype.get=function(p){var y=this.getNode(p);return y?y.value:null},m.prototype.find=function(p){var y=p.value,_=p.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},m.prototype.indexOf=function(p){if(!this._head)return O;for(var y=this._head,_=-1;y.next;){if(_++,this.compare.equal(y.value,p))return _;y=y.next}return y===this._tail&&this.compare.equal(y.value,p)&&(_+=1),_},m.prototype.first=function(p){P(p>=0,"[linked-list] param 'num' ("+p+") should not less than 0");for(var y=this.iterator(),_=[],f=Math.min(p,this.length),k=0;k<f;k++){var M=y.next();_.push(M.value)}return _},m.prototype.toArray=function(){return I(this)},m.prototype.isEmpty=function(){return this._head===null},m.prototype.iterator=function(){var p;return v(this,function(y){switch(y.label){case 0:p=this._head,y.label=1;case 1:return p?[4,p.value]:[3,3];case 2:return y.sent(),p=p.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m}(),B=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return m.apply(this,I(y))||this}return p.prototype.append=function(y){var _=new u(y);return this._tail?(this._tail.next=_,this._tail=_):this._head=this._tail=_,this._length++,!0},p.prototype.prepend=function(y){var _=new u(y);return this._head?(_.next=this._head,this._head=_):this._head=this._tail=_,this._length++,!0},p.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}}},p.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},p.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}},p.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=_}},p.prototype.clone=function(){var y=this.toArray();return new(p.bind.apply(p,I([void 0],y)))},p}(E),$=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=m.apply(this,I(y))||this;return f.cyclization(),f}return p.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]}})},p.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]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=m.prototype[y].apply(this,_);return this.cyclization(),k},p.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},p.prototype.append=function(y){return this.mapToNormalListFn("append",y)},p.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},p.prototype.find=function(y){return this.mapToNormalListFn("find",y)},p.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},p.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},p.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},p.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},p.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},p.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},p.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},p}(B),Z=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=m.apply(this,I(y))||this;return f.cyclization(),f}return p.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},p.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},p.prototype.clone=function(){var y=this.toArray();return new(p.bind.apply(p,I([void 0],y)))},p}($),H=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];return m.apply(this,I(y))||this}return p.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},p.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},p.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}}},p.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},p.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},p.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=_}},p.prototype.clone=function(){var y=this.toArray();return new(p.bind.apply(p,I([void 0],y)))},p}(E),te=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=m.apply(this,I(y))||this;return f.cyclization(),f}return p.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]}})},p.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]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p.prototype.mapToNormalListFn=function(y){for(var _=[],f=1;f<arguments.length;f++)_[f-1]=arguments[f];this.breakCircle();var k=m.prototype[y].apply(this,_);return this.cyclization(),k},p.prototype.getNode=function(y){return this.mapToNormalListFn("getNode",y)},p.prototype.append=function(y){return this.mapToNormalListFn("append",y)},p.prototype.prepend=function(y){return this.mapToNormalListFn("prepend",y)},p.prototype.find=function(y){return this.mapToNormalListFn("find",y)},p.prototype.indexOf=function(y){return this.mapToNormalListFn("indexOf",y)},p.prototype.remove=function(y){return this.mapToNormalListFn("remove",y)},p.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},p.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},p.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},p.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},p.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},p}(H),U=function(m){b(p,m);function p(){for(var y=[],_=0;_<arguments.length;_++)y[_]=arguments[_];var f=m.apply(this,I(y))||this;return f.cyclization(),f}return p.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},p.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},p.prototype.clone=function(){var y=this.toArray();return new(p.bind.apply(p,I([void 0],y)))},p}(te);function V(m,p){var y=typeof Symbol=="function"&&m[Symbol.iterator];if(!y)return m;var _=y.call(m),f,k=[],M;try{for(;(p===void 0||p-- >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 m=[],p=0;p<arguments.length;p++)m=m.concat(V(arguments[p]));return m}var K=function(){function m(){for(var p=[],y=0;y<arguments.length;y++)p[y]=arguments[y];this.queue=new(B.bind.apply(B,F([void 0],p)))}return Object.defineProperty(m.prototype,"length",{get:function(){return this.queue.length},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"peek",{get:function(){return this.queue.head},enumerable:!0,configurable:!0}),m.prototype.isEmpty=function(){return this.queue.isEmpty()},m.prototype.enqueue=function(p){return this.queue.append(p)},m.prototype.dequeue=function(){var p=this.queue.removeHead();return typeof p<"u"?p:void 0},m.prototype.toArray=function(){return this.queue.toArray()},m}();function C(m,p){var y=typeof Symbol=="function"&&m[Symbol.iterator];if(!y)return m;var _=y.call(m),f,k=[],M;try{for(;(p===void 0||p-- >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 m=[],p=0;p<arguments.length;p++)m=m.concat(C(arguments[p]));return m}var c=function(){function m(){for(var p=[],y=0;y<arguments.length;y++)p[y]=arguments[y];this.stack=new(B.bind.apply(B,A([void 0],p)))}return Object.defineProperty(m.prototype,"length",{get:function(){return this.stack.length},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"peek",{get:function(){return this.stack.tail},enumerable:!0,configurable:!0}),m.prototype.isEmpty=function(){return this.stack.isEmpty()},m.prototype.push=function(p){return this.stack.append(p)},m.prototype.pop=function(){var p=this.stack.removeTail();return typeof p<"u"?p:void 0},m.prototype.popBottom=function(){var p=this.stack.removeHead();return typeof p<"u"?p:void 0},m.prototype.toArray=function(){return this.stack.toArray()},m}();function d(m,p,y,_){if(m){p.push(m),_.set(m.getKey(),!0);var f=m.getNeighbors().filter(function(k){return!_.get(k.getKey())});y.push(f)}}function g(m,p,y){var _=m.pop();_&&y.set(_.getKey(),!1),p.pop()}var w=function(){function m(p){p===void 0&&(p=!1),this.vertices={},this.edges={},this.isDirected=p}return m.prototype.addVertex=function(p){return this.vertices[p.getKey()]=p,this},m.prototype.getVertexByKey=function(p){return this.vertices[p]},m.prototype.getNeighbors=function(p){return p.getNeighbors()},m.prototype.getAllVertices=function(){return Object.values(this.vertices)},m.prototype.getAllEdges=function(){return Object.values(this.edges)},m.prototype.addEdge=function(p,y){if(y===void 0&&(y=!1),this.edges[p.getKey()]){if(y)return this;i(!1,"Edge has already been added before")}var _=this.getVertexByKey(p.startVertex.getKey()),f=this.getVertexByKey(p.endVertex.getKey());if(_||(this.addVertex(p.startVertex),_=this.getVertexByKey(p.startVertex.getKey())),f||(this.addVertex(p.endVertex),f=this.getVertexByKey(p.endVertex.getKey())),this.edges[p.getKey()]=p,this.isDirected)_.addEdge(p);else{_.addEdge(p);var k=p.clone();f.addEdge(k.reverse())}return this},m.prototype.deleteEdge=function(p,y){if(y===void 0&&(y=!1),!this.edges[p.getKey()]){if(y)return this;i(!1,"Edge not found in graph")}delete this.edges[p.getKey()];var _=this.getVertexByKey(p.startVertex.getKey()),f=this.getVertexByKey(p.endVertex.getKey());return _.deleteEdge(p),f.deleteEdge(p),this},m.prototype.findEdge=function(p,y){var _=this.getVertexByKey(p.getKey());return _?_.findEdge(y):null},m.prototype.getWeight=function(){return this.getAllEdges().reduce(function(p,y){return p+y.weight},0)},m.prototype.reverse=function(){var p=this;return this.getAllEdges().forEach(function(y){p.deleteEdge(y),y.reverse(),p.addEdge(y)}),this},m.prototype.getVerticesIndices=function(){var p={};return this.getAllVertices().forEach(function(y,_){p[y.getKey()]=_}),p},m.prototype.getAdjacencyMatrix=function(){var p=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=p.findEdge(k,j);R&&(f[M][L]=R.weight)})}),f},m.prototype.toString=function(){return Object.keys(this.vertices).toString()},m.prototype.bfs=function(p){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new K,_.enqueue(p),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]}})},m.prototype.dfs=function(p){var y,_,f;return e.__generator(this,function(k){switch(k.label){case 0:y=new Map,_=new c,_.push(p),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]}})},m.prototype.findAllPath=function(p,y){var _,f,k,M,j,L,R;return e.__generator(this,function(W){switch(W.label){case 0:return _=[],p!==y?[3,2]:(_.push(p),[4,_]);case 1:return W.sent(),[2];case 2:f=new Map,k=new c,M=new c,d(p,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]}})},m}();t.GraphEdge=n,t.GraphVertex=o,t.Graph=w,Object.defineProperty(t,"__esModule",{value:!0})})});var Fh=pi((yu,bu)=>{"use strict";(function(t,e){typeof yu=="object"&&typeof bu<"u"?bu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(yu,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 b(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||!b(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
+ 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 w=c.value;d.push((w&&(w>>>0).toString(16))+", ")}}catch(m){g.e(m)}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 w=32767&c,m=c>>>15,p=0,y=d,_=0;_<g;_++){var f=this.__digit(_),k=32767&f,M=f>>>15,j=C.__imul(k,w),L=C.__imul(k,m),R=C.__imul(M,w),W=C.__imul(M,m),ne=y+j+p;p=ne>>>30,ne&=1073741823,ne+=((32767&L)<<15)+((32767&R)<<15),p+=ne>>>30,y=W+(L>>>15)+(R>>>15),this.__setDigit(_,1073741823&ne)}if(p!==0||y!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(c,d,g){for(var w,m=0,p=0;p<g;p++)w=this.__halfDigit(d+p)+c.__halfDigit(p)+m,m=w>>>15,this.__setHalfDigit(d+p,32767&w);return m}},{key:"__inplaceSub",value:function(c,d,g){var w=0;if(1&d){d>>=1;for(var m=this.__digit(d),p=32767&m,y=0;y<g-1>>>1;y++){var _=c.__digit(y),f=(m>>>15)-(32767&_)-w;w=1&f>>>15,this.__setDigit(d+y,(32767&f)<<15|32767&p),m=this.__digit(d+y+1),p=(32767&m)-(_>>>15)-w,w=1&p>>>15}var k=c.__digit(y),M=(m>>>15)-(32767&k)-w;if(w=1&M>>>15,this.__setDigit(d+y,(32767&M)<<15|32767&p),d+y+1>=this.length)throw new RangeError("out of bounds");!(1&g)&&(m=this.__digit(d+y+1),p=(32767&m)-(k>>>15)-w,w=1&p>>>15,this.__setDigit(d+c.length,1073709056&m|32767&p))}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)-w;w=1&W>>>15;var ne=(L>>>15)-(R>>>15)-w;w=1&ne>>>15,this.__setDigit(d+j,(32767&ne)<<15|32767&W)}var pe=this.__digit(d+j),ue=c.__digit(j),me=(32767&pe)-(32767&ue)-w;w=1&me>>>15;var vt=0;!(1&g)&&(vt=(pe>>>15)-(ue>>>15)-w,w=1&vt>>>15),this.__setDigit(d+j,(32767&vt)<<15|32767&me)}return w}},{key:"__inplaceRightShift",value:function(c){if(c!==0){for(var d,g=this.__digit(0)>>>c,w=this.length-1,m=0;m<w;m++)d=this.__digit(m+1),this.__setDigit(m,1073741823&d<<30-c|g),g=d>>>c;this.__setDigit(w,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,w=this.__digit(g),m=1&c?32767&w|d<<15:1073709056&w|32767&d;this.__setDigit(g,m)}}],[{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 w=C.__toPrimitive(c);return C.BigInt(w)}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 w=c.__digit(d-1),m=C.__clz30(w),p=30*d-m;if(1024<p)return c.sign?-1/0:1/0;var y=p-1,_=w,f=d-1,k=m+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 w=1+(0|g/30),m=c.sign&&(1&g)!=0,p=new C(w,m);p.__initializeDigits();var y=1<<g%30;return p.__setDigit(w-1,y),p}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 w=new C(g,c.sign!==d.sign);w.__initializeDigits();for(var m=0;m<c.length;m++)C.__multiplyAccumulate(d,c.__digit(m),w,m);return w.__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,w=c.sign!==d.sign,m=d.__unsignedDigit(0);if(d.length===1&&32767>=m){if(m===1)return w===c.sign?c:C.unaryMinus(c);g=C.__absoluteDivSmall(c,m,null)}else g=C.__absoluteDivLarge(c,d,!0,!1);return g.sign=w,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 w=g.__unsignedDigit(0);if(g.length===1&&32767>=w){if(w===1)return C.__zero();var m=C.__absoluteModSmall(d,w);return m===0?C.__zero():C.__oneDigit(m,d.sign)}var p=C.__absoluteDivLarge(d,g,!1,!0);return p.sign=d.sign,p.__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,w=C.__absoluteSubOne(c,g),m=C.__absoluteSubOne(d);return w=C.__absoluteOr(w,m,w),C.__absoluteAddOne(w,!0,w).__trim()}if(c.sign){var p=[d,c];c=p[0],d=p[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),w=C.__absoluteSubOne(c,g),m=C.__absoluteSubOne(d);return C.__absoluteXor(w,m,w).__trim()}var p=F(c.length,d.length)+1;if(c.sign){var y=[d,c];c=y[0],d=y[1]}var _=C.__absoluteSubOne(d,p);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 w=C.__absoluteSubOne(c,g),m=C.__absoluteSubOne(d);return w=C.__absoluteAnd(w,m,w),C.__absoluteAddOne(w,!0,w).__trim()}if(c.sign){var p=[d,c];c=p[0],d=p[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 w=d.__unsignedDigit(g-1),m=1<<(c-1)%30;if(d.length===g&&w<m)return d;if((w&m)!==m)return C.__truncateToNBits(c,d);if(!d.sign)return C.__truncateAndSubFromPowerOfTwo(c,d,!0);if(!(w&m-1)){for(var p=g-2;0<=p;p--)if(d.__digit(p)!==0)return C.__truncateAndSubFromPowerOfTwo(c,d,!1);return d.length===g&&w===m?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 w=c%30;if(d.length==g){if(w===0)return d;var m=d.__digit(g-1);if(!(m>>>w))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],w=g?[4,0]:[0,4],m=P(w,2),p=m[0],y=m[1],_=c.getUint32(d+p,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 w=3<arguments.length&&arguments[3]!==void 0&&arguments[3];C.DataViewSetBigUint64(c,d,g,w)}},{key:"DataViewSetBigUint64",value:function(c,d,g){var w=3<arguments.length&&arguments[3]!==void 0&&arguments[3];g=C.asUintN(64,g);var m=0,p=0;if(0<g.length&&(p=g.__digit(0),1<g.length)){var y=g.__digit(1);p|=y<<30,m=y>>>2,2<g.length&&(m|=g.__digit(2)<<28)}var _=w?[4,0]:[0,4],f=P(_,2),k=f[0],M=f[1];c.setUint32(d+k,m,w),c.setUint32(d+M,p,w)}},{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,w){if(0<d)return-1;var m;if(0>d)m=-d-1;else{if(g===0)return-1;g--,w=c.__digit(g),m=29}var p=1<<m;if(!(w&p))return-1;if(p-=1,(w&p)!=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,w=g-1023,m=(0|w/30)+1,p=new C(m,0>c),y=1048575&C.__kBitConversionInts[1]|1048576,_=C.__kBitConversionInts[0],f=20,k=w%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}p.__setDigit(m-1,d);for(var R=m-2;0<=R;R--)0<M?(M-=30,d=y>>>2,y=y<<30|_>>>2,_<<=30):d=0,p.__setDigit(R,d);return p.__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,w=c.length,m=0;if(m===w)return C.__zero();for(var p=c.charCodeAt(m);C.__isWhitespace(p);){if(++m===w)return C.__zero();p=c.charCodeAt(m)}if(p===43){if(++m===w)return null;p=c.charCodeAt(m),g=1}else if(p===45){if(++m===w)return null;p=c.charCodeAt(m),g=-1}if(d===0){if(d=10,p===48){if(++m===w)return C.__zero();if(p=c.charCodeAt(m),p===88||p===120){if(d=16,++m===w)return null;p=c.charCodeAt(m)}else if(p===79||p===111){if(d=8,++m===w)return null;p=c.charCodeAt(m)}else if(p===66||p===98){if(d=2,++m===w)return null;p=c.charCodeAt(m)}}}else if(d===16&&p===48){if(++m===w)return C.__zero();if(p=c.charCodeAt(m),p===88||p===120){if(++m===w)return null;p=c.charCodeAt(m)}}if(g!==0&&d!==10)return null;for(;p===48;){if(++m===w)return C.__zero();p=c.charCodeAt(m)}var y=w-m,_=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,$i=0,Ne=1;;){if(je=void 0,p-48>>>0<j)je=p-48;else if((32|p)-97>>>0<L)je=(32|p)-87;else{vt=!0;break}var Fe=Ne*d;if(1073741823<Fe)break;if(Ne=Fe,$i=$i*d+je,De++,++m===w){vt=!0;break}p=c.charCodeAt(m)}f=30*C.__kBitsPerCharTableMultiplier-1;var jo=0|(_*De+f>>>C.__kBitsPerCharTableShift)/30;M.__inplaceMultiplyAdd(Ne,$i,jo)}while(!vt)}else{_>>=C.__kBitsPerCharTableShift;var R=[],W=[],ne=!1;do{for(var pe,ue=0,me=0;;){if(pe=void 0,p-48>>>0<j)pe=p-48;else if((32|p)-97>>>0<L)pe=(32|p)-87;else{ne=!0;break}if(me+=_,ue=ue<<_|pe,++m===w){ne=!0;break}if(p=c.charCodeAt(m),30<me+_)break}R.push(ue),W.push(me)}while(!ne);C.__fillFromParts(M,R,W)}if(m!==w){if(!C.__isWhitespace(p))return null;for(m++;m<w;m++)if(p=c.charCodeAt(m),!C.__isWhitespace(p))return null}return M.sign=g===-1,M.__trim()}},{key:"__fillFromParts",value:function(c,d,g){for(var w=0,m=0,p=0,y=d.length-1;0<=y;y--){var _=d[y],f=g[y];m|=_<<p,p+=f,p===30?(c.__setDigit(w++,m),p=0,m=0):30<p&&(c.__setDigit(w++,1073741823&m),p-=30,m=_>>>f-p)}if(m!==0){if(w>=c.length)throw new Error("implementation bug");c.__setDigit(w++,m)}for(;w<c.length;w++)c.__setDigit(w,0)}},{key:"__toStringBasePowerOfTwo",value:function(c,d){var g=c.length,w=d-1;w=(85&w>>>1)+(85&w),w=(51&w>>>2)+(51&w),w=(15&w>>>4)+(15&w);var m=w,p=d-1,y=c.__digit(g-1),_=C.__clz30(y),f=0|(30*g-_+m-1)/m;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)&p;k[M--]=C.__kConversionChars[ne];var pe=m-L;for(j=W>>>pe,L=30-pe;L>=m;)k[M--]=C.__kConversionChars[j&p],j>>>=m,L-=m}var ue=(j|y<<L)&p;for(k[M--]=C.__kConversionChars[ue],j=y>>>m-L;j!==0;)k[M--]=C.__kConversionChars[j&p],j>>>=m;if(c.sign&&(k[M--]="-"),M!==-1)throw new Error("implementation bug");return k.join("")}},{key:"__toStringGeneric",value:function(c,d,g){var w=c.length;if(w===0)return"";if(w===1){var m=c.__unsignedDigit(0).toString(d);return g===!1&&c.sign&&(m="-"+m),m}var p=30*w-C.__clz30(c.__digit(w-1)),y=C.__kMaxBitsPerChar[d],_=y-1,f=p*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,pe=2*c.length-1;0<=pe;pe--)W=ne<<15|c.__halfDigit(pe),k.__setHalfDigit(pe,0|W/R),ne=0|W%R;M=ne.toString(d)}else{var ue=C.__absoluteDivLarge(c,L,!0,!0);k=ue.quotient;var me=ue.remainder.__trim();M=C.__toStringGeneric(me,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 w=C.__absoluteCompare(c,d);return 0<w?C.__absoluteGreater(g):0>w?C.__absoluteLess(g):0}},{key:"__compareToNumber",value:function(c,d){if(C.__isOneDigitInt(d)){var g=c.sign,w=0>d;if(g!==w)return C.__unequalSign(g);if(c.length===0){if(w)throw new Error("implementation bug");return d===0?0:-1}if(1<c.length)return C.__absoluteGreater(g);var m=V(d),p=c.__unsignedDigit(0);return p>m?C.__absoluteGreater(g):p<m?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 w=2047&C.__kBitConversionInts[1]>>>20;if(w==2047)throw new Error("implementation bug: handled elsewhere");var m=w-1023;if(0>m)return C.__absoluteGreater(g);var p=c.length,y=c.__digit(p-1),_=C.__clz30(y),f=30*p-_,k=m+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 pe=L-R;ne=pe+32,W=M>>>pe,M=M<<32-pe|j>>>pe,j<<=32-pe}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 me=p-2;0<=me;me--){0<ne?(ne-=30,W=M>>>2,M=M<<30|j>>>2,j<<=30):W=0;var vt=c.__unsignedDigit(me);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 w=c.length;(c.__clzmsd()===0||d.length===c.length&&d.__clzmsd()===0)&&w++;for(var m,p=new C(w,g),y=0,_=0;_<d.length;_++)m=c.__digit(_)+d.__digit(_)+y,y=m>>>30,p.__setDigit(_,1073741823&m);for(;_<c.length;_++){var f=c.__digit(_)+y;y=f>>>30,p.__setDigit(_,1073741823&f)}return _<p.length&&p.__setDigit(_,y),p.__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 w,m=new C(c.length,g),p=0,y=0;y<d.length;y++)w=c.__digit(y)-d.__digit(y)-p,p=1&w>>>30,m.__setDigit(y,1073741823&w);for(;y<c.length;y++){var _=c.__digit(y)-p;p=1&_>>>30,m.__setDigit(y,1073741823&_)}return m.__trim()}},{key:"__absoluteAddOne",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,w=c.length;g===null?g=new C(w,d):g.sign=d;for(var m,p=1,y=0;y<w;y++)m=c.__digit(y)+p,p=m>>>30,g.__setDigit(y,1073741823&m);return p!==0&&g.__setDigitGrow(w,1),g}},{key:"__absoluteSubOne",value:function(c,d){var g=c.length;d=d||g;for(var w,m=new C(d,!1),p=1,y=0;y<g;y++)w=c.__digit(y)-p,p=1&w>>>30,m.__setDigit(y,1073741823&w);if(p!==0)throw new Error("implementation bug");for(var _=g;_<d;_++)m.__setDigit(_,0);return m}},{key:"__absoluteAnd",value:function(c,d){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,w=c.length,m=d.length,p=m;if(w<m){p=w;var y=c,_=w;c=d,w=m,d=y,m=_}var f=p;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<p;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,w=c.length,m=d.length,p=m;w<m&&(p=w);var y=w;g===null?g=new C(y,!1):y=g.length;for(var _=0;_<p;_++)g.__setDigit(_,c.__digit(_)&~d.__digit(_));for(;_<w;_++)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,w=c.length,m=d.length,p=m;if(w<m){p=w;var y=c,_=w;c=d,w=m,d=y,m=_}var f=w;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<p;k++)g.__setDigit(k,c.__digit(k)|d.__digit(k));for(;k<w;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,w=c.length,m=d.length,p=m;if(w<m){p=w;var y=c,_=w;c=d,w=m,d=y,m=_}var f=w;g===null?g=new C(f,!1):f=g.length;for(var k=0;k<p;k++)g.__setDigit(k,c.__digit(k)^d.__digit(k));for(;k<w;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 w=c.length-1;0<=w&&c.__digit(w)===d.__digit(w);)w--;return 0>w?0:c.__unsignedDigit(w)>d.__unsignedDigit(w)?1:-1}},{key:"__multiplyAccumulate",value:function(c,d,g,w){if(d!==0){for(var m=32767&d,p=d>>>15,y=0,_=0,f=0;f<c.length;f++,w++){var k=g.__digit(w),M=c.__digit(f),j=32767&M,L=M>>>15,R=C.__imul(j,m),W=C.__imul(j,p),ne=C.__imul(L,m),pe=C.__imul(L,p);k+=_+R+y,y=k>>>30,k&=1073741823,k+=((32767&W)<<15)+((32767&ne)<<15),y+=k>>>30,_=pe+(W>>>15)+(ne>>>15),g.__setDigit(w,1073741823&k)}for(;y!==0||_!==0;w++){var ue=g.__digit(w);ue+=y+_,_=0,y=ue>>>30,g.__setDigit(w,1073741823&ue)}}}},{key:"__internalMultiplyAdd",value:function(c,d,g,w,m){for(var p=g,y=0,_=0;_<w;_++){var f=c.__digit(_),k=C.__imul(32767&f,d),M=C.__imul(f>>>15,d),j=k+((32767&M)<<15)+y+p;p=j>>>30,y=M>>>15,m.__setDigit(_,1073741823&j)}if(m.length>w)for(m.__setDigit(w++,p+y);w<m.length;)m.__setDigit(w++,0);else if(p+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 w=0,m=2*c.length-1;0<=m;m-=2){var p=(w<<15|c.__halfDigit(m))>>>0,y=0|p/d;w=0|p%d,p=(w<<15|c.__halfDigit(m-1))>>>0;var _=0|p/d;w=0|p%d,g.__setDigit(m>>>1,y<<15|_)}return g}},{key:"__absoluteModSmall",value:function(c,d){for(var g,w=0,m=2*c.length-1;0<=m;m--)g=(w<<15|c.__halfDigit(m))>>>0,w=0|g%d;return w}},{key:"__absoluteDivLarge",value:function(c,d,g,w){var m=d.__halfDigitLength(),p=d.length,y=c.__halfDigitLength()-m,_=null;g&&(_=new C(y+2>>>1,!1),_.__initializeDigits());var f=new C(m+2>>>1,!1);f.__initializeDigits();var k=C.__clz15(d.__halfDigit(m-1));0<k&&(d=C.__specialLeftShift(d,k,0));for(var M=C.__specialLeftShift(c,k,1),j=d.__halfDigit(m-1),L=0,R=y;0<=R;R--){var W=32767,ne=M.__halfDigit(R+m);if(ne!==j){var pe=(ne<<15|M.__halfDigit(R+m-1))>>>0;W=0|pe/j;for(var ue=0|pe%j,me=d.__halfDigit(m-2),vt=M.__halfDigit(R+m-2);C.__imul(W,me)>>>0>(ue<<16|vt)>>>0&&(W--,ue+=j,!(32767<ue)););}C.__internalMultiplyAdd(d,W,0,p,f);var De=M.__inplaceSub(f,R,m+1);De!==0&&(De=M.__inplaceAdd(d,R,m),M.__setHalfDigit(R+m,32767&M.__halfDigit(R+m)+De),W--),g&&(1&R?L=W<<15:_.__setDigit(R>>>1,L|W))}if(w)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 w=c.length,m=new C(w+g,!1);if(d===0){for(var p=0;p<w;p++)m.__setDigit(p,c.__digit(p));return 0<g&&m.__setDigit(w,0),m}for(var y,_=0,f=0;f<w;f++)y=c.__digit(f),m.__setDigit(f,1073741823&y<<d|_),_=y>>>30-d;return 0<g&&m.__setDigit(w,_),m}},{key:"__leftShiftByAbsolute",value:function(c,d){var g=C.__toShiftAmount(d);if(0>g)throw new RangeError("BigInt too big");var w=0|g/30,m=g%30,p=c.length,y=m!==0&&c.__digit(p-1)>>>30-m!=0,_=p+w+(y?1:0),f=new C(_,c.sign);if(m===0){for(var k=0;k<w;k++)f.__setDigit(k,0);for(;k<_;k++)f.__setDigit(k,c.__digit(k-w))}else{for(var M=0,j=0;j<w;j++)f.__setDigit(j,0);for(var L,R=0;R<p;R++)L=c.__digit(R),f.__setDigit(R+w,1073741823&L<<m|M),M=L>>>30-m;if(y)f.__setDigit(p+w,M);else if(M!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(c,d){var g=c.length,w=c.sign,m=C.__toShiftAmount(d);if(0>m)return C.__rightShiftByMaximum(w);var p=0|m/30,y=m%30,_=g-p;if(0>=_)return C.__rightShiftByMaximum(w);var f=!1;if(w){if(c.__digit(p)&(1<<y)-1)f=!0;else for(var k=0;k<p;k++)if(c.__digit(k)!==0){f=!0;break}}if(f&&y===0){var M=c.__digit(g-1);!~M&&_++}var j=new C(_,w);if(y===0){j.__setDigit(_-1,0);for(var L=p;L<g;L++)j.__setDigit(L-p,c.__digit(L))}else{for(var R,W=c.__digit(p)>>>y,ne=g-p-1,pe=0;pe<ne;pe++)R=c.__digit(pe+p+1),j.__setDigit(pe,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 w=g(d);if(n(w)!=="object")return w;throw new TypeError("Cannot convert object to primitive value")}}var m=c.valueOf;if(m){var p=m.call(c);if(n(p)!=="object")return p}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,w=new C(g,d.sign),m=g-1,p=0;p<m;p++)w.__setDigit(p,d.__digit(p));var y=d.__digit(m);if(c%30!=0){var _=32-c%30;y=y<<_>>>_}return w.__setDigit(m,y),w.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(c,d,g){for(var w=Math.min,m,p=0|(c+29)/30,y=new C(p,g),_=0,f=p-1,k=0,M=w(f,d.length);_<M;_++)m=0-d.__digit(_)-k,k=1&m>>>30,y.__setDigit(_,1073741823&m);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 bk={};ml(bk,{AddressBookSDK:()=>Ki,COIN_TYPE_ARG_REGEX:()=>Ku,Coin:()=>Do,CoinHelper:()=>Po,CreateHelper:()=>Ui,DEV_API_URL:()=>Mg,DEV_SYNCING_URL:()=>Bg,ENV_CONFIGS:()=>Fg,Formatter:()=>$n,HexToUint8Array:()=>fa,LOCAL_API_URL:()=>Yu,LOCAL_SYNCING_URL:()=>Qu,MAINNET_RPC_URL:()=>Ju,MSafeAccount:()=>Li,MSafeClient:()=>ka,MSafeEnv:()=>Eg,MSafeGlobals:()=>Bo,PREV_API_URL:()=>jg,PROD_API_URL:()=>Ng,SUI_COIN:()=>gk,SignatureVerifier:()=>Vu,TESTNET_RPC_URL:()=>va,Uint8ArrayToHex:()=>mk,addPrefix:()=>zu,getAllCoins:()=>yk,getMSafeConfig:()=>el,getPublicKeyFromChain:()=>Gu,stringToBuffer:()=>da});module.exports=_l(bk);var On=require("@msafe/sui3-utils"),Ui=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 On.MultiSigAccount(n).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,n){let i=On.PublicKeySerde.de(n);if(!(0,On.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=On.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,...On.PublicKeySerde.ser(i[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:n})}};var Ta=require("@msafe/sui3-utils");var yl=require("@msafe/sui3-utils"),Ki=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let n=yl.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 Fo=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 bp=require("@msafe/sui3-utils"),wp=require("@msafe/sui3-utils"),vp=ge(Ro(),1);var Br=require("@mysten/sui.js/utils"),Ji=require("@mysten/sui.js/transactions"),tn=ge(ke(),1);var Ga=8192;function Wa(t){if(t.length<Ga)return btoa(String.fromCharCode(...t));let e="";for(var n=0;n<t.length;n+=Ga){let i=t.slice(n,n+Ga);e+=String.fromCharCode(...i)}return btoa(e)}var y0=require("@mysten/sui.js/keypairs/ed25519"),b0=require("@mysten/sui.js/keypairs/secp256k1"),Gn=ge(ke(),1),bt=ge(ke(),1);var zi=9e15,Vn=1e9,Ha="0123456789abcdef",Lo="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",$o="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Za={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-zi,maxE:zi,crypto:!1},Bl,Pn,fe=!0,Ko="[DecimalError] ",zn=Ko+"Invalid argument: ",jl=Ko+"Precision limit exceeded",Nl=Ko+"crypto unavailable",Fl="[object Decimal]",jt=Math.floor,kt=Math.pow,n_=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,i_=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,r_=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Rl=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,ln=1e7,le=7,o_=9007199254740991,s_=Lo.length-1,Xa=$o.length-1,z={toStringTag:Fl};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(zn+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=a_(i,Kl(i,n)),i.precision=t,i.rounding=e,oe(Pn==2||Pn==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,b=h.constructor;if(!h.isFinite()||h.isZero())return new b(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 b(n),i.s=h.s):i=new b(o.toString()),s=(t=b.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,b.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/Vo(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=Vi(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=Vi(o,2,r,r,!0);else{t=1.4*Math.sqrt(i),t=t>16?16:t|0,r=r.times(1/Vo(5,t)),r=Vi(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()?un(n,r,o):new n(0):new n(NaN):e.isZero()?un(n,r+4,o).times(.5):(n.precision=r+6,n.rounding=1,e=e.asin(),t=un(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=un(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,b=h.precision,v=h.rounding;if(l.isFinite()){if(l.isZero())return new h(l);if(l.abs().eq(1)&&b+4<=Xa)return s=un(h,b+4,v).times(.25),s.s=l.s,s}else{if(!l.s)return new h(NaN);if(b+4<=Xa)return s=un(h,b+4,v).times(.5),s.s=l.s,s}for(h.precision=a=b+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=b,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,b=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=b+T,s=Kn(l,a),i=e?Uo(h,a+10):Kn(t,a),u=Ee(s,i,a,1),Dr(u.d,r=b,v))do if(a+=10,s=Kn(l,a),i=e?Uo(h,a+10):Kn(t,a),u=Ee(s,i,a,1),!o){+xt(u.d).slice(r+1,r+15)+1==1e14&&(u=oe(u,b+1,0));break}while(Dr(u.d,r+=10,v));return fe=!0,oe(u,b,v)};z.minus=z.sub=function(t){var e,n,i,r,o,s,a,u,l,h,b,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(b=o<0,b?(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,b=i<s,b&&(s=i),i=0;i<s;i++)if(l[i]!=v[i]){b=l[i]<v[i];break}o=0}for(b&&(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]=ln-1;--l[r],l[i]+=ln}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=zo(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 Ja(this)};z.naturalLogarithm=z.ln=function(){return Kn(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,b=this,v=b.constructor;if(t=new v(t),!b.d||!t.d)return!b.s||!t.s?t=new v(NaN):b.d||(t=new v(t.d||b.s===t.s?b:NaN)),t;if(b.s!=t.s)return t.s=-t.s,b.minus(t);if(l=b.d,h=t.d,a=v.precision,u=v.rounding,!l[0]||!h[0])return h[0]||(t=new v(b)),fe?oe(t,a,u):t;if(o=jt(b.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)/ln|0,l[r]%=ln;for(e&&(l.unshift(e),++i),s=l.length;l[--s]==0;)l.pop();return t.d=l,t.e=zo(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(zn+t);return n.d?(e=ql(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=u_(i,Kl(i,n)),i.precision=t,i.rounding=e,oe(Pn>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(Pn==2||Pn==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,b=h.constructor,v=h.d,T=(t=new b(t)).d;if(t.s*=h.s,!v||!v[0]||!T||!T[0])return new b(!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%ln|0,e=a/ln|0;o[r]=(o[r]+e)%ln|0}for(;!o[--s];)o.pop();return e?++n:o.shift(),t.d=o,t.e=zo(o,n),fe?oe(t,b.precision,b.rounding):t};z.toBinary=function(t,e){return Qa(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:($t(t,0,Vn),e===void 0?e=i.rounding:$t(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=vn(i,!0):($t(t,0,Vn),e===void 0?e=r.rounding:$t(e,0,8),i=oe(new r(i),t+1,e),n=vn(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=vn(r):($t(t,0,Vn),e===void 0?e=o.rounding:$t(e,0,8),i=oe(new o(r),t+r.e+1,e),n=vn(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,b,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=ql(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(zn+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;b=Ee(a,e,0,1,1),r=n.plus(b.times(i)),r.cmp(t)!=1;)n=i,i=r,r=l,l=u.plus(b.times(r)),u=r,r=e,e=a.minus(b.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 Qa(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:$t(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 Qa(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)<=o_)return r=Ll(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=Ja(t.times(Kn(a,i+n)),i),r.d&&(r=oe(r,i+5,1),Dr(r.d,i,o)&&(e=i+10,r=oe(Ja(t.times(Kn(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=vn(i,i.e<=r.toExpNeg||i.e>=r.toExpPos):($t(t,1,Vn),e===void 0?e=r.rounding:$t(e,0,8),i=oe(new r(i),t,e),n=vn(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):($t(t,1,Vn),e===void 0?e=i.rounding:$t(e,0,8)),oe(new i(n),t,e)};z.toString=function(){var t=this,e=t.constructor,n=vn(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=vn(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+=Un(n)),o+=i;s=t[e],i=s+"",n=le-i.length,n&&(o+=Un(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function $t(t,e,n){if(t!==~~t||t<e||t>n)throw Error(zn+t)}function Dr(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 qo(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]+=Ha.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 a_(t,e){var n,i,r;if(e.isZero())return e;i=e.d.length,i<32?(n=Math.ceil(i/3),r=(1/Vo(4,n)).toString()):(n=16,r="2.3283064365386962890625e-10"),t.precision+=n,e=Vi(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,b,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=ln,T=le,h=jt(i.e/T)-jt(r.e/T)),K=g.length,V=d.length,O=new A(c),E=O.d=[],b=0;g[b]==(d[b]||0);b++);if(g[b]>(d[b]||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,b=0,K==1){for(v=0,g=g[0],H++;(b<V||v)&&H--;b++)te=v*u+(d[b]||0),E[b]=te/g|0,v=te%g|0;I=v||b<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[b++]=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,Bl=I;else{for(b=1,v=E[0];v>=10;v/=10)b++;O.e=b+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,b,v,T=t.constructor;e:if(e!=null){if(b=t.d,!b)return t;for(r=1,a=b[0];a>=10;a/=10)r++;if(o=e-r,o<0)o+=le,s=e,h=b[v=0],u=h/kt(10,r-s-1)%10|0;else if(v=Math.ceil((o+1)/le),a=b.length,v>=a)if(i){for(;a++<=v;)b.push(0);h=u=0,r=1,o%=le,s=o-le+1}else break e;else{for(h=a=b[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||b[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:b[v-1])%10&1||n==(t.s<0?8:7)),e<1||!b[0])return b.length=0,l?(e-=t.e+1,b[0]=kt(10,(le-e%le)%le),t.e=-e||0):b[0]=t.e=0,t;if(o==0?(b.length=v,a=1,v--):(b.length=v+1,a=kt(10,le-o),b[v]=s>0?(h/kt(10,r-s)%kt(10,s)|0)*a:0),l)for(;;)if(v==0){for(o=1,s=b[0];s>=10;s/=10)o++;for(s=b[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(t.e++,b[0]==ln&&(b[0]=1));break}else{if(b[v]+=a,b[v]!=ln)break;b[v--]=0,a=1}for(o=b.length;b[--o]===0;)b.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 vn(t,e,n){if(!t.isFinite())return Ul(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)+Un(i):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):r<0?(o="0."+Un(-r-1)+o,n&&(i=n-s)>0&&(o+=Un(i))):r>=s?(o+=Un(r+1-s),n&&(i=n-r-1)>0&&(o=o+"."+Un(i))):((i=r+1)<s&&(o=o.slice(0,i)+"."+o.slice(i)),n&&(i=n-s)>0&&(r+1===s&&(o+="."),o+=Un(i))),o}function zo(t,e){var n=t[0];for(e*=le;n>=10;n/=10)e++;return e}function Uo(t,e,n){if(e>s_)throw fe=!0,n&&(t.precision=n),Error(jl);return oe(new t(Lo),e,1,!0)}function un(t,e,n){if(e>Xa)throw Error(jl);return oe(new t($o),e,n,!0)}function ql(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 Un(t){for(var e="";t--;)e+="0";return e}function Ll(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),El(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),El(e.d,s)}return fe=!0,o}function Dl(t){return t.d[t.d.length-1]&1}function $l(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 Ja(t,e){var n,i,r,o,s,a,u,l=0,h=0,b=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),b+=5;for(i=Math.log(kt(2,b))/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=b;r--;)s=oe(s.times(s),u,1);if(e==null)if(l<3&&Dr(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 Kn(t,e){var n,i,r,o,s,a,u,l,h,b,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=Uo(O,h+2,B).times(o+""),x=Kn(new O(i+"."+n.slice(1)),h-I).plus(l),O.precision=B,e==null?oe(x,B,E,fe=!0):x;for(b=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(Uo(O,h+2,B).times(o+""))),u=Ee(u,new O(T),h,1),e==null)if(Dr(u.d,h-I,E,a))O.precision=h+=I,l=s=x=Ee(b.minus(1),b.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 Ul(t){return String(t.s*t.s/0)}function Ya(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 c_(t,e){var n,i,r,o,s,a,u,l,h;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Rl.test(e))return Ya(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(i_.test(e))n=16,e=e.toLowerCase();else if(n_.test(e))n=2;else if(r_.test(e))n=8;else throw Error(zn+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=Ll(i,new i(n),o,o*2)),l=qo(e,n,ln),h=l.length-1,o=h;l[o]===0;--o)l.pop();return o<0?new i(t.s*0):(t.e=zo(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):Er.pow(2,u))),fe=!0,t)}function u_(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Vi(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/Vo(5,n)),e=Vi(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 Vi(t,e,n,i,r){var o,s,a,u,l=1,h=t.precision,b=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[b]!==void 0){for(o=b;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=b+1,s}function Vo(t,e){for(var n=t;--e;)n*=t;return n}function Kl(t,e){var n,i=e.s<0,r=un(t,t.precision,1),o=r.times(.5);if(e=e.abs(),e.lte(o))return Pn=i?4:1,e;if(n=e.divToInt(r),n.isZero())Pn=i?3:2;else{if(e=e.minus(n.times(r)),e.lte(o))return Pn=Dl(n)?i?2:3:i?4:1,e;Pn=Dl(n)?i?1:4:i?3:2}return e.minus(r).abs()}function Qa(t,e,n,i){var r,o,s,a,u,l,h,b,v,T=t.constructor,I=n!==void 0;if(I?($t(n,1,Vn),i===void 0?i=T.rounding:$t(i,0,8)):(n=T.precision,i=T.rounding),!t.isFinite())h=Ul(t);else{for(h=vn(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=qo(vn(v),10,r),v.e=v.d.length),b=qo(h,10,r),o=u=b.length;b[--u]==0;)b.pop();if(!b[0])h=I?"0p+0":"0";else{if(s<0?o--:(t=new T(t),t.d=b,t.e=o,t=Ee(t,v,n,i,0,r),b=t.d,o=t.e,l=Bl),s=b[n],a=r/2,l=l||b[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&&b[n-1]&1||i===(t.s<0?8:7)),b.length=n,l)for(;++b[--n]>r-1;)b[n]=0,n||(++o,b.unshift(1));for(u=b.length;!b[u-1];--u);for(s=0,h="";s<u;s++)h+=Ha.charAt(b[s]);if(I){if(u>1)if(e==16||e==8){for(s=e==16?4:3,--u;u%s;u++)h+="0";for(b=qo(h,r,e),u=b.length;!b[u-1];--u);for(s=1,h="1.";s<u;s++)h+=Ha.charAt(b[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 El(t,e){if(t.length>e)return t.length=e,!0}function l_(t){return new this(t).abs()}function d_(t){return new this(t).acos()}function f_(t){return new this(t).acosh()}function h_(t,e){return new this(t).plus(e)}function p_(t){return new this(t).asin()}function m_(t){return new this(t).asinh()}function g_(t){return new this(t).atan()}function __(t){return new this(t).atanh()}function y_(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=un(this,o,1).times(e.s>0?.25:.75),n.s=t.s):!e.d||t.isZero()?(n=e.s<0?un(this,i,r):new this(0),n.s=t.s):!t.d||e.isZero()?(n=un(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=un(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 b_(t){return new this(t).cbrt()}function w_(t){return oe(t=new this(t),t.e+1,2)}function v_(t,e,n){return new this(t).clamp(e,n)}function k_(t){if(!t||typeof t!="object")throw Error(Ko+"Object expected");var e,n,i,r=t.defaults===!0,o=["precision",1,Vn,"rounding",0,8,"toExpNeg",-zi,0,"toExpPos",0,zi,"maxE",0,zi,"minE",-zi,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(n=o[e],r&&(this[n]=Za[n]),(i=t[n])!==void 0)if(jt(i)===i&&i>=o[e+1]&&i<=o[e+2])this[n]=i;else throw Error(zn+n+": "+i);if(n="crypto",r&&(this[n]=Za[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(Nl);else this[n]=!1;else throw Error(zn+n+": "+i);return this}function T_(t){return new this(t).cos()}function C_(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,Ml(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 Ya(l,o.toString())}else if(u!=="string")throw Error(zn+o);return(a=o.charCodeAt(0))===45?(o=o.slice(1),l.s=-1):(a===43&&(o=o.slice(1)),l.s=1),Rl.test(o)?Ya(l,o):c_(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=k_,r.clone=zl,r.isDecimal=Ml,r.abs=l_,r.acos=d_,r.acosh=f_,r.add=h_,r.asin=p_,r.asinh=m_,r.atan=g_,r.atanh=__,r.atan2=y_,r.cbrt=b_,r.ceil=w_,r.clamp=v_,r.cos=T_,r.cosh=C_,r.div=S_,r.exp=A_,r.floor=x_,r.hypot=I_,r.ln=O_,r.log=P_,r.log10=E_,r.log2=D_,r.max=M_,r.min=B_,r.mod=j_,r.mul=N_,r.pow=F_,r.random=R_,r.round=q_,r.sign=L_,r.sin=$_,r.sinh=U_,r.sqrt=K_,r.sub=z_,r.sum=V_,r.tan=G_,r.tanh=W_,r.trunc=H_,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 S_(t,e){return new this(t).div(e)}function A_(t){return new this(t).exp()}function x_(t){return oe(t=new this(t),t.e+1,3)}function I_(){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 Ml(t){return t instanceof Er||t&&t.toStringTag===Fl||!1}function O_(t){return new this(t).ln()}function P_(t,e){return new this(t).log(e)}function D_(t){return new this(t).log(2)}function E_(t){return new this(t).log(10)}function M_(){return $l(this,arguments,"lt")}function B_(){return $l(this,arguments,"gt")}function j_(t,e){return new this(t).mod(e)}function N_(t,e){return new this(t).mul(e)}function F_(t,e){return new this(t).pow(e)}function R_(t){var e,n,i,r,o=0,s=new this(1),a=[];if(t===void 0?t=this.precision:$t(t,1,Vn),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(Nl);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 q_(t){return oe(t=new this(t),t.e+1,this.rounding)}function L_(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function $_(t){return new this(t).sin()}function U_(t){return new this(t).sinh()}function K_(t){return new this(t).sqrt()}function z_(t,e){return new this(t).sub(e)}function V_(){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 G_(t){return new this(t).tan()}function W_(t){return new this(t).tanh()}function H_(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 Er=z.constructor=zl(Za);Lo=new Er(Lo);$o=new Er($o);var N=Er;var $d=ge(ke(),1),Nr=ge(ke(),1);var ce=ge(ke(),1),Ie=ge(ke(),1),zd=ge(ke(),1),ds=require("@mysten/sui.js/utils"),W0=ge(ke(),1),fc=ge(ke(),1),H0=ge(ke(),1);var mi=ge(ke(),1),jr=ge(ke(),1);var gi=require("@mysten/sui.js/transactions"),ry=require("@mysten/sui.js/utils"),oy=require("@mysten/sui.js/transactions"),Pt=ge(ke(),1),is=require("@mysten/sui.js/transactions"),pc=ge(ke(),1),_i=require("@mysten/sui.js/transactions"),Qd=require("@mysten/sui.js/utils"),Me=ge(ke(),1),rs=require("@mysten/sui.js/transactions"),Wt=ge(ke(),1),bi=ge(gd(),1),ef=require("@mysten/sui.js/transactions"),yi=ge(ke(),1);var mc=require("@mysten/sui.js/transactions");var kd="3.7.7",n0=kd,Hi=typeof Buffer=="function",_d=typeof TextDecoder=="function"?new TextDecoder:void 0,yd=typeof TextEncoder=="function"?new TextEncoder:void 0,i0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Mr=Array.prototype.slice.call(i0),Xo=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(Mr),r0=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,It=String.fromCharCode.bind(String),bd=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),Td=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Cd=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Sd=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+=Mr[e>>18&63]+Mr[e>>12&63]+Mr[e>>6&63]+Mr[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},rc=typeof btoa=="function"?t=>btoa(t):Hi?t=>Buffer.from(t,"binary").toString("base64"):Sd,nc=Hi?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 rc(n.join(""))},Jo=(t,e=!1)=>e?Td(nc(t)):nc(t),o0=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)}},s0=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Ad=t=>t.replace(s0,o0),wd=Hi?t=>Buffer.from(t,"utf8").toString("base64"):yd?t=>nc(yd.encode(t)):t=>rc(Ad(t)),Wi=(t,e=!1)=>e?Td(wd(t)):wd(t),vd=t=>Wi(t,!0),a0=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,c0=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))}},xd=t=>t.replace(a0,c0),Id=t=>{if(t=t.replace(/\s+/g,""),!r0.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=Xo[t.charAt(o++)]<<18|Xo[t.charAt(o++)]<<12|(i=Xo[t.charAt(o++)])<<6|(r=Xo[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},oc=typeof atob=="function"?t=>atob(Cd(t)):Hi?t=>Buffer.from(t,"base64").toString("binary"):Id,Od=Hi?t=>bd(Buffer.from(t,"base64")):t=>bd(oc(t).split("").map(e=>e.charCodeAt(0))),Pd=t=>Od(Dd(t)),u0=Hi?t=>Buffer.from(t,"base64").toString("utf8"):_d?t=>_d.decode(Od(t)):t=>xd(oc(t)),Dd=t=>Cd(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),ic=t=>u0(Dd(t)),l0=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)},Ed=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Md=function(){let t=(e,n)=>Object.defineProperty(String.prototype,e,Ed(n));t("fromBase64",function(){return ic(this)}),t("toBase64",function(e){return Wi(this,e)}),t("toBase64URI",function(){return Wi(this,!0)}),t("toBase64URL",function(){return Wi(this,!0)}),t("toUint8Array",function(){return Pd(this)})},Bd=function(){let t=(e,n)=>Object.defineProperty(Uint8Array.prototype,e,Ed(n));t("toBase64",function(e){return Jo(this,e)}),t("toBase64URI",function(){return Jo(this,!0)}),t("toBase64URL",function(){return Jo(this,!0)})},d0=()=>{Md(),Bd()},Zi={version:kd,VERSION:n0,atob:oc,atobPolyfill:Id,btoa:rc,btoaPolyfill:Sd,fromBase64:ic,toBase64:Wi,encode:Wi,encodeURI:vd,encodeURL:vd,utob:Ad,btou:xd,decode:ic,isValid:l0,fromUint8Array:Jo,toUint8Array:Pd,extendString:Md,extendUint8Array:Bd,extendBuiltins:d0};var gc=require("@mysten/sui.js/transactions"),tf=require("@mysten/sui.js/utils"),dn=ge(ke(),1);var Yo,f0=new Uint8Array(16);function sc(){if(!Yo&&(Yo=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Yo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Yo(f0)}var Ot=[];for(let t=0;t<256;++t)Ot.push((t+256).toString(16).slice(1));function jd(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 h0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ac={randomUUID:h0};function p0(t,e,n){if(ac.randomUUID&&!e&&!t)return ac.randomUUID();t=t||{};let i=t.random||(t.rng||sc)();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 jd(i)}var Qo=p0;var os=require("@mysten/sui.js/utils"),nf=require("@mysten/sui.js/transactions"),rf=require("@mysten/sui.js/client"),of=require("@mysten/sui.js/bcs");var m0=Object.defineProperty,g0=(t,e,n)=>e in t?m0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_0=(t,e,n)=>(g0(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 bt.default(0),kn=new bt.default(1),cs=new bt.default(2),Xk=cs.pow(new bt.default(128)),er=cs.pow(new bt.default(64)).sub(kn),w0=cs.pow(new bt.default(128)).sub(kn),Te=class{static toX64_BN(t){return t.mul(new bt.default(2).pow(new bt.default(64)))}static toX64_Decimal(t){return t.mul(Dt.pow(2,64))}static toX64(t){return new bt.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 bt.default(2).pow(new bt.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(er).gt(ie)&&(e=e.add(kn)),e}static divRoundUp(t,e){return t.mod(e).eq(ie)?t.div(e):t.div(e).add(new bt.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(w0):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(kn)).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 bt.default(2).pow(new bt.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(er).gt(ie)?r.shrn(64).add(kn):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(cs.pow(new bt.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 bt.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 bt.default(1)))}static neg_from(t){return t.eq(ie)?t:this.u128_neg(t).add(new bt.default(1)).or(new bt.default(1).shln(127))}};function v0(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new Gn.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new Gn.default(t.fee_growth_global_a),feeGrowthGlobalB:new Gn.default(t.fee_growth_global_b),feeProtocolCoinA:new Gn.default(t.fee_protocol_coin_a),feeProtocolCoinB:new Gn.default(t.fee_protocol_coin_b),feeRate:new Gn.default(t.fee_rate),liquidity:new Gn.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var Ud=443636,Kd=-443636,us="79226673515401279992447579055";var ls="4295048016",Yi=new $d.default(1e6),G="0x0000000000000000000000000000000000000000000000000000000000000006",k0="partner",Qi="pool_script",Dn="pool_script_v2",Wn="router",cc="router_with_partner",Ut="fetcher_script",T0="expect_swap",Nd="utils";var uc="custodian_v2",C0="clob_v2",S0="endpoints_v2";var _c=(t=>(t.Deleted="Deleted",t.Exists="Exists",t.NotExists="NotExists",t))(_c||{});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 A0=14,x0="59543866431248",I0="184467440737095516",O0="15793534762490258745",P0=443636;function D0(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 E0(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 M0(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(E0(t)):new ce.default(M0(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ce.default(us))||t.lt(new ce.default(ls)))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=D0(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<A0;){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(x0)),b=_e(h.sub(new ce.default(I0)),64,128).toNumber(),v=_e(h.add(new ce.default(O0)),64,128).toNumber();return b===v?b:ee.tickIndexToSqrtPriceX64(v).lte(t)?v:b}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(P0))}var Yk=new Nr.default(365),Qk=new Nr.default(24),eT=new Nr.default(3600),tT=new Nr.default(.5);var fn=class{static getDefaultSqrtPriceLimit(t){return new zd.default(t?ls:us)}static getDefaultOtherAmountThreshold(t){return t?ie:er}};function Vd(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(ls)))throw new J("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(a.gt(new Ie.default(us)))throw new J("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return a}function Gd(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(ls))||o.gt(new Ie.default(us)))throw new J("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function j0(t,e,n,i){return i?Vd(t,e,n,!0):Gd(t,e,n,!0)}function N0(t,e,n,i){return i?Gd(t,e,n,!1):Vd(t,e,n,!1)}function Fd(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(kn)}else{let s=new Ie.default(n).mul(new Ie.default(r));o=s.and(er).gt(ie)?s.shrn(64).add(kn):s.shrn(64)}return o}function Rd(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 F0(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 b=Te.checkMulDivFloor(i,Te.checkUnsignedSub(Yi,r),Yi,64),v=Fd(t,e,n,s);v.gt(b)?(a=b,h=Te.checkUnsignedSub(i,b),l=j0(t,n,b,s)):(a=v,h=Te.checkMulDivCeil(a,r,Yi.sub(r),64),l=e),u=Rd(t,l,n,s)}else{let b=Rd(t,e,n,s);b.gt(i)?(u=i,l=N0(t,n,i,s)):(u=b,l=e),a=Fd(t,l,n,s),h=Te.checkMulDivCeil(a,r,Yi.sub(r),64)}return{amountIn:a,amountOut:u,nextSqrtPrice:l,feeAmount:h}}function R0(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,b=fn.getDefaultSqrtPriceLimit(t);for(let v of r){if(t&&i.currentTickIndex<v.index||!t&&i.currentTickIndex>=v.index||v===null)continue;t&&b.gt(v.sqrtPrice)||!t&&b.lt(v.sqrtPrice)?l=b:l=v.sqrtPrice;let T=F0(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 es(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 ts(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),Yi,64),s=n===0?ie:Te.checkMulDivFloor(e,new Ie.default(n),Yi,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=es(u,l,n)}else if(a>e){if(i)throw new J("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");h=ts(l,u,n)}else i?h=es(s,l,n):h=ts(s,u,n);let b=$e.getCoinAmountFromLiquidity(h,s,u,l,r),v=r?S(b.coinA.toString()).mul(1+o).toString():S(b.coinA.toString()).mul(1-o).toString(),T=r?S(b.coinB.toString()).mul(1+o).toString():S(b.coinB.toString()).mul(1-o).toString();return{coinAmountA:b.coinA,coinAmountB:b.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 es(o,s,i.coinA);if(r>=n)return ts(s,o,i.coinB);let a=es(t,s,i.coinA),u=ts(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 yc(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var q0=0,Wd=1,L0=2;function qd(t,e){return t===e?q0:t<e?Wd:L0}function $0(t,e){let n=0,i=t.length<=e.length?t.length:e.length,r=qd(t.length,e.length);for(;n<i;){let o=qd(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,o!==0)return o}return r}function ss(t,e){return $0(t,e)===Wd}function tr(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=>be.isSuiCoin(l)?l:q(l).source_address),u.source_address=tr(u.full_address,u.type_arguments),u}let r=e.split("::"),s={full_address:e,address:e===Fr||e===G0?"0x2":(0,ds.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=tr(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 U0(t){return t.toLowerCase().startsWith("0x")?(0,ds.normalizeSuiObjectId)(t):t}var K0=(t,e=!0)=>{let n=t.split("::"),i=n.shift(),r=(0,ds.normalizeSuiObjectId)(i);return e&&(r=yc(r)),`${r}::${n.join("::")}`};function fs(t){for(let e in t){let n=typeof t[e];if(n==="object")fs(t[e]);else if(n==="string"){let i=t[e];i&&!i.includes("::")&&(t[e]=U0(i))}}}var z0="0x2::coin::Coin",V0=/^0x2::coin::Coin<(.+)>$/;var Fr="0x2::sui::SUI",G0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var be=class{static getCoinTypeArg(t){let e=t.type.match(V0);return e?e[1]:null}static isSUI(t){let e=be.getCoinTypeArg(t);return e?be.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`${z0}<${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===Fr}static selectCoinObjectIdGreaterThanOrEqual(t,e,n=[]){let i=be.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=be.sortByBalance(t.filter(u=>!n.includes(u.coinObjectId))),r=be.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(b=>b.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:be.sortByBalance(s),remainingCoins:be.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 nr=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return nr.fromFraction(t.toDecimalPlaces(1).mul(10).toNumber(),1e3)}static fromFraction(t,e){let n=typeof t=="number"?new fc.default(t.toString()):t,i=typeof e=="number"?new fc.default(e.toString()):e;return new nr(n,i)}};function hc(t,{numerator:e,denominator:n},i){return i?t.mul(n.add(e)).div(n):t.mul(n).div(n.add(e))}function hs(t,e,n){return{tokenMaxA:hc(t.coinA,e,n),tokenMaxB:hc(t.coinB,e,n)}}function S(t){return N.isDecimal(t)?t:new N(t===void 0?0:t)}function Z0(t){return S(10).pow(S(t).abs())}function Rr(t){return t.data}function Hd(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 Zd(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function X0(t){if("reference"in t)return t.reference;let e=Rr(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Hd(t)}function qt(t){return"objectId"in t?t.objectId:X0(t)?.objectId??Zd(t)}function J0(t){return t.data!==void 0}function Y0(t){return t.content!==void 0}function Xd(t){let e="data"in t?Rr(t):t;if(!(!e||!Y0(e)||e.content.dataType!=="moveObject"))return e.content}function Mt(t){return Xd(t)?.type}function hn(t){let e=J0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":Mt(t):e?.type}function wi(t){return Rr(t)?.previousTransaction}function ir(t){return Rr(t)?.owner}function Q0(t){let e=Rr(t)?.display;return e||{data:null,error:null}}function Q(t){let e=Xd(t)?.fields;if(e)return"fields"in e?e.fields:e}function Jd(t,e){let n=Z0(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 ey(t,e,n){let i=q(t).name,r=q(e).name;return`${i}-${r}[${n}]`}function lc(t){let e=Mt(t),n=q(e),i=Q(t);if(i==null)throw new J(`Pool id ${qt(t)} not exists.`,"InvalidPoolObject");let r=[];i.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:a}=s.fields,u=Te.fromX64(new tn.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:qt(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=ey(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function vi(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 En(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=ir(t);"nft"in i?(i=i.nft.fields,e.description=i.description,e.name=i.name,e.link=i.url):e=vi(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=Hd(t);r&&(n.pos_object_id=r.objectId,n.position_status="Deleted");let o=Zd(t);return o&&(n.pos_object_id=o,n.position_status="NotExists"),n}function Yd(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 dc(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:qt(t),index:Re(BigInt(n.index.fields.bits)),sqrtPrice:new tn.default(n.sqrt_price),liquidityNet:new tn.default(n.liquidity_net.fields.bits),liquidityGross:new tn.default(n.liquidity_gross),feeGrowthOutsideA:new tn.default(n.fee_growth_outside_a),feeGrowthOutsideB:new tn.default(n.fee_growth_outside_b),rewardersGrowthOutside:n.rewards_growth_outside}}function ty(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 tn.default(t.sqrt_price),i=new tn.default(t.liquidity_net.bits),r=new tn.default(t.liquidity_gross),o=new tn.default(t.fee_growth_outside_a),s=new tn.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 ny(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 mi.default(e.rewardersGrowthOutside[u])):l=e.rewardersGrowthOutside[u]);let h=new mi.default(0);n!==null&&(t.current_tick_index>=r?h=o[u].sub(new mi.default(n.rewardersGrowthOutside[u])):h=n.rewardersGrowthOutside[u]);let b=Te.subUnderflowU128(Te.subUnderflowU128(new mi.default(o[u]),new mi.default(l)),new mi.default(h));a.push(b)}return a}function as(t){let e=be.isSuiCoin(t.coinTypeA),n=be.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:n}}function iy(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=be.selectCoinAssetGreaterThanOrEqual(e,n).selectedCoins;if(r.length===0)throw new J("Insufficient balance","InsufficientBalance");let o=be.calculateTotalBalance(e);if(o-n>1e9)return{fixAmount:n};let s=await t.fullClient.calculationTxGas(i);if(be.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 gi.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}=as(n),s=o?n.amount_a:n.amount_b,a=await se.adjustTransactionForGas(t,be.getCoinAssets(o?n.coinTypeA:n.coinTypeB,e),BigInt(s),r),{fixAmount:u}=a,{newTx:l}=a;if(l!==void 0){let h,b;if(o)n.amount_a=Number(u),h=se.buildAddLiquidityFixTokenCoinInput(l,!n.fix_amount_a,u.toString(),n.slippage,n.coinTypeA,e,!1),b=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),b=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,b),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 gi.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(iy(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 jr.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),b=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}::${Dn}::${a}`,typeArguments:s,arguments:b}),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,be.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 gi.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=fn.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,b=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}::${Dn}::${b}`,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,be.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),b=se.buildSwapTransactionWithoutTransferCoinArgs(t,u,e,t.sdkOptions,l,h);r=b.tx,o=b.txRes}return{tx:r,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,n){let i=new gi.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=fn.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,b=h?"swap_with_partner":"swap",v=h?cc:Wn,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}::${b}`,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=hc(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=be.getCoinAssets(i,e);if(n===BigInt(0)&&s.length===0)return se.buildZeroValueCoin(e,t,i,r);let a=be.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(be.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=be.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.object(E.objectArray[0]),remainCoins:E.remainCoins,tragetCoinAmount:E.amountArray[0],isMintZeroCoin:!1}}let P=be.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=be.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,...b]=l,v=t.object(h),T=v,I=a.amountArray.reduce((P,O)=>Number(P)+Number(O),0).toString(),x;return b.length>0&&t.mergeCoins(v,b.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=be.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=be.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 gi.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],b=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,b,!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:b,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()),b=Number(l.reduce((B,$)=>B.add($.amountOut),ie).toString()),v=Math.round(n?Number(b.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?Wn:cc;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=fn.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=fn.getDefaultSqrtPriceLimit(B.a2b[0]),U=fn.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(b=>b.basePaths.some(v=>v.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!h){let b=[];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 jr.default(Z.inputAmount.toString())),$===0?E.push(Z.fromCoin,Z.toCoin):E.push(Z.toCoin)}let B={amountIn:new jr.default(I.inputAmount.toString()),amountOut:new jr.default(I.outputAmount.toString()),poolAddress:P,a2b:x,rawAmountLimit:O,isExceed:!1,coinType:E};b.push(B)}let v={paths:b,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 b=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]=Ld.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}::${Nd}::send_coin`,typeArguments:[E.fromCoin],arguments:[P,s.pure(a)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,l,b,e.toCoin),v&&(s=Ld.deleteAccountCapByObject(T,t.sdkOptions,s))}return{fromCoin:u,toCoin:l,tx:s}}static async buildAggregatorSwapTransaction(t,e,n,i,r,o){let s=new gi.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),b=await this.buildAggregatorSwapReturnCoins(t,e,u,h,i,r,s,o),{fromCoin:v,toCoin:T}=b;s=b.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}::${Wn}::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],b=n.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:h,arguments:l});return r=e.direction?b[0]:b[1],o=e.direction?b[1]:b[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,b=e.direction?r:o,v=e.direction?o:r,T=a==="",I=T?Wn:cc,x=T?"swap":"swap_with_partner",P=i?e.inputAmount.toString():e.outputAmount.toString(),O=fn.getDefaultSqrtPriceLimit(e.direction),E=T?[n.object(h),n.object(e.poolAddress),b,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),b,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 b=$[0],v=$[1],r=e.direction?b:v,o=e.direction?v:b,{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}::${Nd}::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;_0(re,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function Nt(t){return!(!t.startsWith("0x")||t.length!==66)}var Xi=new Pt.default(1e9),Ld=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}::${C0}::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}::${uc}::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}::${uc}::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:uc}}});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 is.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 b=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(b.length===0)return a;for(let v=0;v<b[0].parsedJson.depths.length;v++){let T=b[0].parsedJson.price[v],I=b[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 is.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 b=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(v=>q(v.type).name==="BookStatus");if(b.length===0)return a;for(let v=0;v<b[0].parsedJson.depths.length;v++){let T=b[0].parsedJson.price[v],I=b[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,b)=>b.price-h.price);for(let h=0;h<l.length;h+=1){let b=new Pt.default(l[h].quantity),v=new Pt.default(l[h].price),T=b.mul(new Pt.default(v)).mul(new Pt.default(e.takerFeeRate)).div(Xi).div(Xi);if(s.gt(b))s=s.sub(b),o=o.add(b.mul(v).div(Xi).sub(T)),a=a.add(T);else{let I=s.mul(new Pt.default(l[h].price)).div(Xi),x=I.mul(new Pt.default(e.takerFeeRate)).div(Xi);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 b=new Pt.default(l[h].price).mul(new Pt.default(l[h].quantity)).div(new Pt.default(1e9)),v=b.mul(new Pt.default(e.takerFeeRate)).div(Xi),T=b.add(v);if(s.gt(b))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 is.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}::${S0}::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}}},sy=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(b=>{let v=b.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 b=a[h];l&&!t.includes(b.poolAddress)||!l&&(h<e||h>=e+n)||u.push(b)}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=lc(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 b={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(b)}})}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=lc(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=lc(r);return this.updateCache(n,o),o}async creatPoolsTransactionPayload(t){for(let n of t)if(ss((0,Br.normalizeSuiAddress)(n.coinTypeA),(0,Br.normalizeSuiAddress)(n.coinTypeB))){let i=n.coinTypeB;n.coinTypeB=n.coinTypeA,n.coinTypeA=i}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(ss((0,Br.normalizeSuiAddress)(t.coinTypeA),(0,Br.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=wi(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 Ji.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}::${Qi}::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 Ji.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}::${Dn}::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 Ji.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Ut}::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(ty(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 Ji.TransactionBlock,u=[a.object(t.pool_id),a.pure(r,"u64"),a.pure(o.toString(),"u64")];if(a.moveCall({target:`${e.published_at}::${Ut}::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(b=>{q(b.type).name==="FetchPositionsEvent"&&b.parsedJson.positions.forEach(v=>{let T=Yd(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=dc(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 dc(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 dc(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 Ji.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}::${k0}::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]}},ay=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=En(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=En(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=En(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 Yd(r)}catch(n){console.log(n);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new _i.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}::${Ut}::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 pc.default(l.fee_owned_a),feeOwedB:new pc.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}=as(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 _i.TransactionBlock,a=!(0,Qd.isValidSuiObjectId)(t.pos_id),u=BigInt(t.max_amount_a),l=BigInt(t.max_amount_b),h=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),b=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}::${Dn}::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),b.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,b.remainCoins,v.remainCoins),s.moveCall({target:`${e.published_at}::${Dn}::add_liquidity`,typeArguments:o,arguments:[s.object(D(n).global_config_id),s.object(t.pool_id),s.object(t.pos_id),b.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 _i.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}::${Qi}::${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 _i.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}::${Qi}::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 _i.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}::${Qi}::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 _i.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}::${Dn}::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]}},cy=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=ny(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=kn);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=kn);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=kn);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 rs.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}::${Ut}::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 rs.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}::${Ut}::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 rs.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}::${Dn}::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 ns(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var uy=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new bi.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}=ns(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 bi.GraphVertex(r.base),s=this.graph.getVertexByKey(r.quote)??new bi.GraphVertex(r.quote);this.graph.addEdge(new bi.GraphEdge(o,s));let a=this._coinAddressMap.get(r.base),u=this._coinAddressMap.get(r.quote);if(a!=null&&u!=null){let l=ns(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=ns(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=ns(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),b=this.graph.findAllPath(l,h),v=Array.from(b);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 w=K[g].value.toString(),m=K[g+1].value.toString(),p=this.getPoolAddressMapAndDirection(w,m),y=p?.addressMap,_=p?.direction;y!=null&&_!=null&&(A.push(_),C.push(w),C.push(m),y.forEach(f=>{g===0?c.push(f):d.push(f)}))}for(let g of c)if(d.length>0)for(let w of d){let m={stepNums:2,poolAB:g,poolBC:w,a2b:A[0],b2c:A[1],amount:n,byAmountIn:i,coinTypeA:C[0],coinTypeB:C[1],coinTypeC:C[3]};T.push(m)}else{let w={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(w)}}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 Wt.default(F.estimatedAmountIn),amountOut:new Wt.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 Wt.default(F.estimatedAmountIn),amountOut:new Wt.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 Wt.default(K.estimatedAmountIn),amountOut:new Wt.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 Wt.default(K.estimatedAmountIn),amountOut:new Wt.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 ef.TransactionBlock;for(let b of t)if(b.stepNums>1){let v=[i.object(b.poolAB),i.object(b.poolBC),i.pure(b.a2b),i.pure(b.b2c),i.pure(b.byAmountIn),i.pure(b.amount.toString())],T=[];b.a2b?T.push(b.coinTypeA,b.coinTypeB):T.push(b.coinTypeB,b.coinTypeA),b.b2c?T.push(b.coinTypeB,b.coinTypeC):T.push(b.coinTypeC,b.coinTypeB),i.moveCall({target:`${e.published_at}::${Wn}::calculate_router_swap_result`,typeArguments:T,arguments:v})}else{let v=[i.pure(b.poolAB),i.pure(b.a2b),i.pure(b.byAmountIn),i.pure(b.amount.toString())],T=b.a2b?[b.coinTypeA,b.coinTypeB]:[b.coinTypeB,b.coinTypeA];i.moveCall({target:`${e.published_at}::${T0}::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(b=>q(b.type).name==="CalculatedRouterSwapResultEvent"||q(b.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?ie:er,a=0;for(let b=0;b<o.length;b+=1)if(!o[b].parsedJson.data.is_exceed)if(t[0].byAmountIn){let v=new Wt.default(o[b].parsedJson.data.amount_out);v.gt(s)&&(a=b,s=v)}else{let v=t[b].stepNums>1?new Wt.default(o[b].parsedJson.data.amount_in):new Wt.default(o[b].parsedJson.data.amount_in).add(new Wt.default(o[b].parsedJson.data.fee_amount));v.lt(s)&&(a=b,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 ly=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),b=l.div(h);e=e.add(this.calculateSingleImpact(b,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 mc.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}::${Ut}::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:er,u=0;for(let l=0;l<s.length;l+=1)if(!s[l].parsedJson.data.is_exceed)if(t.byAmountIn){let h=new yi.default(s[l].parsedJson.data.amount_out);h.gt(a)&&(u=l,a=h)}else{let h=new yi.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 mc.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}::${Ut}::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 yi.default(e.amount_in).add(new yi.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 yi.default(n.amount_in).add(new yi.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=v0(e),i;t.a2b?i=t.swapTicks.sort((b,v)=>v.index-b.index):i=t.swapTicks.sort((b,v)=>b.index-v.index);let r=R0(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=fn.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}=as(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}=as(t);if(t.a2b&&i||!t.a2b&&r)return await re.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,n,e)}return re.buildSwapTransactionWithoutTransferCoins(this.sdk,t,n)}},dy=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 b=new gc.TransactionBlock;b.moveCall({target:`${i.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[b.pure(h.coin_registry_id),b.pure(t),b.pure(u),b.pure(a)]:[b.pure(h.coin_registry_id),b.pure(u),b.pure(a)]});let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:b,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 b=new gc.TransactionBlock;if(b.moveCall({target:`${i.published_at}::lp_list::${l?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:l?[b.pure(h.pool_registry_id),b.pure(t),b.pure(u),b.pure(a)]:[b.pure(h.pool_registry_id),b.pure(u),b.pure(a)]}),!Nt(n.address))throw new J("this config simulationAccount is not set right","InvalidSimulateAccount");let v=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:b,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=wi(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(Zi.decode(s)))}catch{}o==="pyth_id"&&(s=(0,tf.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]}},fy=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 dn.default(r.current_sqrt_price.toString()),afterSqrtPrice:r.label==="Cetus"?new dn.default(r.after_sqrt_price.toString()):ie,fromDecimal:r.from_decimal,toDecimal:r.to_decimal,currentPrice:this.calculatePrice(new dn.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 b=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(Qo()),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(Qo())}
5
+ `;if(b=await this.fetchAndParseData(I,T),b?.isTimeout||b==null){let x=await this.sdk.Router.price(t,e,new dn.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 dn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new dn.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 dn.default(x.currentSqrtPrice[1]),V,F):ee.sqrtPriceX64ToPrice(new dn.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 dn.default(x.currentSqrtPrice[0]),Z,H):ee.sqrtPriceX64ToPrice(new dn.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",b=O}return{result:b,version:v}}},hy=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:K0(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=qt(t),i.address=q(n.coin_type.fields.name).full_address,n.pyth_id&&(i.pyth_id=(0,os.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=qt(t),i.pool_address=(0,os.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=qt(t),i.pool_address=(0,os.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(Zi.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=Zi.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(Zi.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=wi(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=hn(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}}},py=class extends rf.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"?nf.Inputs.SharedObjectRef({objectId:h,initialSharedVersion:0,mutable:!0}):h}),transactions:t.blockData.transactions}},o=of.bcs.TransactionKind.serialize(r,{maxSize:131072}).toBytes(),s=Wa(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(i){console.log("devInspectTransactionBlock error",i)}}},sf=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new py({url:t.fullRpcUrl}),this._swap=new ly(this),this._pool=new sy(this),this._position=new ay(this),this._rewarder=new cy(this),this._router=new uy(this),this._router_v2=new fy(this),this._token=new dy(this),this._config=new hy(this),fs(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 uf=require("@mysten/sui.js/utils");var _s=require("@mysten/sui.js/transactions");var Ht=require("@mysten/sui.js/transactions"),cr=require("@mysten/sui.js/utils"),$r=ge(ke(),1);var lf=require("@mysten/sui.js/utils");var kc=require("@mysten/sui.js/transactions");var Mn=require("@mysten/sui.js/transactions");var Sn=require("@mysten/sui.js/utils"),Zt=require("@mysten/sui.js/transactions");var Tc=require("@mysten/sui.js/utils");var Cy=require("@mysten/sui.js/utils");var qe=ge(ke(),1);var hf=ge(ke(),1);var Cc=ge(ke(),1);var Bn=require("@mysten/sui.js/transactions"),ki=require("@mysten/sui.js/transactions");var Ti=require("@mysten/sui.js/transactions");var Oe=ge(ke(),1);var Sc=require("@mysten/sui.js/bcs"),qr=require("@mysten/sui.js/utils"),ys=require("@mysten/sui.js/transactions");var Xt=require("@mysten/sui.js/transactions"),bc="router",ar=1e4,Hn=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(ar))})}),{basic_percent:Number(S(e.basic_percent).div(ar)),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:qt(t)}}static buildLockNFT(t){let e=q(qt(t)).address;return{lock_clmm_position:En(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}},my=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=Hn.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=Hn.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=Hn.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=Hn.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 b=Hn.buildLockNFT(l);this.updateCache(`${b.locked_nft_id}_getBoosterPositionById`,b,X),b&&(e===void 0||e===b.lock_clmm_position.pool)&&r.push(b)}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=Hn.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=Hn.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 Hn.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 _s.TransactionBlock;return i.moveCall({target:`${e.published_at}::${bc}::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 _s.TransactionBlock;return n.moveCall({target:`${e.published_at}::${bc}::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 _s.TransactionBlock,o=D(n);return r.moveCall({target:`${e.published_at}::${bc}::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]}},Kt="router",df=1e9;var Cn=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,lf.normalizeSuiObjectId)(qt(t)),is_settle:i.is_settle,current_price:S(i.initialize_price).div(S(df)).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 Cn.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,$r.min)(new $r.default(e.total_purchase_amount),new $r.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 Cn.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"}},gy=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(b=>{let v=b.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 b=a[h];if(!(l&&!t.includes(b.pool_address))){if(!l){let v=h;if(v<e||v>=e+n)continue}u.push(b)}}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=Cn.buildLaunchPadPool(s);await Cn.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 Cn.updatePoolStatus(s),s}let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=Cn.buildLaunchPadPool(r);return await Cn.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=wi(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 En(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=Cn.priceRealToFix(Number(t.initialize_price),t.sale_decimals,t.raise_decimals),r=new Ht.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,cr.normalizeSuiAddress)(t.recipient)),r.pure((i*df).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}::${Kt}::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 Ht.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}::${Kt}::${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 Ht.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}::${Kt}::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 Ht.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),b=be.calculateTotalBalance(h);be.isSuiCoin(l)&&(b-=BigInt(2e8));let T=re.buildCoinForAmount(o,h,b,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}::${Kt}::${I}`,typeArguments:s,arguments:x})}else o.moveCall({target:`${e.published_at}::${Kt}::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 Ht.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}::${Kt}::withdraw_sale`,typeArguments:i,arguments:r}),t.raise_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Kt}::withdraw_raise`,typeArguments:i,arguments:r}),n}addUserToWhitelisPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Ht.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}::${Kt}::add_user_to_whitelist`,typeArguments:i,arguments:o})}),n}updateWhitelistCapPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Ht.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.safe_limit_amount>0&&n.moveCall({target:`${e.published_at}::${Kt}::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}::${Kt}::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 Ht.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}::${Kt}::remove_user_from_whitelist`,typeArguments:i,arguments:o})}),n}creatCancelPoolPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Ht.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}::${Kt}::cancel`,typeArguments:i,arguments:r}),n}updateRecipientPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Ht.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}::${Kt}::update_recipient_address`,typeArguments:i,arguments:r}),n}updatePoolDuractionPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new Ht.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}::${Kt}::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 Ht.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=hn(r),s=ir(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,cr.normalizeSuiAddress)(s.AddressOwner)===(0,cr.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,cr.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 tr(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]}},Zn=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(ar)),multiplier:Number(S(r.fields.value).div(ar))})}),{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(ar)),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(ar)),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}},af="router",_y=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(Zn.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 Zn.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=Zn.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=Zn.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=Zn.buildMarkerPositions(u);if(l.length>0){let{period_id:h}=l[0],b=e.filter(v=>v.id===h)[0];i[b.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=Zn.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=Zn.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===_c.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=Zn.buildPoolBonusInfo(s);return this.updateCache(i,a,Ue),a}claimPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new kc.TransactionBlock;return i.moveCall({target:`${e.published_at}::${af}::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 kc.TransactionBlock;return t.whale_nfts.forEach(r=>{r.nft_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::${af}::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]}},rr="router",wc="router",Lr=24*3600,bs=1e3,rn=1e11,Ci=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)/Lr,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=>!Ci.isLocked(e))}static getLockingCetuss(t){return t.filter(e=>Ci.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*Lr));return n+r*i*Lr}},yy=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={...vi(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=Ci.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=Ci.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 Mn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${rr}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xcetus_manager_id)]}),e}async convertPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new Mn.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}::${rr}::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}::${rr}::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 Mn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${rr}::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 Mn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${rr}::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 Mn.TransactionBlock;return e.forEach(o=>{r.moveCall({target:`${n.published_at}::${wc}::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 Mn.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}::${wc}::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 Mn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${wc}::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 Mn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${rr}::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=Ci.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=Ci.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 Ci.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(rn).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(rn).mul(S(n.max_percent_numerator)).sub(i).div(S(bs)).div(rn);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(rn).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(rn).mul(S(n.max_percent_numerator)).sub(i).div(S(bs)).div(rn);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),b=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:qt(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:b,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]}},by="factory",nn="oversubscribe_pool",ff=1e6,sr=1e18;var or="router",vc="router",ps="router";var cf={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 wy(t){return"master_address"in t}var vy="router",ky="vaults",Ty=1e4;var Lt=class{static buildIdoPoolImmutables(t){return{pool_address:(0,Tc.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,Tc.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(ff).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 Lt.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&&Lt.is_claim_period(t.duration_summary)&&!t.is_liquidity_injected}static is_can_withdraw(t){return t.is_withdrawn?!1:Lt.is_sale_failed(t)?!0:(t.liquidity_injection_ratio===0||t.is_liquidity_injected)&&Lt.is_claim_period(t.duration_summary)}static is_sale_failed(t){return!!(t.is_cancelled||Lt.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(Lt.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(sr).div(t.price).toString(),i=e.purchased_raise_amount;else{let o=Lt.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(Lt.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(Lt.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(sr).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(sr).div(S(a).mul(t.price)),l=N.ceil(u.mul(t.price).div(sr));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=Cn.priceFixToReal(Number(S(e.price).div(S(sr)).toString()),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r,e.max_raise_amount=this.raiseTotalAmount(e)}};var Si=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)/Lr,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=>!Si.isLocked(e))}static getLockingTokens(t){return t.filter(e=>Si.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=Lr){let n=Date.now()/1e3,{start_time:i,interval_day:r}=t,o=Math.ceil((n-i)/(r*e));return i+o*r*e}},jn=class{static getDefaultStrategyConfig(t){let e;switch(t){case 4:e=cf.bidAsk;break;default:e=cf.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<Kd)throw Error("Tick lower value is below the minimum allowed value.");if(o>Ud)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=jn.getCreateBidAskLiquidityBins(t);break;default:n=jn.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=jn.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 jn.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,...hs(h,nr.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(Jd(100,6).toString()).mul(l.ratio).toFixed(0).toString(),b=ee.tickIndexToSqrtPriceX64(l.tick_lower),v=ee.tickIndexToSqrtPriceX64(l.tick_upper),T=$e.getCoinAmountFromLiquidity(new qe.default(h),n,b,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 b={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(b),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=nr.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:l,tokenMaxB:h}=hs(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=jn.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 b=$e.estLiquidityAndcoinAmountFromOneAmounts(a.tick_lower_index,a.tick_upper_index,new qe.default(h),n.fix_amount_a,!1,t.slippage,e);return{...b,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:b.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 jn.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),b=nr.fromDecimal(S(t.slippage).mul(100)),{tokenMaxA:v,tokenMaxB:T}=hs(h,b,!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:[],...vi(t)};return n.positions=e.positions.map(i=>jn.buildMasterPosition(i.fields)),n}}},Tn=class{static generateNextTickRange(t,e,n){let i=t-e/2,r=t+e/2;return{new_tick_lower:Tn.getValidTickIndex(i,n),new_tick_upper:Tn.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 hf.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(Ty).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=hn(t),{positions:i}=e;if(e&&i.length>0){let r=Tn.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}}}},ms=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:b,coinB:v}=$e.getCoinAmountFromLiquidity(new Cc.default(n),new Cc.default(s),l,h,!0);return S(b.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:[]}}}},Sy=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=Lt.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=Lt.buildIdoPool(o);await Lt.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=Lt.buildIdoPool(r);return await Lt.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=wi(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=Lt.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 En(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;ss((0,Sn.normalizeSuiAddress)(t.coin_type_sale),(0,Sn.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=Cn.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 Zt.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,Sn.normalizeSuiAddress)(t.owner)),s.pure(S(i).mul(sr).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*ff).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)],b=[t.coin_type_sale,t.coin_type_raise];return s.moveCall({target:`${e.published_at}::${by}::create_oversubscribe_pool`,typeArguments:b,arguments:h}),s}async creatPurchasePayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Zt.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}::${nn}::${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 Zt.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}::${nn}::redeem`,typeArguments:r,arguments:o}),i}injectLiquidityPayload(t){let{ido:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new Zt.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}::${nn}::${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 Zt.TransactionBlock;r.moveCall({target:`${n.published_at}::${Qi}::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}::${nn}::${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 Zt.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}::${nn}::withdraw`,typeArguments:i,arguments:r}),n}updateWhitelistCapPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Zt.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}::${nn}::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,Sn.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}::${nn}::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,Sn.normalizeSuiObjectId)(r)))}),n.object(G)]}),t.update_whites&&t.update_whites.forEach(r=>{n.moveCall({target:`${e.published_at}::${nn}::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 Zt.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}::${nn}::cancel`,typeArguments:i,arguments:r}),n}updatePoolOwnerPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Zt.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}::${nn}::update_pool_owner`,typeArguments:i,arguments:r}),e}updatePoolDuractionPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Zt.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}::${nn}::update_pool_duration`,typeArguments:i,arguments:r}),e}updateProtectionHardCapPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new Zt.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}::${nn}::update_protection_hard_cap`,typeArguments:i,arguments:r}),e}unlockNftPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new Zt.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=hn(r),s=ir(r),a=!1;return s&&o&&q(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,Sn.normalizeSuiAddress)(s.AddressOwner)===(0,Sn.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=hn(i),o=ir(i);if(o&&r&&q(r).source_address===`${t.package_id}::config::AdminCap`){let a=(0,Sn.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]}},Ay=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={...vi(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=Si.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=Si.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 Bn.TransactionBlock;return e.moveCall({target:`${t.published_at}::${or}::mint_venft`,typeArguments:[],arguments:[e.pure(D(t).xtoken_manager_id)]}),e}async convertPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new Bn.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}::${or}::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}::${or}::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 Bn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${or}::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 Bn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${or}::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 Bn.TransactionBlock;return e.forEach(r=>{i.moveCall({target:`${n.published_at}::${vc}::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 Bn.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}::${vc}::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 Bn.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${vc}::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 Bn.TransactionBlock;return n.moveCall({target:`${e.published_at}::${or}::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=Si.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=Si.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 Si.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(rn).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(rn).mul(S(n.max_percent_numerator)).sub(i).div(S(bs)).div(rn);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(rn).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(rn).mul(S(n.max_percent_numerator)).sub(i).div(S(bs)).div(rn);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),b=u.bonus.fields.contents.map(T=>({name:T.fields.key.fields.name,value:T.fields.value})),v={id:qt(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:b,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]}},xy=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 b=[t.coinTypeA,t.coinTypeB],v=new ki.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 wy(t)?v.moveCall({target:`${e.published_at}::router::increase_liquidity`,typeArguments:b,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:b,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=jn.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=jn.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 ki.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}::${Ut}::fetch_position_fees`,arguments:h,typeArguments:l}),o.moveCall({target:`${i.published_at}::${Ut}::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 ki.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}::${ps}::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 ki.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}::${ps}::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 ki.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}::${ps}::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 ki.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}::${ps}::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]}},Iy=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildCoinInput(t,e,n,i,r){let{selectedCoins:o,remainingCoins:s}=be.selectCoinAssetGreaterThanOrEqual(e,BigInt(i)),a=be.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(be.isSuiCoin(n))l=t.splitCoins(t.gas,[t.pure(i)]);else{let[h,...b]=o.map(v=>v.coinObjectId);l=t.object(h),b.length>0?r?t.mergeCoins(l,[...b.map(v=>t.object(v)),r]):t.mergeCoins(l,[...b.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 Ti.TransactionBlock,s,a;if(t.swapParams){let b=await this.handleDepositSwap(t,o,r);s=b.primaryCoinAInputs,a=b.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}::${vy}::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),b=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=fn.getDefaultSqrtPriceLimit(s).toString();v=e.moveCall({target:`${r.published_at}::${Wn}::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)-b;be.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)-b;be.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 Ti.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),b=[t.coinTypeA,t.coinTypeB,t.lp_token_type],v=o.moveCall({target:`${e.published_at}::${ky}::remove`,typeArguments:b,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=fn.getDefaultSqrtPriceLimit(x).toString(),B=o.moveCall({target:`${r.published_at}::${Wn}::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=Tn.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 Ti.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}::${Ut}::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}::${Ut}::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 b=h[0].parsedJson.data,v=h[1].parsedJson.data,T=S(a.coinB.toString()).add(b.amount_out),I=S(a.coinA.toString()).add(v.amount_out);return{maxAmountB:T,maxAmountA:I}}async calculateRemoveSwapAmount(t,e){let n=Tn.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),b=h.sub(l);if(console.log(`\u5B9E\u9645\u5F97\u5230: ${l.toString()} , \u671F\u671B\u5F97\u5230: ${t.receive_amount}, \u5269\u4F59: ${b.toString()} `),(!t.removeLiquidity||t.removeLiquidity&&e)&&b.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}=Tn.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(be.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||be.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,b=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=b.after_sqrt_price,T=ee.sqrtPriceX64ToTickIndex(new Oe.default(v));console.log("1110 \u9996\u6B21\u8BA1\u7B97 \u7ED3\u679C: ",{...b,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}=Tn.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)),b=await this.calculateRebalance(l),v=b.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}=Tn.calculateDepositRatio(t.lowerTick,t.upperTick,new Oe.default(v));console.log("1110 1",{afterRatioA:x,afterRatioB:P,data:b});let O=P.div(x).sub(r.div(i)).greaterThan("0"),E=b.amount_in&&b.fee_amount?new Oe.default(b.amount_in).add(new Oe.default(b.fee_amount)).toString():b.amount_in,B=b.amount_out,{is_exceed:$}=b;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:b.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}=Tn.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(be.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||be.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:b,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,b,!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:b}=this.sdk.ClmmSDK.sdkOptions,v=new Ti.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}::${Ut}::calculate_swap_result`,arguments:I,typeArguments:T});let P=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:v,sender:b.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=Tn.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 Ti.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:b}=l.parsedJson,v=S(h).div(b).toString();return console.log({st_amount:b,sui_amount:h,rate:v}),v}let a=s.results[0].returnValues[0][0],u=Sc.bcs.de("u64",Uint8Array.from(a))/1e6;return console.log("rate ",Sc.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,qr.normalizeSuiObjectId)("0x5")),e.object(t),n,e.pure((0,qr.normalizeSuiObjectId)("0x0"))]})}async requestStake(t,e,n){let{haedal:i}=this._sdk.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),Fr);n=n||new Ti.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),Fr,!1,!0).targetCoin;return n.moveCall({target:`${i.published_at}::interface::request_stake`,typeArguments:[],arguments:[n.object((0,qr.normalizeSuiObjectId)("0x5")),n.object(t),o,n.pure((0,qr.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]}},gs=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=hn(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}},Oy=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=>gs.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 gs.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(...gs.buildOrderLimitEvent(r))}),i}catch(n){return console.error("Error in getLimitOrderLogs:",n),[]}}buildRateOrdersIndexerType(t){let{limit_order:e}=this._sdk.sdkOptions;return tr(`${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 ys.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(gs.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 ys.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 ys.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=ms.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=ms.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:yc(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:""},b=l.pools.fields.id.id,v=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:b,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 b of h.data){let v=ms.buildFramsPositionNFT(b);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 b=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=>{b[v.id]&&(v.rewards=b[v.id]);let I=a[v.pool_id];I?I.push(v):I=[v],a[v.pool_id]=I})):u.forEach(v=>{b[v.id]&&(v.rewards=b[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=ms.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 Xt.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],b=[];h.rewards.contents.forEach(v=>{b.push({rewarder_type:q(v.key.name).full_address,rewarder_amount:v.value})}),s[h.wrapped_position_id]=b}}catch(a){console.log(a)}return s}depositPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new Xt.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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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}::${Dn}::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:b}=D(l);return e.moveCall({target:`${l.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(h),e.object(b),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 Xt.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 Xt.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 Xt.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 Xt.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 Xt.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]}},pf=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 gy(this),this._ido=new Sy(this),this._xcetusModule=new yy(this),this._xtokenModule=new Ay(this),this._boosterModule=new my(this),this._makerModule=new _y(this),this._vaults=new Iy(this),this._limitOrder=new Oy(this),this._farmsModule=new Py(this),this._liquidityStrategy=new xy(this),fs(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,uf.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 Tp=require("@msafe/sui3-utils"),Sp=require("@msafe/sui3-utils"),xp=require("@msafe/sui3-utils"),Op=require("@msafe/sui3-utils"),Dp=require("@msafe/sui3-utils"),Mp=require("@msafe/sui3-utils"),jp=require("@msafe/sui3-utils"),Fp=require("@msafe/sui3-utils"),qp=require("@msafe/sui3-utils"),$p=require("@msafe/sui3-utils"),Kp=require("@msafe/sui3-utils"),Vp=require("@msafe/sui3-utils"),Wp=require("@msafe/sui3-utils"),Zp=require("@msafe/sui3-utils"),Jp=require("@msafe/sui3-utils"),Qp=require("@msafe/sui3-utils"),tm=require("@msafe/sui3-utils"),im=require("@msafe/sui3-utils"),om=require("@msafe/sui3-utils"),km=require("@mysten/sui.js/client"),Ln=ge(require("axios"),1),qi=require("@mysten/sui.js/utils"),Co=require("@mysten/sui.js/transactions"),Iu=require("@mysten/sui.js/transactions"),Ao=require("@mysten/sui.js/utils"),Ou=require("buffer"),Am=require("@mysten/sui.js/utils"),qu=require("@mysten/sui.js/bcs"),xo=require("@mysten/sui.js/utils");var mf=(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 Eu=require("@mysten/sui.js/transactions"),So=require("@mysten/sui.js/transactions"),Io=require("@mysten/sui.js/utils");var Nn=class extends Error{},ws=class extends Nn{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},vs=class extends Nn{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},ks=class extends Nn{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},pn=class extends Nn{},ur=class extends Nn{constructor(e){super(`Invalid unit ${e}`)}},wt=class extends Nn{},mn=class extends Nn{constructor(){super("Zone is an abstract class")}};var Y="numeric",gn="short",Jt="long",Xn={year:Y,month:Y,day:Y},Ur={year:Y,month:gn,day:Y},Ac={year:Y,month:gn,day:Y,weekday:gn},Kr={year:Y,month:Jt,day:Y},zr={year:Y,month:Jt,day:Y,weekday:Jt},Vr={hour:Y,minute:Y},Gr={hour:Y,minute:Y,second:Y},Wr={hour:Y,minute:Y,second:Y,timeZoneName:gn},Hr={hour:Y,minute:Y,second:Y,timeZoneName:Jt},Zr={hour:Y,minute:Y,hourCycle:"h23"},Xr={hour:Y,minute:Y,second:Y,hourCycle:"h23"},Jr={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:gn},Yr={hour:Y,minute:Y,second:Y,hourCycle:"h23",timeZoneName:Jt},Qr={year:Y,month:Y,day:Y,hour:Y,minute:Y},eo={year:Y,month:Y,day:Y,hour:Y,minute:Y,second:Y},to={year:Y,month:gn,day:Y,hour:Y,minute:Y},no={year:Y,month:gn,day:Y,hour:Y,minute:Y,second:Y},xc={year:Y,month:gn,day:Y,weekday:gn,hour:Y,minute:Y},io={year:Y,month:Jt,day:Y,hour:Y,minute:Y,timeZoneName:gn},ro={year:Y,month:Jt,day:Y,hour:Y,minute:Y,second:Y,timeZoneName:gn},oo={year:Y,month:Jt,day:Y,weekday:Jt,hour:Y,minute:Y,timeZoneName:Jt},so={year:Y,month:Jt,day:Y,weekday:Jt,hour:Y,minute:Y,second:Y,timeZoneName:Jt};var zt=class{get type(){throw new mn}get name(){throw new mn}get ianaName(){return this.name}get isUniversal(){throw new mn}offsetName(e,n){throw new mn}formatOffset(e,n){throw new mn}offset(e){throw new mn}equals(e){throw new mn}get isValid(){throw new mn}};var Ic=null,Jn=class t extends zt{static get instance(){return Ic===null&&(Ic=new t),Ic}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:i}){return Cs(e,n,i)}formatOffset(e,n){return Yn(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var As={};function Dy(t){return As[t]||(As[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"})),As[t]}var Ey={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function My(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=Ey[o];o==="era"?i[a]=s:de(a)||(i[a]=parseInt(s,10))}return i}var Ss={},Ft=class t extends zt{static create(e){return Ss[e]||(Ss[e]=new t(e)),Ss[e]}static resetCache(){Ss={},As={}}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 Cs(e,n,i,this.name)}formatOffset(e,n){return Yn(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let i=Dy(this.name),[r,o,s,a,u,l,h]=i.formatToParts?By(i,n):My(i,n);a==="BC"&&(r=-Math.abs(r)+1);let v=lr({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 gf={};function jy(t,e={}){let n=JSON.stringify([t,e]),i=gf[n];return i||(i=new Intl.ListFormat(t,e),gf[n]=i),i}var Oc={};function Pc(t,e={}){let n=JSON.stringify([t,e]),i=Oc[n];return i||(i=new Intl.DateTimeFormat(t,e),Oc[n]=i),i}var Dc={};function Ny(t,e={}){let n=JSON.stringify([t,e]),i=Dc[n];return i||(i=new Intl.NumberFormat(t,e),Dc[n]=i),i}var Ec={};function Fy(t,e={}){let{base:n,...i}=e,r=JSON.stringify([t,i]),o=Ec[r];return o||(o=new Intl.RelativeTimeFormat(t,e),Ec[r]=o),o}var ao=null;function Ry(){return ao||(ao=new Intl.DateTimeFormat().resolvedOptions().locale,ao)}var _f={};function qy(t){let e=_f[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,_f[t]=e}return e}function Ly(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=Pc(t).resolvedOptions(),r=t}catch{let u=t.substring(0,n);i=Pc(u).resolvedOptions(),r=u}let{numberingSystem:o,calendar:s}=i;return[r,o,s]}}function $y(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Uy(t){let e=[];for(let n=1;n<=12;n++){let i=we.utc(2009,n,1);e.push(t(i))}return e}function Ky(t){let e=[];for(let n=1;n<=7;n++){let i=we.utc(2016,11,13+n);e.push(t(i))}return e}function xs(t,e,n,i){let r=t.listingMode();return r==="error"?null:r==="en"?n(e):i(e)}function zy(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 Mc=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=Ny(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):dr(e,3);return Le(n,this.padTo)}}},Bc=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=Pc(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()}},jc=class{constructor(e,n,i){this.opts={style:"long",...i},!n&&Is()&&(this.rtf=Fy(e,i))}format(e,n){return this.rtf?this.rtf.format(e,n):yf(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},Vy={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":Ry()),u=n||Ce.defaultNumberingSystem,l=i||Ce.defaultOutputCalendar,h=co(r)||Ce.defaultWeekSettings;return new t(a,u,l,h,s)}static resetCache(){ao=null,Oc={},Dc={},Ec={}}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]=Ly(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=i||u||null,this.weekSettings=r,this.intl=$y(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=zy(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,co(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 xs(this,e,Nc,()=>{let i=n?{month:e,day:"numeric"}:{month:e},r=n?"format":"standalone";return this.monthsCache[r][e]||(this.monthsCache[r][e]=Uy(o=>this.extract(o,i,"month"))),this.monthsCache[r][e]})}weekdays(e,n=!1){return xs(this,e,Fc,()=>{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]=Ky(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return xs(this,void 0,()=>Rc,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[we.utc(2016,11,13,9),we.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return xs(this,e,qc,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[we.utc(-40,1,1),we.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 Mc(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Bc(e,this.intl,n)}relFormatter(e={}){return new jc(this.intl,this.isEnglish(),e)}listFormatter(e={}){return jy(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:Os()?qy(this.locale):Vy}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 $c=null,Ct=class t extends zt{static get utcInstance(){return $c===null&&($c=new t(0)),$c}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(Ai(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Yn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Yn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return Yn(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 fr=class extends zt{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 _n(t,e){let n;if(de(t)||t===null)return e;if(t instanceof zt)return t;if(bf(t)){let i=t.toLowerCase();return i==="default"?e:i==="local"||i==="system"?Jn.instance:i==="utc"||i==="gmt"?Ct.utcInstance:Ct.parseSpecifier(i)||Ft.create(t)}else return An(t)?Ct.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new fr(t)}var wf=()=>Date.now(),vf="system",kf=null,Tf=null,Cf=null,Sf=60,Af,xf=null,Ce=class{static get now(){return wf}static set now(e){wf=e}static set defaultZone(e){vf=e}static get defaultZone(){return _n(vf,Jn.instance)}static get defaultLocale(){return kf}static set defaultLocale(e){kf=e}static get defaultNumberingSystem(){return Tf}static set defaultNumberingSystem(e){Tf=e}static get defaultOutputCalendar(){return Cf}static set defaultOutputCalendar(e){Cf=e}static get defaultWeekSettings(){return xf}static set defaultWeekSettings(e){xf=co(e)}static get twoDigitCutoffYear(){return Sf}static set twoDigitCutoffYear(e){Sf=e%100}static get throwOnInvalid(){return Af}static set throwOnInvalid(e){Af=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 If=[0,31,59,90,120,151,181,212,243,273,304,334],Of=[0,31,60,91,121,152,182,213,244,274,305,335];function on(t,e){return new St("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Ps(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 Pf(t,e,n){return n+(Ii(t)?Of:If)[e-1]}function Df(t,e){let n=Ii(t)?Of:If,i=n.findIndex(o=>o<e),r=e-n[i];return{month:i+1,day:r}}function Ds(t,e){return(t-e+7)%7+1}function uo(t,e=4,n=1){let{year:i,month:r,day:o}=t,s=Pf(i,r,o),a=Ds(Ps(i,r,o),n),u=Math.floor((s-a+14-e)/7),l;return u<1?(l=i-1,u=xi(l,e,n)):u>xi(i,e,n)?(l=i+1,u=1):l=i,{weekYear:l,weekNumber:u,weekday:a,...fo(t)}}function Uc(t,e=4,n=1){let{weekYear:i,weekNumber:r,weekday:o}=t,s=Ds(Ps(i,1,e),n),a=Qn(i),u=r*7+o-s-7+e,l;u<1?(l=i-1,u+=Qn(l)):u>a?(l=i+1,u-=Qn(i)):l=i;let{month:h,day:b}=Df(l,u);return{year:l,month:h,day:b,...fo(t)}}function Es(t){let{year:e,month:n,day:i}=t,r=Pf(e,n,i);return{year:e,ordinal:r,...fo(t)}}function Kc(t){let{year:e,ordinal:n}=t,{month:i,day:r}=Df(e,n);return{year:e,month:i,day:r,...fo(t)}}function zc(t,e){if(!de(t.localWeekday)||!de(t.localWeekNumber)||!de(t.localWeekYear)){if(!de(t.weekday)||!de(t.weekNumber)||!de(t.weekYear))throw new pn("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 Ef(t,e=4,n=1){let i=lo(t.weekYear),r=Yt(t.weekNumber,1,xi(t.weekYear,e,n)),o=Yt(t.weekday,1,7);return i?r?o?!1:on("weekday",t.weekday):on("week",t.weekNumber):on("weekYear",t.weekYear)}function Mf(t){let e=lo(t.year),n=Yt(t.ordinal,1,Qn(t.year));return e?n?!1:on("ordinal",t.ordinal):on("year",t.year)}function Vc(t){let e=lo(t.year),n=Yt(t.month,1,12),i=Yt(t.day,1,hr(t.year,t.month));return e?n?i?!1:on("day",t.day):on("month",t.month):on("year",t.year)}function Gc(t){let{hour:e,minute:n,second:i,millisecond:r}=t,o=Yt(e,0,23)||e===24&&n===0&&i===0&&r===0,s=Yt(n,0,59),a=Yt(i,0,59),u=Yt(r,0,999);return o?s?a?u?!1:on("millisecond",r):on("second",i):on("minute",n):on("hour",e)}function de(t){return typeof t>"u"}function An(t){return typeof t=="number"}function lo(t){return typeof t=="number"&&t%1===0}function bf(t){return typeof t=="string"}function jf(t){return Object.prototype.toString.call(t)==="[object Date]"}function Is(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Os(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Nf(t){return Array.isArray(t)?t:[t]}function Wc(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 Ff(t,e){return e.reduce((n,i)=>(n[i]=t[i],n),{})}function ei(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function co(t){if(t==null)return null;if(typeof t!="object")throw new wt("Week settings must be an object");if(!Yt(t.firstDay,1,7)||!Yt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Yt(e,1,7)))throw new wt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Yt(t,e,n){return lo(t)&&t>=e&&t<=n}function Gy(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 Fn(t){if(!(de(t)||t===null||t===""))return parseInt(t,10)}function ti(t){if(!(de(t)||t===null||t===""))return parseFloat(t)}function ho(t){if(!(de(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function dr(t,e,n=!1){let i=10**e;return(n?Math.trunc:Math.round)(t*i)/i}function Ii(t){return t%4===0&&(t%100!==0||t%400===0)}function Qn(t){return Ii(t)?366:365}function hr(t,e){let n=Gy(e-1,12)+1,i=t+(e-n)/12;return n===2?Ii(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function lr(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 Bf(t,e,n){return-Ds(Ps(t,1,e),n)+e-1}function xi(t,e=4,n=1){let i=Bf(t,e,n),r=Bf(t+1,e,n);return(Qn(t)-i+r)/7}function po(t){return t>99?t:t>Ce.twoDigitCutoffYear?1900+t:2e3+t}function Cs(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 Ai(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 Hc(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new wt(`Invalid unit value ${t}`);return e}function pr(t,e){let n={};for(let i in t)if(ei(t,i)){let r=t[i];if(r==null)continue;n[e(i)]=Hc(r)}return n}function Yn(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 fo(t){return Ff(t,["hour","minute","second","millisecond"])}var Wy=["January","February","March","April","May","June","July","August","September","October","November","December"],Zc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Hy=["J","F","M","A","M","J","J","A","S","O","N","D"];function Nc(t){switch(t){case"narrow":return[...Hy];case"short":return[...Zc];case"long":return[...Wy];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 Xc=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Jc=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Zy=["M","T","W","T","F","S","S"];function Fc(t){switch(t){case"narrow":return[...Zy];case"short":return[...Jc];case"long":return[...Xc];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Rc=["AM","PM"],Xy=["Before Christ","Anno Domini"],Jy=["BC","AD"],Yy=["B","A"];function qc(t){switch(t){case"narrow":return[...Yy];case"short":return[...Jy];case"long":return[...Xy];default:return null}}function Rf(t){return Rc[t.hour<12?0:1]}function qf(t,e){return Fc(e)[t.weekday-1]}function Lf(t,e){return Nc(e)[t.month-1]}function $f(t,e){return qc(e)[t.year<0?0:1]}function yf(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 b=t==="days";switch(e){case 1:return b?"tomorrow":`next ${r[t][0]}`;case-1:return b?"yesterday":`last ${r[t][0]}`;case 0:return b?"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 Uf(t,e){let n="";for(let i of t)i.literal?n+=i.val:n+=e(i.val);return n}var Qy={D:Xn,DD:Ur,DDD:Kr,DDDD:zr,t:Vr,tt:Gr,ttt:Wr,tttt:Hr,T:Zr,TT:Xr,TTT:Jr,TTTT:Yr,f:Qr,ff:to,fff:io,ffff:oo,F:eo,FF:no,FFF:ro,FFFF:so},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?Rf(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(T,I)=>i?Lf(e,T):o(I?{month:T}:{month:T,day:"numeric"},"month"),l=(T,I)=>i?qf(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},b=T=>i?$f(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 b("short");case"GG":return b("long");case"GGGGG":return b("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 Uf(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 Uf(o,r(a))}};var zf=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function gr(...t){let e=t.reduce((n,i)=>n+i.source,"");return RegExp(`^${e}$`)}function _r(...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 yr(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 Vf(...t){return(e,n)=>{let i={},r;for(r=0;r<t.length;r++)i[t[r]]=Fn(e[n+r]);return[i,null,n+r]}}var Gf=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,eb=`(?:${Gf.source}?(?:\\[(${zf.source})\\])?)?`,Yc=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Wf=RegExp(`${Yc.source}${eb}`),Qc=RegExp(`(?:T${Wf.source})?`),tb=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,nb=/(\d{4})-?W(\d\d)(?:-?(\d))?/,ib=/(\d{4})-?(\d{3})/,rb=Vf("weekYear","weekNumber","weekDay"),ob=Vf("year","ordinal"),sb=/(\d{4})-(\d\d)-(\d\d)/,Hf=RegExp(`${Yc.source} ?(?:${Gf.source}|(${zf.source}))?`),ab=RegExp(`(?: ${Hf.source})?`);function mr(t,e,n){let i=t[e];return de(i)?n:Fn(i)}function cb(t,e){return[{year:mr(t,e),month:mr(t,e+1,1),day:mr(t,e+2,1)},null,e+3]}function br(t,e){return[{hours:mr(t,e,0),minutes:mr(t,e+1,0),seconds:mr(t,e+2,0),milliseconds:ho(t[e+3])},null,e+4]}function mo(t,e){let n=!t[e]&&!t[e+1],i=Ai(t[e+1],t[e+2]),r=n?null:Ct.instance(i);return[{},r,e+3]}function go(t,e){let n=t[e]?Ft.create(t[e]):null;return[{},n,e+1]}var ub=RegExp(`^T?${Yc.source}$`),lb=/^-?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 db(t){let[e,n,i,r,o,s,a,u,l]=t,h=e[0]==="-",b=u&&u[0]==="-",v=(T,I=!1)=>T!==void 0&&(I||T&&h)?-T:T;return[{years:v(ti(n)),months:v(ti(i)),weeks:v(ti(r)),days:v(ti(o)),hours:v(ti(s)),minutes:v(ti(a)),seconds:v(ti(u),u==="-0"),milliseconds:v(ho(l),b)}]}var fb={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 eu(t,e,n,i,r,o,s){let a={year:e.length===2?po(Fn(e)):Fn(e),month:Zc.indexOf(n)+1,day:Fn(i),hour:Fn(r),minute:Fn(o)};return s&&(a.second=Fn(s)),t&&(a.weekday=t.length>3?Xc.indexOf(t)+1:Jc.indexOf(t)+1),a}var hb=/^(?:(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 pb(t){let[,e,n,i,r,o,s,a,u,l,h,b]=t,v=eu(e,r,i,n,o,s,a),T;return u?T=fb[u]:l?T=0:T=Ai(h,b),[v,new Ct(T)]}function mb(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var gb=/^(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$/,_b=/^(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$/,yb=/^(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 Kf(t){let[,e,n,i,r,o,s,a]=t;return[eu(e,r,i,n,o,s,a),Ct.utcInstance]}function bb(t){let[,e,n,i,r,o,s,a]=t;return[eu(e,a,n,i,r,o,s),Ct.utcInstance]}var wb=gr(tb,Qc),vb=gr(nb,Qc),kb=gr(ib,Qc),Tb=gr(Wf),Zf=_r(cb,br,mo,go),Cb=_r(rb,br,mo,go),Sb=_r(ob,br,mo,go),Ab=_r(br,mo,go);function Xf(t){return yr(t,[wb,Zf],[vb,Cb],[kb,Sb],[Tb,Ab])}function Jf(t){return yr(mb(t),[hb,pb])}function Yf(t){return yr(t,[gb,Kf],[_b,Kf],[yb,bb])}function Qf(t){return yr(t,[lb,db])}var xb=_r(br);function eh(t){return yr(t,[ub,xb])}var Ib=gr(sb,ab),Ob=gr(Hf),Pb=_r(br,mo,go);function th(t){return yr(t,[Ib,Zf],[Ob,Pb])}var nh="Invalid Duration",rh={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}},Db={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},...rh},sn=146097/400,wr=146097/4800,Eb={years:{quarters:4,months:12,weeks:sn/7,days:sn,hours:sn*24,minutes:sn*24*60,seconds:sn*24*60*60,milliseconds:sn*24*60*60*1e3},quarters:{months:3,weeks:sn/28,days:sn/4,hours:sn*24/4,minutes:sn*24*60/4,seconds:sn*24*60*60/4,milliseconds:sn*24*60*60*1e3/4},months:{weeks:wr/7,days:wr,hours:wr*24,minutes:wr*24*60,seconds:wr*24*60*60,milliseconds:wr*24*60*60*1e3},...rh},Oi=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Mb=Oi.slice(0).reverse();function ni(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 oh(t,e){let n=e.milliseconds??0;for(let i of Mb.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function ih(t,e){let n=oh(t,e)<0?-1:1;Oi.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),Oi.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 Bb(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?Eb:Db;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 wt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:pr(e,t.normalizeUnit),loc:xe.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(An(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new wt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[i]=Qf(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]=eh(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 wt("need to specify a reason the Duration 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 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 ur(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):nh}toHuman(e={}){if(!this.isValid)return nh;let n=Oi.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+=dr(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},we.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?oh(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 Oi)(ei(n.values,r)||ei(this.values,r))&&(i[r]=n.get(r)+this.get(r));return ni(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]=Hc(e(this.values[i],i));return ni(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...pr(e,t.normalizeUnit)};return ni(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 ni(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return ih(this.matrix,e),ni(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Bb(this.normalize().shiftToAll().toObject());return ni(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 Oi)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;An(r[s])&&(a+=r[s]);let u=Math.trunc(a);n[s]=u,i[s]=(a*1e3-u*1e3)/1e3}else An(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 ih(this.matrix,n),ni(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 ni(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 Oi)if(!n(this.values[i],e.values[i]))return!1;return!0}};var vr="Invalid Interval";function jb(t,e){return!t||!t.isValid?Rn.invalid("missing or invalid start"):!e||!e.isValid?Rn.invalid("missing or invalid end"):e<t?Rn.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 Rn=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 wt("need to specify a reason the Interval is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new vs(i);return new t({invalid:i})}static fromDateTimes(e,n){let i=kr(e),r=kr(n),o=jb(i,r);return o??new t({start:i,end:r})}static after(e,n){let i=Pe.fromDurationLike(n),r=kr(e);return t.fromDateTimes(r,r.plus(i))}static before(e,n){let i=Pe.fromDurationLike(n),r=kr(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=we.fromISO(i,n),s=o.isValid}catch{s=!1}let a,u;try{a=we.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(kr).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()})`:vr}[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=Xn,n={}){return this.isValid?At.create(this.s.loc.clone(n),e).formatInterval(this):vr}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:vr}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:vr}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:vr}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:vr}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 qn=class{static hasDST(e=Ce.defaultZone){let n=we.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 _n(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:Is(),localeWeek:Os()}}};function sh(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 Nb(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=sh(u,l);return(h-h%7)/7}],["days",sh]],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 ah(t,e,n,i){let[r,o,s,a]=Nb(t,e,n),u=e-r,l=n.filter(b=>["hours","minutes","seconds","milliseconds"].indexOf(b)>=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 tu={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"},ch={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]},Fb=tu.hanidec.replace(/[\[|\]]/g,"").split("");function uh(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(tu.hanidec)!==-1)e+=Fb.indexOf(t[n]);else for(let r in ch){let[o,s]=ch[r];i>=o&&i<=s&&(e+=i-o)}}return parseInt(e,10)}else return e}function an({numberingSystem:t},e=""){return new RegExp(`${tu[t||"latn"]}${e}`)}var Rb="missing Intl.DateTimeFormat.formatToParts support";function Se(t,e=n=>n){return{regex:t,deser:([n])=>e(uh(n))}}var qb="\xA0",fh=`[ ${qb}]`,hh=new RegExp(fh,"g");function Lb(t){return t.replace(/\./g,"\\.?").replace(hh,fh)}function lh(t){return t.replace(/\./g,"").replace(hh," ").toLowerCase()}function yn(t,e){return t===null?null:{regex:RegExp(t.map(Lb).join("|")),deser:([n])=>t.findIndex(i=>lh(n)===lh(i))+e}}function dh(t,e){return{regex:t,deser:([,n,i])=>Ai(n,i),groups:e}}function Ms(t){return{regex:t,deser:([e])=>e}}function $b(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ub(t,e){let n=an(e),i=an(e,"{2}"),r=an(e,"{3}"),o=an(e,"{4}"),s=an(e,"{6}"),a=an(e,"{1,2}"),u=an(e,"{1,3}"),l=an(e,"{1,6}"),h=an(e,"{1,9}"),b=an(e,"{2,4}"),v=an(e,"{4,6}"),T=P=>({regex:RegExp($b(P.val)),deser:([O])=>O,literal:!0}),x=(P=>{if(t.literal)return T(P);switch(P.val){case"G":return yn(e.eras("short"),0);case"GG":return yn(e.eras("long"),0);case"y":return Se(l);case"yy":return Se(b,po);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 yn(e.months("short",!0),1);case"MMMM":return yn(e.months("long",!0),1);case"L":return Se(a);case"LL":return Se(i);case"LLL":return yn(e.months("short",!1),1);case"LLLL":return yn(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 Ms(h);case"uu":return Ms(a);case"uuu":return Se(n);case"a":return yn(e.meridiems(),0);case"kkkk":return Se(o);case"kk":return Se(b,po);case"W":return Se(a);case"WW":return Se(i);case"E":case"c":return Se(n);case"EEE":return yn(e.weekdays("short",!1),1);case"EEEE":return yn(e.weekdays("long",!1),1);case"ccc":return yn(e.weekdays("short",!0),1);case"cccc":return yn(e.weekdays("long",!0),1);case"Z":case"ZZ":return dh(new RegExp(`([+-]${a.source})(?::(${i.source}))?`),2);case"ZZZ":return dh(new RegExp(`([+-]${a.source})(${i.source})?`),2);case"z":return Ms(/[a-z_+-/]{1,256}?/i);case" ":return Ms(/[^\S\n\r]/);default:return T(P)}})(t)||{invalidReason:Rb};return x.token=t,x}var Kb={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 zb(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=Kb[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Vb(t){return[`^${t.map(n=>n.regex).reduce((n,i)=>`${n}(${i.source})`,"")}$`,t]}function Gb(t,e,n){let i=t.match(e);if(i){let r={},o=1;for(let s in n)if(ei(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 Wb(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=ho(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),n,i]}var nu=null;function Hb(){return nu||(nu=we.fromMillis(1555555555555)),nu}function Zb(t,e){if(t.literal)return t;let n=At.macroTokenToFormatOpts(t.val),i=ou(n,e);return i==null||i.includes(void 0)?t:i}function iu(t,e){return Array.prototype.concat(...t.map(n=>Zb(n,e)))}function ru(t,e,n){let i=iu(At.parseFormat(n),t),r=i.map(s=>Ub(s,t)),o=r.find(s=>s.invalidReason);if(o)return{input:e,tokens:i,invalidReason:o.invalidReason};{let[s,a]=Vb(r),u=RegExp(s,"i"),[l,h]=Gb(e,u,a),[b,v,T]=h?Wb(h):[null,null,void 0];if(ei(h,"a")&&ei(h,"H"))throw new pn("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:i,regex:u,rawMatches:l,matches:h,result:b,zone:v,specificOffset:T}}}function ph(t,e,n){let{result:i,zone:r,specificOffset:o,invalidReason:s}=ru(t,e,n);return[i,r,o,s]}function ou(t,e){if(!t)return null;let i=At.create(e,t).dtFormatter(Hb()),r=i.formatToParts(),o=i.resolvedOptions();return r.map(s=>zb(s,t,o))}var su="Invalid DateTime",mh=864e13;function Bs(t){return new St("unsupported zone",`the zone "${t.name}" is not supported`)}function au(t){return t.weekData===null&&(t.weekData=uo(t.c)),t.weekData}function cu(t){return t.localWeekData===null&&(t.localWeekData=uo(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Pi(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new we({...n,...e,old:n})}function kh(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 js(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 Fs(t,e,n){return kh(lr(t),e,n)}function gh(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,hr(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=lr(o),[u,l]=kh(a,n,t.zone);return s!==0&&(u+=s,l=t.zone.offset(u)),{ts:u,o:l}}function _o(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=we.fromObject(t,{...n,zone:u,specificOffset:o});return s?l:l.setZone(a)}else return we.invalid(new St("unparsable",`the input "${r}" can't be parsed as ${i}`))}function Ns(t,e,n=!0){return t.isValid?At.create(xe.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function uu(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 _h(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 Th={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Xb={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Jb={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Ch=["year","month","day","hour","minute","second","millisecond"],Yb=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Qb=["year","ordinal","hour","minute","second","millisecond"];function ew(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 ur(t);return e}function yh(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return ew(t)}}function bh(t,e){let n=_n(e.zone,Ce.defaultZone),i=xe.fromObject(e),r=Ce.now(),o,s;if(de(t.year))o=r;else{for(let l of Ch)de(t[l])&&(t[l]=Th[l]);let a=Vc(t)||Gc(t);if(a)return we.invalid(a);let u=n.offset(r);[o,s]=Fs(t,u,n)}return new we({ts:o,zone:n,loc:i,o:s})}function wh(t,e,n){let i=de(n.round)?!0:n.round,r=(s,a)=>(s=dr(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 vh(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 we=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:Bs(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=js(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]=vh(arguments),[i,r,o,s,a,u,l]=n;return bh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static utc(){let[e,n]=vh(arguments),[i,r,o,s,a,u,l]=n;return e.zone=Ct.utcInstance,bh({year:i,month:r,day:o,hour:s,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,n={}){let i=jf(e)?e.valueOf():NaN;if(Number.isNaN(i))return t.invalid("invalid input");let r=_n(n.zone,Ce.defaultZone);return r.isValid?new t({ts:i,zone:r,loc:xe.fromObject(n)}):t.invalid(Bs(r))}static fromMillis(e,n={}){if(An(e))return e<-mh||e>mh?t.invalid("Timestamp out of range"):new t({ts:e,zone:_n(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new wt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(An(e))return new t({ts:e*1e3,zone:_n(n.zone,Ce.defaultZone),loc:xe.fromObject(n)});throw new wt("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let i=_n(n.zone,Ce.defaultZone);if(!i.isValid)return t.invalid(Bs(i));let r=xe.fromObject(n),o=pr(e,yh),{minDaysInFirstWeek:s,startOfWeek:a}=zc(o,r),u=Ce.now(),l=de(n.specificOffset)?i.offset(u):n.specificOffset,h=!de(o.ordinal),b=!de(o.year),v=!de(o.month)||!de(o.day),T=b||v,I=o.weekYear||o.weekNumber;if((T||h)&&I)throw new pn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(v&&h)throw new pn("Can't mix ordinal dates with month/day");let x=I||o.weekday&&!T,P,O,E=js(u,l);x?(P=Yb,O=Xb,E=uo(E,s,a)):h?(P=Qb,O=Jb,E=Es(E)):(P=Ch,O=Th);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?Ef(o,s,a):h?Mf(o):Vc(o),Z=$||Gc(o);if(Z)return t.invalid(Z);let H=x?Uc(o,s,a):h?Kc(o):o,[te,U]=Fs(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]=Xf(e);return _o(i,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[i,r]=Jf(e);return _o(i,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[i,r]=Yf(e);return _o(i,r,n,"HTTP",n)}static fromFormat(e,n,i={}){if(de(e)||de(n))throw new wt("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]=ph(s,e,n);return h?t.invalid(h):_o(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]=th(e);return _o(i,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new wt("need to specify a reason the DateTime is invalid");let i=e instanceof St?e:new St(e,n);if(Ce.throwOnInvalid)throw new ws(i);return new t({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let i=ou(e,xe.fromObject(n));return i?i.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return iu(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?au(this).weekYear:NaN}get weekNumber(){return this.isValid?au(this).weekNumber:NaN}get weekday(){return this.isValid?au(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?cu(this).weekday:NaN}get localWeekNumber(){return this.isValid?cu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?cu(this).weekYear:NaN}get ordinal(){return this.isValid?Es(this.c).ordinal:NaN}get monthShort(){return this.isValid?qn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?qn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?qn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?qn.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=lr(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=js(u,s),b=js(l,a);return h.hour===b.hour&&h.minute===b.minute&&h.second===b.second&&h.millisecond===b.millisecond?[Pi(this,{ts:u}),Pi(this,{ts:l})]:[this]}get isInLeapYear(){return Ii(this.year)}get daysInMonth(){return hr(this.year,this.month)}get daysInYear(){return this.isValid?Qn(this.year):NaN}get weeksInWeekYear(){return this.isValid?xi(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?xi(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=_n(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]=Fs(s,o,e)}return Pi(this,{ts:r,zone:e})}else return t.invalid(Bs(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:i}={}){let r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:i});return Pi(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=pr(e,yh),{minDaysInFirstWeek:i,startOfWeek:r}=zc(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 pn("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&s)throw new pn("Can't mix ordinal dates with month/day");let b;o?b=Uc({...uo(this.c,i,r),...n},i,r):de(n.ordinal)?(b={...this.toObject(),...n},de(n.day)&&(b.day=Math.min(hr(b.year,b.month),b.day))):b=Kc({...Es(this.c),...n});let[v,T]=Fs(b,this.o,this.zone);return Pi(this,{ts:v,o:T})}plus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e);return Pi(this,gh(this,n))}minus(e){if(!this.isValid)return this;let n=Pe.fromDurationLike(e).negate();return Pi(this,gh(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):su}toLocaleString(e=Xn,n={}){return this.isValid?At.create(this.loc.clone(n),e).formatDateTime(this):su}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=uu(this,s);return a+="T",a+=_h(this,s,n,i,r,o),a}toISODate({format:e="extended"}={}){return this.isValid?uu(this,e==="extended"):null}toISOWeekDate(){return Ns(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":"")+_h(this,s==="extended",n,e,i,o):null}toRFC2822(){return Ns(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Ns(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?uu(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")),Ns(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():su}[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=Nf(n).map(Pe.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,u=s?e:this,l=ah(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?Rn.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),wh(n,this.plus(i),{...e,numeric:"always",units:r,unit:o})}toRelativeCalendar(e={}){return this.isValid?wh(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 wt("min requires all arguments be DateTimes");return Wc(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new wt("max requires all arguments be DateTimes");return Wc(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 ru(s,e,n)}static fromStringExplain(e,n,i={}){return t.fromFormatExplain(e,n,i)}static get DATE_SHORT(){return Xn}static get DATE_MED(){return Ur}static get DATE_MED_WITH_WEEKDAY(){return Ac}static get DATE_FULL(){return Kr}static get DATE_HUGE(){return zr}static get TIME_SIMPLE(){return Vr}static get TIME_WITH_SECONDS(){return Gr}static get TIME_WITH_SHORT_OFFSET(){return Wr}static get TIME_WITH_LONG_OFFSET(){return Hr}static get TIME_24_SIMPLE(){return Zr}static get TIME_24_WITH_SECONDS(){return Xr}static get TIME_24_WITH_SHORT_OFFSET(){return Jr}static get TIME_24_WITH_LONG_OFFSET(){return Yr}static get DATETIME_SHORT(){return Qr}static get DATETIME_SHORT_WITH_SECONDS(){return eo}static get DATETIME_MED(){return to}static get DATETIME_MED_WITH_SECONDS(){return no}static get DATETIME_MED_WITH_WEEKDAY(){return xc}static get DATETIME_FULL(){return io}static get DATETIME_FULL_WITH_SECONDS(){return ro}static get DATETIME_HUGE(){return oo}static get DATETIME_HUGE_WITH_SECONDS(){return so}};function kr(t){if(we.isDateTime(t))return t;if(t&&t.valueOf&&An(t.valueOf()))return we.fromJSDate(t);if(t&&typeof t=="object")return we.fromObject(t);throw new wt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Ir=require("@mysten/sui.js/utils");var fi=require("@mysten/sui.js/utils");var Um=ge(Ro(),1),Km=require("@msafe/sui3-utils"),zm=require("@msafe/sui3-utils"),Vm=require("@msafe/sui3-utils"),Nu=require("@mysten/sui.js/bcs"),ui=require("@mysten/sui.js/utils"),Wm=require("@msafe/sui3-utils"),xr=require("@msafe/sui3-utils"),Hm=require("@msafe/sui3-utils"),Xm=require("@msafe/sui3-utils"),Ym=require("@msafe/sui3-utils"),Qm=require("@mysten/sui.js/transactions"),tg=require("@msafe/sui3-utils"),Ar=require("@msafe/sui3-utils"),Fu=require("@mysten/sui.js/bcs"),li=require("@mysten/sui.js/utils"),ng=require("@mysten/sui.js/transactions"),rg=require("@mysten/sui.js/transactions"),sg=require("@mysten/sui.js/transactions"),ug=require("@mysten/sui.js/transactions"),dg=require("@mysten/sui.js/transactions"),aa=require("@msafe/sui3-utils"),hg=require("@mysten/sui.js/transactions"),ca=require("@mysten/sui.js/utils"),IA=ge(Ro(),1),pg=require("@msafe/sui3-utils"),Ri=require("@msafe/sui3-utils"),Ru=require("@mysten/sui.js/bcs"),di=require("@mysten/sui.js/utils");var Cw=ge(ke(),1);var Bi=require("@mysten/sui.js/client"),$h=require("@mysten/sui.js/keypairs/ed25519");function Sh(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function tw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function lu(t,...e){if(!tw(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 du(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 Ah(t,e){lu(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Rs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function nw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Ls=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),bn=(t,e)=>t<<32-e|t>>>e,iw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!iw)throw new Error("Non little-endian hardware is not supported");function rw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function fu(t){if(typeof t=="string"&&(t=rw(t)),!nw(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var qs=class{clone(){return this._cloneInto()}},N2={}.toString;function xh(t){let e=i=>t().update(fu(i)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Ih(t=32){if(Rs&&typeof Rs.getRandomValues=="function")return Rs.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ow(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 $s=class extends qs{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=Ls(this.buffer)}update(e){du(this);let{view:n,buffer:i,blockLen:r}=this;e=fu(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=Ls(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){du(this),Ah(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 b=s;b<r;b++)n[b]=0;ow(i,r-8,BigInt(this.length*8),o),this.process(i,0);let a=Ls(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 b=0;b<l;b++)a.setUint32(4*b,h[b],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 sw=(t,e,n)=>t&e^~t&n,aw=(t,e,n)=>t&e^t&n^e&n,cw=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]),ii=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ri=new Uint32Array(64),hu=class extends $s{constructor(){super(64,32,8,!1),this.A=ii[0]|0,this.B=ii[1]|0,this.C=ii[2]|0,this.D=ii[3]|0,this.E=ii[4]|0,this.F=ii[5]|0,this.G=ii[6]|0,this.H=ii[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 b=0;b<16;b++,n+=4)ri[b]=e.getUint32(n,!1);for(let b=16;b<64;b++){let v=ri[b-15],T=ri[b-2],I=bn(v,7)^bn(v,18)^v>>>3,x=bn(T,17)^bn(T,19)^T>>>10;ri[b]=x+ri[b-7]+I+ri[b-16]|0}let{A:i,B:r,C:o,D:s,E:a,F:u,G:l,H:h}=this;for(let b=0;b<64;b++){let v=bn(a,6)^bn(a,11)^bn(a,25),T=h+v+sw(a,u,l)+cw[b]+ri[b]|0,x=(bn(i,2)^bn(i,13)^bn(i,22))+aw(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(){ri.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Oh=xh(()=>new hu);function Di(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function Us(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function uw(...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 lw(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 dw(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 fw(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 pu(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 b=Math.floor(h/n);if(o[u]=b,!Number.isSafeInteger(b)||b*n+s!==h)throw new Error("convertRadix: carry overflow");if(a)b?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 Ph=(t,e)=>e?Ph(e,t%e):t,Ks=(t,e)=>t+(e-Ph(t,e));function mu(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(Ks(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ks(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 hw(t){return{encode:e=>{if(!Us(e))throw new Error("radix.encode input should be Uint8Array");return pu(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(pu(e,t,2**8))}}}function pw(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ks(8,t)>32||Ks(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Us(n))throw new Error("radix2.encode input should be Uint8Array");return mu(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(mu(n,t,8,e))}}}function mw(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(n){if(!Us(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(!Us(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 yo={alphabet:lw,chain:uw,checksum:mw,convertRadix:pu,convertRadix2:mu,radix:hw,radix2:pw,join:dw,padding:fw};var gw=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function _w(t){lu(t,16,20,24,28,32)}function Dh(t,e=128){if(Sh(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return ww(Ih(e/8),t)}var yw=t=>{let e=8-t.length/4;return new Uint8Array([Oh(t)[0]>>e<<e])};function bw(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}`)}),yo.chain(yo.checksum(1,yw),yo.radix2(11,!0),yo.alphabet(t))}function ww(t,e){return _w(t),bw(e).encode(t).join(gw(e)?"\u3000":" ")}var Eh=`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 To=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=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,Fh=globalThis.AbortSignal;if(typeof Hs>"u"){Fh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},Hs=class{constructor(){e()}signal=new Fh;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 Cb=t=>!Nh.has(t),YA=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?Ir:null:null,Ir=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";Cb(te)&&(Nh.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 Ir(this.#c),n=new Ir(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 Ir(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.#F(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.#F(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#F(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 N=i&&Z.__staleWhileFetching!==void 0;return O&&(O.fetch="inflight",N&&(O.returnedStale=!0)),N?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")}#N(e,n){this.#f[n]=e,this.#u[e]=n}#I(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#N(this.#f[e],this.#u[e]),this.#N(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),Fi=require("@mysten/sui.js/utils"),Ni=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),Sb=Object.defineProperty,Ab=(t,e,n)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,On=(t,e,n)=>(Ab(t,typeof e!="symbol"?e+"":e,n),n);var Xs=443636,Js=-443636,Cu="79226673515401279992447579055",Su="4295048016",Ib=14,Ob="59543866431248",Pb="184467440737095516",Db="15793534762490258745",Eb=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 Mb(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=Mb(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||!Bb(e)||e.content.dataType!=="moveObject"))return e.content}function Bb(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 jb(t){return t.data!==void 0}function Fb(t){var e;let n=jb(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 Nb(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})},Rb=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)),qb=class{priceToSqrtPriceX64(t,e,n){return new ae.default(new F(t).mul(F.pow(10,n-e)).sqrt().mul(F.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new F(t.toString()).mul(F.pow(2,-64)).pow(2).mul(F.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<Ib;){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(Ob)),w=this.signedShiftRight(h.sub(new ae.default(Pb)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(Db)),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(F.pow(2,64))}fromX64_Decimal(t){return t.mul(F.pow(2,-64))}scaleDown(t,e){return new F(t).div(F.pow(10,e)).toString()}scaleUp(t,e){return new F(t).mul(F.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},Or=60*1e3,Lb=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 F(t.amountA),w=new F(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,w)]),I=t.txb||new Ni.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()+(t.deadline||Or),"u64"),I.object(Fi.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 F(t.amountA),T=new F(t.amountB),[I,x]=await Promise.all([this.coin.selectTradeCoins(e,u,v),this.coin.selectTradeCoins(e,l,T)]),P=t.txb||new Ni.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()+(t.deadline||Or),"u64"),P.object(Fi.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 F(t.amountA),a=new F(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 Ni.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()+(t.deadline||Or*3),"u64"),T.object(Fi.SUI_CLOCK_OBJECT_ID),T.object(o.Versioned)]}),T}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new F(t.amountA),s=new F(t.amountB),a=await this.contract.getConfig(),u=await this.getPoolTypeArguments(i),l=t.txb||new Ni.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()+(t.deadline||Or*3),"u64"),l.object(Fi.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 Ni.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()+(t.deadline||Or*3),"u64"),s.object(Fi.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 Ni.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()+(t.deadline||Or*3),"u64"),o.object(Fi.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new F((t.liquidity||new Co.default(1e8)).toString()),n=new F(t.currentSqrtPrice.toString()),i=new F(t.lowerSqrtPrice.toString()),r=new F(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 F(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 F(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 F(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),h=new F(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=Fb(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 F(t),i=new F(1).minus(new F(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},$b=(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),Ub=new xo.default(2),Kb={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=Ub.pow(new xo.default(e)).sub(Kh);return t.gt(n)}},zb=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,w=new ln.default(new F(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=Kb.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 N=t.subUnderflowU128(t.subUnderflowU128(Z,U),V),K=$.amountOwed.shln(64);I[O]=K.add(t.subUnderflowU128(N,$.growthInsideCheckpoint).mul(P)).shrn(64).toString()}return I},Vb=class extends Ao{async getOwner(t){let e=await this.getObject(t),n=Nb(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 F(this.math.scaleDown(v.toString(),u.decimals)).mul(h),x=new F(this.math.scaleDown(T.toString(),l.decimals)).mul(w),P=I.add(x),O=P.isZero()?new F(0):new F(i).mul(365).div(P).mul(100),E=new F(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 F(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 F(s[0].toString()).div(10**a.decimals).mul(i||0),h=new F(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=$b(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 F(1e6).mul(F.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 F(0):new F(u).mul(w),x=l===void 0?new F(0):new F(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=zb(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 F(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(w=w.plus(new F(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})}},Gb=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 F(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}},Wb=60*1e3,Ys=100,Hb=class extends Ao{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new F(t.amountA),a=new F(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()+Wb*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 F(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 F(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 F(100).minus(e).div(100);return new F(t).mul(r).toFixed(0)}let i=new F(100).plus(e).div(100);return new F(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new F(t).mul(n?new F(100).minus(e).div(100):new F(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()}},Lt=class{constructor(t,e){this.network=t,On(this,"pool"),On(this,"contract"),On(this,"math",new qb),On(this,"account",new Eb),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 Rb(this),this.pool=new Lb(this),this.nft=new Vb(this),this.coin=new Gb(this),this.trade=new Hb(this)}};var Zb=Object.defineProperty,vm=(t,e)=>{for(var n in e)Zb(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"},Ht={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 cr(Ku),Xb=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)),Jb=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)),Yb=async(t,e,n)=>(console.log("getRemoveLiquidityTxb txbParams: ",t),console.log("getRemoveLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.closePositionTransactionPayload(t)),Qb=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb txbParams: ",t),console.log("getDecreaseLiquidityTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Position.removeLiquidityTransactionPayload(t)),ev=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb txbParams: ",t),console.log("getClaimFeeAndMiningTxb suiClient: ",n),Dn.senderAddress=e.address,await Dn.Rewarder.collectRewarderTransactionPayload(t)),tv=class Sm extends ve{constructor(e){super(e),this.data=e}txType=Tm.TransactionType.Other;txSubType="OpenAndAddLiquidity";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 Xb(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Sm(e)}},nv=class xm extends ve{constructor(e){super(e),this.data=e}txType=Am.TransactionType.Other;txSubType="ClaimFeeAndMining";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 ev(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new xm(e)}},iv=class Om extends ve{constructor(e){super(e),this.data=e}txType=Im.TransactionType.Other;txSubType="DecreaseLiquidity";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 Qb(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Om(e)}},xt=new cr(Ku),rv=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.openPositionAddLiquidityStakePaylod(t)),ov=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.addLiquidityFixCoinPayload(t)),sv=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),av=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.removeLiquidityPayload(t)),cv=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.claimFeeAndClmmReward(t)),uv=async(t,e,n)=>{console.log("getFarmingHarvest account: ",e),console.log("getFarmingHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt);return console.log("getFarmingHarvest txbParams: ",t),await i.Farms.harvestPayload(t)},lv=async(t,e,n)=>{console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),xt.senderAddress=e.address;let i=new Rt(Ht,xt),r=Object.values(t);return console.log("getFarmingBatchHarvest params: ",r),await i.Farms.batchHarvestPayload(r)},dv=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.depositPayload(t)),fv=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),xt.senderAddress=e.address,await new Rt(Ht,xt).Farms.withdrawPayload(t)),hv=class Dm extends ve{constructor(e){super(e),this.data=e}txType=Pm.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";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 rv(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new Dm(e)}},mv=class Mm extends ve{constructor(e){super(e),this.data=e}txType=Em.TransactionType.Other;txSubType="FarmingBatchHarvest";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 lv(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Mm(e)}},pv=class jm extends ve{constructor(e){super(e),this.data=e}txType=Bm.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";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 cv(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new jm(e)}},gv=class Nm extends ve{constructor(e){super(e),this.data=e}txType=Fm.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";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 sv(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Nm(e)}},_v=class qm extends ve{constructor(e){super(e),this.data=e}txType=Rm.TransactionType.Other;txSubType="FarmingHarvest";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 uv(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new qm(e)}},yv=class $m extends ve{constructor(e){super(e),this.data=e}txType=Lm.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";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 ov(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new $m(e)}},wv=class Km extends ve{constructor(e){super(e),this.data=e}txType=Um.TransactionType.Other;txSubType="FarmingRemoveLiquidity";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 av(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Km(e)}},bv=class Vm extends ve{constructor(e){super(e),this.data=e}txType=zm.TransactionType.Other;txSubType="FarmingStake";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 dv(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new Vm(e)}},vv=class Wm extends ve{constructor(e){super(e),this.data=e}txType=Gm.TransactionType.Other;txSubType="FarmingUnstake";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 fv(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new Wm(e)}},kv=class Zm extends ve{constructor(e){super(e),this.data=e}txType=Hm.TransactionType.Other;txSubType="IncreaseLiquidity";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 Jb(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Zm(e)}},Tv=class Jm extends ve{constructor(e){super(e),this.data=e}txType=Xm.TransactionType.Other;txSubType="RemoveLiquidity";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 Yb(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Jm(e)}},En=new cr(Ku),Cv=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.convertPayload(t)),Sv=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemLockPayload(t)),Av=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemDividendV2Payload(t.venft_id,t.bonus_types,t.xTokenType)),xv=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.cancelRedeemPayload(t)),Iv=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),En.senderAddress=e.address,await new Rt(Ht,En).XCetusModule.redeemPayload(t)),Ov=class Qm extends ve{constructor(e){super(e),this.data=e}txType=Ym.TransactionType.Other;txSubType="xCETUSCancelRedeem";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 xv(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Qm(e)}},Pv=class tp extends ve{constructor(e){super(e),this.data=e}txType=ep.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";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 tp(e)}},Dv=class ip extends ve{constructor(e){super(e),this.data=e}txType=np.TransactionType.Other;txSubType="xCETUSConvert";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 Cv(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new ip(e)}},Ev=class op extends ve{constructor(e){super(e),this.data=e}txType=rp.TransactionType.Other;txSubType="xCETUSRedeem";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 Iv(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new op(e)}},Mv=class ap extends ve{constructor(e){super(e),this.data=e}txType=sp.TransactionType.Other;txSubType="xCETUSRedeemLock";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 ap(e)}},Bv=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:km.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let i;switch(t.txSubType){case"OpenAndAddLiquidity":i=tv.fromData(t.intentionData);break;case"IncreaseLiquidity":i=kv.fromData(t.intentionData);break;case"DecreaseLiquidity":i=iv.fromData(t.intentionData);break;case"RemoveLiquidity":i=Tv.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=nv.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=hv.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=yv.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=gv.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=wv.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=pv.fromData(t.intentionData);break;case"FarmingHarvest":i=_v.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=mv.fromData(t.intentionData);break;case"FarmingStake":i=bv.fromData(t.intentionData);break;case"FarmingUnstake":i=vv.fromData(t.intentionData);break;case"xCETUSConvert":i=Dv.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=Mv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=Pv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=Ov.fromData(t.intentionData);break;case"xCETUSRedeem":i=Ev.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",i),i.build({suiClient:e,account:n})}},up={};vm(up,{contractId:()=>fp,default:()=>jv,feeObjId:()=>pp,roleObjId:()=>hp,status:()=>dp,transaction:()=>lp,upgradeCapObjId:()=>gp,vaultObjId:()=>mp});var lp="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",dp="success",fp="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",hp="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",mp="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",pp="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",gp="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",jv={transaction:lp,status:dp,contractId:fp,roleObjId:hp,vaultObjId:mp,feeObjId:pp,upgradeCapObjId:gp},_p={};vm(_p,{contractId:()=>bp,default:()=>Fv,feeObjId:()=>Tp,roleObjId:()=>vp,status:()=>wp,transaction:()=>yp,upgradeCapObjId:()=>Cp,vaultObjId:()=>kp});var yp="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",wp="success",bp="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",vp="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",kp="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Tp="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Cp="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fv={transaction:yp,status:wp,contractId:bp,roleObjId:vp,vaultObjId:kp,feeObjId:Tp,upgradeCapObjId:Cp},Nv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Rv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",qv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Lv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$v="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Uv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Kv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",zv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Xh=up,Jh=_p,Vv=new Map([["dev",{env:"dev",rpc:{url:Nv},backend:{url:$v},contract:Xh}],["stg",{env:"stg",rpc:{url:Rv},backend:{url:Uv},contract:Xh}],["prev",{env:"prev",rpc:{url:qv},backend:{url:Kv},contract:Jh}],["prod",{env:"prod",rpc:{url:Lv},backend:{url:zv},contract:Jh}]]);function Gv(t,e){let n=Vv.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}},Wv=class extends nn{constructor(){super(11,"Backend is not specified")}},Hv=class extends nn{constructor(){super(1,"Wallet not connected")}},Ou=class extends nn{constructor(t,e){super(10,t,{context:e})}},Zv=class $i{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 $i.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await zn.default.post(`${this.apiURL}/stream`,{sender:e,...n});return $i.parseResponseData(i)}async getStreamHistory(e){let n=await zn.default.post(`${this.apiURL}/stream-events`,e),i=$i.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 $i.parseResponseData(n)}async getAllRecipients(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return $i.parseResponseData(i)}async getAllSenders(e,n){let i=await zn.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return $i.parseResponseData(i)}},Ap=class xp{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Sp.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Zv(e.backend.url))}static new(e,n){let i=Gv(e,n);return new xp(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Wv;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 Hv;return this.signer}async walletAddress(){return this.wallet.address()}},Yh=50n,Pu=10000n,Xv=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 Ip{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 Ip(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})}},Jv=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,Op.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()}},tn=class extends nn{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},Pp={groupId:"string",name:"string"},Yv=64;function Qv(t){return Dp(t),zu.bcs.ser(Pp,t).toString("base64")}function Bu(t){let e=zu.bcs.de(Pp,t,"base64");return Dp(e),e}function Dp(t){if(!nm(t.name))throw new tn("Invalid metadata: Name contains unknown character");if(!nm(t.groupId))throw new tn("Invalid metadata: Group ID contains unknown character");if(t.name.length>Yv)throw new tn("Invalid metadata: Name exceed max length 64")}function nm(t){return/^[\x00-\x7F]+$/.test(t)}function Ep(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 Mp="txn.gas";function e1(){return yf()}var ju=class Bp{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:Qv({name:e.name,groupId:e1()}),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=Bp.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Yh,denominator:Pu},claimFeePercent:{numerator:Xv,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===Mp?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return Ep(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 Jv(i).getU64()}get wallet(){return this.globals.wallet}},t1="0x0000000000000000000000000000000000000000000000000000000000000006",jp=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(Fu.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(Fu.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(t1)}},Fp=class di extends jp{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 jt extends jp{constructor(e,n){super(jt.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:jt.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:jt.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:jt.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:jt.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:jt.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${jt.ModuleName}::${jt.MethodName.claim_stream_by_proxy}`}},Np=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Fp(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 n1(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 i1=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)}},Rp=class{constructor(t){this.requester=t,this.pager=new i1(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]}},r1=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}},o1=25;async function s1(t,e,n,i="0x2::sui::SUI",r=o1){let o=new a1(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 r1(i,n,s);return a}var a1=class extends Rp{constructor(t,e,n,i){super(new c1(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},c1=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}}},u1=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})}},l1=class extends nn{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},d1=(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 u1;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===d1?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 l1(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)}}}},f1=class extends nn{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},h1=1e3,m1=class{constructor(t){this.globals=t,this.coinMetaHelper=new p1(t.suiClient),this.createStreamHelper=new Np(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new f1(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 tn("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 tn("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 tn("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 tn("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new tn("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<h1)throw new tn("Interval shall be at least 1 second","interval",t.interval)}},p1=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})}},g1=25;async function am(t,e,n){let i=new qp(e),r=new Lp(t,i,n);return await n1(r)}var qp=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]}},Lp=class extends Rp{constructor(t,e,n){super(new _1(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},_1=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||g1,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()}}},y1=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 tn("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=>{w1(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 w1(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 Nu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await um.newIncoming(e);return new Nu(n,e.pageSize)}static async newOutgoing(e){let n=await um.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}},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 qp(i.flat().map(s=>s.streamId));this.objectIter=new Lp(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=C1(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 k1(this.globals,e[0].streamId,this.objectIter);return this.current++,$p(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await T1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,v1(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 $p(t,e){if(e===void 0)return!0;let n=b1(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 b1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function v1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{$p(i,e)&&(n=!0)}),n}async function k1(t,e,n){let i=await Up(n,e);return Vu.fromObjectData(t,e,i)}async function T1(t,e,n){let i=[];for(;i.length<e.length;){let r=await Up(n,e[i.length]);i.push(r)}return y1.newFromObjectResponse(t,e,i)}async function Up(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 C1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),sender:zp(t?.sender)}}function S1(t){return{status:Gu(t?.status),coinType:Kp(t?.coinType),recipient:zp(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 tn("Unknown stream filtered status")}}function Kp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeStructTag)(e)):void 0:(0,gi.normalizeStructTag)(t)}function zp(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,gi.normalizeSuiAddress)(e)):void 0:(0,gi.normalizeSuiAddress)(t)}var x1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},I1=class{constructor(t){this.account=t}async address(){return this.account.address}},O1=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(Ep(t.coinType,Ki.SUI_TYPE_ARG))return{primaryCoin:Mp};if(t.amount<=0)throw new tn("Invalid coin request","coinAmount",t.amount);let e=await s1(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)}}},P1=class{globals;helper;constructor(t,e){this.globals=Ap.new(t,e),this.helper=new m1(this.globals)}connectSingleWallet(t){let e=new O1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new x1(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,Ki.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,Ki.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new Np(this.globals)}},D1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Vp.default)(this.data))}},Mo=class extends D1{application="mpay";getClient(t,e){let n=new P1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new I1(e)),n}},fm=class extends Mo{constructor(t){super(t),this.data=t}txType=cp.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=Gp.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=Wp.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=Hp.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Zp=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]}},E1=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 Zp(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 tn("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 Fp(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 E1(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 Zp(t,this.txb)}},gm=class extends Mo{constructor(t){super(t),this.data=t}txType=Xp.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)}},B1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=Ap.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})}},j1=class Yp extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Jp.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Yp(e)}},F1=class eg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Qp.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new eg(e)}},N1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=ng.TransactionBlock.from(this.data.content);if(!(0,tg.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new ig(e)}},R1=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=j1.fromData(t.intentionData);break;case Er.TransactionSubTypes.assets.object.send:i=F1.fromData(t.intentionData);break;case Er.TransactionSubTypes.others.plain:i=N1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},q1={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=q1,L1=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 $1(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 U1(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 K1(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 z1=class sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new og.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;K1(n,r,o,s,a)}),n}static fromData(e){return new sg(e)}},V1=class cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new ag.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 U1(i,r,n)}static fromData(e){return new cg(e)}};async function lg(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var G1=class dg 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 ug.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 lg(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 dg(e)}},W1=class hg 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 fg.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 lg(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 hg(e)}},H1=class pg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new mg.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 $1(i,r,n)}static fromData(e){return new pg(e)}},Z1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new L1(e).decode();return{txType:rg.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=G1.fromData(t.intentionData);break;case"EntryBorrow":i=V1.fromData(t.intentionData);break;case"EntryRepay":i=W1.fromData(t.intentionData);break;case"EntryWithdraw":i=H1.fromData(t.intentionData);break;case"ClaimReward":i=z1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},X1="msafe-plain-tx",J1=da.TransactionSubTypes.others.plain,Y1=class{application;constructor(){this.application=X1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:da.TransactionType.Other,txSubType:J1,intentionData:{content:(0,fa.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=gg.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}},Q1=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}},Li={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},ek=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.isCollectRewardLTransaction())return this.decodeCollectRewardLiquidity();if(this.isBurnTransaction())return this.decodeBurnLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect`)}isCollectRewardLTransaction(){return!!this.getMoveCallTransaction(`${Li.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${Li.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.decodeInputBool(5),s=this.helper.decodeInputU32(6),a=this.helper.decodeInputBool(7);return{txType:Ui.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:o?-r:r,tickUpper:a?-s:s}}}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:Ui.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:Ui.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:Ui.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),i=this.collectRewardHelper.map(r=>r.decodeInputU64(5));return{txType:Ui.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:i,nft:e}}}decodeBurnLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:Ui.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!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new bm(t,this.txb)}get collectRewardHelper(){console.log(this.transactions,"this.transactions");let t=this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${Li.PackageId}::position_manager::collect_reward`);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]}},tk=class yg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:u,tickUpper:l,deadline:h,txb:w}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,deadline:h,txb:w})}static fromData(e){return new yg(e)}},nk=class wg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(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 wg(e)}},ik=class bg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,deadline:u,txb:l}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,deadline:u,txb:l})}static fromData(e){return new bg(e)}},rk=class vg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,deadline:a,txb:u}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,deadline:a,txb:u})}static fromData(e){return new vg(e)}},ok=class kg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(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,deadline:T,txb:I}=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,deadline:T,txb:I})}static fromData(e){return new kg(e)}},sk=class Tg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,decreaseLiquidity:l,deadline:h,txb:w}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,deadline:h,txb:w})}static fromData(e){return new Tg(e)}},ak=class Cg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:u,deadline:l,txb:h}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,deadline:l,txb:h})}static fromData(e){return new Cg(e)}},ck=class Sg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Lt(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,deadline:T,txb:I}=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,deadline:T,txb:I})}static fromData(e){return new Sg(e)}},uk=class{application="turbos";async deserialize(t){let{transactionBlock:e,account:n}=t,i=new ek(e).decode(n.address);return{txType:_g.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=ok.fromData(t.intentionData);break;case"AddLiquidity":r=tk.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ak.fromData(t.intentionData);break;case"DecreaseLiquidity":r=sk.fromData(t.intentionData);break;case"RemoveLiquidity":r=ck.fromData(t.intentionData);break;case"CollectFee":r=ik.fromData(t.intentionData);break;case"CollectReward":r=rk.fromData(t.intentionData);break;case"Burn":r=nk.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},ha=new Q1([new R1,new Z1,new B1,new Y1,new Bv,new uk]);var Ae=require("@msafe/sui3-utils"),tl=require("@mysten/sui.js/transactions"),ba=require("@mysten/sui.js/utils");var Ag=require("@mysten/sui.js/transactions"),lk=1000n,dk=120n,fk=100n,hk={multiplier:{numerator:dk,denominator:fk}};var ma=class{constructor(e){this.globals=e}async simulate(e,n=hk){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=lk*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 Ag.TransactionBlock.from(e.serialize())}};var Wu=require("buffer");function pa(t){return Wu.Buffer.from(t,"utf-8")}function mk(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 xg=require("@msafe/sui3-utils"),Ig=require("@mysten/sui.js/cryptography"),Og=require("@mysten/sui.js/multisig");var pk="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=gk(s,e);if(a)return a}}function gk(t,e){let n=(0,Ig.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new Og.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=xg.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 _k(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 Pg=25;async function Dg(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 Eg(t,e,n){let i=new Qu(t,e,n);return await Dg(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||Pg,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 zi=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 Eg(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}`);console.log("\u{1F680} ~ MSafeAccount ~ simulateBuildTransaction ~ intention:",e);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 Mg=require("@msafe/sui3-utils"),Bg=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,Mg.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,Bg.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 $g=require("@mysten/sui.js/client");var No=require("@msafe/sui3-utils"),Fo=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?No.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??No.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:No.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Fo.default.get(i,n)}catch(r){throw Ca.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Fo.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}=Fo.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(Fo.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 jg=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(jg||{}),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",Fg="https://sui-dev.m-safe.link",Ng="http://13.56.226.148:81",Rg="https://sui-preview.m-safe.link",qg="https://sui.m-safe.link",Lg=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:Fg},syncingURL:Ng,network:"sui:testnet"}],["prev",{suiClient:{url:nl},backend:{url:Rg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:nl},backend:{url:qg},syncingURL:"",network:"sui:mainnet"}]]);function ol(t,e){let n=Lg.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 $g.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 zi(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new zi(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Gi(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 Wi(this.globals)}get Invitation(){return new $o(this.globals)}get Report(){return new ka(this.globals)}async walletAddress(){return this.wallet.address()}};
2053
+ `);var bo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Bh=new Set,gu=typeof process=="object"&&process?process:{},jh=(t,e,n,i)=>{typeof gu.emitWarning=="function"?gu.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},zs=globalThis.AbortController,Mh=globalThis.AbortSignal;if(typeof zs>"u"){Mh=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},zs=class{constructor(){e()}signal=new Mh;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=gu.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,jh("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 vw=t=>!Bh.has(t),Q2=Symbol("type"),oi=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Nh=t=>oi(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Tr:null:null,Tr=class extends Array{constructor(e){super(e),this.fill(0)}},_u=class t{heap;length;static#c=!1;static create(e){let n=Nh(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]}},Vs=class t{#c;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#m;#r;#n;#e;#u;#f;#a;#o;#g;#s;#k;#T;#_;#b;#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.#w(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.#m}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:u,dispose:l,disposeAfter:h,noDisposeOnSet:b,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&&!oi(n))throw new TypeError("max option must be a nonnegative integer");let H=n?Nh(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=_u.create(n),this.#i=0,this.#m=0,typeof l=="function"&&(this.#y=l),typeof h=="function"?(this.#p=h,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!b,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!B,this.allowStaleOnFetchAbort=!!$,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#d!==0&&!oi(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!oi(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=oi(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!oi(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";vw(te)&&(Bh.add(te),jh("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 Tr(this.#c),n=new Tr(this.#c);this.#_=e,this.#T=n,this.#B=(o,s,a=bo.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?bo.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=bo.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 Tr(this.#c);this.#m=0,this.#k=e,this.#x=n=>{this.#m-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!oi(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!oi(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.#m>o;)this.#D(!0)}this.#m+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#m)}}#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};*#w({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.#w())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.#w()){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.#w())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.#w()){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.#w()){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.#w({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=bo.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=bo.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 b=this.#i===0?void 0:this.#r.get(e);if(b===void 0)b=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#D(!1):this.#i,this.#n[b]=e,this.#e[b]=n,this.#r.set(e,b),this.#u[this.#o]=b,this.#f[b]=this.#o,this.#o=b,this.#i++,this.#P(b,h,u),u&&(u.set="add"),l=!1;else{this.#I(b);let v=this.#e[b];if(n!==v){if(this.#S&&this.#t(v)?v.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(v,e,"set"),this.#l&&this.#s?.push([v,e,"set"])),this.#x(b),this.#P(b,h,u),this.#e[b]=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(b,r,o),u&&this.#C(u,b)),!s&&this.#l&&this.#s){let v=this.#s,T;for(;T=v?.shift();)this.#p?.(...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.#p?.(...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.#b||this.#l)&&(this.#b&&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 zs,{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 b(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),b(x)),b=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 zs}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:b=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:b,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.#b||this.#l)&&(this.#b&&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.#p?.(...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.#b&&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.#m=0,this.#i=0,this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#p?.(...n)}}};var ae=ge(ke(),1);var Zs=ge(Fh(),1),Ei=require("@mysten/sui.js/utils"),Mi=require("@mysten/sui.js/transactions");var wo=ge(ke(),1),Vh=require("@mysten/sui.js/transactions"),Vt=ge(ke(),1);var si=ge(ke(),1),cn=ge(ke(),1);var To=ge(ke(),1);var Gh=require("@mysten/sui.js/utils"),Xs=require("@mysten/sui.js/transactions"),Js=require("@mysten/sui.js/utils");var Tu=ge(ke(),1),kw=Object.defineProperty,Tw=(t,e,n)=>e in t?kw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,xn=(t,e,n)=>(Tw(t,typeof e!="symbol"?e+"":e,n),n);var Gs=443636,Ws=-443636,wu="79226673515401279992447579055",vu="4295048016",Sw=14,Aw="59543866431248",xw="184467440737095516",Iw="15793534762490258745",Ow=class{generateMnemonic(t=24){return Dh(Eh,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return $h.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}'`}},ko=class{constructor(t){this.sdk=t,xn(this,"_lru"),xn(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new Vs({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 Pw(t){if("reference"in t)return t.reference;let e=Cu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Kh(t)}function Qs(t){var e,n;return"objectId"in t?t.objectId:(n=(e=Pw(t))==null?void 0:e.objectId)!=null?n:zh(t)}function In(t){var e;return"fields"in t?t.fields:(e=Uh(t))==null?void 0:e.fields}function Uh(t){let e="data"in t?Cu(t):t;if(!(!e||!Dw(e)||e.content.dataType!=="moveObject"))return e.content}function Dw(t){return t.content!==void 0}function Cu(t){return t.data}function Kh(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 zh(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Ew(t){return t.data!==void 0}function Mw(t){var e;let n=Ew(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":Ys(t):n?.type}function Ys(t){var e;return(e=Uh(t))==null?void 0:e.type}function Bw(t){var e;return(e=Cu(t))==null?void 0:e.owner}var vo=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})},jw=class extends ko{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 vo(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=In(i),o=Qs(i),s=Ys(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())}},Rh=new ae.default(2).pow(new ae.default(128)),Nw=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(wu))||t.lt(new ae.default(vu)))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<Sw;){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(Aw)),b=this.signedShiftRight(h.sub(new ae.default(xw)),64,128).toNumber(),v=this.signedShiftRight(h.add(new ae.default(Iw)),64,128).toNumber();return b==v?b:this.tickIndexToSqrtPriceX64(v).lte(t)?v:b}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 Zs.default.toNumber(Zs.default.asIntN(e,Zs.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Rh).sub(e).mod(Rh)}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)}},ku=(t,e)=>{let n=Qs(t);if(Kh(t))throw new Error(`${e}(${n}) had been deleted`);if(zh(t))throw new Error(`${e}(${n}) is not found`);return!0},Cr=60*1e3,Fw=class extends ko{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 vo(this.provider,n,{showContent:!0})).map(a=>In(a).value.fields.pool_id);if(!o.length)return[];let s=await vo(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>In(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 ku(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),b=new N(t.amountB),[v,T]=await Promise.all([this.coin.selectTradeCoins(n,a,h),this.coin.selectTradeCoins(n,u,b)]),I=t.txb||new Mi.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,b):[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(b.toFixed(0),"u64"),I.pure(this.getMinimumAmountBySlippage(h,s),"u64"),I.pure(this.getMinimumAmountBySlippage(b,s),"u64"),I.pure(n,"address"),I.pure(Date.now()+(t.deadline||Cr),"u64"),I.object(Ei.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,b]=await Promise.all([this.coin.getMetadata(u),this.coin.getMetadata(l)]);if(!h||!b)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 Mi.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()+(t.deadline||Cr),"u64"),P.object(Ei.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,[b,v]=await Promise.all([this.coin.selectTradeCoins(i,l,s),this.coin.selectTradeCoins(i,h,a)]),T=t.txb||new Mi.TransactionBlock,I=b.length>0?this.coin.convertTradeCoins(T,b,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()+(t.deadline||Cr*3),"u64"),T.object(Ei.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 Mi.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 wo.default(r).toString(),"u128"),l.pure(this.getMinimumAmountBySlippage(o,e),"u64"),l.pure(this.getMinimumAmountBySlippage(s,e),"u64"),l.pure(Date.now()+(t.deadline||Cr*3),"u64"),l.object(Ei.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 Mi.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()+(t.deadline||Cr*3),"u64"),s.object(Ei.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 Mi.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()+(t.deadline||Cr*3),"u64"),o.object(Ei.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new N((t.liquidity||new wo.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 wo.default(o[a]().toString()),new wo.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=In(t),n=Qs(t),i=Mw(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)}},Rw=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new si.default(n.fee_growth_global_a),a=new si.default(i.fee_growth_inside_a),u=new si.default(i.tokens_owed_a),l=new si.default(n.fee_growth_global_b),h=new si.default(i.fee_growth_inside_b),b=new si.default(i.tokens_owed_b),v=new si.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:b.add(te).toString()}},qh=new To.default(0),Lh=new To.default(1),qw=new To.default(2),Lw={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(qh))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt(qh)?s.add(Lh):s},isOverLimit(t,e){let n=qw.pow(new To.default(e)).sub(Lh);return t.gt(n)}},$w=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:u,tickUpperDetail:l,timeStampInSeconds:h}=e,b=new cn.default(new N(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),T=(h??new cn.default(Date.now()).div(new cn.default(1e3))).sub(new cn.default(b)),I=[],x=new cn.default(s.liquidity),P=new cn.default(a.liquidity);for(let O=0;O<3;++O){let E=s.reward_infos[O],B={emissionsPerSecondX64:new cn.default(E?E.fields.emissions_per_second:"0"),growthGlobalX64:new cn.default(E?E.fields.growth_global:"0")},$={growthInsideCheckpoint:new cn.default((i=(n=a.reward_infos[O])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new cn.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=Lw.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 cn.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},Uw=class extends ko{async getOwner(t){let e=await this.getObject(t),n=Bw(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 In(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return In(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return ku(e,"position"),In(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=In(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new Vt.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Vt.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new Vt.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Vt.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new Vt.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,b]=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||!b||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(b),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 Vt.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 Vt.default(0),r=new Vt.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 Vt.default(t.sqrt_price),h=this.getTokenAFromLiquidity(r,l,a),b=this.getTokenBFromLiquidity(r,s,l);return{minTokenA:this.adjustForSlippage(h),minTokenB:this.adjustForSlippage(b)}}let u=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(u)}}adjustForSlippage(t){let e={numerator:new Vt.default(0),denominator:new Vt.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 Vh.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 Vt.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 Vt.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:b,...v}=u;return{fees:a.unclaimedFees.toString(),rewards:b.toString(),total:l.plus(b).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=Rw(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),b=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(b,s.decimals)&&(b="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(b),x=l===void 0?new N(0):new N(l).mul(v);return{unclaimedFees:I.plus(x),scaledFeeOwedA:b,scaledFeeOwedB:v,...h}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=$w(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 b=new N(0);return n.reward_infos.some((v,T)=>{let I=h[T];return I?(b=b.plus(new N(I).mul(a[T])),!1):(b=b.plus(1),!0)}),{unclaimedRewards:b,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 ku(e,"nft"),e})}},Kw=class extends ko{isSUI(t){return(0,Gh.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}},zw=60*1e3,Hs=100,Vw=class extends ko{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:b,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 Xs.TransactionBlock;return I.moveCall({target:`${u.PackageId}::swap_router::${b}`,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()+zw*3,"u64"),I.object(Js.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(b=>b.pool),u=await vo(this.provider,a,{showContent:!0}),l=new Xs.TransactionBlock;u.map(async b=>{let v=In(b),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||Hs),P=I+v.tick_spacing*(o||Hs);x=x<Ws?Ws:x,P=P>Gs?Gs:P;let O=this.pool.parsePoolType(Ys(b));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(Js.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(b=>b.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 vo(this.provider,Array.from(new Set(s)),{showContent:!0}),u=new Xs.TransactionBlock;e.forEach(async h=>{let b=a.find(O=>Qs(O)===h.pool),v=In(b),T=this.math.bitsToNumber(v.tick_current_index.fields.bits),I=T-v.tick_spacing*(r||Hs),x=T+v.tick_spacing*(r||Hs);I=I<Ws?Ws:I,x=x>Gs?Gs:x;let P=this.pool.parsePoolType(Ys(b));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(Js.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 Tu.BN(vu))?vu:s.gt(new Tu.BN(wu))?wu:s.toString()}},Rt=class{constructor(t,e){this.network=t,xn(this,"pool"),xn(this,"contract"),xn(this,"math",new Nw),xn(this,"account",new Ow),xn(this,"coin"),xn(this,"nft"),xn(this,"trade"),xn(this,"provider"),this.provider=e?e instanceof Bi.SuiClient?e:new Bi.SuiClient(e):new Bi.SuiClient({url:t==="mainnet"?(0,Bi.getFullnodeUrl)("mainnet"):(0,Bi.getFullnodeUrl)("testnet")}),this.contract=new jw(this),this.pool=new Fw(this),this.nft=new Uw(this),this.coin=new Kw(this),this.trade=new Vw(this)}};var Gw=Object.defineProperty,yp=(t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})},ve=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,vp.default)(this.data))}},Ww={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"},Hw={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"}]}}},Zw={fullRpcUrl:"https://fullnode.testnet.sui.io/",simulationAccount:{address:"0xcd0247d0b67e53dde69b285e7a748e3dc390e8a5244eb9dd9c5c53d95e4cf0aa"},cetus_config:{package_id:"0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca",published_at:"0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca",config:{coin_list_id:"0x257eb2ba592a5480bba0a97d05338fab17cc3283f8df6998a0e12e4ab9b84478",launchpad_pools_id:"0xdc3a7bd66a6dcff73c77c866e87d73826e446e9171f34e1c1b656377314f94da",clmm_pools_id:"0x26c85500f5dd2983bf35123918a144de24e18936d0b234ef2b49fbb2d3d6307d",admin_cap_id:"0x1a496f6c67668eb2c27c99e07e1d61754715c1acf86dac45020c886ac601edb8",global_config_id:"0xe1f3db327e75f7ec30585fa52241edf66f7e359ef550b533f89aa1528dd1be52",coin_list_handle:"0x3204350fc603609c91675e07b8f9ac0999b9607d83845086321fca7f469de235",launchpad_pools_handle:"0xae67ff87c34aceea4d28107f9c6c62e297a111e9f8e70b9abbc2f4c9f5ec20fd",clmm_pools_handle:"0xd28736923703342b4752f5ed8c2f2a5c0cb2336c30e1fed42b387234ce8408ec"}},clmm_pool:{package_id:"0x0868b71c0cba55bf0faf6c40df8c179c67a4d0ba0e79965b68b3d72d7dfbf666",published_at:"0x1c29d658882c40eeb39a8bb8fe58f71a216a918acb3e3eb3b47d24efd07257f2",config:{pools_id:"0xc090b101978bd6370def2666b7a31d7d07704f84e833e108a969eda86150e8cf",global_config_id:"0x6f4149091a5aea0e818e7243a13adcfb403842d670b9a2089de058512620687a",global_vault_id:"0xf3114a74d54cbe56b3e68f9306661c043ede8c6615f0351b0c3a93ce895e1699",admin_cap_id:""}},integrate:{package_id:"0x8627c5cdcd8b63bc3daa09a6ab7ed81a829a90cafce6003ae13372d611fbb1a9",published_at:"0xf1a5d0c5b0593e41d13f9684ca91365bdfe54a98836c1d33c90e361a031fac74",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6",published_at:"0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6"},aggregatorUrl:"https://api-sui.devcetus.com/router",swapCountUrl:"https://api-sui.devcetus.com/v2/sui/swap/count"},Xw={launchpad:{package_id:"0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335",published_at:"0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335",config:{pools_id:"0xccc10403ab3da4ae943847908e0e674fe1fdab81c6383e4c6dcd0eea0edade3d",admin_cap_id:"0x8a72713049dbcfc40902ff209dc5e6066fe455d152baa235957c84d7a3b875ed",config_cap_id:"0x16492b4252b01debb60f8a825334020d7fdb9d895b52f8139c98618de30817fc"}},ido:{package_id:"0x1352bf18ef20458f7cc773852d4a90b240015a6a54479dda3a1debfc500bf044",published_at:"0xbd09a0889ea9970b821512428bab3e2fd01e16809a90a325cd3b3d3573eab6a4",config:{pools_id:"0x346bee25ab4d15bcfa9484ef5ebd4d7c94eb665ebaa745ff4094936a7f59a8b1",admin_cap_id:"0xc1bb19a24d3bb65dfd4f3835637b63347c223c67cde4b0888f1a857974f33cbb",package_version_id:"0x3ccf1b38e3259e638b980d4e6b49eac8c5aa94d3cb2ace5e75f0a551c8e67e5e"}},xcetus:{package_id:"0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966",published_at:"0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966",config:{xcetus_manager_id:"0x3be34cbad122c8b100ed7157d762b9610e68b3c65734e08bc3c3baf857da807d",lock_manager_id:"0x7c67e805182e3fecd098bd68a6b06c317f28f8c6249bd771e07904a10b424e60",lock_handle_id:"0xc5f3bbfefe9a45c13da7a34bc72cac122ee45d633690476a8ac56bd2c4e78c86"}},xcetus_dividends:{package_id:"0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828",published_at:"0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828",config:{dividend_manager_id:"0x13b7facb704fae1d199ff0038b8acabc253415a77d142b39189dee97d457e442",dividend_admin_id:"0x5eb78463007422d4130b21f61c180bcd190819b7792f56e00a61df3b8fb928ef",dividend_settle_id:"0x495095e13a170ff494d242ae44ac2c7453011ca6c33cff27498010105e10e4b4"}},cetus_faucet:{package_id:"0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7",published_at:"0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7"},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:"0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9",published_at:"0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9",config:{admin_cap_id:"0x9b2d6f5be2650d16d27cd630c4539a76d7793970343ed3cbb023e13f1637c07c",vaults_manager_id:"0xc0a1a937df08880e395d85014ff40c74f13abe7a53abdbffea36f51adaaaf79e",vaults_pool_handle:"0x3ab02203de753de9c8198cc0ce7594dc960878f2c34c5c5a4b7742082241860a"}},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:"0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0",published_at:"0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0",config:{global_config_id:"0x5082c7a5ee9a758025d7b0a5e8aa08b56625c7cd535b8909d2b7993991e229cc",rewarder_manager_id:"0xe789e092dbd9dceadbe89350c4761a6f2e11647aab97f09746a01b151926cc0e",rewarder_manager_handle:"0x7e7dd42392b5d82564dc9ad5093a111c5f0598cc9f806cff257d7dacb71f7837",admin_cap_id:"0x4ec248bca2d1fc05f39fd7491ab490464a46d128624caa4d3c2a66d957ef40b0"}},haedal:{package_id:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472",published_at:"0x9dac9c5770e5f930d2223ff68782958701acfaee9337e8d8363978ce7670dffb",config:{support_stakings:[{staking_id:"0x6e384d2da5b040b27f973155e25bbe4beb0ad5ca8ee0a36e20dff356094c9fc0",from_coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",to_coin_type:"0xac2afb455cbcdc2ff1a2e9bbb8aa4ccb4506a544b08c740886892a5cdf92f472::hasui::HASUI"}]}}},Or=(t,e)=>{let n=t==="sui:mainnet"?Ww:Zw,i=new sf(n);return i.senderAddress=e.address,i},Gt=(t,e)=>{let n=Or(t,e),i=t==="sui:mainnet"?Hw:Xw;return new pf(i,n)},Jw=async(t,e,n)=>await Or(n,e).Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg),Yw=async(t,e,n)=>await Or(n,e).Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg),Qw=async(t,e,n)=>await Or(n,e).Position.closePositionTransactionPayload(t),ev=async(t,e,n)=>await Or(n,e).Position.removeLiquidityTransactionPayload(t),tv=async(t,e,n)=>await Or(n,e).Rewarder.collectRewarderTransactionPayload(t),nv=class kp extends ve{constructor(e){super(e),this.data=e}txType=wp.TransactionType.Other;txSubType="OpenAndAddLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Jw(r,n,i)}static fromData(e){return new kp(e)}},iv=class Cp extends ve{constructor(e){super(e),this.data=e}txType=Tp.TransactionType.Other;txSubType="ClaimFeeAndMining";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await tv(r,n,i)}static fromData(e){return new Cp(e)}},rv=class Ap extends ve{constructor(e){super(e),this.data=e}txType=Sp.TransactionType.Other;txSubType="DecreaseLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await ev(r,n,i)}static fromData(e){return new Ap(e)}},ov=async(t,e,n)=>await Gt(n,e).Farms.openPositionAddLiquidityStakePaylod(t),sv=async(t,e,n)=>await Gt(n,e).Farms.addLiquidityFixCoinPayload(t),av=async(t,e,n)=>await Gt(n,e).Farms.removeLiquidityPayload(t),cv=async(t,e,n)=>await Gt(n,e).Farms.removeLiquidityPayload(t),uv=async(t,e,n)=>await Gt(n,e).Farms.claimFeeAndClmmReward(t),lv=async(t,e,n)=>{let i=Gt(n,e);return console.log("getFarmingHarvest txbParams: ",t),await i.Farms.harvestPayload(t)},dv=async(t,e,n)=>{let i=Gt(n,e),r=Object.values(t);return console.log("getFarmingBatchHarvest params: ",r),await i.Farms.batchHarvestPayload(r)},fv=async(t,e,n)=>await Gt(n,e).Farms.depositPayload(t),hv=async(t,e,n)=>await Gt(n,e).Farms.withdrawPayload(t),pv=class Ip extends ve{constructor(e){super(e),this.data=e}txType=xp.TransactionType.Other;txSubType="FarmingOpenAndAddLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await ov(r,n,i)}static fromData(e){return new Ip(e)}},mv=class Pp extends ve{constructor(e){super(e),this.data=e}txType=Op.TransactionType.Other;txSubType="FarmingBatchHarvest";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await dv(r,n,i)}static fromData(e){return new Pp(e)}},gv=class Ep extends ve{constructor(e){super(e),this.data=e}txType=Dp.TransactionType.Other;txSubType="FarmingClaimFeeAndReward";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await uv(r,n,i)}static fromData(e){return new Ep(e)}},_v=class Bp extends ve{constructor(e){super(e),this.data=e}txType=Mp.TransactionType.Other;txSubType="FarmingDecreaseLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await av(r,n,i)}static fromData(e){return new Bp(e)}},yv=class Np extends ve{constructor(e){super(e),this.data=e}txType=jp.TransactionType.Other;txSubType="FarmingHarvest";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await lv(r,n,i)}static fromData(e){return new Np(e)}},bv=class Rp extends ve{constructor(e){super(e),this.data=e}txType=Fp.TransactionType.Other;txSubType="FarmingIncreaseLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await sv(r,n,i)}static fromData(e){return new Rp(e)}},wv=class Lp extends ve{constructor(e){super(e),this.data=e}txType=qp.TransactionType.Other;txSubType="FarmingRemoveLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await cv(r,n,i)}static fromData(e){return new Lp(e)}},vv=class Up extends ve{constructor(e){super(e),this.data=e}txType=$p.TransactionType.Other;txSubType="FarmingStake";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await fv(r,n,i)}static fromData(e){return new Up(e)}},kv=class zp extends ve{constructor(e){super(e),this.data=e}txType=Kp.TransactionType.Other;txSubType="FarmingUnstake";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await hv(r,n,i)}static fromData(e){return new zp(e)}},Tv=class Gp extends ve{constructor(e){super(e),this.data=e}txType=Vp.TransactionType.Other;txSubType="IncreaseLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Yw(r,n,i)}static fromData(e){return new Gp(e)}},Cv=class Hp extends ve{constructor(e){super(e),this.data=e}txType=Wp.TransactionType.Other;txSubType="RemoveLiquidity";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Qw(r,n,i)}static fromData(e){return new Hp(e)}},Sv=async(t,e,n)=>await Gt(n,e).XCetusModule.convertPayload(t),Av=async(t,e,n)=>await Gt(n,e).XCetusModule.redeemLockPayload(t),xv=async(t,e,n)=>await Gt(n,e).XCetusModule.redeemDividendV2Payload(t.venft_id,t.bonus_types,t.xTokenType),Iv=async(t,e,n)=>await Gt(n,e).XCetusModule.cancelRedeemPayload(t),Ov=async(t,e,n)=>await Gt(n,e).XCetusModule.redeemPayload(t),Pv=class Xp extends ve{constructor(e){super(e),this.data=e}txType=Zp.TransactionType.Other;txSubType="xCETUSCancelRedeem";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Iv(r,n,i)}static fromData(e){return new Xp(e)}},Dv=class Yp extends ve{constructor(e){super(e),this.data=e}txType=Jp.TransactionType.Other;txSubType="xCETUSClaimStakingRwewards";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await xv(r,n,i)}static fromData(e){return new Yp(e)}},Ev=class em extends ve{constructor(e){super(e),this.data=e}txType=Qp.TransactionType.Other;txSubType="xCETUSConvert";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Sv(r,n,i)}static fromData(e){return new em(e)}},Mv=class nm extends ve{constructor(e){super(e),this.data=e}txType=tm.TransactionType.Other;txSubType="xCETUSRedeem";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Ov(r,n,i)}static fromData(e){return new nm(e)}},Bv=class rm extends ve{constructor(e){super(e),this.data=e}txType=im.TransactionType.Other;txSubType="xCETUSRedeemLock";async build(e){let{account:n,network:i}=e,{txbParams:r}=this.data;return await Av(r,n,i)}static fromData(e){return new rm(e)}},jv=class{application="cetus";async deserialize(t){console.log("Cetus helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:bp.TransactionType.Other,txSubType:n,intentionData:{txbParams:{...e},action:n}}}async build(t){let{suiClient:e,account:n,network:i}=t;console.log("helper build input: ",t),console.log("helper build input.intentionData: ",t.intentionData),console.log("helper build input.intentionData JSON: ",JSON.stringify(t.intentionData));let r;switch(t.txSubType){case"OpenAndAddLiquidity":r=nv.fromData(t.intentionData);break;case"IncreaseLiquidity":r=Tv.fromData(t.intentionData);break;case"DecreaseLiquidity":r=rv.fromData(t.intentionData);break;case"RemoveLiquidity":r=Cv.fromData(t.intentionData);break;case"ClaimFeeAndMining":r=iv.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":r=pv.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":r=bv.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":r=_v.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":r=wv.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":r=gv.fromData(t.intentionData);break;case"FarmingHarvest":r=yv.fromData(t.intentionData);break;case"FarmingBatchHarvest":r=mv.fromData(t.intentionData);break;case"FarmingStake":r=vv.fromData(t.intentionData);break;case"FarmingUnstake":r=kv.fromData(t.intentionData);break;case"xCETUSConvert":r=Ev.fromData(t.intentionData);break;case"xCETUSRedeemLock":r=Bv.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":r=Dv.fromData(t.intentionData);break;case"xCETUSCancelRedeem":r=Pv.fromData(t.intentionData);break;case"xCETUSRedeem":r=Mv.fromData(t.intentionData);break;default:throw new Error("not implemented")}return console.log("helper build intention: ",r),console.log("helper build account: ",n),console.log("helper build network: ",i),r.build({suiClient:e,account:n,network:i})}},sm={};yp(sm,{contractId:()=>um,default:()=>Nv,feeObjId:()=>fm,roleObjId:()=>lm,status:()=>cm,transaction:()=>am,upgradeCapObjId:()=>hm,vaultObjId:()=>dm});var am="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",cm="success",um="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",lm="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",dm="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",fm="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",hm="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Nv={transaction:am,status:cm,contractId:um,roleObjId:lm,vaultObjId:dm,feeObjId:fm,upgradeCapObjId:hm},pm={};yp(pm,{contractId:()=>_m,default:()=>Fv,feeObjId:()=>wm,roleObjId:()=>ym,status:()=>gm,transaction:()=>mm,upgradeCapObjId:()=>vm,vaultObjId:()=>bm});var mm="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",gm="success",_m="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",ym="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",bm="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",wm="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",vm="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Fv={transaction:mm,status:gm,contractId:_m,roleObjId:ym,vaultObjId:bm,feeObjId:wm,upgradeCapObjId:vm},Rv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",qv="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Lv="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$v="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Uv="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Kv="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",zv="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Vv="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",Wh=sm,Hh=pm,Gv=new Map([["dev",{env:"dev",rpc:{url:Rv},backend:{url:Uv},contract:Wh}],["stg",{env:"stg",rpc:{url:qv},backend:{url:Kv},contract:Wh}],["prev",{env:"prev",rpc:{url:Lv},backend:{url:zv},contract:Hh}],["prod",{env:"prod",rpc:{url:$v},backend:{url:Vv},contract:Hh}]]);function Wv(t,e){let n=Gv.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 en=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}},Hv=class extends en{constructor(){super(11,"Backend is not specified")}},Zv=class extends en{constructor(){super(1,"Wallet not connected")}},Su=class extends en{constructor(t,e){super(10,t,{context:e})}},Xv=class Fi{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof Ln.AxiosError)throw new Su(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Su(e.data.code)}throw new Su(e.status.toString())}async getIncomingStreams(e,n){let i=await Ln.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return Fi.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await Ln.default.post(`${this.apiURL}/stream`,{sender:e,...n});return Fi.parseResponseData(i)}async getStreamHistory(e){let n=await Ln.default.post(`${this.apiURL}/stream-events`,e),i=Fi.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 Ln.default.post(`${this.apiURL}/stream-info`,{address:e});return Fi.parseResponseData(n)}async getAllRecipients(e,n){let i=await Ln.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return Fi.parseResponseData(i)}async getAllSenders(e,n){let i=await Ln.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return Fi.parseResponseData(i)}},Tm=class Cm{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new km.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new Xv(e.backend.url))}static new(e,n){let i=Wv(e,n);return new Cm(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Hv;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 Zv;return this.signer}async walletAddress(){return this.wallet.address()}},Zh=50n,Au=10000n,Jv=25n,Xh=100000000n,ji=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Jh=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},ra=class Sm{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 Sm(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}},Yh=class extends en{constructor(t,e){super(3,t,{context:e})}},Yv=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 Yh("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,Am.normalizeSuiAddress)(Ou.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new Yh("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Ou.Buffer.from(n).readBigInt64LE()}},Qt=class extends en{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},xm={groupId:"string",name:"string"},Qv=64;function e1(t){return Im(t),qu.bcs.ser(xm,t).toString("base64")}function Pu(t){let e=qu.bcs.de(xm,t,"base64");return Im(e),e}function Im(t){if(!Qh(t.name))throw new Qt("Invalid metadata: Name contains unknown character");if(!Qh(t.groupId))throw new Qt("Invalid metadata: Group ID contains unknown character");if(t.name.length>Qv)throw new Qt("Invalid metadata: Name exceed max length 64")}function Qh(t){return/^[\x00-\x7F]+$/.test(t)}function Om(t,e){return(0,xo.normalizeStructTag)(t)===(0,xo.normalizeStructTag)(e)}function Sr(t,e){return(0,xo.normalizeStructTag)(t)===(0,xo.normalizeStructTag)(e)}var Pm="txn.gas";function t1(){return mf()}var Du=class Dm{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:e1({name:e.name,groupId:t1()}),coinType:(0,Ao.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 Iu.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),b=this.getStreamFeeLocal(h),[v]=n.splitCoins(s,[n.pure(h+b,"u64")]),[T]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new ra(v),flatFeeCoin:new ra(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=Dm.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:Zh,denominator:Au},claimFeePercent:{numerator:Jv,denominator:Au},flatFeePerStream:Xh}}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===Pm?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return Om(i,Ao.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Ao.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 Xh}getStreamFeeLocal(e){return e*Zh/Au}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new Iu.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new Yv(i).getU64()}get wallet(){return this.globals.wallet}},n1="0x0000000000000000000000000000000000000000000000000000000000000006",Em=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(Eu.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof Jh?i.moveArgs(t):i instanceof ji?i.moveArg(t):i instanceof ra?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(Eu.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof Jh?r.moveArgs(t):r instanceof ji?r.moveArg(t):r instanceof ra?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new ji(t):t}vaultObject(){return new ji(this.config.vaultObjId)}roleObject(){return new ji(this.config.roleObjId)}feeObject(){return new ji(this.config.feeObjId)}clockObject(){return new ji(n1)}},Mm=class ai extends Em{constructor(e,n){super(ai.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:ai.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:ai.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:ai.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:ai.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:ai.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:ai.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},sa=class Bt extends Em{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}`}},Bm=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Mm(e,t),this.streamContract=new sa(e,t)}feeContract;streamContract;async createStreams(t){let e=Du.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Du(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new Co.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new Co.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new Co.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new Co.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},wn=class extends en{constructor(t,e={}){super(0,t,e)}};async function i1(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 r1=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)}},jm=class{constructor(t){this.requester=t,this.pager=new r1(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]}},o1=class extends en{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}},s1=25;async function a1(t,e,n,i="0x2::sui::SUI",r=s1){let o=new c1(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 o1(i,n,s);return a}var c1=class extends jm{constructor(t,e,n,i){super(new u1(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},u1=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new wn("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}}},l1=class extends en{constructor(){super(7,"Connected wallet is not creator")}},ep=class extends en{constructor(){super(8,"Connected wallet is not recipient")}},tp=class extends en{constructor(t,e){super(6,t,{context:e})}},d1=class extends en{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},f1=(1n<<64n)-1n,oa=1e3;function np(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/oa);return we.fromMillis(n*oa)}function ip(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/oa);return Pe.fromMillis(n*oa)}var Lu=class ci{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new sa(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await ci.fetchStreamData(e,n);return new ci(e,n,i)}static fromObjectData(e,n,i){let r=ci.parseRawStreamData(n,i);return new ci(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 ci.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new wn("Object Id does not align");this.rawData=ci.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 l1;let e=new So.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new ep;let e=new So.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 ep;let n=new So.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new So.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,Io.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 ip(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Pu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Pu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return np(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return ip(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:np((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===f1?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=we.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 ci.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new d1(e):new tp(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new tp("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Io.parseStructTag)(i.type),o=(0,Io.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)}}}},h1=class extends en{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},p1=1e3,m1=class{constructor(t){this.globals=t,this.coinMetaHelper=new g1(t.suiClient),this.createStreamHelper=new Bm(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new h1(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 Qt("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 Qt("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 Qt("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,Ir.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,Ir.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 Qt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Qt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<p1)throw new Qt("Interval shall be at least 1 second","interval",t.interval)}},g1=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ir.normalizeStructTag)(t||Ir.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}},xu=class extends en{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}},_1=25;async function rp(t,e,n){let i=new Nm(e),r=new Fm(t,i,n);return await i1(r)}var Nm=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]}},Fm=class extends jm{constructor(t,e,n){super(new y1(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},y1=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||_1,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()}}},b1=class ea{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new xu("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new Qt("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await rp(e.suiClient,n);return i.forEach(r=>{if(!r)throw new wn("stream group object data undefined")}),ea.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await ea.parseGroupStreams(e,n,i);return new ea(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{w1(i,o)||(r=!1)}),r}async refresh(){let e=await rp(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)=>Lu.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new xu("Not same group ID");if(!this.checkStreamGroup(r))throw new xu("Not same stream settings");return r}};function w1(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 op=class Mu{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await sp.newIncoming(e);return new Mu(n,e.pageSize)}static async newOutgoing(e){let n=await sp.newOutgoing(e);return new Mu(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}},sp=class Bu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await ap.newIncomingQuery(e);return new Bu(n)}static async newOutgoing(e){let n=await ap.newOutgoingQuery(e);return new Bu(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 wn("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new wn("No more results");return e}},ap=class ju{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new Nm(i.flat().map(s=>s.streamId));this.objectIter=new Fm(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=S1(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,fi.normalizeSuiAddress)(s.recipient)===(0,fi.normalizeSuiAddress)(i)),o=cp(r);return new ju(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=A1(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=cp(r);return new ju(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 T1(this.globals,e[0].streamId,this.objectIter);return this.current++,Rm(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await C1(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,k1(n,this.query)?n:this.doNextRequest()}throw new wn("Stream group with no stream")}};function cp(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)=>we.fromISO(i[0].createDate).toMillis()-we.fromISO(n[0].createDate).toMillis())}function Rm(t,e){if(e===void 0)return!0;let n=v1(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 v1(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function k1(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{Rm(i,e)&&(n=!0)}),n}async function T1(t,e,n){let i=await qm(n,e);return Lu.fromObjectData(t,e,i)}async function C1(t,e,n){let i=[];for(;i.length<e.length;){let r=await qm(n,e[i.length]);i.push(r)}return b1.newFromObjectResponse(t,e,i)}async function qm(t,e){if(!await t.hasNext())throw new wn("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new wn("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new wn("stream id not aligned");return n}function S1(t){return{status:$u(t?.status),coinType:Lm(t?.coinType),sender:$m(t?.sender)}}function A1(t){return{status:$u(t?.status),coinType:Lm(t?.coinType),recipient:$m(t?.recipient)}}function $u(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=$u(n);return!e||e===i?i:"all"},void 0):x1(t)}function x1(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Qt("Unknown stream filtered status")}}function Lm(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,fi.normalizeStructTag)(e)):void 0:(0,fi.normalizeStructTag)(t)}function $m(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,fi.normalizeSuiAddress)(e)):void 0:(0,fi.normalizeSuiAddress)(t)}var I1=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},O1=class{constructor(t){this.account=t}async address(){return this.account.address}},P1=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(Om(t.coinType,qi.SUI_TYPE_ARG))return{primaryCoin:Pm};if(t.amount<=0)throw new Qt("Invalid coin request","coinAmount",t.amount);let e=await a1(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new wn("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=Tm.new(t,e),this.helper=new m1(this.globals)}connectSingleWallet(t){let e=new P1(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new I1(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return Lu.new(this.globals,t)}async getIncomingStreams(t,e=10){return op.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return op.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,qi.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,qi.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,qi.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new Bm(this.globals)}},E1=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Um.default)(this.data))}},Oo=class extends E1{application="mpay";getClient(t,e){let n=new D1(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new O1(e)),n}},up=class extends Oo{constructor(t){super(t),this.data=t}txType=om.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},lp=class extends Oo{constructor(t){super(t),this.data=t}txType=Km.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},dp=class extends Oo{constructor(t){super(t),this.data=t}txType=zm.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},fp=class extends Oo{constructor(t){super(t),this.data=t}txType=Vm.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Gm=class ta{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return ta.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return ta.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,ui.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 ta.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 Nu.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,ui.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ui.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,ui.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ui.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 Nu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,ui.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},M1=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"&&Sr(e.target,this.contract.createStreamTarget));if(t.length===0)throw new wn("No create stream transactions");return t.map(e=>new Gm(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Pu(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),b=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:u,amountPerEpoch:l,cancelable:h,coinType:b}}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 Qt("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 sa(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Mm(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Du(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]}},B1=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new sa(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"&&Sr(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Sr(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Sr(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Sr(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Sr(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new M1(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 Gm(t,this.txb)}},hp=class extends Oo{constructor(t){super(t),this.data=t}txType=Wm.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)}},j1=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=Tm.new(e==="sui:mainnet"?"prod":"dev"),r=new B1(i,n).decode(),o;switch(r.type){case"CreateStream":o=new fp(r.info);break;case"SetAutoClaim":o=new hp({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new dp({streamId:r.streamId});break;case"ClaimByProxy":o=new lp({streamId:r.streamId});break;case"Cancel":o=new up({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 fp(e);break;case"Claim":n=new dp(e);break;case"ClaimByProxy":n=new lp(e);break;case"SetAutoClaim":n=new hp(e);break;case"Cancel":n=new up(e);break;default:throw new Error("not implemented")}return n.build({...t})}},N1=class Zm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Hm.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Zm(e)}},F1=class Jm extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Xm.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new Jm(e)}},R1=class eg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=Qm.TransactionBlock.from(this.data.content);if(!(0,Ym.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new eg(e)}},q1=class{application;constructor(){this.application=xr.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 xr.TransactionSubTypes.assets.coin.send:i=N1.fromData(t.intentionData);break;case xr.TransactionSubTypes.assets.object.send:i=F1.fromData(t.intentionData);break;case xr.TransactionSubTypes.others.plain:i=R1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},L1={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=L1,$1=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 pp(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:Ar.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:Ar.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:Ar.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:Ar.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:Ar.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 pp(t,this.txb)}},pp=class na{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return na.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return na.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,li.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 na.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 Fu.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,li.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,li.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,li.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,li.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 Fu.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,li.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function mp(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 U1(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 gp(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 z1(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 V1=class ig extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new ng.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;z1(n,r,o,s,a)}),n}static fromData(e){return new ig(e)}},G1=class og extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new rg.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 og(e)}};async function ag(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var W1=class cg 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 sg.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return mp(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 ag(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 mp(s,a,s.object(l),o)}static fromData(e){return new cg(e)}},H1=class lg 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 ug.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[h]=s.splitCoins(s.gas,[o]);return gp(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 ag(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 gp(s,a,s.object(l),o)}static fromData(e){return new lg(e)}},Z1=class fg extends ve{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new dg.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 U1(i,r,n)}static fromData(e){return new fg(e)}},X1=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new $1(e).decode();return{txType:tg.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=W1.fromData(t.intentionData);break;case"EntryBorrow":i=G1.fromData(t.intentionData);break;case"EntryRepay":i=H1.fromData(t.intentionData);break;case"EntryWithdraw":i=Z1.fromData(t.intentionData);break;case"ClaimReward":i=V1.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},J1="msafe-plain-tx",Y1=aa.TransactionSubTypes.others.plain,Q1=class{application;constructor(){this.application=J1}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:aa.TransactionType.Other,txSubType:Y1,intentionData:{content:(0,ca.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=hg.TransactionBlock.from((0,ca.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}},ek=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}},Ni={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},tk=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.isCollectRewardLTransaction())return this.decodeCollectRewardLiquidity();if(this.isBurnTransaction())return this.decodeBurnLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ni.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ni.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ni.PackageId}::position_manager::decrease_liquidity`)}isCollectFeeLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Ni.PackageId}::position_manager::collect`)}isCollectRewardLTransaction(){return!!this.getMoveCallTransaction(`${Ni.PackageId}::position_manager::collect_reward`)}isBurnTransaction(){return!!this.getMoveCallTransaction(`${Ni.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.decodeInputBool(5),s=this.helper.decodeInputU32(6),a=this.helper.decodeInputBool(7);return{txType:Ri.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:o?-r:r,tickUpper:a?-s:s}}}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:Ri.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:Ri.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:Ri.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),i=this.collectRewardHelper.map(r=>r.decodeInputU64(5));return{txType:Ri.TransactionType.Other,type:"CollectReward",intentionData:{pool:t,address:n,rewardAmounts:i,nft:e}}}decodeBurnLiquidity(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeSharedObjectId(2);return{txType:Ri.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!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new _p(t,this.txb)}get collectRewardHelper(){console.log(this.transactions,"this.transactions");let t=this.transactions.filter(e=>e.kind==="MoveCall"&&e.target===`${Ni.PackageId}::position_manager::collect_reward`);return console.log(t,this.txb,"this.txb"),t.map(e=>new _p(e,this.txb))}},_p=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)}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,di.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 Ru.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,di.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,di.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,di.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,di.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 Ru.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,di.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},nk=class mg 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,deadline:h,txb:b}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:u,tickUpper:l,deadline:h,txb:b})}static fromData(e){return new mg(e)}},ik=class gg 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 gg(e)}},rk=class _g 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,deadline:u,txb:l}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,deadline:u,txb:l})}static fromData(e){return new _g(e)}},ok=class yg 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,deadline:a,txb:u}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,deadline:a,txb:u})}static fromData(e){return new yg(e)}},sk=class bg 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:b,amountB:v,deadline:T,txb:I}=this.data;return n.pool.createPool({fee:i,amountA:b,amountB:v,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:u,coinTypeA:l,coinTypeB:h,deadline:T,txb:I})}static fromData(e){return new bg(e)}},ak=class wg 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,deadline:h,txb:b}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,decreaseLiquidity:l,deadline:h,txb:b})}static fromData(e){return new wg(e)}},ck=class vg 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,deadline:l,txb:h}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:u,deadline:l,txb:h})}static fromData(e){return new vg(e)}},uk=class kg 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:b,rewardAmounts:v,deadline:T,txb:I}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:l,nft:u,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:h,collectAmountB:b,rewardAmounts:v,deadline:T,txb:I})}static fromData(e){return new kg(e)}},lk=class{application="turbos";async deserialize(t){let{transactionBlock:e,account:n}=t,i=new tk(e).decode(n.address);return{txType:pg.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=sk.fromData(t.intentionData);break;case"AddLiquidity":r=nk.fromData(t.intentionData);break;case"IncreaseLiquidity":r=ck.fromData(t.intentionData);break;case"DecreaseLiquidity":r=ak.fromData(t.intentionData);break;case"RemoveLiquidity":r=uk.fromData(t.intentionData);break;case"CollectFee":r=rk.fromData(t.intentionData);break;case"CollectReward":r=ok.fromData(t.intentionData);break;case"Burn":r=ik.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},ua=new ek([new q1,new X1,new j1,new Q1,new jv,new lk]);var Ae=require("@msafe/sui3-utils"),Xu=require("@mysten/sui.js/transactions"),ga=require("@mysten/sui.js/utils");var Tg=require("@mysten/sui.js/transactions"),dk=1000n,fk=120n,hk=100n,pk={multiplier:{numerator:fk,denominator:hk}};var la=class{constructor(e){this.globals=e}async simulate(e,n=pk){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=dk*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 Tg.TransactionBlock.from(e.serialize())}};var Uu=require("buffer");function da(t){return Uu.Buffer.from(t,"utf-8")}function mk(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function fa(t){return Uint8Array.from(Uu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var pa=require("@mysten/sui.js/verify");var hi=require("@mysten/sui.js/utils");var ha=require("@mysten/sui.js/utils"),Po=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,ha.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}},Ku=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Do=class t{static isCoin(e){return e?(0,ha.normalizeStructTag)(e).match(Ku)!=null:!1}static getCoinType(e){let[,n]=(0,ha.normalizeStructTag)(e).match(Ku)??[];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 $n=class{static normalizeSuiAddress(e){return(0,hi.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,hi.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,hi.normalizeSuiAddress)(e)===(0,hi.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,hi.normalizeStructTag)(e)===(0,hi.normalizeStructTag)(n)}static isCoinObjectType(e){return Do.isCoin(e)}};function zu(t,e){return t.startsWith(e)?t:e+t}var Vu=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,pa.verifyTransactionBlock)(e.message,e.signature):(0,pa.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=da(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return $n.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=da(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 Cg=require("@msafe/sui3-utils"),Sg=require("@mysten/sui.js/cryptography"),Ag=require("@mysten/sui.js/multisig");var gk="0x2::sui::SUI";async function Gu(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=_k(s,e);if(a)return a}}function _k(t,e){let n=(0,Sg.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new Ag.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if($n.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if($n.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=Cg.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return $n.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function yk(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 xg=25;async function Ig(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 Wu=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)}},ma=class{constructor(e){this.requester=e;this.pager=new Wu(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 Og(t,e,n){let i=new Hu(t,e,n);return await Ig(i)}var Hu=class extends ma{constructor(n,i,r){super(new Zu(n,i,r));this.provider=n;this.owner=i;this.options=r}},Zu=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||xg,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 Li=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 Po(this.suiClient),this.simulator=new la(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,ga.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return Og(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=ua.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=ua.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,ga.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=Xu.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=fa(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 Xu.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=ua.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);console.log("\u{1F680} ~ MSafeAccount ~ simulateBuildTransaction ~ intention:",e);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:fa(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"),Dg=require("@mysten/sui.js/utils");var _a=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,Dg.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 Gu(this.globals.suiClient,e)}};var ya=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Rg=require("@mysten/sui.js/client");var Mo=require("@msafe/sui3-utils"),Eo=ge(require("axios"),1);var ba=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?Mo.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??Mo.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:Mo.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Eo.default.get(i,n)}catch(r){throw wa.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Eo.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw wa.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${zu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=Eo.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]}},wa=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(Eo.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 Eg=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Eg||{}),va="https://fullnode.testnet.sui.io",Ju="https://fullnode.mainnet.sui.io",Yu="http://127.0.0.1:3000",Qu="http://127.0.0.1:3001",Mg="https://sui-dev.m-safe.link",Bg="http://13.56.226.148:81",jg="https://sui-preview.m-safe.link",Ng="https://sui.m-safe.link",Fg=new Map([["unit",{suiClient:{url:va},backend:{url:Yu},syncingURL:Qu,network:"sui:testnet"}],["local",{suiClient:{url:va},backend:{url:Yu},syncingURL:Qu,network:"sui:testnet"}],["dev",{suiClient:{url:va},backend:{url:Mg},syncingURL:Bg,network:"sui:testnet"}],["prev",{suiClient:{url:Ju},backend:{url:jg},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Ju},backend:{url:Ng},syncingURL:"",network:"sui:mainnet"}]]);function el(t,e){let n=Fg.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 Bo=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=el(e,n),r=new Rg.SuiClient(i.suiClient),o=new ba(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 ka=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await Bo.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=Ta.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:Ta.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Li(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new Li(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Ui(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _a(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 Ki(this.globals)}get Invitation(){return new Fo(this.globals)}get Report(){return new ya(this.globals)}async walletAddress(){return this.wallet.address()}};
2054
2054
  /*! Bundled license information:
2055
2055
 
2056
2056
  @syntsugar/cc-graph/dist/index.umd.js: