@msafe/sui3-sdk 0.0.49-pre-d867e6d.0 → 0.0.49-pre-e5b1664.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 +6 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +6 -21
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,8 @@
|
|
|
1
|
-
"use strict";var Dv=Object.create;var dc=Object.defineProperty;var Bv=Object.getOwnPropertyDescriptor;var Mv=Object.getOwnPropertyNames;var jv=Object.getPrototypeOf,Nv=Object.prototype.hasOwnProperty;var Rv=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wp=(t,e)=>{for(var n in e)dc(t,n,{get:e[n],enumerable:!0})},yp=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Mv(e))!Nv.call(t,r)&&r!==n&&dc(t,r,{get:()=>e[r],enumerable:!(i=Bv(e,r))||i.enumerable});return t};var Pe=(t,e,n)=>(n=t!=null?Dv(jv(t)):{},yp(e||!t||!t.__esModule?dc(n,"default",{value:t,enumerable:!0}):n,t)),bp=t=>yp(dc({},"__esModule",{value:!0}),t);var Tp=Ue((m4,kp)=>{"use strict";kp.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Ap=Ue((g4,Cp)=>{"use strict";var Vl=Tp();Cp.exports=(t,e={})=>{if(!Vl(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:n}=e,i=[],r=[],o=a=>{let c=i.indexOf(a);if(c!==-1)return r[c];let u=[];return i.push(a),r.push(u),u.push(...a.map(d=>Array.isArray(d)?o(d):Vl(d)?s(d):d)),u},s=a=>{let c=i.indexOf(a);if(c!==-1)return r[c];let u={},d=Object.keys(a).sort(e.compare);i.push(a),r.push(u);for(let h of d){let _=a[h],C;n&&Array.isArray(_)?C=o(_):C=n&&Vl(_)?s(_):_,Object.defineProperty(u,h,{...Object.getOwnPropertyDescriptor(a,h),value:C})}return u};return Array.isArray(t)?n?o(t):t.slice():s(t)}});var xp=Ue((_4,Ip)=>{"use strict";var Fv=Object.prototype.toString;Ip.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 Gv(e)?"generatorfunction":"function";if(qv(e))return"array";if(Kv(e))return"buffer";if(Vv(e))return"arguments";if(Uv(e))return"date";if(Lv(e))return"error";if($v(e))return"regexp";switch(Sp(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(zv(e))return"generator";switch(n=Fv.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 Sp(t){return typeof t.constructor=="function"?t.constructor.name:null}function qv(t){return Array.isArray?Array.isArray(t):t instanceof Array}function Lv(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function Uv(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function $v(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function Gv(t,e){return Sp(t)==="GeneratorFunction"}function zv(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function Vv(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 Kv(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var hc=Ue((w4,Dp)=>{"use strict";var Wv=Ap(),Kl=xp(),Op=(t,e)=>!e||Kl(e)!=="array"?!1:e.indexOf(t)>-1,Hv=(t,e)=>Wv(t,{compare:e}),Pp=(t,e)=>{let n=e&&e.compareFunction;return t.slice().sort(n)};function Ep(t,e){let n=e&&e.compareFunction,i=Hv(t,n);return Object.keys(t).forEach(function(r){let o=i[r],s=Kl(o);if(s==="object"){(!e||!Op(r,e.ignoreObjectAtKeys))&&(i[r]=Ep(o,e));return}s==="array"&&(!e||!Op(r,e.ignoreArrayAtKeys))&&(i[r]=Pp(o,e))}),i}var Cs=(t,e)=>{let n=Kl(t);return Cs[n]?Cs[n](t,e):t};Cs.array=Pp;Cs.object=Ep;Dp.exports=Cs});var Ee=Ue((Bp,Wl)=>{"use strict";(function(t,e){"use strict";function n(N,l){if(!N)throw new Error(l||"Assertion failed")}function i(N,l){N.super_=l;var f=function(){};f.prototype=l.prototype,N.prototype=new f,N.prototype.constructor=N}function r(N,l,f){if(r.isBN(N))return N;this.negative=0,this.words=null,this.length=0,this.red=null,N!==null&&((l==="le"||l==="be")&&(f=l,l=10),this._init(N||0,l||10,f||"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(l){return l instanceof r?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===r.wordSize&&Array.isArray(l.words)},r.max=function(l,f){return l.cmp(f)>0?l:f},r.min=function(l,f){return l.cmp(f)<0?l:f},r.prototype._init=function(l,f,w){if(typeof l=="number")return this._initNumber(l,f,w);if(typeof l=="object")return this._initArray(l,f,w);f==="hex"&&(f=16),n(f===(f|0)&&f>=2&&f<=36),l=l.toString().replace(/\s+/g,"");var k=0;l[0]==="-"&&(k++,this.negative=1),k<l.length&&(f===16?this._parseHex(l,k,w):(this._parseBase(l,f,k),w==="le"&&this._initArray(this.toArray(),f,w)))},r.prototype._initNumber=function(l,f,w){l<0&&(this.negative=1,l=-l),l<67108864?(this.words=[l&67108863],this.length=1):l<4503599627370496?(this.words=[l&67108863,l/67108864&67108863],this.length=2):(n(l<9007199254740992),this.words=[l&67108863,l/67108864&67108863,1],this.length=3),w==="le"&&this._initArray(this.toArray(),f,w)},r.prototype._initArray=function(l,f,w){if(n(typeof l.length=="number"),l.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(l.length/3),this.words=new Array(this.length);for(var k=0;k<this.length;k++)this.words[k]=0;var g,m,b=0;if(w==="be")for(k=l.length-1,g=0;k>=0;k-=3)m=l[k]|l[k-1]<<8|l[k-2]<<16,this.words[g]|=m<<b&67108863,this.words[g+1]=m>>>26-b&67108863,b+=24,b>=26&&(b-=26,g++);else if(w==="le")for(k=0,g=0;k<l.length;k+=3)m=l[k]|l[k+1]<<8|l[k+2]<<16,this.words[g]|=m<<b&67108863,this.words[g+1]=m>>>26-b&67108863,b+=24,b>=26&&(b-=26,g++);return this._strip()};function s(N,l){var f=N.charCodeAt(l);if(f>=48&&f<=57)return f-48;if(f>=65&&f<=70)return f-55;if(f>=97&&f<=102)return f-87;n(!1,"Invalid character in "+N)}function a(N,l,f){var w=s(N,f);return f-1>=l&&(w|=s(N,f-1)<<4),w}r.prototype._parseHex=function(l,f,w){this.length=Math.ceil((l.length-f)/6),this.words=new Array(this.length);for(var k=0;k<this.length;k++)this.words[k]=0;var g=0,m=0,b;if(w==="be")for(k=l.length-1;k>=f;k-=2)b=a(l,f,k)<<g,this.words[m]|=b&67108863,g>=18?(g-=18,m+=1,this.words[m]|=b>>>26):g+=8;else{var y=l.length-f;for(k=y%2===0?f+1:f;k<l.length;k+=2)b=a(l,f,k)<<g,this.words[m]|=b&67108863,g>=18?(g-=18,m+=1,this.words[m]|=b>>>26):g+=8}this._strip()};function c(N,l,f,w){for(var k=0,g=0,m=Math.min(N.length,f),b=l;b<m;b++){var y=N.charCodeAt(b)-48;k*=w,y>=49?g=y-49+10:y>=17?g=y-17+10:g=y,n(y>=0&&g<w,"Invalid character"),k+=g}return k}r.prototype._parseBase=function(l,f,w){this.words=[0],this.length=1;for(var k=0,g=1;g<=67108863;g*=f)k++;k--,g=g/f|0;for(var m=l.length-w,b=m%k,y=Math.min(m,m-b)+w,p=0,T=w;T<y;T+=k)p=c(l,T,T+k,f),this.imuln(g),this.words[0]+p<67108864?this.words[0]+=p:this._iaddn(p);if(b!==0){var F=1;for(p=c(l,T,l.length,f),T=0;T<b;T++)F*=f;this.imuln(F),this.words[0]+p<67108864?this.words[0]+=p:this._iaddn(p)}this._strip()},r.prototype.copy=function(l){l.words=new Array(this.length);for(var f=0;f<this.length;f++)l.words[f]=this.words[f];l.length=this.length,l.negative=this.negative,l.red=this.red};function u(N,l){N.words=l.words,N.length=l.length,N.negative=l.negative,N.red=l.red}if(r.prototype._move=function(l){u(l,this)},r.prototype.clone=function(){var l=new r(null);return this.copy(l),l},r.prototype._expand=function(l){for(;this.length<l;)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")]=d}catch{r.prototype.inspect=d}else r.prototype.inspect=d;function d(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","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"],_=[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],C=[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(l,f){l=l||10,f=f|0||1;var w;if(l===16||l==="hex"){w="";for(var k=0,g=0,m=0;m<this.length;m++){var b=this.words[m],y=((b<<k|g)&16777215).toString(16);g=b>>>24-k&16777215,k+=2,k>=26&&(k-=26,m--),g!==0||m!==this.length-1?w=h[6-y.length]+y+w:w=y+w}for(g!==0&&(w=g.toString(16)+w);w.length%f!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}if(l===(l|0)&&l>=2&&l<=36){var p=_[l],T=C[l];w="";var F=this.clone();for(F.negative=0;!F.isZero();){var z=F.modrn(T).toString(l);F=F.idivn(T),F.isZero()?w=z+w:w=h[p-z.length]+z+w}for(this.isZero()&&(w="0"+w);w.length%f!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}n(!1,"Base should be between 2 and 36")},r.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},r.prototype.toJSON=function(){return this.toString(16,2)},o&&(r.prototype.toBuffer=function(l,f){return this.toArrayLike(o,l,f)}),r.prototype.toArray=function(l,f){return this.toArrayLike(Array,l,f)};var D=function(l,f){return l.allocUnsafe?l.allocUnsafe(f):new l(f)};r.prototype.toArrayLike=function(l,f,w){this._strip();var k=this.byteLength(),g=w||Math.max(1,k);n(k<=g,"byte array longer than desired length"),n(g>0,"Requested array length <= 0");var m=D(l,g),b=f==="le"?"LE":"BE";return this["_toArrayLike"+b](m,k),m},r.prototype._toArrayLikeLE=function(l,f){for(var w=0,k=0,g=0,m=0;g<this.length;g++){var b=this.words[g]<<m|k;l[w++]=b&255,w<l.length&&(l[w++]=b>>8&255),w<l.length&&(l[w++]=b>>16&255),m===6?(w<l.length&&(l[w++]=b>>24&255),k=0,m=0):(k=b>>>24,m+=2)}if(w<l.length)for(l[w++]=k;w<l.length;)l[w++]=0},r.prototype._toArrayLikeBE=function(l,f){for(var w=l.length-1,k=0,g=0,m=0;g<this.length;g++){var b=this.words[g]<<m|k;l[w--]=b&255,w>=0&&(l[w--]=b>>8&255),w>=0&&(l[w--]=b>>16&255),m===6?(w>=0&&(l[w--]=b>>24&255),k=0,m=0):(k=b>>>24,m+=2)}if(w>=0)for(l[w--]=k;w>=0;)l[w--]=0},Math.clz32?r.prototype._countBits=function(l){return 32-Math.clz32(l)}:r.prototype._countBits=function(l){var f=l,w=0;return f>=4096&&(w+=13,f>>>=13),f>=64&&(w+=7,f>>>=7),f>=8&&(w+=4,f>>>=4),f>=2&&(w+=2,f>>>=2),w+f},r.prototype._zeroBits=function(l){if(l===0)return 26;var f=l,w=0;return f&8191||(w+=13,f>>>=13),f&127||(w+=7,f>>>=7),f&15||(w+=4,f>>>=4),f&3||(w+=2,f>>>=2),f&1||w++,w},r.prototype.bitLength=function(){var l=this.words[this.length-1],f=this._countBits(l);return(this.length-1)*26+f};function O(N){for(var l=new Array(N.bitLength()),f=0;f<l.length;f++){var w=f/26|0,k=f%26;l[f]=N.words[w]>>>k&1}return l}r.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,f=0;f<this.length;f++){var w=this._zeroBits(this.words[f]);if(l+=w,w!==26)break}return l},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(l){return this.negative!==0?this.abs().inotn(l).iaddn(1):this.clone()},r.prototype.fromTwos=function(l){return this.testn(l-1)?this.notn(l).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(l){for(;this.length<l.length;)this.words[this.length++]=0;for(var f=0;f<l.length;f++)this.words[f]=this.words[f]|l.words[f];return this._strip()},r.prototype.ior=function(l){return n((this.negative|l.negative)===0),this.iuor(l)},r.prototype.or=function(l){return this.length>l.length?this.clone().ior(l):l.clone().ior(this)},r.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},r.prototype.iuand=function(l){var f;this.length>l.length?f=l:f=this;for(var w=0;w<f.length;w++)this.words[w]=this.words[w]&l.words[w];return this.length=f.length,this._strip()},r.prototype.iand=function(l){return n((this.negative|l.negative)===0),this.iuand(l)},r.prototype.and=function(l){return this.length>l.length?this.clone().iand(l):l.clone().iand(this)},r.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},r.prototype.iuxor=function(l){var f,w;this.length>l.length?(f=this,w=l):(f=l,w=this);for(var k=0;k<w.length;k++)this.words[k]=f.words[k]^w.words[k];if(this!==f)for(;k<f.length;k++)this.words[k]=f.words[k];return this.length=f.length,this._strip()},r.prototype.ixor=function(l){return n((this.negative|l.negative)===0),this.iuxor(l)},r.prototype.xor=function(l){return this.length>l.length?this.clone().ixor(l):l.clone().ixor(this)},r.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},r.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var f=Math.ceil(l/26)|0,w=l%26;this._expand(f),w>0&&f--;for(var k=0;k<f;k++)this.words[k]=~this.words[k]&67108863;return w>0&&(this.words[k]=~this.words[k]&67108863>>26-w),this._strip()},r.prototype.notn=function(l){return this.clone().inotn(l)},r.prototype.setn=function(l,f){n(typeof l=="number"&&l>=0);var w=l/26|0,k=l%26;return this._expand(w+1),f?this.words[w]=this.words[w]|1<<k:this.words[w]=this.words[w]&~(1<<k),this._strip()},r.prototype.iadd=function(l){var f;if(this.negative!==0&&l.negative===0)return this.negative=0,f=this.isub(l),this.negative^=1,this._normSign();if(this.negative===0&&l.negative!==0)return l.negative=0,f=this.isub(l),l.negative=1,f._normSign();var w,k;this.length>l.length?(w=this,k=l):(w=l,k=this);for(var g=0,m=0;m<k.length;m++)f=(w.words[m]|0)+(k.words[m]|0)+g,this.words[m]=f&67108863,g=f>>>26;for(;g!==0&&m<w.length;m++)f=(w.words[m]|0)+g,this.words[m]=f&67108863,g=f>>>26;if(this.length=w.length,g!==0)this.words[this.length]=g,this.length++;else if(w!==this)for(;m<w.length;m++)this.words[m]=w.words[m];return this},r.prototype.add=function(l){var f;return l.negative!==0&&this.negative===0?(l.negative=0,f=this.sub(l),l.negative^=1,f):l.negative===0&&this.negative!==0?(this.negative=0,f=l.sub(this),this.negative=1,f):this.length>l.length?this.clone().iadd(l):l.clone().iadd(this)},r.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var f=this.iadd(l);return l.negative=1,f._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var w=this.cmp(l);if(w===0)return this.negative=0,this.length=1,this.words[0]=0,this;var k,g;w>0?(k=this,g=l):(k=l,g=this);for(var m=0,b=0;b<g.length;b++)f=(k.words[b]|0)-(g.words[b]|0)+m,m=f>>26,this.words[b]=f&67108863;for(;m!==0&&b<k.length;b++)f=(k.words[b]|0)+m,m=f>>26,this.words[b]=f&67108863;if(m===0&&b<k.length&&k!==this)for(;b<k.length;b++)this.words[b]=k.words[b];return this.length=Math.max(this.length,b),k!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(l){return this.clone().isub(l)};function B(N,l,f){f.negative=l.negative^N.negative;var w=N.length+l.length|0;f.length=w,w=w-1|0;var k=N.words[0]|0,g=l.words[0]|0,m=k*g,b=m&67108863,y=m/67108864|0;f.words[0]=b;for(var p=1;p<w;p++){for(var T=y>>>26,F=y&67108863,z=Math.min(p,l.length-1),Q=Math.max(0,p-N.length+1);Q<=z;Q++){var H=p-Q|0;k=N.words[H]|0,g=l.words[Q]|0,m=k*g+F,T+=m/67108864|0,F=m&67108863}f.words[p]=F|0,y=T|0}return y!==0?f.words[p]=y|0:f.length--,f._strip()}var j=function(l,f,w){var k=l.words,g=f.words,m=w.words,b=0,y,p,T,F=k[0]|0,z=F&8191,Q=F>>>13,H=k[1]|0,ae=H&8191,fe=H>>>13,Ce=k[2]|0,ke=Ce&8191,Fe=Ce>>>13,kt=k[3]|0,it=kt&8191,Qe=kt>>>13,ti=k[4]|0,mt=ti&8191,gt=ti>>>13,Jr=k[5]|0,Bt=Jr&8191,Mt=Jr>>>13,Za=k[6]|0,jt=Za&8191,Nt=Za>>>13,Ja=k[7]|0,Rt=Ja&8191,Ft=Ja>>>13,Ya=k[8]|0,qt=Ya&8191,Lt=Ya>>>13,Qa=k[9]|0,Ut=Qa&8191,$t=Qa>>>13,ec=g[0]|0,Pt=ec&8191,Gt=ec>>>13,tc=g[1]|0,zt=tc&8191,Vt=tc>>>13,ks=g[2]|0,Kt=ks&8191,Wt=ks>>>13,nc=g[3]|0,Ht=nc&8191,Xt=nc>>>13,ic=g[4]|0,Zt=ic&8191,Jt=ic>>>13,rc=g[5]|0,Yt=rc&8191,Qt=rc>>>13,oc=g[6]|0,en=oc&8191,tn=oc>>>13,sc=g[7]|0,nn=sc&8191,rn=sc>>>13,ac=g[8]|0,on=ac&8191,sn=ac>>>13,v=g[9]|0,A=v&8191,S=v>>>13;w.negative=l.negative^f.negative,w.length=19,y=Math.imul(z,Pt),p=Math.imul(z,Gt),p=p+Math.imul(Q,Pt)|0,T=Math.imul(Q,Gt);var x=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(x>>>26)|0,x&=67108863,y=Math.imul(ae,Pt),p=Math.imul(ae,Gt),p=p+Math.imul(fe,Pt)|0,T=Math.imul(fe,Gt),y=y+Math.imul(z,zt)|0,p=p+Math.imul(z,Vt)|0,p=p+Math.imul(Q,zt)|0,T=T+Math.imul(Q,Vt)|0;var P=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(P>>>26)|0,P&=67108863,y=Math.imul(ke,Pt),p=Math.imul(ke,Gt),p=p+Math.imul(Fe,Pt)|0,T=Math.imul(Fe,Gt),y=y+Math.imul(ae,zt)|0,p=p+Math.imul(ae,Vt)|0,p=p+Math.imul(fe,zt)|0,T=T+Math.imul(fe,Vt)|0,y=y+Math.imul(z,Kt)|0,p=p+Math.imul(z,Wt)|0,p=p+Math.imul(Q,Kt)|0,T=T+Math.imul(Q,Wt)|0;var E=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(E>>>26)|0,E&=67108863,y=Math.imul(it,Pt),p=Math.imul(it,Gt),p=p+Math.imul(Qe,Pt)|0,T=Math.imul(Qe,Gt),y=y+Math.imul(ke,zt)|0,p=p+Math.imul(ke,Vt)|0,p=p+Math.imul(Fe,zt)|0,T=T+Math.imul(Fe,Vt)|0,y=y+Math.imul(ae,Kt)|0,p=p+Math.imul(ae,Wt)|0,p=p+Math.imul(fe,Kt)|0,T=T+Math.imul(fe,Wt)|0,y=y+Math.imul(z,Ht)|0,p=p+Math.imul(z,Xt)|0,p=p+Math.imul(Q,Ht)|0,T=T+Math.imul(Q,Xt)|0;var q=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(q>>>26)|0,q&=67108863,y=Math.imul(mt,Pt),p=Math.imul(mt,Gt),p=p+Math.imul(gt,Pt)|0,T=Math.imul(gt,Gt),y=y+Math.imul(it,zt)|0,p=p+Math.imul(it,Vt)|0,p=p+Math.imul(Qe,zt)|0,T=T+Math.imul(Qe,Vt)|0,y=y+Math.imul(ke,Kt)|0,p=p+Math.imul(ke,Wt)|0,p=p+Math.imul(Fe,Kt)|0,T=T+Math.imul(Fe,Wt)|0,y=y+Math.imul(ae,Ht)|0,p=p+Math.imul(ae,Xt)|0,p=p+Math.imul(fe,Ht)|0,T=T+Math.imul(fe,Xt)|0,y=y+Math.imul(z,Zt)|0,p=p+Math.imul(z,Jt)|0,p=p+Math.imul(Q,Zt)|0,T=T+Math.imul(Q,Jt)|0;var L=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(L>>>26)|0,L&=67108863,y=Math.imul(Bt,Pt),p=Math.imul(Bt,Gt),p=p+Math.imul(Mt,Pt)|0,T=Math.imul(Mt,Gt),y=y+Math.imul(mt,zt)|0,p=p+Math.imul(mt,Vt)|0,p=p+Math.imul(gt,zt)|0,T=T+Math.imul(gt,Vt)|0,y=y+Math.imul(it,Kt)|0,p=p+Math.imul(it,Wt)|0,p=p+Math.imul(Qe,Kt)|0,T=T+Math.imul(Qe,Wt)|0,y=y+Math.imul(ke,Ht)|0,p=p+Math.imul(ke,Xt)|0,p=p+Math.imul(Fe,Ht)|0,T=T+Math.imul(Fe,Xt)|0,y=y+Math.imul(ae,Zt)|0,p=p+Math.imul(ae,Jt)|0,p=p+Math.imul(fe,Zt)|0,T=T+Math.imul(fe,Jt)|0,y=y+Math.imul(z,Yt)|0,p=p+Math.imul(z,Qt)|0,p=p+Math.imul(Q,Yt)|0,T=T+Math.imul(Q,Qt)|0;var V=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(V>>>26)|0,V&=67108863,y=Math.imul(jt,Pt),p=Math.imul(jt,Gt),p=p+Math.imul(Nt,Pt)|0,T=Math.imul(Nt,Gt),y=y+Math.imul(Bt,zt)|0,p=p+Math.imul(Bt,Vt)|0,p=p+Math.imul(Mt,zt)|0,T=T+Math.imul(Mt,Vt)|0,y=y+Math.imul(mt,Kt)|0,p=p+Math.imul(mt,Wt)|0,p=p+Math.imul(gt,Kt)|0,T=T+Math.imul(gt,Wt)|0,y=y+Math.imul(it,Ht)|0,p=p+Math.imul(it,Xt)|0,p=p+Math.imul(Qe,Ht)|0,T=T+Math.imul(Qe,Xt)|0,y=y+Math.imul(ke,Zt)|0,p=p+Math.imul(ke,Jt)|0,p=p+Math.imul(Fe,Zt)|0,T=T+Math.imul(Fe,Jt)|0,y=y+Math.imul(ae,Yt)|0,p=p+Math.imul(ae,Qt)|0,p=p+Math.imul(fe,Yt)|0,T=T+Math.imul(fe,Qt)|0,y=y+Math.imul(z,en)|0,p=p+Math.imul(z,tn)|0,p=p+Math.imul(Q,en)|0,T=T+Math.imul(Q,tn)|0;var U=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(U>>>26)|0,U&=67108863,y=Math.imul(Rt,Pt),p=Math.imul(Rt,Gt),p=p+Math.imul(Ft,Pt)|0,T=Math.imul(Ft,Gt),y=y+Math.imul(jt,zt)|0,p=p+Math.imul(jt,Vt)|0,p=p+Math.imul(Nt,zt)|0,T=T+Math.imul(Nt,Vt)|0,y=y+Math.imul(Bt,Kt)|0,p=p+Math.imul(Bt,Wt)|0,p=p+Math.imul(Mt,Kt)|0,T=T+Math.imul(Mt,Wt)|0,y=y+Math.imul(mt,Ht)|0,p=p+Math.imul(mt,Xt)|0,p=p+Math.imul(gt,Ht)|0,T=T+Math.imul(gt,Xt)|0,y=y+Math.imul(it,Zt)|0,p=p+Math.imul(it,Jt)|0,p=p+Math.imul(Qe,Zt)|0,T=T+Math.imul(Qe,Jt)|0,y=y+Math.imul(ke,Yt)|0,p=p+Math.imul(ke,Qt)|0,p=p+Math.imul(Fe,Yt)|0,T=T+Math.imul(Fe,Qt)|0,y=y+Math.imul(ae,en)|0,p=p+Math.imul(ae,tn)|0,p=p+Math.imul(fe,en)|0,T=T+Math.imul(fe,tn)|0,y=y+Math.imul(z,nn)|0,p=p+Math.imul(z,rn)|0,p=p+Math.imul(Q,nn)|0,T=T+Math.imul(Q,rn)|0;var Z=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(Z>>>26)|0,Z&=67108863,y=Math.imul(qt,Pt),p=Math.imul(qt,Gt),p=p+Math.imul(Lt,Pt)|0,T=Math.imul(Lt,Gt),y=y+Math.imul(Rt,zt)|0,p=p+Math.imul(Rt,Vt)|0,p=p+Math.imul(Ft,zt)|0,T=T+Math.imul(Ft,Vt)|0,y=y+Math.imul(jt,Kt)|0,p=p+Math.imul(jt,Wt)|0,p=p+Math.imul(Nt,Kt)|0,T=T+Math.imul(Nt,Wt)|0,y=y+Math.imul(Bt,Ht)|0,p=p+Math.imul(Bt,Xt)|0,p=p+Math.imul(Mt,Ht)|0,T=T+Math.imul(Mt,Xt)|0,y=y+Math.imul(mt,Zt)|0,p=p+Math.imul(mt,Jt)|0,p=p+Math.imul(gt,Zt)|0,T=T+Math.imul(gt,Jt)|0,y=y+Math.imul(it,Yt)|0,p=p+Math.imul(it,Qt)|0,p=p+Math.imul(Qe,Yt)|0,T=T+Math.imul(Qe,Qt)|0,y=y+Math.imul(ke,en)|0,p=p+Math.imul(ke,tn)|0,p=p+Math.imul(Fe,en)|0,T=T+Math.imul(Fe,tn)|0,y=y+Math.imul(ae,nn)|0,p=p+Math.imul(ae,rn)|0,p=p+Math.imul(fe,nn)|0,T=T+Math.imul(fe,rn)|0,y=y+Math.imul(z,on)|0,p=p+Math.imul(z,sn)|0,p=p+Math.imul(Q,on)|0,T=T+Math.imul(Q,sn)|0;var ee=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(ee>>>26)|0,ee&=67108863,y=Math.imul(Ut,Pt),p=Math.imul(Ut,Gt),p=p+Math.imul($t,Pt)|0,T=Math.imul($t,Gt),y=y+Math.imul(qt,zt)|0,p=p+Math.imul(qt,Vt)|0,p=p+Math.imul(Lt,zt)|0,T=T+Math.imul(Lt,Vt)|0,y=y+Math.imul(Rt,Kt)|0,p=p+Math.imul(Rt,Wt)|0,p=p+Math.imul(Ft,Kt)|0,T=T+Math.imul(Ft,Wt)|0,y=y+Math.imul(jt,Ht)|0,p=p+Math.imul(jt,Xt)|0,p=p+Math.imul(Nt,Ht)|0,T=T+Math.imul(Nt,Xt)|0,y=y+Math.imul(Bt,Zt)|0,p=p+Math.imul(Bt,Jt)|0,p=p+Math.imul(Mt,Zt)|0,T=T+Math.imul(Mt,Jt)|0,y=y+Math.imul(mt,Yt)|0,p=p+Math.imul(mt,Qt)|0,p=p+Math.imul(gt,Yt)|0,T=T+Math.imul(gt,Qt)|0,y=y+Math.imul(it,en)|0,p=p+Math.imul(it,tn)|0,p=p+Math.imul(Qe,en)|0,T=T+Math.imul(Qe,tn)|0,y=y+Math.imul(ke,nn)|0,p=p+Math.imul(ke,rn)|0,p=p+Math.imul(Fe,nn)|0,T=T+Math.imul(Fe,rn)|0,y=y+Math.imul(ae,on)|0,p=p+Math.imul(ae,sn)|0,p=p+Math.imul(fe,on)|0,T=T+Math.imul(fe,sn)|0,y=y+Math.imul(z,A)|0,p=p+Math.imul(z,S)|0,p=p+Math.imul(Q,A)|0,T=T+Math.imul(Q,S)|0;var ie=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(ie>>>26)|0,ie&=67108863,y=Math.imul(Ut,zt),p=Math.imul(Ut,Vt),p=p+Math.imul($t,zt)|0,T=Math.imul($t,Vt),y=y+Math.imul(qt,Kt)|0,p=p+Math.imul(qt,Wt)|0,p=p+Math.imul(Lt,Kt)|0,T=T+Math.imul(Lt,Wt)|0,y=y+Math.imul(Rt,Ht)|0,p=p+Math.imul(Rt,Xt)|0,p=p+Math.imul(Ft,Ht)|0,T=T+Math.imul(Ft,Xt)|0,y=y+Math.imul(jt,Zt)|0,p=p+Math.imul(jt,Jt)|0,p=p+Math.imul(Nt,Zt)|0,T=T+Math.imul(Nt,Jt)|0,y=y+Math.imul(Bt,Yt)|0,p=p+Math.imul(Bt,Qt)|0,p=p+Math.imul(Mt,Yt)|0,T=T+Math.imul(Mt,Qt)|0,y=y+Math.imul(mt,en)|0,p=p+Math.imul(mt,tn)|0,p=p+Math.imul(gt,en)|0,T=T+Math.imul(gt,tn)|0,y=y+Math.imul(it,nn)|0,p=p+Math.imul(it,rn)|0,p=p+Math.imul(Qe,nn)|0,T=T+Math.imul(Qe,rn)|0,y=y+Math.imul(ke,on)|0,p=p+Math.imul(ke,sn)|0,p=p+Math.imul(Fe,on)|0,T=T+Math.imul(Fe,sn)|0,y=y+Math.imul(ae,A)|0,p=p+Math.imul(ae,S)|0,p=p+Math.imul(fe,A)|0,T=T+Math.imul(fe,S)|0;var we=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(we>>>26)|0,we&=67108863,y=Math.imul(Ut,Kt),p=Math.imul(Ut,Wt),p=p+Math.imul($t,Kt)|0,T=Math.imul($t,Wt),y=y+Math.imul(qt,Ht)|0,p=p+Math.imul(qt,Xt)|0,p=p+Math.imul(Lt,Ht)|0,T=T+Math.imul(Lt,Xt)|0,y=y+Math.imul(Rt,Zt)|0,p=p+Math.imul(Rt,Jt)|0,p=p+Math.imul(Ft,Zt)|0,T=T+Math.imul(Ft,Jt)|0,y=y+Math.imul(jt,Yt)|0,p=p+Math.imul(jt,Qt)|0,p=p+Math.imul(Nt,Yt)|0,T=T+Math.imul(Nt,Qt)|0,y=y+Math.imul(Bt,en)|0,p=p+Math.imul(Bt,tn)|0,p=p+Math.imul(Mt,en)|0,T=T+Math.imul(Mt,tn)|0,y=y+Math.imul(mt,nn)|0,p=p+Math.imul(mt,rn)|0,p=p+Math.imul(gt,nn)|0,T=T+Math.imul(gt,rn)|0,y=y+Math.imul(it,on)|0,p=p+Math.imul(it,sn)|0,p=p+Math.imul(Qe,on)|0,T=T+Math.imul(Qe,sn)|0,y=y+Math.imul(ke,A)|0,p=p+Math.imul(ke,S)|0,p=p+Math.imul(Fe,A)|0,T=T+Math.imul(Fe,S)|0;var He=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(He>>>26)|0,He&=67108863,y=Math.imul(Ut,Ht),p=Math.imul(Ut,Xt),p=p+Math.imul($t,Ht)|0,T=Math.imul($t,Xt),y=y+Math.imul(qt,Zt)|0,p=p+Math.imul(qt,Jt)|0,p=p+Math.imul(Lt,Zt)|0,T=T+Math.imul(Lt,Jt)|0,y=y+Math.imul(Rt,Yt)|0,p=p+Math.imul(Rt,Qt)|0,p=p+Math.imul(Ft,Yt)|0,T=T+Math.imul(Ft,Qt)|0,y=y+Math.imul(jt,en)|0,p=p+Math.imul(jt,tn)|0,p=p+Math.imul(Nt,en)|0,T=T+Math.imul(Nt,tn)|0,y=y+Math.imul(Bt,nn)|0,p=p+Math.imul(Bt,rn)|0,p=p+Math.imul(Mt,nn)|0,T=T+Math.imul(Mt,rn)|0,y=y+Math.imul(mt,on)|0,p=p+Math.imul(mt,sn)|0,p=p+Math.imul(gt,on)|0,T=T+Math.imul(gt,sn)|0,y=y+Math.imul(it,A)|0,p=p+Math.imul(it,S)|0,p=p+Math.imul(Qe,A)|0,T=T+Math.imul(Qe,S)|0;var je=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(je>>>26)|0,je&=67108863,y=Math.imul(Ut,Zt),p=Math.imul(Ut,Jt),p=p+Math.imul($t,Zt)|0,T=Math.imul($t,Jt),y=y+Math.imul(qt,Yt)|0,p=p+Math.imul(qt,Qt)|0,p=p+Math.imul(Lt,Yt)|0,T=T+Math.imul(Lt,Qt)|0,y=y+Math.imul(Rt,en)|0,p=p+Math.imul(Rt,tn)|0,p=p+Math.imul(Ft,en)|0,T=T+Math.imul(Ft,tn)|0,y=y+Math.imul(jt,nn)|0,p=p+Math.imul(jt,rn)|0,p=p+Math.imul(Nt,nn)|0,T=T+Math.imul(Nt,rn)|0,y=y+Math.imul(Bt,on)|0,p=p+Math.imul(Bt,sn)|0,p=p+Math.imul(Mt,on)|0,T=T+Math.imul(Mt,sn)|0,y=y+Math.imul(mt,A)|0,p=p+Math.imul(mt,S)|0,p=p+Math.imul(gt,A)|0,T=T+Math.imul(gt,S)|0;var pn=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(pn>>>26)|0,pn&=67108863,y=Math.imul(Ut,Yt),p=Math.imul(Ut,Qt),p=p+Math.imul($t,Yt)|0,T=Math.imul($t,Qt),y=y+Math.imul(qt,en)|0,p=p+Math.imul(qt,tn)|0,p=p+Math.imul(Lt,en)|0,T=T+Math.imul(Lt,tn)|0,y=y+Math.imul(Rt,nn)|0,p=p+Math.imul(Rt,rn)|0,p=p+Math.imul(Ft,nn)|0,T=T+Math.imul(Ft,rn)|0,y=y+Math.imul(jt,on)|0,p=p+Math.imul(jt,sn)|0,p=p+Math.imul(Nt,on)|0,T=T+Math.imul(Nt,sn)|0,y=y+Math.imul(Bt,A)|0,p=p+Math.imul(Bt,S)|0,p=p+Math.imul(Mt,A)|0,T=T+Math.imul(Mt,S)|0;var _t=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(_t>>>26)|0,_t&=67108863,y=Math.imul(Ut,en),p=Math.imul(Ut,tn),p=p+Math.imul($t,en)|0,T=Math.imul($t,tn),y=y+Math.imul(qt,nn)|0,p=p+Math.imul(qt,rn)|0,p=p+Math.imul(Lt,nn)|0,T=T+Math.imul(Lt,rn)|0,y=y+Math.imul(Rt,on)|0,p=p+Math.imul(Rt,sn)|0,p=p+Math.imul(Ft,on)|0,T=T+Math.imul(Ft,sn)|0,y=y+Math.imul(jt,A)|0,p=p+Math.imul(jt,S)|0,p=p+Math.imul(Nt,A)|0,T=T+Math.imul(Nt,S)|0;var Vn=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(Vn>>>26)|0,Vn&=67108863,y=Math.imul(Ut,nn),p=Math.imul(Ut,rn),p=p+Math.imul($t,nn)|0,T=Math.imul($t,rn),y=y+Math.imul(qt,on)|0,p=p+Math.imul(qt,sn)|0,p=p+Math.imul(Lt,on)|0,T=T+Math.imul(Lt,sn)|0,y=y+Math.imul(Rt,A)|0,p=p+Math.imul(Rt,S)|0,p=p+Math.imul(Ft,A)|0,T=T+Math.imul(Ft,S)|0;var rt=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(rt>>>26)|0,rt&=67108863,y=Math.imul(Ut,on),p=Math.imul(Ut,sn),p=p+Math.imul($t,on)|0,T=Math.imul($t,sn),y=y+Math.imul(qt,A)|0,p=p+Math.imul(qt,S)|0,p=p+Math.imul(Lt,A)|0,T=T+Math.imul(Lt,S)|0;var un=(b+y|0)+((p&8191)<<13)|0;b=(T+(p>>>13)|0)+(un>>>26)|0,un&=67108863,y=Math.imul(Ut,A),p=Math.imul(Ut,S),p=p+Math.imul($t,A)|0,T=Math.imul($t,S);var wr=(b+y|0)+((p&8191)<<13)|0;return b=(T+(p>>>13)|0)+(wr>>>26)|0,wr&=67108863,m[0]=x,m[1]=P,m[2]=E,m[3]=q,m[4]=L,m[5]=V,m[6]=U,m[7]=Z,m[8]=ee,m[9]=ie,m[10]=we,m[11]=He,m[12]=je,m[13]=pn,m[14]=_t,m[15]=Vn,m[16]=rt,m[17]=un,m[18]=wr,b!==0&&(m[19]=b,w.length++),w};Math.imul||(j=B);function M(N,l,f){f.negative=l.negative^N.negative,f.length=N.length+l.length;for(var w=0,k=0,g=0;g<f.length-1;g++){var m=k;k=0;for(var b=w&67108863,y=Math.min(g,l.length-1),p=Math.max(0,g-N.length+1);p<=y;p++){var T=g-p,F=N.words[T]|0,z=l.words[p]|0,Q=F*z,H=Q&67108863;m=m+(Q/67108864|0)|0,H=H+b|0,b=H&67108863,m=m+(H>>>26)|0,k+=m>>>26,m&=67108863}f.words[g]=b,w=m,m=k}return w!==0?f.words[g]=w:f.length--,f._strip()}function R(N,l,f){return M(N,l,f)}r.prototype.mulTo=function(l,f){var w,k=this.length+l.length;return this.length===10&&l.length===10?w=j(this,l,f):k<63?w=B(this,l,f):k<1024?w=M(this,l,f):w=R(this,l,f),w};function K(N,l){this.x=N,this.y=l}K.prototype.makeRBT=function(l){for(var f=new Array(l),w=r.prototype._countBits(l)-1,k=0;k<l;k++)f[k]=this.revBin(k,w,l);return f},K.prototype.revBin=function(l,f,w){if(l===0||l===w-1)return l;for(var k=0,g=0;g<f;g++)k|=(l&1)<<f-g-1,l>>=1;return k},K.prototype.permute=function(l,f,w,k,g,m){for(var b=0;b<m;b++)k[b]=f[l[b]],g[b]=w[l[b]]},K.prototype.transform=function(l,f,w,k,g,m){this.permute(m,l,f,w,k,g);for(var b=1;b<g;b<<=1)for(var y=b<<1,p=Math.cos(2*Math.PI/y),T=Math.sin(2*Math.PI/y),F=0;F<g;F+=y)for(var z=p,Q=T,H=0;H<b;H++){var ae=w[F+H],fe=k[F+H],Ce=w[F+H+b],ke=k[F+H+b],Fe=z*Ce-Q*ke;ke=z*ke+Q*Ce,Ce=Fe,w[F+H]=ae+Ce,k[F+H]=fe+ke,w[F+H+b]=ae-Ce,k[F+H+b]=fe-ke,H!==y&&(Fe=p*z-T*Q,Q=p*Q+T*z,z=Fe)}},K.prototype.guessLen13b=function(l,f){var w=Math.max(f,l)|1,k=w&1,g=0;for(w=w/2|0;w;w=w>>>1)g++;return 1<<g+1+k},K.prototype.conjugate=function(l,f,w){if(!(w<=1))for(var k=0;k<w/2;k++){var g=l[k];l[k]=l[w-k-1],l[w-k-1]=g,g=f[k],f[k]=-f[w-k-1],f[w-k-1]=-g}},K.prototype.normalize13b=function(l,f){for(var w=0,k=0;k<f/2;k++){var g=Math.round(l[2*k+1]/f)*8192+Math.round(l[2*k]/f)+w;l[k]=g&67108863,g<67108864?w=0:w=g/67108864|0}return l},K.prototype.convert13b=function(l,f,w,k){for(var g=0,m=0;m<f;m++)g=g+(l[m]|0),w[2*m]=g&8191,g=g>>>13,w[2*m+1]=g&8191,g=g>>>13;for(m=2*f;m<k;++m)w[m]=0;n(g===0),n((g&-8192)===0)},K.prototype.stub=function(l){for(var f=new Array(l),w=0;w<l;w++)f[w]=0;return f},K.prototype.mulp=function(l,f,w){var k=2*this.guessLen13b(l.length,f.length),g=this.makeRBT(k),m=this.stub(k),b=new Array(k),y=new Array(k),p=new Array(k),T=new Array(k),F=new Array(k),z=new Array(k),Q=w.words;Q.length=k,this.convert13b(l.words,l.length,b,k),this.convert13b(f.words,f.length,T,k),this.transform(b,m,y,p,k,g),this.transform(T,m,F,z,k,g);for(var H=0;H<k;H++){var ae=y[H]*F[H]-p[H]*z[H];p[H]=y[H]*z[H]+p[H]*F[H],y[H]=ae}return this.conjugate(y,p,k),this.transform(y,p,Q,m,k,g),this.conjugate(Q,m,k),this.normalize13b(Q,k),w.negative=l.negative^f.negative,w.length=l.length+f.length,w._strip()},r.prototype.mul=function(l){var f=new r(null);return f.words=new Array(this.length+l.length),this.mulTo(l,f)},r.prototype.mulf=function(l){var f=new r(null);return f.words=new Array(this.length+l.length),R(this,l,f)},r.prototype.imul=function(l){return this.clone().mulTo(l,this)},r.prototype.imuln=function(l){var f=l<0;f&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var w=0,k=0;k<this.length;k++){var g=(this.words[k]|0)*l,m=(g&67108863)+(w&67108863);w>>=26,w+=g/67108864|0,w+=m>>>26,this.words[k]=m&67108863}return w!==0&&(this.words[k]=w,this.length++),f?this.ineg():this},r.prototype.muln=function(l){return this.clone().imuln(l)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(l){var f=O(l);if(f.length===0)return new r(1);for(var w=this,k=0;k<f.length&&f[k]===0;k++,w=w.sqr());if(++k<f.length)for(var g=w.sqr();k<f.length;k++,g=g.sqr())f[k]!==0&&(w=w.mul(g));return w},r.prototype.iushln=function(l){n(typeof l=="number"&&l>=0);var f=l%26,w=(l-f)/26,k=67108863>>>26-f<<26-f,g;if(f!==0){var m=0;for(g=0;g<this.length;g++){var b=this.words[g]&k,y=(this.words[g]|0)-b<<f;this.words[g]=y|m,m=b>>>26-f}m&&(this.words[g]=m,this.length++)}if(w!==0){for(g=this.length-1;g>=0;g--)this.words[g+w]=this.words[g];for(g=0;g<w;g++)this.words[g]=0;this.length+=w}return this._strip()},r.prototype.ishln=function(l){return n(this.negative===0),this.iushln(l)},r.prototype.iushrn=function(l,f,w){n(typeof l=="number"&&l>=0);var k;f?k=(f-f%26)/26:k=0;var g=l%26,m=Math.min((l-g)/26,this.length),b=67108863^67108863>>>g<<g,y=w;if(k-=m,k=Math.max(0,k),y){for(var p=0;p<m;p++)y.words[p]=this.words[p];y.length=m}if(m!==0)if(this.length>m)for(this.length-=m,p=0;p<this.length;p++)this.words[p]=this.words[p+m];else this.words[0]=0,this.length=1;var T=0;for(p=this.length-1;p>=0&&(T!==0||p>=k);p--){var F=this.words[p]|0;this.words[p]=T<<26-g|F>>>g,T=F&b}return y&&T!==0&&(y.words[y.length++]=T),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(l,f,w){return n(this.negative===0),this.iushrn(l,f,w)},r.prototype.shln=function(l){return this.clone().ishln(l)},r.prototype.ushln=function(l){return this.clone().iushln(l)},r.prototype.shrn=function(l){return this.clone().ishrn(l)},r.prototype.ushrn=function(l){return this.clone().iushrn(l)},r.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var f=l%26,w=(l-f)/26,k=1<<f;if(this.length<=w)return!1;var g=this.words[w];return!!(g&k)},r.prototype.imaskn=function(l){n(typeof l=="number"&&l>=0);var f=l%26,w=(l-f)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=w)return this;if(f!==0&&w++,this.length=Math.min(w,this.length),f!==0){var k=67108863^67108863>>>f<<f;this.words[this.length-1]&=k}return this._strip()},r.prototype.maskn=function(l){return this.clone().imaskn(l)},r.prototype.iaddn=function(l){return n(typeof l=="number"),n(l<67108864),l<0?this.isubn(-l):this.negative!==0?this.length===1&&(this.words[0]|0)<=l?(this.words[0]=l-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(l),this.negative=1,this):this._iaddn(l)},r.prototype._iaddn=function(l){this.words[0]+=l;for(var f=0;f<this.length&&this.words[f]>=67108864;f++)this.words[f]-=67108864,f===this.length-1?this.words[f+1]=1:this.words[f+1]++;return this.length=Math.max(this.length,f+1),this},r.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var f=0;f<this.length&&this.words[f]<0;f++)this.words[f]+=67108864,this.words[f+1]-=1;return this._strip()},r.prototype.addn=function(l){return this.clone().iaddn(l)},r.prototype.subn=function(l){return this.clone().isubn(l)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(l,f,w){var k=l.length+w,g;this._expand(k);var m,b=0;for(g=0;g<l.length;g++){m=(this.words[g+w]|0)+b;var y=(l.words[g]|0)*f;m-=y&67108863,b=(m>>26)-(y/67108864|0),this.words[g+w]=m&67108863}for(;g<this.length-w;g++)m=(this.words[g+w]|0)+b,b=m>>26,this.words[g+w]=m&67108863;if(b===0)return this._strip();for(n(b===-1),b=0,g=0;g<this.length;g++)m=-(this.words[g]|0)+b,b=m>>26,this.words[g]=m&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(l,f){var w=this.length-l.length,k=this.clone(),g=l,m=g.words[g.length-1]|0,b=this._countBits(m);w=26-b,w!==0&&(g=g.ushln(w),k.iushln(w),m=g.words[g.length-1]|0);var y=k.length-g.length,p;if(f!=="mod"){p=new r(null),p.length=y+1,p.words=new Array(p.length);for(var T=0;T<p.length;T++)p.words[T]=0}var F=k.clone()._ishlnsubmul(g,1,y);F.negative===0&&(k=F,p&&(p.words[y]=1));for(var z=y-1;z>=0;z--){var Q=(k.words[g.length+z]|0)*67108864+(k.words[g.length+z-1]|0);for(Q=Math.min(Q/m|0,67108863),k._ishlnsubmul(g,Q,z);k.negative!==0;)Q--,k.negative=0,k._ishlnsubmul(g,1,z),k.isZero()||(k.negative^=1);p&&(p.words[z]=Q)}return p&&p._strip(),k._strip(),f!=="div"&&w!==0&&k.iushrn(w),{div:p||null,mod:k}},r.prototype.divmod=function(l,f,w){if(n(!l.isZero()),this.isZero())return{div:new r(0),mod:new r(0)};var k,g,m;return this.negative!==0&&l.negative===0?(m=this.neg().divmod(l,f),f!=="mod"&&(k=m.div.neg()),f!=="div"&&(g=m.mod.neg(),w&&g.negative!==0&&g.iadd(l)),{div:k,mod:g}):this.negative===0&&l.negative!==0?(m=this.divmod(l.neg(),f),f!=="mod"&&(k=m.div.neg()),{div:k,mod:m.mod}):this.negative&l.negative?(m=this.neg().divmod(l.neg(),f),f!=="div"&&(g=m.mod.neg(),w&&g.negative!==0&&g.isub(l)),{div:m.div,mod:g}):l.length>this.length||this.cmp(l)<0?{div:new r(0),mod:this}:l.length===1?f==="div"?{div:this.divn(l.words[0]),mod:null}:f==="mod"?{div:null,mod:new r(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new r(this.modrn(l.words[0]))}:this._wordDiv(l,f)},r.prototype.div=function(l){return this.divmod(l,"div",!1).div},r.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},r.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},r.prototype.divRound=function(l){var f=this.divmod(l);if(f.mod.isZero())return f.div;var w=f.div.negative!==0?f.mod.isub(l):f.mod,k=l.ushrn(1),g=l.andln(1),m=w.cmp(k);return m<0||g===1&&m===0?f.div:f.div.negative!==0?f.div.isubn(1):f.div.iaddn(1)},r.prototype.modrn=function(l){var f=l<0;f&&(l=-l),n(l<=67108863);for(var w=(1<<26)%l,k=0,g=this.length-1;g>=0;g--)k=(w*k+(this.words[g]|0))%l;return f?-k:k},r.prototype.modn=function(l){return this.modrn(l)},r.prototype.idivn=function(l){var f=l<0;f&&(l=-l),n(l<=67108863);for(var w=0,k=this.length-1;k>=0;k--){var g=(this.words[k]|0)+w*67108864;this.words[k]=g/l|0,w=g%l}return this._strip(),f?this.ineg():this},r.prototype.divn=function(l){return this.clone().idivn(l)},r.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var f=this,w=l.clone();f.negative!==0?f=f.umod(l):f=f.clone();for(var k=new r(1),g=new r(0),m=new r(0),b=new r(1),y=0;f.isEven()&&w.isEven();)f.iushrn(1),w.iushrn(1),++y;for(var p=w.clone(),T=f.clone();!f.isZero();){for(var F=0,z=1;!(f.words[0]&z)&&F<26;++F,z<<=1);if(F>0)for(f.iushrn(F);F-- >0;)(k.isOdd()||g.isOdd())&&(k.iadd(p),g.isub(T)),k.iushrn(1),g.iushrn(1);for(var Q=0,H=1;!(w.words[0]&H)&&Q<26;++Q,H<<=1);if(Q>0)for(w.iushrn(Q);Q-- >0;)(m.isOdd()||b.isOdd())&&(m.iadd(p),b.isub(T)),m.iushrn(1),b.iushrn(1);f.cmp(w)>=0?(f.isub(w),k.isub(m),g.isub(b)):(w.isub(f),m.isub(k),b.isub(g))}return{a:m,b,gcd:w.iushln(y)}},r.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var f=this,w=l.clone();f.negative!==0?f=f.umod(l):f=f.clone();for(var k=new r(1),g=new r(0),m=w.clone();f.cmpn(1)>0&&w.cmpn(1)>0;){for(var b=0,y=1;!(f.words[0]&y)&&b<26;++b,y<<=1);if(b>0)for(f.iushrn(b);b-- >0;)k.isOdd()&&k.iadd(m),k.iushrn(1);for(var p=0,T=1;!(w.words[0]&T)&&p<26;++p,T<<=1);if(p>0)for(w.iushrn(p);p-- >0;)g.isOdd()&&g.iadd(m),g.iushrn(1);f.cmp(w)>=0?(f.isub(w),k.isub(g)):(w.isub(f),g.isub(k))}var F;return f.cmpn(1)===0?F=k:F=g,F.cmpn(0)<0&&F.iadd(l),F},r.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var f=this.clone(),w=l.clone();f.negative=0,w.negative=0;for(var k=0;f.isEven()&&w.isEven();k++)f.iushrn(1),w.iushrn(1);do{for(;f.isEven();)f.iushrn(1);for(;w.isEven();)w.iushrn(1);var g=f.cmp(w);if(g<0){var m=f;f=w,w=m}else if(g===0||w.cmpn(1)===0)break;f.isub(w)}while(!0);return w.iushln(k)},r.prototype.invm=function(l){return this.egcd(l).a.umod(l)},r.prototype.isEven=function(){return(this.words[0]&1)===0},r.prototype.isOdd=function(){return(this.words[0]&1)===1},r.prototype.andln=function(l){return this.words[0]&l},r.prototype.bincn=function(l){n(typeof l=="number");var f=l%26,w=(l-f)/26,k=1<<f;if(this.length<=w)return this._expand(w+1),this.words[w]|=k,this;for(var g=k,m=w;g!==0&&m<this.length;m++){var b=this.words[m]|0;b+=g,g=b>>>26,b&=67108863,this.words[m]=b}return g!==0&&(this.words[m]=g,this.length++),this},r.prototype.isZero=function(){return this.length===1&&this.words[0]===0},r.prototype.cmpn=function(l){var f=l<0;if(this.negative!==0&&!f)return-1;if(this.negative===0&&f)return 1;this._strip();var w;if(this.length>1)w=1;else{f&&(l=-l),n(l<=67108863,"Number is too big");var k=this.words[0]|0;w=k===l?0:k<l?-1:1}return this.negative!==0?-w|0:w},r.prototype.cmp=function(l){if(this.negative!==0&&l.negative===0)return-1;if(this.negative===0&&l.negative!==0)return 1;var f=this.ucmp(l);return this.negative!==0?-f|0:f},r.prototype.ucmp=function(l){if(this.length>l.length)return 1;if(this.length<l.length)return-1;for(var f=0,w=this.length-1;w>=0;w--){var k=this.words[w]|0,g=l.words[w]|0;if(k!==g){k<g?f=-1:k>g&&(f=1);break}}return f},r.prototype.gtn=function(l){return this.cmpn(l)===1},r.prototype.gt=function(l){return this.cmp(l)===1},r.prototype.gten=function(l){return this.cmpn(l)>=0},r.prototype.gte=function(l){return this.cmp(l)>=0},r.prototype.ltn=function(l){return this.cmpn(l)===-1},r.prototype.lt=function(l){return this.cmp(l)===-1},r.prototype.lten=function(l){return this.cmpn(l)<=0},r.prototype.lte=function(l){return this.cmp(l)<=0},r.prototype.eqn=function(l){return this.cmpn(l)===0},r.prototype.eq=function(l){return this.cmp(l)===0},r.red=function(l){return new W(l)},r.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},r.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(l){return this.red=l,this},r.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},r.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},r.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},r.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},r.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},r.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},r.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},r.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},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(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var X={k256:null,p224:null,p192:null,p25519:null};function Y(N,l){this.name=N,this.p=new r(l,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Y.prototype._tmp=function(){var l=new r(null);return l.words=new Array(Math.ceil(this.n/13)),l},Y.prototype.ireduce=function(l){var f=l,w;do this.split(f,this.tmp),f=this.imulK(f),f=f.iadd(this.tmp),w=f.bitLength();while(w>this.n);var k=w<this.n?-1:f.ucmp(this.p);return k===0?(f.words[0]=0,f.length=1):k>0?f.isub(this.p):f.strip!==void 0?f.strip():f._strip(),f},Y.prototype.split=function(l,f){l.iushrn(this.n,0,f)},Y.prototype.imulK=function(l){return l.imul(this.k)};function oe(){Y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(oe,Y),oe.prototype.split=function(l,f){for(var w=4194303,k=Math.min(l.length,9),g=0;g<k;g++)f.words[g]=l.words[g];if(f.length=k,l.length<=9){l.words[0]=0,l.length=1;return}var m=l.words[9];for(f.words[f.length++]=m&w,g=10;g<l.length;g++){var b=l.words[g]|0;l.words[g-10]=(b&w)<<4|m>>>22,m=b}m>>>=22,l.words[g-10]=m,m===0&&l.length>10?l.length-=10:l.length-=9},oe.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var f=0,w=0;w<l.length;w++){var k=l.words[w]|0;f+=k*977,l.words[w]=f&67108863,f=k*64+(f/67108864|0)}return l.words[l.length-1]===0&&(l.length--,l.words[l.length-1]===0&&l.length--),l};function $(){Y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i($,Y);function ne(){Y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(ne,Y);function G(){Y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(G,Y),G.prototype.imulK=function(l){for(var f=0,w=0;w<l.length;w++){var k=(l.words[w]|0)*19+f,g=k&67108863;k>>>=26,l.words[w]=g,f=k}return f!==0&&(l.words[l.length++]=f),l},r._prime=function(l){if(X[l])return X[l];var f;if(l==="k256")f=new oe;else if(l==="p224")f=new $;else if(l==="p192")f=new ne;else if(l==="p25519")f=new G;else throw new Error("Unknown prime "+l);return X[l]=f,f};function W(N){if(typeof N=="string"){var l=r._prime(N);this.m=l.p,this.prime=l}else n(N.gtn(1),"modulus must be greater than 1"),this.m=N,this.prime=null}W.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},W.prototype._verify2=function(l,f){n((l.negative|f.negative)===0,"red works only with positives"),n(l.red&&l.red===f.red,"red works only with red numbers")},W.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(u(l,l.umod(this.m)._forceRed(this)),l)},W.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},W.prototype.add=function(l,f){this._verify2(l,f);var w=l.add(f);return w.cmp(this.m)>=0&&w.isub(this.m),w._forceRed(this)},W.prototype.iadd=function(l,f){this._verify2(l,f);var w=l.iadd(f);return w.cmp(this.m)>=0&&w.isub(this.m),w},W.prototype.sub=function(l,f){this._verify2(l,f);var w=l.sub(f);return w.cmpn(0)<0&&w.iadd(this.m),w._forceRed(this)},W.prototype.isub=function(l,f){this._verify2(l,f);var w=l.isub(f);return w.cmpn(0)<0&&w.iadd(this.m),w},W.prototype.shl=function(l,f){return this._verify1(l),this.imod(l.ushln(f))},W.prototype.imul=function(l,f){return this._verify2(l,f),this.imod(l.imul(f))},W.prototype.mul=function(l,f){return this._verify2(l,f),this.imod(l.mul(f))},W.prototype.isqr=function(l){return this.imul(l,l.clone())},W.prototype.sqr=function(l){return this.mul(l,l)},W.prototype.sqrt=function(l){if(l.isZero())return l.clone();var f=this.m.andln(3);if(n(f%2===1),f===3){var w=this.m.add(new r(1)).iushrn(2);return this.pow(l,w)}for(var k=this.m.subn(1),g=0;!k.isZero()&&k.andln(1)===0;)g++,k.iushrn(1);n(!k.isZero());var m=new r(1).toRed(this),b=m.redNeg(),y=this.m.subn(1).iushrn(1),p=this.m.bitLength();for(p=new r(2*p*p).toRed(this);this.pow(p,y).cmp(b)!==0;)p.redIAdd(b);for(var T=this.pow(p,k),F=this.pow(l,k.addn(1).iushrn(1)),z=this.pow(l,k),Q=g;z.cmp(m)!==0;){for(var H=z,ae=0;H.cmp(m)!==0;ae++)H=H.redSqr();n(ae<Q);var fe=this.pow(T,new r(1).iushln(Q-ae-1));F=F.redMul(fe),T=fe.redSqr(),z=z.redMul(T),Q=ae}return F},W.prototype.invm=function(l){var f=l._invmp(this.m);return f.negative!==0?(f.negative=0,this.imod(f).redNeg()):this.imod(f)},W.prototype.pow=function(l,f){if(f.isZero())return new r(1).toRed(this);if(f.cmpn(1)===0)return l.clone();var w=4,k=new Array(1<<w);k[0]=new r(1).toRed(this),k[1]=l;for(var g=2;g<k.length;g++)k[g]=this.mul(k[g-1],l);var m=k[0],b=0,y=0,p=f.bitLength()%26;for(p===0&&(p=26),g=f.length-1;g>=0;g--){for(var T=f.words[g],F=p-1;F>=0;F--){var z=T>>F&1;if(m!==k[0]&&(m=this.sqr(m)),z===0&&b===0){y=0;continue}b<<=1,b|=z,y++,!(y!==w&&(g!==0||F!==0))&&(m=this.mul(m,k[b]),y=0,b=0)}p=26}return m},W.prototype.convertTo=function(l){var f=l.umod(this.m);return f===l?f.clone():f},W.prototype.convertFrom=function(l){var f=l.clone();return f.red=null,f},r.mont=function(l){return new I(l)};function I(N){W.call(this,N),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(I,W),I.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},I.prototype.convertFrom=function(l){var f=this.imod(l.mul(this.rinv));return f.red=null,f},I.prototype.imul=function(l,f){if(l.isZero()||f.isZero())return l.words[0]=0,l.length=1,l;var w=l.imul(f),k=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=w.isub(k).iushrn(this.shift),m=g;return g.cmp(this.m)>=0?m=g.isub(this.m):g.cmpn(0)<0&&(m=g.iadd(this.m)),m._forceRed(this)},I.prototype.mul=function(l,f){if(l.isZero()||f.isZero())return new r(0)._forceRed(this);var w=l.mul(f),k=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=w.isub(k).iushrn(this.shift),m=g;return g.cmp(this.m)>=0?m=g.isub(this.m):g.cmpn(0)<0&&(m=g.iadd(this.m)),m._forceRed(this)},I.prototype.invm=function(l){var f=this.imod(l._invmp(this.m).mul(this.r2));return f._forceRed(this)}})(typeof Wl>"u"||Wl,Bp)});var jp=Ue((y4,Mp)=>{"use strict";function Xv(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var i=0;i<t.length;i++){var r=t.charAt(i),o=r.charCodeAt(0);if(e[o]!==255)throw new TypeError(r+" is ambiguous");e[o]=i}var s=t.length,a=t.charAt(0),c=Math.log(s)/Math.log(256),u=Math.log(256)/Math.log(s);function d(C){if(C instanceof Uint8Array||(ArrayBuffer.isView(C)?C=new Uint8Array(C.buffer,C.byteOffset,C.byteLength):Array.isArray(C)&&(C=Uint8Array.from(C))),!(C instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(C.length===0)return"";for(var D=0,O=0,B=0,j=C.length;B!==j&&C[B]===0;)B++,D++;for(var M=(j-B)*u+1>>>0,R=new Uint8Array(M);B!==j;){for(var K=C[B],X=0,Y=M-1;(K!==0||X<O)&&Y!==-1;Y--,X++)K+=256*R[Y]>>>0,R[Y]=K%s>>>0,K=K/s>>>0;if(K!==0)throw new Error("Non-zero carry");O=X,B++}for(var oe=M-O;oe!==M&&R[oe]===0;)oe++;for(var $=a.repeat(D);oe<M;++oe)$+=t.charAt(R[oe]);return $}function h(C){if(typeof C!="string")throw new TypeError("Expected String");if(C.length===0)return new Uint8Array;for(var D=0,O=0,B=0;C[D]===a;)O++,D++;for(var j=(C.length-D)*c+1>>>0,M=new Uint8Array(j);C[D];){var R=e[C.charCodeAt(D)];if(R===255)return;for(var K=0,X=j-1;(R!==0||K<B)&&X!==-1;X--,K++)R+=s*M[X]>>>0,M[X]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");B=K,D++}for(var Y=j-B;Y!==j&&M[Y]===0;)Y++;for(var oe=new Uint8Array(O+(j-Y)),$=O;Y!==j;)oe[$++]=M[Y++];return oe}function _(C){var D=h(C);if(D)return D;throw new Error("Non-base"+s+" character")}return{encode:d,decodeUnsafe:h,decode:_}}Mp.exports=Xv});var Rp=Ue((b4,Np)=>{"use strict";var Zv=jp(),Jv="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";Np.exports=Zv(Jv)});var bm={};wp(bm,{__addDisposableResource:()=>wm,__assign:()=>vc,__asyncDelegator:()=>lm,__asyncGenerator:()=>um,__asyncValues:()=>dm,__await:()=>Eo,__awaiter:()=>im,__classPrivateFieldGet:()=>mm,__classPrivateFieldIn:()=>_m,__classPrivateFieldSet:()=>gm,__createBinding:()=>Tc,__decorate:()=>em,__disposeResources:()=>ym,__esDecorate:()=>V1,__exportStar:()=>om,__extends:()=>Yp,__generator:()=>rm,__importDefault:()=>pm,__importStar:()=>hm,__makeTemplateObject:()=>fm,__metadata:()=>nm,__param:()=>tm,__propKey:()=>W1,__read:()=>id,__rest:()=>Qp,__runInitializers:()=>K1,__setFunctionName:()=>H1,__spread:()=>sm,__spreadArray:()=>cm,__spreadArrays:()=>am,__values:()=>kc,default:()=>J1});function Yp(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");nd(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Qp(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 em(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 tm(t,e){return function(n,i){e(n,i,t)}}function V1(t,e,n,i,r,o){function s(j){if(j!==void 0&&typeof j!="function")throw new TypeError("Function expected");return j}for(var a=i.kind,c=a==="getter"?"get":a==="setter"?"set":"value",u=!e&&t?i.static?t:t.prototype:null,d=e||(u?Object.getOwnPropertyDescriptor(u,i.name):{}),h,_=!1,C=n.length-1;C>=0;C--){var D={};for(var O in i)D[O]=O==="access"?{}:i[O];for(var O in i.access)D.access[O]=i.access[O];D.addInitializer=function(j){if(_)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(j||null))};var B=(0,n[C])(a==="accessor"?{get:d.get,set:d.set}:d[c],D);if(a==="accessor"){if(B===void 0)continue;if(B===null||typeof B!="object")throw new TypeError("Object expected");(h=s(B.get))&&(d.get=h),(h=s(B.set))&&(d.set=h),(h=s(B.init))&&r.unshift(h)}else(h=s(B))&&(a==="field"?r.unshift(h):d[c]=h)}u&&Object.defineProperty(u,i.name,d),_=!0}function K1(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 W1(t){return typeof t=="symbol"?t:"".concat(t)}function H1(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 nm(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function im(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(d){try{u(i.next(d))}catch(h){s(h)}}function c(d){try{u(i.throw(d))}catch(h){s(h)}}function u(d){d.done?o(d.value):r(d.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function rm(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(u){return function(d){return c([u,d])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(n=0)),n;)try{if(i=1,r&&(o=u[0]&2?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,r=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){n.label=u[1];break}if(u[0]===6&&n.label<o[1]){n.label=o[1],o=u;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(u);break}o[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(d){u=[6,d],r=0}finally{i=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function om(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Tc(e,t,n)}function kc(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 id(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 sm(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(id(arguments[e]));return t}function am(){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 cm(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 Eo(t){return this instanceof Eo?(this.v=t,this):new Eo(t)}function um(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(_){i[_]&&(r[_]=function(C){return new Promise(function(D,O){o.push([_,C,D,O])>1||a(_,C)})})}function a(_,C){try{c(i[_](C))}catch(D){h(o[0][3],D)}}function c(_){_.value instanceof Eo?Promise.resolve(_.value.v).then(u,d):h(o[0][2],_)}function u(_){a("next",_)}function d(_){a("throw",_)}function h(_,C){_(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function lm(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:Eo(t[r](s)),done:!1}:o?o(s):s}:o}}function dm(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 kc=="function"?kc(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,c){s=t[o](s),r(a,c,s.done,s.value)})}}function r(o,s,a,c){Promise.resolve(c).then(function(u){o({value:u,done:a})},s)}}function fm(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function hm(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)&&Tc(e,t,n);return X1(e,t),e}function pm(t){return t&&t.__esModule?t:{default:t}}function mm(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 gm(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 _m(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 wm(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 ym(t){function e(i){t.error=t.hasError?new Z1(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 nd,vc,Tc,X1,Z1,J1,vm=Rv(()=>{"use strict";nd=function(t,e){return nd=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])},nd(t,e)};vc=function(){return vc=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},vc.apply(this,arguments)};Tc=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]};X1=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};Z1=typeof SuppressedError=="function"?SuppressedError:function(t,e,n){var i=new Error(n);return i.name="SuppressedError",i.error=t,i.suppressed=e,i};J1={__extends:Yp,__assign:vc,__rest:Qp,__decorate:em,__param:tm,__metadata:nm,__awaiter:im,__generator:rm,__createBinding:Tc,__exportStar:om,__values:kc,__read:id,__spread:sm,__spreadArrays:am,__spreadArray:cm,__await:Eo,__asyncGenerator:um,__asyncDelegator:lm,__asyncValues:dm,__makeTemplateObject:fm,__importStar:hm,__importDefault:pm,__classPrivateFieldGet:mm,__classPrivateFieldSet:gm,__classPrivateFieldIn:_m,__addDisposableResource:wm,__disposeResources:ym}});var rd=Ue((Cc,km)=>{"use strict";(function(t,e){typeof Cc=="object"&&typeof km<"u"?e(Cc,(vm(),bp(bm))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(Cc,function(t,e){"use strict";var n=function(){function g(m,b,y){y===void 0&&(y=0),this.startVertex=m,this.endVertex=b,this.weight=y}return g.prototype.getKey=function(){var m=this.startVertex.getKey(),b=this.endVertex.getKey();return m+"_"+b},g.prototype.reverse=function(){var m=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=m,this},g.prototype.clone=function(){return new g(this.startVertex,this.endVertex,this.weight)},g.prototype.toString=function(){return this.getKey()},g}();function i(g,m,b){if(b===void 0&&(b="cc-graph"),!g)throw new Error((b?"["+b+"]":"")+" Invariant failed: "+m)}function r(g,m){m===void 0&&(m=!0);var b=typeof g<"u"&&g!==null;return m?b&&g!=="undefined"&&g!=="null":b}var o=function(){function g(m){i(r(m),"Graph vertex must have a value"),this.value=m,this.edges=new Map}return g.prototype.addEdge=function(m){return this.edges.set(m.getKey(),m),this},g.prototype.deleteEdge=function(m){this.edges.delete(m.getKey())},g.prototype.getNeighbors=function(){var m=this,b=this.getEdges(),y=function(p){return p.startVertex===m?p.endVertex:p.startVertex};return b.map(y)},g.prototype.getEdges=function(){return Array.from(this.edges.values())},g.prototype.getDegree=function(){return this.getEdges().length},g.prototype.hasEdge=function(m){var b=this.getEdges().find(function(y){return y===m});return!!b},g.prototype.hasNeighbor=function(m){var b=this.getEdges().find(function(y){return y.startVertex===m||y.endVertex===m});return!!b},g.prototype.findEdge=function(m){var b=function(p){return p.startVertex===m||p.endVertex===m},y=this.getEdges().find(b);return y||null},g.prototype.getKey=function(){return this.value},g.prototype.deleteAllEdges=function(){var m=this;return this.getEdges().forEach(function(b){return m.deleteEdge(b)}),this},g.prototype.toString=function(m){return m?m(this.value):""+this.value},g}(),s;(function(g){g[g.EQUAL=0]="EQUAL",g[g.GREATER=1]="GREATER",g[g.LESS=-1]="LESS"})(s||(s={}));var a=function(){function g(m){this.compare=m||g.defaultCompareFunction}return g.defaultCompareFunction=function(m,b){return m===b?s.EQUAL:m<b?s.LESS:s.GREATER},g.prototype.equal=function(m,b){return this.compare(m,b)===s.EQUAL},g.prototype.lessThan=function(m,b){return this.compare(m,b)===s.LESS},g.prototype.greaterThan=function(m,b){return this.compare(m,b)===s.GREATER},g.prototype.lessThanOrEqual=function(m,b){return this.lessThan(m,b)||this.equal(m,b)},g.prototype.greaterThanOrEqual=function(m,b){return this.greaterThan(m,b)||this.equal(m,b)},g.prototype.reverse=function(){var m=this.compare;this.compare=function(b,y){return m(y,b)}},g}(),c=function(){function g(m){this.value=m,this.next=null}return g}(),u=function(){function g(m){this.value=m,this.next=null,this.prev=null}return g}();var d=function(g,m){return d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,y){b.__proto__=y}||function(b,y){for(var p in y)y.hasOwnProperty(p)&&(b[p]=y[p])},d(g,m)};function h(g,m){d(g,m);function b(){this.constructor=g}g.prototype=m===null?Object.create(m):(b.prototype=m.prototype,new b)}function _(g,m){var b={label:0,sent:function(){if(T[0]&1)throw T[1];return T[1]},trys:[],ops:[]},y,p,T,F;return F={next:z(0),throw:z(1),return:z(2)},typeof Symbol=="function"&&(F[Symbol.iterator]=function(){return this}),F;function z(H){return function(ae){return Q([H,ae])}}function Q(H){if(y)throw new TypeError("Generator is already executing.");for(;b;)try{if(y=1,p&&(T=H[0]&2?p.return:H[0]?p.throw||((T=p.return)&&T.call(p),0):p.next)&&!(T=T.call(p,H[1])).done)return T;switch(p=0,T&&(H=[H[0]&2,T.value]),H[0]){case 0:case 1:T=H;break;case 4:return b.label++,{value:H[1],done:!1};case 5:b.label++,p=H[1],H=[0];continue;case 7:H=b.ops.pop(),b.trys.pop();continue;default:if(T=b.trys,!(T=T.length>0&&T[T.length-1])&&(H[0]===6||H[0]===2)){b=0;continue}if(H[0]===3&&(!T||H[1]>T[0]&&H[1]<T[3])){b.label=H[1];break}if(H[0]===6&&b.label<T[1]){b.label=T[1],T=H;break}if(T&&b.label<T[2]){b.label=T[2],b.ops.push(H);break}T[2]&&b.ops.pop(),b.trys.pop();continue}H=m.call(g,b)}catch(ae){H=[6,ae],p=0}finally{y=T=0}if(H[0]&5)throw H[1];return{value:H[0]?H[1]:void 0,done:!0}}}function C(g,m){var b=typeof Symbol=="function"&&g[Symbol.iterator];if(!b)return g;var y=b.call(g),p,T=[],F;try{for(;(m===void 0||m-- >0)&&!(p=y.next()).done;)T.push(p.value)}catch(z){F={error:z}}finally{try{p&&!p.done&&(b=y.return)&&b.call(y)}finally{if(F)throw F.error}}return T}function D(){for(var g=[],m=0;m<arguments.length;m++)g=g.concat(C(arguments[m]));return g}var O="obfuse error occur";function B(g,m){if(!g)throw new Error("[linked-list] "+(m||O))}var j=-1,M=function(){function g(){for(var m=this,b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];this._head=null,this._tail=null,this._length=0,this.compare=new a,b.length>0&&b.forEach(function(p){m.append(p)})}return Object.defineProperty(g.prototype,"head",{get:function(){return this._head?this._head.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(g.prototype,"tail",{get:function(){return this._tail?this._tail.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(g.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),Object.defineProperty(g.prototype,"loopLength",{get:function(){var m=!1,b=1;if(!this._head)return 0;for(var y=this._head,p=this._head;p.next&&p.next.next;)if(p=p.next.next,y=y.next,y===p){m=!0;break}if(m){for(p=p.next;y!==p;)b++,p=p.next;return b}else return 0},enumerable:!0,configurable:!0}),g.prototype.getNode=function(m){var b=this._length;B(b>0&&m>=0&&m<b,"[linked-list] index "+m+" out of scope of list, which length is "+b);for(var y=this._head,p=0;p<m;)y=y.next,p++;return y},g.prototype.get=function(m){var b=this.getNode(m);return b?b.value:null},g.prototype.find=function(m){var b=m.value,y=m.callback;if(!this._head)return null;for(var p=this._head;p;){if(y&&y(p.value)||b!==void 0&&this.compare.equal(p.value,b))return p;p=p.next}return null},g.prototype.indexOf=function(m){if(!this._head)return j;for(var b=this._head,y=-1;b.next;){if(y++,this.compare.equal(b.value,m))return y;b=b.next}return b===this._tail&&this.compare.equal(b.value,m)&&(y+=1),y},g.prototype.first=function(m){B(m>=0,"[linked-list] param 'num' ("+m+") should not less than 0");for(var b=this.iterator(),y=[],p=Math.min(m,this.length),T=0;T<p;T++){var F=b.next();y.push(F.value)}return y},g.prototype.toArray=function(){return D(this)},g.prototype.isEmpty=function(){return this._head===null},g.prototype.iterator=function(){var m;return _(this,function(b){switch(b.label){case 0:m=this._head,b.label=1;case 1:return m?[4,m.value]:[3,3];case 2:return b.sent(),m=m.next,[3,1];case 3:return[2]}})},g.prototype[Symbol.iterator]=function(){return this.iterator()},g}(),R=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];return g.apply(this,D(b))||this}return m.prototype.append=function(b){var y=new c(b);return this._tail?(this._tail.next=y,this._tail=y):this._head=this._tail=y,this._length++,!0},m.prototype.prepend=function(b){var y=new c(b);return this._head?(y.next=this._head,this._head=y):this._head=this._tail=y,this._length++,!0},m.prototype.remove=function(b){var y=this._head;if(y){if(this.compare.equal(y.value,b))return y.next?(this._head=y.next,y.next=null):this._head=this._tail=null,this._length--,b;for(var p=y;;){if(this.compare.equal(y.value,b))return y.next?p.next=y.next:(this._tail=p,this._tail.next=null),y.next=null,this._length--,b;if(y.next)p=y,y=y.next;else return}}},m.prototype.removeHead=function(){var b=this._head;if(b)return this._head.next?(this._head=b.next,b.next=null):(this._head=null,this._tail=null),this._length--,b.value},m.prototype.removeTail=function(){var b=this._tail;if(b){if(!this._head.next)this._head=null,this._tail=null;else{for(var y=this._head;y.next!==b;)y=y.next;y.next=null,this._tail=y}return this._length--,b.value}},m.prototype.reverse=function(){if(this._head){var b=this._head,y=null,p;for(this._tail=this._head;b!==null;)p=b.next,b.next=y,y=b,b=p;this._head=y}},m.prototype.clone=function(){var b=this.toArray();return new(m.bind.apply(m,D([void 0],b)))},m}(M),K=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];var p=g.apply(this,D(b))||this;return p.cyclization(),p}return m.prototype.iterator=function(){var b;return _(this,function(y){switch(y.label){case 0:b=this._head,y.label=1;case 1:return b?[4,b.value]:[3,3];case 2:return y.sent(),b=b.next,b===this._head&&(b=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var b;return _(this,function(y){switch(y.label){case 0:b=this._head,y.label=1;case 1:return b?[4,b.value]:[3,3];case 2:return y.sent(),b=b.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(b){for(var y=[],p=1;p<arguments.length;p++)y[p-1]=arguments[p];this.breakCircle();var T=g.prototype[b].apply(this,y);return this.cyclization(),T},m.prototype.getNode=function(b){return this.mapToNormalListFn("getNode",b)},m.prototype.append=function(b){return this.mapToNormalListFn("append",b)},m.prototype.prepend=function(b){return this.mapToNormalListFn("prepend",b)},m.prototype.find=function(b){return this.mapToNormalListFn("find",b)},m.prototype.indexOf=function(b){return this.mapToNormalListFn("indexOf",b)},m.prototype.remove=function(b){return this.mapToNormalListFn("remove",b)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(b){B(b>=0,"[linked-list] param 'num' ("+b+") should not less than 0");for(var y=this.circleIterator(),p=[],T=0;T<b;T++){var F=y.next();p.push(F.value)}return p},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(R),X=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];var p=g.apply(this,D(b))||this;return p.cyclization(),p}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 b=this.toArray();return new(m.bind.apply(m,D([void 0],b)))},m}(K),Y=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];return g.apply(this,D(b))||this}return m.prototype.append=function(b){var y=new u(b);return this._tail?(this._tail.next=y,y.prev=this._tail,this._tail=y):this._head=this._tail=y,this._length++,!0},m.prototype.prepend=function(b){var y=new u(b);return this._head?(y.next=this._head,this._head.prev=y,this._head=y):this._head=this._tail=y,this._length++,!0},m.prototype.remove=function(b){var y=this._head;if(y){if(this.compare.equal(y.value,b))return y.next?(this._head=y.next,this._head.prev=null,y.next=y.prev=null):this._head=this._tail=null,this._length--,b;for(;;){if(this.compare.equal(y.value,b))return y.next?(y.prev.next=y.next,y.next.prev=y.prev,y.next=y.prev=null):(y.prev.next=null,this._tail=y.prev,y.next=y.prev=null),this._length--,y.value;if(y.next)y=y.next;else return}}},m.prototype.removeHead=function(){var b=this._head;if(b)return this._head.next?(b.next.prev=null,this._head=b.next,b.next=null):(this._head=null,this._tail=null),this._length--,b.value},m.prototype.removeTail=function(){var b=this._tail;if(b)return this._head.next?(b.prev.next=null,this._tail=b.prev,b.next=b.prev=null):(this._head=null,this._tail=null),this._length--,b.value},m.prototype.reverse=function(){if(this._head){var b=this._head,y=null,p;for(this._tail=this._head;b!==null;)p=b.next,b.next=y,b.prev=p,y=b,b=p;this._head=y}},m.prototype.clone=function(){var b=this.toArray();return new(m.bind.apply(m,D([void 0],b)))},m}(M),oe=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];var p=g.apply(this,D(b))||this;return p.cyclization(),p}return m.prototype.iterator=function(){var b;return _(this,function(y){switch(y.label){case 0:b=this._head,y.label=1;case 1:return b?[4,b.value]:[3,3];case 2:return y.sent(),b=b.next,b===this._head&&(b=null),[3,1];case 3:return[2]}})},m.prototype.circleIterator=function(){var b;return _(this,function(y){switch(y.label){case 0:b=this._head,y.label=1;case 1:return b?[4,b.value]:[3,3];case 2:return y.sent(),b=b.next,[3,1];case 3:return[2]}})},m.prototype[Symbol.iterator]=function(){return this.iterator()},m.prototype.mapToNormalListFn=function(b){for(var y=[],p=1;p<arguments.length;p++)y[p-1]=arguments[p];this.breakCircle();var T=g.prototype[b].apply(this,y);return this.cyclization(),T},m.prototype.getNode=function(b){return this.mapToNormalListFn("getNode",b)},m.prototype.append=function(b){return this.mapToNormalListFn("append",b)},m.prototype.prepend=function(b){return this.mapToNormalListFn("prepend",b)},m.prototype.find=function(b){return this.mapToNormalListFn("find",b)},m.prototype.indexOf=function(b){return this.mapToNormalListFn("indexOf",b)},m.prototype.remove=function(b){return this.mapToNormalListFn("remove",b)},m.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},m.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},m.prototype.first=function(b){B(b>=0,"[linked-list] param 'num' ("+b+") should not less than 0");for(var y=this.circleIterator(),p=[],T=0;T<b;T++){var F=y.next();p.push(F.value)}return p},m.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},m.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},m}(Y),$=function(g){h(m,g);function m(){for(var b=[],y=0;y<arguments.length;y++)b[y]=arguments[y];var p=g.apply(this,D(b))||this;return p.cyclization(),p}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 b=this.toArray();return new(m.bind.apply(m,D([void 0],b)))},m}(oe);function ne(g,m){var b=typeof Symbol=="function"&&g[Symbol.iterator];if(!b)return g;var y=b.call(g),p,T=[],F;try{for(;(m===void 0||m-- >0)&&!(p=y.next()).done;)T.push(p.value)}catch(z){F={error:z}}finally{try{p&&!p.done&&(b=y.return)&&b.call(y)}finally{if(F)throw F.error}}return T}function G(){for(var g=[],m=0;m<arguments.length;m++)g=g.concat(ne(arguments[m]));return g}var W=function(){function g(){for(var m=[],b=0;b<arguments.length;b++)m[b]=arguments[b];this.queue=new(R.bind.apply(R,G([void 0],m)))}return Object.defineProperty(g.prototype,"length",{get:function(){return this.queue.length},enumerable:!0,configurable:!0}),Object.defineProperty(g.prototype,"peek",{get:function(){return this.queue.head},enumerable:!0,configurable:!0}),g.prototype.isEmpty=function(){return this.queue.isEmpty()},g.prototype.enqueue=function(m){return this.queue.append(m)},g.prototype.dequeue=function(){var m=this.queue.removeHead();return typeof m<"u"?m:void 0},g.prototype.toArray=function(){return this.queue.toArray()},g}();function I(g,m){var b=typeof Symbol=="function"&&g[Symbol.iterator];if(!b)return g;var y=b.call(g),p,T=[],F;try{for(;(m===void 0||m-- >0)&&!(p=y.next()).done;)T.push(p.value)}catch(z){F={error:z}}finally{try{p&&!p.done&&(b=y.return)&&b.call(y)}finally{if(F)throw F.error}}return T}function N(){for(var g=[],m=0;m<arguments.length;m++)g=g.concat(I(arguments[m]));return g}var l=function(){function g(){for(var m=[],b=0;b<arguments.length;b++)m[b]=arguments[b];this.stack=new(R.bind.apply(R,N([void 0],m)))}return Object.defineProperty(g.prototype,"length",{get:function(){return this.stack.length},enumerable:!0,configurable:!0}),Object.defineProperty(g.prototype,"peek",{get:function(){return this.stack.tail},enumerable:!0,configurable:!0}),g.prototype.isEmpty=function(){return this.stack.isEmpty()},g.prototype.push=function(m){return this.stack.append(m)},g.prototype.pop=function(){var m=this.stack.removeTail();return typeof m<"u"?m:void 0},g.prototype.popBottom=function(){var m=this.stack.removeHead();return typeof m<"u"?m:void 0},g.prototype.toArray=function(){return this.stack.toArray()},g}();function f(g,m,b,y){if(g){m.push(g),y.set(g.getKey(),!0);var p=g.getNeighbors().filter(function(T){return!y.get(T.getKey())});b.push(p)}}function w(g,m,b){var y=g.pop();y&&b.set(y.getKey(),!1),m.pop()}var k=function(){function g(m){m===void 0&&(m=!1),this.vertices={},this.edges={},this.isDirected=m}return g.prototype.addVertex=function(m){return this.vertices[m.getKey()]=m,this},g.prototype.getVertexByKey=function(m){return this.vertices[m]},g.prototype.getNeighbors=function(m){return m.getNeighbors()},g.prototype.getAllVertices=function(){return Object.values(this.vertices)},g.prototype.getAllEdges=function(){return Object.values(this.edges)},g.prototype.addEdge=function(m,b){if(b===void 0&&(b=!1),this.edges[m.getKey()]){if(b)return this;i(!1,"Edge has already been added before")}var y=this.getVertexByKey(m.startVertex.getKey()),p=this.getVertexByKey(m.endVertex.getKey());if(y||(this.addVertex(m.startVertex),y=this.getVertexByKey(m.startVertex.getKey())),p||(this.addVertex(m.endVertex),p=this.getVertexByKey(m.endVertex.getKey())),this.edges[m.getKey()]=m,this.isDirected)y.addEdge(m);else{y.addEdge(m);var T=m.clone();p.addEdge(T.reverse())}return this},g.prototype.deleteEdge=function(m,b){if(b===void 0&&(b=!1),!this.edges[m.getKey()]){if(b)return this;i(!1,"Edge not found in graph")}delete this.edges[m.getKey()];var y=this.getVertexByKey(m.startVertex.getKey()),p=this.getVertexByKey(m.endVertex.getKey());return y.deleteEdge(m),p.deleteEdge(m),this},g.prototype.findEdge=function(m,b){var y=this.getVertexByKey(m.getKey());return y?y.findEdge(b):null},g.prototype.getWeight=function(){return this.getAllEdges().reduce(function(m,b){return m+b.weight},0)},g.prototype.reverse=function(){var m=this;return this.getAllEdges().forEach(function(b){m.deleteEdge(b),b.reverse(),m.addEdge(b)}),this},g.prototype.getVerticesIndices=function(){var m={};return this.getAllVertices().forEach(function(b,y){m[b.getKey()]=y}),m},g.prototype.getAdjacencyMatrix=function(){var m=this,b=this.getAllVertices(),y=this.getVerticesIndices(),p=Array(b.length).fill(null).map(function(){return Array(b.length).fill(1/0)});return b.forEach(function(T,F){T.getNeighbors().forEach(function(z){var Q=y[z.getKey()],H=m.findEdge(T,z);H&&(p[F][Q]=H.weight)})}),p},g.prototype.toString=function(){return Object.keys(this.vertices).toString()},g.prototype.bfs=function(m){var b,y,p;return e.__generator(this,function(T){switch(T.label){case 0:b=new Map,y=new W,y.enqueue(m),T.label=1;case 1:return y.isEmpty()?[3,4]:(p=y.dequeue(),p&&!b.has(p.getKey())?[4,p]:[3,3]);case 2:T.sent(),b.set(p.getKey(),p),p.getNeighbors().forEach(function(F){return y.enqueue(F)}),T.label=3;case 3:return[3,1];case 4:return[2]}})},g.prototype.dfs=function(m){var b,y,p;return e.__generator(this,function(T){switch(T.label){case 0:b=new Map,y=new l,y.push(m),T.label=1;case 1:return y.isEmpty()?[3,4]:(p=y.pop(),p&&!b.has(p.getKey())?[4,p]:[3,3]);case 2:T.sent(),b.set(p.getKey(),p),p.getNeighbors().forEach(function(F){return y.push(F)}),T.label=3;case 3:return[3,1];case 4:return[2]}})},g.prototype.findAllPath=function(m,b){var y,p,T,F,z,Q,H;return e.__generator(this,function(ae){switch(ae.label){case 0:return y=[],m!==b?[3,2]:(y.push(m),[4,y]);case 1:return ae.sent(),[2];case 2:p=new Map,T=new l,F=new l,f(m,T,F,p),ae.label=3;case 3:if(T.isEmpty())return[3,6];if(z=F.pop(),z&&z.length)Q=z.shift(),F.push(z),Q&&f(Q,T,F,p);else return F.push(z),w(T,F,p),[3,3];return H=T.peek,H!==b?[3,5]:[4,T.toArray()];case 4:ae.sent(),w(T,F,p),ae.label=5;case 5:return[3,3];case 6:return[2]}})},g}();t.GraphEdge=n,t.GraphVertex=o,t.Graph=k,Object.defineProperty(t,"__esModule",{value:!0})})});var Bs=Ue((y3,gg)=>{"use strict";var hT=Object.create,Gc=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,mT=Object.getOwnPropertyNames,gT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty,wT=(t,e)=>{for(var n in e)Gc(t,n,{get:e[n],enumerable:!0})},hg=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mT(e))!_T.call(t,r)&&r!==n&&Gc(t,r,{get:()=>e[r],enumerable:!(i=pT(e,r))||i.enumerable});return t},yT=(t,e,n)=>(n=t!=null?hT(gT(t)):{},hg(e||!t||!t.__esModule?Gc(n,"default",{value:t,enumerable:!0}):n,t)),bT=t=>hg(Gc({},"__esModule",{value:!0}),t),pg={};wT(pg,{fromB58:()=>kT,toB58:()=>vT});gg.exports=bT(pg);var mg=yT(Rp()),vT=t=>mg.default.encode(t),kT=t=>mg.default.decode(t)});var Ms=Ue((b3,wg)=>{"use strict";var Ad=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,CT=Object.getOwnPropertyNames,AT=Object.prototype.hasOwnProperty,ST=(t,e)=>{for(var n in e)Ad(t,n,{get:e[n],enumerable:!0})},IT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of CT(e))!AT.call(t,r)&&r!==n&&Ad(t,r,{get:()=>e[r],enumerable:!(i=TT(e,r))||i.enumerable});return t},xT=t=>IT(Ad({},"__esModule",{value:!0}),t),_g={};ST(_g,{fromB64:()=>OT,toB64:()=>PT});wg.exports=xT(_g);function OT(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}var Cd=8192;function PT(t){if(t.length<Cd)return btoa(String.fromCharCode(...t));let e="";for(var n=0;n<t.length;n+=Cd){let i=t.slice(n,n+Cd);e+=String.fromCharCode(...i)}return btoa(e)}});var js=Ue((v3,bg)=>{"use strict";var Sd=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,DT=Object.getOwnPropertyNames,BT=Object.prototype.hasOwnProperty,MT=(t,e)=>{for(var n in e)Sd(t,n,{get:e[n],enumerable:!0})},jT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of DT(e))!BT.call(t,r)&&r!==n&&Sd(t,r,{get:()=>e[r],enumerable:!(i=ET(e,r))||i.enumerable});return t},NT=t=>jT(Sd({},"__esModule",{value:!0}),t),yg={};MT(yg,{fromHEX:()=>RT,toHEX:()=>FT});bg.exports=NT(yg);function RT(t){let e=t.startsWith("0x")?t.slice(2):t,i=(e.length%2===0?e:`0${e}}`).match(/.{2}/g)?.map(r=>parseInt(r,16))??[];return Uint8Array.from(i)}function FT(t){return t.reduce((e,n)=>e+n.toString(16).padStart(2,"0"),"")}});var Ns=Ue((k3,kg)=>{"use strict";var Id=Object.defineProperty,qT=Object.getOwnPropertyDescriptor,LT=Object.getOwnPropertyNames,UT=Object.prototype.hasOwnProperty,$T=(t,e)=>{for(var n in e)Id(t,n,{get:e[n],enumerable:!0})},GT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of LT(e))!UT.call(t,r)&&r!==n&&Id(t,r,{get:()=>e[r],enumerable:!(i=qT(e,r))||i.enumerable});return t},zT=t=>GT(Id({},"__esModule",{value:!0}),t),vg={};$T(vg,{ulebDecode:()=>KT,ulebEncode:()=>VT});kg.exports=zT(vg);function VT(t){let e=[],n=0;if(t===0)return[0];for(;t>0;)e[n]=t&127,(t>>=7)&&(e[n]|=128),n+=1;return e}function KT(t){let e=0,n=0,i=0;for(;;){let r=t[i];if(i+=1,e|=(r&127)<<n,!(r&128))break;n+=7}return{value:e,length:i}}});var zc=Ue((T3,Cg)=>{"use strict";var Od=Object.defineProperty,WT=Object.getOwnPropertyDescriptor,HT=Object.getOwnPropertyNames,XT=Object.prototype.hasOwnProperty,ZT=(t,e)=>{for(var n in e)Od(t,n,{get:e[n],enumerable:!0})},JT=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of HT(e))!XT.call(t,r)&&r!==n&&Od(t,r,{get:()=>e[r],enumerable:!(i=WT(e,r))||i.enumerable});return t},YT=t=>JT(Od({},"__esModule",{value:!0}),t),Tg={};ZT(Tg,{BcsReader:()=>xd});Cg.exports=YT(Tg);var QT=Ns(),xd=class{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer)}shift(e){return this.bytePosition+=e,this}read8(){let e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){let e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){let e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){let e=this.read32(),i=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+i).toString(10)}read128(){let e=BigInt(this.read64()),i=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+i).toString(10)}read256(){let e=BigInt(this.read128()),i=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+i).toString(10)}readBytes(e){let n=this.bytePosition+this.dataView.byteOffset,i=new Uint8Array(this.dataView.buffer,n,e);return this.shift(e),i}readULEB(){let e=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,e),{value:i,length:r}=(0,QT.ulebDecode)(n);return this.shift(r),i}readVec(e){let n=this.readULEB(),i=[];for(let r=0;r<n;r++)i.push(e(this,r,n));return i}}});var Vc=Ue((C3,Og)=>{"use strict";var Pd=Object.defineProperty,eC=Object.getOwnPropertyDescriptor,tC=Object.getOwnPropertyNames,nC=Object.prototype.hasOwnProperty,iC=(t,e)=>{for(var n in e)Pd(t,n,{get:e[n],enumerable:!0})},rC=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of tC(e))!nC.call(t,r)&&r!==n&&Pd(t,r,{get:()=>e[r],enumerable:!(i=eC(e,r))||i.enumerable});return t},oC=t=>rC(Pd({},"__esModule",{value:!0}),t),Ag={};iC(Ag,{decodeStr:()=>aC,encodeStr:()=>sC,splitGenericParameters:()=>cC});Og.exports=oC(Ag);var Sg=Bs(),Ig=Ms(),xg=js();function sC(t,e){switch(e){case"base58":return(0,Sg.toB58)(t);case"base64":return(0,Ig.toB64)(t);case"hex":return(0,xg.toHEX)(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function aC(t,e){switch(e){case"base58":return(0,Sg.fromB58)(t);case"base64":return(0,Ig.fromB64)(t);case"hex":return(0,xg.fromHEX)(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function cC(t,e=["<",">"]){let[n,i]=e,r=[],o="",s=0;for(let a=0;a<t.length;a++){let c=t[a];if(c===n&&s++,c===i&&s--,s===0&&c===","){r.push(o.trim()),o="";continue}o+=c}return r.push(o.trim()),r}});var Kc=Ue((A3,Eg)=>{"use strict";var Bd=Object.defineProperty,uC=Object.getOwnPropertyDescriptor,lC=Object.getOwnPropertyNames,dC=Object.prototype.hasOwnProperty,fC=(t,e)=>{for(var n in e)Bd(t,n,{get:e[n],enumerable:!0})},hC=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lC(e))!dC.call(t,r)&&r!==n&&Bd(t,r,{get:()=>e[r],enumerable:!(i=uC(e,r))||i.enumerable});return t},pC=t=>hC(Bd({},"__esModule",{value:!0}),t),Pg={};fC(Pg,{BcsWriter:()=>Dd});Eg.exports=pC(Pg);var mC=Ns(),gC=Vc(),Dd=class{constructor({size:e=1024,maxSize:n,allocateSize:i=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=n||e,this.allocateSize=i,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){let n=this.bytePosition+e;if(n>this.size){let i=Math.min(this.maxSize,this.size+this.allocateSize);if(n>i)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${n}`);this.size=i;let r=new ArrayBuffer(this.size);new Uint8Array(r).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(r)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return Ed(BigInt(e),8).forEach(n=>this.write8(n)),this}write128(e){return Ed(BigInt(e),16).forEach(n=>this.write8(n)),this}write256(e){return Ed(BigInt(e),32).forEach(n=>this.write8(n)),this}writeULEB(e){return(0,mC.ulebEncode)(e).forEach(n=>this.write8(n)),this}writeVec(e,n){return this.writeULEB(e.length),Array.from(e).forEach((i,r)=>n(this,i,r,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return(0,gC.encodeStr)(this.toBytes(),e)}};function Ed(t,e){let n=new Uint8Array(e),i=0;for(;t>0;)n[i]=Number(t%BigInt(256)),t=t/BigInt(256),i+=1;return n}});var Jc=Ue((S3,Ng)=>{"use strict";var Md=Object.defineProperty,_C=Object.getOwnPropertyDescriptor,wC=Object.getOwnPropertyNames,yC=Object.prototype.hasOwnProperty,bC=(t,e)=>{for(var n in e)Md(t,n,{get:e[n],enumerable:!0})},vC=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wC(e))!yC.call(t,r)&&r!==n&&Md(t,r,{get:()=>e[r],enumerable:!(i=_C(e,r))||i.enumerable});return t},kC=t=>vC(Md({},"__esModule",{value:!0}),t),Dg=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},Oi=(t,e,n)=>(Dg(t,e,"read from private field"),n?n.call(t):e.get(t)),Hc=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},Xc=(t,e,n,i)=>(Dg(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),Bg={};bC(Bg,{BcsType:()=>Fs,SerializedBcs:()=>Zc,bigUIntBcsType:()=>EC,dynamicSizeBcsType:()=>DC,fixedSizeBcsType:()=>jd,isSerializedBcs:()=>OC,lazyBcsType:()=>MC,stringLikeBcsType:()=>BC,uIntBcsType:()=>PC});Ng.exports=kC(Bg);var TC=Bs(),CC=Ms(),AC=js(),SC=zc(),IC=Ns(),xC=Kc(),Go,Rs,Wc,Sr,Mg=class{constructor(t){Hc(this,Go,void 0),Hc(this,Rs,void 0),this.name=t.name,this.read=t.read,this.serializedSize=t.serializedSize??(()=>null),Xc(this,Go,t.write),Xc(this,Rs,t.serialize??((e,n)=>{let i=new xC.BcsWriter({size:this.serializedSize(e)??void 0,...n});return Oi(this,Go).call(this,e,i),i.toBytes()})),this.validate=t.validate??(()=>{})}write(t,e){this.validate(t),Oi(this,Go).call(this,t,e)}serialize(t,e){return this.validate(t),new Zc(this,Oi(this,Rs).call(this,t,e))}parse(t){let e=new SC.BcsReader(t);return this.read(e)}transform({name:t,input:e,output:n}){return new Mg({name:t??this.name,read:i=>n(this.read(i)),write:(i,r)=>Oi(this,Go).call(this,e(i),r),serializedSize:i=>this.serializedSize(e(i)),serialize:(i,r)=>Oi(this,Rs).call(this,e(i),r),validate:i=>this.validate(e(i))})}},Fs=Mg;Go=new WeakMap;Rs=new WeakMap;var jg=Symbol.for("@mysten/serialized-bcs");function OC(t){return!!t&&typeof t=="object"&&t[jg]===!0}var Zc=class{constructor(e,n){Hc(this,Wc,void 0),Hc(this,Sr,void 0),Xc(this,Wc,e),Xc(this,Sr,n)}get[jg](){return!0}toBytes(){return Oi(this,Sr)}toHex(){return(0,AC.toHEX)(Oi(this,Sr))}toBase64(){return(0,CC.toB64)(Oi(this,Sr))}toBase58(){return(0,TC.toB58)(Oi(this,Sr))}parse(){return Oi(this,Wc).parse(Oi(this,Sr))}};Wc=new WeakMap;Sr=new WeakMap;function jd({size:t,...e}){return new Fs({...e,serializedSize:()=>t})}function PC({readMethod:t,writeMethod:e,...n}){return jd({...n,read:i=>i[t](),write:(i,r)=>r[e](i),validate:i=>{if(i<0||i>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${i}. Expected value in range 0-${n.maxValue}`);n.validate?.(i)}})}function EC({readMethod:t,writeMethod:e,...n}){return jd({...n,read:i=>i[t](),write:(i,r)=>r[e](BigInt(i)),validate:i=>{let r=BigInt(i);if(r<0||r>n.maxValue)throw new TypeError(`Invalid ${n.name} value: ${r}. Expected value in range 0-${n.maxValue}`);n.validate?.(r)}})}function DC({serialize:t,...e}){let n=new Fs({...e,serialize:t,write:(i,r)=>{for(let o of n.serialize(i).toBytes())r.write8(o)}});return n}function BC({toBytes:t,fromBytes:e,...n}){return new Fs({...n,read:i=>{let r=i.readULEB(),o=i.readBytes(r);return e(o)},write:(i,r)=>{let o=t(i);r.writeULEB(o.length);for(let s=0;s<o.length;s++)r.write8(o[s])},serialize:i=>{let r=t(i),o=(0,IC.ulebEncode)(r.length),s=new Uint8Array(o.length+r.length);return s.set(o,0),s.set(r,o.length),s},validate:i=>{if(typeof i!="string")throw new TypeError(`Invalid ${n.name} value: ${i}. Expected string`);n.validate?.(i)}})}function MC(t){let e=null;function n(){return e||(e=t()),e}return new Fs({name:"lazy",read:i=>n().read(i),serializedSize:i=>n().serializedSize(i),write:(i,r)=>n().write(i,r),serialize:(i,r)=>n().serialize(i,r).toBytes()})}});var qg=Ue((x3,Fg)=>{"use strict";var Nd=Object.defineProperty,jC=Object.getOwnPropertyDescriptor,NC=Object.getOwnPropertyNames,RC=Object.prototype.hasOwnProperty,FC=(t,e)=>{for(var n in e)Nd(t,n,{get:e[n],enumerable:!0})},qC=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of NC(e))!RC.call(t,r)&&r!==n&&Nd(t,r,{get:()=>e[r],enumerable:!(i=jC(e,r))||i.enumerable});return t},LC=t=>qC(Nd({},"__esModule",{value:!0}),t),Rg={};FC(Rg,{bcs:()=>Yc});Fg.exports=LC(Rg);var jn=Jc(),UC=Ns(),Yc={u8(t){return(0,jn.uIntBcsType)({name:"u8",readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...t})},u16(t){return(0,jn.uIntBcsType)({name:"u16",readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...t})},u32(t){return(0,jn.uIntBcsType)({name:"u32",readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...t})},u64(t){return(0,jn.bigUIntBcsType)({name:"u64",readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...t})},u128(t){return(0,jn.bigUIntBcsType)({name:"u128",readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...t})},u256(t){return(0,jn.bigUIntBcsType)({name:"u256",readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...t})},bool(t){return(0,jn.fixedSizeBcsType)({name:"bool",size:1,read:e=>e.read8()===1,write:(e,n)=>n.write8(e?1:0),...t,validate:e=>{if(t?.validate?.(e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(t){return(0,jn.dynamicSizeBcsType)({name:"uleb128",read:e=>e.readULEB(),serialize:e=>Uint8Array.from((0,UC.ulebEncode)(e)),...t})},bytes(t,e){return(0,jn.fixedSizeBcsType)({name:`bytes[${t}]`,size:t,read:n=>n.readBytes(t),write:(n,i)=>{for(let r=0;r<t;r++)i.write8(n[r]??0)},...e,validate:n=>{if(e?.validate?.(n),!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t)throw new TypeError(`Expected array of length ${t}, found ${n.length}`)}})},string(t){return(0,jn.stringLikeBcsType)({name:"string",toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...t})},fixedArray(t,e,n){return new jn.BcsType({name:`${e.name}[${t}]`,read:i=>{let r=new Array(t);for(let o=0;o<t;o++)r[o]=e.read(i);return r},write:(i,r)=>{for(let o of i)e.write(o,r)},...n,validate:i=>{if(n?.validate?.(i),!("length"in i))throw new TypeError(`Expected array, found ${typeof i}`);if(i.length!==t)throw new TypeError(`Expected array of length ${t}, found ${i.length}`)}})},option(t){return Yc.enum(`Option<${t.name}>`,{None:null,Some:t}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>"Some"in e?e.Some:null})},vector(t,e){return new jn.BcsType({name:`vector<${t.name}>`,read:n=>{let i=n.readULEB(),r=new Array(i);for(let o=0;o<i;o++)r[o]=t.read(n);return r},write:(n,i)=>{i.writeULEB(n.length);for(let r of n)t.write(r,i)},...e,validate:n=>{if(e?.validate?.(n),!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`)}})},tuple(t,e){return new jn.BcsType({name:`(${t.map(n=>n.name).join(", ")})`,serializedSize:n=>{let i=0;for(let r=0;r<t.length;r++){let o=t[r].serializedSize(n[r]);if(o==null)return null;i+=o}return i},read:n=>{let i=[];for(let r of t)i.push(r.read(n));return i},write:(n,i)=>{for(let r=0;r<t.length;r++)t[r].write(n[r],i)},...e,validate:n=>{if(e?.validate?.(n),!Array.isArray(n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==t.length)throw new TypeError(`Expected array of length ${t.length}, found ${n.length}`)}})},struct(t,e,n){let i=Object.entries(e);return new jn.BcsType({name:t,serializedSize:r=>{let o=0;for(let[s,a]of i){let c=a.serializedSize(r[s]);if(c==null)return null;o+=c}return o},read:r=>{let o={};for(let[s,a]of i)o[s]=a.read(r);return o},write:(r,o)=>{for(let[s,a]of i)a.write(r[s],o)},...n,validate:r=>{if(n?.validate?.(r),typeof r!="object"||r==null)throw new TypeError(`Expected object, found ${typeof r}`)}})},enum(t,e,n){let i=Object.entries(e);return new jn.BcsType({name:t,read:r=>{let o=r.readULEB(),[s,a]=i[o];return{[s]:a?.read(r)??!0}},write:(r,o)=>{let[s,a]=Object.entries(r)[0];for(let c=0;c<i.length;c++){let[u,d]=i[c];if(u===s){o.writeULEB(c),d?.write(a,o);return}}},...n,validate:r=>{if(n?.validate?.(r),typeof r!="object"||r==null)throw new TypeError(`Expected object, found ${typeof r}`);let o=Object.keys(r);if(o.length!==1)throw new TypeError(`Expected object with one key, found ${o.length}`);let[s]=o;if(!Object.hasOwn(e,s))throw new TypeError(`Invalid enum variant ${s}`)}})},map(t,e){return Yc.vector(Yc.tuple([t,e])).transform({name:`Map<${t.name}, ${e.name}>`,input:n=>[...n.entries()],output:n=>{let i=new Map;for(let[r,o]of n)i.set(r,o);return i}})},generic(t,e){return(...n)=>e(...n).transform({name:`${e.name}<${n.map(i=>i.name).join(", ")}>`,input:i=>i,output:i=>i})},lazy(t){return(0,jn.lazyBcsType)(t)}}});var Wg=Ue((O3,Kg)=>{"use strict";var Rd=Object.defineProperty,$C=Object.getOwnPropertyDescriptor,GC=Object.getOwnPropertyNames,zC=Object.prototype.hasOwnProperty,VC=(t,e)=>{for(var n in e)Rd(t,n,{get:e[n],enumerable:!0})},KC=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of GC(e))!zC.call(t,r)&&r!==n&&Rd(t,r,{get:()=>e[r],enumerable:!(i=$C(e,r))||i.enumerable});return t},WC=t=>KC(Rd({},"__esModule",{value:!0}),t),Gg={};VC(Gg,{BCS:()=>Tt,getRustConfig:()=>ZC,getSuiMoveConfig:()=>JC,registerPrimitives:()=>Vg});Kg.exports=WC(Gg);var Lg=Bs(),Qc=Ms(),Ug=Jc(),eu=js(),HC=zc(),$g=Vc(),XC=Kc(),zg=32,qs=class{constructor(t){if(this.types=new Map,this.counter=0,t instanceof qs){this.schema=t.schema,this.types=new Map(t.types);return}if(this.schema=t,this.registerAddressType(qs.ADDRESS,t.addressLength,t.addressEncoding),this.registerVectorType(t.vectorType),t.types&&t.types.structs)for(let e of Object.keys(t.types.structs))this.registerStructType(e,t.types.structs[e]);if(t.types&&t.types.enums)for(let e of Object.keys(t.types.enums))this.registerEnumType(e,t.types.enums[e]);if(t.types&&t.types.aliases)for(let e of Object.keys(t.types.aliases))this.registerAlias(e,t.types.aliases[e]);t.withPrimitives!==!1&&Vg(this)}tempKey(){return`bcs-struct-${++this.counter}`}ser(t,e,n){if(typeof t=="string"||Array.isArray(t)){let{name:i,params:r}=this.parseTypeName(t);return this.getTypeInterface(i).encode(this,e,n,r)}if(typeof t=="object"){let i=this.tempKey();return new qs(this).registerStructType(i,t).ser(i,e,n)}throw new Error(`Incorrect type passed into the '.ser()' function.
|
|
2
|
-
|
|
3
|
-
${JSON.stringify(t)}`)}hasType(t){return this.types.has(t)}registerAlias(t,e){return this.types.set(t,e),this}registerType(t,e,n,i=()=>!0){let{name:r,params:o}=this.parseTypeName(t);return this.types.set(r,{encode(s,a,c,u){let d=o.reduce((h,_,C)=>Object.assign(h,{[_]:u[C]}),{});return this._encodeRaw.call(s,new XC.BcsWriter(c),a,u,d)},decode(s,a,c){let u=o.reduce((d,h,_)=>Object.assign(d,{[h]:c[_]}),{});return this._decodeRaw.call(s,new HC.BcsReader(a),c,u)},_encodeRaw(s,a,c,u){if(i(a))return e.call(this,s,a,c,u);throw new Error(`Validation failed for type ${r}, data: ${a}`)},_decodeRaw(s,a,c){return n.call(this,s,a,c)}}),this}registerBcsType(t,e){return this.registerType(t,(n,i,r)=>{let o=r.map(s=>new Ug.BcsType({name:String(s),write:(a,c)=>{let{name:u,params:d}=this.parseTypeName(s),h=this.getTypeInterface(u),_=d.reduce((C,D,O)=>Object.assign(C,{[D]:r[O]}),{});return h._encodeRaw.call(this,c,a,d,_)},read:()=>{throw new Error("Not implemented")}}));return e(...o).write(i,n),n},(n,i)=>{let r=i.map(o=>new Ug.BcsType({name:String(o),write:(s,a)=>{throw new Error("Not implemented")},read:s=>{let{name:a,params:c}=this.parseTypeName(o),u=this.getTypeInterface(a),d=c.reduce((h,_,C)=>Object.assign(h,{[_]:i[C]}),{});return u._decodeRaw.call(this,s,c,d)}}));return e(...r).read(n)}),this}registerAddressType(t,e,n="hex"){switch(n){case"base64":return this.registerType(t,function(r,o){return(0,Qc.fromB64)(o).reduce((s,a)=>s.write8(a),r)},function(r){return(0,Qc.toB64)(r.readBytes(e))});case"hex":return this.registerType(t,function(r,o){return(0,eu.fromHEX)(o).reduce((s,a)=>s.write8(a),r)},function(r){return(0,eu.toHEX)(r.readBytes(e))});default:throw new Error("Unsupported encoding! Use either hex or base64")}}registerVectorType(t){let{name:e,params:n}=this.parseTypeName(t);if(n.length>1)throw new Error("Vector can have only one type parameter; got "+e);return this.registerType(t,function(r,o,s,a){return r.writeVec(o,(c,u)=>{let d=s[0];if(!d)throw new Error(`Incorrect number of type parameters passed a to vector '${t}'`);let{name:h,params:_}=this.parseTypeName(d);if(this.hasType(h))return this.getTypeInterface(h)._encodeRaw.call(this,c,u,_,a);if(!(h in a))throw new Error(`Unable to find a matching type definition for ${h} in vector; make sure you passed a generic`);let{name:C,params:D}=this.parseTypeName(a[h]);return this.getTypeInterface(C)._encodeRaw.call(this,c,u,D,a)})},function(r,o,s){return r.readVec(a=>{let c=o[0];if(!c)throw new Error(`Incorrect number of type parameters passed to a vector '${t}'`);let{name:u,params:d}=this.parseTypeName(c);if(this.hasType(u))return this.getTypeInterface(u)._decodeRaw.call(this,a,d,s);if(!(u in s))throw new Error(`Unable to find a matching type definition for ${u} in vector; make sure you passed a generic`);let{name:h,params:_}=this.parseTypeName(s[u]);return this.getTypeInterface(h)._decodeRaw.call(this,a,_,s)})})}registerStructType(t,e){for(let s in e){let a=this.tempKey(),c=e[s];!Array.isArray(c)&&typeof c!="string"&&(e[s]=a,this.registerStructType(a,c))}let n=Object.freeze(e),i=Object.keys(n),{name:r,params:o}=this.parseTypeName(t);return this.registerType(t,function(a,c,u,d){if(!c||c.constructor!==Object)throw new Error(`Expected ${r} to be an Object, got: ${c}`);if(u.length!==o.length)throw new Error(`Incorrect number of generic parameters passed; expected: ${o.length}, got: ${u.length}`);for(let h of i){if(!(h in c))throw new Error(`Struct ${r} requires field ${h}:${n[h]}`);let{name:_,params:C}=this.parseTypeName(n[h]);if(!o.includes(_))this.getTypeInterface(_)._encodeRaw.call(this,a,c[h],C,d);else{let D=o.indexOf(_),{name:O,params:B}=this.parseTypeName(u[D]);if(this.hasType(O)){this.getTypeInterface(O)._encodeRaw.call(this,a,c[h],B,d);continue}if(!(O in d))throw new Error(`Unable to find a matching type definition for ${O} in ${r}; make sure you passed a generic`);let{name:j,params:M}=this.parseTypeName(d[O]);this.getTypeInterface(j)._encodeRaw.call(this,a,c[h],M,d)}}return a},function(a,c,u){if(c.length!==o.length)throw new Error(`Incorrect number of generic parameters passed; expected: ${o.length}, got: ${c.length}`);let d={};for(let h of i){let{name:_,params:C}=this.parseTypeName(n[h]);if(!o.includes(_))d[h]=this.getTypeInterface(_)._decodeRaw.call(this,a,C,u);else{let D=o.indexOf(_),{name:O,params:B}=this.parseTypeName(c[D]);if(this.hasType(O)){d[h]=this.getTypeInterface(O)._decodeRaw.call(this,a,B,u);continue}if(!(O in u))throw new Error(`Unable to find a matching type definition for ${O} in ${r}; make sure you passed a generic`);let{name:j,params:M}=this.parseTypeName(u[O]);d[h]=this.getTypeInterface(j)._decodeRaw.call(this,a,M,u)}}return d})}registerEnumType(t,e){for(let s in e){let a=this.tempKey(),c=e[s];c!==null&&!Array.isArray(c)&&typeof c!="string"&&(e[s]=a,this.registerStructType(a,c))}let n=Object.freeze(e),i=Object.keys(n),{name:r,params:o}=this.parseTypeName(t);return this.registerType(t,function(a,c,u,d){if(!c)throw new Error(`Unable to write enum "${r}", missing data.
|
|
4
|
-
|
|
5
|
-
Received: "${JSON.stringify(c)}"`);let h=Object.keys(c)[0];if(h===void 0)throw new Error(`Empty object passed as invariant of the enum "${r}"`);let _=i.indexOf(h);if(_===-1)throw new Error(`Unknown invariant of the enum "${r}", allowed values: "${i.join(" | ")}"; received "${h}"`);let C=i[_],D=n[C];if(a.write8(_),D===null)return a;let O=o.indexOf(D),B=O===-1?D:u[O];{let{name:j,params:M}=this.parseTypeName(B);return this.getTypeInterface(j)._encodeRaw.call(this,a,c[h],M,d)}},function(a,c,u){let d=a.readULEB(),h=i[d],_=n[h];if(d===-1)throw new Error(`Decoding type mismatch, expected enum "${r}" invariant index, received "${d}"`);if(_===null)return{[h]:!0};let C=o.indexOf(_),D=C===-1?_:c[C];{let{name:O,params:B}=this.parseTypeName(D);return{[h]:this.getTypeInterface(O)._decodeRaw.call(this,a,B,u)}}})}getTypeInterface(t){let e=this.types.get(t);if(typeof e=="string"){let n=[];for(;typeof e=="string";){if(n.includes(e))throw new Error(`Recursive definition found: ${n.join(" -> ")} -> ${e}`);n.push(e),e=this.types.get(e)}}if(e===void 0)throw new Error(`Type ${t} is not registered`);return e}parseTypeName(t){if(Array.isArray(t)){let[a,...c]=t;return{name:a,params:c}}if(typeof t!="string")throw new Error(`Illegal type passed as a name of the type: ${t}`);let[e,n]=this.schema.genericSeparators||["<",">"],i=t.indexOf(e),r=Array.from(t).reverse().indexOf(n);if(i===-1&&r===-1)return{name:t,params:[]};if(i===-1||r===-1)throw new Error(`Unclosed generic in name '${t}'`);let o=t.slice(0,i),s=(0,$g.splitGenericParameters)(t.slice(i+1,t.length-r-1),this.schema.genericSeparators);return{name:o,params:s}}},Tt=qs;Tt.U8="u8";Tt.U16="u16";Tt.U32="u32";Tt.U64="u64";Tt.U128="u128";Tt.U256="u256";Tt.BOOL="bool";Tt.VECTOR="vector";Tt.ADDRESS="address";Tt.STRING="string";Tt.HEX="hex-string";Tt.BASE58="base58-string";Tt.BASE64="base64-string";function Vg(t){t.registerType(Tt.U8,function(e,n){return e.write8(n)},function(e){return e.read8()},e=>e<256),t.registerType(Tt.U16,function(e,n){return e.write16(n)},function(e){return e.read16()},e=>e<65536),t.registerType(Tt.U32,function(e,n){return e.write32(n)},function(e){return e.read32()},e=>e<=4294967296n),t.registerType(Tt.U64,function(e,n){return e.write64(n)},function(e){return e.read64()}),t.registerType(Tt.U128,function(e,n){return e.write128(n)},function(e){return e.read128()}),t.registerType(Tt.U256,function(e,n){return e.write256(n)},function(e){return e.read256()}),t.registerType(Tt.BOOL,function(e,n){return e.write8(n)},function(e){return e.read8().toString(10)==="1"}),t.registerType(Tt.STRING,function(e,n){return e.writeVec(Array.from(n),(i,r)=>i.write8(r.charCodeAt(0)))},function(e){return e.readVec(n=>n.read8()).map(n=>String.fromCharCode(Number(n))).join("")},e=>!0),t.registerType(Tt.HEX,function(e,n){return e.writeVec(Array.from((0,eu.fromHEX)(n)),(i,r)=>i.write8(r))},function(e){let n=e.readVec(i=>i.read8());return(0,eu.toHEX)(new Uint8Array(n))}),t.registerType(Tt.BASE58,function(e,n){return e.writeVec(Array.from((0,Lg.fromB58)(n)),(i,r)=>i.write8(r))},function(e){let n=e.readVec(i=>i.read8());return(0,Lg.toB58)(new Uint8Array(n))}),t.registerType(Tt.BASE64,function(e,n){return e.writeVec(Array.from((0,Qc.fromB64)(n)),(i,r)=>i.write8(r))},function(e){let n=e.readVec(i=>i.read8());return(0,Qc.toB64)(new Uint8Array(n))})}function ZC(){return{genericSeparators:["<",">"],vectorType:"Vec",addressLength:zg,addressEncoding:"hex"}}function JC(){return{genericSeparators:["<",">"],vectorType:"vector",addressLength:zg,addressEncoding:"hex"}}});var zd=Ue((E3,Gd)=>{"use strict";var Ud=Object.defineProperty,YC=Object.getOwnPropertyDescriptor,QC=Object.getOwnPropertyNames,eA=Object.prototype.hasOwnProperty,tA=(t,e)=>{for(var n in e)Ud(t,n,{get:e[n],enumerable:!0})},Ld=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of QC(e))!eA.call(t,r)&&r!==n&&Ud(t,r,{get:()=>e[r],enumerable:!(i=YC(e,r))||i.enumerable});return t},nA=(t,e,n)=>(Ld(t,e,"default"),n&&Ld(n,e,"default")),iA=t=>Ld(Ud({},"__esModule",{value:!0}),t),$d={};tA($d,{BcsReader:()=>oA.BcsReader,BcsType:()=>Fd.BcsType,BcsWriter:()=>sA.BcsWriter,SerializedBcs:()=>Fd.SerializedBcs,bcs:()=>rA.bcs,decodeStr:()=>qd.decodeStr,encodeStr:()=>qd.encodeStr,fromB58:()=>Hg.fromB58,fromB64:()=>Xg.fromB64,fromHEX:()=>Zg.fromHEX,isSerializedBcs:()=>Fd.isSerializedBcs,splitGenericParameters:()=>qd.splitGenericParameters,toB58:()=>Hg.toB58,toB64:()=>Xg.toB64,toHEX:()=>Zg.toHEX});Gd.exports=iA($d);var Hg=Bs(),Xg=Ms(),Fd=Jc(),rA=qg(),Zg=js(),oA=zc(),qd=Vc(),sA=Kc();nA($d,Wg(),Gd.exports)});var ro=Ue((Jg,tu)=>{"use strict";(function(t){"use strict";var e=9e15,n=1e9,i="0123456789abcdef",r="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",o="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",s={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-e,maxE:e,crypto:!1},a,c,u,d,h=!0,_="[DecimalError] ",C=_+"Invalid argument: ",D=_+"Precision limit exceeded",O=_+"crypto unavailable",B="[object Decimal]",j=Math.floor,M=Math.pow,R=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,K=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,X=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Y=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,oe=1e7,$=7,ne=9007199254740991,G=r.length-1,W=o.length-1,I={toStringTag:B};I.absoluteValue=I.abs=function(){var v=new this.constructor(this);return v.s<0&&(v.s=1),m(v)},I.ceil=function(){return m(new this.constructor(this),this.e+1,2)},I.clampedTo=I.clamp=function(v,A){var S,x=this,P=x.constructor;if(v=new P(v),A=new P(A),!v.s||!A.s)return new P(NaN);if(v.gt(A))throw Error(C+A);return S=x.cmp(v),S<0?v:x.cmp(A)>0?A:new P(x)},I.comparedTo=I.cmp=function(v){var A,S,x,P,E=this,q=E.d,L=(v=new E.constructor(v)).d,V=E.s,U=v.s;if(!q||!L)return!V||!U?NaN:V!==U?V:q===L?0:!q^V<0?1:-1;if(!q[0]||!L[0])return q[0]?V:L[0]?-U:0;if(V!==U)return V;if(E.e!==v.e)return E.e>v.e^V<0?1:-1;for(x=q.length,P=L.length,A=0,S=x<P?x:P;A<S;++A)if(q[A]!==L[A])return q[A]>L[A]^V<0?1:-1;return x===P?0:x>P^V<0?1:-1},I.cosine=I.cos=function(){var v,A,S=this,x=S.constructor;return S.d?S.d[0]?(v=x.precision,A=x.rounding,x.precision=v+Math.max(S.e,S.sd())+$,x.rounding=1,S=k(x,mt(x,S)),x.precision=v,x.rounding=A,m(d==2||d==3?S.neg():S,v,A,!0)):new x(1):new x(NaN)},I.cubeRoot=I.cbrt=function(){var v,A,S,x,P,E,q,L,V,U,Z=this,ee=Z.constructor;if(!Z.isFinite()||Z.isZero())return new ee(Z);for(h=!1,E=Z.s*M(Z.s*Z,1/3),!E||Math.abs(E)==1/0?(S=N(Z.d),v=Z.e,(E=(v-S.length+1)%3)&&(S+=E==1||E==-2?"0":"00"),E=M(S,1/3),v=j((v+1)/3)-(v%3==(v<0?-1:2)),E==1/0?S="5e"+v:(S=E.toExponential(),S=S.slice(0,S.indexOf("e")+1)+v),x=new ee(S),x.s=Z.s):x=new ee(E.toString()),q=(v=ee.precision)+3;;)if(L=x,V=L.times(L).times(L),U=V.plus(Z),x=g(U.plus(Z).times(L),U.plus(V),q+2,1),N(L.d).slice(0,q)===(S=N(x.d)).slice(0,q))if(S=S.slice(q-3,q+1),S=="9999"||!P&&S=="4999"){if(!P&&(m(L,v+1,0),L.times(L).times(L).eq(Z))){x=L;break}q+=4,P=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(m(x,v+1,1),A=!x.times(x).times(x).eq(Z));break}return h=!0,m(x,v,ee.rounding,A)},I.decimalPlaces=I.dp=function(){var v,A=this.d,S=NaN;if(A){if(v=A.length-1,S=(v-j(this.e/$))*$,v=A[v],v)for(;v%10==0;v/=10)S--;S<0&&(S=0)}return S},I.dividedBy=I.div=function(v){return g(this,new this.constructor(v))},I.dividedToIntegerBy=I.divToInt=function(v){var A=this,S=A.constructor;return m(g(A,new S(v),0,1,1),S.precision,S.rounding)},I.equals=I.eq=function(v){return this.cmp(v)===0},I.floor=function(){return m(new this.constructor(this),this.e+1,3)},I.greaterThan=I.gt=function(v){return this.cmp(v)>0},I.greaterThanOrEqualTo=I.gte=function(v){var A=this.cmp(v);return A==1||A===0},I.hyperbolicCosine=I.cosh=function(){var v,A,S,x,P,E=this,q=E.constructor,L=new q(1);if(!E.isFinite())return new q(E.s?1/0:NaN);if(E.isZero())return L;S=q.precision,x=q.rounding,q.precision=S+Math.max(E.e,E.sd())+4,q.rounding=1,P=E.d.length,P<32?(v=Math.ceil(P/3),A=(1/ti(4,v)).toString()):(v=16,A="2.3283064365386962890625e-10"),E=Qe(q,1,E.times(A),new q(1),!0);for(var V,U=v,Z=new q(8);U--;)V=E.times(E),E=L.minus(V.times(Z.minus(V.times(Z))));return m(E,q.precision=S,q.rounding=x,!0)},I.hyperbolicSine=I.sinh=function(){var v,A,S,x,P=this,E=P.constructor;if(!P.isFinite()||P.isZero())return new E(P);if(A=E.precision,S=E.rounding,E.precision=A+Math.max(P.e,P.sd())+4,E.rounding=1,x=P.d.length,x<3)P=Qe(E,2,P,P,!0);else{v=1.4*Math.sqrt(x),v=v>16?16:v|0,P=P.times(1/ti(5,v)),P=Qe(E,2,P,P,!0);for(var q,L=new E(5),V=new E(16),U=new E(20);v--;)q=P.times(P),P=P.times(L.plus(q.times(V.times(q).plus(U))))}return E.precision=A,E.rounding=S,m(P,A,S,!0)},I.hyperbolicTangent=I.tanh=function(){var v,A,S=this,x=S.constructor;return S.isFinite()?S.isZero()?new x(S):(v=x.precision,A=x.rounding,x.precision=v+7,x.rounding=1,g(S.sinh(),S.cosh(),x.precision=v,x.rounding=A)):new x(S.s)},I.inverseCosine=I.acos=function(){var v,A=this,S=A.constructor,x=A.abs().cmp(1),P=S.precision,E=S.rounding;return x!==-1?x===0?A.isNeg()?T(S,P,E):new S(0):new S(NaN):A.isZero()?T(S,P+4,E).times(.5):(S.precision=P+6,S.rounding=1,A=A.asin(),v=T(S,P+4,E).times(.5),S.precision=P,S.rounding=E,v.minus(A))},I.inverseHyperbolicCosine=I.acosh=function(){var v,A,S=this,x=S.constructor;return S.lte(1)?new x(S.eq(1)?0:NaN):S.isFinite()?(v=x.precision,A=x.rounding,x.precision=v+Math.max(Math.abs(S.e),S.sd())+4,x.rounding=1,h=!1,S=S.times(S).minus(1).sqrt().plus(S),h=!0,x.precision=v,x.rounding=A,S.ln()):new x(S)},I.inverseHyperbolicSine=I.asinh=function(){var v,A,S=this,x=S.constructor;return!S.isFinite()||S.isZero()?new x(S):(v=x.precision,A=x.rounding,x.precision=v+2*Math.max(Math.abs(S.e),S.sd())+6,x.rounding=1,h=!1,S=S.times(S).plus(1).sqrt().plus(S),h=!0,x.precision=v,x.rounding=A,S.ln())},I.inverseHyperbolicTangent=I.atanh=function(){var v,A,S,x,P=this,E=P.constructor;return P.isFinite()?P.e>=0?new E(P.abs().eq(1)?P.s/0:P.isZero()?P:NaN):(v=E.precision,A=E.rounding,x=P.sd(),Math.max(x,v)<2*-P.e-1?m(new E(P),v,A,!0):(E.precision=S=x-P.e,P=g(P.plus(1),new E(1).minus(P),S+v,1),E.precision=v+4,E.rounding=1,P=P.ln(),E.precision=v,E.rounding=A,P.times(.5))):new E(NaN)},I.inverseSine=I.asin=function(){var v,A,S,x,P=this,E=P.constructor;return P.isZero()?new E(P):(A=P.abs().cmp(1),S=E.precision,x=E.rounding,A!==-1?A===0?(v=T(E,S+4,x).times(.5),v.s=P.s,v):new E(NaN):(E.precision=S+6,E.rounding=1,P=P.div(new E(1).minus(P.times(P)).sqrt().plus(1)).atan(),E.precision=S,E.rounding=x,P.times(2)))},I.inverseTangent=I.atan=function(){var v,A,S,x,P,E,q,L,V,U=this,Z=U.constructor,ee=Z.precision,ie=Z.rounding;if(U.isFinite()){if(U.isZero())return new Z(U);if(U.abs().eq(1)&&ee+4<=W)return q=T(Z,ee+4,ie).times(.25),q.s=U.s,q}else{if(!U.s)return new Z(NaN);if(ee+4<=W)return q=T(Z,ee+4,ie).times(.5),q.s=U.s,q}for(Z.precision=L=ee+10,Z.rounding=1,S=Math.min(28,L/$+2|0),v=S;v;--v)U=U.div(U.times(U).plus(1).sqrt().plus(1));for(h=!1,A=Math.ceil(L/$),x=1,V=U.times(U),q=new Z(U),P=U;v!==-1;)if(P=P.times(V),E=q.minus(P.div(x+=2)),P=P.times(V),q=E.plus(P.div(x+=2)),q.d[A]!==void 0)for(v=A;q.d[v]===E.d[v]&&v--;);return S&&(q=q.times(2<<S-1)),h=!0,m(q,Z.precision=ee,Z.rounding=ie,!0)},I.isFinite=function(){return!!this.d},I.isInteger=I.isInt=function(){return!!this.d&&j(this.e/$)>this.d.length-2},I.isNaN=function(){return!this.s},I.isNegative=I.isNeg=function(){return this.s<0},I.isPositive=I.isPos=function(){return this.s>0},I.isZero=function(){return!!this.d&&this.d[0]===0},I.lessThan=I.lt=function(v){return this.cmp(v)<0},I.lessThanOrEqualTo=I.lte=function(v){return this.cmp(v)<1},I.logarithm=I.log=function(v){var A,S,x,P,E,q,L,V,U=this,Z=U.constructor,ee=Z.precision,ie=Z.rounding,we=5;if(v==null)v=new Z(10),A=!0;else{if(v=new Z(v),S=v.d,v.s<0||!S||!S[0]||v.eq(1))return new Z(NaN);A=v.eq(10)}if(S=U.d,U.s<0||!S||!S[0]||U.eq(1))return new Z(S&&!S[0]?-1/0:U.s!=1?NaN:S?0:1/0);if(A)if(S.length>1)E=!0;else{for(P=S[0];P%10===0;)P/=10;E=P!==1}if(h=!1,L=ee+we,q=Ce(U,L),x=A?p(Z,L+10):Ce(v,L),V=g(q,x,L,1),f(V.d,P=ee,ie))do if(L+=10,q=Ce(U,L),x=A?p(Z,L+10):Ce(v,L),V=g(q,x,L,1),!E){+N(V.d).slice(P+1,P+15)+1==1e14&&(V=m(V,ee+1,0));break}while(f(V.d,P+=10,ie));return h=!0,m(V,ee,ie)},I.minus=I.sub=function(v){var A,S,x,P,E,q,L,V,U,Z,ee,ie,we=this,He=we.constructor;if(v=new He(v),!we.d||!v.d)return!we.s||!v.s?v=new He(NaN):we.d?v.s=-v.s:v=new He(v.d||we.s!==v.s?we:NaN),v;if(we.s!=v.s)return v.s=-v.s,we.plus(v);if(U=we.d,ie=v.d,L=He.precision,V=He.rounding,!U[0]||!ie[0]){if(ie[0])v.s=-v.s;else if(U[0])v=new He(we);else return new He(V===3?-0:0);return h?m(v,L,V):v}if(S=j(v.e/$),Z=j(we.e/$),U=U.slice(),E=Z-S,E){for(ee=E<0,ee?(A=U,E=-E,q=ie.length):(A=ie,S=Z,q=U.length),x=Math.max(Math.ceil(L/$),q)+2,E>x&&(E=x,A.length=1),A.reverse(),x=E;x--;)A.push(0);A.reverse()}else{for(x=U.length,q=ie.length,ee=x<q,ee&&(q=x),x=0;x<q;x++)if(U[x]!=ie[x]){ee=U[x]<ie[x];break}E=0}for(ee&&(A=U,U=ie,ie=A,v.s=-v.s),q=U.length,x=ie.length-q;x>0;--x)U[q++]=0;for(x=ie.length;x>E;){if(U[--x]<ie[x]){for(P=x;P&&U[--P]===0;)U[P]=oe-1;--U[P],U[x]+=oe}U[x]-=ie[x]}for(;U[--q]===0;)U.pop();for(;U[0]===0;U.shift())--S;return U[0]?(v.d=U,v.e=y(U,S),h?m(v,L,V):v):new He(V===3?-0:0)},I.modulo=I.mod=function(v){var A,S=this,x=S.constructor;return v=new x(v),!S.d||!v.s||v.d&&!v.d[0]?new x(NaN):!v.d||S.d&&!S.d[0]?m(new x(S),x.precision,x.rounding):(h=!1,x.modulo==9?(A=g(S,v.abs(),0,3,1),A.s*=v.s):A=g(S,v,0,x.modulo,1),A=A.times(v),h=!0,S.minus(A))},I.naturalExponential=I.exp=function(){return fe(this)},I.naturalLogarithm=I.ln=function(){return Ce(this)},I.negated=I.neg=function(){var v=new this.constructor(this);return v.s=-v.s,m(v)},I.plus=I.add=function(v){var A,S,x,P,E,q,L,V,U,Z,ee=this,ie=ee.constructor;if(v=new ie(v),!ee.d||!v.d)return!ee.s||!v.s?v=new ie(NaN):ee.d||(v=new ie(v.d||ee.s===v.s?ee:NaN)),v;if(ee.s!=v.s)return v.s=-v.s,ee.minus(v);if(U=ee.d,Z=v.d,L=ie.precision,V=ie.rounding,!U[0]||!Z[0])return Z[0]||(v=new ie(ee)),h?m(v,L,V):v;if(E=j(ee.e/$),x=j(v.e/$),U=U.slice(),P=E-x,P){for(P<0?(S=U,P=-P,q=Z.length):(S=Z,x=E,q=U.length),E=Math.ceil(L/$),q=E>q?E+1:q+1,P>q&&(P=q,S.length=1),S.reverse();P--;)S.push(0);S.reverse()}for(q=U.length,P=Z.length,q-P<0&&(P=q,S=Z,Z=U,U=S),A=0;P;)A=(U[--P]=U[P]+Z[P]+A)/oe|0,U[P]%=oe;for(A&&(U.unshift(A),++x),q=U.length;U[--q]==0;)U.pop();return v.d=U,v.e=y(U,x),h?m(v,L,V):v},I.precision=I.sd=function(v){var A,S=this;if(v!==void 0&&v!==!!v&&v!==1&&v!==0)throw Error(C+v);return S.d?(A=F(S.d),v&&S.e+1>A&&(A=S.e+1)):A=NaN,A},I.round=function(){var v=this,A=v.constructor;return m(new A(v),v.e+1,A.rounding)},I.sine=I.sin=function(){var v,A,S=this,x=S.constructor;return S.isFinite()?S.isZero()?new x(S):(v=x.precision,A=x.rounding,x.precision=v+Math.max(S.e,S.sd())+$,x.rounding=1,S=it(x,mt(x,S)),x.precision=v,x.rounding=A,m(d>2?S.neg():S,v,A,!0)):new x(NaN)},I.squareRoot=I.sqrt=function(){var v,A,S,x,P,E,q=this,L=q.d,V=q.e,U=q.s,Z=q.constructor;if(U!==1||!L||!L[0])return new Z(!U||U<0&&(!L||L[0])?NaN:L?q:1/0);for(h=!1,U=Math.sqrt(+q),U==0||U==1/0?(A=N(L),(A.length+V)%2==0&&(A+="0"),U=Math.sqrt(A),V=j((V+1)/2)-(V<0||V%2),U==1/0?A="5e"+V:(A=U.toExponential(),A=A.slice(0,A.indexOf("e")+1)+V),x=new Z(A)):x=new Z(U.toString()),S=(V=Z.precision)+3;;)if(E=x,x=E.plus(g(q,E,S+2,1)).times(.5),N(E.d).slice(0,S)===(A=N(x.d)).slice(0,S))if(A=A.slice(S-3,S+1),A=="9999"||!P&&A=="4999"){if(!P&&(m(E,V+1,0),E.times(E).eq(q))){x=E;break}S+=4,P=1}else{(!+A||!+A.slice(1)&&A.charAt(0)=="5")&&(m(x,V+1,1),v=!x.times(x).eq(q));break}return h=!0,m(x,V,Z.rounding,v)},I.tangent=I.tan=function(){var v,A,S=this,x=S.constructor;return S.isFinite()?S.isZero()?new x(S):(v=x.precision,A=x.rounding,x.precision=v+10,x.rounding=1,S=S.sin(),S.s=1,S=g(S,new x(1).minus(S.times(S)).sqrt(),v+10,0),x.precision=v,x.rounding=A,m(d==2||d==4?S.neg():S,v,A,!0)):new x(NaN)},I.times=I.mul=function(v){var A,S,x,P,E,q,L,V,U,Z=this,ee=Z.constructor,ie=Z.d,we=(v=new ee(v)).d;if(v.s*=Z.s,!ie||!ie[0]||!we||!we[0])return new ee(!v.s||ie&&!ie[0]&&!we||we&&!we[0]&&!ie?NaN:!ie||!we?v.s/0:v.s*0);for(S=j(Z.e/$)+j(v.e/$),V=ie.length,U=we.length,V<U&&(E=ie,ie=we,we=E,q=V,V=U,U=q),E=[],q=V+U,x=q;x--;)E.push(0);for(x=U;--x>=0;){for(A=0,P=V+x;P>x;)L=E[P]+we[x]*ie[P-x-1]+A,E[P--]=L%oe|0,A=L/oe|0;E[P]=(E[P]+A)%oe|0}for(;!E[--q];)E.pop();return A?++S:E.shift(),v.d=E,v.e=y(E,S),h?m(v,ee.precision,ee.rounding):v},I.toBinary=function(v,A){return gt(this,2,v,A)},I.toDecimalPlaces=I.toDP=function(v,A){var S=this,x=S.constructor;return S=new x(S),v===void 0?S:(l(v,0,n),A===void 0?A=x.rounding:l(A,0,8),m(S,v+S.e+1,A))},I.toExponential=function(v,A){var S,x=this,P=x.constructor;return v===void 0?S=b(x,!0):(l(v,0,n),A===void 0?A=P.rounding:l(A,0,8),x=m(new P(x),v+1,A),S=b(x,!0,v+1)),x.isNeg()&&!x.isZero()?"-"+S:S},I.toFixed=function(v,A){var S,x,P=this,E=P.constructor;return v===void 0?S=b(P):(l(v,0,n),A===void 0?A=E.rounding:l(A,0,8),x=m(new E(P),v+P.e+1,A),S=b(x,!1,v+x.e+1)),P.isNeg()&&!P.isZero()?"-"+S:S},I.toFraction=function(v){var A,S,x,P,E,q,L,V,U,Z,ee,ie,we=this,He=we.d,je=we.constructor;if(!He)return new je(we);if(U=S=new je(1),x=V=new je(0),A=new je(x),E=A.e=F(He)-we.e-1,q=E%$,A.d[0]=M(10,q<0?$+q:q),v==null)v=E>0?A:U;else{if(L=new je(v),!L.isInt()||L.lt(U))throw Error(C+L);v=L.gt(A)?E>0?A:U:L}for(h=!1,L=new je(N(He)),Z=je.precision,je.precision=E=He.length*$*2;ee=g(L,A,0,1,1),P=S.plus(ee.times(x)),P.cmp(v)!=1;)S=x,x=P,P=U,U=V.plus(ee.times(P)),V=P,P=A,A=L.minus(ee.times(P)),L=P;return P=g(v.minus(S),x,0,1,1),V=V.plus(P.times(U)),S=S.plus(P.times(x)),V.s=U.s=we.s,ie=g(U,x,E,1).minus(we).abs().cmp(g(V,S,E,1).minus(we).abs())<1?[U,x]:[V,S],je.precision=Z,h=!0,ie},I.toHexadecimal=I.toHex=function(v,A){return gt(this,16,v,A)},I.toNearest=function(v,A){var S=this,x=S.constructor;if(S=new x(S),v==null){if(!S.d)return S;v=new x(1),A=x.rounding}else{if(v=new x(v),A===void 0?A=x.rounding:l(A,0,8),!S.d)return v.s?S:v;if(!v.d)return v.s&&(v.s=S.s),v}return v.d[0]?(h=!1,S=g(S,v,0,A,1).times(v),h=!0,m(S)):(v.s=S.s,S=v),S},I.toNumber=function(){return+this},I.toOctal=function(v,A){return gt(this,8,v,A)},I.toPower=I.pow=function(v){var A,S,x,P,E,q,L=this,V=L.constructor,U=+(v=new V(v));if(!L.d||!v.d||!L.d[0]||!v.d[0])return new V(M(+L,U));if(L=new V(L),L.eq(1))return L;if(x=V.precision,E=V.rounding,v.eq(1))return m(L,x,E);if(A=j(v.e/$),A>=v.d.length-1&&(S=U<0?-U:U)<=ne)return P=Q(V,L,S,x),v.s<0?new V(1).div(P):m(P,x,E);if(q=L.s,q<0){if(A<v.d.length-1)return new V(NaN);if(v.d[A]&1||(q=1),L.e==0&&L.d[0]==1&&L.d.length==1)return L.s=q,L}return S=M(+L,U),A=S==0||!isFinite(S)?j(U*(Math.log("0."+N(L.d))/Math.LN10+L.e+1)):new V(S+"").e,A>V.maxE+1||A<V.minE-1?new V(A>0?q/0:0):(h=!1,V.rounding=L.s=1,S=Math.min(12,(A+"").length),P=fe(v.times(Ce(L,x+S)),x),P.d&&(P=m(P,x+5,1),f(P.d,x,E)&&(A=x+10,P=m(fe(v.times(Ce(L,A+S)),A),A+5,1),+N(P.d).slice(x+1,x+15)+1==1e14&&(P=m(P,x+1,0)))),P.s=q,h=!0,V.rounding=E,m(P,x,E))},I.toPrecision=function(v,A){var S,x=this,P=x.constructor;return v===void 0?S=b(x,x.e<=P.toExpNeg||x.e>=P.toExpPos):(l(v,1,n),A===void 0?A=P.rounding:l(A,0,8),x=m(new P(x),v,A),S=b(x,v<=x.e||x.e<=P.toExpNeg,v)),x.isNeg()&&!x.isZero()?"-"+S:S},I.toSignificantDigits=I.toSD=function(v,A){var S=this,x=S.constructor;return v===void 0?(v=x.precision,A=x.rounding):(l(v,1,n),A===void 0?A=x.rounding:l(A,0,8)),m(new x(S),v,A)},I.toString=function(){var v=this,A=v.constructor,S=b(v,v.e<=A.toExpNeg||v.e>=A.toExpPos);return v.isNeg()&&!v.isZero()?"-"+S:S},I.truncated=I.trunc=function(){return m(new this.constructor(this),this.e+1,1)},I.valueOf=I.toJSON=function(){var v=this,A=v.constructor,S=b(v,v.e<=A.toExpNeg||v.e>=A.toExpPos);return v.isNeg()?"-"+S:S};function N(v){var A,S,x,P=v.length-1,E="",q=v[0];if(P>0){for(E+=q,A=1;A<P;A++)x=v[A]+"",S=$-x.length,S&&(E+=z(S)),E+=x;q=v[A],x=q+"",S=$-x.length,S&&(E+=z(S))}else if(q===0)return"0";for(;q%10===0;)q/=10;return E+q}function l(v,A,S){if(v!==~~v||v<A||v>S)throw Error(C+v)}function f(v,A,S,x){var P,E,q,L;for(E=v[0];E>=10;E/=10)--A;return--A<0?(A+=$,P=0):(P=Math.ceil((A+1)/$),A%=$),E=M(10,$-A),L=v[P]%E|0,x==null?A<3?(A==0?L=L/100|0:A==1&&(L=L/10|0),q=S<4&&L==99999||S>3&&L==49999||L==5e4||L==0):q=(S<4&&L+1==E||S>3&&L+1==E/2)&&(v[P+1]/E/100|0)==M(10,A-2)-1||(L==E/2||L==0)&&(v[P+1]/E/100|0)==0:A<4?(A==0?L=L/1e3|0:A==1?L=L/100|0:A==2&&(L=L/10|0),q=(x||S<4)&&L==9999||!x&&S>3&&L==4999):q=((x||S<4)&&L+1==E||!x&&S>3&&L+1==E/2)&&(v[P+1]/E/1e3|0)==M(10,A-3)-1,q}function w(v,A,S){for(var x,P=[0],E,q=0,L=v.length;q<L;){for(E=P.length;E--;)P[E]*=A;for(P[0]+=i.indexOf(v.charAt(q++)),x=0;x<P.length;x++)P[x]>S-1&&(P[x+1]===void 0&&(P[x+1]=0),P[x+1]+=P[x]/S|0,P[x]%=S)}return P.reverse()}function k(v,A){var S,x,P;if(A.isZero())return A;x=A.d.length,x<32?(S=Math.ceil(x/3),P=(1/ti(4,S)).toString()):(S=16,P="2.3283064365386962890625e-10"),v.precision+=S,A=Qe(v,1,A.times(P),new v(1));for(var E=S;E--;){var q=A.times(A);A=q.times(q).minus(q).times(8).plus(1)}return v.precision-=S,A}var g=function(){function v(x,P,E){var q,L=0,V=x.length;for(x=x.slice();V--;)q=x[V]*P+L,x[V]=q%E|0,L=q/E|0;return L&&x.unshift(L),x}function A(x,P,E,q){var L,V;if(E!=q)V=E>q?1:-1;else for(L=V=0;L<E;L++)if(x[L]!=P[L]){V=x[L]>P[L]?1:-1;break}return V}function S(x,P,E,q){for(var L=0;E--;)x[E]-=L,L=x[E]<P[E]?1:0,x[E]=L*q+x[E]-P[E];for(;!x[0]&&x.length>1;)x.shift()}return function(x,P,E,q,L,V){var U,Z,ee,ie,we,He,je,pn,_t,Vn,rt,un,wr,Qi,$l,cc,Ts,Gl,Ti,uc,lc=x.constructor,zl=x.s==P.s?1:-1,En=x.d,bt=P.d;if(!En||!En[0]||!bt||!bt[0])return new lc(!x.s||!P.s||(En?bt&&En[0]==bt[0]:!bt)?NaN:En&&En[0]==0||!bt?zl*0:zl/0);for(V?(we=1,Z=x.e-P.e):(V=oe,we=$,Z=j(x.e/we)-j(P.e/we)),Ti=bt.length,Ts=En.length,_t=new lc(zl),Vn=_t.d=[],ee=0;bt[ee]==(En[ee]||0);ee++);if(bt[ee]>(En[ee]||0)&&Z--,E==null?(Qi=E=lc.precision,q=lc.rounding):L?Qi=E+(x.e-P.e)+1:Qi=E,Qi<0)Vn.push(1),He=!0;else{if(Qi=Qi/we+2|0,ee=0,Ti==1){for(ie=0,bt=bt[0],Qi++;(ee<Ts||ie)&&Qi--;ee++)$l=ie*V+(En[ee]||0),Vn[ee]=$l/bt|0,ie=$l%bt|0;He=ie||ee<Ts}else{for(ie=V/(bt[0]+1)|0,ie>1&&(bt=v(bt,ie,V),En=v(En,ie,V),Ti=bt.length,Ts=En.length),cc=Ti,rt=En.slice(0,Ti),un=rt.length;un<Ti;)rt[un++]=0;uc=bt.slice(),uc.unshift(0),Gl=bt[0],bt[1]>=V/2&&++Gl;do ie=0,U=A(bt,rt,Ti,un),U<0?(wr=rt[0],Ti!=un&&(wr=wr*V+(rt[1]||0)),ie=wr/Gl|0,ie>1?(ie>=V&&(ie=V-1),je=v(bt,ie,V),pn=je.length,un=rt.length,U=A(je,rt,pn,un),U==1&&(ie--,S(je,Ti<pn?uc:bt,pn,V))):(ie==0&&(U=ie=1),je=bt.slice()),pn=je.length,pn<un&&je.unshift(0),S(rt,je,un,V),U==-1&&(un=rt.length,U=A(bt,rt,Ti,un),U<1&&(ie++,S(rt,Ti<un?uc:bt,un,V))),un=rt.length):U===0&&(ie++,rt=[0]),Vn[ee++]=ie,U&&rt[0]?rt[un++]=En[cc]||0:(rt=[En[cc]],un=1);while((cc++<Ts||rt[0]!==void 0)&&Qi--);He=rt[0]!==void 0}Vn[0]||Vn.shift()}if(we==1)_t.e=Z,c=He;else{for(ee=1,ie=Vn[0];ie>=10;ie/=10)ee++;_t.e=ee+Z*we-1,m(_t,L?E+_t.e+1:E,q,He)}return _t}}();function m(v,A,S,x){var P,E,q,L,V,U,Z,ee,ie,we=v.constructor;e:if(A!=null){if(ee=v.d,!ee)return v;for(P=1,L=ee[0];L>=10;L/=10)P++;if(E=A-P,E<0)E+=$,q=A,Z=ee[ie=0],V=Z/M(10,P-q-1)%10|0;else if(ie=Math.ceil((E+1)/$),L=ee.length,ie>=L)if(x){for(;L++<=ie;)ee.push(0);Z=V=0,P=1,E%=$,q=E-$+1}else break e;else{for(Z=L=ee[ie],P=1;L>=10;L/=10)P++;E%=$,q=E-$+P,V=q<0?0:Z/M(10,P-q-1)%10|0}if(x=x||A<0||ee[ie+1]!==void 0||(q<0?Z:Z%M(10,P-q-1)),U=S<4?(V||x)&&(S==0||S==(v.s<0?3:2)):V>5||V==5&&(S==4||x||S==6&&(E>0?q>0?Z/M(10,P-q):0:ee[ie-1])%10&1||S==(v.s<0?8:7)),A<1||!ee[0])return ee.length=0,U?(A-=v.e+1,ee[0]=M(10,($-A%$)%$),v.e=-A||0):ee[0]=v.e=0,v;if(E==0?(ee.length=ie,L=1,ie--):(ee.length=ie+1,L=M(10,$-E),ee[ie]=q>0?(Z/M(10,P-q)%M(10,q)|0)*L:0),U)for(;;)if(ie==0){for(E=1,q=ee[0];q>=10;q/=10)E++;for(q=ee[0]+=L,L=1;q>=10;q/=10)L++;E!=L&&(v.e++,ee[0]==oe&&(ee[0]=1));break}else{if(ee[ie]+=L,ee[ie]!=oe)break;ee[ie--]=0,L=1}for(E=ee.length;ee[--E]===0;)ee.pop()}return h&&(v.e>we.maxE?(v.d=null,v.e=NaN):v.e<we.minE&&(v.e=0,v.d=[0])),v}function b(v,A,S){if(!v.isFinite())return ke(v);var x,P=v.e,E=N(v.d),q=E.length;return A?(S&&(x=S-q)>0?E=E.charAt(0)+"."+E.slice(1)+z(x):q>1&&(E=E.charAt(0)+"."+E.slice(1)),E=E+(v.e<0?"e":"e+")+v.e):P<0?(E="0."+z(-P-1)+E,S&&(x=S-q)>0&&(E+=z(x))):P>=q?(E+=z(P+1-q),S&&(x=S-P-1)>0&&(E=E+"."+z(x))):((x=P+1)<q&&(E=E.slice(0,x)+"."+E.slice(x)),S&&(x=S-q)>0&&(P+1===q&&(E+="."),E+=z(x))),E}function y(v,A){var S=v[0];for(A*=$;S>=10;S/=10)A++;return A}function p(v,A,S){if(A>G)throw h=!0,S&&(v.precision=S),Error(D);return m(new v(r),A,1,!0)}function T(v,A,S){if(A>W)throw Error(D);return m(new v(o),A,S,!0)}function F(v){var A=v.length-1,S=A*$+1;if(A=v[A],A){for(;A%10==0;A/=10)S--;for(A=v[0];A>=10;A/=10)S++}return S}function z(v){for(var A="";v--;)A+="0";return A}function Q(v,A,S,x){var P,E=new v(1),q=Math.ceil(x/$+4);for(h=!1;;){if(S%2&&(E=E.times(A),Jr(E.d,q)&&(P=!0)),S=j(S/2),S===0){S=E.d.length-1,P&&E.d[S]===0&&++E.d[S];break}A=A.times(A),Jr(A.d,q)}return h=!0,E}function H(v){return v.d[v.d.length-1]&1}function ae(v,A,S){for(var x,P=new v(A[0]),E=0;++E<A.length;)if(x=new v(A[E]),x.s)P[S](x)&&(P=x);else{P=x;break}return P}function fe(v,A){var S,x,P,E,q,L,V,U=0,Z=0,ee=0,ie=v.constructor,we=ie.rounding,He=ie.precision;if(!v.d||!v.d[0]||v.e>17)return new ie(v.d?v.d[0]?v.s<0?0:1/0:1:v.s?v.s<0?0:v:NaN);for(A==null?(h=!1,V=He):V=A,L=new ie(.03125);v.e>-2;)v=v.times(L),ee+=5;for(x=Math.log(M(2,ee))/Math.LN10*2+5|0,V+=x,S=E=q=new ie(1),ie.precision=V;;){if(E=m(E.times(v),V,1),S=S.times(++Z),L=q.plus(g(E,S,V,1)),N(L.d).slice(0,V)===N(q.d).slice(0,V)){for(P=ee;P--;)q=m(q.times(q),V,1);if(A==null)if(U<3&&f(q.d,V-x,we,U))ie.precision=V+=10,S=E=L=new ie(1),Z=0,U++;else return m(q,ie.precision=He,we,h=!0);else return ie.precision=He,q}q=L}}function Ce(v,A){var S,x,P,E,q,L,V,U,Z,ee,ie,we=1,He=10,je=v,pn=je.d,_t=je.constructor,Vn=_t.rounding,rt=_t.precision;if(je.s<0||!pn||!pn[0]||!je.e&&pn[0]==1&&pn.length==1)return new _t(pn&&!pn[0]?-1/0:je.s!=1?NaN:pn?0:je);if(A==null?(h=!1,Z=rt):Z=A,_t.precision=Z+=He,S=N(pn),x=S.charAt(0),Math.abs(E=je.e)<15e14){for(;x<7&&x!=1||x==1&&S.charAt(1)>3;)je=je.times(v),S=N(je.d),x=S.charAt(0),we++;E=je.e,x>1?(je=new _t("0."+S),E++):je=new _t(x+"."+S.slice(1))}else return U=p(_t,Z+2,rt).times(E+""),je=Ce(new _t(x+"."+S.slice(1)),Z-He).plus(U),_t.precision=rt,A==null?m(je,rt,Vn,h=!0):je;for(ee=je,V=q=je=g(je.minus(1),je.plus(1),Z,1),ie=m(je.times(je),Z,1),P=3;;){if(q=m(q.times(ie),Z,1),U=V.plus(g(q,new _t(P),Z,1)),N(U.d).slice(0,Z)===N(V.d).slice(0,Z))if(V=V.times(2),E!==0&&(V=V.plus(p(_t,Z+2,rt).times(E+""))),V=g(V,new _t(we),Z,1),A==null)if(f(V.d,Z-He,Vn,L))_t.precision=Z+=He,U=q=je=g(ee.minus(1),ee.plus(1),Z,1),ie=m(je.times(je),Z,1),P=L=1;else return m(V,_t.precision=rt,Vn,h=!0);else return _t.precision=rt,V;V=U,P+=2}}function ke(v){return String(v.s*v.s/0)}function Fe(v,A){var S,x,P;for((S=A.indexOf("."))>-1&&(A=A.replace(".","")),(x=A.search(/e/i))>0?(S<0&&(S=x),S+=+A.slice(x+1),A=A.substring(0,x)):S<0&&(S=A.length),x=0;A.charCodeAt(x)===48;x++);for(P=A.length;A.charCodeAt(P-1)===48;--P);if(A=A.slice(x,P),A){if(P-=x,v.e=S=S-x-1,v.d=[],x=(S+1)%$,S<0&&(x+=$),x<P){for(x&&v.d.push(+A.slice(0,x)),P-=$;x<P;)v.d.push(+A.slice(x,x+=$));A=A.slice(x),x=$-A.length}else x-=P;for(;x--;)A+="0";v.d.push(+A),h&&(v.e>v.constructor.maxE?(v.d=null,v.e=NaN):v.e<v.constructor.minE&&(v.e=0,v.d=[0]))}else v.e=0,v.d=[0];return v}function kt(v,A){var S,x,P,E,q,L,V,U,Z;if(A.indexOf("_")>-1){if(A=A.replace(/(\d)_(?=\d)/g,"$1"),Y.test(A))return Fe(v,A)}else if(A==="Infinity"||A==="NaN")return+A||(v.s=NaN),v.e=NaN,v.d=null,v;if(K.test(A))S=16,A=A.toLowerCase();else if(R.test(A))S=2;else if(X.test(A))S=8;else throw Error(C+A);for(E=A.search(/p/i),E>0?(V=+A.slice(E+1),A=A.substring(2,E)):A=A.slice(2),E=A.indexOf("."),q=E>=0,x=v.constructor,q&&(A=A.replace(".",""),L=A.length,E=L-E,P=Q(x,new x(S),E,E*2)),U=w(A,S,oe),Z=U.length-1,E=Z;U[E]===0;--E)U.pop();return E<0?new x(v.s*0):(v.e=y(U,Z),v.d=U,h=!1,q&&(v=g(v,P,L*4)),V&&(v=v.times(Math.abs(V)<54?M(2,V):a.pow(2,V))),h=!0,v)}function it(v,A){var S,x=A.d.length;if(x<3)return A.isZero()?A:Qe(v,2,A,A);S=1.4*Math.sqrt(x),S=S>16?16:S|0,A=A.times(1/ti(5,S)),A=Qe(v,2,A,A);for(var P,E=new v(5),q=new v(16),L=new v(20);S--;)P=A.times(A),A=A.times(E.plus(P.times(q.times(P).minus(L))));return A}function Qe(v,A,S,x,P){var E,q,L,V,U=1,Z=v.precision,ee=Math.ceil(Z/$);for(h=!1,V=S.times(S),L=new v(x);;){if(q=g(L.times(V),new v(A++*A++),Z,1),L=P?x.plus(q):x.minus(q),x=g(q.times(V),new v(A++*A++),Z,1),q=L.plus(x),q.d[ee]!==void 0){for(E=ee;q.d[E]===L.d[E]&&E--;);if(E==-1)break}E=L,L=x,x=q,q=E,U++}return h=!0,q.d.length=ee+1,q}function ti(v,A){for(var S=v;--A;)S*=v;return S}function mt(v,A){var S,x=A.s<0,P=T(v,v.precision,1),E=P.times(.5);if(A=A.abs(),A.lte(E))return d=x?4:1,A;if(S=A.divToInt(P),S.isZero())d=x?3:2;else{if(A=A.minus(S.times(P)),A.lte(E))return d=H(S)?x?2:3:x?4:1,A;d=H(S)?x?1:4:x?3:2}return A.minus(P).abs()}function gt(v,A,S,x){var P,E,q,L,V,U,Z,ee,ie,we=v.constructor,He=S!==void 0;if(He?(l(S,1,n),x===void 0?x=we.rounding:l(x,0,8)):(S=we.precision,x=we.rounding),!v.isFinite())Z=ke(v);else{for(Z=b(v),q=Z.indexOf("."),He?(P=2,A==16?S=S*4-3:A==8&&(S=S*3-2)):P=A,q>=0&&(Z=Z.replace(".",""),ie=new we(1),ie.e=Z.length-q,ie.d=w(b(ie),10,P),ie.e=ie.d.length),ee=w(Z,10,P),E=V=ee.length;ee[--V]==0;)ee.pop();if(!ee[0])Z=He?"0p+0":"0";else{if(q<0?E--:(v=new we(v),v.d=ee,v.e=E,v=g(v,ie,S,x,0,P),ee=v.d,E=v.e,U=c),q=ee[S],L=P/2,U=U||ee[S+1]!==void 0,U=x<4?(q!==void 0||U)&&(x===0||x===(v.s<0?3:2)):q>L||q===L&&(x===4||U||x===6&&ee[S-1]&1||x===(v.s<0?8:7)),ee.length=S,U)for(;++ee[--S]>P-1;)ee[S]=0,S||(++E,ee.unshift(1));for(V=ee.length;!ee[V-1];--V);for(q=0,Z="";q<V;q++)Z+=i.charAt(ee[q]);if(He){if(V>1)if(A==16||A==8){for(q=A==16?4:3,--V;V%q;V++)Z+="0";for(ee=w(Z,P,A),V=ee.length;!ee[V-1];--V);for(q=1,Z="1.";q<V;q++)Z+=i.charAt(ee[q])}else Z=Z.charAt(0)+"."+Z.slice(1);Z=Z+(E<0?"p":"p+")+E}else if(E<0){for(;++E;)Z="0"+Z;Z="0."+Z}else if(++E>V)for(E-=V;E--;)Z+="0";else E<V&&(Z=Z.slice(0,E)+"."+Z.slice(E))}Z=(A==16?"0x":A==2?"0b":A==8?"0o":"")+Z}return v.s<0?"-"+Z:Z}function Jr(v,A){if(v.length>A)return v.length=A,!0}function Bt(v){return new this(v).abs()}function Mt(v){return new this(v).acos()}function Za(v){return new this(v).acosh()}function jt(v,A){return new this(v).plus(A)}function Nt(v){return new this(v).asin()}function Ja(v){return new this(v).asinh()}function Rt(v){return new this(v).atan()}function Ft(v){return new this(v).atanh()}function Ya(v,A){v=new this(v),A=new this(A);var S,x=this.precision,P=this.rounding,E=x+4;return!v.s||!A.s?S=new this(NaN):!v.d&&!A.d?(S=T(this,E,1).times(A.s>0?.25:.75),S.s=v.s):!A.d||v.isZero()?(S=A.s<0?T(this,x,P):new this(0),S.s=v.s):!v.d||A.isZero()?(S=T(this,E,1).times(.5),S.s=v.s):A.s<0?(this.precision=E,this.rounding=1,S=this.atan(g(v,A,E,1)),A=T(this,E,1),this.precision=x,this.rounding=P,S=v.s<0?S.minus(A):S.plus(A)):S=this.atan(g(v,A,E,1)),S}function qt(v){return new this(v).cbrt()}function Lt(v){return m(v=new this(v),v.e+1,2)}function Qa(v,A,S){return new this(v).clamp(A,S)}function Ut(v){if(!v||typeof v!="object")throw Error(_+"Object expected");var A,S,x,P=v.defaults===!0,E=["precision",1,n,"rounding",0,8,"toExpNeg",-e,0,"toExpPos",0,e,"maxE",0,e,"minE",-e,0,"modulo",0,9];for(A=0;A<E.length;A+=3)if(S=E[A],P&&(this[S]=s[S]),(x=v[S])!==void 0)if(j(x)===x&&x>=E[A+1]&&x<=E[A+2])this[S]=x;else throw Error(C+S+": "+x);if(S="crypto",P&&(this[S]=s[S]),(x=v[S])!==void 0)if(x===!0||x===!1||x===0||x===1)if(x)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[S]=!0;else throw Error(O);else this[S]=!1;else throw Error(C+S+": "+x);return this}function $t(v){return new this(v).cos()}function ec(v){return new this(v).cosh()}function Pt(v){var A,S,x;function P(E){var q,L,V,U=this;if(!(U instanceof P))return new P(E);if(U.constructor=P,ks(E)){U.s=E.s,h?!E.d||E.e>P.maxE?(U.e=NaN,U.d=null):E.e<P.minE?(U.e=0,U.d=[0]):(U.e=E.e,U.d=E.d.slice()):(U.e=E.e,U.d=E.d?E.d.slice():E.d);return}if(V=typeof E,V==="number"){if(E===0){U.s=1/E<0?-1:1,U.e=0,U.d=[0];return}if(E<0?(E=-E,U.s=-1):U.s=1,E===~~E&&E<1e7){for(q=0,L=E;L>=10;L/=10)q++;h?q>P.maxE?(U.e=NaN,U.d=null):q<P.minE?(U.e=0,U.d=[0]):(U.e=q,U.d=[E]):(U.e=q,U.d=[E]);return}else if(E*0!==0){E||(U.s=NaN),U.e=NaN,U.d=null;return}return Fe(U,E.toString())}else if(V!=="string")throw Error(C+E);return(L=E.charCodeAt(0))===45?(E=E.slice(1),U.s=-1):(L===43&&(E=E.slice(1)),U.s=1),Y.test(E)?Fe(U,E):kt(U,E)}if(P.prototype=I,P.ROUND_UP=0,P.ROUND_DOWN=1,P.ROUND_CEIL=2,P.ROUND_FLOOR=3,P.ROUND_HALF_UP=4,P.ROUND_HALF_DOWN=5,P.ROUND_HALF_EVEN=6,P.ROUND_HALF_CEIL=7,P.ROUND_HALF_FLOOR=8,P.EUCLID=9,P.config=P.set=Ut,P.clone=Pt,P.isDecimal=ks,P.abs=Bt,P.acos=Mt,P.acosh=Za,P.add=jt,P.asin=Nt,P.asinh=Ja,P.atan=Rt,P.atanh=Ft,P.atan2=Ya,P.cbrt=qt,P.ceil=Lt,P.clamp=Qa,P.cos=$t,P.cosh=ec,P.div=Gt,P.exp=tc,P.floor=zt,P.hypot=Vt,P.ln=Kt,P.log=Wt,P.log10=Ht,P.log2=nc,P.max=Xt,P.min=ic,P.mod=Zt,P.mul=Jt,P.pow=rc,P.random=Yt,P.round=Qt,P.sign=oc,P.sin=en,P.sinh=tn,P.sqrt=sc,P.sub=nn,P.sum=rn,P.tan=ac,P.tanh=on,P.trunc=sn,v===void 0&&(v={}),v&&v.defaults!==!0)for(x=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],A=0;A<x.length;)v.hasOwnProperty(S=x[A++])||(v[S]=this[S]);return P.config(v),P}function Gt(v,A){return new this(v).div(A)}function tc(v){return new this(v).exp()}function zt(v){return m(v=new this(v),v.e+1,3)}function Vt(){var v,A,S=new this(0);for(h=!1,v=0;v<arguments.length;)if(A=new this(arguments[v++]),A.d)S.d&&(S=S.plus(A.times(A)));else{if(A.s)return h=!0,new this(1/0);S=A}return h=!0,S.sqrt()}function ks(v){return v instanceof a||v&&v.toStringTag===B||!1}function Kt(v){return new this(v).ln()}function Wt(v,A){return new this(v).log(A)}function nc(v){return new this(v).log(2)}function Ht(v){return new this(v).log(10)}function Xt(){return ae(this,arguments,"lt")}function ic(){return ae(this,arguments,"gt")}function Zt(v,A){return new this(v).mod(A)}function Jt(v,A){return new this(v).mul(A)}function rc(v,A){return new this(v).pow(A)}function Yt(v){var A,S,x,P,E=0,q=new this(1),L=[];if(v===void 0?v=this.precision:l(v,1,n),x=Math.ceil(v/$),this.crypto)if(crypto.getRandomValues)for(A=crypto.getRandomValues(new Uint32Array(x));E<x;)P=A[E],P>=429e7?A[E]=crypto.getRandomValues(new Uint32Array(1))[0]:L[E++]=P%1e7;else if(crypto.randomBytes){for(A=crypto.randomBytes(x*=4);E<x;)P=A[E]+(A[E+1]<<8)+(A[E+2]<<16)+((A[E+3]&127)<<24),P>=214e7?crypto.randomBytes(4).copy(A,E):(L.push(P%1e7),E+=4);E=x/4}else throw Error(O);else for(;E<x;)L[E++]=Math.random()*1e7|0;for(x=L[--E],v%=$,x&&v&&(P=M(10,$-v),L[E]=(x/P|0)*P);L[E]===0;E--)L.pop();if(E<0)S=0,L=[0];else{for(S=-1;L[0]===0;S-=$)L.shift();for(x=1,P=L[0];P>=10;P/=10)x++;x<$&&(S-=$-x)}return q.e=S,q.d=L,q}function Qt(v){return m(v=new this(v),v.e+1,this.rounding)}function oc(v){return v=new this(v),v.d?v.d[0]?v.s:0*v.s:v.s||NaN}function en(v){return new this(v).sin()}function tn(v){return new this(v).sinh()}function sc(v){return new this(v).sqrt()}function nn(v,A){return new this(v).sub(A)}function rn(){var v=0,A=arguments,S=new this(A[v]);for(h=!1;S.s&&++v<A.length;)S=S.plus(A[v]);return h=!0,m(S,this.precision,this.rounding)}function ac(v){return new this(v).tan()}function on(v){return new this(v).tanh()}function sn(v){return m(v=new this(v),v.e+1,1)}a=Pt(s),a.prototype.constructor=a,a.default=a.Decimal=a,r=new a(r),o=new a(o),typeof define=="function"&&define.amd?define(function(){return a}):typeof tu<"u"&&tu.exports?(typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"&&(I[Symbol.for("nodejs.util.inspect.custom")]=I.toString,I[Symbol.toStringTag]="Decimal"),tu.exports=a):(t||(t=typeof self<"u"&&self&&self.self==self?self:window),u=t.Decimal,a.noConflict=function(){return t.Decimal=u,a},t.Decimal=a)})(Jg)});var Wd=Ue((Vd,Kd)=>{"use strict";(function(t,e){typeof Vd=="object"&&typeof Kd<"u"?Kd.exports=e():typeof define=="function"&&define.amd?define(e):function(){var n=t.Base64,i=e();i.noConflict=function(){return t.Base64=n,i},t.Meteor&&(Base64=i),t.Base64=i}()})(typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:Vd,function(){"use strict";var t="3.7.7",e=t,n=typeof Buffer=="function",i=typeof TextDecoder=="function"?new TextDecoder:void 0,r=typeof TextEncoder=="function"?new TextEncoder:void 0,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s=Array.prototype.slice.call(o),a=function(T){var F={};return T.forEach(function(z,Q){return F[z]=Q}),F}(s),c=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,u=String.fromCharCode.bind(String),d=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):function(T){return new Uint8Array(Array.prototype.slice.call(T,0))},h=function(T){return T.replace(/=/g,"").replace(/[+\/]/g,function(F){return F=="+"?"-":"_"})},_=function(T){return T.replace(/[^A-Za-z0-9\+\/]/g,"")},C=function(T){for(var F,z,Q,H,ae="",fe=T.length%3,Ce=0;Ce<T.length;){if((z=T.charCodeAt(Ce++))>255||(Q=T.charCodeAt(Ce++))>255||(H=T.charCodeAt(Ce++))>255)throw new TypeError("invalid character found");F=z<<16|Q<<8|H,ae+=s[F>>18&63]+s[F>>12&63]+s[F>>6&63]+s[F&63]}return fe?ae.slice(0,fe-3)+"===".substring(fe):ae},D=typeof btoa=="function"?function(T){return btoa(T)}:n?function(T){return Buffer.from(T,"binary").toString("base64")}:C,O=n?function(T){return Buffer.from(T).toString("base64")}:function(T){for(var F=4096,z=[],Q=0,H=T.length;Q<H;Q+=F)z.push(u.apply(null,T.subarray(Q,Q+F)));return D(z.join(""))},B=function(T,F){return F===void 0&&(F=!1),F?h(O(T)):O(T)},j=function(T){if(T.length<2){var F=T.charCodeAt(0);return F<128?T:F<2048?u(192|F>>>6)+u(128|F&63):u(224|F>>>12&15)+u(128|F>>>6&63)+u(128|F&63)}else{var F=65536+(T.charCodeAt(0)-55296)*1024+(T.charCodeAt(1)-56320);return u(240|F>>>18&7)+u(128|F>>>12&63)+u(128|F>>>6&63)+u(128|F&63)}},M=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,R=function(T){return T.replace(M,j)},K=n?function(T){return Buffer.from(T,"utf8").toString("base64")}:r?function(T){return O(r.encode(T))}:function(T){return D(R(T))},X=function(T,F){return F===void 0&&(F=!1),F?h(K(T)):K(T)},Y=function(T){return X(T,!0)},oe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,$=function(T){switch(T.length){case 4:var F=(7&T.charCodeAt(0))<<18|(63&T.charCodeAt(1))<<12|(63&T.charCodeAt(2))<<6|63&T.charCodeAt(3),z=F-65536;return u((z>>>10)+55296)+u((z&1023)+56320);case 3:return u((15&T.charCodeAt(0))<<12|(63&T.charCodeAt(1))<<6|63&T.charCodeAt(2));default:return u((31&T.charCodeAt(0))<<6|63&T.charCodeAt(1))}},ne=function(T){return T.replace(oe,$)},G=function(T){if(T=T.replace(/\s+/g,""),!c.test(T))throw new TypeError("malformed base64.");T+="==".slice(2-(T.length&3));for(var F,z="",Q,H,ae=0;ae<T.length;)F=a[T.charAt(ae++)]<<18|a[T.charAt(ae++)]<<12|(Q=a[T.charAt(ae++)])<<6|(H=a[T.charAt(ae++)]),z+=Q===64?u(F>>16&255):H===64?u(F>>16&255,F>>8&255):u(F>>16&255,F>>8&255,F&255);return z},W=typeof atob=="function"?function(T){return atob(_(T))}:n?function(T){return Buffer.from(T,"base64").toString("binary")}:G,I=n?function(T){return d(Buffer.from(T,"base64"))}:function(T){return d(W(T).split("").map(function(F){return F.charCodeAt(0)}))},N=function(T){return I(f(T))},l=n?function(T){return Buffer.from(T,"base64").toString("utf8")}:i?function(T){return i.decode(I(T))}:function(T){return ne(W(T))},f=function(T){return _(T.replace(/[-_]/g,function(F){return F=="-"?"+":"/"}))},w=function(T){return l(f(T))},k=function(T){if(typeof T!="string")return!1;var F=T.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(F)||!/[^\s0-9a-zA-Z\-_]/.test(F)},g=function(T){return{value:T,enumerable:!1,writable:!0,configurable:!0}},m=function(){var T=function(F,z){return Object.defineProperty(String.prototype,F,g(z))};T("fromBase64",function(){return w(this)}),T("toBase64",function(F){return X(this,F)}),T("toBase64URI",function(){return X(this,!0)}),T("toBase64URL",function(){return X(this,!0)}),T("toUint8Array",function(){return N(this)})},b=function(){var T=function(F,z){return Object.defineProperty(Uint8Array.prototype,F,g(z))};T("toBase64",function(F){return B(this,F)}),T("toBase64URI",function(){return B(this,!0)}),T("toBase64URL",function(){return B(this,!0)})},y=function(){m(),b()},p={version:t,VERSION:e,atob:W,atobPolyfill:G,btoa:D,btoaPolyfill:C,fromBase64:w,toBase64:X,encode:X,encodeURI:Y,encodeURL:Y,utob:R,btou:ne,decode:w,isValid:k,fromUint8Array:B,toUint8Array:N,extendString:m,extendUint8Array:b,extendBuiltins:y};return p.Base64={},Object.keys(p).forEach(function(T){return p.Base64[T]=p[T]}),p})});var Xd=Ue(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});Hd.default=cA;var nu,aA=new Uint8Array(16);function cA(){if(!nu&&(nu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!nu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return nu(aA)}});var Yg=Ue(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});iu.default=void 0;var uA=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;iu.default=uA});var Ls=Ue(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.default=void 0;var lA=dA(Yg());function dA(t){return t&&t.__esModule?t:{default:t}}function fA(t){return typeof t=="string"&&lA.default.test(t)}var hA=fA;ru.default=hA});var $s=Ue(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.default=void 0;Us.unsafeStringify=Qg;var pA=mA(Ls());function mA(t){return t&&t.__esModule?t:{default:t}}var xn=[];for(let t=0;t<256;++t)xn.push((t+256).toString(16).slice(1));function Qg(t,e=0){return xn[t[e+0]]+xn[t[e+1]]+xn[t[e+2]]+xn[t[e+3]]+"-"+xn[t[e+4]]+xn[t[e+5]]+"-"+xn[t[e+6]]+xn[t[e+7]]+"-"+xn[t[e+8]]+xn[t[e+9]]+"-"+xn[t[e+10]]+xn[t[e+11]]+xn[t[e+12]]+xn[t[e+13]]+xn[t[e+14]]+xn[t[e+15]]}function gA(t,e=0){let n=Qg(t,e);if(!(0,pA.default)(n))throw TypeError("Stringified UUID is invalid");return n}var _A=gA;Us.default=_A});var t_=Ue(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.default=void 0;var wA=bA(Xd()),yA=$s();function bA(t){return t&&t.__esModule?t:{default:t}}var e_,Zd,Jd=0,Yd=0;function vA(t,e,n){let i=e&&n||0,r=e||new Array(16);t=t||{};let o=t.node||e_,s=t.clockseq!==void 0?t.clockseq:Zd;if(o==null||s==null){let _=t.random||(t.rng||wA.default)();o==null&&(o=e_=[_[0]|1,_[1],_[2],_[3],_[4],_[5]]),s==null&&(s=Zd=(_[6]<<8|_[7])&16383)}let a=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Yd+1,u=a-Jd+(c-Yd)/1e4;if(u<0&&t.clockseq===void 0&&(s=s+1&16383),(u<0||a>Jd)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Jd=a,Yd=c,Zd=s,a+=122192928e5;let d=((a&268435455)*1e4+c)%4294967296;r[i++]=d>>>24&255,r[i++]=d>>>16&255,r[i++]=d>>>8&255,r[i++]=d&255;let h=a/4294967296*1e4&268435455;r[i++]=h>>>8&255,r[i++]=h&255,r[i++]=h>>>24&15|16,r[i++]=h>>>16&255,r[i++]=s>>>8|128,r[i++]=s&255;for(let _=0;_<6;++_)r[i+_]=o[_];return e||(0,yA.unsafeStringify)(r)}var kA=vA;ou.default=kA});var Qd=Ue(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.default=void 0;var TA=CA(Ls());function CA(t){return t&&t.__esModule?t:{default:t}}function AA(t){if(!(0,TA.default)(t))throw TypeError("Invalid UUID");let e,n=new Uint8Array(16);return n[0]=(e=parseInt(t.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=e&255,n[4]=(e=parseInt(t.slice(9,13),16))>>>8,n[5]=e&255,n[6]=(e=parseInt(t.slice(14,18),16))>>>8,n[7]=e&255,n[8]=(e=parseInt(t.slice(19,23),16))>>>8,n[9]=e&255,n[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=e&255,n}var SA=AA;su.default=SA});var ef=Ue(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.URL=oo.DNS=void 0;oo.default=EA;var IA=$s(),xA=OA(Qd());function OA(t){return t&&t.__esModule?t:{default:t}}function PA(t){t=unescape(encodeURIComponent(t));let e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var n_="6ba7b810-9dad-11d1-80b4-00c04fd430c8";oo.DNS=n_;var i_="6ba7b811-9dad-11d1-80b4-00c04fd430c8";oo.URL=i_;function EA(t,e,n){function i(r,o,s,a){var c;if(typeof r=="string"&&(r=PA(r)),typeof o=="string"&&(o=(0,xA.default)(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+r.length);if(u.set(o),u.set(r,o.length),u=n(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,s){a=a||0;for(let d=0;d<16;++d)s[a+d]=u[d];return s}return(0,IA.unsafeStringify)(u)}try{i.name=t}catch{}return i.DNS=n_,i.URL=i_,i}});var o_=Ue(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});cu.default=void 0;function DA(t){if(typeof t=="string"){let e=unescape(encodeURIComponent(t));t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n)}return BA(MA(jA(t),t.length*8))}function BA(t){let e=[],n=t.length*32,i="0123456789abcdef";for(let r=0;r<n;r+=8){let o=t[r>>5]>>>r%32&255,s=parseInt(i.charAt(o>>>4&15)+i.charAt(o&15),16);e.push(s)}return e}function r_(t){return(t+64>>>9<<4)+14+1}function MA(t,e){t[e>>5]|=128<<e%32,t[r_(e)-1]=e;let n=1732584193,i=-271733879,r=-1732584194,o=271733878;for(let s=0;s<t.length;s+=16){let a=n,c=i,u=r,d=o;n=Nn(n,i,r,o,t[s],7,-680876936),o=Nn(o,n,i,r,t[s+1],12,-389564586),r=Nn(r,o,n,i,t[s+2],17,606105819),i=Nn(i,r,o,n,t[s+3],22,-1044525330),n=Nn(n,i,r,o,t[s+4],7,-176418897),o=Nn(o,n,i,r,t[s+5],12,1200080426),r=Nn(r,o,n,i,t[s+6],17,-1473231341),i=Nn(i,r,o,n,t[s+7],22,-45705983),n=Nn(n,i,r,o,t[s+8],7,1770035416),o=Nn(o,n,i,r,t[s+9],12,-1958414417),r=Nn(r,o,n,i,t[s+10],17,-42063),i=Nn(i,r,o,n,t[s+11],22,-1990404162),n=Nn(n,i,r,o,t[s+12],7,1804603682),o=Nn(o,n,i,r,t[s+13],12,-40341101),r=Nn(r,o,n,i,t[s+14],17,-1502002290),i=Nn(i,r,o,n,t[s+15],22,1236535329),n=Rn(n,i,r,o,t[s+1],5,-165796510),o=Rn(o,n,i,r,t[s+6],9,-1069501632),r=Rn(r,o,n,i,t[s+11],14,643717713),i=Rn(i,r,o,n,t[s],20,-373897302),n=Rn(n,i,r,o,t[s+5],5,-701558691),o=Rn(o,n,i,r,t[s+10],9,38016083),r=Rn(r,o,n,i,t[s+15],14,-660478335),i=Rn(i,r,o,n,t[s+4],20,-405537848),n=Rn(n,i,r,o,t[s+9],5,568446438),o=Rn(o,n,i,r,t[s+14],9,-1019803690),r=Rn(r,o,n,i,t[s+3],14,-187363961),i=Rn(i,r,o,n,t[s+8],20,1163531501),n=Rn(n,i,r,o,t[s+13],5,-1444681467),o=Rn(o,n,i,r,t[s+2],9,-51403784),r=Rn(r,o,n,i,t[s+7],14,1735328473),i=Rn(i,r,o,n,t[s+12],20,-1926607734),n=Fn(n,i,r,o,t[s+5],4,-378558),o=Fn(o,n,i,r,t[s+8],11,-2022574463),r=Fn(r,o,n,i,t[s+11],16,1839030562),i=Fn(i,r,o,n,t[s+14],23,-35309556),n=Fn(n,i,r,o,t[s+1],4,-1530992060),o=Fn(o,n,i,r,t[s+4],11,1272893353),r=Fn(r,o,n,i,t[s+7],16,-155497632),i=Fn(i,r,o,n,t[s+10],23,-1094730640),n=Fn(n,i,r,o,t[s+13],4,681279174),o=Fn(o,n,i,r,t[s],11,-358537222),r=Fn(r,o,n,i,t[s+3],16,-722521979),i=Fn(i,r,o,n,t[s+6],23,76029189),n=Fn(n,i,r,o,t[s+9],4,-640364487),o=Fn(o,n,i,r,t[s+12],11,-421815835),r=Fn(r,o,n,i,t[s+15],16,530742520),i=Fn(i,r,o,n,t[s+2],23,-995338651),n=qn(n,i,r,o,t[s],6,-198630844),o=qn(o,n,i,r,t[s+7],10,1126891415),r=qn(r,o,n,i,t[s+14],15,-1416354905),i=qn(i,r,o,n,t[s+5],21,-57434055),n=qn(n,i,r,o,t[s+12],6,1700485571),o=qn(o,n,i,r,t[s+3],10,-1894986606),r=qn(r,o,n,i,t[s+10],15,-1051523),i=qn(i,r,o,n,t[s+1],21,-2054922799),n=qn(n,i,r,o,t[s+8],6,1873313359),o=qn(o,n,i,r,t[s+15],10,-30611744),r=qn(r,o,n,i,t[s+6],15,-1560198380),i=qn(i,r,o,n,t[s+13],21,1309151649),n=qn(n,i,r,o,t[s+4],6,-145523070),o=qn(o,n,i,r,t[s+11],10,-1120210379),r=qn(r,o,n,i,t[s+2],15,718787259),i=qn(i,r,o,n,t[s+9],21,-343485551),n=Ir(n,a),i=Ir(i,c),r=Ir(r,u),o=Ir(o,d)}return[n,i,r,o]}function jA(t){if(t.length===0)return[];let e=t.length*8,n=new Uint32Array(r_(e));for(let i=0;i<e;i+=8)n[i>>5]|=(t[i/8]&255)<<i%32;return n}function Ir(t,e){let n=(t&65535)+(e&65535);return(t>>16)+(e>>16)+(n>>16)<<16|n&65535}function NA(t,e){return t<<e|t>>>32-e}function au(t,e,n,i,r,o){return Ir(NA(Ir(Ir(e,t),Ir(i,o)),r),n)}function Nn(t,e,n,i,r,o,s){return au(e&n|~e&i,t,e,r,o,s)}function Rn(t,e,n,i,r,o,s){return au(e&i|n&~i,t,e,r,o,s)}function Fn(t,e,n,i,r,o,s){return au(e^n^i,t,e,r,o,s)}function qn(t,e,n,i,r,o,s){return au(n^(e|~i),t,e,r,o,s)}var RA=DA;cu.default=RA});var a_=Ue(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.default=void 0;var FA=s_(ef()),qA=s_(o_());function s_(t){return t&&t.__esModule?t:{default:t}}var LA=(0,FA.default)("v3",48,qA.default),UA=LA;uu.default=UA});var c_=Ue(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});lu.default=void 0;var $A=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),GA={randomUUID:$A};lu.default=GA});var d_=Ue(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});du.default=void 0;var u_=l_(c_()),zA=l_(Xd()),VA=$s();function l_(t){return t&&t.__esModule?t:{default:t}}function KA(t,e,n){if(u_.default.randomUUID&&!e&&!t)return u_.default.randomUUID();t=t||{};let i=t.random||(t.rng||zA.default)();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(0,VA.unsafeStringify)(i)}var WA=KA;du.default=WA});var f_=Ue(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.default=void 0;function HA(t,e,n,i){switch(t){case 0:return e&n^~e&i;case 1:return e^n^i;case 2:return e&n^e&i^n&i;case 3:return e^n^i}}function tf(t,e){return t<<e|t>>>32-e}function XA(t){let e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){let s=unescape(encodeURIComponent(t));t=[];for(let a=0;a<s.length;++a)t.push(s.charCodeAt(a))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);let i=t.length/4+2,r=Math.ceil(i/16),o=new Array(r);for(let s=0;s<r;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=t[s*64+c*4]<<24|t[s*64+c*4+1]<<16|t[s*64+c*4+2]<<8|t[s*64+c*4+3];o[s]=a}o[r-1][14]=(t.length-1)*8/Math.pow(2,32),o[r-1][14]=Math.floor(o[r-1][14]),o[r-1][15]=(t.length-1)*8&4294967295;for(let s=0;s<r;++s){let a=new Uint32Array(80);for(let C=0;C<16;++C)a[C]=o[s][C];for(let C=16;C<80;++C)a[C]=tf(a[C-3]^a[C-8]^a[C-14]^a[C-16],1);let c=n[0],u=n[1],d=n[2],h=n[3],_=n[4];for(let C=0;C<80;++C){let D=Math.floor(C/20),O=tf(c,5)+HA(D,u,d,h)+_+e[D]+a[C]>>>0;_=h,h=d,d=tf(u,30)>>>0,u=c,c=O}n[0]=n[0]+c>>>0,n[1]=n[1]+u>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+h>>>0,n[4]=n[4]+_>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var ZA=XA;fu.default=ZA});var p_=Ue(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.default=void 0;var JA=h_(ef()),YA=h_(f_());function h_(t){return t&&t.__esModule?t:{default:t}}var QA=(0,JA.default)("v5",80,YA.default),eS=QA;hu.default=eS});var m_=Ue(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.default=void 0;var tS="00000000-0000-0000-0000-000000000000";pu.default=tS});var g_=Ue(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.default=void 0;var nS=iS(Ls());function iS(t){return t&&t.__esModule?t:{default:t}}function rS(t){if(!(0,nS.default)(t))throw TypeError("Invalid UUID");return parseInt(t.slice(14,15),16)}var oS=rS;mu.default=oS});var __=Ue(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Object.defineProperty(Pi,"NIL",{enumerable:!0,get:function(){return lS.default}});Object.defineProperty(Pi,"parse",{enumerable:!0,get:function(){return pS.default}});Object.defineProperty(Pi,"stringify",{enumerable:!0,get:function(){return hS.default}});Object.defineProperty(Pi,"v1",{enumerable:!0,get:function(){return sS.default}});Object.defineProperty(Pi,"v3",{enumerable:!0,get:function(){return aS.default}});Object.defineProperty(Pi,"v4",{enumerable:!0,get:function(){return cS.default}});Object.defineProperty(Pi,"v5",{enumerable:!0,get:function(){return uS.default}});Object.defineProperty(Pi,"validate",{enumerable:!0,get:function(){return fS.default}});Object.defineProperty(Pi,"version",{enumerable:!0,get:function(){return dS.default}});var sS=ir(t_()),aS=ir(a_()),cS=ir(d_()),uS=ir(p_()),lS=ir(m_()),dS=ir(g_()),fS=ir(Ls()),hS=ir($s()),pS=ir(Qd());function ir(t){return t&&t.__esModule?t:{default:t}}});var Un=Ue((Ks,_0)=>{"use strict";var mS=Object.create,Zs=Object.defineProperty,gS=Object.getOwnPropertyDescriptor,_S=Object.getOwnPropertyNames,wS=Object.getPrototypeOf,yS=Object.prototype.hasOwnProperty,bS=(t,e,n)=>e in t?Zs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vS=(t,e)=>{for(var n in e)Zs(t,n,{get:e[n],enumerable:!0})},x_=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _S(e))!yS.call(t,r)&&r!==n&&Zs(t,r,{get:()=>e[r],enumerable:!(i=gS(e,r))||i.enumerable});return t},It=(t,e,n)=>(n=t!=null?mS(wS(t)):{},x_(e||!t||!t.__esModule?Zs(n,"default",{value:t,enumerable:!0}):n,t)),kS=t=>x_(Zs({},"__esModule",{value:!0}),t),TS=(t,e,n)=>(bS(t,typeof e!="symbol"?e+"":e,n),n),O_={};vS(O_,{AMM_SWAP_MODULE:()=>Y2,AmountSpecified:()=>X_,CLOCK_ADDRESS:()=>At,CachedContent:()=>Zo,CetusClmmSDK:()=>g0,ClmmExpectSwapModule:()=>D_,ClmmFetcherModule:()=>Pr,ClmmIntegratePoolModule:()=>Ws,ClmmIntegratePoolV2Module:()=>xr,ClmmIntegrateRouterModule:()=>Xo,ClmmIntegrateRouterWithPartnerModule:()=>vu,ClmmIntegrateUtilsModule:()=>df,ClmmPartnerModule:()=>E_,ClmmPoolUtil:()=>Hs,ClmmPositionStatus:()=>N_,CoinAssist:()=>Ct,CoinInfoAddress:()=>xS,CoinStoreAddress:()=>OS,ConfigModule:()=>p0,DEFAULT_GAS_BUDGET_FOR_MERGE:()=>p2,DEFAULT_GAS_BUDGET_FOR_SPLIT:()=>h2,DEFAULT_GAS_BUDGET_FOR_STAKE:()=>_2,DEFAULT_GAS_BUDGET_FOR_TRANSFER:()=>m2,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI:()=>g2,DEFAULT_NFT_TRANSFER_GAS_FEE:()=>y2,DeepbookClobV2Moudle:()=>B_,DeepbookCustodianV2Moudle:()=>ku,DeepbookEndpointsV2Moudle:()=>M_,DeepbookUtils:()=>_f,FEE_RATE_DENOMINATOR:()=>so,GAS_SYMBOL:()=>w2,GAS_TYPE_ARG:()=>Sf,GAS_TYPE_ARG_LONG:()=>H_,MAX_SQRT_PRICE:()=>Qs,MAX_TICK_INDEX:()=>uf,MIN_SQRT_PRICE:()=>ea,MIN_TICK_INDEX:()=>lf,MathUtil:()=>Te,ONE:()=>gi,POOL_STRUCT:()=>Q2,Percentage:()=>gf,PoolModule:()=>c0,PositionModule:()=>u0,PositionStatus:()=>Z_,PositionUtil:()=>C2,RouterModule:()=>l0,RouterModuleV2:()=>h0,RpcModule:()=>m0,SUI_SYSTEM_STATE_OBJECT_ID:()=>b2,SplitSwap:()=>D2,SplitUnit:()=>Y_,SwapDirection:()=>R_,SwapModule:()=>d0,SwapUtils:()=>Gi,TICK_ARRAY_SIZE:()=>IS,TWO:()=>Ys,TickMath:()=>ft,TickUtil:()=>$2,TokenModule:()=>f0,TransactionUtil:()=>fn,TxBlock:()=>H2,U128:()=>CS,U128_MAX:()=>P_,U64_MAX:()=>Or,ZERO:()=>me,addHexPrefix:()=>Tf,adjustForCoinSlippage:()=>O2,adjustForSlippage:()=>Iu,asIntN:()=>or,asUintN:()=>mi,bufferToHex:()=>r2,buildNFT:()=>o0,buildPool:()=>Tu,buildPosition:()=>Cu,buildPositionReward:()=>Bf,buildTickData:()=>Au,buildTickDataByEvent:()=>s0,cacheTime24h:()=>St,cacheTime5min:()=>Js,checkAddress:()=>i2,checkInvalidSuiAddress:()=>cn,collectFeesQuote:()=>T2,composeType:()=>mf,computeSwap:()=>U_,computeSwapStep:()=>vf,createSplitAmountArray:()=>e0,createSplitArray:()=>Q_,d:()=>Ot,decimalsMultiplier:()=>Of,default:()=>sI,estPoolAPR:()=>GS,estPositionAPRWithDeltaMethod:()=>VS,estPositionAPRWithMultiMethod:()=>KS,estimateLiquidityForCoinA:()=>zs,estimateLiquidityForCoinB:()=>Vs,extractAddressFromType:()=>l2,extractStructTagFromType:()=>Le,findAdjustCoin:()=>Xs,fixCoinType:()=>W_,fixSuiObjectId:()=>K_,fromDecimalsAmount:()=>F2,getAmountFixedDelta:()=>I2,getAmountUnfixedDelta:()=>x2,getCoinAFromLiquidity:()=>If,getCoinBFromLiquidity:()=>xf,getDefaultSuiInputType:()=>j_,getDeltaA:()=>QS,getDeltaB:()=>e2,getDeltaDownFromOutput:()=>hf,getDeltaUpFromInput:()=>ff,getFutureTime:()=>Di,getLiquidityFromCoinA:()=>A2,getLiquidityFromCoinB:()=>S2,getLowerSqrtPriceFromCoinA:()=>HS,getLowerSqrtPriceFromCoinB:()=>ZS,getMoveObject:()=>Ou,getMoveObjectType:()=>Pu,getMovePackageContent:()=>j2,getNearestTickByTick:()=>G2,getNextSqrtPriceAUp:()=>yf,getNextSqrtPriceBDown:()=>bf,getNextSqrtPriceFromInput:()=>q_,getNextSqrtPriceFromOutput:()=>L_,getObjectDeletedResponse:()=>Pf,getObjectDisplay:()=>r0,getObjectFields:()=>rr,getObjectId:()=>ao,getObjectNotExistsResponse:()=>Ef,getObjectOwner:()=>i0,getObjectPreviousTransactionDigest:()=>Eu,getObjectReference:()=>Df,getObjectType:()=>n0,getObjectVersion:()=>B2,getPackagerConfigs:()=>lt,getRewardInTickRange:()=>a0,getSuiObjectData:()=>co,getTickDataFromUrlData:()=>FS,getUpperSqrtPriceFromCoinA:()=>XS,getUpperSqrtPriceFromCoinB:()=>JS,hasPublicTransfer:()=>N2,hexToNumber:()=>o2,hexToString:()=>s2,isSortedSymbols:()=>pf,isSuiObjectResponse:()=>t0,newBits:()=>AS,normalizeCoinType:()=>zi,patchFixSuiObjectId:()=>Af,printTransaction:()=>K2,removeHexPrefix:()=>Cf,secretKeyToEd25519Keypair:()=>q2,secretKeyToSecp256k1Keypair:()=>L2,shortAddress:()=>n2,shortString:()=>$_,tickScore:()=>F_,toBuffer:()=>G_,toCoinAmount:()=>YS,toDecimalsAmount:()=>R2,transClmmpoolDataWithoutTicks:()=>wf,utf8to16:()=>z_});_0.exports=kS(O_);var gu=require("@mysten/sui.js/utils"),Gs=require("@mysten/sui.js/transactions"),Js=5*60*1e3,St=24*60*60*1e3;function Di(t){return Date.parse(new Date().toString())+t}var Zo=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)}},Ei=It(Ee()),Su=zd(),w_=require("@mysten/sui.js/keypairs/ed25519"),y_=require("@mysten/sui.js/keypairs/secp256k1"),pi=It(Ee()),_n=It(Ee()),cf=It(ro());cf.default.config({precision:64,rounding:cf.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var On=cf.default,ue=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof ue&&t.errorCode===e}},me=new _n.default(0),gi=new _n.default(1),Ys=new _n.default(2),CS=Ys.pow(new _n.default(128)),Or=Ys.pow(new _n.default(64)).sub(gi),P_=Ys.pow(new _n.default(128)).sub(gi),Te=class{static toX64_BN(t){return t.mul(new _n.default(2).pow(new _n.default(64)))}static toX64_Decimal(t){return t.mul(On.pow(2,64))}static toX64(t){return new _n.default(t.mul(On.pow(2,64)).floor().toFixed())}static fromX64(t){return new On(t.toString()).mul(On.pow(2,-64))}static fromX64_Decimal(t){return t.mul(On.pow(2,-64))}static fromX64_BN(t){return t.div(new _n.default(2).pow(new _n.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(Or).gt(me)&&(e=e.add(gi)),e}static divRoundUp(t,e){return t.mod(e).eq(me)?t.div(e):t.div(e).add(new _n.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(P_):t.sub(e)}static checkUnsignedSub(t,e){let n=t.sub(e);if(n.isNeg())throw new ue("Unsigned integer sub overflow","UnsignedIntegerOverflow");return n}static checkMul(t,e,n){let i=t.mul(e);if(this.isOverflow(i,n))throw new ue("Multiplication overflow","MultiplicationOverflow");return i}static checkMulDivFloor(t,e,n,i){if(n.eq(me))throw new ue("Devide by zero","DivideByZero");let r=t.mul(e).div(n);if(this.isOverflow(r,i))throw new ue("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivCeil(t,e,n,i){if(n.eq(me))throw new ue("Devide by zero","DivideByZero");let r=t.mul(e).add(n.sub(gi)).div(n);if(this.isOverflow(r,i))throw new ue("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivRound(t,e,n,i){if(n.eq(me))throw new ue("Devide by zero","DivideByZero");let r=t.mul(e.add(n.shrn(1))).div(n);if(this.isOverflow(r,i))throw new ue("Multiplication div overflow","MulDivOverflow");return r}static checkMulShiftRight(t,e,n,i){let r=t.mul(e).div(new _n.default(2).pow(new _n.default(n)));if(this.isOverflow(r,i))throw new ue("Multiplication shift right overflow","MulShiftRightOverflow");return r}static checkMulShiftRight64RoundUpIf(t,e,n,i){let r=t.mul(e),s=i&&r.and(Or).gt(me)?r.shrn(64).add(gi):r.shrn(64);if(this.isOverflow(s,n))throw new ue("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 ue("Multiplication shift left overflow","MulShiftLeftOverflow");return r}static checkDivRoundUpIf(t,e,n){if(e.eq(me))throw new ue("Devide by zero","DivideByZero");return n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(Ys.pow(new _n.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(me)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new _n.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 _n.default(1)))}static neg_from(t){return t.eq(me)?t:this.u128_neg(t).add(new _n.default(1)).or(new _n.default(1).shln(127))}};function wf(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new pi.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new pi.default(t.fee_growth_global_a),feeGrowthGlobalB:new pi.default(t.fee_growth_global_b),feeProtocolCoinA:new pi.default(t.fee_protocol_coin_a),feeProtocolCoinB:new pi.default(t.fee_protocol_coin_b),feeRate:new pi.default(t.fee_rate),liquidity:new pi.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}function AS(t){let e=new pi.default(t);return e.lt(me)?{bits:e.neg().xor(new pi.default(2).pow(new pi.default(64)).sub(new pi.default(1))).add(new pi.default(1)).toString()}:{bits:e.toString()}}var SS=It(Ee()),uf=443636,lf=-443636,Qs="79226673515401279992447579055",IS=64,ea="4295048016",so=new SS.default(1e6),At="0x0000000000000000000000000000000000000000000000000000000000000006",E_="partner",Ws="pool_script",xr="pool_script_v2",Xo="router",vu="router_with_partner",Pr="fetcher_script",D_="expect_swap",df="utils",xS="0x1::coin::CoinInfo",OS="0x1::coin::CoinStore",ku="custodian_v2",B_="clob_v2",M_="endpoints_v2",j_=t=>{if(typeof t=="string"&&t.startsWith("0x"))return"object";if(typeof t=="number"||typeof t=="bigint")return"u64";if(typeof t=="boolean")return"bool";throw new ue(`Unknown type for value: ${t}`,"InvalidType")},N_=(t=>(t.Deleted="Deleted",t.Exists="Exists",t.NotExists="NotExists",t))(N_||{});function lt(t){if(t.config===void 0)throw new ue(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var R_=(t=>(t.A2B="a2b",t.B2A="b2a",t))(R_||{}),xu=It(Ee()),Xe=It(ro()),xe=It(Ee()),PS=14,ES="59543866431248",DS="184467440737095516",BS="15793534762490258745",MS=443636;function jS(t,e,n){let i=t.toTwos(n).shln(e);return i.imaskn(n+1),i.fromTwos(n)}function ze(t,e,n){let i=t.toTwos(n).shrn(e);return i.imaskn(n-e+1),i.fromTwos(n-e)}function NS(t){let e;return t&1?e=new xe.default("79232123823359799118286999567"):e=new xe.default("79228162514264337593543950336"),t&2&&(e=ze(e.mul(new xe.default("79236085330515764027303304731")),96,256)),t&4&&(e=ze(e.mul(new xe.default("79244008939048815603706035061")),96,256)),t&8&&(e=ze(e.mul(new xe.default("79259858533276714757314932305")),96,256)),t&16&&(e=ze(e.mul(new xe.default("79291567232598584799939703904")),96,256)),t&32&&(e=ze(e.mul(new xe.default("79355022692464371645785046466")),96,256)),t&64&&(e=ze(e.mul(new xe.default("79482085999252804386437311141")),96,256)),t&128&&(e=ze(e.mul(new xe.default("79736823300114093921829183326")),96,256)),t&256&&(e=ze(e.mul(new xe.default("80248749790819932309965073892")),96,256)),t&512&&(e=ze(e.mul(new xe.default("81282483887344747381513967011")),96,256)),t&1024&&(e=ze(e.mul(new xe.default("83390072131320151908154831281")),96,256)),t&2048&&(e=ze(e.mul(new xe.default("87770609709833776024991924138")),96,256)),t&4096&&(e=ze(e.mul(new xe.default("97234110755111693312479820773")),96,256)),t&8192&&(e=ze(e.mul(new xe.default("119332217159966728226237229890")),96,256)),t&16384&&(e=ze(e.mul(new xe.default("179736315981702064433883588727")),96,256)),t&32768&&(e=ze(e.mul(new xe.default("407748233172238350107850275304")),96,256)),t&65536&&(e=ze(e.mul(new xe.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=ze(e.mul(new xe.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=ze(e.mul(new xe.default("38992368544603139932233054999993551")),96,256)),ze(e,32,256)}function RS(t){let e=Math.abs(t),n;return e&1?n=new xe.default("18445821805675392311"):n=new xe.default("18446744073709551616"),e&2&&(n=ze(n.mul(new xe.default("18444899583751176498")),64,256)),e&4&&(n=ze(n.mul(new xe.default("18443055278223354162")),64,256)),e&8&&(n=ze(n.mul(new xe.default("18439367220385604838")),64,256)),e&16&&(n=ze(n.mul(new xe.default("18431993317065449817")),64,256)),e&32&&(n=ze(n.mul(new xe.default("18417254355718160513")),64,256)),e&64&&(n=ze(n.mul(new xe.default("18387811781193591352")),64,256)),e&128&&(n=ze(n.mul(new xe.default("18329067761203520168")),64,256)),e&256&&(n=ze(n.mul(new xe.default("18212142134806087854")),64,256)),e&512&&(n=ze(n.mul(new xe.default("17980523815641551639")),64,256)),e&1024&&(n=ze(n.mul(new xe.default("17526086738831147013")),64,256)),e&2048&&(n=ze(n.mul(new xe.default("16651378430235024244")),64,256)),e&4096&&(n=ze(n.mul(new xe.default("15030750278693429944")),64,256)),e&8192&&(n=ze(n.mul(new xe.default("12247334978882834399")),64,256)),e&16384&&(n=ze(n.mul(new xe.default("8131365268884726200")),64,256)),e&32768&&(n=ze(n.mul(new xe.default("3584323654723342297")),64,256)),e&65536&&(n=ze(n.mul(new xe.default("696457651847595233")),64,256)),e&131072&&(n=ze(n.mul(new xe.default("26294789957452057")),64,256)),e&262144&&(n=ze(n.mul(new xe.default("37481735321082")),64,256)),n}var ft=class{static priceToSqrtPriceX64(t,e,n){return Te.toX64(t.mul(On.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return Te.fromX64(t).pow(2).mul(On.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new xe.default(NS(t)):new xe.default(RS(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new xe.default(Qs))||t.lt(new xe.default(ea)))throw new ue("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,n=new xe.default(e-64),i=jS(n,32,128),r=new xe.default("8000000000000000","hex"),o=0,s=new xe.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new xe.default(0))&&o<PS;){a=a.mul(a);let D=a.shrn(127);a=a.shrn(63+D.toNumber()),s=s.add(r.mul(D)),r=r.shrn(1),o+=1}let c=s.shrn(32),d=i.add(c).mul(new xe.default(ES)),h=ze(d.sub(new xe.default(DS)),64,128).toNumber(),_=ze(d.add(new xe.default(BS)),64,128).toNumber();return h===_?h:ft.tickIndexToSqrtPriceX64(_).lte(t)?_:h}static tickIndexToPrice(t,e,n){return ft.sqrtPriceX64ToPrice(ft.tickIndexToSqrtPriceX64(t),e,n)}static priceToTickIndex(t,e,n){return ft.sqrtPriceX64ToTickIndex(ft.priceToSqrtPriceX64(t,e,n))}static priceToInitializableTickIndex(t,e,n,i){return ft.getInitializableTickIndex(ft.priceToTickIndex(t,e,n),i)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ft.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ft.getInitializableTickIndex(t,e)-e}};function FS(t){let e=[];for(let n of t){let i={objectId:n.objectId,index:Number(or(BigInt(n.index)).toString()),sqrtPrice:n.sqrtPrice,liquidityNet:new xe.default(BigInt.asIntN(128,BigInt(BigInt(n.liquidityNet.toString()))).toString()),liquidityGross:n.liquidityGross,feeGrowthOutsideA:n.feeGrowthOutsideA,feeGrowthOutsideB:n.feeGrowthOutsideB,rewardersGrowthOutside:[new xe.default(n.rewardersGrowthOutside[0]),new xe.default(n.rewardersGrowthOutside[1]),new xe.default(n.rewardersGrowthOutside[2])]};e.push(i)}return e}function F_(t){return Ot(t).add(Ot(MS))}var qS=new xu.default(365),LS=new xu.default(24),US=new xu.default(3600),$S=new xu.default(.5);function GS(t,e,n,i){return qS.mul(LS).mul(US).mul($S).mul(t.mul(e).add(n).div(i))}function zS(t,e,n,i,r,o){let s=new Xe.default(t.toString()).div(new Xe.default(10**n)),a=new Xe.default(e.toString()).div(new Xe.default(10**i));return s.mul(r).add(a.mul(o))}function VS(t,e,n,i,r,o,s,a,c,u,d,h,_,C,D,O,B,j,M,R,K,X,Y,oe){let $=new Xe.default(h),ne=new Xe.default(_),G=new Xe.default(O),W=new Xe.default(B),I=new Xe.default(j),N=new Xe.default(M),l=new Xe.default(R),f=new Xe.default(K),w=new Xe.default(X),k=new Xe.default(Y),g=new Xe.default(oe),m=ft.tickIndexToSqrtPriceX64(e),b=ft.tickIndexToSqrtPriceX64(n),y=Te.toX64_Decimal(Te.fromX64(m)).round(),p=Te.toX64_Decimal(Te.fromX64(b)).round(),T=Te.toX64_Decimal(Te.fromX64(i)).round(),F,z=$.mul(new Xe.default(10**o)).mul(p.mul(y)).div(p.sub(y)).round(),Q=ne.mul(new Xe.default(10**s)).div(p.sub(y)).round();t<e?F=z:t>n?F=Q:F=Xe.default.min(z,Q);let H=F.mul(T.sub(y)),fe=F.mul(p.sub(T)).div(T.mul(p)).div(new Xe.default(10**o)).mul(l).add(H.div(new Xe.default(10**s).mul(f))),Ce=zS(C,D,o,s,l,f),ke=fe.div(Ce),Fe=F.eq(new Xe.default(0))?new Xe.default(0):new Xe.default(d/1e4).mul(G).mul(new Xe.default(F.toString()).div(new Xe.default(r.toString()).add(new Xe.default(F.toString())))).div(fe),kt=ke.eq(new Xe.default(0))?new Xe.default(0):ke.mul(new Xe.default(36500/7)).div(fe),it=W.div(new Xe.default(10**a)).mul(w).mul(kt),Qe=I.div(new Xe.default(10**c)).mul(k).mul(kt),ti=N.div(new Xe.default(10**u)).mul(g).mul(kt);return{feeAPR:Fe,posRewarder0APR:it,posRewarder1APR:Qe,posRewarder2APR:ti}}function KS(t,e,n,i){let r=Math.max(t,n),s=Math.min(e,i)-r,a=e-t,c=i-n,u=new Xe.default(a.toString()),d=new Xe.default(c.toString()),h=new Xe.default(s.toString()),_=new Xe.default("0");return s<0?_=new Xe.default("0"):a===s?_=d.div(h):c===s?_=h.div(u):_=h.mul(h).div(d).div(u),_}var ct=It(Ee()),WS=It(Ee()),Gi=class{static getDefaultSqrtPriceLimit(t){return new WS.default(t?ea:Qs)}static getDefaultOtherAmountThreshold(t){return t?me:Or}};function HS(t,e,n){let i=e.mul(n).shln(64),r=e.shln(64).add(t.mul(n));return Te.divRoundUp(i,r)}function XS(t,e,n){let i=e.mul(n).shln(64),r=e.shln(64).sub(t.mul(n));return Te.divRoundUp(i,r)}function ZS(t,e,n){return n.sub(Te.divRoundUp(t.shln(64),e))}function JS(t,e,n){return n.add(t.shln(64).div(e))}function YS(t,e){return{coinA:new ct.default(t.toString()),coinB:new ct.default(e.toString())}}function QS(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t),o=n.mul(r).shln(64),s=t.mul(e),a=o.div(s),c=o.mod(s);return i&&!c.eq(me)?a.add(new ct.default(1)):a}function e2(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.eq(me)||r.eq(me))return me;let o=n.mul(r),a=i&&o.and(Or).gt(me)?o.shrn(64).add(gi):o.shrn(64);if(Te.isOverflow(a,64))throw new ue("Result large than u64 max","IntegerDowncastOverflow");return a}function yf(t,e,n,i){if(n.eq(me))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 ue("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 ct.default(ea)))throw new ue("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(a.gt(new ct.default(Qs)))throw new ue("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return a}function bf(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 ct.default(ea))||o.gt(new ct.default(Qs)))throw new ue("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function q_(t,e,n,i){return i?yf(t,e,n,!0):bf(t,e,n,!0)}function L_(t,e,n,i){return i?bf(t,e,n,!1):yf(t,e,n,!1)}function ff(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(me)||r.eq(me))return me;let o;if(i){let s=new ct.default(n).mul(new ct.default(r)).shln(64),a=e.mul(t),c=s.div(a);o=s.mod(a).eq(me)?c:c.add(gi)}else{let s=new ct.default(n).mul(new ct.default(r));o=s.and(Or).gt(me)?s.shrn(64).add(gi):s.shrn(64)}return o}function hf(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(me)||r.eq(me))return me;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 vf(t,e,n,i,r,o){if(n===me)return{amountIn:me,amountOut:me,nextSqrtPrice:e,feeAmount:me};let s=t.gte(e),a,c,u,d;if(o){let h=Te.checkMulDivFloor(i,Te.checkUnsignedSub(so,r),so,64),_=ff(t,e,n,s);_.gt(h)?(a=h,d=Te.checkUnsignedSub(i,h),u=q_(t,n,h,s)):(a=_,d=Te.checkMulDivCeil(a,r,so.sub(r),64),u=e),c=hf(t,u,n,s)}else{let h=hf(t,e,n,s);h.gt(i)?(c=i,u=L_(t,n,i,s)):(c=h,u=e),a=ff(t,u,n,s),d=Te.checkMulDivCeil(a,r,so.sub(r),64)}return{amountIn:a,amountOut:c,nextSqrtPrice:u,feeAmount:d}}function U_(t,e,n,i,r){let o=n,s=i.liquidity,{currentSqrtPrice:a}=i,c={amountIn:me,amountOut:me,feeAmount:me,refAmount:me,nextSqrtPrice:me,crossTickNum:0},u,d,h=Gi.getDefaultSqrtPriceLimit(t);for(let _ of r){if(t&&i.currentTickIndex<_.index||!t&&i.currentTickIndex>=_.index||_===null)continue;t&&h.gt(_.sqrtPrice)||!t&&h.lt(_.sqrtPrice)?u=h:u=_.sqrtPrice;let C=vf(a,u,s,o,i.feeRate,e);if(C.amountIn.eq(me)||(o=e?o.sub(C.amountIn.add(C.feeAmount)):o.sub(C.amountOut)),c.amountIn=c.amountIn.add(C.amountIn),c.amountOut=c.amountOut.add(C.amountOut),c.feeAmount=c.feeAmount.add(C.feeAmount),C.nextSqrtPrice.eq(_.sqrtPrice)?(d=_.liquidityNet.mul(new ct.default(-1)),t?Te.is_neg(d)?s=s.add(new ct.default(mi(BigInt(d.toString()),128))):s=s.add(d):Te.is_neg(d)?s=s.sub(new ct.default(mi(BigInt(d.toString()),128))):s=s.sub(d),a=_.sqrtPrice):a=C.nextSqrtPrice,c.crossTickNum+=1,o.eq(me))break}return c.amountIn=c.amountIn.add(c.feeAmount),c.nextSqrtPrice=a,c}function zs(t,e,n){let i=ct.default.min(t,e),r=ct.default.max(t,e),o=Te.fromX64_BN(n.mul(r).mul(i)),s=r.sub(i);return o.div(s)}function Vs(t,e,n){let i=ct.default.min(t,e),o=ct.default.max(t,e).sub(i);return n.shln(64).div(o)}var Hs=class{static updateFeeRate(t,e,n,i,r){let o=Te.checkMulDivCeil(e,new ct.default(i),so,64),s=n===0?me:Te.checkMulDivFloor(e,new ct.default(n),so,64),a=e.mul(o).mul(s);if(r?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),a.eq(me)||t.liquidity.eq(me))return{refFee:s,clmm:t};let c=a.shln(64).div(t.liquidity);return r?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(c):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(c),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,n,i,r){let o=new On(t.toString()),s=new On(e.toString()),a=new On(n.toString()),c=new On(i.toString()),u,d;return e.lt(n)?(u=Te.toX64_Decimal(o).mul(c.sub(a)).div(a.mul(c)),d=new On(0)):e.lt(i)?(u=Te.toX64_Decimal(o).mul(c.sub(s)).div(s.mul(c)),d=Te.fromX64_Decimal(o.mul(s.sub(a)))):(u=new On(0),d=Te.fromX64_Decimal(o.mul(c.sub(a)))),r?{coinA:new ct.default(u.ceil().toString()),coinB:new ct.default(d.ceil().toString())}:{coinA:new ct.default(u.floor().toString()),coinB:new ct.default(d.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,n,i,r,o,s){let a=ft.sqrtPriceX64ToTickIndex(s),c=ft.tickIndexToSqrtPriceX64(t),u=ft.tickIndexToSqrtPriceX64(e),d;if(a<t){if(!i)throw new ue("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");d=zs(c,u,n)}else if(a>e){if(i)throw new ue("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");d=Vs(u,c,n)}else i?d=zs(s,u,n):d=Vs(s,c,n);let h=Hs.getCoinAmountFromLiquidity(d,s,c,u,r),_=r?Ot(h.coinA.toString()).mul(1+o).toString():Ot(h.coinA.toString()).mul(1-o).toString(),C=r?Ot(h.coinB.toString()).mul(1+o).toString():Ot(h.coinB.toString()).mul(1-o).toString();return{coinAmountA:h.coinA,coinAmountB:h.coinB,tokenMaxA:r?new ct.default(On.ceil(_).toString()):new ct.default(On.floor(_).toString()),tokenMaxB:r?new ct.default(On.ceil(C).toString()):new ct.default(On.floor(C).toString()),liquidityAmount:d,fix_amount_a:i}}static estimateLiquidityFromcoinAmounts(t,e,n,i){if(e>n)throw new ue("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let r=ft.sqrtPriceX64ToTickIndex(t),o=ft.tickIndexToSqrtPriceX64(e),s=ft.tickIndexToSqrtPriceX64(n);if(r<e)return zs(o,s,i.coinA);if(r>=n)return Vs(s,o,i.coinB);let a=zs(t,s,i.coinA),c=Vs(t,o,i.coinB);return ct.default.min(a,c)}static estCoinAmountsFromTotalAmount(t,e,n,i,r,o){let{ratioA:s,ratioB:a}=Hs.calculateDepositRatioFixTokenA(t,e,n),c=Ot(i).mul(s).div(r),u=Ot(i).mul(a).div(o);return{amountA:c,amountB:u}}static calculateDepositRatioFixTokenA(t,e,n){let i=new ct.default(1e8),{coinAmountB:r}=Hs.estLiquidityAndcoinAmountFromOneAmounts(t,e,i,!0,!0,0,n),o=ft.sqrtPriceX64ToPrice(n,0,0),s=Ot(i.toString()).mul(o),a=s.add(r.toString()),c=s.div(a),u=Ot(r.toString()).div(a);return{ratioA:c,ratioB:u}}},kf=require("@mysten/sui.js/utils"),t2=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function Tf(t){return t.startsWith("0x")?t:`0x${t}`}function Cf(t){return t.startsWith("0x")?`${t.slice(2)}`:t}function $_(t,e=4,n=4){let i=Math.max(e,1),r=Math.max(n,1);return`${t.slice(0,i+2)} ... ${t.slice(-r)}`}function n2(t,e=4,n=4){return $_(Tf(t),e,n)}function i2(t,e={leadingZero:!0}){if(typeof t!="string")return!1;let n=t;if(e.leadingZero){if(!t.startsWith("0x"))return!1;n=n.substring(2)}return t2.test(n)}function G_(t){if(!Buffer.isBuffer(t))if(Array.isArray(t))t=Buffer.from(t);else if(typeof t=="string")Ks.isHexString(t)?t=Buffer.from(Ks.padToEven(Ks.stripHexPrefix(t)),"hex"):t=Buffer.from(t);else if(typeof t=="number")t=Ks.intToBuffer(t);else if(t==null)t=Buffer.allocUnsafe(0);else if(t.toArray)t=Buffer.from(t.toArray());else throw new ue("Invalid type","InvalidType");return t}function r2(t){return Tf(G_(t).toString("hex"))}function o2(t){let e=new ArrayBuffer(4),n=new DataView(e);for(let r=0;r<t.length;r++)n.setUint8(r,t.charCodeAt(r));return n.getUint32(0,!0)}function z_(t){let e,n,i,r,o;e="";let s=t.length;for(n=0;n<s;)switch(i=t.charCodeAt(n++),i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=t.charAt(n-1);break;case 12:case 13:r=t.charCodeAt(n++),e+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=t.charCodeAt(n++),o=t.charCodeAt(n++),e+=String.fromCharCode((i&15)<<12|(r&63)<<6|(o&63)<<0);break}return e}function s2(t){let e="",n=Cf(t),i=n.length/2;for(let r=0;r<i;r++)e+=String.fromCharCode(parseInt(n.substr(r*2,2),16));return z_(e)}var a2=0,V_=1,c2=2;function b_(t,e){return t===e?a2:t<e?V_:c2}function u2(t,e){let n=0,i=t.length<=e.length?t.length:e.length,r=b_(t.length,e.length);for(;n<i;){let o=b_(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,o!==0)return o}return r}function pf(t,e){return u2(t,e)===V_}function mf(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 l2(t){return t.split("::")[0]}function Le(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 c={...Le(e),type_arguments:i.map(u=>Le(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>Ct.isSuiCoin(u)?u:Le(u).source_address),c.source_address=mf(c.full_address,c.type_arguments),c}let r=e.split("::"),s={full_address:e,address:e===Sf||e===H_?"0x2":(0,kf.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=mf(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function zi(t){return Le(t).source_address}function K_(t){return t.toLowerCase().startsWith("0x")?(0,kf.normalizeSuiObjectId)(t):t}var W_=(t,e=!0)=>{let n=t.split("::"),i=n.shift(),r=(0,kf.normalizeSuiObjectId)(i);return e&&(r=Cf(r)),`${r}::${n.join("::")}`};function Af(t){for(let e in t){let n=typeof t[e];if(n==="object")Af(t[e]);else if(n==="string"){let i=t[e];i&&!i.includes("::")&&(t[e]=K_(i))}}}var d2="0x2::coin::Coin",f2=/^0x2::coin::Coin<(.+)>$/,h2=1e3,p2=500,m2=100,g2=100,_2=1e3,Sf="0x2::sui::SUI",H_="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",w2="SUI",y2=450,b2="0x0000000000000000000000000000000000000005",Ct=class{static getCoinTypeArg(t){let e=t.type.match(f2);return e?e[1]:null}static isSUI(t){let e=Ct.getCoinTypeArg(t);return e?Ct.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`${d2}<${t}>`}static getFaucetCoins(t){let{events:e}=t,n=[];return e?.forEach(i=>{let{type:r}=i;if(Le(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=>{zi(i.coinAddress)===zi(t)&&n.push(i)}),n}static isSuiCoin(t){return Le(t).full_address===Sf}static selectCoinObjectIdGreaterThanOrEqual(t,e,n=[]){let i=Ct.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=Ct.sortByBalance(t.filter(c=>!n.includes(c.coinObjectId))),r=Ct.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 c=e-o,u=a.findIndex(h=>h.balance>=c);if(u!==-1){s.push(a[u]),a.splice(u,1);break}let d=a.pop();d.balance>0&&(s.push(d),o+=d.balance)}return{selectedCoins:Ct.sortByBalance(s),remainingCoins:Ct.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))}},xt=It(Ee());function v2(t,e,n){let i=new xt.default(0),r=new xt.default(0);t.current_tick_index<e.index?(i=Te.subUnderflowU128(new xt.default(t.fee_growth_global_a),new xt.default(e.feeGrowthOutsideA)),r=Te.subUnderflowU128(new xt.default(t.fee_growth_global_b),new xt.default(e.feeGrowthOutsideB))):(i=new xt.default(e.feeGrowthOutsideA),r=new xt.default(e.feeGrowthOutsideB));let o=new xt.default(0),s=new xt.default(0);t.current_tick_index<n.index?(o=new xt.default(n.feeGrowthOutsideA),s=new xt.default(n.feeGrowthOutsideB)):(o=Te.subUnderflowU128(new xt.default(t.fee_growth_global_a),new xt.default(n.feeGrowthOutsideA)),s=Te.subUnderflowU128(new xt.default(t.fee_growth_global_b),new xt.default(n.feeGrowthOutsideB)));let a=Te.subUnderflowU128(Te.subUnderflowU128(new xt.default(t.fee_growth_global_a),i),o),c=Te.subUnderflowU128(Te.subUnderflowU128(new xt.default(t.fee_growth_global_b),r),s);return{fee_growth_inside_a:a,fee_growth_inside_b:c}}function k2(t,e,n){let i=Te.subUnderflowU128(e,new xt.default(t.fee_growth_inside_a)),r=new xt.default(t.liquidity).mul(i).shrn(64),o=Te.subUnderflowU128(n,new xt.default(t.fee_growth_inside_b)),s=new xt.default(t.liquidity).mul(o).shrn(64),a=new xt.default(t.fee_owed_a).add(r),c=new xt.default(t.fee_owed_b).add(s);return{position_id:t.pos_object_id,feeOwedA:a,feeOwedB:c}}function T2(t){let{fee_growth_inside_a:e,fee_growth_inside_b:n}=v2(t.clmmpool,t.tickLower,t.tickUpper);return k2(t.position,e,n)}var v_=It(Ee()),gf=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return gf.fromFraction(t.toDecimalPlaces(1).mul(10).toNumber(),1e3)}static fromFraction(t,e){let n=typeof t=="number"?new v_.default(t.toString()):t,i=typeof e=="number"?new v_.default(e.toString()):e;return new gf(n,i)}},X_=(t=>(t.Input="Specified input amount",t.Output="Specified output amount",t))(X_||{}),Z_=(t=>(t[t.BelowRange=0]="BelowRange",t[t.InRange=1]="InRange",t[t.AboveRange=2]="AboveRange",t))(Z_||{}),C2=class{static getPositionStatus(t,e,n){return t<e?0:t<n?1:2}};function J_(t,e){return t.lt(e)?[t,e]:[e,t]}function If(t,e,n,i){let[r,o]=J_(e,n),s=t.mul(o.sub(r)).shln(64),a=o.mul(r);return i?Te.divRoundUp(s,a):s.div(a)}function xf(t,e,n,i){let[r,o]=J_(e,n),s=t.mul(o.sub(r));return i?Te.shiftRightRoundUp(s):s.shrn(64)}function A2(t,e,n,i){let r=t.mul(e).mul(n).div(n.sub(e));return i?Te.shiftRightRoundUp(r):r.shrn(64)}function S2(t,e,n,i){let r=t.shln(64),o=n.sub(e);return i?Te.divRoundUp(r,o):r.div(o)}function I2(t,e,n,i,r){return i==="Specified input amount"==(r==="a2b")?If(n,t,e,i==="Specified input amount"):xf(n,t,e,i==="Specified input amount")}function x2(t,e,n,i,r){return i==="Specified input amount"==(r==="a2b")?xf(n,t,e,i==="Specified output amount"):If(n,t,e,i==="Specified output amount")}function Iu(t,{numerator:e,denominator:n},i){return i?t.mul(n.add(e)).div(n):t.mul(n).div(n.add(e))}function O2(t,e,n){return{tokenMaxA:Iu(t.coinA,e,n),tokenMaxB:Iu(t.coinB,e,n)}}var _u=It(Ee()),Y_=(t=>(t[t.FIVE=5]="FIVE",t[t.TEN=10]="TEN",t[t.TWENTY=20]="TWENTY",t[t.TWENTY_FIVE=25]="TWENTY_FIVE",t[t.FIVETY=50]="FIVETY",t[t.HUNDRED=100]="HUNDRED",t))(Y_||{});function Q_(t){let e;switch(t){case 5:e=5;break;case 10:e=10;break;case 20:e=20;break;case 25:e=25;break;case 50:e=50;break;case 100:e=100;break;default:e=1}let n=100/e+1,i=new Array(n);for(let r=0;r<n;r+=1)i[r]=r*e;return i}function e0(t,e){let n=Q_(e),i=new Array(n.length);for(let r=0;r<n.length;r+=1)i[r]=t.muln(n[r]).divn(100);return i}function P2(t,e,n,i){for(let r=e;r<t;r+=1)n.amountInArray[r]=n.amountInArray[r].add(i.amountIn),n.amountOutArray[r]=n.amountOutArray[r].add(i.amountOut),n.feeAmountArray[r]=n.feeAmountArray[r].add(i.feeAmount);return n}function E2(t,e,n,i,r){let o=new _u.default(i.liquidity),{currentSqrtPrice:s}=i,a={amountInArray:[],amountOutArray:[],feeAmountArray:[],nextSqrtPriceArray:[],isExceed:[]};n.forEach(()=>{a.amountInArray.push(me),a.amountOutArray.push(me),a.feeAmountArray.push(me),a.nextSqrtPriceArray.push(me)});let c,u,d=Gi.getDefaultSqrtPriceLimit(t),h=n.length,_=n[1],C=1,D;t?D=r.sort((O,B)=>B.index-O.index):D=r.sort((O,B)=>O.index-B.index);for(let O of D){if(t){if(i.currentTickIndex<O.index)continue}else if(i.currentTickIndex>O.index)continue;if(O===null)continue;t&&d.gt(O.sqrtPrice)||!t&&d.lt(O.sqrtPrice)?c=d:c=O.sqrtPrice;let B={amountIn:me,amountOut:me,nextSqrtPrice:me,feeAmount:me},j=s,M=o,R=_,K=C;for(let X=C;X<h;X+=1){let Y=vf(s,c,o,_,new _u.default(i.feeRate),e);if(B=Y,Y.amountIn.eq(me)||(_=e?_.sub(Y.amountIn.add(Y.feeAmount)):_.sub(Y.amountOut)),_.eq(me))a.amountInArray[X]=a.amountInArray[X].add(Y.amountIn),a.amountOutArray[X]=a.amountOutArray[X].add(Y.amountOut),a.feeAmountArray[X]=a.feeAmountArray[X].add(Y.feeAmount),Y.nextSqrtPrice.eq(O.sqrtPrice)?(u=t?O.liquidityNet.mul(new _u.default(-1)):O.liquidityNet,o=u.gt(me)?o.add(u):o.sub(u.abs()),s=O.sqrtPrice):s=Y.nextSqrtPrice,a.amountInArray[X]=a.amountInArray[X].add(a.feeAmountArray[X]),a.nextSqrtPriceArray[X]=s,o=M,s=j,X!==h-1&&(_=R.add(n[X+1].sub(n[K]))),C+=1;else{a=P2(h,X,a,Y),R=_,K=C;break}}if(C===h)break;B.nextSqrtPrice.eq(O.sqrtPrice)?(u=t?O.liquidityNet.mul(new _u.default(-1)):O.liquidityNet,o=u.gt(me)?o.add(u):o.sub(u.abs()),s=O.sqrtPrice):s=B.nextSqrtPrice}return e?n.forEach((O,B)=>{a.isExceed.push(a.amountInArray[B].lt(O))}):n.forEach((O,B)=>{a.isExceed.push(a.amountOutArray[B].lt(O))}),a}var D2=class{minSplitUnit;amountArray;byAmountIn;a2b;clmmpool;ticks;splitSwapResult;constructor(t,e,n,i,r,o){this.minSplitUnit=e,this.a2b=i,this.byAmountIn=r,this.clmmpool=n,this.ticks=o,this.amountArray=[],this.createSplitSwapParams=this.createSplitSwapParams.bind(this),this.createSplitSwapParams(t,e),this.splitSwapResult={amountInArray:[],amountOutArray:[],feeAmountArray:[],nextSqrtPriceArray:[],isExceed:[]},this.computeSwap=this.computeSwap.bind(this)}createSplitSwapParams(t,e){let n=e0(t,e);this.amountArray=n}computeSwap(){let t=wf(this.clmmpool);return this.splitSwapResult=E2(this.a2b,this.byAmountIn,this.amountArray,t,this.ticks),this.splitSwapResult}},k_=It(ro());function Ot(t){return k_.default.isDecimal(t)?t:new k_.default(t===void 0?0:t)}function Of(t){return Ot(10).pow(Ot(t).abs())}function co(t){return t.data}function Pf(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 Df(t){if("reference"in t)return t.reference;let e=co(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Pf(t)}function ao(t){return"objectId"in t?t.objectId:Df(t)?.objectId??Ef(t)}function B2(t){return"version"in t?t.version:Df(t)?.version}function t0(t){return t.data!==void 0}function M2(t){return t.content!==void 0}function j2(t){let e=co(t);if(e?.content?.dataType==="package")return e.content.disassembled}function Ou(t){let e="data"in t?co(t):t;if(!(!e||!M2(e)||e.content.dataType!=="moveObject"))return e.content}function Pu(t){return Ou(t)?.type}function n0(t){let e=t0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":Pu(t):e?.type}function Eu(t){return co(t)?.previousTransaction}function i0(t){return co(t)?.owner}function r0(t){let e=co(t)?.display;return e||{data:null,error:null}}function rr(t){let e=Ou(t)?.fields;if(e)return"fields"in e?e.fields:e}function N2(t){return Ou(t)?.hasPublicTransfer??!1}function R2(t,e){let n=Of(Ot(e));return Number(Ot(t).mul(n))}function mi(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function or(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function F2(t,e){let n=Of(Ot(e));return Number(Ot(t).div(n))}function q2(t,e="hex"){if(t instanceof Uint8Array){let i=Buffer.from(t);return w_.Ed25519Keypair.fromSecretKey(i)}let n=e==="hex"?(0,Su.fromHEX)(t):(0,Su.fromB64)(t);return w_.Ed25519Keypair.fromSecretKey(n)}function L2(t,e="hex"){if(t instanceof Uint8Array){let i=Buffer.from(t);return y_.Secp256k1Keypair.fromSecretKey(i)}let n=e==="hex"?(0,Su.fromHEX)(t):(0,Su.fromB64)(t);return y_.Secp256k1Keypair.fromSecretKey(n)}function U2(t,e,n){let i=Le(t).name,r=Le(e).name;return`${i}-${r}[${n}]`}function Tu(t){let e=Pu(t),n=Le(e),i=rr(t);if(i==null)throw new ue(`Pool id ${ao(t)} not exists.`,"InvalidPoolObject");let r=[];i.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:a}=s.fields,c=Te.fromX64(new Ei.default(a)),u=Math.floor(c.toNumber()*60*60*24);r.push({emissions_per_second:a,coinAddress:Le(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:u})});let o={poolAddress:ao(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:or(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=U2(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function o0(t){let e=r0(t).data,n={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(n.creator=e.creator,n.description=e.description,n.image_url=e.image_url,n.link=e.link,n.name=e.name,n.project_url=e.project_url),n}function Cu(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new ue(`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=rr(t);if(i){let s=Pu(t),a=i0(t);"nft"in i?(i=i.nft.fields,e.description=i.description,e.name=i.name,e.link=i.url):e=o0(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:or(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:or(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=Pf(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 Bf(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:c}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=a,e.reward_growth_inside_0=c):s===1?(e.reward_amount_owed_1=a,e.reward_growth_inside_1=c):s===2&&(e.reward_amount_owed_2=a,e.reward_growth_inside_2=c)});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:or(BigInt(n)),tick_upper_index:or(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 Au(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new ue(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let n=rr(t).value.fields.value.fields;return{objectId:ao(t),index:or(BigInt(n.index.fields.bits)),sqrtPrice:new Ei.default(n.sqrt_price),liquidityNet:new Ei.default(n.liquidity_net.fields.bits),liquidityGross:new Ei.default(n.liquidity_gross),feeGrowthOutsideA:new Ei.default(n.fee_growth_outside_a),feeGrowthOutsideB:new Ei.default(n.fee_growth_outside_b),rewardersGrowthOutside:n.rewards_growth_outside}}function s0(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 ue("Invalid tick fields.","InvalidTickFields");let e=or(BigInt(t.index.bits)),n=new Ei.default(t.sqrt_price),i=new Ei.default(t.liquidity_net.bits),r=new Ei.default(t.liquidity_gross),o=new Ei.default(t.fee_growth_outside_a),s=new Ei.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}}var zo=It(Ee()),$2=class{static getMinIndex(t){return lf+Math.abs(lf)%t}static getMaxIndex(t){return uf-uf%t}};function G2(t,e){let n=Math.abs(t)%e;return t>0?n>e/2?t+e-n:t-n:n>e/2?t-e+n:t+n}function a0(t,e,n,i,r,o){let s=t.rewarder_infos,a=[];for(let c=0;c<s.length;c+=1){let u=o[c];e!==null&&(t.current_tick_index<i?u=o[c].sub(new zo.default(e.rewardersGrowthOutside[c])):u=e.rewardersGrowthOutside[c]);let d=new zo.default(0);n!==null&&(t.current_tick_index>=r?d=o[c].sub(new zo.default(n.rewardersGrowthOutside[c])):d=n.rewardersGrowthOutside[c]);let h=Te.subUnderflowU128(Te.subUnderflowU128(new zo.default(o[c]),new zo.default(u)),new zo.default(d));a.push(h)}return a}var wu=It(Ee()),z2=It(ro()),Vo=require("@mysten/sui.js/transactions");function Xs(t){let e=Ct.isSuiCoin(t.coinTypeA),n=Ct.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:n}}function V2(t,e){return z2.default.ceil(Ot(t).div(1+e)).toString()}async function K2(t,e=!0){console.log("inputs",t.blockData.inputs),t.blockData.transactions.forEach((n,i)=>{e&&console.log(`transaction ${i}: `,n)})}var Ie=class{static createCollectRewarderAndFeeParams(t,e,n,i,r,o){r===void 0&&(r=[...i]),o===void 0&&(o=[...i]);let s=zi(n.coinTypeA),a=zi(n.coinTypeB);if(n.collect_fee){let u=Ie.buildCoinForAmount(e,r,BigInt(0),s,!1);r=u.remainCoins;let d=Ie.buildCoinForAmount(e,o,BigInt(0),a,!1);o=d.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:n.pool_id,pos_id:n.pos_id,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB},e,u.targetCoin,d.targetCoin)}let c=[];return n.rewarder_coin_types.forEach(u=>{switch(zi(u)){case s:c.push(Ie.buildCoinForAmount(e,r,BigInt(0),u,!1).targetCoin);break;case a:c.push(Ie.buildCoinForAmount(e,o,BigInt(0),u,!1).targetCoin);break;default:c.push(Ie.buildCoinForAmount(e,i,BigInt(0),u,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(n,e,c),e}static async adjustTransactionForGas(t,e,n,i){i.setSender(t.senderAddress);let r=Ct.selectCoinAssetGreaterThanOrEqual(e,n).selectedCoins;if(r.length===0)throw new ue("Insufficient balance","InsufficientBalance");let o=Ct.calculateTotalBalance(e);if(o-n>1e9)return{fixAmount:n};let s=await t.fullClient.calculationTxGas(i);if(Ct.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),r.map(c=>c.coinObjectId)).selectedCoins.length===0){let c=BigInt(s)+BigInt(500);if(o-n<c){if(n-=c,n<0)throw new ue("gas Insufficient balance","InsufficientBalance");let u=new Vo.TransactionBlock;return{fixAmount:n,newTx:u}}}return{fixAmount:n}}static async buildAddLiquidityFixTokenForGas(t,e,n,i){let r=await Ie.buildAddLiquidityFixToken(t,e,n),{isAdjustCoinA:o}=Xs(n),s=o?n.amount_a:n.amount_b,a=await Ie.adjustTransactionForGas(t,Ct.getCoinAssets(o?n.coinTypeA:n.coinTypeB,e),BigInt(s),r),{fixAmount:c}=a,{newTx:u}=a;if(u!==void 0){let d,h;if(o)n.amount_a=Number(c),d=Ie.buildAddLiquidityFixTokenCoinInput(u,!n.fix_amount_a,c.toString(),n.slippage,n.coinTypeA,e,!1),h=Ie.buildAddLiquidityFixTokenCoinInput(u,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);else return n.amount_b=Number(c),d=Ie.buildAddLiquidityFixTokenCoinInput(u,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),h=Ie.buildAddLiquidityFixTokenCoinInput(u,n.fix_amount_a,c.toString(),n.slippage,n.coinTypeB,e,!1),n=Ie.fixAddLiquidityFixTokenParams(n,i.slippage,i.curSqrtPrice),r=await Ie.buildAddLiquidityFixTokenArgs(u,t,e,n,d,h),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 Vo.TransactionBlock,r=Ie.buildAddLiquidityFixTokenCoinInput(i,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),o=Ie.buildAddLiquidityFixTokenCoinInput(i,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);return i=Ie.buildAddLiquidityFixTokenArgs(i,t,e,n,r,o),i}static buildAddLiquidityFixTokenCoinInput(t,e,n,i,r,o,s=!0){return e?Ie.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(V2(n,i)),amountFirst:BigInt(n)},r,s):Ie.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=Hs.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new wu.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:c,integrate:u}=e.sdkOptions;i.is_open||(t=Ie.createCollectRewarderAndFeeParams(e,t,i,n,r.remainCoins,o.remainCoins));let d=lt(c),h=i.is_open?[t.object(d.global_config_id),t.object(i.pool_id),t.pure(mi(BigInt(i.tick_lower)).toString()),t.pure(mi(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(At)]:[t.object(d.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(At)];return t.moveCall({target:`${u.published_at}::${xr}::${a}`,typeArguments:s,arguments:h}),t}static async buildSwapTransactionForGas(t,e,n,i){let r=Ie.buildSwapTransaction(t,e,n);r.setSender(t.senderAddress);let o=await Ie.adjustTransactionForGas(t,Ct.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 Ie.fixSwapParams(t,e,i);let c=Ie.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),u=Ie.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);r=Ie.buildSwapTransactionArgs(a,e,t.sdkOptions,c,u)}return r}static buildSwapTransaction(t,e,n){let i=new Vo.TransactionBlock;i.setSender(t.senderAddress);let r=Ie.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=Ie.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return i=Ie.buildSwapTransactionArgs(i,e,t.sdkOptions,r,o),i}static buildSwapTransactionArgs(t,e,n,i,r){let{clmm_pool:o,integrate:s}=n,a=Gi.getDefaultSqrtPriceLimit(e.a2b),c=[e.coinTypeA,e.coinTypeB],{global_config_id:u}=lt(o);if(u===void 0)throw Error("clmm.config.global_config_id is undefined");let d=e.swap_partner!==void 0,h=d?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",_=d?[t.pure(u),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(At)]:[t.pure(u),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(At)];return t.moveCall({target:`${s.published_at}::${xr}::${h}`,typeArguments:c,arguments:_}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,n,i){let{tx:r,coinABs:o}=Ie.buildSwapTransactionWithoutTransferCoins(t,e,n);r.setSender(t.senderAddress);let s=await Ie.adjustTransactionForGas(t,Ct.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:a,newTx:c}=s;if(c!==void 0){c.setSender(t.senderAddress),e.by_amount_in?e.amount=a.toString():e.amount_limit=a.toString(),e=await Ie.fixSwapParams(t,e,i);let u=Ie.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),d=Ie.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),h=Ie.buildSwapTransactionWithoutTransferCoinArgs(t,c,e,t.sdkOptions,u,d);r=h.tx,o=h.txRes}return{tx:r,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,n){let i=new Vo.TransactionBlock;i.setSender(t.senderAddress);let r=Ie.buildCoinForAmount(i,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=Ie.buildCoinForAmount(i,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=Ie.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,c=Gi.getDefaultSqrtPriceLimit(n.a2b),{global_config_id:u}=lt(s);if(u===void 0)throw Error("clmm.config.global_config_id is undefined");let d=n.swap_partner!==void 0,h=d?"swap_with_partner":"swap",_=d?vu:Xo,C=d?[e.pure(u),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(c.toString()),e.pure(!1),e.pure(At)]:[e.pure(u),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(c.toString()),e.pure(!1),e.pure(At)],D=[n.coinTypeA,n.coinTypeB],O=e.moveCall({target:`${a.published_at}::${_}::${h}`,typeArguments:D,arguments:C});if(n.by_amount_in){let B=n.a2b?n.coinTypeB:n.coinTypeA,j=n.a2b?O[1]:O[0],M=Number(n.amount_limit);this.checkCoinThreshold(t,n.by_amount_in,e,j,M,B)}return{tx:e,txRes:O}}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=Iu(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 Ie.buildCoinForAmount(e,o,n,i,r).targetCoin}static buildCoinForAmount(t,e,n,i,r=!0,o=!1){let s=Ct.getCoinAssets(i,e);if(n===BigInt(0)&&s.length===0)return Ie.buildZeroValueCoin(e,t,i,r);let a=Ct.calculateTotalBalance(s);if(a<n)throw new ue(`The amount(${a}) is Insufficient balance for ${i} , expect ${n} `,"InsufficientBalance");return Ie.buildCoin(t,e,s,n,i,r,o)}static buildCoin(t,e,n,i,r,o=!0,s=!1){if(Ct.isSuiCoin(r)){if(o){let M=t.splitCoins(t.gas,[t.pure(i.toString())]);return{targetCoin:t.makeMoveVec({objects:[M]}),remainCoins:e,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(i===0n&&n.length>1){let M=Ct.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.object(M.objectArray[0]),remainCoins:M.remainCoins,tragetCoinAmount:M.amountArray[0],isMintZeroCoin:!1}}let B=Ct.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.splitCoins(t.gas,[t.pure(i.toString())]),remainCoins:B.remainCoins,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let a=Ct.selectCoinObjectIdGreaterThanOrEqual(n,i),c=a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),u=a.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:u.map(B=>t.object(B))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),isMintZeroCoin:!1};let[d,...h]=u,_=t.object(d),C=_,D=a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),O;return h.length>0&&t.mergeCoins(_,h.map(B=>t.object(B))),s&&Number(c)>Number(i)&&(C=t.splitCoins(_,[t.pure(i.toString())]),D=i.toString(),O=_),{targetCoin:C,remainCoins:a.remainCoins,originalSplitedCoin:O,tragetCoinAmount:D,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,n,i=!0){let r=Ie.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=Ct.getCoinAssets(i,e);if(n.amountFirst===BigInt(0))return o.length>0?Ie.buildCoin(t,[...e],[...o],n.amountFirst,i,r):Ie.buildZeroValueCoin(e,t,i,r);let s=Ct.calculateTotalBalance(o);if(s>=n.amountFirst)return Ie.buildCoin(t,[...e],[...o],n.amountFirst,i,r);if(s<n.amountSecond)throw new ue(`The amount(${s}) is Insufficient balance for ${i} , expect ${n.amountSecond} `,"InsufficientBalance");return Ie.buildCoin(t,[...e],[...o],n.amountSecond,i,r)}static async buildRouterSwapTransaction(t,e,n,i,r){let o=new Vo.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(R=>R&&R.poolAddress),a=Number(s.reduce((R,K)=>R.add(K.amountIn),me).toString()),c=Number(s.reduce((R,K)=>R.add(K.amountOut),me).toString()),u=Math.round(n?Number(c.toString())*(1-e.priceSlippagePoint):Number(a.toString())*(1+e.priceSlippagePoint)),d=e.paths[0].coinType[0],h=e.paths[0].coinType[e.paths[0].coinType.length-1],_=Ie.buildCoinForAmount(r,i,BigInt(n?a:u),d,!1,!0),C=_.originalSplitedCoin!==void 0,D=Ie.buildCoinForAmount(r,i,0n,h,!1),O=await this.buildRouterBasePathReturnCoins(t,e,n,_,D,r),B=[],{toCoin:j,fromCoin:M}=O;if(r=O.tx,D.isMintZeroCoin?B.push({coinType:h,coin:j}):D.originalSplitedCoin!==void 0?r.mergeCoins(D.originalSplitedCoin,[j]):r.mergeCoins(D.targetCoin,[j]),C){let R=_?.originalSplitedCoin;r.mergeCoins(R,[M])}else B.push({coinType:d,coin:M});for(let R=0;R<B.length;R++)this.buildTransferCoin(t,r,B[R].coin,B[R].coinType,o);return r}static async buildRouterBasePathReturnCoins(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=t.sdkOptions,c=lt(s).global_config_id,u=e.paths.filter(R=>R&&R.poolAddress),d=Number(u.reduce((R,K)=>R.add(K.amountIn),me).toString()),h=Number(u.reduce((R,K)=>R.add(K.amountOut),me).toString()),_=Math.round(n?Number(h.toString())*(1-e.priceSlippagePoint):Number(d.toString())*(1+e.priceSlippagePoint)),C=e.paths[0].coinType[0],D=e.paths[0].coinType[e.paths[0].coinType.length-1],O=i.targetCoin,B;r.isMintZeroCoin||r.originalSplitedCoin!==void 0?B=r.targetCoin:B=Ie.callMintZeroValueCoin(o,D);let j=e.partner==="",M=j?Xo:vu;for(let R of u)if(R.poolAddress.length===1){let K=R.a2b[0],X={amount:Number(R.amountIn.toString()),amountLimit:_,poolCoinA:R.a2b[0]?C:D,poolCoinB:R.a2b[0]?D:C},Y=j?"swap":"swap_with_partner",oe=K?O:B,$=K?B:O,ne=n?R.amountIn.toString():R.amountOut.toString(),G=Gi.getDefaultSqrtPriceLimit(K).toString(),W=j?[o.object(c),o.object(R.poolAddress[0]),oe,$,o.pure(K),o.pure(n),o.pure(ne),o.pure(G),o.pure(!1),o.object(At)]:[o.object(c),o.object(R.poolAddress[0]),o.pure(e.partner),oe,$,o.pure(K),o.pure(n),o.pure(ne),o.pure(G),o.pure(!1),o.object(At)],I=[X.poolCoinA,X.poolCoinB],N=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${M}::${Y}`,typeArguments:I,arguments:W});O=K?N[0]:N[1],B=K?N[1]:N[0]}else{let K=n?R.amountIn:R.rawAmountLimit[0],X=n?0:R.amountOut,Y="";R.a2b[0]?R.a2b[1]?Y="swap_ab_bc":Y="swap_ab_cb":R.a2b[1]?Y="swap_ba_bc":Y="swap_ba_cb",j||(Y=`${Y}_with_partner`);let oe=Gi.getDefaultSqrtPriceLimit(R.a2b[0]),$=Gi.getDefaultSqrtPriceLimit(R.a2b[1]),ne=j?[o.object(c),o.object(R.poolAddress[0]),o.object(R.poolAddress[1]),O,B,o.pure(n),o.pure(K.toString()),o.pure(X.toString()),o.pure(oe.toString()),o.pure($.toString()),o.object(At)]:[o.object(c),o.object(R.poolAddress[0]),o.object(R.poolAddress[1]),o.pure(e.partner),O,B,o.pure(n),o.pure(K.toString()),o.pure(X.toString()),o.pure(oe.toString()),o.pure($.toString()),o.object(At)],G=[R.coinType[0],R.coinType[1],R.coinType[2]],W=o.moveCall({target:`${a.published_at}::${M}::${Y}`,typeArguments:G,arguments:ne});O=W[0],B=W[1]}return this.checkCoinThreshold(t,n,o,B,_,D),{fromCoin:O,toCoin:B,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 c,u,d=e.splitPaths.some(h=>h.basePaths.some(_=>_.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!d){let h=[];for(let D of e.splitPaths){let O=[],B=[],j=[],M=[];for(let K=0;K<D.basePaths.length;K+=1){let X=D.basePaths[K];O.push(X.direction),B.push(X.poolAddress),j.push(new wu.default(X.inputAmount.toString())),K===0?M.push(X.fromCoin,X.toCoin):M.push(X.toCoin)}let R={amountIn:new wu.default(D.inputAmount.toString()),amountOut:new wu.default(D.outputAmount.toString()),poolAddress:B,a2b:O,rawAmountLimit:j,isExceed:!1,coinType:M};h.push(R)}let _={paths:h,partner:r,priceSlippagePoint:o},C=await this.buildRouterBasePathReturnCoins(t,_,e.byAmountIn,n,i,s);c=C.fromCoin,u=C.toCoin,s=C.tx}else{let h=Math.round(e.outputAmount*(1-o));c=n.targetCoin,i.isMintZeroCoin||i.originalSplitedCoin!==void 0?u=i.targetCoin:u=Ie.callMintZeroValueCoin(s,e.toCoin);let _=!1,C;if(d){let[D,O]=_f.createAccountCap(a,t.sdkOptions,s);s=O,C=D,_=!0}for(let D=0;D<e.splitPaths.length;D+=1){let O=e.splitPaths[D],B;for(let j=0;j<O.basePaths.length;j+=1){let M=O.basePaths[j];if(M.label==="Deepbook")if(j===0)if(O.basePaths.length===1){let R=this.buildDeepbookBasePathTx(t,M,s,C,c,u,!1);c=R.from,u=R.to}else{B=Ie.callMintZeroValueCoin(s,M.toCoin);let R=this.buildDeepbookBasePathTx(t,M,s,C,c,B,!1);c=R.from,B=R.to}else{let R=this.buildDeepbookBasePathTx(t,M,s,C,B,u,!0);B=R.from,u=R.to}if(M.label==="Cetus")if(j===0)if(O.basePaths.length===1){let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,c,u,!1,r);c=R.from,u=R.to}else{B=Ie.callMintZeroValueCoin(s,M.toCoin);let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,c,B,!1,r);c=R.from,B=R.to}else{let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,B,u,!0,r);B=R.from,u=R.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${df}::send_coin`,typeArguments:[M.fromCoin],arguments:[B,s.pure(a)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,u,h,e.toCoin),_&&(s=_f.deleteAccountCapByObject(C,t.sdkOptions,s))}return{fromCoin:c,toCoin:u,tx:s}}static async buildAggregatorSwapTransaction(t,e,n,i,r,o){let s=new Vo.TransactionBlock,a=e.byAmountIn?Math.round(e.outputAmount*(1-r)):Math.round(e.inputAmount*(1+r)),c=Ie.buildCoinForAmount(s,n,e.byAmountIn?BigInt(e.inputAmount):BigInt(a),e.fromCoin,!1,!0),u=c.originalSplitedCoin!=null,d=Ie.buildCoinForAmount(s,n,0n,e.toCoin,!1),h=await this.buildAggregatorSwapReturnCoins(t,e,c,d,i,r,s,o),{fromCoin:_,toCoin:C}=h;s=h.tx;let D=[];if(d.isMintZeroCoin?D.push({coinType:e.toCoin,coin:C}):d.originalSplitedCoin!=null?s.mergeCoins(d.originalSplitedCoin,[C]):s.mergeCoins(d.targetCoin,[C]),u){let O=c.originalSplitedCoin;s.mergeCoins(O,[_])}else D.push({coinType:e.fromCoin,coin:_});for(let O=0;O<D.length;O++)this.buildTransferCoin(t,s,D[O].coin,D[O].coinType,o);return s}static checkCoinThreshold(t,e,n,i,r,o){e&&n.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Xo}::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,c=e.direction?o:r,u=[n.object(e.poolAddress),i,n.pure(e.inputAmount),n.pure(0),n.pure(e.direction),a,c,n.pure(s),n.object(At)],d=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],h=n.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:d,arguments:u});return r=e.direction?h[0]:h[1],o=e.direction?h[1]:h[0],{from:r,to:o,tx:n}}static buildClmmBasePathTx(t,e,n,i,r,o,s,a){let{clmm_pool:c,integrate:u}=t.sdkOptions,d=lt(c).global_config_id,h=e.direction?r:o,_=e.direction?o:r,C=a==="",D=C?Xo:vu,O=C?"swap":"swap_with_partner",B=i?e.inputAmount.toString():e.outputAmount.toString(),j=Gi.getDefaultSqrtPriceLimit(e.direction),M=C?[n.object(d),n.object(e.poolAddress),h,_,n.pure(e.direction),n.pure(i),n.pure(B),n.pure(j.toString()),n.pure(s),n.object(At)]:[n.object(d),n.object(e.poolAddress),n.pure(a),h,_,n.pure(e.direction),n.pure(i),n.pure(B),n.pure(j.toString()),n.pure(s),n.object(At)],R=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],K=n.moveCall({target:`${u.published_at}::${D}::${O}`,typeArguments:R,arguments:M});return h=K[0],_=K[1],r=e.direction?h:_,o=e.direction?_:h,{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}::${df}::transfer_coin_to_sender`,typeArguments:[i],arguments:[n]})}static buildTransferCoin(t,e,n,i,r){r!=null?e.transferObjects([n],e.pure(r)):Ie.buildTransferCoinToSender(t,e,n,i)}},fn=Ie;TS(fn,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));var T_=require("@mysten/sui.js/utils"),W2=require("@mysten/sui.js/transactions");function cn(t){return!(!t.startsWith("0x")||t.length!==66)}var H2=class{txBlock;constructor(){this.txBlock=new W2.TransactionBlock}transferSuiToMany(t,e){if(t.length!==e.length)throw new ue("The length of recipients and amounts must be the same","InvalidRecipientAndAmountLength");for(let r of t)if(cn(r))throw new ue("Invalid recipient address","InvalidRecipientAddress");let n=this.txBlock,i=n.splitCoins(n.gas,e.map(r=>n.pure(r)));return t.forEach((r,o)=>{n.transferObjects([i[o]],n.pure(r))}),this}transferSui(t,e){if(cn(t))throw new ue("Invalid recipient address","InvalidRecipientAddress");return this.transferSuiToMany([t],[e])}transferCoin(t,e,n){if(cn(t))throw new ue("Invalid recipient address","InvalidRecipientAddress");let i=this.txBlock,[r,...o]=n,s=i.object(r);o.length>0&&i.mergeCoins(s,o.map(c=>i.object(c)));let a=i.splitCoins(s,[i.pure(e)]);return i.transferObjects([a],i.pure(t)),this}transferObjects(t,e){if(cn(e))throw new ue("Invalid recipient address","InvalidRecipientAddress");let n=this.txBlock;return n.transferObjects(this.convertArgs(t),n.pure(e)),this}moveCall(t,e=[],n=[]){let i=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(i)===null)throw new ue("Invalid target format. Expected `${string}::${string}::${string}`","InvalidTarget");let o=this.convertArgs(n);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:e})}address(t){return this.txBlock.pure(t)}pure(t){return this.txBlock.pure(t)}object(t){return this.txBlock.object(t)}setGasBudget(t){this.txBlock.setGasBudget(t)}makeMoveVec(t,e){if(t.length===0)throw new ue("Transaction builder error: Empty array is not allowed","InvalidTransactionBuilder");if(e==="object"&&t.some(i=>typeof i!="string"))throw new ue("Transaction builder error: Object id must be string","InvalidTransactionBuilder");let n=j_(t[0]);return e==="object"||n==="object"?this.txBlock.makeMoveVec({objects:t.map(i=>this.txBlock.object((0,T_.normalizeSuiObjectId)(i)))}):this.txBlock.makeMoveVec({objects:t.map(i=>this.txBlock.pure(i))})}convertArgs(t){return t.map(e=>typeof e=="string"&&e.startsWith("0x")?this.txBlock.object((0,T_.normalizeSuiObjectId)(e)):typeof e!="object"?this.txBlock.pure(e):Array.isArray(e)?this.makeMoveVec(e):e)}},Ln=It(Ee()),nf=require("@mysten/sui.js/transactions"),Ko=new Ln.default(1e9),_f=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}::${B_}::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}::${ku}::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}::${ku}::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:ku}}});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 nf.TransactionBlock,a=[],c=[n,i],u=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(At)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:u,typeArguments:c});let h=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(_=>Le(_.type).name==="BookStatus");if(h.length===0)return a;for(let _=0;_<h[0].parsedJson.depths.length;_++){let C=h[0].parsedJson.price[_],D=h[0].parsedJson.depths[_],O={price:parseInt(C,10),quantity:parseInt(D,10)};a.push(O)}return a}static async getPoolBids(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new nf.TransactionBlock,a=[],c=[n,i],u=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(At)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:u,typeArguments:c});let h=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(_=>Le(_.type).name==="BookStatus");if(h.length===0)return a;for(let _=0;_<h[0].parsedJson.depths.length;_++){let C=h[0].parsedJson.price[_],D=h[0].parsedJson.depths[_],O={price:parseInt(C,10),quantity:parseInt(D,10)};a.push(O)}return a}static async preSwap(t,e,n,i){let r=!1,o=me,s=new Ln.default(i),a=me,c=new Ln.default(i);if(n){let u=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);u===null&&(r=!0),u=u.sort((d,h)=>h.price-d.price);for(let d=0;d<u.length;d+=1){let h=new Ln.default(u[d].quantity),_=new Ln.default(u[d].price),C=h.mul(new Ln.default(_)).mul(new Ln.default(e.takerFeeRate)).div(Ko).div(Ko);if(s.gt(h))s=s.sub(h),o=o.add(h.mul(_).div(Ko).sub(C)),a=a.add(C);else{let D=s.mul(new Ln.default(u[d].price)).div(Ko),O=D.mul(new Ln.default(e.takerFeeRate)).div(Ko);o=o.add(D.sub(O)),s=s.sub(s),a=a.add(O)}if(s.eq(me))break}}else{let u=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);u===null&&(r=!0);for(let d=0;d<u.length;d+=1){let h=new Ln.default(u[d].price).mul(new Ln.default(u[d].quantity)).div(new Ln.default(1e9)),_=h.mul(new Ln.default(e.takerFeeRate)).div(Ko),C=h.add(_);if(s.gt(h))o=o.add(new Ln.default(u[d].quantity)),s=s.sub(C),a=a.add(_);else{let D=new Ln.default(u[d].quantity).div(new Ln.default(e.lotSize)),O=C.div(D),B=s.div(O);o=o.add(B.muln(e.lotSize)),s=s.sub(B.mul(O)),a=a.add(B.div(D).mul(_))}if(s.eq(me))break}}return{poolAddress:e.poolID,estimatedAmountIn:c.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 nf.TransactionBlock,c=await this.getAccountCap(t),u;if(c===""){let X=this.createAccountCap(t.senderAddress,t.sdkOptions,a),Y=X[0];a=X[1],u=Y}else u=a.pure(c);let d=await t.getOwnerCoinAssets(t.senderAddress),_=fn.buildCoinForAmount(a,d,BigInt(o),n,!1)?.targetCoin,D=fn.buildCoinForAmount(a,d,BigInt(o),i,!1)?.targetCoin,O=[n,i],B=[a.pure(e),u,a.pure(o),a.pure(0),a.pure(r),_,D,a.pure(At)];a.moveCall({target:`${s.published_at}::${M_}::swap`,arguments:B,typeArguments:O});let{simulationAccount:j}=t.sdkOptions,R=(await t.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:j.address})).events?.filter(X=>Le(X.type).name==="DeepbookSwapEvent");if(R.length===0)return null;let K=R[0].parsedJson;return{poolAddress:K.pool,estimatedAmountIn:K.amount_in,estimatedAmountOut:K.amount_out,aToB:K.atob}}},c0=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 ue(`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=[],c=[];if(s!==void 0&&a.push(...s),a.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`})).data.forEach(h=>{let _=h.parsedJson;_&&a.push({poolAddress:_.pool_id,tickSpacing:_.tick_spacing,coinTypeA:Le(_.coin_type_a).full_address,coinTypeB:Le(_.coin_type_b).full_address})}),this.updateCache(o,a,St)}catch(d){console.log("getPoolImmutables",d)}let u=t.length>0;for(let d=0;d<a.length;d+=1){let h=a[d];u&&!t.includes(h.poolAddress)||!u&&(d<e||d>=e+n)||c.push(h)}return c}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 ue(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let a=Tu(s);i.push(a);let c=`${a.poolAddress}_getPoolObject`;this.updateCache(c,a,St)}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`,c=await this._sdk.fullClient.queryEventsByPage({MoveEventType:a},t);r.hasNextPage=c.hasNextPage,r.nextCursor=c.nextCursor,c.data.forEach(u=>{let d=u.parsedJson;if(d){let h={poolAddress:d.pool_id,tickSpacing:d.tick_spacing,coinTypeA:Le(d.coin_type_a).full_address,coinTypeB:Le(d.coin_type_b).full_address};i.push(h)}})}catch(a){console.log("getPoolImmutables",a)}return r.data=i,o&&this.updateCache(`${n}_getPoolImmutables`,i,St),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 ue(`getPoolWithPages error code: ${r.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=Tu(r);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,St)}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 ue(`getPool error code: ${r.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=Tu(r);return this.updateCache(n,o),o}async creatPoolsTransactionPayload(t){for(let n of t)if(pf((0,gu.normalizeSuiAddress)(n.coinTypeA),(0,gu.normalizeSuiAddress)(n.coinTypeB))){let i=n.coinTypeB;n.coinTypeB=n.coinTypeA,n.coinTypeA=i}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(pf((0,gu.normalizeSuiAddress)(t.coinTypeA),(0,gu.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=Eu(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(c=>{let u=c.parsedJson;if(c.type)switch(Le(c.type).full_address){case`${e}::config::InitConfigEvent`:a.global_config_id=u.global_config_id,a.admin_cap_id=u.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=u.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:a.global_vault_id=u.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:a.partners_id=u.partners_id;break;default:break}}),this.updateCache(n,a,St)),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,St),r}async creatPool(t){let e=new Gs.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=lt(i),o=r.global_config_id,s=r.pools_id;return t.forEach(a=>{let c=[e.object(o),e.object(s),e.pure(a.tick_spacing.toString()),e.pure(a.initialize_sqrt_price),e.pure(a.uri),e.object(At)];e.moveCall({target:`${n.published_at}::${Ws}::create_pool`,typeArguments:[a.coinTypeA,a.coinTypeB],arguments:c})}),e}async creatPoolAndAddLiquidity(t){if(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new Gs.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=lt(i),o=r.global_config_id,s=r.pools_id,a=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),c=fn.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,a,!1),u=fn.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,a,!1),d=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),c.targetCoin,u.targetCoin,e.pure(mi(BigInt(t.tick_lower)).toString()),e.pure(mi(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(At)];return e.moveCall({target:`${n.published_at}::${xr}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:d}),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 Gs.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Pr}::fetch_ticks`,arguments:s,typeArguments:r}),!cn(n.address))throw new ue("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 ue(`getTicks error code: ${a.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return a.events?.forEach(c=>{Le(c.type).name==="FetchTicksResultEvent"&&c.parsedJson.ticks.forEach(u=>{i.push(s0(u))})}),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 Gs.TransactionBlock,c=[a.object(t.pool_id),a.pure(r,"u64"),a.pure(o.toString(),"u64")];if(a.moveCall({target:`${e.published_at}::${Pr}::fetch_positions`,arguments:c,typeArguments:s}),!cn(n.address))throw new ue("this config simulationAccount is not set right","InvalidSimulateAccount");let u=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:n.address});if(u.error!=null)throw new ue(`fetch position reward error code: ${u.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let d=[];if(u?.events?.forEach(h=>{Le(h.type).name==="FetchPositionsEvent"&&h.parsedJson.positions.forEach(_=>{let C=Bf(_);d.push(C)})}),i.push(...d),d.length<o)break;r=[d[d.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=>{Le(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 ue(`getTicksByRpc error code: ${i.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let r=Au(i);r!=null&&e.push(r)}return e}async getTickDataByIndex(t,e){let n={type:"u64",value:mi(BigInt(F_(e).toString())).toString()},i=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:n});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new ue(`get tick by index: ${e} error: ${i.error}`,"InvalidTickIndex");return Au(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 ue(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return Au(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 ue(`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 ue(`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 ue(`get coin by object id: ${a.data.objectId} error: ${a.error}`,"InvalidParnterRefFeeFields");let c={coinAddress:a.data.content.fields.name,coinObjectId:a.data.objectId,balance:BigInt(a.data.content.fields.value)};o.push(c)}),o}async claimPartnerRefFeePayload(t,e,n){let i=new Gs.TransactionBlock,{clmm_pool:r}=this.sdk.sdkOptions,{global_config_id:o}=lt(r),s=[n],a=[i.object(o),i.object(t),i.object(e)];return i.moveCall({target:`${r.published_at}::${E_}::claim_ref_fee`,arguments:a,typeArguments:s}),i}updateCache(t,e,n=Js){let i=this._cache[t];i?(i.overdueTime=Di(n),i.value=e):i=new Zo(e,Di(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]}},C_=It(Ee()),Wo=require("@mysten/sui.js/transactions"),X2=require("@mysten/sui.js/utils"),u0=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(Le(o.data.type).full_address===this.buildPositionType()){let a=Cu(o),c=`${a.pos_object_id}_getPositionList`;this.updateCache(c,a,St),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=Cu(i),this.updateCache(e,n,St)}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=Cu(r);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,St)}),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=rr(n.data).value.fields.value;return Bf(r)}catch(n){console.log(n);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new Wo.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(lt(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId)];r.moveCall({target:`${n.published_at}::${Pr}::fetch_position_fees`,arguments:d,typeArguments:u})}if(!cn(i.address))throw new ue("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 ue(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(c=>Le(c.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let c=0;c<s.length;c+=1){let{parsedJson:u}=s[c],d={feeOwedA:new C_.default(u.fee_owned_a),feeOwedB:new C_.default(u.fee_owned_b),position_id:u.position_id};a.push(d)}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(!cn(this._sdk.senderAddress))throw new ue("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}=Xs(t);if(t=t,t.fix_amount_a&&i||!t.fix_amount_a&&r)return await fn.buildAddLiquidityFixTokenForGas(this._sdk,n,t,e)}return fn.buildAddLiquidityFixToken(this._sdk,n,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:n}=this._sdk.sdkOptions;if(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let i=mi(BigInt(t.tick_lower)).toString(),r=mi(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new Wo.TransactionBlock,a=!(0,X2.isValidSuiObjectId)(t.pos_id),c=BigInt(t.max_amount_a),u=BigInt(t.max_amount_b),d=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),h=fn.buildCoinForAmount(s,d,c,t.coinTypeA,!1),_=fn.buildCoinForAmount(s,d,u,t.coinTypeB,!1);return a?s.moveCall({target:`${e.published_at}::${xr}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(lt(n).global_config_id),s.object(t.pool_id),s.pure(i),s.pure(r),h.targetCoin,_.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(At)]}):(s=fn.createCollectRewarderAndFeeParams(this._sdk,s,t,d,h.remainCoins,_.remainCoins),s.moveCall({target:`${e.published_at}::${xr}::add_liquidity`,typeArguments:o,arguments:[s.object(lt(n).global_config_id),s.object(t.pool_id),s.object(t.pos_id),h.targetCoin,_.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(At)]})),s}async removeLiquidityTransactionPayload(t){if(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i="remove_liquidity",r=new Wo.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);r=fn.createCollectRewarderAndFeeParams(this._sdk,r,t,s);let a=[r.object(lt(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(At)];return r.moveCall({target:`${n.published_at}::${Ws}::${i}`,typeArguments:o,arguments:a}),r}async closePositionTransactionPayload(t){if(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new Wo.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return i=fn.createCollectRewarderAndFeeParams(this._sdk,i,t,o),i.moveCall({target:`${n.published_at}::${Ws}::close_position`,typeArguments:r,arguments:[i.object(lt(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(At)]}),i}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new Wo.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=mi(BigInt(t.tick_lower)).toString(),s=mi(BigInt(t.tick_upper)).toString(),a=[i.pure(lt(e).global_config_id),i.pure(t.pool_id),i.pure(o),i.pure(s)];return i.moveCall({target:`${n.published_at}::${Ws}::open_position`,typeArguments:r,arguments:a}),i}async collectFeeTransactionPayload(t){if(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),n=new Wo.TransactionBlock,i=fn.buildCoinForAmount(n,e,BigInt(0),t.coinTypeA,!1),r=fn.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(lt(r).global_config_id),e.object(t.pool_id),e.object(t.pos_id),n,i];return e.moveCall({target:`${o.published_at}::${xr}::collect_fee`,typeArguments:s,arguments:a}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!cn(this._sdk.senderAddress))throw new ue("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(Le(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=Js){let i=this._cache[t];i?(i.overdueTime=Di(n),i.value=e):i=new Zo(e,Di(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]}},vt=It(Ee()),rf=require("@mysten/sui.js/transactions"),Z2=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[me,me,me]}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 vt.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 vt.default(i)))return n;let r=e.div(new vt.default(1e3)).sub(new vt.default(i)).add(new vt.default(15)),o=n.rewarder_infos;for(let s=0;s<o.length;s+=1){let a=o[s],c=Te.checkMulDivFloor(r,new vt.default(a.emissions_per_second),new vt.default(n.liquidity),128);this.growthGlobal[s]=new vt.default(a.growth_global).add(new vt.default(c))}return n}async posRewardersAmount(t,e,n){let i=Date.parse(new Date().toString()),r=await this.updatePoolRewarder(t,new vt.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),c=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(r,o,a,c)}async poolRewardersAmount(t,e){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(e,new vt.default(n)),r=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(i.ticks_handle,r),s=[me,me,me];for(let a=0;a<r.length;a+=1){let c=await this.posRewardersAmountInternal(i,r[a],o[0][a],o[1][a]);for(let u=0;u<3;u+=1)s[u]=s[u].add(c[u].amount_owed)}return s}posRewardersAmountInternal(t,e,n,i){let r=e.tick_lower_index,o=e.tick_upper_index,s=a0(t,n,i,r,o,this.growthGlobal),a=[],c=[];if(s.length>0){let u=Te.subUnderflowU128(s[0],new vt.default(e.reward_growth_inside_0));u.gt(new vt.default("3402823669209384634633745948738404"))&&(u=gi);let d=Te.checkMulShiftRight(new vt.default(e.liquidity),u,64,128);a.push(s[0]),c.push({amount_owed:new vt.default(e.reward_amount_owed_0).add(d),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let u=Te.subUnderflowU128(s[1],new vt.default(e.reward_growth_inside_1));u.gt(new vt.default("3402823669209384634633745948738404"))&&(u=gi);let d=Te.checkMulShiftRight(new vt.default(e.liquidity),u,64,128);a.push(s[1]),c.push({amount_owed:new vt.default(e.reward_amount_owed_1).add(d),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let u=Te.subUnderflowU128(s[2],new vt.default(e.reward_growth_inside_2));u.gt(new vt.default("3402823669209384634633745948738404"))&&(u=gi);let d=Te.checkMulShiftRight(new vt.default(e.liquidity),u,64,128);a.push(s[2]),c.push({amount_owed:new vt.default(e.reward_amount_owed_2).add(d),coin_address:t.rewarder_infos[2].coinAddress})}return c}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 rf.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(lt(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId)];r.moveCall({target:`${n.published_at}::${Pr}::fetch_position_fees`,arguments:d,typeArguments:u})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address})).events?.filter(c=>Le(c.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let c=0;c<s.length;c+=1){let{parsedJson:u}=s[c],d={feeOwedA:new vt.default(u.fee_owned_a),feeOwedB:new vt.default(u.fee_owned_b),position_id:u.position_id};a.push(d)}return a}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new rf.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(lt(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId),r.object(At)];r.moveCall({target:`${n.published_at}::${Pr}::fetch_position_rewards`,arguments:d,typeArguments:u})}if(!cn(i.address))throw new ue(`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 ue(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(c=>Le(c.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new ue("valueData.length !== params.pools.length");let a=[];for(let c=0;c<s.length;c+=1){let u={poolAddress:t[c].poolAddress,positionId:t[c].positionId,rewarderAmountOwed:[]};for(let d=0;d<t[c].rewarderInfo.length;d+=1)u.rewarderAmountOwed.push({amount_owed:new vt.default(s[c].parsedJson.data[d]),coin_address:t[c].rewarderInfo[d].coinAddress});a.push(u)}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=[me,me,me];if(o!=null)for(let a of o)for(let c=0;c<a.rewarderAmountOwed.length;c+=1)s[c]=s[c].add(a.rewarderAmountOwed[c].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(!cn(this._sdk.senderAddress))throw new ue("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),n=new rf.TransactionBlock;return n=fn.createCollectRewarderAndFeeParams(this._sdk,n,t,e),n}createCollectRewarderPaylod(t,e,n){let{clmm_pool:i,integrate:r}=this.sdk.sdkOptions,o=lt(i),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((a,c)=>{e&&e.moveCall({target:`${r.published_at}::${xr}::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[c],e.object(At)]})}),e}},hi=It(Ee()),yu=rd(),J2=require("@mysten/sui.js/transactions");function bu(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var l0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new yu.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}=bu(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 yu.GraphVertex(r.base),s=this.graph.getVertexByKey(r.quote)??new yu.GraphVertex(r.quote);this.graph.addEdge(new yu.GraphEdge(o,s));let a=this._coinAddressMap.get(r.base),c=this._coinAddressMap.get(r.quote);if(a!=null&&c!=null){let u=bu(r.base,r.quote).pair;this.poolAddressMap.set(u,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=bu(t,e).pair,r=this.poolAddressMap.get(i);if(r!=null){for(let[a,c]of r.entries())if(c===n)return a*100}let o=bu(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[a,c]of s.entries())if(c===n)return a*100}return 0}async price(t,e,n,i,r,o,s){let a=this.tokenInfo(t),c=this.tokenInfo(e);if(a===void 0||c===void 0)throw new ue("From/To coin is undefined","InvalidCoin");let u=this.graph.getVertexByKey(a.address),d=this.graph.getVertexByKey(c.address),h=this.graph.findAllPath(u,d),_=Array.from(h);if(_.length===0)throw new ue("No find valid path in coin graph","NotFoundPath");let C=[];for(let G=0;G<_.length;G+=1){let W=_[G];if(W.length>3)continue;let I=[],N=[],l=[],f=[];for(let w=0;w<W.length-1;w+=1){let k=W[w].value.toString(),g=W[w+1].value.toString(),m=this.getPoolAddressMapAndDirection(k,g),b=m?.addressMap,y=m?.direction;b!=null&&y!=null&&(N.push(y),I.push(k),I.push(g),b.forEach(p=>{w===0?l.push(p):f.push(p)}))}for(let w of l)if(f.length>0)for(let k of f){let g={stepNums:2,poolAB:w,poolBC:k,a2b:N[0],b2c:N[1],amount:n,byAmountIn:i,coinTypeA:I[0],coinTypeB:I[1],coinTypeC:I[3]};C.push(g)}else{let k={stepNums:1,poolAB:w,poolBC:void 0,a2b:N[0],b2c:void 0,amount:n,byAmountIn:i,coinTypeA:I[0],coinTypeB:I[1],coinTypeC:void 0};C.push(k)}}let D=C.filter(G=>G.stepNums===1),O=C.filter(G=>G.stepNums!==1),B=[];try{B=await this.getPoolWithTVL()}catch{B=[]}if(B.length>0){let G=new Map(B.map(W=>[W.poolAddress,W]));O.sort((W,I)=>{let N=0,l=0;if(G.has(W.poolAB)&&G.has(W.poolBC)){let f=G.get(W.poolAB),w=G.get(W.poolBC);N=Math.min(f.tvl,w.tvl)}if(G.has(I.poolAB)&&G.has(I.poolBC)){let f=G.get(I.poolAB),w=G.get(I.poolBC);l=Math.min(f.tvl,w.tvl)}return l-N})}if(C=[...D,...O],C.length===0){if(s!=null){let G=await this.sdk.Swap.preSwapWithMultiPool(s),W={amountIn:new hi.default(G.estimatedAmountIn),amountOut:new hi.default(G.estimatedAmountOut),poolAddress:[G.poolAddress],a2b:[G.aToB],rawAmountLimit:i?[G.estimatedAmountOut]:[G.estimatedAmountIn],isExceed:G.isExceed,coinType:[t,e]},I={paths:[W],partner:o,priceSlippagePoint:r};return{amountIn:new hi.default(G.estimatedAmountIn),amountOut:new hi.default(G.estimatedAmountOut),paths:[W],a2b:G.aToB,b2c:void 0,byAmountIn:i,isExceed:G.isExceed,targetSqrtPrice:[G.estimatedEndSqrtPrice],currentSqrtPrice:[G.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:I}}throw new ue("No parameters available for service downgrade","NoDowngradeNeedParams")}let j=await this.preRouterSwapA2B2C(C.slice(0,16));if(j==null){if(s!=null){let W=await this.sdk.Swap.preSwapWithMultiPool(s),I={amountIn:new hi.default(W.estimatedAmountIn),amountOut:new hi.default(W.estimatedAmountOut),poolAddress:[W.poolAddress],a2b:[W.aToB],rawAmountLimit:i?[W.estimatedAmountOut]:[W.estimatedAmountIn],isExceed:W.isExceed,coinType:[t,e]},N={paths:[I],partner:o,priceSlippagePoint:r};return{amountIn:new hi.default(W.estimatedAmountIn),amountOut:new hi.default(W.estimatedAmountOut),paths:[I],a2b:W.aToB,b2c:void 0,byAmountIn:i,isExceed:W.isExceed,targetSqrtPrice:[W.estimatedEndSqrtPrice],currentSqrtPrice:[W.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:N}}return{amountIn:me,amountOut:me,paths:[],a2b:!1,b2c:!1,byAmountIn:i,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let M=j.index,R=C[M].poolBC!=null?[C[M].poolAB,C[M].poolBC]:[C[M].poolAB],K=i?[j.amountMedium,j.amountOut]:[j.amountIn,j.amountMedium],X=[];X.push(C[M].a2b),j.stepNum>1&&X.push(C[M].b2c);let Y=[];Y.push(C[M].coinTypeA),Y.push(C[M].coinTypeB),j.stepNum>1&&Y.push(C[M].coinTypeC);let oe={amountIn:j.amountIn,amountOut:j.amountOut,poolAddress:R,a2b:X,rawAmountLimit:K,isExceed:j.isExceed,coinType:Y},$={paths:[oe],partner:o,priceSlippagePoint:r};return{amountIn:j.amountIn,amountOut:j.amountOut,paths:[oe],a2b:C[M].a2b,b2c:j.stepNum>1?C[M].b2c:void 0,byAmountIn:i,isExceed:j.isExceed,targetSqrtPrice:j.targetSqrtPrice,currentSqrtPrice:j.currentSqrtPrice,coinTypeA:C[M].coinTypeA,coinTypeB:C[M].coinTypeB,coinTypeC:j.stepNum>1?C[M].coinTypeC:void 0,createTxParams:$}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new J2.TransactionBlock;for(let h of t)if(h.stepNums>1){let _=[i.object(h.poolAB),i.object(h.poolBC),i.pure(h.a2b),i.pure(h.b2c),i.pure(h.byAmountIn),i.pure(h.amount.toString())],C=[];h.a2b?C.push(h.coinTypeA,h.coinTypeB):C.push(h.coinTypeB,h.coinTypeA),h.b2c?C.push(h.coinTypeB,h.coinTypeC):C.push(h.coinTypeC,h.coinTypeB),i.moveCall({target:`${e.published_at}::${Xo}::calculate_router_swap_result`,typeArguments:C,arguments:_})}else{let _=[i.pure(h.poolAB),i.pure(h.a2b),i.pure(h.byAmountIn),i.pure(h.amount.toString())],C=h.a2b?[h.coinTypeA,h.coinTypeB]:[h.coinTypeB,h.coinTypeA];i.moveCall({target:`${e.published_at}::${D_}::get_expect_swap_result`,arguments:_,typeArguments:C})}if(!cn(n.address))throw new ue("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(h=>Le(h.type).name==="CalculatedRouterSwapResultEvent"||Le(h.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?me:Or,a=0;for(let h=0;h<o.length;h+=1)if(!o[h].parsedJson.data.is_exceed)if(t[0].byAmountIn){let _=new hi.default(o[h].parsedJson.data.amount_out);_.gt(s)&&(a=h,s=_)}else{let _=t[h].stepNums>1?new hi.default(o[h].parsedJson.data.amount_in):new hi.default(o[h].parsedJson.data.amount_in).add(new hi.default(o[h].parsedJson.data.fee_amount));_.lt(s)&&(a=h,s=_)}let c=[],u=[];return t[a].stepNums>1?(u.push(o[a].parsedJson.data.target_sqrt_price_ab,o[a].parsedJson.data.target_sqrt_price_cd),c.push(o[a].parsedJson.data.current_sqrt_price_ab,o[a].parsedJson.data.current_sqrt_price_cd)):(u.push(o[a].parsedJson.data.after_sqrt_price),c.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:u,currentSqrtPrice:c,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 ue(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let i;try{i=await n.json()}catch{throw new ue(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(i.code!==200)throw new ue(`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}},Ho=It(Ee()),Jn=It(ro()),A_=require("@mysten/sui.js/transactions"),Y2="amm_swap",Q2="Pool",d0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=Ot(0);return t.forEach(n=>{let i=n.basePaths.length;if(i>0){let r=n.basePaths[0],o=r.label==="Cetus"?new Jn.default(r.feeRate).div(10**6):new Jn.default(r.feeRate).div(10**9),s=Ot(r.inputAmount).div(10**r.fromDecimal).mul(o);if(e=e.add(s),i>1){let a=n.basePaths[1],c=r.direction?r.currentPrice:new Jn.default(1).div(r.currentPrice),u=a.direction?a.currentPrice:new Jn.default(1).div(a.currentPrice),d=a.label==="Cetus"?new Jn.default(a.feeRate).div(10**6):new Jn.default(a.feeRate).div(10**9),_=Ot(a.outputAmount).div(10**a.toDecimal).mul(d).div(c.mul(u));e=e.add(_)}}}),e.toString()}calculateSwapPriceImpact(t){let e=Ot(0);return t.forEach(n=>{let i=n.basePaths.length;if(i===1){let r=n.basePaths[0],o=Ot(r.outputAmount).div(10**r.toDecimal),s=Ot(r.inputAmount).div(10**r.fromDecimal),a=o.div(s),c=r.direction?new Jn.default(r.currentPrice):new Jn.default(1).div(r.currentPrice);e=e.add(this.calculateSingleImpact(a,c))}if(i===2){let r=n.basePaths[0],o=n.basePaths[1],s=r.direction?new Jn.default(r.currentPrice):new Jn.default(1).div(r.currentPrice),a=o.direction?new Jn.default(o.currentPrice):new Jn.default(1).div(o.currentPrice),c=s.mul(a),u=new Jn.default(o.outputAmount).div(10**o.toDecimal),d=new Jn.default(r.inputAmount).div(10**r.fromDecimal),h=u.div(d);e=e.add(this.calculateSingleImpact(h,c))}}),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 A_.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];for(let u=0;u<t.poolAddresses.length;u+=1){let d=[i.pure(t.poolAddresses[u]),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];i.moveCall({target:`${e.published_at}::${Pr}::calculate_swap_result`,arguments:d,typeArguments:r})}if(!cn(n.address))throw new ue("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 ue(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(u=>Le(u.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new ue("valueData.length !== params.pools.length","ParamsLengthNotEqual");let a=t.byAmountIn?me:Or,c=0;for(let u=0;u<s.length;u+=1)if(!s[u].parsedJson.data.is_exceed)if(t.byAmountIn){let d=new Ho.default(s[u].parsedJson.data.amount_out);d.gt(a)&&(c=u,a=d)}else{let d=new Ho.default(s[u].parsedJson.data.amount_out);d.lt(a)&&(c=u,a=d)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[c],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[c].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new A_.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}::${Pr}::calculate_swap_result`,arguments:o,typeArguments:r}),!cn(n.address))throw new ue("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 ue(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let a=s.events?.filter(c=>Le(c.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 Ho.default(e.amount_in).add(new Ho.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 Ho.default(n.amount_in).add(new Ho.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=wf(e),i;t.a2b?i=t.swapTicks.sort((h,_)=>_.index-h.index):i=t.swapTicks.sort((h,_)=>h.index-_.index);let r=U_(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=Gi.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 c=ft.sqrtPriceX64ToPrice(n.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),u=ft.sqrtPriceX64ToPrice(r.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),d=Math.abs(c-u)/c*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:d}}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}=Xs(t);if(t.a2b&&i||!t.a2b&&r)return await fn.buildSwapTransactionForGas(this._sdk,t,n,e)}return fn.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}=Xs(t);if(t.a2b&&i||!t.a2b&&r)return await fn.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,n,e)}return fn.buildSwapTransactionWithoutTransferCoins(this.sdk,t,n)}},eI=Wd(),S_=require("@mysten/sui.js/transactions"),tI=require("@mysten/sui.js/utils"),f0=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(zi(s)===zi(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 c=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(c){let u={id:c.id,name:c.name,symbol:c.symbol,official_symbol:c.symbol,coingecko_id:"",decimals:c.decimals,project_url:"",logo_url:c.iconUrl,address:o};e[o]=u,this.updateCache(s,u,St)}}}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,c=0,u=[];if(i===void 0)throw Error("please config token ofsdkOptions");let d=lt(i);for(;;){let h=new S_.TransactionBlock;h.moveCall({target:`${i.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[h.pure(d.coin_registry_id),h.pure(t),h.pure(c),h.pure(a)]:[h.pure(d.coin_registry_id),h.pure(c),h.pure(a)]});let _=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:h,sender:n.address}),C=[];if(_.events?.forEach(D=>{Le(D.type).full_address===`${i.published_at}::coin_list::FetchCoinListEvent`&&D.parsedJson.full_list.value_list.forEach(B=>{C.push(this.transformData(B,!1))})}),u=[...u,...C],C.length<a)break;c=u.length}return u}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,c=0,u=t.length>0;if(i===void 0)throw Error("please config token ofsdkOptions");let d=lt(i);for(;;){let h=new S_.TransactionBlock;if(h.moveCall({target:`${i.published_at}::lp_list::${u?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:u?[h.pure(d.pool_registry_id),h.pure(t),h.pure(c),h.pure(a)]:[h.pure(d.pool_registry_id),h.pure(c),h.pure(a)]}),!cn(n.address))throw new ue("this config simulationAccount is not set right","InvalidSimulateAccount");let _=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:h,sender:n.address}),C=[];if(_.events?.forEach(D=>{Le(D.type).full_address===`${i.published_at}::lp_list::FetchPoolListEvent`&&D.parsedJson.full_list.value_list.forEach(B=>{C.push(this.transformData(B,!0))})}),s=[...s,...C],C.length<a)break;c=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=Eu(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(c=>{let u=Le(c.type);if(c.transactionModule==="coin_list")switch(u.name){case"InitListEvent":a.coin_list_owner=c.parsedJson.list_id;break;case"InitRegistryEvent":a.coin_registry_id=c.parsedJson.registry_id;break;default:break}else if(c.transactionModule==="lp_list")switch(u.name){case"InitListEvent<address>":a.pool_list_owner=c.parsedJson.list_id;break;case"InitRegistryEvent<address>":a.pool_registry_id=c.parsedJson.registry_id;break;default:break}}),a.coin_registry_id.length>0&&this.updateCache(n,a,St),a}transformData(t,e){let n={...t};if(e)try{n.coin_a_address=Le(n.coin_a_address).full_address,n.coin_b_address=Le(n.coin_b_address).full_address}catch{}else n.address=Le(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(eI.Base64.decode(s)))}catch{}o==="pyth_id"&&(s=(0,tI.normalizeSuiObjectId)(s)),n[o]=s}delete n.extensions}return n}updateCache(t,e,n=Js){let i=this._cache[t];i?(i.overdueTime=Di(n),i.value=e):i=new Zo(e,Di(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]}},$i=It(Ee()),of=It(ro()),I_=__(),h0=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"?ft.sqrtPriceX64ToPrice(t,o,s):new of.default(t.toString()).div(new of.default(10).pow(new of.default(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 $i.default(r.current_sqrt_price.toString()),afterSqrtPrice:r.label==="Cetus"?new $i.default(r.after_sqrt_price.toString()):me,fromDecimal:r.from_decimal,toDecimal:r.to_decimal,currentPrice:this.calculatePrice(new $i.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,c=!1,u=!1,d=[]){let h=null,_="v2",C={},D=this.sdk.sdkOptions.aggregatorUrl;if(d.length>0){let O=new URL(D);D=`${O.protocol}//${O.hostname}/router_with_lp_changes`,C={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:n,by_amount_in:i,order_split:c,external_router:u,sender_address:"None",request_id:encodeURIComponent((0,I_.v4)()),lp_changes:d})}}else D=`
|
|
6
|
-
${D}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(n)}&by_amount_in=${encodeURIComponent(i)}&order_split=${encodeURIComponent(c)}&external_router=${encodeURIComponent(u)}&sender_address=''&request_id=${encodeURIComponent((0,I_.v4)())}
|
|
7
|
-
`;if(h=await this.fetchAndParseData(D,C),h?.isTimeout||h==null){let O=await this.sdk.Router.price(t,e,new $i.default(n),i,r,o,a),B=[];for(let M of O.paths){let R=[];if(M.poolAddress.length>1){let X=this.sdk.Router.tokenInfo(M.coinType[0]).decimals,Y=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,oe=M.a2b[0]?ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[0]),X,Y):ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[0]),Y,X),$={direction:M.a2b[0],label:"Cetus",poolAddress:M.poolAddress[0],fromCoin:M.coinType[0],toCoin:M.coinType[1],feeRate:this.sdk.Router.getFeeRate(M.coinType[0],M.coinType[1],M.poolAddress[0]),outputAmount:O.byAmountIn?M.rawAmountLimit[0].toString():M.rawAmountLimit[1].toString(),inputAmount:M.amountIn.toString(),currentSqrtPrice:O.currentSqrtPrice[0],currentPrice:oe,fromDecimal:X,toDecimal:Y},ne=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,G=this.sdk.Router.tokenInfo(M.coinType[2]).decimals,W=M.a2b[1]?ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[1]),ne,G):ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[1]),G,ne),I={direction:M.a2b[1],label:"Cetus",poolAddress:M.poolAddress[1],fromCoin:M.coinType[1],toCoin:M.coinType[2],feeRate:this.sdk.Router.getFeeRate(M.coinType[1],M.coinType[2],M.poolAddress[1]),outputAmount:M.amountOut.toString(),inputAmount:O.byAmountIn?M.rawAmountLimit[0].toString():M.rawAmountLimit[1].toString(),currentSqrtPrice:O.currentSqrtPrice[1],currentPrice:W,fromDecimal:ne,toDecimal:G};R.push($,I)}else{let X=this.sdk.Router.tokenInfo(M.coinType[0]).decimals,Y=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,oe=M.a2b[0]?ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[0]),X,Y):ft.sqrtPriceX64ToPrice(new $i.default(O.currentSqrtPrice[0]),Y,X),$={direction:M.a2b[0],label:"Cetus",poolAddress:M.poolAddress[0],fromCoin:M.coinType[0],toCoin:M.coinType[1],feeRate:this.sdk.Router.getFeeRate(M.coinType[0],M.coinType[1],M.poolAddress[0]),outputAmount:M.amountOut.toString(),inputAmount:M.amountIn.toString(),currentSqrtPrice:O.currentSqrtPrice[0],currentPrice:oe,fromDecimal:X,toDecimal:Y};R.push($)}let K={percent:Number(M.amountIn)/Number(O.amountIn)*100,inputAmount:Number(M.amountIn.toString()),outputAmount:Number(M.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:R};B.push(K)}let j={isExceed:O.isExceed,isTimeout:!0,inputAmount:Number(O.amountIn.toString()),outputAmount:Number(O.amountOut.toString()),fromCoin:O.coinTypeA,toCoin:O.coinTypeC!=null?O.coinTypeC:O.coinTypeB,byAmountIn:O.byAmountIn,splitPaths:B};_="v1",h=j}return{result:h,version:_}}},sf=Wd(),af=require("@mysten/sui.js/utils"),p0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=lt(this.sdk.sdkOptions.cetus_config),n=`${e}_getCoinConfigs`,i=this.getCache(n),r=i?[...i,...t]:t;this.updateCache(n,r,St)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:n}=lt(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 c of s)if(zi(a)===zi(c.address)){e[a]=c;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let a=`${s}_metadata`,c=this.getCache(a);if(c!==void 0)e[s]=c;else{let u=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(u){let d={id:u.id,pyth_id:"",name:u.name,symbol:u.symbol,official_symbol:u.symbol,coingecko_id:"",decimals:u.decimals,project_url:"",logo_url:u.iconUrl,address:s};e[s]=d,this.updateCache(a,d,St)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:n}=lt(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new ue(`when getCoinConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildCoinConfig(u,e);this.updateCache(`${n}_${d.address}_getCoinConfig`,d,St),c.push({...d})}),this.updateCache(i,c,St),c}async getCoinConfig(t,e=!1,n=!0){let{coin_list_handle:i}=lt(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:W_(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new ue(`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,St),a}buildCoinConfig(t,e=!0){let n=rr(t);n=n.value.fields;let i={...n};return i.id=ao(t),i.address=Le(n.coin_type.fields.name).full_address,n.pyth_id&&(i.pyth_id=(0,af.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}=lt(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new ue(`when getClmmPoolsConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildClmmPoolConfig(u,e);this.updateCache(`${d.pool_address}_getClmmPoolConfig`,d,St),c.push({...d})}),this.updateCache(i,c,St),c}async getClmmPoolConfig(t,e=!1,n=!0){let{clmm_pools_handle:i}=lt(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,St),a}buildClmmPoolConfig(t,e=!0){let n=rr(t);n=n.value.fields;let i={...n};return i.id=ao(t),i.pool_address=(0,af.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}=lt(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new ue(`when getCoinConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildLaunchpadPoolConfig(u,e);this.updateCache(`${d.pool_address}_getLaunchpadPoolConfig`,d,St),c.push({...d})}),this.updateCache(i,c,St),c}async getLaunchpadPoolConfig(t,e=!1,n=!0){let{launchpad_pools_handle:i}=lt(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,St),a}buildLaunchpadPoolConfig(t,e=!0){let n=rr(t);n=n.value.fields;let i={...n};i.id=ao(t),i.pool_address=(0,af.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(sf.Base64.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=sf.Base64.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(sf.Base64.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=Eu(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 c of s.data)switch(Le(c.type).name){case"InitCoinListEvent":a.coin_list_id=c.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":a.launchpad_pools_id=c.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":a.clmm_pools_id=c.parsedJson.pools_id;break;case"InitConfigEvent":a.global_config_id=c.parsedJson.global_config_id,a.admin_cap_id=c.parsedJson.admin_cap_id;break;default:break}return a=await this.getCetusConfigHandle(a),a.clmm_pools_id.length>0&&this.updateCache(n,a,St),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 ue(`when getCetusConfigHandle get objects error: ${i.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let r=rr(i),o=n0(i);switch(Le(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=Js){let i=this._cache[t];i?(i.overdueTime=Di(n),i.value=e):i=new Zo(e,Di(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}}},nI=require("@mysten/sui.js/transactions"),iI=require("@mysten/sui.js/client"),rI=require("@mysten/sui.js/bcs"),oI=zd(),m0=class extends iI.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(c=>{let{type:u,value:d}=c;return u==="object"?nI.Inputs.SharedObjectRef({objectId:d,initialSharedVersion:0,mutable:!0}):d}),transactions:t.blockData.transactions}},o=rI.bcs.TransactionKind.serialize(r,{maxSize:131072}).toBytes(),s=(0,oI.toB64)(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(i){console.log("devInspectTransactionBlock error",i)}}},g0=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new m0({url:t.fullRpcUrl}),this._swap=new d0(this),this._pool=new c0(this),this._position=new u0(this),this._rewarder=new Z2(this),this._router=new l0(this),this._router_v2=new h0(this),this._token=new f0(this),this._config=new p0(this),Af(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(c=>{BigInt(c.balance)>0&&i.push({coinAddress:Le(c.coinType).source_address,coinObjectId:c.coinObjectId,balance:BigInt(c.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=St){let i=this._cache[t];i?(i.overdueTime=Di(n),i.value=e):i=new Zo(e,Di(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]}},sI=g0});var Ww=Ue((Bh,Mh)=>{"use strict";(function(t,e){typeof Bh=="object"&&typeof Mh<"u"?Mh.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(Bh,function(){"use strict";var t=Math.imul,e=Math.clz32;function n($){"@babel/helpers - typeof";return n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(ne){return typeof ne}:function(ne){return ne&&typeof Symbol=="function"&&ne.constructor===Symbol&&ne!==Symbol.prototype?"symbol":typeof ne},n($)}function i($,ne){if(!($ instanceof ne))throw new TypeError("Cannot call a class as a function")}function r($,ne){for(var G,W=0;W<ne.length;W++)G=ne[W],G.enumerable=G.enumerable||!1,G.configurable=!0,"value"in G&&(G.writable=!0),Object.defineProperty($,G.key,G)}function o($,ne,G){return ne&&r($.prototype,ne),G&&r($,G),Object.defineProperty($,"prototype",{writable:!1}),$}function s($,ne){if(typeof ne!="function"&&ne!==null)throw new TypeError("Super expression must either be null or a function");$.prototype=Object.create(ne&&ne.prototype,{constructor:{value:$,writable:!0,configurable:!0}}),Object.defineProperty($,"prototype",{writable:!1}),ne&&c($,ne)}function a($){return a=Object.setPrototypeOf?Object.getPrototypeOf:function(ne){return ne.__proto__||Object.getPrototypeOf(ne)},a($)}function c($,ne){return c=Object.setPrototypeOf||function(G,W){return G.__proto__=W,G},c($,ne)}function u(){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 d(){return d=u()?Reflect.construct:function($,ne,G){var W=[null];W.push.apply(W,ne);var I=Function.bind.apply($,W),N=new I;return G&&c(N,G.prototype),N},d.apply(null,arguments)}function h($){return Function.toString.call($).indexOf("[native code]")!==-1}function _($){var ne=typeof Map=="function"?new Map:void 0;return _=function(G){function W(){return d(G,arguments,a(this).constructor)}if(G===null||!h(G))return G;if(typeof G!="function")throw new TypeError("Super expression must either be null or a function");if(typeof ne<"u"){if(ne.has(G))return ne.get(G);ne.set(G,W)}return W.prototype=Object.create(G.prototype,{constructor:{value:W,enumerable:!1,writable:!0,configurable:!0}}),c(W,G)},_($)}function C($){if($===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return $}function D($,ne){if(ne&&(typeof ne=="object"||typeof ne=="function"))return ne;if(ne!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return C($)}function O($){var ne=u();return function(){var G,W=a($);if(ne){var I=a(this).constructor;G=Reflect.construct(W,arguments,I)}else G=W.apply(this,arguments);return D(this,G)}}function B($,ne){return j($)||M($,ne)||R($,ne)||X()}function j($){if(Array.isArray($))return $}function M($,ne){var G=$==null?null:typeof Symbol<"u"&&$[Symbol.iterator]||$["@@iterator"];if(G!=null){var W,I,N=[],l=!0,f=!1;try{for(G=G.call($);!(l=(W=G.next()).done)&&(N.push(W.value),!(ne&&N.length===ne));l=!0);}catch(w){f=!0,I=w}finally{try{l||G.return==null||G.return()}finally{if(f)throw I}}return N}}function R($,ne){if($){if(typeof $=="string")return K($,ne);var G=Object.prototype.toString.call($).slice(8,-1);return G==="Object"&&$.constructor&&(G=$.constructor.name),G==="Map"||G==="Set"?Array.from($):G==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(G)?K($,ne):void 0}}function K($,ne){(ne==null||ne>$.length)&&(ne=$.length);for(var G=0,W=Array(ne);G<ne;G++)W[G]=$[G];return W}function X(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
8
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Y($,ne){var G=typeof Symbol<"u"&&$[Symbol.iterator]||$["@@iterator"];if(!G){if(Array.isArray($)||(G=R($))||ne&&$&&typeof $.length=="number"){G&&($=G);var W=0,I=function(){};return{s:I,n:function(){return W>=$.length?{done:!0}:{done:!1,value:$[W++]}},e:function(w){throw w},f:I}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
9
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var N,l=!0,f=!1;return{s:function(){G=G.call($)},n:function(){var w=G.next();return l=w.done,w},e:function(w){f=!0,N=w},f:function(){try{l||G.return==null||G.return()}finally{if(f)throw N}}}}var oe=function($){var ne=Math.abs,G=Math.max,W=Math.floor;function I(l,f){var w;if(i(this,I),w=N.call(this,l),w.sign=f,Object.setPrototypeOf(C(w),I.prototype),l>I.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return w}s(I,$);var N=O(I);return o(I,[{key:"toDebugString",value:function(){var l,f=["BigInt["],w=Y(this);try{for(w.s();!(l=w.n()).done;){var k=l.value;f.push((k&&(k>>>0).toString(16))+", ")}}catch(g){w.e(g)}finally{w.f()}return f.push("]"),f.join("")}},{key:"toString",value:function(){var l=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>l||36<l)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":l&l-1?I.__toStringGeneric(this,l,!1):I.__toStringBasePowerOfTwo(this,l)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var l=new I(this.length,this.sign),f=0;f<this.length;f++)l[f]=this[f];return l}},{key:"__trim",value:function(){for(var l=this.length,f=this[l-1];f===0;)l--,f=this[l-1],this.pop();return l===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var l=0;l<this.length;l++)this[l]=0}},{key:"__clzmsd",value:function(){return I.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(l,f,w){w>this.length&&(w=this.length);for(var k=32767&l,g=l>>>15,m=0,b=f,y=0;y<w;y++){var p=this.__digit(y),T=32767&p,F=p>>>15,z=I.__imul(T,k),Q=I.__imul(T,g),H=I.__imul(F,k),ae=I.__imul(F,g),fe=b+z+m;m=fe>>>30,fe&=1073741823,fe+=((32767&Q)<<15)+((32767&H)<<15),m+=fe>>>30,b=ae+(Q>>>15)+(H>>>15),this.__setDigit(y,1073741823&fe)}if(m!==0||b!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(l,f,w){for(var k,g=0,m=0;m<w;m++)k=this.__halfDigit(f+m)+l.__halfDigit(m)+g,g=k>>>15,this.__setHalfDigit(f+m,32767&k);return g}},{key:"__inplaceSub",value:function(l,f,w){var k=0;if(1&f){f>>=1;for(var g=this.__digit(f),m=32767&g,b=0;b<w-1>>>1;b++){var y=l.__digit(b),p=(g>>>15)-(32767&y)-k;k=1&p>>>15,this.__setDigit(f+b,(32767&p)<<15|32767&m),g=this.__digit(f+b+1),m=(32767&g)-(y>>>15)-k,k=1&m>>>15}var T=l.__digit(b),F=(g>>>15)-(32767&T)-k;if(k=1&F>>>15,this.__setDigit(f+b,(32767&F)<<15|32767&m),f+b+1>=this.length)throw new RangeError("out of bounds");!(1&w)&&(g=this.__digit(f+b+1),m=(32767&g)-(T>>>15)-k,k=1&m>>>15,this.__setDigit(f+l.length,1073709056&g|32767&m))}else{f>>=1;for(var z=0;z<l.length-1;z++){var Q=this.__digit(f+z),H=l.__digit(z),ae=(32767&Q)-(32767&H)-k;k=1&ae>>>15;var fe=(Q>>>15)-(H>>>15)-k;k=1&fe>>>15,this.__setDigit(f+z,(32767&fe)<<15|32767&ae)}var Ce=this.__digit(f+z),ke=l.__digit(z),Fe=(32767&Ce)-(32767&ke)-k;k=1&Fe>>>15;var kt=0;!(1&w)&&(kt=(Ce>>>15)-(ke>>>15)-k,k=1&kt>>>15),this.__setDigit(f+z,(32767&kt)<<15|32767&Fe)}return k}},{key:"__inplaceRightShift",value:function(l){if(l!==0){for(var f,w=this.__digit(0)>>>l,k=this.length-1,g=0;g<k;g++)f=this.__digit(g+1),this.__setDigit(g,1073741823&f<<30-l|w),w=f>>>l;this.__setDigit(k,w)}}},{key:"__digit",value:function(l){return this[l]}},{key:"__unsignedDigit",value:function(l){return this[l]>>>0}},{key:"__setDigit",value:function(l,f){this[l]=0|f}},{key:"__setDigitGrow",value:function(l,f){this[l]=0|f}},{key:"__halfDigitLength",value:function(){var l=this.length;return 32767>=this.__unsignedDigit(l-1)?2*l-1:2*l}},{key:"__halfDigit",value:function(l){return 32767&this[l>>>1]>>>15*(1&l)}},{key:"__setHalfDigit",value:function(l,f){var w=l>>>1,k=this.__digit(w),g=1&l?32767&k|f<<15:1073709056&k|32767&f;this.__setDigit(w,g)}}],[{key:"BigInt",value:function(l){var f=Number.isFinite;if(typeof l=="number"){if(l===0)return I.__zero();if(I.__isOneDigitInt(l))return 0>l?I.__oneDigit(-l,!0):I.__oneDigit(l,!1);if(!f(l)||W(l)!==l)throw new RangeError("The number "+l+" cannot be converted to BigInt because it is not an integer");return I.__fromDouble(l)}if(typeof l=="string"){var w=I.__fromString(l);if(w===null)throw new SyntaxError("Cannot convert "+l+" to a BigInt");return w}if(typeof l=="boolean")return l===!0?I.__oneDigit(1,!1):I.__zero();if(n(l)==="object"){if(l.constructor===I)return l;var k=I.__toPrimitive(l);return I.BigInt(k)}throw new TypeError("Cannot convert "+l+" to a BigInt")}},{key:"toNumber",value:function(l){var f=l.length;if(f===0)return 0;if(f===1){var w=l.__unsignedDigit(0);return l.sign?-w:w}var k=l.__digit(f-1),g=I.__clz30(k),m=30*f-g;if(1024<m)return l.sign?-1/0:1/0;var b=m-1,y=k,p=f-1,T=g+3,F=T===32?0:y<<T;F>>>=12;var z=T-12,Q=12<=T?0:y<<20+T,H=20+T;for(0<z&&0<p&&(p--,y=l.__digit(p),F|=y>>>30-z,Q=y<<z+2,H=z+2);0<H&&0<p;)p--,y=l.__digit(p),Q|=30<=H?y<<H-30:y>>>30-H,H-=30;var ae=I.__decideRounding(l,H,p,y);if((ae===1||ae===0&&(1&Q)==1)&&(Q=Q+1>>>0,Q===0&&(F++,F>>>20!=0&&(F=0,b++,1023<b))))return l.sign?-1/0:1/0;var fe=l.sign?-2147483648:0;return b=b+1023<<20,I.__kBitConversionInts[1]=fe|b|F,I.__kBitConversionInts[0]=Q,I.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(l){if(l.length===0)return l;var f=l.__copy();return f.sign=!l.sign,f}},{key:"bitwiseNot",value:function(l){return l.sign?I.__absoluteSubOne(l).__trim():I.__absoluteAddOne(l,!0)}},{key:"exponentiate",value:function(l,f){if(f.sign)throw new RangeError("Exponent must be positive");if(f.length===0)return I.__oneDigit(1,!1);if(l.length===0)return l;if(l.length===1&&l.__digit(0)===1)return l.sign&&!(1&f.__digit(0))?I.unaryMinus(l):l;if(1<f.length)throw new RangeError("BigInt too big");var w=f.__unsignedDigit(0);if(w===1)return l;if(w>=I.__kMaxLengthBits)throw new RangeError("BigInt too big");if(l.length===1&&l.__digit(0)===2){var k=1+(0|w/30),g=l.sign&&(1&w)!=0,m=new I(k,g);m.__initializeDigits();var b=1<<w%30;return m.__setDigit(k-1,b),m}var y=null,p=l;for(1&w&&(y=l),w>>=1;w!==0;w>>=1)p=I.multiply(p,p),1&w&&(y===null?y=p:y=I.multiply(y,p));return y}},{key:"multiply",value:function(l,f){if(l.length===0)return l;if(f.length===0)return f;var w=l.length+f.length;30<=l.__clzmsd()+f.__clzmsd()&&w--;var k=new I(w,l.sign!==f.sign);k.__initializeDigits();for(var g=0;g<l.length;g++)I.__multiplyAccumulate(f,l.__digit(g),k,g);return k.__trim()}},{key:"divide",value:function(l,f){if(f.length===0)throw new RangeError("Division by zero");if(0>I.__absoluteCompare(l,f))return I.__zero();var w,k=l.sign!==f.sign,g=f.__unsignedDigit(0);if(f.length===1&&32767>=g){if(g===1)return k===l.sign?l:I.unaryMinus(l);w=I.__absoluteDivSmall(l,g,null)}else w=I.__absoluteDivLarge(l,f,!0,!1);return w.sign=k,w.__trim()}},{key:"remainder",value:function(f,w){if(w.length===0)throw new RangeError("Division by zero");if(0>I.__absoluteCompare(f,w))return f;var k=w.__unsignedDigit(0);if(w.length===1&&32767>=k){if(k===1)return I.__zero();var g=I.__absoluteModSmall(f,k);return g===0?I.__zero():I.__oneDigit(g,f.sign)}var m=I.__absoluteDivLarge(f,w,!1,!0);return m.sign=f.sign,m.__trim()}},{key:"add",value:function(l,f){var w=l.sign;return w===f.sign?I.__absoluteAdd(l,f,w):0<=I.__absoluteCompare(l,f)?I.__absoluteSub(l,f,w):I.__absoluteSub(f,l,!w)}},{key:"subtract",value:function(l,f){var w=l.sign;return w===f.sign?0<=I.__absoluteCompare(l,f)?I.__absoluteSub(l,f,w):I.__absoluteSub(f,l,!w):I.__absoluteAdd(l,f,w)}},{key:"leftShift",value:function(l,f){return f.length===0||l.length===0?l:f.sign?I.__rightShiftByAbsolute(l,f):I.__leftShiftByAbsolute(l,f)}},{key:"signedRightShift",value:function(l,f){return f.length===0||l.length===0?l:f.sign?I.__leftShiftByAbsolute(l,f):I.__rightShiftByAbsolute(l,f)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(l,f){return 0>I.__compareToBigInt(l,f)}},{key:"lessThanOrEqual",value:function(l,f){return 0>=I.__compareToBigInt(l,f)}},{key:"greaterThan",value:function(l,f){return 0<I.__compareToBigInt(l,f)}},{key:"greaterThanOrEqual",value:function(l,f){return 0<=I.__compareToBigInt(l,f)}},{key:"equal",value:function(l,f){if(l.sign!==f.sign||l.length!==f.length)return!1;for(var w=0;w<l.length;w++)if(l.__digit(w)!==f.__digit(w))return!1;return!0}},{key:"notEqual",value:function(l,f){return!I.equal(l,f)}},{key:"bitwiseAnd",value:function(l,f){if(!l.sign&&!f.sign)return I.__absoluteAnd(l,f).__trim();if(l.sign&&f.sign){var w=G(l.length,f.length)+1,k=I.__absoluteSubOne(l,w),g=I.__absoluteSubOne(f);return k=I.__absoluteOr(k,g,k),I.__absoluteAddOne(k,!0,k).__trim()}if(l.sign){var m=[f,l];l=m[0],f=m[1]}return I.__absoluteAndNot(l,I.__absoluteSubOne(f)).__trim()}},{key:"bitwiseXor",value:function(l,f){if(!l.sign&&!f.sign)return I.__absoluteXor(l,f).__trim();if(l.sign&&f.sign){var w=G(l.length,f.length),k=I.__absoluteSubOne(l,w),g=I.__absoluteSubOne(f);return I.__absoluteXor(k,g,k).__trim()}var m=G(l.length,f.length)+1;if(l.sign){var b=[f,l];l=b[0],f=b[1]}var y=I.__absoluteSubOne(f,m);return y=I.__absoluteXor(y,l,y),I.__absoluteAddOne(y,!0,y).__trim()}},{key:"bitwiseOr",value:function(l,f){var w=G(l.length,f.length);if(!l.sign&&!f.sign)return I.__absoluteOr(l,f).__trim();if(l.sign&&f.sign){var k=I.__absoluteSubOne(l,w),g=I.__absoluteSubOne(f);return k=I.__absoluteAnd(k,g,k),I.__absoluteAddOne(k,!0,k).__trim()}if(l.sign){var m=[f,l];l=m[0],f=m[1]}var b=I.__absoluteSubOne(f,w);return b=I.__absoluteAndNot(b,l,b),I.__absoluteAddOne(b,!0,b).__trim()}},{key:"asIntN",value:function(l,f){if(f.length===0)return f;if(l=W(l),0>l)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(l===0)return I.__zero();if(l>=I.__kMaxLengthBits)return f;var w=0|(l+29)/30;if(f.length<w)return f;var k=f.__unsignedDigit(w-1),g=1<<(l-1)%30;if(f.length===w&&k<g)return f;if((k&g)!==g)return I.__truncateToNBits(l,f);if(!f.sign)return I.__truncateAndSubFromPowerOfTwo(l,f,!0);if(!(k&g-1)){for(var m=w-2;0<=m;m--)if(f.__digit(m)!==0)return I.__truncateAndSubFromPowerOfTwo(l,f,!1);return f.length===w&&k===g?f:I.__truncateToNBits(l,f)}return I.__truncateAndSubFromPowerOfTwo(l,f,!1)}},{key:"asUintN",value:function(l,f){if(f.length===0)return f;if(l=W(l),0>l)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(l===0)return I.__zero();if(f.sign){if(l>I.__kMaxLengthBits)throw new RangeError("BigInt too big");return I.__truncateAndSubFromPowerOfTwo(l,f,!1)}if(l>=I.__kMaxLengthBits)return f;var w=0|(l+29)/30;if(f.length<w)return f;var k=l%30;if(f.length==w){if(k===0)return f;var g=f.__digit(w-1);if(!(g>>>k))return f}return I.__truncateToNBits(l,f)}},{key:"ADD",value:function(l,f){if(l=I.__toPrimitive(l),f=I.__toPrimitive(f),typeof l=="string")return typeof f!="string"&&(f=f.toString()),l+f;if(typeof f=="string")return l.toString()+f;if(l=I.__toNumeric(l),f=I.__toNumeric(f),I.__isBigInt(l)&&I.__isBigInt(f))return I.add(l,f);if(typeof l=="number"&&typeof f=="number")return l+f;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(l,f){return I.__compare(l,f,0)}},{key:"LE",value:function(l,f){return I.__compare(l,f,1)}},{key:"GT",value:function(l,f){return I.__compare(l,f,2)}},{key:"GE",value:function(l,f){return I.__compare(l,f,3)}},{key:"EQ",value:function(l,f){for(;;){if(I.__isBigInt(l))return I.__isBigInt(f)?I.equal(l,f):I.EQ(f,l);if(typeof l=="number"){if(I.__isBigInt(f))return I.__equalToNumber(f,l);if(n(f)!=="object")return l==f;f=I.__toPrimitive(f)}else if(typeof l=="string"){if(I.__isBigInt(f))return l=I.__fromString(l),l!==null&&I.equal(l,f);if(n(f)!=="object")return l==f;f=I.__toPrimitive(f)}else if(typeof l=="boolean"){if(I.__isBigInt(f))return I.__equalToNumber(f,+l);if(n(f)!=="object")return l==f;f=I.__toPrimitive(f)}else if(n(l)==="symbol"){if(I.__isBigInt(f))return!1;if(n(f)!=="object")return l==f;f=I.__toPrimitive(f)}else if(n(l)==="object"){if(n(f)==="object"&&f.constructor!==I)return l==f;l=I.__toPrimitive(l)}else return l==f}}},{key:"NE",value:function(l,f){return!I.EQ(l,f)}},{key:"DataViewGetBigInt64",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return I.asIntN(64,I.DataViewGetBigUint64(l,f,w))}},{key:"DataViewGetBigUint64",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0&&arguments[2],k=w?[4,0]:[0,4],g=B(k,2),m=g[0],b=g[1],y=l.getUint32(f+m,w),p=l.getUint32(f+b,w),T=new I(3,!1);return T.__setDigit(0,1073741823&p),T.__setDigit(1,(268435455&y)<<2|p>>>30),T.__setDigit(2,y>>>28),T.__trim()}},{key:"DataViewSetBigInt64",value:function(l,f,w){var k=3<arguments.length&&arguments[3]!==void 0&&arguments[3];I.DataViewSetBigUint64(l,f,w,k)}},{key:"DataViewSetBigUint64",value:function(l,f,w){var k=3<arguments.length&&arguments[3]!==void 0&&arguments[3];w=I.asUintN(64,w);var g=0,m=0;if(0<w.length&&(m=w.__digit(0),1<w.length)){var b=w.__digit(1);m|=b<<30,g=b>>>2,2<w.length&&(g|=w.__digit(2)<<28)}var y=k?[4,0]:[0,4],p=B(y,2),T=p[0],F=p[1];l.setUint32(f+T,g,k),l.setUint32(f+F,m,k)}},{key:"__zero",value:function(){return new I(0,!1)}},{key:"__oneDigit",value:function(l,f){var w=new I(1,f);return w.__setDigit(0,l),w}},{key:"__decideRounding",value:function(l,f,w,k){if(0<f)return-1;var g;if(0>f)g=-f-1;else{if(w===0)return-1;w--,k=l.__digit(w),g=29}var m=1<<g;if(!(k&m))return-1;if(m-=1,(k&m)!=0)return 1;for(;0<w;)if(w--,l.__digit(w)!==0)return 1;return 0}},{key:"__fromDouble",value:function(l){I.__kBitConversionDouble[0]=l;var f,w=2047&I.__kBitConversionInts[1]>>>20,k=w-1023,g=(0|k/30)+1,m=new I(g,0>l),b=1048575&I.__kBitConversionInts[1]|1048576,y=I.__kBitConversionInts[0],p=20,T=k%30,F=0;if(T<p){var z=p-T;F=z+32,f=b>>>z,b=b<<32-z|y>>>z,y<<=32-z}else if(T===p)F=32,f=b,b=y,y=0;else{var Q=T-p;F=32-Q,f=b<<Q|y>>>32-Q,b=y<<Q,y=0}m.__setDigit(g-1,f);for(var H=g-2;0<=H;H--)0<F?(F-=30,f=b>>>2,b=b<<30|y>>>2,y<<=30):f=0,m.__setDigit(H,f);return m.__trim()}},{key:"__isWhitespace",value:function(l){return 13>=l&&9<=l||(159>=l?l==32:131071>=l?l==160||l==5760:196607>=l?(l&=131071,10>=l||l==40||l==41||l==47||l==95||l==4096):l==65279)}},{key:"__fromString",value:function(l){var f=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,w=0,k=l.length,g=0;if(g===k)return I.__zero();for(var m=l.charCodeAt(g);I.__isWhitespace(m);){if(++g===k)return I.__zero();m=l.charCodeAt(g)}if(m===43){if(++g===k)return null;m=l.charCodeAt(g),w=1}else if(m===45){if(++g===k)return null;m=l.charCodeAt(g),w=-1}if(f===0){if(f=10,m===48){if(++g===k)return I.__zero();if(m=l.charCodeAt(g),m===88||m===120){if(f=16,++g===k)return null;m=l.charCodeAt(g)}else if(m===79||m===111){if(f=8,++g===k)return null;m=l.charCodeAt(g)}else if(m===66||m===98){if(f=2,++g===k)return null;m=l.charCodeAt(g)}}}else if(f===16&&m===48){if(++g===k)return I.__zero();if(m=l.charCodeAt(g),m===88||m===120){if(++g===k)return null;m=l.charCodeAt(g)}}if(w!==0&&f!==10)return null;for(;m===48;){if(++g===k)return I.__zero();m=l.charCodeAt(g)}var b=k-g,y=I.__kMaxBitsPerChar[f],p=I.__kBitsPerCharTableMultiplier-1;if(b>1073741824/y)return null;var T=y*b+p>>>I.__kBitsPerCharTableShift,F=new I(0|(T+29)/30,!1),z=10>f?f:10,Q=10<f?f-10:0;if(f&f-1){F.__initializeDigits();var kt=!1,it=0;do{for(var Qe,ti=0,mt=1;;){if(Qe=void 0,m-48>>>0<z)Qe=m-48;else if((32|m)-97>>>0<Q)Qe=(32|m)-87;else{kt=!0;break}var gt=mt*f;if(1073741823<gt)break;if(mt=gt,ti=ti*f+Qe,it++,++g===k){kt=!0;break}m=l.charCodeAt(g)}p=30*I.__kBitsPerCharTableMultiplier-1;var Jr=0|(y*it+p>>>I.__kBitsPerCharTableShift)/30;F.__inplaceMultiplyAdd(mt,ti,Jr)}while(!kt)}else{y>>=I.__kBitsPerCharTableShift;var H=[],ae=[],fe=!1;do{for(var Ce,ke=0,Fe=0;;){if(Ce=void 0,m-48>>>0<z)Ce=m-48;else if((32|m)-97>>>0<Q)Ce=(32|m)-87;else{fe=!0;break}if(Fe+=y,ke=ke<<y|Ce,++g===k){fe=!0;break}if(m=l.charCodeAt(g),30<Fe+y)break}H.push(ke),ae.push(Fe)}while(!fe);I.__fillFromParts(F,H,ae)}if(g!==k){if(!I.__isWhitespace(m))return null;for(g++;g<k;g++)if(m=l.charCodeAt(g),!I.__isWhitespace(m))return null}return F.sign=w===-1,F.__trim()}},{key:"__fillFromParts",value:function(l,f,w){for(var k=0,g=0,m=0,b=f.length-1;0<=b;b--){var y=f[b],p=w[b];g|=y<<m,m+=p,m===30?(l.__setDigit(k++,g),m=0,g=0):30<m&&(l.__setDigit(k++,1073741823&g),m-=30,g=y>>>p-m)}if(g!==0){if(k>=l.length)throw new Error("implementation bug");l.__setDigit(k++,g)}for(;k<l.length;k++)l.__setDigit(k,0)}},{key:"__toStringBasePowerOfTwo",value:function(l,f){var w=l.length,k=f-1;k=(85&k>>>1)+(85&k),k=(51&k>>>2)+(51&k),k=(15&k>>>4)+(15&k);var g=k,m=f-1,b=l.__digit(w-1),y=I.__clz30(b),p=0|(30*w-y+g-1)/g;if(l.sign&&p++,268435456<p)throw new Error("string too long");for(var T=Array(p),F=p-1,z=0,Q=0,H=0;H<w-1;H++){var ae=l.__digit(H),fe=(z|ae<<Q)&m;T[F--]=I.__kConversionChars[fe];var Ce=g-Q;for(z=ae>>>Ce,Q=30-Ce;Q>=g;)T[F--]=I.__kConversionChars[z&m],z>>>=g,Q-=g}var ke=(z|b<<Q)&m;for(T[F--]=I.__kConversionChars[ke],z=b>>>g-Q;z!==0;)T[F--]=I.__kConversionChars[z&m],z>>>=g;if(l.sign&&(T[F--]="-"),F!==-1)throw new Error("implementation bug");return T.join("")}},{key:"__toStringGeneric",value:function(l,f,w){var k=l.length;if(k===0)return"";if(k===1){var g=l.__unsignedDigit(0).toString(f);return w===!1&&l.sign&&(g="-"+g),g}var m=30*k-I.__clz30(l.__digit(k-1)),b=I.__kMaxBitsPerChar[f],y=b-1,p=m*I.__kBitsPerCharTableMultiplier;p+=y-1,p=0|p/y;var T,F,z=p+1>>1,Q=I.exponentiate(I.__oneDigit(f,!1),I.__oneDigit(z,!1)),H=Q.__unsignedDigit(0);if(Q.length===1&&32767>=H){T=new I(l.length,!1),T.__initializeDigits();for(var ae,fe=0,Ce=2*l.length-1;0<=Ce;Ce--)ae=fe<<15|l.__halfDigit(Ce),T.__setHalfDigit(Ce,0|ae/H),fe=0|ae%H;F=fe.toString(f)}else{var ke=I.__absoluteDivLarge(l,Q,!0,!0);T=ke.quotient;var Fe=ke.remainder.__trim();F=I.__toStringGeneric(Fe,f,!0)}T.__trim();for(var kt=I.__toStringGeneric(T,f,!0);F.length<z;)F="0"+F;return w===!1&&l.sign&&(kt="-"+kt),kt+F}},{key:"__unequalSign",value:function(l){return l?-1:1}},{key:"__absoluteGreater",value:function(l){return l?-1:1}},{key:"__absoluteLess",value:function(l){return l?1:-1}},{key:"__compareToBigInt",value:function(l,f){var w=l.sign;if(w!==f.sign)return I.__unequalSign(w);var k=I.__absoluteCompare(l,f);return 0<k?I.__absoluteGreater(w):0>k?I.__absoluteLess(w):0}},{key:"__compareToNumber",value:function(l,f){if(I.__isOneDigitInt(f)){var w=l.sign,k=0>f;if(w!==k)return I.__unequalSign(w);if(l.length===0){if(k)throw new Error("implementation bug");return f===0?0:-1}if(1<l.length)return I.__absoluteGreater(w);var g=ne(f),m=l.__unsignedDigit(0);return m>g?I.__absoluteGreater(w):m<g?I.__absoluteLess(w):0}return I.__compareToDouble(l,f)}},{key:"__compareToDouble",value:function(l,f){if(f!==f)return f;if(f===1/0)return-1;if(f===-1/0)return 1;var w=l.sign;if(w!==0>f)return I.__unequalSign(w);if(f===0)throw new Error("implementation bug: should be handled elsewhere");if(l.length===0)return-1;I.__kBitConversionDouble[0]=f;var k=2047&I.__kBitConversionInts[1]>>>20;if(k==2047)throw new Error("implementation bug: handled elsewhere");var g=k-1023;if(0>g)return I.__absoluteGreater(w);var m=l.length,b=l.__digit(m-1),y=I.__clz30(b),p=30*m-y,T=g+1;if(p<T)return I.__absoluteLess(w);if(p>T)return I.__absoluteGreater(w);var F=1048576|1048575&I.__kBitConversionInts[1],z=I.__kBitConversionInts[0],Q=20,H=29-y;if(H!==(0|(p-1)%30))throw new Error("implementation bug");var ae,fe=0;if(H<Q){var Ce=Q-H;fe=Ce+32,ae=F>>>Ce,F=F<<32-Ce|z>>>Ce,z<<=32-Ce}else if(H===Q)fe=32,ae=F,F=z,z=0;else{var ke=H-Q;fe=32-ke,ae=F<<ke|z>>>32-ke,F=z<<ke,z=0}if(b>>>=0,ae>>>=0,b>ae)return I.__absoluteGreater(w);if(b<ae)return I.__absoluteLess(w);for(var Fe=m-2;0<=Fe;Fe--){0<fe?(fe-=30,ae=F>>>2,F=F<<30|z>>>2,z<<=30):ae=0;var kt=l.__unsignedDigit(Fe);if(kt>ae)return I.__absoluteGreater(w);if(kt<ae)return I.__absoluteLess(w)}if(F!==0||z!==0){if(fe===0)throw new Error("implementation bug");return I.__absoluteLess(w)}return 0}},{key:"__equalToNumber",value:function(l,f){return I.__isOneDigitInt(f)?f===0?l.length===0:l.length===1&&l.sign===0>f&&l.__unsignedDigit(0)===ne(f):I.__compareToDouble(l,f)===0}},{key:"__comparisonResultToBool",value:function(l,f){return f===0?0>l:f===1?0>=l:f===2?0<l:f===3?0<=l:void 0}},{key:"__compare",value:function(l,f,w){if(l=I.__toPrimitive(l),f=I.__toPrimitive(f),typeof l=="string"&&typeof f=="string")switch(w){case 0:return l<f;case 1:return l<=f;case 2:return l>f;case 3:return l>=f}if(I.__isBigInt(l)&&typeof f=="string")return f=I.__fromString(f),f!==null&&I.__comparisonResultToBool(I.__compareToBigInt(l,f),w);if(typeof l=="string"&&I.__isBigInt(f))return l=I.__fromString(l),l!==null&&I.__comparisonResultToBool(I.__compareToBigInt(l,f),w);if(l=I.__toNumeric(l),f=I.__toNumeric(f),I.__isBigInt(l)){if(I.__isBigInt(f))return I.__comparisonResultToBool(I.__compareToBigInt(l,f),w);if(typeof f!="number")throw new Error("implementation bug");return I.__comparisonResultToBool(I.__compareToNumber(l,f),w)}if(typeof l!="number")throw new Error("implementation bug");if(I.__isBigInt(f))return I.__comparisonResultToBool(I.__compareToNumber(f,l),2^w);if(typeof f!="number")throw new Error("implementation bug");return w===0?l<f:w===1?l<=f:w===2?l>f:w===3?l>=f:void 0}},{key:"__absoluteAdd",value:function(l,f,w){if(l.length<f.length)return I.__absoluteAdd(f,l,w);if(l.length===0)return l;if(f.length===0)return l.sign===w?l:I.unaryMinus(l);var k=l.length;(l.__clzmsd()===0||f.length===l.length&&f.__clzmsd()===0)&&k++;for(var g,m=new I(k,w),b=0,y=0;y<f.length;y++)g=l.__digit(y)+f.__digit(y)+b,b=g>>>30,m.__setDigit(y,1073741823&g);for(;y<l.length;y++){var p=l.__digit(y)+b;b=p>>>30,m.__setDigit(y,1073741823&p)}return y<m.length&&m.__setDigit(y,b),m.__trim()}},{key:"__absoluteSub",value:function(l,f,w){if(l.length===0)return l;if(f.length===0)return l.sign===w?l:I.unaryMinus(l);for(var k,g=new I(l.length,w),m=0,b=0;b<f.length;b++)k=l.__digit(b)-f.__digit(b)-m,m=1&k>>>30,g.__setDigit(b,1073741823&k);for(;b<l.length;b++){var y=l.__digit(b)-m;m=1&y>>>30,g.__setDigit(b,1073741823&y)}return g.__trim()}},{key:"__absoluteAddOne",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,k=l.length;w===null?w=new I(k,f):w.sign=f;for(var g,m=1,b=0;b<k;b++)g=l.__digit(b)+m,m=g>>>30,w.__setDigit(b,1073741823&g);return m!==0&&w.__setDigitGrow(k,1),w}},{key:"__absoluteSubOne",value:function(l,f){var w=l.length;f=f||w;for(var k,g=new I(f,!1),m=1,b=0;b<w;b++)k=l.__digit(b)-m,m=1&k>>>30,g.__setDigit(b,1073741823&k);if(m!==0)throw new Error("implementation bug");for(var y=w;y<f;y++)g.__setDigit(y,0);return g}},{key:"__absoluteAnd",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,k=l.length,g=f.length,m=g;if(k<g){m=k;var b=l,y=k;l=f,k=g,f=b,g=y}var p=m;w===null?w=new I(p,!1):p=w.length;for(var T=0;T<m;T++)w.__setDigit(T,l.__digit(T)&f.__digit(T));for(;T<p;T++)w.__setDigit(T,0);return w}},{key:"__absoluteAndNot",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,k=l.length,g=f.length,m=g;k<g&&(m=k);var b=k;w===null?w=new I(b,!1):b=w.length;for(var y=0;y<m;y++)w.__setDigit(y,l.__digit(y)&~f.__digit(y));for(;y<k;y++)w.__setDigit(y,l.__digit(y));for(;y<b;y++)w.__setDigit(y,0);return w}},{key:"__absoluteOr",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,k=l.length,g=f.length,m=g;if(k<g){m=k;var b=l,y=k;l=f,k=g,f=b,g=y}var p=k;w===null?w=new I(p,!1):p=w.length;for(var T=0;T<m;T++)w.__setDigit(T,l.__digit(T)|f.__digit(T));for(;T<k;T++)w.__setDigit(T,l.__digit(T));for(;T<p;T++)w.__setDigit(T,0);return w}},{key:"__absoluteXor",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,k=l.length,g=f.length,m=g;if(k<g){m=k;var b=l,y=k;l=f,k=g,f=b,g=y}var p=k;w===null?w=new I(p,!1):p=w.length;for(var T=0;T<m;T++)w.__setDigit(T,l.__digit(T)^f.__digit(T));for(;T<k;T++)w.__setDigit(T,l.__digit(T));for(;T<p;T++)w.__setDigit(T,0);return w}},{key:"__absoluteCompare",value:function(l,f){var w=l.length-f.length;if(w!=0)return w;for(var k=l.length-1;0<=k&&l.__digit(k)===f.__digit(k);)k--;return 0>k?0:l.__unsignedDigit(k)>f.__unsignedDigit(k)?1:-1}},{key:"__multiplyAccumulate",value:function(l,f,w,k){if(f!==0){for(var g=32767&f,m=f>>>15,b=0,y=0,p=0;p<l.length;p++,k++){var T=w.__digit(k),F=l.__digit(p),z=32767&F,Q=F>>>15,H=I.__imul(z,g),ae=I.__imul(z,m),fe=I.__imul(Q,g),Ce=I.__imul(Q,m);T+=y+H+b,b=T>>>30,T&=1073741823,T+=((32767&ae)<<15)+((32767&fe)<<15),b+=T>>>30,y=Ce+(ae>>>15)+(fe>>>15),w.__setDigit(k,1073741823&T)}for(;b!==0||y!==0;k++){var ke=w.__digit(k);ke+=b+y,y=0,b=ke>>>30,w.__setDigit(k,1073741823&ke)}}}},{key:"__internalMultiplyAdd",value:function(l,f,w,k,g){for(var m=w,b=0,y=0;y<k;y++){var p=l.__digit(y),T=I.__imul(32767&p,f),F=I.__imul(p>>>15,f),z=T+((32767&F)<<15)+b+m;m=z>>>30,b=F>>>15,g.__setDigit(y,1073741823&z)}if(g.length>k)for(g.__setDigit(k++,m+b);k<g.length;)g.__setDigit(k++,0);else if(m+b!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(l,f){var w=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;w===null&&(w=new I(l.length,!1));for(var k=0,g=2*l.length-1;0<=g;g-=2){var m=(k<<15|l.__halfDigit(g))>>>0,b=0|m/f;k=0|m%f,m=(k<<15|l.__halfDigit(g-1))>>>0;var y=0|m/f;k=0|m%f,w.__setDigit(g>>>1,b<<15|y)}return w}},{key:"__absoluteModSmall",value:function(l,f){for(var w,k=0,g=2*l.length-1;0<=g;g--)w=(k<<15|l.__halfDigit(g))>>>0,k=0|w%f;return k}},{key:"__absoluteDivLarge",value:function(l,f,w,k){var g=f.__halfDigitLength(),m=f.length,b=l.__halfDigitLength()-g,y=null;w&&(y=new I(b+2>>>1,!1),y.__initializeDigits());var p=new I(g+2>>>1,!1);p.__initializeDigits();var T=I.__clz15(f.__halfDigit(g-1));0<T&&(f=I.__specialLeftShift(f,T,0));for(var F=I.__specialLeftShift(l,T,1),z=f.__halfDigit(g-1),Q=0,H=b;0<=H;H--){var ae=32767,fe=F.__halfDigit(H+g);if(fe!==z){var Ce=(fe<<15|F.__halfDigit(H+g-1))>>>0;ae=0|Ce/z;for(var ke=0|Ce%z,Fe=f.__halfDigit(g-2),kt=F.__halfDigit(H+g-2);I.__imul(ae,Fe)>>>0>(ke<<16|kt)>>>0&&(ae--,ke+=z,!(32767<ke)););}I.__internalMultiplyAdd(f,ae,0,m,p);var it=F.__inplaceSub(p,H,g+1);it!==0&&(it=F.__inplaceAdd(f,H,g),F.__setHalfDigit(H+g,32767&F.__halfDigit(H+g)+it),ae--),w&&(1&H?Q=ae<<15:y.__setDigit(H>>>1,Q|ae))}if(k)return F.__inplaceRightShift(T),w?{quotient:y,remainder:F}:F;if(w)return y;throw new Error("unreachable")}},{key:"__clz15",value:function(l){return I.__clz30(l)-15}},{key:"__specialLeftShift",value:function(l,f,w){var k=l.length,g=new I(k+w,!1);if(f===0){for(var m=0;m<k;m++)g.__setDigit(m,l.__digit(m));return 0<w&&g.__setDigit(k,0),g}for(var b,y=0,p=0;p<k;p++)b=l.__digit(p),g.__setDigit(p,1073741823&b<<f|y),y=b>>>30-f;return 0<w&&g.__setDigit(k,y),g}},{key:"__leftShiftByAbsolute",value:function(l,f){var w=I.__toShiftAmount(f);if(0>w)throw new RangeError("BigInt too big");var k=0|w/30,g=w%30,m=l.length,b=g!==0&&l.__digit(m-1)>>>30-g!=0,y=m+k+(b?1:0),p=new I(y,l.sign);if(g===0){for(var T=0;T<k;T++)p.__setDigit(T,0);for(;T<y;T++)p.__setDigit(T,l.__digit(T-k))}else{for(var F=0,z=0;z<k;z++)p.__setDigit(z,0);for(var Q,H=0;H<m;H++)Q=l.__digit(H),p.__setDigit(H+k,1073741823&Q<<g|F),F=Q>>>30-g;if(b)p.__setDigit(m+k,F);else if(F!==0)throw new Error("implementation bug")}return p.__trim()}},{key:"__rightShiftByAbsolute",value:function(l,f){var w=l.length,k=l.sign,g=I.__toShiftAmount(f);if(0>g)return I.__rightShiftByMaximum(k);var m=0|g/30,b=g%30,y=w-m;if(0>=y)return I.__rightShiftByMaximum(k);var p=!1;if(k){if(l.__digit(m)&(1<<b)-1)p=!0;else for(var T=0;T<m;T++)if(l.__digit(T)!==0){p=!0;break}}if(p&&b===0){var F=l.__digit(w-1);!~F&&y++}var z=new I(y,k);if(b===0){z.__setDigit(y-1,0);for(var Q=m;Q<w;Q++)z.__setDigit(Q-m,l.__digit(Q))}else{for(var H,ae=l.__digit(m)>>>b,fe=w-m-1,Ce=0;Ce<fe;Ce++)H=l.__digit(Ce+m+1),z.__setDigit(Ce,1073741823&H<<30-b|ae),ae=H>>>b;z.__setDigit(fe,ae)}return p&&(z=I.__absoluteAddOne(z,!0,z)),z.__trim()}},{key:"__rightShiftByMaximum",value:function(l){return l?I.__oneDigit(1,!0):I.__zero()}},{key:"__toShiftAmount",value:function(l){if(1<l.length)return-1;var f=l.__unsignedDigit(0);return f>I.__kMaxLengthBits?-1:f}},{key:"__toPrimitive",value:function(l){var f=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(n(l)!=="object"||l.constructor===I)return l;if(typeof Symbol<"u"&&n(Symbol.toPrimitive)==="symbol"){var w=l[Symbol.toPrimitive];if(w){var k=w(f);if(n(k)!=="object")return k;throw new TypeError("Cannot convert object to primitive value")}}var g=l.valueOf;if(g){var m=g.call(l);if(n(m)!=="object")return m}var b=l.toString;if(b){var y=b.call(l);if(n(y)!=="object")return y}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(l){return I.__isBigInt(l)?l:+l}},{key:"__isBigInt",value:function(l){return n(l)==="object"&&l!==null&&l.constructor===I}},{key:"__truncateToNBits",value:function(l,f){for(var w=0|(l+29)/30,k=new I(w,f.sign),g=w-1,m=0;m<g;m++)k.__setDigit(m,f.__digit(m));var b=f.__digit(g);if(l%30!=0){var y=32-l%30;b=b<<y>>>y}return k.__setDigit(g,b),k.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(l,f,w){for(var k=Math.min,g,m=0|(l+29)/30,b=new I(m,w),y=0,p=m-1,T=0,F=k(p,f.length);y<F;y++)g=0-f.__digit(y)-T,T=1&g>>>30,b.__setDigit(y,1073741823&g);for(;y<p;y++)b.__setDigit(y,0|1073741823&-T);var z,Q=p<f.length?f.__digit(p):0,H=l%30;if(H===0)z=0-Q-T,z&=1073741823;else{var ae=32-H;Q=Q<<ae>>>ae;var fe=1<<32-ae;z=fe-Q-T,z&=fe-1}return b.__setDigit(p,z),b.__trim()}},{key:"__digitPow",value:function(l,f){for(var w=1;0<f;)1&f&&(w*=l),f>>>=1,l*=l;return w}},{key:"__isOneDigitInt",value:function(l){return(1073741823&l)===l}}]),I}(_(Array));return oe.__kMaxLength=33554432,oe.__kMaxLengthBits=oe.__kMaxLength<<5,oe.__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],oe.__kBitsPerCharTableShift=5,oe.__kBitsPerCharTableMultiplier=1<<oe.__kBitsPerCharTableShift,oe.__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"],oe.__kBitConversionBuffer=new ArrayBuffer(8),oe.__kBitConversionDouble=new Float64Array(oe.__kBitConversionBuffer),oe.__kBitConversionInts=new Int32Array(oe.__kBitConversionBuffer),oe.__clz30=e?function($){return e($)-2}:function($){var ne=Math.LN2,G=Math.log;return $===0?30:0|29-(0|G($>>>0)/ne)},oe.__imul=t||function($,ne){return 0|$*ne},oe})});var o4={};wp(o4,{AddressBookSDK:()=>xo,COIN_TYPE_ARG_REGEX:()=>sp,Coin:()=>Ka,CoinHelper:()=>Va,CreateHelper:()=>Io,DEV_API_URL:()=>Sv,DEV_SYNCING_URL:()=>Iv,ENV_CONFIGS:()=>Pv,Formatter:()=>_r,HexToUint8Array:()=>Pl,LOCAL_API_URL:()=>mp,LOCAL_SYNCING_URL:()=>gp,MAINNET_RPC_URL:()=>pp,MSafeAccount:()=>So,MSafeClient:()=>Ll,MSafeEnv:()=>Av,MSafeGlobals:()=>Xa,PREV_API_URL:()=>xv,PROD_API_URL:()=>Ov,SUI_COIN:()=>n4,SignatureVerifier:()=>cp,TESTNET_RPC_URL:()=>ql,Uint8ArrayToHex:()=>t4,addPrefix:()=>ap,getAllCoins:()=>r4,getMSafeConfig:()=>_p,getPublicKeyFromChain:()=>up,stringToBuffer:()=>Ol});module.exports=bp(o4);var er=require("@msafe/sui3-utils"),Io=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 er.MultiSigAccount(n).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,n){let i=er.PublicKeySerde.de(n);if(!(0,er.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=er.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,...er.PublicKeySerde.ser(i[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:n})}};var Ul=require("@msafe/sui3-utils");var vp=require("@msafe/sui3-utils"),xo=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let n=vp.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 fc=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 Oy=require("@msafe/sui3-utils"),Py=Pe(hc(),1);var xs=require("@mysten/sui.js/utils"),No=require("@mysten/sui.js/transactions"),fi=Pe(Ee(),1);var Hl=8192;function Xl(t){if(t.length<Hl)return btoa(String.fromCharCode(...t));let e="";for(var n=0;n<t.length;n+=Hl){let i=t.slice(n,n+Hl);e+=String.fromCharCode(...i)}return btoa(e)}var pk=require("@mysten/sui.js/keypairs/ed25519"),mk=require("@mysten/sui.js/keypairs/secp256k1"),Tr=Pe(Ee(),1),ln=Pe(Ee(),1);var Oo=9e15,kr=1e9,Zl="0123456789abcdef",mc="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",gc="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Jl={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Oo,maxE:Oo,crypto:!1},Up,tr,Ne=!0,wc="[DecimalError] ",vr=wc+"Invalid argument: ",$p=wc+"Precision limit exceeded",Gp=wc+"crypto unavailable",zp="[object Decimal]",Dn=Math.floor,mn=Math.pow,Yv=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Qv=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,e1=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Vp=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ai=1e7,Be=7,t1=9007199254740991,n1=mc.length-1,Yl=gc.length-1,re={toStringTag:zp};re.absoluteValue=re.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),Ae(t)};re.ceil=function(){return Ae(new this.constructor(this),this.e+1,2)};re.clampedTo=re.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(vr+e);return n=i.cmp(t),n<0?t:i.cmp(e)>0?e:new r(i)};re.comparedTo=re.cmp=function(t){var e,n,i,r,o=this,s=o.d,a=(t=new o.constructor(t)).d,c=o.s,u=t.s;if(!s||!a)return!c||!u?NaN:c!==u?c:s===a?0:!s^c<0?1:-1;if(!s[0]||!a[0])return s[0]?c:a[0]?-u:0;if(c!==u)return c;if(o.e!==t.e)return o.e>t.e^c<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]^c<0?1:-1;return i===r?0:i>r^c<0?1:-1};re.cosine=re.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())+Be,i.rounding=1,n=i1(i,Zp(i,n)),i.precision=t,i.rounding=e,Ae(tr==2||tr==3?n.neg():n,t,e,!0)):new i(1):new i(NaN)};re.cubeRoot=re.cbrt=function(){var t,e,n,i,r,o,s,a,c,u,d=this,h=d.constructor;if(!d.isFinite()||d.isZero())return new h(d);for(Ne=!1,o=d.s*mn(d.s*d,1/3),!o||Math.abs(o)==1/0?(n=Tn(d.d),t=d.e,(o=(t-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=mn(n,1/3),t=Dn((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 h(n),i.s=d.s):i=new h(o.toString()),s=(t=h.precision)+3;;)if(a=i,c=a.times(a).times(a),u=c.plus(d),i=wt(u.plus(d).times(a),u.plus(c),s+2,1),Tn(a.d).slice(0,s)===(n=Tn(i.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!r&&n=="4999"){if(!r&&(Ae(a,t+1,0),a.times(a).times(a).eq(d))){i=a;break}s+=4,r=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(Ae(i,t+1,1),e=!i.times(i).times(i).eq(d));break}return Ne=!0,Ae(i,t,h.rounding,e)};re.decimalPlaces=re.dp=function(){var t,e=this.d,n=NaN;if(e){if(t=e.length-1,n=(t-Dn(this.e/Be))*Be,t=e[t],t)for(;t%10==0;t/=10)n--;n<0&&(n=0)}return n};re.dividedBy=re.div=function(t){return wt(this,new this.constructor(t))};re.dividedToIntegerBy=re.divToInt=function(t){var e=this,n=e.constructor;return Ae(wt(e,new n(t),0,1,1),n.precision,n.rounding)};re.equals=re.eq=function(t){return this.cmp(t)===0};re.floor=function(){return Ae(new this.constructor(this),this.e+1,3)};re.greaterThan=re.gt=function(t){return this.cmp(t)>0};re.greaterThanOrEqualTo=re.gte=function(t){var e=this.cmp(t);return e==1||e===0};re.hyperbolicCosine=re.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/bc(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=Po(s,1,o.times(e),new s(1),!0);for(var c,u=t,d=new s(8);u--;)c=o.times(o),o=a.minus(c.times(d.minus(c.times(d))));return Ae(o,s.precision=n,s.rounding=i,!0)};re.hyperbolicSine=re.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=Po(o,2,r,r,!0);else{t=1.4*Math.sqrt(i),t=t>16?16:t|0,r=r.times(1/bc(5,t)),r=Po(o,2,r,r,!0);for(var s,a=new o(5),c=new o(16),u=new o(20);t--;)s=r.times(r),r=r.times(a.plus(s.times(c.times(s).plus(u))))}return o.precision=e,o.rounding=n,Ae(r,e,n,!0)};re.hyperbolicTangent=re.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,wt(n.sinh(),n.cosh(),i.precision=t,i.rounding=e)):new i(n.s)};re.inverseCosine=re.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()?Ci(n,r,o):new n(0):new n(NaN):e.isZero()?Ci(n,r+4,o).times(.5):(n.precision=r+6,n.rounding=1,e=e.asin(),t=Ci(n,r+4,o).times(.5),n.precision=r,n.rounding=o,t.minus(e))};re.inverseHyperbolicCosine=re.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,Ne=!1,n=n.times(n).minus(1).sqrt().plus(n),Ne=!0,i.precision=t,i.rounding=e,n.ln()):new i(n)};re.inverseHyperbolicSine=re.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,Ne=!1,n=n.times(n).plus(1).sqrt().plus(n),Ne=!0,i.precision=t,i.rounding=e,n.ln())};re.inverseHyperbolicTangent=re.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?Ae(new o(r),t,e,!0):(o.precision=n=i-r.e,r=wt(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)};re.inverseSine=re.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=Ci(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)))};re.inverseTangent=re.atan=function(){var t,e,n,i,r,o,s,a,c,u=this,d=u.constructor,h=d.precision,_=d.rounding;if(u.isFinite()){if(u.isZero())return new d(u);if(u.abs().eq(1)&&h+4<=Yl)return s=Ci(d,h+4,_).times(.25),s.s=u.s,s}else{if(!u.s)return new d(NaN);if(h+4<=Yl)return s=Ci(d,h+4,_).times(.5),s.s=u.s,s}for(d.precision=a=h+10,d.rounding=1,n=Math.min(28,a/Be+2|0),t=n;t;--t)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(Ne=!1,e=Math.ceil(a/Be),i=1,c=u.times(u),s=new d(u),r=u;t!==-1;)if(r=r.times(c),o=s.minus(r.div(i+=2)),r=r.times(c),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)),Ne=!0,Ae(s,d.precision=h,d.rounding=_,!0)};re.isFinite=function(){return!!this.d};re.isInteger=re.isInt=function(){return!!this.d&&Dn(this.e/Be)>this.d.length-2};re.isNaN=function(){return!this.s};re.isNegative=re.isNeg=function(){return this.s<0};re.isPositive=re.isPos=function(){return this.s>0};re.isZero=function(){return!!this.d&&this.d[0]===0};re.lessThan=re.lt=function(t){return this.cmp(t)<0};re.lessThanOrEqualTo=re.lte=function(t){return this.cmp(t)<1};re.logarithm=re.log=function(t){var e,n,i,r,o,s,a,c,u=this,d=u.constructor,h=d.precision,_=d.rounding,C=5;if(t==null)t=new d(10),e=!0;else{if(t=new d(t),n=t.d,t.s<0||!n||!n[0]||t.eq(1))return new d(NaN);e=t.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new d(n&&!n[0]?-1/0:u.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(Ne=!1,a=h+C,s=br(u,a),i=e?_c(d,a+10):br(t,a),c=wt(s,i,a,1),As(c.d,r=h,_))do if(a+=10,s=br(u,a),i=e?_c(d,a+10):br(t,a),c=wt(s,i,a,1),!o){+Tn(c.d).slice(r+1,r+15)+1==1e14&&(c=Ae(c,h+1,0));break}while(As(c.d,r+=10,_));return Ne=!0,Ae(c,h,_)};re.minus=re.sub=function(t){var e,n,i,r,o,s,a,c,u,d,h,_,C=this,D=C.constructor;if(t=new D(t),!C.d||!t.d)return!C.s||!t.s?t=new D(NaN):C.d?t.s=-t.s:t=new D(t.d||C.s!==t.s?C:NaN),t;if(C.s!=t.s)return t.s=-t.s,C.plus(t);if(u=C.d,_=t.d,a=D.precision,c=D.rounding,!u[0]||!_[0]){if(_[0])t.s=-t.s;else if(u[0])t=new D(C);else return new D(c===3?-0:0);return Ne?Ae(t,a,c):t}if(n=Dn(t.e/Be),d=Dn(C.e/Be),u=u.slice(),o=d-n,o){for(h=o<0,h?(e=u,o=-o,s=_.length):(e=_,n=d,s=u.length),i=Math.max(Math.ceil(a/Be),s)+2,o>i&&(o=i,e.length=1),e.reverse(),i=o;i--;)e.push(0);e.reverse()}else{for(i=u.length,s=_.length,h=i<s,h&&(s=i),i=0;i<s;i++)if(u[i]!=_[i]){h=u[i]<_[i];break}o=0}for(h&&(e=u,u=_,_=e,t.s=-t.s),s=u.length,i=_.length-s;i>0;--i)u[s++]=0;for(i=_.length;i>o;){if(u[--i]<_[i]){for(r=i;r&&u[--r]===0;)u[r]=Ai-1;--u[r],u[i]+=Ai}u[i]-=_[i]}for(;u[--s]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(t.d=u,t.e=yc(u,n),Ne?Ae(t,a,c):t):new D(c===3?-0:0)};re.modulo=re.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]?Ae(new i(n),i.precision,i.rounding):(Ne=!1,i.modulo==9?(e=wt(n,t.abs(),0,3,1),e.s*=t.s):e=wt(n,t,0,i.modulo,1),e=e.times(t),Ne=!0,n.minus(e))};re.naturalExponential=re.exp=function(){return Ql(this)};re.naturalLogarithm=re.ln=function(){return br(this)};re.negated=re.neg=function(){var t=new this.constructor(this);return t.s=-t.s,Ae(t)};re.plus=re.add=function(t){var e,n,i,r,o,s,a,c,u,d,h=this,_=h.constructor;if(t=new _(t),!h.d||!t.d)return!h.s||!t.s?t=new _(NaN):h.d||(t=new _(t.d||h.s===t.s?h:NaN)),t;if(h.s!=t.s)return t.s=-t.s,h.minus(t);if(u=h.d,d=t.d,a=_.precision,c=_.rounding,!u[0]||!d[0])return d[0]||(t=new _(h)),Ne?Ae(t,a,c):t;if(o=Dn(h.e/Be),i=Dn(t.e/Be),u=u.slice(),r=o-i,r){for(r<0?(n=u,r=-r,s=d.length):(n=d,i=o,s=u.length),o=Math.ceil(a/Be),s=o>s?o+1:s+1,r>s&&(r=s,n.length=1),n.reverse();r--;)n.push(0);n.reverse()}for(s=u.length,r=d.length,s-r<0&&(r=s,n=d,d=u,u=n),e=0;r;)e=(u[--r]=u[r]+d[r]+e)/Ai|0,u[r]%=Ai;for(e&&(u.unshift(e),++i),s=u.length;u[--s]==0;)u.pop();return t.d=u,t.e=yc(u,i),Ne?Ae(t,a,c):t};re.precision=re.sd=function(t){var e,n=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(vr+t);return n.d?(e=Kp(n.d),t&&n.e+1>e&&(e=n.e+1)):e=NaN,e};re.round=function(){var t=this,e=t.constructor;return Ae(new e(t),t.e+1,e.rounding)};re.sine=re.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())+Be,i.rounding=1,n=o1(i,Zp(i,n)),i.precision=t,i.rounding=e,Ae(tr>2?n.neg():n,t,e,!0)):new i(NaN)};re.squareRoot=re.sqrt=function(){var t,e,n,i,r,o,s=this,a=s.d,c=s.e,u=s.s,d=s.constructor;if(u!==1||!a||!a[0])return new d(!u||u<0&&(!a||a[0])?NaN:a?s:1/0);for(Ne=!1,u=Math.sqrt(+s),u==0||u==1/0?(e=Tn(a),(e.length+c)%2==0&&(e+="0"),u=Math.sqrt(e),c=Dn((c+1)/2)-(c<0||c%2),u==1/0?e="5e"+c:(e=u.toExponential(),e=e.slice(0,e.indexOf("e")+1)+c),i=new d(e)):i=new d(u.toString()),n=(c=d.precision)+3;;)if(o=i,i=o.plus(wt(s,o,n+2,1)).times(.5),Tn(o.d).slice(0,n)===(e=Tn(i.d)).slice(0,n))if(e=e.slice(n-3,n+1),e=="9999"||!r&&e=="4999"){if(!r&&(Ae(o,c+1,0),o.times(o).eq(s))){i=o;break}n+=4,r=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(Ae(i,c+1,1),t=!i.times(i).eq(s));break}return Ne=!0,Ae(i,c,d.rounding,t)};re.tangent=re.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=wt(n,new i(1).minus(n.times(n)).sqrt(),t+10,0),i.precision=t,i.rounding=e,Ae(tr==2||tr==4?n.neg():n,t,e,!0)):new i(NaN)};re.times=re.mul=function(t){var e,n,i,r,o,s,a,c,u,d=this,h=d.constructor,_=d.d,C=(t=new h(t)).d;if(t.s*=d.s,!_||!_[0]||!C||!C[0])return new h(!t.s||_&&!_[0]&&!C||C&&!C[0]&&!_?NaN:!_||!C?t.s/0:t.s*0);for(n=Dn(d.e/Be)+Dn(t.e/Be),c=_.length,u=C.length,c<u&&(o=_,_=C,C=o,s=c,c=u,u=s),o=[],s=c+u,i=s;i--;)o.push(0);for(i=u;--i>=0;){for(e=0,r=c+i;r>i;)a=o[r]+C[i]*_[r-i-1]+e,o[r--]=a%Ai|0,e=a/Ai|0;o[r]=(o[r]+e)%Ai|0}for(;!o[--s];)o.pop();return e?++n:o.shift(),t.d=o,t.e=yc(o,n),Ne?Ae(t,h.precision,h.rounding):t};re.toBinary=function(t,e){return td(this,2,t,e)};re.toDecimalPlaces=re.toDP=function(t,e){var n=this,i=n.constructor;return n=new i(n),t===void 0?n:(Xn(t,0,kr),e===void 0?e=i.rounding:Xn(e,0,8),Ae(n,t+n.e+1,e))};re.toExponential=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Li(i,!0):(Xn(t,0,kr),e===void 0?e=r.rounding:Xn(e,0,8),i=Ae(new r(i),t+1,e),n=Li(i,!0,t+1)),i.isNeg()&&!i.isZero()?"-"+n:n};re.toFixed=function(t,e){var n,i,r=this,o=r.constructor;return t===void 0?n=Li(r):(Xn(t,0,kr),e===void 0?e=o.rounding:Xn(e,0,8),i=Ae(new o(r),t+r.e+1,e),n=Li(i,!1,t+i.e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};re.toFraction=function(t){var e,n,i,r,o,s,a,c,u,d,h,_,C=this,D=C.d,O=C.constructor;if(!D)return new O(C);if(u=n=new O(1),i=c=new O(0),e=new O(i),o=e.e=Kp(D)-C.e-1,s=o%Be,e.d[0]=mn(10,s<0?Be+s:s),t==null)t=o>0?e:u;else{if(a=new O(t),!a.isInt()||a.lt(u))throw Error(vr+a);t=a.gt(e)?o>0?e:u:a}for(Ne=!1,a=new O(Tn(D)),d=O.precision,O.precision=o=D.length*Be*2;h=wt(a,e,0,1,1),r=n.plus(h.times(i)),r.cmp(t)!=1;)n=i,i=r,r=u,u=c.plus(h.times(r)),c=r,r=e,e=a.minus(h.times(r)),a=r;return r=wt(t.minus(n),i,0,1,1),c=c.plus(r.times(u)),n=n.plus(r.times(i)),c.s=u.s=C.s,_=wt(u,i,o,1).minus(C).abs().cmp(wt(c,n,o,1).minus(C).abs())<1?[u,i]:[c,n],O.precision=d,Ne=!0,_};re.toHexadecimal=re.toHex=function(t,e){return td(this,16,t,e)};re.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:Xn(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]?(Ne=!1,n=wt(n,t,0,e,1).times(t),Ne=!0,Ae(n)):(t.s=n.s,n=t),n};re.toNumber=function(){return+this};re.toOctal=function(t,e){return td(this,8,t,e)};re.toPower=re.pow=function(t){var e,n,i,r,o,s,a=this,c=a.constructor,u=+(t=new c(t));if(!a.d||!t.d||!a.d[0]||!t.d[0])return new c(mn(+a,u));if(a=new c(a),a.eq(1))return a;if(i=c.precision,o=c.rounding,t.eq(1))return Ae(a,i,o);if(e=Dn(t.e/Be),e>=t.d.length-1&&(n=u<0?-u:u)<=t1)return r=Wp(c,a,n,i),t.s<0?new c(1).div(r):Ae(r,i,o);if(s=a.s,s<0){if(e<t.d.length-1)return new c(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=mn(+a,u),e=n==0||!isFinite(n)?Dn(u*(Math.log("0."+Tn(a.d))/Math.LN10+a.e+1)):new c(n+"").e,e>c.maxE+1||e<c.minE-1?new c(e>0?s/0:0):(Ne=!1,c.rounding=a.s=1,n=Math.min(12,(e+"").length),r=Ql(t.times(br(a,i+n)),i),r.d&&(r=Ae(r,i+5,1),As(r.d,i,o)&&(e=i+10,r=Ae(Ql(t.times(br(a,e+n)),e),e+5,1),+Tn(r.d).slice(i+1,i+15)+1==1e14&&(r=Ae(r,i+1,0)))),r.s=s,Ne=!0,c.rounding=o,Ae(r,i,o))};re.toPrecision=function(t,e){var n,i=this,r=i.constructor;return t===void 0?n=Li(i,i.e<=r.toExpNeg||i.e>=r.toExpPos):(Xn(t,1,kr),e===void 0?e=r.rounding:Xn(e,0,8),i=Ae(new r(i),t,e),n=Li(i,t<=i.e||i.e<=r.toExpNeg,t)),i.isNeg()&&!i.isZero()?"-"+n:n};re.toSignificantDigits=re.toSD=function(t,e){var n=this,i=n.constructor;return t===void 0?(t=i.precision,e=i.rounding):(Xn(t,1,kr),e===void 0?e=i.rounding:Xn(e,0,8)),Ae(new i(n),t,e)};re.toString=function(){var t=this,e=t.constructor,n=Li(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+n:n};re.truncated=re.trunc=function(){return Ae(new this.constructor(this),this.e+1,1)};re.valueOf=re.toJSON=function(){var t=this,e=t.constructor,n=Li(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+n:n};function Tn(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=Be-i.length,n&&(o+=yr(n)),o+=i;s=t[e],i=s+"",n=Be-i.length,n&&(o+=yr(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Xn(t,e,n){if(t!==~~t||t<e||t>n)throw Error(vr+t)}function As(t,e,n,i){var r,o,s,a;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=Be,r=0):(r=Math.ceil((e+1)/Be),e%=Be),o=mn(10,Be-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)==mn(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)==mn(10,e-3)-1,s}function pc(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]+=Zl.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 i1(t,e){var n,i,r;if(e.isZero())return e;i=e.d.length,i<32?(n=Math.ceil(i/3),r=(1/bc(4,n)).toString()):(n=16,r="2.3283064365386962890625e-10"),t.precision+=n,e=Po(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 wt=function(){function t(i,r,o){var s,a=0,c=i.length;for(i=i.slice();c--;)s=i[c]*r+a,i[c]=s%o|0,a=s/o|0;return a&&i.unshift(a),i}function e(i,r,o,s){var a,c;if(o!=s)c=o>s?1:-1;else for(a=c=0;a<o;a++)if(i[a]!=r[a]){c=i[a]>r[a]?1:-1;break}return c}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,c){var u,d,h,_,C,D,O,B,j,M,R,K,X,Y,oe,$,ne,G,W,I,N=i.constructor,l=i.s==r.s?1:-1,f=i.d,w=r.d;if(!f||!f[0]||!w||!w[0])return new N(!i.s||!r.s||(f?w&&f[0]==w[0]:!w)?NaN:f&&f[0]==0||!w?l*0:l/0);for(c?(C=1,d=i.e-r.e):(c=Ai,C=Be,d=Dn(i.e/C)-Dn(r.e/C)),W=w.length,ne=f.length,j=new N(l),M=j.d=[],h=0;w[h]==(f[h]||0);h++);if(w[h]>(f[h]||0)&&d--,o==null?(Y=o=N.precision,s=N.rounding):a?Y=o+(i.e-r.e)+1:Y=o,Y<0)M.push(1),D=!0;else{if(Y=Y/C+2|0,h=0,W==1){for(_=0,w=w[0],Y++;(h<ne||_)&&Y--;h++)oe=_*c+(f[h]||0),M[h]=oe/w|0,_=oe%w|0;D=_||h<ne}else{for(_=c/(w[0]+1)|0,_>1&&(w=t(w,_,c),f=t(f,_,c),W=w.length,ne=f.length),$=W,R=f.slice(0,W),K=R.length;K<W;)R[K++]=0;I=w.slice(),I.unshift(0),G=w[0],w[1]>=c/2&&++G;do _=0,u=e(w,R,W,K),u<0?(X=R[0],W!=K&&(X=X*c+(R[1]||0)),_=X/G|0,_>1?(_>=c&&(_=c-1),O=t(w,_,c),B=O.length,K=R.length,u=e(O,R,B,K),u==1&&(_--,n(O,W<B?I:w,B,c))):(_==0&&(u=_=1),O=w.slice()),B=O.length,B<K&&O.unshift(0),n(R,O,K,c),u==-1&&(K=R.length,u=e(w,R,W,K),u<1&&(_++,n(R,W<K?I:w,K,c))),K=R.length):u===0&&(_++,R=[0]),M[h++]=_,u&&R[0]?R[K++]=f[$]||0:(R=[f[$]],K=1);while(($++<ne||R[0]!==void 0)&&Y--);D=R[0]!==void 0}M[0]||M.shift()}if(C==1)j.e=d,Up=D;else{for(h=1,_=M[0];_>=10;_/=10)h++;j.e=h+d*C-1,Ae(j,a?o+j.e+1:o,s,D)}return j}}();function Ae(t,e,n,i){var r,o,s,a,c,u,d,h,_,C=t.constructor;e:if(e!=null){if(h=t.d,!h)return t;for(r=1,a=h[0];a>=10;a/=10)r++;if(o=e-r,o<0)o+=Be,s=e,d=h[_=0],c=d/mn(10,r-s-1)%10|0;else if(_=Math.ceil((o+1)/Be),a=h.length,_>=a)if(i){for(;a++<=_;)h.push(0);d=c=0,r=1,o%=Be,s=o-Be+1}else break e;else{for(d=a=h[_],r=1;a>=10;a/=10)r++;o%=Be,s=o-Be+r,c=s<0?0:d/mn(10,r-s-1)%10|0}if(i=i||e<0||h[_+1]!==void 0||(s<0?d:d%mn(10,r-s-1)),u=n<4?(c||i)&&(n==0||n==(t.s<0?3:2)):c>5||c==5&&(n==4||i||n==6&&(o>0?s>0?d/mn(10,r-s):0:h[_-1])%10&1||n==(t.s<0?8:7)),e<1||!h[0])return h.length=0,u?(e-=t.e+1,h[0]=mn(10,(Be-e%Be)%Be),t.e=-e||0):h[0]=t.e=0,t;if(o==0?(h.length=_,a=1,_--):(h.length=_+1,a=mn(10,Be-o),h[_]=s>0?(d/mn(10,r-s)%mn(10,s)|0)*a:0),u)for(;;)if(_==0){for(o=1,s=h[0];s>=10;s/=10)o++;for(s=h[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(t.e++,h[0]==Ai&&(h[0]=1));break}else{if(h[_]+=a,h[_]!=Ai)break;h[_--]=0,a=1}for(o=h.length;h[--o]===0;)h.pop()}return Ne&&(t.e>C.maxE?(t.d=null,t.e=NaN):t.e<C.minE&&(t.e=0,t.d=[0])),t}function Li(t,e,n){if(!t.isFinite())return Xp(t);var i,r=t.e,o=Tn(t.d),s=o.length;return e?(n&&(i=n-s)>0?o=o.charAt(0)+"."+o.slice(1)+yr(i):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):r<0?(o="0."+yr(-r-1)+o,n&&(i=n-s)>0&&(o+=yr(i))):r>=s?(o+=yr(r+1-s),n&&(i=n-r-1)>0&&(o=o+"."+yr(i))):((i=r+1)<s&&(o=o.slice(0,i)+"."+o.slice(i)),n&&(i=n-s)>0&&(r+1===s&&(o+="."),o+=yr(i))),o}function yc(t,e){var n=t[0];for(e*=Be;n>=10;n/=10)e++;return e}function _c(t,e,n){if(e>n1)throw Ne=!0,n&&(t.precision=n),Error($p);return Ae(new t(mc),e,1,!0)}function Ci(t,e,n){if(e>Yl)throw Error($p);return Ae(new t(gc),e,n,!0)}function Kp(t){var e=t.length-1,n=e*Be+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 yr(t){for(var e="";t--;)e+="0";return e}function Wp(t,e,n,i){var r,o=new t(1),s=Math.ceil(i/Be+4);for(Ne=!1;;){if(n%2&&(o=o.times(e),qp(o.d,s)&&(r=!0)),n=Dn(n/2),n===0){n=o.d.length-1,r&&o.d[n]===0&&++o.d[n];break}e=e.times(e),qp(e.d,s)}return Ne=!0,o}function Fp(t){return t.d[t.d.length-1]&1}function Hp(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 Ql(t,e){var n,i,r,o,s,a,c,u=0,d=0,h=0,_=t.constructor,C=_.rounding,D=_.precision;if(!t.d||!t.d[0]||t.e>17)return new _(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(Ne=!1,c=D):c=e,a=new _(.03125);t.e>-2;)t=t.times(a),h+=5;for(i=Math.log(mn(2,h))/Math.LN10*2+5|0,c+=i,n=o=s=new _(1),_.precision=c;;){if(o=Ae(o.times(t),c,1),n=n.times(++d),a=s.plus(wt(o,n,c,1)),Tn(a.d).slice(0,c)===Tn(s.d).slice(0,c)){for(r=h;r--;)s=Ae(s.times(s),c,1);if(e==null)if(u<3&&As(s.d,c-i,C,u))_.precision=c+=10,n=o=a=new _(1),d=0,u++;else return Ae(s,_.precision=D,C,Ne=!0);else return _.precision=D,s}s=a}}function br(t,e){var n,i,r,o,s,a,c,u,d,h,_,C=1,D=10,O=t,B=O.d,j=O.constructor,M=j.rounding,R=j.precision;if(O.s<0||!B||!B[0]||!O.e&&B[0]==1&&B.length==1)return new j(B&&!B[0]?-1/0:O.s!=1?NaN:B?0:O);if(e==null?(Ne=!1,d=R):d=e,j.precision=d+=D,n=Tn(B),i=n.charAt(0),Math.abs(o=O.e)<15e14){for(;i<7&&i!=1||i==1&&n.charAt(1)>3;)O=O.times(t),n=Tn(O.d),i=n.charAt(0),C++;o=O.e,i>1?(O=new j("0."+n),o++):O=new j(i+"."+n.slice(1))}else return u=_c(j,d+2,R).times(o+""),O=br(new j(i+"."+n.slice(1)),d-D).plus(u),j.precision=R,e==null?Ae(O,R,M,Ne=!0):O;for(h=O,c=s=O=wt(O.minus(1),O.plus(1),d,1),_=Ae(O.times(O),d,1),r=3;;){if(s=Ae(s.times(_),d,1),u=c.plus(wt(s,new j(r),d,1)),Tn(u.d).slice(0,d)===Tn(c.d).slice(0,d))if(c=c.times(2),o!==0&&(c=c.plus(_c(j,d+2,R).times(o+""))),c=wt(c,new j(C),d,1),e==null)if(As(c.d,d-D,M,a))j.precision=d+=D,u=s=O=wt(h.minus(1),h.plus(1),d,1),_=Ae(O.times(O),d,1),r=a=1;else return Ae(c,j.precision=R,M,Ne=!0);else return j.precision=R,c;c=u,r+=2}}function Xp(t){return String(t.s*t.s/0)}function ed(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)%Be,n<0&&(i+=Be),i<r){for(i&&t.d.push(+e.slice(0,i)),r-=Be;i<r;)t.d.push(+e.slice(i,i+=Be));e=e.slice(i),i=Be-e.length}else i-=r;for(;i--;)e+="0";t.d.push(+e),Ne&&(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 r1(t,e){var n,i,r,o,s,a,c,u,d;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Vp.test(e))return ed(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(Qv.test(e))n=16,e=e.toLowerCase();else if(Yv.test(e))n=2;else if(e1.test(e))n=8;else throw Error(vr+e);for(o=e.search(/p/i),o>0?(c=+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=Wp(i,new i(n),o,o*2)),u=pc(e,n,Ai),d=u.length-1,o=d;u[o]===0;--o)u.pop();return o<0?new i(t.s*0):(t.e=yc(u,d),t.d=u,Ne=!1,s&&(t=wt(t,r,a*4)),c&&(t=t.times(Math.abs(c)<54?mn(2,c):Ss.pow(2,c))),Ne=!0,t)}function o1(t,e){var n,i=e.d.length;if(i<3)return e.isZero()?e:Po(t,2,e,e);n=1.4*Math.sqrt(i),n=n>16?16:n|0,e=e.times(1/bc(5,n)),e=Po(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 Po(t,e,n,i,r){var o,s,a,c,u=1,d=t.precision,h=Math.ceil(d/Be);for(Ne=!1,c=n.times(n),a=new t(i);;){if(s=wt(a.times(c),new t(e++*e++),d,1),a=r?i.plus(s):i.minus(s),i=wt(s.times(c),new t(e++*e++),d,1),s=a.plus(i),s.d[h]!==void 0){for(o=h;s.d[o]===a.d[o]&&o--;);if(o==-1)break}o=a,a=i,i=s,s=o,u++}return Ne=!0,s.d.length=h+1,s}function bc(t,e){for(var n=t;--e;)n*=t;return n}function Zp(t,e){var n,i=e.s<0,r=Ci(t,t.precision,1),o=r.times(.5);if(e=e.abs(),e.lte(o))return tr=i?4:1,e;if(n=e.divToInt(r),n.isZero())tr=i?3:2;else{if(e=e.minus(n.times(r)),e.lte(o))return tr=Fp(n)?i?2:3:i?4:1,e;tr=Fp(n)?i?1:4:i?3:2}return e.minus(r).abs()}function td(t,e,n,i){var r,o,s,a,c,u,d,h,_,C=t.constructor,D=n!==void 0;if(D?(Xn(n,1,kr),i===void 0?i=C.rounding:Xn(i,0,8)):(n=C.precision,i=C.rounding),!t.isFinite())d=Xp(t);else{for(d=Li(t),s=d.indexOf("."),D?(r=2,e==16?n=n*4-3:e==8&&(n=n*3-2)):r=e,s>=0&&(d=d.replace(".",""),_=new C(1),_.e=d.length-s,_.d=pc(Li(_),10,r),_.e=_.d.length),h=pc(d,10,r),o=c=h.length;h[--c]==0;)h.pop();if(!h[0])d=D?"0p+0":"0";else{if(s<0?o--:(t=new C(t),t.d=h,t.e=o,t=wt(t,_,n,i,0,r),h=t.d,o=t.e,u=Up),s=h[n],a=r/2,u=u||h[n+1]!==void 0,u=i<4?(s!==void 0||u)&&(i===0||i===(t.s<0?3:2)):s>a||s===a&&(i===4||u||i===6&&h[n-1]&1||i===(t.s<0?8:7)),h.length=n,u)for(;++h[--n]>r-1;)h[n]=0,n||(++o,h.unshift(1));for(c=h.length;!h[c-1];--c);for(s=0,d="";s<c;s++)d+=Zl.charAt(h[s]);if(D){if(c>1)if(e==16||e==8){for(s=e==16?4:3,--c;c%s;c++)d+="0";for(h=pc(d,r,e),c=h.length;!h[c-1];--c);for(s=1,d="1.";s<c;s++)d+=Zl.charAt(h[s])}else d=d.charAt(0)+"."+d.slice(1);d=d+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)d="0"+d;d="0."+d}else if(++o>c)for(o-=c;o--;)d+="0";else o<c&&(d=d.slice(0,o)+"."+d.slice(o))}d=(e==16?"0x":e==2?"0b":e==8?"0o":"")+d}return t.s<0?"-"+d:d}function qp(t,e){if(t.length>e)return t.length=e,!0}function s1(t){return new this(t).abs()}function a1(t){return new this(t).acos()}function c1(t){return new this(t).acosh()}function u1(t,e){return new this(t).plus(e)}function l1(t){return new this(t).asin()}function d1(t){return new this(t).asinh()}function f1(t){return new this(t).atan()}function h1(t){return new this(t).atanh()}function p1(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=Ci(this,o,1).times(e.s>0?.25:.75),n.s=t.s):!e.d||t.isZero()?(n=e.s<0?Ci(this,i,r):new this(0),n.s=t.s):!t.d||e.isZero()?(n=Ci(this,o,1).times(.5),n.s=t.s):e.s<0?(this.precision=o,this.rounding=1,n=this.atan(wt(t,e,o,1)),e=Ci(this,o,1),this.precision=i,this.rounding=r,n=t.s<0?n.minus(e):n.plus(e)):n=this.atan(wt(t,e,o,1)),n}function m1(t){return new this(t).cbrt()}function g1(t){return Ae(t=new this(t),t.e+1,2)}function _1(t,e,n){return new this(t).clamp(e,n)}function w1(t){if(!t||typeof t!="object")throw Error(wc+"Object expected");var e,n,i,r=t.defaults===!0,o=["precision",1,kr,"rounding",0,8,"toExpNeg",-Oo,0,"toExpPos",0,Oo,"maxE",0,Oo,"minE",-Oo,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(n=o[e],r&&(this[n]=Jl[n]),(i=t[n])!==void 0)if(Dn(i)===i&&i>=o[e+1]&&i<=o[e+2])this[n]=i;else throw Error(vr+n+": "+i);if(n="crypto",r&&(this[n]=Jl[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(Gp);else this[n]=!1;else throw Error(vr+n+": "+i);return this}function y1(t){return new this(t).cos()}function b1(t){return new this(t).cosh()}function Jp(t){var e,n,i;function r(o){var s,a,c,u=this;if(!(u instanceof r))return new r(o);if(u.constructor=r,Lp(o)){u.s=o.s,Ne?!o.d||o.e>r.maxE?(u.e=NaN,u.d=null):o.e<r.minE?(u.e=0,u.d=[0]):(u.e=o.e,u.d=o.d.slice()):(u.e=o.e,u.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){u.s=1/o<0?-1:1,u.e=0,u.d=[0];return}if(o<0?(o=-o,u.s=-1):u.s=1,o===~~o&&o<1e7){for(s=0,a=o;a>=10;a/=10)s++;Ne?s>r.maxE?(u.e=NaN,u.d=null):s<r.minE?(u.e=0,u.d=[0]):(u.e=s,u.d=[o]):(u.e=s,u.d=[o]);return}else if(o*0!==0){o||(u.s=NaN),u.e=NaN,u.d=null;return}return ed(u,o.toString())}else if(c!=="string")throw Error(vr+o);return(a=o.charCodeAt(0))===45?(o=o.slice(1),u.s=-1):(a===43&&(o=o.slice(1)),u.s=1),Vp.test(o)?ed(u,o):r1(u,o)}if(r.prototype=re,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=w1,r.clone=Jp,r.isDecimal=Lp,r.abs=s1,r.acos=a1,r.acosh=c1,r.add=u1,r.asin=l1,r.asinh=d1,r.atan=f1,r.atanh=h1,r.atan2=p1,r.cbrt=m1,r.ceil=g1,r.clamp=_1,r.cos=y1,r.cosh=b1,r.div=v1,r.exp=k1,r.floor=T1,r.hypot=C1,r.ln=A1,r.log=S1,r.log10=x1,r.log2=I1,r.max=O1,r.min=P1,r.mod=E1,r.mul=D1,r.pow=B1,r.random=M1,r.round=j1,r.sign=N1,r.sin=R1,r.sinh=F1,r.sqrt=q1,r.sub=L1,r.sum=U1,r.tan=$1,r.tanh=G1,r.trunc=z1,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 v1(t,e){return new this(t).div(e)}function k1(t){return new this(t).exp()}function T1(t){return Ae(t=new this(t),t.e+1,3)}function C1(){var t,e,n=new this(0);for(Ne=!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 Ne=!0,new this(1/0);n=e}return Ne=!0,n.sqrt()}function Lp(t){return t instanceof Ss||t&&t.toStringTag===zp||!1}function A1(t){return new this(t).ln()}function S1(t,e){return new this(t).log(e)}function I1(t){return new this(t).log(2)}function x1(t){return new this(t).log(10)}function O1(){return Hp(this,arguments,"lt")}function P1(){return Hp(this,arguments,"gt")}function E1(t,e){return new this(t).mod(e)}function D1(t,e){return new this(t).mul(e)}function B1(t,e){return new this(t).pow(e)}function M1(t){var e,n,i,r,o=0,s=new this(1),a=[];if(t===void 0?t=this.precision:Xn(t,1,kr),i=Math.ceil(t/Be),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(Gp);else for(;o<i;)a[o++]=Math.random()*1e7|0;for(i=a[--o],t%=Be,i&&t&&(r=mn(10,Be-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-=Be)a.shift();for(i=1,r=a[0];r>=10;r/=10)i++;i<Be&&(n-=Be-i)}return s.e=n,s.d=a,s}function j1(t){return Ae(t=new this(t),t.e+1,this.rounding)}function N1(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function R1(t){return new this(t).sin()}function F1(t){return new this(t).sinh()}function q1(t){return new this(t).sqrt()}function L1(t,e){return new this(t).sub(e)}function U1(){var t=0,e=arguments,n=new this(e[t]);for(Ne=!1;n.s&&++t<e.length;)n=n.plus(e[t]);return Ne=!0,Ae(n,this.precision,this.rounding)}function $1(t){return new this(t).tan()}function G1(t){return new this(t).tanh()}function z1(t){return Ae(t=new this(t),t.e+1,1)}re[Symbol.for("nodejs.util.inspect.custom")]=re.toString;re[Symbol.toStringTag]="Decimal";var Ss=re.constructor=Jp(Jl);mc=new Ss(mc);gc=new Ss(gc);var J=Ss;var Hm=Pe(Ee(),1),Ps=Pe(Ee(),1);var De=Pe(Ee(),1),dt=Pe(Ee(),1),Jm=Pe(Ee(),1),Uc=require("@mysten/sui.js/utils"),zk=Pe(Ee(),1),gd=Pe(Ee(),1),Vk=Pe(Ee(),1);var Yr=Pe(Ee(),1),Os=Pe(Ee(),1);var Qr=require("@mysten/sui.js/transactions"),nT=require("@mysten/sui.js/utils"),iT=require("@mysten/sui.js/transactions"),Sn=Pe(Ee(),1),Bc=require("@mysten/sui.js/transactions"),wd=Pe(Ee(),1),eo=require("@mysten/sui.js/transactions"),ag=require("@mysten/sui.js/utils"),yt=Pe(Ee(),1),Mc=require("@mysten/sui.js/transactions"),ni=Pe(Ee(),1),io=Pe(rd(),1),cg=require("@mysten/sui.js/transactions"),to=Pe(Ee(),1);var yd=require("@mysten/sui.js/transactions");var xm="3.7.7",Y1=xm,Bo=typeof Buffer=="function",Tm=typeof TextDecoder=="function"?new TextDecoder:void 0,Cm=typeof TextEncoder=="function"?new TextEncoder:void 0,Q1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Is=Array.prototype.slice.call(Q1),Ac=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(Is),ek=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Cn=String.fromCharCode.bind(String),Am=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),Om=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Pm=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Em=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+=Is[e>>18&63]+Is[e>>12&63]+Is[e>>6&63]+Is[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},ad=typeof btoa=="function"?t=>btoa(t):Bo?t=>Buffer.from(t,"binary").toString("base64"):Em,od=Bo?t=>Buffer.from(t).toString("base64"):t=>{let n=[];for(let i=0,r=t.length;i<r;i+=4096)n.push(Cn.apply(null,t.subarray(i,i+4096)));return ad(n.join(""))},Sc=(t,e=!1)=>e?Om(od(t)):od(t),tk=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?Cn(192|e>>>6)+Cn(128|e&63):Cn(224|e>>>12&15)+Cn(128|e>>>6&63)+Cn(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return Cn(240|e>>>18&7)+Cn(128|e>>>12&63)+Cn(128|e>>>6&63)+Cn(128|e&63)}},nk=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Dm=t=>t.replace(nk,tk),Sm=Bo?t=>Buffer.from(t,"utf8").toString("base64"):Cm?t=>od(Cm.encode(t)):t=>ad(Dm(t)),Do=(t,e=!1)=>e?Om(Sm(t)):Sm(t),Im=t=>Do(t,!0),ik=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,rk=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 Cn((n>>>10)+55296)+Cn((n&1023)+56320);case 3:return Cn((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return Cn((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Bm=t=>t.replace(ik,rk),Mm=t=>{if(t=t.replace(/\s+/g,""),!ek.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=Ac[t.charAt(o++)]<<18|Ac[t.charAt(o++)]<<12|(i=Ac[t.charAt(o++)])<<6|(r=Ac[t.charAt(o++)]),n+=i===64?Cn(e>>16&255):r===64?Cn(e>>16&255,e>>8&255):Cn(e>>16&255,e>>8&255,e&255);return n},cd=typeof atob=="function"?t=>atob(Pm(t)):Bo?t=>Buffer.from(t,"base64").toString("binary"):Mm,jm=Bo?t=>Am(Buffer.from(t,"base64")):t=>Am(cd(t).split("").map(e=>e.charCodeAt(0))),Nm=t=>jm(Rm(t)),ok=Bo?t=>Buffer.from(t,"base64").toString("utf8"):Tm?t=>Tm.decode(jm(t)):t=>Bm(cd(t)),Rm=t=>Pm(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),sd=t=>ok(Rm(t)),sk=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)},Fm=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),qm=function(){let t=(e,n)=>Object.defineProperty(String.prototype,e,Fm(n));t("fromBase64",function(){return sd(this)}),t("toBase64",function(e){return Do(this,e)}),t("toBase64URI",function(){return Do(this,!0)}),t("toBase64URL",function(){return Do(this,!0)}),t("toUint8Array",function(){return Nm(this)})},Lm=function(){let t=(e,n)=>Object.defineProperty(Uint8Array.prototype,e,Fm(n));t("toBase64",function(e){return Sc(this,e)}),t("toBase64URI",function(){return Sc(this,!0)}),t("toBase64URL",function(){return Sc(this,!0)})},ak=()=>{qm(),Lm()},Mo={version:xm,VERSION:Y1,atob:cd,atobPolyfill:Mm,btoa:ad,btoaPolyfill:Em,fromBase64:sd,toBase64:Do,encode:Do,encodeURI:Im,encodeURL:Im,utob:Dm,btou:Bm,decode:sd,isValid:sk,fromUint8Array:Sc,toUint8Array:Nm,extendString:qm,extendUint8Array:Lm,extendBuiltins:ak};var bd=require("@mysten/sui.js/transactions"),ug=require("@mysten/sui.js/utils"),Si=Pe(Ee(),1);var Ic,ck=new Uint8Array(16);function ud(){if(!Ic&&(Ic=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ic))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ic(ck)}var An=[];for(let t=0;t<256;++t)An.push((t+256).toString(16).slice(1));function Um(t,e=0){return An[t[e+0]]+An[t[e+1]]+An[t[e+2]]+An[t[e+3]]+"-"+An[t[e+4]]+An[t[e+5]]+"-"+An[t[e+6]]+An[t[e+7]]+"-"+An[t[e+8]]+An[t[e+9]]+"-"+An[t[e+10]]+An[t[e+11]]+An[t[e+12]]+An[t[e+13]]+An[t[e+14]]+An[t[e+15]]}var uk=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ld={randomUUID:uk};function lk(t,e,n){if(ld.randomUUID&&!e&&!t)return ld.randomUUID();t=t||{};let i=t.random||(t.rng||ud)();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 Um(i)}var xc=lk;var jc=require("@mysten/sui.js/utils"),lg=require("@mysten/sui.js/transactions"),dg=require("@mysten/sui.js/client"),fg=require("@mysten/sui.js/bcs");var dk=Object.defineProperty,fk=(t,e,n)=>e in t?dk(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,hk=(t,e,n)=>(fk(t,typeof e!="symbol"?e+"":e,n),n),Ar=5*60*1e3,tt=24*60*60*1e3;function gn(t){return Date.parse(new Date().toString())+t}var xi=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)}};J.config({precision:64,rounding:J.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var In=J,he=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof he&&t.errorCode===e}},be=new ln.default(0),Ui=new ln.default(1),Fc=new ln.default(2),F4=Fc.pow(new ln.default(128)),qo=Fc.pow(new ln.default(64)).sub(Ui),gk=Fc.pow(new ln.default(128)).sub(Ui),nt=class{static toX64_BN(t){return t.mul(new ln.default(2).pow(new ln.default(64)))}static toX64_Decimal(t){return t.mul(In.pow(2,64))}static toX64(t){return new ln.default(t.mul(In.pow(2,64)).floor().toFixed())}static fromX64(t){return new In(t.toString()).mul(In.pow(2,-64))}static fromX64_Decimal(t){return t.mul(In.pow(2,-64))}static fromX64_BN(t){return t.div(new ln.default(2).pow(new ln.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(qo).gt(be)&&(e=e.add(Ui)),e}static divRoundUp(t,e){return t.mod(e).eq(be)?t.div(e):t.div(e).add(new ln.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(gk):t.sub(e)}static checkUnsignedSub(t,e){let n=t.sub(e);if(n.isNeg())throw new he("Unsigned integer sub overflow","UnsignedIntegerOverflow");return n}static checkMul(t,e,n){let i=t.mul(e);if(this.isOverflow(i,n))throw new he("Multiplication overflow","MultiplicationOverflow");return i}static checkMulDivFloor(t,e,n,i){if(n.eq(be))throw new he("Devide by zero","DivideByZero");let r=t.mul(e).div(n);if(this.isOverflow(r,i))throw new he("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivCeil(t,e,n,i){if(n.eq(be))throw new he("Devide by zero","DivideByZero");let r=t.mul(e).add(n.sub(Ui)).div(n);if(this.isOverflow(r,i))throw new he("Multiplication div overflow","MulDivOverflow");return r}static checkMulDivRound(t,e,n,i){if(n.eq(be))throw new he("Devide by zero","DivideByZero");let r=t.mul(e.add(n.shrn(1))).div(n);if(this.isOverflow(r,i))throw new he("Multiplication div overflow","MulDivOverflow");return r}static checkMulShiftRight(t,e,n,i){let r=t.mul(e).div(new ln.default(2).pow(new ln.default(n)));if(this.isOverflow(r,i))throw new he("Multiplication shift right overflow","MulShiftRightOverflow");return r}static checkMulShiftRight64RoundUpIf(t,e,n,i){let r=t.mul(e),s=i&&r.and(qo).gt(be)?r.shrn(64).add(Ui):r.shrn(64);if(this.isOverflow(s,n))throw new he("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 he("Multiplication shift left overflow","MulShiftLeftOverflow");return r}static checkDivRoundUpIf(t,e,n){if(e.eq(be))throw new he("Devide by zero","DivideByZero");return n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(Fc.pow(new ln.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(be)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new ln.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 ln.default(1)))}static neg_from(t){return t.eq(be)?t:this.u128_neg(t).add(new ln.default(1)).or(new ln.default(1).shln(127))}};function _k(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new Tr.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new Tr.default(t.fee_growth_global_a),feeGrowthGlobalB:new Tr.default(t.fee_growth_global_b),feeProtocolCoinA:new Tr.default(t.fee_protocol_coin_a),feeProtocolCoinB:new Tr.default(t.fee_protocol_coin_b),feeRate:new Tr.default(t.fee_rate),liquidity:new Tr.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var Xm=443636,Zm=-443636,qc="79226673515401279992447579055";var Lc="4295048016",Ro=new Hm.default(1e6),Ge="0x0000000000000000000000000000000000000000000000000000000000000006",wk="partner",Dc="pool_script",no="pool_script_v2",Cr="router",dd="router_with_partner",Zn="fetcher_script",yk="expect_swap",$m="utils";var fd="custodian_v2",bk="clob_v2",vk="endpoints_v2";function ye(t){if(t.config===void 0)throw new he(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var kk=14,Tk="59543866431248",Ck="184467440737095516",Ak="15793534762490258745",Sk=443636;function Ik(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 xk(t){let e;return t&1?e=new De.default("79232123823359799118286999567"):e=new De.default("79228162514264337593543950336"),t&2&&(e=$e(e.mul(new De.default("79236085330515764027303304731")),96,256)),t&4&&(e=$e(e.mul(new De.default("79244008939048815603706035061")),96,256)),t&8&&(e=$e(e.mul(new De.default("79259858533276714757314932305")),96,256)),t&16&&(e=$e(e.mul(new De.default("79291567232598584799939703904")),96,256)),t&32&&(e=$e(e.mul(new De.default("79355022692464371645785046466")),96,256)),t&64&&(e=$e(e.mul(new De.default("79482085999252804386437311141")),96,256)),t&128&&(e=$e(e.mul(new De.default("79736823300114093921829183326")),96,256)),t&256&&(e=$e(e.mul(new De.default("80248749790819932309965073892")),96,256)),t&512&&(e=$e(e.mul(new De.default("81282483887344747381513967011")),96,256)),t&1024&&(e=$e(e.mul(new De.default("83390072131320151908154831281")),96,256)),t&2048&&(e=$e(e.mul(new De.default("87770609709833776024991924138")),96,256)),t&4096&&(e=$e(e.mul(new De.default("97234110755111693312479820773")),96,256)),t&8192&&(e=$e(e.mul(new De.default("119332217159966728226237229890")),96,256)),t&16384&&(e=$e(e.mul(new De.default("179736315981702064433883588727")),96,256)),t&32768&&(e=$e(e.mul(new De.default("407748233172238350107850275304")),96,256)),t&65536&&(e=$e(e.mul(new De.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=$e(e.mul(new De.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=$e(e.mul(new De.default("38992368544603139932233054999993551")),96,256)),$e(e,32,256)}function Ok(t){let e=Math.abs(t),n;return e&1?n=new De.default("18445821805675392311"):n=new De.default("18446744073709551616"),e&2&&(n=$e(n.mul(new De.default("18444899583751176498")),64,256)),e&4&&(n=$e(n.mul(new De.default("18443055278223354162")),64,256)),e&8&&(n=$e(n.mul(new De.default("18439367220385604838")),64,256)),e&16&&(n=$e(n.mul(new De.default("18431993317065449817")),64,256)),e&32&&(n=$e(n.mul(new De.default("18417254355718160513")),64,256)),e&64&&(n=$e(n.mul(new De.default("18387811781193591352")),64,256)),e&128&&(n=$e(n.mul(new De.default("18329067761203520168")),64,256)),e&256&&(n=$e(n.mul(new De.default("18212142134806087854")),64,256)),e&512&&(n=$e(n.mul(new De.default("17980523815641551639")),64,256)),e&1024&&(n=$e(n.mul(new De.default("17526086738831147013")),64,256)),e&2048&&(n=$e(n.mul(new De.default("16651378430235024244")),64,256)),e&4096&&(n=$e(n.mul(new De.default("15030750278693429944")),64,256)),e&8192&&(n=$e(n.mul(new De.default("12247334978882834399")),64,256)),e&16384&&(n=$e(n.mul(new De.default("8131365268884726200")),64,256)),e&32768&&(n=$e(n.mul(new De.default("3584323654723342297")),64,256)),e&65536&&(n=$e(n.mul(new De.default("696457651847595233")),64,256)),e&131072&&(n=$e(n.mul(new De.default("26294789957452057")),64,256)),e&262144&&(n=$e(n.mul(new De.default("37481735321082")),64,256)),n}var ve=class{static priceToSqrtPriceX64(t,e,n){return nt.toX64(t.mul(In.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return nt.fromX64(t).pow(2).mul(In.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new De.default(xk(t)):new De.default(Ok(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new De.default(qc))||t.lt(new De.default(Lc)))throw new he("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,n=new De.default(e-64),i=Ik(n,32,128),r=new De.default("8000000000000000","hex"),o=0,s=new De.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new De.default(0))&&o<kk;){a=a.mul(a);let D=a.shrn(127);a=a.shrn(63+D.toNumber()),s=s.add(r.mul(D)),r=r.shrn(1),o+=1}let c=s.shrn(32),d=i.add(c).mul(new De.default(Tk)),h=$e(d.sub(new De.default(Ck)),64,128).toNumber(),_=$e(d.add(new De.default(Ak)),64,128).toNumber();return h===_?h:ve.tickIndexToSqrtPriceX64(_).lte(t)?_:h}static tickIndexToPrice(t,e,n){return ve.sqrtPriceX64ToPrice(ve.tickIndexToSqrtPriceX64(t),e,n)}static priceToTickIndex(t,e,n){return ve.sqrtPriceX64ToTickIndex(ve.priceToSqrtPriceX64(t,e,n))}static priceToInitializableTickIndex(t,e,n,i){return ve.getInitializableTickIndex(ve.priceToTickIndex(t,e,n),i)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ve.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ve.getInitializableTickIndex(t,e)-e}};function Pk(t){return te(t).add(te(Sk))}var L4=new Ps.default(365),U4=new Ps.default(24),$4=new Ps.default(3600),G4=new Ps.default(.5);var Ii=class{static getDefaultSqrtPriceLimit(t){return new Jm.default(t?Lc:qc)}static getDefaultOtherAmountThreshold(t){return t?be:qo}};function Ym(t,e,n,i){if(n.eq(be))return t;let r=nt.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=nt.checkMul(t,n,256);if(!i&&o.lte(s))throw new he("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let a=i?nt.checkDivRoundUpIf(r,o.add(s),!0):nt.checkDivRoundUpIf(r,o.sub(s),!0);if(a.lt(new dt.default(Lc)))throw new he("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(a.gt(new dt.default(qc)))throw new he("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return a}function Qm(t,e,n,i){let r=nt.checkDivRoundUpIf(n.shln(64),e,!i),o=i?t.add(r):t.sub(r);if(o.lt(new dt.default(Lc))||o.gt(new dt.default(qc)))throw new he("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function Ek(t,e,n,i){return i?Ym(t,e,n,!0):Qm(t,e,n,!0)}function Dk(t,e,n,i){return i?Qm(t,e,n,!1):Ym(t,e,n,!1)}function Gm(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(be)||r.eq(be))return be;let o;if(i){let s=new dt.default(n).mul(new dt.default(r)).shln(64),a=e.mul(t),c=s.div(a);o=s.mod(a).eq(be)?c:c.add(Ui)}else{let s=new dt.default(n).mul(new dt.default(r));o=s.and(qo).gt(be)?s.shrn(64).add(Ui):s.shrn(64)}return o}function zm(t,e,n,i){let r=t.gt(e)?t.sub(e):e.sub(t);if(n.lte(be)||r.eq(be))return be;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 Bk(t,e,n,i,r,o){if(n===be)return{amountIn:be,amountOut:be,nextSqrtPrice:e,feeAmount:be};let s=t.gte(e),a,c,u,d;if(o){let h=nt.checkMulDivFloor(i,nt.checkUnsignedSub(Ro,r),Ro,64),_=Gm(t,e,n,s);_.gt(h)?(a=h,d=nt.checkUnsignedSub(i,h),u=Ek(t,n,h,s)):(a=_,d=nt.checkMulDivCeil(a,r,Ro.sub(r),64),u=e),c=zm(t,u,n,s)}else{let h=zm(t,e,n,s);h.gt(i)?(c=i,u=Dk(t,n,i,s)):(c=h,u=e),a=Gm(t,u,n,s),d=nt.checkMulDivCeil(a,r,Ro.sub(r),64)}return{amountIn:a,amountOut:c,nextSqrtPrice:u,feeAmount:d}}function Mk(t,e,n,i,r){let o=n,s=i.liquidity,{currentSqrtPrice:a}=i,c={amountIn:be,amountOut:be,feeAmount:be,refAmount:be,nextSqrtPrice:be,crossTickNum:0},u,d,h=Ii.getDefaultSqrtPriceLimit(t);for(let _ of r){if(t&&i.currentTickIndex<_.index||!t&&i.currentTickIndex>=_.index||_===null)continue;t&&h.gt(_.sqrtPrice)||!t&&h.lt(_.sqrtPrice)?u=h:u=_.sqrtPrice;let C=Bk(a,u,s,o,i.feeRate,e);if(C.amountIn.eq(be)||(o=e?o.sub(C.amountIn.add(C.feeAmount)):o.sub(C.amountOut)),c.amountIn=c.amountIn.add(C.amountIn),c.amountOut=c.amountOut.add(C.amountOut),c.feeAmount=c.feeAmount.add(C.feeAmount),C.nextSqrtPrice.eq(_.sqrtPrice)?(d=_.liquidityNet.mul(new dt.default(-1)),t?nt.is_neg(d)?s=s.add(new dt.default(Mn(BigInt(d.toString()),128))):s=s.add(d):nt.is_neg(d)?s=s.sub(new dt.default(Mn(BigInt(d.toString()),128))):s=s.sub(d),a=_.sqrtPrice):a=C.nextSqrtPrice,c.crossTickNum+=1,o.eq(be))break}return c.amountIn=c.amountIn.add(c.feeAmount),c.nextSqrtPrice=a,c}function Oc(t,e,n){let i=dt.default.min(t,e),r=dt.default.max(t,e),o=nt.fromX64_BN(n.mul(r).mul(i)),s=r.sub(i);return o.div(s)}function Pc(t,e,n){let i=dt.default.min(t,e),o=dt.default.max(t,e).sub(i);return n.shln(64).div(o)}var dn=class{static updateFeeRate(t,e,n,i,r){let o=nt.checkMulDivCeil(e,new dt.default(i),Ro,64),s=n===0?be:nt.checkMulDivFloor(e,new dt.default(n),Ro,64),a=e.mul(o).mul(s);if(r?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),a.eq(be)||t.liquidity.eq(be))return{refFee:s,clmm:t};let c=a.shln(64).div(t.liquidity);return r?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(c):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(c),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,n,i,r){let o=new In(t.toString()),s=new In(e.toString()),a=new In(n.toString()),c=new In(i.toString()),u,d;return e.lt(n)?(u=nt.toX64_Decimal(o).mul(c.sub(a)).div(a.mul(c)),d=new In(0)):e.lt(i)?(u=nt.toX64_Decimal(o).mul(c.sub(s)).div(s.mul(c)),d=nt.fromX64_Decimal(o.mul(s.sub(a)))):(u=new In(0),d=nt.fromX64_Decimal(o.mul(c.sub(a)))),r?{coinA:new dt.default(u.ceil().toString()),coinB:new dt.default(d.ceil().toString())}:{coinA:new dt.default(u.floor().toString()),coinB:new dt.default(d.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,n,i,r,o,s){let a=ve.sqrtPriceX64ToTickIndex(s),c=ve.tickIndexToSqrtPriceX64(t),u=ve.tickIndexToSqrtPriceX64(e),d;if(a<t){if(!i)throw new he("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");d=Oc(c,u,n)}else if(a>e){if(i)throw new he("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");d=Pc(u,c,n)}else i?d=Oc(s,u,n):d=Pc(s,c,n);let h=dn.getCoinAmountFromLiquidity(d,s,c,u,r),_=r?te(h.coinA.toString()).mul(1+o).toString():te(h.coinA.toString()).mul(1-o).toString(),C=r?te(h.coinB.toString()).mul(1+o).toString():te(h.coinB.toString()).mul(1-o).toString();return{coinAmountA:h.coinA,coinAmountB:h.coinB,tokenMaxA:r?new dt.default(In.ceil(_).toString()):new dt.default(In.floor(_).toString()),tokenMaxB:r?new dt.default(In.ceil(C).toString()):new dt.default(In.floor(C).toString()),liquidityAmount:d,fix_amount_a:i}}static estimateLiquidityFromcoinAmounts(t,e,n,i){if(e>n)throw new he("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let r=ve.sqrtPriceX64ToTickIndex(t),o=ve.tickIndexToSqrtPriceX64(e),s=ve.tickIndexToSqrtPriceX64(n);if(r<e)return Oc(o,s,i.coinA);if(r>=n)return Pc(s,o,i.coinB);let a=Oc(t,s,i.coinA),c=Pc(t,o,i.coinB);return dt.default.min(a,c)}static estCoinAmountsFromTotalAmount(t,e,n,i,r,o){let{ratioA:s,ratioB:a}=dn.calculateDepositRatioFixTokenA(t,e,n),c=te(i).mul(s).div(r),u=te(i).mul(a).div(o);return{amountA:c,amountB:u}}static calculateDepositRatioFixTokenA(t,e,n){let i=new dt.default(1e8),{coinAmountB:r}=dn.estLiquidityAndcoinAmountFromOneAmounts(t,e,i,!0,!0,0,n),o=ve.sqrtPriceX64ToPrice(n,0,0),s=te(i.toString()).mul(o),a=s.add(r.toString()),c=s.div(a),u=te(r.toString()).div(a);return{ratioA:c,ratioB:u}}};function jk(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var Nk=0,eg=1,Rk=2;function Vm(t,e){return t===e?Nk:t<e?eg:Rk}function Fk(t,e){let n=0,i=t.length<=e.length?t.length:e.length,r=Vm(t.length,e.length);for(;n<i;){let o=Vm(t.charCodeAt(n),e.charCodeAt(n));if(n+=1,o!==0)return o}return r}function Km(t,e){return Fk(t,e)===eg}function Nc(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 ge(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 c={...ge(e),type_arguments:i.map(u=>ge(u).source_address)};return c.type_arguments=c.type_arguments.map(u=>et.isSuiCoin(u)?u:ge(u).source_address),c.source_address=Nc(c.full_address,c.type_arguments),c}let r=e.split("::"),s={full_address:e,address:e===Es||e===Gk?"0x2":(0,Uc.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=Nc(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function nr(t){return ge(t).source_address}function qk(t){return t.toLowerCase().startsWith("0x")?(0,Uc.normalizeSuiObjectId)(t):t}var Lk=(t,e=!0)=>{let n=t.split("::"),i=n.shift(),r=(0,Uc.normalizeSuiObjectId)(i);return e&&(r=jk(r)),`${r}::${n.join("::")}`};function tg(t){for(let e in t){let n=typeof t[e];if(n==="object")tg(t[e]);else if(n==="string"){let i=t[e];i&&!i.includes("::")&&(t[e]=qk(i))}}}var Uk="0x2::coin::Coin",$k=/^0x2::coin::Coin<(.+)>$/;var Es="0x2::sui::SUI",Gk="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var et=class{static getCoinTypeArg(t){let e=t.type.match($k);return e?e[1]:null}static isSUI(t){let e=et.getCoinTypeArg(t);return e?et.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`${Uk}<${t}>`}static getFaucetCoins(t){let{events:e}=t,n=[];return e?.forEach(i=>{let{type:r}=i;if(ge(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=>{nr(i.coinAddress)===nr(t)&&n.push(i)}),n}static isSuiCoin(t){return ge(t).full_address===Es}static selectCoinObjectIdGreaterThanOrEqual(t,e,n=[]){let i=et.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=et.sortByBalance(t.filter(c=>!n.includes(c.coinObjectId))),r=et.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 c=e-o,u=a.findIndex(h=>h.balance>=c);if(u!==-1){s.push(a[u]),a.splice(u,1);break}let d=a.pop();d.balance>0&&(s.push(d),o+=d.balance)}return{selectedCoins:et.sortByBalance(s),remainingCoins:et.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 Lo=class{numerator;denominator;constructor(t,e){this.toString=()=>`${this.numerator.toString()}/${this.denominator.toString()}`,this.numerator=t,this.denominator=e}static fromDecimal(t){return Lo.fromFraction(t.toDecimalPlaces(1).mul(10).toNumber(),1e3)}static fromFraction(t,e){let n=typeof t=="number"?new gd.default(t.toString()):t,i=typeof e=="number"?new gd.default(e.toString()):e;return new Lo(n,i)}};function _d(t,{numerator:e,denominator:n},i){return i?t.mul(n.add(e)).div(n):t.mul(n).div(n.add(e))}function $c(t,e,n){return{tokenMaxA:_d(t.coinA,e,n),tokenMaxB:_d(t.coinB,e,n)}}function te(t){return J.isDecimal(t)?t:new J(t===void 0?0:t)}function Kk(t){return te(10).pow(te(t).abs())}function Ds(t){return t.data}function ng(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 ig(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Wk(t){if("reference"in t)return t.reference;let e=Ds(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:ng(t)}function Fo(t){return"objectId"in t?t.objectId:Wk(t)?.objectId??ig(t)}function Hk(t){return t.data!==void 0}function Xk(t){return t.content!==void 0}function rg(t){let e="data"in t?Ds(t):t;if(!(!e||!Xk(e)||e.content.dataType!=="moveObject"))return e.content}function vd(t){return rg(t)?.type}function Uo(t){let e=Hk(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":vd(t):e?.type}function kd(t){return Ds(t)?.previousTransaction}function Zk(t){return Ds(t)?.owner}function Jk(t){let e=Ds(t)?.display;return e||{data:null,error:null}}function an(t){let e=rg(t)?.fields;if(e)return"fields"in e?e.fields:e}function og(t,e){let n=Kk(te(e));return Number(te(t).mul(n))}function Mn(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function Kn(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function Yk(t,e,n){let i=ge(t).name,r=ge(e).name;return`${i}-${r}[${n}]`}function hd(t){let e=vd(t),n=ge(e),i=an(t);if(i==null)throw new he(`Pool id ${Fo(t)} not exists.`,"InvalidPoolObject");let r=[];i.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:a}=s.fields,c=nt.fromX64(new fi.default(a)),u=Math.floor(c.toNumber()*60*60*24);r.push({emissions_per_second:a,coinAddress:ge(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:u})});let o={poolAddress:Fo(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:Kn(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=Yk(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function Td(t){let e=Jk(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 pd(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new he(`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=an(t);if(i){let s=vd(t),a=Zk(t);"nft"in i?(i=i.nft.fields,e.description=i.description,e.name=i.name,e.link=i.url):e=Td(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:Kn(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:Kn(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=ng(t);r&&(n.pos_object_id=r.objectId,n.position_status="Deleted");let o=ig(t);return o&&(n.pos_object_id=o,n.position_status="NotExists"),n}function sg(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:c}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=a,e.reward_growth_inside_0=c):s===1?(e.reward_amount_owed_1=a,e.reward_growth_inside_1=c):s===2&&(e.reward_amount_owed_2=a,e.reward_growth_inside_2=c)});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:Kn(BigInt(n)),tick_upper_index:Kn(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 md(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new he(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let n=an(t).value.fields.value.fields;return{objectId:Fo(t),index:Kn(BigInt(n.index.fields.bits)),sqrtPrice:new fi.default(n.sqrt_price),liquidityNet:new fi.default(n.liquidity_net.fields.bits),liquidityGross:new fi.default(n.liquidity_gross),feeGrowthOutsideA:new fi.default(n.fee_growth_outside_a),feeGrowthOutsideB:new fi.default(n.fee_growth_outside_b),rewardersGrowthOutside:n.rewards_growth_outside}}function Qk(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 he("Invalid tick fields.","InvalidTickFields");let e=Kn(BigInt(t.index.bits)),n=new fi.default(t.sqrt_price),i=new fi.default(t.liquidity_net.bits),r=new fi.default(t.liquidity_gross),o=new fi.default(t.fee_growth_outside_a),s=new fi.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 eT(t,e,n,i,r,o){let s=t.rewarder_infos,a=[];for(let c=0;c<s.length;c+=1){let u=o[c];e!==null&&(t.current_tick_index<i?u=o[c].sub(new Yr.default(e.rewardersGrowthOutside[c])):u=e.rewardersGrowthOutside[c]);let d=new Yr.default(0);n!==null&&(t.current_tick_index>=r?d=o[c].sub(new Yr.default(n.rewardersGrowthOutside[c])):d=n.rewardersGrowthOutside[c]);let h=nt.subUnderflowU128(nt.subUnderflowU128(new Yr.default(o[c]),new Yr.default(u)),new Yr.default(d));a.push(h)}return a}function Rc(t){let e=et.isSuiCoin(t.coinTypeA),n=et.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:n}}function tT(t,e){return J.ceil(te(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=nr(n.coinTypeA),a=nr(n.coinTypeB);if(n.collect_fee){let u=Se.buildCoinForAmount(e,r,BigInt(0),s,!1);r=u.remainCoins;let d=Se.buildCoinForAmount(e,o,BigInt(0),a,!1);o=d.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:n.pool_id,pos_id:n.pos_id,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB},e,u.targetCoin,d.targetCoin)}let c=[];return n.rewarder_coin_types.forEach(u=>{switch(nr(u)){case s:c.push(Se.buildCoinForAmount(e,r,BigInt(0),u,!1).targetCoin);break;case a:c.push(Se.buildCoinForAmount(e,o,BigInt(0),u,!1).targetCoin);break;default:c.push(Se.buildCoinForAmount(e,i,BigInt(0),u,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(n,e,c),e}static async adjustTransactionForGas(t,e,n,i){i.setSender(t.senderAddress);let r=et.selectCoinAssetGreaterThanOrEqual(e,n).selectedCoins;if(r.length===0)throw new he("Insufficient balance","InsufficientBalance");let o=et.calculateTotalBalance(e);if(o-n>1e9)return{fixAmount:n};let s=await t.fullClient.calculationTxGas(i);if(et.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),r.map(c=>c.coinObjectId)).selectedCoins.length===0){let c=BigInt(s)+BigInt(500);if(o-n<c){if(n-=c,n<0)throw new he("gas Insufficient balance","InsufficientBalance");let u=new Qr.TransactionBlock;return{fixAmount:n,newTx:u}}}return{fixAmount:n}}static async buildAddLiquidityFixTokenForGas(t,e,n,i){let r=await Se.buildAddLiquidityFixToken(t,e,n),{isAdjustCoinA:o}=Rc(n),s=o?n.amount_a:n.amount_b,a=await Se.adjustTransactionForGas(t,et.getCoinAssets(o?n.coinTypeA:n.coinTypeB,e),BigInt(s),r),{fixAmount:c}=a,{newTx:u}=a;if(u!==void 0){let d,h;if(o)n.amount_a=Number(c),d=Se.buildAddLiquidityFixTokenCoinInput(u,!n.fix_amount_a,c.toString(),n.slippage,n.coinTypeA,e,!1),h=Se.buildAddLiquidityFixTokenCoinInput(u,n.fix_amount_a,n.amount_b,n.slippage,n.coinTypeB,e,!1);else return n.amount_b=Number(c),d=Se.buildAddLiquidityFixTokenCoinInput(u,!n.fix_amount_a,n.amount_a,n.slippage,n.coinTypeA,e,!1),h=Se.buildAddLiquidityFixTokenCoinInput(u,n.fix_amount_a,c.toString(),n.slippage,n.coinTypeB,e,!1),n=Se.fixAddLiquidityFixTokenParams(n,i.slippage,i.curSqrtPrice),r=await Se.buildAddLiquidityFixTokenArgs(u,t,e,n,d,h),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 Qr.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(tT(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=dn.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new Os.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:c,integrate:u}=e.sdkOptions;i.is_open||(t=Se.createCollectRewarderAndFeeParams(e,t,i,n,r.remainCoins,o.remainCoins));let d=ye(c),h=i.is_open?[t.object(d.global_config_id),t.object(i.pool_id),t.pure(Mn(BigInt(i.tick_lower)).toString()),t.pure(Mn(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(Ge)]:[t.object(d.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(Ge)];return t.moveCall({target:`${u.published_at}::${no}::${a}`,typeArguments:s,arguments:h}),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,et.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 c=Se.buildCoinForAmount(r,n,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),u=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,c,u)}return r}static buildSwapTransaction(t,e,n){let i=new Qr.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=Ii.getDefaultSqrtPriceLimit(e.a2b),c=[e.coinTypeA,e.coinTypeB],{global_config_id:u}=ye(o);if(u===void 0)throw Error("clmm.config.global_config_id is undefined");let d=e.swap_partner!==void 0,h=d?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",_=d?[t.pure(u),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(Ge)]:[t.pure(u),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(Ge)];return t.moveCall({target:`${s.published_at}::${no}::${h}`,typeArguments:c,arguments:_}),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,et.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,n),BigInt(e.by_amount_in?e.amount:e.amount_limit),r),{fixAmount:a,newTx:c}=s;if(c!==void 0){c.setSender(t.senderAddress),e.by_amount_in?e.amount=a.toString():e.amount_limit=a.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,!1,!0),d=Se.buildCoinForAmount(r,n,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),h=Se.buildSwapTransactionWithoutTransferCoinArgs(t,c,e,t.sdkOptions,u,d);r=h.tx,o=h.txRes}return{tx:r,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,n){let i=new Qr.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,c=Ii.getDefaultSqrtPriceLimit(n.a2b),{global_config_id:u}=ye(s);if(u===void 0)throw Error("clmm.config.global_config_id is undefined");let d=n.swap_partner!==void 0,h=d?"swap_with_partner":"swap",_=d?dd:Cr,C=d?[e.pure(u),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(c.toString()),e.pure(!1),e.pure(Ge)]:[e.pure(u),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(c.toString()),e.pure(!1),e.pure(Ge)],D=[n.coinTypeA,n.coinTypeB],O=e.moveCall({target:`${a.published_at}::${_}::${h}`,typeArguments:D,arguments:C});if(n.by_amount_in){let B=n.a2b?n.coinTypeB:n.coinTypeA,j=n.a2b?O[1]:O[0],M=Number(n.amount_limit);this.checkCoinThreshold(t,n.by_amount_in,e,j,M,B)}return{tx:e,txRes:O}}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=_d(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=et.getCoinAssets(i,e);if(n===BigInt(0)&&s.length===0)return Se.buildZeroValueCoin(e,t,i,r);let a=et.calculateTotalBalance(s);if(a<n)throw new he(`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(et.isSuiCoin(r)){if(o){let M=t.splitCoins(t.gas,[t.pure(i.toString())]);return{targetCoin:t.makeMoveVec({objects:[M]}),remainCoins:e,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(i===0n&&n.length>1){let M=et.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.object(M.objectArray[0]),remainCoins:M.remainCoins,tragetCoinAmount:M.amountArray[0],isMintZeroCoin:!1}}let B=et.selectCoinObjectIdGreaterThanOrEqual(n,i);return{targetCoin:t.splitCoins(t.gas,[t.pure(i.toString())]),remainCoins:B.remainCoins,tragetCoinAmount:i.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let a=et.selectCoinObjectIdGreaterThanOrEqual(n,i),c=a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),u=a.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:u.map(B=>t.object(B))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),isMintZeroCoin:!1};let[d,...h]=u,_=t.object(d),C=_,D=a.amountArray.reduce((B,j)=>Number(B)+Number(j),0).toString(),O;return h.length>0&&t.mergeCoins(_,h.map(B=>t.object(B))),s&&Number(c)>Number(i)&&(C=t.splitCoins(_,[t.pure(i.toString())]),D=i.toString(),O=_),{targetCoin:C,remainCoins:a.remainCoins,originalSplitedCoin:O,tragetCoinAmount:D,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=et.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=et.calculateTotalBalance(o);if(s>=n.amountFirst)return Se.buildCoin(t,[...e],[...o],n.amountFirst,i,r);if(s<n.amountSecond)throw new he(`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 Qr.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(R=>R&&R.poolAddress),a=Number(s.reduce((R,K)=>R.add(K.amountIn),be).toString()),c=Number(s.reduce((R,K)=>R.add(K.amountOut),be).toString()),u=Math.round(n?Number(c.toString())*(1-e.priceSlippagePoint):Number(a.toString())*(1+e.priceSlippagePoint)),d=e.paths[0].coinType[0],h=e.paths[0].coinType[e.paths[0].coinType.length-1],_=Se.buildCoinForAmount(r,i,BigInt(n?a:u),d,!1,!0),C=_.originalSplitedCoin!==void 0,D=Se.buildCoinForAmount(r,i,0n,h,!1),O=await this.buildRouterBasePathReturnCoins(t,e,n,_,D,r),B=[],{toCoin:j,fromCoin:M}=O;if(r=O.tx,D.isMintZeroCoin?B.push({coinType:h,coin:j}):D.originalSplitedCoin!==void 0?r.mergeCoins(D.originalSplitedCoin,[j]):r.mergeCoins(D.targetCoin,[j]),C){let R=_?.originalSplitedCoin;r.mergeCoins(R,[M])}else B.push({coinType:d,coin:M});for(let R=0;R<B.length;R++)this.buildTransferCoin(t,r,B[R].coin,B[R].coinType,o);return r}static async buildRouterBasePathReturnCoins(t,e,n,i,r,o){let{clmm_pool:s,integrate:a}=t.sdkOptions,c=ye(s).global_config_id,u=e.paths.filter(R=>R&&R.poolAddress),d=Number(u.reduce((R,K)=>R.add(K.amountIn),be).toString()),h=Number(u.reduce((R,K)=>R.add(K.amountOut),be).toString()),_=Math.round(n?Number(h.toString())*(1-e.priceSlippagePoint):Number(d.toString())*(1+e.priceSlippagePoint)),C=e.paths[0].coinType[0],D=e.paths[0].coinType[e.paths[0].coinType.length-1],O=i.targetCoin,B;r.isMintZeroCoin||r.originalSplitedCoin!==void 0?B=r.targetCoin:B=Se.callMintZeroValueCoin(o,D);let j=e.partner==="",M=j?Cr:dd;for(let R of u)if(R.poolAddress.length===1){let K=R.a2b[0],X={amount:Number(R.amountIn.toString()),amountLimit:_,poolCoinA:R.a2b[0]?C:D,poolCoinB:R.a2b[0]?D:C},Y=j?"swap":"swap_with_partner",oe=K?O:B,$=K?B:O,ne=n?R.amountIn.toString():R.amountOut.toString(),G=Ii.getDefaultSqrtPriceLimit(K).toString(),W=j?[o.object(c),o.object(R.poolAddress[0]),oe,$,o.pure(K),o.pure(n),o.pure(ne),o.pure(G),o.pure(!1),o.object(Ge)]:[o.object(c),o.object(R.poolAddress[0]),o.pure(e.partner),oe,$,o.pure(K),o.pure(n),o.pure(ne),o.pure(G),o.pure(!1),o.object(Ge)],I=[X.poolCoinA,X.poolCoinB],N=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${M}::${Y}`,typeArguments:I,arguments:W});O=K?N[0]:N[1],B=K?N[1]:N[0]}else{let K=n?R.amountIn:R.rawAmountLimit[0],X=n?0:R.amountOut,Y="";R.a2b[0]?R.a2b[1]?Y="swap_ab_bc":Y="swap_ab_cb":R.a2b[1]?Y="swap_ba_bc":Y="swap_ba_cb",j||(Y=`${Y}_with_partner`);let oe=Ii.getDefaultSqrtPriceLimit(R.a2b[0]),$=Ii.getDefaultSqrtPriceLimit(R.a2b[1]),ne=j?[o.object(c),o.object(R.poolAddress[0]),o.object(R.poolAddress[1]),O,B,o.pure(n),o.pure(K.toString()),o.pure(X.toString()),o.pure(oe.toString()),o.pure($.toString()),o.object(Ge)]:[o.object(c),o.object(R.poolAddress[0]),o.object(R.poolAddress[1]),o.pure(e.partner),O,B,o.pure(n),o.pure(K.toString()),o.pure(X.toString()),o.pure(oe.toString()),o.pure($.toString()),o.object(Ge)],G=[R.coinType[0],R.coinType[1],R.coinType[2]],W=o.moveCall({target:`${a.published_at}::${M}::${Y}`,typeArguments:G,arguments:ne});O=W[0],B=W[1]}return this.checkCoinThreshold(t,n,o,B,_,D),{fromCoin:O,toCoin:B,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 c,u,d=e.splitPaths.some(h=>h.basePaths.some(_=>_.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!d){let h=[];for(let D of e.splitPaths){let O=[],B=[],j=[],M=[];for(let K=0;K<D.basePaths.length;K+=1){let X=D.basePaths[K];O.push(X.direction),B.push(X.poolAddress),j.push(new Os.default(X.inputAmount.toString())),K===0?M.push(X.fromCoin,X.toCoin):M.push(X.toCoin)}let R={amountIn:new Os.default(D.inputAmount.toString()),amountOut:new Os.default(D.outputAmount.toString()),poolAddress:B,a2b:O,rawAmountLimit:j,isExceed:!1,coinType:M};h.push(R)}let _={paths:h,partner:r,priceSlippagePoint:o},C=await this.buildRouterBasePathReturnCoins(t,_,e.byAmountIn,n,i,s);c=C.fromCoin,u=C.toCoin,s=C.tx}else{let h=Math.round(e.outputAmount*(1-o));c=n.targetCoin,i.isMintZeroCoin||i.originalSplitedCoin!==void 0?u=i.targetCoin:u=Se.callMintZeroValueCoin(s,e.toCoin);let _=!1,C;if(d){let[D,O]=Wm.createAccountCap(a,t.sdkOptions,s);s=O,C=D,_=!0}for(let D=0;D<e.splitPaths.length;D+=1){let O=e.splitPaths[D],B;for(let j=0;j<O.basePaths.length;j+=1){let M=O.basePaths[j];if(M.label==="Deepbook")if(j===0)if(O.basePaths.length===1){let R=this.buildDeepbookBasePathTx(t,M,s,C,c,u,!1);c=R.from,u=R.to}else{B=Se.callMintZeroValueCoin(s,M.toCoin);let R=this.buildDeepbookBasePathTx(t,M,s,C,c,B,!1);c=R.from,B=R.to}else{let R=this.buildDeepbookBasePathTx(t,M,s,C,B,u,!0);B=R.from,u=R.to}if(M.label==="Cetus")if(j===0)if(O.basePaths.length===1){let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,c,u,!1,r);c=R.from,u=R.to}else{B=Se.callMintZeroValueCoin(s,M.toCoin);let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,c,B,!1,r);c=R.from,B=R.to}else{let R=this.buildClmmBasePathTx(t,M,s,e.byAmountIn,B,u,!0,r);B=R.from,u=R.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${$m}::send_coin`,typeArguments:[M.fromCoin],arguments:[B,s.pure(a)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,u,h,e.toCoin),_&&(s=Wm.deleteAccountCapByObject(C,t.sdkOptions,s))}return{fromCoin:c,toCoin:u,tx:s}}static async buildAggregatorSwapTransaction(t,e,n,i,r,o){let s=new Qr.TransactionBlock,a=e.byAmountIn?Math.round(e.outputAmount*(1-r)):Math.round(e.inputAmount*(1+r)),c=Se.buildCoinForAmount(s,n,e.byAmountIn?BigInt(e.inputAmount):BigInt(a),e.fromCoin,!1,!0),u=c.originalSplitedCoin!=null,d=Se.buildCoinForAmount(s,n,0n,e.toCoin,!1),h=await this.buildAggregatorSwapReturnCoins(t,e,c,d,i,r,s,o),{fromCoin:_,toCoin:C}=h;s=h.tx;let D=[];if(d.isMintZeroCoin?D.push({coinType:e.toCoin,coin:C}):d.originalSplitedCoin!=null?s.mergeCoins(d.originalSplitedCoin,[C]):s.mergeCoins(d.targetCoin,[C]),u){let O=c.originalSplitedCoin;s.mergeCoins(O,[_])}else D.push({coinType:e.fromCoin,coin:_});for(let O=0;O<D.length;O++)this.buildTransferCoin(t,s,D[O].coin,D[O].coinType,o);return s}static checkCoinThreshold(t,e,n,i,r,o){e&&n.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Cr}::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,c=e.direction?o:r,u=[n.object(e.poolAddress),i,n.pure(e.inputAmount),n.pure(0),n.pure(e.direction),a,c,n.pure(s),n.object(Ge)],d=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],h=n.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:d,arguments:u});return r=e.direction?h[0]:h[1],o=e.direction?h[1]:h[0],{from:r,to:o,tx:n}}static buildClmmBasePathTx(t,e,n,i,r,o,s,a){let{clmm_pool:c,integrate:u}=t.sdkOptions,d=ye(c).global_config_id,h=e.direction?r:o,_=e.direction?o:r,C=a==="",D=C?Cr:dd,O=C?"swap":"swap_with_partner",B=i?e.inputAmount.toString():e.outputAmount.toString(),j=Ii.getDefaultSqrtPriceLimit(e.direction),M=C?[n.object(d),n.object(e.poolAddress),h,_,n.pure(e.direction),n.pure(i),n.pure(B),n.pure(j.toString()),n.pure(s),n.object(Ge)]:[n.object(d),n.object(e.poolAddress),n.pure(a),h,_,n.pure(e.direction),n.pure(i),n.pure(B),n.pure(j.toString()),n.pure(s),n.object(Ge)],R=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],K=n.moveCall({target:`${u.published_at}::${D}::${O}`,typeArguments:R,arguments:M});return h=K[0],_=K[1],r=e.direction?h:_,o=e.direction?_:h,{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}::${$m}::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)}},Ze=Se;hk(Ze,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function Bn(t){return!(!t.startsWith("0x")||t.length!==66)}var jo=new Sn.default(1e9),Wm=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}::${bk}::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}::${fd}::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}::${fd}::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:fd}}});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 Bc.TransactionBlock,a=[],c=[n,i],u=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ge)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:u,typeArguments:c});let h=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(_=>ge(_.type).name==="BookStatus");if(h.length===0)return a;for(let _=0;_<h[0].parsedJson.depths.length;_++){let C=h[0].parsedJson.price[_],D=h[0].parsedJson.depths[_],O={price:parseInt(C,10),quantity:parseInt(D,10)};a.push(O)}return a}static async getPoolBids(t,e,n,i){let{simulationAccount:r}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new Bc.TransactionBlock,a=[],c=[n,i],u=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ge)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:u,typeArguments:c});let h=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:r.address})).events?.filter(_=>ge(_.type).name==="BookStatus");if(h.length===0)return a;for(let _=0;_<h[0].parsedJson.depths.length;_++){let C=h[0].parsedJson.price[_],D=h[0].parsedJson.depths[_],O={price:parseInt(C,10),quantity:parseInt(D,10)};a.push(O)}return a}static async preSwap(t,e,n,i){let r=!1,o=be,s=new Sn.default(i),a=be,c=new Sn.default(i);if(n){let u=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);u===null&&(r=!0),u=u.sort((d,h)=>h.price-d.price);for(let d=0;d<u.length;d+=1){let h=new Sn.default(u[d].quantity),_=new Sn.default(u[d].price),C=h.mul(new Sn.default(_)).mul(new Sn.default(e.takerFeeRate)).div(jo).div(jo);if(s.gt(h))s=s.sub(h),o=o.add(h.mul(_).div(jo).sub(C)),a=a.add(C);else{let D=s.mul(new Sn.default(u[d].price)).div(jo),O=D.mul(new Sn.default(e.takerFeeRate)).div(jo);o=o.add(D.sub(O)),s=s.sub(s),a=a.add(O)}if(s.eq(be))break}}else{let u=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);u===null&&(r=!0);for(let d=0;d<u.length;d+=1){let h=new Sn.default(u[d].price).mul(new Sn.default(u[d].quantity)).div(new Sn.default(1e9)),_=h.mul(new Sn.default(e.takerFeeRate)).div(jo),C=h.add(_);if(s.gt(h))o=o.add(new Sn.default(u[d].quantity)),s=s.sub(C),a=a.add(_);else{let D=new Sn.default(u[d].quantity).div(new Sn.default(e.lotSize)),O=C.div(D),B=s.div(O);o=o.add(B.muln(e.lotSize)),s=s.sub(B.mul(O)),a=a.add(B.div(D).mul(_))}if(s.eq(be))break}}return{poolAddress:e.poolID,estimatedAmountIn:c.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 Bc.TransactionBlock,c=await this.getAccountCap(t),u;if(c===""){let X=this.createAccountCap(t.senderAddress,t.sdkOptions,a),Y=X[0];a=X[1],u=Y}else u=a.pure(c);let d=await t.getOwnerCoinAssets(t.senderAddress),_=Ze.buildCoinForAmount(a,d,BigInt(o),n,!1)?.targetCoin,D=Ze.buildCoinForAmount(a,d,BigInt(o),i,!1)?.targetCoin,O=[n,i],B=[a.pure(e),u,a.pure(o),a.pure(0),a.pure(r),_,D,a.pure(Ge)];a.moveCall({target:`${s.published_at}::${vk}::swap`,arguments:B,typeArguments:O});let{simulationAccount:j}=t.sdkOptions,R=(await t.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:j.address})).events?.filter(X=>ge(X.type).name==="DeepbookSwapEvent");if(R.length===0)return null;let K=R[0].parsedJson;return{poolAddress:K.pool,estimatedAmountIn:K.amount_in,estimatedAmountOut:K.amount_out,aToB:K.atob}}},rT=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 he(`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=[],c=[];if(s!==void 0&&a.push(...s),a.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`})).data.forEach(h=>{let _=h.parsedJson;_&&a.push({poolAddress:_.pool_id,tickSpacing:_.tick_spacing,coinTypeA:ge(_.coin_type_a).full_address,coinTypeB:ge(_.coin_type_b).full_address})}),this.updateCache(o,a,tt)}catch(d){console.log("getPoolImmutables",d)}let u=t.length>0;for(let d=0;d<a.length;d+=1){let h=a[d];u&&!t.includes(h.poolAddress)||!u&&(d<e||d>=e+n)||c.push(h)}return c}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 he(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let a=hd(s);i.push(a);let c=`${a.poolAddress}_getPoolObject`;this.updateCache(c,a,tt)}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`,c=await this._sdk.fullClient.queryEventsByPage({MoveEventType:a},t);r.hasNextPage=c.hasNextPage,r.nextCursor=c.nextCursor,c.data.forEach(u=>{let d=u.parsedJson;if(d){let h={poolAddress:d.pool_id,tickSpacing:d.tick_spacing,coinTypeA:ge(d.coin_type_a).full_address,coinTypeB:ge(d.coin_type_b).full_address};i.push(h)}})}catch(a){console.log("getPoolImmutables",a)}return r.data=i,o&&this.updateCache(`${n}_getPoolImmutables`,i,tt),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 he(`getPoolWithPages error code: ${r.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=hd(r);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,tt)}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 he(`getPool error code: ${r.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=hd(r);return this.updateCache(n,o),o}async creatPoolsTransactionPayload(t){for(let n of t)if(Km((0,xs.normalizeSuiAddress)(n.coinTypeA),(0,xs.normalizeSuiAddress)(n.coinTypeB))){let i=n.coinTypeB;n.coinTypeB=n.coinTypeA,n.coinTypeA=i}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(Km((0,xs.normalizeSuiAddress)(t.coinTypeA),(0,xs.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=kd(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(c=>{let u=c.parsedJson;if(c.type)switch(ge(c.type).full_address){case`${e}::config::InitConfigEvent`:a.global_config_id=u.global_config_id,a.admin_cap_id=u.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=u.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:a.global_vault_id=u.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:a.partners_id=u.partners_id;break;default:break}}),this.updateCache(n,a,tt)),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,tt),r}async creatPool(t){let e=new No.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=ye(i),o=r.global_config_id,s=r.pools_id;return t.forEach(a=>{let c=[e.object(o),e.object(s),e.pure(a.tick_spacing.toString()),e.pure(a.initialize_sqrt_price),e.pure(a.uri),e.object(Ge)];e.moveCall({target:`${n.published_at}::${Dc}::create_pool`,typeArguments:[a.coinTypeA,a.coinTypeB],arguments:c})}),e}async creatPoolAndAddLiquidity(t){if(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new No.TransactionBlock,{integrate:n,clmm_pool:i}=this.sdk.sdkOptions,r=ye(i),o=r.global_config_id,s=r.pools_id,a=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),c=Ze.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,a,!1),u=Ze.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,a,!1),d=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),c.targetCoin,u.targetCoin,e.pure(Mn(BigInt(t.tick_lower)).toString()),e.pure(Mn(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(Ge)];return e.moveCall({target:`${n.published_at}::${no}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:d}),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 No.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Zn}::fetch_ticks`,arguments:s,typeArguments:r}),!Bn(n.address))throw new he("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 he(`getTicks error code: ${a.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return a.events?.forEach(c=>{ge(c.type).name==="FetchTicksResultEvent"&&c.parsedJson.ticks.forEach(u=>{i.push(Qk(u))})}),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 No.TransactionBlock,c=[a.object(t.pool_id),a.pure(r,"u64"),a.pure(o.toString(),"u64")];if(a.moveCall({target:`${e.published_at}::${Zn}::fetch_positions`,arguments:c,typeArguments:s}),!Bn(n.address))throw new he("this config simulationAccount is not set right","InvalidSimulateAccount");let u=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:a,sender:n.address});if(u.error!=null)throw new he(`fetch position reward error code: ${u.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let d=[];if(u?.events?.forEach(h=>{ge(h.type).name==="FetchPositionsEvent"&&h.parsedJson.positions.forEach(_=>{let C=sg(_);d.push(C)})}),i.push(...d),d.length<o)break;r=[d[d.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=>{ge(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 he(`getTicksByRpc error code: ${i.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let r=md(i);r!=null&&e.push(r)}return e}async getTickDataByIndex(t,e){let n={type:"u64",value:Mn(BigInt(Pk(e).toString())).toString()},i=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:n});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new he(`get tick by index: ${e} error: ${i.error}`,"InvalidTickIndex");return md(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 he(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return md(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 he(`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 he(`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 he(`get coin by object id: ${a.data.objectId} error: ${a.error}`,"InvalidParnterRefFeeFields");let c={coinAddress:a.data.content.fields.name,coinObjectId:a.data.objectId,balance:BigInt(a.data.content.fields.value)};o.push(c)}),o}async claimPartnerRefFeePayload(t,e,n){let i=new No.TransactionBlock,{clmm_pool:r}=this.sdk.sdkOptions,{global_config_id:o}=ye(r),s=[n],a=[i.object(o),i.object(t),i.object(e)];return i.moveCall({target:`${r.published_at}::${wk}::claim_ref_fee`,arguments:a,typeArguments:s}),i}updateCache(t,e,n=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},oT=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(ge(o.data.type).full_address===this.buildPositionType()){let a=pd(o),c=`${a.pos_object_id}_getPositionList`;this.updateCache(c,a,tt),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=pd(i),this.updateCache(e,n,tt)}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=pd(r);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,tt)}),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=an(n.data).value.fields.value;return sg(r)}catch(n){console.log(n);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new eo.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(ye(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId)];r.moveCall({target:`${n.published_at}::${Zn}::fetch_position_fees`,arguments:d,typeArguments:u})}if(!Bn(i.address))throw new he("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 he(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(c=>ge(c.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let c=0;c<s.length;c+=1){let{parsedJson:u}=s[c],d={feeOwedA:new wd.default(u.fee_owned_a),feeOwedB:new wd.default(u.fee_owned_b),position_id:u.position_id};a.push(d)}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(!Bn(this._sdk.senderAddress))throw new he("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}=Rc(t);if(t=t,t.fix_amount_a&&i||!t.fix_amount_a&&r)return await Ze.buildAddLiquidityFixTokenForGas(this._sdk,n,t,e)}return Ze.buildAddLiquidityFixToken(this._sdk,n,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:n}=this._sdk.sdkOptions;if(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let i=Mn(BigInt(t.tick_lower)).toString(),r=Mn(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new eo.TransactionBlock,a=!(0,ag.isValidSuiObjectId)(t.pos_id),c=BigInt(t.max_amount_a),u=BigInt(t.max_amount_b),d=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),h=Ze.buildCoinForAmount(s,d,c,t.coinTypeA,!1),_=Ze.buildCoinForAmount(s,d,u,t.coinTypeB,!1);return a?s.moveCall({target:`${e.published_at}::${no}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(ye(n).global_config_id),s.object(t.pool_id),s.pure(i),s.pure(r),h.targetCoin,_.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ge)]}):(s=Ze.createCollectRewarderAndFeeParams(this._sdk,s,t,d,h.remainCoins,_.remainCoins),s.moveCall({target:`${e.published_at}::${no}::add_liquidity`,typeArguments:o,arguments:[s.object(ye(n).global_config_id),s.object(t.pool_id),s.object(t.pos_id),h.targetCoin,_.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ge)]})),s}async removeLiquidityTransactionPayload(t){if(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i="remove_liquidity",r=new eo.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);r=Ze.createCollectRewarderAndFeeParams(this._sdk,r,t,s);let a=[r.object(ye(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(Ge)];return r.moveCall({target:`${n.published_at}::${Dc}::${i}`,typeArguments:o,arguments:a}),r}async closePositionTransactionPayload(t){if(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new eo.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return i=Ze.createCollectRewarderAndFeeParams(this._sdk,i,t,o),i.moveCall({target:`${n.published_at}::${Dc}::close_position`,typeArguments:r,arguments:[i.object(ye(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(Ge)]}),i}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:n}=this.sdk.sdkOptions,i=new eo.TransactionBlock,r=[t.coinTypeA,t.coinTypeB],o=Mn(BigInt(t.tick_lower)).toString(),s=Mn(BigInt(t.tick_upper)).toString(),a=[i.pure(ye(e).global_config_id),i.pure(t.pool_id),i.pure(o),i.pure(s)];return i.moveCall({target:`${n.published_at}::${Dc}::open_position`,typeArguments:r,arguments:a}),i}async collectFeeTransactionPayload(t){if(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),n=new eo.TransactionBlock,i=Ze.buildCoinForAmount(n,e,BigInt(0),t.coinTypeA,!1),r=Ze.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(ye(r).global_config_id),e.object(t.pool_id),e.object(t.pos_id),n,i];return e.moveCall({target:`${o.published_at}::${no}::collect_fee`,typeArguments:s,arguments:a}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!Bn(this._sdk.senderAddress))throw new he("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(ge(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=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},sT=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[be,be,be]}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=nt.fromX64(new yt.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 yt.default(i)))return n;let r=e.div(new yt.default(1e3)).sub(new yt.default(i)).add(new yt.default(15)),o=n.rewarder_infos;for(let s=0;s<o.length;s+=1){let a=o[s],c=nt.checkMulDivFloor(r,new yt.default(a.emissions_per_second),new yt.default(n.liquidity),128);this.growthGlobal[s]=new yt.default(a.growth_global).add(new yt.default(c))}return n}async posRewardersAmount(t,e,n){let i=Date.parse(new Date().toString()),r=await this.updatePoolRewarder(t,new yt.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),c=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(r,o,a,c)}async poolRewardersAmount(t,e){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(e,new yt.default(n)),r=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(i.ticks_handle,r),s=[be,be,be];for(let a=0;a<r.length;a+=1){let c=await this.posRewardersAmountInternal(i,r[a],o[0][a],o[1][a]);for(let u=0;u<3;u+=1)s[u]=s[u].add(c[u].amount_owed)}return s}posRewardersAmountInternal(t,e,n,i){let r=e.tick_lower_index,o=e.tick_upper_index,s=eT(t,n,i,r,o,this.growthGlobal),a=[],c=[];if(s.length>0){let u=nt.subUnderflowU128(s[0],new yt.default(e.reward_growth_inside_0));u.gt(new yt.default("3402823669209384634633745948738404"))&&(u=Ui);let d=nt.checkMulShiftRight(new yt.default(e.liquidity),u,64,128);a.push(s[0]),c.push({amount_owed:new yt.default(e.reward_amount_owed_0).add(d),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let u=nt.subUnderflowU128(s[1],new yt.default(e.reward_growth_inside_1));u.gt(new yt.default("3402823669209384634633745948738404"))&&(u=Ui);let d=nt.checkMulShiftRight(new yt.default(e.liquidity),u,64,128);a.push(s[1]),c.push({amount_owed:new yt.default(e.reward_amount_owed_1).add(d),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let u=nt.subUnderflowU128(s[2],new yt.default(e.reward_growth_inside_2));u.gt(new yt.default("3402823669209384634633745948738404"))&&(u=Ui);let d=nt.checkMulShiftRight(new yt.default(e.liquidity),u,64,128);a.push(s[2]),c.push({amount_owed:new yt.default(e.reward_amount_owed_2).add(d),coin_address:t.rewarder_infos[2].coinAddress})}return c}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 Mc.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(ye(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId)];r.moveCall({target:`${n.published_at}::${Zn}::fetch_position_fees`,arguments:d,typeArguments:u})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:r,sender:i.address})).events?.filter(c=>ge(c.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let a=[];for(let c=0;c<s.length;c+=1){let{parsedJson:u}=s[c],d={feeOwedA:new yt.default(u.fee_owned_a),feeOwedB:new yt.default(u.fee_owned_b),position_id:u.position_id};a.push(d)}return a}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:n,simulationAccount:i}=this.sdk.sdkOptions,r=new Mc.TransactionBlock;for(let c of t){let u=[c.coinTypeA,c.coinTypeB],d=[r.object(ye(e).global_config_id),r.object(c.poolAddress),r.pure(c.positionId),r.object(Ge)];r.moveCall({target:`${n.published_at}::${Zn}::fetch_position_rewards`,arguments:d,typeArguments:u})}if(!Bn(i.address))throw new he(`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 he(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(c=>ge(c.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new he("valueData.length !== params.pools.length");let a=[];for(let c=0;c<s.length;c+=1){let u={poolAddress:t[c].poolAddress,positionId:t[c].positionId,rewarderAmountOwed:[]};for(let d=0;d<t[c].rewarderInfo.length;d+=1)u.rewarderAmountOwed.push({amount_owed:new yt.default(s[c].parsedJson.data[d]),coin_address:t[c].rewarderInfo[d].coinAddress});a.push(u)}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=[be,be,be];if(o!=null)for(let a of o)for(let c=0;c<a.rewarderAmountOwed.length;c+=1)s[c]=s[c].add(a.rewarderAmountOwed[c].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(!Bn(this._sdk.senderAddress))throw new he("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),n=new Mc.TransactionBlock;return n=Ze.createCollectRewarderAndFeeParams(this._sdk,n,t,e),n}createCollectRewarderPaylod(t,e,n){let{clmm_pool:i,integrate:r}=this.sdk.sdkOptions,o=ye(i),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((a,c)=>{e&&e.moveCall({target:`${r.published_at}::${no}::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[c],e.object(Ge)]})}),e}};function Ec(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var aT=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new io.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}=Ec(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 io.GraphVertex(r.base),s=this.graph.getVertexByKey(r.quote)??new io.GraphVertex(r.quote);this.graph.addEdge(new io.GraphEdge(o,s));let a=this._coinAddressMap.get(r.base),c=this._coinAddressMap.get(r.quote);if(a!=null&&c!=null){let u=Ec(r.base,r.quote).pair;this.poolAddressMap.set(u,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=Ec(t,e).pair,r=this.poolAddressMap.get(i);if(r!=null){for(let[a,c]of r.entries())if(c===n)return a*100}let o=Ec(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[a,c]of s.entries())if(c===n)return a*100}return 0}async price(t,e,n,i,r,o,s){let a=this.tokenInfo(t),c=this.tokenInfo(e);if(a===void 0||c===void 0)throw new he("From/To coin is undefined","InvalidCoin");let u=this.graph.getVertexByKey(a.address),d=this.graph.getVertexByKey(c.address),h=this.graph.findAllPath(u,d),_=Array.from(h);if(_.length===0)throw new he("No find valid path in coin graph","NotFoundPath");let C=[];for(let G=0;G<_.length;G+=1){let W=_[G];if(W.length>3)continue;let I=[],N=[],l=[],f=[];for(let w=0;w<W.length-1;w+=1){let k=W[w].value.toString(),g=W[w+1].value.toString(),m=this.getPoolAddressMapAndDirection(k,g),b=m?.addressMap,y=m?.direction;b!=null&&y!=null&&(N.push(y),I.push(k),I.push(g),b.forEach(p=>{w===0?l.push(p):f.push(p)}))}for(let w of l)if(f.length>0)for(let k of f){let g={stepNums:2,poolAB:w,poolBC:k,a2b:N[0],b2c:N[1],amount:n,byAmountIn:i,coinTypeA:I[0],coinTypeB:I[1],coinTypeC:I[3]};C.push(g)}else{let k={stepNums:1,poolAB:w,poolBC:void 0,a2b:N[0],b2c:void 0,amount:n,byAmountIn:i,coinTypeA:I[0],coinTypeB:I[1],coinTypeC:void 0};C.push(k)}}let D=C.filter(G=>G.stepNums===1),O=C.filter(G=>G.stepNums!==1),B=[];try{B=await this.getPoolWithTVL()}catch{B=[]}if(B.length>0){let G=new Map(B.map(W=>[W.poolAddress,W]));O.sort((W,I)=>{let N=0,l=0;if(G.has(W.poolAB)&&G.has(W.poolBC)){let f=G.get(W.poolAB),w=G.get(W.poolBC);N=Math.min(f.tvl,w.tvl)}if(G.has(I.poolAB)&&G.has(I.poolBC)){let f=G.get(I.poolAB),w=G.get(I.poolBC);l=Math.min(f.tvl,w.tvl)}return l-N})}if(C=[...D,...O],C.length===0){if(s!=null){let G=await this.sdk.Swap.preSwapWithMultiPool(s),W={amountIn:new ni.default(G.estimatedAmountIn),amountOut:new ni.default(G.estimatedAmountOut),poolAddress:[G.poolAddress],a2b:[G.aToB],rawAmountLimit:i?[G.estimatedAmountOut]:[G.estimatedAmountIn],isExceed:G.isExceed,coinType:[t,e]},I={paths:[W],partner:o,priceSlippagePoint:r};return{amountIn:new ni.default(G.estimatedAmountIn),amountOut:new ni.default(G.estimatedAmountOut),paths:[W],a2b:G.aToB,b2c:void 0,byAmountIn:i,isExceed:G.isExceed,targetSqrtPrice:[G.estimatedEndSqrtPrice],currentSqrtPrice:[G.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:I}}throw new he("No parameters available for service downgrade","NoDowngradeNeedParams")}let j=await this.preRouterSwapA2B2C(C.slice(0,16));if(j==null){if(s!=null){let W=await this.sdk.Swap.preSwapWithMultiPool(s),I={amountIn:new ni.default(W.estimatedAmountIn),amountOut:new ni.default(W.estimatedAmountOut),poolAddress:[W.poolAddress],a2b:[W.aToB],rawAmountLimit:i?[W.estimatedAmountOut]:[W.estimatedAmountIn],isExceed:W.isExceed,coinType:[t,e]},N={paths:[I],partner:o,priceSlippagePoint:r};return{amountIn:new ni.default(W.estimatedAmountIn),amountOut:new ni.default(W.estimatedAmountOut),paths:[I],a2b:W.aToB,b2c:void 0,byAmountIn:i,isExceed:W.isExceed,targetSqrtPrice:[W.estimatedEndSqrtPrice],currentSqrtPrice:[W.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:N}}return{amountIn:be,amountOut:be,paths:[],a2b:!1,b2c:!1,byAmountIn:i,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let M=j.index,R=C[M].poolBC!=null?[C[M].poolAB,C[M].poolBC]:[C[M].poolAB],K=i?[j.amountMedium,j.amountOut]:[j.amountIn,j.amountMedium],X=[];X.push(C[M].a2b),j.stepNum>1&&X.push(C[M].b2c);let Y=[];Y.push(C[M].coinTypeA),Y.push(C[M].coinTypeB),j.stepNum>1&&Y.push(C[M].coinTypeC);let oe={amountIn:j.amountIn,amountOut:j.amountOut,poolAddress:R,a2b:X,rawAmountLimit:K,isExceed:j.isExceed,coinType:Y},$={paths:[oe],partner:o,priceSlippagePoint:r};return{amountIn:j.amountIn,amountOut:j.amountOut,paths:[oe],a2b:C[M].a2b,b2c:j.stepNum>1?C[M].b2c:void 0,byAmountIn:i,isExceed:j.isExceed,targetSqrtPrice:j.targetSqrtPrice,currentSqrtPrice:j.currentSqrtPrice,coinTypeA:C[M].coinTypeA,coinTypeB:C[M].coinTypeB,coinTypeC:j.stepNum>1?C[M].coinTypeC:void 0,createTxParams:$}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new cg.TransactionBlock;for(let h of t)if(h.stepNums>1){let _=[i.object(h.poolAB),i.object(h.poolBC),i.pure(h.a2b),i.pure(h.b2c),i.pure(h.byAmountIn),i.pure(h.amount.toString())],C=[];h.a2b?C.push(h.coinTypeA,h.coinTypeB):C.push(h.coinTypeB,h.coinTypeA),h.b2c?C.push(h.coinTypeB,h.coinTypeC):C.push(h.coinTypeC,h.coinTypeB),i.moveCall({target:`${e.published_at}::${Cr}::calculate_router_swap_result`,typeArguments:C,arguments:_})}else{let _=[i.pure(h.poolAB),i.pure(h.a2b),i.pure(h.byAmountIn),i.pure(h.amount.toString())],C=h.a2b?[h.coinTypeA,h.coinTypeB]:[h.coinTypeB,h.coinTypeA];i.moveCall({target:`${e.published_at}::${yk}::get_expect_swap_result`,arguments:_,typeArguments:C})}if(!Bn(n.address))throw new he("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(h=>ge(h.type).name==="CalculatedRouterSwapResultEvent"||ge(h.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?be:qo,a=0;for(let h=0;h<o.length;h+=1)if(!o[h].parsedJson.data.is_exceed)if(t[0].byAmountIn){let _=new ni.default(o[h].parsedJson.data.amount_out);_.gt(s)&&(a=h,s=_)}else{let _=t[h].stepNums>1?new ni.default(o[h].parsedJson.data.amount_in):new ni.default(o[h].parsedJson.data.amount_in).add(new ni.default(o[h].parsedJson.data.fee_amount));_.lt(s)&&(a=h,s=_)}let c=[],u=[];return t[a].stepNums>1?(u.push(o[a].parsedJson.data.target_sqrt_price_ab,o[a].parsedJson.data.target_sqrt_price_cd),c.push(o[a].parsedJson.data.current_sqrt_price_ab,o[a].parsedJson.data.current_sqrt_price_cd)):(u.push(o[a].parsedJson.data.after_sqrt_price),c.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:u,currentSqrtPrice:c,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 he(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let i;try{i=await n.json()}catch{throw new he(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(i.code!==200)throw new he(`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 cT=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=te(0);return t.forEach(n=>{let i=n.basePaths.length;if(i>0){let r=n.basePaths[0],o=r.label==="Cetus"?new J(r.feeRate).div(10**6):new J(r.feeRate).div(10**9),s=te(r.inputAmount).div(10**r.fromDecimal).mul(o);if(e=e.add(s),i>1){let a=n.basePaths[1],c=r.direction?r.currentPrice:new J(1).div(r.currentPrice),u=a.direction?a.currentPrice:new J(1).div(a.currentPrice),d=a.label==="Cetus"?new J(a.feeRate).div(10**6):new J(a.feeRate).div(10**9),_=te(a.outputAmount).div(10**a.toDecimal).mul(d).div(c.mul(u));e=e.add(_)}}}),e.toString()}calculateSwapPriceImpact(t){let e=te(0);return t.forEach(n=>{let i=n.basePaths.length;if(i===1){let r=n.basePaths[0],o=te(r.outputAmount).div(10**r.toDecimal),s=te(r.inputAmount).div(10**r.fromDecimal),a=o.div(s),c=r.direction?new J(r.currentPrice):new J(1).div(r.currentPrice);e=e.add(this.calculateSingleImpact(a,c))}if(i===2){let r=n.basePaths[0],o=n.basePaths[1],s=r.direction?new J(r.currentPrice):new J(1).div(r.currentPrice),a=o.direction?new J(o.currentPrice):new J(1).div(o.currentPrice),c=s.mul(a),u=new J(o.outputAmount).div(10**o.toDecimal),d=new J(r.inputAmount).div(10**r.fromDecimal),h=u.div(d);e=e.add(this.calculateSingleImpact(h,c))}}),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 yd.TransactionBlock,r=[t.coinTypeA,t.coinTypeB];for(let u=0;u<t.poolAddresses.length;u+=1){let d=[i.pure(t.poolAddresses[u]),i.pure(t.a2b),i.pure(t.byAmountIn),i.pure(t.amount)];i.moveCall({target:`${e.published_at}::${Zn}::calculate_swap_result`,arguments:d,typeArguments:r})}if(!Bn(n.address))throw new he("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 he(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(u=>ge(u.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new he("valueData.length !== params.pools.length","ParamsLengthNotEqual");let a=t.byAmountIn?be:qo,c=0;for(let u=0;u<s.length;u+=1)if(!s[u].parsedJson.data.is_exceed)if(t.byAmountIn){let d=new to.default(s[u].parsedJson.data.amount_out);d.gt(a)&&(c=u,a=d)}else{let d=new to.default(s[u].parsedJson.data.amount_out);d.lt(a)&&(c=u,a=d)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[c],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[c].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:n}=this.sdk.sdkOptions,i=new yd.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}::${Zn}::calculate_swap_result`,arguments:o,typeArguments:r}),!Bn(n.address))throw new he("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 he(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let a=s.events?.filter(c=>ge(c.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 to.default(e.amount_in).add(new to.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 to.default(n.amount_in).add(new to.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=_k(e),i;t.a2b?i=t.swapTicks.sort((h,_)=>_.index-h.index):i=t.swapTicks.sort((h,_)=>h.index-_.index);let r=Mk(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=Ii.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 c=ve.sqrtPriceX64ToPrice(n.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),u=ve.sqrtPriceX64ToPrice(r.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),d=Math.abs(c-u)/c*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:d}}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}=Rc(t);if(t.a2b&&i||!t.a2b&&r)return await Ze.buildSwapTransactionForGas(this._sdk,t,n,e)}return Ze.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}=Rc(t);if(t.a2b&&i||!t.a2b&&r)return await Ze.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,n,e)}return Ze.buildSwapTransactionWithoutTransferCoins(this.sdk,t,n)}},uT=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(nr(s)===nr(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 c=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(c){let u={id:c.id,name:c.name,symbol:c.symbol,official_symbol:c.symbol,coingecko_id:"",decimals:c.decimals,project_url:"",logo_url:c.iconUrl,address:o};e[o]=u,this.updateCache(s,u,tt)}}}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,c=0,u=[];if(i===void 0)throw Error("please config token ofsdkOptions");let d=ye(i);for(;;){let h=new bd.TransactionBlock;h.moveCall({target:`${i.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[h.pure(d.coin_registry_id),h.pure(t),h.pure(c),h.pure(a)]:[h.pure(d.coin_registry_id),h.pure(c),h.pure(a)]});let _=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:h,sender:n.address}),C=[];if(_.events?.forEach(D=>{ge(D.type).full_address===`${i.published_at}::coin_list::FetchCoinListEvent`&&D.parsedJson.full_list.value_list.forEach(B=>{C.push(this.transformData(B,!1))})}),u=[...u,...C],C.length<a)break;c=u.length}return u}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,c=0,u=t.length>0;if(i===void 0)throw Error("please config token ofsdkOptions");let d=ye(i);for(;;){let h=new bd.TransactionBlock;if(h.moveCall({target:`${i.published_at}::lp_list::${u?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:u?[h.pure(d.pool_registry_id),h.pure(t),h.pure(c),h.pure(a)]:[h.pure(d.pool_registry_id),h.pure(c),h.pure(a)]}),!Bn(n.address))throw new he("this config simulationAccount is not set right","InvalidSimulateAccount");let _=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:h,sender:n.address}),C=[];if(_.events?.forEach(D=>{ge(D.type).full_address===`${i.published_at}::lp_list::FetchPoolListEvent`&&D.parsedJson.full_list.value_list.forEach(B=>{C.push(this.transformData(B,!0))})}),s=[...s,...C],C.length<a)break;c=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=kd(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(c=>{let u=ge(c.type);if(c.transactionModule==="coin_list")switch(u.name){case"InitListEvent":a.coin_list_owner=c.parsedJson.list_id;break;case"InitRegistryEvent":a.coin_registry_id=c.parsedJson.registry_id;break;default:break}else if(c.transactionModule==="lp_list")switch(u.name){case"InitListEvent<address>":a.pool_list_owner=c.parsedJson.list_id;break;case"InitRegistryEvent<address>":a.pool_registry_id=c.parsedJson.registry_id;break;default:break}}),a.coin_registry_id.length>0&&this.updateCache(n,a,tt),a}transformData(t,e){let n={...t};if(e)try{n.coin_a_address=ge(n.coin_a_address).full_address,n.coin_b_address=ge(n.coin_b_address).full_address}catch{}else n.address=ge(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(Mo.decode(s)))}catch{}o==="pyth_id"&&(s=(0,ug.normalizeSuiObjectId)(s)),n[o]=s}delete n.extensions}return n}updateCache(t,e,n=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},lT=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"?ve.sqrtPriceX64ToPrice(t,o,s):new J(t.toString()).div(new J(10).pow(new J(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 Si.default(r.current_sqrt_price.toString()),afterSqrtPrice:r.label==="Cetus"?new Si.default(r.after_sqrt_price.toString()):be,fromDecimal:r.from_decimal,toDecimal:r.to_decimal,currentPrice:this.calculatePrice(new Si.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,c=!1,u=!1,d=[]){let h=null,_="v2",C={},D=this.sdk.sdkOptions.aggregatorUrl;if(d.length>0){let O=new URL(D);D=`${O.protocol}//${O.hostname}/router_with_lp_changes`,C={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:n,by_amount_in:i,order_split:c,external_router:u,sender_address:"None",request_id:encodeURIComponent(xc()),lp_changes:d})}}else D=`
|
|
10
|
-
${D}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(n)}&by_amount_in=${encodeURIComponent(i)}&order_split=${encodeURIComponent(c)}&external_router=${encodeURIComponent(u)}&sender_address=''&request_id=${encodeURIComponent(xc())}
|
|
11
|
-
`;if(h=await this.fetchAndParseData(D,C),h?.isTimeout||h==null){let O=await this.sdk.Router.price(t,e,new Si.default(n),i,r,o,a),B=[];for(let M of O.paths){let R=[];if(M.poolAddress.length>1){let X=this.sdk.Router.tokenInfo(M.coinType[0]).decimals,Y=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,oe=M.a2b[0]?ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[0]),X,Y):ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[0]),Y,X),$={direction:M.a2b[0],label:"Cetus",poolAddress:M.poolAddress[0],fromCoin:M.coinType[0],toCoin:M.coinType[1],feeRate:this.sdk.Router.getFeeRate(M.coinType[0],M.coinType[1],M.poolAddress[0]),outputAmount:O.byAmountIn?M.rawAmountLimit[0].toString():M.rawAmountLimit[1].toString(),inputAmount:M.amountIn.toString(),currentSqrtPrice:O.currentSqrtPrice[0],currentPrice:oe,fromDecimal:X,toDecimal:Y},ne=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,G=this.sdk.Router.tokenInfo(M.coinType[2]).decimals,W=M.a2b[1]?ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[1]),ne,G):ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[1]),G,ne),I={direction:M.a2b[1],label:"Cetus",poolAddress:M.poolAddress[1],fromCoin:M.coinType[1],toCoin:M.coinType[2],feeRate:this.sdk.Router.getFeeRate(M.coinType[1],M.coinType[2],M.poolAddress[1]),outputAmount:M.amountOut.toString(),inputAmount:O.byAmountIn?M.rawAmountLimit[0].toString():M.rawAmountLimit[1].toString(),currentSqrtPrice:O.currentSqrtPrice[1],currentPrice:W,fromDecimal:ne,toDecimal:G};R.push($,I)}else{let X=this.sdk.Router.tokenInfo(M.coinType[0]).decimals,Y=this.sdk.Router.tokenInfo(M.coinType[1]).decimals,oe=M.a2b[0]?ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[0]),X,Y):ve.sqrtPriceX64ToPrice(new Si.default(O.currentSqrtPrice[0]),Y,X),$={direction:M.a2b[0],label:"Cetus",poolAddress:M.poolAddress[0],fromCoin:M.coinType[0],toCoin:M.coinType[1],feeRate:this.sdk.Router.getFeeRate(M.coinType[0],M.coinType[1],M.poolAddress[0]),outputAmount:M.amountOut.toString(),inputAmount:M.amountIn.toString(),currentSqrtPrice:O.currentSqrtPrice[0],currentPrice:oe,fromDecimal:X,toDecimal:Y};R.push($)}let K={percent:Number(M.amountIn)/Number(O.amountIn)*100,inputAmount:Number(M.amountIn.toString()),outputAmount:Number(M.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:R};B.push(K)}let j={isExceed:O.isExceed,isTimeout:!0,inputAmount:Number(O.amountIn.toString()),outputAmount:Number(O.amountOut.toString()),fromCoin:O.coinTypeA,toCoin:O.coinTypeC!=null?O.coinTypeC:O.coinTypeB,byAmountIn:O.byAmountIn,splitPaths:B};_="v1",h=j}return{result:h,version:_}}},dT=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=ye(this.sdk.sdkOptions.cetus_config),n=`${e}_getCoinConfigs`,i=this.getCache(n),r=i?[...i,...t]:t;this.updateCache(n,r,tt)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:n}=ye(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 c of s)if(nr(a)===nr(c.address)){e[a]=c;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let a=`${s}_metadata`,c=this.getCache(a);if(c!==void 0)e[s]=c;else{let u=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(u){let d={id:u.id,pyth_id:"",name:u.name,symbol:u.symbol,official_symbol:u.symbol,coingecko_id:"",decimals:u.decimals,project_url:"",logo_url:u.iconUrl,address:s};e[s]=d,this.updateCache(a,d,tt)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:n}=ye(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new he(`when getCoinConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildCoinConfig(u,e);this.updateCache(`${n}_${d.address}_getCoinConfig`,d,tt),c.push({...d})}),this.updateCache(i,c,tt),c}async getCoinConfig(t,e=!1,n=!0){let{coin_list_handle:i}=ye(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:Lk(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new he(`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,tt),a}buildCoinConfig(t,e=!0){let n=an(t);n=n.value.fields;let i={...n};return i.id=Fo(t),i.address=ge(n.coin_type.fields.name).full_address,n.pyth_id&&(i.pyth_id=(0,jc.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}=ye(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new he(`when getClmmPoolsConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildClmmPoolConfig(u,e);this.updateCache(`${d.pool_address}_getClmmPoolConfig`,d,tt),c.push({...d})}),this.updateCache(i,c,tt),c}async getClmmPoolConfig(t,e=!1,n=!0){let{clmm_pools_handle:i}=ye(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,tt),a}buildClmmPoolConfig(t,e=!0){let n=an(t);n=n.value.fields;let i={...n};return i.id=Fo(t),i.pool_address=(0,jc.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}=ye(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(u=>u.objectId),a=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),c=[];return a.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new he(`when getCoinConfigs get objects error: ${u.error}, please check the rpc and contracts address config.`,"InvalidConfig");let d=this.buildLaunchpadPoolConfig(u,e);this.updateCache(`${d.pool_address}_getLaunchpadPoolConfig`,d,tt),c.push({...d})}),this.updateCache(i,c,tt),c}async getLaunchpadPoolConfig(t,e=!1,n=!0){let{launchpad_pools_handle:i}=ye(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,tt),a}buildLaunchpadPoolConfig(t,e=!0){let n=an(t);n=n.value.fields;let i={...n};i.id=Fo(t),i.pool_address=(0,jc.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(Mo.decode(i.regulation).replace(/%/g,"%25"))}catch{i.regulation=Mo.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(Mo.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=kd(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 c of s.data)switch(ge(c.type).name){case"InitCoinListEvent":a.coin_list_id=c.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":a.launchpad_pools_id=c.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":a.clmm_pools_id=c.parsedJson.pools_id;break;case"InitConfigEvent":a.global_config_id=c.parsedJson.global_config_id,a.admin_cap_id=c.parsedJson.admin_cap_id;break;default:break}return a=await this.getCetusConfigHandle(a),a.clmm_pools_id.length>0&&this.updateCache(n,a,tt),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 he(`when getCetusConfigHandle get objects error: ${i.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let r=an(i),o=Uo(i);switch(ge(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=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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}}},fT=class extends dg.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(c=>{let{type:u,value:d}=c;return u==="object"?lg.Inputs.SharedObjectRef({objectId:d,initialSharedVersion:0,mutable:!0}):d}),transactions:t.blockData.transactions}},o=fg.bcs.TransactionKind.serialize(r,{maxSize:131072}).toBytes(),s=Xl(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(i){console.log("devInspectTransactionBlock error",i)}}},$o=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new fT({url:t.fullRpcUrl}),this._swap=new cT(this),this._pool=new rT(this),this._position=new oT(this),this._rewarder=new sT(this),this._router=new aT(this),this._router_v2=new lT(this),this._token=new uT(this),this._config=new dT(this),tg(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(c=>{BigInt(c.balance)>0&&i.push({coinAddress:ge(c.coinType).source_address,coinObjectId:c.coinObjectId,balance:BigInt(c.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=tt){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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 dr=Pe(Un(),1),b0=require("@mysten/sui.js/utils"),Ve=Pe(Un(),1),ju=require("@mysten/sui.js/transactions"),yn=Pe(Un(),1),ce=Pe(Un(),1),ii=require("@mysten/sui.js/transactions"),ts=require("@mysten/sui.js/utils"),ia=Pe(Ee(),1),Ke=Pe(Un(),1),v0=require("@mysten/sui.js/utils");var qe=Pe(Un(),1),Rf=require("@mysten/sui.js/transactions"),si=Pe(Un(),1);var le=Pe(Un(),1),sr=require("@mysten/sui.js/transactions"),ur=Pe(Un(),1),se=Pe(Un(),1),Wi=require("@mysten/sui.js/utils"),ri=require("@mysten/sui.js/transactions"),Re=Pe(Un(),1);var Ff=require("@mysten/sui.js/utils");var gI=require("@mysten/sui.js/utils"),lr=Pe(Un(),1),Et=Pe(Ee(),1);var C0=Pe(Ee(),1),wn=Pe(Un(),1),qf=Pe(Ee(),1);var de=Pe(Un(),1),ar=require("@mysten/sui.js/transactions"),uo=require("@mysten/sui.js/transactions");var lo=require("@mysten/sui.js/transactions");var ht=Pe(Ee(),1);var Lf=require("@mysten/sui.js/bcs"),ta=require("@mysten/sui.js/utils"),Nu=require("@mysten/sui.js/transactions");var _e=Pe(Un(),1),oi=require("@mysten/sui.js/transactions"),Mf="router",es=1e4,Er=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:(0,yn.extractStructTagFromType)(e.clmm_pool_id).address,booster_type:(0,yn.extractStructTagFromType)(e.booster_type.fields.name).source_address,pool_id:(0,yn.extractStructTagFromType)(e.pool_id).address,coinTypeA:(0,yn.extractStructTagFromType)(e.coin_type_a.fields.name).source_address,coinTypeB:(0,yn.extractStructTagFromType)(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=(0,yn.getObjectFields)(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({lock_day:Number(r.fields.key),multiplier:Number((0,yn.d)(r.fields.value).div(es))})}),{basic_percent:Number((0,yn.d)(e.basic_percent).div(es)),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:(0,yn.getObjectId)(t)}}static buildLockNFT(t){let e=(0,yn.extractStructTagFromType)((0,yn.getObjectId)(t)).address;return{lock_clmm_position:(0,yn.buildPosition)(t),locked_nft_id:e}}static buildLockPositionInfo(t){let e=(0,yn.getObjectFields)(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}},aI=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((0,Ve.getPackagerConfigs)(e).booster_pool_handle)).data?.forEach(c=>{o.push(c.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let c of a){let u=(0,Ve.getObjectFields)(c);if(u){let d=Er.buildPoolImmutables(u);this.updateCache(`${d.pool_id}_getPoolImmutable`,d,Ve.cacheTime24h),r.push(d)}}}return this.updateCache(n,r,Ve.cacheTime24h),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:(0,Ve.getPackagerConfigs)(e).booster_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=(0,Ve.getObjectFields)(r),s=Er.buildPoolImmutables(o);return this.updateCache(n,s,Ve.cacheTime24h),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=Er.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,Ve.cacheTime24h)}}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=Er.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,Ve.cacheTime24h),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=(0,Ve.getObjectFields)(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 u of a.data)if((0,Ve.extractStructTagFromType)((0,Ve.getMoveObjectType)(u)).source_address===s&&u.data){let h=Er.buildLockNFT(u);this.updateCache(`${h.locked_nft_id}_getBoosterPositionById`,h,Ve.cacheTime24h),h&&(e===void 0||e===h.lock_clmm_position.pool)&&r.push(h)}let c=await this.getLockPositionInfos(n,r.map(u=>u.locked_nft_id));for(let u of r)for(let d of c)if(u.lock_clmm_position.pos_object_id===d.position_id){o.push({...u,...d});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=Er.buildLockNFT(s),this.updateCache(n,r,Ve.cacheTime24h)}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=Er.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 Er.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=(0,Ve.d)(r).sub(n.growth_rewarder).mul(i);return(0,Ve.d)(n.rewarder_owned).add(o).toString()}lockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new ju.TransactionBlock;return i.moveCall({target:`${e.published_at}::${Mf}::lock_position`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[i.pure((0,Ve.getPackagerConfigs)(e).booster_config_id),i.pure((0,Ve.getPackagerConfigs)(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(Ve.CLOCK_ADDRESS)]}),i}canceLockPositionPayload(t){let{booster:e}=this.sdk.sdkOptions,n=new ju.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Mf}::cancel_lock`,typeArguments:[t.booster_type],arguments:[n.pure((0,Ve.getPackagerConfigs)(e).booster_config_id),n.pure(t.booster_pool_id),n.pure(t.lock_nft_id),n.pure(Ve.CLOCK_ADDRESS)]}),n}redeemPayload(t){let{booster:e,xcetus:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions,r=new ju.TransactionBlock,o=(0,Ve.getPackagerConfigs)(n);return r.moveCall({target:`${e.published_at}::${Mf}::redeem`,typeArguments:[t.booster_type,t.coinTypeA,t.coinTypeB],arguments:[r.pure((0,Ve.getPackagerConfigs)(e).booster_config_id),r.pure((0,Ve.getPackagerConfigs)(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(Ve.CLOCK_ADDRESS)]}),r}updateCache(t,e,n=Ve.cacheTime5min){let i=this._cache[t];i?(i.overdueTime=(0,Ve.getFutureTime)(n),i.value=e):i=new Ve.CachedContent(e,(0,Ve.getFutureTime)(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]}},Yn="router",k0=1e9;var Ki=class{static priceRealToFix(t,e,n){let i=(0,Ke.d)(e-n).toNumber();return Number((0,Ke.d)(t).div((0,Ke.d)(10).pow((0,Ke.d)(i))).toString())}static priceFixToReal(t,e,n){let i=(0,Ke.d)(e-n).toNumber();return Number((0,Ke.d)(t).mul((0,Ke.d)(10).pow((0,Ke.d)(i))).toString())}static raiseTotalAmount(t,e,n){let i=(0,Ke.d)(e-n).abs().toNumber();return e>n?Number((0,Ke.d)(t.total_supply).mul(t.current_price).div((0,Ke.d)(10).pow((0,Ke.d)(i))).toString()):Number((0,Ke.d)(t.total_supply).mul(t.current_price).mul((0,Ke.d)(10).pow((0,Ke.d)(i))).toString())}static buildLaunchPadPool(t){let e=(0,Ke.getMoveObjectType)(t),n=(0,Ke.extractStructTagFromType)(e),i=(0,Ke.getObjectFields)(t),r={coin_type_sale:n.type_arguments[0],coin_type_raise:n.type_arguments[1],pool_address:(0,v0.normalizeSuiObjectId)((0,Ke.getObjectId)(t)),is_settle:i.is_settle,current_price:(0,Ke.d)(i.initialize_price).div((0,Ke.d)(k0)).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 Ki.updatePoolStatus(r),r}static updatePoolStatus(t){let e=Number((0,Ke.d)(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((0,Ke.d)(e.softcap).div((0,Ke.d)(e.total_supply))),i,r).toString(),e.max_price=this.priceFixToReal(Number((0,Ke.d)(e.max_raise_amount).div((0,Ke.d)(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((0,Ke.d)(e.harvest_raise).equals((0,Ke.d)(0))){let i=await t.Launchpad.getSettleEvent(e.pool_address);i&&(e.harvest_raise=i.unused_raise)}let n=(0,ia.min)(new ia.default(e.total_purchase_amount),new ia.default(e.max_raise_amount));return(0,Ke.d)(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(0,Ke.d)(i).sub(r).div((0,Ke.d)(e.total_purchase_amount).sub(o)).mul((0,Ke.d)(e.total_purchase_amount).sub(e.max_raise_amount)).toString()}return"0"}static async getCanPurchaseAmount(t,e){let n=await Ki.getOverrecruitReverseAmount(t,e),i=await t.Launchpad.getPurchaseMarks(t.ClmmSDK.senderAddress,[e.pool_address],!1);if(i){let r=i[0].purchased_raise_amount;(0,Ke.d)(r).sub(n).div(e.current_price)}return"0"}},cI=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=[],c=[];if(s!==void 0&&a.push(...s),a.length===0)try{((await this._sdk.ClmmSDK.fullClient.queryEventsByPage({MoveEventType:`${r}::factory::CreatePoolEvent`}))?.data).forEach(h=>{let _=h.parsedJson;_&&a.push({pool_address:_.pool_id,coin_type_sale:(0,ce.extractStructTagFromType)(_.sale_coin.name).full_address,coin_type_raise:(0,ce.extractStructTagFromType)(_.raise_coin.name).full_address})}),this.updateCache(o,a,ce.cacheTime24h)}catch(d){console.log("getPoolImmutables",d)}let u=t.length>0;for(let d=0;d<a.length;d+=1){let h=a[d];if(!(u&&!t.includes(h.pool_address))){if(!u){let _=d;if(_<e||_>=e+n)continue}c.push(h)}}return c}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(c=>{let u=c.parsedJson;u&&r.push({pool_address:u.pool_id,coin_type_sale:(0,ce.extractStructTagFromType)(u.sale_coin.name).full_address,coin_type_raise:(0,ce.extractStructTagFromType)(u.raise_coin.name).full_address})})}catch(a){console.log("getPoolImmutables",a)}return o.data=r,s&&this.updateCache(i,r,ce.cacheTime24h),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=Ki.buildLaunchPadPool(s);await Ki.calculatePoolPrice(this._sdk,a),i.push(a);let c=`${a.pool_address}_getPoolObject`;this.updateCache(c,a,ce.cacheTime24h)}return i}async getPool(t,e=!0){let n=`${t}_getPoolObject`,i=this.getCache(n,e);if(i!==void 0){let s=i;return Ki.updatePoolStatus(s),s}let r=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),o=Ki.buildLaunchPadPool(r);return await Ki.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=(0,ce.getObjectPreviousTransactionDigest)(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(c=>{let u=c.parsedJson;if(u)switch((0,ce.extractStructTagFromType)(c.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=u.admin_cap_id,a.config_cap_id=u.config_cap_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=u.pools_id;break;default:break}}),this.updateCache(n,a,ce.cacheTime24h)),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(0,ce.buildPosition)(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}`===(0,ce.extractStructTagFromType)(a.nft_type).address){let c=await this.getLockNFT(a.lock_nft_id);if(c){let u=(0,ce.extractStructTagFromType)(c.coin_type_a).full_address,d=(0,ce.extractStructTagFromType)(c.coin_type_b).full_address;i.push({...c,coin_type_a:u,coin_type_b:d,...a})}}}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPoolTransactionPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=(0,ce.getPackagerConfigs)(e);if(this.assertLuanchpadConfig(),this._sdk.ClmmSDK.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let i=Ki.priceRealToFix(Number(t.initialize_price),t.sale_decimals,t.raise_decimals),r=new ii.TransactionBlock,o=(0,ce.d)(t.total_supply).add((0,ce.d)(t.total_supply).mul((0,ce.d)(t.liquidity_rate))).toNumber(),s=await ce.TransactionUtil.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,ts.normalizeSuiAddress)(t.recipient)),r.pure((i*k0).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(ce.CLOCK_ADDRESS)],c=[t.coin_type_sale,t.coin_type_raise];return r.moveCall({target:`${e.published_at}::${Yn}::create_launch_pool`,typeArguments:c,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 ii.TransactionBlock,i=await ce.TransactionUtil.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((0,ce.getPackagerConfigs)(e).config_cap_id),n.pure(r.id),i,n.pure(t.purchase_amount.toString()),n.pure(ce.CLOCK_ADDRESS)]:s=[n.pure(t.pool_address),n.pure((0,ce.getPackagerConfigs)(e).config_cap_id),i,n.pure(t.purchase_amount.toString()),n.pure(ce.CLOCK_ADDRESS)],n.moveCall({target:`${e.published_at}::${Yn}::${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 ii.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure(t.pool_address),i.pure((0,ce.getPackagerConfigs)(e).config_cap_id),i.pure(n?.id),i.pure(ce.CLOCK_ADDRESS)];return i.moveCall({target:`${e.published_at}::${Yn}::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=(0,ce.getPackagerConfigs)(n),{clmm_args:r}=t,o=new ii.TransactionBlock;o.setSender(this.sdk.ClmmSDK.senderAddress);let s=[t.coin_type_sale,t.coin_type_raise];if(r){let a=r.opposite?ce.TickMath.priceToSqrtPriceX64((0,ce.d)(1).div(r.current_price),r.raise_decimals,r.sale_decimals).toString():ce.TickMath.priceToSqrtPriceX64((0,ce.d)(r.current_price),r.sale_decimals,r.raise_decimals).toString(),c=BigInt(a)<BigInt(r.clmm_sqrt_price),u=r.opposite?c?t.coin_type_raise:t.coin_type_sale:c?t.coin_type_sale:t.coin_type_raise,d=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,u),h=ce.CoinAssist.calculateTotalBalance(d);ce.CoinAssist.isSuiCoin(u)&&(h-=BigInt(2e8));let C=ce.TransactionUtil.buildCoinForAmount(o,d,h,u).targetCoin,D=r.opposite?c?"settle_with_reverse_clmm_only_with_a":"settle_with_reverse_clmm_only_with_b":c?"settle_only_with_a":"settle_only_with_b",O=[o.pure(t.pool_address),o.pure((0,ce.getPackagerConfigs)(e).config_cap_id),o.pure(r.clmm_pool_address),o.pure(i.global_config_id),o.pure(a),C,o.pure(ce.CLOCK_ADDRESS)];o.moveCall({target:`${e.published_at}::${Yn}::${D}`,typeArguments:s,arguments:O})}else o.moveCall({target:`${e.published_at}::${Yn}::settle`,typeArguments:s,arguments:[o.pure(t.pool_address),o.pure((0,ce.getPackagerConfigs)(e).config_cap_id),o.pure(ce.CLOCK_ADDRESS)]});return o}creatWithdrawPayload(t){let{launchpad:e}=this.sdk.sdkOptions,n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object(t.pool_address),n.object((0,ce.getPackagerConfigs)(e).config_cap_id),n.object(ce.CLOCK_ADDRESS)];return t.sale_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Yn}::withdraw_sale`,typeArguments:i,arguments:r}),t.raise_amount>BigInt(0)&&n.moveCall({target:`${e.published_at}::${Yn}::withdraw_raise`,typeArguments:i,arguments:r}),n}addUserToWhitelisPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object((0,ce.getPackagerConfigs)(e).admin_cap_id),n.object((0,ce.getPackagerConfigs)(e).config_cap_id),n.object(t.pool_address),n.object(r),n.pure(t.safe_limit_amount),n.object(ce.CLOCK_ADDRESS)];n.moveCall({target:`${e.published_at}::${Yn}::add_user_to_whitelist`,typeArguments:i,arguments:o})}),n}updateWhitelistCapPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.safe_limit_amount>0&&n.moveCall({target:`${e.published_at}::${Yn}::update_whitelist_member_safe_limit_amount`,typeArguments:i,arguments:[n.object((0,ce.getPackagerConfigs)(e).admin_cap_id),n.object((0,ce.getPackagerConfigs)(e).config_cap_id),n.object(t.pool_address),n.pure(t.white_list_member),n.pure(t.safe_limit_amount),n.object(ce.CLOCK_ADDRESS)]}),t.hard_cap_total>0&&n.moveCall({target:`${e.published_at}::${Yn}::update_whitelist_hard_cap_total`,typeArguments:i,arguments:[n.object((0,ce.getPackagerConfigs)(e).admin_cap_id),n.object((0,ce.getPackagerConfigs)(e).config_cap_id),n.object(t.pool_address),n.pure(t.hard_cap_total),n.object(ce.CLOCK_ADDRESS)]}),n}creatRemoveWhitelistPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise];return t.user_addrs.forEach(r=>{let o=[n.object((0,ce.getPackagerConfigs)(e).admin_cap_id),n.object((0,ce.getPackagerConfigs)(e).config_cap_id),n.object(t.pool_address),n.object(r),n.object(ce.CLOCK_ADDRESS)];n.moveCall({target:`${e.published_at}::${Yn}::remove_user_from_whitelist`,typeArguments:i,arguments:o})}),n}creatCancelPoolPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure((0,ce.getPackagerConfigs)(e).admin_cap_id),n.pure((0,ce.getPackagerConfigs)(e).config_cap_id),n.pure(t.pool_address),n.pure(ce.CLOCK_ADDRESS)];return n.moveCall({target:`${e.published_at}::${Yn}::cancel`,typeArguments:i,arguments:r}),n}updateRecipientPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure((0,ce.getPackagerConfigs)(e).admin_cap_id),n.pure((0,ce.getPackagerConfigs)(e).config_cap_id),n.pure(t.pool_address),n.pure(t.new_recipient),n.pure(ce.CLOCK_ADDRESS)];return n.moveCall({target:`${e.published_at}::${Yn}::update_recipient_address`,typeArguments:i,arguments:r}),n}updatePoolDuractionPayload(t){let{launchpad:e}=this.sdk.sdkOptions;this.assertLuanchpadConfig();let n=new ii.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure((0,ce.getPackagerConfigs)(e).admin_cap_id),n.pure((0,ce.getPackagerConfigs)(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(ce.CLOCK_ADDRESS)];return n.moveCall({target:`${e.published_at}::${Yn}::update_pool_duration`,typeArguments:i,arguments:r}),n}creatUnlockNftPayload(t){let{launchpad:e}=this.sdk.sdkOptions;if((0,ce.getPackagerConfigs)(e)===void 0)throw Error("getPackagerConfigs(launchpad) is null");let n=new ii.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft),n.pure(ce.CLOCK_ADDRESS)];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((0,ce.getPackagerConfigs)(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:(0,ce.getPackagerConfigs)(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=(0,ce.getObjectType)(r),s=(0,ce.getObjectOwner)(r),a=!1;return s&&o&&(0,ce.extractStructTagFromType)(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,ts.normalizeSuiAddress)(s.AddressOwner)===(0,ts.normalizeSuiAddress)(t)),this.updateCache(n,a,ce.cacheTime24h),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=(0,ce.getObjectFields)(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 c=await this._sdk.ClmmSDK.fullClient.getOwnedObjects({owner:t,options:{showType:!0,showContent:!0,showDisplay:!0},cursor:s});for(let u of c.data){let{fields:d}=u.data.content;if((0,ce.extractStructTagFromType)((0,ce.getMoveObjectType)(u)).source_address===`${i.package_id}::pool::PurchaseMark`){console.log("fields: ",d);let _={id:d.id.id,pool_id:(0,ce.extractStructTagFromType)(d.pool_id).address,purchased_raise_amount:d.purchase_total,obtain_sale_amount:d.obtain_sale_amount,used_raise_amount:d.used_raise_amount};e.length>0?e.includes(_.pool_id)&&a.push(_):a.push(_)}}if(c.hasNextPage)s=c.nextCursor;else break}return this.updateCache(r,a,ce.cacheTime24h),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,ts.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,ce.cacheTime24h),a}}}buildLaunchpadCoinType(t,e){return(0,ce.composeType)(this._sdk.sdkOptions.launchpad.package_id,"pool","PoolLiquidityCoin",[t,e])}assertLuanchpadConfig(){let{launchpad:t}=this.sdk.sdkOptions;if((0,ce.getPackagerConfigs)(t)===void 0)throw Error("sdk getPackagerConfigs(launchpad) is null")}updateCache(t,e,n=ce.cacheTime5min){let i=this._cache[t];i?(i.overdueTime=(0,ce.getFutureTime)(n),i.value=e):i=new ce.CachedContent(e,(0,ce.getFutureTime)(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]}},Dr=class{static buildPoolImmutables(t){let{fields:e}=t.value.fields.value;return{clmm_pool_id:(0,si.extractStructTagFromType)(e.clmm_pool_id).address,bonus_type:(0,si.extractStructTagFromType)(e.bonus_type.fields.name).source_address,pool_id:(0,si.extractStructTagFromType)(e.pool_id).address,coinTypeA:(0,si.extractStructTagFromType)(e.coin_type_a.fields.name).source_address,coinTypeB:(0,si.extractStructTagFromType)(e.coin_type_b.fields.name).source_address}}static buildPoolState(t){let e=(0,si.getObjectFields)(t),n=[];return e.config.fields.contents.forEach(r=>{n.push({rate:Number((0,si.d)(r.fields.key).div(es)),multiplier:Number((0,si.d)(r.fields.value).div(es))})}),{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((0,si.d)(e.minimum_percent_to_reward).div(es)),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((0,si.d)(s.fields.percent).div(es)),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}},w0="router",uI=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((0,qe.getPackagerConfigs)(e).maker_pool_handle)).data?.forEach(c=>{o.push(c.objectId)});let a=await this._sdk.ClmmSDK.fullClient.batchGetObjects(o,{showContent:!0});for(let c of a){let u=(0,qe.getObjectFields)(c);u&&r.push(Dr.buildPoolImmutables(u))}}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:(0,qe.getPackagerConfigs)(e).maker_pool_handle,name:{type:"0x2::object::ID",value:t}}),o=(0,qe.getObjectFields)(r);return Dr.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=Dr.buildPoolState(o);if(s){let a={...e[r],...s};t.push(a);let c=`${a.pool_id}_getPoolObject`;this.updateCache(c,a,qe.cacheTime24h)}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=Dr.buildPoolState(o),a={...r,...s};return this.updateCache(n,a,qe.cacheTime24h),a}async getPoolHandleId(t){let e=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0}}),n=(0,qe.getObjectFields)(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((0,qe.d)(t.start_time).add((0,qe.d)(t.interval_day).mul(24*3600).mul(a.period)).toFixed(0,J.ROUND_DOWN)),a.end_time=Number((0,qe.d)(a.start_time).add((0,qe.d)(t.interval_day).mul(24*3600)).toFixed(0,J.ROUND_DOWN)),n.push(a)}),this.updateCache(i,n,qe.cacheTime24h),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 c=(0,qe.getObjectFields)(a),u=Dr.buildMarkerPositions(c);if(u.length>0){let{period_id:d}=u[0],h=e.filter(_=>_.id===d)[0];i[h.period]=u}});let o=[];for(let s in i)i[s].forEach(c=>{o.push(c)});if(o.length>0){let s=await this._sdk.ClmmSDK.Position.getSipmlePositionList(o.map(a=>a.id));for(let a of o)for(let c of s)if(a.id===c.pos_object_id){a.clmm_position=c;break}}}catch(o){console.log(o)}for(let o in i){let s=`${t}_${o}_getPoolMarkerPositionList`;this.updateCache(s,i[o],qe.cacheTime24h)}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=(0,qe.d)(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=Dr.getBonusPercent(t.config,e.percent),r=(0,qe.d)(e.point).mul(i),o=(0,qe.d)(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=(0,qe.d)(0),r=n[e.period];for(let o of r){let s=Dr.getBonusPercent(t.config,o.percent),a=(0,qe.d)(o.point).mul(s);i=i.add(a)}return i.toString()}async calculateAllXCetusRewarder(t){let e=this._sdk.ClmmSDK.senderAddress,n=(0,qe.d)(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 c of o){let u=s[c.period].filter(d=>e.length===0?!1:d.clmm_position?.owner===e);u.length>0&&(await this._sdk.MakerModule.updateXCetusRewarderAndFee(r,u,c),u.forEach(d=>{d.clmm_position?.position_status===qe.ClmmPositionStatus.Exists&&(0,qe.d)(d.bonus_num).greaterThan(0)&&(n=n.add(d.bonus_num),a.includes(d.clmm_position.pos_object_id)||a.push(d.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=(0,qe.getObjectFields)(o),a=Dr.buildPoolBonusInfo(s);return this.updateCache(i,a,qe.cacheTime5min),a}claimPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Rf.TransactionBlock;return i.moveCall({target:`${e.published_at}::${w0}::claim`,typeArguments:[t.bonus_type],arguments:[i.pure((0,qe.getPackagerConfigs)(e).maker_config_id),i.pure(t.market_pool_id),i.pure(t.position_nft_id),i.pure(t.phase),i.pure((0,qe.getPackagerConfigs)(n).lock_manager_id),i.pure((0,qe.getPackagerConfigs)(n).xcetus_manager_id),i.pure(t.ve_nft_id)]}),i}claimAllPayload(t){let{maker_bonus:e,xcetus:n}=this.sdk.sdkOptions,i=new Rf.TransactionBlock;return t.whale_nfts.forEach(r=>{r.nft_ids.forEach(o=>{i.moveCall({target:`${e.published_at}::${w0}::claim_all`,typeArguments:[r.bonus_type],arguments:[i.object((0,qe.getPackagerConfigs)(e).maker_config_id),i.object(r.pool_id),i.object(o),i.object((0,qe.getPackagerConfigs)(n).lock_manager_id),i.object((0,qe.getPackagerConfigs)(n).xcetus_manager_id),i.object(t.ve_nft_id)]})})}),i}updateCache(t,e,n=qe.cacheTime5min){let i=this._cache[t];i?(i.overdueTime=(0,qe.getFutureTime)(n),i.value=e):i=new qe.CachedContent(e,(0,qe.getFutureTime)(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]}},Jo="router",jf="router",na=24*3600,Ru=1e3,wi=1e11,fo=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:(0,ur.extractStructTagFromType)(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((0,ur.extractStructTagFromType)(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:(0,ur.normalizeCoinType)(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:(0,ur.extractStructTagFromType)(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)/na,n}static getAvailableXCetus(t,e){let n=(0,ur.d)(0);return e.forEach(i=>{n=n.add(i.xcetus_amount)}),(0,ur.d)(t.xcetus_balance).sub(n).toString()}static getWaitUnLockCetuss(t){return t.filter(e=>!fo.isLocked(e))}static getLockingCetuss(t){return t.filter(e=>fo.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*na));return n+r*i*na}},lI=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(c=>{let u=(0,le.extractStructTagFromType)((0,le.getMoveObjectType)(c)).source_address;if(u===s&&c.data&&c.data.content){let{fields:d}=c.data.content;o={...(0,le.buildNFT)(c),id:d.id.id,index:d.index,type:u,xcetus_balance:d.xcetus_balance},this.updateCache(i,o,le.cacheTime24h)}}),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((0,le.extractStructTagFromType)((0,le.getMoveObjectType)(o)).source_address===i&&o.data){let a=fo.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=fo.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 sr.TransactionBlock;return e.moveCall({target:`${t.published_at}::${Jo}::mint_venft`,typeArguments:[],arguments:[e.pure((0,le.getPackagerConfigs)(t).xcetus_manager_id)]}),e}async convertPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new sr.TransactionBlock,i=this.buileCetusCoinType(),r=await le.TransactionUtil.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${Jo}::mint_and_convert`,typeArguments:[],arguments:[n.object((0,le.getPackagerConfigs)(e).lock_manager_id),n.object((0,le.getPackagerConfigs)(e).xcetus_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${Jo}::convert`,typeArguments:[],arguments:[n.object((0,le.getPackagerConfigs)(e).lock_manager_id),n.object((0,le.getPackagerConfigs)(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 sr.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Jo}::redeem_lock`,typeArguments:[],arguments:[n.pure((0,le.getPackagerConfigs)(e).lock_manager_id),n.pure((0,le.getPackagerConfigs)(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(le.CLOCK_ADDRESS)]}),n}redeemPayload(t){let{xcetus:e}=this.sdk.sdkOptions,n=new sr.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Jo}::redeem`,typeArguments:[],arguments:[n.pure((0,le.getPackagerConfigs)(e).lock_manager_id),n.pure((0,le.getPackagerConfigs)(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(le.CLOCK_ADDRESS)]}),n}redeemDividendPayload(t,e){let{xcetus:n,xcetus_dividends:i}=this.sdk.sdkOptions,r=new sr.TransactionBlock;return e.forEach(o=>{r.moveCall({target:`${n.published_at}::${jf}::redeem`,typeArguments:[o],arguments:[r.object((0,le.getPackagerConfigs)(i).dividend_manager_id),r.object(t)]})}),r}redeemDividendV2Payload(t,e,n){let{xcetus_dividends:i}=this.sdk.sdkOptions,r=new sr.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}::${jf}::redeem_v2`,typeArguments:[s],arguments:[r.object((0,le.getPackagerConfigs)(i).dividend_manager_id),r.object(t),r.object(le.CLOCK_ADDRESS)]})}),r}redeemDividendXTokenPayload(t,e){let{xcetus_dividends:n,xcetus:i}=this.sdk.sdkOptions,{xcetus_manager_id:r,lock_manager_id:o}=(0,le.getPackagerConfigs)(i),{dividend_manager_id:s}=(0,le.getPackagerConfigs)(n);return e=e===void 0?new sr.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${jf}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(le.CLOCK_ADDRESS)]}),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 sr.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Jo}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure((0,le.getPackagerConfigs)(e).lock_manager_id),n.pure((0,le.getPackagerConfigs)(e).xcetus_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(le.CLOCK_ADDRESS)]}),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,le.cacheTime24h),r}async getLockUpManager(t=(0,le.getPackagerConfigs)(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=fo.buildLockUpManager((0,le.getObjectFields)(r));return this.updateCache(n,o,le.cacheTime24h),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,le.cacheTime24h))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=(0,le.getPackagerConfigs)(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=(0,le.getObjectFields)(r),s=fo.buildDividendManager(o);return this.updateCache(n,s,le.cacheTime24h),s}async getXcetusManager(t=!0){let{xcetus_manager_id:e}=(0,le.getPackagerConfigs)(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=(0,le.getObjectFields)(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=(0,le.getObjectFields)(n);return fo.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager((0,le.getPackagerConfigs)(this._sdk.sdkOptions.xcetus).lock_manager_id),i=(0,le.d)(wi).mul((0,le.d)(n.max_lock_day).sub((0,le.d)(e))).mul((0,le.d)(n.max_percent_numerator).sub((0,le.d)(n.min_percent_numerator))).div((0,le.d)(n.max_lock_day).sub((0,le.d)(n.min_lock_day))),r=(0,le.d)(wi).mul((0,le.d)(n.max_percent_numerator)).sub(i).div((0,le.d)(Ru)).div(wi);return{amountOut:(0,le.d)(r).mul((0,le.d)(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((0,le.getPackagerConfigs)(this._sdk.sdkOptions.xcetus).lock_manager_id),i=(0,le.d)(wi).mul((0,le.d)(n.max_lock_day).sub((0,le.d)(e))).mul((0,le.d)(n.max_percent_numerator).sub((0,le.d)(n.min_percent_numerator))).div((0,le.d)(n.max_lock_day).sub((0,le.d)(n.min_lock_day))),r=(0,le.d)(wi).mul((0,le.d)(n.max_percent_numerator)).sub(i).div((0,le.d)(Ru)).div(wi);return{amountOut:(0,le.d)(t).div(r).toFixed(0,J.ROUND_UP),percent:r.toString()}}async getXCetusAmount(t){let{lock_handle_id:e}=(0,le.getPackagerConfigs)(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=(0,le.getObjectFields)(r);if(o){let{xcetus_amount:s}=o.value.fields.value.fields;return this.updateCache(n,s,le.cacheTime24h),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=(0,le.getObjectFields)(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=(0,le.getObjectFields)(s),c=a.value.fields.value.fields,u=c.redeemed_num.fields.contents.map(C=>({name:C.fields.key.fields.name,value:C.fields.value})),d=c.bonus_types.map(C=>C.fields.name),h=c.bonus.fields.contents.map(C=>({name:C.fields.key.fields.name,value:C.fields.value})),_={id:(0,le.getObjectId)(s),phase:a.name,settled_num:c.settled_num,register_time:c.register_time,redeemed_num:u,is_settled:c.is_settled,bonus_types:d,bonus:h,phase_end_time:""};return this.updateCache(r,_),_}catch{}}updateCache(t,e,n=le.cacheTime5min){let i=this._cache[t];i?(i.overdueTime=(0,le.getFutureTime)(n),i.value=e):i=new le.CachedContent(e,(0,le.getFutureTime)(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]}},dI="factory",_i="oversubscribe_pool",T0=1e6,Qo=1e18;var Yo="router",Nf="router",Du="router";var y0={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 fI(t){return"master_address"in t}var hI="router",pI="vaults",mI=1e4;var Wn=class{static buildIdoPoolImmutables(t){return{pool_address:(0,Ff.normalizeSuiObjectId)(t.pool_id),coin_type_sale:(0,Re.extractStructTagFromType)(t.sale_coin_type.name).full_address,coin_type_raise:(0,Re.extractStructTagFromType)(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=(0,Re.getMoveObjectType)(t),n=(0,Re.extractStructTagFromType)(e),i=(0,Re.getObjectFields)(t);console.log("fields:",i);let r={pool_address:(0,Ff.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:(0,Re.d)(i.liquidity_injection_ratio).div(T0).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 Wn.updatePoolStatus(s),{...r,...s}}static is_init_period(t){return Number((0,Re.d)(Date.now()/1e3).toFixed(0))<t.start_time}static is_purchase_period(t){let e=Number((0,Re.d)(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((0,Re.d)(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&&Wn.is_claim_period(t.duration_summary)&&!t.is_liquidity_injected}static is_can_withdraw(t){return t.is_withdrawn?!1:Wn.is_sale_failed(t)?!0:(t.liquidity_injection_ratio===0||t.is_liquidity_injected)&&Wn.is_claim_period(t.duration_summary)}static is_sale_failed(t){return!!(t.is_cancelled||Wn.is_claim_period(t.duration_summary)&&(0,Re.d)(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(Wn.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((0,Re.d)(t.total_purchase_amount).lessThanOrEqualTo(t.max_raise_amount))n=(0,Re.d)(e.purchased_raise_amount).mul(Qo).div(t.price).toString(),i=e.purchased_raise_amount;else{let o=Wn.redeemForSaleOversubcribeV2(t,e);n=o.user_obtained_sale_amount,i=o.user_used_raise_amount_ceil}n=J.floor(n);let r=J.floor((0,Re.d)(e.purchased_raise_amount).sub(i).toString());return{obtained_sale_amount:n,refunded_raise_amount:r}}static calculateWithdrawAmount(t){let e,n,i=(0,Re.d)(t.total_supply).mul(t.liquidity_injection_ratio);if(Wn.is_sale_failed(t))e="0",n=(0,Re.d)(i).add(t.total_supply);else{let{max_raise_amount:r}=t;(0,Re.d)(t.total_purchase_amount).greaterThanOrEqualTo(r)?(e=(0,Re.d)(r).sub(t.liquidity_used_raise_amount).toString(),n="0"):(e=(0,Re.d)(t.total_purchase_amount).sub(t.liquidity_used_raise_amount),n=(0,Re.d)(t.total_supply).add(i).sub(t.liquidity_used_sale_amount).sub(Wn.get_sold_amount(t)))}return{obtained_raise_amount:J.floor(e).toString(),refunded_sale_amount:J.ceil(n).toString()}}static get_sold_amount(t){return(0,Re.d)(t.total_purchase_amount).greaterThanOrEqualTo(t.max_raise_amount)?t.total_supply:(0,Re.d)(t.total_purchase_amount).mul(Qo).div(t.price)}static redeemForSaleOversubcribe(t,e){let n=e.protection_raise_amount,i=(0,Re.d)(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=(0,Re.d)(r).sub(o),a=(0,Re.d)(t.total_purchase_amount).sub(o),c=J.ceil(i.mul(s).div(a).add(n)),u=J.floor(i.mul(s).div(a).add(n));return{user_obtained_sale_amount:J.floor((0,Re.d)(t.total_supply).mul(u).div(r)),user_used_raise_amount_ceil:c}}static redeemForSaleOversubcribeV2(t,e){let n=e.protection_raise_amount,i=(0,Re.d)(e.purchased_raise_amount).sub(n),r=t.max_raise_amount,{protection_limit_used:o}=t.white_summary,s=(0,Re.d)(r).sub(o),a=(0,Re.d)(t.total_purchase_amount).sub(o),c=(0,Re.d)(n).mul(a).add((0,Re.d)(i).mul(s)).mul(Qo).div((0,Re.d)(a).mul(t.price)),u=J.ceil(c.mul(t.price).div(Qo));return{user_obtained_sale_amount:c,user_used_raise_amount_ceil:u}}static raiseTotalAmount(t){let e=(0,Re.d)(t.sale_decimals-t.raise_decimals).abs().toNumber();return t.sale_decimals>t.raise_decimals?(0,Re.d)(t.total_supply).mul(t.current_price).div((0,Re.d)(10).pow((0,Re.d)(e))).toString():(0,Re.d)(t.total_supply).mul(t.current_price).mul((0,Re.d)(10).pow((0,Re.d)(e))).toString()}static updatePoolStatus(t){let e=Number((0,Re.d)(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":(0,Re.d)(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=Ki.priceFixToReal(Number((0,Re.d)(e.price).div((0,Re.d)(Qo)).toString()),i,r).toString(),e.sale_decimals=i,e.raise_decimals=r,e.max_raise_amount=this.raiseTotalAmount(e)}};var ho=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:(0,lr.extractStructTagFromType)(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((0,lr.extractStructTagFromType)(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:(0,lr.normalizeCoinType)(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:(0,lr.extractStructTagFromType)(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)/na,n}static getAvailableXToken(t,e){let n=(0,lr.d)(0);return e.forEach(i=>{n=n.add(i.xtoken_amount)}),(0,lr.d)(t.xtoken_balance).sub(n).toString()}static getWaitUnLockTokens(t){return t.filter(e=>!ho.isLocked(e))}static getLockingTokens(t){return t.filter(e=>ho.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=na){let n=Date.now()/1e3,{start_time:i,interval_day:r}=t,o=Math.ceil((n-i)/(r*e));return i+o*r*e}},cr=class{static getDefaultStrategyConfig(t){let e;switch(t){case 4:e=y0.bidAsk;break;default:e=y0.curve;break}return e}static geTickIndexRange(t,e,n,i){let r,o;switch(t=ve.getInitializableTickIndex(t,e),i){case"left":t>0?(o=te(t).sub(e).toNumber(),r=te(t).mul(te(1).add(n)).toDecimalPlaces(0).toNumber()):(o=te(t).sub(e).toNumber(),r=te(t).mul(te(1).sub(n)).toDecimalPlaces(0).toNumber());break;case"right":t>0?(o=te(t).mul(te(1).add(n)).toDecimalPlaces(0).toNumber(),r=te(t).add(e).toNumber()):(o=te(t).mul(te(1).sub(n)).toDecimalPlaces(0).toNumber(),r=te(t).add(e).toNumber());break;default:t>0?(r=te(t).mul(te(1).sub(n)).toDecimalPlaces(0).toNumber(),o=te(t).mul(te(1).add(n)).toDecimalPlaces(0).toNumber()):(r=te(t).mul(te(1).add(n)).toDecimalPlaces(0).toNumber(),o=te(t).mul(te(1).sub(n)).toDecimalPlaces(0).toNumber());break}if(r=ve.getInitializableTickIndex(r,e),o=ve.getInitializableTickIndex(o,e),r<Zm)throw Error("Tick lower value is below the minimum allowed value.");if(o>Xm)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=cr.getCreateBidAskLiquidityBins(t);break;default:n=cr.getCreateCurveLiquidityBins(t);break}return n}static getCreateBidAskLiquidityBins(t){let e=te(Math.floor(te(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,c;t.tick_upper<=t.curr_tick?(c=te(t.tick_upper).sub(e.mul(s)).toNumber(),a=te(c).sub(e).toNumber()):t.tick_lower>=t.curr_tick?(a=te(t.tick_lower).add(e.mul(s)).toNumber(),c=te(t.tick_lower).add(e.mul(s+1)).toNumber()):s===4?(a=te(t.tick_lower).add(e.mul(s)).toNumber(),c=te(a).add(e.mul(2)).toNumber()):s>4?(a=te(t.tick_lower).add(e.mul(s+1)).toNumber(),c=te(a).add(e).toNumber()):(a=te(t.tick_lower).add(e.mul(s)).toNumber(),c=te(a).add(e).toNumber()),r=ve.getInitializableTickIndex(a,t.tick_spacing),o=ve.getInitializableTickIndex(c,t.tick_spacing),n.push({tick_lower:r,tick_upper:o,ratio:i[s],liquidity:"0"})}return n}static getCreateCurveLiquidityBins(t){let e=te(Math.floor(te(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=te(t.tick_upper).sub(e.mul(r+1)).toNumber()):t.tick_lower>=t.curr_tick?(o=t.tick_lower,s=te(o).add(e.mul(r+1)).toNumber()):(o=te(t.curr_tick).sub(e.mul(r+1)).toNumber(),s=te(t.curr_tick).add(e.mul(r+1)).toNumber()),n.push({tick_lower:ve.getInitializableTickIndex(o,t.tick_spacing),tick_upper:ve.getInitializableTickIndex(s,t.tick_spacing),ratio:i[r],liquidity:"0"})}return n}static calculateAddLiquidityInputs(t){let e=new Et.default(ve.tickIndexToSqrtPriceX64(t.curr_tick)),n=cr.calculateCoinRatios(t.curr_tick,t.liquidity_bins),i=t.liquidity_bins.map((r,o)=>{let s=n[o],a=te(t.coin_amount).mul(t.fix_amount_a?s.coinRatioA:s.coinRatioB).toFixed(0).toString();try{return{...dn.estLiquidityAndcoinAmountFromOneAmounts(r.tick_lower,r.tick_upper,new Et.default(a),t.fix_amount_a,!0,t.slippage,e),...r}}catch{return{coinAmountA:new Et.default(0),coinAmountB:new Et.default(0),tokenMaxA:new Et.default(0),tokenMaxB:new Et.default(0),liquidityAmount:new Et.default(0),fix_amount_a:!t.fix_amount_a,...r}}});return cr.fixLiquidityInputs(e,t.slippage,i,!0)}static fixLiquidityInputs(t,e,n,i){let r=n.filter(s=>s.liquidityAmount.gt(be));if(r.length===0)return[];let o=r[0];return n.map(s=>{if(s.liquidityAmount.eq(be)){let a=te(o.liquidityAmount.toString()).mul(s.ratio).div(o.ratio).toFixed(0),c=ve.tickIndexToSqrtPriceX64(s.tick_lower),u=ve.tickIndexToSqrtPriceX64(s.tick_upper),d=dn.getCoinAmountFromLiquidity(new Et.default(a.toString()),t,c,u,!1);return{coinAmountA:d.coinA,coinAmountB:d.coinB,liquidityAmount:new Et.default(a.toString()),fix_amount_a:s.fix_amount_a,...$c(d,Lo.fromDecimal(te(e).mul(100)),i)}}return s})}static calculateCoinRatios(t,e){let n=new Et.default(ve.tickIndexToSqrtPriceX64(t)),i=[],r=te(0),o=te(0),s=e.map(u=>{let d=te(og(100,6).toString()).mul(u.ratio).toFixed(0).toString(),h=ve.tickIndexToSqrtPriceX64(u.tick_lower),_=ve.tickIndexToSqrtPriceX64(u.tick_upper),C=dn.getCoinAmountFromLiquidity(new Et.default(d),n,h,_,!0);return r=r.add(C.coinA.toString()),o=o.add(C.coinB.toString()),{...C,liquidity:d}}),a=[],c=[];return s.forEach((u,d)=>{let h={coinRatioA:r.eq(te(0))?0:te(u.coinA.toString()).div(r).toNumber(),coinRatioB:o.eq(te(0))?0:te(u.coinB.toString()).div(o).toNumber(),liquiditys:u.liquidity,tick_lower:e[d].tick_lower,tick_upper:e[d].tick_upper};i.push(h),a.push(r.eq(te(0))?0:te(u.coinA.toString()).div(r).toNumber()),c.push(o.eq(te(0))?0:te(u.coinB.toString()).div(o).toNumber())}),i}static calculateCloseMasterLiquidityInputs(t){let e=new Et.default(ve.tickIndexToSqrtPriceX64(t.curr_tick));return t.positions.map(i=>{let r=new Et.default(i.liquidity),o=ve.tickIndexToSqrtPriceX64(i.tick_lower_index),s=ve.tickIndexToSqrtPriceX64(i.tick_upper_index),a=dn.getCoinAmountFromLiquidity(r,e,o,s,!1),c=Lo.fromDecimal(te(t.slippage).mul(100)),{tokenMaxA:u,tokenMaxB:d}=$c(a,c,!1);return{coinAmountA:a.coinA,coinAmountB:a.coinB,tokenMaxA:u,tokenMaxB:d,liquidityAmount:r,fix_amount_a:!1}})}static calculateRemoveMasterLiquidityInputs(t){let e=new Et.default(ve.tickIndexToSqrtPriceX64(t.curr_tick)),{fix_token:n}=t;if(n){let r=t.positions.map((a,c)=>({tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,ratio:t.ratios[c]})),o=cr.calculateCoinRatios(t.curr_tick,r),s=t.positions.map((a,c)=>{let u=o[c],d=te(n.coin_amount).mul(n.fix_amount_a?u.coinRatioA:u.coinRatioB).toFixed(0).toString();try{let h=dn.estLiquidityAndcoinAmountFromOneAmounts(a.tick_lower_index,a.tick_upper_index,new Et.default(d),n.fix_amount_a,!1,t.slippage,e);return{...h,tick_lower:a.tick_lower_index,tick_upper:a.tick_upper_index,liquidity:h.liquidityAmount.toString(),ratio:t.ratios[c]}}catch{return{coinAmountA:new Et.default(0),coinAmountB:new Et.default(0),tokenMaxA:new Et.default(0),tokenMaxB:new Et.default(0),liquidityAmount:new Et.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[c]}}});return cr.fixLiquidityInputs(e,t.slippage,s,!1)}return t.positions.map((r,o)=>{let s=t.ratios[o],a=te(t.liquidity).mul(s).toFixed(0);te(a).greaterThan(r.liquidity)&&(a=r.liquidity);let c=ve.tickIndexToSqrtPriceX64(r.tick_lower_index),u=ve.tickIndexToSqrtPriceX64(r.tick_upper_index),d=dn.getCoinAmountFromLiquidity(new Et.default(a),e,c,u,!1),h=Lo.fromDecimal(te(t.slippage).mul(100)),{tokenMaxA:_,tokenMaxB:C}=$c(d,h,!1);return{coinAmountA:d.coinA,coinAmountB:d.coinB,tokenMaxA:_,tokenMaxB:C,liquidityAmount:new Et.default(a),fix_amount_a:!1}})}static buildMasterPosition(t){return{coin_type_a:ge(t.coin_type_a.fields.name).full_address,coin_type_b:ge(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:Kn(BigInt(t.tick_lower_index.fields.bits)),tick_upper_index:Kn(BigInt(t.tick_upper_index.fields.bits)),url:t.url}}static buildMasterNFT(t){let e=an(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:Kn(BigInt(e.tick_lower_index)),tick_upper_index:Kn(BigInt(e.tick_upper_index)),positions:[],...Td(t)};return n.positions=e.positions.map(i=>cr.buildMasterPosition(i.fields)),n}}},Vi=class{static generateNextTickRange(t,e,n){let i=t-e/2,r=t+e/2;return{new_tick_lower:Vi.getValidTickIndex(i,n),new_tick_upper:Vi.getValidTickIndex(r,n)}}static calculateDepositRatio(t,e,n){let i=ve.sqrtPriceX64ToTickIndex(n);if(i<t)return{ratioA:new J(1),ratioB:new J(0)};if(i>e)return{ratioA:new J(0),ratioB:new J(1)};let r=new C0.default(1e8),{coinAmountB:o}=dn.estLiquidityAndcoinAmountFromOneAmounts(t,e,r,!0,!0,0,n),s=ve.sqrtPriceX64ToPrice(n,0,0),a=te(r.toString()).mul(s),c=a.add(o.toString()),u=a.div(c),d=te(o.toString()).div(c);return{ratioA:u,ratioB:d}}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":te(t.total_supply).mul(e).div(t.liquidity).toFixed(0,J.ROUND_DOWN).toString()}static get_share_liquidity_by_amount(t,e){return t.total_supply==="0"?"0":te(e).mul(t.liquidity).div(t.total_supply).toFixed(0,J.ROUND_DOWN).toString()}static get_protocol_fee_amount(t,e){return te(e).mul(t.protocol_fee_rate).div(mI).toFixed(0,J.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:ge(e.coin_type_a.fields.name).full_address,coinTypeB:ge(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:Kn(BigInt(e.tick_lower_index.fields.bits)),tick_upper_index:Kn(BigInt(e.tick_upper_index.fields.bits)),rewards:[]}}static buildPool(t){let e=an(t),n=Uo(t),{positions:i}=e;if(e&&i.length>0){let r=Vi.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:ge(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}}}},Bu=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 c=0;e<o?c=e:c=o;let u=wn.TickMath.tickIndexToSqrtPriceX64(a),d=wn.TickMath.tickIndexToSqrtPriceX64(c),{coinA:h,coinB:_}=wn.ClmmPoolUtil.getCoinAmountFromLiquidity(new qf.default(n),new qf.default(s),u,d,!0);return(0,wn.d)(h.toString()).mul(i).div(1e12).add(_.toString()).toString()}static buildFramsPool(t){let e=(0,wn.getObjectFields)(t);if(e)try{let n=[];return e.rewarders.forEach(r=>{n.push({reward_coin:(0,wn.extractStructTagFromType)(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:(0,wn.asIntN)(BigInt(e.effective_tick_lower.fields.bits)),effective_tick_upper:(0,wn.asIntN)(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=(0,wn.getObjectFields)(t);if(e){let n=e.clmm_postion.fields;return{id:e.id.id,url:n.url,pool_id:e.pool_id,coinTypeA:(0,wn.extractStructTagFromType)(n.coin_type_a.fields.name).full_address,coinTypeB:(0,wn.extractStructTagFromType)(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:(0,wn.asIntN)(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:(0,wn.asIntN)(BigInt(n.tick_upper_index.fields.bits)),rewards:[]}}}},_I=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(c=>{let u=c.parsedJson;if(u){let d=Wn.buildIdoPoolImmutables(u);s.push(d)}}),o.hasNextPage=a.hasNextPage,o.nextCursor=a.nextCursor,this.updateCache(i,s,se.cacheTime24h)}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=Wn.buildIdoPool(o);await Wn.calculatePoolUiPrice(this._sdk,s),n.push(s);let a=`${s.pool_address}_getPoolObject`;this.updateCache(a,s,se.cacheTime24h)}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=Wn.buildIdoPool(r);return await Wn.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=(0,se.getObjectPreviousTransactionDigest)(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(c=>{console.log("item: ",c);let u=c.parsedJson;if(u)switch((0,se.extractStructTagFromType)(c.type).full_address){case`${e}::config::InitConfigEvent`:a.admin_cap_id=u.admin_cap_id,a.package_version_id=u.package_version_id;break;case`${e}::factory::InitFactoryEvent`:a.pools_id=u.pools_id;break;default:break}}),this.updateCache(n,a,se.cacheTime24h)),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=Wn.buildPurchaseInfo((0,se.getObjectFields)(o));return this.updateCache(i,s,se.cacheTime5min),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(0,se.buildPosition)(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=(0,se.getObjectFields)(o);if(s){let a=s.nft.fields,c={locked_at:Number(s.locked_at),lock_duration:Number(s.lock_duration),lock_nft_id:s.id.id,type:s.nft.type,...a};c.end_lock_time=c.locked_at+c.lock_duration,c.coin_type_a=(0,se.extractStructTagFromType)(a.coin_type_a.fields.name).full_address,c.coin_type_b=(0,se.extractStructTagFromType)(a.coin_type_b.fields.name).full_address,c.id=a.id.id,c.tick_lower_index=(0,se.asIntN)(BigInt(a.tick_lower_index.fields.bits)),c.tick_upper_index=(0,se.asIntN)(BigInt(a.tick_upper_index.fields.bits)),i.push(c)}}return i}catch(r){return console.log("getLockNFTList:",r),[]}}async creatPool(t){let{ido:e}=this.sdk.sdkOptions;(0,se.isSortedSymbols)((0,Wi.normalizeSuiAddress)(t.coin_type_sale),(0,Wi.normalizeSuiAddress)(t.coin_type_raise))&&(t.price_min=(0,se.d)(1).div(t.price_max).toNumber(),t.price_max=(0,se.d)(1).div(t.price_min).toNumber());let i=Ki.priceRealToFix(Number(t.price),t.sale_decimals,t.raise_decimals),r=se.TickMath.priceToSqrtPriceX64((0,se.d)(t.price_min),t.sale_decimals,t.raise_decimals).toString(),o=se.TickMath.priceToSqrtPriceX64((0,se.d)(t.price_max),t.sale_decimals,t.raise_decimals).toString(),s=new ri.TransactionBlock,a=(0,se.d)(t.total_supply).add((0,se.d)(t.total_supply).mul((0,se.d)(t.liquidity_injection_ratio))).toNumber(),c=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.coin_type_sale),u=se.TransactionUtil.buildCoinForAmount(s,c,BigInt(a),t.coin_type_sale,!1),d=[s.pure((0,se.getPackagerConfigs)(e).admin_cap_id),s.pure((0,se.getPackagerConfigs)(e).package_version_id),s.pure((0,se.getPackagerConfigs)(e).pools_id),s.pure((0,Wi.normalizeSuiAddress)(t.owner)),s.pure((0,se.d)(i).mul(Qo).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*T0).toString()),s.pure(r),s.pure(o),s.pure(t.tick_spacing.toString()),u.targetCoin,s.pure(t.protection_hard_cap.toString()),s.pure(se.CLOCK_ADDRESS)],h=[t.coin_type_sale,t.coin_type_raise];return s.moveCall({target:`${e.published_at}::${dI}::create_oversubscribe_pool`,typeArguments:h,arguments:d}),s}async creatPurchasePayload(t){let{ido:e}=this.sdk.sdkOptions,n=new ri.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=se.TransactionUtil.buildCoinForAmount(n,r,BigInt(t.raise_amount),t.coin_type_raise,!1),s=[t.coin_type_sale,t.coin_type_raise],a,c;return i?(c="purchase",a=[n.object((0,se.getPackagerConfigs)(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(se.CLOCK_ADDRESS)]):(c="create_certificate_and_purchase",a=[n.object((0,se.getPackagerConfigs)(e).package_version_id),n.object(t.pool_address),n.pure(t.raise_amount.toString()),o.targetCoin,n.pure(se.CLOCK_ADDRESS)]),n.moveCall({target:`${e.published_at}::${_i}::${c}`,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 ri.TransactionBlock,r=[t.coin_type_sale,t.coin_type_raise],o=[i.pure((0,se.getPackagerConfigs)(e).package_version_id),i.pure(t.pool_address),i.pure(n.purchase_certificate_id),i.pure(se.CLOCK_ADDRESS)];return i.moveCall({target:`${e.published_at}::${_i}::redeem`,typeArguments:r,arguments:o}),i}injectLiquidityPayload(t){let{ido:e}=this.sdk.sdkOptions,{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,i=new ri.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((0,se.getPackagerConfigs)(e).package_version_id),i.pure(t.pool_address),i.pure((0,se.getPackagerConfigs)(n).global_config_id),i.pure(t.clmm_pool_address),i.pure(se.CLOCK_ADDRESS)];return i.moveCall({target:`${e.published_at}::${_i}::${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 ri.TransactionBlock;r.moveCall({target:`${n.published_at}::${se.ClmmIntegratePoolModule}::unpause_pool`,typeArguments:[t.coin_type_a,t.coin_type_b],arguments:[r.object((0,se.getPackagerConfigs)(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((0,se.getPackagerConfigs)(e).package_version_id),r.object(t.pool_address),r.object((0,se.getPackagerConfigs)(i).global_config_id),r.object(t.clmm_pool_address),r.object(se.CLOCK_ADDRESS)];return r.moveCall({target:`${e.published_at}::${_i}::${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&&((0,se.d)(e.current_sqrt_price).lessThanOrEqualTo(t.current_sqrt_price_min)||(0,se.d)(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 ri.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.object((0,se.getPackagerConfigs)(e).package_version_id),n.object(t.pool_address),n.object(se.CLOCK_ADDRESS)];return n.moveCall({target:`${e.published_at}::${_i}::withdraw`,typeArguments:i,arguments:r}),n}updateWhitelistCapPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new ri.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}::${_i}::add_white_listed_addresses`,typeArguments:i,arguments:[n.object((0,se.getPackagerConfigs)(e).admin_cap_id),n.object((0,se.getPackagerConfigs)(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.add_whites.addresses.map(r=>n.object((0,Wi.normalizeSuiObjectId)(r)))}),n.pure(t.add_whites.protection_limit),n.object(se.CLOCK_ADDRESS)]}),t.remove_whites&&t.remove_whites.length>0&&n.moveCall({target:`${e.published_at}::${_i}::remove_white_listed_addresses`,typeArguments:i,arguments:[n.object((0,se.getPackagerConfigs)(e).admin_cap_id),n.object((0,se.getPackagerConfigs)(e).package_version_id),n.object(t.pool_address),n.makeMoveVec({type:"address",objects:t.remove_whites.map(r=>n.object((0,Wi.normalizeSuiObjectId)(r)))}),n.object(se.CLOCK_ADDRESS)]}),t.update_whites&&t.update_whites.forEach(r=>{n.moveCall({target:`${e.published_at}::${_i}::update_white_listed_address`,typeArguments:i,arguments:[n.object((0,se.getPackagerConfigs)(e).admin_cap_id),n.object((0,se.getPackagerConfigs)(e).package_version_id),n.object(t.pool_address),n.object(r.address),n.pure(r.protection_limit),n.object(se.CLOCK_ADDRESS)]})}),n}creatCancelPoolPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new ri.TransactionBlock,i=[t.coin_type_sale,t.coin_type_raise],r=[n.pure((0,se.getPackagerConfigs)(e).admin_cap_id),n.pure((0,se.getPackagerConfigs)(e).package_version_id),n.pure(t.pool_address),n.pure(se.CLOCK_ADDRESS)];return n.moveCall({target:`${e.published_at}::${_i}::cancel`,typeArguments:i,arguments:r}),n}updatePoolOwnerPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new ri.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object((0,se.getPackagerConfigs)(n).admin_cap_id),e.object((0,se.getPackagerConfigs)(n).package_version_id),e.object(t.pool_address),e.object(t.new_owner),e.object(se.CLOCK_ADDRESS)];return e.moveCall({target:`${n.published_at}::${_i}::update_pool_owner`,typeArguments:i,arguments:r}),e}updatePoolDuractionPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new ri.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object((0,se.getPackagerConfigs)(n).admin_cap_id),e.object((0,se.getPackagerConfigs)(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(se.CLOCK_ADDRESS)];return e.moveCall({target:`${n.published_at}::${_i}::update_pool_duration`,typeArguments:i,arguments:r}),e}updateProtectionHardCapPayload(t,e){let{ido:n}=this.sdk.sdkOptions;e=e===void 0?new ri.TransactionBlock:e;let i=[t.coin_type_sale,t.coin_type_raise],r=[e.object((0,se.getPackagerConfigs)(n).admin_cap_id),e.object((0,se.getPackagerConfigs)(n).package_version_id),e.object(t.pool_address),e.pure(t.protection_hard_cap),e.object(se.CLOCK_ADDRESS)];return e.moveCall({target:`${n.published_at}::${_i}::update_protection_hard_cap`,typeArguments:i,arguments:r}),e}unlockNftPayload(t){let{ido:e}=this.sdk.sdkOptions,n=new ri.TransactionBlock,i=[t.nft_type],r=[n.pure(t.lock_nft_id),n.pure(se.CLOCK_ADDRESS)];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:(0,se.getPackagerConfigs)(e).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(r);let o=(0,se.getObjectType)(r),s=(0,se.getObjectOwner)(r),a=!1;return s&&o&&(0,se.extractStructTagFromType)(o).source_address===`${e.package_id}::config::AdminCap`&&(a=(0,Wi.normalizeSuiAddress)(s.AddressOwner)===(0,Wi.normalizeSuiAddress)(t)),this.updateCache(n,a,se.cacheTime24h),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=(0,se.getObjectFields)(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=(0,se.getObjectFields)(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=`${(0,se.getPackagerConfigs)(t).admin_cap_id}_getAdminAddress`,n=this.getCache(e);if(n)return n;let i=await this._sdk.ClmmSDK.fullClient.getObject({id:(0,se.getPackagerConfigs)(t).admin_cap_id,options:{showType:!0,showOwner:!0}});console.log(i);let r=(0,se.getObjectType)(i),o=(0,se.getObjectOwner)(i);if(o&&r&&(0,se.extractStructTagFromType)(r).source_address===`${t.package_id}::config::AdminCap`){let a=(0,Wi.normalizeSuiAddress)(o.AddressOwner);return this.updateCache(e,a,se.cacheTime24h),a}return""}updateCache(t,e,n=se.cacheTime24h){let i=this._cache[t];i?(i.overdueTime=(0,se.getFutureTime)(n),i.value=e):i=new se.CachedContent(e,(0,se.getFutureTime)(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]}},wI=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(c=>{let u=(0,de.extractStructTagFromType)((0,de.getMoveObjectType)(c)).source_address;if(u===s&&c.data&&c.data.content){let{fields:d}=c.data.content;o={...(0,de.buildNFT)(c),id:d.id.id,index:d.index,type:u,xtoken_balance:d.xtoken_balance},this.updateCache(i,o,de.cacheTime24h)}}),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((0,de.extractStructTagFromType)((0,de.getMoveObjectType)(o)).source_address===i&&o.data){let a=ho.buildLockToken(o.data.content),c=await this.getLockXToken(a.id);c&&(a.xtoken_amount=c.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=ho.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 ar.TransactionBlock;return e.moveCall({target:`${t.published_at}::${Yo}::mint_venft`,typeArguments:[],arguments:[e.pure((0,de.getPackagerConfigs)(t).xtoken_manager_id)]}),e}async convertPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new ar.TransactionBlock,i=this.buileTokenCoinType(),r=await de.TransactionUtil.syncBuildCoinInputForAmount(this._sdk.ClmmSDK,n,BigInt(t.amount),i);return t.venft_id===void 0?n.moveCall({target:`${e.published_at}::${Yo}::mint_and_convert`,typeArguments:[],arguments:[n.object((0,de.getPackagerConfigs)(e).lock_manager_id),n.object((0,de.getPackagerConfigs)(e).xtoken_manager_id),r,n.pure(t.amount)]}):n.moveCall({target:`${e.published_at}::${Yo}::convert`,typeArguments:[],arguments:[n.object((0,de.getPackagerConfigs)(e).lock_manager_id),n.object((0,de.getPackagerConfigs)(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 ar.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Yo}::redeem_lock`,typeArguments:[],arguments:[n.pure((0,de.getPackagerConfigs)(e).lock_manager_id),n.pure((0,de.getPackagerConfigs)(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.amount),n.pure(t.lock_day),n.pure(de.CLOCK_ADDRESS)]}),n}redeemPayload(t){let{xtoken:e}=this.sdk.sdkOptions,n=new ar.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Yo}::redeem`,typeArguments:[],arguments:[n.pure((0,de.getPackagerConfigs)(e).lock_manager_id),n.pure((0,de.getPackagerConfigs)(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(de.CLOCK_ADDRESS)]}),n}redeemDividendPayload(t,e){let{xtoken_dividends:n}=this.sdk.sdkOptions,i=new ar.TransactionBlock;return e.forEach(r=>{i.moveCall({target:`${n.published_at}::${Nf}::redeem`,typeArguments:[r],arguments:[i.object((0,de.getPackagerConfigs)(n).dividend_manager_id),i.object(t)]})}),i}redeemDividendV2Payload(t,e,n){let{xtoken_dividends:i}=this.sdk.sdkOptions,r=new ar.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}::${Nf}::redeem_v2`,typeArguments:[s],arguments:[r.object((0,de.getPackagerConfigs)(i).dividend_manager_id),r.object(t),r.object(de.CLOCK_ADDRESS)]})}),r}redeemDividendXTokenPayload(t,e){let{xtoken_dividends:n,xtoken:i}=this.sdk.sdkOptions,{xtoken_manager_id:r,lock_manager_id:o}=(0,de.getPackagerConfigs)(i),{dividend_manager_id:s}=(0,de.getPackagerConfigs)(n);return e=e===void 0?new ar.TransactionBlock:e,e.moveCall({target:`${n.published_at}::${Nf}::redeem_xtoken`,typeArguments:[],arguments:[e.object(o),e.object(r),e.object(s),e.object(t),e.object(de.CLOCK_ADDRESS)]}),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 ar.TransactionBlock;return n.moveCall({target:`${e.published_at}::${Yo}::cancel_redeem_lock`,typeArguments:[],arguments:[n.pure((0,de.getPackagerConfigs)(e).lock_manager_id),n.pure((0,de.getPackagerConfigs)(e).xtoken_manager_id),n.pure(t.venft_id),n.pure(t.lock_id),n.pure(de.CLOCK_ADDRESS)]}),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,de.cacheTime24h),r}async getLockUpManager(t=(0,de.getPackagerConfigs)(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=ho.buildLockUpManager((0,de.getObjectFields)(r));return this.updateCache(n,o,de.cacheTime24h),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=(0,de.getObjectFields)(r);return o&&(i=o.lock_infos.fields.id.id,this.updateCache(e,i,de.cacheTime24h)),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,de.cacheTime24h))}),r}async getDividendManager(t=!1){let{dividend_manager_id:e}=(0,de.getPackagerConfigs)(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=(0,de.getObjectFields)(r),s=ho.buildDividendManager(o);return this.updateCache(n,s,de.cacheTime24h),s}async getXcetusManager(t=!0){let{xtoken_manager_id:e}=(0,de.getPackagerConfigs)(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=(0,de.getObjectFields)(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=(0,de.getObjectFields)(n);return ho.buildVeNFTDividendInfo(i)}catch{return}}async redeemNum(t,e){if(BigInt(t)===BigInt(0))return{amountOut:"0",percent:"0"};let n=await this.getLockUpManager(),i=(0,de.d)(wi).mul((0,de.d)(n.max_lock_day).sub((0,de.d)(e))).mul((0,de.d)(n.max_percent_numerator).sub((0,de.d)(n.min_percent_numerator))).div((0,de.d)(n.max_lock_day).sub((0,de.d)(n.min_lock_day))),r=(0,de.d)(wi).mul((0,de.d)(n.max_percent_numerator)).sub(i).div((0,de.d)(Ru)).div(wi);return{amountOut:(0,de.d)(r).mul((0,de.d)(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=(0,de.d)(wi).mul((0,de.d)(n.max_lock_day).sub((0,de.d)(e))).mul((0,de.d)(n.max_percent_numerator).sub((0,de.d)(n.min_percent_numerator))).div((0,de.d)(n.max_lock_day).sub((0,de.d)(n.min_lock_day))),r=(0,de.d)(wi).mul((0,de.d)(n.max_percent_numerator)).sub(i).div((0,de.d)(Ru)).div(wi);return{amountOut:(0,de.d)(t).div(r).toFixed(0,J.ROUND_UP),percent:r.toString()}}async getLockXToken(t){let{lock_handle_id:e}=(0,de.getPackagerConfigs)(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=(0,de.getObjectFields)(r);if(o){let s=o.value.fields.value.fields;return this.updateCache(n,s,de.cacheTime24h),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=(0,de.getObjectFields)(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=(0,de.getObjectFields)(s),c=a.value.fields.value.fields,u=c.redeemed_num.fields.contents.map(C=>({name:C.fields.key.fields.name,value:C.fields.value})),d=c.bonus_types.map(C=>C.fields.name),h=c.bonus.fields.contents.map(C=>({name:C.fields.key.fields.name,value:C.fields.value})),_={id:(0,de.getObjectId)(s),phase:a.name,settled_num:c.settled_num,register_time:c.register_time,redeemed_num:u,is_settled:c.is_settled,bonus_types:d,bonus:h,phase_end_time:""};return this.updateCache(r,_),_}catch{}}updateCache(t,e,n=de.cacheTime5min){let i=this._cache[t];i?(i.overdueTime=(0,de.getFutureTime)(n),i.value=e):i=new de.CachedContent(e,(0,de.getFutureTime)(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]}},yI=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=te(0),o=te(0),s=[],a=[],c=[],u=[],d=[];t.liquidity_bins.forEach((O,B)=>{let j=t.amounts_a[B],M=t.amounts_b[B],R=t.bins_fix_amount_a[B];r=r.add(j),o=o.add(M),s.push(j),a.push(M),c.push(Mn(BigInt(O.tick_lower)).toString()),u.push(Mn(BigInt(O.tick_upper)).toString()),d.push(R)});let h=[t.coinTypeA,t.coinTypeB],_=new uo.TransactionBlock,C=Ze.buildAddLiquidityFixTokenCoinInput(_,!t.fix_amount_a,r.toString(),t.slippage,t.coinTypeA,i,!1)?.targetCoin,D=Ze.buildAddLiquidityFixTokenCoinInput(_,t.fix_amount_a,o.toString(),t.slippage,t.coinTypeB,i,!1)?.targetCoin;return fI(t)?_.moveCall({target:`${e.published_at}::router::increase_liquidity`,typeArguments:h,arguments:[_.object(ye(e).master_manger_id),_.object(t.master_address),_.object(ye(n).global_config_id),_.object(t.pool_address),C,D,_.pure(s.map(O=>_.pure(O,"u64"))),_.pure(a.map(O=>_.pure(O,"u64"))),_.pure(d.map(O=>_.pure(O,"bool"))),_.object(Ge)]}):_.moveCall({target:`${e.published_at}::router::create_master_liquidity`,typeArguments:h,arguments:[_.object(ye(e).master_manger_id),_.object(ye(n).global_config_id),_.object(t.pool_address),C,D,_.pure(c.map(O=>_.pure(O,"u32"))),_.pure(u.map(O=>_.pure(O,"u32"))),_.pure(s.map(O=>_.pure(O,"u64"))),_.pure(a.map(O=>_.pure(O,"u64"))),_.pure(d.map(O=>_.pure(O,"bool"))),_.pure(t.strategy),_.pure(Mn(BigInt(t.tick_lower)).toString()),_.pure(Mn(BigInt(t.tick_upper)).toString()),_.object(Ge)]}),_}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(ge(o.data.type).full_address===this.buildMasterNFTType()){let a=cr.buildMasterNFT(o);if(a){let c=`${a.id}_masterNFT`;this.updateCache(c,a,tt),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(ge(r.data.type).full_address===this.buildMasterNFTType()){let s=cr.buildMasterNFT(r);return s&&this.updateCache(n,s,tt),s}}catch(r){console.log(r)}}async fetchMasterPositionInfos(t){let e={},{clmm_pool:n,integrate:i,simulationAccount:r}=this.sdk.ClmmSDK.sdkOptions,o=new uo.TransactionBlock;return t.forEach(a=>{a.position_ids.forEach(c=>{let u=[a.coinTypeA,a.coinTypeB],d=[o.object(ye(n).global_config_id),o.object(a.pool_id),o.object(c)];o.moveCall({target:`${i.published_at}::${Zn}::fetch_position_fees`,arguments:d,typeArguments:u}),o.moveCall({target:`${i.published_at}::${Zn}::fetch_position_rewards`,arguments:[...d,o.object(Ge)],typeArguments:u})})}),(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address})).events?.forEach(a=>{let{parsedJson:c}=a,{position_id:u}=c,d=e[u];switch(d===void 0&&(d={position_id:u,feeOwedA:"0",feeOwedB:"0",rewarders:[]},e[u]=d),ge(a.type).name){case"FetchPositionFeesEvent":d.feeOwedA=c.fee_owned_a,d.feeOwedB=c.fee_owned_b;break;case"FetchPositionRewardsEvent":d.rewarders=c.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 c=await this._sdk.ClmmSDK.fullClient.getObject({id:a.id,options:{showContent:!0}}),u=an(c);o.master_liquidity_handle=u.position_maps.fields.id.id;break}this.updateCache(n,o,tt)}return o}removeMasterLiquidity(t){let{clmm_pool:e}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:n}=this.sdk.sdkOptions,i=new uo.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(ye(n).master_manger_id),i.object(t.pool_address),i.object(t.master_address),i.object(ye(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(Ge)];return i.moveCall({target:`${n.published_at}::${Du}::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 uo.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}::${Du}::close_master_liquidity`,typeArguments:r,arguments:[i.object(ye(n).master_manger_id),i.object(t.master_address),i.object(ye(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(Ge)]}),i}collectFee(t,e){let{clmm_pool:n}=this.sdk.ClmmSDK.sdkOptions,{liquidity_stratefy:i}=this.sdk.sdkOptions;e=e===void 0?new uo.TransactionBlock:e;let r=[t.coinTypeA,t.coinTypeB],o=[e.object(ye(i).master_manger_id),e.object(t.master_address),e.object(ye(n).global_config_id),e.object(t.pool_address)];return e.moveCall({target:`${i.published_at}::${Du}::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 uo.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(ye(i).master_manger_id),e.object(t.master_address),e.object(ye(n).global_config_id),e.object(t.pool_address),e.object(ye(n).global_vault_id),e.object(Ge)];e.moveCall({target:`${i.published_at}::${Du}::collect_reward`,typeArguments:o,arguments:s})}}),e}updateCache(t,e,n=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},bI=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildCoinInput(t,e,n,i,r){let{selectedCoins:o,remainingCoins:s}=et.selectCoinAssetGreaterThanOrEqual(e,BigInt(i)),a=et.calculateTotalBalance(o);if(a<BigInt(i))throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${i} `);let c=a-BigInt(i),u;if(et.isSuiCoin(n))u=t.splitCoins(t.gas,[t.pure(i)]);else{let[d,...h]=o.map(_=>_.coinObjectId);u=t.object(d),h.length>0?r?t.mergeCoins(u,[...h.map(_=>t.object(_)),r]):t.mergeCoins(u,[...h.map(_=>t.object(_))]):r&&t.mergeCoins(u,[r])}return{selectedUnusedAmount:c,coinInput:u,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 lo.TransactionBlock,s,a;if(t.swapParams){let h=await this.handleDepositSwap(t,o,r);s=h.primaryCoinAInputs,a=h.primaryCoinBInputs}else s=Ze.buildAddLiquidityFixTokenCoinInput(o,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,r,!1)?.targetCoin,a=Ze.buildAddLiquidityFixTokenCoinInput(o,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,r,!1)?.targetCoin;let c=ye(e),u=ye(n),d=ye(i);return o.moveCall({target:`${e.published_at}::${hI}::deposit`,typeArguments:[t.coinTypeA,t.coinTypeB,t.lp_token_type],arguments:[o.object(c.vaults_manager_id),o.object(t.vault_id),o.object(u.rewarder_manager_id),o.object(u.global_config_id),o.object(t.farming_pool),o.object(d.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(Ge)]}),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:c}=t.swapParams,u=s?t.coinTypeA:t.coinTypeB,d=Ze.buildCoinForAmount(e,n,BigInt(o),u,!1),h=BigInt(d.tragetCoinAmount)-BigInt(o),_=[];if(c){let j=this.requestStakeCoin(c,e,d.targetCoin),M=Ze.buildCoinForAmount(e,d.remainCoins,BigInt(0),u,!1).targetCoin;_=s?[M,j]:[j,M]}else if(a){let j=Ze.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),M=await Ze.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,a,d,j,"",t.slippage,e);_=s?[M.fromCoin,M.toCoin]:[M.toCoin,M.fromCoin],console.log("swapCoinInputTo.isMintZeroCoin: ",j),!j.isMintZeroCoin&&j.originalSplitedCoin===void 0&&e.transferObjects([j.targetCoin],e.pure(this._sdk.getVerifySenderAddress()))}else{let j=Ze.buildCoinForAmount(e,n,0n,s?t.coinTypeB:t.coinTypeA,!1),M=Ii.getDefaultSqrtPriceLimit(s).toString();_=e.moveCall({target:`${r.published_at}::${Cr}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[e.object(ye(i).global_config_id),e.object(t.clmm_pool),s?d.targetCoin:j.targetCoin,s?j.targetCoin:d.targetCoin,e.pure(s),e.pure(!0),e.pure(o),e.pure(M),e.pure(!1),e.object(Ge)]})}let C,D,O=_[0],B=_[1];if(s){let j=BigInt(t.amount_a)-h;et.isSuiCoin(u)?(e.transferObjects([O],e.pure(this._sdk.getVerifySenderAddress())),C=e.splitCoins(e.gas,[e.pure(t.amount_a)])):j>0n?C=this.buildCoinInput(e,d.remainCoins,u,j,O).coinInput:C=O,D=B}else{C=O;let j=BigInt(t.amount_b)-h;et.isSuiCoin(u)?(e.transferObjects([B],e.pure(this._sdk.getVerifySenderAddress())),D=e.splitCoins(e.gas,[e.pure(t.amount_b)])):j>0n?D=this.buildCoinInput(e,d.remainCoins,u,j,B).coinInput:D=B}return{primaryCoinAInputs:C,primaryCoinBInputs:D}}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 lo.TransactionBlock,s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),t.lp_token_type),a=Ze.buildCoinForAmount(o,s,BigInt(t.lp_token_amount),t.lp_token_type,!1).targetCoin,c=ye(e),u=ye(n),d=ye(i),h=[t.coinTypeA,t.coinTypeB,t.lp_token_type],_=o.moveCall({target:`${e.published_at}::${pI}::remove`,typeArguments:h,arguments:[o.object(c.vaults_manager_id),o.object(t.vault_id),o.object(u.rewarder_manager_id),o.object(u.global_config_id),o.object(t.farming_pool),o.object(d.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(Ge)]}),C=_[0],D=_[1];if(t.swapParams){let{a2b:O,swap_amount:B,route_obj:j}=t.swapParams;if(j){let M={targetCoin:O?C:D,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},R={targetCoin:O?D:C,remainCoins:[],isMintZeroCoin:!1,tragetCoinAmount:""},K=await Ze.buildAggregatorSwapReturnCoins(this._sdk.ClmmSDK,j,M,R,"",t.slippage,o),X=O?[K.fromCoin,K.toCoin]:[K.toCoin,K.fromCoin];O?o.mergeCoins(X[1],[D]):o.mergeCoins(X[0],[C]),o.transferObjects([...X],o.pure(this._sdk.getVerifySenderAddress()))}else{let M=Ii.getDefaultSqrtPriceLimit(O).toString(),R=o.moveCall({target:`${r.published_at}::${Cr}::swap`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:[o.object(ye(i).global_config_id),o.object(t.clmm_pool),C,D,o.pure(O),o.pure(!0),o.pure(B),o.pure(M),o.pure(!0),o.object(Ge)]});o.transferObjects([R[0],R[1]],o.pure(this._sdk.getVerifySenderAddress()))}}else o.transferObjects([C,D],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=Vi.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}=ye(n);return i.length===0?void 0:i.filter(o=>{let s=ge(o.from_coin_type).full_address,a=ge(o.to_coin_type).full_address,c=ge(t).full_address,u=ge(e).full_address;return c===s&&u===a||c===a&&u===s})[0]?.staking_id||void 0}savePoolToCache(t){let e=`${t.id}_mirrorPool`;this.updateCache(e,t,tt)}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 lo.TransactionBlock,r=ve.tickIndexToSqrtPriceX64(t.lowerTick),o=ve.tickIndexToSqrtPriceX64(t.upperTick),s=new ht.default(t.curSqrtPrice),a=dn.getCoinAmountFromLiquidity(new ht.default(t.input_amount),s,r,o,!1),c=[t.coinTypeA,t.coinTypeB];i.moveCall({target:`${e.published_at}::${Zn}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!0),i.pure(!0),i.pure(a.coinA.toString())],typeArguments:c}),i.moveCall({target:`${e.published_at}::${Zn}::calculate_swap_result`,arguments:[i.object(t.clmm_pool),i.pure(!1),i.pure(!0),i.pure(a.coinB.toString())],typeArguments:c});let d=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(O=>ge(O.type).name==="CalculatedSwapResultEvent");if(d.length===0)return null;let h=d[0].parsedJson.data,_=d[1].parsedJson.data,C=te(a.coinB.toString()).add(h.amount_out),D=te(a.coinA.toString()).add(_.amount_out);return{maxAmountB:C,maxAmountA:D}}async calculateRemoveSwapAmount(t,e){let n=Vi.calculateDepositRatio(t.lowerTick,t.upperTick,new ht.default(t.curSqrtPrice)),i=t.fix_amount_a?n.ratioA:n.ratioB;console.log({fixRatio:i});let r=te(t.receive_amount).mul(i),o,s;if(t.removeLiquidity){let O=ve.tickIndexToSqrtPriceX64(t.lowerTick),B=ve.tickIndexToSqrtPriceX64(t.upperTick),j=dn.getCoinAmountFromLiquidity(new ht.default(t.removeLiquidity),new ht.default(t.curSqrtPrice),O,B,!1);s=t.removeLiquidity,o=t.fix_amount_a?j.coinB.toString():j.coinA.toString(),r=t.fix_amount_a?te(j.coinA.toString()):te(j.coinB.toString())}else{let O=dn.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ht.default(r.toFixed(0)),t.fix_amount_a,!1,.2,new ht.default(t.curSqrtPrice));s=O.liquidityAmount.toString(),o=t.fix_amount_a?O.coinAmountB.toString():O.coinAmountA.toString()}console.log({fixAmount:r,otherSideAmount:o});let a=!t.fix_amount_a,c=await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,te(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:c,range:e});let u=r.add(c.amount_out),d=te(t.receive_amount),h=d.sub(u);if(console.log(`\u5B9E\u9645\u5F97\u5230: ${u.toString()} , \u671F\u671B\u5F97\u5230: ${t.receive_amount}, \u5269\u4F59: ${h.toString()} `),(!t.removeLiquidity||t.removeLiquidity&&e)&&h.abs().greaterThan(d.mul(.01))){let O=u.lessThan(d),B,j;e?O?(B=te(s),j=e.right):(B=e.left,j=te(s)):(B=O?te(s):te(0),j=O?te(t.maxLiquidity):te(s));let M=te(B).add(j).div(2).toFixed(0);if(console.log({left:B.toString(),right:j.toString(),midLiquidity:M.toString()}),!e||e&&e.count<15&&B<j)return await this.calculateRemoveSwapAmount({...t,removeLiquidity:M},{left:B,right:j,count:e?e.count+1:0})}let _=c.amount_in&&c.fee_amount?new ht.default(c.amount_in).add(new ht.default(c.fee_amount)).toString():c.amount_in,C=c.amount_out,{is_exceed:D}=c;return{swapInAmount:_,swapOutAmount:C,liquidity:s,is_exceed:D,routeObj:c.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=dn.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,new ht.default(r.toString()),!t.fixCoinA,!0,0,new ht.default(t.curSqrtPrice)),s=t.fixCoinA?o.coinAmountA.toString():o.coinAmountB.toString(),a=te(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=ve.sqrtPriceX64ToTickIndex(new ht.default(t.curSqrtPrice)),{ratioA:i,ratioB:r}=Vi.calculateDepositRatio(t.lowerTick,t.upperTick,new ht.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:n,adjustBestAmount:e});let o=te(t.input_amount).mul(t.fix_amount_a?i:r),s=te(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(et.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||et.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let Y=await this.calculateHaedalDepositFixSui({inputSuiAmount:te(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 J(s.toFixed(0)):new J(0),rightSuiAmount:a?new J(t.input_amount):new J(s.toFixed(0)),staking_id:t.staking_id});return Y?{...Y,request_id:t.request_id}:null}throw Error("Only support fix sui")}let c=n<t.lowerTick||n>t.upperTick,u={clmm_pool:t.clmm_pool,curSqrtPrice:t.curSqrtPrice,a2b:a,amount_a:a?new J(t.input_amount):new J(0),amount_b:a?new J(0):new J(t.input_amount),amount_left:a?new J(s.toFixed(0)):new J(0),amount_right:a?new J(t.input_amount):new J(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},d=e&&n<=t.upperTick,h=d?await this.calculateRebalance(u):await this.clmmPreSwap(t.clmm_pool,t.curSqrtPrice,a,s,t.coinTypeA,t.coinTypeB,!0,t.priceSplitPoint,t.use_route),_=h.after_sqrt_price,C=ve.sqrtPriceX64ToTickIndex(new ht.default(_));console.log("1110 \u9996\u6B21\u8BA1\u7B97 \u7ED3\u679C: ",{...h,currentTick:C},null,2);let D=C<t.lowerTick||C>t.upperTick;if(c!==D&&!d&&C<=t.upperTick){console.log("1110 \u533A\u95F4\u53D1\u751F\u53D8\u5316, \u518D\u6B21\u8FDB\u884Cswap: ");let{ratioA:Y,ratioB:oe}=Vi.calculateDepositRatio(t.lowerTick,t.upperTick,new ht.default(_));console.log("1110 ",{newAfterRatioA:Y,newAfterRatioB:oe}),s=te(t.input_amount).sub(te(t.input_amount).mul(t.fix_amount_a?Y:oe)),u.amount_left=a?new J(s.toFixed(0)):new J(0),u.amount_right=a?new J(t.input_amount):new J(s.toFixed(0)),h=await this.calculateRebalance(u),_=h.after_sqrt_price;let $=ve.sqrtPriceX64ToTickIndex(new ht.default(_));console.log("1110 \u518D\u6B21\u8BA1\u7B97\u53D8\u5316\u540E: ",{lowerTick:t.lowerTick,upperTick:t.upperTick,currentTick:$,afterSqrtPrice:_})}let{ratioA:O,ratioB:B}=Vi.calculateDepositRatio(t.lowerTick,t.upperTick,new ht.default(_));console.log("1110 1",{afterRatioA:O,afterRatioB:B,data:h});let j=B.div(O).sub(r.div(i)).greaterThan("0"),M=h.amount_in&&h.fee_amount?new ht.default(h.amount_in).add(new ht.default(h.fee_amount)).toString():h.amount_in,R=h.amount_out,{is_exceed:K}=h;if(C<t.lowerTick)j=!0;else if(C>t.upperTick)j=!1;else{let Y=j===a?new ht.default(te(t.input_amount).sub(M).toString()):new ht.default(R),oe=dn.estLiquidityAndcoinAmountFromOneAmounts(t.lowerTick,t.upperTick,Y,j,!0,0,new ht.default(_)),$=oe.coinAmountA,ne=oe.coinAmountB,G=te(t.fix_amount_a?$.toString():ne.toString()).add(M);console.log("1110 \u5B9E\u9645\u6D88\u8017:",{preAmountTotal:G.toString(),fixAmountA:j}),G.greaterThanOrEqualTo(t.input_amount)&&(j=!j)}let X={swapInAmount:M,swapOutAmount:R,afterSqrtPrice:_,is_exceed:K,fixAmountA:j,routeObj:h.route_obj,request_id:t.request_id,use_Haedal_stake:!1};return console.log(X),X}async calculateHaedalDepositSwapAmount(t){let e=ve.sqrtPriceX64ToTickIndex(new ht.default(t.curSqrtPrice)),{ratioA:n,ratioB:i}=Vi.calculateDepositRatio(t.lowerTick,t.upperTick,new ht.default(t.curSqrtPrice));console.log("1110 calculateDepositSwapAmount params: ",{...t,currentTick:e});let r=te(t.input_amount).mul(t.fix_amount_a?n:i),o=te(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(et.isSuiCoin(t.coinTypeA)&&t.fix_amount_a||et.isSuiCoin(t.coinTypeB)&&!t.fix_amount_a){let a=await this.calculateHaedalDepositFixSui({inputSuiAmount:te(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 J(o.toFixed(0)):new J(0),rightSuiAmount:s?new J(t.input_amount):new J(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:c,amount_right:u,coinTypeA:d,coinTypeB:h,useRoute:_,priceSplitPoint:C,remainRate:D}=t,O=async(B,j,M)=>{let R=B.plus(j).div(2),K=await this.clmmPreSwap(e,i,n,R,d,h,!0,C,_);if(K.amount_out==="0")return K;if(K.after_sqrt_price||(K.after_sqrt_price=t.curSqrtPrice),K.is_exceed)return j=R,O(B,j,M+1);let X=n?r.sub(K.amount_in):r.add(K.amount_out),Y=n?o.add(K.amount_out):o.sub(K.amount_in),oe=ve.sqrtPriceX64ToTickIndex(new ht.default(K.after_sqrt_price)),$=dn.estLiquidityAndcoinAmountFromOneAmounts(s,a,new ht.default(X.toString()),!0,!0,1,new ht.default(K.after_sqrt_price)),ne=new J($.coinAmountA.toString()),G=new J($.coinAmountB.toString());if(console.log("1110 swap\u9012\u5F52\u8BA1\u7B97 ",{preRes:K,left:B.toString(),right:j.toString(),mid:R.toString(),afterPoolTickIndex:oe,afterA:X.toString(),afterB:Y.toString(),usedA:ne.toString(),usedB:toString(),count:M}),ne.toString()!==X.toString())throw new Error("usedA does not match afterA");if(Y.lessThan(G))n?B=R:j=R;else{n?j=R:B=R;let W=Y.sub(G),I=Y.mul(D);if(console.log("1110 \u5269\u4F59\u672A\u4F7F\u7528amount ",{remainingB:W.toString(),maxRemainingB:I.toString(),remainRate:D,count:M}),I.sub(W).greaterThanOrEqualTo(0))return console.log("break"),{...K,remainingB:W}}return B.greaterThan(j)||j.sub(B).lessThan(10)?K:O(B,j,M+1)};return c.greaterThanOrEqualTo(u)?O(new J(0),c,0):O(c,u,0)}async clmmPreSwap(t,e,n,i,r,o,s,a,c,u){if(c)try{let j=await this._sdk.ClmmSDK.RouterV2.getBestRouter(n?r:o,n?o:r,Number(i.toFixed(0)),s,a,"",void 0,void 0,!0,!1,u);if(!j.result)throw new Error("route unavailable");let{result:M}=j,R=e;return M.splitPaths.forEach(K=>{let X=K.basePaths.find(Y=>Y.poolAddress.toLowerCase()===t.toLowerCase());X&&(R=X.afterSqrtPrice.toString())}),{amount_in:M.inputAmount.toString(),amount_out:M.outputAmount.toString(),after_sqrt_price:R,is_exceed:M.isExceed,route_obj:M}}catch{throw new Error("route unavailable")}let{integrate:d,simulationAccount:h}=this.sdk.ClmmSDK.sdkOptions,_=new lo.TransactionBlock,C=[r,o],D=[_.pure(t),_.pure(n),_.pure(s),_.pure(i.toFixed(0))];_.moveCall({target:`${d.published_at}::${Zn}::calculate_swap_result`,arguments:D,typeArguments:C});let B=(await this.sdk.ClmmSDK.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:h.address})).events?.filter(j=>ge(j.type).name==="CalculatedSwapResultEvent");return B.length===0?null:B[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=Vi.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 c=await this._sdk.ClmmSDK.fullClient.getObject({id:o.vaults_manager_id,options:{showContent:!0}}),u=an(c);o.vaults_pool_handle=u.vault_to_pool_maps.fields.id.id;break}this.updateCache(n,o,tt)}return o}async getExchangeRateForHaedal(t,e,n){let{haedal:i}=this._sdk.sdkOptions,{simulationAccount:r}=this._sdk.ClmmSDK.sdkOptions;try{let o=new lo.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 u=s.events.find(C=>C.type.includes("UserStaked")),{sui_amount:d,st_amount:h}=u.parsedJson,_=te(d).div(h).toString();return console.log({st_amount:h,sui_amount:d,rate:_}),_}let a=s.results[0].returnValues[0][0],c=Lf.bcs.de("u64",Uint8Array.from(a))/1e6;return console.log("rate ",Lf.bcs.de("u64",Uint8Array.from(a))),c.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,ta.normalizeSuiObjectId)("0x5")),e.object(t),n,e.pure((0,ta.normalizeSuiObjectId)("0x0"))]})}async requestStake(t,e,n){let{haedal:i}=this._sdk.sdkOptions,r=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.getVerifySenderAddress(),Es);n=n||new lo.TransactionBlock;let o;if(e>95e10){let[s,...a]=r;a.length>0&&n.mergeCoins(n.object(s.coinObjectId),a.map(c=>n.object(c.coinObjectId))),o=n.splitCoins(n.object(s.coinObjectId),[e])}else o=Ze.buildCoinForAmount(n,r,BigInt(e),Es,!1,!0).targetCoin;return n.moveCall({target:`${i.published_at}::interface::request_stake`,typeArguments:[],arguments:[n.object((0,ta.normalizeSuiObjectId)("0x5")),n.object(t),o,n.pure((0,ta.normalizeSuiObjectId)("0x0"))]}),n}updateCache(t,e,n=Ar){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},Mu=class{static buildOrderLimitEvent(t){let{events:e}=t,n=[];return e&&e.forEach(i=>{let r=ge(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=an(t),n=Uo(t);if(e&&n)try{let i=ge(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=te(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 te(t).mul(te(10).pow(i)).toString()}static calculateRate(t,e,n){let i=20+e-n;return Number(t)/10**i}},vI=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}=ye(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:ge(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}=ye(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,c={pay_coin_type:ge(a.pay_coin.fields.name).full_address,target_coin_type:ge(a.target_coin.fields.name).full_address,indexer_id:a.indexer_id};return this._sdk.updateCache(`${c.pay_coin_type}_${c.target_coin_type}`,c.indexer_id),c})}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(u=>u.name.value),c=(await n.batchGetObjects(s,{showContent:!0})).map(u=>Mu.buildLimitOrderInfo(u)).filter(u=>u!==void 0);i.data=c}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=an(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=an(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=an(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 Mu.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(...Mu.buildOrderLimitEvent(r))}),i}catch(n){return console.error("Error in getLimitOrderLogs:",n),[]}}buildRateOrdersIndexerType(t){let{limit_order:e}=this._sdk.sdkOptions;return Nc(`${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}=ye(e),o=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress,t.pay_coin_type),s=new Nu.TransactionBlock,a=await this.getPoolIndexerId(t.pay_coin_type,t.target_coin_type),c=Ze.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),c.targetCoin,s.pure(Mu.calculateFormatRate(t.rate,t.pay_decimal,t.target_decimal)),s.pure(t.expired_ts),s.object(Ge)]}),s}async cancelOrdersByOwner(t){let{limit_order:e}=this._sdk.sdkOptions,{global_config_id:n}=ye(e),i=new Nu.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(Ge)]})}),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 Nu.TransactionBlock;r.moveCall({target:`${n.published_at}::limit_order::get_orders_indexer_by_owner`,typeArguments:[],arguments:[r.pure(t),r.object(ye(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=tt){let i=this._cache[t];i?(i.overdueTime=gn(n),i.value=e):i=new xi(e,gn(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]}},kI=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=Bu.buildFramsPool(s);a&&(a.rewarders=await this.getFramsRewarderConfig(a.clmm_pool_id,a.rewarders.map(c=>c.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=Bu.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 c=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:(0,_e.getPackagerConfigs)(i).rewarder_manager_handle,name:{type:"0x1::type_name::TypeName",value:(0,_e.removeHexPrefix)(o)}}),{fields:u}=c.data.content.fields.value.fields.value,d={reward_coin:o,last_reward_time:u.last_reward_time,emission_per_second:u.emission_per_second,total_allocate_point:u.total_allocate_point,allocate_point:""},h=u.pools.fields.id.id,_=await this._sdk.ClmmSDK.fullClient.getDynamicFieldObject({parentId:h,name:{type:"0x2::object::ID",value:t}}),{allocate_point:C}=_.data.content.fields.value.fields.value.fields;d.allocate_point=C,this.updateCache(s,d),r.push(d)}catch(c){console.log(c)}}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={},c=[],u=e.length>0,d=await this._sdk.ClmmSDK.fullClient.getOwnedObjectsByPage(t,{filter:{StructType:`${o}::pool::WrappedPositionNFT`},options:{showContent:!0}},r);s.hasNextPage=d.hasNextPage,s.nextCursor=d.nextCursor;for(let h of d.data){let _=Bu.buildFramsPositionNFT(h);if(_)if(u){if(e.includes(_.pool_id)){c.push(_);let C=a[_.pool_id];C?C.push(_):C=[_],a[_.pool_id]=C}}else c.push(_)}if(n&&c.length>0){let h=await this.calculateFarmingRewards(c.map(_=>({pool_id:_.pool_id,position_nft_id:_.id,clmm_pool_id:_.clmm_pool_id})),i);u?(a={},c.forEach(_=>{h[_.id]&&(_.rewards=h[_.id]);let D=a[_.pool_id];D?D.push(_):D=[_],a[_.pool_id]=D})):c.forEach(_=>{h[_.id]&&(_.rewards=h[_.id])})}return u?a:(s.data=c,s)}async getFramsPositionNFT(t,e=!0){let n=await this._sdk.ClmmSDK.fullClient.getObject({id:t,options:{showContent:!0,showType:!0}}),i=Bu.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 oi.TransactionBlock,{rewarder_manager_id:r,global_config_id:o}=(0,_e.getPackagerConfigs)(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(_e.CLOCK_ADDRESS)]})});let s={};try{let a=await this._sdk.ClmmSDK.fullClient.sendSimulationTransaction(i,this._sdk.ClmmSDK.senderAddress,e);console.log({simulateRes:a});let c=a?.events?.filter(u=>(0,_e.extractStructTagFromType)(u.type).name==="AccumulatedPositionRewardsEvent");if(c&&c.length>0)for(let u=0;u<c.length;u+=1){let{parsedJson:d}=c[u],h=[];d.rewards.contents.forEach(_=>{h.push({rewarder_type:(0,_e.extractStructTagFromType)(_.key.name).full_address,rewarder_amount:_.value})}),s[d.wrapped_position_id]=h}}catch(a){console.log(a)}return s}depositPayload(t,e){let{frams:n}=this.sdk.sdkOptions;e=e||new oi.TransactionBlock;let{global_config_id:i,rewarder_manager_id:r}=(0,_e.getPackagerConfigs)(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(_e.CLOCK_ADDRESS)]}),e}async withdrawPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{global_config_id:i,rewarder_manager_id:r}=(0,_e.getPackagerConfigs)(n);return e=e||new oi.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(_e.CLOCK_ADDRESS)]}),e}async batchHarvestPayload(t,e){e=e||new oi.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 oi.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}=(0,_e.getPackagerConfigs)(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(_e.CLOCK_ADDRESS)]})}),e}async claimFeeAndClmmReward(t){let e=new oi.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 oi.TransactionBlock,{clmm_pool:n,integrate:i}=this._sdk.ClmmSDK.sdkOptions,r=(0,_e.getPackagerConfigs)(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((0,_e.asUintN)(BigInt(t.tick_lower)).toString()),e.pure((0,_e.asUintN)(BigInt(t.tick_upper)).toString())]}),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=_e.TransactionUtil.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),c=_e.TransactionUtil.buildCoinForAmount(e,s,BigInt(t.amount_b),t.coinTypeB,!1);e.moveCall({target:`${i.published_at}::${_e.ClmmIntegratePoolV2Module}::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,c.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(_e.CLOCK_ADDRESS)]});let{frams:u}=this.sdk.sdkOptions,{global_config_id:d,rewarder_manager_id:h}=(0,_e.getPackagerConfigs)(u);return e.moveCall({target:`${u.published_at}::router::deposit`,typeArguments:[],arguments:[e.object(d),e.object(h),e.object(t.pool_id),o,e.object(_e.CLOCK_ADDRESS)]}),e}async addLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new oi.TransactionBlock;let r=(0,_e.getPackagerConfigs)(n),o=(0,_e.getPackagerConfigs)(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=_e.TransactionUtil.buildCoinForAmount(e,s,BigInt(t.amount_limit_a),t.coinTypeA,!1),c=_e.TransactionUtil.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 u=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,u,a.remainCoins,c.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,c.targetCoin,e.pure(t.amount_limit_a),e.pure(t.amount_limit_b),e.pure(t.delta_liquidity),e.object(_e.CLOCK_ADDRESS)]}),e}async addLiquidityFixCoinPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new oi.TransactionBlock;let r=(0,_e.getPackagerConfigs)(n),o=(0,_e.getPackagerConfigs)(i),s=await this._sdk.ClmmSDK.getOwnerCoinAssets(this._sdk.ClmmSDK.senderAddress),a=_e.TransactionUtil.buildCoinForAmount(e,s,BigInt(t.amount_a),t.coinTypeA,!1),c=_e.TransactionUtil.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 u=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,u,a.remainCoins,c.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,c.targetCoin,e.pure(t.amount_a.toString()),e.pure(t.amount_b.toString()),e.pure(t.fix_amount_a),e.object(_e.CLOCK_ADDRESS)]}),e}async removeLiquidityPayload(t,e){let{frams:n}=this.sdk.sdkOptions,{clmm_pool:i}=this.sdk.ClmmSDK.sdkOptions;e=e||new oi.TransactionBlock;let r=(0,_e.getPackagerConfigs)(n),o=(0,_e.getPackagerConfigs)(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(_e.CLOCK_ADDRESS)]})}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(_e.CLOCK_ADDRESS)]}),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=(0,_e.normalizeCoinType)(t.coinTypeA),s=(0,_e.normalizeCoinType)(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(c=>{switch((0,_e.normalizeCoinType)(c)){case o:a.push(_e.TransactionUtil.buildCoinForAmount(e,i,BigInt(0),c,!1).targetCoin);break;case s:a.push(_e.TransactionUtil.buildCoinForAmount(e,r,BigInt(0),c,!1).targetCoin);break;default:a.push(_e.TransactionUtil.buildCoinForAmount(e,n,BigInt(0),c,!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 oi.TransactionBlock;let r=(0,_e.getPackagerConfigs)(n),o=(0,_e.getPackagerConfigs)(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 oi.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(c=>{r.push(_e.TransactionUtil.buildCoinForAmount(e,a,BigInt(0),c,!1).targetCoin)})}let o=(0,_e.getPackagerConfigs)(n),s=(0,_e.getPackagerConfigs)(i);return t.clmm_rewarder_types?.forEach((a,c)=>{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[c],e.object(_e.CLOCK_ADDRESS)]})}),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=_e.cacheTime24h){let i=this._cache[t];i?(i.overdueTime=(0,_e.getFutureTime)(n),i.value=e):i=new _e.CachedContent(e,(0,_e.getFutureTime)(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]}},Hn=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 cI(this),this._ido=new _I(this),this._xcetusModule=new lI(this),this._xtokenModule=new wI(this),this._boosterModule=new aI(this),this._makerModule=new uI(this),this._vaults=new bI(this),this._limitOrder=new vI(this),this._farmsModule=new kI(this),this._liquidityStrategy=new yI(this),(0,dr.patchFixSuiObjectId)(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,b0.isValidSuiAddress)(t))throw Error("this clmm config sdk senderAddess is illegal");return t}updateCache(t,e,n=dr.cacheTime24h){let i=this._cache[t];i?(i.overdueTime=(0,dr.getFutureTime)(n),i.value=e):i=new dr.CachedContent(e,(0,dr.getFutureTime)(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 Jy=require("@msafe/sui3-utils"),pb=require("@mysten/sui.js/client"),gr=Pe(require("axios"),1),Ao=require("@mysten/sui.js/utils"),vs=require("@mysten/sui.js/utils");var fr=class extends Error{},Fu=class extends fr{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},qu=class extends fr{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Lu=class extends fr{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Bi=class extends fr{},ns=class extends fr{constructor(e){super(`Invalid unit ${e}`)}},hn=class extends fr{},Mi=class extends fr{constructor(){super("Zone is an abstract class")}};var pe="numeric",ji="short",ai="long",Br={year:pe,month:pe,day:pe},ra={year:pe,month:ji,day:pe},Uf={year:pe,month:ji,day:pe,weekday:ji},oa={year:pe,month:ai,day:pe},sa={year:pe,month:ai,day:pe,weekday:ai},aa={hour:pe,minute:pe},ca={hour:pe,minute:pe,second:pe},ua={hour:pe,minute:pe,second:pe,timeZoneName:ji},la={hour:pe,minute:pe,second:pe,timeZoneName:ai},da={hour:pe,minute:pe,hourCycle:"h23"},fa={hour:pe,minute:pe,second:pe,hourCycle:"h23"},ha={hour:pe,minute:pe,second:pe,hourCycle:"h23",timeZoneName:ji},pa={hour:pe,minute:pe,second:pe,hourCycle:"h23",timeZoneName:ai},ma={year:pe,month:pe,day:pe,hour:pe,minute:pe},ga={year:pe,month:pe,day:pe,hour:pe,minute:pe,second:pe},_a={year:pe,month:ji,day:pe,hour:pe,minute:pe},wa={year:pe,month:ji,day:pe,hour:pe,minute:pe,second:pe},$f={year:pe,month:ji,day:pe,weekday:ji,hour:pe,minute:pe},ya={year:pe,month:ai,day:pe,hour:pe,minute:pe,timeZoneName:ji},ba={year:pe,month:ai,day:pe,hour:pe,minute:pe,second:pe,timeZoneName:ji},va={year:pe,month:ai,day:pe,weekday:ai,hour:pe,minute:pe,timeZoneName:ai},ka={year:pe,month:ai,day:pe,weekday:ai,hour:pe,minute:pe,second:pe,timeZoneName:ai};var Qn=class{get type(){throw new Mi}get name(){throw new Mi}get ianaName(){return this.name}get isUniversal(){throw new Mi}offsetName(e,n){throw new Mi}formatOffset(e,n){throw new Mi}offset(e){throw new Mi}equals(e){throw new Mi}get isValid(){throw new Mi}};var Gf=null,Mr=class t extends Qn{static get instance(){return Gf===null&&(Gf=new t),Gf}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:i}){return $u(e,n,i)}formatOffset(e,n){return jr(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var zu={};function TI(t){return zu[t]||(zu[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"})),zu[t]}var CI={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function AI(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,c,u,d]=i;return[s,r,o,a,c,u,d]}function SI(t,e){let n=t.formatToParts(e),i=[];for(let r=0;r<n.length;r++){let{type:o,value:s}=n[r],a=CI[o];o==="era"?i[a]=s:Me(a)||(i[a]=parseInt(s,10))}return i}var Gu={},$n=class t extends Qn{static create(e){return Gu[e]||(Gu[e]=new t(e)),Gu[e]}static resetCache(){Gu={},zu={}}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 $u(e,n,i,this.name)}formatOffset(e,n){return jr(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let i=TI(this.name),[r,o,s,a,c,u,d]=i.formatToParts?SI(i,n):AI(i,n);a==="BC"&&(r=-Math.abs(r)+1);let _=is({year:r,month:o,day:s,hour:c===24?0:c,minute:u,second:d,millisecond:0}),C=+n,D=C%1e3;return C-=D>=0?D:1e3+D,(_-C)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var A0={};function II(t,e={}){let n=JSON.stringify([t,e]),i=A0[n];return i||(i=new Intl.ListFormat(t,e),A0[n]=i),i}var zf={};function Vf(t,e={}){let n=JSON.stringify([t,e]),i=zf[n];return i||(i=new Intl.DateTimeFormat(t,e),zf[n]=i),i}var Kf={};function xI(t,e={}){let n=JSON.stringify([t,e]),i=Kf[n];return i||(i=new Intl.NumberFormat(t,e),Kf[n]=i),i}var Wf={};function OI(t,e={}){let{base:n,...i}=e,r=JSON.stringify([t,i]),o=Wf[r];return o||(o=new Intl.RelativeTimeFormat(t,e),Wf[r]=o),o}var Ta=null;function PI(){return Ta||(Ta=new Intl.DateTimeFormat().resolvedOptions().locale,Ta)}var S0={};function EI(t){let e=S0[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,S0[t]=e}return e}function DI(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=Vf(t).resolvedOptions(),r=t}catch{let c=t.substring(0,n);i=Vf(c).resolvedOptions(),r=c}let{numberingSystem:o,calendar:s}=i;return[r,o,s]}}function BI(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function MI(t){let e=[];for(let n=1;n<=12;n++){let i=Je.utc(2009,n,1);e.push(t(i))}return e}function jI(t){let e=[];for(let n=1;n<=7;n++){let i=Je.utc(2016,11,13+n);e.push(t(i))}return e}function Vu(t,e,n,i){let r=t.listingMode();return r==="error"?null:r==="en"?n(e):i(e)}function NI(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 Hf=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=xI(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):rs(e,3);return Dt(n,this.padTo)}}},Xf=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&&$n.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=Vf(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()}},Zf=class{constructor(e,n,i){this.opts={style:"long",...i},!n&&Ku()&&(this.rtf=OI(e,i))}format(e,n){return this.rtf?this.rtf.format(e,n):I0(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},RI={firstDay:1,minimalDays:4,weekend:[6,7]},ut=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||ot.defaultLocale,a=s||(o?"en-US":PI()),c=n||ot.defaultNumberingSystem,u=i||ot.defaultOutputCalendar,d=Ca(r)||ot.defaultWeekSettings;return new t(a,c,u,d,s)}static resetCache(){Ta=null,zf={},Kf={},Wf={}}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,c]=DI(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=i||c||null,this.weekSettings=r,this.intl=BI(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=NI(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,Ca(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 Vu(this,e,Jf,()=>{let i=n?{month:e,day:"numeric"}:{month:e},r=n?"format":"standalone";return this.monthsCache[r][e]||(this.monthsCache[r][e]=MI(o=>this.extract(o,i,"month"))),this.monthsCache[r][e]})}weekdays(e,n=!1){return Vu(this,e,Yf,()=>{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]=jI(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return Vu(this,void 0,()=>Qf,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Je.utc(2016,11,13,9),Je.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Vu(this,e,eh,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[Je.utc(-40,1,1),Je.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 Hf(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Xf(e,this.intl,n)}relFormatter(e={}){return new Zf(this.intl,this.isEnglish(),e)}listFormatter(e={}){return II(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:Wu()?EI(this.locale):RI}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 nh=null,bn=class t extends Qn{static get utcInstance(){return nh===null&&(nh=new t(0)),nh}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(po(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${jr(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${jr(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return jr(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 os=class extends Qn{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 Ni(t,e){let n;if(Me(t)||t===null)return e;if(t instanceof Qn)return t;if(x0(t)){let i=t.toLowerCase();return i==="default"?e:i==="local"||i==="system"?Mr.instance:i==="utc"||i==="gmt"?bn.utcInstance:bn.parseSpecifier(i)||$n.create(t)}else return Hi(t)?bn.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new os(t)}var O0=()=>Date.now(),P0="system",E0=null,D0=null,B0=null,M0=60,j0,N0=null,ot=class{static get now(){return O0}static set now(e){O0=e}static set defaultZone(e){P0=e}static get defaultZone(){return Ni(P0,Mr.instance)}static get defaultLocale(){return E0}static set defaultLocale(e){E0=e}static get defaultNumberingSystem(){return D0}static set defaultNumberingSystem(e){D0=e}static get defaultOutputCalendar(){return B0}static set defaultOutputCalendar(e){B0=e}static get defaultWeekSettings(){return N0}static set defaultWeekSettings(e){N0=Ca(e)}static get twoDigitCutoffYear(){return M0}static set twoDigitCutoffYear(e){M0=e%100}static get throwOnInvalid(){return j0}static set throwOnInvalid(e){j0=e}static resetCaches(){ut.resetCache(),$n.resetCache()}};var vn=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var R0=[0,31,59,90,120,151,181,212,243,273,304,334],F0=[0,31,60,91,121,152,182,213,244,274,305,335];function yi(t,e){return new vn("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Hu(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 q0(t,e,n){return n+(go(t)?F0:R0)[e-1]}function L0(t,e){let n=go(t)?F0:R0,i=n.findIndex(o=>o<e),r=e-n[i];return{month:i+1,day:r}}function Xu(t,e){return(t-e+7)%7+1}function Aa(t,e=4,n=1){let{year:i,month:r,day:o}=t,s=q0(i,r,o),a=Xu(Hu(i,r,o),n),c=Math.floor((s-a+14-e)/7),u;return c<1?(u=i-1,c=mo(u,e,n)):c>mo(i,e,n)?(u=i+1,c=1):u=i,{weekYear:u,weekNumber:c,weekday:a,...Ia(t)}}function ih(t,e=4,n=1){let{weekYear:i,weekNumber:r,weekday:o}=t,s=Xu(Hu(i,1,e),n),a=Nr(i),c=r*7+o-s-7+e,u;c<1?(u=i-1,c+=Nr(u)):c>a?(u=i+1,c-=Nr(i)):u=i;let{month:d,day:h}=L0(u,c);return{year:u,month:d,day:h,...Ia(t)}}function Zu(t){let{year:e,month:n,day:i}=t,r=q0(e,n,i);return{year:e,ordinal:r,...Ia(t)}}function rh(t){let{year:e,ordinal:n}=t,{month:i,day:r}=L0(e,n);return{year:e,month:i,day:r,...Ia(t)}}function oh(t,e){if(!Me(t.localWeekday)||!Me(t.localWeekNumber)||!Me(t.localWeekYear)){if(!Me(t.weekday)||!Me(t.weekNumber)||!Me(t.weekYear))throw new Bi("Cannot mix locale-based week fields with ISO-based week fields");return Me(t.localWeekday)||(t.weekday=t.localWeekday),Me(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),Me(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 U0(t,e=4,n=1){let i=Sa(t.weekYear),r=ci(t.weekNumber,1,mo(t.weekYear,e,n)),o=ci(t.weekday,1,7);return i?r?o?!1:yi("weekday",t.weekday):yi("week",t.weekNumber):yi("weekYear",t.weekYear)}function $0(t){let e=Sa(t.year),n=ci(t.ordinal,1,Nr(t.year));return e?n?!1:yi("ordinal",t.ordinal):yi("year",t.year)}function sh(t){let e=Sa(t.year),n=ci(t.month,1,12),i=ci(t.day,1,ss(t.year,t.month));return e?n?i?!1:yi("day",t.day):yi("month",t.month):yi("year",t.year)}function ah(t){let{hour:e,minute:n,second:i,millisecond:r}=t,o=ci(e,0,23)||e===24&&n===0&&i===0&&r===0,s=ci(n,0,59),a=ci(i,0,59),c=ci(r,0,999);return o?s?a?c?!1:yi("millisecond",r):yi("second",i):yi("minute",n):yi("hour",e)}function Me(t){return typeof t>"u"}function Hi(t){return typeof t=="number"}function Sa(t){return typeof t=="number"&&t%1===0}function x0(t){return typeof t=="string"}function z0(t){return Object.prototype.toString.call(t)==="[object Date]"}function Ku(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Wu(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function V0(t){return Array.isArray(t)?t:[t]}function ch(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 K0(t,e){return e.reduce((n,i)=>(n[i]=t[i],n),{})}function Rr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ca(t){if(t==null)return null;if(typeof t!="object")throw new hn("Week settings must be an object");if(!ci(t.firstDay,1,7)||!ci(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!ci(e,1,7)))throw new hn("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function ci(t,e,n){return Sa(t)&&t>=e&&t<=n}function FI(t,e){return t-e*Math.floor(t/e)}function Dt(t,e=2){let n=t<0,i;return n?i="-"+(""+-t).padStart(e,"0"):i=(""+t).padStart(e,"0"),i}function hr(t){if(!(Me(t)||t===null||t===""))return parseInt(t,10)}function Fr(t){if(!(Me(t)||t===null||t===""))return parseFloat(t)}function xa(t){if(!(Me(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function rs(t,e,n=!1){let i=10**e;return(n?Math.trunc:Math.round)(t*i)/i}function go(t){return t%4===0&&(t%100!==0||t%400===0)}function Nr(t){return go(t)?366:365}function ss(t,e){let n=FI(e-1,12)+1,i=t+(e-n)/12;return n===2?go(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function is(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 G0(t,e,n){return-Xu(Hu(t,1,e),n)+e-1}function mo(t,e=4,n=1){let i=G0(t,e,n),r=G0(t+1,e,n);return(Nr(t)-i+r)/7}function Oa(t){return t>99?t:t>ot.twoDigitCutoffYear?1900+t:2e3+t}function $u(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(c=>c.type.toLowerCase()==="timezonename");return a?a.value:null}function po(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 uh(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new hn(`Invalid unit value ${t}`);return e}function as(t,e){let n={};for(let i in t)if(Rr(t,i)){let r=t[i];if(r==null)continue;n[e(i)]=uh(r)}return n}function jr(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}${Dt(n,2)}:${Dt(i,2)}`;case"narrow":return`${r}${n}${i>0?`:${i}`:""}`;case"techie":return`${r}${Dt(n,2)}${Dt(i,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Ia(t){return K0(t,["hour","minute","second","millisecond"])}var qI=["January","February","March","April","May","June","July","August","September","October","November","December"],lh=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],LI=["J","F","M","A","M","J","J","A","S","O","N","D"];function Jf(t){switch(t){case"narrow":return[...LI];case"short":return[...lh];case"long":return[...qI];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 dh=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],fh=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],UI=["M","T","W","T","F","S","S"];function Yf(t){switch(t){case"narrow":return[...UI];case"short":return[...fh];case"long":return[...dh];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Qf=["AM","PM"],$I=["Before Christ","Anno Domini"],GI=["BC","AD"],zI=["B","A"];function eh(t){switch(t){case"narrow":return[...zI];case"short":return[...GI];case"long":return[...$I];default:return null}}function W0(t){return Qf[t.hour<12?0:1]}function H0(t,e){return Yf(e)[t.weekday-1]}function X0(t,e){return Jf(e)[t.month-1]}function Z0(t,e){return eh(e)[t.year<0?0:1]}function I0(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 h=t==="days";switch(e){case 1:return h?"tomorrow":`next ${r[t][0]}`;case-1:return h?"yesterday":`last ${r[t][0]}`;case 0:return h?"today":`this ${r[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),c=a===1,u=r[t],d=i?c?u[1]:u[2]||u[1]:c?r[t][0]:t;return s?`${a} ${d} ago`:`in ${a} ${d}`}function J0(t,e){let n="";for(let i of t)i.literal?n+=i.val:n+=e(i.val);return n}var VI={D:Br,DD:ra,DDD:oa,DDDD:sa,t:aa,tt:ca,ttt:ua,tttt:la,T:da,TT:fa,TTT:ha,TTTT:pa,f:ma,ff:_a,fff:ya,ffff:va,F:ga,FF:wa,FFF:ba,FFFF:ka},kn=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 VI[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 Dt(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=(C,D)=>this.loc.extract(e,C,D),s=C=>e.isOffsetFixed&&e.offset===0&&C.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,C.format):"",a=()=>i?W0(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(C,D)=>i?X0(e,C):o(D?{month:C}:{month:C,day:"numeric"},"month"),u=(C,D)=>i?H0(e,C):o(D?{weekday:C}:{weekday:C,month:"long",day:"numeric"},"weekday"),d=C=>{let D=t.macroTokenToFormatOpts(C);return D?this.formatWithSystemDefault(e,D):C},h=C=>i?Z0(e,C):o({era:C},"era"),_=C=>{switch(C){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 u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("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 c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("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 c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("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 h("short");case"GG":return h("long");case"GGGGG":return h("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 d(C)}};return J0(t.parseFormat(n),_)}formatDurationFromString(e,n){let i=c=>{switch(c[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=c=>u=>{let d=i(u);return d?this.num(c.get(d),u.length):u},o=t.parseFormat(n),s=o.reduce((c,{literal:u,val:d})=>u?c:c.concat(d),[]),a=e.shiftTo(...s.map(i).filter(c=>c));return J0(o,r(a))}};var Q0=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function us(...t){let e=t.reduce((n,i)=>n+i.source,"");return RegExp(`^${e}$`)}function ls(...t){return e=>t.reduce(([n,i,r],o)=>{let[s,a,c]=o(e,r);return[{...n,...s},a||i,c]},[{},null,1]).slice(0,2)}function ds(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 ew(...t){return(e,n)=>{let i={},r;for(r=0;r<t.length;r++)i[t[r]]=hr(e[n+r]);return[i,null,n+r]}}var tw=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,KI=`(?:${tw.source}?(?:\\[(${Q0.source})\\])?)?`,hh=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,nw=RegExp(`${hh.source}${KI}`),ph=RegExp(`(?:T${nw.source})?`),WI=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,HI=/(\d{4})-?W(\d\d)(?:-?(\d))?/,XI=/(\d{4})-?(\d{3})/,ZI=ew("weekYear","weekNumber","weekDay"),JI=ew("year","ordinal"),YI=/(\d{4})-(\d\d)-(\d\d)/,iw=RegExp(`${hh.source} ?(?:${tw.source}|(${Q0.source}))?`),QI=RegExp(`(?: ${iw.source})?`);function cs(t,e,n){let i=t[e];return Me(i)?n:hr(i)}function ex(t,e){return[{year:cs(t,e),month:cs(t,e+1,1),day:cs(t,e+2,1)},null,e+3]}function fs(t,e){return[{hours:cs(t,e,0),minutes:cs(t,e+1,0),seconds:cs(t,e+2,0),milliseconds:xa(t[e+3])},null,e+4]}function Pa(t,e){let n=!t[e]&&!t[e+1],i=po(t[e+1],t[e+2]),r=n?null:bn.instance(i);return[{},r,e+3]}function Ea(t,e){let n=t[e]?$n.create(t[e]):null;return[{},n,e+1]}var tx=RegExp(`^T?${hh.source}$`),nx=/^-?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 ix(t){let[e,n,i,r,o,s,a,c,u]=t,d=e[0]==="-",h=c&&c[0]==="-",_=(C,D=!1)=>C!==void 0&&(D||C&&d)?-C:C;return[{years:_(Fr(n)),months:_(Fr(i)),weeks:_(Fr(r)),days:_(Fr(o)),hours:_(Fr(s)),minutes:_(Fr(a)),seconds:_(Fr(c),c==="-0"),milliseconds:_(xa(u),h)}]}var rx={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 mh(t,e,n,i,r,o,s){let a={year:e.length===2?Oa(hr(e)):hr(e),month:lh.indexOf(n)+1,day:hr(i),hour:hr(r),minute:hr(o)};return s&&(a.second=hr(s)),t&&(a.weekday=t.length>3?dh.indexOf(t)+1:fh.indexOf(t)+1),a}var ox=/^(?:(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 sx(t){let[,e,n,i,r,o,s,a,c,u,d,h]=t,_=mh(e,r,i,n,o,s,a),C;return c?C=rx[c]:u?C=0:C=po(d,h),[_,new bn(C)]}function ax(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var cx=/^(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$/,ux=/^(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$/,lx=/^(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 Y0(t){let[,e,n,i,r,o,s,a]=t;return[mh(e,r,i,n,o,s,a),bn.utcInstance]}function dx(t){let[,e,n,i,r,o,s,a]=t;return[mh(e,a,n,i,r,o,s),bn.utcInstance]}var fx=us(WI,ph),hx=us(HI,ph),px=us(XI,ph),mx=us(nw),rw=ls(ex,fs,Pa,Ea),gx=ls(ZI,fs,Pa,Ea),_x=ls(JI,fs,Pa,Ea),wx=ls(fs,Pa,Ea);function ow(t){return ds(t,[fx,rw],[hx,gx],[px,_x],[mx,wx])}function sw(t){return ds(ax(t),[ox,sx])}function aw(t){return ds(t,[cx,Y0],[ux,Y0],[lx,dx])}function cw(t){return ds(t,[nx,ix])}var yx=ls(fs);function uw(t){return ds(t,[tx,yx])}var bx=us(YI,QI),vx=us(iw),kx=ls(fs,Pa,Ea);function lw(t){return ds(t,[bx,rw],[vx,kx])}var dw="Invalid Duration",hw={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}},Tx={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},...hw},bi=146097/400,hs=146097/4800,Cx={years:{quarters:4,months:12,weeks:bi/7,days:bi,hours:bi*24,minutes:bi*24*60,seconds:bi*24*60*60,milliseconds:bi*24*60*60*1e3},quarters:{months:3,weeks:bi/28,days:bi/4,hours:bi*24/4,minutes:bi*24*60/4,seconds:bi*24*60*60/4,milliseconds:bi*24*60*60*1e3/4},months:{weeks:hs/7,days:hs,hours:hs*24,minutes:hs*24*60,seconds:hs*24*60*60,milliseconds:hs*24*60*60*1e3},...hw},_o=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Ax=_o.slice(0).reverse();function qr(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 pt(i)}function pw(t,e){let n=e.milliseconds??0;for(let i of Ax.slice(1))e[i]&&(n+=e[i]*t[i].milliseconds);return n}function fw(t,e){let n=pw(t,e)<0?-1:1;_o.reduceRight((i,r)=>{if(Me(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),_o.reduce((i,r)=>{if(Me(e[r]))return i;if(i){let o=e[i]%1;e[i]-=o,e[r]+=o*t[i][r]}return r},null)}function Sx(t){let e={};for(let[n,i]of Object.entries(t))i!==0&&(e[n]=i);return e}var pt=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,i=n?Cx:Tx;e.matrix&&(i=e.matrix),this.values=e.values,this.loc=e.loc||ut.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 hn(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:as(e,t.normalizeUnit),loc:ut.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(Hi(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new hn(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[i]=cw(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]=uw(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 hn("need to specify a reason the Duration is invalid");let i=e instanceof vn?e:new vn(e,n);if(ot.throwOnInvalid)throw new Lu(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 ns(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?kn.create(this.loc,i).formatDurationFromString(this,e):dw}toHuman(e={}){if(!this.isValid)return dw;let n=_o.map(i=>{let r=this.values[i];return Me(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+=rs(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},Je.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?pw(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 _o)(Rr(n.values,r)||Rr(this.values,r))&&(i[r]=n.get(r)+this.get(r));return qr(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]=uh(e(this.values[i],i));return qr(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...as(e,t.normalizeUnit)};return qr(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 qr(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return fw(this.matrix,e),qr(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Sx(this.normalize().shiftToAll().toObject());return qr(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 _o)if(e.indexOf(s)>=0){o=s;let a=0;for(let u in i)a+=this.matrix[u][s]*i[u],i[u]=0;Hi(r[s])&&(a+=r[s]);let c=Math.trunc(a);n[s]=c,i[s]=(a*1e3-c*1e3)/1e3}else Hi(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 fw(this.matrix,n),qr(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 qr(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 _o)if(!n(this.values[i],e.values[i]))return!1;return!0}};var ps="Invalid Interval";function Ix(t,e){return!t||!t.isValid?pr.invalid("missing or invalid start"):!e||!e.isValid?pr.invalid("missing or invalid end"):e<t?pr.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 pr=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 hn("need to specify a reason the Interval is invalid");let i=e instanceof vn?e:new vn(e,n);if(ot.throwOnInvalid)throw new qu(i);return new t({invalid:i})}static fromDateTimes(e,n){let i=ms(e),r=ms(n),o=Ix(i,r);return o??new t({start:i,end:r})}static after(e,n){let i=pt.fromDurationLike(n),r=ms(e);return t.fromDateTimes(r,r.plus(i))}static before(e,n){let i=pt.fromDurationLike(n),r=ms(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=Je.fromISO(i,n),s=o.isValid}catch{s=!1}let a,c;try{a=Je.fromISO(r,n),c=a.isValid}catch{c=!1}if(s&&c)return t.fromDateTimes(o,a);if(s){let u=pt.fromISO(r,n);if(u.isValid)return t.after(o,u)}else if(c){let u=pt.fromISO(i,n);if(u.isValid)return t.before(a,u)}}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(ms).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=pt.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(c=>c*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(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((c,u)=>c.time-u.time);for(let c of a)i+=c.type==="s"?1:-1,i===1?n=c.time:(n&&+n!=+c.time&&r.push(t.fromDateTimes(n,c.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()})`:ps}[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=Br,n={}){return this.isValid?kn.create(this.s.loc.clone(n),e).formatInterval(this):ps}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:ps}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:ps}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:ps}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:ps}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):pt.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var mr=class{static hasDST(e=ot.defaultZone){let n=Je.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return $n.isValidZone(e)}static normalizeZone(e){return Ni(e,ot.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ut.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ut.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ut.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||ut.create(n,i,o)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null,outputCalendar:o="gregory"}={}){return(r||ut.create(n,i,o)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||ut.create(n,i,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:i=null,locObj:r=null}={}){return(r||ut.create(n,i,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ut.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ut.create(n,null,"gregory").eras(e)}static features(){return{relative:Ku(),localeWeek:Wu()}}};function mw(t,e){let n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),i=n(e)-n(t);return Math.floor(pt.fromMillis(i).as("days"))}function xx(t,e,n){let i=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{let d=mw(c,u);return(d-d%7)/7}],["days",mw]],r={},o=t,s,a;for(let[c,u]of i)n.indexOf(c)>=0&&(s=c,r[c]=u(t,e),a=o.plus(r),a>e?(r[c]--,t=o.plus(r),t>e&&(a=t,r[c]--,t=o.plus(r))):t=a);return[t,r,a,s]}function gw(t,e,n,i){let[r,o,s,a]=xx(t,e,n),c=e-r,u=n.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);u.length===0&&(s<e&&(s=r.plus({[a]:1})),s!==r&&(o[a]=(o[a]||0)+c/(s-r)));let d=pt.fromObject(o,i);return u.length>0?pt.fromMillis(c,i).shiftTo(...u).plus(d):d}var gh={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"},_w={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]},Ox=gh.hanidec.replace(/[\[|\]]/g,"").split("");function ww(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(gh.hanidec)!==-1)e+=Ox.indexOf(t[n]);else for(let r in _w){let[o,s]=_w[r];i>=o&&i<=s&&(e+=i-o)}}return parseInt(e,10)}else return e}function vi({numberingSystem:t},e=""){return new RegExp(`${gh[t||"latn"]}${e}`)}var Px="missing Intl.DateTimeFormat.formatToParts support";function st(t,e=n=>n){return{regex:t,deser:([n])=>e(ww(n))}}var Ex="\xA0",vw=`[ ${Ex}]`,kw=new RegExp(vw,"g");function Dx(t){return t.replace(/\./g,"\\.?").replace(kw,vw)}function yw(t){return t.replace(/\./g,"").replace(kw," ").toLowerCase()}function Ri(t,e){return t===null?null:{regex:RegExp(t.map(Dx).join("|")),deser:([n])=>t.findIndex(i=>yw(n)===yw(i))+e}}function bw(t,e){return{regex:t,deser:([,n,i])=>po(n,i),groups:e}}function Ju(t){return{regex:t,deser:([e])=>e}}function Bx(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Mx(t,e){let n=vi(e),i=vi(e,"{2}"),r=vi(e,"{3}"),o=vi(e,"{4}"),s=vi(e,"{6}"),a=vi(e,"{1,2}"),c=vi(e,"{1,3}"),u=vi(e,"{1,6}"),d=vi(e,"{1,9}"),h=vi(e,"{2,4}"),_=vi(e,"{4,6}"),C=B=>({regex:RegExp(Bx(B.val)),deser:([j])=>j,literal:!0}),O=(B=>{if(t.literal)return C(B);switch(B.val){case"G":return Ri(e.eras("short"),0);case"GG":return Ri(e.eras("long"),0);case"y":return st(u);case"yy":return st(h,Oa);case"yyyy":return st(o);case"yyyyy":return st(_);case"yyyyyy":return st(s);case"M":return st(a);case"MM":return st(i);case"MMM":return Ri(e.months("short",!0),1);case"MMMM":return Ri(e.months("long",!0),1);case"L":return st(a);case"LL":return st(i);case"LLL":return Ri(e.months("short",!1),1);case"LLLL":return Ri(e.months("long",!1),1);case"d":return st(a);case"dd":return st(i);case"o":return st(c);case"ooo":return st(r);case"HH":return st(i);case"H":return st(a);case"hh":return st(i);case"h":return st(a);case"mm":return st(i);case"m":return st(a);case"q":return st(a);case"qq":return st(i);case"s":return st(a);case"ss":return st(i);case"S":return st(c);case"SSS":return st(r);case"u":return Ju(d);case"uu":return Ju(a);case"uuu":return st(n);case"a":return Ri(e.meridiems(),0);case"kkkk":return st(o);case"kk":return st(h,Oa);case"W":return st(a);case"WW":return st(i);case"E":case"c":return st(n);case"EEE":return Ri(e.weekdays("short",!1),1);case"EEEE":return Ri(e.weekdays("long",!1),1);case"ccc":return Ri(e.weekdays("short",!0),1);case"cccc":return Ri(e.weekdays("long",!0),1);case"Z":case"ZZ":return bw(new RegExp(`([+-]${a.source})(?::(${i.source}))?`),2);case"ZZZ":return bw(new RegExp(`([+-]${a.source})(${i.source})?`),2);case"z":return Ju(/[a-z_+-/]{1,256}?/i);case" ":return Ju(/[^\S\n\r]/);default:return C(B)}})(t)||{invalidReason:Px};return O.token=t,O}var jx={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 Nx(t,e,n){let{type:i,value:r}=t;if(i==="literal"){let c=/^\s+$/.test(r);return{literal:!c,val:c?" ":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=jx[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Rx(t){return[`^${t.map(n=>n.regex).reduce((n,i)=>`${n}(${i.source})`,"")}$`,t]}function Fx(t,e,n){let i=t.match(e);if(i){let r={},o=1;for(let s in n)if(Rr(n,s)){let a=n[s],c=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(i.slice(o,o+c))),o+=c}return[i,r]}else return[i,{}]}function qx(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 Me(t.z)||(n=$n.create(t.z)),Me(t.Z)||(n||(n=new bn(t.Z)),i=t.Z),Me(t.q)||(t.M=(t.q-1)*3+1),Me(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),Me(t.u)||(t.S=xa(t.u)),[Object.keys(t).reduce((o,s)=>{let a=e(s);return a&&(o[a]=t[s]),o},{}),n,i]}var _h=null;function Lx(){return _h||(_h=Je.fromMillis(1555555555555)),_h}function Ux(t,e){if(t.literal)return t;let n=kn.macroTokenToFormatOpts(t.val),i=bh(n,e);return i==null||i.includes(void 0)?t:i}function wh(t,e){return Array.prototype.concat(...t.map(n=>Ux(n,e)))}function yh(t,e,n){let i=wh(kn.parseFormat(n),t),r=i.map(s=>Mx(s,t)),o=r.find(s=>s.invalidReason);if(o)return{input:e,tokens:i,invalidReason:o.invalidReason};{let[s,a]=Rx(r),c=RegExp(s,"i"),[u,d]=Fx(e,c,a),[h,_,C]=d?qx(d):[null,null,void 0];if(Rr(d,"a")&&Rr(d,"H"))throw new Bi("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:i,regex:c,rawMatches:u,matches:d,result:h,zone:_,specificOffset:C}}}function Tw(t,e,n){let{result:i,zone:r,specificOffset:o,invalidReason:s}=yh(t,e,n);return[i,r,o,s]}function bh(t,e){if(!t)return null;let i=kn.create(e,t).dtFormatter(Lx()),r=i.formatToParts(),o=i.resolvedOptions();return r.map(s=>Nx(s,t,o))}var vh="Invalid DateTime",Cw=864e13;function Yu(t){return new vn("unsupported zone",`the zone "${t.name}" is not supported`)}function kh(t){return t.weekData===null&&(t.weekData=Aa(t.c)),t.weekData}function Th(t){return t.localWeekData===null&&(t.localWeekData=Aa(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function wo(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new Je({...n,...e,old:n})}function Ew(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 Qu(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 tl(t,e,n){return Ew(is(t),e,n)}function Aw(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,ss(i,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=pt.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=is(o),[c,u]=Ew(a,n,t.zone);return s!==0&&(c+=s,u=t.zone.offset(c)),{ts:c,o:u}}function Da(t,e,n,i,r,o){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let c=e||a,u=Je.fromObject(t,{...n,zone:c,specificOffset:o});return s?u:u.setZone(a)}else return Je.invalid(new vn("unparsable",`the input "${r}" can't be parsed as ${i}`))}function el(t,e,n=!0){return t.isValid?kn.create(ut.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Ch(t,e){let n=t.c.year>9999||t.c.year<0,i="";return n&&t.c.year>=0&&(i+="+"),i+=Dt(t.c.year,n?6:4),e?(i+="-",i+=Dt(t.c.month),i+="-",i+=Dt(t.c.day)):(i+=Dt(t.c.month),i+=Dt(t.c.day)),i}function Sw(t,e,n,i,r,o){let s=Dt(t.c.hour);return e?(s+=":",s+=Dt(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=Dt(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=Dt(t.c.second),(t.c.millisecond!==0||!i)&&(s+=".",s+=Dt(t.c.millisecond,3))),r&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Dt(Math.trunc(-t.o/60)),s+=":",s+=Dt(Math.trunc(-t.o%60))):(s+="+",s+=Dt(Math.trunc(t.o/60)),s+=":",s+=Dt(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var Dw={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},$x={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Gx={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Bw=["year","month","day","hour","minute","second","millisecond"],zx=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Vx=["year","ordinal","hour","minute","second","millisecond"];function Kx(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 ns(t);return e}function Iw(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Kx(t)}}function xw(t,e){let n=Ni(e.zone,ot.defaultZone),i=ut.fromObject(e),r=ot.now(),o,s;if(Me(t.year))o=r;else{for(let u of Bw)Me(t[u])&&(t[u]=Dw[u]);let a=sh(t)||ah(t);if(a)return Je.invalid(a);let c=n.offset(r);[o,s]=tl(t,c,n)}return new Je({ts:o,zone:n,loc:i,o:s})}function Ow(t,e,n){let i=Me(n.round)?!0:n.round,r=(s,a)=>(s=rs(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 Pw(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 Je=class t{constructor(e){let n=e.zone||ot.defaultZone,i=e.invalid||(Number.isNaN(e.ts)?new vn("invalid input"):null)||(n.isValid?null:Yu(n));this.ts=Me(e.ts)?ot.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=Qu(this.ts,a),i=Number.isNaN(r.year)?new vn("invalid input"):null,r=i?null:r,o=i?null:a}this._zone=n,this.loc=e.loc||ut.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]=Pw(arguments),[i,r,o,s,a,c,u]=n;return xw({year:i,month:r,day:o,hour:s,minute:a,second:c,millisecond:u},e)}static utc(){let[e,n]=Pw(arguments),[i,r,o,s,a,c,u]=n;return e.zone=bn.utcInstance,xw({year:i,month:r,day:o,hour:s,minute:a,second:c,millisecond:u},e)}static fromJSDate(e,n={}){let i=z0(e)?e.valueOf():NaN;if(Number.isNaN(i))return t.invalid("invalid input");let r=Ni(n.zone,ot.defaultZone);return r.isValid?new t({ts:i,zone:r,loc:ut.fromObject(n)}):t.invalid(Yu(r))}static fromMillis(e,n={}){if(Hi(e))return e<-Cw||e>Cw?t.invalid("Timestamp out of range"):new t({ts:e,zone:Ni(n.zone,ot.defaultZone),loc:ut.fromObject(n)});throw new hn(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(Hi(e))return new t({ts:e*1e3,zone:Ni(n.zone,ot.defaultZone),loc:ut.fromObject(n)});throw new hn("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let i=Ni(n.zone,ot.defaultZone);if(!i.isValid)return t.invalid(Yu(i));let r=ut.fromObject(n),o=as(e,Iw),{minDaysInFirstWeek:s,startOfWeek:a}=oh(o,r),c=ot.now(),u=Me(n.specificOffset)?i.offset(c):n.specificOffset,d=!Me(o.ordinal),h=!Me(o.year),_=!Me(o.month)||!Me(o.day),C=h||_,D=o.weekYear||o.weekNumber;if((C||d)&&D)throw new Bi("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(_&&d)throw new Bi("Can't mix ordinal dates with month/day");let O=D||o.weekday&&!C,B,j,M=Qu(c,u);O?(B=zx,j=$x,M=Aa(M,s,a)):d?(B=Vx,j=Gx,M=Zu(M)):(B=Bw,j=Dw);let R=!1;for(let G of B){let W=o[G];Me(W)?R?o[G]=j[G]:o[G]=M[G]:R=!0}let K=O?U0(o,s,a):d?$0(o):sh(o),X=K||ah(o);if(X)return t.invalid(X);let Y=O?ih(o,s,a):d?rh(o):o,[oe,$]=tl(Y,u,i),ne=new t({ts:oe,zone:i,o:$,loc:r});return o.weekday&&C&&e.weekday!==ne.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${ne.toISO()}`):ne}static fromISO(e,n={}){let[i,r]=ow(e);return Da(i,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[i,r]=sw(e);return Da(i,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[i,r]=aw(e);return Da(i,r,n,"HTTP",n)}static fromFormat(e,n,i={}){if(Me(e)||Me(n))throw new hn("fromFormat requires an input string and a format");let{locale:r=null,numberingSystem:o=null}=i,s=ut.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0}),[a,c,u,d]=Tw(s,e,n);return d?t.invalid(d):Da(a,c,i,`format ${n}`,e,u)}static fromString(e,n,i={}){return t.fromFormat(e,n,i)}static fromSQL(e,n={}){let[i,r]=lw(e);return Da(i,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new hn("need to specify a reason the DateTime is invalid");let i=e instanceof vn?e:new vn(e,n);if(ot.throwOnInvalid)throw new Fu(i);return new t({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let i=bh(e,ut.fromObject(n));return i?i.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return wh(kn.parseFormat(e),ut.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?kh(this).weekYear:NaN}get weekNumber(){return this.isValid?kh(this).weekNumber:NaN}get weekday(){return this.isValid?kh(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Th(this).weekday:NaN}get localWeekNumber(){return this.isValid?Th(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Th(this).weekYear:NaN}get ordinal(){return this.isValid?Zu(this.c).ordinal:NaN}get monthShort(){return this.isValid?mr.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?mr.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?mr.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?mr.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=is(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 c=i-s*n,u=i-a*n,d=Qu(c,s),h=Qu(u,a);return d.hour===h.hour&&d.minute===h.minute&&d.second===h.second&&d.millisecond===h.millisecond?[wo(this,{ts:c}),wo(this,{ts:u})]:[this]}get isInLeapYear(){return go(this.year)}get daysInMonth(){return ss(this.year,this.month)}get daysInYear(){return this.isValid?Nr(this.year):NaN}get weeksInWeekYear(){return this.isValid?mo(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?mo(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:i,calendar:r}=kn.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:i,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(bn.instance(e),n)}toLocal(){return this.setZone(ot.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:i=!1}={}){if(e=Ni(e,ot.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]=tl(s,o,e)}return wo(this,{ts:r,zone:e})}else return t.invalid(Yu(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:i}={}){let r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:i});return wo(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=as(e,Iw),{minDaysInFirstWeek:i,startOfWeek:r}=oh(n,this.loc),o=!Me(n.weekYear)||!Me(n.weekNumber)||!Me(n.weekday),s=!Me(n.ordinal),a=!Me(n.year),c=!Me(n.month)||!Me(n.day),u=a||c,d=n.weekYear||n.weekNumber;if((u||s)&&d)throw new Bi("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&s)throw new Bi("Can't mix ordinal dates with month/day");let h;o?h=ih({...Aa(this.c,i,r),...n},i,r):Me(n.ordinal)?(h={...this.toObject(),...n},Me(n.day)&&(h.day=Math.min(ss(h.year,h.month),h.day))):h=rh({...Zu(this.c),...n});let[_,C]=tl(h,this.o,this.zone);return wo(this,{ts:_,o:C})}plus(e){if(!this.isValid)return this;let n=pt.fromDurationLike(e);return wo(this,Aw(this,n))}minus(e){if(!this.isValid)return this;let n=pt.fromDurationLike(e).negate();return wo(this,Aw(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let i={},r=pt.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?kn.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):vh}toLocaleString(e=Br,n={}){return this.isValid?kn.create(this.loc.clone(n),e).formatDateTime(this):vh}toLocaleParts(e={}){return this.isValid?kn.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=Ch(this,s);return a+="T",a+=Sw(this,s,n,i,r,o),a}toISODate({format:e="extended"}={}){return this.isValid?Ch(this,e==="extended"):null}toISOWeekDate(){return el(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":"")+Sw(this,s==="extended",n,e,i,o):null}toRFC2822(){return el(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return el(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Ch(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")),el(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():vh}[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 pt.invalid("created by diffing an invalid DateTime");let r={locale:this.locale,numberingSystem:this.numberingSystem,...i},o=V0(n).map(pt.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,c=s?e:this,u=gw(a,c,o,r);return s?u.negate():u}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?pr.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),Ow(n,this.plus(i),{...e,numeric:"always",units:r,unit:o})}toRelativeCalendar(e={}){return this.isValid?Ow(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 hn("min requires all arguments be DateTimes");return ch(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new hn("max requires all arguments be DateTimes");return ch(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,i={}){let{locale:r=null,numberingSystem:o=null}=i,s=ut.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0});return yh(s,e,n)}static fromStringExplain(e,n,i={}){return t.fromFormatExplain(e,n,i)}static get DATE_SHORT(){return Br}static get DATE_MED(){return ra}static get DATE_MED_WITH_WEEKDAY(){return Uf}static get DATE_FULL(){return oa}static get DATE_HUGE(){return sa}static get TIME_SIMPLE(){return aa}static get TIME_WITH_SECONDS(){return ca}static get TIME_WITH_SHORT_OFFSET(){return ua}static get TIME_WITH_LONG_OFFSET(){return la}static get TIME_24_SIMPLE(){return da}static get TIME_24_WITH_SECONDS(){return fa}static get TIME_24_WITH_SHORT_OFFSET(){return ha}static get TIME_24_WITH_LONG_OFFSET(){return pa}static get DATETIME_SHORT(){return ma}static get DATETIME_SHORT_WITH_SECONDS(){return ga}static get DATETIME_MED(){return _a}static get DATETIME_MED_WITH_SECONDS(){return wa}static get DATETIME_MED_WITH_WEEKDAY(){return $f}static get DATETIME_FULL(){return ya}static get DATETIME_FULL_WITH_SECONDS(){return ba}static get DATETIME_HUGE(){return va}static get DATETIME_HUGE_WITH_SECONDS(){return ka}};function ms(t){if(Je.isDateTime(t))return t;if(t&&t.valueOf&&Hi(t.valueOf()))return Je.fromJSDate(t);if(t&&typeof t=="object")return Je.fromObject(t);throw new hn(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var qa=require("@mysten/sui.js/transactions"),zh=require("@mysten/sui.js/transactions"),Ua=require("@mysten/sui.js/utils"),Vh=require("buffer"),wb=require("@mysten/sui.js/utils"),np=require("@mysten/sui.js/bcs"),$a=require("@mysten/sui.js/utils");var Mw=(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 Hh=require("@mysten/sui.js/transactions"),Xr=require("@mysten/sui.js/utils");var La=require("@mysten/sui.js/transactions"),Ga=require("@mysten/sui.js/utils");var Mb=Pe(hc(),1),jb=require("@msafe/sui3-utils"),Nb=require("@msafe/sui3-utils"),Rb=require("@msafe/sui3-utils"),Yh=require("@mysten/sui.js/bcs"),Kr=require("@mysten/sui.js/utils"),qb=require("@msafe/sui3-utils"),bs=require("@msafe/sui3-utils"),Lb=require("@msafe/sui3-utils"),$b=require("@msafe/sui3-utils"),zb=require("@msafe/sui3-utils"),Vb=require("@mysten/sui.js/transactions"),Wb=require("@msafe/sui3-utils"),ys=require("@msafe/sui3-utils"),Qh=require("@mysten/sui.js/bcs"),Wr=require("@mysten/sui.js/utils"),Hb=require("@mysten/sui.js/transactions"),Zb=require("@mysten/sui.js/transactions"),Yb=require("@mysten/sui.js/transactions"),tv=require("@mysten/sui.js/transactions"),iv=require("@mysten/sui.js/transactions"),Al=require("@msafe/sui3-utils"),ov=require("@mysten/sui.js/transactions"),Sl=require("@mysten/sui.js/utils"),i5=Pe(hc(),1),sv=require("@msafe/sui3-utils"),av=require("@msafe/sui3-utils"),ep=require("@mysten/sui.js/bcs"),Hr=require("@mysten/sui.js/utils");var g6=Pe(Ee(),1);var ko=require("@mysten/sui.js/client"),Jw=require("@mysten/sui.js/keypairs/ed25519");function jw(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Wx(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Ah(t,...e){if(!Wx(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 Sh(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 Nw(t,e){Ah(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var nl=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Hx(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var rl=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Fi=(t,e)=>t<<32-e|t>>>e,Xx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Xx)throw new Error("Non little-endian hardware is not supported");function Zx(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Ih(t){if(typeof t=="string"&&(t=Zx(t)),!Hx(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var il=class{clone(){return this._cloneInto()}},c8={}.toString;function Rw(t){let e=i=>t().update(Ih(i)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Fw(t=32){if(nl&&typeof nl.getRandomValues=="function")return nl.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Jx(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),c=i?4:0,u=i?0:4;t.setUint32(e+c,s,i),t.setUint32(e+u,a,i)}var ol=class extends il{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=rl(this.buffer)}update(e){Sh(this);let{view:n,buffer:i,blockLen:r}=this;e=Ih(e);let o=e.length;for(let s=0;s<o;){let a=Math.min(r-this.pos,o-s);if(a===r){let c=rl(e);for(;r<=o-s;s+=r)this.process(c,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){Sh(this),Nw(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 h=s;h<r;h++)n[h]=0;Jx(i,r-8,BigInt(this.length*8),o),this.process(i,0);let a=rl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,d[h],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 Yx=(t,e,n)=>t&e^~t&n,Qx=(t,e,n)=>t&e^t&n^e&n,e6=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]),Lr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ur=new Uint32Array(64),xh=class extends ol{constructor(){super(64,32,8,!1),this.A=Lr[0]|0,this.B=Lr[1]|0,this.C=Lr[2]|0,this.D=Lr[3]|0,this.E=Lr[4]|0,this.F=Lr[5]|0,this.G=Lr[6]|0,this.H=Lr[7]|0}get(){let{A:e,B:n,C:i,D:r,E:o,F:s,G:a,H:c}=this;return[e,n,i,r,o,s,a,c]}set(e,n,i,r,o,s,a,c){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=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)Ur[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){let _=Ur[h-15],C=Ur[h-2],D=Fi(_,7)^Fi(_,18)^_>>>3,O=Fi(C,17)^Fi(C,19)^C>>>10;Ur[h]=O+Ur[h-7]+D+Ur[h-16]|0}let{A:i,B:r,C:o,D:s,E:a,F:c,G:u,H:d}=this;for(let h=0;h<64;h++){let _=Fi(a,6)^Fi(a,11)^Fi(a,25),C=d+_+Yx(a,c,u)+e6[h]+Ur[h]|0,O=(Fi(i,2)^Fi(i,13)^Fi(i,22))+Qx(i,r,o)|0;d=u,u=c,c=a,a=s+C|0,s=o,o=r,r=i,i=C+O|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,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(i,r,o,s,a,c,u,d)}roundClean(){Ur.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var qw=Rw(()=>new xh);function yo(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function sl(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function t6(...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 n6(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 i6(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 r6(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 Oh(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 c=i;c<o.length;c++){let u=o[c],d=e*s+u;if(!Number.isSafeInteger(d)||e*s/e!==s||d-u!==e*s)throw new Error("convertRadix: carry overflow");s=d%n;let h=Math.floor(d/n);if(o[c]=h,!Number.isSafeInteger(h)||h*n+s!==d)throw new Error("convertRadix: carry overflow");if(a)h?a=!1:i=c;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 Lw=(t,e)=>e?Lw(e,t%e):t,al=(t,e)=>t+(e-Lw(t,e));function Ph(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(al(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${al(e,n)}`);let r=0,o=0,s=2**n-1,a=[];for(let c of t){if(c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(r=r<<e|c,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 o6(t){return{encode:e=>{if(!sl(e))throw new Error("radix.encode input should be Uint8Array");return Oh(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(Oh(e,t,2**8))}}}function s6(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(al(8,t)>32||al(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!sl(n))throw new Error("radix2.encode input should be Uint8Array");return Ph(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(Ph(n,t,8,e))}}}function a6(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(n){if(!sl(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(!sl(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 Ba={alphabet:n6,chain:t6,checksum:a6,convertRadix:Oh,convertRadix2:Ph,radix:o6,radix2:s6,join:i6,padding:r6};var c6=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function u6(t){Ah(t,16,20,24,28,32)}function Uw(t,e=128){if(jw(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return f6(Fw(e/8),t)}var l6=t=>{let e=8-t.length/4;return new Uint8Array([qw(t)[0]>>e<<e])};function d6(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}`)}),Ba.chain(Ba.checksum(1,l6),Ba.radix2(11,!0),Ba.alphabet(t))}function f6(t,e){return u6(t),d6(e).encode(t).join(c6(e)?"\u3000":" ")}var $w=`abandon
|
|
1
|
+
"use strict";var Hp=Object.create;var Vi=Object.defineProperty;var Zp=Object.getOwnPropertyDescriptor;var Kp=Object.getOwnPropertyNames;var Jp=Object.getPrototypeOf,Xp=Object.prototype.hasOwnProperty;var Yp=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),fc=(t,e)=>{for(var r in e)Vi(t,r,{get:e[r],enumerable:!0})},hc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Kp(e))!Xp.call(t,i)&&i!==r&&Vi(t,i,{get:()=>e[i],enumerable:!(n=Zp(e,i))||n.enumerable});return t};var de=(t,e,r)=>(r=t!=null?Hp(Jp(t)):{},hc(e||!t||!t.__esModule?Vi(r,"default",{value:t,enumerable:!0}):r,t)),pc=t=>hc(Vi({},"__esModule",{value:!0}),t);var wc=Fr((U_,gc)=>{"use strict";gc.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var bc=Fr(($_,yc)=>{"use strict";var Ws=wc();yc.exports=(t,e={})=>{if(!Ws(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");let{deep:r}=e,n=[],i=[],o=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d=[];return n.push(u),i.push(d),d.push(...u.map(b=>Array.isArray(b)?o(b):Ws(b)?s(b):b)),d},s=u=>{let l=n.indexOf(u);if(l!==-1)return i[l];let d={},b=Object.keys(u).sort(e.compare);n.push(u),i.push(d);for(let _ of b){let T=u[_],x;r&&Array.isArray(T)?x=o(T):x=r&&Ws(T)?s(T):T,Object.defineProperty(d,_,{...Object.getOwnPropertyDescriptor(u,_),value:x})}return d};return Array.isArray(t)?r?o(t):t.slice():s(t)}});var Tc=Fr((G_,vc)=>{"use strict";var Qp=Object.prototype.toString;vc.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var r=typeof e;if(r==="boolean")return"boolean";if(r==="string")return"string";if(r==="number")return"number";if(r==="symbol")return"symbol";if(r==="function")return im(e)?"generatorfunction":"function";if(em(e))return"array";if(am(e))return"buffer";if(sm(e))return"arguments";if(rm(e))return"date";if(tm(e))return"error";if(nm(e))return"regexp";switch(_c(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(om(e))return"generator";switch(r=Qp.call(e),r){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return r.slice(8,-1).toLowerCase().replace(/\s/g,"")};function _c(t){return typeof t.constructor=="function"?t.constructor.name:null}function em(t){return Array.isArray?Array.isArray(t):t instanceof Array}function tm(t){return t instanceof Error||typeof t.message=="string"&&t.constructor&&typeof t.constructor.stackTraceLimit=="number"}function rm(t){return t instanceof Date?!0:typeof t.toDateString=="function"&&typeof t.getDate=="function"&&typeof t.setDate=="function"}function nm(t){return t instanceof RegExp?!0:typeof t.flags=="string"&&typeof t.ignoreCase=="boolean"&&typeof t.multiline=="boolean"&&typeof t.global=="boolean"}function im(t,e){return _c(t)==="GeneratorFunction"}function om(t){return typeof t.throw=="function"&&typeof t.return=="function"&&typeof t.next=="function"}function sm(t){try{if(typeof t.length=="number"&&typeof t.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function am(t){return t.constructor&&typeof t.constructor.isBuffer=="function"?t.constructor.isBuffer(t):!1}});var Wi=Fr((V_,Ac)=>{"use strict";var um=bc(),Hs=Tc(),Sc=(t,e)=>!e||Hs(e)!=="array"?!1:e.indexOf(t)>-1,cm=(t,e)=>um(t,{compare:e}),xc=(t,e)=>{let r=e&&e.compareFunction;return t.slice().sort(r)};function kc(t,e){let r=e&&e.compareFunction,n=cm(t,r);return Object.keys(t).forEach(function(i){let o=n[i],s=Hs(o);if(s==="object"){(!e||!Sc(i,e.ignoreObjectAtKeys))&&(n[i]=kc(o,e));return}s==="array"&&(!e||!Sc(i,e.ignoreArrayAtKeys))&&(n[i]=xc(o,e))}),n}var Un=(t,e)=>{let r=Hs(t);return Un[r]?Un[r](t,e):t};Un.array=xc;Un.object=kc;Ac.exports=Un});var we=Fr((Ic,Zs)=>{"use strict";(function(t,e){"use strict";function r(k,a){if(!k)throw new Error(a||"Assertion failed")}function n(k,a){k.super_=a;var c=function(){};c.prototype=a.prototype,k.prototype=new c,k.prototype.constructor=k}function i(k,a,c){if(i.isBN(k))return k;this.negative=0,this.words=null,this.length=0,this.red=null,k!==null&&((a==="le"||a==="be")&&(c=a,a=10),this._init(k||0,a||10,c||"be"))}typeof t=="object"?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=require("buffer").Buffer}catch{}i.isBN=function(a){return a instanceof i?!0:a!==null&&typeof a=="object"&&a.constructor.wordSize===i.wordSize&&Array.isArray(a.words)},i.max=function(a,c){return a.cmp(c)>0?a:c},i.min=function(a,c){return a.cmp(c)<0?a:c},i.prototype._init=function(a,c,m){if(typeof a=="number")return this._initNumber(a,c,m);if(typeof a=="object")return this._initArray(a,c,m);c==="hex"&&(c=16),r(c===(c|0)&&c>=2&&c<=36),a=a.toString().replace(/\s+/g,"");var y=0;a[0]==="-"&&(y++,this.negative=1),y<a.length&&(c===16?this._parseHex(a,y,m):(this._parseBase(a,c,y),m==="le"&&this._initArray(this.toArray(),c,m)))},i.prototype._initNumber=function(a,c,m){a<0&&(this.negative=1,a=-a),a<67108864?(this.words=[a&67108863],this.length=1):a<4503599627370496?(this.words=[a&67108863,a/67108864&67108863],this.length=2):(r(a<9007199254740992),this.words=[a&67108863,a/67108864&67108863,1],this.length=3),m==="le"&&this._initArray(this.toArray(),c,m)},i.prototype._initArray=function(a,c,m){if(r(typeof a.length=="number"),a.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(a.length/3),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p,h,w=0;if(m==="be")for(y=a.length-1,p=0;y>=0;y-=3)h=a[y]|a[y-1]<<8|a[y-2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);else if(m==="le")for(y=0,p=0;y<a.length;y+=3)h=a[y]|a[y+1]<<8|a[y+2]<<16,this.words[p]|=h<<w&67108863,this.words[p+1]=h>>>26-w&67108863,w+=24,w>=26&&(w-=26,p++);return this._strip()};function s(k,a){var c=k.charCodeAt(a);if(c>=48&&c<=57)return c-48;if(c>=65&&c<=70)return c-55;if(c>=97&&c<=102)return c-87;r(!1,"Invalid character in "+k)}function u(k,a,c){var m=s(k,c);return c-1>=a&&(m|=s(k,c-1)<<4),m}i.prototype._parseHex=function(a,c,m){this.length=Math.ceil((a.length-c)/6),this.words=new Array(this.length);for(var y=0;y<this.length;y++)this.words[y]=0;var p=0,h=0,w;if(m==="be")for(y=a.length-1;y>=c;y-=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8;else{var g=a.length-c;for(y=g%2===0?c+1:c;y<a.length;y+=2)w=u(a,c,y)<<p,this.words[h]|=w&67108863,p>=18?(p-=18,h+=1,this.words[h]|=w>>>26):p+=8}this._strip()};function l(k,a,c,m){for(var y=0,p=0,h=Math.min(k.length,c),w=a;w<h;w++){var g=k.charCodeAt(w)-48;y*=m,g>=49?p=g-49+10:g>=17?p=g-17+10:p=g,r(g>=0&&p<m,"Invalid character"),y+=p}return y}i.prototype._parseBase=function(a,c,m){this.words=[0],this.length=1;for(var y=0,p=1;p<=67108863;p*=c)y++;y--,p=p/c|0;for(var h=a.length-m,w=h%y,g=Math.min(h,h-w)+m,f=0,v=m;v<g;v+=y)f=l(a,v,v+y,c),this.imuln(p),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f);if(w!==0){var O=1;for(f=l(a,v,a.length,c),v=0;v<w;v++)O*=c;this.imuln(O),this.words[0]+f<67108864?this.words[0]+=f:this._iaddn(f)}this._strip()},i.prototype.copy=function(a){a.words=new Array(this.length);for(var c=0;c<this.length;c++)a.words[c]=this.words[c];a.length=this.length,a.negative=this.negative,a.red=this.red};function d(k,a){k.words=a.words,k.length=a.length,k.negative=a.negative,k.red=a.red}if(i.prototype._move=function(a){d(a,this)},i.prototype.clone=function(){var a=new i(null);return this.copy(a),a},i.prototype._expand=function(a){for(;this.length<a;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=b}catch{i.prototype.inspect=b}else i.prototype.inspect=b;function b(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var _=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],T=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],x=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(a,c){a=a||10,c=c|0||1;var m;if(a===16||a==="hex"){m="";for(var y=0,p=0,h=0;h<this.length;h++){var w=this.words[h],g=((w<<y|p)&16777215).toString(16);p=w>>>24-y&16777215,y+=2,y>=26&&(y-=26,h--),p!==0||h!==this.length-1?m=_[6-g.length]+g+m:m=g+m}for(p!==0&&(m=p.toString(16)+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}if(a===(a|0)&&a>=2&&a<=36){var f=T[a],v=x[a];m="";var O=this.clone();for(O.negative=0;!O.isZero();){var M=O.modrn(v).toString(a);O=O.idivn(v),O.isZero()?m=M+m:m=_[f-M.length]+M+m}for(this.isZero()&&(m="0"+m);m.length%c!==0;)m="0"+m;return this.negative!==0&&(m="-"+m),m}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var a=this.words[0];return this.length===2?a+=this.words[1]*67108864:this.length===3&&this.words[2]===1?a+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-a:a},i.prototype.toJSON=function(){return this.toString(16,2)},o&&(i.prototype.toBuffer=function(a,c){return this.toArrayLike(o,a,c)}),i.prototype.toArray=function(a,c){return this.toArrayLike(Array,a,c)};var A=function(a,c){return a.allocUnsafe?a.allocUnsafe(c):new a(c)};i.prototype.toArrayLike=function(a,c,m){this._strip();var y=this.byteLength(),p=m||Math.max(1,y);r(y<=p,"byte array longer than desired length"),r(p>0,"Requested array length <= 0");var h=A(a,p),w=c==="le"?"LE":"BE";return this["_toArrayLike"+w](h,y),h},i.prototype._toArrayLikeLE=function(a,c){for(var m=0,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m++]=w&255,m<a.length&&(a[m++]=w>>8&255),m<a.length&&(a[m++]=w>>16&255),h===6?(m<a.length&&(a[m++]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m<a.length)for(a[m++]=y;m<a.length;)a[m++]=0},i.prototype._toArrayLikeBE=function(a,c){for(var m=a.length-1,y=0,p=0,h=0;p<this.length;p++){var w=this.words[p]<<h|y;a[m--]=w&255,m>=0&&(a[m--]=w>>8&255),m>=0&&(a[m--]=w>>16&255),h===6?(m>=0&&(a[m--]=w>>24&255),y=0,h=0):(y=w>>>24,h+=2)}if(m>=0)for(a[m--]=y;m>=0;)a[m--]=0},Math.clz32?i.prototype._countBits=function(a){return 32-Math.clz32(a)}:i.prototype._countBits=function(a){var c=a,m=0;return c>=4096&&(m+=13,c>>>=13),c>=64&&(m+=7,c>>>=7),c>=8&&(m+=4,c>>>=4),c>=2&&(m+=2,c>>>=2),m+c},i.prototype._zeroBits=function(a){if(a===0)return 26;var c=a,m=0;return c&8191||(m+=13,c>>>=13),c&127||(m+=7,c>>>=7),c&15||(m+=4,c>>>=4),c&3||(m+=2,c>>>=2),c&1||m++,m},i.prototype.bitLength=function(){var a=this.words[this.length-1],c=this._countBits(a);return(this.length-1)*26+c};function I(k){for(var a=new Array(k.bitLength()),c=0;c<a.length;c++){var m=c/26|0,y=c%26;a[c]=k.words[m]>>>y&1}return a}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var a=0,c=0;c<this.length;c++){var m=this._zeroBits(this.words[c]);if(a+=m,m!==26)break}return a},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(a){return this.negative!==0?this.abs().inotn(a).iaddn(1):this.clone()},i.prototype.fromTwos=function(a){return this.testn(a-1)?this.notn(a).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(a){for(;this.length<a.length;)this.words[this.length++]=0;for(var c=0;c<a.length;c++)this.words[c]=this.words[c]|a.words[c];return this._strip()},i.prototype.ior=function(a){return r((this.negative|a.negative)===0),this.iuor(a)},i.prototype.or=function(a){return this.length>a.length?this.clone().ior(a):a.clone().ior(this)},i.prototype.uor=function(a){return this.length>a.length?this.clone().iuor(a):a.clone().iuor(this)},i.prototype.iuand=function(a){var c;this.length>a.length?c=a:c=this;for(var m=0;m<c.length;m++)this.words[m]=this.words[m]&a.words[m];return this.length=c.length,this._strip()},i.prototype.iand=function(a){return r((this.negative|a.negative)===0),this.iuand(a)},i.prototype.and=function(a){return this.length>a.length?this.clone().iand(a):a.clone().iand(this)},i.prototype.uand=function(a){return this.length>a.length?this.clone().iuand(a):a.clone().iuand(this)},i.prototype.iuxor=function(a){var c,m;this.length>a.length?(c=this,m=a):(c=a,m=this);for(var y=0;y<m.length;y++)this.words[y]=c.words[y]^m.words[y];if(this!==c)for(;y<c.length;y++)this.words[y]=c.words[y];return this.length=c.length,this._strip()},i.prototype.ixor=function(a){return r((this.negative|a.negative)===0),this.iuxor(a)},i.prototype.xor=function(a){return this.length>a.length?this.clone().ixor(a):a.clone().ixor(this)},i.prototype.uxor=function(a){return this.length>a.length?this.clone().iuxor(a):a.clone().iuxor(this)},i.prototype.inotn=function(a){r(typeof a=="number"&&a>=0);var c=Math.ceil(a/26)|0,m=a%26;this._expand(c),m>0&&c--;for(var y=0;y<c;y++)this.words[y]=~this.words[y]&67108863;return m>0&&(this.words[y]=~this.words[y]&67108863>>26-m),this._strip()},i.prototype.notn=function(a){return this.clone().inotn(a)},i.prototype.setn=function(a,c){r(typeof a=="number"&&a>=0);var m=a/26|0,y=a%26;return this._expand(m+1),c?this.words[m]=this.words[m]|1<<y:this.words[m]=this.words[m]&~(1<<y),this._strip()},i.prototype.iadd=function(a){var c;if(this.negative!==0&&a.negative===0)return this.negative=0,c=this.isub(a),this.negative^=1,this._normSign();if(this.negative===0&&a.negative!==0)return a.negative=0,c=this.isub(a),a.negative=1,c._normSign();var m,y;this.length>a.length?(m=this,y=a):(m=a,y=this);for(var p=0,h=0;h<y.length;h++)c=(m.words[h]|0)+(y.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;for(;p!==0&&h<m.length;h++)c=(m.words[h]|0)+p,this.words[h]=c&67108863,p=c>>>26;if(this.length=m.length,p!==0)this.words[this.length]=p,this.length++;else if(m!==this)for(;h<m.length;h++)this.words[h]=m.words[h];return this},i.prototype.add=function(a){var c;return a.negative!==0&&this.negative===0?(a.negative=0,c=this.sub(a),a.negative^=1,c):a.negative===0&&this.negative!==0?(this.negative=0,c=a.sub(this),this.negative=1,c):this.length>a.length?this.clone().iadd(a):a.clone().iadd(this)},i.prototype.isub=function(a){if(a.negative!==0){a.negative=0;var c=this.iadd(a);return a.negative=1,c._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(a),this.negative=1,this._normSign();var m=this.cmp(a);if(m===0)return this.negative=0,this.length=1,this.words[0]=0,this;var y,p;m>0?(y=this,p=a):(y=a,p=this);for(var h=0,w=0;w<p.length;w++)c=(y.words[w]|0)-(p.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;for(;h!==0&&w<y.length;w++)c=(y.words[w]|0)+h,h=c>>26,this.words[w]=c&67108863;if(h===0&&w<y.length&&y!==this)for(;w<y.length;w++)this.words[w]=y.words[w];return this.length=Math.max(this.length,w),y!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(a){return this.clone().isub(a)};function C(k,a,c){c.negative=a.negative^k.negative;var m=k.length+a.length|0;c.length=m,m=m-1|0;var y=k.words[0]|0,p=a.words[0]|0,h=y*p,w=h&67108863,g=h/67108864|0;c.words[0]=w;for(var f=1;f<m;f++){for(var v=g>>>26,O=g&67108863,M=Math.min(f,a.length-1),R=Math.max(0,f-k.length+1);R<=M;R++){var B=f-R|0;y=k.words[B]|0,p=a.words[R]|0,h=y*p+O,v+=h/67108864|0,O=h&67108863}c.words[f]=O|0,g=v|0}return g!==0?c.words[f]=g|0:c.length--,c._strip()}var E=function(a,c,m){var y=a.words,p=c.words,h=m.words,w=0,g,f,v,O=y[0]|0,M=O&8191,R=O>>>13,B=y[1]|0,G=B&8191,Z=B>>>13,oe=y[2]|0,te=oe&8191,ae=oe>>>13,dt=y[3]|0,ve=dt&8191,xe=dt>>>13,an=y[4]|0,Ae=an&8191,Me=an>>>13,Gi=y[5]|0,De=Gi&8191,Be=Gi>>>13,Yu=y[6]|0,Ne=Yu&8191,Re=Yu>>>13,Qu=y[7]|0,je=Qu&8191,Fe=Qu>>>13,ec=y[8]|0,qe=ec&8191,Le=ec>>>13,tc=y[9]|0,Ue=tc&8191,$e=tc>>>13,rc=p[0]|0,Ge=rc&8191,Ve=rc>>>13,nc=p[1]|0,ze=nc&8191,We=nc>>>13,ic=p[2]|0,He=ic&8191,Ze=ic>>>13,oc=p[3]|0,Ke=oc&8191,Je=oc>>>13,sc=p[4]|0,Xe=sc&8191,Ye=sc>>>13,ac=p[5]|0,Qe=ac&8191,et=ac>>>13,uc=p[6]|0,tt=uc&8191,rt=uc>>>13,cc=p[7]|0,nt=cc&8191,it=cc>>>13,lc=p[8]|0,ot=lc&8191,st=lc>>>13,dc=p[9]|0,at=dc&8191,ut=dc>>>13;m.negative=a.negative^c.negative,m.length=19,g=Math.imul(M,Ge),f=Math.imul(M,Ve),f=f+Math.imul(R,Ge)|0,v=Math.imul(R,Ve);var Is=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Is>>>26)|0,Is&=67108863,g=Math.imul(G,Ge),f=Math.imul(G,Ve),f=f+Math.imul(Z,Ge)|0,v=Math.imul(Z,Ve),g=g+Math.imul(M,ze)|0,f=f+Math.imul(M,We)|0,f=f+Math.imul(R,ze)|0,v=v+Math.imul(R,We)|0;var Cs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Cs>>>26)|0,Cs&=67108863,g=Math.imul(te,Ge),f=Math.imul(te,Ve),f=f+Math.imul(ae,Ge)|0,v=Math.imul(ae,Ve),g=g+Math.imul(G,ze)|0,f=f+Math.imul(G,We)|0,f=f+Math.imul(Z,ze)|0,v=v+Math.imul(Z,We)|0,g=g+Math.imul(M,He)|0,f=f+Math.imul(M,Ze)|0,f=f+Math.imul(R,He)|0,v=v+Math.imul(R,Ze)|0;var Os=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Os>>>26)|0,Os&=67108863,g=Math.imul(ve,Ge),f=Math.imul(ve,Ve),f=f+Math.imul(xe,Ge)|0,v=Math.imul(xe,Ve),g=g+Math.imul(te,ze)|0,f=f+Math.imul(te,We)|0,f=f+Math.imul(ae,ze)|0,v=v+Math.imul(ae,We)|0,g=g+Math.imul(G,He)|0,f=f+Math.imul(G,Ze)|0,f=f+Math.imul(Z,He)|0,v=v+Math.imul(Z,Ze)|0,g=g+Math.imul(M,Ke)|0,f=f+Math.imul(M,Je)|0,f=f+Math.imul(R,Ke)|0,v=v+Math.imul(R,Je)|0;var Ms=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ms>>>26)|0,Ms&=67108863,g=Math.imul(Ae,Ge),f=Math.imul(Ae,Ve),f=f+Math.imul(Me,Ge)|0,v=Math.imul(Me,Ve),g=g+Math.imul(ve,ze)|0,f=f+Math.imul(ve,We)|0,f=f+Math.imul(xe,ze)|0,v=v+Math.imul(xe,We)|0,g=g+Math.imul(te,He)|0,f=f+Math.imul(te,Ze)|0,f=f+Math.imul(ae,He)|0,v=v+Math.imul(ae,Ze)|0,g=g+Math.imul(G,Ke)|0,f=f+Math.imul(G,Je)|0,f=f+Math.imul(Z,Ke)|0,v=v+Math.imul(Z,Je)|0,g=g+Math.imul(M,Xe)|0,f=f+Math.imul(M,Ye)|0,f=f+Math.imul(R,Xe)|0,v=v+Math.imul(R,Ye)|0;var Es=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Es>>>26)|0,Es&=67108863,g=Math.imul(De,Ge),f=Math.imul(De,Ve),f=f+Math.imul(Be,Ge)|0,v=Math.imul(Be,Ve),g=g+Math.imul(Ae,ze)|0,f=f+Math.imul(Ae,We)|0,f=f+Math.imul(Me,ze)|0,v=v+Math.imul(Me,We)|0,g=g+Math.imul(ve,He)|0,f=f+Math.imul(ve,Ze)|0,f=f+Math.imul(xe,He)|0,v=v+Math.imul(xe,Ze)|0,g=g+Math.imul(te,Ke)|0,f=f+Math.imul(te,Je)|0,f=f+Math.imul(ae,Ke)|0,v=v+Math.imul(ae,Je)|0,g=g+Math.imul(G,Xe)|0,f=f+Math.imul(G,Ye)|0,f=f+Math.imul(Z,Xe)|0,v=v+Math.imul(Z,Ye)|0,g=g+Math.imul(M,Qe)|0,f=f+Math.imul(M,et)|0,f=f+Math.imul(R,Qe)|0,v=v+Math.imul(R,et)|0;var Ps=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ps>>>26)|0,Ps&=67108863,g=Math.imul(Ne,Ge),f=Math.imul(Ne,Ve),f=f+Math.imul(Re,Ge)|0,v=Math.imul(Re,Ve),g=g+Math.imul(De,ze)|0,f=f+Math.imul(De,We)|0,f=f+Math.imul(Be,ze)|0,v=v+Math.imul(Be,We)|0,g=g+Math.imul(Ae,He)|0,f=f+Math.imul(Ae,Ze)|0,f=f+Math.imul(Me,He)|0,v=v+Math.imul(Me,Ze)|0,g=g+Math.imul(ve,Ke)|0,f=f+Math.imul(ve,Je)|0,f=f+Math.imul(xe,Ke)|0,v=v+Math.imul(xe,Je)|0,g=g+Math.imul(te,Xe)|0,f=f+Math.imul(te,Ye)|0,f=f+Math.imul(ae,Xe)|0,v=v+Math.imul(ae,Ye)|0,g=g+Math.imul(G,Qe)|0,f=f+Math.imul(G,et)|0,f=f+Math.imul(Z,Qe)|0,v=v+Math.imul(Z,et)|0,g=g+Math.imul(M,tt)|0,f=f+Math.imul(M,rt)|0,f=f+Math.imul(R,tt)|0,v=v+Math.imul(R,rt)|0;var Ds=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ds>>>26)|0,Ds&=67108863,g=Math.imul(je,Ge),f=Math.imul(je,Ve),f=f+Math.imul(Fe,Ge)|0,v=Math.imul(Fe,Ve),g=g+Math.imul(Ne,ze)|0,f=f+Math.imul(Ne,We)|0,f=f+Math.imul(Re,ze)|0,v=v+Math.imul(Re,We)|0,g=g+Math.imul(De,He)|0,f=f+Math.imul(De,Ze)|0,f=f+Math.imul(Be,He)|0,v=v+Math.imul(Be,Ze)|0,g=g+Math.imul(Ae,Ke)|0,f=f+Math.imul(Ae,Je)|0,f=f+Math.imul(Me,Ke)|0,v=v+Math.imul(Me,Je)|0,g=g+Math.imul(ve,Xe)|0,f=f+Math.imul(ve,Ye)|0,f=f+Math.imul(xe,Xe)|0,v=v+Math.imul(xe,Ye)|0,g=g+Math.imul(te,Qe)|0,f=f+Math.imul(te,et)|0,f=f+Math.imul(ae,Qe)|0,v=v+Math.imul(ae,et)|0,g=g+Math.imul(G,tt)|0,f=f+Math.imul(G,rt)|0,f=f+Math.imul(Z,tt)|0,v=v+Math.imul(Z,rt)|0,g=g+Math.imul(M,nt)|0,f=f+Math.imul(M,it)|0,f=f+Math.imul(R,nt)|0,v=v+Math.imul(R,it)|0;var Bs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Bs>>>26)|0,Bs&=67108863,g=Math.imul(qe,Ge),f=Math.imul(qe,Ve),f=f+Math.imul(Le,Ge)|0,v=Math.imul(Le,Ve),g=g+Math.imul(je,ze)|0,f=f+Math.imul(je,We)|0,f=f+Math.imul(Fe,ze)|0,v=v+Math.imul(Fe,We)|0,g=g+Math.imul(Ne,He)|0,f=f+Math.imul(Ne,Ze)|0,f=f+Math.imul(Re,He)|0,v=v+Math.imul(Re,Ze)|0,g=g+Math.imul(De,Ke)|0,f=f+Math.imul(De,Je)|0,f=f+Math.imul(Be,Ke)|0,v=v+Math.imul(Be,Je)|0,g=g+Math.imul(Ae,Xe)|0,f=f+Math.imul(Ae,Ye)|0,f=f+Math.imul(Me,Xe)|0,v=v+Math.imul(Me,Ye)|0,g=g+Math.imul(ve,Qe)|0,f=f+Math.imul(ve,et)|0,f=f+Math.imul(xe,Qe)|0,v=v+Math.imul(xe,et)|0,g=g+Math.imul(te,tt)|0,f=f+Math.imul(te,rt)|0,f=f+Math.imul(ae,tt)|0,v=v+Math.imul(ae,rt)|0,g=g+Math.imul(G,nt)|0,f=f+Math.imul(G,it)|0,f=f+Math.imul(Z,nt)|0,v=v+Math.imul(Z,it)|0,g=g+Math.imul(M,ot)|0,f=f+Math.imul(M,st)|0,f=f+Math.imul(R,ot)|0,v=v+Math.imul(R,st)|0;var Ns=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ns>>>26)|0,Ns&=67108863,g=Math.imul(Ue,Ge),f=Math.imul(Ue,Ve),f=f+Math.imul($e,Ge)|0,v=Math.imul($e,Ve),g=g+Math.imul(qe,ze)|0,f=f+Math.imul(qe,We)|0,f=f+Math.imul(Le,ze)|0,v=v+Math.imul(Le,We)|0,g=g+Math.imul(je,He)|0,f=f+Math.imul(je,Ze)|0,f=f+Math.imul(Fe,He)|0,v=v+Math.imul(Fe,Ze)|0,g=g+Math.imul(Ne,Ke)|0,f=f+Math.imul(Ne,Je)|0,f=f+Math.imul(Re,Ke)|0,v=v+Math.imul(Re,Je)|0,g=g+Math.imul(De,Xe)|0,f=f+Math.imul(De,Ye)|0,f=f+Math.imul(Be,Xe)|0,v=v+Math.imul(Be,Ye)|0,g=g+Math.imul(Ae,Qe)|0,f=f+Math.imul(Ae,et)|0,f=f+Math.imul(Me,Qe)|0,v=v+Math.imul(Me,et)|0,g=g+Math.imul(ve,tt)|0,f=f+Math.imul(ve,rt)|0,f=f+Math.imul(xe,tt)|0,v=v+Math.imul(xe,rt)|0,g=g+Math.imul(te,nt)|0,f=f+Math.imul(te,it)|0,f=f+Math.imul(ae,nt)|0,v=v+Math.imul(ae,it)|0,g=g+Math.imul(G,ot)|0,f=f+Math.imul(G,st)|0,f=f+Math.imul(Z,ot)|0,v=v+Math.imul(Z,st)|0,g=g+Math.imul(M,at)|0,f=f+Math.imul(M,ut)|0,f=f+Math.imul(R,at)|0,v=v+Math.imul(R,ut)|0;var Rs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Rs>>>26)|0,Rs&=67108863,g=Math.imul(Ue,ze),f=Math.imul(Ue,We),f=f+Math.imul($e,ze)|0,v=Math.imul($e,We),g=g+Math.imul(qe,He)|0,f=f+Math.imul(qe,Ze)|0,f=f+Math.imul(Le,He)|0,v=v+Math.imul(Le,Ze)|0,g=g+Math.imul(je,Ke)|0,f=f+Math.imul(je,Je)|0,f=f+Math.imul(Fe,Ke)|0,v=v+Math.imul(Fe,Je)|0,g=g+Math.imul(Ne,Xe)|0,f=f+Math.imul(Ne,Ye)|0,f=f+Math.imul(Re,Xe)|0,v=v+Math.imul(Re,Ye)|0,g=g+Math.imul(De,Qe)|0,f=f+Math.imul(De,et)|0,f=f+Math.imul(Be,Qe)|0,v=v+Math.imul(Be,et)|0,g=g+Math.imul(Ae,tt)|0,f=f+Math.imul(Ae,rt)|0,f=f+Math.imul(Me,tt)|0,v=v+Math.imul(Me,rt)|0,g=g+Math.imul(ve,nt)|0,f=f+Math.imul(ve,it)|0,f=f+Math.imul(xe,nt)|0,v=v+Math.imul(xe,it)|0,g=g+Math.imul(te,ot)|0,f=f+Math.imul(te,st)|0,f=f+Math.imul(ae,ot)|0,v=v+Math.imul(ae,st)|0,g=g+Math.imul(G,at)|0,f=f+Math.imul(G,ut)|0,f=f+Math.imul(Z,at)|0,v=v+Math.imul(Z,ut)|0;var js=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(js>>>26)|0,js&=67108863,g=Math.imul(Ue,He),f=Math.imul(Ue,Ze),f=f+Math.imul($e,He)|0,v=Math.imul($e,Ze),g=g+Math.imul(qe,Ke)|0,f=f+Math.imul(qe,Je)|0,f=f+Math.imul(Le,Ke)|0,v=v+Math.imul(Le,Je)|0,g=g+Math.imul(je,Xe)|0,f=f+Math.imul(je,Ye)|0,f=f+Math.imul(Fe,Xe)|0,v=v+Math.imul(Fe,Ye)|0,g=g+Math.imul(Ne,Qe)|0,f=f+Math.imul(Ne,et)|0,f=f+Math.imul(Re,Qe)|0,v=v+Math.imul(Re,et)|0,g=g+Math.imul(De,tt)|0,f=f+Math.imul(De,rt)|0,f=f+Math.imul(Be,tt)|0,v=v+Math.imul(Be,rt)|0,g=g+Math.imul(Ae,nt)|0,f=f+Math.imul(Ae,it)|0,f=f+Math.imul(Me,nt)|0,v=v+Math.imul(Me,it)|0,g=g+Math.imul(ve,ot)|0,f=f+Math.imul(ve,st)|0,f=f+Math.imul(xe,ot)|0,v=v+Math.imul(xe,st)|0,g=g+Math.imul(te,at)|0,f=f+Math.imul(te,ut)|0,f=f+Math.imul(ae,at)|0,v=v+Math.imul(ae,ut)|0;var Fs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Fs>>>26)|0,Fs&=67108863,g=Math.imul(Ue,Ke),f=Math.imul(Ue,Je),f=f+Math.imul($e,Ke)|0,v=Math.imul($e,Je),g=g+Math.imul(qe,Xe)|0,f=f+Math.imul(qe,Ye)|0,f=f+Math.imul(Le,Xe)|0,v=v+Math.imul(Le,Ye)|0,g=g+Math.imul(je,Qe)|0,f=f+Math.imul(je,et)|0,f=f+Math.imul(Fe,Qe)|0,v=v+Math.imul(Fe,et)|0,g=g+Math.imul(Ne,tt)|0,f=f+Math.imul(Ne,rt)|0,f=f+Math.imul(Re,tt)|0,v=v+Math.imul(Re,rt)|0,g=g+Math.imul(De,nt)|0,f=f+Math.imul(De,it)|0,f=f+Math.imul(Be,nt)|0,v=v+Math.imul(Be,it)|0,g=g+Math.imul(Ae,ot)|0,f=f+Math.imul(Ae,st)|0,f=f+Math.imul(Me,ot)|0,v=v+Math.imul(Me,st)|0,g=g+Math.imul(ve,at)|0,f=f+Math.imul(ve,ut)|0,f=f+Math.imul(xe,at)|0,v=v+Math.imul(xe,ut)|0;var qs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(qs>>>26)|0,qs&=67108863,g=Math.imul(Ue,Xe),f=Math.imul(Ue,Ye),f=f+Math.imul($e,Xe)|0,v=Math.imul($e,Ye),g=g+Math.imul(qe,Qe)|0,f=f+Math.imul(qe,et)|0,f=f+Math.imul(Le,Qe)|0,v=v+Math.imul(Le,et)|0,g=g+Math.imul(je,tt)|0,f=f+Math.imul(je,rt)|0,f=f+Math.imul(Fe,tt)|0,v=v+Math.imul(Fe,rt)|0,g=g+Math.imul(Ne,nt)|0,f=f+Math.imul(Ne,it)|0,f=f+Math.imul(Re,nt)|0,v=v+Math.imul(Re,it)|0,g=g+Math.imul(De,ot)|0,f=f+Math.imul(De,st)|0,f=f+Math.imul(Be,ot)|0,v=v+Math.imul(Be,st)|0,g=g+Math.imul(Ae,at)|0,f=f+Math.imul(Ae,ut)|0,f=f+Math.imul(Me,at)|0,v=v+Math.imul(Me,ut)|0;var Ls=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Ls>>>26)|0,Ls&=67108863,g=Math.imul(Ue,Qe),f=Math.imul(Ue,et),f=f+Math.imul($e,Qe)|0,v=Math.imul($e,et),g=g+Math.imul(qe,tt)|0,f=f+Math.imul(qe,rt)|0,f=f+Math.imul(Le,tt)|0,v=v+Math.imul(Le,rt)|0,g=g+Math.imul(je,nt)|0,f=f+Math.imul(je,it)|0,f=f+Math.imul(Fe,nt)|0,v=v+Math.imul(Fe,it)|0,g=g+Math.imul(Ne,ot)|0,f=f+Math.imul(Ne,st)|0,f=f+Math.imul(Re,ot)|0,v=v+Math.imul(Re,st)|0,g=g+Math.imul(De,at)|0,f=f+Math.imul(De,ut)|0,f=f+Math.imul(Be,at)|0,v=v+Math.imul(Be,ut)|0;var Us=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Us>>>26)|0,Us&=67108863,g=Math.imul(Ue,tt),f=Math.imul(Ue,rt),f=f+Math.imul($e,tt)|0,v=Math.imul($e,rt),g=g+Math.imul(qe,nt)|0,f=f+Math.imul(qe,it)|0,f=f+Math.imul(Le,nt)|0,v=v+Math.imul(Le,it)|0,g=g+Math.imul(je,ot)|0,f=f+Math.imul(je,st)|0,f=f+Math.imul(Fe,ot)|0,v=v+Math.imul(Fe,st)|0,g=g+Math.imul(Ne,at)|0,f=f+Math.imul(Ne,ut)|0,f=f+Math.imul(Re,at)|0,v=v+Math.imul(Re,ut)|0;var $s=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+($s>>>26)|0,$s&=67108863,g=Math.imul(Ue,nt),f=Math.imul(Ue,it),f=f+Math.imul($e,nt)|0,v=Math.imul($e,it),g=g+Math.imul(qe,ot)|0,f=f+Math.imul(qe,st)|0,f=f+Math.imul(Le,ot)|0,v=v+Math.imul(Le,st)|0,g=g+Math.imul(je,at)|0,f=f+Math.imul(je,ut)|0,f=f+Math.imul(Fe,at)|0,v=v+Math.imul(Fe,ut)|0;var Gs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Gs>>>26)|0,Gs&=67108863,g=Math.imul(Ue,ot),f=Math.imul(Ue,st),f=f+Math.imul($e,ot)|0,v=Math.imul($e,st),g=g+Math.imul(qe,at)|0,f=f+Math.imul(qe,ut)|0,f=f+Math.imul(Le,at)|0,v=v+Math.imul(Le,ut)|0;var Vs=(w+g|0)+((f&8191)<<13)|0;w=(v+(f>>>13)|0)+(Vs>>>26)|0,Vs&=67108863,g=Math.imul(Ue,at),f=Math.imul(Ue,ut),f=f+Math.imul($e,at)|0,v=Math.imul($e,ut);var zs=(w+g|0)+((f&8191)<<13)|0;return w=(v+(f>>>13)|0)+(zs>>>26)|0,zs&=67108863,h[0]=Is,h[1]=Cs,h[2]=Os,h[3]=Ms,h[4]=Es,h[5]=Ps,h[6]=Ds,h[7]=Bs,h[8]=Ns,h[9]=Rs,h[10]=js,h[11]=Fs,h[12]=qs,h[13]=Ls,h[14]=Us,h[15]=$s,h[16]=Gs,h[17]=Vs,h[18]=zs,w!==0&&(h[19]=w,m.length++),m};Math.imul||(E=C);function P(k,a,c){c.negative=a.negative^k.negative,c.length=k.length+a.length;for(var m=0,y=0,p=0;p<c.length-1;p++){var h=y;y=0;for(var w=m&67108863,g=Math.min(p,a.length-1),f=Math.max(0,p-k.length+1);f<=g;f++){var v=p-f,O=k.words[v]|0,M=a.words[f]|0,R=O*M,B=R&67108863;h=h+(R/67108864|0)|0,B=B+w|0,w=B&67108863,h=h+(B>>>26)|0,y+=h>>>26,h&=67108863}c.words[p]=w,m=h,h=y}return m!==0?c.words[p]=m:c.length--,c._strip()}function D(k,a,c){return P(k,a,c)}i.prototype.mulTo=function(a,c){var m,y=this.length+a.length;return this.length===10&&a.length===10?m=E(this,a,c):y<63?m=C(this,a,c):y<1024?m=P(this,a,c):m=D(this,a,c),m};function L(k,a){this.x=k,this.y=a}L.prototype.makeRBT=function(a){for(var c=new Array(a),m=i.prototype._countBits(a)-1,y=0;y<a;y++)c[y]=this.revBin(y,m,a);return c},L.prototype.revBin=function(a,c,m){if(a===0||a===m-1)return a;for(var y=0,p=0;p<c;p++)y|=(a&1)<<c-p-1,a>>=1;return y},L.prototype.permute=function(a,c,m,y,p,h){for(var w=0;w<h;w++)y[w]=c[a[w]],p[w]=m[a[w]]},L.prototype.transform=function(a,c,m,y,p,h){this.permute(h,a,c,m,y,p);for(var w=1;w<p;w<<=1)for(var g=w<<1,f=Math.cos(2*Math.PI/g),v=Math.sin(2*Math.PI/g),O=0;O<p;O+=g)for(var M=f,R=v,B=0;B<w;B++){var G=m[O+B],Z=y[O+B],oe=m[O+B+w],te=y[O+B+w],ae=M*oe-R*te;te=M*te+R*oe,oe=ae,m[O+B]=G+oe,y[O+B]=Z+te,m[O+B+w]=G-oe,y[O+B+w]=Z-te,B!==g&&(ae=f*M-v*R,R=f*R+v*M,M=ae)}},L.prototype.guessLen13b=function(a,c){var m=Math.max(c,a)|1,y=m&1,p=0;for(m=m/2|0;m;m=m>>>1)p++;return 1<<p+1+y},L.prototype.conjugate=function(a,c,m){if(!(m<=1))for(var y=0;y<m/2;y++){var p=a[y];a[y]=a[m-y-1],a[m-y-1]=p,p=c[y],c[y]=-c[m-y-1],c[m-y-1]=-p}},L.prototype.normalize13b=function(a,c){for(var m=0,y=0;y<c/2;y++){var p=Math.round(a[2*y+1]/c)*8192+Math.round(a[2*y]/c)+m;a[y]=p&67108863,p<67108864?m=0:m=p/67108864|0}return a},L.prototype.convert13b=function(a,c,m,y){for(var p=0,h=0;h<c;h++)p=p+(a[h]|0),m[2*h]=p&8191,p=p>>>13,m[2*h+1]=p&8191,p=p>>>13;for(h=2*c;h<y;++h)m[h]=0;r(p===0),r((p&-8192)===0)},L.prototype.stub=function(a){for(var c=new Array(a),m=0;m<a;m++)c[m]=0;return c},L.prototype.mulp=function(a,c,m){var y=2*this.guessLen13b(a.length,c.length),p=this.makeRBT(y),h=this.stub(y),w=new Array(y),g=new Array(y),f=new Array(y),v=new Array(y),O=new Array(y),M=new Array(y),R=m.words;R.length=y,this.convert13b(a.words,a.length,w,y),this.convert13b(c.words,c.length,v,y),this.transform(w,h,g,f,y,p),this.transform(v,h,O,M,y,p);for(var B=0;B<y;B++){var G=g[B]*O[B]-f[B]*M[B];f[B]=g[B]*M[B]+f[B]*O[B],g[B]=G}return this.conjugate(g,f,y),this.transform(g,f,R,h,y,p),this.conjugate(R,h,y),this.normalize13b(R,y),m.negative=a.negative^c.negative,m.length=a.length+c.length,m._strip()},i.prototype.mul=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),this.mulTo(a,c)},i.prototype.mulf=function(a){var c=new i(null);return c.words=new Array(this.length+a.length),D(this,a,c)},i.prototype.imul=function(a){return this.clone().mulTo(a,this)},i.prototype.imuln=function(a){var c=a<0;c&&(a=-a),r(typeof a=="number"),r(a<67108864);for(var m=0,y=0;y<this.length;y++){var p=(this.words[y]|0)*a,h=(p&67108863)+(m&67108863);m>>=26,m+=p/67108864|0,m+=h>>>26,this.words[y]=h&67108863}return m!==0&&(this.words[y]=m,this.length++),c?this.ineg():this},i.prototype.muln=function(a){return this.clone().imuln(a)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(a){var c=I(a);if(c.length===0)return new i(1);for(var m=this,y=0;y<c.length&&c[y]===0;y++,m=m.sqr());if(++y<c.length)for(var p=m.sqr();y<c.length;y++,p=p.sqr())c[y]!==0&&(m=m.mul(p));return m},i.prototype.iushln=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=67108863>>>26-c<<26-c,p;if(c!==0){var h=0;for(p=0;p<this.length;p++){var w=this.words[p]&y,g=(this.words[p]|0)-w<<c;this.words[p]=g|h,h=w>>>26-c}h&&(this.words[p]=h,this.length++)}if(m!==0){for(p=this.length-1;p>=0;p--)this.words[p+m]=this.words[p];for(p=0;p<m;p++)this.words[p]=0;this.length+=m}return this._strip()},i.prototype.ishln=function(a){return r(this.negative===0),this.iushln(a)},i.prototype.iushrn=function(a,c,m){r(typeof a=="number"&&a>=0);var y;c?y=(c-c%26)/26:y=0;var p=a%26,h=Math.min((a-p)/26,this.length),w=67108863^67108863>>>p<<p,g=m;if(y-=h,y=Math.max(0,y),g){for(var f=0;f<h;f++)g.words[f]=this.words[f];g.length=h}if(h!==0)if(this.length>h)for(this.length-=h,f=0;f<this.length;f++)this.words[f]=this.words[f+h];else this.words[0]=0,this.length=1;var v=0;for(f=this.length-1;f>=0&&(v!==0||f>=y);f--){var O=this.words[f]|0;this.words[f]=v<<26-p|O>>>p,v=O&w}return g&&v!==0&&(g.words[g.length++]=v),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(a,c,m){return r(this.negative===0),this.iushrn(a,c,m)},i.prototype.shln=function(a){return this.clone().ishln(a)},i.prototype.ushln=function(a){return this.clone().iushln(a)},i.prototype.shrn=function(a){return this.clone().ishrn(a)},i.prototype.ushrn=function(a){return this.clone().iushrn(a)},i.prototype.testn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return!1;var p=this.words[m];return!!(p&y)},i.prototype.imaskn=function(a){r(typeof a=="number"&&a>=0);var c=a%26,m=(a-c)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=m)return this;if(c!==0&&m++,this.length=Math.min(m,this.length),c!==0){var y=67108863^67108863>>>c<<c;this.words[this.length-1]&=y}return this._strip()},i.prototype.maskn=function(a){return this.clone().imaskn(a)},i.prototype.iaddn=function(a){return r(typeof a=="number"),r(a<67108864),a<0?this.isubn(-a):this.negative!==0?this.length===1&&(this.words[0]|0)<=a?(this.words[0]=a-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(a),this.negative=1,this):this._iaddn(a)},i.prototype._iaddn=function(a){this.words[0]+=a;for(var c=0;c<this.length&&this.words[c]>=67108864;c++)this.words[c]-=67108864,c===this.length-1?this.words[c+1]=1:this.words[c+1]++;return this.length=Math.max(this.length,c+1),this},i.prototype.isubn=function(a){if(r(typeof a=="number"),r(a<67108864),a<0)return this.iaddn(-a);if(this.negative!==0)return this.negative=0,this.iaddn(a),this.negative=1,this;if(this.words[0]-=a,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var c=0;c<this.length&&this.words[c]<0;c++)this.words[c]+=67108864,this.words[c+1]-=1;return this._strip()},i.prototype.addn=function(a){return this.clone().iaddn(a)},i.prototype.subn=function(a){return this.clone().isubn(a)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(a,c,m){var y=a.length+m,p;this._expand(y);var h,w=0;for(p=0;p<a.length;p++){h=(this.words[p+m]|0)+w;var g=(a.words[p]|0)*c;h-=g&67108863,w=(h>>26)-(g/67108864|0),this.words[p+m]=h&67108863}for(;p<this.length-m;p++)h=(this.words[p+m]|0)+w,w=h>>26,this.words[p+m]=h&67108863;if(w===0)return this._strip();for(r(w===-1),w=0,p=0;p<this.length;p++)h=-(this.words[p]|0)+w,w=h>>26,this.words[p]=h&67108863;return this.negative=1,this._strip()},i.prototype._wordDiv=function(a,c){var m=this.length-a.length,y=this.clone(),p=a,h=p.words[p.length-1]|0,w=this._countBits(h);m=26-w,m!==0&&(p=p.ushln(m),y.iushln(m),h=p.words[p.length-1]|0);var g=y.length-p.length,f;if(c!=="mod"){f=new i(null),f.length=g+1,f.words=new Array(f.length);for(var v=0;v<f.length;v++)f.words[v]=0}var O=y.clone()._ishlnsubmul(p,1,g);O.negative===0&&(y=O,f&&(f.words[g]=1));for(var M=g-1;M>=0;M--){var R=(y.words[p.length+M]|0)*67108864+(y.words[p.length+M-1]|0);for(R=Math.min(R/h|0,67108863),y._ishlnsubmul(p,R,M);y.negative!==0;)R--,y.negative=0,y._ishlnsubmul(p,1,M),y.isZero()||(y.negative^=1);f&&(f.words[M]=R)}return f&&f._strip(),y._strip(),c!=="div"&&m!==0&&y.iushrn(m),{div:f||null,mod:y}},i.prototype.divmod=function(a,c,m){if(r(!a.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var y,p,h;return this.negative!==0&&a.negative===0?(h=this.neg().divmod(a,c),c!=="mod"&&(y=h.div.neg()),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.iadd(a)),{div:y,mod:p}):this.negative===0&&a.negative!==0?(h=this.divmod(a.neg(),c),c!=="mod"&&(y=h.div.neg()),{div:y,mod:h.mod}):this.negative&a.negative?(h=this.neg().divmod(a.neg(),c),c!=="div"&&(p=h.mod.neg(),m&&p.negative!==0&&p.isub(a)),{div:h.div,mod:p}):a.length>this.length||this.cmp(a)<0?{div:new i(0),mod:this}:a.length===1?c==="div"?{div:this.divn(a.words[0]),mod:null}:c==="mod"?{div:null,mod:new i(this.modrn(a.words[0]))}:{div:this.divn(a.words[0]),mod:new i(this.modrn(a.words[0]))}:this._wordDiv(a,c)},i.prototype.div=function(a){return this.divmod(a,"div",!1).div},i.prototype.mod=function(a){return this.divmod(a,"mod",!1).mod},i.prototype.umod=function(a){return this.divmod(a,"mod",!0).mod},i.prototype.divRound=function(a){var c=this.divmod(a);if(c.mod.isZero())return c.div;var m=c.div.negative!==0?c.mod.isub(a):c.mod,y=a.ushrn(1),p=a.andln(1),h=m.cmp(y);return h<0||p===1&&h===0?c.div:c.div.negative!==0?c.div.isubn(1):c.div.iaddn(1)},i.prototype.modrn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=(1<<26)%a,y=0,p=this.length-1;p>=0;p--)y=(m*y+(this.words[p]|0))%a;return c?-y:y},i.prototype.modn=function(a){return this.modrn(a)},i.prototype.idivn=function(a){var c=a<0;c&&(a=-a),r(a<=67108863);for(var m=0,y=this.length-1;y>=0;y--){var p=(this.words[y]|0)+m*67108864;this.words[y]=p/a|0,m=p%a}return this._strip(),c?this.ineg():this},i.prototype.divn=function(a){return this.clone().idivn(a)},i.prototype.egcd=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=new i(0),w=new i(1),g=0;c.isEven()&&m.isEven();)c.iushrn(1),m.iushrn(1),++g;for(var f=m.clone(),v=c.clone();!c.isZero();){for(var O=0,M=1;!(c.words[0]&M)&&O<26;++O,M<<=1);if(O>0)for(c.iushrn(O);O-- >0;)(y.isOdd()||p.isOdd())&&(y.iadd(f),p.isub(v)),y.iushrn(1),p.iushrn(1);for(var R=0,B=1;!(m.words[0]&B)&&R<26;++R,B<<=1);if(R>0)for(m.iushrn(R);R-- >0;)(h.isOdd()||w.isOdd())&&(h.iadd(f),w.isub(v)),h.iushrn(1),w.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(h),p.isub(w)):(m.isub(c),h.isub(y),w.isub(p))}return{a:h,b:w,gcd:m.iushln(g)}},i.prototype._invmp=function(a){r(a.negative===0),r(!a.isZero());var c=this,m=a.clone();c.negative!==0?c=c.umod(a):c=c.clone();for(var y=new i(1),p=new i(0),h=m.clone();c.cmpn(1)>0&&m.cmpn(1)>0;){for(var w=0,g=1;!(c.words[0]&g)&&w<26;++w,g<<=1);if(w>0)for(c.iushrn(w);w-- >0;)y.isOdd()&&y.iadd(h),y.iushrn(1);for(var f=0,v=1;!(m.words[0]&v)&&f<26;++f,v<<=1);if(f>0)for(m.iushrn(f);f-- >0;)p.isOdd()&&p.iadd(h),p.iushrn(1);c.cmp(m)>=0?(c.isub(m),y.isub(p)):(m.isub(c),p.isub(y))}var O;return c.cmpn(1)===0?O=y:O=p,O.cmpn(0)<0&&O.iadd(a),O},i.prototype.gcd=function(a){if(this.isZero())return a.abs();if(a.isZero())return this.abs();var c=this.clone(),m=a.clone();c.negative=0,m.negative=0;for(var y=0;c.isEven()&&m.isEven();y++)c.iushrn(1),m.iushrn(1);do{for(;c.isEven();)c.iushrn(1);for(;m.isEven();)m.iushrn(1);var p=c.cmp(m);if(p<0){var h=c;c=m,m=h}else if(p===0||m.cmpn(1)===0)break;c.isub(m)}while(!0);return m.iushln(y)},i.prototype.invm=function(a){return this.egcd(a).a.umod(a)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(a){return this.words[0]&a},i.prototype.bincn=function(a){r(typeof a=="number");var c=a%26,m=(a-c)/26,y=1<<c;if(this.length<=m)return this._expand(m+1),this.words[m]|=y,this;for(var p=y,h=m;p!==0&&h<this.length;h++){var w=this.words[h]|0;w+=p,p=w>>>26,w&=67108863,this.words[h]=w}return p!==0&&(this.words[h]=p,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(a){var c=a<0;if(this.negative!==0&&!c)return-1;if(this.negative===0&&c)return 1;this._strip();var m;if(this.length>1)m=1;else{c&&(a=-a),r(a<=67108863,"Number is too big");var y=this.words[0]|0;m=y===a?0:y<a?-1:1}return this.negative!==0?-m|0:m},i.prototype.cmp=function(a){if(this.negative!==0&&a.negative===0)return-1;if(this.negative===0&&a.negative!==0)return 1;var c=this.ucmp(a);return this.negative!==0?-c|0:c},i.prototype.ucmp=function(a){if(this.length>a.length)return 1;if(this.length<a.length)return-1;for(var c=0,m=this.length-1;m>=0;m--){var y=this.words[m]|0,p=a.words[m]|0;if(y!==p){y<p?c=-1:y>p&&(c=1);break}}return c},i.prototype.gtn=function(a){return this.cmpn(a)===1},i.prototype.gt=function(a){return this.cmp(a)===1},i.prototype.gten=function(a){return this.cmpn(a)>=0},i.prototype.gte=function(a){return this.cmp(a)>=0},i.prototype.ltn=function(a){return this.cmpn(a)===-1},i.prototype.lt=function(a){return this.cmp(a)===-1},i.prototype.lten=function(a){return this.cmpn(a)<=0},i.prototype.lte=function(a){return this.cmp(a)<=0},i.prototype.eqn=function(a){return this.cmpn(a)===0},i.prototype.eq=function(a){return this.cmp(a)===0},i.red=function(a){return new j(a)},i.prototype.toRed=function(a){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),a.convertTo(this)._forceRed(a)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(a){return this.red=a,this},i.prototype.forceRed=function(a){return r(!this.red,"Already a number in reduction context"),this._forceRed(a)},i.prototype.redAdd=function(a){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,a)},i.prototype.redIAdd=function(a){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,a)},i.prototype.redSub=function(a){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,a)},i.prototype.redISub=function(a){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,a)},i.prototype.redShl=function(a){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,a)},i.prototype.redMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.mul(this,a)},i.prototype.redIMul=function(a){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.imul(this,a)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(a){return r(this.red&&!a.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,a)};var H={k256:null,p224:null,p192:null,p25519:null};function W(k,a){this.name=k,this.p=new i(a,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}W.prototype._tmp=function(){var a=new i(null);return a.words=new Array(Math.ceil(this.n/13)),a},W.prototype.ireduce=function(a){var c=a,m;do this.split(c,this.tmp),c=this.imulK(c),c=c.iadd(this.tmp),m=c.bitLength();while(m>this.n);var y=m<this.n?-1:c.ucmp(this.p);return y===0?(c.words[0]=0,c.length=1):y>0?c.isub(this.p):c.strip!==void 0?c.strip():c._strip(),c},W.prototype.split=function(a,c){a.iushrn(this.n,0,c)},W.prototype.imulK=function(a){return a.imul(this.k)};function K(){W.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(K,W),K.prototype.split=function(a,c){for(var m=4194303,y=Math.min(a.length,9),p=0;p<y;p++)c.words[p]=a.words[p];if(c.length=y,a.length<=9){a.words[0]=0,a.length=1;return}var h=a.words[9];for(c.words[c.length++]=h&m,p=10;p<a.length;p++){var w=a.words[p]|0;a.words[p-10]=(w&m)<<4|h>>>22,h=w}h>>>=22,a.words[p-10]=h,h===0&&a.length>10?a.length-=10:a.length-=9},K.prototype.imulK=function(a){a.words[a.length]=0,a.words[a.length+1]=0,a.length+=2;for(var c=0,m=0;m<a.length;m++){var y=a.words[m]|0;c+=y*977,a.words[m]=c&67108863,c=y*64+(c/67108864|0)}return a.words[a.length-1]===0&&(a.length--,a.words[a.length-1]===0&&a.length--),a};function F(){W.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(F,W);function U(){W.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(U,W);function N(){W.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(N,W),N.prototype.imulK=function(a){for(var c=0,m=0;m<a.length;m++){var y=(a.words[m]|0)*19+c,p=y&67108863;y>>>=26,a.words[m]=p,c=y}return c!==0&&(a.words[a.length++]=c),a},i._prime=function(a){if(H[a])return H[a];var c;if(a==="k256")c=new K;else if(a==="p224")c=new F;else if(a==="p192")c=new U;else if(a==="p25519")c=new N;else throw new Error("Unknown prime "+a);return H[a]=c,c};function j(k){if(typeof k=="string"){var a=i._prime(k);this.m=a.p,this.prime=a}else r(k.gtn(1),"modulus must be greater than 1"),this.m=k,this.prime=null}j.prototype._verify1=function(a){r(a.negative===0,"red works only with positives"),r(a.red,"red works only with red numbers")},j.prototype._verify2=function(a,c){r((a.negative|c.negative)===0,"red works only with positives"),r(a.red&&a.red===c.red,"red works only with red numbers")},j.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(d(a,a.umod(this.m)._forceRed(this)),a)},j.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},j.prototype.add=function(a,c){this._verify2(a,c);var m=a.add(c);return m.cmp(this.m)>=0&&m.isub(this.m),m._forceRed(this)},j.prototype.iadd=function(a,c){this._verify2(a,c);var m=a.iadd(c);return m.cmp(this.m)>=0&&m.isub(this.m),m},j.prototype.sub=function(a,c){this._verify2(a,c);var m=a.sub(c);return m.cmpn(0)<0&&m.iadd(this.m),m._forceRed(this)},j.prototype.isub=function(a,c){this._verify2(a,c);var m=a.isub(c);return m.cmpn(0)<0&&m.iadd(this.m),m},j.prototype.shl=function(a,c){return this._verify1(a),this.imod(a.ushln(c))},j.prototype.imul=function(a,c){return this._verify2(a,c),this.imod(a.imul(c))},j.prototype.mul=function(a,c){return this._verify2(a,c),this.imod(a.mul(c))},j.prototype.isqr=function(a){return this.imul(a,a.clone())},j.prototype.sqr=function(a){return this.mul(a,a)},j.prototype.sqrt=function(a){if(a.isZero())return a.clone();var c=this.m.andln(3);if(r(c%2===1),c===3){var m=this.m.add(new i(1)).iushrn(2);return this.pow(a,m)}for(var y=this.m.subn(1),p=0;!y.isZero()&&y.andln(1)===0;)p++,y.iushrn(1);r(!y.isZero());var h=new i(1).toRed(this),w=h.redNeg(),g=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);this.pow(f,g).cmp(w)!==0;)f.redIAdd(w);for(var v=this.pow(f,y),O=this.pow(a,y.addn(1).iushrn(1)),M=this.pow(a,y),R=p;M.cmp(h)!==0;){for(var B=M,G=0;B.cmp(h)!==0;G++)B=B.redSqr();r(G<R);var Z=this.pow(v,new i(1).iushln(R-G-1));O=O.redMul(Z),v=Z.redSqr(),M=M.redMul(v),R=G}return O},j.prototype.invm=function(a){var c=a._invmp(this.m);return c.negative!==0?(c.negative=0,this.imod(c).redNeg()):this.imod(c)},j.prototype.pow=function(a,c){if(c.isZero())return new i(1).toRed(this);if(c.cmpn(1)===0)return a.clone();var m=4,y=new Array(1<<m);y[0]=new i(1).toRed(this),y[1]=a;for(var p=2;p<y.length;p++)y[p]=this.mul(y[p-1],a);var h=y[0],w=0,g=0,f=c.bitLength()%26;for(f===0&&(f=26),p=c.length-1;p>=0;p--){for(var v=c.words[p],O=f-1;O>=0;O--){var M=v>>O&1;if(h!==y[0]&&(h=this.sqr(h)),M===0&&w===0){g=0;continue}w<<=1,w|=M,g++,!(g!==m&&(p!==0||O!==0))&&(h=this.mul(h,y[w]),g=0,w=0)}f=26}return h},j.prototype.convertTo=function(a){var c=a.umod(this.m);return c===a?c.clone():c},j.prototype.convertFrom=function(a){var c=a.clone();return c.red=null,c},i.mont=function(a){return new S(a)};function S(k){j.call(this,k),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(S,j),S.prototype.convertTo=function(a){return this.imod(a.ushln(this.shift))},S.prototype.convertFrom=function(a){var c=this.imod(a.mul(this.rinv));return c.red=null,c},S.prototype.imul=function(a,c){if(a.isZero()||c.isZero())return a.words[0]=0,a.length=1,a;var m=a.imul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.mul=function(a,c){if(a.isZero()||c.isZero())return new i(0)._forceRed(this);var m=a.mul(c),y=m.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),p=m.isub(y).iushrn(this.shift),h=p;return p.cmp(this.m)>=0?h=p.isub(this.m):p.cmpn(0)<0&&(h=p.iadd(this.m)),h._forceRed(this)},S.prototype.invm=function(a){var c=this.imod(a._invmp(this.m).mul(this.r2));return c._forceRed(this)}})(typeof Zs>"u"||Zs,Ic)});var ll={};fc(ll,{__addDisposableResource:()=>ul,__assign:()=>eo,__asyncDelegator:()=>el,__asyncGenerator:()=>Qc,__asyncValues:()=>tl,__await:()=>fn,__awaiter:()=>Hc,__classPrivateFieldGet:()=>ol,__classPrivateFieldIn:()=>al,__classPrivateFieldSet:()=>sl,__createBinding:()=>ro,__decorate:()=>Vc,__disposeResources:()=>cl,__esDecorate:()=>ng,__exportStar:()=>Kc,__extends:()=>$c,__generator:()=>Zc,__importDefault:()=>il,__importStar:()=>nl,__makeTemplateObject:()=>rl,__metadata:()=>Wc,__param:()=>zc,__propKey:()=>og,__read:()=>ia,__rest:()=>Gc,__runInitializers:()=>ig,__setFunctionName:()=>sg,__spread:()=>Jc,__spreadArray:()=>Yc,__spreadArrays:()=>Xc,__values:()=>to,default:()=>cg});function $c(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");na(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Gc(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Vc(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var u=t.length-1;u>=0;u--)(s=t[u])&&(o=(i<3?s(o):i>3?s(e,r,o):s(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function zc(t,e){return function(r,n){e(r,n,t)}}function ng(t,e,r,n,i,o){function s(E){if(E!==void 0&&typeof E!="function")throw new TypeError("Function expected");return E}for(var u=n.kind,l=u==="getter"?"get":u==="setter"?"set":"value",d=!e&&t?n.static?t:t.prototype:null,b=e||(d?Object.getOwnPropertyDescriptor(d,n.name):{}),_,T=!1,x=r.length-1;x>=0;x--){var A={};for(var I in n)A[I]=I==="access"?{}:n[I];for(var I in n.access)A.access[I]=n.access[I];A.addInitializer=function(E){if(T)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(E||null))};var C=(0,r[x])(u==="accessor"?{get:b.get,set:b.set}:b[l],A);if(u==="accessor"){if(C===void 0)continue;if(C===null||typeof C!="object")throw new TypeError("Object expected");(_=s(C.get))&&(b.get=_),(_=s(C.set))&&(b.set=_),(_=s(C.init))&&i.unshift(_)}else(_=s(C))&&(u==="field"?i.unshift(_):b[l]=_)}d&&Object.defineProperty(d,n.name,b),T=!0}function ig(t,e,r){for(var n=arguments.length>2,i=0;i<e.length;i++)r=n?e[i].call(t,r):e[i].call(t);return n?r:void 0}function og(t){return typeof t=="symbol"?t:"".concat(t)}function sg(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function Wc(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Hc(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function u(b){try{d(n.next(b))}catch(_){s(_)}}function l(b){try{d(n.throw(b))}catch(_){s(_)}}function d(b){b.done?o(b.value):i(b.value).then(u,l)}d((n=n.apply(t,e||[])).next())})}function Zc(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(d){return function(b){return l([d,b])}}function l(d){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(r=0)),r;)try{if(n=1,i&&(o=d[0]&2?i.return:d[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,d[1])).done)return o;switch(i=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,i=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){r.label=d[1];break}if(d[0]===6&&r.label<o[1]){r.label=o[1],o=d;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(d);break}o[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(b){d=[6,b],i=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function Kc(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ro(e,t,r)}function to(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ia(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function Jc(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ia(arguments[e]));return t}function Xc(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],s=0,u=o.length;s<u;s++,i++)n[i]=o[s];return n}function Yc(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}function fn(t){return this instanceof fn?(this.v=t,this):new fn(t)}function Qc(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(T){n[T]&&(i[T]=function(x){return new Promise(function(A,I){o.push([T,x,A,I])>1||u(T,x)})})}function u(T,x){try{l(n[T](x))}catch(A){_(o[0][3],A)}}function l(T){T.value instanceof fn?Promise.resolve(T.value.v).then(d,b):_(o[0][2],T)}function d(T){u("next",T)}function b(T){u("throw",T)}function _(T,x){T(x),o.shift(),o.length&&u(o[0][0],o[0][1])}}function el(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(s){return(r=!r)?{value:fn(t[i](s)),done:!1}:o?o(s):s}:o}}function tl(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof to=="function"?to(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(u,l){s=t[o](s),i(u,l,s.done,s.value)})}}function i(o,s,u,l){Promise.resolve(l).then(function(d){o({value:d,done:u})},s)}}function rl(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function nl(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ro(e,t,r);return ag(e,t),e}function il(t){return t&&t.__esModule?t:{default:t}}function ol(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function sl(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function al(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function ul(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function cl(t){function e(n){t.error=t.hasError?new ug(n,t.error,"An error was suppressed during disposal."):n,t.hasError=!0}function r(){for(;t.stack.length;){var n=t.stack.pop();try{var i=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(i).then(r,function(o){return e(o),r()})}catch(o){e(o)}}if(t.hasError)throw t.error}return r()}var na,eo,ro,ag,ug,cg,dl=Yp(()=>{"use strict";na=function(t,e){return na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},na(t,e)};eo=function(){return eo=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},eo.apply(this,arguments)};ro=Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]};ag=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};ug=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};cg={__extends:$c,__assign:eo,__rest:Gc,__decorate:Vc,__param:zc,__metadata:Wc,__awaiter:Hc,__generator:Zc,__createBinding:ro,__exportStar:Kc,__values:to,__read:ia,__spread:Jc,__spreadArrays:Xc,__spreadArray:Yc,__await:fn,__asyncGenerator:Qc,__asyncDelegator:el,__asyncValues:tl,__makeTemplateObject:rl,__importStar:nl,__importDefault:il,__classPrivateFieldGet:ol,__classPrivateFieldSet:sl,__classPrivateFieldIn:al,__addDisposableResource:ul,__disposeResources:cl}});var hl=Fr((no,fl)=>{"use strict";(function(t,e){typeof no=="object"&&typeof fl<"u"?e(no,(dl(),pc(ll))):typeof define=="function"&&define.amd?define(["exports","tslib"],e):e(t.ssGraph={},t.tslib)})(no,function(t,e){"use strict";var r=function(){function p(h,w,g){g===void 0&&(g=0),this.startVertex=h,this.endVertex=w,this.weight=g}return p.prototype.getKey=function(){var h=this.startVertex.getKey(),w=this.endVertex.getKey();return h+"_"+w},p.prototype.reverse=function(){var h=this.startVertex;return this.startVertex=this.endVertex,this.endVertex=h,this},p.prototype.clone=function(){return new p(this.startVertex,this.endVertex,this.weight)},p.prototype.toString=function(){return this.getKey()},p}();function n(p,h,w){if(w===void 0&&(w="cc-graph"),!p)throw new Error((w?"["+w+"]":"")+" Invariant failed: "+h)}function i(p,h){h===void 0&&(h=!0);var w=typeof p<"u"&&p!==null;return h?w&&p!=="undefined"&&p!=="null":w}var o=function(){function p(h){n(i(h),"Graph vertex must have a value"),this.value=h,this.edges=new Map}return p.prototype.addEdge=function(h){return this.edges.set(h.getKey(),h),this},p.prototype.deleteEdge=function(h){this.edges.delete(h.getKey())},p.prototype.getNeighbors=function(){var h=this,w=this.getEdges(),g=function(f){return f.startVertex===h?f.endVertex:f.startVertex};return w.map(g)},p.prototype.getEdges=function(){return Array.from(this.edges.values())},p.prototype.getDegree=function(){return this.getEdges().length},p.prototype.hasEdge=function(h){var w=this.getEdges().find(function(g){return g===h});return!!w},p.prototype.hasNeighbor=function(h){var w=this.getEdges().find(function(g){return g.startVertex===h||g.endVertex===h});return!!w},p.prototype.findEdge=function(h){var w=function(f){return f.startVertex===h||f.endVertex===h},g=this.getEdges().find(w);return g||null},p.prototype.getKey=function(){return this.value},p.prototype.deleteAllEdges=function(){var h=this;return this.getEdges().forEach(function(w){return h.deleteEdge(w)}),this},p.prototype.toString=function(h){return h?h(this.value):""+this.value},p}(),s;(function(p){p[p.EQUAL=0]="EQUAL",p[p.GREATER=1]="GREATER",p[p.LESS=-1]="LESS"})(s||(s={}));var u=function(){function p(h){this.compare=h||p.defaultCompareFunction}return p.defaultCompareFunction=function(h,w){return h===w?s.EQUAL:h<w?s.LESS:s.GREATER},p.prototype.equal=function(h,w){return this.compare(h,w)===s.EQUAL},p.prototype.lessThan=function(h,w){return this.compare(h,w)===s.LESS},p.prototype.greaterThan=function(h,w){return this.compare(h,w)===s.GREATER},p.prototype.lessThanOrEqual=function(h,w){return this.lessThan(h,w)||this.equal(h,w)},p.prototype.greaterThanOrEqual=function(h,w){return this.greaterThan(h,w)||this.equal(h,w)},p.prototype.reverse=function(){var h=this.compare;this.compare=function(w,g){return h(g,w)}},p}(),l=function(){function p(h){this.value=h,this.next=null}return p}(),d=function(){function p(h){this.value=h,this.next=null,this.prev=null}return p}();var b=function(p,h){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,g){w.__proto__=g}||function(w,g){for(var f in g)g.hasOwnProperty(f)&&(w[f]=g[f])},b(p,h)};function _(p,h){b(p,h);function w(){this.constructor=p}p.prototype=h===null?Object.create(h):(w.prototype=h.prototype,new w)}function T(p,h){var w={label:0,sent:function(){if(v[0]&1)throw v[1];return v[1]},trys:[],ops:[]},g,f,v,O;return O={next:M(0),throw:M(1),return:M(2)},typeof Symbol=="function"&&(O[Symbol.iterator]=function(){return this}),O;function M(B){return function(G){return R([B,G])}}function R(B){if(g)throw new TypeError("Generator is already executing.");for(;w;)try{if(g=1,f&&(v=B[0]&2?f.return:B[0]?f.throw||((v=f.return)&&v.call(f),0):f.next)&&!(v=v.call(f,B[1])).done)return v;switch(f=0,v&&(B=[B[0]&2,v.value]),B[0]){case 0:case 1:v=B;break;case 4:return w.label++,{value:B[1],done:!1};case 5:w.label++,f=B[1],B=[0];continue;case 7:B=w.ops.pop(),w.trys.pop();continue;default:if(v=w.trys,!(v=v.length>0&&v[v.length-1])&&(B[0]===6||B[0]===2)){w=0;continue}if(B[0]===3&&(!v||B[1]>v[0]&&B[1]<v[3])){w.label=B[1];break}if(B[0]===6&&w.label<v[1]){w.label=v[1],v=B;break}if(v&&w.label<v[2]){w.label=v[2],w.ops.push(B);break}v[2]&&w.ops.pop(),w.trys.pop();continue}B=h.call(p,w)}catch(G){B=[6,G],f=0}finally{g=v=0}if(B[0]&5)throw B[1];return{value:B[0]?B[1]:void 0,done:!0}}}function x(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function A(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(x(arguments[h]));return p}var I="obfuse error occur";function C(p,h){if(!p)throw new Error("[linked-list] "+(h||I))}var E=-1,P=function(){function p(){for(var h=this,w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];this._head=null,this._tail=null,this._length=0,this.compare=new u,w.length>0&&w.forEach(function(f){h.append(f)})}return Object.defineProperty(p.prototype,"head",{get:function(){return this._head?this._head.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"tail",{get:function(){return this._tail?this._tail.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"loopLength",{get:function(){var h=!1,w=1;if(!this._head)return 0;for(var g=this._head,f=this._head;f.next&&f.next.next;)if(f=f.next.next,g=g.next,g===f){h=!0;break}if(h){for(f=f.next;g!==f;)w++,f=f.next;return w}else return 0},enumerable:!0,configurable:!0}),p.prototype.getNode=function(h){var w=this._length;C(w>0&&h>=0&&h<w,"[linked-list] index "+h+" out of scope of list, which length is "+w);for(var g=this._head,f=0;f<h;)g=g.next,f++;return g},p.prototype.get=function(h){var w=this.getNode(h);return w?w.value:null},p.prototype.find=function(h){var w=h.value,g=h.callback;if(!this._head)return null;for(var f=this._head;f;){if(g&&g(f.value)||w!==void 0&&this.compare.equal(f.value,w))return f;f=f.next}return null},p.prototype.indexOf=function(h){if(!this._head)return E;for(var w=this._head,g=-1;w.next;){if(g++,this.compare.equal(w.value,h))return g;w=w.next}return w===this._tail&&this.compare.equal(w.value,h)&&(g+=1),g},p.prototype.first=function(h){C(h>=0,"[linked-list] param 'num' ("+h+") should not less than 0");for(var w=this.iterator(),g=[],f=Math.min(h,this.length),v=0;v<f;v++){var O=w.next();g.push(O.value)}return g},p.prototype.toArray=function(){return A(this)},p.prototype.isEmpty=function(){return this._head===null},p.prototype.iterator=function(){var h;return T(this,function(w){switch(w.label){case 0:h=this._head,w.label=1;case 1:return h?[4,h.value]:[3,3];case 2:return w.sent(),h=h.next,[3,1];case 3:return[2]}})},p.prototype[Symbol.iterator]=function(){return this.iterator()},p}(),D=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new l(w);return this._tail?(this._tail.next=g,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new l(w);return this._head?(g.next=this._head,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,g.next=null):this._head=this._tail=null,this._length--,w;for(var f=g;;){if(this.compare.equal(g.value,w))return g.next?f.next=g.next:(this._tail=f,this._tail.next=null),g.next=null,this._length--,w;if(g.next)f=g,g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w){if(!this._head.next)this._head=null,this._tail=null;else{for(var g=this._head;g.next!==w;)g=g.next;g.next=null,this._tail=g}return this._length--,w.value}},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),L=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(D),H=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._tail.next===this._head&&(this._tail.next=null)},h.prototype.cyclization=function(){this._tail&&this._tail.next===null&&(this._tail.next=this._head)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(L),W=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];return p.apply(this,A(w))||this}return h.prototype.append=function(w){var g=new d(w);return this._tail?(this._tail.next=g,g.prev=this._tail,this._tail=g):this._head=this._tail=g,this._length++,!0},h.prototype.prepend=function(w){var g=new d(w);return this._head?(g.next=this._head,this._head.prev=g,this._head=g):this._head=this._tail=g,this._length++,!0},h.prototype.remove=function(w){var g=this._head;if(g){if(this.compare.equal(g.value,w))return g.next?(this._head=g.next,this._head.prev=null,g.next=g.prev=null):this._head=this._tail=null,this._length--,w;for(;;){if(this.compare.equal(g.value,w))return g.next?(g.prev.next=g.next,g.next.prev=g.prev,g.next=g.prev=null):(g.prev.next=null,this._tail=g.prev,g.next=g.prev=null),this._length--,g.value;if(g.next)g=g.next;else return}}},h.prototype.removeHead=function(){var w=this._head;if(w)return this._head.next?(w.next.prev=null,this._head=w.next,w.next=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.removeTail=function(){var w=this._tail;if(w)return this._head.next?(w.prev.next=null,this._tail=w.prev,w.next=w.prev=null):(this._head=null,this._tail=null),this._length--,w.value},h.prototype.reverse=function(){if(this._head){var w=this._head,g=null,f;for(this._tail=this._head;w!==null;)f=w.next,w.next=g,w.prev=f,g=w,w=f;this._head=g}},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(P),K=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.iterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,w===this._head&&(w=null),[3,1];case 3:return[2]}})},h.prototype.circleIterator=function(){var w;return T(this,function(g){switch(g.label){case 0:w=this._head,g.label=1;case 1:return w?[4,w.value]:[3,3];case 2:return g.sent(),w=w.next,[3,1];case 3:return[2]}})},h.prototype[Symbol.iterator]=function(){return this.iterator()},h.prototype.mapToNormalListFn=function(w){for(var g=[],f=1;f<arguments.length;f++)g[f-1]=arguments[f];this.breakCircle();var v=p.prototype[w].apply(this,g);return this.cyclization(),v},h.prototype.getNode=function(w){return this.mapToNormalListFn("getNode",w)},h.prototype.append=function(w){return this.mapToNormalListFn("append",w)},h.prototype.prepend=function(w){return this.mapToNormalListFn("prepend",w)},h.prototype.find=function(w){return this.mapToNormalListFn("find",w)},h.prototype.indexOf=function(w){return this.mapToNormalListFn("indexOf",w)},h.prototype.remove=function(w){return this.mapToNormalListFn("remove",w)},h.prototype.removeHead=function(){return this.mapToNormalListFn("removeHead")},h.prototype.removeTail=function(){return this.mapToNormalListFn("removeTail")},h.prototype.first=function(w){C(w>=0,"[linked-list] param 'num' ("+w+") should not less than 0");for(var g=this.circleIterator(),f=[],v=0;v<w;v++){var O=g.next();f.push(O.value)}return f},h.prototype.toArray=function(){return this.mapToNormalListFn("toArray")},h.prototype.reverse=function(){return this.mapToNormalListFn("reverse")},h}(W),F=function(p){_(h,p);function h(){for(var w=[],g=0;g<arguments.length;g++)w[g]=arguments[g];var f=p.apply(this,A(w))||this;return f.cyclization(),f}return h.prototype.breakCircle=function(){this._tail&&this._head&&this._tail.next===this._head&&(this._tail.next=null,this._head.prev=null)},h.prototype.cyclization=function(){this._head&&this._tail&&this._tail.next===null&&(this._tail.next=this._head,this._head.prev=this._tail)},h.prototype.clone=function(){var w=this.toArray();return new(h.bind.apply(h,A([void 0],w)))},h}(K);function U(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function N(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(U(arguments[h]));return p}var j=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.queue=new(D.bind.apply(D,N([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.queue.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.queue.head},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.queue.isEmpty()},p.prototype.enqueue=function(h){return this.queue.append(h)},p.prototype.dequeue=function(){var h=this.queue.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.queue.toArray()},p}();function S(p,h){var w=typeof Symbol=="function"&&p[Symbol.iterator];if(!w)return p;var g=w.call(p),f,v=[],O;try{for(;(h===void 0||h-- >0)&&!(f=g.next()).done;)v.push(f.value)}catch(M){O={error:M}}finally{try{f&&!f.done&&(w=g.return)&&w.call(g)}finally{if(O)throw O.error}}return v}function k(){for(var p=[],h=0;h<arguments.length;h++)p=p.concat(S(arguments[h]));return p}var a=function(){function p(){for(var h=[],w=0;w<arguments.length;w++)h[w]=arguments[w];this.stack=new(D.bind.apply(D,k([void 0],h)))}return Object.defineProperty(p.prototype,"length",{get:function(){return this.stack.length},enumerable:!0,configurable:!0}),Object.defineProperty(p.prototype,"peek",{get:function(){return this.stack.tail},enumerable:!0,configurable:!0}),p.prototype.isEmpty=function(){return this.stack.isEmpty()},p.prototype.push=function(h){return this.stack.append(h)},p.prototype.pop=function(){var h=this.stack.removeTail();return typeof h<"u"?h:void 0},p.prototype.popBottom=function(){var h=this.stack.removeHead();return typeof h<"u"?h:void 0},p.prototype.toArray=function(){return this.stack.toArray()},p}();function c(p,h,w,g){if(p){h.push(p),g.set(p.getKey(),!0);var f=p.getNeighbors().filter(function(v){return!g.get(v.getKey())});w.push(f)}}function m(p,h,w){var g=p.pop();g&&w.set(g.getKey(),!1),h.pop()}var y=function(){function p(h){h===void 0&&(h=!1),this.vertices={},this.edges={},this.isDirected=h}return p.prototype.addVertex=function(h){return this.vertices[h.getKey()]=h,this},p.prototype.getVertexByKey=function(h){return this.vertices[h]},p.prototype.getNeighbors=function(h){return h.getNeighbors()},p.prototype.getAllVertices=function(){return Object.values(this.vertices)},p.prototype.getAllEdges=function(){return Object.values(this.edges)},p.prototype.addEdge=function(h,w){if(w===void 0&&(w=!1),this.edges[h.getKey()]){if(w)return this;n(!1,"Edge has already been added before")}var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());if(g||(this.addVertex(h.startVertex),g=this.getVertexByKey(h.startVertex.getKey())),f||(this.addVertex(h.endVertex),f=this.getVertexByKey(h.endVertex.getKey())),this.edges[h.getKey()]=h,this.isDirected)g.addEdge(h);else{g.addEdge(h);var v=h.clone();f.addEdge(v.reverse())}return this},p.prototype.deleteEdge=function(h,w){if(w===void 0&&(w=!1),!this.edges[h.getKey()]){if(w)return this;n(!1,"Edge not found in graph")}delete this.edges[h.getKey()];var g=this.getVertexByKey(h.startVertex.getKey()),f=this.getVertexByKey(h.endVertex.getKey());return g.deleteEdge(h),f.deleteEdge(h),this},p.prototype.findEdge=function(h,w){var g=this.getVertexByKey(h.getKey());return g?g.findEdge(w):null},p.prototype.getWeight=function(){return this.getAllEdges().reduce(function(h,w){return h+w.weight},0)},p.prototype.reverse=function(){var h=this;return this.getAllEdges().forEach(function(w){h.deleteEdge(w),w.reverse(),h.addEdge(w)}),this},p.prototype.getVerticesIndices=function(){var h={};return this.getAllVertices().forEach(function(w,g){h[w.getKey()]=g}),h},p.prototype.getAdjacencyMatrix=function(){var h=this,w=this.getAllVertices(),g=this.getVerticesIndices(),f=Array(w.length).fill(null).map(function(){return Array(w.length).fill(1/0)});return w.forEach(function(v,O){v.getNeighbors().forEach(function(M){var R=g[M.getKey()],B=h.findEdge(v,M);B&&(f[O][R]=B.weight)})}),f},p.prototype.toString=function(){return Object.keys(this.vertices).toString()},p.prototype.bfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new j,g.enqueue(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.dequeue(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.enqueue(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.dfs=function(h){var w,g,f;return e.__generator(this,function(v){switch(v.label){case 0:w=new Map,g=new a,g.push(h),v.label=1;case 1:return g.isEmpty()?[3,4]:(f=g.pop(),f&&!w.has(f.getKey())?[4,f]:[3,3]);case 2:v.sent(),w.set(f.getKey(),f),f.getNeighbors().forEach(function(O){return g.push(O)}),v.label=3;case 3:return[3,1];case 4:return[2]}})},p.prototype.findAllPath=function(h,w){var g,f,v,O,M,R,B;return e.__generator(this,function(G){switch(G.label){case 0:return g=[],h!==w?[3,2]:(g.push(h),[4,g]);case 1:return G.sent(),[2];case 2:f=new Map,v=new a,O=new a,c(h,v,O,f),G.label=3;case 3:if(v.isEmpty())return[3,6];if(M=O.pop(),M&&M.length)R=M.shift(),O.push(M),R&&c(R,v,O,f);else return O.push(M),m(v,O,f),[3,3];return B=v.peek,B!==w?[3,5]:[4,v.toArray()];case 4:G.sent(),m(v,O,f),G.label=5;case 5:return[3,3];case 6:return[2]}})},p}();t.GraphEdge=r,t.GraphVertex=o,t.Graph=y,Object.defineProperty(t,"__esModule",{value:!0})})});var If=Fr((hu,pu)=>{"use strict";(function(t,e){typeof hu=="object"&&typeof pu<"u"?pu.exports=e():typeof define=="function"&&define.amd?define(e):(t=t||self,t.JSBI=e())})(hu,function(){"use strict";var t=Math.imul,e=Math.clz32;function r(F){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U},r(F)}function n(F,U){if(!(F instanceof U))throw new TypeError("Cannot call a class as a function")}function i(F,U){for(var N,j=0;j<U.length;j++)N=U[j],N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(F,N.key,N)}function o(F,U,N){return U&&i(F.prototype,U),N&&i(F,N),Object.defineProperty(F,"prototype",{writable:!1}),F}function s(F,U){if(typeof U!="function"&&U!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(U&&U.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),U&&l(F,U)}function u(F){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(U){return U.__proto__||Object.getPrototypeOf(U)},u(F)}function l(F,U){return l=Object.setPrototypeOf||function(N,j){return N.__proto__=j,N},l(F,U)}function d(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function b(){return b=d()?Reflect.construct:function(F,U,N){var j=[null];j.push.apply(j,U);var S=Function.bind.apply(F,j),k=new S;return N&&l(k,N.prototype),k},b.apply(null,arguments)}function _(F){return Function.toString.call(F).indexOf("[native code]")!==-1}function T(F){var U=typeof Map=="function"?new Map:void 0;return T=function(N){function j(){return b(N,arguments,u(this).constructor)}if(N===null||!_(N))return N;if(typeof N!="function")throw new TypeError("Super expression must either be null or a function");if(typeof U<"u"){if(U.has(N))return U.get(N);U.set(N,j)}return j.prototype=Object.create(N.prototype,{constructor:{value:j,enumerable:!1,writable:!0,configurable:!0}}),l(j,N)},T(F)}function x(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}function A(F,U){if(U&&(typeof U=="object"||typeof U=="function"))return U;if(U!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return x(F)}function I(F){var U=d();return function(){var N,j=u(F);if(U){var S=u(this).constructor;N=Reflect.construct(j,arguments,S)}else N=j.apply(this,arguments);return A(this,N)}}function C(F,U){return E(F)||P(F,U)||D(F,U)||H()}function E(F){if(Array.isArray(F))return F}function P(F,U){var N=F==null?null:typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(N!=null){var j,S,k=[],a=!0,c=!1;try{for(N=N.call(F);!(a=(j=N.next()).done)&&(k.push(j.value),!(U&&k.length===U));a=!0);}catch(m){c=!0,S=m}finally{try{a||N.return==null||N.return()}finally{if(c)throw S}}return k}}function D(F,U){if(F){if(typeof F=="string")return L(F,U);var N=Object.prototype.toString.call(F).slice(8,-1);return N==="Object"&&F.constructor&&(N=F.constructor.name),N==="Map"||N==="Set"?Array.from(F):N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N)?L(F,U):void 0}}function L(F,U){(U==null||U>F.length)&&(U=F.length);for(var N=0,j=Array(U);N<U;N++)j[N]=F[N];return j}function H(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function W(F,U){var N=typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(!N){if(Array.isArray(F)||(N=D(F))||U&&F&&typeof F.length=="number"){N&&(F=N);var j=0,S=function(){};return{s:S,n:function(){return j>=F.length?{done:!0}:{done:!1,value:F[j++]}},e:function(m){throw m},f:S}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
3
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var k,a=!0,c=!1;return{s:function(){N=N.call(F)},n:function(){var m=N.next();return a=m.done,m},e:function(m){c=!0,k=m},f:function(){try{a||N.return==null||N.return()}finally{if(c)throw k}}}}var K=function(F){var U=Math.abs,N=Math.max,j=Math.floor;function S(a,c){var m;if(n(this,S),m=k.call(this,a),m.sign=c,Object.setPrototypeOf(x(m),S.prototype),a>S.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return m}s(S,F);var k=I(S);return o(S,[{key:"toDebugString",value:function(){var a,c=["BigInt["],m=W(this);try{for(m.s();!(a=m.n()).done;){var y=a.value;c.push((y&&(y>>>0).toString(16))+", ")}}catch(p){m.e(p)}finally{m.f()}return c.push("]"),c.join("")}},{key:"toString",value:function(){var a=0<arguments.length&&arguments[0]!==void 0?arguments[0]:10;if(2>a||36<a)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":a&a-1?S.__toStringGeneric(this,a,!1):S.__toStringBasePowerOfTwo(this,a)}},{key:"valueOf",value:function(){throw new Error("Convert JSBI instances to native numbers using `toNumber`.")}},{key:"__copy",value:function(){for(var a=new S(this.length,this.sign),c=0;c<this.length;c++)a[c]=this[c];return a}},{key:"__trim",value:function(){for(var a=this.length,c=this[a-1];c===0;)a--,c=this[a-1],this.pop();return a===0&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var a=0;a<this.length;a++)this[a]=0}},{key:"__clzmsd",value:function(){return S.__clz30(this.__digit(this.length-1))}},{key:"__inplaceMultiplyAdd",value:function(a,c,m){m>this.length&&(m=this.length);for(var y=32767&a,p=a>>>15,h=0,w=c,g=0;g<m;g++){var f=this.__digit(g),v=32767&f,O=f>>>15,M=S.__imul(v,y),R=S.__imul(v,p),B=S.__imul(O,y),G=S.__imul(O,p),Z=w+M+h;h=Z>>>30,Z&=1073741823,Z+=((32767&R)<<15)+((32767&B)<<15),h+=Z>>>30,w=G+(R>>>15)+(B>>>15),this.__setDigit(g,1073741823&Z)}if(h!==0||w!==0)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(a,c,m){for(var y,p=0,h=0;h<m;h++)y=this.__halfDigit(c+h)+a.__halfDigit(h)+p,p=y>>>15,this.__setHalfDigit(c+h,32767&y);return p}},{key:"__inplaceSub",value:function(a,c,m){var y=0;if(1&c){c>>=1;for(var p=this.__digit(c),h=32767&p,w=0;w<m-1>>>1;w++){var g=a.__digit(w),f=(p>>>15)-(32767&g)-y;y=1&f>>>15,this.__setDigit(c+w,(32767&f)<<15|32767&h),p=this.__digit(c+w+1),h=(32767&p)-(g>>>15)-y,y=1&h>>>15}var v=a.__digit(w),O=(p>>>15)-(32767&v)-y;if(y=1&O>>>15,this.__setDigit(c+w,(32767&O)<<15|32767&h),c+w+1>=this.length)throw new RangeError("out of bounds");!(1&m)&&(p=this.__digit(c+w+1),h=(32767&p)-(v>>>15)-y,y=1&h>>>15,this.__setDigit(c+a.length,1073709056&p|32767&h))}else{c>>=1;for(var M=0;M<a.length-1;M++){var R=this.__digit(c+M),B=a.__digit(M),G=(32767&R)-(32767&B)-y;y=1&G>>>15;var Z=(R>>>15)-(B>>>15)-y;y=1&Z>>>15,this.__setDigit(c+M,(32767&Z)<<15|32767&G)}var oe=this.__digit(c+M),te=a.__digit(M),ae=(32767&oe)-(32767&te)-y;y=1&ae>>>15;var dt=0;!(1&m)&&(dt=(oe>>>15)-(te>>>15)-y,y=1&dt>>>15),this.__setDigit(c+M,(32767&dt)<<15|32767&ae)}return y}},{key:"__inplaceRightShift",value:function(a){if(a!==0){for(var c,m=this.__digit(0)>>>a,y=this.length-1,p=0;p<y;p++)c=this.__digit(p+1),this.__setDigit(p,1073741823&c<<30-a|m),m=c>>>a;this.__setDigit(y,m)}}},{key:"__digit",value:function(a){return this[a]}},{key:"__unsignedDigit",value:function(a){return this[a]>>>0}},{key:"__setDigit",value:function(a,c){this[a]=0|c}},{key:"__setDigitGrow",value:function(a,c){this[a]=0|c}},{key:"__halfDigitLength",value:function(){var a=this.length;return 32767>=this.__unsignedDigit(a-1)?2*a-1:2*a}},{key:"__halfDigit",value:function(a){return 32767&this[a>>>1]>>>15*(1&a)}},{key:"__setHalfDigit",value:function(a,c){var m=a>>>1,y=this.__digit(m),p=1&a?32767&y|c<<15:1073709056&y|32767&c;this.__setDigit(m,p)}}],[{key:"BigInt",value:function(a){var c=Number.isFinite;if(typeof a=="number"){if(a===0)return S.__zero();if(S.__isOneDigitInt(a))return 0>a?S.__oneDigit(-a,!0):S.__oneDigit(a,!1);if(!c(a)||j(a)!==a)throw new RangeError("The number "+a+" cannot be converted to BigInt because it is not an integer");return S.__fromDouble(a)}if(typeof a=="string"){var m=S.__fromString(a);if(m===null)throw new SyntaxError("Cannot convert "+a+" to a BigInt");return m}if(typeof a=="boolean")return a===!0?S.__oneDigit(1,!1):S.__zero();if(r(a)==="object"){if(a.constructor===S)return a;var y=S.__toPrimitive(a);return S.BigInt(y)}throw new TypeError("Cannot convert "+a+" to a BigInt")}},{key:"toNumber",value:function(a){var c=a.length;if(c===0)return 0;if(c===1){var m=a.__unsignedDigit(0);return a.sign?-m:m}var y=a.__digit(c-1),p=S.__clz30(y),h=30*c-p;if(1024<h)return a.sign?-1/0:1/0;var w=h-1,g=y,f=c-1,v=p+3,O=v===32?0:g<<v;O>>>=12;var M=v-12,R=12<=v?0:g<<20+v,B=20+v;for(0<M&&0<f&&(f--,g=a.__digit(f),O|=g>>>30-M,R=g<<M+2,B=M+2);0<B&&0<f;)f--,g=a.__digit(f),R|=30<=B?g<<B-30:g>>>30-B,B-=30;var G=S.__decideRounding(a,B,f,g);if((G===1||G===0&&(1&R)==1)&&(R=R+1>>>0,R===0&&(O++,O>>>20!=0&&(O=0,w++,1023<w))))return a.sign?-1/0:1/0;var Z=a.sign?-2147483648:0;return w=w+1023<<20,S.__kBitConversionInts[1]=Z|w|O,S.__kBitConversionInts[0]=R,S.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(a){if(a.length===0)return a;var c=a.__copy();return c.sign=!a.sign,c}},{key:"bitwiseNot",value:function(a){return a.sign?S.__absoluteSubOne(a).__trim():S.__absoluteAddOne(a,!0)}},{key:"exponentiate",value:function(a,c){if(c.sign)throw new RangeError("Exponent must be positive");if(c.length===0)return S.__oneDigit(1,!1);if(a.length===0)return a;if(a.length===1&&a.__digit(0)===1)return a.sign&&!(1&c.__digit(0))?S.unaryMinus(a):a;if(1<c.length)throw new RangeError("BigInt too big");var m=c.__unsignedDigit(0);if(m===1)return a;if(m>=S.__kMaxLengthBits)throw new RangeError("BigInt too big");if(a.length===1&&a.__digit(0)===2){var y=1+(0|m/30),p=a.sign&&(1&m)!=0,h=new S(y,p);h.__initializeDigits();var w=1<<m%30;return h.__setDigit(y-1,w),h}var g=null,f=a;for(1&m&&(g=a),m>>=1;m!==0;m>>=1)f=S.multiply(f,f),1&m&&(g===null?g=f:g=S.multiply(g,f));return g}},{key:"multiply",value:function(a,c){if(a.length===0)return a;if(c.length===0)return c;var m=a.length+c.length;30<=a.__clzmsd()+c.__clzmsd()&&m--;var y=new S(m,a.sign!==c.sign);y.__initializeDigits();for(var p=0;p<a.length;p++)S.__multiplyAccumulate(c,a.__digit(p),y,p);return y.__trim()}},{key:"divide",value:function(a,c){if(c.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(a,c))return S.__zero();var m,y=a.sign!==c.sign,p=c.__unsignedDigit(0);if(c.length===1&&32767>=p){if(p===1)return y===a.sign?a:S.unaryMinus(a);m=S.__absoluteDivSmall(a,p,null)}else m=S.__absoluteDivLarge(a,c,!0,!1);return m.sign=y,m.__trim()}},{key:"remainder",value:function(c,m){if(m.length===0)throw new RangeError("Division by zero");if(0>S.__absoluteCompare(c,m))return c;var y=m.__unsignedDigit(0);if(m.length===1&&32767>=y){if(y===1)return S.__zero();var p=S.__absoluteModSmall(c,y);return p===0?S.__zero():S.__oneDigit(p,c.sign)}var h=S.__absoluteDivLarge(c,m,!1,!0);return h.sign=c.sign,h.__trim()}},{key:"add",value:function(a,c){var m=a.sign;return m===c.sign?S.__absoluteAdd(a,c,m):0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m)}},{key:"subtract",value:function(a,c){var m=a.sign;return m===c.sign?0<=S.__absoluteCompare(a,c)?S.__absoluteSub(a,c,m):S.__absoluteSub(c,a,!m):S.__absoluteAdd(a,c,m)}},{key:"leftShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__rightShiftByAbsolute(a,c):S.__leftShiftByAbsolute(a,c)}},{key:"signedRightShift",value:function(a,c){return c.length===0||a.length===0?a:c.sign?S.__leftShiftByAbsolute(a,c):S.__rightShiftByAbsolute(a,c)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(a,c){return 0>S.__compareToBigInt(a,c)}},{key:"lessThanOrEqual",value:function(a,c){return 0>=S.__compareToBigInt(a,c)}},{key:"greaterThan",value:function(a,c){return 0<S.__compareToBigInt(a,c)}},{key:"greaterThanOrEqual",value:function(a,c){return 0<=S.__compareToBigInt(a,c)}},{key:"equal",value:function(a,c){if(a.sign!==c.sign||a.length!==c.length)return!1;for(var m=0;m<a.length;m++)if(a.__digit(m)!==c.__digit(m))return!1;return!0}},{key:"notEqual",value:function(a,c){return!S.equal(a,c)}},{key:"bitwiseAnd",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteAnd(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length)+1,y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteOr(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}return S.__absoluteAndNot(a,S.__absoluteSubOne(c)).__trim()}},{key:"bitwiseXor",value:function(a,c){if(!a.sign&&!c.sign)return S.__absoluteXor(a,c).__trim();if(a.sign&&c.sign){var m=N(a.length,c.length),y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return S.__absoluteXor(y,p,y).__trim()}var h=N(a.length,c.length)+1;if(a.sign){var w=[c,a];a=w[0],c=w[1]}var g=S.__absoluteSubOne(c,h);return g=S.__absoluteXor(g,a,g),S.__absoluteAddOne(g,!0,g).__trim()}},{key:"bitwiseOr",value:function(a,c){var m=N(a.length,c.length);if(!a.sign&&!c.sign)return S.__absoluteOr(a,c).__trim();if(a.sign&&c.sign){var y=S.__absoluteSubOne(a,m),p=S.__absoluteSubOne(c);return y=S.__absoluteAnd(y,p,y),S.__absoluteAddOne(y,!0,y).__trim()}if(a.sign){var h=[c,a];a=h[0],c=h[1]}var w=S.__absoluteSubOne(c,m);return w=S.__absoluteAndNot(w,a,w),S.__absoluteAddOne(w,!0,w).__trim()}},{key:"asIntN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=c.__unsignedDigit(m-1),p=1<<(a-1)%30;if(c.length===m&&y<p)return c;if((y&p)!==p)return S.__truncateToNBits(a,c);if(!c.sign)return S.__truncateAndSubFromPowerOfTwo(a,c,!0);if(!(y&p-1)){for(var h=m-2;0<=h;h--)if(c.__digit(h)!==0)return S.__truncateAndSubFromPowerOfTwo(a,c,!1);return c.length===m&&y===p?c:S.__truncateToNBits(a,c)}return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}},{key:"asUintN",value:function(a,c){if(c.length===0)return c;if(a=j(a),0>a)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(a===0)return S.__zero();if(c.sign){if(a>S.__kMaxLengthBits)throw new RangeError("BigInt too big");return S.__truncateAndSubFromPowerOfTwo(a,c,!1)}if(a>=S.__kMaxLengthBits)return c;var m=0|(a+29)/30;if(c.length<m)return c;var y=a%30;if(c.length==m){if(y===0)return c;var p=c.__digit(m-1);if(!(p>>>y))return c}return S.__truncateToNBits(a,c)}},{key:"ADD",value:function(a,c){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string")return typeof c!="string"&&(c=c.toString()),a+c;if(typeof c=="string")return a.toString()+c;if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)&&S.__isBigInt(c))return S.add(a,c);if(typeof a=="number"&&typeof c=="number")return a+c;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(a,c){return S.__compare(a,c,0)}},{key:"LE",value:function(a,c){return S.__compare(a,c,1)}},{key:"GT",value:function(a,c){return S.__compare(a,c,2)}},{key:"GE",value:function(a,c){return S.__compare(a,c,3)}},{key:"EQ",value:function(a,c){for(;;){if(S.__isBigInt(a))return S.__isBigInt(c)?S.equal(a,c):S.EQ(c,a);if(typeof a=="number"){if(S.__isBigInt(c))return S.__equalToNumber(c,a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="string"){if(S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.equal(a,c);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(typeof a=="boolean"){if(S.__isBigInt(c))return S.__equalToNumber(c,+a);if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="symbol"){if(S.__isBigInt(c))return!1;if(r(c)!=="object")return a==c;c=S.__toPrimitive(c)}else if(r(a)==="object"){if(r(c)==="object"&&c.constructor!==S)return a==c;a=S.__toPrimitive(a)}else return a==c}}},{key:"NE",value:function(a,c){return!S.EQ(a,c)}},{key:"DataViewGetBigInt64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2];return S.asIntN(64,S.DataViewGetBigUint64(a,c,m))}},{key:"DataViewGetBigUint64",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0&&arguments[2],y=m?[4,0]:[0,4],p=C(y,2),h=p[0],w=p[1],g=a.getUint32(c+h,m),f=a.getUint32(c+w,m),v=new S(3,!1);return v.__setDigit(0,1073741823&f),v.__setDigit(1,(268435455&g)<<2|f>>>30),v.__setDigit(2,g>>>28),v.__trim()}},{key:"DataViewSetBigInt64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];S.DataViewSetBigUint64(a,c,m,y)}},{key:"DataViewSetBigUint64",value:function(a,c,m){var y=3<arguments.length&&arguments[3]!==void 0&&arguments[3];m=S.asUintN(64,m);var p=0,h=0;if(0<m.length&&(h=m.__digit(0),1<m.length)){var w=m.__digit(1);h|=w<<30,p=w>>>2,2<m.length&&(p|=m.__digit(2)<<28)}var g=y?[4,0]:[0,4],f=C(g,2),v=f[0],O=f[1];a.setUint32(c+v,p,y),a.setUint32(c+O,h,y)}},{key:"__zero",value:function(){return new S(0,!1)}},{key:"__oneDigit",value:function(a,c){var m=new S(1,c);return m.__setDigit(0,a),m}},{key:"__decideRounding",value:function(a,c,m,y){if(0<c)return-1;var p;if(0>c)p=-c-1;else{if(m===0)return-1;m--,y=a.__digit(m),p=29}var h=1<<p;if(!(y&h))return-1;if(h-=1,(y&h)!=0)return 1;for(;0<m;)if(m--,a.__digit(m)!==0)return 1;return 0}},{key:"__fromDouble",value:function(a){S.__kBitConversionDouble[0]=a;var c,m=2047&S.__kBitConversionInts[1]>>>20,y=m-1023,p=(0|y/30)+1,h=new S(p,0>a),w=1048575&S.__kBitConversionInts[1]|1048576,g=S.__kBitConversionInts[0],f=20,v=y%30,O=0;if(v<f){var M=f-v;O=M+32,c=w>>>M,w=w<<32-M|g>>>M,g<<=32-M}else if(v===f)O=32,c=w,w=g,g=0;else{var R=v-f;O=32-R,c=w<<R|g>>>32-R,w=g<<R,g=0}h.__setDigit(p-1,c);for(var B=p-2;0<=B;B--)0<O?(O-=30,c=w>>>2,w=w<<30|g>>>2,g<<=30):c=0,h.__setDigit(B,c);return h.__trim()}},{key:"__isWhitespace",value:function(a){return 13>=a&&9<=a||(159>=a?a==32:131071>=a?a==160||a==5760:196607>=a?(a&=131071,10>=a||a==40||a==41||a==47||a==95||a==4096):a==65279)}},{key:"__fromString",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,m=0,y=a.length,p=0;if(p===y)return S.__zero();for(var h=a.charCodeAt(p);S.__isWhitespace(h);){if(++p===y)return S.__zero();h=a.charCodeAt(p)}if(h===43){if(++p===y)return null;h=a.charCodeAt(p),m=1}else if(h===45){if(++p===y)return null;h=a.charCodeAt(p),m=-1}if(c===0){if(c=10,h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(c=16,++p===y)return null;h=a.charCodeAt(p)}else if(h===79||h===111){if(c=8,++p===y)return null;h=a.charCodeAt(p)}else if(h===66||h===98){if(c=2,++p===y)return null;h=a.charCodeAt(p)}}}else if(c===16&&h===48){if(++p===y)return S.__zero();if(h=a.charCodeAt(p),h===88||h===120){if(++p===y)return null;h=a.charCodeAt(p)}}if(m!==0&&c!==10)return null;for(;h===48;){if(++p===y)return S.__zero();h=a.charCodeAt(p)}var w=y-p,g=S.__kMaxBitsPerChar[c],f=S.__kBitsPerCharTableMultiplier-1;if(w>1073741824/g)return null;var v=g*w+f>>>S.__kBitsPerCharTableShift,O=new S(0|(v+29)/30,!1),M=10>c?c:10,R=10<c?c-10:0;if(c&c-1){O.__initializeDigits();var dt=!1,ve=0;do{for(var xe,an=0,Ae=1;;){if(xe=void 0,h-48>>>0<M)xe=h-48;else if((32|h)-97>>>0<R)xe=(32|h)-87;else{dt=!0;break}var Me=Ae*c;if(1073741823<Me)break;if(Ae=Me,an=an*c+xe,ve++,++p===y){dt=!0;break}h=a.charCodeAt(p)}f=30*S.__kBitsPerCharTableMultiplier-1;var Gi=0|(g*ve+f>>>S.__kBitsPerCharTableShift)/30;O.__inplaceMultiplyAdd(Ae,an,Gi)}while(!dt)}else{g>>=S.__kBitsPerCharTableShift;var B=[],G=[],Z=!1;do{for(var oe,te=0,ae=0;;){if(oe=void 0,h-48>>>0<M)oe=h-48;else if((32|h)-97>>>0<R)oe=(32|h)-87;else{Z=!0;break}if(ae+=g,te=te<<g|oe,++p===y){Z=!0;break}if(h=a.charCodeAt(p),30<ae+g)break}B.push(te),G.push(ae)}while(!Z);S.__fillFromParts(O,B,G)}if(p!==y){if(!S.__isWhitespace(h))return null;for(p++;p<y;p++)if(h=a.charCodeAt(p),!S.__isWhitespace(h))return null}return O.sign=m===-1,O.__trim()}},{key:"__fillFromParts",value:function(a,c,m){for(var y=0,p=0,h=0,w=c.length-1;0<=w;w--){var g=c[w],f=m[w];p|=g<<h,h+=f,h===30?(a.__setDigit(y++,p),h=0,p=0):30<h&&(a.__setDigit(y++,1073741823&p),h-=30,p=g>>>f-h)}if(p!==0){if(y>=a.length)throw new Error("implementation bug");a.__setDigit(y++,p)}for(;y<a.length;y++)a.__setDigit(y,0)}},{key:"__toStringBasePowerOfTwo",value:function(a,c){var m=a.length,y=c-1;y=(85&y>>>1)+(85&y),y=(51&y>>>2)+(51&y),y=(15&y>>>4)+(15&y);var p=y,h=c-1,w=a.__digit(m-1),g=S.__clz30(w),f=0|(30*m-g+p-1)/p;if(a.sign&&f++,268435456<f)throw new Error("string too long");for(var v=Array(f),O=f-1,M=0,R=0,B=0;B<m-1;B++){var G=a.__digit(B),Z=(M|G<<R)&h;v[O--]=S.__kConversionChars[Z];var oe=p-R;for(M=G>>>oe,R=30-oe;R>=p;)v[O--]=S.__kConversionChars[M&h],M>>>=p,R-=p}var te=(M|w<<R)&h;for(v[O--]=S.__kConversionChars[te],M=w>>>p-R;M!==0;)v[O--]=S.__kConversionChars[M&h],M>>>=p;if(a.sign&&(v[O--]="-"),O!==-1)throw new Error("implementation bug");return v.join("")}},{key:"__toStringGeneric",value:function(a,c,m){var y=a.length;if(y===0)return"";if(y===1){var p=a.__unsignedDigit(0).toString(c);return m===!1&&a.sign&&(p="-"+p),p}var h=30*y-S.__clz30(a.__digit(y-1)),w=S.__kMaxBitsPerChar[c],g=w-1,f=h*S.__kBitsPerCharTableMultiplier;f+=g-1,f=0|f/g;var v,O,M=f+1>>1,R=S.exponentiate(S.__oneDigit(c,!1),S.__oneDigit(M,!1)),B=R.__unsignedDigit(0);if(R.length===1&&32767>=B){v=new S(a.length,!1),v.__initializeDigits();for(var G,Z=0,oe=2*a.length-1;0<=oe;oe--)G=Z<<15|a.__halfDigit(oe),v.__setHalfDigit(oe,0|G/B),Z=0|G%B;O=Z.toString(c)}else{var te=S.__absoluteDivLarge(a,R,!0,!0);v=te.quotient;var ae=te.remainder.__trim();O=S.__toStringGeneric(ae,c,!0)}v.__trim();for(var dt=S.__toStringGeneric(v,c,!0);O.length<M;)O="0"+O;return m===!1&&a.sign&&(dt="-"+dt),dt+O}},{key:"__unequalSign",value:function(a){return a?-1:1}},{key:"__absoluteGreater",value:function(a){return a?-1:1}},{key:"__absoluteLess",value:function(a){return a?1:-1}},{key:"__compareToBigInt",value:function(a,c){var m=a.sign;if(m!==c.sign)return S.__unequalSign(m);var y=S.__absoluteCompare(a,c);return 0<y?S.__absoluteGreater(m):0>y?S.__absoluteLess(m):0}},{key:"__compareToNumber",value:function(a,c){if(S.__isOneDigitInt(c)){var m=a.sign,y=0>c;if(m!==y)return S.__unequalSign(m);if(a.length===0){if(y)throw new Error("implementation bug");return c===0?0:-1}if(1<a.length)return S.__absoluteGreater(m);var p=U(c),h=a.__unsignedDigit(0);return h>p?S.__absoluteGreater(m):h<p?S.__absoluteLess(m):0}return S.__compareToDouble(a,c)}},{key:"__compareToDouble",value:function(a,c){if(c!==c)return c;if(c===1/0)return-1;if(c===-1/0)return 1;var m=a.sign;if(m!==0>c)return S.__unequalSign(m);if(c===0)throw new Error("implementation bug: should be handled elsewhere");if(a.length===0)return-1;S.__kBitConversionDouble[0]=c;var y=2047&S.__kBitConversionInts[1]>>>20;if(y==2047)throw new Error("implementation bug: handled elsewhere");var p=y-1023;if(0>p)return S.__absoluteGreater(m);var h=a.length,w=a.__digit(h-1),g=S.__clz30(w),f=30*h-g,v=p+1;if(f<v)return S.__absoluteLess(m);if(f>v)return S.__absoluteGreater(m);var O=1048576|1048575&S.__kBitConversionInts[1],M=S.__kBitConversionInts[0],R=20,B=29-g;if(B!==(0|(f-1)%30))throw new Error("implementation bug");var G,Z=0;if(B<R){var oe=R-B;Z=oe+32,G=O>>>oe,O=O<<32-oe|M>>>oe,M<<=32-oe}else if(B===R)Z=32,G=O,O=M,M=0;else{var te=B-R;Z=32-te,G=O<<te|M>>>32-te,O=M<<te,M=0}if(w>>>=0,G>>>=0,w>G)return S.__absoluteGreater(m);if(w<G)return S.__absoluteLess(m);for(var ae=h-2;0<=ae;ae--){0<Z?(Z-=30,G=O>>>2,O=O<<30|M>>>2,M<<=30):G=0;var dt=a.__unsignedDigit(ae);if(dt>G)return S.__absoluteGreater(m);if(dt<G)return S.__absoluteLess(m)}if(O!==0||M!==0){if(Z===0)throw new Error("implementation bug");return S.__absoluteLess(m)}return 0}},{key:"__equalToNumber",value:function(a,c){return S.__isOneDigitInt(c)?c===0?a.length===0:a.length===1&&a.sign===0>c&&a.__unsignedDigit(0)===U(c):S.__compareToDouble(a,c)===0}},{key:"__comparisonResultToBool",value:function(a,c){return c===0?0>a:c===1?0>=a:c===2?0<a:c===3?0<=a:void 0}},{key:"__compare",value:function(a,c,m){if(a=S.__toPrimitive(a),c=S.__toPrimitive(c),typeof a=="string"&&typeof c=="string")switch(m){case 0:return a<c;case 1:return a<=c;case 2:return a>c;case 3:return a>=c}if(S.__isBigInt(a)&&typeof c=="string")return c=S.__fromString(c),c!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof a=="string"&&S.__isBigInt(c))return a=S.__fromString(a),a!==null&&S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(a=S.__toNumeric(a),c=S.__toNumeric(c),S.__isBigInt(a)){if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToBigInt(a,c),m);if(typeof c!="number")throw new Error("implementation bug");return S.__comparisonResultToBool(S.__compareToNumber(a,c),m)}if(typeof a!="number")throw new Error("implementation bug");if(S.__isBigInt(c))return S.__comparisonResultToBool(S.__compareToNumber(c,a),2^m);if(typeof c!="number")throw new Error("implementation bug");return m===0?a<c:m===1?a<=c:m===2?a>c:m===3?a>=c:void 0}},{key:"__absoluteAdd",value:function(a,c,m){if(a.length<c.length)return S.__absoluteAdd(c,a,m);if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);var y=a.length;(a.__clzmsd()===0||c.length===a.length&&c.__clzmsd()===0)&&y++;for(var p,h=new S(y,m),w=0,g=0;g<c.length;g++)p=a.__digit(g)+c.__digit(g)+w,w=p>>>30,h.__setDigit(g,1073741823&p);for(;g<a.length;g++){var f=a.__digit(g)+w;w=f>>>30,h.__setDigit(g,1073741823&f)}return g<h.length&&h.__setDigit(g,w),h.__trim()}},{key:"__absoluteSub",value:function(a,c,m){if(a.length===0)return a;if(c.length===0)return a.sign===m?a:S.unaryMinus(a);for(var y,p=new S(a.length,m),h=0,w=0;w<c.length;w++)y=a.__digit(w)-c.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);for(;w<a.length;w++){var g=a.__digit(w)-h;h=1&g>>>30,p.__setDigit(w,1073741823&g)}return p.__trim()}},{key:"__absoluteAddOne",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length;m===null?m=new S(y,c):m.sign=c;for(var p,h=1,w=0;w<y;w++)p=a.__digit(w)+h,h=p>>>30,m.__setDigit(w,1073741823&p);return h!==0&&m.__setDigitGrow(y,1),m}},{key:"__absoluteSubOne",value:function(a,c){var m=a.length;c=c||m;for(var y,p=new S(c,!1),h=1,w=0;w<m;w++)y=a.__digit(w)-h,h=1&y>>>30,p.__setDigit(w,1073741823&y);if(h!==0)throw new Error("implementation bug");for(var g=m;g<c;g++)p.__setDigit(g,0);return p}},{key:"__absoluteAnd",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=h;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)&c.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteAndNot",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;y<p&&(h=y);var w=y;m===null?m=new S(w,!1):w=m.length;for(var g=0;g<h;g++)m.__setDigit(g,a.__digit(g)&~c.__digit(g));for(;g<y;g++)m.__setDigit(g,a.__digit(g));for(;g<w;g++)m.__setDigit(g,0);return m}},{key:"__absoluteOr",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)|c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteXor",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null,y=a.length,p=c.length,h=p;if(y<p){h=y;var w=a,g=y;a=c,y=p,c=w,p=g}var f=y;m===null?m=new S(f,!1):f=m.length;for(var v=0;v<h;v++)m.__setDigit(v,a.__digit(v)^c.__digit(v));for(;v<y;v++)m.__setDigit(v,a.__digit(v));for(;v<f;v++)m.__setDigit(v,0);return m}},{key:"__absoluteCompare",value:function(a,c){var m=a.length-c.length;if(m!=0)return m;for(var y=a.length-1;0<=y&&a.__digit(y)===c.__digit(y);)y--;return 0>y?0:a.__unsignedDigit(y)>c.__unsignedDigit(y)?1:-1}},{key:"__multiplyAccumulate",value:function(a,c,m,y){if(c!==0){for(var p=32767&c,h=c>>>15,w=0,g=0,f=0;f<a.length;f++,y++){var v=m.__digit(y),O=a.__digit(f),M=32767&O,R=O>>>15,B=S.__imul(M,p),G=S.__imul(M,h),Z=S.__imul(R,p),oe=S.__imul(R,h);v+=g+B+w,w=v>>>30,v&=1073741823,v+=((32767&G)<<15)+((32767&Z)<<15),w+=v>>>30,g=oe+(G>>>15)+(Z>>>15),m.__setDigit(y,1073741823&v)}for(;w!==0||g!==0;y++){var te=m.__digit(y);te+=w+g,g=0,w=te>>>30,m.__setDigit(y,1073741823&te)}}}},{key:"__internalMultiplyAdd",value:function(a,c,m,y,p){for(var h=m,w=0,g=0;g<y;g++){var f=a.__digit(g),v=S.__imul(32767&f,c),O=S.__imul(f>>>15,c),M=v+((32767&O)<<15)+w+h;h=M>>>30,w=O>>>15,p.__setDigit(g,1073741823&M)}if(p.length>y)for(p.__setDigit(y++,h+w);y<p.length;)p.__setDigit(y++,0);else if(h+w!==0)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(a,c){var m=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;m===null&&(m=new S(a.length,!1));for(var y=0,p=2*a.length-1;0<=p;p-=2){var h=(y<<15|a.__halfDigit(p))>>>0,w=0|h/c;y=0|h%c,h=(y<<15|a.__halfDigit(p-1))>>>0;var g=0|h/c;y=0|h%c,m.__setDigit(p>>>1,w<<15|g)}return m}},{key:"__absoluteModSmall",value:function(a,c){for(var m,y=0,p=2*a.length-1;0<=p;p--)m=(y<<15|a.__halfDigit(p))>>>0,y=0|m%c;return y}},{key:"__absoluteDivLarge",value:function(a,c,m,y){var p=c.__halfDigitLength(),h=c.length,w=a.__halfDigitLength()-p,g=null;m&&(g=new S(w+2>>>1,!1),g.__initializeDigits());var f=new S(p+2>>>1,!1);f.__initializeDigits();var v=S.__clz15(c.__halfDigit(p-1));0<v&&(c=S.__specialLeftShift(c,v,0));for(var O=S.__specialLeftShift(a,v,1),M=c.__halfDigit(p-1),R=0,B=w;0<=B;B--){var G=32767,Z=O.__halfDigit(B+p);if(Z!==M){var oe=(Z<<15|O.__halfDigit(B+p-1))>>>0;G=0|oe/M;for(var te=0|oe%M,ae=c.__halfDigit(p-2),dt=O.__halfDigit(B+p-2);S.__imul(G,ae)>>>0>(te<<16|dt)>>>0&&(G--,te+=M,!(32767<te)););}S.__internalMultiplyAdd(c,G,0,h,f);var ve=O.__inplaceSub(f,B,p+1);ve!==0&&(ve=O.__inplaceAdd(c,B,p),O.__setHalfDigit(B+p,32767&O.__halfDigit(B+p)+ve),G--),m&&(1&B?R=G<<15:g.__setDigit(B>>>1,R|G))}if(y)return O.__inplaceRightShift(v),m?{quotient:g,remainder:O}:O;if(m)return g;throw new Error("unreachable")}},{key:"__clz15",value:function(a){return S.__clz30(a)-15}},{key:"__specialLeftShift",value:function(a,c,m){var y=a.length,p=new S(y+m,!1);if(c===0){for(var h=0;h<y;h++)p.__setDigit(h,a.__digit(h));return 0<m&&p.__setDigit(y,0),p}for(var w,g=0,f=0;f<y;f++)w=a.__digit(f),p.__setDigit(f,1073741823&w<<c|g),g=w>>>30-c;return 0<m&&p.__setDigit(y,g),p}},{key:"__leftShiftByAbsolute",value:function(a,c){var m=S.__toShiftAmount(c);if(0>m)throw new RangeError("BigInt too big");var y=0|m/30,p=m%30,h=a.length,w=p!==0&&a.__digit(h-1)>>>30-p!=0,g=h+y+(w?1:0),f=new S(g,a.sign);if(p===0){for(var v=0;v<y;v++)f.__setDigit(v,0);for(;v<g;v++)f.__setDigit(v,a.__digit(v-y))}else{for(var O=0,M=0;M<y;M++)f.__setDigit(M,0);for(var R,B=0;B<h;B++)R=a.__digit(B),f.__setDigit(B+y,1073741823&R<<p|O),O=R>>>30-p;if(w)f.__setDigit(h+y,O);else if(O!==0)throw new Error("implementation bug")}return f.__trim()}},{key:"__rightShiftByAbsolute",value:function(a,c){var m=a.length,y=a.sign,p=S.__toShiftAmount(c);if(0>p)return S.__rightShiftByMaximum(y);var h=0|p/30,w=p%30,g=m-h;if(0>=g)return S.__rightShiftByMaximum(y);var f=!1;if(y){if(a.__digit(h)&(1<<w)-1)f=!0;else for(var v=0;v<h;v++)if(a.__digit(v)!==0){f=!0;break}}if(f&&w===0){var O=a.__digit(m-1);!~O&&g++}var M=new S(g,y);if(w===0){M.__setDigit(g-1,0);for(var R=h;R<m;R++)M.__setDigit(R-h,a.__digit(R))}else{for(var B,G=a.__digit(h)>>>w,Z=m-h-1,oe=0;oe<Z;oe++)B=a.__digit(oe+h+1),M.__setDigit(oe,1073741823&B<<30-w|G),G=B>>>w;M.__setDigit(Z,G)}return f&&(M=S.__absoluteAddOne(M,!0,M)),M.__trim()}},{key:"__rightShiftByMaximum",value:function(a){return a?S.__oneDigit(1,!0):S.__zero()}},{key:"__toShiftAmount",value:function(a){if(1<a.length)return-1;var c=a.__unsignedDigit(0);return c>S.__kMaxLengthBits?-1:c}},{key:"__toPrimitive",value:function(a){var c=1<arguments.length&&arguments[1]!==void 0?arguments[1]:"default";if(r(a)!=="object"||a.constructor===S)return a;if(typeof Symbol<"u"&&r(Symbol.toPrimitive)==="symbol"){var m=a[Symbol.toPrimitive];if(m){var y=m(c);if(r(y)!=="object")return y;throw new TypeError("Cannot convert object to primitive value")}}var p=a.valueOf;if(p){var h=p.call(a);if(r(h)!=="object")return h}var w=a.toString;if(w){var g=w.call(a);if(r(g)!=="object")return g}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(a){return S.__isBigInt(a)?a:+a}},{key:"__isBigInt",value:function(a){return r(a)==="object"&&a!==null&&a.constructor===S}},{key:"__truncateToNBits",value:function(a,c){for(var m=0|(a+29)/30,y=new S(m,c.sign),p=m-1,h=0;h<p;h++)y.__setDigit(h,c.__digit(h));var w=c.__digit(p);if(a%30!=0){var g=32-a%30;w=w<<g>>>g}return y.__setDigit(p,w),y.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(a,c,m){for(var y=Math.min,p,h=0|(a+29)/30,w=new S(h,m),g=0,f=h-1,v=0,O=y(f,c.length);g<O;g++)p=0-c.__digit(g)-v,v=1&p>>>30,w.__setDigit(g,1073741823&p);for(;g<f;g++)w.__setDigit(g,0|1073741823&-v);var M,R=f<c.length?c.__digit(f):0,B=a%30;if(B===0)M=0-R-v,M&=1073741823;else{var G=32-B;R=R<<G>>>G;var Z=1<<32-G;M=Z-R-v,M&=Z-1}return w.__setDigit(f,M),w.__trim()}},{key:"__digitPow",value:function(a,c){for(var m=1;0<c;)1&c&&(m*=a),c>>>=1,a*=a;return m}},{key:"__isOneDigitInt",value:function(a){return(1073741823&a)===a}}]),S}(T(Array));return K.__kMaxLength=33554432,K.__kMaxLengthBits=K.__kMaxLength<<5,K.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],K.__kBitsPerCharTableShift=5,K.__kBitsPerCharTableMultiplier=1<<K.__kBitsPerCharTableShift,K.__kConversionChars=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],K.__kBitConversionBuffer=new ArrayBuffer(8),K.__kBitConversionDouble=new Float64Array(K.__kBitConversionBuffer),K.__kBitConversionInts=new Int32Array(K.__kBitConversionBuffer),K.__clz30=e?function(F){return e(F)-2}:function(F){var U=Math.LN2,N=Math.log;return F===0?30:0|29-(0|N(F>>>0)/U)},K.__imul=t||function(F,U){return 0|F*U},K})});var E_={};fc(E_,{AddressBookSDK:()=>cn,COIN_TYPE_ARG_REGEX:()=>Lu,Coin:()=>qi,CoinHelper:()=>Fi,CreateHelper:()=>un,DEV_API_URL:()=>Up,DEV_SYNCING_URL:()=>$p,ENV_CONFIGS:()=>zp,Formatter:()=>fr,HexToUint8Array:()=>ms,LOCAL_API_URL:()=>Ku,LOCAL_SYNCING_URL:()=>Ju,MAINNET_RPC_URL:()=>Zu,MSafeAccount:()=>sn,MSafeClient:()=>ks,MSafeEnv:()=>Lp,MSafeGlobals:()=>$i,PREV_API_URL:()=>Gp,PROD_API_URL:()=>Vp,SUI_COIN:()=>C_,SignatureVerifier:()=>$u,TESTNET_RPC_URL:()=>xs,Uint8ArrayToHex:()=>I_,addPrefix:()=>Uu,getAllCoins:()=>M_,getMSafeConfig:()=>Xu,getPublicKeyFromChain:()=>Gu,stringToBuffer:()=>ps});module.exports=pc(E_);var ir=require("@msafe/sui3-utils"),un=class{constructor(e,r){this.globals=e;this.pkHelper=r}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let r=await this.reduceCreationInfoToRawConfig(e);return new ir.MultiSigAccount(r).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,r){let n=ir.PublicKeySerde.de(r);if(!(0,ir.isSameAddress)(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let r=await this.validateCreateInfo(e),n=ir.SigningMessageHelper.createMSafeMessage(r),i=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,i.signature),r}async reduceCreationInfoToRawConfig(e){let r=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return r.forEach((n,i)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[i].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,i)=>({publicKey:r[i],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,r){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(i=>i.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((i,o)=>({address:i.address,weight:i.weight,...ir.PublicKeySerde.ser(n[o])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:r})}};var As=require("@msafe/sui3-utils");var mc=require("@msafe/sui3-utils"),cn=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let r=mc.SigningMessageHelper.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:r});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var zi=class{constructor(e){this.globals=e}async getMSafeByStatus(e,r){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:r})}async updateMSafeStatus(e,r){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:r})}};var ch=require("@msafe/sui3-utils"),lh=de(Wi(),1);var zn=require("@mysten/sui.js/utils"),wn=require("@mysten/sui.js/transactions"),Rt=de(we(),1);var Ks=8192;function Js(t){if(t.length<Ks)return btoa(String.fromCharCode(...t));let e="";for(var r=0;r<t.length;r+=Ks){let n=t.slice(r,r+Ks);e+=String.fromCharCode(...n)}return btoa(e)}var Ag=require("@mysten/sui.js/keypairs/ed25519"),Ig=require("@mysten/sui.js/keypairs/secp256k1"),wr=de(we(),1),ct=de(we(),1);var ln=9e15,gr=1e9,Xs="0123456789abcdef",Zi="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ki="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ys={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ln,maxE:ln,crypto:!1},Ec,or,ie=!0,Xi="[DecimalError] ",mr=Xi+"Invalid argument: ",Pc=Xi+"Precision limit exceeded",Dc=Xi+"crypto unavailable",Bc="[object Decimal]",xt=Math.floor,ft=Math.pow,lm=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,dm=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,fm=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Nc=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,$t=1e7,re=7,hm=9007199254740991,pm=Zi.length-1,Qs=Ki.length-1,q={toStringTag:Bc};q.absoluteValue=q.abs=function(){var t=new this.constructor(this);return t.s<0&&(t.s=1),J(t)};q.ceil=function(){return J(new this.constructor(this),this.e+1,2)};q.clampedTo=q.clamp=function(t,e){var r,n=this,i=n.constructor;if(t=new i(t),e=new i(e),!t.s||!e.s)return new i(NaN);if(t.gt(e))throw Error(mr+e);return r=n.cmp(t),r<0?t:n.cmp(e)>0?e:new i(n)};q.comparedTo=q.cmp=function(t){var e,r,n,i,o=this,s=o.d,u=(t=new o.constructor(t)).d,l=o.s,d=t.s;if(!s||!u)return!l||!d?NaN:l!==d?l:s===u?0:!s^l<0?1:-1;if(!s[0]||!u[0])return s[0]?l:u[0]?-d:0;if(l!==d)return l;if(o.e!==t.e)return o.e>t.e^l<0?1:-1;for(n=s.length,i=u.length,e=0,r=n<i?n:i;e<r;++e)if(s[e]!==u[e])return s[e]>u[e]^l<0?1:-1;return n===i?0:n>i^l<0?1:-1};q.cosine=q.cos=function(){var t,e,r=this,n=r.constructor;return r.d?r.d[0]?(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=mm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or==2||or==3?r.neg():r,t,e,!0)):new n(1):new n(NaN)};q.cubeRoot=q.cbrt=function(){var t,e,r,n,i,o,s,u,l,d,b=this,_=b.constructor;if(!b.isFinite()||b.isZero())return new _(b);for(ie=!1,o=b.s*ft(b.s*b,1/3),!o||Math.abs(o)==1/0?(r=gt(b.d),t=b.e,(o=(t-r.length+1)%3)&&(r+=o==1||o==-2?"0":"00"),o=ft(r,1/3),t=xt((t+1)/3)-(t%3==(t<0?-1:2)),o==1/0?r="5e"+t:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+t),n=new _(r),n.s=b.s):n=new _(o.toString()),s=(t=_.precision)+3;;)if(u=n,l=u.times(u).times(u),d=l.plus(b),n=Te(d.plus(b).times(u),d.plus(l),s+2,1),gt(u.d).slice(0,s)===(r=gt(n.d)).slice(0,s))if(r=r.slice(s-3,s+1),r=="9999"||!i&&r=="4999"){if(!i&&(J(u,t+1,0),u.times(u).times(u).eq(b))){n=u;break}s+=4,i=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(J(n,t+1,1),e=!n.times(n).times(n).eq(b));break}return ie=!0,J(n,t,_.rounding,e)};q.decimalPlaces=q.dp=function(){var t,e=this.d,r=NaN;if(e){if(t=e.length-1,r=(t-xt(this.e/re))*re,t=e[t],t)for(;t%10==0;t/=10)r--;r<0&&(r=0)}return r};q.dividedBy=q.div=function(t){return Te(this,new this.constructor(t))};q.dividedToIntegerBy=q.divToInt=function(t){var e=this,r=e.constructor;return J(Te(e,new r(t),0,1,1),r.precision,r.rounding)};q.equals=q.eq=function(t){return this.cmp(t)===0};q.floor=function(){return J(new this.constructor(this),this.e+1,3)};q.greaterThan=q.gt=function(t){return this.cmp(t)>0};q.greaterThanOrEqualTo=q.gte=function(t){var e=this.cmp(t);return e==1||e===0};q.hyperbolicCosine=q.cosh=function(){var t,e,r,n,i,o=this,s=o.constructor,u=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return u;r=s.precision,n=s.rounding,s.precision=r+Math.max(o.e,o.sd())+4,s.rounding=1,i=o.d.length,i<32?(t=Math.ceil(i/3),e=(1/Qi(4,t)).toString()):(t=16,e="2.3283064365386962890625e-10"),o=dn(s,1,o.times(e),new s(1),!0);for(var l,d=t,b=new s(8);d--;)l=o.times(o),o=u.minus(l.times(b.minus(l.times(b))));return J(o,s.precision=r,s.rounding=n,!0)};q.hyperbolicSine=q.sinh=function(){var t,e,r,n,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(e=o.precision,r=o.rounding,o.precision=e+Math.max(i.e,i.sd())+4,o.rounding=1,n=i.d.length,n<3)i=dn(o,2,i,i,!0);else{t=1.4*Math.sqrt(n),t=t>16?16:t|0,i=i.times(1/Qi(5,t)),i=dn(o,2,i,i,!0);for(var s,u=new o(5),l=new o(16),d=new o(20);t--;)s=i.times(i),i=i.times(u.plus(s.times(l.times(s).plus(d))))}return o.precision=e,o.rounding=r,J(i,e,r,!0)};q.hyperbolicTangent=q.tanh=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+7,n.rounding=1,Te(r.sinh(),r.cosh(),n.precision=t,n.rounding=e)):new n(r.s)};q.inverseCosine=q.acos=function(){var t,e=this,r=e.constructor,n=e.abs().cmp(1),i=r.precision,o=r.rounding;return n!==-1?n===0?e.isNeg()?Ut(r,i,o):new r(0):new r(NaN):e.isZero()?Ut(r,i+4,o).times(.5):(r.precision=i+6,r.rounding=1,e=e.asin(),t=Ut(r,i+4,o).times(.5),r.precision=i,r.rounding=o,t.minus(e))};q.inverseHyperbolicCosine=q.acosh=function(){var t,e,r=this,n=r.constructor;return r.lte(1)?new n(r.eq(1)?0:NaN):r.isFinite()?(t=n.precision,e=n.rounding,n.precision=t+Math.max(Math.abs(r.e),r.sd())+4,n.rounding=1,ie=!1,r=r.times(r).minus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln()):new n(r)};q.inverseHyperbolicSine=q.asinh=function(){var t,e,r=this,n=r.constructor;return!r.isFinite()||r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+2*Math.max(Math.abs(r.e),r.sd())+6,n.rounding=1,ie=!1,r=r.times(r).plus(1).sqrt().plus(r),ie=!0,n.precision=t,n.rounding=e,r.ln())};q.inverseHyperbolicTangent=q.atanh=function(){var t,e,r,n,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(t=o.precision,e=o.rounding,n=i.sd(),Math.max(n,t)<2*-i.e-1?J(new o(i),t,e,!0):(o.precision=r=n-i.e,i=Te(i.plus(1),new o(1).minus(i),r+t,1),o.precision=t+4,o.rounding=1,i=i.ln(),o.precision=t,o.rounding=e,i.times(.5))):new o(NaN)};q.inverseSine=q.asin=function(){var t,e,r,n,i=this,o=i.constructor;return i.isZero()?new o(i):(e=i.abs().cmp(1),r=o.precision,n=o.rounding,e!==-1?e===0?(t=Ut(o,r+4,n).times(.5),t.s=i.s,t):new o(NaN):(o.precision=r+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=r,o.rounding=n,i.times(2)))};q.inverseTangent=q.atan=function(){var t,e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding;if(d.isFinite()){if(d.isZero())return new b(d);if(d.abs().eq(1)&&_+4<=Qs)return s=Ut(b,_+4,T).times(.25),s.s=d.s,s}else{if(!d.s)return new b(NaN);if(_+4<=Qs)return s=Ut(b,_+4,T).times(.5),s.s=d.s,s}for(b.precision=u=_+10,b.rounding=1,r=Math.min(28,u/re+2|0),t=r;t;--t)d=d.div(d.times(d).plus(1).sqrt().plus(1));for(ie=!1,e=Math.ceil(u/re),n=1,l=d.times(d),s=new b(d),i=d;t!==-1;)if(i=i.times(l),o=s.minus(i.div(n+=2)),i=i.times(l),s=o.plus(i.div(n+=2)),s.d[e]!==void 0)for(t=e;s.d[t]===o.d[t]&&t--;);return r&&(s=s.times(2<<r-1)),ie=!0,J(s,b.precision=_,b.rounding=T,!0)};q.isFinite=function(){return!!this.d};q.isInteger=q.isInt=function(){return!!this.d&&xt(this.e/re)>this.d.length-2};q.isNaN=function(){return!this.s};q.isNegative=q.isNeg=function(){return this.s<0};q.isPositive=q.isPos=function(){return this.s>0};q.isZero=function(){return!!this.d&&this.d[0]===0};q.lessThan=q.lt=function(t){return this.cmp(t)<0};q.lessThanOrEqualTo=q.lte=function(t){return this.cmp(t)<1};q.logarithm=q.log=function(t){var e,r,n,i,o,s,u,l,d=this,b=d.constructor,_=b.precision,T=b.rounding,x=5;if(t==null)t=new b(10),e=!0;else{if(t=new b(t),r=t.d,t.s<0||!r||!r[0]||t.eq(1))return new b(NaN);e=t.eq(10)}if(r=d.d,d.s<0||!r||!r[0]||d.eq(1))return new b(r&&!r[0]?-1/0:d.s!=1?NaN:r?0:1/0);if(e)if(r.length>1)o=!0;else{for(i=r[0];i%10===0;)i/=10;o=i!==1}if(ie=!1,u=_+x,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),$n(l.d,i=_,T))do if(u+=10,s=pr(d,u),n=e?Ji(b,u+10):pr(t,u),l=Te(s,n,u,1),!o){+gt(l.d).slice(i+1,i+15)+1==1e14&&(l=J(l,_+1,0));break}while($n(l.d,i+=10,T));return ie=!0,J(l,_,T)};q.minus=q.sub=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.constructor;if(t=new A(t),!x.d||!t.d)return!x.s||!t.s?t=new A(NaN):x.d?t.s=-t.s:t=new A(t.d||x.s!==t.s?x:NaN),t;if(x.s!=t.s)return t.s=-t.s,x.plus(t);if(d=x.d,T=t.d,u=A.precision,l=A.rounding,!d[0]||!T[0]){if(T[0])t.s=-t.s;else if(d[0])t=new A(x);else return new A(l===3?-0:0);return ie?J(t,u,l):t}if(r=xt(t.e/re),b=xt(x.e/re),d=d.slice(),o=b-r,o){for(_=o<0,_?(e=d,o=-o,s=T.length):(e=T,r=b,s=d.length),n=Math.max(Math.ceil(u/re),s)+2,o>n&&(o=n,e.length=1),e.reverse(),n=o;n--;)e.push(0);e.reverse()}else{for(n=d.length,s=T.length,_=n<s,_&&(s=n),n=0;n<s;n++)if(d[n]!=T[n]){_=d[n]<T[n];break}o=0}for(_&&(e=d,d=T,T=e,t.s=-t.s),s=d.length,n=T.length-s;n>0;--n)d[s++]=0;for(n=T.length;n>o;){if(d[--n]<T[n]){for(i=n;i&&d[--i]===0;)d[i]=$t-1;--d[i],d[n]+=$t}d[n]-=T[n]}for(;d[--s]===0;)d.pop();for(;d[0]===0;d.shift())--r;return d[0]?(t.d=d,t.e=Yi(d,r),ie?J(t,u,l):t):new A(l===3?-0:0)};q.modulo=q.mod=function(t){var e,r=this,n=r.constructor;return t=new n(t),!r.d||!t.s||t.d&&!t.d[0]?new n(NaN):!t.d||r.d&&!r.d[0]?J(new n(r),n.precision,n.rounding):(ie=!1,n.modulo==9?(e=Te(r,t.abs(),0,3,1),e.s*=t.s):e=Te(r,t,0,n.modulo,1),e=e.times(t),ie=!0,r.minus(e))};q.naturalExponential=q.exp=function(){return ea(this)};q.naturalLogarithm=q.ln=function(){return pr(this)};q.negated=q.neg=function(){var t=new this.constructor(this);return t.s=-t.s,J(t)};q.plus=q.add=function(t){var e,r,n,i,o,s,u,l,d,b,_=this,T=_.constructor;if(t=new T(t),!_.d||!t.d)return!_.s||!t.s?t=new T(NaN):_.d||(t=new T(t.d||_.s===t.s?_:NaN)),t;if(_.s!=t.s)return t.s=-t.s,_.minus(t);if(d=_.d,b=t.d,u=T.precision,l=T.rounding,!d[0]||!b[0])return b[0]||(t=new T(_)),ie?J(t,u,l):t;if(o=xt(_.e/re),n=xt(t.e/re),d=d.slice(),i=o-n,i){for(i<0?(r=d,i=-i,s=b.length):(r=b,n=o,s=d.length),o=Math.ceil(u/re),s=o>s?o+1:s+1,i>s&&(i=s,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(s=d.length,i=b.length,s-i<0&&(i=s,r=b,b=d,d=r),e=0;i;)e=(d[--i]=d[i]+b[i]+e)/$t|0,d[i]%=$t;for(e&&(d.unshift(e),++n),s=d.length;d[--s]==0;)d.pop();return t.d=d,t.e=Yi(d,n),ie?J(t,u,l):t};q.precision=q.sd=function(t){var e,r=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(mr+t);return r.d?(e=Rc(r.d),t&&r.e+1>e&&(e=r.e+1)):e=NaN,e};q.round=function(){var t=this,e=t.constructor;return J(new e(t),t.e+1,e.rounding)};q.sine=q.sin=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+Math.max(r.e,r.sd())+re,n.rounding=1,r=wm(n,Lc(n,r)),n.precision=t,n.rounding=e,J(or>2?r.neg():r,t,e,!0)):new n(NaN)};q.squareRoot=q.sqrt=function(){var t,e,r,n,i,o,s=this,u=s.d,l=s.e,d=s.s,b=s.constructor;if(d!==1||!u||!u[0])return new b(!d||d<0&&(!u||u[0])?NaN:u?s:1/0);for(ie=!1,d=Math.sqrt(+s),d==0||d==1/0?(e=gt(u),(e.length+l)%2==0&&(e+="0"),d=Math.sqrt(e),l=xt((l+1)/2)-(l<0||l%2),d==1/0?e="5e"+l:(e=d.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),n=new b(e)):n=new b(d.toString()),r=(l=b.precision)+3;;)if(o=n,n=o.plus(Te(s,o,r+2,1)).times(.5),gt(o.d).slice(0,r)===(e=gt(n.d)).slice(0,r))if(e=e.slice(r-3,r+1),e=="9999"||!i&&e=="4999"){if(!i&&(J(o,l+1,0),o.times(o).eq(s))){n=o;break}r+=4,i=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(J(n,l+1,1),t=!n.times(n).eq(s));break}return ie=!0,J(n,l,b.rounding,t)};q.tangent=q.tan=function(){var t,e,r=this,n=r.constructor;return r.isFinite()?r.isZero()?new n(r):(t=n.precision,e=n.rounding,n.precision=t+10,n.rounding=1,r=r.sin(),r.s=1,r=Te(r,new n(1).minus(r.times(r)).sqrt(),t+10,0),n.precision=t,n.rounding=e,J(or==2||or==4?r.neg():r,t,e,!0)):new n(NaN)};q.times=q.mul=function(t){var e,r,n,i,o,s,u,l,d,b=this,_=b.constructor,T=b.d,x=(t=new _(t)).d;if(t.s*=b.s,!T||!T[0]||!x||!x[0])return new _(!t.s||T&&!T[0]&&!x||x&&!x[0]&&!T?NaN:!T||!x?t.s/0:t.s*0);for(r=xt(b.e/re)+xt(t.e/re),l=T.length,d=x.length,l<d&&(o=T,T=x,x=o,s=l,l=d,d=s),o=[],s=l+d,n=s;n--;)o.push(0);for(n=d;--n>=0;){for(e=0,i=l+n;i>n;)u=o[i]+x[n]*T[i-n-1]+e,o[i--]=u%$t|0,e=u/$t|0;o[i]=(o[i]+e)%$t|0}for(;!o[--s];)o.pop();return e?++r:o.shift(),t.d=o,t.e=Yi(o,r),ie?J(t,_.precision,_.rounding):t};q.toBinary=function(t,e){return ra(this,2,t,e)};q.toDecimalPlaces=q.toDP=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(Ct(t,0,gr),e===void 0?e=n.rounding:Ct(e,0,8),J(r,t+r.e+1,e))};q.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,!0):(Ct(t,0,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t+1,e),r=Yt(n,!0,t+1)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?r=Yt(i):(Ct(t,0,gr),e===void 0?e=o.rounding:Ct(e,0,8),n=J(new o(i),t+i.e+1,e),r=Yt(n,!1,t+n.e+1)),i.isNeg()&&!i.isZero()?"-"+r:r};q.toFraction=function(t){var e,r,n,i,o,s,u,l,d,b,_,T,x=this,A=x.d,I=x.constructor;if(!A)return new I(x);if(d=r=new I(1),n=l=new I(0),e=new I(n),o=e.e=Rc(A)-x.e-1,s=o%re,e.d[0]=ft(10,s<0?re+s:s),t==null)t=o>0?e:d;else{if(u=new I(t),!u.isInt()||u.lt(d))throw Error(mr+u);t=u.gt(e)?o>0?e:d:u}for(ie=!1,u=new I(gt(A)),b=I.precision,I.precision=o=A.length*re*2;_=Te(u,e,0,1,1),i=r.plus(_.times(n)),i.cmp(t)!=1;)r=n,n=i,i=d,d=l.plus(_.times(i)),l=i,i=e,e=u.minus(_.times(i)),u=i;return i=Te(t.minus(r),n,0,1,1),l=l.plus(i.times(d)),r=r.plus(i.times(n)),l.s=d.s=x.s,T=Te(d,n,o,1).minus(x).abs().cmp(Te(l,r,o,1).minus(x).abs())<1?[d,n]:[l,r],I.precision=b,ie=!0,T};q.toHexadecimal=q.toHex=function(t,e){return ra(this,16,t,e)};q.toNearest=function(t,e){var r=this,n=r.constructor;if(r=new n(r),t==null){if(!r.d)return r;t=new n(1),e=n.rounding}else{if(t=new n(t),e===void 0?e=n.rounding:Ct(e,0,8),!r.d)return t.s?r:t;if(!t.d)return t.s&&(t.s=r.s),t}return t.d[0]?(ie=!1,r=Te(r,t,0,e,1).times(t),ie=!0,J(r)):(t.s=r.s,r=t),r};q.toNumber=function(){return+this};q.toOctal=function(t,e){return ra(this,8,t,e)};q.toPower=q.pow=function(t){var e,r,n,i,o,s,u=this,l=u.constructor,d=+(t=new l(t));if(!u.d||!t.d||!u.d[0]||!t.d[0])return new l(ft(+u,d));if(u=new l(u),u.eq(1))return u;if(n=l.precision,o=l.rounding,t.eq(1))return J(u,n,o);if(e=xt(t.e/re),e>=t.d.length-1&&(r=d<0?-d:d)<=hm)return i=jc(l,u,r,n),t.s<0?new l(1).div(i):J(i,n,o);if(s=u.s,s<0){if(e<t.d.length-1)return new l(NaN);if(t.d[e]&1||(s=1),u.e==0&&u.d[0]==1&&u.d.length==1)return u.s=s,u}return r=ft(+u,d),e=r==0||!isFinite(r)?xt(d*(Math.log("0."+gt(u.d))/Math.LN10+u.e+1)):new l(r+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(ie=!1,l.rounding=u.s=1,r=Math.min(12,(e+"").length),i=ea(t.times(pr(u,n+r)),n),i.d&&(i=J(i,n+5,1),$n(i.d,n,o)&&(e=n+10,i=J(ea(t.times(pr(u,e+r)),e),e+5,1),+gt(i.d).slice(n+1,n+15)+1==1e14&&(i=J(i,n+1,0)))),i.s=s,ie=!0,l.rounding=o,J(i,n,o))};q.toPrecision=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Yt(n,n.e<=i.toExpNeg||n.e>=i.toExpPos):(Ct(t,1,gr),e===void 0?e=i.rounding:Ct(e,0,8),n=J(new i(n),t,e),r=Yt(n,t<=n.e||n.e<=i.toExpNeg,t)),n.isNeg()&&!n.isZero()?"-"+r:r};q.toSignificantDigits=q.toSD=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(Ct(t,1,gr),e===void 0?e=n.rounding:Ct(e,0,8)),J(new n(r),t,e)};q.toString=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()&&!t.isZero()?"-"+r:r};q.truncated=q.trunc=function(){return J(new this.constructor(this),this.e+1,1)};q.valueOf=q.toJSON=function(){var t=this,e=t.constructor,r=Yt(t,t.e<=e.toExpNeg||t.e>=e.toExpPos);return t.isNeg()?"-"+r:r};function gt(t){var e,r,n,i=t.length-1,o="",s=t[0];if(i>0){for(o+=s,e=1;e<i;e++)n=t[e]+"",r=re-n.length,r&&(o+=hr(r)),o+=n;s=t[e],n=s+"",r=re-n.length,r&&(o+=hr(r))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}function Ct(t,e,r){if(t!==~~t||t<e||t>r)throw Error(mr+t)}function $n(t,e,r,n){var i,o,s,u;for(o=t[0];o>=10;o/=10)--e;return--e<0?(e+=re,i=0):(i=Math.ceil((e+1)/re),e%=re),o=ft(10,re-e),u=t[i]%o|0,n==null?e<3?(e==0?u=u/100|0:e==1&&(u=u/10|0),s=r<4&&u==99999||r>3&&u==49999||u==5e4||u==0):s=(r<4&&u+1==o||r>3&&u+1==o/2)&&(t[i+1]/o/100|0)==ft(10,e-2)-1||(u==o/2||u==0)&&(t[i+1]/o/100|0)==0:e<4?(e==0?u=u/1e3|0:e==1?u=u/100|0:e==2&&(u=u/10|0),s=(n||r<4)&&u==9999||!n&&r>3&&u==4999):s=((n||r<4)&&u+1==o||!n&&r>3&&u+1==o/2)&&(t[i+1]/o/1e3|0)==ft(10,e-3)-1,s}function Hi(t,e,r){for(var n,i=[0],o,s=0,u=t.length;s<u;){for(o=i.length;o--;)i[o]*=e;for(i[0]+=Xs.indexOf(t.charAt(s++)),n=0;n<i.length;n++)i[n]>r-1&&(i[n+1]===void 0&&(i[n+1]=0),i[n+1]+=i[n]/r|0,i[n]%=r)}return i.reverse()}function mm(t,e){var r,n,i;if(e.isZero())return e;n=e.d.length,n<32?(r=Math.ceil(n/3),i=(1/Qi(4,r)).toString()):(r=16,i="2.3283064365386962890625e-10"),t.precision+=r,e=dn(t,1,e.times(i),new t(1));for(var o=r;o--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return t.precision-=r,e}var Te=function(){function t(n,i,o){var s,u=0,l=n.length;for(n=n.slice();l--;)s=n[l]*i+u,n[l]=s%o|0,u=s/o|0;return u&&n.unshift(u),n}function e(n,i,o,s){var u,l;if(o!=s)l=o>s?1:-1;else for(u=l=0;u<o;u++)if(n[u]!=i[u]){l=n[u]>i[u]?1:-1;break}return l}function r(n,i,o,s){for(var u=0;o--;)n[o]-=u,u=n[o]<i[o]?1:0,n[o]=u*s+n[o]-i[o];for(;!n[0]&&n.length>1;)n.shift()}return function(n,i,o,s,u,l){var d,b,_,T,x,A,I,C,E,P,D,L,H,W,K,F,U,N,j,S,k=n.constructor,a=n.s==i.s?1:-1,c=n.d,m=i.d;if(!c||!c[0]||!m||!m[0])return new k(!n.s||!i.s||(c?m&&c[0]==m[0]:!m)?NaN:c&&c[0]==0||!m?a*0:a/0);for(l?(x=1,b=n.e-i.e):(l=$t,x=re,b=xt(n.e/x)-xt(i.e/x)),j=m.length,U=c.length,E=new k(a),P=E.d=[],_=0;m[_]==(c[_]||0);_++);if(m[_]>(c[_]||0)&&b--,o==null?(W=o=k.precision,s=k.rounding):u?W=o+(n.e-i.e)+1:W=o,W<0)P.push(1),A=!0;else{if(W=W/x+2|0,_=0,j==1){for(T=0,m=m[0],W++;(_<U||T)&&W--;_++)K=T*l+(c[_]||0),P[_]=K/m|0,T=K%m|0;A=T||_<U}else{for(T=l/(m[0]+1)|0,T>1&&(m=t(m,T,l),c=t(c,T,l),j=m.length,U=c.length),F=j,D=c.slice(0,j),L=D.length;L<j;)D[L++]=0;S=m.slice(),S.unshift(0),N=m[0],m[1]>=l/2&&++N;do T=0,d=e(m,D,j,L),d<0?(H=D[0],j!=L&&(H=H*l+(D[1]||0)),T=H/N|0,T>1?(T>=l&&(T=l-1),I=t(m,T,l),C=I.length,L=D.length,d=e(I,D,C,L),d==1&&(T--,r(I,j<C?S:m,C,l))):(T==0&&(d=T=1),I=m.slice()),C=I.length,C<L&&I.unshift(0),r(D,I,L,l),d==-1&&(L=D.length,d=e(m,D,j,L),d<1&&(T++,r(D,j<L?S:m,L,l))),L=D.length):d===0&&(T++,D=[0]),P[_++]=T,d&&D[0]?D[L++]=c[F]||0:(D=[c[F]],L=1);while((F++<U||D[0]!==void 0)&&W--);A=D[0]!==void 0}P[0]||P.shift()}if(x==1)E.e=b,Ec=A;else{for(_=1,T=P[0];T>=10;T/=10)_++;E.e=_+b*x-1,J(E,u?o+E.e+1:o,s,A)}return E}}();function J(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor;e:if(e!=null){if(_=t.d,!_)return t;for(i=1,u=_[0];u>=10;u/=10)i++;if(o=e-i,o<0)o+=re,s=e,b=_[T=0],l=b/ft(10,i-s-1)%10|0;else if(T=Math.ceil((o+1)/re),u=_.length,T>=u)if(n){for(;u++<=T;)_.push(0);b=l=0,i=1,o%=re,s=o-re+1}else break e;else{for(b=u=_[T],i=1;u>=10;u/=10)i++;o%=re,s=o-re+i,l=s<0?0:b/ft(10,i-s-1)%10|0}if(n=n||e<0||_[T+1]!==void 0||(s<0?b:b%ft(10,i-s-1)),d=r<4?(l||n)&&(r==0||r==(t.s<0?3:2)):l>5||l==5&&(r==4||n||r==6&&(o>0?s>0?b/ft(10,i-s):0:_[T-1])%10&1||r==(t.s<0?8:7)),e<1||!_[0])return _.length=0,d?(e-=t.e+1,_[0]=ft(10,(re-e%re)%re),t.e=-e||0):_[0]=t.e=0,t;if(o==0?(_.length=T,u=1,T--):(_.length=T+1,u=ft(10,re-o),_[T]=s>0?(b/ft(10,i-s)%ft(10,s)|0)*u:0),d)for(;;)if(T==0){for(o=1,s=_[0];s>=10;s/=10)o++;for(s=_[0]+=u,u=1;s>=10;s/=10)u++;o!=u&&(t.e++,_[0]==$t&&(_[0]=1));break}else{if(_[T]+=u,_[T]!=$t)break;_[T--]=0,u=1}for(o=_.length;_[--o]===0;)_.pop()}return ie&&(t.e>x.maxE?(t.d=null,t.e=NaN):t.e<x.minE&&(t.e=0,t.d=[0])),t}function Yt(t,e,r){if(!t.isFinite())return qc(t);var n,i=t.e,o=gt(t.d),s=o.length;return e?(r&&(n=r-s)>0?o=o.charAt(0)+"."+o.slice(1)+hr(n):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(t.e<0?"e":"e+")+t.e):i<0?(o="0."+hr(-i-1)+o,r&&(n=r-s)>0&&(o+=hr(n))):i>=s?(o+=hr(i+1-s),r&&(n=r-i-1)>0&&(o=o+"."+hr(n))):((n=i+1)<s&&(o=o.slice(0,n)+"."+o.slice(n)),r&&(n=r-s)>0&&(i+1===s&&(o+="."),o+=hr(n))),o}function Yi(t,e){var r=t[0];for(e*=re;r>=10;r/=10)e++;return e}function Ji(t,e,r){if(e>pm)throw ie=!0,r&&(t.precision=r),Error(Pc);return J(new t(Zi),e,1,!0)}function Ut(t,e,r){if(e>Qs)throw Error(Pc);return J(new t(Ki),e,r,!0)}function Rc(t){var e=t.length-1,r=e*re+1;if(e=t[e],e){for(;e%10==0;e/=10)r--;for(e=t[0];e>=10;e/=10)r++}return r}function hr(t){for(var e="";t--;)e+="0";return e}function jc(t,e,r,n){var i,o=new t(1),s=Math.ceil(n/re+4);for(ie=!1;;){if(r%2&&(o=o.times(e),Oc(o.d,s)&&(i=!0)),r=xt(r/2),r===0){r=o.d.length-1,i&&o.d[r]===0&&++o.d[r];break}e=e.times(e),Oc(e.d,s)}return ie=!0,o}function Cc(t){return t.d[t.d.length-1]&1}function Fc(t,e,r){for(var n,i=new t(e[0]),o=0;++o<e.length;)if(n=new t(e[o]),n.s)i[r](n)&&(i=n);else{i=n;break}return i}function ea(t,e){var r,n,i,o,s,u,l,d=0,b=0,_=0,T=t.constructor,x=T.rounding,A=T.precision;if(!t.d||!t.d[0]||t.e>17)return new T(t.d?t.d[0]?t.s<0?0:1/0:1:t.s?t.s<0?0:t:NaN);for(e==null?(ie=!1,l=A):l=e,u=new T(.03125);t.e>-2;)t=t.times(u),_+=5;for(n=Math.log(ft(2,_))/Math.LN10*2+5|0,l+=n,r=o=s=new T(1),T.precision=l;;){if(o=J(o.times(t),l,1),r=r.times(++b),u=s.plus(Te(o,r,l,1)),gt(u.d).slice(0,l)===gt(s.d).slice(0,l)){for(i=_;i--;)s=J(s.times(s),l,1);if(e==null)if(d<3&&$n(s.d,l-n,x,d))T.precision=l+=10,r=o=u=new T(1),b=0,d++;else return J(s,T.precision=A,x,ie=!0);else return T.precision=A,s}s=u}}function pr(t,e){var r,n,i,o,s,u,l,d,b,_,T,x=1,A=10,I=t,C=I.d,E=I.constructor,P=E.rounding,D=E.precision;if(I.s<0||!C||!C[0]||!I.e&&C[0]==1&&C.length==1)return new E(C&&!C[0]?-1/0:I.s!=1?NaN:C?0:I);if(e==null?(ie=!1,b=D):b=e,E.precision=b+=A,r=gt(C),n=r.charAt(0),Math.abs(o=I.e)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)I=I.times(t),r=gt(I.d),n=r.charAt(0),x++;o=I.e,n>1?(I=new E("0."+r),o++):I=new E(n+"."+r.slice(1))}else return d=Ji(E,b+2,D).times(o+""),I=pr(new E(n+"."+r.slice(1)),b-A).plus(d),E.precision=D,e==null?J(I,D,P,ie=!0):I;for(_=I,l=s=I=Te(I.minus(1),I.plus(1),b,1),T=J(I.times(I),b,1),i=3;;){if(s=J(s.times(T),b,1),d=l.plus(Te(s,new E(i),b,1)),gt(d.d).slice(0,b)===gt(l.d).slice(0,b))if(l=l.times(2),o!==0&&(l=l.plus(Ji(E,b+2,D).times(o+""))),l=Te(l,new E(x),b,1),e==null)if($n(l.d,b-A,P,u))E.precision=b+=A,d=s=I=Te(_.minus(1),_.plus(1),b,1),T=J(I.times(I),b,1),i=u=1;else return J(l,E.precision=D,P,ie=!0);else return E.precision=D,l;l=d,i+=2}}function qc(t){return String(t.s*t.s/0)}function ta(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;n++);for(i=e.length;e.charCodeAt(i-1)===48;--i);if(e=e.slice(n,i),e){if(i-=n,t.e=r=r-n-1,t.d=[],n=(r+1)%re,r<0&&(n+=re),n<i){for(n&&t.d.push(+e.slice(0,n)),i-=re;n<i;)t.d.push(+e.slice(n,n+=re));e=e.slice(n),n=re-e.length}else n-=i;for(;n--;)e+="0";t.d.push(+e),ie&&(t.e>t.constructor.maxE?(t.d=null,t.e=NaN):t.e<t.constructor.minE&&(t.e=0,t.d=[0]))}else t.e=0,t.d=[0];return t}function gm(t,e){var r,n,i,o,s,u,l,d,b;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Nc.test(e))return ta(t,e)}else if(e==="Infinity"||e==="NaN")return+e||(t.s=NaN),t.e=NaN,t.d=null,t;if(dm.test(e))r=16,e=e.toLowerCase();else if(lm.test(e))r=2;else if(fm.test(e))r=8;else throw Error(mr+e);for(o=e.search(/p/i),o>0?(l=+e.slice(o+1),e=e.substring(2,o)):e=e.slice(2),o=e.indexOf("."),s=o>=0,n=t.constructor,s&&(e=e.replace(".",""),u=e.length,o=u-o,i=jc(n,new n(r),o,o*2)),d=Hi(e,r,$t),b=d.length-1,o=b;d[o]===0;--o)d.pop();return o<0?new n(t.s*0):(t.e=Yi(d,b),t.d=d,ie=!1,s&&(t=Te(t,i,u*4)),l&&(t=t.times(Math.abs(l)<54?ft(2,l):Gn.pow(2,l))),ie=!0,t)}function wm(t,e){var r,n=e.d.length;if(n<3)return e.isZero()?e:dn(t,2,e,e);r=1.4*Math.sqrt(n),r=r>16?16:r|0,e=e.times(1/Qi(5,r)),e=dn(t,2,e,e);for(var i,o=new t(5),s=new t(16),u=new t(20);r--;)i=e.times(e),e=e.times(o.plus(i.times(s.times(i).minus(u))));return e}function dn(t,e,r,n,i){var o,s,u,l,d=1,b=t.precision,_=Math.ceil(b/re);for(ie=!1,l=r.times(r),u=new t(n);;){if(s=Te(u.times(l),new t(e++*e++),b,1),u=i?n.plus(s):n.minus(s),n=Te(s.times(l),new t(e++*e++),b,1),s=u.plus(n),s.d[_]!==void 0){for(o=_;s.d[o]===u.d[o]&&o--;);if(o==-1)break}o=u,u=n,n=s,s=o,d++}return ie=!0,s.d.length=_+1,s}function Qi(t,e){for(var r=t;--e;)r*=t;return r}function Lc(t,e){var r,n=e.s<0,i=Ut(t,t.precision,1),o=i.times(.5);if(e=e.abs(),e.lte(o))return or=n?4:1,e;if(r=e.divToInt(i),r.isZero())or=n?3:2;else{if(e=e.minus(r.times(i)),e.lte(o))return or=Cc(r)?n?2:3:n?4:1,e;or=Cc(r)?n?1:4:n?3:2}return e.minus(i).abs()}function ra(t,e,r,n){var i,o,s,u,l,d,b,_,T,x=t.constructor,A=r!==void 0;if(A?(Ct(r,1,gr),n===void 0?n=x.rounding:Ct(n,0,8)):(r=x.precision,n=x.rounding),!t.isFinite())b=qc(t);else{for(b=Yt(t),s=b.indexOf("."),A?(i=2,e==16?r=r*4-3:e==8&&(r=r*3-2)):i=e,s>=0&&(b=b.replace(".",""),T=new x(1),T.e=b.length-s,T.d=Hi(Yt(T),10,i),T.e=T.d.length),_=Hi(b,10,i),o=l=_.length;_[--l]==0;)_.pop();if(!_[0])b=A?"0p+0":"0";else{if(s<0?o--:(t=new x(t),t.d=_,t.e=o,t=Te(t,T,r,n,0,i),_=t.d,o=t.e,d=Ec),s=_[r],u=i/2,d=d||_[r+1]!==void 0,d=n<4?(s!==void 0||d)&&(n===0||n===(t.s<0?3:2)):s>u||s===u&&(n===4||d||n===6&&_[r-1]&1||n===(t.s<0?8:7)),_.length=r,d)for(;++_[--r]>i-1;)_[r]=0,r||(++o,_.unshift(1));for(l=_.length;!_[l-1];--l);for(s=0,b="";s<l;s++)b+=Xs.charAt(_[s]);if(A){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)b+="0";for(_=Hi(b,i,e),l=_.length;!_[l-1];--l);for(s=1,b="1.";s<l;s++)b+=Xs.charAt(_[s])}else b=b.charAt(0)+"."+b.slice(1);b=b+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)b="0"+b;b="0."+b}else if(++o>l)for(o-=l;o--;)b+="0";else o<l&&(b=b.slice(0,o)+"."+b.slice(o))}b=(e==16?"0x":e==2?"0b":e==8?"0o":"")+b}return t.s<0?"-"+b:b}function Oc(t,e){if(t.length>e)return t.length=e,!0}function ym(t){return new this(t).abs()}function bm(t){return new this(t).acos()}function _m(t){return new this(t).acosh()}function vm(t,e){return new this(t).plus(e)}function Tm(t){return new this(t).asin()}function Sm(t){return new this(t).asinh()}function xm(t){return new this(t).atan()}function km(t){return new this(t).atanh()}function Am(t,e){t=new this(t),e=new this(e);var r,n=this.precision,i=this.rounding,o=n+4;return!t.s||!e.s?r=new this(NaN):!t.d&&!e.d?(r=Ut(this,o,1).times(e.s>0?.25:.75),r.s=t.s):!e.d||t.isZero()?(r=e.s<0?Ut(this,n,i):new this(0),r.s=t.s):!t.d||e.isZero()?(r=Ut(this,o,1).times(.5),r.s=t.s):e.s<0?(this.precision=o,this.rounding=1,r=this.atan(Te(t,e,o,1)),e=Ut(this,o,1),this.precision=n,this.rounding=i,r=t.s<0?r.minus(e):r.plus(e)):r=this.atan(Te(t,e,o,1)),r}function Im(t){return new this(t).cbrt()}function Cm(t){return J(t=new this(t),t.e+1,2)}function Om(t,e,r){return new this(t).clamp(e,r)}function Mm(t){if(!t||typeof t!="object")throw Error(Xi+"Object expected");var e,r,n,i=t.defaults===!0,o=["precision",1,gr,"rounding",0,8,"toExpNeg",-ln,0,"toExpPos",0,ln,"maxE",0,ln,"minE",-ln,0,"modulo",0,9];for(e=0;e<o.length;e+=3)if(r=o[e],i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(xt(n)===n&&n>=o[e+1]&&n<=o[e+2])this[r]=n;else throw Error(mr+r+": "+n);if(r="crypto",i&&(this[r]=Ys[r]),(n=t[r])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[r]=!0;else throw Error(Dc);else this[r]=!1;else throw Error(mr+r+": "+n);return this}function Em(t){return new this(t).cos()}function Pm(t){return new this(t).cosh()}function Uc(t){var e,r,n;function i(o){var s,u,l,d=this;if(!(d instanceof i))return new i(o);if(d.constructor=i,Mc(o)){d.s=o.s,ie?!o.d||o.e>i.maxE?(d.e=NaN,d.d=null):o.e<i.minE?(d.e=0,d.d=[0]):(d.e=o.e,d.d=o.d.slice()):(d.e=o.e,d.d=o.d?o.d.slice():o.d);return}if(l=typeof o,l==="number"){if(o===0){d.s=1/o<0?-1:1,d.e=0,d.d=[0];return}if(o<0?(o=-o,d.s=-1):d.s=1,o===~~o&&o<1e7){for(s=0,u=o;u>=10;u/=10)s++;ie?s>i.maxE?(d.e=NaN,d.d=null):s<i.minE?(d.e=0,d.d=[0]):(d.e=s,d.d=[o]):(d.e=s,d.d=[o]);return}else if(o*0!==0){o||(d.s=NaN),d.e=NaN,d.d=null;return}return ta(d,o.toString())}else if(l!=="string")throw Error(mr+o);return(u=o.charCodeAt(0))===45?(o=o.slice(1),d.s=-1):(u===43&&(o=o.slice(1)),d.s=1),Nc.test(o)?ta(d,o):gm(d,o)}if(i.prototype=q,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Mm,i.clone=Uc,i.isDecimal=Mc,i.abs=ym,i.acos=bm,i.acosh=_m,i.add=vm,i.asin=Tm,i.asinh=Sm,i.atan=xm,i.atanh=km,i.atan2=Am,i.cbrt=Im,i.ceil=Cm,i.clamp=Om,i.cos=Em,i.cosh=Pm,i.div=Dm,i.exp=Bm,i.floor=Nm,i.hypot=Rm,i.ln=jm,i.log=Fm,i.log10=Lm,i.log2=qm,i.max=Um,i.min=$m,i.mod=Gm,i.mul=Vm,i.pow=zm,i.random=Wm,i.round=Hm,i.sign=Zm,i.sin=Km,i.sinh=Jm,i.sqrt=Xm,i.sub=Ym,i.sum=Qm,i.tan=eg,i.tanh=tg,i.trunc=rg,t===void 0&&(t={}),t&&t.defaults!==!0)for(n=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<n.length;)t.hasOwnProperty(r=n[e++])||(t[r]=this[r]);return i.config(t),i}function Dm(t,e){return new this(t).div(e)}function Bm(t){return new this(t).exp()}function Nm(t){return J(t=new this(t),t.e+1,3)}function Rm(){var t,e,r=new this(0);for(ie=!1,t=0;t<arguments.length;)if(e=new this(arguments[t++]),e.d)r.d&&(r=r.plus(e.times(e)));else{if(e.s)return ie=!0,new this(1/0);r=e}return ie=!0,r.sqrt()}function Mc(t){return t instanceof Gn||t&&t.toStringTag===Bc||!1}function jm(t){return new this(t).ln()}function Fm(t,e){return new this(t).log(e)}function qm(t){return new this(t).log(2)}function Lm(t){return new this(t).log(10)}function Um(){return Fc(this,arguments,"lt")}function $m(){return Fc(this,arguments,"gt")}function Gm(t,e){return new this(t).mod(e)}function Vm(t,e){return new this(t).mul(e)}function zm(t,e){return new this(t).pow(e)}function Wm(t){var e,r,n,i,o=0,s=new this(1),u=[];if(t===void 0?t=this.precision:Ct(t,1,gr),n=Math.ceil(t/re),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(n));o<n;)i=e[o],i>=429e7?e[o]=crypto.getRandomValues(new Uint32Array(1))[0]:u[o++]=i%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(n*=4);o<n;)i=e[o]+(e[o+1]<<8)+(e[o+2]<<16)+((e[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(e,o):(u.push(i%1e7),o+=4);o=n/4}else throw Error(Dc);else for(;o<n;)u[o++]=Math.random()*1e7|0;for(n=u[--o],t%=re,n&&t&&(i=ft(10,re-t),u[o]=(n/i|0)*i);u[o]===0;o--)u.pop();if(o<0)r=0,u=[0];else{for(r=-1;u[0]===0;r-=re)u.shift();for(n=1,i=u[0];i>=10;i/=10)n++;n<re&&(r-=re-n)}return s.e=r,s.d=u,s}function Hm(t){return J(t=new this(t),t.e+1,this.rounding)}function Zm(t){return t=new this(t),t.d?t.d[0]?t.s:0*t.s:t.s||NaN}function Km(t){return new this(t).sin()}function Jm(t){return new this(t).sinh()}function Xm(t){return new this(t).sqrt()}function Ym(t,e){return new this(t).sub(e)}function Qm(){var t=0,e=arguments,r=new this(e[t]);for(ie=!1;r.s&&++t<e.length;)r=r.plus(e[t]);return ie=!0,J(r,this.precision,this.rounding)}function eg(t){return new this(t).tan()}function tg(t){return new this(t).tanh()}function rg(t){return J(t=new this(t),t.e+1,1)}q[Symbol.for("nodejs.util.inspect.custom")]=q.toString;q[Symbol.toStringTag]="Decimal";var Gn=q.constructor=Uc(Ys);Zi=new Gn(Zi);Ki=new Gn(Ki);var $=Gn;var Ll=de(we(),1),Kn=de(we(),1);var ee=de(we(),1),ye=de(we(),1),Ul=de(we(),1),To=require("@mysten/sui.js/utils"),r0=de(we(),1),n0=de(we(),1),o0=de(we(),1);var qr=de(we(),1),Hn=de(we(),1);var Lr=require("@mysten/sui.js/transactions"),w0=require("@mysten/sui.js/utils"),y0=require("@mysten/sui.js/transactions"),bt=de(we(),1),po=require("@mysten/sui.js/transactions"),ga=de(we(),1),Ur=require("@mysten/sui.js/transactions"),Xl=require("@mysten/sui.js/utils"),Se=de(we(),1),mo=require("@mysten/sui.js/transactions"),Et=de(we(),1),Wr=de(hl(),1),Yl=require("@mysten/sui.js/transactions"),$r=de(we(),1);var wa=require("@mysten/sui.js/transactions");var bl="3.7.7",lg=bl,pn=typeof Buffer=="function",pl=typeof TextDecoder=="function"?new TextDecoder:void 0,ml=typeof TextEncoder=="function"?new TextEncoder:void 0,dg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Vn=Array.prototype.slice.call(dg),io=(t=>{let e={};return t.forEach((r,n)=>e[r]=n),e})(Vn),fg=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,wt=String.fromCharCode.bind(String),gl=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),_l=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),vl=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),Tl=t=>{let e,r,n,i,o="",s=t.length%3;for(let u=0;u<t.length;){if((r=t.charCodeAt(u++))>255||(n=t.charCodeAt(u++))>255||(i=t.charCodeAt(u++))>255)throw new TypeError("invalid character found");e=r<<16|n<<8|i,o+=Vn[e>>18&63]+Vn[e>>12&63]+Vn[e>>6&63]+Vn[e&63]}return s?o.slice(0,s-3)+"===".substring(s):o},aa=typeof btoa=="function"?t=>btoa(t):pn?t=>Buffer.from(t,"binary").toString("base64"):Tl,oa=pn?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let n=0,i=t.length;n<i;n+=4096)r.push(wt.apply(null,t.subarray(n,n+4096)));return aa(r.join(""))},oo=(t,e=!1)=>e?_l(oa(t)):oa(t),hg=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?wt(192|e>>>6)+wt(128|e&63):wt(224|e>>>12&15)+wt(128|e>>>6&63)+wt(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return wt(240|e>>>18&7)+wt(128|e>>>12&63)+wt(128|e>>>6&63)+wt(128|e&63)}},pg=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Sl=t=>t.replace(pg,hg),wl=pn?t=>Buffer.from(t,"utf8").toString("base64"):ml?t=>oa(ml.encode(t)):t=>aa(Sl(t)),hn=(t,e=!1)=>e?_l(wl(t)):wl(t),yl=t=>hn(t,!0),mg=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,gg=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return wt((r>>>10)+55296)+wt((r&1023)+56320);case 3:return wt((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return wt((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},xl=t=>t.replace(mg,gg),kl=t=>{if(t=t.replace(/\s+/g,""),!fg.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r="",n,i;for(let o=0;o<t.length;)e=io[t.charAt(o++)]<<18|io[t.charAt(o++)]<<12|(n=io[t.charAt(o++)])<<6|(i=io[t.charAt(o++)]),r+=n===64?wt(e>>16&255):i===64?wt(e>>16&255,e>>8&255):wt(e>>16&255,e>>8&255,e&255);return r},ua=typeof atob=="function"?t=>atob(vl(t)):pn?t=>Buffer.from(t,"base64").toString("binary"):kl,Al=pn?t=>gl(Buffer.from(t,"base64")):t=>gl(ua(t).split("").map(e=>e.charCodeAt(0))),Il=t=>Al(Cl(t)),wg=pn?t=>Buffer.from(t,"base64").toString("utf8"):pl?t=>pl.decode(Al(t)):t=>xl(ua(t)),Cl=t=>vl(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),sa=t=>wg(Cl(t)),yg=t=>{if(typeof t!="string")return!1;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},Ol=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Ml=function(){let t=(e,r)=>Object.defineProperty(String.prototype,e,Ol(r));t("fromBase64",function(){return sa(this)}),t("toBase64",function(e){return hn(this,e)}),t("toBase64URI",function(){return hn(this,!0)}),t("toBase64URL",function(){return hn(this,!0)}),t("toUint8Array",function(){return Il(this)})},El=function(){let t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,Ol(r));t("toBase64",function(e){return oo(this,e)}),t("toBase64URI",function(){return oo(this,!0)}),t("toBase64URL",function(){return oo(this,!0)})},bg=()=>{Ml(),El()},mn={version:bl,VERSION:lg,atob:ua,atobPolyfill:kl,btoa:aa,btoaPolyfill:Tl,fromBase64:sa,toBase64:hn,encode:hn,encodeURI:yl,encodeURL:yl,utob:Sl,btou:xl,decode:sa,isValid:yg,fromUint8Array:oo,toUint8Array:Il,extendString:Ml,extendUint8Array:El,extendBuiltins:bg};var ya=require("@mysten/sui.js/transactions"),Ql=require("@mysten/sui.js/utils"),Gt=de(we(),1);var so,_g=new Uint8Array(16);function ca(){if(!so&&(so=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!so))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return so(_g)}var yt=[];for(let t=0;t<256;++t)yt.push((t+256).toString(16).slice(1));function Pl(t,e=0){return yt[t[e+0]]+yt[t[e+1]]+yt[t[e+2]]+yt[t[e+3]]+"-"+yt[t[e+4]]+yt[t[e+5]]+"-"+yt[t[e+6]]+yt[t[e+7]]+"-"+yt[t[e+8]]+yt[t[e+9]]+"-"+yt[t[e+10]]+yt[t[e+11]]+yt[t[e+12]]+yt[t[e+13]]+yt[t[e+14]]+yt[t[e+15]]}var vg=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),la={randomUUID:vg};function Tg(t,e,r){if(la.randomUUID&&!e&&!t)return la.randomUUID();t=t||{};let n=t.random||(t.rng||ca)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let i=0;i<16;++i)e[r+i]=n[i];return e}return Pl(n)}var ao=Tg;var go=require("@mysten/sui.js/utils"),ed=require("@mysten/sui.js/transactions"),td=require("@mysten/sui.js/client"),rd=require("@mysten/sui.js/bcs");var Sg=Object.defineProperty,xg=(t,e,r)=>e in t?Sg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kg=(t,e,r)=>(xg(t,typeof e!="symbol"?e+"":e,r),r),yo=5*60*1e3,Oe=24*60*60*1e3;function er(t){return Date.parse(new Date().toString())+t}var Zn=class{overdueTime;value;constructor(t,e=0){this.overdueTime=e,this.value=t}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};$.config({precision:64,rounding:$.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var _t=$,V=class extends Error{message;errorCode;constructor(t,e){super(t),this.message=t,this.errorCode=e}static isClmmpoolsErrorCode(t,e){return t instanceof V&&t.errorCode===e}},Y=new ct.default(0),Qt=new ct.default(1),bo=new ct.default(2),uv=bo.pow(new ct.default(128)),_n=bo.pow(new ct.default(64)).sub(Qt),Cg=bo.pow(new ct.default(128)).sub(Qt),fe=class{static toX64_BN(t){return t.mul(new ct.default(2).pow(new ct.default(64)))}static toX64_Decimal(t){return t.mul(_t.pow(2,64))}static toX64(t){return new ct.default(t.mul(_t.pow(2,64)).floor().toFixed())}static fromX64(t){return new _t(t.toString()).mul(_t.pow(2,-64))}static fromX64_Decimal(t){return t.mul(_t.pow(2,-64))}static fromX64_BN(t){return t.div(new ct.default(2).pow(new ct.default(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(_n).gt(Y)&&(e=e.add(Qt)),e}static divRoundUp(t,e){return t.mod(e).eq(Y)?t.div(e):t.div(e).add(new ct.default(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(Cg):t.sub(e)}static checkUnsignedSub(t,e){let r=t.sub(e);if(r.isNeg())throw new V("Unsigned integer sub overflow","UnsignedIntegerOverflow");return r}static checkMul(t,e,r){let n=t.mul(e);if(this.isOverflow(n,r))throw new V("Multiplication overflow","MultiplicationOverflow");return n}static checkMulDivFloor(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivCeil(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e).add(r.sub(Qt)).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulDivRound(t,e,r,n){if(r.eq(Y))throw new V("Devide by zero","DivideByZero");let i=t.mul(e.add(r.shrn(1))).div(r);if(this.isOverflow(i,n))throw new V("Multiplication div overflow","MulDivOverflow");return i}static checkMulShiftRight(t,e,r,n){let i=t.mul(e).div(new ct.default(2).pow(new ct.default(r)));if(this.isOverflow(i,n))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return i}static checkMulShiftRight64RoundUpIf(t,e,r,n){let i=t.mul(e),s=n&&i.and(_n).gt(Y)?i.shrn(64).add(Qt):i.shrn(64);if(this.isOverflow(s,r))throw new V("Multiplication shift right overflow","MulShiftRightOverflow");return s}static checkMulShiftLeft(t,e,r,n){let i=t.mul(e).shln(r);if(this.isOverflow(i,n))throw new V("Multiplication shift left overflow","MulShiftLeftOverflow");return i}static checkDivRoundUpIf(t,e,r){if(e.eq(Y))throw new V("Devide by zero","DivideByZero");return r?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(bo.pow(new ct.default(e)))}static sign(t){return t.testn(127)?1:0}static is_neg(t){return this.sign(t)===1}static abs_u128(t){return t.gt(Y)?t:this.u128_neg(t.subn(1))}static u128_neg(t){return t.uxor(new ct.default("ffffffffffffffffffffffffffffffff",16))}static neg(t){return this.is_neg(t)?t.abs():this.neg_from(t)}static abs(t){return this.sign(t)===0?t:this.u128_neg(t.sub(new ct.default(1)))}static neg_from(t){return t.eq(Y)?t:this.u128_neg(t).add(new ct.default(1)).or(new ct.default(1).shln(127))}};function Og(t){return{coinA:t.coinTypeA,coinB:t.coinTypeB,currentSqrtPrice:new wr.default(t.current_sqrt_price),currentTickIndex:t.current_tick_index,feeGrowthGlobalA:new wr.default(t.fee_growth_global_a),feeGrowthGlobalB:new wr.default(t.fee_growth_global_b),feeProtocolCoinA:new wr.default(t.fee_protocol_coin_a),feeProtocolCoinB:new wr.default(t.fee_protocol_coin_b),feeRate:new wr.default(t.fee_rate),liquidity:new wr.default(t.liquidity),tickIndexes:[],tickSpacing:Number(t.tickSpacing),ticks:[],collection_name:""}}var _o="79226673515401279992447579055";var vo="4295048016",yn=new Ll.default(1e6),Ce="0x0000000000000000000000000000000000000000000000000000000000000006",Mg="partner",fo="pool_script",Gr="pool_script_v2",Wn="router",da="router_with_partner",Vr="fetcher_script",Eg="expect_swap",Dl="utils";var fa="custodian_v2",Pg="clob_v2",Dg="endpoints_v2";function be(t){if(t.config===void 0)throw new V(`package: ${t.package_id} not config in sdk SdkOptions`,"InvalidConfig");return t.config}var Bg=14,Ng="59543866431248",Rg="184467440737095516",jg="15793534762490258745",Fg=443636;function qg(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}function ue(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}function Lg(t){let e;return t&1?e=new ee.default("79232123823359799118286999567"):e=new ee.default("79228162514264337593543950336"),t&2&&(e=ue(e.mul(new ee.default("79236085330515764027303304731")),96,256)),t&4&&(e=ue(e.mul(new ee.default("79244008939048815603706035061")),96,256)),t&8&&(e=ue(e.mul(new ee.default("79259858533276714757314932305")),96,256)),t&16&&(e=ue(e.mul(new ee.default("79291567232598584799939703904")),96,256)),t&32&&(e=ue(e.mul(new ee.default("79355022692464371645785046466")),96,256)),t&64&&(e=ue(e.mul(new ee.default("79482085999252804386437311141")),96,256)),t&128&&(e=ue(e.mul(new ee.default("79736823300114093921829183326")),96,256)),t&256&&(e=ue(e.mul(new ee.default("80248749790819932309965073892")),96,256)),t&512&&(e=ue(e.mul(new ee.default("81282483887344747381513967011")),96,256)),t&1024&&(e=ue(e.mul(new ee.default("83390072131320151908154831281")),96,256)),t&2048&&(e=ue(e.mul(new ee.default("87770609709833776024991924138")),96,256)),t&4096&&(e=ue(e.mul(new ee.default("97234110755111693312479820773")),96,256)),t&8192&&(e=ue(e.mul(new ee.default("119332217159966728226237229890")),96,256)),t&16384&&(e=ue(e.mul(new ee.default("179736315981702064433883588727")),96,256)),t&32768&&(e=ue(e.mul(new ee.default("407748233172238350107850275304")),96,256)),t&65536&&(e=ue(e.mul(new ee.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=ue(e.mul(new ee.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=ue(e.mul(new ee.default("38992368544603139932233054999993551")),96,256)),ue(e,32,256)}function Ug(t){let e=Math.abs(t),r;return e&1?r=new ee.default("18445821805675392311"):r=new ee.default("18446744073709551616"),e&2&&(r=ue(r.mul(new ee.default("18444899583751176498")),64,256)),e&4&&(r=ue(r.mul(new ee.default("18443055278223354162")),64,256)),e&8&&(r=ue(r.mul(new ee.default("18439367220385604838")),64,256)),e&16&&(r=ue(r.mul(new ee.default("18431993317065449817")),64,256)),e&32&&(r=ue(r.mul(new ee.default("18417254355718160513")),64,256)),e&64&&(r=ue(r.mul(new ee.default("18387811781193591352")),64,256)),e&128&&(r=ue(r.mul(new ee.default("18329067761203520168")),64,256)),e&256&&(r=ue(r.mul(new ee.default("18212142134806087854")),64,256)),e&512&&(r=ue(r.mul(new ee.default("17980523815641551639")),64,256)),e&1024&&(r=ue(r.mul(new ee.default("17526086738831147013")),64,256)),e&2048&&(r=ue(r.mul(new ee.default("16651378430235024244")),64,256)),e&4096&&(r=ue(r.mul(new ee.default("15030750278693429944")),64,256)),e&8192&&(r=ue(r.mul(new ee.default("12247334978882834399")),64,256)),e&16384&&(r=ue(r.mul(new ee.default("8131365268884726200")),64,256)),e&32768&&(r=ue(r.mul(new ee.default("3584323654723342297")),64,256)),e&65536&&(r=ue(r.mul(new ee.default("696457651847595233")),64,256)),e&131072&&(r=ue(r.mul(new ee.default("26294789957452057")),64,256)),e&262144&&(r=ue(r.mul(new ee.default("37481735321082")),64,256)),r}var ke=class{static priceToSqrtPriceX64(t,e,r){return fe.toX64(t.mul(_t.pow(10,r-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,r){return fe.fromX64(t).pow(2).mul(_t.pow(10,e-r))}static tickIndexToSqrtPriceX64(t){return t>0?new ee.default(Lg(t)):new ee.default(Ug(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new ee.default(_o))||t.lt(new ee.default(vo)))throw new V("Provided sqrtPrice is not within the supported sqrtPrice range.","InvalidSqrtPrice");let e=t.bitLength()-1,r=new ee.default(e-64),n=qg(r,32,128),i=new ee.default("8000000000000000","hex"),o=0,s=new ee.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new ee.default(0))&&o<Bg;){u=u.mul(u);let A=u.shrn(127);u=u.shrn(63+A.toNumber()),s=s.add(i.mul(A)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new ee.default(Ng)),_=ue(b.sub(new ee.default(Rg)),64,128).toNumber(),T=ue(b.add(new ee.default(jg)),64,128).toNumber();return _===T?_:ke.tickIndexToSqrtPriceX64(T).lte(t)?T:_}static tickIndexToPrice(t,e,r){return ke.sqrtPriceX64ToPrice(ke.tickIndexToSqrtPriceX64(t),e,r)}static priceToTickIndex(t,e,r){return ke.sqrtPriceX64ToTickIndex(ke.priceToSqrtPriceX64(t,e,r))}static priceToInitializableTickIndex(t,e,r,n){return ke.getInitializableTickIndex(ke.priceToTickIndex(t,e,r),n)}static getInitializableTickIndex(t,e){return t-t%e}static getNextInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)+e}static getPrevInitializableTickIndex(t,e){return ke.getInitializableTickIndex(t,e)-e}};function $g(t){return vt(t).add(vt(Fg))}var lv=new Kn.default(365),dv=new Kn.default(24),fv=new Kn.default(3600),hv=new Kn.default(.5);var yr=class{static getDefaultSqrtPriceLimit(t){return new Ul.default(t?vo:_o)}static getDefaultOtherAmountThreshold(t){return t?Y:_n}};function $l(t,e,r,n){if(r.eq(Y))return t;let i=fe.checkMulShiftLeft(t,e,64,256),o=e.shln(64),s=fe.checkMul(t,r,256);if(!n&&o.lte(s))throw new V("getNextSqrtPriceAUp - Unable to divide liquidityShl64 by product","DivideByZero");let u=n?fe.checkDivRoundUpIf(i,o.add(s),!0):fe.checkDivRoundUpIf(i,o.sub(s),!0);if(u.lt(new ye.default(vo)))throw new V("getNextSqrtPriceAUp - Next sqrt price less than min sqrt price","CoinAmountMinSubceeded ");if(u.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price greater than max sqrt price","CoinAmountMaxExceeded");return u}function Gl(t,e,r,n){let i=fe.checkDivRoundUpIf(r.shln(64),e,!n),o=n?t.add(i):t.sub(i);if(o.lt(new ye.default(vo))||o.gt(new ye.default(_o)))throw new V("getNextSqrtPriceAUp - Next sqrt price out of bounds","SqrtPriceOutOfBounds");return o}function Gg(t,e,r,n){return n?$l(t,e,r,!0):Gl(t,e,r,!0)}function Vg(t,e,r,n){return n?Gl(t,e,r,!1):$l(t,e,r,!1)}function Bl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n){let s=new ye.default(r).mul(new ye.default(i)).shln(64),u=e.mul(t),l=s.div(u);o=s.mod(u).eq(Y)?l:l.add(Qt)}else{let s=new ye.default(r).mul(new ye.default(i));o=s.and(_n).gt(Y)?s.shrn(64).add(Qt):s.shrn(64)}return o}function Nl(t,e,r,n){let i=t.gt(e)?t.sub(e):e.sub(t);if(r.lte(Y)||i.eq(Y))return Y;let o;if(n)o=r.mul(i).shrn(64);else{let s=r.mul(i).shln(64),u=e.mul(t);o=s.div(u)}return o}function zg(t,e,r,n,i,o){if(r===Y)return{amountIn:Y,amountOut:Y,nextSqrtPrice:e,feeAmount:Y};let s=t.gte(e),u,l,d,b;if(o){let _=fe.checkMulDivFloor(n,fe.checkUnsignedSub(yn,i),yn,64),T=Bl(t,e,r,s);T.gt(_)?(u=_,b=fe.checkUnsignedSub(n,_),d=Gg(t,r,_,s)):(u=T,b=fe.checkMulDivCeil(u,i,yn.sub(i),64),d=e),l=Nl(t,d,r,s)}else{let _=Nl(t,e,r,s);_.gt(n)?(l=n,d=Vg(t,r,n,s)):(l=_,d=e),u=Bl(t,d,r,s),b=fe.checkMulDivCeil(u,i,yn.sub(i),64)}return{amountIn:u,amountOut:l,nextSqrtPrice:d,feeAmount:b}}function Wg(t,e,r,n,i){let o=r,s=n.liquidity,{currentSqrtPrice:u}=n,l={amountIn:Y,amountOut:Y,feeAmount:Y,refAmount:Y,nextSqrtPrice:Y,crossTickNum:0},d,b,_=yr.getDefaultSqrtPriceLimit(t);for(let T of i){if(t&&n.currentTickIndex<T.index||!t&&n.currentTickIndex>=T.index||T===null)continue;t&&_.gt(T.sqrtPrice)||!t&&_.lt(T.sqrtPrice)?d=_:d=T.sqrtPrice;let x=zg(u,d,s,o,n.feeRate,e);if(x.amountIn.eq(Y)||(o=e?o.sub(x.amountIn.add(x.feeAmount)):o.sub(x.amountOut)),l.amountIn=l.amountIn.add(x.amountIn),l.amountOut=l.amountOut.add(x.amountOut),l.feeAmount=l.feeAmount.add(x.feeAmount),x.nextSqrtPrice.eq(T.sqrtPrice)?(b=T.liquidityNet.mul(new ye.default(-1)),t?fe.is_neg(b)?s=s.add(new ye.default(Vt(BigInt(b.toString()),128))):s=s.add(b):fe.is_neg(b)?s=s.sub(new ye.default(Vt(BigInt(b.toString()),128))):s=s.sub(b),u=T.sqrtPrice):u=x.nextSqrtPrice,l.crossTickNum+=1,o.eq(Y))break}return l.amountIn=l.amountIn.add(l.feeAmount),l.nextSqrtPrice=u,l}function uo(t,e,r){let n=ye.default.min(t,e),i=ye.default.max(t,e),o=fe.fromX64_BN(r.mul(i).mul(n)),s=i.sub(n);return o.div(s)}function co(t,e,r){let n=ye.default.min(t,e),o=ye.default.max(t,e).sub(n);return r.shln(64).div(o)}var ho=class{static updateFeeRate(t,e,r,n,i){let o=fe.checkMulDivCeil(e,new ye.default(n),yn,64),s=r===0?Y:fe.checkMulDivFloor(e,new ye.default(r),yn,64),u=e.mul(o).mul(s);if(i?t.feeProtocolCoinA=t.feeProtocolCoinA.add(o):t.feeProtocolCoinB=t.feeProtocolCoinB.add(o),u.eq(Y)||t.liquidity.eq(Y))return{refFee:s,clmm:t};let l=u.shln(64).div(t.liquidity);return i?t.feeGrowthGlobalA=t.feeGrowthGlobalA.add(l):t.feeGrowthGlobalB=t.feeGrowthGlobalB.add(l),{refFee:s,clmm:t}}static getCoinAmountFromLiquidity(t,e,r,n,i){let o=new _t(t.toString()),s=new _t(e.toString()),u=new _t(r.toString()),l=new _t(n.toString()),d,b;return e.lt(r)?(d=fe.toX64_Decimal(o).mul(l.sub(u)).div(u.mul(l)),b=new _t(0)):e.lt(n)?(d=fe.toX64_Decimal(o).mul(l.sub(s)).div(s.mul(l)),b=fe.fromX64_Decimal(o.mul(s.sub(u)))):(d=new _t(0),b=fe.fromX64_Decimal(o.mul(l.sub(u)))),i?{coinA:new ye.default(d.ceil().toString()),coinB:new ye.default(b.ceil().toString())}:{coinA:new ye.default(d.floor().toString()),coinB:new ye.default(b.floor().toString())}}static estLiquidityAndcoinAmountFromOneAmounts(t,e,r,n,i,o,s){let u=ke.sqrtPriceX64ToTickIndex(s),l=ke.tickIndexToSqrtPriceX64(t),d=ke.tickIndexToSqrtPriceX64(e),b;if(u<t){if(!n)throw new V("lower tick cannot calculate liquidity by coinB","NotSupportedThisCoin");b=uo(l,d,r)}else if(u>e){if(n)throw new V("upper tick cannot calculate liquidity by coinA","NotSupportedThisCoin");b=co(d,l,r)}else n?b=uo(s,d,r):b=co(s,l,r);let _=ho.getCoinAmountFromLiquidity(b,s,l,d,i),T=i?vt(_.coinA.toString()).mul(1+o).toString():vt(_.coinA.toString()).mul(1-o).toString(),x=i?vt(_.coinB.toString()).mul(1+o).toString():vt(_.coinB.toString()).mul(1-o).toString();return{coinAmountA:_.coinA,coinAmountB:_.coinB,tokenMaxA:i?new ye.default(_t.ceil(T).toString()):new ye.default(_t.floor(T).toString()),tokenMaxB:i?new ye.default(_t.ceil(x).toString()):new ye.default(_t.floor(x).toString()),liquidityAmount:b,fix_amount_a:n}}static estimateLiquidityFromcoinAmounts(t,e,r,n){if(e>r)throw new V("lower tick cannot be greater than lower tick","InvalidTwoTickIndex");let i=ke.sqrtPriceX64ToTickIndex(t),o=ke.tickIndexToSqrtPriceX64(e),s=ke.tickIndexToSqrtPriceX64(r);if(i<e)return uo(o,s,n.coinA);if(i>=r)return co(s,o,n.coinB);let u=uo(t,s,n.coinA),l=co(t,o,n.coinB);return ye.default.min(u,l)}static estCoinAmountsFromTotalAmount(t,e,r,n,i,o){let{ratioA:s,ratioB:u}=ho.calculateDepositRatioFixTokenA(t,e,r),l=vt(n).mul(s).div(i),d=vt(n).mul(u).div(o);return{amountA:l,amountB:d}}static calculateDepositRatioFixTokenA(t,e,r){let n=new ye.default(1e8),{coinAmountB:i}=ho.estLiquidityAndcoinAmountFromOneAmounts(t,e,n,!0,!0,0,r),o=ke.sqrtPriceX64ToPrice(r,0,0),s=vt(n.toString()).mul(o),u=s.add(i.toString()),l=s.div(u),d=vt(i.toString()).div(u);return{ratioA:l,ratioB:d}}};function Hg(t){return t.startsWith("0x")?`${t.slice(2)}`:t}var Zg=0,Vl=1,Kg=2;function Rl(t,e){return t===e?Zg:t<e?Vl:Kg}function Jg(t,e){let r=0,n=t.length<=e.length?t.length:e.length,i=Rl(t.length,e.length);for(;r<n;){let o=Rl(t.charCodeAt(r),e.charCodeAt(r));if(r+=1,o!==0)return o}return i}function jl(t,e){return Jg(t,e)===Vl}function Fl(t,...e){let r=Array.isArray(e[e.length-1])?e.pop():[],i=[t,...e].filter(Boolean).join("::");return r&&r.length&&(i+=`<${r.join(", ")}>`),i}function se(t){try{let e=t.replace(/\s/g,""),n=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){e=e.slice(0,e.indexOf("<"));let l={...se(e),type_arguments:n.map(d=>se(d).source_address)};return l.type_arguments=l.type_arguments.map(d=>Ie.isSuiCoin(d)?d:se(d).source_address),l.source_address=Fl(l.full_address,l.type_arguments),l}let i=e.split("::"),s={full_address:e,address:e===Wl||e===t0?"0x2":(0,To.normalizeSuiObjectId)(i[0]),module:i[1],name:i[2],type_arguments:[],source_address:""};return s.full_address=`${s.address}::${s.module}::${s.name}`,s.source_address=Fl(s.full_address,s.type_arguments),s}catch{return{full_address:t,address:"",module:"",name:"",type_arguments:[],source_address:t}}}function sr(t){return se(t).source_address}function Xg(t){return t.toLowerCase().startsWith("0x")?(0,To.normalizeSuiObjectId)(t):t}var Yg=(t,e=!0)=>{let r=t.split("::"),n=r.shift(),i=(0,To.normalizeSuiObjectId)(n);return e&&(i=Hg(i)),`${i}::${r.join("::")}`};function zl(t){for(let e in t){let r=typeof t[e];if(r==="object")zl(t[e]);else if(r==="string"){let n=t[e];n&&!n.includes("::")&&(t[e]=Xg(n))}}}var Qg="0x2::coin::Coin",e0=/^0x2::coin::Coin<(.+)>$/;var Wl="0x2::sui::SUI",t0="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Ie=class{static getCoinTypeArg(t){let e=t.type.match(e0);return e?e[1]:null}static isSUI(t){let e=Ie.getCoinTypeArg(t);return e?Ie.getCoinSymbol(e)==="SUI":!1}static getCoinSymbol(t){return t.substring(t.lastIndexOf(":")+1)}static getBalance(t){return BigInt(t.fields.balance)}static totalBalance(t,e){let r=BigInt(0);return t.forEach(n=>{e===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(t){return t.fields.id.id}static getCoinTypeFromArg(t){return`${Qg}<${t}>`}static getFaucetCoins(t){let{events:e}=t,r=[];return e?.forEach(n=>{let{type:i}=n;if(se(i).name==="InitEvent"){let o=n.parsedJson;r.push({transactionModule:n.transactionModule,suplyID:o.suplyID,decimals:o.decimals})}}),r}static getCoinAssets(t,e){let r=[];return e.forEach(n=>{sr(n.coinAddress)===sr(t)&&r.push(n)}),r}static isSuiCoin(t){return se(t).full_address===Wl}static selectCoinObjectIdGreaterThanOrEqual(t,e,r=[]){let n=Ie.selectCoinAssetGreaterThanOrEqual(t,e,r),i=n.selectedCoins.map(u=>u.coinObjectId),o=n.remainingCoins,s=n.selectedCoins.map(u=>u.balance.toString());return{objectArray:i,remainCoins:o,amountArray:s}}static selectCoinAssetGreaterThanOrEqual(t,e,r=[]){let n=Ie.sortByBalance(t.filter(l=>!r.includes(l.coinObjectId))),i=Ie.calculateTotalBalance(n);if(i<e)return{selectedCoins:[],remainingCoins:n};if(i===e)return{selectedCoins:n,remainingCoins:[]};let o=BigInt(0),s=[],u=[...n];for(;o<i;){let l=e-o,d=u.findIndex(_=>_.balance>=l);if(d!==-1){s.push(u[d]),u.splice(d,1);break}let b=u.pop();b.balance>0&&(s.push(b),o+=b.balance)}return{selectedCoins:Ie.sortByBalance(s),remainingCoins:Ie.sortByBalance(u)}}static sortByBalance(t){return t.sort((e,r)=>e.balance<r.balance?-1:e.balance>r.balance?1:0)}static sortByBalanceDes(t){return t.sort((e,r)=>e.balance>r.balance?-1:e.balance<r.balance?0:1)}static calculateTotalBalance(t){return t.reduce((e,r)=>e+r.balance,BigInt(0))}};function i0(t,{numerator:e,denominator:r},n){return n?t.mul(r.add(e)).div(r):t.mul(r).div(r.add(e))}function vt(t){return $.isDecimal(t)?t:new $(t===void 0?0:t)}function Jn(t){return t.data}function Hl(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let{error:e}=t;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Zl(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function s0(t){if("reference"in t)return t.reference;let e=Jn(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Hl(t)}function bn(t){return"objectId"in t?t.objectId:s0(t)?.objectId??Zl(t)}function a0(t){return t.data!==void 0}function u0(t){return t.content!==void 0}function Kl(t){let e="data"in t?Jn(t):t;if(!(!e||!u0(e)||e.content.dataType!=="moveObject"))return e.content}function ba(t){return Kl(t)?.type}function c0(t){let e=a0(t)?t.data:t;return!e?.type&&"data"in t?e?.content?.dataType==="package"?"package":ba(t):e?.type}function _a(t){return Jn(t)?.previousTransaction}function l0(t){return Jn(t)?.owner}function d0(t){let e=Jn(t)?.display;return e||{data:null,error:null}}function br(t){let e=Kl(t)?.fields;if(e)return"fields"in e?e.fields:e}function Vt(t,e=32){return BigInt.asUintN(e,BigInt(t)).toString()}function zr(t,e=32){return Number(BigInt.asIntN(e,BigInt(t)))}function f0(t,e,r){let n=se(t).name,i=se(e).name;return`${n}-${i}[${r}]`}function ha(t){let e=ba(t),r=se(e),n=br(t);if(n==null)throw new V(`Pool id ${bn(t)} not exists.`,"InvalidPoolObject");let i=[];n.rewarder_manager.fields.rewarders.forEach(s=>{let{emissions_per_second:u}=s.fields,l=fe.fromX64(new Rt.default(u)),d=Math.floor(l.toNumber()*60*60*24);i.push({emissions_per_second:u,coinAddress:se(s.fields.reward_coin.fields.name).source_address,growth_global:s.fields.growth_global,emissionsEveryDay:d})});let o={poolAddress:bn(t),poolType:e,coinTypeA:r.type_arguments[0],coinTypeB:r.type_arguments[1],coinAmountA:n.coin_a,coinAmountB:n.coin_b,current_sqrt_price:n.current_sqrt_price,current_tick_index:zr(BigInt(n.current_tick_index.fields.bits)),fee_growth_global_a:n.fee_growth_global_a,fee_growth_global_b:n.fee_growth_global_b,fee_protocol_coin_a:n.fee_protocol_coin_a,fee_protocol_coin_b:n.fee_protocol_coin_b,fee_rate:n.fee_rate,is_pause:n.is_pause,liquidity:n.liquidity,position_manager:{positions_handle:n.position_manager.fields.positions.fields.id.id,size:n.position_manager.fields.positions.fields.size},rewarder_infos:i,rewarder_last_updated_time:n.rewarder_manager.fields.last_updated_time,tickSpacing:n.tick_spacing,ticks_handle:n.tick_manager.fields.ticks.fields.id.id,uri:n.url,index:Number(n.index),name:""};return o.name=f0(o.coinTypeA,o.coinTypeB,o.tickSpacing),o}function h0(t){let e=d0(t).data,r={creator:"",description:"",image_url:"",link:"",name:"",project_url:""};return e&&(r.creator=e.creator,r.description=e.description,r.image_url=e.image_url,r.link=e.link,r.name=e.name,r.project_url=e.project_url),r}function pa(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Position not exists. Get Position error:${t.error}`,"InvalidPositionObject");let e={creator:"",description:"",image_url:"",link:"",name:"",project_url:""},r={...e,pos_object_id:"",owner:"",type:"",coin_type_a:"",coin_type_b:"",liquidity:"",tick_lower_index:0,tick_upper_index:0,index:0,pool:"",reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"},n=br(t);if(n){let s=ba(t),u=l0(t);"nft"in n?(n=n.nft.fields,e.description=n.description,e.name=n.name,e.link=n.url):e=h0(t),r={...e,pos_object_id:n.id.id,owner:u.AddressOwner,type:s,coin_type_a:n.coin_type_a.fields.name,coin_type_b:n.coin_type_b.fields.name,liquidity:n.liquidity,tick_lower_index:zr(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:zr(BigInt(n.tick_upper_index.fields.bits)),index:n.index,pool:n.pool,reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0",fee_growth_inside_a:"0",fee_owed_a:"0",fee_growth_inside_b:"0",fee_owed_b:"0",position_status:"Exists"}}let i=Hl(t);i&&(r.pos_object_id=i.objectId,r.position_status="Deleted");let o=Zl(t);return o&&(r.pos_object_id=o,r.position_status="NotExists"),r}function Jl(t){let e={reward_amount_owed_0:"0",reward_amount_owed_1:"0",reward_amount_owed_2:"0",reward_growth_inside_0:"0",reward_growth_inside_1:"0",reward_growth_inside_2:"0"};t="fields"in t?t.fields:t,t.rewards.forEach((o,s)=>{let{amount_owned:u,growth_inside:l}="fields"in o?o.fields:o;s===0?(e.reward_amount_owed_0=u,e.reward_growth_inside_0=l):s===1?(e.reward_amount_owed_1=u,e.reward_growth_inside_1=l):s===2&&(e.reward_amount_owed_2=u,e.reward_growth_inside_2=l)});let r="fields"in t.tick_lower_index?t.tick_lower_index.fields.bits:t.tick_lower_index.bits,n="fields"in t.tick_upper_index?t.tick_upper_index.fields.bits:t.tick_upper_index.bits;return{liquidity:t.liquidity,tick_lower_index:zr(BigInt(r)),tick_upper_index:zr(BigInt(n)),...e,fee_growth_inside_a:t.fee_growth_inside_a,fee_owed_a:t.fee_owned_a,fee_growth_inside_b:t.fee_growth_inside_b,fee_owed_b:t.fee_owned_b,pos_object_id:t.position_id}}function ma(t){if(t.error!=null||t.data?.content?.dataType!=="moveObject")throw new V(`Tick not exists. Get tick data error:${t.error}`,"InvalidTickObject");let r=br(t).value.fields.value.fields;return{objectId:bn(t),index:zr(BigInt(r.index.fields.bits)),sqrtPrice:new Rt.default(r.sqrt_price),liquidityNet:new Rt.default(r.liquidity_net.fields.bits),liquidityGross:new Rt.default(r.liquidity_gross),feeGrowthOutsideA:new Rt.default(r.fee_growth_outside_a),feeGrowthOutsideB:new Rt.default(r.fee_growth_outside_b),rewardersGrowthOutside:r.rewards_growth_outside}}function p0(t){if(!t||!t.index||!t.sqrt_price||!t.liquidity_net||!t.liquidity_gross||!t.fee_growth_outside_a||!t.fee_growth_outside_b)throw new V("Invalid tick fields.","InvalidTickFields");let e=zr(BigInt(t.index.bits)),r=new Rt.default(t.sqrt_price),n=new Rt.default(t.liquidity_net.bits),i=new Rt.default(t.liquidity_gross),o=new Rt.default(t.fee_growth_outside_a),s=new Rt.default(t.fee_growth_outside_b),u=t.rewards_growth_outside||[];return{objectId:"",index:e,sqrtPrice:r,liquidityNet:n,liquidityGross:i,feeGrowthOutsideA:o,feeGrowthOutsideB:s,rewardersGrowthOutside:u}}function m0(t,e,r,n,i,o){let s=t.rewarder_infos,u=[];for(let l=0;l<s.length;l+=1){let d=o[l];e!==null&&(t.current_tick_index<n?d=o[l].sub(new qr.default(e.rewardersGrowthOutside[l])):d=e.rewardersGrowthOutside[l]);let b=new qr.default(0);r!==null&&(t.current_tick_index>=i?b=o[l].sub(new qr.default(r.rewardersGrowthOutside[l])):b=r.rewardersGrowthOutside[l]);let _=fe.subUnderflowU128(fe.subUnderflowU128(new qr.default(o[l]),new qr.default(d)),new qr.default(b));u.push(_)}return u}function wo(t){let e=Ie.isSuiCoin(t.coinTypeA),r=Ie.isSuiCoin(t.coinTypeB);return{isAdjustCoinA:e,isAdjustCoinB:r}}function g0(t,e){return $.ceil(vt(t).div(1+e)).toString()}var X=class{static createCollectRewarderAndFeeParams(t,e,r,n,i,o){i===void 0&&(i=[...n]),o===void 0&&(o=[...n]);let s=sr(r.coinTypeA),u=sr(r.coinTypeB);if(r.collect_fee){let d=X.buildCoinForAmount(e,i,BigInt(0),s,!1);i=d.remainCoins;let b=X.buildCoinForAmount(e,o,BigInt(0),u,!1);o=b.remainCoins,e=t.Position.createCollectFeePaylod({pool_id:r.pool_id,pos_id:r.pos_id,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB},e,d.targetCoin,b.targetCoin)}let l=[];return r.rewarder_coin_types.forEach(d=>{switch(sr(d)){case s:l.push(X.buildCoinForAmount(e,i,BigInt(0),d,!1).targetCoin);break;case u:l.push(X.buildCoinForAmount(e,o,BigInt(0),d,!1).targetCoin);break;default:l.push(X.buildCoinForAmount(e,n,BigInt(0),d,!1).targetCoin);break}}),e=t.Rewarder.createCollectRewarderPaylod(r,e,l),e}static async adjustTransactionForGas(t,e,r,n){n.setSender(t.senderAddress);let i=Ie.selectCoinAssetGreaterThanOrEqual(e,r).selectedCoins;if(i.length===0)throw new V("Insufficient balance","InsufficientBalance");let o=Ie.calculateTotalBalance(e);if(o-r>1e9)return{fixAmount:r};let s=await t.fullClient.calculationTxGas(n);if(Ie.selectCoinAssetGreaterThanOrEqual(e,BigInt(s),i.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(s)+BigInt(500);if(o-r<l){if(r-=l,r<0)throw new V("gas Insufficient balance","InsufficientBalance");let d=new Lr.TransactionBlock;return{fixAmount:r,newTx:d}}}return{fixAmount:r}}static async buildAddLiquidityFixTokenForGas(t,e,r,n){let i=await X.buildAddLiquidityFixToken(t,e,r),{isAdjustCoinA:o}=wo(r),s=o?r.amount_a:r.amount_b,u=await X.adjustTransactionForGas(t,Ie.getCoinAssets(o?r.coinTypeA:r.coinTypeB,e),BigInt(s),i),{fixAmount:l}=u,{newTx:d}=u;if(d!==void 0){let b,_;if(o)r.amount_a=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,l.toString(),r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);else return r.amount_b=Number(l),b=X.buildAddLiquidityFixTokenCoinInput(d,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),_=X.buildAddLiquidityFixTokenCoinInput(d,r.fix_amount_a,l.toString(),r.slippage,r.coinTypeB,e,!1),r=X.fixAddLiquidityFixTokenParams(r,n.slippage,n.curSqrtPrice),i=await X.buildAddLiquidityFixTokenArgs(d,t,e,r,b,_),i}return i}static async buildAddLiquidityFixToken(t,e,r){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let n=new Lr.TransactionBlock,i=X.buildAddLiquidityFixTokenCoinInput(n,!r.fix_amount_a,r.amount_a,r.slippage,r.coinTypeA,e,!1),o=X.buildAddLiquidityFixTokenCoinInput(n,r.fix_amount_a,r.amount_b,r.slippage,r.coinTypeB,e,!1);return n=X.buildAddLiquidityFixTokenArgs(n,t,e,r,i,o),n}static buildAddLiquidityFixTokenCoinInput(t,e,r,n,i,o,s=!0){return e?X.buildCoinForAmountInterval(t,o,{amountSecond:BigInt(g0(r,n)),amountFirst:BigInt(r)},i,s):X.buildCoinForAmount(t,o,BigInt(r),i,s)}static fixAddLiquidityFixTokenParams(t,e,r){let n=t.fix_amount_a?t.amount_a:t.amount_b,i=ho.estLiquidityAndcoinAmountFromOneAmounts(Number(t.tick_lower),Number(t.tick_upper),new Hn.default(n),t.fix_amount_a,!0,e,r);return t.amount_a=t.fix_amount_a?t.amount_a:i.tokenMaxA.toNumber(),t.amount_b=t.fix_amount_a?i.tokenMaxB.toNumber():t.amount_b,t}static buildAddLiquidityFixTokenArgs(t,e,r,n,i,o){let s=[n.coinTypeA,n.coinTypeB],u=n.is_open?"open_position_with_liquidity_by_fix_coin":"add_liquidity_by_fix_coin",{clmm_pool:l,integrate:d}=e.sdkOptions;n.is_open||(t=X.createCollectRewarderAndFeeParams(e,t,n,r,i.remainCoins,o.remainCoins));let b=be(l),_=n.is_open?[t.object(b.global_config_id),t.object(n.pool_id),t.pure(Vt(BigInt(n.tick_lower)).toString()),t.pure(Vt(BigInt(n.tick_upper)).toString()),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)]:[t.object(b.global_config_id),t.object(n.pool_id),t.object(n.pos_id),i.targetCoin,o.targetCoin,t.pure(n.amount_a),t.pure(n.amount_b),t.pure(n.fix_amount_a),t.object(Ce)];return t.moveCall({target:`${d.published_at}::${Gr}::${u}`,typeArguments:s,arguments:_}),t}static async buildSwapTransactionForGas(t,e,r,n){let i=X.buildSwapTransaction(t,e,r);i.setSender(t.senderAddress);let o=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:s,newTx:u}=o;if(u!==void 0){u.setSender(t.senderAddress),e.by_amount_in?e.amount=s.toString():e.amount_limit=s.toString(),e=await X.fixSwapParams(t,e,n);let l=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA),d=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB);i=X.buildSwapTransactionArgs(u,e,t.sdkOptions,l,d)}return i}static buildSwapTransaction(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1);return n=X.buildSwapTransactionArgs(n,e,t.sdkOptions,i,o),n}static buildSwapTransactionArgs(t,e,r,n,i){let{clmm_pool:o,integrate:s}=r,u=yr.getDefaultSqrtPriceLimit(e.a2b),l=[e.coinTypeA,e.coinTypeB],{global_config_id:d}=be(o);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=e.swap_partner!==void 0,_=b?e.a2b?"swap_a2b_with_partner":"swap_b2a_with_partner":e.a2b?"swap_a2b":"swap_b2a",T=b?[t.pure(d),t.pure(e.pool_id),t.pure(e.swap_partner),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)]:[t.pure(d),t.pure(e.pool_id),n.targetCoin,i.targetCoin,t.pure(e.by_amount_in),t.pure(e.amount),t.pure(e.amount_limit),t.pure(u.toString()),t.pure(Ce)];return t.moveCall({target:`${s.published_at}::${Gr}::${_}`,typeArguments:l,arguments:T}),t}static async buildSwapTransactionWithoutTransferCoinsForGas(t,e,r,n){let{tx:i,coinABs:o}=X.buildSwapTransactionWithoutTransferCoins(t,e,r);i.setSender(t.senderAddress);let s=await X.adjustTransactionForGas(t,Ie.getCoinAssets(e.a2b?e.coinTypeA:e.coinTypeB,r),BigInt(e.by_amount_in?e.amount:e.amount_limit),i),{fixAmount:u,newTx:l}=s;if(l!==void 0){l.setSender(t.senderAddress),e.by_amount_in?e.amount=u.toString():e.amount_limit=u.toString(),e=await X.fixSwapParams(t,e,n);let d=X.buildCoinForAmount(i,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),b=X.buildCoinForAmount(i,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),_=X.buildSwapTransactionWithoutTransferCoinArgs(t,l,e,t.sdkOptions,d,b);i=_.tx,o=_.txRes}return{tx:i,coinABs:o}}static buildSwapTransactionWithoutTransferCoins(t,e,r){let n=new Lr.TransactionBlock;n.setSender(t.senderAddress);let i=X.buildCoinForAmount(n,r,e.a2b?BigInt(e.by_amount_in?e.amount:e.amount_limit):BigInt(0),e.coinTypeA,!1,!0),o=X.buildCoinForAmount(n,r,e.a2b?BigInt(0):BigInt(e.by_amount_in?e.amount:e.amount_limit),e.coinTypeB,!1,!0),s=X.buildSwapTransactionWithoutTransferCoinArgs(t,n,e,t.sdkOptions,i,o);return{tx:s.tx,coinABs:s.txRes}}static buildSwapTransactionWithoutTransferCoinArgs(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=n,l=yr.getDefaultSqrtPriceLimit(r.a2b),{global_config_id:d}=be(s);if(d===void 0)throw Error("clmm.config.global_config_id is undefined");let b=r.swap_partner!==void 0,_=b?"swap_with_partner":"swap",T=b?da:Wn,x=b?[e.pure(d),e.pure(r.pool_id),e.pure(r.swap_partner),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)]:[e.pure(d),e.pure(r.pool_id),i.targetCoin,o.targetCoin,e.pure(r.a2b),e.pure(r.by_amount_in),e.pure(r.amount),e.pure(l.toString()),e.pure(!1),e.pure(Ce)],A=[r.coinTypeA,r.coinTypeB],I=e.moveCall({target:`${u.published_at}::${T}::${_}`,typeArguments:A,arguments:x});if(r.by_amount_in){let C=r.a2b?r.coinTypeB:r.coinTypeA,E=r.a2b?I[1]:I[0],P=Number(r.amount_limit);this.checkCoinThreshold(t,r.by_amount_in,e,E,P,C)}return{tx:e,txRes:I}}static async fixSwapParams(t,e,r){let{currentPool:n}=r;try{let i=await t.Swap.preswap({decimalsA:r.decimalsA,decimalsB:r.decimalsB,a2b:e.a2b,byAmountIn:e.by_amount_in,amount:e.amount,pool:n,currentSqrtPrice:n.current_sqrt_price,coinTypeA:n.coinTypeA,coinTypeB:n.coinTypeB}),o=r.byAmountIn?i.estimatedAmountOut:i.estimatedAmountIn,s=i0(o,r.slippage,!r.byAmountIn);e.amount_limit=s.toString()}catch(i){console.log("fixSwapParams",i)}return e}static async syncBuildCoinInputForAmount(t,e,r,n,i=!0){if(t.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let o=await t.getOwnerCoinAssets(t.senderAddress,n);return X.buildCoinForAmount(e,o,r,n,i).targetCoin}static buildCoinForAmount(t,e,r,n,i=!0,o=!1){let s=Ie.getCoinAssets(n,e);if(r===BigInt(0)&&s.length===0)return X.buildZeroValueCoin(e,t,n,i);let u=Ie.calculateTotalBalance(s);if(u<r)throw new V(`The amount(${u}) is Insufficient balance for ${n} , expect ${r} `,"InsufficientBalance");return X.buildCoin(t,e,s,r,n,i,o)}static buildCoin(t,e,r,n,i,o=!0,s=!1){if(Ie.isSuiCoin(i)){if(o){let P=t.splitCoins(t.gas,[t.pure(n.toString())]);return{targetCoin:t.makeMoveVec({objects:[P]}),remainCoins:e,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}if(n===0n&&r.length>1){let P=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.object(P.objectArray[0]),remainCoins:P.remainCoins,tragetCoinAmount:P.amountArray[0],isMintZeroCoin:!1}}let C=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:t.splitCoins(t.gas,[t.pure(n.toString())]),remainCoins:C.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:t.gas}}let u=Ie.selectCoinObjectIdGreaterThanOrEqual(r,n),l=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),d=u.objectArray;if(o)return{targetCoin:t.makeMoveVec({objects:d.map(C=>t.object(C))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),isMintZeroCoin:!1};let[b,..._]=d,T=t.object(b),x=T,A=u.amountArray.reduce((C,E)=>Number(C)+Number(E),0).toString(),I;return _.length>0&&t.mergeCoins(T,_.map(C=>t.object(C))),s&&Number(l)>Number(n)&&(x=t.splitCoins(T,[t.pure(n.toString())]),A=n.toString(),I=T),{targetCoin:x,remainCoins:u.remainCoins,originalSplitedCoin:I,tragetCoinAmount:A,isMintZeroCoin:!1}}static buildZeroValueCoin(t,e,r,n=!0){let i=X.callMintZeroValueCoin(e,r),o;return n?o=e.makeMoveVec({objects:[i]}):o=i,{targetCoin:o,remainCoins:t,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(t,e,r,n,i=!0){let o=Ie.getCoinAssets(n,e);if(r.amountFirst===BigInt(0))return o.length>0?X.buildCoin(t,[...e],[...o],r.amountFirst,n,i):X.buildZeroValueCoin(e,t,n,i);let s=Ie.calculateTotalBalance(o);if(s>=r.amountFirst)return X.buildCoin(t,[...e],[...o],r.amountFirst,n,i);if(s<r.amountSecond)throw new V(`The amount(${s}) is Insufficient balance for ${n} , expect ${r.amountSecond} `,"InsufficientBalance");return X.buildCoin(t,[...e],[...o],r.amountSecond,n,i)}static async buildRouterSwapTransaction(t,e,r,n,i){let o=new Lr.TransactionBlock;return e.paths.length>1&&(e.partner=""),o=await this.buildRouterBasePathTx(t,e,r,n,o,i),o}static async buildRouterBasePathTx(t,e,r,n,i,o){let s=e.paths.filter(D=>D&&D.poolAddress),u=Number(s.reduce((D,L)=>D.add(L.amountIn),Y).toString()),l=Number(s.reduce((D,L)=>D.add(L.amountOut),Y).toString()),d=Math.round(r?Number(l.toString())*(1-e.priceSlippagePoint):Number(u.toString())*(1+e.priceSlippagePoint)),b=e.paths[0].coinType[0],_=e.paths[0].coinType[e.paths[0].coinType.length-1],T=X.buildCoinForAmount(i,n,BigInt(r?u:d),b,!1,!0),x=T.originalSplitedCoin!==void 0,A=X.buildCoinForAmount(i,n,0n,_,!1),I=await this.buildRouterBasePathReturnCoins(t,e,r,T,A,i),C=[],{toCoin:E,fromCoin:P}=I;if(i=I.tx,A.isMintZeroCoin?C.push({coinType:_,coin:E}):A.originalSplitedCoin!==void 0?i.mergeCoins(A.originalSplitedCoin,[E]):i.mergeCoins(A.targetCoin,[E]),x){let D=T?.originalSplitedCoin;i.mergeCoins(D,[P])}else C.push({coinType:b,coin:P});for(let D=0;D<C.length;D++)this.buildTransferCoin(t,i,C[D].coin,C[D].coinType,o);return i}static async buildRouterBasePathReturnCoins(t,e,r,n,i,o){let{clmm_pool:s,integrate:u}=t.sdkOptions,l=be(s).global_config_id,d=e.paths.filter(D=>D&&D.poolAddress),b=Number(d.reduce((D,L)=>D.add(L.amountIn),Y).toString()),_=Number(d.reduce((D,L)=>D.add(L.amountOut),Y).toString()),T=Math.round(r?Number(_.toString())*(1-e.priceSlippagePoint):Number(b.toString())*(1+e.priceSlippagePoint)),x=e.paths[0].coinType[0],A=e.paths[0].coinType[e.paths[0].coinType.length-1],I=n.targetCoin,C;i.isMintZeroCoin||i.originalSplitedCoin!==void 0?C=i.targetCoin:C=X.callMintZeroValueCoin(o,A);let E=e.partner==="",P=E?Wn:da;for(let D of d)if(D.poolAddress.length===1){let L=D.a2b[0],H={amount:Number(D.amountIn.toString()),amountLimit:T,poolCoinA:D.a2b[0]?x:A,poolCoinB:D.a2b[0]?A:x},W=E?"swap":"swap_with_partner",K=L?I:C,F=L?C:I,U=r?D.amountIn.toString():D.amountOut.toString(),N=yr.getDefaultSqrtPriceLimit(L).toString(),j=E?[o.object(l),o.object(D.poolAddress[0]),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.pure(e.partner),K,F,o.pure(L),o.pure(r),o.pure(U),o.pure(N),o.pure(!1),o.object(Ce)],S=[H.poolCoinA,H.poolCoinB],k=o.moveCall({target:`${t.sdkOptions.integrate.published_at}::${P}::${W}`,typeArguments:S,arguments:j});I=L?k[0]:k[1],C=L?k[1]:k[0]}else{let L=r?D.amountIn:D.rawAmountLimit[0],H=r?0:D.amountOut,W="";D.a2b[0]?D.a2b[1]?W="swap_ab_bc":W="swap_ab_cb":D.a2b[1]?W="swap_ba_bc":W="swap_ba_cb",E||(W=`${W}_with_partner`);let K=yr.getDefaultSqrtPriceLimit(D.a2b[0]),F=yr.getDefaultSqrtPriceLimit(D.a2b[1]),U=E?[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)]:[o.object(l),o.object(D.poolAddress[0]),o.object(D.poolAddress[1]),o.pure(e.partner),I,C,o.pure(r),o.pure(L.toString()),o.pure(H.toString()),o.pure(K.toString()),o.pure(F.toString()),o.object(Ce)],N=[D.coinType[0],D.coinType[1],D.coinType[2]],j=o.moveCall({target:`${u.published_at}::${P}::${W}`,typeArguments:N,arguments:U});I=j[0],C=j[1]}return this.checkCoinThreshold(t,r,o,C,T,A),{fromCoin:I,toCoin:C,tx:o}}static async buildAggregatorSwapReturnCoins(t,e,r,n,i,o,s,u){if(u==null){if(t.senderAddress.length===0)throw Error("recipient and this config sdk senderAddress all not set");u=t.senderAddress}e.splitPaths.length>1&&(i="");let l,d,b=e.splitPaths.some(_=>_.basePaths.some(T=>T.label==="Deepbook"));if((!e.byAmountIn||e.splitPaths.length===1)&&!b){let _=[];for(let A of e.splitPaths){let I=[],C=[],E=[],P=[];for(let L=0;L<A.basePaths.length;L+=1){let H=A.basePaths[L];I.push(H.direction),C.push(H.poolAddress),E.push(new Hn.default(H.inputAmount.toString())),L===0?P.push(H.fromCoin,H.toCoin):P.push(H.toCoin)}let D={amountIn:new Hn.default(A.inputAmount.toString()),amountOut:new Hn.default(A.outputAmount.toString()),poolAddress:C,a2b:I,rawAmountLimit:E,isExceed:!1,coinType:P};_.push(D)}let T={paths:_,partner:i,priceSlippagePoint:o},x=await this.buildRouterBasePathReturnCoins(t,T,e.byAmountIn,r,n,s);l=x.fromCoin,d=x.toCoin,s=x.tx}else{let _=Math.round(e.outputAmount*(1-o));l=r.targetCoin,n.isMintZeroCoin||n.originalSplitedCoin!==void 0?d=n.targetCoin:d=X.callMintZeroValueCoin(s,e.toCoin);let T=!1,x;if(b){let[A,I]=ql.createAccountCap(u,t.sdkOptions,s);s=I,x=A,T=!0}for(let A=0;A<e.splitPaths.length;A+=1){let I=e.splitPaths[A],C;for(let E=0;E<I.basePaths.length;E+=1){let P=I.basePaths[E];if(P.label==="Deepbook")if(E===0)if(I.basePaths.length===1){let D=this.buildDeepbookBasePathTx(t,P,s,x,l,d,!1);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildDeepbookBasePathTx(t,P,s,x,l,C,!1);l=D.from,C=D.to}else{let D=this.buildDeepbookBasePathTx(t,P,s,x,C,d,!0);C=D.from,d=D.to}if(P.label==="Cetus")if(E===0)if(I.basePaths.length===1){let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,d,!1,i);l=D.from,d=D.to}else{C=X.callMintZeroValueCoin(s,P.toCoin);let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,l,C,!1,i);l=D.from,C=D.to}else{let D=this.buildClmmBasePathTx(t,P,s,e.byAmountIn,C,d,!0,i);C=D.from,d=D.to,s.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::send_coin`,typeArguments:[P.fromCoin],arguments:[C,s.pure(u)]})}}}this.checkCoinThreshold(t,e.byAmountIn,s,d,_,e.toCoin),T&&(s=ql.deleteAccountCapByObject(x,t.sdkOptions,s))}return{fromCoin:l,toCoin:d,tx:s}}static async buildAggregatorSwapTransaction(t,e,r,n,i,o){let s=new Lr.TransactionBlock,u=e.byAmountIn?Math.round(e.outputAmount*(1-i)):Math.round(e.inputAmount*(1+i)),l=X.buildCoinForAmount(s,r,e.byAmountIn?BigInt(e.inputAmount):BigInt(u),e.fromCoin,!1,!0),d=l.originalSplitedCoin!=null,b=X.buildCoinForAmount(s,r,0n,e.toCoin,!1),_=await this.buildAggregatorSwapReturnCoins(t,e,l,b,n,i,s,o),{fromCoin:T,toCoin:x}=_;s=_.tx;let A=[];if(b.isMintZeroCoin?A.push({coinType:e.toCoin,coin:x}):b.originalSplitedCoin!=null?s.mergeCoins(b.originalSplitedCoin,[x]):s.mergeCoins(b.targetCoin,[x]),d){let I=l.originalSplitedCoin;s.mergeCoins(I,[T])}else A.push({coinType:e.fromCoin,coin:T});for(let I=0;I<A.length;I++)this.buildTransferCoin(t,s,A[I].coin,A[I].coinType,o);return s}static checkCoinThreshold(t,e,r,n,i,o){e&&r.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Wn}::check_coin_threshold`,typeArguments:[o],arguments:[n,r.pure(i)]})}static buildDeepbookBasePathTx(t,e,r,n,i,o,s){let u=e.direction?i:o,l=e.direction?o:i,d=[r.object(e.poolAddress),n,r.pure(e.inputAmount),r.pure(0),r.pure(e.direction),u,l,r.pure(s),r.object(Ce)],b=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],_=r.moveCall({target:`${t.sdkOptions.deepbook_endpoint_v2.published_at}::endpoints_v2::swap`,typeArguments:b,arguments:d});return i=e.direction?_[0]:_[1],o=e.direction?_[1]:_[0],{from:i,to:o,tx:r}}static buildClmmBasePathTx(t,e,r,n,i,o,s,u){let{clmm_pool:l,integrate:d}=t.sdkOptions,b=be(l).global_config_id,_=e.direction?i:o,T=e.direction?o:i,x=u==="",A=x?Wn:da,I=x?"swap":"swap_with_partner",C=n?e.inputAmount.toString():e.outputAmount.toString(),E=yr.getDefaultSqrtPriceLimit(e.direction),P=x?[r.object(b),r.object(e.poolAddress),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)]:[r.object(b),r.object(e.poolAddress),r.pure(u),_,T,r.pure(e.direction),r.pure(n),r.pure(C),r.pure(E.toString()),r.pure(s),r.object(Ce)],D=e.direction?[e.fromCoin,e.toCoin]:[e.toCoin,e.fromCoin],L=r.moveCall({target:`${d.published_at}::${A}::${I}`,typeArguments:D,arguments:P});return _=L[0],T=L[1],i=e.direction?_:T,o=e.direction?T:_,{from:i,to:o,tx:r}}static buildCoinTypePair(t,e){let r=[];if(t.length===2){let n=[];n.push(t[0],t[1]),r.push(n)}else{let n=[];n.push(t[0],t[t.length-1]),r.push(n);for(let i=1;i<t.length-1;i+=1){if(e[i-1]===0)continue;let o=[];o.push(t[0],t[i],t[t.length-1]),r.push(o)}}return r}static buildTransferCoinToSender(t,e,r,n){e.moveCall({target:`${t.sdkOptions.integrate.published_at}::${Dl}::transfer_coin_to_sender`,typeArguments:[n],arguments:[r]})}static buildTransferCoin(t,e,r,n,i){i!=null?e.transferObjects([r],e.pure(i)):X.buildTransferCoinToSender(t,e,r,n)}},Pe=X;kg(Pe,"callMintZeroValueCoin",(t,e)=>t.moveCall({target:"0x2::coin::zero",typeArguments:[e]}));function kt(t){return!(!t.startsWith("0x")||t.length!==66)}var gn=new bt.default(1e9),ql=class{static createAccountCap(t,e,r,n=!1){if(t.length===0)throw Error("this config sdk senderAddress is empty");let{deepbook:i}=e,[o]=r.moveCall({target:`${i.published_at}::${Pg}::create_account`,typeArguments:[],arguments:[]});return n&&r.transferObjects([o],r.pure(t)),[o,r]}static deleteAccountCap(t,e,r){let{deepbook:n}=e,i=[r.pure(t)];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static deleteAccountCapByObject(t,e,r){let{deepbook:n}=e,i=[t];return r.moveCall({target:`${n.published_at}::${fa}::delete_account_cap`,typeArguments:[],arguments:i}),r}static async getAccountCap(t){let e=await t.fullClient.getOwnedObjectsByPage(t.senderAddress,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{MoveModule:{package:t.sdkOptions.deepbook.package_id,module:fa}}});return e.data.length===0?"":e.data[0].data.objectId}static async getPools(t){let e=t.sdkOptions.deepbook.package_id,r=[];try{(await t.fullClient.queryEventsByPage({MoveEventType:`${e}::clob_v2::PoolCreated`})).data.forEach(i=>{let o=i.parsedJson;o&&r.push({poolID:o.pool_id,tickSize:Number(o.tick_size),lotSize:Number(o.lot_size),takerFeeRate:Number(o.taker_fee_rate),makerRebateRate:Number(o.maker_rebate_rate),baseAsset:o.base_asset.name,quoteAsset:o.quote_asset.name})})}catch(n){console.log("getPoolImmutables",n)}return r}static async getPoolAsks(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_ask_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>se(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async getPoolBids(t,e,r,n){let{simulationAccount:i}=t.sdkOptions,{deepbook_endpoint_v2:o}=t.sdkOptions,s=new po.TransactionBlock,u=[],l=[r,n],d=[s.pure(e),s.pure("0"),s.pure("999999999999"),s.pure(Ce)];s.moveCall({target:`${o.published_at}::endpoints_v2::get_level2_book_status_bid_side`,arguments:d,typeArguments:l});let _=(await t.fullClient.devInspectTransactionBlock({transactionBlock:s,sender:i.address})).events?.filter(T=>se(T.type).name==="BookStatus");if(_.length===0)return u;for(let T=0;T<_[0].parsedJson.depths.length;T++){let x=_[0].parsedJson.price[T],A=_[0].parsedJson.depths[T],I={price:parseInt(x,10),quantity:parseInt(A,10)};u.push(I)}return u}static async preSwap(t,e,r,n){let i=!1,o=Y,s=new bt.default(n),u=Y,l=new bt.default(n);if(r){let d=await this.getPoolBids(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0),d=d.sort((b,_)=>_.price-b.price);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].quantity),T=new bt.default(d[b].price),x=_.mul(new bt.default(T)).mul(new bt.default(e.takerFeeRate)).div(gn).div(gn);if(s.gt(_))s=s.sub(_),o=o.add(_.mul(T).div(gn).sub(x)),u=u.add(x);else{let A=s.mul(new bt.default(d[b].price)).div(gn),I=A.mul(new bt.default(e.takerFeeRate)).div(gn);o=o.add(A.sub(I)),s=s.sub(s),u=u.add(I)}if(s.eq(Y))break}}else{let d=await this.getPoolAsks(t,e.poolID,e.baseAsset,e.quoteAsset);d===null&&(i=!0);for(let b=0;b<d.length;b+=1){let _=new bt.default(d[b].price).mul(new bt.default(d[b].quantity)).div(new bt.default(1e9)),T=_.mul(new bt.default(e.takerFeeRate)).div(gn),x=_.add(T);if(s.gt(_))o=o.add(new bt.default(d[b].quantity)),s=s.sub(x),u=u.add(T);else{let A=new bt.default(d[b].quantity).div(new bt.default(e.lotSize)),I=x.div(A),C=s.div(I);o=o.add(C.muln(e.lotSize)),s=s.sub(C.mul(I)),u=u.add(C.div(A).mul(T))}if(s.eq(Y))break}}return{poolAddress:e.poolID,estimatedAmountIn:l.sub(s).toNumber(),estimatedAmountOut:o.toNumber(),estimatedFeeAmount:u,isExceed:i,amount:Number(n),aToB:r,byAmountIn:!0}}static async simulateSwap(t,e,r,n,i,o){let{deepbook_endpoint_v2:s}=t.sdkOptions,u=new po.TransactionBlock,l=await this.getAccountCap(t),d;if(l===""){let H=this.createAccountCap(t.senderAddress,t.sdkOptions,u),W=H[0];u=H[1],d=W}else d=u.pure(l);let b=await t.getOwnerCoinAssets(t.senderAddress),T=Pe.buildCoinForAmount(u,b,BigInt(o),r,!1)?.targetCoin,A=Pe.buildCoinForAmount(u,b,BigInt(o),n,!1)?.targetCoin,I=[r,n],C=[u.pure(e),d,u.pure(o),u.pure(0),u.pure(i),T,A,u.pure(Ce)];u.moveCall({target:`${s.published_at}::${Dg}::swap`,arguments:C,typeArguments:I});let{simulationAccount:E}=t.sdkOptions,D=(await t.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:E.address})).events?.filter(H=>se(H.type).name==="DeepbookSwapEvent");if(D.length===0)return null;let L=D[0].parsedJson;return{poolAddress:L.pool,estimatedAmountIn:L.amount_in,estimatedAmountOut:L.amount_out,aToB:L.atob}}},b0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getPositionList(t,e="all"){let r={data:[],hasNextPage:!0},n=await this._sdk.fullClient.getDynamicFieldsByPage(t,e);r.hasNextPage=n.hasNextPage,r.nextCursor=n.nextCursor;let i=n.data.map(s=>{if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getPositionList get position objects error: ${s.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");return s.name.value}),o=await this._sdk.Position.getSipmlePositionList(i);return r.data=o,r}async getPoolImmutables(t=[],e=0,r=100,n=!1){let{package_id:i}=this._sdk.sdkOptions.clmm_pool,o=`${i}_getInitPoolEvent`,s=this.getCache(o,n),u=[],l=[];if(s!==void 0&&u.push(...s),u.length===0)try{(await this._sdk.fullClient.queryEventsByPage({MoveEventType:`${i}::factory::CreatePoolEvent`})).data.forEach(_=>{let T=_.parsedJson;T&&u.push({poolAddress:T.pool_id,tickSpacing:T.tick_spacing,coinTypeA:se(T.coin_type_a).full_address,coinTypeB:se(T.coin_type_b).full_address})}),this.updateCache(o,u,Oe)}catch(b){console.log("getPoolImmutables",b)}let d=t.length>0;for(let b=0;b<u.length;b+=1){let _=u[b];d&&!t.includes(_.poolAddress)||!d&&(b<e||b>=e+r)||l.push(_)}return l}async getPools(t=[],e=0,r=100){let n=[],i=[];t.length>0?i=[...t]:(await this.getPoolImmutables([],e,r,!1)).forEach(u=>i.push(u.poolAddress));let o=await this._sdk.fullClient.batchGetObjects(i,{showContent:!0,showType:!0});for(let s of o){if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`getPools error code: ${s.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let u=ha(s);n.push(u);let l=`${u.poolAddress}_getPoolObject`;this.updateCache(l,u,Oe)}return n}async getPoolImmutablesWithPage(t="all",e=!1){let{package_id:r}=this._sdk.sdkOptions.clmm_pool,n=[],i={data:[],hasNextPage:!1},o=t==="all",s=`${r}_getPoolImmutables`;if(o){let u=this.getCache(s,e);u&&n.push(...u)}if(n.length===0)try{let u=`${r}::factory::CreatePoolEvent`,l=await this._sdk.fullClient.queryEventsByPage({MoveEventType:u},t);i.hasNextPage=l.hasNextPage,i.nextCursor=l.nextCursor,l.data.forEach(d=>{let b=d.parsedJson;if(b){let _={poolAddress:b.pool_id,tickSpacing:b.tick_spacing,coinTypeA:se(b.coin_type_a).full_address,coinTypeB:se(b.coin_type_b).full_address};n.push(_)}})}catch(u){console.log("getPoolImmutables",u)}return i.data=n,o&&this.updateCache(`${r}_getPoolImmutables`,n,Oe),i}async getPoolsWithPage(t=[]){let e=[],r=[];t.length>0?r=[...t]:(await this.getPoolImmutablesWithPage()).data.forEach(o=>r.push(o.poolAddress));let n=await this._sdk.fullClient.batchGetObjects(r,{showContent:!0,showType:!0});for(let i of n){if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPoolWithPages error code: ${i.error?.code??"unknown error"}, please check config and object ids`,"InvalidPoolObject");let o=ha(i);e.push(o);let s=`${o.poolAddress}_getPoolObject`;this.updateCache(s,o,Oe)}return e}async getPool(t,e=!0){let r=`${t}_getPoolObject`,n=this.getCache(r,e);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:t,options:{showType:!0,showContent:!0}});if(i.error!=null||i.data?.content?.dataType!=="moveObject")throw new V(`getPool error code: ${i.error?.code??"unknown error"}, please check config and object id`,"InvalidPoolObject");let o=ha(i);return this.updateCache(r,o),o}async creatPoolsTransactionPayload(t){for(let r of t)if(jl((0,zn.normalizeSuiAddress)(r.coinTypeA),(0,zn.normalizeSuiAddress)(r.coinTypeB))){let n=r.coinTypeB;r.coinTypeB=r.coinTypeA,r.coinTypeA=n}return await this.creatPool(t)}async creatPoolTransactionPayload(t){if(jl((0,zn.normalizeSuiAddress)(t.coinTypeA),(0,zn.normalizeSuiAddress)(t.coinTypeB))){let e=t.coinTypeB;t.coinTypeB=t.coinTypeA,t.coinTypeA=e}return"fix_amount_a"in t?await this.creatPoolAndAddLiquidity(t):await this.creatPool([t])}async getClmmConfigs(t=!1){let{package_id:e}=this._sdk.sdkOptions.clmm_pool,r=`${e}_getInitEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=(await this._sdk.fullClient.queryEventsByPage({Transaction:o})).data,u={pools_id:"",global_config_id:"",global_vault_id:"",admin_cap_id:""};return s.length>0&&(s.forEach(l=>{let d=l.parsedJson;if(l.type)switch(se(l.type).full_address){case`${e}::config::InitConfigEvent`:u.global_config_id=d.global_config_id,u.admin_cap_id=d.admin_cap_id;break;case`${e}::factory::InitFactoryEvent`:u.pools_id=d.pools_id;break;case`${e}::rewarder::RewarderInitEvent`:u.global_vault_id=d.global_vault_id;break;case`${e}::partner::InitPartnerEvent`:u.partners_id=d.partners_id;break;default:break}}),this.updateCache(r,u,Oe)),u}async getSuiTransactionResponse(t,e=!1){let r=`${t}_getSuiTransactionResponse`,n=this.getCache(r,e);if(n!==void 0)return n;let i;try{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{i=await this._sdk.fullClient.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,i,Oe),i}async creatPool(t){let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id;return t.forEach(u=>{let l=[e.object(o),e.object(s),e.pure(u.tick_spacing.toString()),e.pure(u.initialize_sqrt_price),e.pure(u.uri),e.object(Ce)];e.moveCall({target:`${r.published_at}::${fo}::create_pool`,typeArguments:[u.coinTypeA,u.coinTypeB],arguments:l})}),e}async creatPoolAndAddLiquidity(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=new wn.TransactionBlock,{integrate:r,clmm_pool:n}=this.sdk.sdkOptions,i=be(n),o=i.global_config_id,s=i.pools_id,u=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),l=Pe.buildAddLiquidityFixTokenCoinInput(e,!t.fix_amount_a,t.amount_a,t.slippage,t.coinTypeA,u,!1),d=Pe.buildAddLiquidityFixTokenCoinInput(e,t.fix_amount_a,t.amount_b,t.slippage,t.coinTypeB,u,!1),b=[e.pure(o),e.pure(s),e.pure(t.tick_spacing.toString()),e.pure(t.initialize_sqrt_price),e.pure(t.uri),l.targetCoin,d.targetCoin,e.pure(Vt(BigInt(t.tick_lower)).toString()),e.pure(Vt(BigInt(t.tick_upper)).toString()),e.pure(t.amount_a),e.pure(t.amount_b),e.pure(t.fix_amount_a),e.pure(Ce)];return e.moveCall({target:`${r.published_at}::${Gr}::create_pool_with_liquidity`,typeArguments:[t.coinTypeA,t.coinTypeB],arguments:b}),e}async fetchTicks(t){let e=[],r=[];for(;;){let i=await this.getTicks({pool_id:t.pool_id,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,start:r,limit:512});if(e=[...e,...i],i.length<512)break;r=[i[i.length-1].index]}return e}async getTicks(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[t.coinTypeA,t.coinTypeB],o=new wn.TransactionBlock,s=[o.pure(t.pool_id),o.pure(t.start),o.pure(t.limit.toString())];if(o.moveCall({target:`${e.published_at}::${Vr}::fetch_ticks`,arguments:s,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let u=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:o,sender:r.address});if(u.error!=null)throw new V(`getTicks error code: ${u.error??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return u.events?.forEach(l=>{se(l.type).name==="FetchTicksResultEvent"&&l.parsedJson.ticks.forEach(d=>{n.push(p0(d))})}),n}async fetchPositionRewardList(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=[],i=[],o=512;for(;;){let s=[t.coinTypeA,t.coinTypeB],u=new wn.TransactionBlock,l=[u.object(t.pool_id),u.pure(i,"u64"),u.pure(o.toString(),"u64")];if(u.moveCall({target:`${e.published_at}::${Vr}::fetch_positions`,arguments:l,typeArguments:s}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let d=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:u,sender:r.address});if(d.error!=null)throw new V(`fetch position reward error code: ${d.error??"unknown error"}, please check config and tick object ids`,"InvalidPositionRewardObject");let b=[];if(d?.events?.forEach(_=>{se(_.type).name==="FetchPositionsEvent"&&_.parsedJson.positions.forEach(T=>{let x=Jl(T);b.push(x)})}),n.push(...b),b.length<o)break;i=[b[b.length-1].pos_object_id]}return n}async fetchTicksByRpc(t){let e=[],r=null,n=512;for(;;){let i=[],o=await this.sdk.fullClient.getDynamicFields({parentId:t,cursor:r,limit:n});if(r=o.nextCursor,o.data.forEach(s=>{se(s.objectType).module==="skip_list"&&i.push(s.objectId)}),e=[...e,...await this.getTicksByRpc(i)],r===null||o.data.length<n)break}return e}async getTicksByRpc(t){let e=[],r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0,showType:!0});for(let n of r){if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${n.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");let i=ma(n);i!=null&&e.push(i)}return e}async getTickDataByIndex(t,e){let r={type:"u64",value:Vt(BigInt($g(e).toString())).toString()},n=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:r});if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`get tick by index: ${e} error: ${n.error}`,"InvalidTickIndex");return ma(n)}async getTickDataByObjectId(t){let e=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0}});if(e.error!=null||e.data?.content?.dataType!=="moveObject")throw new V(`getTicksByRpc error code: ${e.error?.code??"unknown error"}, please check config and tick object ids`,"InvalidTickObjectId");return ma(e)}async getPartnerRefFeeAmount(t){let e=await this._sdk.fullClient.batchGetObjects([t],{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0});if(e[0].error!=null||e[0].data?.content?.dataType!=="moveObject")throw new V(`get partner by object id: ${t} error: ${e[0].error}`,"NotFoundPartnerObject");let r=e[0].data.content.fields.balances,n=await this._sdk.fullClient.getDynamicFieldsByPage(r.fields.id.id),i=[];n.data.forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`when getPartnerRefFeeAmount get partner object error: ${u.error}, please check the rpc, contracts address config and position id.`,"InvalidConfig");i.push(u.objectId)});let o=[];return(await this._sdk.fullClient.batchGetObjects(i,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(u=>{if(u.error!=null||u.data?.content?.dataType!=="moveObject")throw new V(`get coin by object id: ${u.data.objectId} error: ${u.error}`,"InvalidParnterRefFeeFields");let l={coinAddress:u.data.content.fields.name,coinObjectId:u.data.objectId,balance:BigInt(u.data.content.fields.value)};o.push(l)}),o}async claimPartnerRefFeePayload(t,e,r){let n=new wn.TransactionBlock,{clmm_pool:i}=this.sdk.sdkOptions,{global_config_id:o}=be(i),s=[r],u=[n.object(o),n.object(t),n.object(e)];return n.moveCall({target:`${i.published_at}::${Mg}::claim_ref_fee`,arguments:u,typeArguments:s}),n}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},_0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}buildPositionType(){return`${this._sdk.sdkOptions.clmm_pool.package_id}::position::Position`}async getPositionList(t,e=[]){let r=[],n=await this._sdk.fullClient.getOwnedObjectsByPage(t,{options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0},filter:{Package:this._sdk.sdkOptions.clmm_pool.package_id}}),i=e.length>0;for(let o of n.data)if(se(o.data.type).full_address===this.buildPositionType()){let u=pa(o),l=`${u.pos_object_id}_getPositionList`;this.updateCache(l,u,Oe),i?e.includes(u.pool)&&r.push(u):r.push(u)}return r}async getPosition(t,e,r=!0){let n=await this.getSimplePosition(e);return r&&(n=await this.updatePositionRewarders(t,n)),n}async getPositionById(t,e=!0){let r=await this.getSimplePosition(t);if(e){let n=await this._sdk.Pool.getPool(r.pool,!1);return await this.updatePositionRewarders(n.position_manager.positions_handle,r)}return r}async getSimplePosition(t){let e=`${t}_getPositionList`,r=this.getSimplePositionByCache(t);if(r===void 0){let n=await this.sdk.fullClient.getObject({id:t,options:{showContent:!0,showType:!0,showDisplay:!0,showOwner:!0}});r=pa(n),this.updateCache(e,r,Oe)}return r}getSimplePositionByCache(t){let e=`${t}_getPositionList`;return this.getCache(e)}async getSipmlePositionList(t){let e=[],r=[];return t.forEach(n=>{let i=this.getSimplePositionByCache(n);i?e.push(i):r.push(n)}),r.length>0&&(await this._sdk.fullClient.batchGetObjects(r,{showOwner:!0,showContent:!0,showDisplay:!0,showType:!0})).forEach(i=>{let o=pa(i);e.push(o);let s=`${o.pos_object_id}_getPositionList`;this.updateCache(s,o,Oe)}),e}async updatePositionRewarders(t,e){let r=await this.getPositionRewarders(t,e.pos_object_id);return{...e,...r}}async getPositionRewarders(t,e){try{let r=await this._sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}}),i=br(r.data).value.fields.value;return Jl(i)}catch(r){console.log(r);return}}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new Ur.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position fee error code: ${o.error??"unknown error"}, please check config and postion and pool object ids`,"InvalidPoolObject");let s=o.events?.filter(l=>se(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new ga.default(d.fee_owned_a),feeOwedB:new ga.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async createAddLiquidityFixTokenPayload(t,e){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t=t,t.fix_amount_a&&n||!t.fix_amount_a&&i)return await Pe.buildAddLiquidityFixTokenForGas(this._sdk,r,t,e)}return Pe.buildAddLiquidityFixToken(this._sdk,r,t)}async createAddLiquidityPayload(t){let{integrate:e,clmm_pool:r}=this._sdk.sdkOptions;if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let n=Vt(BigInt(t.tick_lower)).toString(),i=Vt(BigInt(t.tick_upper)).toString(),o=[t.coinTypeA,t.coinTypeB],s=new Ur.TransactionBlock,u=!(0,Xl.isValidSuiObjectId)(t.pos_id),l=BigInt(t.max_amount_a),d=BigInt(t.max_amount_b),b=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress),_=Pe.buildCoinForAmount(s,b,l,t.coinTypeA,!1),T=Pe.buildCoinForAmount(s,b,d,t.coinTypeB,!1);return u?s.moveCall({target:`${e.published_at}::${Gr}::open_position_with_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.pure(n),s.pure(i),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]}):(s=Pe.createCollectRewarderAndFeeParams(this._sdk,s,t,b,_.remainCoins,T.remainCoins),s.moveCall({target:`${e.published_at}::${Gr}::add_liquidity`,typeArguments:o,arguments:[s.object(be(r).global_config_id),s.object(t.pool_id),s.object(t.pos_id),_.targetCoin,T.targetCoin,s.pure(t.max_amount_a),s.pure(t.max_amount_b),s.pure(t.delta_liquidity),s.object(Ce)]})),s}async removeLiquidityTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n="remove_liquidity",i=new Ur.TransactionBlock,o=[t.coinTypeA,t.coinTypeB],s=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);i=Pe.createCollectRewarderAndFeeParams(this._sdk,i,t,s);let u=[i.object(be(e).global_config_id),i.object(t.pool_id),i.object(t.pos_id),i.pure(t.delta_liquidity),i.pure(t.min_amount_a),i.pure(t.min_amount_b),i.object(Ce)];return i.moveCall({target:`${r.published_at}::${fo}::${n}`,typeArguments:o,arguments:u}),i}async closePositionTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);return n=Pe.createCollectRewarderAndFeeParams(this._sdk,n,t,o),n.moveCall({target:`${r.published_at}::${fo}::close_position`,typeArguments:i,arguments:[n.object(be(e).global_config_id),n.object(t.pool_id),n.object(t.pos_id),n.pure(t.min_amount_a),n.pure(t.min_amount_b),n.object(Ce)]}),n}openPositionTransactionPayload(t){let{clmm_pool:e,integrate:r}=this.sdk.sdkOptions,n=new Ur.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=Vt(BigInt(t.tick_lower)).toString(),s=Vt(BigInt(t.tick_upper)).toString(),u=[n.pure(be(e).global_config_id),n.pure(t.pool_id),n.pure(o),n.pure(s)];return n.moveCall({target:`${r.published_at}::${fo}::open_position`,typeArguments:i,arguments:u}),n}async collectFeeTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null,!0),r=new Ur.TransactionBlock,n=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeA,!1),i=Pe.buildCoinForAmount(r,e,BigInt(0),t.coinTypeB,!1);return this.createCollectFeePaylod(t,r,n.targetCoin,i.targetCoin),r}createCollectFeePaylod(t,e,r,n){let{clmm_pool:i,integrate:o}=this.sdk.sdkOptions,s=[t.coinTypeA,t.coinTypeB],u=[e.object(be(i).global_config_id),e.object(t.pool_id),e.object(t.pos_id),r,n];return e.moveCall({target:`${o.published_at}::${Gr}::collect_fee`,typeArguments:s,arguments:u}),e}async calculateFee(t){let e=await this.collectFeeTransactionPayload(t);if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let r=await this._sdk.fullClient.devInspectTransactionBlock({transactionBlock:e,sender:this._sdk.senderAddress});for(let n of r.events)if(se(n.type).name==="CollectFeeEvent"){let i=n.parsedJson;return{feeOwedA:i.amount_a,feeOwedB:i.amount_b}}return{feeOwedA:"0",feeOwedB:"0"}}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},v0=class{_sdk;growthGlobal;constructor(t){this._sdk=t,this.growthGlobal=[Y,Y,Y]}get sdk(){return this._sdk}async emissionsEveryDay(t){let r=(await this.sdk.Pool.getPool(t)).rewarder_infos;if(!r)return null;let n=[];for(let i of r){let o=fe.fromX64(new Se.default(i.emissions_per_second));n.push({emissions:Math.floor(o.toNumber()*60*60*24),coin_address:i.coinAddress})}return n}async updatePoolRewarder(t,e){let r=await this.sdk.Pool.getPool(t),n=r.rewarder_last_updated_time;if(r.rewarder_last_updated_time=e.toString(),Number(r.liquidity)===0||e.eq(new Se.default(n)))return r;let i=e.div(new Se.default(1e3)).sub(new Se.default(n)).add(new Se.default(15)),o=r.rewarder_infos;for(let s=0;s<o.length;s+=1){let u=o[s],l=fe.checkMulDivFloor(i,new Se.default(u.emissions_per_second),new Se.default(r.liquidity),128);this.growthGlobal[s]=new Se.default(u.growth_global).add(new Se.default(l))}return r}async posRewardersAmount(t,e,r){let n=Date.parse(new Date().toString()),i=await this.updatePoolRewarder(t,new Se.default(n)),o=await this.sdk.Position.getPositionRewarders(e,r);if(o===void 0)return[];let s=i.ticks_handle,u=await this.sdk.Pool.getTickDataByIndex(s,o.tick_lower_index),l=await this.sdk.Pool.getTickDataByIndex(s,o.tick_upper_index);return this.posRewardersAmountInternal(i,o,u,l)}async poolRewardersAmount(t,e){let r=Date.parse(new Date().toString()),n=await this.updatePoolRewarder(e,new Se.default(r)),i=await this.sdk.Position.getPositionList(t,[e]),o=await this.getPoolLowerAndUpperTicks(n.ticks_handle,i),s=[Y,Y,Y];for(let u=0;u<i.length;u+=1){let l=await this.posRewardersAmountInternal(n,i[u],o[0][u],o[1][u]);for(let d=0;d<3;d+=1)s[d]=s[d].add(l[d].amount_owed)}return s}posRewardersAmountInternal(t,e,r,n){let i=e.tick_lower_index,o=e.tick_upper_index,s=m0(t,r,n,i,o,this.growthGlobal),u=[],l=[];if(s.length>0){let d=fe.subUnderflowU128(s[0],new Se.default(e.reward_growth_inside_0));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[0]),l.push({amount_owed:new Se.default(e.reward_amount_owed_0).add(b),coin_address:t.rewarder_infos[0].coinAddress})}if(s.length>1){let d=fe.subUnderflowU128(s[1],new Se.default(e.reward_growth_inside_1));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[1]),l.push({amount_owed:new Se.default(e.reward_amount_owed_1).add(b),coin_address:t.rewarder_infos[1].coinAddress})}if(s.length>2){let d=fe.subUnderflowU128(s[2],new Se.default(e.reward_growth_inside_2));d.gt(new Se.default("3402823669209384634633745948738404"))&&(d=Qt);let b=fe.checkMulShiftRight(new Se.default(e.liquidity),d,64,128);u.push(s[2]),l.push({amount_owed:new Se.default(e.reward_amount_owed_2).add(b),coin_address:t.rewarder_infos[2].coinAddress})}return l}async batchFetchPositionRewarders(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB,rewarderInfo:o.rewarder_infos})}let r={};if(e.length>0){let n=await this.fetchPosRewardersAmount(e);for(let i of n)r[i.positionId]=i.rewarderAmountOwed;return r}return r}async fetchPositionRewarders(t,e){let r={poolAddress:t.poolAddress,positionId:e,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB,rewarderInfo:t.rewarder_infos};return(await this.fetchPosRewardersAmount([r]))[0].rewarderAmountOwed}async batchFetchPositionFees(t){let e=[];for(let n of t){let i=await this._sdk.Position.getPositionById(n,!1),o=await this._sdk.Pool.getPool(i.pool,!1);e.push({poolAddress:o.poolAddress,positionId:i.pos_object_id,coinTypeA:o.coinTypeA,coinTypeB:o.coinTypeB})}let r={};if(e.length>0){let n=await this.fetchPosFeeAmount(e);for(let i of n)r[i.position_id]=i;return r}return r}async fetchPosFeeAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_fees`,arguments:b,typeArguments:d})}let s=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address})).events?.filter(l=>se(l.type).name==="FetchPositionFeesEvent");if(s.length===0)return[];let u=[];for(let l=0;l<s.length;l+=1){let{parsedJson:d}=s[l],b={feeOwedA:new Se.default(d.fee_owned_a),feeOwedB:new Se.default(d.fee_owned_b),position_id:d.position_id};u.push(b)}return u}async fetchPosRewardersAmount(t){let{clmm_pool:e,integrate:r,simulationAccount:n}=this.sdk.sdkOptions,i=new mo.TransactionBlock;for(let l of t){let d=[l.coinTypeA,l.coinTypeB],b=[i.object(be(e).global_config_id),i.object(l.poolAddress),i.pure(l.positionId),i.object(Ce)];i.moveCall({target:`${r.published_at}::${Vr}::fetch_position_rewards`,arguments:b,typeArguments:d})}if(!kt(n.address))throw new V(`this config simulationAccount: ${n.address} is not set right`,"InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:i,sender:n.address});if(o.error!=null)throw new V(`fetch position rewards error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(l=>se(l.type).name==="FetchPositionRewardsEvent");if(s.length===0)return[];if(s.length!==t.length)throw new V("valueData.length !== params.pools.length");let u=[];for(let l=0;l<s.length;l+=1){let d={poolAddress:t[l].poolAddress,positionId:t[l].positionId,rewarderAmountOwed:[]};for(let b=0;b<t[l].rewarderInfo.length;b+=1)d.rewarderAmountOwed.push({amount_owed:new Se.default(s[l].parsedJson.data[b]),coin_address:t[l].rewarderInfo[b].coinAddress});u.push(d)}return u}async fetchPoolRewardersAmount(t,e){let r=await this.sdk.Pool.getPool(e),n=await this.sdk.Position.getPositionList(t,[e]),i=[];for(let u of n)i.push({poolAddress:r.poolAddress,positionId:u.pos_object_id,rewarderInfo:r.rewarder_infos,coinTypeA:r.coinTypeA,coinTypeB:r.coinTypeB});let o=await this.fetchPosRewardersAmount(i),s=[Y,Y,Y];if(o!=null)for(let u of o)for(let l=0;l<u.rewarderAmountOwed.length;l+=1)s[l]=s[l].add(u.rewarderAmountOwed[l].amount_owed);return s}async getPoolLowerAndUpperTicks(t,e){let r=[],n=[];for(let i of e){let o=await this.sdk.Pool.getTickDataByIndex(t,i.tick_lower_index),s=await this.sdk.Pool.getTickDataByIndex(t,i.tick_upper_index);r.push(o),n.push(s)}return[r,n]}async collectRewarderTransactionPayload(t){if(!kt(this._sdk.senderAddress))throw new V("this config sdk senderAddress is not set right","InvalidSendAddress");let e=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress,null),r=new mo.TransactionBlock;return r=Pe.createCollectRewarderAndFeeParams(this._sdk,r,t,e),r}createCollectRewarderPaylod(t,e,r){let{clmm_pool:n,integrate:i}=this.sdk.sdkOptions,o=be(n),s=[t.coinTypeA,t.coinTypeB];return t.rewarder_coin_types.forEach((u,l)=>{e&&e.moveCall({target:`${i.published_at}::${Gr}::collect_reward`,typeArguments:[...s,u],arguments:[e.object(o.global_config_id),e.object(t.pool_id),e.object(t.pos_id),e.object(o.global_vault_id),r[l],e.object(Ce)]})}),e}};function lo(t,e){return{pair:`${t}-${e}`,reversePair:`${e}-${t}`}}var T0=class{graph;pathProviders;coinProviders;_coinAddressMap;poolAddressMap;_sdk;constructor(t){this.pathProviders=[],this.coinProviders={coins:[]},this.graph=new Wr.Graph(!1),this._coinAddressMap=new Map,this.poolAddressMap=new Map,this._sdk=t,this.getPoolAddressMapAndDirection=this.getPoolAddressMapAndDirection.bind(this),this.setCoinList=this.setCoinList.bind(this),this.loadGraph=this.loadGraph.bind(this),this.addCoinProvider=this.addCoinProvider.bind(this),this.addPathProvider=this.addPathProvider.bind(this),this.preRouterSwapA2B2C=this.preRouterSwapA2B2C.bind(this),this.price=this.price.bind(this),this.getPoolWithTVL=this.getPoolWithTVL.bind(this)}get sdk(){return this._sdk}getPoolAddressMapAndDirection(t,e){let{pair:r,reversePair:n}=lo(t,e),i=this.poolAddressMap.get(r);if(i!=null)return{addressMap:i,direction:!0};if(i=this.poolAddressMap.get(n),i!=null)return{addressMap:i,direction:!1}}setCoinList(){this.coinProviders.coins.forEach(t=>{this._coinAddressMap.set(t.address,t)})}loadGraph(t,e){this.addCoinProvider(t),this.addPathProvider(e),this.setCoinList(),this.pathProviders.forEach(r=>{let{paths:n}=r;n.forEach(i=>{let o=this.graph.getVertexByKey(i.base)??new Wr.GraphVertex(i.base),s=this.graph.getVertexByKey(i.quote)??new Wr.GraphVertex(i.quote);this.graph.addEdge(new Wr.GraphEdge(o,s));let u=this._coinAddressMap.get(i.base),l=this._coinAddressMap.get(i.quote);if(u!=null&&l!=null){let d=lo(i.base,i.quote).pair;this.poolAddressMap.set(d,i.addressMap)}})})}addPathProvider(t){for(let e=0;e<t.paths.length;e+=1){let{base:r,quote:n}=t.paths[e];r.localeCompare(n)<0&&(t.paths[e].base=n,t.paths[e].quote=r),r==="0x2::sui::SUI"&&(t.paths[e].base=n,t.paths[e].quote=r),n==="0x2::sui::SUI"&&(t.paths[e].base=r,t.paths[e].quote=n)}return this.pathProviders.push(t),this}addCoinProvider(t){return this.coinProviders=t,this}tokenInfo(t){return this._coinAddressMap.get(t)}getFeeRate(t,e,r){let n=lo(t,e).pair,i=this.poolAddressMap.get(n);if(i!=null){for(let[u,l]of i.entries())if(l===r)return u*100}let o=lo(t,e).reversePair,s=this.poolAddressMap.get(o);if(s!=null){for(let[u,l]of s.entries())if(l===r)return u*100}return 0}async price(t,e,r,n,i,o,s){let u=this.tokenInfo(t),l=this.tokenInfo(e);if(u===void 0||l===void 0)throw new V("From/To coin is undefined","InvalidCoin");let d=this.graph.getVertexByKey(u.address),b=this.graph.getVertexByKey(l.address),_=this.graph.findAllPath(d,b),T=Array.from(_);if(T.length===0)throw new V("No find valid path in coin graph","NotFoundPath");let x=[];for(let N=0;N<T.length;N+=1){let j=T[N];if(j.length>3)continue;let S=[],k=[],a=[],c=[];for(let m=0;m<j.length-1;m+=1){let y=j[m].value.toString(),p=j[m+1].value.toString(),h=this.getPoolAddressMapAndDirection(y,p),w=h?.addressMap,g=h?.direction;w!=null&&g!=null&&(k.push(g),S.push(y),S.push(p),w.forEach(f=>{m===0?a.push(f):c.push(f)}))}for(let m of a)if(c.length>0)for(let y of c){let p={stepNums:2,poolAB:m,poolBC:y,a2b:k[0],b2c:k[1],amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:S[3]};x.push(p)}else{let y={stepNums:1,poolAB:m,poolBC:void 0,a2b:k[0],b2c:void 0,amount:r,byAmountIn:n,coinTypeA:S[0],coinTypeB:S[1],coinTypeC:void 0};x.push(y)}}let A=x.filter(N=>N.stepNums===1),I=x.filter(N=>N.stepNums!==1),C=[];try{C=await this.getPoolWithTVL()}catch{C=[]}if(C.length>0){let N=new Map(C.map(j=>[j.poolAddress,j]));I.sort((j,S)=>{let k=0,a=0;if(N.has(j.poolAB)&&N.has(j.poolBC)){let c=N.get(j.poolAB),m=N.get(j.poolBC);k=Math.min(c.tvl,m.tvl)}if(N.has(S.poolAB)&&N.has(S.poolBC)){let c=N.get(S.poolAB),m=N.get(S.poolBC);a=Math.min(c.tvl,m.tvl)}return a-k})}if(x=[...A,...I],x.length===0){if(s!=null){let N=await this.sdk.Swap.preSwapWithMultiPool(s),j={amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),poolAddress:[N.poolAddress],a2b:[N.aToB],rawAmountLimit:n?[N.estimatedAmountOut]:[N.estimatedAmountIn],isExceed:N.isExceed,coinType:[t,e]},S={paths:[j],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(N.estimatedAmountIn),amountOut:new Et.default(N.estimatedAmountOut),paths:[j],a2b:N.aToB,b2c:void 0,byAmountIn:n,isExceed:N.isExceed,targetSqrtPrice:[N.estimatedEndSqrtPrice],currentSqrtPrice:[N.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:S}}throw new V("No parameters available for service downgrade","NoDowngradeNeedParams")}let E=await this.preRouterSwapA2B2C(x.slice(0,16));if(E==null){if(s!=null){let j=await this.sdk.Swap.preSwapWithMultiPool(s),S={amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),poolAddress:[j.poolAddress],a2b:[j.aToB],rawAmountLimit:n?[j.estimatedAmountOut]:[j.estimatedAmountIn],isExceed:j.isExceed,coinType:[t,e]},k={paths:[S],partner:o,priceSlippagePoint:i};return{amountIn:new Et.default(j.estimatedAmountIn),amountOut:new Et.default(j.estimatedAmountOut),paths:[S],a2b:j.aToB,b2c:void 0,byAmountIn:n,isExceed:j.isExceed,targetSqrtPrice:[j.estimatedEndSqrtPrice],currentSqrtPrice:[j.estimatedStartSqrtPrice],coinTypeA:t,coinTypeB:e,coinTypeC:void 0,createTxParams:k}}return{amountIn:Y,amountOut:Y,paths:[],a2b:!1,b2c:!1,byAmountIn:n,isExceed:!0,targetSqrtPrice:[],currentSqrtPrice:[],coinTypeA:"",coinTypeB:"",coinTypeC:void 0,createTxParams:void 0}}let P=E.index,D=x[P].poolBC!=null?[x[P].poolAB,x[P].poolBC]:[x[P].poolAB],L=n?[E.amountMedium,E.amountOut]:[E.amountIn,E.amountMedium],H=[];H.push(x[P].a2b),E.stepNum>1&&H.push(x[P].b2c);let W=[];W.push(x[P].coinTypeA),W.push(x[P].coinTypeB),E.stepNum>1&&W.push(x[P].coinTypeC);let K={amountIn:E.amountIn,amountOut:E.amountOut,poolAddress:D,a2b:H,rawAmountLimit:L,isExceed:E.isExceed,coinType:W},F={paths:[K],partner:o,priceSlippagePoint:i};return{amountIn:E.amountIn,amountOut:E.amountOut,paths:[K],a2b:x[P].a2b,b2c:E.stepNum>1?x[P].b2c:void 0,byAmountIn:n,isExceed:E.isExceed,targetSqrtPrice:E.targetSqrtPrice,currentSqrtPrice:E.currentSqrtPrice,coinTypeA:x[P].coinTypeA,coinTypeB:x[P].coinTypeB,coinTypeC:E.stepNum>1?x[P].coinTypeC:void 0,createTxParams:F}}async preRouterSwapA2B2C(t){if(t.length===0)return null;let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new Yl.TransactionBlock;for(let _ of t)if(_.stepNums>1){let T=[n.object(_.poolAB),n.object(_.poolBC),n.pure(_.a2b),n.pure(_.b2c),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=[];_.a2b?x.push(_.coinTypeA,_.coinTypeB):x.push(_.coinTypeB,_.coinTypeA),_.b2c?x.push(_.coinTypeB,_.coinTypeC):x.push(_.coinTypeC,_.coinTypeB),n.moveCall({target:`${e.published_at}::${Wn}::calculate_router_swap_result`,typeArguments:x,arguments:T})}else{let T=[n.pure(_.poolAB),n.pure(_.a2b),n.pure(_.byAmountIn),n.pure(_.amount.toString())],x=_.a2b?[_.coinTypeA,_.coinTypeB]:[_.coinTypeB,_.coinTypeA];n.moveCall({target:`${e.published_at}::${Eg}::get_expect_swap_result`,arguments:T,typeArguments:x})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=(await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address})).events?.filter(_=>se(_.type).name==="CalculatedRouterSwapResultEvent"||se(_.type).name==="ExpectSwapResultEvent");if(o.length===0)return null;let s=t[0].byAmountIn?Y:_n,u=0;for(let _=0;_<o.length;_+=1)if(!o[_].parsedJson.data.is_exceed)if(t[0].byAmountIn){let T=new Et.default(o[_].parsedJson.data.amount_out);T.gt(s)&&(u=_,s=T)}else{let T=t[_].stepNums>1?new Et.default(o[_].parsedJson.data.amount_in):new Et.default(o[_].parsedJson.data.amount_in).add(new Et.default(o[_].parsedJson.data.fee_amount));T.lt(s)&&(u=_,s=T)}let l=[],d=[];return t[u].stepNums>1?(d.push(o[u].parsedJson.data.target_sqrt_price_ab,o[u].parsedJson.data.target_sqrt_price_cd),l.push(o[u].parsedJson.data.current_sqrt_price_ab,o[u].parsedJson.data.current_sqrt_price_cd)):(d.push(o[u].parsedJson.data.after_sqrt_price),l.push(o[u].parsedJson.current_sqrt_price)),{index:u,amountIn:t[0].byAmountIn?t[u].amount:s,amountMedium:o[u].parsedJson.data.amount_medium,amountOut:t[0].byAmountIn?s:t[u].amount,targetSqrtPrice:d,currentSqrtPrice:l,isExceed:o[u].parsedJson.data.is_exceed,stepNum:t[u].stepNums}}async getPoolWithTVL(){let t=[],{swapCountUrl:e}=this._sdk.sdkOptions;if(!e)return t;let r;try{r=await fetch(e)}catch{throw new V(`Failed to get pool list with liquidity from ${e}.`,"InvalidSwapCountUrl")}let n;try{n=await r.json()}catch{throw new V(`Failed tp [arse response from ${e}].`,"InvalidSwapCountUrl")}if(n.code!==200)throw new V(`Failed to get pool list from ${e}. Statu code is ${n.code}.`,"InvalidSwapCountUrl");let{pools:i}=n.data;for(let o of i)t.push({poolAddress:o.swap_account,tvl:Number(o.tvl_in_usd)});return t}};var S0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculateSwapFee(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n>0){let i=r.basePaths[0],o=i.label==="Cetus"?new $(i.feeRate).div(10**6):new $(i.feeRate).div(10**9),s=vt(i.inputAmount).div(10**i.fromDecimal).mul(o);if(e=e.add(s),n>1){let u=r.basePaths[1],l=i.direction?i.currentPrice:new $(1).div(i.currentPrice),d=u.direction?u.currentPrice:new $(1).div(u.currentPrice),b=u.label==="Cetus"?new $(u.feeRate).div(10**6):new $(u.feeRate).div(10**9),T=vt(u.outputAmount).div(10**u.toDecimal).mul(b).div(l.mul(d));e=e.add(T)}}}),e.toString()}calculateSwapPriceImpact(t){let e=vt(0);return t.forEach(r=>{let n=r.basePaths.length;if(n===1){let i=r.basePaths[0],o=vt(i.outputAmount).div(10**i.toDecimal),s=vt(i.inputAmount).div(10**i.fromDecimal),u=o.div(s),l=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice);e=e.add(this.calculateSingleImpact(u,l))}if(n===2){let i=r.basePaths[0],o=r.basePaths[1],s=i.direction?new $(i.currentPrice):new $(1).div(i.currentPrice),u=o.direction?new $(o.currentPrice):new $(1).div(o.currentPrice),l=s.mul(u),d=new $(o.outputAmount).div(10**o.toDecimal),b=new $(i.inputAmount).div(10**i.fromDecimal),_=d.div(b);e=e.add(this.calculateSingleImpact(_,l))}}),e.toString()}calculateSingleImpact=(t,e)=>e.minus(t).div(e).mul(100);async preSwapWithMultiPool(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB];for(let d=0;d<t.poolAddresses.length;d+=1){let b=[n.pure(t.poolAddresses[d]),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:b,typeArguments:i})}if(!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let o=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(o.error!=null)throw new V(`pre swap with multi pools error code: ${o.error??"unknown error"}, please check config and params`,"InvalidConfig");let s=o.events?.filter(d=>se(d.type).name==="CalculatedSwapResultEvent");if(s.length===0)return null;if(s.length!==t.poolAddresses.length)throw new V("valueData.length !== params.pools.length","ParamsLengthNotEqual");let u=t.byAmountIn?Y:_n,l=0;for(let d=0;d<s.length;d+=1)if(!s[d].parsedJson.data.is_exceed)if(t.byAmountIn){let b=new $r.default(s[d].parsedJson.data.amount_out);b.gt(u)&&(l=d,u=b)}else{let b=new $r.default(s[d].parsedJson.data.amount_out);b.lt(u)&&(l=d,u=b)}return this.transformSwapWithMultiPoolData({poolAddress:t.poolAddresses[l],a2b:t.a2b,byAmountIn:t.byAmountIn,amount:t.amount,coinTypeA:t.coinTypeA,coinTypeB:t.coinTypeB},s[l].parsedJson)}async preswap(t){let{integrate:e,simulationAccount:r}=this.sdk.sdkOptions,n=new wa.TransactionBlock,i=[t.coinTypeA,t.coinTypeB],o=[n.pure(t.pool.poolAddress),n.pure(t.a2b),n.pure(t.byAmountIn),n.pure(t.amount)];if(n.moveCall({target:`${e.published_at}::${Vr}::calculate_swap_result`,arguments:o,typeArguments:i}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let s=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(s.error!=null)throw new V(`preswap error code: ${s.error??"unknown error"}, please check config and params`,"InvalidConfig");let u=s.events?.filter(l=>se(l.type).name==="CalculatedSwapResultEvent");return u.length===0?null:this.transformSwapData(t,u[0].parsedJson.data)}transformSwapData(t,e){let r=e.amount_in&&e.fee_amount?new $r.default(e.amount_in).add(new $r.default(e.fee_amount)).toString():"";return{poolAddress:t.pool.poolAddress,currentSqrtPrice:t.currentSqrtPrice,estimatedAmountIn:r,estimatedAmountOut:e.amount_out,estimatedEndSqrtPrice:e.after_sqrt_price,estimatedFeeAmount:e.fee_amount,isExceed:e.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}transformSwapWithMultiPoolData(t,e){let{data:r}=e,n=r.amount_in&&r.fee_amount?new $r.default(r.amount_in).add(new $r.default(r.fee_amount)).toString():"";return{poolAddress:t.poolAddress,estimatedAmountIn:n,estimatedAmountOut:r.amount_out,estimatedEndSqrtPrice:r.after_sqrt_price,estimatedStartSqrtPrice:e.current_sqrt_price,estimatedFeeAmount:r.fee_amount,isExceed:r.is_exceed,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn}}calculateRates(t){let{currentPool:e}=t,r=Og(e),n;t.a2b?n=t.swapTicks.sort((_,T)=>T.index-_.index):n=t.swapTicks.sort((_,T)=>_.index-T.index);let i=Wg(t.a2b,t.byAmountIn,t.amount,r,n),o=!1;t.byAmountIn?o=i.amountIn.lt(t.amount):o=i.amountOut.lt(t.amount);let s=yr.getDefaultSqrtPriceLimit(t.a2b);t.a2b&&i.nextSqrtPrice.lt(s)&&(o=!0),!t.a2b&&i.nextSqrtPrice.gt(s)&&(o=!0);let u=0;i.crossTickNum>6&&i.crossTickNum<40&&(u=22e3*(i.crossTickNum-6)),i.crossTickNum>40&&(o=!0);let l=ke.sqrtPriceX64ToPrice(r.currentSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),d=ke.sqrtPriceX64ToPrice(i.nextSqrtPrice,t.decimalsA,t.decimalsB).toNumber(),b=Math.abs(l-d)/l*100;return{estimatedAmountIn:i.amountIn,estimatedAmountOut:i.amountOut,estimatedEndSqrtPrice:i.nextSqrtPrice,estimatedFeeAmount:i.feeAmount,isExceed:o,extraComputeLimit:u,amount:t.amount,aToB:t.a2b,byAmountIn:t.byAmountIn,priceImpactPct:b}}async createSwapTransactionPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionForGas(this._sdk,t,r,e)}return Pe.buildSwapTransaction(this.sdk,t,r)}async createSwapTransactionWithoutTransferCoinsPayload(t,e){if(this._sdk.senderAddress.length===0)throw Error("this config sdk senderAddress is empty");let r=await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);if(e){let{isAdjustCoinA:n,isAdjustCoinB:i}=wo(t);if(t.a2b&&n||!t.a2b&&i)return await Pe.buildSwapTransactionWithoutTransferCoinsForGas(this._sdk,t,r,e)}return Pe.buildSwapTransactionWithoutTransferCoins(this.sdk,t,r)}},x0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}async getAllRegisteredTokenList(t=!1){return await this.factchTokenList("",t)}async getOwnerTokenList(t="",e=!1){return await this.factchTokenList(t,e)}async getAllRegisteredPoolList(t=!1){return await this.factchPoolList("",t)}async getOwnerPoolList(t="",e=!1){return await this.factchPoolList(t,e)}async getWarpPoolList(t=!1){return await this.factchWarpPoolList("","",t)}async getOwnerWarpPoolList(t="",e="",r=!1){return await this.factchWarpPoolList(t,e,r)}async getTokenListByCoinTypes(t){let e={},n=this.getCache("getAllRegisteredTokenList");if(n!==void 0){let o=n;for(let s of t)for(let u of o)if(sr(s)===sr(u.address)){e[s]=u;continue}}let i=t.filter(o=>e[o]===void 0);for(let o of i){let s=`${o}_metadata`,u=this.getCache(s);if(u!==void 0)e[o]=u;else{let l=await this._sdk.fullClient.getCoinMetadata({coinType:o});if(l){let d={id:l.id,name:l.name,symbol:l.symbol,official_symbol:l.symbol,coingecko_id:"",decimals:l.decimals,project_url:"",logo_url:l.iconUrl,address:o};e[o]=d,this.updateCache(s,d,Oe)}}}return e}async factchTokenList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredTokenList",e);if(o!==void 0)return o;let s=t.length>0,u=512,l=0,d=[];if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;_.moveCall({target:`${n.published_at}::coin_list::${s?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:s?[_.pure(b.coin_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.coin_registry_id),_.pure(l),_.pure(u)]});let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{se(A.type).full_address===`${n.published_at}::coin_list::FetchCoinListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!1))})}),d=[...d,...x],x.length<u)break;l=d.length}return d}async factchPoolList(t="",e=!1){let{simulationAccount:r,token:n}=this.sdk.sdkOptions,o=this.getCache("getAllRegisteredPoolList",e);if(o!==void 0)return o;let s=[],u=512,l=0,d=t.length>0;if(n===void 0)throw Error("please config token ofsdkOptions");let b=be(n);for(;;){let _=new ya.TransactionBlock;if(_.moveCall({target:`${n.published_at}::lp_list::${d?"fetch_full_list_with_limit":"fetch_all_registered_coin_info_with_limit"}`,arguments:d?[_.pure(b.pool_registry_id),_.pure(t),_.pure(l),_.pure(u)]:[_.pure(b.pool_registry_id),_.pure(l),_.pure(u)]}),!kt(r.address))throw new V("this config simulationAccount is not set right","InvalidSimulateAccount");let T=await this.sdk.fullClient.devInspectTransactionBlock({transactionBlock:_,sender:r.address}),x=[];if(T.events?.forEach(A=>{se(A.type).full_address===`${n.published_at}::lp_list::FetchPoolListEvent`&&A.parsedJson.full_list.value_list.forEach(C=>{x.push(this.transformData(C,!0))})}),s=[...s,...x],x.length<u)break;l=s.length}return s}async factchWarpPoolList(t="",e="",r=!1){let n=await this.factchPoolList(t,r);if(n.length===0)return[];let i=await this.factchTokenList(e,r),o=[];for(let s of n){for(let u of i)u.address===s.coin_a_address&&(s.coinA=u),u.address===s.coin_b_address&&(s.coinB=u);o.push(s)}return o}async getTokenConfigEvent(t=!1){let e=this._sdk.sdkOptions.token.package_id,r=`${e}_getTokenConfigEvent`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_registry_id:"",pool_registry_id:"",coin_list_owner:"",pool_list_owner:""};return s.data.length>0&&s.data.forEach(l=>{let d=se(l.type);if(l.transactionModule==="coin_list")switch(d.name){case"InitListEvent":u.coin_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent":u.coin_registry_id=l.parsedJson.registry_id;break;default:break}else if(l.transactionModule==="lp_list")switch(d.name){case"InitListEvent<address>":u.pool_list_owner=l.parsedJson.list_id;break;case"InitRegistryEvent<address>":u.pool_registry_id=l.parsedJson.registry_id;break;default:break}}),u.coin_registry_id.length>0&&this.updateCache(r,u,Oe),u}transformData(t,e){let r={...t};if(e)try{r.coin_a_address=se(r.coin_a_address).full_address,r.coin_b_address=se(r.coin_b_address).full_address}catch{}else r.address=se(r.address).full_address;if(t.extensions){let n=t.extensions.contents;for(let i of n){let{key:o}=i,{value:s}=i;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}o==="pyth_id"&&(s=(0,Ql.normalizeSuiObjectId)(s)),r[o]=s}delete r.extensions}return r}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}},k0=class{_sdk;constructor(t){this._sdk=t}get sdk(){return this._sdk}calculatePrice(t,e,r,n,i){let o=n?e:r,s=n?r:e;return i==="Cetus"?ke.sqrtPriceX64ToPrice(t,o,s):new $(t.toString()).div(new $(10).pow(new $(s+9-o)))}parseJsonResult(t){return{isExceed:t.is_exceed,isTimeout:t.is_timeout,inputAmount:t.input_amount,outputAmount:t.output_amount,fromCoin:t.from_coin,toCoin:t.to_coin,byAmountIn:t.by_amount_in,splitPaths:t.split_paths.map(r=>({pathIndex:r.path_index,lastQuoteOutput:r.last_quote_output,percent:r.percent,basePaths:r.best_path.map(i=>({direction:i.direction,label:i.label,poolAddress:i.provider,fromCoin:i.from_coin,toCoin:i.to_coin,outputAmount:i.output_amount,inputAmount:i.input_amount,feeRate:i.fee_rate,currentSqrtPrice:new Gt.default(i.current_sqrt_price.toString()),afterSqrtPrice:i.label==="Cetus"?new Gt.default(i.after_sqrt_price.toString()):Y,fromDecimal:i.from_decimal,toDecimal:i.to_decimal,currentPrice:this.calculatePrice(new Gt.default(i.current_sqrt_price.toString()),i.from_decimal,i.to_decimal,i.direction,i.label)})),inputAmount:r.input_amount,outputAmount:r.output_amount}))}}async fetchWithTimeout(t,e,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let o=await fetch(t,{...e,signal:n.signal});return clearTimeout(i),o}catch{return null}}async fetchAndParseData(t,e){try{let n=await this.fetchWithTimeout(t,e,1500);return n.status===200?this.parseJsonResult(await n.json()):null}catch{return null}}async getBestRouter(t,e,r,n,i,o,s,u,l=!1,d=!1,b=[]){let _=null,T="v2",x={},A=this.sdk.sdkOptions.aggregatorUrl;if(b.length>0){let I=new URL(A);A=`${I.protocol}//${I.hostname}/router_with_lp_changes`,x={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:t,to:e,amount:r,by_amount_in:n,order_split:l,external_router:d,sender_address:"None",request_id:encodeURIComponent(ao()),lp_changes:b})}}else A=`
|
|
4
|
+
${A}?from=${encodeURIComponent(t)}&to=${encodeURIComponent(e)}&amount=${encodeURIComponent(r)}&by_amount_in=${encodeURIComponent(n)}&order_split=${encodeURIComponent(l)}&external_router=${encodeURIComponent(d)}&sender_address=''&request_id=${encodeURIComponent(ao())}
|
|
5
|
+
`;if(_=await this.fetchAndParseData(A,x),_?.isTimeout||_==null){let I=await this.sdk.Router.price(t,e,new Gt.default(r),n,i,o,u),C=[];for(let P of I.paths){let D=[];if(P.poolAddress.length>1){let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W},U=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,N=this.sdk.Router.tokenInfo(P.coinType[2]).decimals,j=P.a2b[1]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),U,N):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[1]),N,U),S={direction:P.a2b[1],label:"Cetus",poolAddress:P.poolAddress[1],fromCoin:P.coinType[1],toCoin:P.coinType[2],feeRate:this.sdk.Router.getFeeRate(P.coinType[1],P.coinType[2],P.poolAddress[1]),outputAmount:P.amountOut.toString(),inputAmount:I.byAmountIn?P.rawAmountLimit[0].toString():P.rawAmountLimit[1].toString(),currentSqrtPrice:I.currentSqrtPrice[1],currentPrice:j,fromDecimal:U,toDecimal:N};D.push(F,S)}else{let H=this.sdk.Router.tokenInfo(P.coinType[0]).decimals,W=this.sdk.Router.tokenInfo(P.coinType[1]).decimals,K=P.a2b[0]?ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),H,W):ke.sqrtPriceX64ToPrice(new Gt.default(I.currentSqrtPrice[0]),W,H),F={direction:P.a2b[0],label:"Cetus",poolAddress:P.poolAddress[0],fromCoin:P.coinType[0],toCoin:P.coinType[1],feeRate:this.sdk.Router.getFeeRate(P.coinType[0],P.coinType[1],P.poolAddress[0]),outputAmount:P.amountOut.toString(),inputAmount:P.amountIn.toString(),currentSqrtPrice:I.currentSqrtPrice[0],currentPrice:K,fromDecimal:H,toDecimal:W};D.push(F)}let L={percent:Number(P.amountIn)/Number(I.amountIn)*100,inputAmount:Number(P.amountIn.toString()),outputAmount:Number(P.amountOut.toString()),pathIndex:0,lastQuoteOutput:0,basePaths:D};C.push(L)}let E={isExceed:I.isExceed,isTimeout:!0,inputAmount:Number(I.amountIn.toString()),outputAmount:Number(I.amountOut.toString()),fromCoin:I.coinTypeA,toCoin:I.coinTypeC!=null?I.coinTypeC:I.coinTypeB,byAmountIn:I.byAmountIn,splitPaths:C};T="v1",_=E}return{result:_,version:T}}},A0=class{_sdk;_cache={};constructor(t){this._sdk=t}get sdk(){return this._sdk}setTokenListCache(t){let{coin_list_handle:e}=be(this.sdk.sdkOptions.cetus_config),r=`${e}_getCoinConfigs`,n=this.getCache(r),i=n?[...n,...t]:t;this.updateCache(r,i,Oe)}async getTokenListByCoinTypes(t){let e={},{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n);if(i!==void 0){let s=i;for(let u of t)for(let l of s)if(sr(u)===sr(l.address)){e[u]=l;continue}}let o=t.filter(s=>e[s]===void 0);for(let s of o){let u=`${s}_metadata`,l=this.getCache(u);if(l!==void 0)e[s]=l;else{let d=await this._sdk.fullClient.getCoinMetadata({coinType:s});if(d){let b={id:d.id,pyth_id:"",name:d.name,symbol:d.symbol,official_symbol:d.symbol,coingecko_id:"",decimals:d.decimals,project_url:"",logo_url:d.iconUrl,address:s};e[s]=b,this.updateCache(u,b,Oe)}else console.log(`not found ${s}`)}}return e}async getCoinConfigs(t=!1,e=!0){let{coin_list_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getCoinConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildCoinConfig(d,e);this.updateCache(`${r}_${b.address}_getCoinConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getCoinConfig(t,e=!1,r=!0){let{coin_list_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${n}_${t}_getCoinConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"0x1::type_name::TypeName",value:{name:Yg(t)}}});if(s.error!=null||s.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfig get object error: ${s.error}, please check the rpc and contracts address config.`,"InvalidConfig");let u=this.buildCoinConfig(s,r);return this.updateCache(i,u,Oe),u}buildCoinConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.address=se(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=(0,go.normalizeSuiObjectId)(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,e),delete n.coin_type,n}async getClmmPoolConfigs(t=!1,e=!0){let{clmm_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getClmmPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getClmmPoolsConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildClmmPoolConfig(d,e);this.updateCache(`${b.pool_address}_getClmmPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getClmmPoolConfig(t,e=!1,r=!0){let{clmm_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getClmmPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildClmmPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildClmmPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};return n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e),n}async getLaunchpadPoolConfigs(t=!1,e=!0){let{launchpad_pools_handle:r}=be(this.sdk.sdkOptions.cetus_config),n=`${r}_getLaunchpadPoolConfigs`,i=this.getCache(n,t);if(i)return i;let s=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(d=>d.objectId),u=await this._sdk.fullClient.batchGetObjects(s,{showContent:!0}),l=[];return u.forEach(d=>{if(d.error!=null||d.data?.content?.dataType!=="moveObject")throw new V(`when getCoinConfigs get objects error: ${d.error}, please check the rpc and contracts address config.`,"InvalidConfig");let b=this.buildLaunchpadPoolConfig(d,e);this.updateCache(`${b.pool_address}_getLaunchpadPoolConfig`,b,Oe),l.push({...b})}),this.updateCache(n,l,Oe),l}async getLaunchpadPoolConfig(t,e=!1,r=!0){let{launchpad_pools_handle:n}=be(this.sdk.sdkOptions.cetus_config),i=`${t}_getLaunchpadPoolConfig`,o=this.getCache(i,e);if(o)return o;let s=await this._sdk.fullClient.getDynamicFieldObject({parentId:n,name:{type:"address",value:t}}),u=this.buildLaunchpadPoolConfig(s,r);return this.updateCache(i,u,Oe),u}buildLaunchpadPoolConfig(t,e=!0){let r=br(t);r=r.value.fields;let n={...r};n.id=bn(t),n.pool_address=(0,go.normalizeSuiObjectId)(r.pool_address),this.transformExtensions(n,r.extension_fields.fields.contents,e);let i=[];r.social_media.fields.contents.forEach(o=>{i.push({name:o.fields.value.fields.name,link:o.fields.value.fields.link})}),n.social_media=i;try{n.regulation=decodeURIComponent(mn.decode(n.regulation).replace(/%/g,"%25"))}catch{n.regulation=mn.decode(n.regulation)}return n}transformExtensions(t,e,r=!0){let n=[];for(let i of e){let{key:o}=i.fields,{value:s}=i.fields;if(o==="labels")try{s=JSON.parse(decodeURIComponent(mn.decode(s)))}catch{}r&&(t[o]=s),n.push({key:o,value:s})}delete t.extension_fields,r||(t.extensions=n)}async getCetusConfig(t=!1){let e=this._sdk.sdkOptions.cetus_config.package_id,r=`${e}_getCetusConfig`,n=this.getCache(r,t);if(n!==void 0)return n;let i=await this._sdk.fullClient.getObject({id:e,options:{showPreviousTransaction:!0}}),o=_a(i),s=await this._sdk.fullClient.queryEventsByPage({Transaction:o}),u={coin_list_id:"",launchpad_pools_id:"",clmm_pools_id:"",admin_cap_id:"",global_config_id:"",coin_list_handle:"",launchpad_pools_handle:"",clmm_pools_handle:""};if(s.data.length>0)for(let l of s.data)switch(se(l.type).name){case"InitCoinListEvent":u.coin_list_id=l.parsedJson.coin_list_id;break;case"InitLaunchpadPoolsEvent":u.launchpad_pools_id=l.parsedJson.launchpad_pools_id;break;case"InitClmmPoolsEvent":u.clmm_pools_id=l.parsedJson.pools_id;break;case"InitConfigEvent":u.global_config_id=l.parsedJson.global_config_id,u.admin_cap_id=l.parsedJson.admin_cap_id;break;default:break}return u=await this.getCetusConfigHandle(u),u.clmm_pools_id.length>0&&this.updateCache(r,u,Oe),u}async getCetusConfigHandle(t){let e=[t.clmm_pools_id,t.coin_list_id,t.launchpad_pools_id];return(await this._sdk.fullClient.multiGetObjects({ids:e,options:{showContent:!0}})).forEach(n=>{if(n.error!=null||n.data?.content?.dataType!=="moveObject")throw new V(`when getCetusConfigHandle get objects error: ${n.error}, please check the rpc and contracts address config.`,"InvalidConfigHandle");let i=br(n),o=c0(n);switch(se(o).name){case"ClmmPools":t.clmm_pools_handle=i.pools.fields.id.id;break;case"CoinList":t.coin_list_handle=i.coins.fields.id.id;break;case"LaunchpadPools":t.launchpad_pools_handle=i.pools.fields.id.id;break;default:break}}),t}updateCache(t,e,r=yo){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){try{let r=this._cache[t];if(!r)return;if(e||!r.isValid()){delete this._cache[t];return}return r.value}catch(r){console.error(`Error accessing cache for key ${t}:`,r);return}}},I0=class extends td.SuiClient{async queryEventsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.queryEvents({query:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async getOwnedObjectsByPage(t,e,r="all"){let n=[],i=!0,o=r==="all",s=o?null:r.cursor;do{let u=await this.getOwnedObjects({owner:t,...e,cursor:s,limit:o?null:r.limit});u.data?(n=[...n,...u.data],i=u.hasNextPage,s=u.nextCursor):i=!1}while(o&&i);return{data:n,nextCursor:s,hasNextPage:i}}async getDynamicFieldsByPage(t,e="all"){let r=[],n=!0,i=e==="all",o=i?null:e.cursor;do{let s=await this.getDynamicFields({parentId:t,cursor:o,limit:i?null:e.limit});s.data?(r=[...r,...s.data],n=s.hasNextPage,o=s.nextCursor):n=!1}while(i&&n);return{data:r,nextCursor:o,hasNextPage:n}}async batchGetObjects(t,e,r=50){let n=[];try{for(let i=0;i<Math.ceil(t.length/r);i++){let o=await this.multiGetObjects({ids:t.slice(i*r,r*(i+1)),options:e});n=[...n,...o]}}catch(i){console.log(i)}return n}async calculationTxGas(t){let{sender:e}=t.blockData;if(e===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:t,sender:e}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(t,e){try{return await this.signAndExecuteTransactionBlock({transactionBlock:e,signer:t,options:{showEffects:!0,showEvents:!0}})}catch(r){console.log("error: ",r)}}async sendSimulationTransaction(t,e,r=!0){try{if(r)return await this.devInspectTransactionBlock({transactionBlock:t,sender:e});let i={ProgrammableTransaction:{inputs:t.blockData.inputs.map(l=>{let{type:d,value:b}=l;return d==="object"?ed.Inputs.SharedObjectRef({objectId:b,initialSharedVersion:0,mutable:!0}):b}),transactions:t.blockData.transactions}},o=rd.bcs.TransactionKind.serialize(i,{maxSize:131072}).toBytes(),s=Js(o);return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e,s,null,null]})}catch(n){console.log("devInspectTransactionBlock error",n)}}},nd=class{_cache={};_rpcModule;_pool;_position;_swap;_rewarder;_router;_router_v2;_token;_config;_sdkOptions;_senderAddress="";constructor(t){this._sdkOptions=t,this._rpcModule=new I0({url:t.fullRpcUrl}),this._swap=new S0(this),this._pool=new b0(this),this._position=new _0(this),this._rewarder=new v0(this),this._router=new T0(this),this._router_v2=new k0(this),this._token=new x0(this),this._config=new A0(this),zl(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(t){this._senderAddress=t}get Swap(){return this._swap}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}get Pool(){return this._pool}get Position(){return this._position}get Rewarder(){return this._rewarder}get Router(){return this._router}get RouterV2(){return this._router_v2}get CetusConfig(){return this._config}get Token(){return this._token}async getOwnerCoinAssets(t,e,r=!0){let n=[],i=null,o=`${this.sdkOptions.fullRpcUrl}_${t}_${e}_getOwnerCoinAssets`,s=this.getCache(o,r);if(s)return s;for(;;){let u=await(e?this.fullClient.getCoins({owner:t,coinType:e,cursor:i}):this.fullClient.getAllCoins({owner:t,cursor:i}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&n.push({coinAddress:se(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),i=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,n,30*1e3),n}async getOwnerCoinBalances(t,e){let r=[];return e?r=[await this.fullClient.getBalance({owner:t,coinType:e})]:r=[...await this.fullClient.getAllBalances({owner:t})],r}updateCache(t,e,r=Oe){let n=this._cache[t];n?(n.overdueTime=er(r),n.value=e):n=new Zn(e,er(r)),this._cache[t]=n}getCache(t,e=!1){let r=this._cache[t],n=r?.isValid();if(!e&&n)return r.value;n||delete this._cache[t]}};var fh=require("@msafe/sui3-utils"),Oh=require("@mysten/sui.js/client"),dr=de(require("axios"),1),on=require("@mysten/sui.js/utils"),Ln=require("@mysten/sui.js/utils");var ar=class extends Error{},So=class extends ar{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},xo=class extends ar{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},ko=class extends ar{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},zt=class extends ar{},vn=class extends ar{constructor(e){super(`Invalid unit ${e}`)}},lt=class extends ar{},Wt=class extends ar{constructor(){super("Zone is an abstract class")}};var z="numeric",Ht="short",Pt="long",_r={year:z,month:z,day:z},Xn={year:z,month:Ht,day:z},va={year:z,month:Ht,day:z,weekday:Ht},Yn={year:z,month:Pt,day:z},Qn={year:z,month:Pt,day:z,weekday:Pt},ei={hour:z,minute:z},ti={hour:z,minute:z,second:z},ri={hour:z,minute:z,second:z,timeZoneName:Ht},ni={hour:z,minute:z,second:z,timeZoneName:Pt},ii={hour:z,minute:z,hourCycle:"h23"},oi={hour:z,minute:z,second:z,hourCycle:"h23"},si={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Ht},ai={hour:z,minute:z,second:z,hourCycle:"h23",timeZoneName:Pt},ui={year:z,month:z,day:z,hour:z,minute:z},ci={year:z,month:z,day:z,hour:z,minute:z,second:z},li={year:z,month:Ht,day:z,hour:z,minute:z},di={year:z,month:Ht,day:z,hour:z,minute:z,second:z},Ta={year:z,month:Ht,day:z,weekday:Ht,hour:z,minute:z},fi={year:z,month:Pt,day:z,hour:z,minute:z,timeZoneName:Ht},hi={year:z,month:Pt,day:z,hour:z,minute:z,second:z,timeZoneName:Ht},pi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,timeZoneName:Pt},mi={year:z,month:Pt,day:z,weekday:Pt,hour:z,minute:z,second:z,timeZoneName:Pt};var Ot=class{get type(){throw new Wt}get name(){throw new Wt}get ianaName(){return this.name}get isUniversal(){throw new Wt}offsetName(e,r){throw new Wt}formatOffset(e,r){throw new Wt}offset(e){throw new Wt}equals(e){throw new Wt}get isValid(){throw new Wt}};var Sa=null,vr=class t extends Ot{static get instance(){return Sa===null&&(Sa=new t),Sa}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Oo={};function C0(t){return Oo[t]||(Oo[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Oo[t]}var O0={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function M0(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,o,s,u,l,d,b]=n;return[s,i,o,u,l,d,b]}function E0(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:o,value:s}=r[i],u=O0[o];o==="era"?n[u]=s:ne(u)||(n[u]=parseInt(s,10))}return n}var Co={},At=class t extends Ot{static create(e){return Co[e]||(Co[e]=new t(e)),Co[e]}static resetCache(){Co={},Oo={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return Io(e,r,n,this.name)}formatOffset(e,r){return Tr(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=C0(this.name),[i,o,s,u,l,d,b]=n.formatToParts?E0(n,r):M0(n,r);u==="BC"&&(i=-Math.abs(i)+1);let T=Tn({year:i,month:o,day:s,hour:l===24?0:l,minute:d,second:b,millisecond:0}),x=+r,A=x%1e3;return x-=A>=0?A:1e3+A,(T-x)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var id={};function P0(t,e={}){let r=JSON.stringify([t,e]),n=id[r];return n||(n=new Intl.ListFormat(t,e),id[r]=n),n}var xa={};function ka(t,e={}){let r=JSON.stringify([t,e]),n=xa[r];return n||(n=new Intl.DateTimeFormat(t,e),xa[r]=n),n}var Aa={};function D0(t,e={}){let r=JSON.stringify([t,e]),n=Aa[r];return n||(n=new Intl.NumberFormat(t,e),Aa[r]=n),n}var Ia={};function B0(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),o=Ia[i];return o||(o=new Intl.RelativeTimeFormat(t,e),Ia[i]=o),o}var gi=null;function N0(){return gi||(gi=new Intl.DateTimeFormat().resolvedOptions().locale,gi)}var od={};function R0(t){let e=od[t];if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,od[t]=e}return e}function j0(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,i;try{n=ka(t).resolvedOptions(),i=t}catch{let l=t.substring(0,r);n=ka(l).resolvedOptions(),i=l}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function F0(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function q0(t){let e=[];for(let r=1;r<=12;r++){let n=le.utc(2009,r,1);e.push(t(n))}return e}function L0(t){let e=[];for(let r=1;r<=7;r++){let n=le.utc(2016,11,13+r);e.push(t(n))}return e}function Mo(t,e,r,n){let i=t.listingMode();return i==="error"?null:i==="en"?r(e):n(e)}function U0(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var Ca=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!r||Object.keys(s).length>0){let u={useGrouping:!1,...n};n.padTo>0&&(u.minimumIntegerDigits=n.padTo),this.inf=D0(e,u)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):Sn(e,3);return Ee(r,this.padTo)}}},Oa=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),u=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&At.create(u).valid?(i=u,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=ka(r,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Ma=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&Eo()&&(this.rtf=B0(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):sd(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},$0={firstDay:1,minimalDays:4,weekend:[6,7]},ge=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,i,o=!1){let s=e||he.defaultLocale,u=s||(o?"en-US":N0()),l=r||he.defaultNumberingSystem,d=n||he.defaultOutputCalendar,b=wi(i)||he.defaultWeekSettings;return new t(u,l,d,b,s)}static resetCache(){gi=null,xa={},Aa={},Ia={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:i}={}){return t.create(e,r,n,i)}constructor(e,r,n,i,o){let[s,u,l]=j0(e);this.locale=s,this.numberingSystem=r||u||null,this.outputCalendar=n||l||null,this.weekSettings=i,this.intl=F0(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=o,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=U0(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,wi(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return Mo(this,e,Ea,()=>{let n=r?{month:e,day:"numeric"}:{month:e},i=r?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=q0(o=>this.extract(o,n,"month"))),this.monthsCache[i][e]})}weekdays(e,r=!1){return Mo(this,e,Pa,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=r?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=L0(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return Mo(this,void 0,()=>Da,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[le.utc(2016,11,13,9),le.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Mo(this,e,Ba,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[le.utc(-40,1,1),le.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),o=i.formatToParts(),s=o.find(u=>u.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new Ca(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Oa(e,this.intl,r)}relFormatter(e={}){return new Ma(this.intl,this.isEnglish(),e)}listFormatter(e={}){return P0(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Po()?R0(this.locale):$0}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var Ra=null,ht=class t extends Ot{static get utcInstance(){return Ra===null&&(Ra=new t(0)),Ra}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(Hr(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Tr(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Tr(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return Tr(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var xn=class extends Ot{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Zt(t,e){let r;if(ne(t)||t===null)return e;if(t instanceof Ot)return t;if(ad(t)){let n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?vr.instance:n==="utc"||n==="gmt"?ht.utcInstance:ht.parseSpecifier(n)||At.create(t)}else return tr(t)?ht.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new xn(t)}var ud=()=>Date.now(),cd="system",ld=null,dd=null,fd=null,hd=60,pd,md=null,he=class{static get now(){return ud}static set now(e){ud=e}static set defaultZone(e){cd=e}static get defaultZone(){return Zt(cd,vr.instance)}static get defaultLocale(){return ld}static set defaultLocale(e){ld=e}static get defaultNumberingSystem(){return dd}static set defaultNumberingSystem(e){dd=e}static get defaultOutputCalendar(){return fd}static set defaultOutputCalendar(e){fd=e}static get defaultWeekSettings(){return md}static set defaultWeekSettings(e){md=wi(e)}static get twoDigitCutoffYear(){return hd}static set twoDigitCutoffYear(e){hd=e%100}static get throwOnInvalid(){return pd}static set throwOnInvalid(e){pd=e}static resetCaches(){ge.resetCache(),At.resetCache()}};var pt=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var gd=[0,31,59,90,120,151,181,212,243,273,304,334],wd=[0,31,60,91,121,152,182,213,244,274,305,335];function jt(t,e){return new pt("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Do(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function yd(t,e,r){return r+(Kr(t)?wd:gd)[e-1]}function bd(t,e){let r=Kr(t)?wd:gd,n=r.findIndex(o=>o<e),i=e-r[n];return{month:n+1,day:i}}function Bo(t,e){return(t-e+7)%7+1}function yi(t,e=4,r=1){let{year:n,month:i,day:o}=t,s=yd(n,i,o),u=Bo(Do(n,i,o),r),l=Math.floor((s-u+14-e)/7),d;return l<1?(d=n-1,l=Zr(d,e,r)):l>Zr(n,e,r)?(d=n+1,l=1):d=n,{weekYear:d,weekNumber:l,weekday:u,..._i(t)}}function ja(t,e=4,r=1){let{weekYear:n,weekNumber:i,weekday:o}=t,s=Bo(Do(n,1,e),r),u=Sr(n),l=i*7+o-s-7+e,d;l<1?(d=n-1,l+=Sr(d)):l>u?(d=n+1,l-=Sr(n)):d=n;let{month:b,day:_}=bd(d,l);return{year:d,month:b,day:_,..._i(t)}}function No(t){let{year:e,month:r,day:n}=t,i=yd(e,r,n);return{year:e,ordinal:i,..._i(t)}}function Fa(t){let{year:e,ordinal:r}=t,{month:n,day:i}=bd(e,r);return{year:e,month:n,day:i,..._i(t)}}function qa(t,e){if(!ne(t.localWeekday)||!ne(t.localWeekNumber)||!ne(t.localWeekYear)){if(!ne(t.weekday)||!ne(t.weekNumber)||!ne(t.weekYear))throw new zt("Cannot mix locale-based week fields with ISO-based week fields");return ne(t.localWeekday)||(t.weekday=t.localWeekday),ne(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),ne(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function _d(t,e=4,r=1){let n=bi(t.weekYear),i=Dt(t.weekNumber,1,Zr(t.weekYear,e,r)),o=Dt(t.weekday,1,7);return n?i?o?!1:jt("weekday",t.weekday):jt("week",t.weekNumber):jt("weekYear",t.weekYear)}function vd(t){let e=bi(t.year),r=Dt(t.ordinal,1,Sr(t.year));return e?r?!1:jt("ordinal",t.ordinal):jt("year",t.year)}function La(t){let e=bi(t.year),r=Dt(t.month,1,12),n=Dt(t.day,1,kn(t.year,t.month));return e?r?n?!1:jt("day",t.day):jt("month",t.month):jt("year",t.year)}function Ua(t){let{hour:e,minute:r,second:n,millisecond:i}=t,o=Dt(e,0,23)||e===24&&r===0&&n===0&&i===0,s=Dt(r,0,59),u=Dt(n,0,59),l=Dt(i,0,999);return o?s?u?l?!1:jt("millisecond",i):jt("second",n):jt("minute",r):jt("hour",e)}function ne(t){return typeof t>"u"}function tr(t){return typeof t=="number"}function bi(t){return typeof t=="number"&&t%1===0}function ad(t){return typeof t=="string"}function Sd(t){return Object.prototype.toString.call(t)==="[object Date]"}function Eo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Po(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xd(t){return Array.isArray(t)?t:[t]}function $a(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let o=[e(i),i];return n&&r(n[0],o[0])===n[0]?n:o},null)[1]}function kd(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function xr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wi(t){if(t==null)return null;if(typeof t!="object")throw new lt("Week settings must be an object");if(!Dt(t.firstDay,1,7)||!Dt(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Dt(e,1,7)))throw new lt("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Dt(t,e,r){return bi(t)&&t>=e&&t<=r}function G0(t,e){return t-e*Math.floor(t/e)}function Ee(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function ur(t){if(!(ne(t)||t===null||t===""))return parseInt(t,10)}function kr(t){if(!(ne(t)||t===null||t===""))return parseFloat(t)}function vi(t){if(!(ne(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function Sn(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function Kr(t){return t%4===0&&(t%100!==0||t%400===0)}function Sr(t){return Kr(t)?366:365}function kn(t,e){let r=G0(e-1,12)+1,n=t+(e-r)/12;return r===2?Kr(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function Tn(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Td(t,e,r){return-Bo(Do(t,1,e),r)+e-1}function Zr(t,e=4,r=1){let n=Td(t,e,r),i=Td(t+1,e,r);return(Sr(t)-n+i)/7}function Ti(t){return t>99?t:t>he.twoDigitCutoffYear?1900+t:2e3+t}function Io(t,e,r,n=null){let i=new Date(t),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},u=new Intl.DateTimeFormat(r,s).formatToParts(i).find(l=>l.type.toLowerCase()==="timezonename");return u?u.value:null}function Hr(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function Ga(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new lt(`Invalid unit value ${t}`);return e}function An(t,e){let r={};for(let n in t)if(xr(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=Ga(i)}return r}function Tr(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Ee(r,2)}:${Ee(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${Ee(r,2)}${Ee(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function _i(t){return kd(t,["hour","minute","second","millisecond"])}var V0=["January","February","March","April","May","June","July","August","September","October","November","December"],Va=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],z0=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ea(t){switch(t){case"narrow":return[...z0];case"short":return[...Va];case"long":return[...V0];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var za=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Wa=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],W0=["M","T","W","T","F","S","S"];function Pa(t){switch(t){case"narrow":return[...W0];case"short":return[...Wa];case"long":return[...za];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Da=["AM","PM"],H0=["Before Christ","Anno Domini"],Z0=["BC","AD"],K0=["B","A"];function Ba(t){switch(t){case"narrow":return[...K0];case"short":return[...Z0];case"long":return[...H0];default:return null}}function Ad(t){return Da[t.hour<12?0:1]}function Id(t,e){return Pa(e)[t.weekday-1]}function Cd(t,e){return Ea(e)[t.month-1]}function Od(t,e){return Ba(e)[t.year<0?0:1]}function sd(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&o){let _=t==="days";switch(e){case 1:return _?"tomorrow":`next ${i[t][0]}`;case-1:return _?"yesterday":`last ${i[t][0]}`;case 0:return _?"today":`this ${i[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,u=Math.abs(e),l=u===1,d=i[t],b=n?l?d[1]:d[2]||d[1]:l?i[t][0]:t;return s?`${u} ${b} ago`:`in ${u} ${b}`}function Md(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var J0={D:_r,DD:Xn,DDD:Yn,DDDD:Qn,t:ei,tt:ti,ttt:ri,tttt:ni,T:ii,TT:oi,TTT:si,TTTT:ai,f:ui,ff:li,fff:fi,ffff:pi,F:ci,FF:di,FFF:hi,FFFF:mi},mt=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let u=e.charAt(s);u==="'"?(n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),r=null,n="",i=!i):i||u===r?n+=u:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=u,r=u)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return J0[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return Ee(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(x,A)=>this.loc.extract(e,x,A),s=x=>e.isOffsetFixed&&e.offset===0&&x.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,x.format):"",u=()=>n?Ad(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(x,A)=>n?Cd(e,x):o(A?{month:x}:{month:x,day:"numeric"},"month"),d=(x,A)=>n?Id(e,x):o(A?{weekday:x}:{weekday:x,month:"long",day:"numeric"},"weekday"),b=x=>{let A=t.macroTokenToFormatOpts(x);return A?this.formatWithSystemDefault(e,A):x},_=x=>n?Od(e,x):o({era:x},"era"),T=x=>{switch(x){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return u();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return d("short",!0);case"cccc":return d("long",!0);case"ccccc":return d("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return d("short",!1);case"EEEE":return d("long",!1);case"EEEEE":return d("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return _("short");case"GG":return _("long");case"GGGGG":return _("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return b(x)}};return Md(t.parseFormat(r),T)}formatDurationFromString(e,r){let n=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=l=>d=>{let b=n(d);return b?this.num(l.get(b),d.length):d},o=t.parseFormat(r),s=o.reduce((l,{literal:d,val:b})=>d?l:l.concat(b),[]),u=e.shiftTo(...s.map(n).filter(l=>l));return Md(o,i(u))}};var Pd=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Cn(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function On(...t){return e=>t.reduce(([r,n,i],o)=>{let[s,u,l]=o(e,i);return[{...r,...s},u||n,l]},[{},null,1]).slice(0,2)}function Mn(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function Dd(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=ur(e[r+i]);return[n,null,r+i]}}var Bd=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,X0=`(?:${Bd.source}?(?:\\[(${Pd.source})\\])?)?`,Ha=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Nd=RegExp(`${Ha.source}${X0}`),Za=RegExp(`(?:T${Nd.source})?`),Y0=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Q0=/(\d{4})-?W(\d\d)(?:-?(\d))?/,ew=/(\d{4})-?(\d{3})/,tw=Dd("weekYear","weekNumber","weekDay"),rw=Dd("year","ordinal"),nw=/(\d{4})-(\d\d)-(\d\d)/,Rd=RegExp(`${Ha.source} ?(?:${Bd.source}|(${Pd.source}))?`),iw=RegExp(`(?: ${Rd.source})?`);function In(t,e,r){let n=t[e];return ne(n)?r:ur(n)}function ow(t,e){return[{year:In(t,e),month:In(t,e+1,1),day:In(t,e+2,1)},null,e+3]}function En(t,e){return[{hours:In(t,e,0),minutes:In(t,e+1,0),seconds:In(t,e+2,0),milliseconds:vi(t[e+3])},null,e+4]}function Si(t,e){let r=!t[e]&&!t[e+1],n=Hr(t[e+1],t[e+2]),i=r?null:ht.instance(n);return[{},i,e+3]}function xi(t,e){let r=t[e]?At.create(t[e]):null;return[{},r,e+1]}var sw=RegExp(`^T?${Ha.source}$`),aw=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function uw(t){let[e,r,n,i,o,s,u,l,d]=t,b=e[0]==="-",_=l&&l[0]==="-",T=(x,A=!1)=>x!==void 0&&(A||x&&b)?-x:x;return[{years:T(kr(r)),months:T(kr(n)),weeks:T(kr(i)),days:T(kr(o)),hours:T(kr(s)),minutes:T(kr(u)),seconds:T(kr(l),l==="-0"),milliseconds:T(vi(d),_)}]}var cw={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Ka(t,e,r,n,i,o,s){let u={year:e.length===2?Ti(ur(e)):ur(e),month:Va.indexOf(r)+1,day:ur(n),hour:ur(i),minute:ur(o)};return s&&(u.second=ur(s)),t&&(u.weekday=t.length>3?za.indexOf(t)+1:Wa.indexOf(t)+1),u}var lw=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function dw(t){let[,e,r,n,i,o,s,u,l,d,b,_]=t,T=Ka(e,i,n,r,o,s,u),x;return l?x=cw[l]:d?x=0:x=Hr(b,_),[T,new ht(x)]}function fw(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var hw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,pw=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,mw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Ed(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,i,n,r,o,s,u),ht.utcInstance]}function gw(t){let[,e,r,n,i,o,s,u]=t;return[Ka(e,u,r,n,i,o,s),ht.utcInstance]}var ww=Cn(Y0,Za),yw=Cn(Q0,Za),bw=Cn(ew,Za),_w=Cn(Nd),jd=On(ow,En,Si,xi),vw=On(tw,En,Si,xi),Tw=On(rw,En,Si,xi),Sw=On(En,Si,xi);function Fd(t){return Mn(t,[ww,jd],[yw,vw],[bw,Tw],[_w,Sw])}function qd(t){return Mn(fw(t),[lw,dw])}function Ld(t){return Mn(t,[hw,Ed],[pw,Ed],[mw,gw])}function Ud(t){return Mn(t,[aw,uw])}var xw=On(En);function $d(t){return Mn(t,[sw,xw])}var kw=Cn(nw,iw),Aw=Cn(Rd),Iw=On(En,Si,xi);function Gd(t){return Mn(t,[kw,jd],[Aw,Iw])}var Vd="Invalid Duration",Wd={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Cw={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Wd},Ft=146097/400,Pn=146097/4800,Ow={years:{quarters:4,months:12,weeks:Ft/7,days:Ft,hours:Ft*24,minutes:Ft*24*60,seconds:Ft*24*60*60,milliseconds:Ft*24*60*60*1e3},quarters:{months:3,weeks:Ft/28,days:Ft/4,hours:Ft*24/4,minutes:Ft*24*60/4,seconds:Ft*24*60*60/4,milliseconds:Ft*24*60*60*1e3/4},months:{weeks:Pn/7,days:Pn,hours:Pn*24,minutes:Pn*24*60,seconds:Pn*24*60*60,milliseconds:Pn*24*60*60*1e3},...Wd},Jr=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Mw=Jr.slice(0).reverse();function Ar(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new _e(n)}function Hd(t,e){let r=e.milliseconds??0;for(let n of Mw.slice(1))e[n]&&(r+=e[n]*t[n].milliseconds);return r}function zd(t,e){let r=Hd(t,e)<0?-1:1;Jr.reduceRight((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]*r,s=t[i][n],u=Math.floor(o/s);e[i]+=u*r,e[n]-=u*s*r}return i},null),Jr.reduce((n,i)=>{if(ne(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*t[n][i]}return i},null)}function Ew(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var _e=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?Ow:Cw;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||ge.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new lt(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:An(e,t.normalizeUnit),loc:ge.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(tr(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new lt(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=Ud(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=$d(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Duration is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new ko(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new vn(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?mt.create(this.loc,n).formatDurationFromString(this,e):Vd}toHuman(e={}){if(!this.isValid)return Vd;let r=Jr.map(n=>{let i=this.values[n];return ne(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Sn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},le.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Hd(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of Jr)(xr(r.values,i)||xr(this.values,i))&&(n[i]=r.get(i)+this.get(i));return Ar(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=Ga(e(this.values[n],n));return Ar(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...An(e,t.normalizeUnit)};return Ar(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:i,conversionAccuracy:n};return Ar(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return zd(this.matrix,e),Ar(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Ew(this.normalize().shiftToAll().toObject());return Ar(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let r={},n={},i=this.toObject(),o;for(let s of Jr)if(e.indexOf(s)>=0){o=s;let u=0;for(let d in n)u+=this.matrix[d][s]*n[d],n[d]=0;tr(i[s])&&(u+=i[s]);let l=Math.trunc(u);r[s]=l,n[s]=(u*1e3-l*1e3)/1e3}else tr(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(r[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return zd(this.matrix,r),Ar(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Ar(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of Jr)if(!r(this.values[n],e.values[n]))return!1;return!0}};var Dn="Invalid Interval";function Pw(t,e){return!t||!t.isValid?cr.invalid("missing or invalid start"):!e||!e.isValid?cr.invalid("missing or invalid end"):e<t?cr.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var cr=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the Interval is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new xo(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=Bn(e),i=Bn(r),o=Pw(n,i);return o??new t({start:n,end:i})}static after(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=_e.fromDurationLike(r),i=Bn(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=le.fromISO(n,r),s=o.isValid}catch{s=!1}let u,l;try{u=le.fromISO(i,r),l=u.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(o,u);if(s){let d=_e.fromISO(i,r);if(d.isValid)return t.after(o,d)}else if(l){let d=_e.fromISO(n,r);if(d.isValid)return t.before(u,d)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),i;return r?.useLocaleWeeks?i=this.end.reconfigure({locale:n.locale}):i=this.end,i=i.startOf(e,r),Math.floor(i.diff(n,e).get(e))+(i.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(Bn).filter(s=>this.contains(s)).sort((s,u)=>s.toMillis()-u.toMillis()),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=r[o]||this.e,u=+s>+this.e?this.e:s;n.push(t.fromDateTimes(i,u)),i=u,o+=1}return n}splitBy(e){let r=_e.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let u=this.start.plus(r.mapUnits(l=>l*i));o=+u>+this.e?this.e:u,s.push(t.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],o=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...o),u=s.sort((l,d)=>l.time-d.time);for(let l of u)n+=l.type==="s"?1:-1,n===1?r=l.time:(r&&+r!=+l.time&&i.push(t.fromDateTimes(r,l.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Dn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.s.loc.clone(r),e).formatInterval(this):Dn}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Dn}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Dn}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Dn}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Dn}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):_e.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var lr=class{static hasDST(e=he.defaultZone){let r=le.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return At.isValidZone(e)}static normalizeZone(e){return Zt(e,he.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||ge.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||ge.create(r,n,o)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||ge.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ge.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return ge.create(r,null,"gregory").eras(e)}static features(){return{relative:Eo(),localeWeek:Po()}}};function Zd(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(_e.fromMillis(n).as("days"))}function Dw(t,e,r){let n=[["years",(l,d)=>d.year-l.year],["quarters",(l,d)=>d.quarter-l.quarter+(d.year-l.year)*4],["months",(l,d)=>d.month-l.month+(d.year-l.year)*12],["weeks",(l,d)=>{let b=Zd(l,d);return(b-b%7)/7}],["days",Zd]],i={},o=t,s,u;for(let[l,d]of n)r.indexOf(l)>=0&&(s=l,i[l]=d(t,e),u=o.plus(i),u>e?(i[l]--,t=o.plus(i),t>e&&(u=t,i[l]--,t=o.plus(i))):t=u);return[t,i,u,s]}function Kd(t,e,r,n){let[i,o,s,u]=Dw(t,e,r),l=e-i,d=r.filter(_=>["hours","minutes","seconds","milliseconds"].indexOf(_)>=0);d.length===0&&(s<e&&(s=i.plus({[u]:1})),s!==i&&(o[u]=(o[u]||0)+l/(s-i)));let b=_e.fromObject(o,n);return d.length>0?_e.fromMillis(l,n).shiftTo(...d).plus(b):b}var Ja={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Jd={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Bw=Ja.hanidec.replace(/[\[|\]]/g,"").split("");function Xd(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(Ja.hanidec)!==-1)e+=Bw.indexOf(t[r]);else for(let i in Jd){let[o,s]=Jd[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}function qt({numberingSystem:t},e=""){return new RegExp(`${Ja[t||"latn"]}${e}`)}var Nw="missing Intl.DateTimeFormat.formatToParts support";function pe(t,e=r=>r){return{regex:t,deser:([r])=>e(Xd(r))}}var Rw="\xA0",ef=`[ ${Rw}]`,tf=new RegExp(ef,"g");function jw(t){return t.replace(/\./g,"\\.?").replace(tf,ef)}function Yd(t){return t.replace(/\./g,"").replace(tf," ").toLowerCase()}function Kt(t,e){return t===null?null:{regex:RegExp(t.map(jw).join("|")),deser:([r])=>t.findIndex(n=>Yd(r)===Yd(n))+e}}function Qd(t,e){return{regex:t,deser:([,r,n])=>Hr(r,n),groups:e}}function Ro(t){return{regex:t,deser:([e])=>e}}function Fw(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function qw(t,e){let r=qt(e),n=qt(e,"{2}"),i=qt(e,"{3}"),o=qt(e,"{4}"),s=qt(e,"{6}"),u=qt(e,"{1,2}"),l=qt(e,"{1,3}"),d=qt(e,"{1,6}"),b=qt(e,"{1,9}"),_=qt(e,"{2,4}"),T=qt(e,"{4,6}"),x=C=>({regex:RegExp(Fw(C.val)),deser:([E])=>E,literal:!0}),I=(C=>{if(t.literal)return x(C);switch(C.val){case"G":return Kt(e.eras("short"),0);case"GG":return Kt(e.eras("long"),0);case"y":return pe(d);case"yy":return pe(_,Ti);case"yyyy":return pe(o);case"yyyyy":return pe(T);case"yyyyyy":return pe(s);case"M":return pe(u);case"MM":return pe(n);case"MMM":return Kt(e.months("short",!0),1);case"MMMM":return Kt(e.months("long",!0),1);case"L":return pe(u);case"LL":return pe(n);case"LLL":return Kt(e.months("short",!1),1);case"LLLL":return Kt(e.months("long",!1),1);case"d":return pe(u);case"dd":return pe(n);case"o":return pe(l);case"ooo":return pe(i);case"HH":return pe(n);case"H":return pe(u);case"hh":return pe(n);case"h":return pe(u);case"mm":return pe(n);case"m":return pe(u);case"q":return pe(u);case"qq":return pe(n);case"s":return pe(u);case"ss":return pe(n);case"S":return pe(l);case"SSS":return pe(i);case"u":return Ro(b);case"uu":return Ro(u);case"uuu":return pe(r);case"a":return Kt(e.meridiems(),0);case"kkkk":return pe(o);case"kk":return pe(_,Ti);case"W":return pe(u);case"WW":return pe(n);case"E":case"c":return pe(r);case"EEE":return Kt(e.weekdays("short",!1),1);case"EEEE":return Kt(e.weekdays("long",!1),1);case"ccc":return Kt(e.weekdays("short",!0),1);case"cccc":return Kt(e.weekdays("long",!0),1);case"Z":case"ZZ":return Qd(new RegExp(`([+-]${u.source})(?::(${n.source}))?`),2);case"ZZZ":return Qd(new RegExp(`([+-]${u.source})(${n.source})?`),2);case"z":return Ro(/[a-z_+-/]{1,256}?/i);case" ":return Ro(/[^\S\n\r]/);default:return x(C)}})(t)||{invalidReason:Nw};return I.token=t,I}var Lw={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Uw(t,e,r){let{type:n,value:i}=t;if(n==="literal"){let l=/^\s+$/.test(i);return{literal:!l,val:l?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=r.hour12?"hour12":"hour24");let u=Lw[s];if(typeof u=="object"&&(u=u[o]),u)return{literal:!1,val:u}}function $w(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function Gw(t,e,r){let n=t.match(e);if(n){let i={},o=1;for(let s in r)if(xr(r,s)){let u=r[s],l=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(n.slice(o,o+l))),o+=l}return[n,i]}else return[n,{}]}function Vw(t){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return ne(t.z)||(r=At.create(t.z)),ne(t.Z)||(r||(r=new ht(t.Z)),n=t.Z),ne(t.q)||(t.M=(t.q-1)*3+1),ne(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),ne(t.u)||(t.S=vi(t.u)),[Object.keys(t).reduce((o,s)=>{let u=e(s);return u&&(o[u]=t[s]),o},{}),r,n]}var Xa=null;function zw(){return Xa||(Xa=le.fromMillis(1555555555555)),Xa}function Ww(t,e){if(t.literal)return t;let r=mt.macroTokenToFormatOpts(t.val),n=eu(r,e);return n==null||n.includes(void 0)?t:n}function Ya(t,e){return Array.prototype.concat(...t.map(r=>Ww(r,e)))}function Qa(t,e,r){let n=Ya(mt.parseFormat(r),t),i=n.map(s=>qw(s,t)),o=i.find(s=>s.invalidReason);if(o)return{input:e,tokens:n,invalidReason:o.invalidReason};{let[s,u]=$w(i),l=RegExp(s,"i"),[d,b]=Gw(e,l,u),[_,T,x]=b?Vw(b):[null,null,void 0];if(xr(b,"a")&&xr(b,"H"))throw new zt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:l,rawMatches:d,matches:b,result:_,zone:T,specificOffset:x}}}function rf(t,e,r){let{result:n,zone:i,specificOffset:o,invalidReason:s}=Qa(t,e,r);return[n,i,o,s]}function eu(t,e){if(!t)return null;let n=mt.create(e,t).dtFormatter(zw()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>Uw(s,t,o))}var tu="Invalid DateTime",nf=864e13;function jo(t){return new pt("unsupported zone",`the zone "${t.name}" is not supported`)}function ru(t){return t.weekData===null&&(t.weekData=yi(t.c)),t.weekData}function nu(t){return t.localWeekData===null&&(t.localWeekData=yi(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function Xr(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new le({...r,...e,old:r})}function df(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=r.offset(n);return i===o?[n,i]:[t-Math.min(i,o)*60*1e3,Math.max(i,o)]}function Fo(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function Lo(t,e,r){return df(Tn(t),e,r)}function of(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...t.c,year:n,month:i,day:Math.min(t.c.day,kn(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=_e.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),u=Tn(o),[l,d]=df(u,r,t.zone);return s!==0&&(l+=s,d=t.zone.offset(l)),{ts:l,o:d}}function ki(t,e,r,n,i,o){let{setZone:s,zone:u}=r;if(t&&Object.keys(t).length!==0||e){let l=e||u,d=le.fromObject(t,{...r,zone:l,specificOffset:o});return s?d:d.setZone(u)}else return le.invalid(new pt("unparsable",`the input "${i}" can't be parsed as ${n}`))}function qo(t,e,r=!0){return t.isValid?mt.create(ge.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function iu(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=Ee(t.c.year,r?6:4),e?(n+="-",n+=Ee(t.c.month),n+="-",n+=Ee(t.c.day)):(n+=Ee(t.c.month),n+=Ee(t.c.day)),n}function sf(t,e,r,n,i,o){let s=Ee(t.c.hour);return e?(s+=":",s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=":")):s+=Ee(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(s+=Ee(t.c.second),(t.c.millisecond!==0||!n)&&(s+=".",s+=Ee(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!o?s+="Z":t.o<0?(s+="-",s+=Ee(Math.trunc(-t.o/60)),s+=":",s+=Ee(Math.trunc(-t.o%60))):(s+="+",s+=Ee(Math.trunc(t.o/60)),s+=":",s+=Ee(Math.trunc(t.o%60)))),o&&(s+="["+t.zone.ianaName+"]"),s}var ff={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Hw={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Zw={ordinal:1,hour:0,minute:0,second:0,millisecond:0},hf=["year","month","day","hour","minute","second","millisecond"],Kw=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Jw=["year","ordinal","hour","minute","second","millisecond"];function Xw(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new vn(t);return e}function af(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Xw(t)}}function uf(t,e){let r=Zt(e.zone,he.defaultZone),n=ge.fromObject(e),i=he.now(),o,s;if(ne(t.year))o=i;else{for(let d of hf)ne(t[d])&&(t[d]=ff[d]);let u=La(t)||Ua(t);if(u)return le.invalid(u);let l=r.offset(i);[o,s]=Lo(t,l,r)}return new le({ts:o,zone:r,loc:n,o:s})}function cf(t,e,r){let n=ne(r.round)?!0:r.round,i=(s,u)=>(s=Sn(s,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(s,u)),o=s=>r.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(r.unit)return i(o(r.unit),r.unit);for(let s of r.units){let u=o(s);if(Math.abs(u)>=1)return i(u,s)}return i(t>e?-0:0,r.units[r.units.length-1])}function lf(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var le=class t{constructor(e){let r=e.zone||he.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new pt("invalid input"):null)||(r.isValid?null:jo(r));this.ts=ne(e.ts)?he.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,o]=[e.old.c,e.old.o];else{let u=r.offset(this.ts);i=Fo(this.ts,u),n=Number.isNaN(i.year)?new pt("invalid input"):null,i=n?null:i,o=n?null:u}this._zone=r,this.loc=e.loc||ge.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static utc(){let[e,r]=lf(arguments),[n,i,o,s,u,l,d]=r;return e.zone=ht.utcInstance,uf({year:n,month:i,day:o,hour:s,minute:u,second:l,millisecond:d},e)}static fromJSDate(e,r={}){let n=Sd(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Zt(r.zone,he.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:ge.fromObject(r)}):t.invalid(jo(i))}static fromMillis(e,r={}){if(tr(e))return e<-nf||e>nf?t.invalid("Timestamp out of range"):new t({ts:e,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(tr(e))return new t({ts:e*1e3,zone:Zt(r.zone,he.defaultZone),loc:ge.fromObject(r)});throw new lt("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Zt(r.zone,he.defaultZone);if(!n.isValid)return t.invalid(jo(n));let i=ge.fromObject(r),o=An(e,af),{minDaysInFirstWeek:s,startOfWeek:u}=qa(o,i),l=he.now(),d=ne(r.specificOffset)?n.offset(l):r.specificOffset,b=!ne(o.ordinal),_=!ne(o.year),T=!ne(o.month)||!ne(o.day),x=_||T,A=o.weekYear||o.weekNumber;if((x||b)&&A)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(T&&b)throw new zt("Can't mix ordinal dates with month/day");let I=A||o.weekday&&!x,C,E,P=Fo(l,d);I?(C=Kw,E=Hw,P=yi(P,s,u)):b?(C=Jw,E=Zw,P=No(P)):(C=hf,E=ff);let D=!1;for(let N of C){let j=o[N];ne(j)?D?o[N]=E[N]:o[N]=P[N]:D=!0}let L=I?_d(o,s,u):b?vd(o):La(o),H=L||Ua(o);if(H)return t.invalid(H);let W=I?ja(o,s,u):b?Fa(o):o,[K,F]=Lo(W,d,n),U=new t({ts:K,zone:n,o:F,loc:i});return o.weekday&&x&&e.weekday!==U.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${U.toISO()}`):U}static fromISO(e,r={}){let[n,i]=Fd(e);return ki(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=qd(e);return ki(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=Ld(e);return ki(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(ne(e)||ne(r))throw new lt("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[u,l,d,b]=rf(s,e,r);return b?t.invalid(b):ki(u,l,n,`format ${r}`,e,d)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=Gd(e);return ki(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new lt("need to specify a reason the DateTime is invalid");let n=e instanceof pt?e:new pt(e,r);if(he.throwOnInvalid)throw new So(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=eu(e,ge.fromObject(r));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,r={}){return Ya(mt.parseFormat(e),ge.fromObject(r)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?ru(this).weekYear:NaN}get weekNumber(){return this.isValid?ru(this).weekNumber:NaN}get weekday(){return this.isValid?ru(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?nu(this).weekday:NaN}get localWeekNumber(){return this.isValid?nu(this).weekNumber:NaN}get localWeekYear(){return this.isValid?nu(this).weekYear:NaN}get ordinal(){return this.isValid?No(this.c).ordinal:NaN}get monthShort(){return this.isValid?lr.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?lr.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?lr.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?lr.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=Tn(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*r),u=this.zone.offset(n-o*r);if(s===u)return[this];let l=n-s*r,d=n-u*r,b=Fo(l,s),_=Fo(d,u);return b.hour===_.hour&&b.minute===_.minute&&b.second===_.second&&b.millisecond===_.millisecond?[Xr(this,{ts:l}),Xr(this,{ts:d})]:[this]}get isInLeapYear(){return Kr(this.year)}get daysInMonth(){return kn(this.year,this.month)}get daysInYear(){return this.isValid?Sr(this.year):NaN}get weeksInWeekYear(){return this.isValid?Zr(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Zr(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=mt.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(ht.instance(e),r)}toLocal(){return this.setZone(he.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Zt(e,he.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let o=e.offset(this.ts),s=this.toObject();[i]=Lo(s,o,e)}return Xr(this,{ts:i,zone:e})}else return t.invalid(jo(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return Xr(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=An(e,af),{minDaysInFirstWeek:n,startOfWeek:i}=qa(r,this.loc),o=!ne(r.weekYear)||!ne(r.weekNumber)||!ne(r.weekday),s=!ne(r.ordinal),u=!ne(r.year),l=!ne(r.month)||!ne(r.day),d=u||l,b=r.weekYear||r.weekNumber;if((d||s)&&b)throw new zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new zt("Can't mix ordinal dates with month/day");let _;o?_=ja({...yi(this.c,n,i),...r},n,i):ne(r.ordinal)?(_={...this.toObject(),...r},ne(r.day)&&(_.day=Math.min(kn(_.year,_.month),_.day))):_=Fa({...No(this.c),...r});let[T,x]=Lo(_,this.o,this.zone);return Xr(this,{ts:T,o:x})}plus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e);return Xr(this,of(this,r))}minus(e){if(!this.isValid)return this;let r=_e.fromDurationLike(e).negate();return Xr(this,of(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},i=_e.normalizeUnit(e);switch(i){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(i==="weeks")if(r){let o=this.loc.getStartOfWeek(),{weekday:s}=this;s<o&&(n.weekNumber=this.weekNumber-1),n.weekday=o}else n.weekday=1;if(i==="quarters"){let o=Math.ceil(this.month/3);n.month=(o-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?mt.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):tu}toLocaleString(e=_r,r={}){return this.isValid?mt.create(this.loc.clone(r),e).formatDateTime(this):tu}toLocaleParts(e={}){return this.isValid?mt.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",u=iu(this,s);return u+="T",u+=sf(this,s,r,n,i,o),u}toISODate({format:e="extended"}={}){return this.isValid?iu(this,e==="extended"):null}toISOWeekDate(){return qo(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(i?"T":"")+sf(this,s==="extended",r,e,n,o):null}toRFC2822(){return qo(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return qo(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?iu(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),qo(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():tu}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return _e.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=xd(r).map(_e.normalizeUnit),s=e.valueOf()>this.valueOf(),u=s?this:e,l=s?e:this,d=Kd(u,l,o,i);return s?d.negate():d}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?cr.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let i=e.valueOf(),o=this.setZone(e.zone,{keepLocalTime:!0});return o.startOf(r,n)<=i&&i<=o.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),cf(r,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?cf(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new lt("min requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new lt("max requires all arguments be DateTimes");return $a(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=ge.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return Qa(s,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return _r}static get DATE_MED(){return Xn}static get DATE_MED_WITH_WEEKDAY(){return va}static get DATE_FULL(){return Yn}static get DATE_HUGE(){return Qn}static get TIME_SIMPLE(){return ei}static get TIME_WITH_SECONDS(){return ti}static get TIME_WITH_SHORT_OFFSET(){return ri}static get TIME_WITH_LONG_OFFSET(){return ni}static get TIME_24_SIMPLE(){return ii}static get TIME_24_WITH_SECONDS(){return oi}static get TIME_24_WITH_SHORT_OFFSET(){return si}static get TIME_24_WITH_LONG_OFFSET(){return ai}static get DATETIME_SHORT(){return ui}static get DATETIME_SHORT_WITH_SECONDS(){return ci}static get DATETIME_MED(){return li}static get DATETIME_MED_WITH_SECONDS(){return di}static get DATETIME_MED_WITH_WEEKDAY(){return Ta}static get DATETIME_FULL(){return fi}static get DATETIME_FULL_WITH_SECONDS(){return hi}static get DATETIME_HUGE(){return pi}static get DATETIME_HUGE_WITH_SECONDS(){return mi}};function Bn(t){if(le.isDateTime(t))return t;if(t&&t.valueOf&&tr(t.valueOf()))return le.fromJSDate(t);if(t&&typeof t=="object")return le.fromObject(t);throw new lt(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Pi=require("@mysten/sui.js/transactions"),ku=require("@mysten/sui.js/transactions"),Bi=require("@mysten/sui.js/utils"),Au=require("buffer"),Dh=require("@mysten/sui.js/utils"),Ru=require("@mysten/sui.js/bcs"),Ni=require("@mysten/sui.js/utils");var pf=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((e,r)=>(r&=63,r<36?e+=r.toString(36):r<62?e+=(r-26).toString(36).toUpperCase():r>62?e+="-":e+="_",e),"");var Ou=require("@mysten/sui.js/transactions"),Rr=require("@mysten/sui.js/utils");var Di=require("@mysten/sui.js/transactions"),Ri=require("@mysten/sui.js/utils");var Kh=de(Wi(),1),Jh=require("@msafe/sui3-utils"),Xh=require("@msafe/sui3-utils"),Yh=require("@msafe/sui3-utils"),Du=require("@mysten/sui.js/bcs"),Dr=require("@mysten/sui.js/utils"),ep=require("@msafe/sui3-utils"),qn=require("@msafe/sui3-utils"),tp=require("@msafe/sui3-utils"),np=require("@msafe/sui3-utils"),op=require("@msafe/sui3-utils"),sp=require("@mysten/sui.js/transactions"),up=require("@msafe/sui3-utils"),Fn=require("@msafe/sui3-utils"),Bu=require("@mysten/sui.js/bcs"),Br=require("@mysten/sui.js/utils"),cp=require("@mysten/sui.js/transactions"),dp=require("@mysten/sui.js/transactions"),hp=require("@mysten/sui.js/transactions"),gp=require("@mysten/sui.js/transactions"),yp=require("@mysten/sui.js/transactions"),ls=require("@msafe/sui3-utils"),_p=require("@mysten/sui.js/transactions"),ds=require("@mysten/sui.js/utils"),$T=de(Wi(),1),vp=require("@msafe/sui3-utils"),Tp=require("@msafe/sui3-utils"),Nu=require("@mysten/sui.js/bcs"),Nr=require("@mysten/sui.js/utils");var vy=de(we(),1);var tn=require("@mysten/sui.js/client"),Ef=require("@mysten/sui.js/keypairs/ed25519");function mf(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Yw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function ou(t,...e){if(!Yw(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function su(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gf(t,e){ou(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Uo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qw(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Go=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Jt=(t,e)=>t<<32-e|t>>>e,ey=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ey)throw new Error("Non little-endian hardware is not supported");function ty(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function au(t){if(typeof t=="string"&&(t=ty(t)),!Qw(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}var $o=class{clone(){return this._cloneInto()}},X2={}.toString;function wf(t){let e=n=>t().update(au(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yf(t=32){if(Uo&&typeof Uo.getRandomValues=="function")return Uo.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ry(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),u=Number(r&o),l=n?4:0,d=n?0:4;t.setUint32(e+l,s,n),t.setUint32(e+d,u,n)}var Vo=class extends $o{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Go(this.buffer)}update(e){su(this);let{view:r,buffer:n,blockLen:i}=this;e=au(e);let o=e.length;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let l=Go(e);for(;i<=o-s;s+=i)this.process(l,s);continue}n.set(e.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){su(this),gf(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let _=s;_<i;_++)r[_]=0;ry(n,i-8,BigInt(this.length*8),o),this.process(n,0);let u=Go(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=l/4,b=this.get();if(d>b.length)throw new Error("_sha2: outputLen bigger than state");for(let _=0;_<d;_++)u.setUint32(4*_,b[_],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:u}=this;return e.length=i,e.pos=u,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var ny=(t,e,r)=>t&e^~t&r,iy=(t,e,r)=>t&e^t&r^e&r,oy=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ir=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=new Uint32Array(64),uu=class extends Vo{constructor(){super(64,32,8,!1),this.A=Ir[0]|0,this.B=Ir[1]|0,this.C=Ir[2]|0,this.D=Ir[3]|0,this.E=Ir[4]|0,this.F=Ir[5]|0,this.G=Ir[6]|0,this.H=Ir[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:u,H:l}=this;return[e,r,n,i,o,s,u,l]}set(e,r,n,i,o,s,u,l){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=u|0,this.H=l|0}process(e,r){for(let _=0;_<16;_++,r+=4)Cr[_]=e.getUint32(r,!1);for(let _=16;_<64;_++){let T=Cr[_-15],x=Cr[_-2],A=Jt(T,7)^Jt(T,18)^T>>>3,I=Jt(x,17)^Jt(x,19)^x>>>10;Cr[_]=I+Cr[_-7]+A+Cr[_-16]|0}let{A:n,B:i,C:o,D:s,E:u,F:l,G:d,H:b}=this;for(let _=0;_<64;_++){let T=Jt(u,6)^Jt(u,11)^Jt(u,25),x=b+T+ny(u,l,d)+oy[_]+Cr[_]|0,I=(Jt(n,2)^Jt(n,13)^Jt(n,22))+iy(n,i,o)|0;b=d,d=l,l=u,u=s+x|0,s=o,o=i,i=n,n=x+I|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,u=u+this.E|0,l=l+this.F|0,d=d+this.G|0,b=b+this.H|0,this.set(n,i,o,s,u,l,d,b)}roundClean(){Cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var bf=wf(()=>new uu);function Yr(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function zo(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function sy(...t){let e=o=>o,r=(o,s)=>u=>o(s(u)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function ay(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function uy(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function cy(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function cu(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],o=Array.from(t);for(o.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,u=!0;for(let l=n;l<o.length;l++){let d=o[l],b=e*s+d;if(!Number.isSafeInteger(b)||e*s/e!==s||b-d!==e*s)throw new Error("convertRadix: carry overflow");s=b%r;let _=Math.floor(b/r);if(o[l]=_,!Number.isSafeInteger(_)||_*r+s!==b)throw new Error("convertRadix: carry overflow");if(u)_?u=!1:n=l;else continue}if(i.push(s),u)break}for(let s=0;s<t.length-1&&t[s]===0;s++)i.push(0);return i.reverse()}var _f=(t,e)=>e?_f(e,t%e):t,Wo=(t,e)=>t+(e-_f(t,e));function lu(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Wo(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Wo(e,r)}`);let i=0,o=0,s=2**r-1,u=[];for(let l of t){if(l>=2**e)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(i=i<<e|l,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)u.push((i>>o-r&s)>>>0);i&=2**o-1}if(i=i<<r-o&s,!n&&o>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&u.push(i>>>0),u}function ly(t){return{encode:e=>{if(!zo(e))throw new Error("radix.encode input should be Uint8Array");return cu(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(cu(e,t,2**8))}}}function dy(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Wo(8,t)>32||Wo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!zo(r))throw new Error("radix2.encode input should be Uint8Array");return lu(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(lu(r,t,8,e))}}}function fy(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!zo(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!zo(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),o=r.slice(-t);for(let s=0;s<t;s++)if(i[s]!==o[s])throw new Error("Invalid checksum");return n}}}var Ai={alphabet:ay,chain:sy,checksum:fy,convertRadix:cu,convertRadix2:lu,radix:ly,radix2:dy,join:uy,padding:cy};var hy=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function py(t){ou(t,16,20,24,28,32)}function vf(t,e=128){if(mf(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return wy(yf(e/8),t)}var my=t=>{let e=8-t.length/4;return new Uint8Array([bf(t)[0]>>e<<e])};function gy(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),Ai.chain(Ai.checksum(1,my),Ai.radix2(11,!0),Ai.alphabet(t))}function wy(t,e){return py(t),gy(e).encode(t).join(hy(e)?"\u3000":" ")}var Tf=`abandon
|
|
12
6
|
ability
|
|
13
7
|
able
|
|
14
8
|
about
|
|
@@ -2056,7 +2050,7 @@ zebra
|
|
|
2056
2050
|
zero
|
|
2057
2051
|
zone
|
|
2058
2052
|
zoo`.split(`
|
|
2059
|
-
`);var Ma=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,zw=new Set,Eh=typeof process=="object"&&process?process:{},Vw=(t,e,n,i)=>{typeof Eh.emitWarning=="function"?Eh.emitWarning(t,e,n,i):console.error(`[${n}] ${e}: ${t}`)},cl=globalThis.AbortController,Gw=globalThis.AbortSignal;if(typeof cl>"u"){Gw=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,r){this._onabort.push(r)}},cl=class{constructor(){e()}signal=new Gw;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=Eh.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Vw("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 h6=t=>!zw.has(t),A8=Symbol("type"),$r=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Kw=t=>$r(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?gs:null:null,gs=class extends Array{constructor(e){super(e),this.fill(0)}},Dh=class t{heap;length;static#c=!1;static create(e){let n=Kw(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]}},ul=class t{#c;#d;#w;#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;#_;#y;#A;#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.#D(n,i,r,o),moveToTail:n=>e.#x(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.#m}get size(){return this.#i}get fetchMethod(){return this.#O}get dispose(){return this.#w}get disposeAfter(){return this.#p}constructor(e){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:h,noUpdateTTL:_,maxSize:C=0,maxEntrySize:D=0,sizeCalculation:O,fetchMethod:B,noDeleteOnFetchRejection:j,noDeleteOnStaleGet:M,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:K,ignoreFetchAbort:X}=e;if(n!==0&&!$r(n))throw new TypeError("max option must be a nonnegative integer");let Y=n?Kw(n):Array;if(!Y)throw new Error("invalid max value: "+n);if(this.#c=n,this.#d=C,this.maxEntrySize=D||this.#d,this.sizeCalculation=O,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(B!==void 0&&typeof B!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=B,this.#A=!!B,this.#r=new Map,this.#n=new Array(n).fill(void 0),this.#e=new Array(n).fill(void 0),this.#u=new Y(n),this.#f=new Y(n),this.#a=0,this.#o=0,this.#g=Dh.create(n),this.#i=0,this.#m=0,typeof u=="function"&&(this.#w=u),typeof d=="function"?(this.#p=d,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#y=!!this.#w,this.#l=!!this.#p,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!_,this.noDeleteOnFetchRejection=!!j,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!K,this.ignoreFetchAbort=!!X,this.maxEntrySize!==0){if(this.#d!==0&&!$r(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!$r(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!M,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=$r(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!$r(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#B()}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 oe="LRU_CACHE_UNBOUNDED";h6(oe)&&(zw.add(oe),Vw("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",oe,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#B(){let e=new gs(this.#c),n=new gs(this.#c);this.#_=e,this.#T=n,this.#M=(o,s,a=Ma.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#h(o)&&this.delete(this.#n[o])},s+1);c.unref&&c.unref()}},this.#S=o=>{n[o]=e[o]!==0?Ma.now():0},this.#C=(o,s)=>{if(e[s]){let a=e[s],c=n[s];o.ttl=a,o.start=c,o.now=i||r();let u=o.now-c;o.remainingTTL=a-u}};let i=0,r=()=>{let o=Ma.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],c=n[s];if(a===0||c===0)return 1/0;let u=(i||r())-c;return a-u},this.#h=o=>e[o]!==0&&n[o]!==0&&(i||r())-n[o]>e[o]}#S=()=>{};#C=()=>{};#M=()=>{};#h=()=>!1;#F(){let e=new gs(this.#c);this.#m=0,this.#k=e,this.#I=n=>{this.#m-=e[n],e[n]=0},this.#j=(n,i,r,o)=>{if(this.#t(i))return 0;if(!$r(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(i,n),!$r(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.#E(!0)}this.#m+=e[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#m)}}#I=e=>{};#P=(e,n,i)=>{};#j=(e,n,i,r)=>{if(i||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#o;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#a));)n=this.#f[n]}*#v({allowStale:e=this.allowStale}={}){if(this.#i)for(let n=this.#a;!(!this.#N(n)||((e||!this.#h(n))&&(yield n),n===this.#o));)n=this.#u[n]}#N(e){return e!==void 0&&this.#r.get(this.#n[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#n[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#n[e],this.#e[e]])}*keys(){for(let e of this.#b()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*rkeys(){for(let e of this.#v()){let n=this.#n[e];n!==void 0&&!this.#t(this.#e[e])&&(yield n)}}*values(){for(let e of this.#b())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,n={}){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&e(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(e,n=this){for(let i of this.#b()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}rforEach(e,n=this){for(let i of this.#v()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&e.call(n,o,this.#n[i],this)}}purgeStale(){let e=!1;for(let n of this.#v({allowStale:!0}))this.#h(n)&&(this.delete(this.#n[n]),e=!0);return e}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let s={value:o};if(this.#_&&this.#T){s.ttl=this.#_[n];let a=Ma.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=Ma.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:c}=i,{noUpdateTTL:u=this.noUpdateTTL}=i,d=this.#j(e,n,i.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let h=this.#i===0?void 0:this.#r.get(e);if(h===void 0)h=this.#i===0?this.#o:this.#g.length!==0?this.#g.pop():this.#i===this.#c?this.#E(!1):this.#i,this.#n[h]=e,this.#e[h]=n,this.#r.set(e,h),this.#u[this.#o]=h,this.#f[h]=this.#o,this.#o=h,this.#i++,this.#P(h,d,c),c&&(c.set="add"),u=!1;else{this.#x(h);let _=this.#e[h];if(n!==_){if(this.#A&&this.#t(_)?_.__abortController.abort(new Error("replaced")):s||(this.#y&&this.#w?.(_,e,"set"),this.#l&&this.#s?.push([_,e,"set"])),this.#I(h),this.#P(h,d,c),this.#e[h]=n,c){c.set="replace";let C=_&&this.#t(_)?_.__staleWhileFetching:_;C!==void 0&&(c.oldValue=C)}}else c&&(c.set="update")}if(r!==0&&!this.#_&&this.#B(),this.#_&&(u||this.#M(h,r,o),c&&this.#C(c,h)),!s&&this.#l&&this.#s){let _=this.#s,C;for(;C=_?.shift();)this.#p?.(...C)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,n;for(;n=e?.shift();)this.#p?.(...n)}}}#E(e){let n=this.#a,i=this.#n[n],r=this.#e[n];return this.#A&&this.#t(r)?r.__abortController.abort(new Error("evicted")):(this.#y||this.#l)&&(this.#y&&this.#w?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#I(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.#S(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}}#D(e,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let s=new cl,{signal:a}=i;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:i,context:r},u=(O,B=!1)=>{let{aborted:j}=s.signal,M=i.ignoreFetchAbort&&O!==void 0;if(i.status&&(j&&!B?(i.status.fetchAborted=!0,i.status.fetchError=s.signal.reason,M&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),j&&!M&&!B)return h(s.signal.reason);let R=C;return this.#e[n]===C&&(O===void 0?R.__staleWhileFetching?this.#e[n]=R.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,O,c.options))),O},d=O=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=O),h(O)),h=O=>{let{aborted:B}=s.signal,j=B&&i.allowStaleOnFetchAbort,M=j||i.allowStaleOnFetchRejection,R=M||i.noDeleteOnFetchRejection,K=C;if(this.#e[n]===C&&(!R||K.__staleWhileFetching===void 0?this.delete(e):j||(this.#e[n]=K.__staleWhileFetching)),M)return i.status&&K.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),K.__staleWhileFetching;if(K.__returned===K)throw O},_=(O,B)=>{let j=this.#O?.(e,o,c);j&&j instanceof Promise&&j.then(M=>O(M),B),s.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(O(),i.allowStaleOnFetchAbort&&(O=M=>u(M,!0)))})};i.status&&(i.status.fetchDispatched=!0);let C=new Promise(_).then(u,d),D=Object.assign(C,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,D,{...c.options,status:void 0}),n=this.#r.get(e)):this.#e[n]=D,D}#t(e){if(!this.#A)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof cl}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:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:_=this.allowStaleOnFetchRejection,ignoreFetchAbort:C=this.ignoreFetchAbort,allowStaleOnFetchAbort:D=this.allowStaleOnFetchAbort,context:O,forceRefresh:B=!1,status:j,signal:M}=n;if(!this.#A)return j&&(j.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:j});let R={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:D,ignoreFetchAbort:C,status:j,signal:M},K=this.#r.get(e);if(K===void 0){j&&(j.fetch="miss");let X=this.#D(e,K,R,O);return X.__returned=X}else{let X=this.#e[K];if(this.#t(X)){let G=i&&X.__staleWhileFetching!==void 0;return j&&(j.fetch="inflight",G&&(j.returnedStale=!0)),G?X.__staleWhileFetching:X.__returned=X}let Y=this.#h(K);if(!B&&!Y)return j&&(j.fetch="hit"),this.#x(K),r&&this.#S(K),j&&this.#C(j,K),X;let oe=this.#D(e,K,R,O),ne=oe.__staleWhileFetching!==void 0&&i;return j&&(j.fetch=Y?"stale":"refresh",ne&&Y&&(j.returnedStale=!0)),ne?oe.__staleWhileFetching:oe.__returned=oe}}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 c=this.#e[a],u=this.#t(c);return s&&this.#C(s,a),this.#h(a)?(s&&(s.get="stale"),u?(s&&i&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),i?c.__staleWhileFetching:void 0):(o||this.delete(e),s&&i&&(s.returnedStale=!0),i?c:void 0)):(s&&(s.get="hit"),u?c.__staleWhileFetching:(this.#x(a),r&&this.#S(a),c))}else s&&(s.get="miss")}#R(e,n){this.#f[n]=e,this.#u[e]=n}#x(e){e!==this.#o&&(e===this.#a?this.#a=this.#u[e]:this.#R(this.#f[e],this.#u[e]),this.#R(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.#I(i);let r=this.#e[i];this.#t(r)?r.__abortController.abort(new Error("deleted")):(this.#y||this.#l)&&(this.#y&&this.#w?.(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.#y&&this.#w?.(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 Oe=Pe(Ee(),1);var hl=Pe(Ww(),1),bo=require("@mysten/sui.js/utils"),vo=require("@mysten/sui.js/transactions");var ja=Pe(Ee(),1),ty=require("@mysten/sui.js/transactions"),ei=Pe(Ee(),1);var Gr=Pe(Ee(),1),ki=Pe(Ee(),1);var Fa=Pe(Ee(),1);var ny=require("@mysten/sui.js/utils"),pl=require("@mysten/sui.js/transactions"),ml=require("@mysten/sui.js/utils");var Fh=Pe(Ee(),1),p6=Object.defineProperty,m6=(t,e,n)=>e in t?p6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xi=(t,e,n)=>(m6(t,typeof e!="symbol"?e+"":e,n),n);var ll=443636,dl=-443636,jh="79226673515401279992447579055",Nh="4295048016",_6=14,w6="59543866431248",y6="184467440737095516",b6="15793534762490258745",v6=class{generateMnemonic(t=24){return Uw($w,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let n=this.getDerivePath(e);return Jw.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}'`}},Ra=class{constructor(t){this.sdk=t,Xi(this,"_lru"),Xi(this,"_fetching",{})}async getCacheOrSet(t,e,n=0){var i;let r=this._lru||(this._lru=new ul({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 k6(t){if("reference"in t)return t.reference;let e=qh(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Qw(t)}function _l(t){var e,n;return"objectId"in t?t.objectId:(n=(e=k6(t))==null?void 0:e.objectId)!=null?n:ey(t)}function Zi(t){var e;return"fields"in t?t.fields:(e=Yw(t))==null?void 0:e.fields}function Yw(t){let e="data"in t?qh(t):t;if(!(!e||!T6(e)||e.content.dataType!=="moveObject"))return e.content}function T6(t){return t.content!==void 0}function qh(t){return t.data}function Qw(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 ey(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function C6(t){return t.data!==void 0}function A6(t){var e;let n=C6(t)?t.data:t;return!n?.type&&"data"in t?((e=n?.content)==null?void 0:e.dataType)==="package"?"package":gl(t):n?.type}function gl(t){var e;return(e=Yw(t))==null?void 0:e.type}function S6(t){var e;return(e=qh(t))==null?void 0:e.owner}var Na=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})},I6=class extends Ra{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 Na(this.provider,Object.values(e),{showContent:!0})).map(i=>{let r=Zi(i),o=_l(i),s=gl(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())}},Hw=new Oe.default(2).pow(new Oe.default(128)),x6=class{priceToSqrtPriceX64(t,e,n){return new Oe.default(new J(t).mul(J.pow(10,n-e)).sqrt().mul(J.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,n){return new J(t.toString()).mul(J.pow(2,-64)).pow(2).mul(J.pow(10,e-n))}priceToTickIndex(t,e,n){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,n))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Oe.default(jh))||t.lt(new Oe.default(Nh)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new Oe.default(e-64),i=this.signedShiftLeft(n,32,128),r=new Oe.default("8000000000000000","hex"),o=0,s=new Oe.default(0),a=e>=64?t.shrn(e-63):t.shln(63-e);for(;r.gt(new Oe.default(0))&&o<_6;){a=a.mul(a);let C=a.shrn(127);a=a.shrn(63+C.toNumber()),s=s.add(r.mul(C)),r=r.shrn(1),o+=1}let c=s.shrn(32),d=i.add(c).mul(new Oe.default(w6)),h=this.signedShiftRight(d.sub(new Oe.default(y6)),64,128).toNumber(),_=this.signedShiftRight(d.add(new Oe.default(b6)),64,128).toNumber();return h==_?h:this.tickIndexToSqrtPriceX64(_).lte(t)?_:h}tickIndexToSqrtPriceX64(t){return t>0?new Oe.default(this.tickIndexToSqrtPricePositive(t)):new Oe.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,n){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,n)}toX64_Decimal(t){return t.mul(J.pow(2,64))}fromX64_Decimal(t){return t.mul(J.pow(2,-64))}scaleDown(t,e){return new J(t).div(J.pow(10,e)).toString()}scaleUp(t,e){return new J(t).mul(J.pow(10,e)).toString()}bitsToNumber(t,e=32){return hl.default.toNumber(hl.default.asIntN(e,hl.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Hw).sub(e).mod(Hw)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Oe.default("79232123823359799118286999567"):e=new Oe.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Oe.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Oe.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Oe.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Oe.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Oe.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Oe.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Oe.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Oe.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Oe.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Oe.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Oe.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Oe.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Oe.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Oe.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Oe.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Oe.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Oe.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Oe.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),n;return e&1?n=new Oe.default("18445821805675392311"):n=new Oe.default("18446744073709551616"),e&2&&(n=this.signedShiftRight(n.mul(new Oe.default("18444899583751176498")),64,256)),e&4&&(n=this.signedShiftRight(n.mul(new Oe.default("18443055278223354162")),64,256)),e&8&&(n=this.signedShiftRight(n.mul(new Oe.default("18439367220385604838")),64,256)),e&16&&(n=this.signedShiftRight(n.mul(new Oe.default("18431993317065449817")),64,256)),e&32&&(n=this.signedShiftRight(n.mul(new Oe.default("18417254355718160513")),64,256)),e&64&&(n=this.signedShiftRight(n.mul(new Oe.default("18387811781193591352")),64,256)),e&128&&(n=this.signedShiftRight(n.mul(new Oe.default("18329067761203520168")),64,256)),e&256&&(n=this.signedShiftRight(n.mul(new Oe.default("18212142134806087854")),64,256)),e&512&&(n=this.signedShiftRight(n.mul(new Oe.default("17980523815641551639")),64,256)),e&1024&&(n=this.signedShiftRight(n.mul(new Oe.default("17526086738831147013")),64,256)),e&2048&&(n=this.signedShiftRight(n.mul(new Oe.default("16651378430235024244")),64,256)),e&4096&&(n=this.signedShiftRight(n.mul(new Oe.default("15030750278693429944")),64,256)),e&8192&&(n=this.signedShiftRight(n.mul(new Oe.default("12247334978882834399")),64,256)),e&16384&&(n=this.signedShiftRight(n.mul(new Oe.default("8131365268884726200")),64,256)),e&32768&&(n=this.signedShiftRight(n.mul(new Oe.default("3584323654723342297")),64,256)),e&65536&&(n=this.signedShiftRight(n.mul(new Oe.default("696457651847595233")),64,256)),e&131072&&(n=this.signedShiftRight(n.mul(new Oe.default("26294789957452057")),64,256)),e&262144&&(n=this.signedShiftRight(n.mul(new Oe.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)}},Rh=(t,e)=>{let n=_l(t);if(Qw(t))throw new Error(`${e}(${n}) had been deleted`);if(ey(t))throw new Error(`${e}(${n}) is not found`);return!0},_s=60*1e3,O6=class extends Ra{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 Na(this.provider,n,{showContent:!0})).map(a=>Zi(a).value.fields.pool_id);if(!o.length)return[];let s=await Na(this.provider,o,{showContent:!0});return t||(s=s.filter(a=>Zi(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 Rh(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:c}=t,u=await this.contract.getConfig(),d=new J(t.amountA),h=new J(t.amountB),[_,C]=await Promise.all([this.coin.selectTradeCoins(n,a,d),this.coin.selectTradeCoins(n,c,h)]),D=t.txb||new vo.TransactionBlock,O=_.length>0?this.coin.convertTradeCoins(D,_,a,d):[this.coin.zero(a,D)],B=C.length>0?this.coin.convertTradeCoins(D,C,c,h):[this.coin.zero(c,D)];return D.moveCall({target:`${u.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[a,c,e.type],arguments:[D.object(u.PoolConfig),D.object(e.objectId),D.pure(o,"u128"),D.object(u.Positions),D.makeMoveVec({objects:O}),D.makeMoveVec({objects:B}),D.pure(Math.abs(i).toFixed(0),"u32"),D.pure(i<0,"bool"),D.pure(Math.abs(r).toFixed(0),"u32"),D.pure(r<0,"bool"),D.pure(d.toFixed(0),"u64"),D.pure(h.toFixed(0),"u64"),D.pure(this.getMinimumAmountBySlippage(d,s),"u64"),D.pure(this.getMinimumAmountBySlippage(h,s),"u64"),D.pure(n,"address"),D.pure(Date.now()+_s,"u64"),D.object(bo.SUI_CLOCK_OBJECT_ID),D.object(u.Versioned)]}),D}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),[c,u]=a,[d,h]=await Promise.all([this.coin.getMetadata(c),this.coin.getMetadata(u)]);if(!d||!h)throw new Error("Invalid coin type");let _=new J(t.amountA),C=new J(t.amountB),[D,O]=await Promise.all([this.coin.selectTradeCoins(e,c,_),this.coin.selectTradeCoins(e,u,C)]),B=t.txb||new vo.TransactionBlock,j=D.length>0?this.coin.convertTradeCoins(B,D,c,_):[this.coin.zero(c,B)],M=O.length>0?this.coin.convertTradeCoins(B,O,u,C):[this.coin.zero(u,B)];return B.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:a,arguments:[B.object(o),B.object(s.Positions),B.makeMoveVec({objects:j}),B.makeMoveVec({objects:M}),B.pure(Math.abs(n).toFixed(0),"u32"),B.pure(n<0,"bool"),B.pure(Math.abs(i).toFixed(0),"u32"),B.pure(i<0,"bool"),B.pure(_.toFixed(0),"u64"),B.pure(C.toFixed(0),"u64"),B.pure(this.getMinimumAmountBySlippage(_,r),"u64"),B.pure(this.getMinimumAmountBySlippage(C,r),"u64"),B.pure(e,"address"),B.pure(Date.now()+_s,"u64"),B.object(bo.SUI_CLOCK_OBJECT_ID),B.object(s.Versioned)]}),B}async increaseLiquidity(t){let{pool:e,slippage:n,address:i,nft:r}=t,o=await this.contract.getConfig(),s=new J(t.amountA),a=new J(t.amountB),c=await this.getPoolTypeArguments(e),[u,d]=c,[h,_]=await Promise.all([this.coin.selectTradeCoins(i,u,s),this.coin.selectTradeCoins(i,d,a)]),C=t.txb||new vo.TransactionBlock,D=h.length>0?this.coin.convertTradeCoins(C,h,u,s):[this.coin.zero(u,C)],O=_.length>0?this.coin.convertTradeCoins(C,_,d,a):[this.coin.zero(d,C)];return C.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:c,arguments:[C.object(e),C.object(o.Positions),C.makeMoveVec({objects:D}),C.makeMoveVec({objects:O}),C.object(r),C.pure(s.toFixed(0),"u64"),C.pure(a.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(s,n),"u64"),C.pure(this.getMinimumAmountBySlippage(a,n),"u64"),C.pure(Date.now()+_s*3,"u64"),C.object(bo.SUI_CLOCK_OBJECT_ID),C.object(o.Versioned)]}),C}async decreaseLiquidity(t){let{slippage:e,nft:n,pool:i,decreaseLiquidity:r}=t,o=new J(t.amountA),s=new J(t.amountB),a=await this.contract.getConfig(),c=await this.getPoolTypeArguments(i),u=t.txb||new vo.TransactionBlock;return u.moveCall({target:`${a.PackageId}::position_manager::decrease_liquidity`,typeArguments:c,arguments:[u.object(i),u.object(a.Positions),u.object(n),u.pure(new ja.default(r).toString(),"u128"),u.pure(this.getMinimumAmountBySlippage(o,e),"u64"),u.pure(this.getMinimumAmountBySlippage(s,e),"u64"),u.pure(Date.now()+_s*3,"u64"),u.object(bo.SUI_CLOCK_OBJECT_ID),u.object(a.Versioned)]}),u}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 vo.TransactionBlock;if(Number(r)===0&&Number(o)===0)return s;let a=await this.contract.getConfig(),c=await this.getPoolTypeArguments(e);return s.moveCall({target:`${a.PackageId}::position_manager::collect`,typeArguments:c,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()+_s*3,"u64"),s.object(bo.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 vo.TransactionBlock,s=await this.contract.getConfig(),a=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((u,d)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...a,u.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(n),o.object(u.fields.vault),o.pure(d,"u64"),o.pure(i[d],"u64"),o.pure(r),o.pure(Date.now()+_s*3,"u64"),o.object(bo.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new J((t.liquidity||new ja.default(1e8)).toString()),n=new J(t.currentSqrtPrice.toString()),i=new J(t.lowerSqrtPrice.toString()),r=new J(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 J(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 J(0),s=this.math.fromX64_Decimal(e.mul(r.sub(i))));let a=t.ceil!==!1?"ceil":"floor";return[new ja.default(o[a]().toString()),new ja.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,c]=await Promise.all([this.coin.getMetadata(i),this.coin.getMetadata(r)]),u=new J(this.math.scaleDown(o,a.decimals)).mul((e=t.priceA)!=null?e:1),d=new J(this.math.scaleDown(s,c.decimals)).mul((n=t.priceB)!=null?n:1);return{liquidityA:u.toString(),liquidityB:d.toString(),liquidity:u.plus(d).toString()}}parsePool(t){let e=Zi(t),n=_l(t),i=A6(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 J(t),i=new J(1).minus(new J(e).div(100));if(i.lte(0)||i.gt(1))throw new Error("invalid slippage range");return n.mul(i).toFixed(0)}},P6=(t,e)=>{let{pool:n,position:i,tickLowerDetail:r,tickUpperDetail:o}=e,s=new Gr.default(n.fee_growth_global_a),a=new Gr.default(i.fee_growth_inside_a),c=new Gr.default(i.tokens_owed_a),u=new Gr.default(n.fee_growth_global_b),d=new Gr.default(i.fee_growth_inside_b),h=new Gr.default(i.tokens_owed_b),_=new Gr.default(i.liquidity),C,D,O,B,j=t.bitsToNumber(n.tick_current_index.fields.bits),M=t.bitsToNumber(i.tick_lower_index.fields.bits),R=t.bitsToNumber(i.tick_upper_index.fields.bits);j<M?(C=t.subUnderflowU128(s,r.feeGrowthOutsideA),D=t.subUnderflowU128(u,r.feeGrowthOutsideB)):(C=r.feeGrowthOutsideA,D=r.feeGrowthOutsideB),j<R?(O=o.feeGrowthOutsideA,B=o.feeGrowthOutsideB):(O=t.subUnderflowU128(s,o.feeGrowthOutsideA),B=t.subUnderflowU128(u,o.feeGrowthOutsideB));let K=t.subUnderflowU128(t.subUnderflowU128(s,C),O),X=t.subUnderflowU128(t.subUnderflowU128(u,D),B),Y=t.subUnderflowU128(K,a).mul(_).shrn(64),oe=t.subUnderflowU128(X,d).mul(_).shrn(64);return{feeOwedA:c.add(Y).toString(),feeOwedB:h.add(oe).toString()}},Xw=new Fa.default(0),Zw=new Fa.default(1),E6=new Fa.default(2),D6={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(Xw))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,r),s=o.div(n);return i&&o.mod(n).gt(Xw)?s.add(Zw):s},isOverLimit(t,e){let n=E6.pow(new Fa.default(e)).sub(Zw);return t.gt(n)}},B6=(t,e)=>{var n,i,r,o;let{pool:s,position:a,tickLowerDetail:c,tickUpperDetail:u,timeStampInSeconds:d}=e,h=new ki.default(new J(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),C=(d??new ki.default(Date.now()).div(new ki.default(1e3))).sub(new ki.default(h)),D=[],O=new ki.default(s.liquidity),B=new ki.default(a.liquidity);for(let j=0;j<3;++j){let M=s.reward_infos[j],R={emissionsPerSecondX64:new ki.default(M?M.fields.emissions_per_second:"0"),growthGlobalX64:new ki.default(M?M.fields.growth_global:"0")},K={growthInsideCheckpoint:new ki.default((i=(n=a.reward_infos[j])==null?void 0:n.fields.reward_growth_inside)!=null?i:"0"),amountOwed:new ki.default((o=(r=a.reward_infos[j])==null?void 0:r.fields.amount_owed)!=null?o:"0")},X=R.growthGlobalX64;if(!O.isZero()){let I=D6.mulDiv(C,R.emissionsPerSecondX64,O,128);X=R.growthGlobalX64.add(I)}let Y=c.rewardGrowthsOutside[j],oe=u.rewardGrowthsOutside[j],$=X;c.initialized&&($=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_lower_index.fields.bits)?t.subUnderflowU128(X,Y):Y);let ne=new ki.default(0);u.initialized&&(ne=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(a.tick_upper_index.fields.bits)?oe:t.subUnderflowU128(X,oe));let G=t.subUnderflowU128(t.subUnderflowU128(X,$),ne),W=K.amountOwed.shln(64);D[j]=W.add(t.subUnderflowU128(G,K.growthInsideCheckpoint).mul(B)).shrn(64).toString()}return D},M6=class extends Ra{async getOwner(t){let e=await this.getObject(t),n=S6(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 Zi(e)}async getPositionFields(t){let e=await this.contract.getConfig(),n=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return Zi(n)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return Rh(e,"position"),Zi(e)}async getPositionTick(t,e){let n=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),i=Zi(n);if(i)return{tickIndex:this.math.bitsToNumber(i.name.fields.bits),initialized:i.value.fields.initialized,liquidityNet:new ei.default(this.math.bitsToNumber(i.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new ei.default(i.value.fields.liquidity_gross),feeGrowthOutsideA:new ei.default(i.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new ei.default(i.value.fields.fee_growth_outside_b),rewardGrowthsOutside:i.value.fields.reward_growths_outside.map(r=>new ei.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),[c,u,d,h]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),n(s.types[0]),n(s.types[1])]);if(!d||!h||r>=o||a<r||a>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:_,minTokenB:C}=this.getRemoveLiquidityQuote(s,r,o),D=new J(this.math.scaleDown(_.toString(),c.decimals)).mul(d),O=new J(this.math.scaleDown(C.toString(),u.decimals)).mul(h),B=D.add(O),j=B.isZero()?new J(0):new J(i).mul(365).div(B).mul(100),M=new J(0);return await Promise.all(s.reward_infos.map(async R=>{let{emissions_per_second:K}=R.fields,X=this.coin.formatCoinType(R.fields.vault_coin_type),[Y,oe]=await Promise.all([n(X),this.coin.getMetadata(X)]);!K||K==="0"||!Y||(M=M.add(new J(new ei.default(K).shrn(64).toString()).div(10**oe.decimals).mul(31536e3).mul(Y).div(B).mul(100)))})),{fees:j.toString(),rewards:M.toString(),total:j.plus(M).toString()}}getRemoveLiquidityQuote(t,e,n){let i=new ei.default(0),r=new ei.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 u=this.getTokenAFromLiquidity(r,s,a);return{minTokenA:this.adjustForSlippage(u),minTokenB:i}}if(o<n){let u=new ei.default(t.sqrt_price),d=this.getTokenAFromLiquidity(r,u,a),h=this.getTokenBFromLiquidity(r,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:this.adjustForSlippage(h)}}let c=this.getTokenBFromLiquidity(r,s,a);return{minTokenA:i,minTokenB:this.adjustForSlippage(c)}}adjustForSlippage(t){let e={numerator:new ei.default(0),denominator:new ei.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 ty.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 ei.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 ei.default(e.liquidity===void 0?1e8:e.liquidity)}),[a,c]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),u=new J(s[0].toString()).div(10**a.decimals).mul(i||0),d=new J(s[1].toString()).div(10**c.decimals).mul(r||0);return u.plus(d).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,c]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:u,...d}=a,{unclaimedRewards:h,..._}=c;return{fees:a.unclaimedFees.toString(),rewards:h.toString(),total:u.plus(h).toString(),fields:{...d,..._}}}async getUnclaimedFees(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,[s,a,c,u]=await Promise.all([this.coin.getMetadata(n.types[0]),this.coin.getMetadata(n.types[1]),i(n.types[0]),i(n.types[1])]),d=P6(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),h=this.math.scaleDown(d.feeOwedA,s.decimals),_=this.math.scaleDown(d.feeOwedB,a.decimals);function C(B,j){return new J(1e6).mul(J.pow(10,j)).lt(B)}C(h,s.decimals)&&(h="0",d.feeOwedA="0"),C(_,a.decimals)&&(_="0",d.feeOwedB="0");let D=c===void 0?new J(0):new J(c).mul(h),O=u===void 0?new J(0):new J(u).mul(_);return{unclaimedFees:D.plus(O),scaledFeeOwedA:h,scaledFeeOwedB:_,...d}}async getUnclaimedRewards(t){let{position:e,pool:n,getPrice:i,tickLowerDetail:r,tickUpperDetail:o}=t,s=B6(this.math,{pool:n,position:e,tickLowerDetail:r,tickUpperDetail:o}),a=[...s],c=n.reward_infos.map(_=>this.coin.formatCoinType(_.fields.vault_coin_type)),u=await Promise.all([...n.reward_infos.map((_,C)=>this.coin.getMetadata(c[C]))]),d=await Promise.all(n.reward_infos.map((_,C)=>i(c[C])));u.forEach((_,C)=>{a[C]=this.math.scaleDown(a[C],_.decimals)});let h=new J(0);return n.reward_infos.some((_,C)=>{let D=d[C];return D?(h=h.plus(new J(D).mul(a[C])),!1):(h=h.plus(1),!0)}),{unclaimedRewards:h,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 Rh(e,"nft"),e})}},j6=class extends Ra{isSUI(t){return(0,ny.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 J(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,c)=>Number(c.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}},N6=60*1e3,fl=100,R6=class extends Ra{async swap(t){let{coinTypeA:e,coinTypeB:n,address:i,amountSpecifiedIsInput:r,slippage:o}=t,s=new J(t.amountA),a=new J(t.amountB),c=await this.contract.getConfig(),u=await Promise.all(t.routes.map(async O=>{let B=await this.pool.getPoolTypeArguments(O.pool),[j,M]=await Promise.all([this.coin.getMetadata(B[0]),this.coin.getMetadata(B[1])]);return{...O,coinA:j,coinB:M,typeArguments:B}})),d=await this.coin.selectTradeCoins(i,e,s),{functionName:h,typeArguments:_}=this.getFunctionNameAndTypeArguments(u.map(({typeArguments:O})=>O),e,n),C=u.map(({nextTickIndex:O,coinA:B,coinB:j,a2b:M})=>{let R=this.math.tickIndexToPrice(O,B.decimals,j.decimals);return this.sqrtPriceWithSlippage(R,o,M,B.decimals,j.decimals)}),D=t.txb||new pl.TransactionBlock;return D.moveCall({target:`${c.PackageId}::swap_router::${h}`,typeArguments:_,arguments:[...u.map(({pool:O})=>D.object(O)),D.makeMoveVec({objects:this.coin.convertTradeCoins(D,d,e,s)}),D.pure((r?s:a).toFixed(0),"u64"),D.pure(this.amountOutWithSlippage(r?a:s,o,r),"u64"),...C.map(O=>D.pure(O,"u128")),D.pure(r,"bool"),D.pure(i,"address"),D.pure(Date.now()+N6*3,"u64"),D.object(ml.SUI_CLOCK_OBJECT_ID),D.object(c.Versioned)]}),D}async computeSwapResult(t){let{pools:e,amountSpecified:n,amountSpecifiedIsInput:i,address:r,tickStep:o}=t,s=await this.contract.getConfig(),a=e.map(h=>h.pool),c=await Na(this.provider,a,{showContent:!0}),u=new pl.TransactionBlock;c.map(async h=>{let _=Zi(h),C=e.find(M=>M.pool===_.id.id),D=this.math.bitsToNumber(_.tick_current_index.fields.bits),O=D-_.tick_spacing*(o||fl),B=D+_.tick_spacing*(o||fl);O=O<dl?dl:O,B=B>ll?ll:B;let j=this.pool.parsePoolType(gl(h));u.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:j,arguments:[u.object(_.id.id),u.pure(C.a2b,"bool"),u.pure(new J(n).toFixed(0),"u128"),u.pure(i,"bool"),u.pure(this.math.tickIndexToSqrtPriceX64(C.a2b?O:B).toString(),"u128"),u.object(ml.SUI_CLOCK_OBJECT_ID),u.object(s.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:u,sender:r});if(d.error)throw new Error(d.error);return d.events.map(h=>h.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:n,address:i,tickStep:r}=t,o=await this.contract.getConfig(),s=e.map(d=>d.pool),a=await Na(this.provider,Array.from(new Set(s)),{showContent:!0}),c=new pl.TransactionBlock;e.forEach(async d=>{let h=a.find(j=>_l(j)===d.pool),_=Zi(h),C=this.math.bitsToNumber(_.tick_current_index.fields.bits),D=C-_.tick_spacing*(r||fl),O=C+_.tick_spacing*(r||fl);D=D<dl?dl:D,O=O>ll?ll:O;let B=this.pool.parsePoolType(gl(h));c.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:B,arguments:[c.object(_.id.id),c.pure(d.a2b,"bool"),c.pure(new J(d.amountSpecified).toFixed(0),"u128"),c.pure(n,"bool"),c.pure(this.math.tickIndexToSqrtPriceX64(d.a2b?D:O).toString(),"u128"),c.object(ml.SUI_CLOCK_OBJECT_ID),c.object(o.Versioned)]})});let u=await this.provider.devInspectTransactionBlock({transactionBlock:c,sender:i});if(u.error)throw new Error(u.error);return u.events.map(d=>d.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 J(100).minus(e).div(100);return new J(t).mul(r).toFixed(0)}let i=new J(100).plus(e).div(100);return new J(t).mul(i).toFixed(0)}sqrtPriceWithSlippage(t,e,n,i,r){let o=new J(t).mul(n?new J(100).minus(e).div(100):new J(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,i,r);return s.lt(new Fh.BN(Nh))?Nh:s.gt(new Fh.BN(jh))?jh:s.toString()}},Gn=class{constructor(t,e){this.network=t,Xi(this,"pool"),Xi(this,"contract"),Xi(this,"math",new x6),Xi(this,"account",new v6),Xi(this,"coin"),Xi(this,"nft"),Xi(this,"trade"),Xi(this,"provider"),this.provider=e?e instanceof ko.SuiClient?e:new ko.SuiClient(e):new ko.SuiClient({url:t==="mainnet"?(0,ko.getFullnodeUrl)("mainnet"):(0,ko.getFullnodeUrl)("testnet")}),this.contract=new I6(this),this.pool=new O6(this),this.nft=new M6(this),this.coin=new j6(this),this.trade=new R6(this)}};var F6=Object.defineProperty,xy=(t,e)=>{for(var n in e)F6(t,n,{get:e[n],enumerable:!0})},Ye=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Py.default)(this.data))}},tp={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"},li={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"}]}}},Ji=new $o(tp),q6=async(t,e,n)=>(console.log("getAddLiquidityTxb suiClient: ",n),Ji.senderAddress=e.address,await Ji.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),L6=async(t,e,n)=>(console.log("getIncreaseLiquidityTxb suiClient: ",n),Ji.senderAddress=e.address,await Ji.Position.createAddLiquidityFixTokenPayload(t?.parameter,t?.gasEstimateArg)),U6=async(t,e,n)=>(console.log("getRemoveLiquidityTxb suiClient: ",n),Ji.senderAddress=e.address,await Ji.Position.closePositionTransactionPayload(t?.parameter)),$6=async(t,e,n)=>(console.log("getDecreaseLiquidityTxb suiClient: ",n),Ji.senderAddress=e.address,await Ji.Position.removeLiquidityTransactionPayload(t?.parameter)),G6=async(t,e,n)=>(console.log("getClaimFeeAndMiningTxb suiClient: ",n),Ji.senderAddress=e.address,await Ji.Rewarder.collectRewarderTransactionPayload(t?.parameter)),z6=class Ey extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await q6(r,n,i);return console.log("AddLiquidityIntention build txb: ",o),o}static fromData(e){return new Ey(e)}},V6=class Dy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await G6(r,n,i);return console.log("ClaimFeeAndMiningIntention build txb: ",o),o}static fromData(e){return new Dy(e)}},K6=class By extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await $6(r,n,i);return console.log("DecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new By(e)}},zn=new $o(tp),W6=async(t,e,n)=>(console.log("getFarmingAddLiquidityTxb account: ",e),console.log("getFarmingAddLiquidityTxb suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.openPositionAddLiquidityStakePaylod(t?.parameter)),H6=async(t,e,n)=>(console.log("getFarmingIncreaseLiquidityTxb account: ",e),console.log("getFarmingIncreaseLiquidityTxb suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.addLiquidityFixCoinPayload(t?.parameter)),X6=async(t,e,n)=>(console.log("getFarmingDecreaseLiquidityTxb account: ",e),console.log("getFarmingDecreaseLiquidityTxb suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.removeLiquidityPayload(t?.parameter)),Z6=async(t,e,n)=>(console.log("getFarmingRemoveLiquidityTxb account: ",e),console.log("getFarmingRemoveLiquidityTxb suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.removeLiquidityPayload(t?.parameter)),J6=async(t,e,n)=>(console.log("getFarmingClaimFeeAndRewardTxb account: ",e),console.log("getFarmingClaimFeeAndRewardTxb suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.claimFeeAndClmmReward(t?.parameter)),My=async(t,e,n)=>(console.log("getFarmingBatchHarvest account: ",e),console.log("getFarmingBatchHarvest suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.batchHarvestPayload(t?.parameter)),Y6=async(t,e,n)=>(console.log("getFarmingStake account: ",e),console.log("getFarmingStake suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.depositPayload(t?.parameter)),Q6=async(t,e,n)=>(console.log("getFarmingUnstake account: ",e),console.log("getFarmingUnstake suiClient: ",n),zn.senderAddress=e.address,await new Hn(li,zn).Farms.withdrawPayload(t?.parameter)),eO=class jy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await W6(r,n,i);return console.log("FarmingAddLiquidityIntention build txb: ",o),o}static fromData(e){return new jy(e)}},tO=class Ny extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await My(r,n,i);return console.log("FarmingBatchHarvestIntention build txb: ",o),o}static fromData(e){return new Ny(e)}},nO=class Ry extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await J6(r,n,i);return console.log("FarmingClaimFeeAndRewardIntention build txb: ",o),o}static fromData(e){return new Ry(e)}},iO=class Fy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await X6(r,n,i);return console.log("FarmingDecreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Fy(e)}},rO=class qy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await My(r,n,i);return console.log("FarmingHarvestIntention build txb: ",o),o}static fromData(e){return new qy(e)}},oO=class Ly extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await H6(r,n,i);return console.log("FarmingIncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new Ly(e)}},sO=class Uy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Z6(r,n,i);return console.log("FarmingRemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Uy(e)}},aO=class $y extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Y6(r,n,i);return console.log("FarmingStakeIntention build txb: ",o),o}static fromData(e){return new $y(e)}},cO=class Gy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await Q6(r,n,i);return console.log("FarmingUnstakeIntention build txb: ",o),o}static fromData(e){return new Gy(e)}},uO=class zy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await L6(r,n,i);return console.log("IncreaseLiquidityIntention build txb: ",o),o}static fromData(e){return new zy(e)}},lO=class Vy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await U6(r,n,i);return console.log("RemoveLiquidityIntention build txb: ",o),o}static fromData(e){return new Vy(e)}},Yi=new $o(tp),dO=async(t,e,n)=>(console.log("getXcetusConvertTxb account: ",e),console.log("getXcetusConvertTxb suiClient: ",n),Yi.senderAddress=e.address,await new Hn(li,Yi).XCetusModule.convertPayload(t?.parameter)),fO=async(t,e,n)=>(console.log("getXcetusRedeemLockTxb account: ",e),console.log("getXcetusRedeemLockTxb suiClient: ",n),Yi.senderAddress=e.address,await new Hn(li,Yi).XCetusModule.redeemLockPayload(t?.parameter)),hO=async(t,e,n)=>(console.log("getXcetusClaimingStakeRewardsTxb account: ",e),console.log("getXcetusClaimingStakeRewardsTxb suiClient: ",n),Yi.senderAddress=e.address,await new Hn(li,Yi).XCetusModule.redeemDividendV2Payload(t.parameter.venft_id,t.parameter.bonus_types,t.parameter.xTokenType)),pO=async(t,e,n)=>(console.log("getXcetusCancelRedeemTxb account: ",e),console.log("getXcetusCancelRedeemTxb suiClient: ",n),Yi.senderAddress=e.address,await new Hn(li,Yi).XCetusModule.cancelRedeemPayload(t?.parameter)),mO=async(t,e,n)=>(console.log("getXcetusRedeemTxb account: ",e),console.log("getXcetusRedeemTxb suiClient: ",n),Yi.senderAddress=e.address,await new Hn(li,Yi).XCetusModule.redeemPayload(t?.parameter)),gO=class Ky extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await pO(r,n,i);return console.log("XcetusCancelIntention build txb: ",o),o}static fromData(e){return new Ky(e)}},_O=class Wy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await hO(r,n,i);return console.log("XcetusClaimingStakeRewardsIntention build txb: ",o),o}static fromData(e){return new Wy(e)}},wO=class Hy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await dO(r,n,i);return console.log("XcetusConvertIntention build txb: ",o),o}static fromData(e){return new Hy(e)}},yO=class Xy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await mO(r,n,i);return console.log("XcetusRedeemIntention build txb: ",o),o}static fromData(e){return new Xy(e)}},bO=class Zy extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n,suiClient:i}=e,{txbParams:r}=this.data,o=await fO(r,n,i);return console.log("XcetusRedeemLockIntention build txb: ",o),o}static fromData(e){return new Zy(e)}},vO=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{txbParams:e,action:n}=t;return{txType:Oy.TransactionType.Other,txSubType:n,intentionData:{txbParams:e,action:n}}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"OpenAndAddLiquidity":i=z6.fromData(t.intentionData);break;case"IncreaseLiquidity":i=uO.fromData(t.intentionData);break;case"DecreaseLiquidity":i=K6.fromData(t.intentionData);break;case"RemoveLiquidity":i=lO.fromData(t.intentionData);break;case"ClaimFeeAndMining":i=V6.fromData(t.intentionData);break;case"FarmingOpenAndAddLiquidity":i=eO.fromData(t.intentionData);break;case"FarmingIncreaseLiquidity":i=oO.fromData(t.intentionData);break;case"FarmingDecreaseLiquidity":i=iO.fromData(t.intentionData);break;case"FarmingRemoveLiquidity":i=sO.fromData(t.intentionData);break;case"FarmingClaimFeeAndReward":i=nO.fromData(t.intentionData);break;case"FarmingHarvest":i=rO.fromData(t.intentionData);break;case"FarmingBatchHarvest":i=tO.fromData(t.intentionData);break;case"FarmingStake":i=aO.fromData(t.intentionData);break;case"FarmingUnstake":i=cO.fromData(t.intentionData);break;case"xCETUSConvert":i=wO.fromData(t.intentionData);break;case"xCETUSRedeemLock":i=bO.fromData(t.intentionData);break;case"xCETUSClaimStakingRwewards":i=_O.fromData(t.intentionData);break;case"xCETUSCancelRedeem":i=gO.fromData(t.intentionData);break;case"xCETUSRedeem":i=yO.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},Yy={};xy(Yy,{contractId:()=>tb,default:()=>kO,feeObjId:()=>rb,roleObjId:()=>nb,status:()=>eb,transaction:()=>Qy,upgradeCapObjId:()=>ob,vaultObjId:()=>ib});var Qy="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",eb="success",tb="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",nb="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",ib="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",rb="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",ob="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",kO={transaction:Qy,status:eb,contractId:tb,roleObjId:nb,vaultObjId:ib,feeObjId:rb,upgradeCapObjId:ob},sb={};xy(sb,{contractId:()=>ub,default:()=>TO,feeObjId:()=>fb,roleObjId:()=>lb,status:()=>cb,transaction:()=>ab,upgradeCapObjId:()=>hb,vaultObjId:()=>db});var ab="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",cb="success",ub="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",lb="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",db="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",fb="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",hb="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",TO={transaction:ab,status:cb,contractId:ub,roleObjId:lb,vaultObjId:db,feeObjId:fb,upgradeCapObjId:hb},CO="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",AO="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",SO="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",IO="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",xO="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",OO="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",PO="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",EO="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",iy=Yy,ry=sb,DO=new Map([["dev",{env:"dev",rpc:{url:CO},backend:{url:xO},contract:iy}],["stg",{env:"stg",rpc:{url:AO},backend:{url:OO},contract:iy}],["prev",{env:"prev",rpc:{url:SO},backend:{url:PO},contract:ry}],["prod",{env:"prod",rpc:{url:IO},backend:{url:EO},contract:ry}]]);function BO(t,e){let n=DO.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 di=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}},MO=class extends di{constructor(){super(11,"Backend is not specified")}},jO=class extends di{constructor(){super(1,"Wallet not connected")}},Lh=class extends di{constructor(t,e){super(10,t,{context:e})}},NO=class Co{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof gr.AxiosError)throw new Lh(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Lh(e.data.code)}throw new Lh(e.status.toString())}async getIncomingStreams(e,n){let i=await gr.default.post(`${this.apiURL}/stream`,{recipient:e,...n});return Co.parseResponseData(i)}async getOutgoingStreams(e,n){let i=await gr.default.post(`${this.apiURL}/stream`,{sender:e,...n});return Co.parseResponseData(i)}async getStreamHistory(e){let n=await gr.default.post(`${this.apiURL}/stream-events`,e),i=Co.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 gr.default.post(`${this.apiURL}/stream-info`,{address:e});return Co.parseResponseData(n)}async getAllRecipients(e,n){let i=await gr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:n});return Co.parseResponseData(i)}async getAllSenders(e,n){let i=await gr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:n});return Co.parseResponseData(i)}},mb=class gb{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new pb.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new NO(e.backend.url))}static new(e,n){let i=BO(e,n);return new gb(i)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new MO;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 jO;return this.signer}async walletAddress(){return this.wallet.address()}},oy=50n,Uh=10000n,RO=25n,sy=100000000n,To=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},ay=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},kl=class _b{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 _b(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}},cy=class extends di{constructor(t,e){super(3,t,{context:e})}},FO=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 cy("Invalid contract return type.",{ctx:{expectType:"address",gotType:i}});return(0,wb.normalizeSuiAddress)(Vh.Buffer.from(n).toString("hex"))}getU64(t=0,e=0){let[n,i]=this.getValue(t,e);if(i!=="u64")throw new cy("Invalid contract return type.",{ctx:{expectType:"u64",gotType:i}});return Vh.Buffer.from(n).readBigInt64LE()}},ui=class extends di{constructor(t,e,n){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:n}})}},yb={groupId:"string",name:"string"},qO=64;function LO(t){return bb(t),np.bcs.ser(yb,t).toString("base64")}function Kh(t){let e=np.bcs.de(yb,t,"base64");return bb(e),e}function bb(t){if(!uy(t.name))throw new ui("Invalid metadata: Name contains unknown character");if(!uy(t.groupId))throw new ui("Invalid metadata: Group ID contains unknown character");if(t.name.length>qO)throw new ui("Invalid metadata: Name exceed max length 64")}function uy(t){return/^[\x00-\x7F]+$/.test(t)}function vb(t,e){return(0,$a.normalizeStructTag)(t)===(0,$a.normalizeStructTag)(e)}function ws(t,e){return(0,$a.normalizeStructTag)(t)===(0,$a.normalizeStructTag)(e)}var kb="txn.gas";function UO(){return Mw()}var Wh=class Tb{constructor(e,n,i){this.globals=e,this.feeContract=n,this.streamContract=i}static convertCreateStreamInfoToInternal(e){return{metadata:LO({name:e.name,groupId:UO()}),coinType:(0,Ua.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 zh.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 c=0;c<e.recipients.length;c++){let u=e.recipients[c],d=this.amountForRecipient(u,e.numberEpoch),h=this.getStreamFeeLocal(d),[_]=n.splitCoins(s,[n.pure(d+h,"u64")]),[C]=n.splitCoins(a,[n.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(n,{paymentCoin:new kl(_),flatFeeCoin:new kl(C),metadata:e.metadata,recipient:u.address,timeStart:e.startTime,cliff:u.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return n}calculateCreateStreamFees(e){let n=Tb.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(n)}feeParams(){return{createFeePercent:{numerator:oy,denominator:Uh},claimFeePercent:{numerator:RO,denominator:Uh},flatFeePerStream:sy}}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===kb?i=e.gas:i=e.object(n.primaryCoin),i}getCreateStreamCoinRequests(e,n){let i=e.coinType;return vb(i,Ua.SUI_TYPE_ARG)?[{coinType:i,amount:n.totalAmount+n.streamFeeAmount+n.flatFeeAmount}]:[{coinType:i,amount:n.totalAmount+n.streamFeeAmount},{coinType:Ua.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 sy}getStreamFeeLocal(e){return e*oy/Uh}async getStreamFeeRemote(e){let n=this.feeContract.streamingFee(new zh.TransactionBlock,e),i=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:n});return new FO(i).getU64()}get wallet(){return this.globals.wallet}},$O="0x0000000000000000000000000000000000000000000000000000000000000006",Cb=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(Hh.Transactions.MoveCall({target:n,arguments:e.arguments.map(i=>i instanceof ay?i.moveArgs(t):i instanceof To?i.moveArg(t):i instanceof kl?i.moveArg():t.pure(i)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,n=[],i=[]){t.add(Hh.Transactions.MoveCall({target:e,arguments:n.map(r=>r instanceof ay?r.moveArgs(t):r instanceof To?r.moveArg(t):r instanceof kl?r.moveArg():t.pure(r)),typeArguments:i}))}makeObject(t){return typeof t=="string"?new To(t):t}vaultObject(){return new To(this.config.vaultObjId)}roleObject(){return new To(this.config.roleObjId)}feeObject(){return new To(this.config.feeObjId)}clockObject(){return new To($O)}},Ab=class zr extends Cb{constructor(e,n){super(zr.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:zr.MethodName.set_streaming_fee,arguments:[i,r,n],typeArgs:[]})}setStreamingFlatFee(e,n){let i=this.roleObject(),r=this.feeObject();return this.addContractCall(e,{method:zr.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:zr.MethodName.set_claim_fee,arguments:[i,r,n],typeArgs:[]})}streamingFee(e,n){let i=this.feeObject();return this.addContractCall(e,{method:zr.MethodName.streaming_fee,arguments:[i,n],typeArgs:[]})}claimFee(e,n){return this.addContractCall(e,{method:zr.MethodName.claim_fee,arguments:[this.feeObject(),n],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:zr.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},Cl=class Pn extends Cb{constructor(e,n){super(Pn.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:Pn.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:Pn.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:Pn.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:Pn.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:Pn.MethodName.claim_stream_by_proxy,arguments:[i,r,o,s],typeArgs:[n.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Pn.ModuleName}::${Pn.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Pn.ModuleName}::${Pn.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Pn.ModuleName}::${Pn.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Pn.ModuleName}::${Pn.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Pn.ModuleName}::${Pn.MethodName.claim_stream_by_proxy}`}},Sb=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Ab(e,t),this.streamContract=new Cl(e,t)}feeContract;streamContract;async createStreams(t){let e=Wh.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Wh(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,n){let i=new qa.TransactionBlock;return this.streamContract.setAutoClaim(i,{streamId:t,enabled:e,coinType:n})}claimStream(t,e){let n=new qa.TransactionBlock;return this.streamContract.claimStream(n,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let n=new qa.TransactionBlock;return this.streamContract.claimStreamByProxy(n,{streamId:t,coinType:e})}cancelStream(t,e){let n=new qa.TransactionBlock;return this.streamContract.cancelStream(n,{streamId:t,coinType:e}),n}},GO=class extends di{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},zO=1e3,VO=class{constructor(t){this.globals=t,this.coinMetaHelper=new KO(t.suiClient),this.createStreamHelper=new Sb(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new GO(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 ui("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 ui("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 ui("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,n=t.timeStart.plus(pt.fromMillis(Number(e*t.steps))),i={timeStart:t.timeStart,timeEnd:n,interval:pt.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,vs.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,vs.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 ui("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new ui("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<zO)throw new ui("Interval shall be at least 1 second","interval",t.interval)}},KO=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,vs.normalizeStructTag)(t||vs.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}},WO=class extends di{constructor(){super(7,"Connected wallet is not creator")}},ly=class extends di{constructor(){super(8,"Connected wallet is not recipient")}},dy=class extends di{constructor(t,e){super(6,t,{context:e})}},qi=class extends di{constructor(t,e={}){super(0,t,e)}},HO=class extends di{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},XO=(1n<<64n)-1n,Tl=1e3;function fy(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/Tl);return Je.fromMillis(n*Tl)}function hy(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let n=Math.round(e/Tl);return pt.fromMillis(n*Tl)}var ip=class Vr{constructor(e,n,i){this.globals=e,this.streamId=n,this.rawData=i,this.streamContract=new Cl(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,n){let i=await Vr.fetchStreamData(e,n);return new Vr(e,n,i)}static fromObjectData(e,n,i){let r=Vr.parseRawStreamData(n,i);return new Vr(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 Vr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new qi("Object Id does not align");this.rawData=Vr.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 WO;let e=new La.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new ly;let e=new La.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 ly;let n=new La.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:this.streamId,coinType:this.coinType,enabled:e}),n}async claimByProxy(){let e=new La.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,Ga.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 hy(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Kh(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Kh(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return fy(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,n=e.epochInterval*e.totalEpoch;return hy(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:fy((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===XO?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=Je.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 Vr.parseRawStreamData(n,i)}static parseRawStreamData(e,n){if(n.error)throw n.error.code==="notExists"?new HO(e):new dy(`get stream data: ${n.error.code}`,{streamId:e,...n.error});let i=n.data.content;if(i.dataType!=="moveObject")throw new dy("Unexpected object type",{gotType:i.dataType});let{typeParams:r}=(0,Ga.parseStructTag)(i.type),o=(0,Ga.normalizeStructTag)(r[0]),s=i.fields,a=s.config.fields,c=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:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}},$h=class extends di{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function ZO(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 JO=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)}},Ib=class{constructor(t){this.requester=t,this.pager=new JO(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]}},YO=25;async function py(t,e,n){let i=new xb(e),r=new Ob(t,i,n);return await ZO(r)}var xb=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]}},Ob=class extends Ib{constructor(t,e,n){super(new QO(t,e,n)),this.suiClient=t,this.idIter=e,this.options=n}},QO=class{constructor(t,e,n){this.suiClient=t,this.stringIter=e,this.options=n,this.filter=n?.filter,this.pageSize=n?.pageSize||YO,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()}}},eP=class wl{constructor(e,n){if(this.globals=e,this.streams=n,n.length===0)throw new $h("stream size 0");let i=n.map(r=>r.groupId);if(new Set(i).size!==1)throw new ui("Stream does not have same group ID")}type="StreamGroup";static async new(e,n){let i=await py(e.suiClient,n);return i.forEach(r=>{if(!r)throw new qi("stream group object data undefined")}),wl.newFromObjectResponse(e,n,i)}static async newFromObjectResponse(e,n,i){let r=await wl.parseGroupStreams(e,n,i);return new wl(e,r)}static checkStreamGroup(e){let n=e.map(o=>o.groupCommonInfo),i=n[0],r=!0;return n.forEach(o=>{tP(i,o)||(r=!1)}),r}async refresh(){let e=await py(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)=>ip.fromObjectData(e,n[s],o)).filter(o=>!!o);if(new Set(r.map(o=>o.groupId)).size!==1)throw new $h("Not same group ID");if(!this.checkStreamGroup(r))throw new $h("Not same stream settings");return r}};function tP(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 my=class Xh{constructor(e,n){this.it=e,this.pageSize=n}static async newIncoming(e){let n=await gy.newIncoming(e);return new Xh(n,e.pageSize)}static async newOutgoing(e){let n=await gy.newOutgoing(e);return new Xh(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}},gy=class Zh{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let n=await _y.newIncomingQuery(e);return new Zh(n)}static async newOutgoing(e){let n=await _y.newOutgoingQuery(e);return new Zh(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 qi("No more results");return n}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new qi("No more results");return e}},_y=class Jh{constructor(e,n,i,r){this.globals=e,this.recipient=n,this.groupRefs=i,this.query=r,this.current=0;let o=new xb(i.flat().map(s=>s.streamId));this.objectIter=new Ob(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let n=sP(e.query),i=await e.globals.walletAddress(),r=(await e.globals.backend.getIncomingStreams(i,n)).filter(s=>(0,Xr.normalizeSuiAddress)(s.recipient)===(0,Xr.normalizeSuiAddress)(i)),o=wy(r);return new Jh(e.globals,i,o,e.query)}static async newOutgoingQuery(e){let n=aP(e.query),i=await e.globals.walletAddress(),r=await e.globals.backend.getOutgoingStreams(i,n),o=wy(r);return new Jh(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 rP(this.globals,e[0].streamId,this.objectIter);return this.current++,Pb(n,this.query)?n:this.doNextRequest()}if(e.length>1){let n=await oP(this.globals,e.map(i=>i.streamId),this.objectIter);return this.current++,iP(n,this.query)?n:this.doNextRequest()}throw new qi("Stream group with no stream")}};function wy(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)=>Je.fromISO(i[0].createDate).toMillis()-Je.fromISO(n[0].createDate).toMillis())}function Pb(t,e){if(e===void 0)return!0;let n=nP(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 nP(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function iP(t,e){if(!e)return!0;let n=!1;return t.streams.forEach(i=>{Pb(i,e)&&(n=!0)}),n}async function rP(t,e,n){let i=await Eb(n,e);return ip.fromObjectData(t,e,i)}async function oP(t,e,n){let i=[];for(;i.length<e.length;){let r=await Eb(n,e[i.length]);i.push(r)}return eP.newFromObjectResponse(t,e,i)}async function Eb(t,e){if(!await t.hasNext())throw new qi("object iterator has been consumed");let n=await t.next();if(!n||n.error||n.data===void 0||n.data===null)throw new qi("object iterator undefined response",{cause:n?.error});if(n?.data?.objectId!==e)throw new qi("stream id not aligned");return n}function sP(t){return{status:rp(t?.status),coinType:Db(t?.coinType),sender:Bb(t?.sender)}}function aP(t){return{status:rp(t?.status),coinType:Db(t?.coinType),recipient:Bb(t?.recipient)}}function rp(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,n)=>{let i=rp(n);return!e||e===i?i:"all"},void 0):cP(t)}function cP(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new ui("Unknown stream filtered status")}}function Db(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Xr.normalizeStructTag)(e)):void 0:(0,Xr.normalizeStructTag)(t)}function Bb(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Xr.normalizeSuiAddress)(e)):void 0:(0,Xr.normalizeSuiAddress)(t)}var uP=class extends di{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}},lP=25;async function dP(t,e,n,i="0x2::sui::SUI",r=lP){let o=new fP(t,e,i,r),s=BigInt(0),a=[];for(;await o.hasNext()&&s<n;){let c=await o.next();c&&(a.push(c),s+=BigInt(c.balance))}if(s<n)throw new uP(i,n,s);return a}var fP=class extends Ib{constructor(t,e,n,i){super(new hP(t,e,n,i)),this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i}},hP=class{constructor(t,e,n,i){if(this.suiClient=t,this.owner=e,this.coinType=n,this.reqPageSize=i,i<=0)throw new qi("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}}},pP=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},mP=class{constructor(t){this.account=t}async address(){return this.account.address}},gP=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(vb(t.coinType,Ao.SUI_TYPE_ARG))return{primaryCoin:kb};if(t.amount<=0)throw new ui("Invalid coin request","coinAmount",t.amount);let e=await dP(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new qi("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(n=>n.coinObjectId)}}},_P=class{globals;helper;constructor(t,e){this.globals=mb.new(t,e),this.helper=new VO(this.globals)}connectSingleWallet(t){let e=new gP(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new pP(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ip.new(this.globals,t)}async getIncomingStreams(t,e=10){return my.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return my.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,Ao.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(n=>(0,Ao.normalizeSuiAddress)(n))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(n=>(0,Ao.normalizeSuiAddress)(n))}get wallet(){return this.globals.wallet}builder(){return new Sb(this.globals)}},wP=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Mb.default)(this.data))}},za=class extends wP{application="mpay";getClient(t,e){let n=new _P(t==="sui:mainnet"?"prod":"dev");return n.connectSingleWallet(new mP(e)),n}},yy=class extends za{constructor(t){super(t),this.data=t}txType=Jy.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).cancel()}},by=class extends za{constructor(t){super(t),this.data=t}txType=jb.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claimByProxy()}},vy=class extends za{constructor(t){super(t),this.data=t}txType=Nb.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:n}=t;return(await this.getClient(e,n).getStream(this.data.streamId)).claim()}},ky=class extends za{constructor(t){super(t),this.data=t}txType=Rb.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:n}=t;return this.getClient(e,n).createStream(this.data)}},Fb=class yl{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return yl.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return yl.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return BigInt(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,Kr.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 yl.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 Yh.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,Kr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Kr.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,Kr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Kr.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 Yh.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,Kr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},yP=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"&&ws(e.target,this.contract.createStreamTarget));if(t.length===0)throw new qi("No create stream transactions");return t.map(e=>new Fb(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:n,groupId:i}=Kh(e),r=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),a=t.decodeInputU64(8),c=t.decodeInputU64(9),u=t.decodeInputU64(10),d=t.decodeInputBool(11),h=t.typeArg(0);return{name:n,groupId:i,recipient:r,timeStart:o,cliff:s,epochInterval:a,totalEpoch:c,amountPerEpoch:u,cancelable:d,coinType:h}}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 ui("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 Cl(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ab(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Wh(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]}},bP=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new Cl(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"&&ws(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ws(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ws(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ws(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&ws(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new yP(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 Fb(t,this.txb)}},Ty=class extends za{constructor(t){super(t),this.data=t}txType=qb.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)}},vP=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:n}=t,i=mb.new(e==="sui:mainnet"?"prod":"dev"),r=new bP(i,n).decode(),o;switch(r.type){case"CreateStream":o=new ky(r.info);break;case"SetAutoClaim":o=new Ty({streamId:r.streamId,enabled:r.enabled});break;case"Claim":o=new vy({streamId:r.streamId});break;case"ClaimByProxy":o=new by({streamId:r.streamId});break;case"Cancel":o=new yy({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 ky(e);break;case"Claim":n=new vy(e);break;case"ClaimByProxy":n=new by(e);break;case"SetAutoClaim":n=new Ty(e);break;case"Cancel":n=new yy(e);break;default:throw new Error("not implemented")}return n.build({...t})}},kP=class Ub extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,Lb.buildCoinTransferTxb)(n,this.data,i.address)}static fromData(e){return new Ub(e)}},TP=class Gb extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:n,account:i}=e;return(0,$b.buildObjectTransferTxb)(n,this.data,i.address)}static fromData(e){return new Gb(e)}},CP=class Kb extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:n}=e,i=Vb.TransactionBlock.from(this.data.content);if(!(0,zb.isSameAddress)(i.blockData.sender,n.address))throw new Error("Invalid sender address");return i}static fromData(e){return new Kb(e)}},AP=class{application;constructor(){this.application=bs.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 bs.TransactionSubTypes.assets.coin.send:i=kP.fromData(t.intentionData);break;case bs.TransactionSubTypes.assets.object.send:i=TP.fromData(t.intentionData);break;case bs.TransactionSubTypes.others.plain:i=CP.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},SP={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"}}},We=SP,IP=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(`${We.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${We.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${We.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${We.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${We.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(We.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===`${We.ProtocolPackage}::incentive_v2::claim_reward`){let n=new Cy(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:ys.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:ys.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:ys.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:ys.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:ys.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:n.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(We.ProtocolPackage));return new Cy(t,this.txb)}},Cy=class bl{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return bl.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return bl.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,Wr.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 bl.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 Qh.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,Wr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Wr.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,Wr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Wr.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 Qh.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,Wr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function Ay(t,e,n,i){return t.moveCall({target:`${We.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(We.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(We.Incentive),t.object(We.IncentiveV2)],typeArguments:[e.type]}),t}function xP(t,e,n){return t.moveCall({target:`${We.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(We.PriceOracle),t.object(We.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(We.Incentive),t.object(We.IncentiveV2)],typeArguments:[e.type]}),t}function OP(t,e,n){return t.moveCall({target:`${We.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(We.PriceOracle),t.object(We.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(n),t.object(We.IncentiveV2)],typeArguments:[e.type]}),t}function Sy(t,e,n,i){return t.moveCall({target:`${We.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(We.PriceOracle),t.object(We.StorageId),t.object(e.poolId),t.pure(e.assetId),n,t.pure(i),t.object(We.IncentiveV2)],typeArguments:[e.type]}),t}function PP(t,e,n,i,r){return t.moveCall({target:`${We.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(We.IncentiveV2),t.object(n),t.object(We.StorageId),t.pure(e),t.pure(i)],typeArguments:r}),t}var EP=class Xb extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,n=new Hb.TransactionBlock;return e.forEach(i=>{let{assetId:r,poolId:o,option:s,typeArguments:a}=i;PP(n,r,o,s,a)}),n}static fromData(e){return new Xb(e)}},DP=class Jb extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new Zb.TransactionBlock;console.log("build",this.data);let r=We.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(We.pool).join(", ")}.`);return OP(i,r,n)}static fromData(e){return new Jb(e)}};async function Qb(t,e,n){let i=await t.getCoins({owner:e,coinType:n});return console.log("getTokenObjs",e,i),i}var BP=class ev extends Ye{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 Yb.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[d]=s.splitCoins(s.gas,[o]);return Ay(s,We.pool.sui,d,o)}let a=We.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(We.pool).join(", ")}.`);let c=await Qb(n,i.address,a.type);if(!c.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let u=c.data[0].coinObjectId;if(c.data.length>=2){let d=1;for(;d<c.data.length;)s.mergeCoins(u,[c.data[d].coinObjectId]),d++}return Ay(s,a,s.object(u),o)}static fromData(e){return new ev(e)}},MP=class nv extends Ye{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 tv.TransactionBlock;if(console.log("build",this.data),r==="sui"){let[d]=s.splitCoins(s.gas,[o]);return Sy(s,We.pool.sui,d,o)}let a=We.pool[r];if(!a)throw new Error(`${r} not support, please use ${Object.keys(We.pool).join(", ")}.`);let c=await Qb(n,i.address,a.type);if(!c.data[0])throw new Error(`Insufficient balance for ${a.name} Token`);let u=c.data[0].coinObjectId;if(c.data.length>=2){let d=1;for(;d<c.data.length;)s.mergeCoins(u,[c.data[d].coinObjectId]),d++}return Sy(s,a,s.object(u),o)}static fromData(e){return new nv(e)}},jP=class rv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:n}=this.data,i=new iv.TransactionBlock;console.log("build",this.data);let r=We.pool[e];if(!r)throw new Error(`${e} not support, please use ${Object.keys(We.pool).join(", ")}.`);return xP(i,r,n)}static fromData(e){return new rv(e)}},NP=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,n=new IP(e).decode();return{txType:Wb.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:n}=t,i;switch(t.txSubType){case"EntryDeposit":i=BP.fromData(t.intentionData);break;case"EntryBorrow":i=DP.fromData(t.intentionData);break;case"EntryRepay":i=MP.fromData(t.intentionData);break;case"EntryWithdraw":i=jP.fromData(t.intentionData);break;case"ClaimReward":i=EP.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:n})}},RP=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}},FP="msafe-plain-tx",qP=Al.TransactionSubTypes.others.plain,LP=class{application;constructor(){this.application=FP}async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=await e.build({client:n});return{txType:Al.TransactionType.Other,txSubType:qP,intentionData:{content:(0,Sl.toHEX)(i)}}}async build(t){let{suiClient:e,account:n}=t,i=ov.TransactionBlock.from((0,Sl.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}},Gh={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},UP=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Gh.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Gh.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${Gh.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),n=this.helper.decodeInputU64(8),i=this.helper.decodeInputU64(9),r=this.helper.decodeInputU32(5),o=this.helper.decodeInputU32(7);return{txType:av.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:n,amountB:i,tickLower:r,tickUpper:o}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new $P(t,this.txb)}},$P=class vl{constructor(e,n){this.moveCall=e,this.txb=n}decodeSharedObjectId(e){let n=this.getInputParam(e);return vl.getSharedObjectId(n)}decodeOwnedObjectId(e){let n=this.getInputParam(e);return vl.getOwnedObjectId(n)}decodeInputU64(e){let n=this.decodePureArg(e,"u64");return Number(n)}decodeInputU32(e){let n=this.decodePureArg(e,"u32");return Number(n)}decodeInputU8(e){let n=this.decodePureArg(e,"u8");return Number(n)}decodeInputAddress(e){let n=this.decodePureArg(e,"address");return(0,Hr.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 vl.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 ep.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,Hr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Hr.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,Hr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Hr.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 ep.bcs.de(n,new Uint8Array(i))}typeArg(e){return(0,Hr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},GP=class cv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,tickLower:c,tickUpper:u,txb:d}=this.data;return n.pool.addLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,tickLower:c,tickUpper:u,txb:d})}static fromData(e){return new cv(e)}},zP=class uv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(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 uv(e)}},VP=class lv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,collectAmountA:s,collectAmountB:a,txb:c}=this.data;return n.pool.collectFee({pool:i,address:r,collectAmountA:s,collectAmountB:a,nft:o,txb:c})}static fromData(e){return new lv(e)}},KP=class dv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,nft:o,rewardAmounts:s,txb:a}=this.data;return n.pool.collectReward({pool:i,address:r,rewardAmounts:s,nft:o,txb:a})}static fromData(e){return new dv(e)}},WP=class fv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{fee:i,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:c,coinTypeA:u,coinTypeB:d,amountA:h,amountB:_,txb:C}=this.data;return n.pool.createPool({fee:i,amountA:h,amountB:_,address:r,tickLower:o,tickUpper:s,sqrtPrice:a,slippage:c,coinTypeA:u,coinTypeB:d,txb:C})}static fromData(e){return new fv(e)}},HP=class hv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:c,decreaseLiquidity:u,txb:d}=this.data;return n.pool.decreaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:c,decreaseLiquidity:u,txb:d})}static fromData(e){return new hv(e)}},XP=class pv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:c,txb:u}=this.data;return n.pool.increaseLiquidity({pool:i,slippage:a,address:r,amountA:o,amountB:s,nft:c,txb:u})}static fromData(e){return new pv(e)}},ZP=class mv extends Ye{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let n=new Gn(e.network.replace("sui:",""),e.suiClient),{pool:i,address:r,amountA:o,amountB:s,slippage:a,nft:c,decreaseLiquidity:u,collectAmountA:d,collectAmountB:h,rewardAmounts:_,txb:C}=this.data;return n.pool.removeLiquidity({pool:i,decreaseLiquidity:u,nft:c,amountA:o,amountB:s,slippage:a,address:r,collectAmountA:d,collectAmountB:h,rewardAmounts:_,txb:C})}static fromData(e){return new mv(e)}},Iy=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:n}=t,i=new UP(e).decode();return{txType:sv.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=WP.fromData(t.intentionData);break;case"AddLiquidity":r=GP.fromData(t.intentionData);break;case"IncreaseLiquidity":r=XP.fromData(t.intentionData);break;case"DecreaseLiquidity":r=HP.fromData(t.intentionData);break;case"RemoveLiquidity":r=ZP.fromData(t.intentionData);break;case"CollectFee":r=VP.fromData(t.intentionData);break;case"CollectReward":r=KP.fromData(t.intentionData);break;case"Burn":r=zP.fromData(t.intentionData);break;default:throw new Error("not implemented")}return r.build({suiClient:e,account:n,network:i})}},Il=new RP([new AP,new NP,new Iy,new vP,new LP,new vO,new Iy]);var at=require("@msafe/sui3-utils"),hp=require("@mysten/sui.js/transactions"),Ml=require("@mysten/sui.js/utils");var gv=require("@mysten/sui.js/transactions"),JP=1000n,YP=120n,QP=100n,e4={multiplier:{numerator:YP,denominator:QP}};var xl=class{constructor(e){this.globals=e}async simulate(e,n=e4){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,c=this.toGasBudget(a,o),u=s.effects.status.status==="success",d;return u||(d=s.effects.status.error),{success:u,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:a,gasBudget:c,simulationError:d}}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=JP*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 gv.TransactionBlock.from(e.serialize())}};var op=require("buffer");function Ol(t){return op.Buffer.from(t,"utf-8")}function t4(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function Pl(t){return Uint8Array.from(op.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var Dl=require("@mysten/sui.js/verify");var Zr=require("@mysten/sui.js/utils");var El=require("@mysten/sui.js/utils"),Va=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let n=(0,El.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}},sp=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Ka=class t{static isCoin(e){return e?(0,El.normalizeStructTag)(e).match(sp)!=null:!1}static getCoinType(e){let[,n]=(0,El.normalizeStructTag)(e).match(sp)??[];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 _r=class{static normalizeSuiAddress(e){return(0,Zr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,Zr.normalizeStructTag)(e)}static isSuiAddressEqual(e,n){return(0,Zr.normalizeSuiAddress)(e)===(0,Zr.normalizeSuiAddress)(n)}static isSuiStructEqual(e,n){return(0,Zr.normalizeStructTag)(e)===(0,Zr.normalizeStructTag)(n)}static isCoinObjectType(e){return Ka.isCoin(e)}};function ap(t,e){return t.startsWith(e)?t:e+t}var cp=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,Dl.verifyTransactionBlock)(e.message,e.signature):(0,Dl.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let n=Ol(e.messageStr);return this.getPublicKeyFromSignature({message:n,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let n=await t.getPublicKeyFromSignature(e);return _r.isSuiAddressEqual(n.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let n=Ol(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 _v=require("@msafe/sui3-utils"),wv=require("@mysten/sui.js/cryptography"),yv=require("@mysten/sui.js/multisig");var n4="0x2::sui::SUI";async function up(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=i4(s,e);if(a)return a}}function i4(t,e){let n=(0,wv.parseSerializedSignature)(t);switch(n.signatureScheme){case"MultiSig":{let i=new yv.MultiSigPublicKey(n.multisig.multisig_pk).toSuiAddress();if(_r.isSuiAddressEqual(i,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(_r.isSuiAddressEqual(n.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let i=_v.PublicKeySerde.de({publicKeyEncoded:n.publicKey,schema:n.signatureScheme});return _r.isSuiAddressEqual(i.toSuiAddress(),e)?i:void 0}default:throw new Error("Unknown schema")}}async function r4(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 bv=25;async function vv(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 lp=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)}},Bl=class{constructor(e){this.requester=e;this.pager=new lp(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 kv(t,e,n){let i=new dp(t,e,n);return await vv(i)}var dp=class extends Bl{constructor(n,i,r){super(new fp(n,i,r));this.provider=n;this.owner=i;this.options=r}},fp=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||bv,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 So=class t{constructor(e,n){this.globals=e;this.info=n;this.multiSig=new at.MultiSigAccount({threshold:n.threshold,ownersWithWeight:n.owners,creationNonce:n.creationNonce}),this.coinHelper=new Va(this.suiClient),this.simulator=new xl(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,Ml.normalizeStructTag)(n.coinType),balance:BigInt(r),metadata:i}}))}async ownedObjects(e){let n={filter:i=>!i?.data?.type?.startsWith("0x2::coin::Coin"),...e};return kv(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=Il.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=at.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=Il.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,Ml.toHEX)(r),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Assets,txSubType:at.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async proposeCoinTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Assets,txSubType:at.TransactionSubTypes.assets.coin.send,sequenceNumber:n,intention:e})}async simulateObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Assets,txSubType:at.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async proposeObjectTransferIntention(e){let n=await this.nextSequenceNumber();return this.proposeIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Assets,txSubType:at.TransactionSubTypes.assets.object.send,sequenceNumber:n,intention:e})}async simulatePlainPayloadIntention(e){let n=await this.nextSequenceNumber();return this.simulateIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Other,txSubType:at.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async proposePlainPayloadIntention(e){let n=await this.nextSequenceNumber(),i=hp.TransactionBlock.from(e.payload);if(!i.blockData.sender||!(0,at.isSameAddress)(i.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:at.TransactionDefaultApplication,txType:at.TransactionType.Other,txSubType:at.TransactionSubTypes.others.plain,sequenceNumber:n,intention:e})}async voteForTransaction(e,n){let i=Pl(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 hp.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,at.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,at.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=Il.getAppHelper(e.application);if(!n)throw new Error(`Can't find app helper for application ${e.application}`);let i=await n.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:i,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,n=!1){let i=n?e.rejectVotes:e.votes,r=n?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(i)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(i.map(c=>[c.userAddress,c.signature]));for(let c=0;c<this.info.owners.length;c++){let u=this.info.owners[c],d=s.get(u.address);d&&o.push(d)}let a=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:Pl(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,at.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 Tv=require("@msafe/sui3-utils"),Cv=require("@mysten/sui.js/utils");var jl=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,Tv.isSameAddress)(e,n.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,Cv.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 up(this.globals.suiClient,e)}};var Nl=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Ev=require("@mysten/sui.js/client");var Ha=require("@msafe/sui3-utils"),Wa=Pe(require("axios"),1);var Rl=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?Ha.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??Ha.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:Ha.PublicKeySerde.de({publicKeyEncoded:n.publicKeyEncoded,schema:n.schema})}))}}async get(e,n){let i=this.getFullUrl(e);try{return await Wa.default.get(i,n)}catch(r){throw Fl.fromError(r)??r}}async post(e,n,i){let r=this.getFullUrl(e);try{return await Wa.default.post(r,n,{...i,transformRequest:this.getTransformRequest()})}catch(o){throw Fl.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${ap(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:n}=Wa.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]}},Fl=class t extends Error{constructor(n){super();this.e=n;Error.captureStackTrace(this,this.constructor)}name;static fromError(n){if(Wa.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 Av=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Av||{}),ql="https://fullnode.testnet.sui.io",pp="https://fullnode.mainnet.sui.io",mp="http://127.0.0.1:3000",gp="http://127.0.0.1:3001",Sv="https://sui-dev.m-safe.link",Iv="http://13.56.226.148:81",xv="https://sui-preview.m-safe.link",Ov="https://sui.m-safe.link",Pv=new Map([["unit",{suiClient:{url:ql},backend:{url:mp},syncingURL:gp,network:"sui:testnet"}],["local",{suiClient:{url:ql},backend:{url:mp},syncingURL:gp,network:"sui:testnet"}],["dev",{suiClient:{url:ql},backend:{url:Sv},syncingURL:Iv,network:"sui:testnet"}],["prev",{suiClient:{url:pp},backend:{url:xv},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:pp},backend:{url:Ov},syncingURL:"",network:"sui:mainnet"}]]);function _p(t,e){let n=Pv.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 Xa=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=_p(e,n),r=new Ev.SuiClient(i.suiClient),o=new Rl(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 Ll=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,n){let i=await Xa.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=Ul.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:Ul.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new So(this.globals,e)}async getMSafeAccountFromAddress(e){let n=await this.backend.getMSafeAccountInfo(e);return new So(this.globals,n)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Io(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new jl(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 xo(this.globals)}get Invitation(){return new fc(this.globals)}get Report(){return new Nl(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2053
|
+
`);var Ii=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,du=typeof process=="object"&&process?process:{},kf=(t,e,r,n)=>{typeof du.emitWarning=="function"?du.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},Ho=globalThis.AbortController,Sf=globalThis.AbortSignal;if(typeof Ho>"u"){Sf=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Ho=class{constructor(){e()}signal=new Sf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=du.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,kf("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var yy=t=>!xf.has(t),pT=Symbol("type"),Or=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Af=t=>Or(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Nn:null:null,Nn=class extends Array{constructor(e){super(e),this.fill(0)}},fu=class t{heap;length;static#u=!1;static create(e){let r=Af(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Zo=class t{#u;#d;#y;#p;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#i;#r;#e;#c;#f;#a;#o;#g;#s;#T;#S;#w;#b;#k;#l;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#w,sizes:e.#T,keyMap:e.#i,keyList:e.#r,valList:e.#e,next:e.#c,prev:e.#f,get head(){return e.#a},get tail(){return e.#o},free:e.#g,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,o)=>e.#P(r,n,i,o),moveToTail:r=>e.#C(r),indexes:r=>e.#_(r),rindexes:r=>e.#v(r),isStale:r=>e.#h(r)}}get max(){return this.#u}get maxSize(){return this.#d}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#O}get dispose(){return this.#y}get disposeAfter(){return this.#p}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:u,allowStale:l,dispose:d,disposeAfter:b,noDisposeOnSet:_,noUpdateTTL:T,maxSize:x=0,maxEntrySize:A=0,sizeCalculation:I,fetchMethod:C,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:P,allowStaleOnFetchRejection:D,allowStaleOnFetchAbort:L,ignoreFetchAbort:H}=e;if(r!==0&&!Or(r))throw new TypeError("max option must be a nonnegative integer");let W=r?Af(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#u=r,this.#d=x,this.maxEntrySize=A||this.#d,this.sizeCalculation=I,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(C!==void 0&&typeof C!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#O=C,this.#k=!!C,this.#i=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#c=new W(r),this.#f=new W(r),this.#a=0,this.#o=0,this.#g=fu.create(r),this.#n=0,this.#m=0,typeof d=="function"&&(this.#y=d),typeof b=="function"?(this.#p=b,this.#s=[]):(this.#p=void 0,this.#s=void 0),this.#b=!!this.#y,this.#l=!!this.#p,this.noDisposeOnSet=!!_,this.noUpdateTTL=!!T,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!D,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!H,this.maxEntrySize!==0){if(this.#d!==0&&!Or(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!Or(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!P,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!u,this.ttlResolution=Or(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!Or(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#u===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#d){let K="LRU_CACHE_UNBOUNDED";yy(K)&&(xf.add(K),kf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",K,t))}}getRemainingTTL(e){return this.#i.has(e)?1/0:0}#D(){let e=new Nn(this.#u),r=new Nn(this.#u);this.#w=e,this.#S=r,this.#B=(o,s,u=Ii.now())=>{if(r[o]=s!==0?u:0,e[o]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#h(o)&&this.delete(this.#r[o])},s+1);l.unref&&l.unref()}},this.#A=o=>{r[o]=e[o]!==0?Ii.now():0},this.#x=(o,s)=>{if(e[s]){let u=e[s],l=r[s];o.ttl=u,o.start=l,o.now=n||i();let d=o.now-l;o.remainingTTL=u-d}};let n=0,i=()=>{let o=Ii.now();if(this.ttlResolution>0){n=o;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#i.get(o);if(s===void 0)return 0;let u=e[s],l=r[s];if(u===0||l===0)return 1/0;let d=(n||i())-l;return u-d},this.#h=o=>e[o]!==0&&r[o]!==0&&(n||i())-r[o]>e[o]}#A=()=>{};#x=()=>{};#B=()=>{};#h=()=>!1;#F(){let e=new Nn(this.#u);this.#m=0,this.#T=e,this.#I=r=>{this.#m-=e[r],e[r]=0},this.#N=(r,n,i,o)=>{if(this.#t(n))return 0;if(!Or(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(n,r),!Or(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#d){let o=this.#d-e[r];for(;this.#m>o;)this.#E(!0)}this.#m+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#m)}}#I=e=>{};#M=(e,r,n)=>{};#N=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#o;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#v({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#R(r)||((e||!this.#h(r))&&(yield r),r===this.#o));)r=this.#c[r]}#R(e){return e!==void 0&&this.#i.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#v())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#_()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#v()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#_())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#v())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#_()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#v()){let i=this.#e[n],o=this.#t(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#v({allowStale:!0}))this.#h(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#_({allowStale:!0})){let n=this.#r[r],i=this.#e[r],o=this.#t(i)?i.__staleWhileFetching:i;if(o===void 0||n===void 0)continue;let s={value:o};if(this.#w&&this.#S){s.ttl=this.#w[r];let u=Ii.now()-this.#S[r];s.start=Math.floor(Date.now()-u)}this.#T&&(s.size=this.#T[r]),e.unshift([n,s])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=Ii.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:u=this.sizeCalculation,status:l}=n,{noUpdateTTL:d=this.noUpdateTTL}=n,b=this.#N(e,r,n.size||0,u);if(this.maxEntrySize&&b>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.delete(e),this;let _=this.#n===0?void 0:this.#i.get(e);if(_===void 0)_=this.#n===0?this.#o:this.#g.length!==0?this.#g.pop():this.#n===this.#u?this.#E(!1):this.#n,this.#r[_]=e,this.#e[_]=r,this.#i.set(e,_),this.#c[this.#o]=_,this.#f[_]=this.#o,this.#o=_,this.#n++,this.#M(_,b,l),l&&(l.set="add"),d=!1;else{this.#C(_);let T=this.#e[_];if(r!==T){if(this.#k&&this.#t(T)?T.__abortController.abort(new Error("replaced")):s||(this.#b&&this.#y?.(T,e,"set"),this.#l&&this.#s?.push([T,e,"set"])),this.#I(_),this.#M(_,b,l),this.#e[_]=r,l){l.set="replace";let x=T&&this.#t(T)?T.__staleWhileFetching:T;x!==void 0&&(l.oldValue=x)}}else l&&(l.set="update")}if(i!==0&&!this.#w&&this.#D(),this.#w&&(d||this.#B(_,i,o),l&&this.#x(l,_)),!s&&this.#l&&this.#s){let T=this.#s,x;for(;x=T?.shift();)this.#p?.(...x)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#E(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}}#E(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#k&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,n,"evict"),this.#l&&this.#s?.push([i,n,"evict"])),this.#I(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#g.push(r)),this.#n===1?(this.#a=this.#o=0,this.#g.length=0):this.#a=this.#c[r],this.#i.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,o=this.#i.get(e);if(o!==void 0){let s=this.#e[o];if(this.#t(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#h(o))i&&(i.has="stale",this.#x(i,o));else return n&&this.#A(o),i&&(i.has="hit",this.#x(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#i.get(e);if(i!==void 0&&(n||!this.#h(i))){let o=this.#e[i];return this.#t(o)?o.__staleWhileFetching:o}}#P(e,r,n,i){let o=r===void 0?void 0:this.#e[r];if(this.#t(o))return o;let s=new Ho,{signal:u}=n;u?.addEventListener("abort",()=>s.abort(u.reason),{signal:s.signal});let l={signal:s.signal,options:n,context:i},d=(I,C=!1)=>{let{aborted:E}=s.signal,P=n.ignoreFetchAbort&&I!==void 0;if(n.status&&(E&&!C?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,P&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),E&&!P&&!C)return _(s.signal.reason);let D=x;return this.#e[r]===x&&(I===void 0?D.__staleWhileFetching?this.#e[r]=D.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,I,l.options))),I},b=I=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=I),_(I)),_=I=>{let{aborted:C}=s.signal,E=C&&n.allowStaleOnFetchAbort,P=E||n.allowStaleOnFetchRejection,D=P||n.noDeleteOnFetchRejection,L=x;if(this.#e[r]===x&&(!D||L.__staleWhileFetching===void 0?this.delete(e):E||(this.#e[r]=L.__staleWhileFetching)),P)return n.status&&L.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),L.__staleWhileFetching;if(L.__returned===L)throw I},T=(I,C)=>{let E=this.#O?.(e,o,l);E&&E instanceof Promise&&E.then(P=>I(P),C),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(I(),n.allowStaleOnFetchAbort&&(I=P=>d(P,!0)))})};n.status&&(n.status.fetchDispatched=!0);let x=new Promise(T).then(d,b),A=Object.assign(x,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,A,{...l.options,status:void 0}),r=this.#i.get(e)):this.#e[r]=A,A}#t(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Ho}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:u=this.noDisposeOnSet,size:l=0,sizeCalculation:d=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:_=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:T=this.allowStaleOnFetchRejection,ignoreFetchAbort:x=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:I,forceRefresh:C=!1,status:E,signal:P}=r;if(!this.#k)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:E});let D={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:u,size:l,sizeCalculation:d,noUpdateTTL:b,noDeleteOnFetchRejection:_,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:A,ignoreFetchAbort:x,status:E,signal:P},L=this.#i.get(e);if(L===void 0){E&&(E.fetch="miss");let H=this.#P(e,L,D,I);return H.__returned=H}else{let H=this.#e[L];if(this.#t(H)){let N=n&&H.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=!0)),N?H.__staleWhileFetching:H.__returned=H}let W=this.#h(L);if(!C&&!W)return E&&(E.fetch="hit"),this.#C(L),i&&this.#A(L),E&&this.#x(E,L),H;let K=this.#P(e,L,D,I),U=K.__staleWhileFetching!==void 0&&n;return E&&(E.fetch=W?"stale":"refresh",U&&W&&(E.returnedStale=!0)),U?K.__staleWhileFetching:K.__returned=K}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=r,u=this.#i.get(e);if(u!==void 0){let l=this.#e[u],d=this.#t(l);return s&&this.#x(s,u),this.#h(u)?(s&&(s.get="stale"),d?(s&&n&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?l.__staleWhileFetching:void 0):(o||this.delete(e),s&&n&&(s.returnedStale=!0),n?l:void 0)):(s&&(s.get="hit"),d?l.__staleWhileFetching:(this.#C(u),i&&this.#A(u),l))}else s&&(s.get="miss")}#j(e,r){this.#f[r]=e,this.#c[e]=r}#C(e){e!==this.#o&&(e===this.#a?this.#a=this.#c[e]:this.#j(this.#f[e],this.#c[e]),this.#j(this.#o,e),this.#o=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#i.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#I(n);let i=this.#e[n];this.#t(i)?i.__abortController.abort(new Error("deleted")):(this.#b||this.#l)&&(this.#b&&this.#y?.(i,e,"delete"),this.#l&&this.#s?.push([i,e,"delete"])),this.#i.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#o?this.#o=this.#f[n]:n===this.#a?this.#a=this.#c[n]:(this.#c[this.#f[n]]=this.#c[n],this.#f[this.#c[n]]=this.#f[n]),this.#n--,this.#g.push(n)}}if(this.#l&&this.#s?.length){let n=this.#s,i;for(;i=n?.shift();)this.#p?.(...i)}return r}clear(){for(let e of this.#v({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#b&&this.#y?.(r,n,"delete"),this.#l&&this.#s?.push([r,n,"delete"])}}if(this.#i.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#w&&this.#S&&(this.#w.fill(0),this.#S.fill(0)),this.#T&&this.#T.fill(0),this.#a=0,this.#o=0,this.#g.length=0,this.#m=0,this.#n=0,this.#l&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#p?.(...r)}}};var Q=de(we(),1);var Yo=de(If(),1),Qr=require("@mysten/sui.js/utils"),en=require("@mysten/sui.js/transactions");var Ci=de(we(),1),Nf=require("@mysten/sui.js/transactions"),Mt=de(we(),1);var Mr=de(we(),1),Lt=de(we(),1);var Ei=de(we(),1);var Rf=require("@mysten/sui.js/utils"),Qo=require("@mysten/sui.js/transactions"),es=require("@mysten/sui.js/utils");var yu=de(we(),1),by=Object.defineProperty,_y=(t,e,r)=>e in t?by(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e,r)=>(_y(t,typeof e!="symbol"?e+"":e,r),r);var Ko=443636,Jo=-443636,mu="79226673515401279992447579055",gu="4295048016",Ty=14,Sy="59543866431248",xy="184467440737095516",ky="15793534762490258745",Ay=class{generateMnemonic(t=24){return vf(Tf,t===12?128:256)}getKeypairFromMnemonics(t,e={}){let r=this.getDerivePath(e);return Ef.Ed25519Keypair.deriveKeypair(t,r)}getDerivePath(t={}){let{accountIndex:e=0,isExternal:r=!1,addressIndex:n=0}=t;return`m/44'/784'/${e}'/${r?1:0}'/${n}'`}},Mi=class{constructor(t){this.sdk=t,rr(this,"_lru"),rr(this,"_fetching",{})}async getCacheOrSet(t,e,r=0){var n;let i=this._lru||(this._lru=new Zo({max:100}));if(i.has(t))return i.get(t);let s=await((n=this._fetching)[t]||(n[t]=e()));return delete this._fetching[t],i.set(t,s,{ttl:r}),s}get provider(){return this.sdk.provider}get math(){return this.sdk.math}get account(){return this.sdk.account}get network(){return this.sdk.network}get contract(){return this.sdk.contract}get nft(){return this.sdk.nft}get coin(){return this.sdk.coin}get trade(){return this.sdk.trade}get pool(){return this.sdk.pool}};function Iy(t){if("reference"in t)return t.reference;let e=bu(t);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Df(t)}function rs(t){var e,r;return"objectId"in t?t.objectId:(r=(e=Iy(t))==null?void 0:e.objectId)!=null?r:Bf(t)}function nr(t){var e;return"fields"in t?t.fields:(e=Pf(t))==null?void 0:e.fields}function Pf(t){let e="data"in t?bu(t):t;if(!(!e||!Cy(e)||e.content.dataType!=="moveObject"))return e.content}function Cy(t){return t.content!==void 0}function bu(t){return t.data}function Df(t){if(t.error&&"object_id"in t.error&&"version"in t.error&&"digest"in t.error){let e=t.error;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Bf(t){if(t.error&&"object_id"in t.error&&!("version"in t.error)&&!("digest"in t.error))return t.error.object_id}function Oy(t){return t.data!==void 0}function My(t){var e;let r=Oy(t)?t.data:t;return!r?.type&&"data"in t?((e=r?.content)==null?void 0:e.dataType)==="package"?"package":ts(t):r?.type}function ts(t){var e;return(e=Pf(t))==null?void 0:e.type}function Ey(t){var e;return(e=bu(t))==null?void 0:e.owner}var Oi=async(t,e,r)=>{let i=e.length;if(i>50){let o=[],s=0,u=Math.ceil(i/50);for(s;s<u;s++)o.push(t.multiGetObjects({ids:e.slice(s*50,(s+1)*50),options:r}));return(await Promise.all(o)).flat()}return await t.multiGetObjects({ids:e,options:r})},Py=class extends Mi{async getConfig(){return(await this.fetchJSON())[this.network].contract}getFees(){return this.getCacheOrSet("fees",async()=>{let e=(await this.fetchJSON())[this.network].fee;return(await Oi(this.provider,Object.values(e),{showContent:!0})).map(n=>{let i=nr(n),o=rs(n),s=ts(n);return{objectId:o,type:s.split("<")[1].slice(0,-1),fee:i.fee,tickSpacing:i.tick_spacing}})})}fetchJSON(){return this.getCacheOrSet("contract-json",async()=>await(await fetch("https://s3.amazonaws.com/app.turbos.finance/sdk/contract.json?t="+Date.now(),{method:"GET"})).json())}},Cf=new Q.default(2).pow(new Q.default(128)),Dy=class{priceToSqrtPriceX64(t,e,r){return new Q.default(new $(t).mul($.pow(10,r-e)).sqrt().mul($.pow(2,64)).floor().toFixed(0))}sqrtPriceX64ToPrice(t,e,r){return new $(t.toString()).mul($.pow(2,-64)).pow(2).mul($.pow(10,e-r))}priceToTickIndex(t,e,r){return this.sqrtPriceX64ToTickIndex(this.priceToSqrtPriceX64(t,e,r))}sqrtPriceX64ToTickIndex(t){if(t.gt(new Q.default(mu))||t.lt(new Q.default(gu)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,r=new Q.default(e-64),n=this.signedShiftLeft(r,32,128),i=new Q.default("8000000000000000","hex"),o=0,s=new Q.default(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;i.gt(new Q.default(0))&&o<Ty;){u=u.mul(u);let x=u.shrn(127);u=u.shrn(63+x.toNumber()),s=s.add(i.mul(x)),i=i.shrn(1),o+=1}let l=s.shrn(32),b=n.add(l).mul(new Q.default(Sy)),_=this.signedShiftRight(b.sub(new Q.default(xy)),64,128).toNumber(),T=this.signedShiftRight(b.add(new Q.default(ky)),64,128).toNumber();return _==T?_:this.tickIndexToSqrtPriceX64(T).lte(t)?T:_}tickIndexToSqrtPriceX64(t){return t>0?new Q.default(this.tickIndexToSqrtPricePositive(t)):new Q.default(this.tickIndexToSqrtPriceNegative(t))}tickIndexToPrice(t,e,r){return this.sqrtPriceX64ToPrice(this.tickIndexToSqrtPriceX64(t),e,r)}toX64_Decimal(t){return t.mul($.pow(2,64))}fromX64_Decimal(t){return t.mul($.pow(2,-64))}scaleDown(t,e){return new $(t).div($.pow(10,e)).toString()}scaleUp(t,e){return new $(t).mul($.pow(10,e)).toString()}bitsToNumber(t,e=32){return Yo.default.toNumber(Yo.default.asIntN(e,Yo.default.BigInt(t)))}subUnderflowU128(t,e){return t.add(Cf).sub(e).mod(Cf)}tickIndexToSqrtPricePositive(t){let e;return t&1?e=new Q.default("79232123823359799118286999567"):e=new Q.default("79228162514264337593543950336"),t&2&&(e=this.signedShiftRight(e.mul(new Q.default("79236085330515764027303304731")),96,256)),t&4&&(e=this.signedShiftRight(e.mul(new Q.default("79244008939048815603706035061")),96,256)),t&8&&(e=this.signedShiftRight(e.mul(new Q.default("79259858533276714757314932305")),96,256)),t&16&&(e=this.signedShiftRight(e.mul(new Q.default("79291567232598584799939703904")),96,256)),t&32&&(e=this.signedShiftRight(e.mul(new Q.default("79355022692464371645785046466")),96,256)),t&64&&(e=this.signedShiftRight(e.mul(new Q.default("79482085999252804386437311141")),96,256)),t&128&&(e=this.signedShiftRight(e.mul(new Q.default("79736823300114093921829183326")),96,256)),t&256&&(e=this.signedShiftRight(e.mul(new Q.default("80248749790819932309965073892")),96,256)),t&512&&(e=this.signedShiftRight(e.mul(new Q.default("81282483887344747381513967011")),96,256)),t&1024&&(e=this.signedShiftRight(e.mul(new Q.default("83390072131320151908154831281")),96,256)),t&2048&&(e=this.signedShiftRight(e.mul(new Q.default("87770609709833776024991924138")),96,256)),t&4096&&(e=this.signedShiftRight(e.mul(new Q.default("97234110755111693312479820773")),96,256)),t&8192&&(e=this.signedShiftRight(e.mul(new Q.default("119332217159966728226237229890")),96,256)),t&16384&&(e=this.signedShiftRight(e.mul(new Q.default("179736315981702064433883588727")),96,256)),t&32768&&(e=this.signedShiftRight(e.mul(new Q.default("407748233172238350107850275304")),96,256)),t&65536&&(e=this.signedShiftRight(e.mul(new Q.default("2098478828474011932436660412517")),96,256)),t&131072&&(e=this.signedShiftRight(e.mul(new Q.default("55581415166113811149459800483533")),96,256)),t&262144&&(e=this.signedShiftRight(e.mul(new Q.default("38992368544603139932233054999993551")),96,256)),this.signedShiftRight(e,32,256)}tickIndexToSqrtPriceNegative(t){let e=Math.abs(t),r;return e&1?r=new Q.default("18445821805675392311"):r=new Q.default("18446744073709551616"),e&2&&(r=this.signedShiftRight(r.mul(new Q.default("18444899583751176498")),64,256)),e&4&&(r=this.signedShiftRight(r.mul(new Q.default("18443055278223354162")),64,256)),e&8&&(r=this.signedShiftRight(r.mul(new Q.default("18439367220385604838")),64,256)),e&16&&(r=this.signedShiftRight(r.mul(new Q.default("18431993317065449817")),64,256)),e&32&&(r=this.signedShiftRight(r.mul(new Q.default("18417254355718160513")),64,256)),e&64&&(r=this.signedShiftRight(r.mul(new Q.default("18387811781193591352")),64,256)),e&128&&(r=this.signedShiftRight(r.mul(new Q.default("18329067761203520168")),64,256)),e&256&&(r=this.signedShiftRight(r.mul(new Q.default("18212142134806087854")),64,256)),e&512&&(r=this.signedShiftRight(r.mul(new Q.default("17980523815641551639")),64,256)),e&1024&&(r=this.signedShiftRight(r.mul(new Q.default("17526086738831147013")),64,256)),e&2048&&(r=this.signedShiftRight(r.mul(new Q.default("16651378430235024244")),64,256)),e&4096&&(r=this.signedShiftRight(r.mul(new Q.default("15030750278693429944")),64,256)),e&8192&&(r=this.signedShiftRight(r.mul(new Q.default("12247334978882834399")),64,256)),e&16384&&(r=this.signedShiftRight(r.mul(new Q.default("8131365268884726200")),64,256)),e&32768&&(r=this.signedShiftRight(r.mul(new Q.default("3584323654723342297")),64,256)),e&65536&&(r=this.signedShiftRight(r.mul(new Q.default("696457651847595233")),64,256)),e&131072&&(r=this.signedShiftRight(r.mul(new Q.default("26294789957452057")),64,256)),e&262144&&(r=this.signedShiftRight(r.mul(new Q.default("37481735321082")),64,256)),r}signedShiftLeft(t,e,r){let n=t.toTwos(r).shln(e);return n.imaskn(r+1),n.fromTwos(r)}signedShiftRight(t,e,r){let n=t.toTwos(r).shrn(e);return n.imaskn(r-e+1),n.fromTwos(r-e)}},wu=(t,e)=>{let r=rs(t);if(Df(t))throw new Error(`${e}(${r}) had been deleted`);if(Bf(t))throw new Error(`${e}(${r}) is not found`);return!0},Rn=60*1e3,By=class extends Mi{async getPools(t=!1){let e=await this.contract.getConfig(),r=[],n;do n=await this.provider.getDynamicFields({parentId:e.PoolTableId,cursor:n?.nextCursor,limit:15}),r.push(...n.data.map(u=>u.objectId));while(n.hasNextPage);if(!r.length)return[];let o=(await Oi(this.provider,r,{showContent:!0})).map(u=>nr(u).value.fields.pool_id);if(!o.length)return[];let s=await Oi(this.provider,o,{showContent:!0});return t||(s=s.filter(u=>nr(u).unlocked)),s.map(u=>this.parsePool(u))}async getPool(t){return this.getCacheOrSet(`pool-${t}`,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"pool"),this.parsePool(e)},1500)}async createPool(t){let{fee:e,address:r,tickLower:n,tickUpper:i,sqrtPrice:o,slippage:s,coinTypeA:u,coinTypeB:l}=t,d=await this.contract.getConfig(),b=new $(t.amountA),_=new $(t.amountB),[T,x]=await Promise.all([this.coin.selectTradeCoins(r,u,b),this.coin.selectTradeCoins(r,l,_)]),A=t.txb||new en.TransactionBlock,I=T.length>0?this.coin.convertTradeCoins(A,T,u,b):[this.coin.zero(u,A)],C=x.length>0?this.coin.convertTradeCoins(A,x,l,_):[this.coin.zero(l,A)];return A.moveCall({target:`${d.PackageId}::pool_factory::deploy_pool_and_mint`,typeArguments:[u,l,e.type],arguments:[A.object(d.PoolConfig),A.object(e.objectId),A.pure(o,"u128"),A.object(d.Positions),A.makeMoveVec({objects:I}),A.makeMoveVec({objects:C}),A.pure(Math.abs(n).toFixed(0),"u32"),A.pure(n<0,"bool"),A.pure(Math.abs(i).toFixed(0),"u32"),A.pure(i<0,"bool"),A.pure(b.toFixed(0),"u64"),A.pure(_.toFixed(0),"u64"),A.pure(this.getMinimumAmountBySlippage(b,s),"u64"),A.pure(this.getMinimumAmountBySlippage(_,s),"u64"),A.pure(r,"address"),A.pure(Date.now()+Rn,"u64"),A.object(Qr.SUI_CLOCK_OBJECT_ID),A.object(d.Versioned)]}),A}async addLiquidity(t){let{address:e,tickLower:r,tickUpper:n,slippage:i,pool:o}=t,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(o),[l,d]=u,[b,_]=await Promise.all([this.coin.getMetadata(l),this.coin.getMetadata(d)]);if(!b||!_)throw new Error("Invalid coin type");let T=new $(t.amountA),x=new $(t.amountB),[A,I]=await Promise.all([this.coin.selectTradeCoins(e,l,T),this.coin.selectTradeCoins(e,d,x)]),C=t.txb||new en.TransactionBlock,E=A.length>0?this.coin.convertTradeCoins(C,A,l,T):[this.coin.zero(l,C)],P=I.length>0?this.coin.convertTradeCoins(C,I,d,x):[this.coin.zero(d,C)];return C.moveCall({target:`${s.PackageId}::position_manager::mint`,typeArguments:u,arguments:[C.object(o),C.object(s.Positions),C.makeMoveVec({objects:E}),C.makeMoveVec({objects:P}),C.pure(Math.abs(r).toFixed(0),"u32"),C.pure(r<0,"bool"),C.pure(Math.abs(n).toFixed(0),"u32"),C.pure(n<0,"bool"),C.pure(T.toFixed(0),"u64"),C.pure(x.toFixed(0),"u64"),C.pure(this.getMinimumAmountBySlippage(T,i),"u64"),C.pure(this.getMinimumAmountBySlippage(x,i),"u64"),C.pure(e,"address"),C.pure(Date.now()+Rn,"u64"),C.object(Qr.SUI_CLOCK_OBJECT_ID),C.object(s.Versioned)]}),C}async increaseLiquidity(t){let{pool:e,slippage:r,address:n,nft:i}=t,o=await this.contract.getConfig(),s=new $(t.amountA),u=new $(t.amountB),l=await this.getPoolTypeArguments(e),[d,b]=l,[_,T]=await Promise.all([this.coin.selectTradeCoins(n,d,s),this.coin.selectTradeCoins(n,b,u)]),x=t.txb||new en.TransactionBlock,A=_.length>0?this.coin.convertTradeCoins(x,_,d,s):[this.coin.zero(d,x)],I=T.length>0?this.coin.convertTradeCoins(x,T,b,u):[this.coin.zero(b,x)];return x.moveCall({target:`${o.PackageId}::position_manager::increase_liquidity`,typeArguments:l,arguments:[x.object(e),x.object(o.Positions),x.makeMoveVec({objects:A}),x.makeMoveVec({objects:I}),x.object(i),x.pure(s.toFixed(0),"u64"),x.pure(u.toFixed(0),"u64"),x.pure(this.getMinimumAmountBySlippage(s,r),"u64"),x.pure(this.getMinimumAmountBySlippage(u,r),"u64"),x.pure(Date.now()+Rn*3,"u64"),x.object(Qr.SUI_CLOCK_OBJECT_ID),x.object(o.Versioned)]}),x}async decreaseLiquidity(t){let{slippage:e,nft:r,pool:n,decreaseLiquidity:i}=t,o=new $(t.amountA),s=new $(t.amountB),u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(n),d=t.txb||new en.TransactionBlock;return d.moveCall({target:`${u.PackageId}::position_manager::decrease_liquidity`,typeArguments:l,arguments:[d.object(n),d.object(u.Positions),d.object(r),d.pure(new Ci.default(i).toString(),"u128"),d.pure(this.getMinimumAmountBySlippage(o,e),"u64"),d.pure(this.getMinimumAmountBySlippage(s,e),"u64"),d.pure(Date.now()+Rn*3,"u64"),d.object(Qr.SUI_CLOCK_OBJECT_ID),d.object(u.Versioned)]}),d}async removeLiquidity(t){let e=await this.decreaseLiquidity(t);return e=await this.collectFee({txb:e,...t}),e=await this.collectReward({txb:e,...t}),e=await this.nft.burn({txb:e,nft:t.nft,pool:t.pool}),e}async collectFee(t){let{pool:e,nft:r,address:n,collectAmountA:i,collectAmountB:o}=t,s=t.txb||new en.TransactionBlock;if(Number(i)===0&&Number(o)===0)return s;let u=await this.contract.getConfig(),l=await this.getPoolTypeArguments(e);return s.moveCall({target:`${u.PackageId}::position_manager::collect`,typeArguments:l,arguments:[s.object(e),s.object(u.Positions),s.object(r),s.pure(i,"u64"),s.pure(o,"u64"),s.pure(n),s.pure(Date.now()+Rn*3,"u64"),s.object(Qr.SUI_CLOCK_OBJECT_ID),s.object(u.Versioned)]}),s}async collectReward(t){let{pool:e,nft:r,rewardAmounts:n,address:i}=t,o=t.txb||new en.TransactionBlock,s=await this.contract.getConfig(),u=await this.getPoolTypeArguments(e);return(await this.getPool(e)).reward_infos.forEach((d,b)=>{o.moveCall({target:`${s.PackageId}::position_manager::collect_reward`,typeArguments:[...u,d.fields.vault_coin_type],arguments:[o.object(e),o.object(s.Positions),o.object(r),o.object(d.fields.vault),o.pure(b,"u64"),o.pure(n[b],"u64"),o.pure(i),o.pure(Date.now()+Rn*3,"u64"),o.object(Qr.SUI_CLOCK_OBJECT_ID),o.object(s.Versioned)]})}),o}getTokenAmountsFromLiquidity(t){let e=new $((t.liquidity||new Ci.default(1e8)).toString()),r=new $(t.currentSqrtPrice.toString()),n=new $(t.lowerSqrtPrice.toString()),i=new $(t.upperSqrtPrice.toString()),o,s;t.currentSqrtPrice.lt(t.lowerSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(n)).div(n.mul(i)),s=new $(0)):t.currentSqrtPrice.lt(t.upperSqrtPrice)?(o=this.math.toX64_Decimal(e).mul(i.sub(r)).div(r.mul(i)),s=this.math.fromX64_Decimal(e.mul(r.sub(n)))):(o=new $(0),s=this.math.fromX64_Decimal(e.mul(i.sub(n))));let u=t.ceil!==!1?"ceil":"floor";return[new Ci.default(o[u]().toString()),new Ci.default(s[u]().toString())]}async getPoolTypeArguments(t){return this.getCacheOrSet("pool-type-"+t,async()=>(await this.getPool(t)).types)}parsePoolType(t,e){var r;let n=((r=t.replace(">","").split("<")[1])==null?void 0:r.split(/,\s*/))||[];if(e!==void 0&&e!==n.length)throw new Error("Invalid pool type");return n}async getFixedLiquidity(t){var e,r;let{coinTypeA:n,coinTypeB:i,amountA:o,amountB:s}=t,[u,l]=await Promise.all([this.coin.getMetadata(n),this.coin.getMetadata(i)]),d=new $(this.math.scaleDown(o,u.decimals)).mul((e=t.priceA)!=null?e:1),b=new $(this.math.scaleDown(s,l.decimals)).mul((r=t.priceB)!=null?r:1);return{liquidityA:d.toString(),liquidityB:b.toString(),liquidity:d.plus(b).toString()}}parsePool(t){let e=nr(t),r=rs(t),n=My(t),i=this.parsePoolType(n,3);return this.getCacheOrSet("pool-type-"+r,async()=>i),{...e,objectId:r,type:n,types:i}}getMinimumAmountBySlippage(t,e){let r=new $(t),n=new $(1).minus(new $(e).div(100));if(n.lte(0)||n.gt(1))throw new Error("invalid slippage range");return r.mul(n).toFixed(0)}},Ny=(t,e)=>{let{pool:r,position:n,tickLowerDetail:i,tickUpperDetail:o}=e,s=new Mr.default(r.fee_growth_global_a),u=new Mr.default(n.fee_growth_inside_a),l=new Mr.default(n.tokens_owed_a),d=new Mr.default(r.fee_growth_global_b),b=new Mr.default(n.fee_growth_inside_b),_=new Mr.default(n.tokens_owed_b),T=new Mr.default(n.liquidity),x,A,I,C,E=t.bitsToNumber(r.tick_current_index.fields.bits),P=t.bitsToNumber(n.tick_lower_index.fields.bits),D=t.bitsToNumber(n.tick_upper_index.fields.bits);E<P?(x=t.subUnderflowU128(s,i.feeGrowthOutsideA),A=t.subUnderflowU128(d,i.feeGrowthOutsideB)):(x=i.feeGrowthOutsideA,A=i.feeGrowthOutsideB),E<D?(I=o.feeGrowthOutsideA,C=o.feeGrowthOutsideB):(I=t.subUnderflowU128(s,o.feeGrowthOutsideA),C=t.subUnderflowU128(d,o.feeGrowthOutsideB));let L=t.subUnderflowU128(t.subUnderflowU128(s,x),I),H=t.subUnderflowU128(t.subUnderflowU128(d,A),C),W=t.subUnderflowU128(L,u).mul(T).shrn(64),K=t.subUnderflowU128(H,b).mul(T).shrn(64);return{feeOwedA:l.add(W).toString(),feeOwedB:_.add(K).toString()}},Of=new Ei.default(0),Mf=new Ei.default(1),Ry=new Ei.default(2),jy={mul(t,e,r){let n=t.mul(e);if(this.isOverLimit(n,r))throw new Error(`Mul result higher than u${r}`);return n},mulDiv(t,e,r,n){return this.mulDivRoundUpIf(t,e,r,!1,n)},mulDivRoundUpIf(t,e,r,n,i){if(r.eq(Of))throw new Error("mulDiv denominator is zero");let o=this.mul(t,e,i),s=o.div(r);return n&&o.mod(r).gt(Of)?s.add(Mf):s},isOverLimit(t,e){let r=Ry.pow(new Ei.default(e)).sub(Mf);return t.gt(r)}},Fy=(t,e)=>{var r,n,i,o;let{pool:s,position:u,tickLowerDetail:l,tickUpperDetail:d,timeStampInSeconds:b}=e,_=new Lt.default(new $(s.reward_last_updated_time_ms).div(1e3).toFixed(0)),x=(b??new Lt.default(Date.now()).div(new Lt.default(1e3))).sub(new Lt.default(_)),A=[],I=new Lt.default(s.liquidity),C=new Lt.default(u.liquidity);for(let E=0;E<3;++E){let P=s.reward_infos[E],D={emissionsPerSecondX64:new Lt.default(P?P.fields.emissions_per_second:"0"),growthGlobalX64:new Lt.default(P?P.fields.growth_global:"0")},L={growthInsideCheckpoint:new Lt.default((n=(r=u.reward_infos[E])==null?void 0:r.fields.reward_growth_inside)!=null?n:"0"),amountOwed:new Lt.default((o=(i=u.reward_infos[E])==null?void 0:i.fields.amount_owed)!=null?o:"0")},H=D.growthGlobalX64;if(!I.isZero()){let S=jy.mulDiv(x,D.emissionsPerSecondX64,I,128);H=D.growthGlobalX64.add(S)}let W=l.rewardGrowthsOutside[E],K=d.rewardGrowthsOutside[E],F=H;l.initialized&&(F=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_lower_index.fields.bits)?t.subUnderflowU128(H,W):W);let U=new Lt.default(0);d.initialized&&(U=t.bitsToNumber(s.tick_current_index.fields.bits)<t.bitsToNumber(u.tick_upper_index.fields.bits)?K:t.subUnderflowU128(H,K));let N=t.subUnderflowU128(t.subUnderflowU128(H,F),U),j=L.amountOwed.shln(64);A[E]=j.add(t.subUnderflowU128(N,L.growthInsideCheckpoint).mul(C)).shrn(64).toString()}return A},qy=class extends Mi{async getOwner(t){let e=await this.getObject(t),r=Ey(e);if(!(!r||typeof r=="string")){if("ObjectOwner"in r)return r.ObjectOwner;if("AddressOwner"in r)return r.AddressOwner}}async getFields(t){let e=await this.getObject(t);return nr(e)}async getPositionFields(t){let e=await this.contract.getConfig(),r=await this.provider.getDynamicFieldObject({parentId:e.Positions,name:{type:"address",value:t}});return nr(r)}async getPositionFieldsByPositionId(t){let e=await this.provider.getObject({id:t,options:{showContent:!0}});return wu(e,"position"),nr(e)}async getPositionTick(t,e){let r=await this.provider.getDynamicFieldObject({parentId:t,name:{type:e.type,value:e.fields}}),n=nr(r);if(n)return{tickIndex:this.math.bitsToNumber(n.name.fields.bits),initialized:n.value.fields.initialized,liquidityNet:new Mt.default(this.math.bitsToNumber(n.value.fields.liquidity_net.fields.bits,128).toString()),liquidityGross:new Mt.default(n.value.fields.liquidity_gross),feeGrowthOutsideA:new Mt.default(n.value.fields.fee_growth_outside_a),feeGrowthOutsideB:new Mt.default(n.value.fields.fee_growth_outside_b),rewardGrowthsOutside:n.value.fields.reward_growths_outside.map(i=>new Mt.default(i))}}async getPositionAPR(t){let{poolId:e,getPrice:r,fees24h:n,tickLower:i,tickUpper:o}=t,s=await this.pool.getPool(e),u=this.math.bitsToNumber(s.tick_current_index.fields.bits),[l,d,b,_]=await Promise.all([this.coin.getMetadata(s.types[0]),this.coin.getMetadata(s.types[1]),r(s.types[0]),r(s.types[1])]);if(!b||!_||i>=o||u<i||u>=o)return{fees:"0",rewards:"0",total:"0"};let{minTokenA:T,minTokenB:x}=this.getRemoveLiquidityQuote(s,i,o),A=new $(this.math.scaleDown(T.toString(),l.decimals)).mul(b),I=new $(this.math.scaleDown(x.toString(),d.decimals)).mul(_),C=A.add(I),E=C.isZero()?new $(0):new $(n).mul(365).div(C).mul(100),P=new $(0);return await Promise.all(s.reward_infos.map(async D=>{let{emissions_per_second:L}=D.fields,H=this.coin.formatCoinType(D.fields.vault_coin_type),[W,K]=await Promise.all([r(H),this.coin.getMetadata(H)]);!L||L==="0"||!W||(P=P.add(new $(new Mt.default(L).shrn(64).toString()).div(10**K.decimals).mul(31536e3).mul(W).div(C).mul(100)))})),{fees:E.toString(),rewards:P.toString(),total:E.plus(P).toString()}}getRemoveLiquidityQuote(t,e,r){let n=new Mt.default(0),i=new Mt.default(t.liquidity),o=this.math.bitsToNumber(t.tick_current_index.fields.bits),s=this.math.tickIndexToSqrtPriceX64(e),u=this.math.tickIndexToSqrtPriceX64(r);if(o<e){let d=this.getTokenAFromLiquidity(i,s,u);return{minTokenA:this.adjustForSlippage(d),minTokenB:n}}if(o<r){let d=new Mt.default(t.sqrt_price),b=this.getTokenAFromLiquidity(i,d,u),_=this.getTokenBFromLiquidity(i,s,d);return{minTokenA:this.adjustForSlippage(b),minTokenB:this.adjustForSlippage(_)}}let l=this.getTokenBFromLiquidity(i,s,u);return{minTokenA:n,minTokenB:this.adjustForSlippage(l)}}adjustForSlippage(t){let e={numerator:new Mt.default(0),denominator:new Mt.default(1e3)};return t.mul(e.denominator).div(e.denominator.add(e.numerator))}getTokenAFromLiquidity(t,e,r){let n=t.mul(r.sub(e)).shln(64),i=r.mul(e);return n.div(i)}getTokenBFromLiquidity(t,e,r){return t.mul(r.sub(e)).shrn(64)}async burn(t){let{pool:e,nft:r}=t,n=t.txb||new Nf.TransactionBlock,i=await this.contract.getConfig(),o=await this.pool.getPoolTypeArguments(e);return n.moveCall({target:`${i.PackageId}::position_manager::burn`,typeArguments:o,arguments:[n.object(i.Positions),n.object(r),n.object(i.Versioned)]}),n}async getPositionLiquidityUSD(t){let{position:e,poolId:r,priceA:n,priceB:i}=t,o=await this.pool.getPool(r),s=this.pool.getTokenAmountsFromLiquidity({currentSqrtPrice:new Mt.default(o.sqrt_price),lowerSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_lower_index.fields.bits)),upperSqrtPrice:this.math.tickIndexToSqrtPriceX64(this.math.bitsToNumber(e.tick_upper_index.fields.bits)),liquidity:new Mt.default(e.liquidity===void 0?1e8:e.liquidity)}),[u,l]=await Promise.all([this.coin.getMetadata(o.types[0]),this.coin.getMetadata(o.types[1])]),d=new $(s[0].toString()).div(10**u.decimals).mul(n||0),b=new $(s[1].toString()).div(10**l.decimals).mul(i||0);return d.plus(b).toString()}async getUnclaimedFeesAndRewards(t){let{position:e,poolId:r}=t,[n,i,o]=await Promise.all([this.pool.getPool(r),this.nft.getPositionTick(r,e.tick_lower_index),this.nft.getPositionTick(r,e.tick_upper_index)]),s={...t,pool:n,tickLowerDetail:i,tickUpperDetail:o},[u,l]=await Promise.all([this.getUnclaimedFees(s),this.getUnclaimedRewards(s)]),{unclaimedFees:d,...b}=u,{unclaimedRewards:_,...T}=l;return{fees:u.unclaimedFees.toString(),rewards:_.toString(),total:d.plus(_).toString(),fields:{...b,...T}}}async getUnclaimedFees(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,[s,u,l,d]=await Promise.all([this.coin.getMetadata(r.types[0]),this.coin.getMetadata(r.types[1]),n(r.types[0]),n(r.types[1])]),b=Ny(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),_=this.math.scaleDown(b.feeOwedA,s.decimals),T=this.math.scaleDown(b.feeOwedB,u.decimals);function x(C,E){return new $(1e6).mul($.pow(10,E)).lt(C)}x(_,s.decimals)&&(_="0",b.feeOwedA="0"),x(T,u.decimals)&&(T="0",b.feeOwedB="0");let A=l===void 0?new $(0):new $(l).mul(_),I=d===void 0?new $(0):new $(d).mul(T);return{unclaimedFees:A.plus(I),scaledFeeOwedA:_,scaledFeeOwedB:T,...b}}async getUnclaimedRewards(t){let{position:e,pool:r,getPrice:n,tickLowerDetail:i,tickUpperDetail:o}=t,s=Fy(this.math,{pool:r,position:e,tickLowerDetail:i,tickUpperDetail:o}),u=[...s],l=r.reward_infos.map(T=>this.coin.formatCoinType(T.fields.vault_coin_type)),d=await Promise.all([...r.reward_infos.map((T,x)=>this.coin.getMetadata(l[x]))]),b=await Promise.all(r.reward_infos.map((T,x)=>n(l[x])));d.forEach((T,x)=>{u[x]=this.math.scaleDown(u[x],T.decimals)});let _=new $(0);return r.reward_infos.some((T,x)=>{let A=b[x];return A?(_=_.plus(new $(A).mul(u[x])),!1):(_=_.plus(1),!0)}),{unclaimedRewards:_,collectRewards:s,scaledCollectRewards:u}}getObject(t){return this.getCacheOrSet("nft-object-"+t,async()=>{let e=await this.provider.getObject({id:t,options:{showContent:!0,showOwner:!0}});return wu(e,"nft"),e})}},Ly=class extends Mi{isSUI(t){return(0,Rf.normalizeSuiAddress)(t)==="0x000000000000000000000000000000000000000000000000000002::sui::sui"}async getMetadata(t){return this.getCacheOrSet(`coin-metadata-${t}`,async()=>{let e=await this.provider.getCoinMetadata({coinType:t});if(!e)throw new Error(`Coin "${t}" is not found`);return e})}async selectTradeCoins(t,e,r){if(r.eq(0))return[];let n=[],i=[],o=new $(0),s;do s=await this.provider.getCoins({owner:t,coinType:e,cursor:s?.nextCursor}),n.push(...s.data);while(s.hasNextPage);n.sort((u,l)=>Number(l.balance)-Number(u.balance));for(let u of n)if(i.push(u.coinObjectId),o=o.add(u.balance),o.gte(r))break;return i}convertTradeCoins(t,e,r,n){return this.isSUI(r)?[t.splitCoins(t.gas,[t.pure(n.toNumber())])[0]]:e.map(i=>t.object(i))}zero(t,e){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}formatCoinType(t,e=!1){let n=t.replace(/^0x/i,"");return n=n.replace(/^0+(2::sui::SUI)$/,"$1"),"0x"+(e&&n.length<64&&t!=="2::sui:SUI"?"0".repeat(64-n.length):"")+n}},Uy=60*1e3,Xo=100,$y=class extends Mi{async swap(t){let{coinTypeA:e,coinTypeB:r,address:n,amountSpecifiedIsInput:i,slippage:o}=t,s=new $(t.amountA),u=new $(t.amountB),l=await this.contract.getConfig(),d=await Promise.all(t.routes.map(async I=>{let C=await this.pool.getPoolTypeArguments(I.pool),[E,P]=await Promise.all([this.coin.getMetadata(C[0]),this.coin.getMetadata(C[1])]);return{...I,coinA:E,coinB:P,typeArguments:C}})),b=await this.coin.selectTradeCoins(n,e,s),{functionName:_,typeArguments:T}=this.getFunctionNameAndTypeArguments(d.map(({typeArguments:I})=>I),e,r),x=d.map(({nextTickIndex:I,coinA:C,coinB:E,a2b:P})=>{let D=this.math.tickIndexToPrice(I,C.decimals,E.decimals);return this.sqrtPriceWithSlippage(D,o,P,C.decimals,E.decimals)}),A=t.txb||new Qo.TransactionBlock;return A.moveCall({target:`${l.PackageId}::swap_router::${_}`,typeArguments:T,arguments:[...d.map(({pool:I})=>A.object(I)),A.makeMoveVec({objects:this.coin.convertTradeCoins(A,b,e,s)}),A.pure((i?s:u).toFixed(0),"u64"),A.pure(this.amountOutWithSlippage(i?u:s,o,i),"u64"),...x.map(I=>A.pure(I,"u128")),A.pure(i,"bool"),A.pure(n,"address"),A.pure(Date.now()+Uy*3,"u64"),A.object(es.SUI_CLOCK_OBJECT_ID),A.object(l.Versioned)]}),A}async computeSwapResult(t){let{pools:e,amountSpecified:r,amountSpecifiedIsInput:n,address:i,tickStep:o}=t,s=await this.contract.getConfig(),u=e.map(_=>_.pool),l=await Oi(this.provider,u,{showContent:!0}),d=new Qo.TransactionBlock;l.map(async _=>{let T=nr(_),x=e.find(P=>P.pool===T.id.id),A=this.math.bitsToNumber(T.tick_current_index.fields.bits),I=A-T.tick_spacing*(o||Xo),C=A+T.tick_spacing*(o||Xo);I=I<Jo?Jo:I,C=C>Ko?Ko:C;let E=this.pool.parsePoolType(ts(_));d.moveCall({target:`${s.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:E,arguments:[d.object(T.id.id),d.pure(x.a2b,"bool"),d.pure(new $(r).toFixed(0),"u128"),d.pure(n,"bool"),d.pure(this.math.tickIndexToSqrtPriceX64(x.a2b?I:C).toString(),"u128"),d.object(es.SUI_CLOCK_OBJECT_ID),d.object(s.Versioned)]})});let b=await this.provider.devInspectTransactionBlock({transactionBlock:d,sender:i});if(b.error)throw new Error(b.error);return b.events.map(_=>_.parsedJson)}async computeSwapResultV2(t){let{pools:e,amountSpecifiedIsInput:r,address:n,tickStep:i}=t,o=await this.contract.getConfig(),s=e.map(b=>b.pool),u=await Oi(this.provider,Array.from(new Set(s)),{showContent:!0}),l=new Qo.TransactionBlock;e.forEach(async b=>{let _=u.find(E=>rs(E)===b.pool),T=nr(_),x=this.math.bitsToNumber(T.tick_current_index.fields.bits),A=x-T.tick_spacing*(i||Xo),I=x+T.tick_spacing*(i||Xo);A=A<Jo?Jo:A,I=I>Ko?Ko:I;let C=this.pool.parsePoolType(ts(_));l.moveCall({target:`${o.PackageId}::pool_fetcher::compute_swap_result`,typeArguments:C,arguments:[l.object(T.id.id),l.pure(b.a2b,"bool"),l.pure(new $(b.amountSpecified).toFixed(0),"u128"),l.pure(r,"bool"),l.pure(this.math.tickIndexToSqrtPriceX64(b.a2b?A:I).toString(),"u128"),l.object(es.SUI_CLOCK_OBJECT_ID),l.object(o.Versioned)]})});let d=await this.provider.devInspectTransactionBlock({transactionBlock:l,sender:n});if(d.error)throw new Error(d.error);return d.events.map(b=>b.parsedJson)}getFunctionNameAndTypeArguments(t,e,r){let n=[],i=["swap"];if(t.length===1)n=t[0],e===n[0]?i.push("a","b"):i.push("b","a");else{let o=t[0],s=t[1];e===o[0]?(i.push("a","b"),n.push(o[0],o[2],o[1])):(i.push("b","a"),n.push(o[1],o[2],o[0])),n.push(s[2],r),r===s[0]?i.push("c","b"):i.push("b","c")}return{functionName:i.join("_"),typeArguments:n}}amountOutWithSlippage(t,e,r){if(r){let i=new $(100).minus(e).div(100);return new $(t).mul(i).toFixed(0)}let n=new $(100).plus(e).div(100);return new $(t).mul(n).toFixed(0)}sqrtPriceWithSlippage(t,e,r,n,i){let o=new $(t).mul(r?new $(100).minus(e).div(100):new $(100).plus(e).div(100)),s=this.math.priceToSqrtPriceX64(o,n,i);return s.lt(new yu.BN(gu))?gu:s.gt(new yu.BN(mu))?mu:s.toString()}},It=class{constructor(t,e){this.network=t,rr(this,"pool"),rr(this,"contract"),rr(this,"math",new Dy),rr(this,"account",new Ay),rr(this,"coin"),rr(this,"nft"),rr(this,"trade"),rr(this,"provider"),this.provider=e?e instanceof tn.SuiClient?e:new tn.SuiClient(e):new tn.SuiClient({url:t==="mainnet"?(0,tn.getFullnodeUrl)("mainnet"):(0,tn.getFullnodeUrl)("testnet")}),this.contract=new Py(this),this.pool=new By(this),this.nft=new qy(this),this.coin=new Ly(this),this.trade=new $y(this)}};var Gy=Object.defineProperty,uh=(t,e)=>{for(var r in e)Gy(t,r,{get:e[r],enumerable:!0})},St=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,lh.default)(this.data))}},Vy={fullRpcUrl:"https://fullnode.mainnet.sui.io/",simulationAccount:{address:"0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb"},cetus_config:{package_id:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",published_at:"0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f",config:{coin_list_id:"0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23",launchpad_pools_id:"0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115",clmm_pools_id:"0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e",admin_cap_id:"0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113",global_config_id:"0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f",coin_list_handle:"0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063",launchpad_pools_handle:"0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c",clmm_pools_handle:"0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb"}},clmm_pool:{package_id:"0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb",published_at:"0xc33c3e937e5aa2009cc0c3fdb3f345a0c3193d4ee663ffc601fe8b894fbc4ba6",version:4,config:{pools_id:"0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b",admin_cap_id:"0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"}},integrate:{package_id:"0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3",published_at:"0xd43348b8879c1457f882b02555ba862f2bc87bcc31b16294ca14a82f608875d2",version:6},deepbook:{package_id:"0x000000000000000000000000000000000000000000000000000000000000dee9",published_at:"0x000000000000000000000000000000000000000000000000000000000000dee9"},deepbook_endpoint_v2:{package_id:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6",published_at:"0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6"},aggregatorUrl:"https://api-sui.cetus.zone/router",swapCountUrl:"https://api-sui.cetus.zone/v2/sui/swap/count"},_u=new nd(Vy),zy=async(t,e,r,n,i)=>{console.log("getSwapRouterTxb account2: ",n),console.log("getSwapRouterTxb suiClient: ",i),_u.senderAddress=r;let o=await _u.getOwnerCoinAssets(r);return await Pe.buildAggregatorSwapTransaction(_u,t,o,"",e)},Wy=class dh extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r,suiClient:n}=e,{payloadParams:i}=this.data,o=await zy(i?.createTxParams,i?.slippage,i?.account,r,n);return console.log("Swap intention build txb: ",o),o}static fromData(e){return new dh(e)}},Hy=class{application="cetus";async deserialize(t){console.log("Helper deserialize input: ",t);let{payloadParams:e,action:r}=t;return{txType:ch.TransactionType.Other,txSubType:`Cetus${r}`,intentionData:{payloadParams:e,action:r}}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"CetusSwap":n=Wy.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},hh={};uh(hh,{contractId:()=>gh,default:()=>Zy,feeObjId:()=>bh,roleObjId:()=>wh,status:()=>mh,transaction:()=>ph,upgradeCapObjId:()=>_h,vaultObjId:()=>yh});var ph="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",mh="success",gh="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",wh="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",yh="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",bh="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",_h="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Zy={transaction:ph,status:mh,contractId:gh,roleObjId:wh,vaultObjId:yh,feeObjId:bh,upgradeCapObjId:_h},vh={};uh(vh,{contractId:()=>xh,default:()=>Ky,feeObjId:()=>Ih,roleObjId:()=>kh,status:()=>Sh,transaction:()=>Th,upgradeCapObjId:()=>Ch,vaultObjId:()=>Ah});var Th="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Sh="success",xh="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",kh="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Ah="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Ih="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ch="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Ky={transaction:Th,status:Sh,contractId:xh,roleObjId:kh,vaultObjId:Ah,feeObjId:Ih,upgradeCapObjId:Ch},Jy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Xy="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Yy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Qy="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",eb="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",tb="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",rb="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",nb="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",jf=hh,Ff=vh,ib=new Map([["dev",{env:"dev",rpc:{url:Jy},backend:{url:eb},contract:jf}],["stg",{env:"stg",rpc:{url:Xy},backend:{url:tb},contract:jf}],["prev",{env:"prev",rpc:{url:Yy},backend:{url:rb},contract:Ff}],["prod",{env:"prod",rpc:{url:Qy},backend:{url:nb},contract:Ff}]]);function ob(t,e){let r=ib.get(t);if(!r)throw new Error(`Env not supported: ${t}`);return e&&e.rpc&&(r.rpc=e.rpc),e&&e.backend&&(r.backend=e.backend),e&&e.contract&&(r.contract=e.contract),r}var Nt=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:n,context:i}=r;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=i}},sb=class extends Nt{constructor(){super(11,"Backend is not specified")}},ab=class extends Nt{constructor(){super(1,"Wallet not connected")}},vu=class extends Nt{constructor(t,e){super(10,t,{context:e})}},ub=class nn{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof dr.AxiosError)throw new vu(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new vu(e.data.code)}throw new vu(e.status.toString())}async getIncomingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{recipient:e,...r});return nn.parseResponseData(n)}async getOutgoingStreams(e,r){let n=await dr.default.post(`${this.apiURL}/stream`,{sender:e,...r});return nn.parseResponseData(n)}async getStreamHistory(e){let r=await dr.default.post(`${this.apiURL}/stream-events`,e),n=nn.parseResponseData(r);return n.data.forEach(i=>{let o=i;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),n}async getAllCoinTypes(e){let r=await dr.default.post(`${this.apiURL}/stream-info`,{address:e});return nn.parseResponseData(r)}async getAllRecipients(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{sender:e,status:r});return nn.parseResponseData(n)}async getAllSenders(e,r){let n=await dr.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:r});return nn.parseResponseData(n)}},Mh=class Eh{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Oh.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new ub(e.backend.url))}static new(e,r){let n=ob(e,r);return new Eh(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new sb;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new ab;return this.signer}async walletAddress(){return this.wallet.address()}},qf=50n,Tu=10000n,cb=25n,Lf=100000000n,rn=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},Uf=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},as=class Ph{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(r,n){if(n in r)return Reflect.get(r,n);let i=s=>new Ph(r.result[s]);if(n===Symbol.iterator)return function*(){let s=0;for(;;)yield i(s),s++};if(typeof n=="symbol")return;let o=parseInt(n,10);if(!(Number.isNaN(o)||o<0))return i(o)}})}moveArg(){return this.result}},$f=class extends Nt{constructor(t,e){super(3,t,{context:e})}},lb=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="address")throw new $f("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Dh.normalizeSuiAddress)(Au.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,n]=this.getValue(t,e);if(n!=="u64")throw new $f("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Au.Buffer.from(r).readBigInt64LE()}},Bt=class extends Nt{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}},Bh={groupId:"string",name:"string"},db=64;function fb(t){return Nh(t),Ru.bcs.ser(Bh,t).toString("base64")}function Iu(t){let e=Ru.bcs.de(Bh,t,"base64");return Nh(e),e}function Nh(t){if(!Gf(t.name))throw new Bt("Invalid metadata: Name contains unknown character");if(!Gf(t.groupId))throw new Bt("Invalid metadata: Group ID contains unknown character");if(t.name.length>db)throw new Bt("Invalid metadata: Name exceed max length 64")}function Gf(t){return/^[\x00-\x7F]+$/.test(t)}function Rh(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}function jn(t,e){return(0,Ni.normalizeStructTag)(t)===(0,Ni.normalizeStructTag)(e)}var jh="txn.gas";function hb(){return pf()}var Cu=class Fh{constructor(e,r,n){this.globals=e,this.feeContract=r,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:fb({name:e.name,groupId:hb()}),coinType:(0,Bi.normalizeStructTag)(e.coinType),recipients:e.recipients.map(r=>({address:r.address,cliffAmount:r.cliffAmount,amountPerEpoch:r.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let r=new ku.TransactionBlock,n=this.calculateFeesInternal(e),i=this.getCreateStreamCoinRequests(e,n),o=await this.wallet.requestCoins(i),s=await this.addMergeCoins(r,o[0]),u;i.length>1?u=await this.addMergeCoins(r,o[1]):u=s;for(let l=0;l<e.recipients.length;l++){let d=e.recipients[l],b=this.amountForRecipient(d,e.numberEpoch),_=this.getStreamFeeLocal(b),[T]=r.splitCoins(s,[r.pure(b+_,"u64")]),[x]=r.splitCoins(u,[r.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(r,{paymentCoin:new as(T),flatFeeCoin:new as(x),metadata:e.metadata,recipient:d.address,timeStart:e.startTime,cliff:d.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:d.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return r}calculateCreateStreamFees(e){let r=Fh.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(r)}feeParams(){return{createFeePercent:{numerator:qf,denominator:Tu},claimFeePercent:{numerator:cb,denominator:Tu},flatFeePerStream:Lf}}async addMergeCoins(e,r){let n;return r.mergedCoins&&r.mergedCoins.length?(e.mergeCoins(e.object(r.primaryCoin),r.mergedCoins.map(i=>e.object(i))),n=e.object(r.primaryCoin)):r.primaryCoin===jh?n=e.gas:n=e.object(r.primaryCoin),n}getCreateStreamCoinRequests(e,r){let n=e.coinType;return Rh(n,Bi.SUI_TYPE_ARG)?[{coinType:n,amount:r.totalAmount+r.streamFeeAmount+r.flatFeeAmount}]:[{coinType:n,amount:r.totalAmount+r.streamFeeAmount},{coinType:Bi.SUI_TYPE_ARG,amount:r.flatFeeAmount}]}calculateFeesInternal(e){let r=e.recipients.reduce((n,i)=>{let o=this.amountForRecipient(i,e.numberEpoch),s=this.getStreamFeeLocal(o);return{totalAmount:n.totalAmount+o,streamFeeAmount:n.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...r}}amountForRecipient(e,r){return BigInt(e.amountPerEpoch)*BigInt(r)+BigInt(e.cliffAmount)}get flatSuiFee(){return Lf}getStreamFeeLocal(e){return e*qf/Tu}async getStreamFeeRemote(e){let r=this.feeContract.streamingFee(new ku.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:r});return new lb(n).getU64()}get wallet(){return this.globals.wallet}},pb="0x0000000000000000000000000000000000000000000000000000000000000006",qh=class{constructor(t,e,r){this.moduleName=t,this.config=e,this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Ou.Transactions.MoveCall({target:r,arguments:e.arguments.map(n=>n instanceof Uf?n.moveArgs(t):n instanceof rn?n.moveArg(t):n instanceof as?n.moveArg():t.pure(n)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],n=[]){t.add(Ou.Transactions.MoveCall({target:e,arguments:r.map(i=>i instanceof Uf?i.moveArgs(t):i instanceof rn?i.moveArg(t):i instanceof as?i.moveArg():t.pure(i)),typeArguments:n}))}makeObject(t){return typeof t=="string"?new rn(t):t}vaultObject(){return new rn(this.config.vaultObjId)}roleObject(){return new rn(this.config.roleObjId)}feeObject(){return new rn(this.config.feeObjId)}clockObject(){return new rn(pb)}},Lh=class Er extends qh{constructor(e,r){super(Er.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_fee,arguments:[n,i,r],typeArgs:[]})}setStreamingFlatFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_streaming_flat_fee,arguments:[n,i,r],typeArgs:[]})}setClaimFee(e,r){let n=this.roleObject(),i=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.set_claim_fee,arguments:[n,i,r],typeArgs:[]})}streamingFee(e,r){let n=this.feeObject();return this.addContractCall(e,{method:Er.MethodName.streaming_fee,arguments:[n,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:Er.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:Er.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},cs=class Tt extends qh{constructor(e,r){super(Tt.ModuleName,e,r),this.config=e,this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let n=this.feeObject(),i=this.vaultObject(),o=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),u=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.create_stream,arguments:[n,i,o,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,u],typeArgs:[r.coinType]})}setAutoClaim(e,r){let n=this.makeObject(r.streamId);return this.addContractCall(e,{method:Tt.MethodName.set_auto_claim,arguments:[n,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.cancel_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStream(e,r){let n=this.makeObject(r.streamId),i=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream,arguments:[n,i],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let n=this.makeObject(r.streamId),i=this.vaultObject(),o=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:Tt.MethodName.claim_stream_by_proxy,arguments:[n,i,o,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${Tt.ModuleName}::${Tt.MethodName.claim_stream_by_proxy}`}},Uh=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new Lh(e,t),this.streamContract=new cs(e,t)}feeContract;streamContract;async createStreams(t){let e=Cu.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let n=new Pi.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new Pi.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new Pi.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}},mb=class extends Nt{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}},gb=1e3,wb=class{constructor(t){this.globals=t,this.coinMetaHelper=new yb(t.suiClient),this.createStreamHelper=new Uh(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new mb(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,n=(t.totalAmount-r)/t.steps,i={realTotalAmount:n*t.steps+r,cliffAmount:r,amountPerStep:n};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new Bt("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(_e.fromMillis(Number(e*t.steps))),n={timeStart:t.timeStart,timeEnd:r,interval:_e.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(n),n}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),n=await this.getCoinMeta(e);return{...r,coinType:(0,Ln.normalizeStructTag)(r.coinType),coinMeta:n}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,i)=>({...n,coinType:(0,Ln.normalizeStructTag)(n.coinType),coinMeta:r[i]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new Bt("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new Bt("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<gb)throw new Bt("Interval shall be at least 1 second","interval",t.interval)}},yb=class{constructor(t){this.suiClient=t,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,Ln.normalizeStructTag)(t||Ln.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}},bb=class extends Nt{constructor(){super(7,"Connected wallet is not creator")}},Vf=class extends Nt{constructor(){super(8,"Connected wallet is not recipient")}},zf=class extends Nt{constructor(t,e){super(6,t,{context:e})}},Xt=class extends Nt{constructor(t,e={}){super(0,t,e)}},_b=class extends Nt{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}},vb=(1n<<64n)-1n,us=1e3;function Wf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return le.fromMillis(r*us)}function Hf(t){let e;typeof t=="number"?e=t:typeof t=="bigint"?e=Number(t):e=t.toMillis();let r=Math.round(e/us);return _e.fromMillis(r*us)}var ju=class Pr{constructor(e,r,n){this.globals=e,this.streamId=r,this.rawData=n,this.streamContract=new cs(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,r){let n=await Pr.fetchStreamData(e,r);return new Pr(e,r,n)}static fromObjectData(e,r,n){let i=Pr.parseRawStreamData(r,n);return new Pr(e,r,i)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await Pr.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new Xt("Object Id does not align");this.rawData=Pr.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new bb;let e=new Di.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let e=new Di.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new Vf;let r=new Di.TransactionBlock;return this.streamContract.setAutoClaim(r,{streamId:this.streamId,coinType:this.coinType,enabled:e}),r}async claimByProxy(){let e=new Di.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Ri.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Hf(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Iu(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Iu(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Wf(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,r=e.epochInterval*e.totalEpoch;return Hf(r)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Wf((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===vb?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=le.now().toMillis(),r=this.timeStart.toMillis();if(e<r)return-1n;let n=Math.floor((e-r)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,r){let n=await e.suiClient.getObject({id:r,options:{showContent:!0,showType:!0}});return Pr.parseRawStreamData(r,n)}static parseRawStreamData(e,r){if(r.error)throw r.error.code==="notExists"?new _b(e):new zf(`get stream data: ${r.error.code}`,{streamId:e,...r.error});let n=r.data.content;if(n.dataType!=="moveObject")throw new zf("Unexpected object type",{gotType:n.dataType});let{typeParams:i}=(0,Ri.parseStructTag)(n.type),o=(0,Ri.normalizeStructTag)(i[0]),s=n.fields,u=s.config.fields,l=s.status.fields;return{coinType:o,autoClaim:s.auto_claim,balance:BigInt(s.balance.fields.balance),config:{amountPerEpoch:BigInt(u.amount_per_epoch),cancelable:u.cancelable,cliff:BigInt(u.cliff),creator:u.creator,epochInterval:BigInt(u.epoch_interval),metadata:u.metadata,recipient:u.recipient,timeStart:BigInt(u.time_start),totalEpoch:BigInt(u.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}},Su=class extends Nt{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Tb(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Sb=class{constructor(t){this.requester=t,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},$h=class{constructor(t){this.requester=t,this.pager=new Sb(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},xb=25;async function Zf(t,e,r){let n=new Gh(e),i=new Vh(t,n,r);return await Tb(i)}var Gh=class{constructor(t){this.ids=t,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},Vh=class extends $h{constructor(t,e,r){super(new kb(t,e,r)),this.suiClient=t,this.idIter=e,this.options=r}},kb=class{constructor(t,e,r){this.suiClient=t,this.stringIter=e,this.options=r,this.filter=r?.filter,this.pageSize=r?.pageSize||xb,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&t.push(n)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:n}=this;r=e.filter(i=>n?.(i))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}},Ab=class ns{constructor(e,r){if(this.globals=e,this.streams=r,r.length===0)throw new Su("stream size 0");let n=r.map(i=>i.groupId);if(new Set(n).size!==1)throw new Bt("Stream does not have same group ID")}type="StreamGroup";static async new(e,r){let n=await Zf(e.suiClient,r);return n.forEach(i=>{if(!i)throw new Xt("stream group object data undefined")}),ns.newFromObjectResponse(e,r,n)}static async newFromObjectResponse(e,r,n){let i=await ns.parseGroupStreams(e,r,n);return new ns(e,i)}static checkStreamGroup(e){let r=e.map(o=>o.groupCommonInfo),n=r[0],i=!0;return r.forEach(o=>{Ib(n,o)||(i=!1)}),i}async refresh(){let e=await Zf(this.globals.suiClient,this.streams.map(r=>r.streamId));this.streams.forEach((r,n)=>{r.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,r)=>e+r.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,r)=>e+r.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,r)=>r.nextReleaseAmount===null?e:e+r.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,r)=>e+r.totalAmount,0n),streamed:this.streams.reduce((e,r)=>e+r.streamedAmount,0n),claimed:this.streams.reduce((e,r)=>e+r.claimedAmount,0n),claimable:this.streams.reduce((e,r)=>e+r.claimable,0n),canceled:this.streams.reduce((e,r)=>e+r.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,r,n){let i=n.map((o,s)=>ju.fromObjectData(e,r[s],o)).filter(o=>!!o);if(new Set(i.map(o=>o.groupId)).size!==1)throw new Su("Not same group ID");if(!this.checkStreamGroup(i))throw new Su("Not same stream settings");return i}};function Ib(t,e){return t.name===e.name&&t.groupId===e.groupId&&t.creator===e.creator&&t.start.toMillis()===e.start.toMillis()&&t.interval.toMillis()===e.interval.toMillis()&&t.steps===e.steps&&t.cancelable===e.cancelable}var Kf=class Mu{constructor(e,r){this.it=e,this.pageSize=r}static async newIncoming(e){let r=await Jf.newIncoming(e);return new Mu(r,e.pageSize)}static async newOutgoing(e){let r=await Jf.newOutgoing(e);return new Mu(r,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},Jf=class Eu{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let r=await Xf.newIncomingQuery(e);return new Eu(r)}static async newOutgoing(e){let r=await Xf.newOutgoingQuery(e);return new Eu(r)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let r=await this.requester.doNextRequest();if(r===null)throw new Xt("No more results");return r}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new Xt("No more results");return e}},Xf=class Pu{constructor(e,r,n,i){this.globals=e,this.recipient=r,this.groupRefs=n,this.query=i,this.current=0;let o=new Gh(n.flat().map(s=>s.streamId));this.objectIter=new Vh(e.suiClient,o)}current=0;objectIter;static async newIncomingQuery(e){let r=Pb(e.query),n=await e.globals.walletAddress(),i=(await e.globals.backend.getIncomingStreams(n,r)).filter(s=>(0,Rr.normalizeSuiAddress)(s.recipient)===(0,Rr.normalizeSuiAddress)(n)),o=Yf(i);return new Pu(e.globals,n,o,e.query)}static async newOutgoingQuery(e){let r=Db(e.query),n=await e.globals.walletAddress(),i=await e.globals.backend.getOutgoingStreams(n,r),o=Yf(i);return new Pu(e.globals,n,o,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let r=await Mb(this.globals,e[0].streamId,this.objectIter);return this.current++,zh(r,this.query)?r:this.doNextRequest()}if(e.length>1){let r=await Eb(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Ob(r,this.query)?r:this.doNextRequest()}throw new Xt("Stream group with no stream")}};function Yf(t){let e=new Map;return t.forEach(r=>{let n=e.get(r.groupId);n?(n.push(r),e.set(r.groupId,n)):e.set(r.groupId,[r])}),Array.from(e.values()).sort((r,n)=>le.fromISO(n[0].createDate).toMillis()-le.fromISO(r[0].createDate).toMillis())}function zh(t,e){if(e===void 0)return!0;let r=Cb(t,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?t.progress.claimable!==0n:t.progress.claimable===0n;return r&&n}return r}function Cb(t,e){return e===void 0?!0:Array.isArray(e)?e.includes(t.progress.status):t.progress.status===e}function Ob(t,e){if(!e)return!0;let r=!1;return t.streams.forEach(n=>{zh(n,e)&&(r=!0)}),r}async function Mb(t,e,r){let n=await Wh(r,e);return ju.fromObjectData(t,e,n)}async function Eb(t,e,r){let n=[];for(;n.length<e.length;){let i=await Wh(r,e[n.length]);n.push(i)}return Ab.newFromObjectResponse(t,e,n)}async function Wh(t,e){if(!await t.hasNext())throw new Xt("object iterator has been consumed");let r=await t.next();if(!r||r.error||r.data===void 0||r.data===null)throw new Xt("object iterator undefined response",{cause:r?.error});if(r?.data?.objectId!==e)throw new Xt("stream id not aligned");return r}function Pb(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),sender:Zh(t?.sender)}}function Db(t){return{status:Fu(t?.status),coinType:Hh(t?.coinType),recipient:Zh(t?.recipient)}}function Fu(t){return t===void 0||t.length===0?"all":Array.isArray(t)?t.reduce((e,r)=>{let n=Fu(r);return!e||e===n?n:"all"},void 0):Bb(t)}function Bb(t){switch(t){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new Bt("Unknown stream filtered status")}}function Hh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeStructTag)(e)):void 0:(0,Rr.normalizeStructTag)(t)}function Zh(t){if(t)return Array.isArray(t)?t.length!==0?t.map(e=>(0,Rr.normalizeSuiAddress)(e)):void 0:(0,Rr.normalizeSuiAddress)(t)}var Nb=class extends Nt{constructor(t,e,r){super(4,`Not enough balance: ${t}`,{context:{coinType:t,requestAmount:e,gotAmount:r}}),this.coinType=t,this.requestAmount=e,this.gotAmount=r}},Rb=25;async function jb(t,e,r,n="0x2::sui::SUI",i=Rb){let o=new Fb(t,e,n,i),s=BigInt(0),u=[];for(;await o.hasNext()&&s<r;){let l=await o.next();l&&(u.push(l),s+=BigInt(l.balance))}if(s<r)throw new Nb(n,r,s);return u}var Fb=class extends $h{constructor(t,e,r,n){super(new qb(t,e,r,n)),this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n}},qb=class{constructor(t,e,r,n){if(this.suiClient=t,this.owner=e,this.coinType=r,this.reqPageSize=n,n<=0)throw new Xt("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}},Lb=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},Ub=class{constructor(t){this.account=t}async address(){return this.account.address}},$b=class{constructor(t,e){this.singleWallet=t,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(Rh(t.coinType,on.SUI_TYPE_ARG))return{primaryCoin:jh};if(t.amount<=0)throw new Bt("Invalid coin request","coinAmount",t.amount);let e=await jb(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new Xt("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},Gb=class{globals;helper;constructor(t,e){this.globals=Mh.new(t,e),this.helper=new wb(this.globals)}connectSingleWallet(t){let e=new $b(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new Lb(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return ju.new(this.globals,t)}async getIncomingStreams(t,e=10){return Kf.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Kf.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(e=>(0,on.normalizeStructTag)(e))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(r=>(0,on.normalizeSuiAddress)(r))}get wallet(){return this.globals.wallet}builder(){return new Uh(this.globals)}},Vb=class{constructor(t){this.data=t}serialize(){return JSON.stringify((0,Kh.default)(this.data))}},ji=class extends Vb{application="mpay";getClient(t,e){let r=new Gb(t==="sui:mainnet"?"prod":"dev");return r.connectSingleWallet(new Ub(e)),r}},Qf=class extends ji{constructor(t){super(t),this.data=t}txType=fh.TransactionType.Stream;txSubType="Cancel";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).cancel()}},eh=class extends ji{constructor(t){super(t),this.data=t}txType=Jh.TransactionType.Stream;txSubType="ClaimByProxy";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claimByProxy()}},th=class extends ji{constructor(t){super(t),this.data=t}txType=Xh.TransactionType.Stream;txSubType="Claim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).claim()}},rh=class extends ji{constructor(t){super(t),this.data=t}txType=Yh.TransactionType.Stream;txSubType="CreateStream";async build(t){let{network:e,account:r}=t;return this.getClient(e,r).createStream(this.data)}},Qh=class is{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return is.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return is.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return BigInt(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Dr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return is.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Dr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Dr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Dr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Dr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Du.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Dr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},zb=class{constructor(t,e){this.globals=t,this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t);return{type:"CreateStream",info:t,fees:e}}decodeCreateStreamInfo(){let t=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(t)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&jn(e.target,this.contract.createStreamTarget));if(t.length===0)throw new Xt("No create stream transactions");return t.map(e=>new Qh(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:n}=Iu(e),i=t.decodeInputAddress(5),o=t.decodeInputU64(6),s=t.decodeInputU64(7),u=t.decodeInputU64(8),l=t.decodeInputU64(9),d=t.decodeInputU64(10),b=t.decodeInputBool(11),_=t.typeArg(0);return{name:r,groupId:n,recipient:i,timeStart:o,cliff:s,epochInterval:u,totalEpoch:l,amountPerEpoch:d,cancelable:b,coinType:_}}aggregateGroupStreamInfo(t){if(new Set(t.map(r=>JSON.stringify({name:r.name,groupId:r.groupId,timeStart:String(r.timeStart),epochInterval:String(r.epochInterval),totalEpoch:String(r.totalEpoch),cancelable:r.cancelable,coinType:r.coinType}))).size!==1)throw new Bt("Stream group not have common info");let e=t.map(r=>({address:r.recipient,amountPerStep:r.amountPerEpoch,cliffAmount:r.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:e,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new cs(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Lh(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Cu(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}},Wb=class{constructor(t,e){this.globals=t,this.txb=e,this.contract=new cs(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction();throw new Error("Unknown stream transaction type")}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(t=>t.kind==="MoveCall"&&jn(t.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&jn(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new zb(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let t=this.transactions[0];return new Qh(t,this.txb)}},nh=class extends ji{constructor(t){super(t),this.data=t}txType=ep.TransactionType.Stream;txSubType="SetAutoClaim";async build(t){let{network:e,account:r}=t;return(await this.getClient(e,r).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Hb=class{application="mpay";async deserialize(t){let{network:e,transactionBlock:r}=t,n=Mh.new(e==="sui:mainnet"?"prod":"dev"),i=new Wb(n,r).decode(),o;switch(i.type){case"CreateStream":o=new rh(i.info);break;case"SetAutoClaim":o=new nh({streamId:i.streamId,enabled:i.enabled});break;case"Claim":o=new th({streamId:i.streamId});break;case"ClaimByProxy":o=new eh({streamId:i.streamId});break;case"Cancel":o=new Qf({streamId:i.streamId});break;default:throw new Error(`Unknown transaction type: ${i}`)}return{txType:o.txType,txSubType:o.txSubType,intentionData:o.data}}async build(t){let{intentionData:e}=t,r;switch(t.txSubType){case"CreateStream":r=new rh(e);break;case"Claim":r=new th(e);break;case"ClaimByProxy":r=new eh(e);break;case"SetAutoClaim":r=new nh(e);break;case"Cancel":r=new Qf(e);break;default:throw new Error("not implemented")}return r.build({...t})}},Zb=class rp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,tp.buildCoinTransferTxb)(r,this.data,n.address)}static fromData(e){return new rp(e)}},Kb=class ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e;return(0,np.buildObjectTransferTxb)(r,this.data,n.address)}static fromData(e){return new ip(e)}},Jb=class ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:r}=e,n=sp.TransactionBlock.from(this.data.content);if(!(0,op.isSameAddress)(n.blockData.sender,r.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ap(e)}},Xb=class{application;constructor(){this.application=qn.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case qn.TransactionSubTypes.assets.coin.send:n=Zb.fromData(t.intentionData);break;case qn.TransactionSubTypes.assets.object.send:n=Kb.fromData(t.intentionData);break;case qn.TransactionSubTypes.others.plain:n=Jb.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},Yb={ProtocolPackage:"0x7c9b90b3fda0fa4aa8ee88ae6c4a0b83c773f74936b5354448cb94662e94442d",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},ce=Yb,Qb=class{constructor(t){this.txb=t}decode(){if(console.log("txb",this.txb),this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isClaimRewardTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return!!this.getMoveCallTransaction(`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(t){let e=Object.values(ce.pool).find(r=>r.assetId===t);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let t=[];return this.transactions.forEach(e=>{if(e.kind==="MoveCall"&&e.target===`${ce.ProtocolPackage}::incentive_v2::claim_reward`){let r=new ih(e,this.txb),n=r.decodeInputU8(4),i=r.decodeInputU8(5),o=r.decodeSharedObjectId(2),s=this.findPoolByAssetId(n),u=[...e.typeArguments];t.push({coinType:s.coinType,option:i,typeArguments:u,assetId:n,poolId:o})}}),console.log("decode claims",t),{txType:Fn.TransactionType.Other,type:"ClaimReward",intentionData:{claims:t}}}decodeEntryBorrow(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryBorrow",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryDeposit(){let t=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryDeposit",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryRepay(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryRepay",intentionData:{amount:e,coinType:r.coinType}}}decodeEntryWithdraw(){let t=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),r=this.findPoolByAssetId(t);return{txType:Fn.TransactionType.Other,type:"EntryWithdraw",intentionData:{amount:e,coinType:r.coinType}}}get helper(){let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith(ce.ProtocolPackage));return new ih(t,this.txb)}},ih=class os{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return os.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return os.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Br.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return os.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Br.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Br.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Br.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Br.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Bu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Br.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function oh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[t.object("0x06"),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function e_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.Incentive),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function t_(t,e,r){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),t.pure(r),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function sh(t,e,r,n){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[t.object("0x06"),t.object(ce.PriceOracle),t.object(ce.StorageId),t.object(e.poolId),t.pure(e.assetId),r,t.pure(n),t.object(ce.IncentiveV2)],typeArguments:[e.type]}),t}function r_(t,e,r,n,i){return t.moveCall({target:`${ce.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[t.object("0x06"),t.object(ce.IncentiveV2),t.object(r),t.object(ce.StorageId),t.pure(e),t.pure(n)],typeArguments:i}),t}var n_=class lp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{claims:e}=this.data,r=new cp.TransactionBlock;return e.forEach(n=>{let{assetId:i,poolId:o,option:s,typeArguments:u}=n;r_(r,i,o,s,u)}),r}static fromData(e){return new lp(e)}},i_=class fp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new dp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return t_(n,i,r)}static fromData(e){return new fp(e)}};async function pp(t,e,r){let n=await t.getCoins({owner:e,coinType:r});return console.log("getTokenObjs",e,n),n}var o_=class mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new hp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return oh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return oh(s,u,s.object(d),o)}static fromData(e){return new mp(e)}},s_=class wp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:n}=e,{coinType:i,amount:o}=this.data,s=new gp.TransactionBlock;if(console.log("build",this.data),i==="sui"){let[b]=s.splitCoins(s.gas,[o]);return sh(s,ce.pool.sui,b,o)}let u=ce.pool[i];if(!u)throw new Error(`${i} not support, please use ${Object.keys(ce.pool).join(", ")}.`);let l=await pp(r,n.address,u.type);if(!l.data[0])throw new Error(`Insufficient balance for ${u.name} Token`);let d=l.data[0].coinObjectId;if(l.data.length>=2){let b=1;for(;b<l.data.length;)s.mergeCoins(d,[l.data[b].coinObjectId]),b++}return sh(s,u,s.object(d),o)}static fromData(e){return new wp(e)}},a_=class bp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:r}=this.data,n=new yp.TransactionBlock;console.log("build",this.data);let i=ce.pool[e];if(!i)throw new Error(`${e} not support, please use ${Object.keys(ce.pool).join(", ")}.`);return e_(n,i,r)}static fromData(e){return new bp(e)}},u_=class{application="navi";async deserialize(t){let{transactionBlock:e}=t,r=new Qb(e).decode();return{txType:up.TransactionType.Other,txSubType:r.type,intentionData:r.intentionData}}async build(t){let{suiClient:e,account:r}=t,n;switch(t.txSubType){case"EntryDeposit":n=o_.fromData(t.intentionData);break;case"EntryBorrow":n=i_.fromData(t.intentionData);break;case"EntryRepay":n=s_.fromData(t.intentionData);break;case"EntryWithdraw":n=a_.fromData(t.intentionData);break;case"ClaimReward":n=n_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:r})}},c_=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}},l_="msafe-plain-tx",d_=ls.TransactionSubTypes.others.plain,f_=class{application;constructor(){this.application=l_}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=await e.build({client:r});return{txType:ls.TransactionType.Other,txSubType:d_,intentionData:{content:(0,ds.toHEX)(n)}}}async build(t){let{suiClient:e,account:r}=t,n=_p.TransactionBlock.from((0,ds.fromHEX)(t.intentionData.content)),i=await e.devInspectTransactionBlock({transactionBlock:n,sender:r.address});if(i.effects.status.status!=="success")throw new Error(i.effects.status.error);return n}},xu={PackageId:"0x9632f61a796fc54952d9151d80b319e066cba5498a27b495c99e113db09726b1"},h_=class{constructor(t){this.txb=t}get transactions(){return this.txb.blockData.transactions}decode(){if(this.isAddLiquidityTransaction())return this.decodeAddLiquidity();throw new Error("Unknown transaction type")}getMoveCallTransaction(t){return this.transactions.find(e=>e.kind==="MoveCall"&&e.target===t)}isAddLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::mint`)}isIncreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::increase_liquidity`)}isDecreaseLiquidityTransaction(){return!!this.getMoveCallTransaction(`${xu.PackageId}::position_manager::decrease_liquidity`)}decodeAddLiquidity(){console.log(this.helper,"this.helper");let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputAddress(12),r=this.helper.decodeInputU64(10),n=this.helper.decodeInputU64(11),i=this.helper.decodeInputU32(6),o=this.helper.decodeInputU32(8);return{txType:Tp.TransactionType.Other,type:"AddLiquidity",intentionData:{pool:t,slippage:5,address:e,amountA:r,amountB:n,tickLower:i,tickUpper:o}}}get helper(){console.log(this.transactions,"this.transactions");let t=this.transactions.find(e=>e.kind==="MoveCall"&&e.target.startsWith("")&&e.target!=="0x2::coin::zero");return console.log(t,this.txb,"this.txb"),new p_(t,this.txb)}},p_=class ss{constructor(e,r){this.moveCall=e,this.txb=r}decodeSharedObjectId(e){let r=this.getInputParam(e);return ss.getSharedObjectId(r)}decodeOwnedObjectId(e){let r=this.getInputParam(e);return ss.getOwnedObjectId(r)}decodeInputU64(e){let r=this.decodePureArg(e,"u64");return Number(r)}decodeInputU32(e){let r=this.decodePureArg(e,"u32");return Number(r)}decodeInputU8(e){let r=this.decodePureArg(e,"u8");return Number(r)}decodeInputAddress(e){let r=this.decodePureArg(e,"address");return(0,Nr.normalizeSuiAddress)(r)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,r){let n=this.getInputParam(e);return ss.getPureInputValue(n,r)}getInputParam(e){let r=this.moveCall.arguments[e];if(r.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[r.index]}static getPureInputValue(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,Nr.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,Nr.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,Nr.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,Nr.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,r){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Nu.bcs.de(r,new Uint8Array(n))}typeArg(e){return(0,Nr.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},m_=class Sp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,tickLower:l,tickUpper:d,txb:b}=this.data;return r.pool.addLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,tickLower:l,tickUpper:d,txb:b})}static fromData(e){return new Sp(e)}},g_=class xp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,nft:i,txb:o}=this.data;return r.nft.burn({pool:n,nft:i,txb:o})}static fromData(e){return new xp(e)}},w_=class kp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,collectAmountA:s,collectAmountB:u,txb:l}=this.data;return r.pool.collectFee({pool:n,address:i,collectAmountA:s,collectAmountB:u,nft:o,txb:l})}static fromData(e){return new kp(e)}},y_=class Ap extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,nft:o,rewardAmounts:s,txb:u}=this.data;return r.pool.collectReward({pool:n,address:i,rewardAmounts:s,nft:o,txb:u})}static fromData(e){return new Ap(e)}},b_=class Ip extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{fee:n,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,amountA:_,amountB:T,txb:x}=this.data;return r.pool.createPool({fee:n,amountA:_,amountB:T,address:i,tickLower:o,tickUpper:s,sqrtPrice:u,slippage:l,coinTypeA:d,coinTypeB:b,txb:x})}static fromData(e){return new Ip(e)}},__=class Cp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,txb:b}=this.data;return r.pool.decreaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,decreaseLiquidity:d,txb:b})}static fromData(e){return new Cp(e)}},v_=class Op extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,txb:d}=this.data;return r.pool.increaseLiquidity({pool:n,slippage:u,address:i,amountA:o,amountB:s,nft:l,txb:d})}static fromData(e){return new Op(e)}},T_=class Mp extends St{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let r=new It(e.network.replace("sui:",""),e.suiClient),{pool:n,address:i,amountA:o,amountB:s,slippage:u,nft:l,decreaseLiquidity:d,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x}=this.data;return r.pool.removeLiquidity({pool:n,decreaseLiquidity:d,nft:l,amountA:o,amountB:s,slippage:u,address:i,collectAmountA:b,collectAmountB:_,rewardAmounts:T,txb:x})}static fromData(e){return new Mp(e)}},ah=class{application="turbos";async deserialize(t){let{transactionBlock:e,suiClient:r}=t,n=new h_(e).decode();return{txType:vp.TransactionType.Other,txSubType:n.type,intentionData:n.intentionData}}async build(t){let{suiClient:e,account:r,network:n}=t,i;switch(t.txSubType){case"CreatePool":i=b_.fromData(t.intentionData);break;case"AddLiquidity":i=m_.fromData(t.intentionData);break;case"IncreaseLiquidity":i=v_.fromData(t.intentionData);break;case"DecreaseLiquidity":i=__.fromData(t.intentionData);break;case"RemoveLiquidity":i=T_.fromData(t.intentionData);break;case"CollectFee":i=w_.fromData(t.intentionData);break;case"CollectReward":i=y_.fromData(t.intentionData);break;case"Burn":i=g_.fromData(t.intentionData);break;default:throw new Error("not implemented")}return i.build({suiClient:e,account:r,network:n})}},fs=new c_([new Xb,new u_,new ah,new Hb,new f_,new Hy,new ah]);var me=require("@msafe/sui3-utils"),Hu=require("@mysten/sui.js/transactions"),bs=require("@mysten/sui.js/utils");var Ep=require("@mysten/sui.js/transactions"),S_=1000n,x_=120n,k_=100n,A_={multiplier:{numerator:x_,denominator:k_}};var hs=class{constructor(e){this.globals=e}async simulate(e,r=A_){let n=this.copyTransactionBlock(e.txb),{suiClient:i}=this.globals,o=await this.getGasPrice(r);n.setGasPrice(o);let s=await i.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:u}=s.effects,l=this.toGasBudget(u,o),d=s.effects.status.status==="success",b;return d||(b=s.effects.status.error),{success:d,gasPrice:o,gasObject:s.effects.gasObject.reference,gasUsed:u,gasBudget:l,simulationError:b}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let r=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(r,e)}toGasBudget(e,r){let{computationCost:n,storageCost:i}=e,o=S_*r,s=BigInt(n)+o,u=s+BigInt(i);return u>s?u:s}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,r){if(this.isFixedValue(r))return r.fixedVal;if(this.isMultiplier(r)){let{multiplier:n}=r;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ep.TransactionBlock.from(e.serialize())}};var qu=require("buffer");function ps(t){return qu.Buffer.from(t,"utf-8")}function I_(t){return`0x${Array.prototype.map.call(t,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ms(t){return Uint8Array.from(qu.Buffer.from(t.startsWith("0x")?t.slice(2):t,"hex"))}var ws=require("@mysten/sui.js/verify");var jr=require("@mysten/sui.js/utils");var gs=require("@mysten/sui.js/utils"),Fi=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let r=(0,gs.normalizeStructTag)(e);if(this._coinMetaReg.has(r))return this._coinMetaReg.get(r);let n=await this.queryCoinMeta(r);return n&&this._coinMetaReg.set(r,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Lu=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,qi=class t{static isCoin(e){return e?(0,gs.normalizeStructTag)(e).match(Lu)!=null:!1}static getCoinType(e){let[,r]=(0,gs.normalizeStructTag)(e).match(Lu)??[];return r||null}static getBalance(e){if(!t.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:r}=e.content?.fields;if(r!==void 0)return BigInt(r)}};var fr=class{static normalizeSuiAddress(e){return(0,jr.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,jr.normalizeStructTag)(e)}static isSuiAddressEqual(e,r){return(0,jr.normalizeSuiAddress)(e)===(0,jr.normalizeSuiAddress)(r)}static isSuiStructEqual(e,r){return(0,jr.normalizeStructTag)(e)===(0,jr.normalizeStructTag)(r)}static isCoinObjectType(e){return qi.isCoin(e)}};function Uu(t,e){return t.startsWith(e)?t:e+t}var $u=class t{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,ws.verifyTransactionBlock)(e.message,e.signature):(0,ws.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let r=ps(e.messageStr);return this.getPublicKeyFromSignature({message:r,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let r=await t.getPublicKeyFromSignature(e);return fr.isSuiAddressEqual(r.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let r=ps(e.messageStr);return this.verifySignature({message:r,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Pp=require("@msafe/sui3-utils"),Dp=require("@mysten/sui.js/cryptography"),Bp=require("@mysten/sui.js/multisig");var C_="0x2::sui::SUI";async function Gu(t,e){let r;try{r=await t.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(r.data.length===0||!r.data[0].transaction?.txSignatures)return;let i=r.data[0].transaction?.txSignatures;for(let o=0;o!==i.length;o++){let s=i[o],u=O_(s,e);if(u)return u}}function O_(t,e){let r=(0,Dp.parseSerializedSignature)(t);switch(r.signatureScheme){case"MultiSig":{let n=new Bp.MultiSigPublicKey(r.multisig.multisig_pk).toSuiAddress();if(fr.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(fr.isSuiAddressEqual(r.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Pp.PublicKeySerde.de({publicKeyEncoded:r.publicKey,schema:r.signatureScheme});return fr.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function M_(t){let e=!0,r,n=[];for(;e;){let i=await t.suiClient.getCoins({owner:t.owner,coinType:t.coinType,cursor:r});n.push(...i.data),e=i.hasNextPage,r=i.nextCursor}return n}var Np=25;async function Rp(t){let e=[];for(;await t.hasNext();){let r=await t.next();e.push(r)}return e&&Array.isArray(e[0])?e.flat(1):e}var Vu=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ys=class{constructor(e){this.requester=e;this.pager=new Vu(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function jp(t,e,r){let n=new zu(t,e,r);return await Rp(n)}var zu=class extends ys{constructor(r,n,i){super(new Wu(r,n,i));this.provider=r;this.owner=n;this.options=i}},Wu=class{constructor(e,r,n){this.provider=e;this.owner=r;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Np,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let r;if(this.filter){let{filter:n}=this;r=e.data.filter(i=>n?.(i))}else r=e.data;return{data:r.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var sn=class t{constructor(e,r){this.globals=e;this.info=r;this.multiSig=new me.MultiSigAccount({threshold:r.threshold,ownersWithWeight:r.owners,creationNonce:r.creationNonce}),this.coinHelper=new Fi(this.suiClient),this.simulator=new hs(e)}multiSig;coinHelper;simulator;static async New(e,r){let n=await e.backend.getMSafeAccountInfo(r);if(new t(e,n).address!==r)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async r=>{let n=await this.coinHelper.getCoinMeta(r.coinType),i=r.lockedBalance.number?BigInt(r.totalBalance)-BigInt(r.lockedBalance.number):BigInt(r.totalBalance);return{type:(0,bs.normalizeStructTag)(r.coinType),balance:BigInt(i),metadata:n}}))}async ownedObjects(e){let r={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return jp(this.suiClient,this.address,r)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let r=e.pending,n=e.reject;return{application:r.application,txType:r.txType,txSubType:r.txSubType,createdAt:r.createdAt,creator:r.creator,digest:r.digest,intention:r.intention,sequenceNumber:r.sequenceNumber,payload:r.payload,votes:r.votes,approvalWeight:this.calculateWeightFromVotes(r.votes),msafeAddress:r.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let r=me.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:r});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let i=await n.build({client:this.globals.suiClient}),o=await n.getDigest({client:this.globals.suiClient}),s=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,bs.toHEX)(i),digest:o,msafeAddress:this.address,signature:s.signature})}async simulateCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async proposeCoinTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.coin.send,sequenceNumber:r,intention:e})}async simulateObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async proposeObjectTransferIntention(e){let r=await this.nextSequenceNumber();return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Assets,txSubType:me.TransactionSubTypes.assets.object.send,sequenceNumber:r,intention:e})}async simulatePlainPayloadIntention(e){let r=await this.nextSequenceNumber();return this.simulateIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async proposePlainPayloadIntention(e){let r=await this.nextSequenceNumber(),n=Hu.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,me.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:me.TransactionDefaultApplication,txType:me.TransactionType.Other,txSubType:me.TransactionSubTypes.others.plain,sequenceNumber:r,intention:e})}async voteForTransaction(e,r){let n=ms(r),i=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:i.signature})}async proposePendingTransaction(e){let r=new Hu.TransactionBlock,n=await r.build({client:this.suiClient}),i=await r.getDigest({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:i,signature:o.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let r=e.payload,n=(0,me.buildRejectTxb)(this.address,r);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let r=await this.pendingTransaction();if(!r||r.rejectDigest!=="")throw new Error("Already rejected");let n=r.payload,i=(0,me.buildRejectTxb)(this.address,n),o=await i.getDigest({client:this.suiClient}),s=await i.build({client:this.suiClient}),u=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:o,signature:u.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),r=fs.getAppHelper(e.application);if(!r)throw new Error(`Can't find app helper for application ${e.application}`);let n=await r.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,r=!1){let n=r?e.rejectVotes:e.votes,i=r?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let o=[],s=new Map(n.map(l=>[l.userAddress,l.signature]));for(let l=0;l<this.info.owners.length;l++){let d=this.info.owners[l],b=s.get(d.address);b&&o.push(b)}let u=this.multiSig.combinePartialSignatures(o);return this.suiClient.executeTransactionBlock({transactionBlock:ms(i),signature:u,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(r=>r.userAddress))}calculateWeight(e){let r=0;for(let n=0;n<e.length;n++){let i=this.info.owners.find(o=>(0,me.isSameAddress)(o.address,e[n]));i&&(r+=i.weight)}return r}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Fp=require("@msafe/sui3-utils"),qp=require("@mysten/sui.js/utils");var _s=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let r=this.knownPublicKeys.get(e);if(r)return r;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let r=new Array(e.length).fill(void 0);for(let o=0;o<e.length;o++){let s=e[o];r[o]=this.knownPublicKeys.get(s)}let n=r.map((o,s)=>o===void 0?s:-1).filter(o=>o!==-1);if(n.length===0)return r;let i=await this.globals.backend.getPublicKeyBatch(n.map(o=>e[o]));for(let o=0;o<n.length;o++){let s=n[o];r[s]=i[o]}for(let o=0;o<r.length;o++)r[o]===void 0&&(r[o]=await this.getPublicKeyFromChain(e[o]));for(let o=0;o<e.length;o++)r[o]&&this.knownPublicKeys.set(e[o],r[o]);return r}addPublicKey(e,r){if(!(0,Fp.isSameAddress)(e,r.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,qp.normalizeSuiAddress)(e),r)}async _getPublicKey(e){let r=await this.getPublicKeyFromBackend(e);if(r)return r;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return Gu(this.globals.suiClient,e)}};var vs=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Wp=require("@mysten/sui.js/client");var Ui=require("@msafe/sui3-utils"),Li=de(require("axios"),1);var Ts=class t{constructor(e){this.apiURL=e}_token;async authSign(e){let r=await this.post("/auth/login",e);return this._token=r.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let r={userAddressList:e};return(await this.get("/user/public-keys",{params:r,headers:this.headers()})).data?.map(i=>i?Ui.PublicKeySerde.de(i):void 0)}async getMSafeAccountInfo(e){let r={msafeAddress:e},n=await this.get("/msafe",{params:r,headers:this.headers()});return t.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let r={status:e.status??Ui.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:r,headers:this.headers()});return{data:n.data.data.map(t.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let r=e;await this.post("/msafe/status",r,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(r=>({address:r.address,weight:r.weight,publicKey:Ui.PublicKeySerde.de({publicKeyEncoded:r.publicKeyEncoded,schema:r.schema})}))}}async get(e,r){let n=this.getFullUrl(e);try{return await Li.default.get(n,r)}catch(i){throw Ss.fromError(i)??i}}async post(e,r,n){let i=this.getFullUrl(e);try{return await Li.default.post(i,r,{...n,transformRequest:this.getTransformRequest()})}catch(o){throw Ss.fromError(o)??o}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Uu(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:r}=Li.default.defaults;return r?r instanceof Array?e=r:e=[r]:e=[],[n=>JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?`${o.toString()}n`:o)),...e]}},Ss=class t extends Error{constructor(r){super();this.e=r;Error.captureStackTrace(this,this.constructor)}name;static fromError(r){if(Li.default.isAxiosError(r)&&r?.response?.data&&"message"in r.response.data)return new t(r)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Lp=(o=>(o.local="local",o.unit="unit",o.dev="dev",o.prev="prev",o.prod="prod",o))(Lp||{}),xs="https://fullnode.testnet.sui.io",Zu="https://fullnode.mainnet.sui.io",Ku="http://127.0.0.1:3000",Ju="http://127.0.0.1:3001",Up="https://sui-dev.m-safe.link",$p="http://13.56.226.148:81",Gp="https://sui-preview.m-safe.link",Vp="https://sui.m-safe.link",zp=new Map([["unit",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["local",{suiClient:{url:xs},backend:{url:Ku},syncingURL:Ju,network:"sui:testnet"}],["dev",{suiClient:{url:xs},backend:{url:Up},syncingURL:$p,network:"sui:testnet"}],["prev",{suiClient:{url:Zu},backend:{url:Gp},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Zu},backend:{url:Vp},syncingURL:"",network:"sui:mainnet"}]]);function Xu(t,e){let r=zp.get(t);if(!r)throw new Error("Unknown environment");return e?.suiClient?.url&&(r.suiClient.url=e.suiClient.url),e?.backend?.url&&(r.backend.url=e.backend.url),r}var $i=class t{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,r){let n=Xu(e,r),i=new Wp.SuiClient(n.suiClient),o=new Ts(n.backend.url);return new t({backend:o,suiClient:i,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var ks=class t{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,r){let n=await $i.New(e,r);return new t(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let r=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(r),r}async authSign(e){let r=As.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:r});return this.backend.authSign({address:await e.address(),message:r,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:As.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new sn(this.globals,e)}async getMSafeAccountFromAddress(e){let r=await this.backend.getMSafeAccountInfo(e);return new sn(this.globals,r)}get creationHelper(){return this._creationHelper||(this._creationHelper=new un(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new _s(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new cn(this.globals)}get Invitation(){return new zi(this.globals)}get Report(){return new vs(this.globals)}async walletAddress(){return this.wallet.address()}};
|
|
2060
2054
|
/*! Bundled license information:
|
|
2061
2055
|
|
|
2062
2056
|
@syntsugar/cc-graph/dist/index.umd.js:
|
|
@@ -2075,15 +2069,6 @@ zoo`.split(`
|
|
|
2075
2069
|
and limitations under the License.
|
|
2076
2070
|
***************************************************************************** *)
|
|
2077
2071
|
|
|
2078
|
-
decimal.js/decimal.js:
|
|
2079
|
-
(*!
|
|
2080
|
-
* decimal.js v10.4.3
|
|
2081
|
-
* An arbitrary-precision Decimal type for JavaScript.
|
|
2082
|
-
* https://github.com/MikeMcl/decimal.js
|
|
2083
|
-
* Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>
|
|
2084
|
-
* MIT Licence
|
|
2085
|
-
*)
|
|
2086
|
-
|
|
2087
2072
|
decimal.js/decimal.mjs:
|
|
2088
2073
|
(*!
|
|
2089
2074
|
* decimal.js v10.4.3
|