haedal-vault-sdk 2.2.1 → 2.4.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 +1 -0
- package/dist/index.d.ts +7 -8
- package/dist/index.js +1 -16
- package/package.json +43 -36
- package/tsup.config.js +1 -0
- package/version.js +1 -1
- package/vitest.config.ts +15 -0
- package/dist/index.mjs +0 -16
- package/jest.config.js +0 -17
package/dist/index.js
CHANGED
|
@@ -1,16 +1 @@
|
|
|
1
|
-
"use strict";var Ao=Object.create;var Ye=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var Vo=Object.getOwnPropertyNames;var Do=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty;var Bo=(i,e)=>{for(var t in e)Ye(i,t,{get:e[t],enumerable:!0})},Ln=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vo(e))!xo.call(i,o)&&o!==t&&Ye(i,o,{get:()=>e[o],enumerable:!(n=Oo(e,o))||n.enumerable});return i};var ie=(i,e,t)=>(t=i!=null?Ao(Do(i)):{},Ln(e||!i||!i.__esModule?Ye(t,"default",{value:i,enumerable:!0}):t,i)),To=i=>Ln(Ye({},"__esModule",{value:!0}),i);var vs={};Bo(vs,{PythPriceModule:()=>De,SdkEnv:()=>po,VaultsModule:()=>Ge,VaultsModuleV2:()=>Qe,VestModule:()=>He,VolatileVaultsSDK:()=>he,buildCLMMMarketId:()=>ln,buildCLMMMarketPosition:()=>sn,buildDLMMMarketId:()=>cn,buildDLMMMarketPosition:()=>rn,buildDLMMPositionId:()=>hs,buildPoolData:()=>Se,buildPoolV2Data:()=>pi,buildVaultMarket:()=>on,buildVaultsBalance:()=>Ji,buildVaultsBalanceV2:()=>hi,calcExactSwapAmount:()=>je,calcSingleSideSwap:()=>un,calculateAum:()=>Qi,calculateAumV2:()=>an,calculateDepositRatioFixTokenA:()=>mo,calculateTotalAumBasedOnQuote:()=>Ce,checkIsMinOrMaxIndex:()=>mi,convertU64BytesToDecimal:()=>us,default:()=>ys,defaultProvider:()=>gn,dlmm_split_rate:()=>ws,estCoinAmountsFromTotalAmount:()=>Hi,feed_map_mainnet:()=>mn,feed_map_testnet:()=>pn,getAmountBalanceByLpAmount:()=>Xe,getCoinAmountsFromRatio:()=>_e,getPositionPriceRange:()=>_s,getPriceWithFormattedDecimals:()=>Yi,getPrimitivePricesFromBaseQuote:()=>_o,getQuotePerBaseAndBasePerQuote:()=>Ke,getShareBufferAssets:()=>Oe,getUpdatePriceType:()=>Ee,getVaultValidBalances:()=>Ze,get_lp_amount_by_liquidity:()=>ms,get_lp_amount_by_tvl:()=>We,get_share_liquidity_by_amount:()=>Ae,initMainnetSDK:()=>_n,initTestnetSDK:()=>hn,initVaultSDK:()=>gs,oraclePriceMultiplierDecimal:()=>ke,parseVaultVestNFT:()=>en,parseVaultsVestInfo:()=>fi,printTransaction:()=>ds,toSuiObjectId:()=>tn,vaults_mainnet:()=>dn,vaults_testnet:()=>fn});module.exports=To(vs);var ko=require("@mysten/sui/client"),bi=require("@mysten/sui/utils"),Je=require("@cetusprotocol/aggregator-sdk");var Uo=require("@mysten/sui/utils"),Wo=require("@mysten/sui/client"),Zo=require("@mysten/sui/utils"),zo=require("@mysten/sui/keypairs/ed25519"),Xo=require("@mysten/sui/keypairs/secp256k1"),Pe=require("@mysten/sui/utils"),qi=require("@mysten/sui/transactions"),Kr=require("@mysten/sui/bcs"),Wr=require("@mysten/sui/utils"),Zr=require("@mysten/sui/graphql/schemas/latest"),zr=require("@mysten/sui/graphql"),Wi=require("@mysten/sui/client"),Eo=Object.create,zn=Object.defineProperty,Fo=Object.getOwnPropertyDescriptor,jo=Object.getOwnPropertyNames,Io=Object.getPrototypeOf,Lo=Object.prototype.hasOwnProperty,qo=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),Ro=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),No=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jo(e))!Lo.call(i,o)&&o!==t&&zn(i,o,{get:()=>e[o],enumerable:!(n=Fo(e,o))||n.enumerable});return i},Ne=(i,e,t)=>(t=i!=null?Eo(Io(i)):{},No(e||!i||!i.__esModule?zn(t,"default",{value:i,enumerable:!0}):t,i)),Ue=Ro((i,e)=>{"use strict";(function(t,n){"use strict";function o(a,u){if(!a)throw new Error(u||"Assertion failed")}function s(a,u){a.super_=u;var _=function(){};_.prototype=u.prototype,a.prototype=new _,a.prototype.constructor=a}function r(a,u,_){if(r.isBN(a))return a;this.negative=0,this.words=null,this.length=0,this.red=null,a!==null&&((u==="le"||u==="be")&&(_=u,u=10),this._init(a||0,u||10,_||"be"))}typeof t=="object"?t.exports=r:n.BN=r,r.BN=r,r.wordSize=26;var c;try{typeof window<"u"&&typeof window.Buffer<"u"?c=window.Buffer:c=qo("buffer").Buffer}catch{}r.isBN=function(a){return a instanceof r?!0:a!==null&&typeof a=="object"&&a.constructor.wordSize===r.wordSize&&Array.isArray(a.words)},r.max=function(a,u){return a.cmp(u)>0?a:u},r.min=function(a,u){return a.cmp(u)<0?a:u},r.prototype._init=function(a,u,_){if(typeof a=="number")return this._initNumber(a,u,_);if(typeof a=="object")return this._initArray(a,u,_);u==="hex"&&(u=16),o(u===(u|0)&&u>=2&&u<=36),a=a.toString().replace(/\s+/g,"");var g=0;a[0]==="-"&&(g++,this.negative=1),g<a.length&&(u===16?this._parseHex(a,g,_):(this._parseBase(a,u,g),_==="le"&&this._initArray(this.toArray(),u,_)))},r.prototype._initNumber=function(a,u,_){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):(o(a<9007199254740992),this.words=[a&67108863,a/67108864&67108863,1],this.length=3),_==="le"&&this._initArray(this.toArray(),u,_)},r.prototype._initArray=function(a,u,_){if(o(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 g=0;g<this.length;g++)this.words[g]=0;var b,P,k=0;if(_==="be")for(g=a.length-1,b=0;g>=0;g-=3)P=a[g]|a[g-1]<<8|a[g-2]<<16,this.words[b]|=P<<k&67108863,this.words[b+1]=P>>>26-k&67108863,k+=24,k>=26&&(k-=26,b++);else if(_==="le")for(g=0,b=0;g<a.length;g+=3)P=a[g]|a[g+1]<<8|a[g+2]<<16,this.words[b]|=P<<k&67108863,this.words[b+1]=P>>>26-k&67108863,k+=24,k>=26&&(k-=26,b++);return this._strip()};function d(a,u){var _=a.charCodeAt(u);if(_>=48&&_<=57)return _-48;if(_>=65&&_<=70)return _-55;if(_>=97&&_<=102)return _-87;o(!1,"Invalid character in "+a)}function m(a,u,_){var g=d(a,_);return _-1>=u&&(g|=d(a,_-1)<<4),g}r.prototype._parseHex=function(a,u,_){this.length=Math.ceil((a.length-u)/6),this.words=new Array(this.length);for(var g=0;g<this.length;g++)this.words[g]=0;var b=0,P=0,k;if(_==="be")for(g=a.length-1;g>=u;g-=2)k=m(a,u,g)<<b,this.words[P]|=k&67108863,b>=18?(b-=18,P+=1,this.words[P]|=k>>>26):b+=8;else{var w=a.length-u;for(g=w%2===0?u+1:u;g<a.length;g+=2)k=m(a,u,g)<<b,this.words[P]|=k&67108863,b>=18?(b-=18,P+=1,this.words[P]|=k>>>26):b+=8}this._strip()};function f(a,u,_,g){for(var b=0,P=0,k=Math.min(a.length,_),w=u;w<k;w++){var l=a.charCodeAt(w)-48;b*=g,l>=49?P=l-49+10:l>=17?P=l-17+10:P=l,o(l>=0&&P<g,"Invalid character"),b+=P}return b}r.prototype._parseBase=function(a,u,_){this.words=[0],this.length=1;for(var g=0,b=1;b<=67108863;b*=u)g++;g--,b=b/u|0;for(var P=a.length-_,k=P%g,w=Math.min(P,P-k)+_,l=0,y=_;y<w;y+=g)l=f(a,y,y+g,u),this.imuln(b),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(k!==0){var q=1;for(l=f(a,y,a.length,u),y=0;y<k;y++)q*=u;this.imuln(q),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},r.prototype.copy=function(a){a.words=new Array(this.length);for(var u=0;u<this.length;u++)a.words[u]=this.words[u];a.length=this.length,a.negative=this.negative,a.red=this.red};function p(a,u){a.words=u.words,a.length=u.length,a.negative=u.negative,a.red=u.red}if(r.prototype._move=function(a){p(a,this)},r.prototype.clone=function(){var a=new r(null);return this.copy(a),a},r.prototype._expand=function(a){for(;this.length<a;)this.words[this.length++]=0;return this},r.prototype._strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},r.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{r.prototype[Symbol.for("nodejs.util.inspect.custom")]=h}catch{r.prototype.inspect=h}else r.prototype.inspect=h;function h(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var v=["","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"],M=[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(a,u){a=a||10,u=u|0||1;var _;if(a===16||a==="hex"){_="";for(var g=0,b=0,P=0;P<this.length;P++){var k=this.words[P],w=((k<<g|b)&16777215).toString(16);b=k>>>24-g&16777215,g+=2,g>=26&&(g-=26,P--),b!==0||P!==this.length-1?_=v[6-w.length]+w+_:_=w+_}for(b!==0&&(_=b.toString(16)+_);_.length%u!==0;)_="0"+_;return this.negative!==0&&(_="-"+_),_}if(a===(a|0)&&a>=2&&a<=36){var l=M[a],y=C[a];_="";var q=this.clone();for(q.negative=0;!q.isZero();){var R=q.modrn(y).toString(a);q=q.idivn(y),q.isZero()?_=R+_:_=v[l-R.length]+R+_}for(this.isZero()&&(_="0"+_);_.length%u!==0;)_="0"+_;return this.negative!==0&&(_="-"+_),_}o(!1,"Base should be between 2 and 36")},r.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&&o(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-a:a},r.prototype.toJSON=function(){return this.toString(16,2)},c&&(r.prototype.toBuffer=function(a,u){return this.toArrayLike(c,a,u)}),r.prototype.toArray=function(a,u){return this.toArrayLike(Array,a,u)};var A=function(a,u){return a.allocUnsafe?a.allocUnsafe(u):new a(u)};r.prototype.toArrayLike=function(a,u,_){this._strip();var g=this.byteLength(),b=_||Math.max(1,g);o(g<=b,"byte array longer than desired length"),o(b>0,"Requested array length <= 0");var P=A(a,b),k=u==="le"?"LE":"BE";return this["_toArrayLike"+k](P,g),P},r.prototype._toArrayLikeLE=function(a,u){for(var _=0,g=0,b=0,P=0;b<this.length;b++){var k=this.words[b]<<P|g;a[_++]=k&255,_<a.length&&(a[_++]=k>>8&255),_<a.length&&(a[_++]=k>>16&255),P===6?(_<a.length&&(a[_++]=k>>24&255),g=0,P=0):(g=k>>>24,P+=2)}if(_<a.length)for(a[_++]=g;_<a.length;)a[_++]=0},r.prototype._toArrayLikeBE=function(a,u){for(var _=a.length-1,g=0,b=0,P=0;b<this.length;b++){var k=this.words[b]<<P|g;a[_--]=k&255,_>=0&&(a[_--]=k>>8&255),_>=0&&(a[_--]=k>>16&255),P===6?(_>=0&&(a[_--]=k>>24&255),g=0,P=0):(g=k>>>24,P+=2)}if(_>=0)for(a[_--]=g;_>=0;)a[_--]=0},Math.clz32?r.prototype._countBits=function(a){return 32-Math.clz32(a)}:r.prototype._countBits=function(a){var u=a,_=0;return u>=4096&&(_+=13,u>>>=13),u>=64&&(_+=7,u>>>=7),u>=8&&(_+=4,u>>>=4),u>=2&&(_+=2,u>>>=2),_+u},r.prototype._zeroBits=function(a){if(a===0)return 26;var u=a,_=0;return!(u&8191)&&(_+=13,u>>>=13),!(u&127)&&(_+=7,u>>>=7),!(u&15)&&(_+=4,u>>>=4),!(u&3)&&(_+=2,u>>>=2),!(u&1)&&_++,_},r.prototype.bitLength=function(){var a=this.words[this.length-1],u=this._countBits(a);return(this.length-1)*26+u};function D(a){for(var u=new Array(a.bitLength()),_=0;_<u.length;_++){var g=_/26|0,b=_%26;u[_]=a.words[g]>>>b&1}return u}r.prototype.zeroBits=function(){if(this.isZero())return 0;for(var a=0,u=0;u<this.length;u++){var _=this._zeroBits(this.words[u]);if(a+=_,_!==26)break}return a},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(a){return this.negative!==0?this.abs().inotn(a).iaddn(1):this.clone()},r.prototype.fromTwos=function(a){return this.testn(a-1)?this.notn(a).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(a){for(;this.length<a.length;)this.words[this.length++]=0;for(var u=0;u<a.length;u++)this.words[u]=this.words[u]|a.words[u];return this._strip()},r.prototype.ior=function(a){return o((this.negative|a.negative)===0),this.iuor(a)},r.prototype.or=function(a){return this.length>a.length?this.clone().ior(a):a.clone().ior(this)},r.prototype.uor=function(a){return this.length>a.length?this.clone().iuor(a):a.clone().iuor(this)},r.prototype.iuand=function(a){var u;this.length>a.length?u=a:u=this;for(var _=0;_<u.length;_++)this.words[_]=this.words[_]&a.words[_];return this.length=u.length,this._strip()},r.prototype.iand=function(a){return o((this.negative|a.negative)===0),this.iuand(a)},r.prototype.and=function(a){return this.length>a.length?this.clone().iand(a):a.clone().iand(this)},r.prototype.uand=function(a){return this.length>a.length?this.clone().iuand(a):a.clone().iuand(this)},r.prototype.iuxor=function(a){var u,_;this.length>a.length?(u=this,_=a):(u=a,_=this);for(var g=0;g<_.length;g++)this.words[g]=u.words[g]^_.words[g];if(this!==u)for(;g<u.length;g++)this.words[g]=u.words[g];return this.length=u.length,this._strip()},r.prototype.ixor=function(a){return o((this.negative|a.negative)===0),this.iuxor(a)},r.prototype.xor=function(a){return this.length>a.length?this.clone().ixor(a):a.clone().ixor(this)},r.prototype.uxor=function(a){return this.length>a.length?this.clone().iuxor(a):a.clone().iuxor(this)},r.prototype.inotn=function(a){o(typeof a=="number"&&a>=0);var u=Math.ceil(a/26)|0,_=a%26;this._expand(u),_>0&&u--;for(var g=0;g<u;g++)this.words[g]=~this.words[g]&67108863;return _>0&&(this.words[g]=~this.words[g]&67108863>>26-_),this._strip()},r.prototype.notn=function(a){return this.clone().inotn(a)},r.prototype.setn=function(a,u){o(typeof a=="number"&&a>=0);var _=a/26|0,g=a%26;return this._expand(_+1),u?this.words[_]=this.words[_]|1<<g:this.words[_]=this.words[_]&~(1<<g),this._strip()},r.prototype.iadd=function(a){var u;if(this.negative!==0&&a.negative===0)return this.negative=0,u=this.isub(a),this.negative^=1,this._normSign();if(this.negative===0&&a.negative!==0)return a.negative=0,u=this.isub(a),a.negative=1,u._normSign();var _,g;this.length>a.length?(_=this,g=a):(_=a,g=this);for(var b=0,P=0;P<g.length;P++)u=(_.words[P]|0)+(g.words[P]|0)+b,this.words[P]=u&67108863,b=u>>>26;for(;b!==0&&P<_.length;P++)u=(_.words[P]|0)+b,this.words[P]=u&67108863,b=u>>>26;if(this.length=_.length,b!==0)this.words[this.length]=b,this.length++;else if(_!==this)for(;P<_.length;P++)this.words[P]=_.words[P];return this},r.prototype.add=function(a){var u;return a.negative!==0&&this.negative===0?(a.negative=0,u=this.sub(a),a.negative^=1,u):a.negative===0&&this.negative!==0?(this.negative=0,u=a.sub(this),this.negative=1,u):this.length>a.length?this.clone().iadd(a):a.clone().iadd(this)},r.prototype.isub=function(a){if(a.negative!==0){a.negative=0;var u=this.iadd(a);return a.negative=1,u._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(a),this.negative=1,this._normSign();var _=this.cmp(a);if(_===0)return this.negative=0,this.length=1,this.words[0]=0,this;var g,b;_>0?(g=this,b=a):(g=a,b=this);for(var P=0,k=0;k<b.length;k++)u=(g.words[k]|0)-(b.words[k]|0)+P,P=u>>26,this.words[k]=u&67108863;for(;P!==0&&k<g.length;k++)u=(g.words[k]|0)+P,P=u>>26,this.words[k]=u&67108863;if(P===0&&k<g.length&&g!==this)for(;k<g.length;k++)this.words[k]=g.words[k];return this.length=Math.max(this.length,k),g!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(a){return this.clone().isub(a)};function V(a,u,_){_.negative=u.negative^a.negative;var g=a.length+u.length|0;_.length=g,g=g-1|0;var b=a.words[0]|0,P=u.words[0]|0,k=b*P,w=k&67108863,l=k/67108864|0;_.words[0]=w;for(var y=1;y<g;y++){for(var q=l>>>26,R=l&67108863,Z=Math.min(y,u.length-1),H=Math.max(0,y-a.length+1);H<=Z;H++){var Y=y-H|0;b=a.words[Y]|0,P=u.words[H]|0,k=b*P+R,q+=k/67108864|0,R=k&67108863}_.words[y]=R|0,l=q|0}return l!==0?_.words[y]=l|0:_.length--,_._strip()}var O=function(a,u,_){var g=a.words,b=u.words,P=_.words,k=0,w,l,y,q=g[0]|0,R=q&8191,Z=q>>>13,H=g[1]|0,Y=H&8191,it=H>>>13,be=g[2]|0,nt=be&8191,ot=be>>>13,vn=g[3]|0,st=vn&8191,at=vn>>>13,Mn=g[4]|0,ct=Mn&8191,lt=Mn>>>13,Cn=g[5]|0,ut=Cn&8191,dt=Cn>>>13,Pn=g[6]|0,mt=Pn&8191,_t=Pn>>>13,kn=g[7]|0,ft=kn&8191,pt=kn>>>13,Sn=g[8]|0,ht=Sn&8191,gt=Sn>>>13,An=g[9]|0,bt=An&8191,wt=An>>>13,On=b[0]|0,yt=On&8191,vt=On>>>13,Vn=b[1]|0,Mt=Vn&8191,Ct=Vn>>>13,Dn=b[2]|0,Pt=Dn&8191,kt=Dn>>>13,xn=b[3]|0,St=xn&8191,At=xn>>>13,Bn=b[4]|0,Ot=Bn&8191,Vt=Bn>>>13,Tn=b[5]|0,Dt=Tn&8191,xt=Tn>>>13,En=b[6]|0,Bt=En&8191,Tt=En>>>13,Fn=b[7]|0,Et=Fn&8191,Ft=Fn>>>13,jn=b[8]|0,jt=jn&8191,It=jn>>>13,In=b[9]|0,Lt=In&8191,qt=In>>>13;_.negative=a.negative^u.negative,_.length=19,w=Math.imul(R,yt),l=Math.imul(R,vt),l=l+Math.imul(Z,yt)|0,y=Math.imul(Z,vt);var wi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(wi>>>26)|0,wi&=67108863,w=Math.imul(Y,yt),l=Math.imul(Y,vt),l=l+Math.imul(it,yt)|0,y=Math.imul(it,vt),w=w+Math.imul(R,Mt)|0,l=l+Math.imul(R,Ct)|0,l=l+Math.imul(Z,Mt)|0,y=y+Math.imul(Z,Ct)|0;var yi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(yi>>>26)|0,yi&=67108863,w=Math.imul(nt,yt),l=Math.imul(nt,vt),l=l+Math.imul(ot,yt)|0,y=Math.imul(ot,vt),w=w+Math.imul(Y,Mt)|0,l=l+Math.imul(Y,Ct)|0,l=l+Math.imul(it,Mt)|0,y=y+Math.imul(it,Ct)|0,w=w+Math.imul(R,Pt)|0,l=l+Math.imul(R,kt)|0,l=l+Math.imul(Z,Pt)|0,y=y+Math.imul(Z,kt)|0;var vi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(vi>>>26)|0,vi&=67108863,w=Math.imul(st,yt),l=Math.imul(st,vt),l=l+Math.imul(at,yt)|0,y=Math.imul(at,vt),w=w+Math.imul(nt,Mt)|0,l=l+Math.imul(nt,Ct)|0,l=l+Math.imul(ot,Mt)|0,y=y+Math.imul(ot,Ct)|0,w=w+Math.imul(Y,Pt)|0,l=l+Math.imul(Y,kt)|0,l=l+Math.imul(it,Pt)|0,y=y+Math.imul(it,kt)|0,w=w+Math.imul(R,St)|0,l=l+Math.imul(R,At)|0,l=l+Math.imul(Z,St)|0,y=y+Math.imul(Z,At)|0;var Mi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Mi>>>26)|0,Mi&=67108863,w=Math.imul(ct,yt),l=Math.imul(ct,vt),l=l+Math.imul(lt,yt)|0,y=Math.imul(lt,vt),w=w+Math.imul(st,Mt)|0,l=l+Math.imul(st,Ct)|0,l=l+Math.imul(at,Mt)|0,y=y+Math.imul(at,Ct)|0,w=w+Math.imul(nt,Pt)|0,l=l+Math.imul(nt,kt)|0,l=l+Math.imul(ot,Pt)|0,y=y+Math.imul(ot,kt)|0,w=w+Math.imul(Y,St)|0,l=l+Math.imul(Y,At)|0,l=l+Math.imul(it,St)|0,y=y+Math.imul(it,At)|0,w=w+Math.imul(R,Ot)|0,l=l+Math.imul(R,Vt)|0,l=l+Math.imul(Z,Ot)|0,y=y+Math.imul(Z,Vt)|0;var Ci=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Ci>>>26)|0,Ci&=67108863,w=Math.imul(ut,yt),l=Math.imul(ut,vt),l=l+Math.imul(dt,yt)|0,y=Math.imul(dt,vt),w=w+Math.imul(ct,Mt)|0,l=l+Math.imul(ct,Ct)|0,l=l+Math.imul(lt,Mt)|0,y=y+Math.imul(lt,Ct)|0,w=w+Math.imul(st,Pt)|0,l=l+Math.imul(st,kt)|0,l=l+Math.imul(at,Pt)|0,y=y+Math.imul(at,kt)|0,w=w+Math.imul(nt,St)|0,l=l+Math.imul(nt,At)|0,l=l+Math.imul(ot,St)|0,y=y+Math.imul(ot,At)|0,w=w+Math.imul(Y,Ot)|0,l=l+Math.imul(Y,Vt)|0,l=l+Math.imul(it,Ot)|0,y=y+Math.imul(it,Vt)|0,w=w+Math.imul(R,Dt)|0,l=l+Math.imul(R,xt)|0,l=l+Math.imul(Z,Dt)|0,y=y+Math.imul(Z,xt)|0;var Pi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Pi>>>26)|0,Pi&=67108863,w=Math.imul(mt,yt),l=Math.imul(mt,vt),l=l+Math.imul(_t,yt)|0,y=Math.imul(_t,vt),w=w+Math.imul(ut,Mt)|0,l=l+Math.imul(ut,Ct)|0,l=l+Math.imul(dt,Mt)|0,y=y+Math.imul(dt,Ct)|0,w=w+Math.imul(ct,Pt)|0,l=l+Math.imul(ct,kt)|0,l=l+Math.imul(lt,Pt)|0,y=y+Math.imul(lt,kt)|0,w=w+Math.imul(st,St)|0,l=l+Math.imul(st,At)|0,l=l+Math.imul(at,St)|0,y=y+Math.imul(at,At)|0,w=w+Math.imul(nt,Ot)|0,l=l+Math.imul(nt,Vt)|0,l=l+Math.imul(ot,Ot)|0,y=y+Math.imul(ot,Vt)|0,w=w+Math.imul(Y,Dt)|0,l=l+Math.imul(Y,xt)|0,l=l+Math.imul(it,Dt)|0,y=y+Math.imul(it,xt)|0,w=w+Math.imul(R,Bt)|0,l=l+Math.imul(R,Tt)|0,l=l+Math.imul(Z,Bt)|0,y=y+Math.imul(Z,Tt)|0;var ki=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(ki>>>26)|0,ki&=67108863,w=Math.imul(ft,yt),l=Math.imul(ft,vt),l=l+Math.imul(pt,yt)|0,y=Math.imul(pt,vt),w=w+Math.imul(mt,Mt)|0,l=l+Math.imul(mt,Ct)|0,l=l+Math.imul(_t,Mt)|0,y=y+Math.imul(_t,Ct)|0,w=w+Math.imul(ut,Pt)|0,l=l+Math.imul(ut,kt)|0,l=l+Math.imul(dt,Pt)|0,y=y+Math.imul(dt,kt)|0,w=w+Math.imul(ct,St)|0,l=l+Math.imul(ct,At)|0,l=l+Math.imul(lt,St)|0,y=y+Math.imul(lt,At)|0,w=w+Math.imul(st,Ot)|0,l=l+Math.imul(st,Vt)|0,l=l+Math.imul(at,Ot)|0,y=y+Math.imul(at,Vt)|0,w=w+Math.imul(nt,Dt)|0,l=l+Math.imul(nt,xt)|0,l=l+Math.imul(ot,Dt)|0,y=y+Math.imul(ot,xt)|0,w=w+Math.imul(Y,Bt)|0,l=l+Math.imul(Y,Tt)|0,l=l+Math.imul(it,Bt)|0,y=y+Math.imul(it,Tt)|0,w=w+Math.imul(R,Et)|0,l=l+Math.imul(R,Ft)|0,l=l+Math.imul(Z,Et)|0,y=y+Math.imul(Z,Ft)|0;var Si=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Si>>>26)|0,Si&=67108863,w=Math.imul(ht,yt),l=Math.imul(ht,vt),l=l+Math.imul(gt,yt)|0,y=Math.imul(gt,vt),w=w+Math.imul(ft,Mt)|0,l=l+Math.imul(ft,Ct)|0,l=l+Math.imul(pt,Mt)|0,y=y+Math.imul(pt,Ct)|0,w=w+Math.imul(mt,Pt)|0,l=l+Math.imul(mt,kt)|0,l=l+Math.imul(_t,Pt)|0,y=y+Math.imul(_t,kt)|0,w=w+Math.imul(ut,St)|0,l=l+Math.imul(ut,At)|0,l=l+Math.imul(dt,St)|0,y=y+Math.imul(dt,At)|0,w=w+Math.imul(ct,Ot)|0,l=l+Math.imul(ct,Vt)|0,l=l+Math.imul(lt,Ot)|0,y=y+Math.imul(lt,Vt)|0,w=w+Math.imul(st,Dt)|0,l=l+Math.imul(st,xt)|0,l=l+Math.imul(at,Dt)|0,y=y+Math.imul(at,xt)|0,w=w+Math.imul(nt,Bt)|0,l=l+Math.imul(nt,Tt)|0,l=l+Math.imul(ot,Bt)|0,y=y+Math.imul(ot,Tt)|0,w=w+Math.imul(Y,Et)|0,l=l+Math.imul(Y,Ft)|0,l=l+Math.imul(it,Et)|0,y=y+Math.imul(it,Ft)|0,w=w+Math.imul(R,jt)|0,l=l+Math.imul(R,It)|0,l=l+Math.imul(Z,jt)|0,y=y+Math.imul(Z,It)|0;var Ai=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Ai>>>26)|0,Ai&=67108863,w=Math.imul(bt,yt),l=Math.imul(bt,vt),l=l+Math.imul(wt,yt)|0,y=Math.imul(wt,vt),w=w+Math.imul(ht,Mt)|0,l=l+Math.imul(ht,Ct)|0,l=l+Math.imul(gt,Mt)|0,y=y+Math.imul(gt,Ct)|0,w=w+Math.imul(ft,Pt)|0,l=l+Math.imul(ft,kt)|0,l=l+Math.imul(pt,Pt)|0,y=y+Math.imul(pt,kt)|0,w=w+Math.imul(mt,St)|0,l=l+Math.imul(mt,At)|0,l=l+Math.imul(_t,St)|0,y=y+Math.imul(_t,At)|0,w=w+Math.imul(ut,Ot)|0,l=l+Math.imul(ut,Vt)|0,l=l+Math.imul(dt,Ot)|0,y=y+Math.imul(dt,Vt)|0,w=w+Math.imul(ct,Dt)|0,l=l+Math.imul(ct,xt)|0,l=l+Math.imul(lt,Dt)|0,y=y+Math.imul(lt,xt)|0,w=w+Math.imul(st,Bt)|0,l=l+Math.imul(st,Tt)|0,l=l+Math.imul(at,Bt)|0,y=y+Math.imul(at,Tt)|0,w=w+Math.imul(nt,Et)|0,l=l+Math.imul(nt,Ft)|0,l=l+Math.imul(ot,Et)|0,y=y+Math.imul(ot,Ft)|0,w=w+Math.imul(Y,jt)|0,l=l+Math.imul(Y,It)|0,l=l+Math.imul(it,jt)|0,y=y+Math.imul(it,It)|0,w=w+Math.imul(R,Lt)|0,l=l+Math.imul(R,qt)|0,l=l+Math.imul(Z,Lt)|0,y=y+Math.imul(Z,qt)|0;var Oi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Oi>>>26)|0,Oi&=67108863,w=Math.imul(bt,Mt),l=Math.imul(bt,Ct),l=l+Math.imul(wt,Mt)|0,y=Math.imul(wt,Ct),w=w+Math.imul(ht,Pt)|0,l=l+Math.imul(ht,kt)|0,l=l+Math.imul(gt,Pt)|0,y=y+Math.imul(gt,kt)|0,w=w+Math.imul(ft,St)|0,l=l+Math.imul(ft,At)|0,l=l+Math.imul(pt,St)|0,y=y+Math.imul(pt,At)|0,w=w+Math.imul(mt,Ot)|0,l=l+Math.imul(mt,Vt)|0,l=l+Math.imul(_t,Ot)|0,y=y+Math.imul(_t,Vt)|0,w=w+Math.imul(ut,Dt)|0,l=l+Math.imul(ut,xt)|0,l=l+Math.imul(dt,Dt)|0,y=y+Math.imul(dt,xt)|0,w=w+Math.imul(ct,Bt)|0,l=l+Math.imul(ct,Tt)|0,l=l+Math.imul(lt,Bt)|0,y=y+Math.imul(lt,Tt)|0,w=w+Math.imul(st,Et)|0,l=l+Math.imul(st,Ft)|0,l=l+Math.imul(at,Et)|0,y=y+Math.imul(at,Ft)|0,w=w+Math.imul(nt,jt)|0,l=l+Math.imul(nt,It)|0,l=l+Math.imul(ot,jt)|0,y=y+Math.imul(ot,It)|0,w=w+Math.imul(Y,Lt)|0,l=l+Math.imul(Y,qt)|0,l=l+Math.imul(it,Lt)|0,y=y+Math.imul(it,qt)|0;var Vi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Vi>>>26)|0,Vi&=67108863,w=Math.imul(bt,Pt),l=Math.imul(bt,kt),l=l+Math.imul(wt,Pt)|0,y=Math.imul(wt,kt),w=w+Math.imul(ht,St)|0,l=l+Math.imul(ht,At)|0,l=l+Math.imul(gt,St)|0,y=y+Math.imul(gt,At)|0,w=w+Math.imul(ft,Ot)|0,l=l+Math.imul(ft,Vt)|0,l=l+Math.imul(pt,Ot)|0,y=y+Math.imul(pt,Vt)|0,w=w+Math.imul(mt,Dt)|0,l=l+Math.imul(mt,xt)|0,l=l+Math.imul(_t,Dt)|0,y=y+Math.imul(_t,xt)|0,w=w+Math.imul(ut,Bt)|0,l=l+Math.imul(ut,Tt)|0,l=l+Math.imul(dt,Bt)|0,y=y+Math.imul(dt,Tt)|0,w=w+Math.imul(ct,Et)|0,l=l+Math.imul(ct,Ft)|0,l=l+Math.imul(lt,Et)|0,y=y+Math.imul(lt,Ft)|0,w=w+Math.imul(st,jt)|0,l=l+Math.imul(st,It)|0,l=l+Math.imul(at,jt)|0,y=y+Math.imul(at,It)|0,w=w+Math.imul(nt,Lt)|0,l=l+Math.imul(nt,qt)|0,l=l+Math.imul(ot,Lt)|0,y=y+Math.imul(ot,qt)|0;var Di=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Di>>>26)|0,Di&=67108863,w=Math.imul(bt,St),l=Math.imul(bt,At),l=l+Math.imul(wt,St)|0,y=Math.imul(wt,At),w=w+Math.imul(ht,Ot)|0,l=l+Math.imul(ht,Vt)|0,l=l+Math.imul(gt,Ot)|0,y=y+Math.imul(gt,Vt)|0,w=w+Math.imul(ft,Dt)|0,l=l+Math.imul(ft,xt)|0,l=l+Math.imul(pt,Dt)|0,y=y+Math.imul(pt,xt)|0,w=w+Math.imul(mt,Bt)|0,l=l+Math.imul(mt,Tt)|0,l=l+Math.imul(_t,Bt)|0,y=y+Math.imul(_t,Tt)|0,w=w+Math.imul(ut,Et)|0,l=l+Math.imul(ut,Ft)|0,l=l+Math.imul(dt,Et)|0,y=y+Math.imul(dt,Ft)|0,w=w+Math.imul(ct,jt)|0,l=l+Math.imul(ct,It)|0,l=l+Math.imul(lt,jt)|0,y=y+Math.imul(lt,It)|0,w=w+Math.imul(st,Lt)|0,l=l+Math.imul(st,qt)|0,l=l+Math.imul(at,Lt)|0,y=y+Math.imul(at,qt)|0;var xi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(xi>>>26)|0,xi&=67108863,w=Math.imul(bt,Ot),l=Math.imul(bt,Vt),l=l+Math.imul(wt,Ot)|0,y=Math.imul(wt,Vt),w=w+Math.imul(ht,Dt)|0,l=l+Math.imul(ht,xt)|0,l=l+Math.imul(gt,Dt)|0,y=y+Math.imul(gt,xt)|0,w=w+Math.imul(ft,Bt)|0,l=l+Math.imul(ft,Tt)|0,l=l+Math.imul(pt,Bt)|0,y=y+Math.imul(pt,Tt)|0,w=w+Math.imul(mt,Et)|0,l=l+Math.imul(mt,Ft)|0,l=l+Math.imul(_t,Et)|0,y=y+Math.imul(_t,Ft)|0,w=w+Math.imul(ut,jt)|0,l=l+Math.imul(ut,It)|0,l=l+Math.imul(dt,jt)|0,y=y+Math.imul(dt,It)|0,w=w+Math.imul(ct,Lt)|0,l=l+Math.imul(ct,qt)|0,l=l+Math.imul(lt,Lt)|0,y=y+Math.imul(lt,qt)|0;var Bi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Bi>>>26)|0,Bi&=67108863,w=Math.imul(bt,Dt),l=Math.imul(bt,xt),l=l+Math.imul(wt,Dt)|0,y=Math.imul(wt,xt),w=w+Math.imul(ht,Bt)|0,l=l+Math.imul(ht,Tt)|0,l=l+Math.imul(gt,Bt)|0,y=y+Math.imul(gt,Tt)|0,w=w+Math.imul(ft,Et)|0,l=l+Math.imul(ft,Ft)|0,l=l+Math.imul(pt,Et)|0,y=y+Math.imul(pt,Ft)|0,w=w+Math.imul(mt,jt)|0,l=l+Math.imul(mt,It)|0,l=l+Math.imul(_t,jt)|0,y=y+Math.imul(_t,It)|0,w=w+Math.imul(ut,Lt)|0,l=l+Math.imul(ut,qt)|0,l=l+Math.imul(dt,Lt)|0,y=y+Math.imul(dt,qt)|0;var Ti=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Ti>>>26)|0,Ti&=67108863,w=Math.imul(bt,Bt),l=Math.imul(bt,Tt),l=l+Math.imul(wt,Bt)|0,y=Math.imul(wt,Tt),w=w+Math.imul(ht,Et)|0,l=l+Math.imul(ht,Ft)|0,l=l+Math.imul(gt,Et)|0,y=y+Math.imul(gt,Ft)|0,w=w+Math.imul(ft,jt)|0,l=l+Math.imul(ft,It)|0,l=l+Math.imul(pt,jt)|0,y=y+Math.imul(pt,It)|0,w=w+Math.imul(mt,Lt)|0,l=l+Math.imul(mt,qt)|0,l=l+Math.imul(_t,Lt)|0,y=y+Math.imul(_t,qt)|0;var Ei=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Ei>>>26)|0,Ei&=67108863,w=Math.imul(bt,Et),l=Math.imul(bt,Ft),l=l+Math.imul(wt,Et)|0,y=Math.imul(wt,Ft),w=w+Math.imul(ht,jt)|0,l=l+Math.imul(ht,It)|0,l=l+Math.imul(gt,jt)|0,y=y+Math.imul(gt,It)|0,w=w+Math.imul(ft,Lt)|0,l=l+Math.imul(ft,qt)|0,l=l+Math.imul(pt,Lt)|0,y=y+Math.imul(pt,qt)|0;var Fi=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(Fi>>>26)|0,Fi&=67108863,w=Math.imul(bt,jt),l=Math.imul(bt,It),l=l+Math.imul(wt,jt)|0,y=Math.imul(wt,It),w=w+Math.imul(ht,Lt)|0,l=l+Math.imul(ht,qt)|0,l=l+Math.imul(gt,Lt)|0,y=y+Math.imul(gt,qt)|0;var ji=(k+w|0)+((l&8191)<<13)|0;k=(y+(l>>>13)|0)+(ji>>>26)|0,ji&=67108863,w=Math.imul(bt,Lt),l=Math.imul(bt,qt),l=l+Math.imul(wt,Lt)|0,y=Math.imul(wt,qt);var Ii=(k+w|0)+((l&8191)<<13)|0;return k=(y+(l>>>13)|0)+(Ii>>>26)|0,Ii&=67108863,P[0]=wi,P[1]=yi,P[2]=vi,P[3]=Mi,P[4]=Ci,P[5]=Pi,P[6]=ki,P[7]=Si,P[8]=Ai,P[9]=Oi,P[10]=Vi,P[11]=Di,P[12]=xi,P[13]=Bi,P[14]=Ti,P[15]=Ei,P[16]=Fi,P[17]=ji,P[18]=Ii,k!==0&&(P[19]=k,_.length++),_};Math.imul||(O=V);function B(a,u,_){_.negative=u.negative^a.negative,_.length=a.length+u.length;for(var g=0,b=0,P=0;P<_.length-1;P++){var k=b;b=0;for(var w=g&67108863,l=Math.min(P,u.length-1),y=Math.max(0,P-a.length+1);y<=l;y++){var q=P-y,R=a.words[q]|0,Z=u.words[y]|0,H=R*Z,Y=H&67108863;k=k+(H/67108864|0)|0,Y=Y+w|0,w=Y&67108863,k=k+(Y>>>26)|0,b+=k>>>26,k&=67108863}_.words[P]=w,g=k,k=b}return g!==0?_.words[P]=g:_.length--,_._strip()}function T(a,u,_){return B(a,u,_)}r.prototype.mulTo=function(a,u){var _,g=this.length+a.length;return this.length===10&&a.length===10?_=O(this,a,u):g<63?_=V(this,a,u):g<1024?_=B(this,a,u):_=T(this,a,u),_};function E(a,u){this.x=a,this.y=u}E.prototype.makeRBT=function(a){for(var u=new Array(a),_=r.prototype._countBits(a)-1,g=0;g<a;g++)u[g]=this.revBin(g,_,a);return u},E.prototype.revBin=function(a,u,_){if(a===0||a===_-1)return a;for(var g=0,b=0;b<u;b++)g|=(a&1)<<u-b-1,a>>=1;return g},E.prototype.permute=function(a,u,_,g,b,P){for(var k=0;k<P;k++)g[k]=u[a[k]],b[k]=_[a[k]]},E.prototype.transform=function(a,u,_,g,b,P){this.permute(P,a,u,_,g,b);for(var k=1;k<b;k<<=1)for(var w=k<<1,l=Math.cos(2*Math.PI/w),y=Math.sin(2*Math.PI/w),q=0;q<b;q+=w)for(var R=l,Z=y,H=0;H<k;H++){var Y=_[q+H],it=g[q+H],be=_[q+H+k],nt=g[q+H+k],ot=R*be-Z*nt;nt=R*nt+Z*be,be=ot,_[q+H]=Y+be,g[q+H]=it+nt,_[q+H+k]=Y-be,g[q+H+k]=it-nt,H!==w&&(ot=l*R-y*Z,Z=l*Z+y*R,R=ot)}},E.prototype.guessLen13b=function(a,u){var _=Math.max(u,a)|1,g=_&1,b=0;for(_=_/2|0;_;_=_>>>1)b++;return 1<<b+1+g},E.prototype.conjugate=function(a,u,_){if(!(_<=1))for(var g=0;g<_/2;g++){var b=a[g];a[g]=a[_-g-1],a[_-g-1]=b,b=u[g],u[g]=-u[_-g-1],u[_-g-1]=-b}},E.prototype.normalize13b=function(a,u){for(var _=0,g=0;g<u/2;g++){var b=Math.round(a[2*g+1]/u)*8192+Math.round(a[2*g]/u)+_;a[g]=b&67108863,b<67108864?_=0:_=b/67108864|0}return a},E.prototype.convert13b=function(a,u,_,g){for(var b=0,P=0;P<u;P++)b=b+(a[P]|0),_[2*P]=b&8191,b=b>>>13,_[2*P+1]=b&8191,b=b>>>13;for(P=2*u;P<g;++P)_[P]=0;o(b===0),o((b&-8192)===0)},E.prototype.stub=function(a){for(var u=new Array(a),_=0;_<a;_++)u[_]=0;return u},E.prototype.mulp=function(a,u,_){var g=2*this.guessLen13b(a.length,u.length),b=this.makeRBT(g),P=this.stub(g),k=new Array(g),w=new Array(g),l=new Array(g),y=new Array(g),q=new Array(g),R=new Array(g),Z=_.words;Z.length=g,this.convert13b(a.words,a.length,k,g),this.convert13b(u.words,u.length,y,g),this.transform(k,P,w,l,g,b),this.transform(y,P,q,R,g,b);for(var H=0;H<g;H++){var Y=w[H]*q[H]-l[H]*R[H];l[H]=w[H]*R[H]+l[H]*q[H],w[H]=Y}return this.conjugate(w,l,g),this.transform(w,l,Z,P,g,b),this.conjugate(Z,P,g),this.normalize13b(Z,g),_.negative=a.negative^u.negative,_.length=a.length+u.length,_._strip()},r.prototype.mul=function(a){var u=new r(null);return u.words=new Array(this.length+a.length),this.mulTo(a,u)},r.prototype.mulf=function(a){var u=new r(null);return u.words=new Array(this.length+a.length),T(this,a,u)},r.prototype.imul=function(a){return this.clone().mulTo(a,this)},r.prototype.imuln=function(a){var u=a<0;u&&(a=-a),o(typeof a=="number"),o(a<67108864);for(var _=0,g=0;g<this.length;g++){var b=(this.words[g]|0)*a,P=(b&67108863)+(_&67108863);_>>=26,_+=b/67108864|0,_+=P>>>26,this.words[g]=P&67108863}return _!==0&&(this.words[g]=_,this.length++),this.length=a===0?1:this.length,u?this.ineg():this},r.prototype.muln=function(a){return this.clone().imuln(a)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(a){var u=D(a);if(u.length===0)return new r(1);for(var _=this,g=0;g<u.length&&u[g]===0;g++,_=_.sqr());if(++g<u.length)for(var b=_.sqr();g<u.length;g++,b=b.sqr())u[g]!==0&&(_=_.mul(b));return _},r.prototype.iushln=function(a){o(typeof a=="number"&&a>=0);var u=a%26,_=(a-u)/26,g=67108863>>>26-u<<26-u,b;if(u!==0){var P=0;for(b=0;b<this.length;b++){var k=this.words[b]&g,w=(this.words[b]|0)-k<<u;this.words[b]=w|P,P=k>>>26-u}P&&(this.words[b]=P,this.length++)}if(_!==0){for(b=this.length-1;b>=0;b--)this.words[b+_]=this.words[b];for(b=0;b<_;b++)this.words[b]=0;this.length+=_}return this._strip()},r.prototype.ishln=function(a){return o(this.negative===0),this.iushln(a)},r.prototype.iushrn=function(a,u,_){o(typeof a=="number"&&a>=0);var g;u?g=(u-u%26)/26:g=0;var b=a%26,P=Math.min((a-b)/26,this.length),k=67108863^67108863>>>b<<b,w=_;if(g-=P,g=Math.max(0,g),w){for(var l=0;l<P;l++)w.words[l]=this.words[l];w.length=P}if(P!==0)if(this.length>P)for(this.length-=P,l=0;l<this.length;l++)this.words[l]=this.words[l+P];else this.words[0]=0,this.length=1;var y=0;for(l=this.length-1;l>=0&&(y!==0||l>=g);l--){var q=this.words[l]|0;this.words[l]=y<<26-b|q>>>b,y=q&k}return w&&y!==0&&(w.words[w.length++]=y),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(a,u,_){return o(this.negative===0),this.iushrn(a,u,_)},r.prototype.shln=function(a){return this.clone().ishln(a)},r.prototype.ushln=function(a){return this.clone().iushln(a)},r.prototype.shrn=function(a){return this.clone().ishrn(a)},r.prototype.ushrn=function(a){return this.clone().iushrn(a)},r.prototype.testn=function(a){o(typeof a=="number"&&a>=0);var u=a%26,_=(a-u)/26,g=1<<u;if(this.length<=_)return!1;var b=this.words[_];return!!(b&g)},r.prototype.imaskn=function(a){o(typeof a=="number"&&a>=0);var u=a%26,_=(a-u)/26;if(o(this.negative===0,"imaskn works only with positive numbers"),this.length<=_)return this;if(u!==0&&_++,this.length=Math.min(_,this.length),u!==0){var g=67108863^67108863>>>u<<u;this.words[this.length-1]&=g}return this._strip()},r.prototype.maskn=function(a){return this.clone().imaskn(a)},r.prototype.iaddn=function(a){return o(typeof a=="number"),o(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)},r.prototype._iaddn=function(a){this.words[0]+=a;for(var u=0;u<this.length&&this.words[u]>=67108864;u++)this.words[u]-=67108864,u===this.length-1?this.words[u+1]=1:this.words[u+1]++;return this.length=Math.max(this.length,u+1),this},r.prototype.isubn=function(a){if(o(typeof a=="number"),o(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 u=0;u<this.length&&this.words[u]<0;u++)this.words[u]+=67108864,this.words[u+1]-=1;return this._strip()},r.prototype.addn=function(a){return this.clone().iaddn(a)},r.prototype.subn=function(a){return this.clone().isubn(a)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(a,u,_){var g=a.length+_,b;this._expand(g);var P,k=0;for(b=0;b<a.length;b++){P=(this.words[b+_]|0)+k;var w=(a.words[b]|0)*u;P-=w&67108863,k=(P>>26)-(w/67108864|0),this.words[b+_]=P&67108863}for(;b<this.length-_;b++)P=(this.words[b+_]|0)+k,k=P>>26,this.words[b+_]=P&67108863;if(k===0)return this._strip();for(o(k===-1),k=0,b=0;b<this.length;b++)P=-(this.words[b]|0)+k,k=P>>26,this.words[b]=P&67108863;return this.negative=1,this._strip()},r.prototype._wordDiv=function(a,u){var _=this.length-a.length,g=this.clone(),b=a,P=b.words[b.length-1]|0,k=this._countBits(P);_=26-k,_!==0&&(b=b.ushln(_),g.iushln(_),P=b.words[b.length-1]|0);var w=g.length-b.length,l;if(u!=="mod"){l=new r(null),l.length=w+1,l.words=new Array(l.length);for(var y=0;y<l.length;y++)l.words[y]=0}var q=g.clone()._ishlnsubmul(b,1,w);q.negative===0&&(g=q,l&&(l.words[w]=1));for(var R=w-1;R>=0;R--){var Z=(g.words[b.length+R]|0)*67108864+(g.words[b.length+R-1]|0);for(Z=Math.min(Z/P|0,67108863),g._ishlnsubmul(b,Z,R);g.negative!==0;)Z--,g.negative=0,g._ishlnsubmul(b,1,R),g.isZero()||(g.negative^=1);l&&(l.words[R]=Z)}return l&&l._strip(),g._strip(),u!=="div"&&_!==0&&g.iushrn(_),{div:l||null,mod:g}},r.prototype.divmod=function(a,u,_){if(o(!a.isZero()),this.isZero())return{div:new r(0),mod:new r(0)};var g,b,P;return this.negative!==0&&a.negative===0?(P=this.neg().divmod(a,u),u!=="mod"&&(g=P.div.neg()),u!=="div"&&(b=P.mod.neg(),_&&b.negative!==0&&b.iadd(a)),{div:g,mod:b}):this.negative===0&&a.negative!==0?(P=this.divmod(a.neg(),u),u!=="mod"&&(g=P.div.neg()),{div:g,mod:P.mod}):this.negative&a.negative?(P=this.neg().divmod(a.neg(),u),u!=="div"&&(b=P.mod.neg(),_&&b.negative!==0&&b.isub(a)),{div:P.div,mod:b}):a.length>this.length||this.cmp(a)<0?{div:new r(0),mod:this}:a.length===1?u==="div"?{div:this.divn(a.words[0]),mod:null}:u==="mod"?{div:null,mod:new r(this.modrn(a.words[0]))}:{div:this.divn(a.words[0]),mod:new r(this.modrn(a.words[0]))}:this._wordDiv(a,u)},r.prototype.div=function(a){return this.divmod(a,"div",!1).div},r.prototype.mod=function(a){return this.divmod(a,"mod",!1).mod},r.prototype.umod=function(a){return this.divmod(a,"mod",!0).mod},r.prototype.divRound=function(a){var u=this.divmod(a);if(u.mod.isZero())return u.div;var _=u.div.negative!==0?u.mod.isub(a):u.mod,g=a.ushrn(1),b=a.andln(1),P=_.cmp(g);return P<0||b===1&&P===0?u.div:u.div.negative!==0?u.div.isubn(1):u.div.iaddn(1)},r.prototype.modrn=function(a){var u=a<0;u&&(a=-a),o(a<=67108863);for(var _=(1<<26)%a,g=0,b=this.length-1;b>=0;b--)g=(_*g+(this.words[b]|0))%a;return u?-g:g},r.prototype.modn=function(a){return this.modrn(a)},r.prototype.idivn=function(a){var u=a<0;u&&(a=-a),o(a<=67108863);for(var _=0,g=this.length-1;g>=0;g--){var b=(this.words[g]|0)+_*67108864;this.words[g]=b/a|0,_=b%a}return this._strip(),u?this.ineg():this},r.prototype.divn=function(a){return this.clone().idivn(a)},r.prototype.egcd=function(a){o(a.negative===0),o(!a.isZero());var u=this,_=a.clone();u.negative!==0?u=u.umod(a):u=u.clone();for(var g=new r(1),b=new r(0),P=new r(0),k=new r(1),w=0;u.isEven()&&_.isEven();)u.iushrn(1),_.iushrn(1),++w;for(var l=_.clone(),y=u.clone();!u.isZero();){for(var q=0,R=1;!(u.words[0]&R)&&q<26;++q,R<<=1);if(q>0)for(u.iushrn(q);q-- >0;)(g.isOdd()||b.isOdd())&&(g.iadd(l),b.isub(y)),g.iushrn(1),b.iushrn(1);for(var Z=0,H=1;!(_.words[0]&H)&&Z<26;++Z,H<<=1);if(Z>0)for(_.iushrn(Z);Z-- >0;)(P.isOdd()||k.isOdd())&&(P.iadd(l),k.isub(y)),P.iushrn(1),k.iushrn(1);u.cmp(_)>=0?(u.isub(_),g.isub(P),b.isub(k)):(_.isub(u),P.isub(g),k.isub(b))}return{a:P,b:k,gcd:_.iushln(w)}},r.prototype._invmp=function(a){o(a.negative===0),o(!a.isZero());var u=this,_=a.clone();u.negative!==0?u=u.umod(a):u=u.clone();for(var g=new r(1),b=new r(0),P=_.clone();u.cmpn(1)>0&&_.cmpn(1)>0;){for(var k=0,w=1;!(u.words[0]&w)&&k<26;++k,w<<=1);if(k>0)for(u.iushrn(k);k-- >0;)g.isOdd()&&g.iadd(P),g.iushrn(1);for(var l=0,y=1;!(_.words[0]&y)&&l<26;++l,y<<=1);if(l>0)for(_.iushrn(l);l-- >0;)b.isOdd()&&b.iadd(P),b.iushrn(1);u.cmp(_)>=0?(u.isub(_),g.isub(b)):(_.isub(u),b.isub(g))}var q;return u.cmpn(1)===0?q=g:q=b,q.cmpn(0)<0&&q.iadd(a),q},r.prototype.gcd=function(a){if(this.isZero())return a.abs();if(a.isZero())return this.abs();var u=this.clone(),_=a.clone();u.negative=0,_.negative=0;for(var g=0;u.isEven()&&_.isEven();g++)u.iushrn(1),_.iushrn(1);do{for(;u.isEven();)u.iushrn(1);for(;_.isEven();)_.iushrn(1);var b=u.cmp(_);if(b<0){var P=u;u=_,_=P}else if(b===0||_.cmpn(1)===0)break;u.isub(_)}while(!0);return _.iushln(g)},r.prototype.invm=function(a){return this.egcd(a).a.umod(a)},r.prototype.isEven=function(){return(this.words[0]&1)===0},r.prototype.isOdd=function(){return(this.words[0]&1)===1},r.prototype.andln=function(a){return this.words[0]&a},r.prototype.bincn=function(a){o(typeof a=="number");var u=a%26,_=(a-u)/26,g=1<<u;if(this.length<=_)return this._expand(_+1),this.words[_]|=g,this;for(var b=g,P=_;b!==0&&P<this.length;P++){var k=this.words[P]|0;k+=b,b=k>>>26,k&=67108863,this.words[P]=k}return b!==0&&(this.words[P]=b,this.length++),this},r.prototype.isZero=function(){return this.length===1&&this.words[0]===0},r.prototype.cmpn=function(a){var u=a<0;if(this.negative!==0&&!u)return-1;if(this.negative===0&&u)return 1;this._strip();var _;if(this.length>1)_=1;else{u&&(a=-a),o(a<=67108863,"Number is too big");var g=this.words[0]|0;_=g===a?0:g<a?-1:1}return this.negative!==0?-_|0:_},r.prototype.cmp=function(a){if(this.negative!==0&&a.negative===0)return-1;if(this.negative===0&&a.negative!==0)return 1;var u=this.ucmp(a);return this.negative!==0?-u|0:u},r.prototype.ucmp=function(a){if(this.length>a.length)return 1;if(this.length<a.length)return-1;for(var u=0,_=this.length-1;_>=0;_--){var g=this.words[_]|0,b=a.words[_]|0;if(g!==b){g<b?u=-1:g>b&&(u=1);break}}return u},r.prototype.gtn=function(a){return this.cmpn(a)===1},r.prototype.gt=function(a){return this.cmp(a)===1},r.prototype.gten=function(a){return this.cmpn(a)>=0},r.prototype.gte=function(a){return this.cmp(a)>=0},r.prototype.ltn=function(a){return this.cmpn(a)===-1},r.prototype.lt=function(a){return this.cmp(a)===-1},r.prototype.lten=function(a){return this.cmpn(a)<=0},r.prototype.lte=function(a){return this.cmp(a)<=0},r.prototype.eqn=function(a){return this.cmpn(a)===0},r.prototype.eq=function(a){return this.cmp(a)===0},r.red=function(a){return new $(a)},r.prototype.toRed=function(a){return o(!this.red,"Already a number in reduction context"),o(this.negative===0,"red works only with positives"),a.convertTo(this)._forceRed(a)},r.prototype.fromRed=function(){return o(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(a){return this.red=a,this},r.prototype.forceRed=function(a){return o(!this.red,"Already a number in reduction context"),this._forceRed(a)},r.prototype.redAdd=function(a){return o(this.red,"redAdd works only with red numbers"),this.red.add(this,a)},r.prototype.redIAdd=function(a){return o(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,a)},r.prototype.redSub=function(a){return o(this.red,"redSub works only with red numbers"),this.red.sub(this,a)},r.prototype.redISub=function(a){return o(this.red,"redISub works only with red numbers"),this.red.isub(this,a)},r.prototype.redShl=function(a){return o(this.red,"redShl works only with red numbers"),this.red.shl(this,a)},r.prototype.redMul=function(a){return o(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.mul(this,a)},r.prototype.redIMul=function(a){return o(this.red,"redMul works only with red numbers"),this.red._verify2(this,a),this.red.imul(this,a)},r.prototype.redSqr=function(){return o(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},r.prototype.redISqr=function(){return o(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},r.prototype.redSqrt=function(){return o(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},r.prototype.redInvm=function(){return o(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},r.prototype.redNeg=function(){return o(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},r.prototype.redPow=function(a){return o(this.red&&!a.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,a)};var N={k256:null,p224:null,p192:null,p25519:null};function F(a,u){this.name=a,this.p=new r(u,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}F.prototype._tmp=function(){var a=new r(null);return a.words=new Array(Math.ceil(this.n/13)),a},F.prototype.ireduce=function(a){var u=a,_;do this.split(u,this.tmp),u=this.imulK(u),u=u.iadd(this.tmp),_=u.bitLength();while(_>this.n);var g=_<this.n?-1:u.ucmp(this.p);return g===0?(u.words[0]=0,u.length=1):g>0?u.isub(this.p):u.strip!==void 0?u.strip():u._strip(),u},F.prototype.split=function(a,u){a.iushrn(this.n,0,u)},F.prototype.imulK=function(a){return a.imul(this.k)};function I(){F.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}s(I,F),I.prototype.split=function(a,u){for(var _=4194303,g=Math.min(a.length,9),b=0;b<g;b++)u.words[b]=a.words[b];if(u.length=g,a.length<=9){a.words[0]=0,a.length=1;return}var P=a.words[9];for(u.words[u.length++]=P&_,b=10;b<a.length;b++){var k=a.words[b]|0;a.words[b-10]=(k&_)<<4|P>>>22,P=k}P>>>=22,a.words[b-10]=P,P===0&&a.length>10?a.length-=10:a.length-=9},I.prototype.imulK=function(a){a.words[a.length]=0,a.words[a.length+1]=0,a.length+=2;for(var u=0,_=0;_<a.length;_++){var g=a.words[_]|0;u+=g*977,a.words[_]=u&67108863,u=g*64+(u/67108864|0)}return a.words[a.length-1]===0&&(a.length--,a.words[a.length-1]===0&&a.length--),a};function W(){F.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}s(W,F);function j(){F.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}s(j,F);function Q(){F.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}s(Q,F),Q.prototype.imulK=function(a){for(var u=0,_=0;_<a.length;_++){var g=(a.words[_]|0)*19+u,b=g&67108863;g>>>=26,a.words[_]=b,u=g}return u!==0&&(a.words[a.length++]=u),a},r._prime=function(a){if(N[a])return N[a];var u;if(a==="k256")u=new I;else if(a==="p224")u=new W;else if(a==="p192")u=new j;else if(a==="p25519")u=new Q;else throw new Error("Unknown prime "+a);return N[a]=u,u};function $(a){if(typeof a=="string"){var u=r._prime(a);this.m=u.p,this.prime=u}else o(a.gtn(1),"modulus must be greater than 1"),this.m=a,this.prime=null}$.prototype._verify1=function(a){o(a.negative===0,"red works only with positives"),o(a.red,"red works only with red numbers")},$.prototype._verify2=function(a,u){o((a.negative|u.negative)===0,"red works only with positives"),o(a.red&&a.red===u.red,"red works only with red numbers")},$.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(p(a,a.umod(this.m)._forceRed(this)),a)},$.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},$.prototype.add=function(a,u){this._verify2(a,u);var _=a.add(u);return _.cmp(this.m)>=0&&_.isub(this.m),_._forceRed(this)},$.prototype.iadd=function(a,u){this._verify2(a,u);var _=a.iadd(u);return _.cmp(this.m)>=0&&_.isub(this.m),_},$.prototype.sub=function(a,u){this._verify2(a,u);var _=a.sub(u);return _.cmpn(0)<0&&_.iadd(this.m),_._forceRed(this)},$.prototype.isub=function(a,u){this._verify2(a,u);var _=a.isub(u);return _.cmpn(0)<0&&_.iadd(this.m),_},$.prototype.shl=function(a,u){return this._verify1(a),this.imod(a.ushln(u))},$.prototype.imul=function(a,u){return this._verify2(a,u),this.imod(a.imul(u))},$.prototype.mul=function(a,u){return this._verify2(a,u),this.imod(a.mul(u))},$.prototype.isqr=function(a){return this.imul(a,a.clone())},$.prototype.sqr=function(a){return this.mul(a,a)},$.prototype.sqrt=function(a){if(a.isZero())return a.clone();var u=this.m.andln(3);if(o(u%2===1),u===3){var _=this.m.add(new r(1)).iushrn(2);return this.pow(a,_)}for(var g=this.m.subn(1),b=0;!g.isZero()&&g.andln(1)===0;)b++,g.iushrn(1);o(!g.isZero());var P=new r(1).toRed(this),k=P.redNeg(),w=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new r(2*l*l).toRed(this);this.pow(l,w).cmp(k)!==0;)l.redIAdd(k);for(var y=this.pow(l,g),q=this.pow(a,g.addn(1).iushrn(1)),R=this.pow(a,g),Z=b;R.cmp(P)!==0;){for(var H=R,Y=0;H.cmp(P)!==0;Y++)H=H.redSqr();o(Y<Z);var it=this.pow(y,new r(1).iushln(Z-Y-1));q=q.redMul(it),y=it.redSqr(),R=R.redMul(y),Z=Y}return q},$.prototype.invm=function(a){var u=a._invmp(this.m);return u.negative!==0?(u.negative=0,this.imod(u).redNeg()):this.imod(u)},$.prototype.pow=function(a,u){if(u.isZero())return new r(1).toRed(this);if(u.cmpn(1)===0)return a.clone();var _=4,g=new Array(1<<_);g[0]=new r(1).toRed(this),g[1]=a;for(var b=2;b<g.length;b++)g[b]=this.mul(g[b-1],a);var P=g[0],k=0,w=0,l=u.bitLength()%26;for(l===0&&(l=26),b=u.length-1;b>=0;b--){for(var y=u.words[b],q=l-1;q>=0;q--){var R=y>>q&1;if(P!==g[0]&&(P=this.sqr(P)),R===0&&k===0){w=0;continue}k<<=1,k|=R,w++,!(w!==_&&(b!==0||q!==0))&&(P=this.mul(P,g[k]),w=0,k=0)}l=26}return P},$.prototype.convertTo=function(a){var u=a.umod(this.m);return u===a?u.clone():u},$.prototype.convertFrom=function(a){var u=a.clone();return u.red=null,u},r.mont=function(a){return new K(a)};function K(a){$.call(this,a),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new r(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}s(K,$),K.prototype.convertTo=function(a){return this.imod(a.ushln(this.shift))},K.prototype.convertFrom=function(a){var u=this.imod(a.mul(this.rinv));return u.red=null,u},K.prototype.imul=function(a,u){if(a.isZero()||u.isZero())return a.words[0]=0,a.length=1,a;var _=a.imul(u),g=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),b=_.isub(g).iushrn(this.shift),P=b;return b.cmp(this.m)>=0?P=b.isub(this.m):b.cmpn(0)<0&&(P=b.iadd(this.m)),P._forceRed(this)},K.prototype.mul=function(a,u){if(a.isZero()||u.isZero())return new r(0)._forceRed(this);var _=a.mul(u),g=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),b=_.isub(g).iushrn(this.shift),P=b;return b.cmp(this.m)>=0?P=b.isub(this.m):b.cmpn(0)<0&&(P=b.iadd(this.m)),P._forceRed(this)},K.prototype.invm=function(a){var u=this.imod(a._invmp(this.m).mul(this.r2));return u._forceRed(this)}})(typeof e>"u"||e,i)}),Li={REQUEST_PARAMS:"requestParams",METHOD_NAME:"methodName"},$o=class Xn extends Error{constructor(e,t,n){super(e),this.code=t,this.details=n,this.name=this.constructor.name}static{this.DETAILS_KEYS=Li}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details}}toString(){return JSON.stringify(this.toJSON())}static isErrorCode(e,t){return e instanceof Xn&&e.code===t}},Ko=class extends $o{constructor(i,e,t){super(i,e||"UnknownError",t)}static isCommonErrorCode(i,e){return this.isErrorCode(i,e)}},te=(i,e,t)=>{throw new Ko(e,i,t)};var Gn=864e5;var Be=9e15,Me=1e9,Ri="0123456789abcdef",oi="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ri="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ni={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Be,maxE:Be,crypto:!1},Hn,pe,G=!0,ai="[DecimalError] ",ve=ai+"Invalid argument: ",Qn=ai+"Precision limit exceeded",Jn=ai+"crypto unavailable",Yn="[object Decimal]",zt=Math.floor,Ut=Math.pow,Go=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Ho=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Qo=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,to=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,re=1e7,X=7,Jo=9007199254740991,Yo=oi.length-1,Ui=ri.length-1,x={toStringTag:Yn};x.absoluteValue=x.abs=function(){var i=new this.constructor(this);return i.s<0&&(i.s=1),U(i)};x.ceil=function(){return U(new this.constructor(this),this.e+1,2)};x.clampedTo=x.clamp=function(i,e){var t,n=this,o=n.constructor;if(i=new o(i),e=new o(e),!i.s||!e.s)return new o(NaN);if(i.gt(e))throw Error(ve+e);return t=n.cmp(i),t<0?i:n.cmp(e)>0?e:new o(n)};x.comparedTo=x.cmp=function(i){var e,t,n,o,s=this,r=s.d,c=(i=new s.constructor(i)).d,d=s.s,m=i.s;if(!r||!c)return!d||!m?NaN:d!==m?d:r===c?0:!r^d<0?1:-1;if(!r[0]||!c[0])return r[0]?d:c[0]?-m:0;if(d!==m)return d;if(s.e!==i.e)return s.e>i.e^d<0?1:-1;for(n=r.length,o=c.length,e=0,t=n<o?n:o;e<t;++e)if(r[e]!==c[e])return r[e]>c[e]^d<0?1:-1;return n===o?0:n>o^d<0?1:-1};x.cosine=x.cos=function(){var i,e,t=this,n=t.constructor;return t.d?t.d[0]?(i=n.precision,e=n.rounding,n.precision=i+Math.max(t.e,t.sd())+X,n.rounding=1,t=tr(n,ro(n,t)),n.precision=i,n.rounding=e,U(pe==2||pe==3?t.neg():t,i,e,!0)):new n(1):new n(NaN)};x.cubeRoot=x.cbrt=function(){var i,e,t,n,o,s,r,c,d,m,f=this,p=f.constructor;if(!f.isFinite()||f.isZero())return new p(f);for(G=!1,s=f.s*Ut(f.s*f,1/3),!s||Math.abs(s)==1/0?(t=Kt(f.d),i=f.e,(s=(i-t.length+1)%3)&&(t+=s==1||s==-2?"0":"00"),s=Ut(t,1/3),i=zt((i+1)/3)-(i%3==(i<0?-1:2)),s==1/0?t="5e"+i:(t=s.toExponential(),t=t.slice(0,t.indexOf("e")+1)+i),n=new p(t),n.s=f.s):n=new p(s.toString()),r=(i=p.precision)+3;;)if(c=n,d=c.times(c).times(c),m=d.plus(f),n=et(m.plus(f).times(c),m.plus(d),r+2,1),Kt(c.d).slice(0,r)===(t=Kt(n.d)).slice(0,r))if(t=t.slice(r-3,r+1),t=="9999"||!o&&t=="4999"){if(!o&&(U(c,i+1,0),c.times(c).times(c).eq(f))){n=c;break}r+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(U(n,i+1,1),e=!n.times(n).times(n).eq(f));break}return G=!0,U(n,i,p.rounding,e)};x.decimalPlaces=x.dp=function(){var i,e=this.d,t=NaN;if(e){if(i=e.length-1,t=(i-zt(this.e/X))*X,i=e[i],i)for(;i%10==0;i/=10)t--;t<0&&(t=0)}return t};x.dividedBy=x.div=function(i){return et(this,new this.constructor(i))};x.dividedToIntegerBy=x.divToInt=function(i){var e=this,t=e.constructor;return U(et(e,new t(i),0,1,1),t.precision,t.rounding)};x.equals=x.eq=function(i){return this.cmp(i)===0};x.floor=function(){return U(new this.constructor(this),this.e+1,3)};x.greaterThan=x.gt=function(i){return this.cmp(i)>0};x.greaterThanOrEqualTo=x.gte=function(i){var e=this.cmp(i);return e==1||e===0};x.hyperbolicCosine=x.cosh=function(){var i,e,t,n,o,s=this,r=s.constructor,c=new r(1);if(!s.isFinite())return new r(s.s?1/0:NaN);if(s.isZero())return c;t=r.precision,n=r.rounding,r.precision=t+Math.max(s.e,s.sd())+4,r.rounding=1,o=s.d.length,o<32?(i=Math.ceil(o/3),e=(1/li(4,i)).toString()):(i=16,e="2.3283064365386962890625e-10"),s=Te(r,1,s.times(e),new r(1),!0);for(var d,m=i,f=new r(8);m--;)d=s.times(s),s=c.minus(d.times(f.minus(d.times(f))));return U(s,r.precision=t,r.rounding=n,!0)};x.hyperbolicSine=x.sinh=function(){var i,e,t,n,o=this,s=o.constructor;if(!o.isFinite()||o.isZero())return new s(o);if(e=s.precision,t=s.rounding,s.precision=e+Math.max(o.e,o.sd())+4,s.rounding=1,n=o.d.length,n<3)o=Te(s,2,o,o,!0);else{i=1.4*Math.sqrt(n),i=i>16?16:i|0,o=o.times(1/li(5,i)),o=Te(s,2,o,o,!0);for(var r,c=new s(5),d=new s(16),m=new s(20);i--;)r=o.times(o),o=o.times(c.plus(r.times(d.times(r).plus(m))))}return s.precision=e,s.rounding=t,U(o,e,t,!0)};x.hyperbolicTangent=x.tanh=function(){var i,e,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(i=n.precision,e=n.rounding,n.precision=i+7,n.rounding=1,et(t.sinh(),t.cosh(),n.precision=i,n.rounding=e)):new n(t.s)};x.inverseCosine=x.acos=function(){var i=this,e=i.constructor,t=i.abs().cmp(1),n=e.precision,o=e.rounding;return t!==-1?t===0?i.isNeg()?ue(e,n,o):new e(0):new e(NaN):i.isZero()?ue(e,n+4,o).times(.5):(e.precision=n+6,e.rounding=1,i=new e(1).minus(i).div(i.plus(1)).sqrt().atan(),e.precision=n,e.rounding=o,i.times(2))};x.inverseHyperbolicCosine=x.acosh=function(){var i,e,t=this,n=t.constructor;return t.lte(1)?new n(t.eq(1)?0:NaN):t.isFinite()?(i=n.precision,e=n.rounding,n.precision=i+Math.max(Math.abs(t.e),t.sd())+4,n.rounding=1,G=!1,t=t.times(t).minus(1).sqrt().plus(t),G=!0,n.precision=i,n.rounding=e,t.ln()):new n(t)};x.inverseHyperbolicSine=x.asinh=function(){var i,e,t=this,n=t.constructor;return!t.isFinite()||t.isZero()?new n(t):(i=n.precision,e=n.rounding,n.precision=i+2*Math.max(Math.abs(t.e),t.sd())+6,n.rounding=1,G=!1,t=t.times(t).plus(1).sqrt().plus(t),G=!0,n.precision=i,n.rounding=e,t.ln())};x.inverseHyperbolicTangent=x.atanh=function(){var i,e,t,n,o=this,s=o.constructor;return o.isFinite()?o.e>=0?new s(o.abs().eq(1)?o.s/0:o.isZero()?o:NaN):(i=s.precision,e=s.rounding,n=o.sd(),Math.max(n,i)<2*-o.e-1?U(new s(o),i,e,!0):(s.precision=t=n-o.e,o=et(o.plus(1),new s(1).minus(o),t+i,1),s.precision=i+4,s.rounding=1,o=o.ln(),s.precision=i,s.rounding=e,o.times(.5))):new s(NaN)};x.inverseSine=x.asin=function(){var i,e,t,n,o=this,s=o.constructor;return o.isZero()?new s(o):(e=o.abs().cmp(1),t=s.precision,n=s.rounding,e!==-1?e===0?(i=ue(s,t+4,n).times(.5),i.s=o.s,i):new s(NaN):(s.precision=t+6,s.rounding=1,o=o.div(new s(1).minus(o.times(o)).sqrt().plus(1)).atan(),s.precision=t,s.rounding=n,o.times(2)))};x.inverseTangent=x.atan=function(){var i,e,t,n,o,s,r,c,d,m=this,f=m.constructor,p=f.precision,h=f.rounding;if(m.isFinite()){if(m.isZero())return new f(m);if(m.abs().eq(1)&&p+4<=Ui)return r=ue(f,p+4,h).times(.25),r.s=m.s,r}else{if(!m.s)return new f(NaN);if(p+4<=Ui)return r=ue(f,p+4,h).times(.5),r.s=m.s,r}for(f.precision=c=p+10,f.rounding=1,t=Math.min(28,c/X+2|0),i=t;i;--i)m=m.div(m.times(m).plus(1).sqrt().plus(1));for(G=!1,e=Math.ceil(c/X),n=1,d=m.times(m),r=new f(m),o=m;i!==-1;)if(o=o.times(d),s=r.minus(o.div(n+=2)),o=o.times(d),r=s.plus(o.div(n+=2)),r.d[e]!==void 0)for(i=e;r.d[i]===s.d[i]&&i--;);return t&&(r=r.times(2<<t-1)),G=!0,U(r,f.precision=p,f.rounding=h,!0)};x.isFinite=function(){return!!this.d};x.isInteger=x.isInt=function(){return!!this.d&&zt(this.e/X)>this.d.length-2};x.isNaN=function(){return!this.s};x.isNegative=x.isNeg=function(){return this.s<0};x.isPositive=x.isPos=function(){return this.s>0};x.isZero=function(){return!!this.d&&this.d[0]===0};x.lessThan=x.lt=function(i){return this.cmp(i)<0};x.lessThanOrEqualTo=x.lte=function(i){return this.cmp(i)<1};x.logarithm=x.log=function(i){var e,t,n,o,s,r,c,d,m=this,f=m.constructor,p=f.precision,h=f.rounding,v=5;if(i==null)i=new f(10),e=!0;else{if(i=new f(i),t=i.d,i.s<0||!t||!t[0]||i.eq(1))return new f(NaN);e=i.eq(10)}if(t=m.d,m.s<0||!t||!t[0]||m.eq(1))return new f(t&&!t[0]?-1/0:m.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)s=!0;else{for(o=t[0];o%10===0;)o/=10;s=o!==1}if(G=!1,c=p+v,r=ye(m,c),n=e?si(f,c+10):ye(i,c),d=et(r,n,c,1),Re(d.d,o=p,h))do if(c+=10,r=ye(m,c),n=e?si(f,c+10):ye(i,c),d=et(r,n,c,1),!s){+Kt(d.d).slice(o+1,o+15)+1==1e14&&(d=U(d,p+1,0));break}while(Re(d.d,o+=10,h));return G=!0,U(d,p,h)};x.minus=x.sub=function(i){var e,t,n,o,s,r,c,d,m,f,p,h,v=this,M=v.constructor;if(i=new M(i),!v.d||!i.d)return!v.s||!i.s?i=new M(NaN):v.d?i.s=-i.s:i=new M(i.d||v.s!==i.s?v:NaN),i;if(v.s!=i.s)return i.s=-i.s,v.plus(i);if(m=v.d,h=i.d,c=M.precision,d=M.rounding,!m[0]||!h[0]){if(h[0])i.s=-i.s;else if(m[0])i=new M(v);else return new M(d===3?-0:0);return G?U(i,c,d):i}if(t=zt(i.e/X),f=zt(v.e/X),m=m.slice(),s=f-t,s){for(p=s<0,p?(e=m,s=-s,r=h.length):(e=h,t=f,r=m.length),n=Math.max(Math.ceil(c/X),r)+2,s>n&&(s=n,e.length=1),e.reverse(),n=s;n--;)e.push(0);e.reverse()}else{for(n=m.length,r=h.length,p=n<r,p&&(r=n),n=0;n<r;n++)if(m[n]!=h[n]){p=m[n]<h[n];break}s=0}for(p&&(e=m,m=h,h=e,i.s=-i.s),r=m.length,n=h.length-r;n>0;--n)m[r++]=0;for(n=h.length;n>s;){if(m[--n]<h[n]){for(o=n;o&&m[--o]===0;)m[o]=re-1;--m[o],m[n]+=re}m[n]-=h[n]}for(;m[--r]===0;)m.pop();for(;m[0]===0;m.shift())--t;return m[0]?(i.d=m,i.e=ci(m,t),G?U(i,c,d):i):new M(d===3?-0:0)};x.modulo=x.mod=function(i){var e,t=this,n=t.constructor;return i=new n(i),!t.d||!i.s||i.d&&!i.d[0]?new n(NaN):!i.d||t.d&&!t.d[0]?U(new n(t),n.precision,n.rounding):(G=!1,n.modulo==9?(e=et(t,i.abs(),0,3,1),e.s*=i.s):e=et(t,i,0,n.modulo,1),e=e.times(i),G=!0,t.minus(e))};x.naturalExponential=x.exp=function(){return $i(this)};x.naturalLogarithm=x.ln=function(){return ye(this)};x.negated=x.neg=function(){var i=new this.constructor(this);return i.s=-i.s,U(i)};x.plus=x.add=function(i){var e,t,n,o,s,r,c,d,m,f,p=this,h=p.constructor;if(i=new h(i),!p.d||!i.d)return!p.s||!i.s?i=new h(NaN):p.d||(i=new h(i.d||p.s===i.s?p:NaN)),i;if(p.s!=i.s)return i.s=-i.s,p.minus(i);if(m=p.d,f=i.d,c=h.precision,d=h.rounding,!m[0]||!f[0])return f[0]||(i=new h(p)),G?U(i,c,d):i;if(s=zt(p.e/X),n=zt(i.e/X),m=m.slice(),o=s-n,o){for(o<0?(t=m,o=-o,r=f.length):(t=f,n=s,r=m.length),s=Math.ceil(c/X),r=s>r?s+1:r+1,o>r&&(o=r,t.length=1),t.reverse();o--;)t.push(0);t.reverse()}for(r=m.length,o=f.length,r-o<0&&(o=r,t=f,f=m,m=t),e=0;o;)e=(m[--o]=m[o]+f[o]+e)/re|0,m[o]%=re;for(e&&(m.unshift(e),++n),r=m.length;m[--r]==0;)m.pop();return i.d=m,i.e=ci(m,n),G?U(i,c,d):i};x.precision=x.sd=function(i){var e,t=this;if(i!==void 0&&i!==!!i&&i!==1&&i!==0)throw Error(ve+i);return t.d?(e=eo(t.d),i&&t.e+1>e&&(e=t.e+1)):e=NaN,e};x.round=function(){var i=this,e=i.constructor;return U(new e(i),i.e+1,e.rounding)};x.sine=x.sin=function(){var i,e,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(i=n.precision,e=n.rounding,n.precision=i+Math.max(t.e,t.sd())+X,n.rounding=1,t=ir(n,ro(n,t)),n.precision=i,n.rounding=e,U(pe>2?t.neg():t,i,e,!0)):new n(NaN)};x.squareRoot=x.sqrt=function(){var i,e,t,n,o,s,r=this,c=r.d,d=r.e,m=r.s,f=r.constructor;if(m!==1||!c||!c[0])return new f(!m||m<0&&(!c||c[0])?NaN:c?r:1/0);for(G=!1,m=Math.sqrt(+r),m==0||m==1/0?(e=Kt(c),(e.length+d)%2==0&&(e+="0"),m=Math.sqrt(e),d=zt((d+1)/2)-(d<0||d%2),m==1/0?e="5e"+d:(e=m.toExponential(),e=e.slice(0,e.indexOf("e")+1)+d),n=new f(e)):n=new f(m.toString()),t=(d=f.precision)+3;;)if(s=n,n=s.plus(et(r,s,t+2,1)).times(.5),Kt(s.d).slice(0,t)===(e=Kt(n.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!o&&e=="4999"){if(!o&&(U(s,d+1,0),s.times(s).eq(r))){n=s;break}t+=4,o=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(U(n,d+1,1),i=!n.times(n).eq(r));break}return G=!0,U(n,d,f.rounding,i)};x.tangent=x.tan=function(){var i,e,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(i=n.precision,e=n.rounding,n.precision=i+10,n.rounding=1,t=t.sin(),t.s=1,t=et(t,new n(1).minus(t.times(t)).sqrt(),i+10,0),n.precision=i,n.rounding=e,U(pe==2||pe==4?t.neg():t,i,e,!0)):new n(NaN)};x.times=x.mul=function(i){var e,t,n,o,s,r,c,d,m,f=this,p=f.constructor,h=f.d,v=(i=new p(i)).d;if(i.s*=f.s,!h||!h[0]||!v||!v[0])return new p(!i.s||h&&!h[0]&&!v||v&&!v[0]&&!h?NaN:!h||!v?i.s/0:i.s*0);for(t=zt(f.e/X)+zt(i.e/X),d=h.length,m=v.length,d<m&&(s=h,h=v,v=s,r=d,d=m,m=r),s=[],r=d+m,n=r;n--;)s.push(0);for(n=m;--n>=0;){for(e=0,o=d+n;o>n;)c=s[o]+v[n]*h[o-n-1]+e,s[o--]=c%re|0,e=c/re|0;s[o]=(s[o]+e)%re|0}for(;!s[--r];)s.pop();return e?++t:s.shift(),i.d=s,i.e=ci(s,t),G?U(i,p.precision,p.rounding):i};x.toBinary=function(i,e){return Ki(this,2,i,e)};x.toDecimalPlaces=x.toDP=function(i,e){var t=this,n=t.constructor;return t=new n(t),i===void 0?t:(Gt(i,0,Me),e===void 0?e=n.rounding:Gt(e,0,8),U(t,i+t.e+1,e))};x.toExponential=function(i,e){var t,n=this,o=n.constructor;return i===void 0?t=de(n,!0):(Gt(i,0,Me),e===void 0?e=o.rounding:Gt(e,0,8),n=U(new o(n),i+1,e),t=de(n,!0,i+1)),n.isNeg()&&!n.isZero()?"-"+t:t};x.toFixed=function(i,e){var t,n,o=this,s=o.constructor;return i===void 0?t=de(o):(Gt(i,0,Me),e===void 0?e=s.rounding:Gt(e,0,8),n=U(new s(o),i+o.e+1,e),t=de(n,!1,i+n.e+1)),o.isNeg()&&!o.isZero()?"-"+t:t};x.toFraction=function(i){var e,t,n,o,s,r,c,d,m,f,p,h,v=this,M=v.d,C=v.constructor;if(!M)return new C(v);if(m=t=new C(1),n=d=new C(0),e=new C(n),s=e.e=eo(M)-v.e-1,r=s%X,e.d[0]=Ut(10,r<0?X+r:r),i==null)i=s>0?e:m;else{if(c=new C(i),!c.isInt()||c.lt(m))throw Error(ve+c);i=c.gt(e)?s>0?e:m:c}for(G=!1,c=new C(Kt(M)),f=C.precision,C.precision=s=M.length*X*2;p=et(c,e,0,1,1),o=t.plus(p.times(n)),o.cmp(i)!=1;)t=n,n=o,o=m,m=d.plus(p.times(o)),d=o,o=e,e=c.minus(p.times(o)),c=o;return o=et(i.minus(t),n,0,1,1),d=d.plus(o.times(m)),t=t.plus(o.times(n)),d.s=m.s=v.s,h=et(m,n,s,1).minus(v).abs().cmp(et(d,t,s,1).minus(v).abs())<1?[m,n]:[d,t],C.precision=f,G=!0,h};x.toHexadecimal=x.toHex=function(i,e){return Ki(this,16,i,e)};x.toNearest=function(i,e){var t=this,n=t.constructor;if(t=new n(t),i==null){if(!t.d)return t;i=new n(1),e=n.rounding}else{if(i=new n(i),e===void 0?e=n.rounding:Gt(e,0,8),!t.d)return i.s?t:i;if(!i.d)return i.s&&(i.s=t.s),i}return i.d[0]?(G=!1,t=et(t,i,0,e,1).times(i),G=!0,U(t)):(i.s=t.s,t=i),t};x.toNumber=function(){return+this};x.toOctal=function(i,e){return Ki(this,8,i,e)};x.toPower=x.pow=function(i){var e,t,n,o,s,r,c=this,d=c.constructor,m=+(i=new d(i));if(!c.d||!i.d||!c.d[0]||!i.d[0])return new d(Ut(+c,m));if(c=new d(c),c.eq(1))return c;if(n=d.precision,s=d.rounding,i.eq(1))return U(c,n,s);if(e=zt(i.e/X),e>=i.d.length-1&&(t=m<0?-m:m)<=Jo)return o=io(d,c,t,n),i.s<0?new d(1).div(o):U(o,n,s);if(r=c.s,r<0){if(e<i.d.length-1)return new d(NaN);if(!(i.d[e]&1)&&(r=1),c.e==0&&c.d[0]==1&&c.d.length==1)return c.s=r,c}return t=Ut(+c,m),e=t==0||!isFinite(t)?zt(m*(Math.log("0."+Kt(c.d))/Math.LN10+c.e+1)):new d(t+"").e,e>d.maxE+1||e<d.minE-1?new d(e>0?r/0:0):(G=!1,d.rounding=c.s=1,t=Math.min(12,(e+"").length),o=$i(i.times(ye(c,n+t)),n),o.d&&(o=U(o,n+5,1),Re(o.d,n,s)&&(e=n+10,o=U($i(i.times(ye(c,e+t)),e),e+5,1),+Kt(o.d).slice(n+1,n+15)+1==1e14&&(o=U(o,n+1,0)))),o.s=r,G=!0,d.rounding=s,U(o,n,s))};x.toPrecision=function(i,e){var t,n=this,o=n.constructor;return i===void 0?t=de(n,n.e<=o.toExpNeg||n.e>=o.toExpPos):(Gt(i,1,Me),e===void 0?e=o.rounding:Gt(e,0,8),n=U(new o(n),i,e),t=de(n,i<=n.e||n.e<=o.toExpNeg,i)),n.isNeg()&&!n.isZero()?"-"+t:t};x.toSignificantDigits=x.toSD=function(i,e){var t=this,n=t.constructor;return i===void 0?(i=n.precision,e=n.rounding):(Gt(i,1,Me),e===void 0?e=n.rounding:Gt(e,0,8)),U(new n(t),i,e)};x.toString=function(){var i=this,e=i.constructor,t=de(i,i.e<=e.toExpNeg||i.e>=e.toExpPos);return i.isNeg()&&!i.isZero()?"-"+t:t};x.truncated=x.trunc=function(){return U(new this.constructor(this),this.e+1,1)};x.valueOf=x.toJSON=function(){var i=this,e=i.constructor,t=de(i,i.e<=e.toExpNeg||i.e>=e.toExpPos);return i.isNeg()?"-"+t:t};function Kt(i){var e,t,n,o=i.length-1,s="",r=i[0];if(o>0){for(s+=r,e=1;e<o;e++)n=i[e]+"",t=X-n.length,t&&(s+=we(t)),s+=n;r=i[e],n=r+"",t=X-n.length,t&&(s+=we(t))}else if(r===0)return"0";for(;r%10===0;)r/=10;return s+r}function Gt(i,e,t){if(i!==~~i||i<e||i>t)throw Error(ve+i)}function Re(i,e,t,n){var o,s,r,c;for(s=i[0];s>=10;s/=10)--e;return--e<0?(e+=X,o=0):(o=Math.ceil((e+1)/X),e%=X),s=Ut(10,X-e),c=i[o]%s|0,n==null?e<3?(e==0?c=c/100|0:e==1&&(c=c/10|0),r=t<4&&c==99999||t>3&&c==49999||c==5e4||c==0):r=(t<4&&c+1==s||t>3&&c+1==s/2)&&(i[o+1]/s/100|0)==Ut(10,e-2)-1||(c==s/2||c==0)&&(i[o+1]/s/100|0)==0:e<4?(e==0?c=c/1e3|0:e==1?c=c/100|0:e==2&&(c=c/10|0),r=(n||t<4)&&c==9999||!n&&t>3&&c==4999):r=((n||t<4)&&c+1==s||!n&&t>3&&c+1==s/2)&&(i[o+1]/s/1e3|0)==Ut(10,e-3)-1,r}function ii(i,e,t){for(var n,o=[0],s,r=0,c=i.length;r<c;){for(s=o.length;s--;)o[s]*=e;for(o[0]+=Ri.indexOf(i.charAt(r++)),n=0;n<o.length;n++)o[n]>t-1&&(o[n+1]===void 0&&(o[n+1]=0),o[n+1]+=o[n]/t|0,o[n]%=t)}return o.reverse()}function tr(i,e){var t,n,o;if(e.isZero())return e;n=e.d.length,n<32?(t=Math.ceil(n/3),o=(1/li(4,t)).toString()):(t=16,o="2.3283064365386962890625e-10"),i.precision+=t,e=Te(i,1,e.times(o),new i(1));for(var s=t;s--;){var r=e.times(e);e=r.times(r).minus(r).times(8).plus(1)}return i.precision-=t,e}var et=function(){function i(n,o,s){var r,c=0,d=n.length;for(n=n.slice();d--;)r=n[d]*o+c,n[d]=r%s|0,c=r/s|0;return c&&n.unshift(c),n}function e(n,o,s,r){var c,d;if(s!=r)d=s>r?1:-1;else for(c=d=0;c<s;c++)if(n[c]!=o[c]){d=n[c]>o[c]?1:-1;break}return d}function t(n,o,s,r){for(var c=0;s--;)n[s]-=c,c=n[s]<o[s]?1:0,n[s]=c*r+n[s]-o[s];for(;!n[0]&&n.length>1;)n.shift()}return function(n,o,s,r,c,d){var m,f,p,h,v,M,C,A,D,V,O,B,T,E,N,F,I,W,j,Q,$=n.constructor,K=n.s==o.s?1:-1,a=n.d,u=o.d;if(!a||!a[0]||!u||!u[0])return new $(!n.s||!o.s||(a?u&&a[0]==u[0]:!u)?NaN:a&&a[0]==0||!u?K*0:K/0);for(d?(v=1,f=n.e-o.e):(d=re,v=X,f=zt(n.e/v)-zt(o.e/v)),j=u.length,I=a.length,D=new $(K),V=D.d=[],p=0;u[p]==(a[p]||0);p++);if(u[p]>(a[p]||0)&&f--,s==null?(E=s=$.precision,r=$.rounding):c?E=s+(n.e-o.e)+1:E=s,E<0)V.push(1),M=!0;else{if(E=E/v+2|0,p=0,j==1){for(h=0,u=u[0],E++;(p<I||h)&&E--;p++)N=h*d+(a[p]||0),V[p]=N/u|0,h=N%u|0;M=h||p<I}else{for(h=d/(u[0]+1)|0,h>1&&(u=i(u,h,d),a=i(a,h,d),j=u.length,I=a.length),F=j,O=a.slice(0,j),B=O.length;B<j;)O[B++]=0;Q=u.slice(),Q.unshift(0),W=u[0],u[1]>=d/2&&++W;do h=0,m=e(u,O,j,B),m<0?(T=O[0],j!=B&&(T=T*d+(O[1]||0)),h=T/W|0,h>1?(h>=d&&(h=d-1),C=i(u,h,d),A=C.length,B=O.length,m=e(C,O,A,B),m==1&&(h--,t(C,j<A?Q:u,A,d))):(h==0&&(m=h=1),C=u.slice()),A=C.length,A<B&&C.unshift(0),t(O,C,B,d),m==-1&&(B=O.length,m=e(u,O,j,B),m<1&&(h++,t(O,j<B?Q:u,B,d))),B=O.length):m===0&&(h++,O=[0]),V[p++]=h,m&&O[0]?O[B++]=a[F]||0:(O=[a[F]],B=1);while((F++<I||O[0]!==void 0)&&E--);M=O[0]!==void 0}V[0]||V.shift()}if(v==1)D.e=f,Hn=M;else{for(p=1,h=V[0];h>=10;h/=10)p++;D.e=p+f*v-1,U(D,c?s+D.e+1:s,r,M)}return D}}();function U(i,e,t,n){var o,s,r,c,d,m,f,p,h,v=i.constructor;t:if(e!=null){if(p=i.d,!p)return i;for(o=1,c=p[0];c>=10;c/=10)o++;if(s=e-o,s<0)s+=X,r=e,f=p[h=0],d=f/Ut(10,o-r-1)%10|0;else if(h=Math.ceil((s+1)/X),c=p.length,h>=c)if(n){for(;c++<=h;)p.push(0);f=d=0,o=1,s%=X,r=s-X+1}else break t;else{for(f=c=p[h],o=1;c>=10;c/=10)o++;s%=X,r=s-X+o,d=r<0?0:f/Ut(10,o-r-1)%10|0}if(n=n||e<0||p[h+1]!==void 0||(r<0?f:f%Ut(10,o-r-1)),m=t<4?(d||n)&&(t==0||t==(i.s<0?3:2)):d>5||d==5&&(t==4||n||t==6&&(s>0?r>0?f/Ut(10,o-r):0:p[h-1])%10&1||t==(i.s<0?8:7)),e<1||!p[0])return p.length=0,m?(e-=i.e+1,p[0]=Ut(10,(X-e%X)%X),i.e=-e||0):p[0]=i.e=0,i;if(s==0?(p.length=h,c=1,h--):(p.length=h+1,c=Ut(10,X-s),p[h]=r>0?(f/Ut(10,o-r)%Ut(10,r)|0)*c:0),m)for(;;)if(h==0){for(s=1,r=p[0];r>=10;r/=10)s++;for(r=p[0]+=c,c=1;r>=10;r/=10)c++;s!=c&&(i.e++,p[0]==re&&(p[0]=1));break}else{if(p[h]+=c,p[h]!=re)break;p[h--]=0,c=1}for(s=p.length;p[--s]===0;)p.pop()}return G&&(i.e>v.maxE?(i.d=null,i.e=NaN):i.e<v.minE&&(i.e=0,i.d=[0])),i}function de(i,e,t){if(!i.isFinite())return oo(i);var n,o=i.e,s=Kt(i.d),r=s.length;return e?(t&&(n=t-r)>0?s=s.charAt(0)+"."+s.slice(1)+we(n):r>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(i.e<0?"e":"e+")+i.e):o<0?(s="0."+we(-o-1)+s,t&&(n=t-r)>0&&(s+=we(n))):o>=r?(s+=we(o+1-r),t&&(n=t-o-1)>0&&(s=s+"."+we(n))):((n=o+1)<r&&(s=s.slice(0,n)+"."+s.slice(n)),t&&(n=t-r)>0&&(o+1===r&&(s+="."),s+=we(n))),s}function ci(i,e){var t=i[0];for(e*=X;t>=10;t/=10)e++;return e}function si(i,e,t){if(e>Yo)throw G=!0,t&&(i.precision=t),Error(Qn);return U(new i(oi),e,1,!0)}function ue(i,e,t){if(e>Ui)throw Error(Qn);return U(new i(ri),e,t,!0)}function eo(i){var e=i.length-1,t=e*X+1;if(e=i[e],e){for(;e%10==0;e/=10)t--;for(e=i[0];e>=10;e/=10)t++}return t}function we(i){for(var e="";i--;)e+="0";return e}function io(i,e,t,n){var o,s=new i(1),r=Math.ceil(n/X+4);for(G=!1;;){if(t%2&&(s=s.times(e),Rn(s.d,r)&&(o=!0)),t=zt(t/2),t===0){t=s.d.length-1,o&&s.d[t]===0&&++s.d[t];break}e=e.times(e),Rn(e.d,r)}return G=!0,s}function qn(i){return i.d[i.d.length-1]&1}function no(i,e,t){for(var n,o,s=new i(e[0]),r=0;++r<e.length;){if(o=new i(e[r]),!o.s){s=o;break}n=s.cmp(o),(n===t||n===0&&s.s===t)&&(s=o)}return s}function $i(i,e){var t,n,o,s,r,c,d,m=0,f=0,p=0,h=i.constructor,v=h.rounding,M=h.precision;if(!i.d||!i.d[0]||i.e>17)return new h(i.d?i.d[0]?i.s<0?0:1/0:1:i.s?i.s<0?0:i:NaN);for(e==null?(G=!1,d=M):d=e,c=new h(.03125);i.e>-2;)i=i.times(c),p+=5;for(n=Math.log(Ut(2,p))/Math.LN10*2+5|0,d+=n,t=s=r=new h(1),h.precision=d;;){if(s=U(s.times(i),d,1),t=t.times(++f),c=r.plus(et(s,t,d,1)),Kt(c.d).slice(0,d)===Kt(r.d).slice(0,d)){for(o=p;o--;)r=U(r.times(r),d,1);if(e==null)if(m<3&&Re(r.d,d-n,v,m))h.precision=d+=10,t=s=c=new h(1),f=0,m++;else return U(r,h.precision=M,v,G=!0);else return h.precision=M,r}r=c}}function ye(i,e){var t,n,o,s,r,c,d,m,f,p,h,v=1,M=10,C=i,A=C.d,D=C.constructor,V=D.rounding,O=D.precision;if(C.s<0||!A||!A[0]||!C.e&&A[0]==1&&A.length==1)return new D(A&&!A[0]?-1/0:C.s!=1?NaN:A?0:C);if(e==null?(G=!1,f=O):f=e,D.precision=f+=M,t=Kt(A),n=t.charAt(0),Math.abs(s=C.e)<15e14){for(;n<7&&n!=1||n==1&&t.charAt(1)>3;)C=C.times(i),t=Kt(C.d),n=t.charAt(0),v++;s=C.e,n>1?(C=new D("0."+t),s++):C=new D(n+"."+t.slice(1))}else return m=si(D,f+2,O).times(s+""),C=ye(new D(n+"."+t.slice(1)),f-M).plus(m),D.precision=O,e==null?U(C,O,V,G=!0):C;for(p=C,d=r=C=et(C.minus(1),C.plus(1),f,1),h=U(C.times(C),f,1),o=3;;){if(r=U(r.times(h),f,1),m=d.plus(et(r,new D(o),f,1)),Kt(m.d).slice(0,f)===Kt(d.d).slice(0,f))if(d=d.times(2),s!==0&&(d=d.plus(si(D,f+2,O).times(s+""))),d=et(d,new D(v),f,1),e==null)if(Re(d.d,f-M,V,c))D.precision=f+=M,m=r=C=et(p.minus(1),p.plus(1),f,1),h=U(C.times(C),f,1),o=c=1;else return U(d,D.precision=O,V,G=!0);else return D.precision=O,d;d=m,o+=2}}function oo(i){return String(i.s*i.s/0)}function ni(i,e){var t,n,o;for((t=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(t<0&&(t=n),t+=+e.slice(n+1),e=e.substring(0,n)):t<0&&(t=e.length),n=0;e.charCodeAt(n)===48;n++);for(o=e.length;e.charCodeAt(o-1)===48;--o);if(e=e.slice(n,o),e){if(o-=n,i.e=t=t-n-1,i.d=[],n=(t+1)%X,t<0&&(n+=X),n<o){for(n&&i.d.push(+e.slice(0,n)),o-=X;n<o;)i.d.push(+e.slice(n,n+=X));e=e.slice(n),n=X-e.length}else n-=o;for(;n--;)e+="0";i.d.push(+e),G&&(i.e>i.constructor.maxE?(i.d=null,i.e=NaN):i.e<i.constructor.minE&&(i.e=0,i.d=[0]))}else i.e=0,i.d=[0];return i}function er(i,e){var t,n,o,s,r,c,d,m,f;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),to.test(e))return ni(i,e)}else if(e==="Infinity"||e==="NaN")return+e||(i.s=NaN),i.e=NaN,i.d=null,i;if(Ho.test(e))t=16,e=e.toLowerCase();else if(Go.test(e))t=2;else if(Qo.test(e))t=8;else throw Error(ve+e);for(s=e.search(/p/i),s>0?(d=+e.slice(s+1),e=e.substring(2,s)):e=e.slice(2),s=e.indexOf("."),r=s>=0,n=i.constructor,r&&(e=e.replace(".",""),c=e.length,s=c-s,o=io(n,new n(t),s,s*2)),m=ii(e,t,re),f=m.length-1,s=f;m[s]===0;--s)m.pop();return s<0?new n(i.s*0):(i.e=ci(m,f),i.d=m,G=!1,r&&(i=et(i,o,c*4)),d&&(i=i.times(Math.abs(d)<54?Ut(2,d):$e.pow(2,d))),G=!0,i)}function ir(i,e){var t,n=e.d.length;if(n<3)return e.isZero()?e:Te(i,2,e,e);t=1.4*Math.sqrt(n),t=t>16?16:t|0,e=e.times(1/li(5,t)),e=Te(i,2,e,e);for(var o,s=new i(5),r=new i(16),c=new i(20);t--;)o=e.times(e),e=e.times(s.plus(o.times(r.times(o).minus(c))));return e}function Te(i,e,t,n,o){var s,r,c,d,m=1,f=i.precision,p=Math.ceil(f/X);for(G=!1,d=t.times(t),c=new i(n);;){if(r=et(c.times(d),new i(e++*e++),f,1),c=o?n.plus(r):n.minus(r),n=et(r.times(d),new i(e++*e++),f,1),r=c.plus(n),r.d[p]!==void 0){for(s=p;r.d[s]===c.d[s]&&s--;);if(s==-1)break}s=c,c=n,n=r,r=s,m++}return G=!0,r.d.length=p+1,r}function li(i,e){for(var t=i;--e;)t*=i;return t}function ro(i,e){var t,n=e.s<0,o=ue(i,i.precision,1),s=o.times(.5);if(e=e.abs(),e.lte(s))return pe=n?4:1,e;if(t=e.divToInt(o),t.isZero())pe=n?3:2;else{if(e=e.minus(t.times(o)),e.lte(s))return pe=qn(t)?n?2:3:n?4:1,e;pe=qn(t)?n?1:4:n?3:2}return e.minus(o).abs()}function Ki(i,e,t,n){var o,s,r,c,d,m,f,p,h,v=i.constructor,M=t!==void 0;if(M?(Gt(t,1,Me),n===void 0?n=v.rounding:Gt(n,0,8)):(t=v.precision,n=v.rounding),!i.isFinite())f=oo(i);else{for(f=de(i),r=f.indexOf("."),M?(o=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):o=e,r>=0&&(f=f.replace(".",""),h=new v(1),h.e=f.length-r,h.d=ii(de(h),10,o),h.e=h.d.length),p=ii(f,10,o),s=d=p.length;p[--d]==0;)p.pop();if(!p[0])f=M?"0p+0":"0";else{if(r<0?s--:(i=new v(i),i.d=p,i.e=s,i=et(i,h,t,n,0,o),p=i.d,s=i.e,m=Hn),r=p[t],c=o/2,m=m||p[t+1]!==void 0,m=n<4?(r!==void 0||m)&&(n===0||n===(i.s<0?3:2)):r>c||r===c&&(n===4||m||n===6&&p[t-1]&1||n===(i.s<0?8:7)),p.length=t,m)for(;++p[--t]>o-1;)p[t]=0,t||(++s,p.unshift(1));for(d=p.length;!p[d-1];--d);for(r=0,f="";r<d;r++)f+=Ri.charAt(p[r]);if(M){if(d>1)if(e==16||e==8){for(r=e==16?4:3,--d;d%r;d++)f+="0";for(p=ii(f,o,e),d=p.length;!p[d-1];--d);for(r=1,f="1.";r<d;r++)f+=Ri.charAt(p[r])}else f=f.charAt(0)+"."+f.slice(1);f=f+(s<0?"p":"p+")+s}else if(s<0){for(;++s;)f="0"+f;f="0."+f}else if(++s>d)for(s-=d;s--;)f+="0";else s<d&&(f=f.slice(0,s)+"."+f.slice(s))}f=(e==16?"0x":e==2?"0b":e==8?"0o":"")+f}return i.s<0?"-"+f:f}function Rn(i,e){if(i.length>e)return i.length=e,!0}function nr(i){return new this(i).abs()}function or(i){return new this(i).acos()}function rr(i){return new this(i).acosh()}function sr(i,e){return new this(i).plus(e)}function ar(i){return new this(i).asin()}function cr(i){return new this(i).asinh()}function lr(i){return new this(i).atan()}function ur(i){return new this(i).atanh()}function dr(i,e){i=new this(i),e=new this(e);var t,n=this.precision,o=this.rounding,s=n+4;return!i.s||!e.s?t=new this(NaN):!i.d&&!e.d?(t=ue(this,s,1).times(e.s>0?.25:.75),t.s=i.s):!e.d||i.isZero()?(t=e.s<0?ue(this,n,o):new this(0),t.s=i.s):!i.d||e.isZero()?(t=ue(this,s,1).times(.5),t.s=i.s):e.s<0?(this.precision=s,this.rounding=1,t=this.atan(et(i,e,s,1)),e=ue(this,s,1),this.precision=n,this.rounding=o,t=i.s<0?t.minus(e):t.plus(e)):t=this.atan(et(i,e,s,1)),t}function mr(i){return new this(i).cbrt()}function _r(i){return U(i=new this(i),i.e+1,2)}function fr(i,e,t){return new this(i).clamp(e,t)}function pr(i){if(!i||typeof i!="object")throw Error(ai+"Object expected");var e,t,n,o=i.defaults===!0,s=["precision",1,Me,"rounding",0,8,"toExpNeg",-Be,0,"toExpPos",0,Be,"maxE",0,Be,"minE",-Be,0,"modulo",0,9];for(e=0;e<s.length;e+=3)if(t=s[e],o&&(this[t]=Ni[t]),(n=i[t])!==void 0)if(zt(n)===n&&n>=s[e+1]&&n<=s[e+2])this[t]=n;else throw Error(ve+t+": "+n);if(t="crypto",o&&(this[t]=Ni[t]),(n=i[t])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(Jn);else this[t]=!1;else throw Error(ve+t+": "+n);return this}function hr(i){return new this(i).cos()}function gr(i){return new this(i).cosh()}function so(i){var e,t,n;function o(s){var r,c,d,m=this;if(!(m instanceof o))return new o(s);if(m.constructor=o,Nn(s)){m.s=s.s,G?!s.d||s.e>o.maxE?(m.e=NaN,m.d=null):s.e<o.minE?(m.e=0,m.d=[0]):(m.e=s.e,m.d=s.d.slice()):(m.e=s.e,m.d=s.d?s.d.slice():s.d);return}if(d=typeof s,d==="number"){if(s===0){m.s=1/s<0?-1:1,m.e=0,m.d=[0];return}if(s<0?(s=-s,m.s=-1):m.s=1,s===~~s&&s<1e7){for(r=0,c=s;c>=10;c/=10)r++;G?r>o.maxE?(m.e=NaN,m.d=null):r<o.minE?(m.e=0,m.d=[0]):(m.e=r,m.d=[s]):(m.e=r,m.d=[s]);return}if(s*0!==0){s||(m.s=NaN),m.e=NaN,m.d=null;return}return ni(m,s.toString())}if(d==="string")return(c=s.charCodeAt(0))===45?(s=s.slice(1),m.s=-1):(c===43&&(s=s.slice(1)),m.s=1),to.test(s)?ni(m,s):er(m,s);if(d==="bigint")return s<0?(s=-s,m.s=-1):m.s=1,ni(m,s.toString());throw Error(ve+s)}if(o.prototype=x,o.ROUND_UP=0,o.ROUND_DOWN=1,o.ROUND_CEIL=2,o.ROUND_FLOOR=3,o.ROUND_HALF_UP=4,o.ROUND_HALF_DOWN=5,o.ROUND_HALF_EVEN=6,o.ROUND_HALF_CEIL=7,o.ROUND_HALF_FLOOR=8,o.EUCLID=9,o.config=o.set=pr,o.clone=so,o.isDecimal=Nn,o.abs=nr,o.acos=or,o.acosh=rr,o.add=sr,o.asin=ar,o.asinh=cr,o.atan=lr,o.atanh=ur,o.atan2=dr,o.cbrt=mr,o.ceil=_r,o.clamp=fr,o.cos=hr,o.cosh=gr,o.div=br,o.exp=wr,o.floor=yr,o.hypot=vr,o.ln=Mr,o.log=Cr,o.log10=kr,o.log2=Pr,o.max=Sr,o.min=Ar,o.mod=Or,o.mul=Vr,o.pow=Dr,o.random=xr,o.round=Br,o.sign=Tr,o.sin=Er,o.sinh=Fr,o.sqrt=jr,o.sub=Ir,o.sum=Lr,o.tan=qr,o.tanh=Rr,o.trunc=Nr,i===void 0&&(i={}),i&&i.defaults!==!0)for(n=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<n.length;)i.hasOwnProperty(t=n[e++])||(i[t]=this[t]);return o.config(i),o}function br(i,e){return new this(i).div(e)}function wr(i){return new this(i).exp()}function yr(i){return U(i=new this(i),i.e+1,3)}function vr(){var i,e,t=new this(0);for(G=!1,i=0;i<arguments.length;)if(e=new this(arguments[i++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return G=!0,new this(1/0);t=e}return G=!0,t.sqrt()}function Nn(i){return i instanceof $e||i&&i.toStringTag===Yn||!1}function Mr(i){return new this(i).ln()}function Cr(i,e){return new this(i).log(e)}function Pr(i){return new this(i).log(2)}function kr(i){return new this(i).log(10)}function Sr(){return no(this,arguments,-1)}function Ar(){return no(this,arguments,1)}function Or(i,e){return new this(i).mod(e)}function Vr(i,e){return new this(i).mul(e)}function Dr(i,e){return new this(i).pow(e)}function xr(i){var e,t,n,o,s=0,r=new this(1),c=[];if(i===void 0?i=this.precision:Gt(i,1,Me),n=Math.ceil(i/X),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(n));s<n;)o=e[s],o>=429e7?e[s]=crypto.getRandomValues(new Uint32Array(1))[0]:c[s++]=o%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(n*=4);s<n;)o=e[s]+(e[s+1]<<8)+(e[s+2]<<16)+((e[s+3]&127)<<24),o>=214e7?crypto.randomBytes(4).copy(e,s):(c.push(o%1e7),s+=4);s=n/4}else throw Error(Jn);else for(;s<n;)c[s++]=Math.random()*1e7|0;for(n=c[--s],i%=X,n&&i&&(o=Ut(10,X-i),c[s]=(n/o|0)*o);c[s]===0;s--)c.pop();if(s<0)t=0,c=[0];else{for(t=-1;c[0]===0;t-=X)c.shift();for(n=1,o=c[0];o>=10;o/=10)n++;n<X&&(t-=X-n)}return r.e=t,r.d=c,r}function Br(i){return U(i=new this(i),i.e+1,this.rounding)}function Tr(i){return i=new this(i),i.d?i.d[0]?i.s:0*i.s:i.s||NaN}function Er(i){return new this(i).sin()}function Fr(i){return new this(i).sinh()}function jr(i){return new this(i).sqrt()}function Ir(i,e){return new this(i).sub(e)}function Lr(){var i=0,e=arguments,t=new this(e[i]);for(G=!1;t.s&&++i<e.length;)t=t.plus(e[i]);return G=!0,U(t,this.precision,this.rounding)}function qr(i){return new this(i).tan()}function Rr(i){return new this(i).tanh()}function Nr(i){return U(i=new this(i),i.e+1,1)}x[Symbol.for("nodejs.util.inspect.custom")]=x.toString;x[Symbol.toStringTag]="Decimal";var $e=x.constructor=so(Ni);oi=new $e(oi);ri=new $e(ri);var ne=$e;function S(i){return ne.isDecimal(i)?i:new ne(i===void 0?0:i)}function ao(i){return S(10).pow(S(i).abs())}function Qt(i,e,t=ne.ROUND_DOWN){let n=ao(S(e));return S(i).mul(n).toFixed(0,t).toString()}function me(i,e=32){return Number(BigInt.asIntN(e,BigInt(i)))}function ee(i,e){let t=ao(S(e));return S(i).div(t).toString()}var co="0x2::sui::SUI",Ur="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";var Jt=class Rt{static totalBalance(e,t){let n=BigInt(0);return e.forEach(o=>{t===o.coin_type&&(n+=BigInt(o.balance))}),n}static getCoinAssets(e,t){let n=[];return t.forEach(o=>{$n(o.coin_type)===$n(e)&&n.push(o)}),n}static isSuiCoin(e){return se(e).full_address===co}static selectCoinObjectIdGreaterThanOrEqual(e,t,n=[]){let o=Rt.selectCoinAssetGreaterThanOrEqual(e,t,n),s=o.selected_coins.map(d=>d.coin_object_id),r=o.remain_coins,c=o.selected_coins.map(d=>d.balance.toString());return{object_array:s,remain_coins:r,amount_array:c}}static selectCoinAssetGreaterThanOrEqual(e,t,n=[]){let o=Rt.sortByBalance(e.filter(m=>!n.includes(m.coin_object_id))),s=Rt.calculateTotalBalance(o);if(s<t)return{selected_coins:[],remain_coins:o};if(s===t)return{selected_coins:o,remain_coins:[]};let r=BigInt(0),c=[],d=[...o];for(;r<s;){let m=t-r,f=d.findIndex(h=>h.balance>=m);if(f!==-1){c.push(d[f]),d.splice(f,1);break}let p=d.pop();p.balance>0&&(c.push(p),r+=p.balance)}return{selected_coins:Rt.sortByBalance(c),remain_coins:Rt.sortByBalance(d)}}static sortByBalance(e){return e.sort((t,n)=>t.balance<n.balance?-1:t.balance>n.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,n)=>t.balance>n.balance?-1:t.balance<n.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,n)=>t+n.balance,BigInt(0))}static buildCoinForAmount(e,t,n,o,s=!0,r=!0){let c=Rt.getCoinAssets(o,t);if(n===BigInt(0))return this.buildZeroValueCoin(t,e,o,s);let d=Rt.calculateTotalBalance(c);if(d<n)throw new Error(`The amount(${d}) is Insufficient balance for ${o} , expect ${n} `);return this.buildCoin(e,t,c,n,o,s,r)}static buildCoinWithBalance(e,t,n){return e===BigInt(0)&&Rt.isSuiCoin(t)?n.add((0,qi.coinWithBalance)({balance:e,useGasCoin:!1})):n.add((0,qi.coinWithBalance)({balance:e,type:t}))}static buildVectorCoin(e,t,n,o,s,r=!0){if(Rt.isSuiCoin(s)){let h=e.splitCoins(e.gas,[e.pure.u64(o)]);return{selected_coins:[],target_coin:h,remain_coins:t,target_coin_amount:o.toString(),is_mint_zero_coin:!1,original_spited_coin:e.gas}}let{original_spited_coin:c,target_coin:d,target_coin_amount:m,remain_coins:f,selected_coins:p}=this.buildSpitTargeCoin(e,o,n,r);return r?{target_coin:e.makeMoveVec({elements:[d]}),selected_coins:p,remain_coins:f,target_coin_amount:m,is_mint_zero_coin:!1,original_spited_coin:c}:{selected_coins:p,target_coin:e.makeMoveVec({elements:p.map(h=>e.object(h))}),remain_coins:f,target_coin_amount:m,is_mint_zero_coin:!1}}static buildOneCoin(e,t,n,o,s=!0){if(Rt.isSuiCoin(o)){if(n===0n&&t.length>1){let d=Rt.selectCoinObjectIdGreaterThanOrEqual(t,n);return{selected_coins:d.object_array,target_coin:e.object(d.object_array[0]),remain_coins:d.remain_coins,target_coin_amount:d.amount_array[0],is_mint_zero_coin:!1}}let r=Rt.selectCoinObjectIdGreaterThanOrEqual(t,n),c=e.splitCoins(e.gas,[e.pure.u64(n)]);return{selected_coins:[],target_coin:c,remain_coins:r.remain_coins,target_coin_amount:n.toString(),is_mint_zero_coin:!1,original_spited_coin:e.gas}}return this.buildSpitTargeCoin(e,n,t,s)}static buildSpitTargeCoin(e,t,n,o){let s=Rt.selectCoinObjectIdGreaterThanOrEqual(n,t),r=s.amount_array.reduce((M,C)=>Number(M)+Number(C),0).toString(),c=s.object_array,[d,...m]=c,f=e.object(d),p=f,h=s.amount_array.reduce((M,C)=>Number(M)+Number(C),0).toString(),v;return m.length>0&&e.mergeCoins(f,m.map(M=>e.object(M))),o&&Number(r)>Number(t)&&(p=e.splitCoins(f,[e.pure.u64(t)]),v=f),{original_spited_coin:v,target_coin:p,target_coin_amount:h,remain_coins:s.remain_coins,selected_coins:s.object_array,is_mint_zero_coin:!1}}static buildCoin(e,t,n,o,s,r=!0,c=!0){return r?this.buildVectorCoin(e,t,n,o,s,c):this.buildOneCoin(e,n,o,s,c)}static buildZeroValueCoin(e,t,n,o=!0){let s=this.callMintZeroValueCoin(t,n),r;return o?r=t.makeMoveVec({elements:[s]}):r=s,{target_coin:r,remain_coins:e,selected_coins:[],is_mint_zero_coin:!0,target_coin_amount:"0"}}static buildCoinForAmountInterval(e,t,n,o,s=!0,r=!0){let c=Rt.getCoinAssets(o,t);if(n.amount_first===BigInt(0))return c.length>0?this.buildCoin(e,[...t],[...c],n.amount_first,o,s,r):this.buildZeroValueCoin(t,e,o,s);let d=Rt.calculateTotalBalance(c);if(d>=n.amount_first)return this.buildCoin(e,[...t],[...c],n.amount_first,o,s,r);if(d<n.amount_second)throw new Error(`The amount(${d}) is Insufficient balance for ${o} , expect ${n.amount_second} `);return this.buildCoin(e,[...t],[...c],n.amount_second,o,s,r)}static{this.callMintZeroValueCoin=(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]})}static fromBalance(e,t,n){return n.moveCall({target:"0x2::coin::from_balance",typeArguments:[t],arguments:[e]})}static intoBalance(e,t,n){return n.moveCall({target:"0x2::coin::into_balance",typeArguments:[t],arguments:[typeof e=="string"?n.object(e):e]})}static mintBalanceZero(e,t){return t.moveCall({target:"0x2::balance::zero",typeArguments:[e],arguments:[]})}static destroyBalanceZero(e,t,n){return n.moveCall({target:"0x2::balance::destroy_zero",typeArguments:[t],arguments:[e]})}static getCoinAmountObjId(e,t){let n=e.amount_coin_array.find(o=>!o.used&&S(o.amount).eq(t)?(o.used=!0,!0):!1);return n?n.coin_object_id:te("CoinNotFound",`Coin not found for ${t} ${e.coin_type}`)}static buildMultiCoinInput(e,t,n,o){let s=Rt.getCoinAssets(n,t);if(Rt.isSuiCoin(n)){let p=e.splitCoins(e.gas,o.map(h=>e.pure.u64(h)));return{amount_coin_array:o.map((h,v)=>({coin_object_id:p[v],amount:h.toString(),used:!1})),coin_type:n,remain_coins:s}}let r=o.reduce((p,h)=>p+h,BigInt(0)),c=Rt.selectCoinObjectIdGreaterThanOrEqual(s,r);if(c.object_array.length===0)return te("InsufficientBalance",`No enough coins for ${n} expect ${r} actual ${Rt.calculateTotalBalance(s)}`);let[d,...m]=c.object_array;m.length>0&&e.mergeCoins(d,[...m]);let f=e.splitCoins(d,o.map(p=>e.pure.u64(p)));return{amount_coin_array:o.map((p,h)=>({coin_object_id:f[h],amount:p.toString(),used:!1})),remain_coins:c.remain_coins,coin_type:n}}};function $r(i){return i.startsWith("0x")?`${i.slice(2)}`:i}function Un(i,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[i,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function se(i){try{let e=i.replace(/\s/g,""),t=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(t){e=e.slice(0,e.indexOf("<"));let s={...se(e),type_arguments:t.map(r=>se(r).source_address)};return s.type_arguments=s.type_arguments.map(r=>Jt.isSuiCoin(r)?r:se(r).source_address),s.source_address=Un(s.full_address,s.type_arguments),s}let n=e.split("::"),o={full_address:e,address:e===co||e===Ur?"0x2":(0,Pe.normalizeSuiObjectId)(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=Un(o.full_address,o.type_arguments),o}catch{return{full_address:i,address:"",module:"",name:"",type_arguments:[],source_address:i}}}function $n(i){return se(i).source_address}var L=(i,e=!0)=>{let t=i.split("::"),n=t.shift(),o=(0,Pe.normalizeSuiObjectId)(n);return e&&(o=$r(o)),`${o}::${t.join("::")}`};var Xr=Ne(Ue()),Kn=443636,Wn=-443636,Gr="79226673515401279992447579055";var Hr="4295048016",Cs=new Xr.default(1e6),Qr=(i=>(i[i.BelowRange=0]="BelowRange",i[i.InRange=1]="InRange",i[i.AboveRange=2]="AboveRange",i))(Qr||{}),rt="0x0000000000000000000000000000000000000000000000000000000000000006";var Ps=(0,Wi.getFullnodeUrl)("mainnet"),ks=(0,Wi.getFullnodeUrl)("testnet");var Nt=Ne(Ue()),fe=new Nt.default(0),qe=new Nt.default(1),ui=new Nt.default(2),Jr=ui.pow(new Nt.default(128)),Zn=ui.pow(new Nt.default(64)).sub(qe),Yr=ui.pow(new Nt.default(128)).sub(qe),oe=class{static toX64BN(i){return i.mul(new Nt.default(2).pow(new Nt.default(64)))}static toX64Decimal(i){return i.mul(ne.pow(2,64))}static toX64(i){return new Nt.default(i.mul(ne.pow(2,64)).floor().toFixed())}static fromX64(i){return new ne(i.toString()).mul(ne.pow(2,-64))}static fromX64Decimal(i){return i.mul(ne.pow(2,-64))}static fromX64BN(i){return i.div(new Nt.default(2).pow(new Nt.default(64)))}static shiftRightRoundUp(i){let e=i.shrn(64);return i.mod(Zn).gt(fe)&&(e=e.add(qe)),e}static divRoundUp(i,e){return i.mod(e).eq(fe)?i.div(e):i.div(e).add(new Nt.default(1))}static subUnderflowU128(i,e){return i.lt(e)?i.sub(e).add(Yr):i.sub(e)}static checkUnsignedSub(i,e){let t=i.sub(e);if(t.isNeg())throw new Error("Unsigned integer sub overflow");return t}static checkMul(i,e,t){let n=i.mul(e);return this.isOverflow(n,t)&&te("MultiplicationOverflow","Multiplication overflow"),n}static checkMulDivFloor(i,e,t,n){t.eq(fe)&&te("DivisionByZero","Divide by zero");let o=i.mul(e).div(t);return this.isOverflow(o,n)&&te("MultiplicationOverflow","Multiplication div overflow"),o}static checkMulDivCeil(i,e,t,n){if(t.eq(fe))throw new Error("Divide by zero");let o=i.mul(e).add(t.sub(qe)).div(t);if(this.isOverflow(o,n))throw new Error("Multiplication div overflow");return o}static checkMulDivRound(i,e,t,n){t.eq(fe)&&te("DivisionByZero","Divide by zero");let o=i.mul(e.add(t.shrn(1))).div(t);return this.isOverflow(o,n)&&te("MultiplicationOverflow","Multiplication div overflow"),o}static checkMulShiftRight(i,e,t,n){let o=i.mul(e).div(new Nt.default(2).pow(new Nt.default(t)));return this.isOverflow(o,n)&&te("MultiplicationOverflow","Multiplication shift right overflow"),o}static checkMulShiftRight64RoundUpIf(i,e,t,n){let o=i.mul(e),s=n&&o.and(Zn).gt(fe)?o.shrn(64).add(qe):o.shrn(64);return this.isOverflow(s,t)&&te("MultiplicationOverflow","Multiplication shift right overflow"),s}static checkMulShiftLeft(i,e,t,n){let o=i.mul(e).shln(t);return this.isOverflow(o,n)&&te("MultiplicationOverflow","Multiplication shift left overflow"),o}static checkDivRoundUpIf(i,e,t){return e.eq(fe)&&te("DivisionByZero","Divide by zero"),t?this.divRoundUp(i,e):i.div(e)}static isOverflow(i,e){return i.gte(ui.pow(new Nt.default(e)))}static sign(i){return i.testn(127)?1:0}static is_neg(i){return this.sign(i)===1}static abs_u128(i){return i.gt(fe)?i:this.u128Neg(i.subn(1))}static u128Neg(i){return i.uxor(new Nt.default("ffffffffffffffffffffffffffffffff",16))}static neg(i){return this.is_neg(i)?i.abs():this.negFrom(i)}static abs(i){return this.sign(i)===0?i:this.u128Neg(i.sub(new Nt.default(1)))}static negFrom(i){return i.eq(fe)?i:this.u128Neg(i).add(new Nt.default(1)).or(new Nt.default(1).shln(127))}static u128ToI128(i){return i.testn(127)?Jr.sub(i).neg():i}},Zi=class{static getMinIndex(i){return Wn+Math.abs(Wn)%i}static getMaxIndex(i){return Kn-Kn%i}};function lo(i){return i.data}function ts(i){return i.data!==void 0}function es(i){return i.content!==void 0}function uo(i){let e="data"in i?lo(i):i;if(!(!e||!es(e)||e.content.dataType!=="moveObject"))return e.content}function is(i){return uo(i)?.type}function zi(i){let e=ts(i)?i.data:i;return!e?.type&&"data"in i?e?.content?.dataType==="package"?"package":is(i):e?.type}function di(i){return lo(i)?.previousTransaction}function ae(i){let e=uo(i)?.fields;if(e)return"fields"in e?e.fields:e}ne.config({precision:64,rounding:ne.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var Zt=ne,Ht=Ne(Ue()),z=Ne(Ue()),ns=14,os="59543866431248",rs="184467440737095516",ss="15793534762490258745";function as(i,e,t){let n=i.toTwos(t).shln(e);return n.imaskn(t+1),n.fromTwos(t)}function J(i,e,t){let n=i.toTwos(t).shrn(e);return n.imaskn(t-e+1),n.fromTwos(t-e)}function cs(i){let e;return i&1?e=new z.default("79232123823359799118286999567"):e=new z.default("79228162514264337593543950336"),i&2&&(e=J(e.mul(new z.default("79236085330515764027303304731")),96,256)),i&4&&(e=J(e.mul(new z.default("79244008939048815603706035061")),96,256)),i&8&&(e=J(e.mul(new z.default("79259858533276714757314932305")),96,256)),i&16&&(e=J(e.mul(new z.default("79291567232598584799939703904")),96,256)),i&32&&(e=J(e.mul(new z.default("79355022692464371645785046466")),96,256)),i&64&&(e=J(e.mul(new z.default("79482085999252804386437311141")),96,256)),i&128&&(e=J(e.mul(new z.default("79736823300114093921829183326")),96,256)),i&256&&(e=J(e.mul(new z.default("80248749790819932309965073892")),96,256)),i&512&&(e=J(e.mul(new z.default("81282483887344747381513967011")),96,256)),i&1024&&(e=J(e.mul(new z.default("83390072131320151908154831281")),96,256)),i&2048&&(e=J(e.mul(new z.default("87770609709833776024991924138")),96,256)),i&4096&&(e=J(e.mul(new z.default("97234110755111693312479820773")),96,256)),i&8192&&(e=J(e.mul(new z.default("119332217159966728226237229890")),96,256)),i&16384&&(e=J(e.mul(new z.default("179736315981702064433883588727")),96,256)),i&32768&&(e=J(e.mul(new z.default("407748233172238350107850275304")),96,256)),i&65536&&(e=J(e.mul(new z.default("2098478828474011932436660412517")),96,256)),i&131072&&(e=J(e.mul(new z.default("55581415166113811149459800483533")),96,256)),i&262144&&(e=J(e.mul(new z.default("38992368544603139932233054999993551")),96,256)),J(e,32,256)}function ls(i){let e=Math.abs(i),t;return e&1?t=new z.default("18445821805675392311"):t=new z.default("18446744073709551616"),e&2&&(t=J(t.mul(new z.default("18444899583751176498")),64,256)),e&4&&(t=J(t.mul(new z.default("18443055278223354162")),64,256)),e&8&&(t=J(t.mul(new z.default("18439367220385604838")),64,256)),e&16&&(t=J(t.mul(new z.default("18431993317065449817")),64,256)),e&32&&(t=J(t.mul(new z.default("18417254355718160513")),64,256)),e&64&&(t=J(t.mul(new z.default("18387811781193591352")),64,256)),e&128&&(t=J(t.mul(new z.default("18329067761203520168")),64,256)),e&256&&(t=J(t.mul(new z.default("18212142134806087854")),64,256)),e&512&&(t=J(t.mul(new z.default("17980523815641551639")),64,256)),e&1024&&(t=J(t.mul(new z.default("17526086738831147013")),64,256)),e&2048&&(t=J(t.mul(new z.default("16651378430235024244")),64,256)),e&4096&&(t=J(t.mul(new z.default("15030750278693429944")),64,256)),e&8192&&(t=J(t.mul(new z.default("12247334978882834399")),64,256)),e&16384&&(t=J(t.mul(new z.default("8131365268884726200")),64,256)),e&32768&&(t=J(t.mul(new z.default("3584323654723342297")),64,256)),e&65536&&(t=J(t.mul(new z.default("696457651847595233")),64,256)),e&131072&&(t=J(t.mul(new z.default("26294789957452057")),64,256)),e&262144&&(t=J(t.mul(new z.default("37481735321082")),64,256)),t}var tt=class le{static priceToSqrtPriceX64(e,t,n){return oe.toX64(e.mul(Zt.pow(10,n-t)).sqrt())}static sqrtPriceX64ToPrice(e,t,n){return oe.fromX64(e).pow(2).mul(Zt.pow(10,t-n))}static tickIndexToSqrtPriceX64(e){return e>0?new z.default(cs(e)):new z.default(ls(e))}static sqrtPriceX64ToTickIndex(e){if(e.gt(new z.default(Gr))||e.lt(new z.default(Hr)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let t=e.bitLength()-1,n=new z.default(t-64),o=as(n,32,128),s=new z.default("8000000000000000","hex"),r=0,c=new z.default(0),d=t>=64?e.shrn(t-63):e.shln(63-t);for(;s.gt(new z.default(0))&&r<ns;){d=d.mul(d);let v=d.shrn(127);d=d.shrn(63+v.toNumber()),c=c.add(s.mul(v)),s=s.shrn(1),r+=1}let m=c.shrn(32),f=o.add(m).mul(new z.default(os)),p=J(f.sub(new z.default(rs)),64,128).toNumber(),h=J(f.add(new z.default(ss)),64,128).toNumber();return p===h?p:le.tickIndexToSqrtPriceX64(h).lte(e)?h:p}static tickIndexToPrice(e,t,n){return le.sqrtPriceX64ToPrice(le.tickIndexToSqrtPriceX64(e),t,n)}static priceToTickIndex(e,t,n){return le.sqrtPriceX64ToTickIndex(le.priceToSqrtPriceX64(e,t,n))}static priceToInitializeTickIndex(e,t,n,o){return le.getInitializeTickIndex(le.priceToTickIndex(e,t,n),o)}static getInitializeTickIndex(e,t){return e-e%t}static getNextInitializeTickIndex(e,t){return le.getInitializeTickIndex(e,t)+t}static getPrevInitializeTickIndex(e,t){return le.getInitializeTickIndex(e,t)-t}};function ti(i,e,t){let n=Ht.default.min(i,e),o=Ht.default.max(i,e),s=oe.fromX64BN(t.mul(o).mul(n)),r=o.sub(n);return!s.isZero()&&!r.isZero()?s.div(r):new Ht.default(0)}function ei(i,e,t){let n=Ht.default.min(i,e),o=Ht.default.max(i,e).sub(n);return o.isZero()?new Ht.default(0):t.shln(64).div(o)}var $t=class xe{static getCoinAmountFromLiquidity(e,t,n,o,s){let r=new Zt(e.toString()),c=new Zt(t.toString()),d=new Zt(n.toString()),m=new Zt(o.toString()),f,p;return t.lt(n)?(f=oe.toX64Decimal(r).mul(m.sub(d)).div(d.mul(m)),p=new Zt(0)):t.lt(o)?(f=oe.toX64Decimal(r).mul(m.sub(c)).div(c.mul(m)),p=oe.fromX64Decimal(r.mul(c.sub(d)))):(f=new Zt(0),p=oe.fromX64Decimal(r.mul(m.sub(d)))),s?{coin_amount_a:f.ceil().toString(),coin_amount_b:p.ceil().toString()}:{coin_amount_a:f.floor().toString(),coin_amount_b:p.floor().toString()}}static estLiquidityAndCoinAmountFromOneAmounts(e,t,n,o,s,r,c){let d=tt.sqrtPriceX64ToTickIndex(c),m=tt.tickIndexToSqrtPriceX64(e),f=tt.tickIndexToSqrtPriceX64(t),p;if(d<e){if(!o)throw new Error("lower tick cannot calculate liquidity by coinB");p=ti(m,f,n)}else if(d>t){if(o)throw new Error("upper tick cannot calculate liquidity by coinA");p=ei(f,m,n)}else o?p=ti(c,f,n):p=ei(c,m,n);let h=xe.getCoinAmountFromLiquidity(p,c,m,f,s),v=s?S(h.coin_amount_a.toString()).mul(1+r).toString():S(h.coin_amount_a.toString()).mul(1-r).toString(),M=s?S(h.coin_amount_b.toString()).mul(1+r).toString():S(h.coin_amount_b.toString()).mul(1-r).toString();return{coin_amount_a:h.coin_amount_a,coin_amount_b:h.coin_amount_b,coin_amount_limit_a:s?Zt.ceil(v).toString():Zt.floor(v).toString(),coin_amount_limit_b:s?Zt.ceil(M).toString():Zt.floor(M).toString(),liquidity_amount:p.toString(),fix_amount_a:o}}static estimateLiquidityFromCoinAmounts(e,t,n,o){if(t>n)return te("InvalidTick","lower tick cannot be greater than lower tick",{[Li.METHOD_NAME]:"estimateLiquidityFromCoinAmounts",[Li.REQUEST_PARAMS]:{lower_tick:t,upper_tick:n,token_amount:o}});let s=tt.sqrtPriceX64ToTickIndex(e),r=tt.tickIndexToSqrtPriceX64(t),c=tt.tickIndexToSqrtPriceX64(n);if(s<t)return ti(r,c,new Ht.default(o.coin_amount_a)).toString();if(s>=n)return ei(c,r,new Ht.default(o.coin_amount_b)).toString();let d=ti(e,c,new Ht.default(o.coin_amount_a)),m=ei(e,r,new Ht.default(o.coin_amount_b));return Ht.default.min(d,m).toString()}static calculateDepositRatio(e,t,n){let o=new Ht.default(1e8),{coin_amount_b:s}=xe.estLiquidityAndCoinAmountFromOneAmounts(e,t,o,!0,!0,0,n),r=tt.sqrtPriceX64ToPrice(n,0,0),c=S(o.toString()).mul(r),d=c.add(s.toString()),m=c.div(d),f=S(s.toString()).div(d);return{ratio_a:m,ratio_b:f}}static calculateAmountDepositRatio(e,t,n,o,s){let r=tt.sqrtPriceX64ToPrice(n,o,s),c=tt.sqrtPriceX64ToTickIndex(n);if(c<e)return{ratio_a:new Zt(1),ratio_b:new Zt(0),curr_price:r};if(c>t)return{ratio_a:new Zt(0),ratio_b:new Zt(1),curr_price:r};let d=new Ht.default(Qt(1,o)),{coin_amount_b:m}=xe.estLiquidityAndCoinAmountFromOneAmounts(e,t,d,!0,!0,0,n),f=ee(d.toString(),o),p=ee(m.toString(),s),h=S(f).add(p),v=S(f).div(h),M=S(p).div(h);return{ratio_a:v,ratio_b:M,curr_price:r}}static getCoinAmountsFromRatio(e,t,n,o,s,r,c){let d=S(Qt(S(n).mul(e).div(o).toString(),r)).toFixed(0),m=S(Qt(S(n).mul(t).div(s).toString(),c)).toFixed(0);return{amount_a:d,amount_b:m}}static estCoinAmountsFromTotalAmount(e,t,n,o,s,r,c,d){let{ratio_a:m,ratio_b:f}=xe.calculateDepositRatio(e,t,n);return xe.getCoinAmountsFromRatio(m,f,o,s,r,c,d)}static getPositionStatus(e,t,n){return e<t?0:e<n?1:2}};function ce(i){if(i.config===void 0)throw new Error(`package: ${i.package_id} not config in sdk SdkOptions`);return i.config}var Ss=Ne(Ue());var yn=require("@cetusprotocol/sui-clmm-sdk");var Le=require("@mysten/sui/transactions"),Yt=ie(require("bn.js")),go=require("@cetusprotocol/aggregator-sdk");var bo=require("@mysten/sui/utils"),wo=ie(require("decimal.js"));var Wt=ie(require("bn.js")),_i=ie(require("decimal.js"));var Xi=ie(require("bn.js")),Gi=ie(require("decimal.js")),mi=(i,e,t)=>{if(e==="min"){if(i===Zi.getMinIndex(t))return!0}else if(i===Zi.getMaxIndex(t))return!0;return!1};function us(i){if(i.length!==8)throw new Error("Invalid u64 byte array length");let e=i.map(t=>t.toString(16).padStart(2,"0")).reverse().join("");return BigInt(`0x${e}`).toString()}function mo(i,e,t,n,o){let s=new Xi.default(10).pow(new Xi.default(n)),{coin_amount_b:r}=$t.estLiquidityAndCoinAmountFromOneAmounts(i,e,s,!0,!0,0,t),c=tt.sqrtPriceX64ToPrice(t,n,o),d=S(s.toString()).mul(c).div(new Gi.default(10).pow(n)).mul(new Gi.default(10).pow(o)),m=d.add(r.toString()),f=d.div(m),p=S(r.toString()).div(m);return{ratioA:f,ratioB:p}}function _e(i,e,t,n,o,s,r){let c=S(Qt(S(t).mul(i).div(n).toString(),s)).toFixed(0),d=S(Qt(S(t).mul(e).div(o).toString(),r)).toFixed(0);return{amountA:c,amountB:d}}function Hi(i,e,t,n,o,s,r,c){let{ratioA:d,ratioB:m}=mo(i,e,t,r,c);return _e(d,m,n,o,s,r,c)}var ke=10n;function Se(i){let{fields:e,type:t}=i,{liquidity_range:n,pool_id:o,wrapped_position:s}=e.clmm_vault.fields,r=s.fields,c={clmm_pool_id:o,liquidity_range:{lower_offset:n.fields.lower_offset,rebalance_threshold:n.fields.rebalance_threshold,upper_offset:n.fields.upper_offset},wrapped_position:{coin_type_a:L(r.coin_type_a.fields.name,!1),coin_type_b:L(r.coin_type_b.fields.name,!1),description:r.description,id:r.id.id,index:r.index,liquidity:r.liquidity,name:r.name,pool:r.pool,tick_lower_index:me(BigInt(r.tick_lower_index.fields.bits)),tick_upper_index:me(BigInt(r.tick_upper_index.fields.bits)),url:r.url}},{balances:d}=e.buffer_assets.fields,m=d.fields.contents.map(p=>{let{key:h,value:v}=p.fields;return{coin_type:L(h.fields.name,!1),value:v}});return{id:e.id.id,is_pause:e.is_pause,clmm_vault:c,lp_token_treasury:e.lp_token_treasury.fields.total_supply.fields.value,protocol_fees_handle:e.protocol_fees.fields.id.id,hard_cap:e.hard_cap,quote_type:se(e.quote_type.fields.name).full_address,lp_token_type:se(t).type_arguments[0],balances:m,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function ds(i,e=!0){i.getData().commands.forEach((t,n)=>{})}function Ke(i,e){let t=S(i).div(e).toString(),n=S(e).div(i).toString();return{quote_per_base:t,base_per_quote:n}}function _o(i,e,t,n){let o=10n**(ke+n-t),s=10n**(ke+t-n),r=oe.checkMulDivFloor(new Wt.default(i.toString()),new Wt.default(o.toString()),new Wt.default(e.toString()),64),c=oe.checkMulDivFloor(new Wt.default(e.toString()),new Wt.default(s.toString()),new Wt.default(i.toString()),64);return{primitive_base_price:BigInt(r.toString()),primitive_quote_price:BigInt(c.toString())}}function Ce(i,e){let t=e?i[e].price:{coin_type:"",price:"1",coin_decimals:6,oracle_price:1000000000000000000000000n},n=new Wt.default("0");for(let[o,{price:s,value:r}]of Object.entries(i)){let{primitive_quote_price:c}=_o(BigInt(t.oracle_price),BigInt(s.oracle_price),BigInt(t.coin_decimals),BigInt(s.coin_decimals)),d=oe.checkMulDivFloor(new Wt.default(c.toString()),new Wt.default(r),new Wt.default((BigInt(10)**ke).toString()),64);n=n.add(d)}return n.toString()}async function Qi(i,e,t,n,o=!1){let{clmm_vault:s,quote_type:r}=e,{wrapped_position:c}=s,{tick_lower_index:d,tick_upper_index:m,liquidity:f}=c,{current_sqrt_price:p,coin_type_a:h,coin_type_b:v}=t,M=[...n],C=r&&L(e.quote_type,!1),A=tt.tickIndexToSqrtPriceX64(d),D=tt.tickIndexToSqrtPriceX64(m),{coin_amount_a:V,coin_amount_b:O}=$t.getCoinAmountFromLiquidity(new Wt.default(f),new Wt.default(p),new Wt.default(A),new Wt.default(D),!1);M.push({coin_type:h,value:V.toString()}),M.push({coin_type:v,value:O.toString()});let B={};M.forEach(I=>{let W=L(I.coin_type,!1),j=S(I.value),Q=B[W]||0;B[W]=j.add(Q).toString()});let T=Object.entries(B).filter(([I,W])=>S(W).gt(0)).map(([I])=>I);if(C&&!T.includes(C)&&T.push(C),T.length===0)return"0";let E=await i.PythPrice.getLatestPrice(T,o),N={};return T.forEach(I=>{let W=E[I];if(W)N[I]={price:W,value:B[I]||"0"};else throw Error(`find ${I} price fail `)}),Ce(N,C).toString()}function We(i,e,t){return S(i).eq(0)?e:S(i).mul(e).div(t).toFixed(0,_i.default.ROUND_HALF_UP)}function ms(i,e,t){return S(i).eq(0)?"0":S(i).mul(e).div(t).toFixed(0,_i.default.ROUND_HALF_UP)}function Ae(i,e,t){return S(i).eq(0)?"0":S(e).mul(t).div(i).toFixed(0,_i.default.ROUND_HALF_UP)}function Oe(i,e,t){let n={};return e.forEach(o=>{let s=Ae(t,i,o.value),r={coin_type:o.coin_type,value:s};n[r.coin_type]=r}),n}function Ji(i,e,t,n,o=!0){let{tick_lower_index:s,tick_upper_index:r,coin_type_a:c,coin_type_b:d,liquidity:m}=t.clmm_vault.wrapped_position,f=Ae(t.lp_token_treasury,e,m),p=tt.tickIndexToSqrtPriceX64(s),h=tt.tickIndexToSqrtPriceX64(r),v=$t.getCoinAmountFromLiquidity(new Wt.default(f),new Wt.default(n.current_sqrt_price),p,h,!0),M=v.coin_amount_a.toString(),C=v.coin_amount_b.toString(),A=Oe(e,t.balances,t.lp_token_treasury),D=S(M).add(o&&A[c]?.value||"0").toFixed(0),V=S(C).add(o&&A[d]?.value||"0").toFixed(0),O=o?Object.values(A).filter(T=>T.coin_type!==c&&T.coin_type!==d):Object.values(A);return{vault_id:t.id,clmm_pool_id:n.id,owner:i,lp_token_type:t.lp_token_type,lp_token_balance:e,liquidity:f,tick_lower_index:s,tick_upper_index:r,amount_a:D,amount_b:V,coin_type_a:c,coin_type_b:d,share_buffer_assets:O}}function Ze(i,e,t){let n=[];return e.forEach(o=>{S(o.value).gt(0)&&n.push(o)}),t.forEach(o=>{S(o.value).gt(0)&&n.push(o)}),i.forEach(o=>{S(o.value).gt(0)&&n.push(o)}),n}function Ee(i,e,t){let n=new Set;return i.forEach(o=>n.add(o)),n.add(e),n.add(t),Array.from(n)}function Yi(i,e){if(!ke)throw new Error("oraclePriceMultiplierDecimal is required");if(i===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(ke- -e);return i*t}return i/10n**(e+ke)}function tn(i){return`0x${Buffer.from(i).toString("hex")}`}function _s(i,e,t,n,o){let s="0",r="0";return mi(i,"min",Number(t))?s="0":s=tt.tickIndexToPrice(Number(i),n,o).toString(),mi(e,"max",Number(t))?r="\u221E":r=tt.tickIndexToPrice(Number(e),n,o).toString(),{minPrice:s,maxPrice:r}}function fi(i){let e=ae(i),t=zi(i),n=se(t),o=e.position.fields,s={id:o.id.id,pool_id:o.pool,index:o.index,liquidity:o.liquidity,tick_lower_index:me(BigInt(o.tick_lower_index.fields.bits)),tick_upper_index:me(BigInt(o.tick_upper_index.fields.bits)),coin_type_a:L(o.coin_type_a.fields.name,!1),coin_type_b:L(o.coin_type_b.fields.name,!1),name:o.name,description:o.description,url:o.url},r=e.global_vesting_periods.map(d=>({period:d.fields.period,release_time:d.fields.release_time,redeemed_amount:d.fields.redeemed_amount,cetus_amount:d.fields.cetus_amount}));return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_coin_type:e.lp_coin_type.fields.name,allocated_lp_amount:e.allocated_lp_amount,position:s,balance:e.balance,total_supply:e.total_supply,impaired_a:e.impaired_a,impaired_b:e.impaired_b,redeemed_amount:e.redeemed_amount,url:e.url,coin_type_a:L(e.coin_a.fields.name,!1),coin_type_b:L(e.coin_b.fields.name,!1),cetus_amount:e.cetus_amount,start_time:e.start_time,global_vesting_periods:r,vest_infos:{id:e.vester_infos.fields.id,size:e.vester_infos.fields.size}}}function en(i){let e=ae(i),t=zi(i);return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_amount:e.lp_amount,url:e.url,redeemed_amount:e.redeemed_amount,impaired_a:e.impaired_a,impaired_b:e.impaired_b,period_infos:e.period_infos.map(o=>({period:o.fields.period,cetus_amount:o.fields.cetus_amount,is_redeemed:o.fields.is_redeemed})),name:e.name,vester_id:e.vester_id}}var nn=require("@cetusprotocol/dlmm-sdk");var fo=ie(require("decimal.js")),Fe=require("@mysten/sui/bcs"),ze=require("@mysten/sui/utils"),Ve=ie(require("bn.js"));function on(i){try{let{fields:e,type:t}=i,{certified_pools:n,positions:o,id:s,coin_type_a:r,coin_type_b:c,vault_id:d,position_keys:m}=e;return{type:t.includes("CLMMMarket")?"CLMM":"DLMM",id:s.id,certified_pools:n.fields.contents.map(h=>h.fields.key),positions_handle:{id:o.fields.id.id,size:o.fields.size},position_list:[],coin_type_a:L(r.fields.name,!1),coin_type_b:L(c.fields.name,!1),vault_id:d,position_keys:m.fields.contents}}catch{return}}function fs(i){return{uri:i.uri,index:i.index,id:i.id.id,name:i.name,pool_id:i.pool_id,lower_bin_id:me(BigInt(i.lower_bin_id.fields.bits)),upper_bin_id:me(BigInt(i.upper_bin_id.fields.bits)),liquidity_shares:i.liquidity_shares,description:i.description,coin_type_a:L(i.coin_type_a,!1),coin_type_b:L(i.coin_type_b,!1)}}function ps(i){return{id:i.id.id,pool_id:i.pool,index:i.index,description:i.description,uri:i.url,liquidity:i.liquidity,tick_lower_index:me(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:me(BigInt(i.tick_upper_index.fields.bits)),name:i.name,coin_type_a:L(i.coin_type_a.fields.name,!1),coin_type_b:L(i.coin_type_b.fields.name,!1)}}function rn(i){let{fields:e}=i,{position:t,amounts:n,id:o}=e,s=n.fields.contents.map(h=>{let{key:v,value:M}=h.fields;return{coin_type:L(v.fields.name,!1),value:M}}),r=fs(t.fields),c=r.lower_bin_id,d=r.liquidity_shares.map((h,v)=>({bin_id:c+v,liquidity:h})).filter(h=>S(h.liquidity).gt(0)),m=d.length>0?d[0].bin_id:c,f=d.length>0?d[d.length-1].bin_id:c+r.liquidity_shares.length-1;return{id:o.id,valid_lower_bin_id:m,valid_upper_bin_id:f,position:r,amounts:s}}function sn(i){let{fields:e}=i,{position:t,amounts:n,id:o}=e,s=n.fields.contents.map(d=>{let{key:m,value:f}=d.fields;return{coin_type:L(m.fields.name,!1),value:f}}),r=ps(t.fields);return{id:o.id,position:r,amounts:s}}function pi(i){let{fields:e,type:t}=i,{action_status:n,buffer_assets:o,coin_type_a:s,coin_type_b:r,hard_cap:c,id:d,last_aum:m,lp_token_treasury:f,markets:p,protocol_fee_rate:h,protocol_fees:v,quote_type:M}=e,C=(Number(n)&1)!==0,A=(Number(n)&2)!==0,{balances:D}=o.fields,V=D.fields.contents.map(T=>{let{key:E,value:N}=T.fields;return{coin_type:L(E.fields.name,!1),value:N}}),O=M.fields.pos0.fields.name;return{id:d.id,lp_token_treasury:f.fields.total_supply.fields.value,hard_cap:c,quote_type:O?L(O,!1):void 0,protocol_fee_rate:h,buffer_assets:V,protocol_fees_handle:{id:v.fields.id.id,size:v.fields.size},markets_handle:{id:p.fields.id.id,size:p.fields.size},markets:[],action_status:{is_deposit_allowed:C,is_withdraw_allowed:A},is_multiple_pool:!1,last_aum:m,coin_type_a:L(s.fields.name,!1),coin_type_b:L(r.fields.name,!1),lp_token_type:se(t).type_arguments[0],version:"v2"}}async function an(i,e,t,n=!1){let{pool:o,marketList:s}=await i.VaultsV2.getVaultAndPool(e),{quote_type:r,coin_type_a:c,coin_type_b:d}=o,m=[...t],f="0",p="0";for(let V of s)if(V.type==="DLMM"){let{position_list:O}=V;for(let B of O){let{lower_bin_id:T,liquidity_shares:E,pool_id:N}=B.position,F=V.certified_pool_obj[N],I=await i.CetusDlmmSDK.Pool.getBinInfo(F.bin_manager.bin_manager_handle,F.active_id,F.bin_step,!1),W=(0,nn.parseLiquidityShares)(E,F.bin_step,T,I);f=S(f).add(W.amount_a.toString()).toFixed(0),p=S(p).add(W.amount_b.toString()).toFixed(0)}}else if(V.type==="CLMM"){let{position_list:O}=V;for(let B of O){let{tick_lower_index:T,tick_upper_index:E,liquidity:N,pool_id:F}=B.position,I=V.certified_pool_obj[F],W=tt.tickIndexToSqrtPriceX64(T),j=tt.tickIndexToSqrtPriceX64(E),{coin_amount_a:Q,coin_amount_b:$}=$t.getCoinAmountFromLiquidity(new Ve.default(N),new Ve.default(I.current_sqrt_price),new Ve.default(W),new Ve.default(j),!1);f=S(f).add(Q.toString()).toFixed(0),p=S(p).add($.toString()).toFixed(0)}}let h=r&&L(r,!1);m.push({coin_type:c,value:f}),m.push({coin_type:d,value:p});let v={};m.forEach(V=>{let O=L(V.coin_type,!1),B=S(V.value),T=v[O]||0;v[O]=B.add(T).toString()});let M=Object.entries(v).filter(([V,O])=>S(O).gt(0)).map(([V])=>V);if(h&&!M.includes(h)&&M.push(h),M.length===0)return"0";let C=await i.VaultsV2.PythPrice.getLatestPrice(M,n),A={};return M.forEach(V=>{let O=C[V];if(O)A[V]={price:O,value:v[V]||"0"};else throw Error(`find ${V} price fail `)}),Ce(A,h).toString()}async function hi(i,e,t,n,o=!0){let s=await Xe(i,e,t,o);return s.owner=n||"0x0",s}async function Xe(i,e,t,n=!0){let{pool:o,marketList:s}=await i.VaultsV2.getVaultAndPool(t),{lp_token_type:r,lp_token_treasury:c,coin_type_a:d,coin_type_b:m}=o;if(S(c).isZero())return{vault_id:t,lp_token_type:r,lp_token_balance:e,owner:"0x0",coin_type_a:d,coin_type_b:m,amount_a:"0",amount_b:"0",position_amount_a:"0",position_amount_b:"0",dlmm_balances:[],clmm_balances:[],share_buffer_assets:[]};let f=S(e).div(c),p=[],h=[],v=S(0),M=S(0);for(let T of s)if(T.type==="DLMM"){let{position_list:E}=T;for(let N of E){let{lower_bin_id:F,upper_bin_id:I,liquidity_shares:W,id:j,pool_id:Q}=N.position,$=T.certified_pool_obj[Q],{bin_manager:K,bin_step:a,active_id:u}=$,_=await i.CetusDlmmSDK.Pool.getBinInfo(K.bin_manager_handle,u,a,!1),g=(0,nn.parseLiquidityShares)(W.map(q=>S(q.toString()).mul(f).toFixed(0,fo.default.ROUND_HALF_UP).toString()),a,F,_),b=g.amount_a,P=g.amount_b,k=g.bins.filter(q=>S(q.liquidity).gt(0)),w=k.length>0?k[0].bin_id:g.bins[0].bin_id,l=k.length>0?k[k.length-1].bin_id:g.bins[g.bins.length-1].bin_id,y={position_id:j,certified_pool_id:$.id,liquidity_shares:W,valid_lower_bin_id:w,valid_upper_bin_id:l,original_lower_bin_id:F,original_upper_bin_id:I,position_amount_a:b,position_amount_b:P,coin_type_a:d,coin_type_b:m,bin_infos:{bins:k,amount_a:g.amount_a,amount_b:g.amount_b}};p.push(y),v=v.add(S(b)),M=M.add(S(P))}}else if(T.type==="CLMM"){let{position_list:E}=T;for(let N of E){let{tick_lower_index:F,tick_upper_index:I,liquidity:W,id:j,pool_id:Q}=N.position,$=T.certified_pool_obj[Q],K=S(W).mul(f).toFixed(0),a=tt.tickIndexToSqrtPriceX64(F),u=tt.tickIndexToSqrtPriceX64(I),_=$t.getCoinAmountFromLiquidity(new Ve.default(K),new Ve.default($.current_sqrt_price),a,u,!1),g=_.coin_amount_a.toString(),b=_.coin_amount_b.toString(),P={position_id:j,certified_pool_id:$.id,liquidity:K,tick_lower_index:F,tick_upper_index:I,position_amount_a:g,position_amount_b:b};h.push(P),v=v.add(S(g)),M=M.add(S(b))}}let C=Oe(e,o.buffer_assets,c),A=n&&C[d]?.value||"0",D=n&&C[m]?.value||"0",V=v.add(A).toFixed(0),O=M.add(D).toFixed(0),B=n?Object.values(C).filter(T=>T.coin_type!==d&&T.coin_type!==m):Object.values(C);return{vault_id:t,lp_token_type:r,lp_token_balance:e,owner:"0x0",coin_type_a:d,coin_type_b:m,amount_a:V,amount_b:O,position_amount_a:v.toFixed(0),position_amount_b:M.toFixed(0),dlmm_balances:p,clmm_balances:h,share_buffer_assets:B}}function cn(i){let e=Fe.bcs.vector(Fe.bcs.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return(0,ze.deriveObjectID)(i,"vector<u8>",e)}function ln(i){let e=Fe.bcs.vector(Fe.bcs.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return(0,ze.deriveObjectID)(i,"vector<u8>",e)}function hs(i,e){let t=Fe.bcs.Address.serialize(e).toBytes();return(0,ze.deriveDynamicFieldID)(i,"0x2::object::ID",t)}function je(i,e,t,n){let o=S(i),s=S(t),r=S(n),c=o,d=e?o:S(0),m=e?S(0):o,f=r,p=S(r).mul(.999),h=S(0),v=c,M=null;function C(V){if(e){let O=d.minus(V),B=m.plus(V.mul(s));return{A:O,B,R:B.div(O)}}else{let O=d.plus(V.mul(s)),B=m.minus(V);return{A:O,B,R:O.div(B)}}}for(let V=0;V<120;V++){let O=h.plus(v).div(2),{A:B,B:T,R:E}=C(O);if(B.lte(0)||T.lte(0)){v=O;continue}if(E.gt(f))v=O;else if(E.lt(p))h=O;else{if(M=O,S(p).eq(0))break;v=O}}if(!M)return{swap_amount:"0",final_amount_a:d.toFixed(0),final_amount_b:m.toFixed(0)};let{A,B:D}=C(M);return{swap_amount:M.toFixed(0),final_amount_a:A.toFixed(0),final_amount_b:D.toFixed(0),best:M.toString()}}function un(i,e,t,n,o,s){if(s){let r=S(i).mul(t).sub(S(e).mul(n)),c=S(t).add(S(o).mul(n));return(S(c).eq(0)?S(0):S(r).div(c)).toString()}else{let r=S(e).mul(n).sub(S(i).mul(t)),c=S(o).mul(t).add(n);return(S(c).eq(0)?S(0):S(r).div(c)).toString()}}var Ie=require("@pythnetwork/pyth-sui-js"),bn=require("@mysten/sui/bcs");var dn={env:"mainnet",fullRpcUrl:"https://fullnode.mainnet.sui.io",vaults:{package_id:"0xc4ebf35be1478318d78c324342854dd2735a036139373a9d41a1aa3a46a01d05",published_at:"0x720f861bda572e891eb422c117fb7224c0f91aaf69b655f6e40bcd68f0edad41",configs:{registry_id:"0x23014734280164270fa4c58f973c00079651e730d6f46491678ea8858f3bd13a",pools_handle:"0x31c810b6fcf3bb8699384e7c61fe9f7db53a04c4c22d514b3f79b6caa86183a8",pyth_oracle_id:"0xaed73fd854dfceedb2522903feec8c0e251764f5945bd38f969473024c4fb4d0",oracle_infos_handle:"0x6951ab4b36639e79ddbd9ba4478d7f72d1c5396b9198d0864c00e796c5815b01",prices_handle:"0x20a65a0f747f4f1ad465bdb61d784bbc5080ee5d200d5dd6594a354723b8c171",global_config_id:"0x5f8371674cd8e1e9eef5542ffe8adb339e3ff3a67894b14c954c7a92e992e0c1"},clmm_configs:{global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b"}},vaultsV2:{package_id:"0xfbc91f75397ce25b3b1b01cab2bf494d2e3f9b9e89c97545d88bd616cbbfcc37",published_at:"0x4893ee6665ad7b1a83810c16e0151b9500a7296bba85f2571ba9e79115ce1a83",configs:{registry_id:"0xb6e0d2a2457af53a83b1435ea398f9460ba8abd98686387a4399fceefdfc22e2",pools_handle:"0xc88e97a3a3bb71dfcf8cc90e6383d7e3e1dee0170fa07c9365d233568659fc8f",global_config_id:"0x05bedfb68e6bf273946f8e1f2529e8f30acdf8b287dec524973c6bae9e979743",versioned_id:"0x70bea2f242b057cda9994e9fecee121cb35ee914c360cc86f061268110b6d9ec",oracle_infos_handle:"0x4631c11bfeae9461863d233285d03e3dba14f8dfb574781f1e2cbe9b58ba903e",pyth_oracle_id:"0xc08cdf8479075b0dae05aadc76f941038a25d74dcbedd9c339f7ce5da08fab92"}},pythConfigs:{pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",hermes_service_urls:{primary:"https://hermes.pyth.network"},wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91"},aggregatorUrl:"https://api-sui.cetus.zone/router_v3",providers:[],vest:{package_id:"0xd0587f397e47d31a79d1c36710c2c28f48ff8f1e8ea73b6a54fa2ec6fdfe0a7d",published_at:"0x57731e8bd3971eca68019afecb0e11699ece6301f0d4f255969f5b4227e0c5f8",version:1,config:{versioned_id:"0xee1e2214314737df6193cc4cf6815cf8dc3b4cc1c5cc0a078c6579dda19e8552",create_event_list:[{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xb2d502d4ef89395934de020b195ded323bfa86d7f40b65ed5b15d6b66c722a3d::lpcoin::LPCOIN",pool_id:"0x2fc6ee9183d0f1ca0d2dded02c416be6f4671bb82db55c26ce12b536812a4b8e",position_id:"0x99f7fbeaf18c88e8af7553ad2ef055772477a1851550a2e7c2d7a503420c6b05",vault_id:"0xbd6252e0d56ae5eaabf055fd6c518ee5f66c1114287ca957cc698a17c3d25b16",vault_vester_id:"0xe4196586ed151a38c7c9169c72b9e5e3f51bfea9afbc2d1f082d6bedb88b086f"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x0484a9162669957e1c1883fc2da59e3cce9afdc1eec3c72c983898dbc9e92b91::lpcoin::LPCOIN",pool_id:"0xaa020ad81e1621d98d4fb82c4acb80dc064722f24ef828ab633bef50fc28268b",position_id:"0x90918d035e37b4447e11c2043c4c4374baeb7c2cbd2729063d939d016b04770f",vault_id:"0x99db9a7d3320d31fe6e4dc4122b948162010e331c41dc279636ca75567b93497",vault_vester_id:"0xd891e4c866a67e6339d1539edd1c28db629c81d9fb8499ee029cfa3803a0819e"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x242ddc526b9cb75513bee2fc629e01d5b7dc6da4c02d39cdab0160794635334f::lpcoin::LPCOIN",pool_id:"0x2e041f3fd93646dcc877f783c1f2b7fa62d30271bdef1f21ef002cebf857bded",position_id:"0xf82ebf822b0a7eff84f0079f3998611c4fec2ae714fe627225640eb305dc5a7c",vault_id:"0xbbd2d4850e4f238d39c3aa24957d2dfbb5787fa43d6c7de306bf15abe27f29f2",vault_vester_id:"0x7cc6404b903542ff6410b8e85c9647005713f8a23166ef08a488fe267c81c8bb"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xd418945e16ef3db737df093d0827f5ce387b36f089523e13c16e50dec6bd2524::lpcoin::LPCOIN",pool_id:"0xe01243f37f712ef87e556afb9b1d03d0fae13f96d324ec912daffc339dfdcbd2",position_id:"0x1ea05f946e995edcda18ba9fdaefd1021eddfb8d62e4fa09da89753ffb5b90ee",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0xd67cd239a34852cbc2e530db2ef296bc3e4a977464309c21ce706d90a17a5d5d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xf21d82f767cac2e8892db252aa539c137dcf8a6d1e6ebd2d0a11c16362171df7::lpcoin::LPCOIN",pool_id:"0x72f5c6eef73d77de271886219a2543e7c29a33de19a6c69c5cf1899f729c3f17",position_id:"0x5bd93e30000eb9f3217a04c938c7f939ee33ac161f6fe7ea34bac268dbe36893",vault_id:"0x12ac7deea4b92b3e2c16687e2d2695fa8c045ec0a52844db7b2fc3876c9552aa",vault_vester_id:"0x5d87bb3db28e77604f9bd210cdde0916e95a9d37925ec3c466fa785bba3d63f9"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x2f46a040b9bc3a584a3be4d7bfbb02a5fb479da17a04c6d2860ed61d95e97f3f::lpcoin::LPCOIN",pool_id:"0xb8d7d9e66a60c239e7a60110efcf8de6c705580ed924d0dde141f4a0e2c90105",position_id:"0xa2141e99975e203172f62c97b1f314f845b94730f6dfdb8ab2d32d014c659bcf",vault_id:"0x41a4ab1e82f90f5965bbcd828b8ffa13bab7560bd2e352ab067e343db552f527",vault_vester_id:"0x0e4782ee96095af233a6c5219b50cd8c92bd79d84f1df7e629bcc7a094c5a09d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x5c79c0ab2c45682aba43b1acbe5c478d947f7c8397d47447906d6cc127e180fb::lpcoin::LPCOIN",pool_id:"0xea648440bd640d3530e8a5f02c0b56da82c2efe851156c39974b901bbb0eeab1",position_id:"0x896a01cc57ba25799ec320dc25d1969f3129f2591689ce8c8dbf380c7e00bf48",vault_id:"0x5525f5a70fffd93f616c39b59f3abdd2054fc2d19f09c8a4d94950d611a43b74",vault_vester_id:"0xe116bb120d2d91f85ee419cbff73fdd9d7f87e9b085dd4de781347b51361ae17"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x8275bc774497b319db110bb97a4812a19859ab6f19dc1574746097f06103c0f9::lpcoin::LPCOIN",pool_id:"0x9e59de50d9e5979fc03ac5bcacdb581c823dbd27d63a036131e17b391f2fac88",position_id:"0xd080bfb32b9c24f8875bd5a803a417b8ca0c02f2208d0b9058692f9013db3b52",vault_id:"0xedfb22d1bbe5045fd1888bb8bc1c4bc1823ab24d40f5a4bea9f6eb9758a4b820",vault_vester_id:"0x8bc7ccefae4db25873a0692bfb0d2c7cbdbbe644574a537789b98815960155a4"}]}}},mn={"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{coin_type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",price_feed_id:"0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",coin_decimals:6},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",price_feed_id:"0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",coin_decimals:9},"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS":{coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",price_feed_id:"0xe5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",coin_decimals:9},"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP":{coin_type:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",price_feed_id:"0x29bdd5248234e33bd93d3b81100b5fa32eaa5997843847e2c2cb16d7c6d9f7ff",coin_decimals:6},"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX":{coin_type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",price_feed_id:"0x88250f854c019ef4f88a5c073d52a18bb1c6ac437033f5932cd017d24917ab46",coin_decimals:9},"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN":{coin_type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",price_feed_id:"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",coin_decimals:9},"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI":{coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",price_feed_id:"0x6120ffcf96395c70aa77e72dcb900bf9d40dccab228efca59a17b90ce423d5e8",coin_decimals:9},"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH":{coin_type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",price_feed_id:"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",coin_decimals:8},"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL":{coin_type:"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL",price_feed_id:"0xeba0732395fae9dec4bae12e52760b35fc1c5671e2da8b449c9af4efe5d54341",coin_decimals:9},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{coin_type:"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC",price_feed_id:"0x8f257aab6e7698bb92b15511915e593d6f8eae914452f781874754b03d0c612b",coin_decimals:8},"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL":{coin_type:"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL",price_feed_id:"0xe67d98cc1fbd94f569d5ba6c3c3c759eb3ffc5d2b28e64538a53ae13efad8fd1",coin_decimals:9}};function _n(i,e,t){return i&&(dn.fullRpcUrl=i),new he(dn,e,t)}var fn={env:"testnet",fullRpcUrl:"https://fullnode.testnet.sui.io",vaults:{package_id:"0x0a624f2dcafc9f7f381684b3d553a9837411925b6e8530b1f8f4e6ff3f1fde77",published_at:"0x36f9d8e6219e6ba4d8840165ec27676a1bcb43fc5712f87ca702ac7b5924507d",configs:{registry_id:"0xa2ebae3656c5fbdd2473caadfc077cd1780a881759a356f1a5bc0f9fd470adb9",pools_handle:"0x0df305d395f8e0359da0ac5717bc96e0e1da9792684ec8e8f6a20b7ab544f98e",pyth_oracle_id:"0x6c74aec8d4471d9b05f718c467204c9010c450b94a4e40b0b4031a7d6c386337",global_config_id:"0x8969b09cfdd72b1635263b569027ded4b91bbabd7d8cd91b21e355325e218b10",oracle_infos_handle:"0x8707c6665d202f277ffe8e7fd58684e232622a3e6826b94ba99f7569f253fa9d",prices_handle:"0x74230bb2c6a63235acbfe477ce16144afca7ccd16a458fa93f4605330b5d1c58"},clmm_configs:{global_config_id:"0x9774e359588ead122af1c7e7f64e14ade261cfeecdb5d0eb4a5b3b4c8ab8bd3e",global_vault_id:"0xf78d2ee3c312f298882cb680695e5e8c81b1d441a646caccc058006c2851ddea"}},pythConfigs:{pyth_state_id:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",wormhole_state_id:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",hermes_service_urls:{primary:"https://hermes-beta.pyth.network"},pyth_package_id:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837",pyth_published_at:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837"},vaultsV2:{package_id:"0x0000000000000000000000000000000000000000000000000000000000000000",published_at:"0x0000000000000000000000000000000000000000000000000000000000000000",configs:{registry_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pools_handle:"0x0000000000000000000000000000000000000000000000000000000000000000",global_config_id:"0x0000000000000000000000000000000000000000000000000000000000000000",versioned_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pyth_oracle_id:"0x0000000000000000000000000000000000000000000000000000000000000000",oracle_infos_handle:"0x0000000000000000000000000000000000000000000000000000000000000000"}},aggregatorUrl:"https://api-sui.devcetus.com/router_v2",providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"],vest:{package_id:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",published_at:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",config:{versioned_id:"0x2c5b6227da87ce840035955e0d82725178ce53c8cd2b01934d6540feccf2a8f7",create_event_list:[{clmm_vester_id:"0x308b24963e5992f699e32db2f7088b812566a0cae580317fd3b8bf61de7f5508",lp_coin_type:"0xb0c18dcd849d4b47528831c64707f2f7f6aa1b7fd9ed5e1ac2f8ab356e031f25::lp_token::LP_TOKEN",pool_id:"0x403c7d9c1e959c029f61d970286eac8ad5bca2db2edba358585abf4dbd4ed3cd",position_id:"0xd1dbcdb1789b92772b367bc1f68d7d078b4fd3326b8bfb53750bf28585463508",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0x6098c69613ed5d503ff2b81447e96408feab8f2e4bf582966a811b5b582d23e3"}]}}},pn={};function hn(i,e,t){return i&&(fn.fullRpcUrl=i),new he(fn,e,t)}var po=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(po||{});function gs(i,e,t){let{env:n,fullNodeUrl:o}=i;return n==="mainnet"?_n(o,e,t):hn(o,e,t)}var gn=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];function ho(i){try{let{request_time:e,error:t,request_params:n,request_url:o,action:s}=i;if(window?.gtag){let r=t.message==="Request Timeout";window.gtag("event","API_Error",{request_action:s,request_url:o,request_time:e,request_params:JSON.stringify(n),error_msg:String(t)})}}catch{}}var bs=16*1024,De=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;errorList=[];pythConfigs;global_config_id;pyth_oracle_id;oracle_infos_handle;vaults_published_at;versioned_id;isV2;constructor(e,t,n,o,s,r,c,d){this.vaults_published_at=n,this.pythConfigs=t,this.global_config_id=o,this.pyth_oracle_id=s,this.oracle_infos_handle=c,this.isV2=d,this.versioned_id=r;let{pyth_state_id:m,wormhole_state_id:f,hermes_service_urls:p}=t;this._sdk=e,this.hasChangeConnection=!1;let{primary:h}=p;if(h.length===0)throw new Error("primary url is empty");this.connection=new Ie.SuiPriceServiceConnection(h),this.suiPythClient=new Ie.SuiPythClient(this._sdk.FullClient,m,f)}get sdk(){return this._sdk}recordError(e,t,n){let{secondary:o,primary:s}=this.pythConfigs.hermes_service_urls,r={error:e,request_params:t,request_url:this.hasChangeConnection&&o?o:s,action:n,request_time:Date.now()};ho(r),this.errorList.push(r)}readErrorList(){let e=this.errorList;return this.errorList=[],e}async getFeedInfoList(e){let t=e.map(o=>this.getFeedInfo(o,!1));return await Promise.all(t)}priceCheck(e,t=60){let n=Math.floor(Date.now()/1e3);if(!(Math.abs(n-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let n={},o=[];if(t?e.forEach(c=>{let d=this._sdk.getCache(`getLatestPrice_${c}`);d&&this.priceCheck(d,60)?n[c]=d:o.push(c)}):o=[...e],o.length===0)return n;let s=await this.getFeedInfoList(o);return(await this.getLatestPriceFeeds(s.map(c=>c.price_feed_id)))?.parsed?.forEach((c,d)=>{if(c){let{price:m,expo:f,publish_time:p}=c.price,h=S(m).mul(S(10).pow(S(f))).toString(),v=s[d],M={coin_type:v.coin_type,price:h,coin_decimals:v.coin_decimals,oracle_price:0n,last_update_time:p};M.oracle_price=Yi(BigInt(m),BigInt(f)),n[o[d]]=M,this._sdk.updateCache(`getLatestPrice_${M.coin_type}`,M)}}),n}async getPriceFeedsUpdateData(e){try{return await this.connection.getPriceFeedsUpdateData(e)}catch(t){this.recordError(t,e,"getPriceFeedsUpdateData");let{secondary:n}=this.pythConfigs.hermes_service_urls;if(n){this.hasChangeConnection=!0,this.connection=new Ie.SuiPriceServiceConnection(n);try{return await this.connection.getPriceFeedsUpdateData(e)}catch(o){this.recordError(o,e,"getPriceFeedsUpdateData")}}}}async getLatestPriceFeeds(e){try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(t){this.recordError(t,e,"getLatestPriceFeeds");let{secondary:n}=this.pythConfigs.hermes_service_urls;if(n){this.hasChangeConnection=!0,this.connection=new Ie.SuiPriceServiceConnection(n);try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(o){this.recordError(o,e,"getLatestPriceFeeds")}}}}async buildUpdatePythPricePayload(e,t){let{pyth_state_id:n,pyth_published_at:o,pyth_package_id:s}=this.pythConfigs,r=(await this.getFeedInfoList(e)).map(h=>h.price_feed_id);if(e.length!==r.length)throw Error("find feed id fail");let c=await this.getPriceFeedsUpdateData(r);if(!c)throw new Error("get price update data fail");if(c.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let d=this.suiPythClient.extractVaaBytesFromAccumulatorMessage(c[0]),m=await this.suiPythClient.verifyVaas([d],t),[f]=t.moveCall({target:`${o}::pyth::create_authenticated_price_infos_using_accumulator`,typeArguments:[],arguments:[t.object(n),t.pure(bn.bcs.vector(bn.bcs.U8).serialize(Array.from(c[0]),{maxSize:bs}).toBytes()),m[0],t.object(rt)]}),p=0;for(let h of r){let v=await this.suiPythClient.getPriceFeedObjectId(h);if(!v)throw new Error(`Price feed ${h} not found, please create it first`);this.isV2?[f]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[p]],arguments:[t.object(this.pyth_oracle_id),t.object(n),f,t.object(v),t.object(rt),t.object(this.versioned_id)]}):[f]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[p]],arguments:[t.object(this.pyth_oracle_id),t.object(this.global_config_id),t.object(n),f,t.object(v),t.object(rt)]}),p+=1}return t.moveCall({target:`${o}::hot_potato_vector::destroy`,arguments:[f],typeArguments:[`${s}::price_info::PriceInfo`]}),t}async buildUpdatePythPricePayloadV2(e,t){if(e.length===0)return t;let n=(await this.getFeedInfoList(e)).map(c=>c.price_feed_id);if(e.length!==n.length)throw Error("find feed id fail");let o=await this.getPriceFeedsUpdateData(n);if(!o)throw new Error("get price update data fail");if(o.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let s=await this.suiPythClient.updatePriceFeeds(t,o,n),r=0;for(let c of s)t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price_into_pyth_oracle`,typeArguments:[e[r]],arguments:[t.object(this.pyth_oracle_id),t.object(c),t.object(rt),t.object(this.versioned_id)]}),r+=1;return t}getFeedInfoByJson(e){let{env:t}=this._sdk.sdkOptions,n=L(e,!1);return t==="mainnet"?mn[n]:pn[n]}async getFeedInfo(e,t){let n=`getFeedInfo_${e}`,o=this._sdk.getCache(n,t);if(o)return o;let s=this.getFeedInfoByJson(e);if(s)return s;let r=await this._sdk.FullClient.getDynamicFieldObject({parentId:this.oracle_infos_handle,name:{type:"0x1::type_name::TypeName",value:L(e,!0)}}),{fields:c}=r.data.content.fields.value,d={coin_type:e,price_feed_id:tn(c.price_feed_id),coin_decimals:c.coin_decimals};return this._sdk.updateCache(n,d),d}};var Ge=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:n}=e.sdkOptions;this.pythPrice=new De(e,n,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,"",t.configs.oracle_infos_handle,!1)}get sdk(){return this._sdk}get PythPrice(){return this.pythPrice}async getProtocolFeeRate(){let e="getProtocolFeeRate",t=this._sdk.getCache(e);if(t)return t;let{configs:n}=this._sdk.sdkOptions.vaults,s=(await this._sdk.FullClient.getObject({id:n.global_config_id,options:{showContent:!0}})).data.content.fields.protocol_fee_rate;return this._sdk.updateCache(e,s),s}async getOwnerVaultsBalance(e,t,n=!0){let{pool:o,clmmPool:s}=await this.getVaultAndPool(t,!0),c=(await this._sdk.FullClient.getBalance({owner:e,coinType:o.lp_token_type})).totalBalance;return Ji(e,c,o,s,n)}async getOwnerVaultsBalanceList(e,t=!0){let{data:n}=await this.getPoolList(),o=[];for(let s=0;s<n.length;s++){let r=await this.getOwnerVaultsBalance(e,n[s].id,t);o.push(r)}return o}async getVaultsPositionRewarderAndFee(e){try{let{package_id:t}=this._sdk.sdkOptions.vaults,{pool:n,clmmPool:o}=await this.getVaultAndPool(e,!1),s=`getVaultsPositionRewarderAndFee_${e}`,r=this._sdk.getCache(s);if(r)return r;let{lp_token_type:c}=n,{rewarder_infos:d,id:m,coin_type_a:f,coin_type_b:p}=o,h=new Le.Transaction;this.buildCollectRewardPayload({reward_coin_types:[...d.map(V=>V.coin_type)],lp_token_type:c,pool_id:e,clmm_pool_id:m,coin_type_a:f,coin_type_b:p},h),this.buildCollectFeePayload({lp_token_type:c,pool_id:e,clmm_pool_id:m,coin_type_a:f,coin_type_b:p},h);let v=await this._sdk.FullClient.sendSimulationTransaction(h,(0,bo.normalizeSuiAddress)("0x0")),M=`${t}::pool::FeeClaimedEvent`,C=`${t}::pool::RewardClaimedEvent`,A=[],D=[];return v?.events.forEach(V=>{let{parsedJson:O,type:B}=V;B===M&&(A.push({coin_type:L(f,!1),value:O.amount_a}),A.push({coin_type:L(p,!1),value:O.amount_b})),B===C&&D.push({coin_type:L(O.reward_type.name,!1),value:O.amount})}),this._sdk.updateCache(s,{feeList:A,rewarderList:D},10*1e3),{feeList:A,rewarderList:D}}catch{}return{feeList:[],rewarderList:[]}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaults:n}=this._sdk.sdkOptions,{FullClient:o}=this._sdk,s=await o.getDynamicFieldsByPage(n.configs.pools_handle,e),r=s.data.map(c=>c.name.value);return r.length>0&&((await o.batchGetObjects(r,{showContent:!0})).forEach(d=>{let m=Se(d.data.content);this._sdk.updateCache(`getPool_${m.id}`,m),t.data.push(m)}),t.next_cursor=s.next_cursor,t.has_next_page=s.has_next_page),t}async getAssignPoolList(e){if(e.length===0)return[];let t=[],n=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0,showType:!0});for(let o of n){let s=Se(o.data.content);this._sdk.updateCache(`getPool_${s.id}`,s),t.push(s)}return t}async getPool(e,t=!0){let n=`getPool_${e}`,o=this._sdk.getCache(n,t);if(o)return o;let s=await this._sdk.FullClient.getObject({id:e,options:{showContent:!0}}),r=Se(s.data.content);return this._sdk.updateCache(n,r),r}buildCollectRewardPayload(e,t){let{coin_type_a:n,coin_type_b:o,pool_id:s,clmm_pool_id:r,lp_token_type:c,reward_coin_types:d}=e,{published_at:m,configs:f,clmm_configs:p}=this._sdk.sdkOptions.vaults;return t=t||new Le.Transaction,d.forEach(h=>{t.moveCall({target:`${m}::pool::collect_reward`,typeArguments:[n,o,c,h],arguments:[t.object(s),t.object(f.global_config_id),t.object(p.global_config_id),t.object(r),t.object(p.global_vault_id),t.object(rt)]})}),t}buildCollectFeePayload(e,t){let{coin_type_a:n,coin_type_b:o,pool_id:s,clmm_pool_id:r,lp_token_type:c}=e,{published_at:d,configs:m,clmm_configs:f}=this._sdk.sdkOptions.vaults;return t=t||new Le.Transaction,t.moveCall({target:`${d}::pool::collect_fee`,typeArguments:[n,o,c],arguments:[t.object(s),t.object(m.global_config_id),t.object(f.global_config_id),t.object(r)]}),t}async buildDepositPayload(e,t){let{pool_id:n,amount_a:o,amount_b:s,return_lp_coin:r,re_balance:c}=e,{pool:d,clmmPool:m}=await this.getVaultAndPool(n,!0),{lp_token_type:f}=d,{rewarder_infos:p,id:h,coin_type_a:v,coin_type_b:M}=m,C=p.map(N=>L(N.coin_type,!1)),A=Ee(C,m.coin_type_a,m.coin_type_b),{published_at:D,configs:V,clmm_configs:O}=this._sdk.sdkOptions.vaults;t=t||new Le.Transaction,t=this.buildCollectRewardPayload({reward_coin_types:C,lp_token_type:f,pool_id:n,clmm_pool_id:h,coin_type_a:v,coin_type_b:M},t),t=this.buildCollectFeePayload({lp_token_type:f,pool_id:n,clmm_pool_id:h,coin_type_a:v,coin_type_b:M},t),t=await this.pythPrice.buildUpdatePythPricePayload(A,t),t.moveCall({target:`${D}::pool::calculate_aum`,typeArguments:[v,M,f],arguments:[t.object(n),t.object(V.global_config_id),t.object(V.pyth_oracle_id),t.object(O.global_config_id),t.object(h),t.object(rt)]});let B,T;if(c&&c.swap_result){let{swap_result:N,coin_amount:F,mode:I,swap_slippage:W}=c,{swap_in_amount:j,swap_out_amount:Q,route_obj:$}=N,K=Jt.buildCoinWithBalance(BigInt(F),I==="OnlyCoinA"?v:M,t),a=t.splitCoins(K,[j]),u={router:$,slippage:W,txb:t,inputCoin:a},_=await this._sdk.AggregatorClient.fixableRouterSwapV3(u);B=I==="OnlyCoinA"?K:_,T=I==="OnlyCoinA"?_:K}else B=Jt.buildCoinWithBalance(BigInt(o),v,t),T=Jt.buildCoinWithBalance(BigInt(s),M,t);let E=t.moveCall({target:`${D}::pool::${r?"deposit_for":"deposit"}`,typeArguments:[v,M,f],arguments:[t.object(n),t.object(V.global_config_id),t.object(V.pyth_oracle_id),t.object(O.global_config_id),t.object(h),B,T,t.object(rt)]});return r?E:void 0}async buildWithdrawPayload(e,t){let{pool_id:n,burn_lp_amount:o,mode:s,slippage:r,partner:c,extra_burn:d,return_coin:m}=e,{pool:f,clmmPool:p}=await this.getVaultAndPool(n,!0),{published_at:h,configs:v,clmm_configs:M}=this._sdk.sdkOptions.vaults;t=t||new Le.Transaction;let{lp_token_type:C,clmm_vault:A,lp_token_treasury:D}=f,{rewarder_infos:V,id:O,coin_type_a:B,coin_type_b:T,liquidity:E}=p,N=V.map(K=>L(K.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:N,lp_token_type:C,pool_id:n,clmm_pool_id:O,coin_type_a:B,coin_type_b:T},t),t=this.buildCollectFeePayload({lp_token_type:C,pool_id:n,clmm_pool_id:O,coin_type_a:B,coin_type_b:T},t);let F,I=d?S(d.burn_lp_amount).add(S(o)).toFixed(0):S(o).toFixed(0),W=S(o).isZero();if(W&&!d)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");W?F=d.lp_burn_coin:(F=Jt.buildCoinWithBalance(BigInt(o),C,t),d&&t.mergeCoins(F,[d.lp_burn_coin]));let[j,Q,$]=t.moveCall({target:`${h}::pool::withdraw`,typeArguments:[B,T,C],arguments:[t.object(n),t.object(v.global_config_id),t.object(M.global_config_id),t.object(O),F,t.object(rt)]});if(this.buildWithdrawBufferReward({reward_coin_types:N.filter(K=>![L(B,!1),L(T,!1)].includes(K)),pool_id:n,withdraw_cert:$,lp_token_type:C},t),t.moveCall({target:`${h}::pool::destory_withdraw_cert`,typeArguments:[C],arguments:[t.object(n),t.object(v.global_config_id),$]}),s!=="FixedOneSide"){if(r===void 0)throw Error("the slippage is undefined");let K=s==="OnlyCoinA",a=K?Q:j,u=Ae(D,I,E.toString()),_=await this.handleWithSwap(t,a,B,T,I,n,K,r,c,[{poolID:O,ticklower:A.wrapped_position.tick_lower_index,tickUpper:A.wrapped_position.tick_upper_index,deltaLiquidity:Number(u)}],m);if(m&&_)return K?t.mergeCoins(_,[j]):t.mergeCoins(_,[Q]),{return_coin_a:K?_:void 0,return_coin_b:K?void 0:_};t.transferObjects([K?j:Q],this._sdk.senderAddress)}else{if(m)return{return_coin_a:j,return_coin_b:Q};t.transferObjects([j,Q],this._sdk.senderAddress)}return{return_coin_a:void 0,return_coin_b:void 0}}async handleWithSwap(e,t,n,o,s,r,c,d,m,f,p){let{receive_amount_a:h,receive_amount_b:v}=await this.preCalculateWithdrawAmount({pool_id:r,mode:"FixedOneSide",burn_lp_amount:s}),M=c?o:n,C=c?n:o,A=c?v:h;if(S(A).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let D={from:M,target:C,amount:new Yt.default(A),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers,liquidityChanges:f},V=await this._sdk.AggregatorClient.findRouters(D);if(!V)throw Error("not find Router");if(V.error!==void 0)throw Error(`find Router error : ${V.error}`);let O={router:V,inputCoin:t,slippage:d,txb:e,partner:m},B=await this._sdk.AggregatorClient.fixableRouterSwapV3(O);if(p)return B;e.transferObjects([B],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:n,lp_token_type:o},s){let{published_at:r,configs:c}=this._sdk.sdkOptions.vaults;e.forEach(d=>{let m=s.moveCall({target:`${r}::pool::withdraw_buffer_reward`,typeArguments:[o,d],arguments:[s.object(t),s.object(c.global_config_id),n]});s.transferObjects([m],this._sdk.getVerifySenderAddress())})}async preCalculateDepositValue(e,t){let{amount_usd:n,pool_id:o,mode:s,uuid:r}=e,{pool:c,clmmPool:d}=await this.getVaultAndPool(o,!1),{current_sqrt_price:m}=d,{tick_lower_index:f,tick_upper_index:p,coin_type_a:h,coin_type_b:v}=c.clmm_vault.wrapped_position,M="0",C="0",A=await this.pythPrice.getLatestPrice([h,v],!0),D=A[h],V=A[v];if(!D||!V)throw new Error("get coin price failed");switch(s){case"FixedOneSide":{let{amountA:O,amountB:B}=Hi(f,p,new Yt.default(m),n,D.price,V.price,D.coin_decimals,V.coin_decimals);M=O.toString(),C=B.toString();break}case"FlexibleBoth":{let{amountA:O,amountB:B}=_e(S(.5),S(.5),n,D.price,V.price,D.coin_decimals,V.coin_decimals);M=O.toString(),C=B.toString();break}case"OnlyCoinA":{let{amountA:O,amountB:B}=_e(S(1),S(0),n,D.price,V.price,D.coin_decimals,V.coin_decimals);M=O.toString(),C=B.toString();break}case"OnlyCoinB":{let{amountA:O,amountB:B}=_e(S(0),S(1),n,D.price,V.price,D.coin_decimals,V.coin_decimals);M=O.toString(),C=B.toString();break}default:throw new Error(`Unsupported deposit mode: ${s}`)}return t&&this.calculateDepositLpAmountBoth(c,d,M,C).then(O=>{t.onSuccess(O,r)}).catch(O=>{t.onError(O,r)}),{deposit_amount_a:M,deposit_amount_b:C,mode:s}}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:n}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:o,clmmPool:s}=await this.getVaultAndPool(n,!1),{clmm_vault:r}=o,{current_sqrt_price:c,coin_type_a:d,coin_type_b:m}=s,f=r.wrapped_position.tick_lower_index,p=r.wrapped_position.tick_upper_index,h=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,v=t==="OnlyCoinA",M=$t.estLiquidityAndCoinAmountFromOneAmounts(f,p,new Yt.default(h),v,!0,1,new Yt.default(c)),C=v?S(M.coin_amount_b).div(M.coin_amount_a):S(M.coin_amount_a).div(M.coin_amount_b),A=v?S(c).toString():S(1).div(S(c)).toString();try{let E=await this._sdk.VaultsV2.findRouters(v?d:m,v?m:d,h);E&&(A=S(E.swap_out_amount).div(E.swap_in_amount).toString())}catch{}let{swap_amount:D}=je(h,v,A.toString(),C.toString()),V=S(h).sub(D).toFixed(0),O=await this._sdk.VaultsV2.findRouters(v?d:m,v?m:d,D),B=S(O.swap_out_amount).mul(.999).toFixed(0),T=$t.estLiquidityAndCoinAmountFromOneAmounts(f,p,new Yt.default(V),v,!0,1,new Yt.default(c));return v?T.coin_amount_b=B:T.coin_amount_a=B,{swap_result:O,liquidity_info:T}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:n,pool_id:o,uuid:s}=e,r="0",c="0",d,m,{pool:f,clmmPool:p}=await this.getVaultAndPool(o,!1);switch(n){case"FixedOneSide":{let{fixed_amount:h,fixed_coin_a:v}=e,{other_amount:M,lp_amount:C}=await this.calculateDepositOtherSide(f,p,h,v,t,s);m=C,v?(r=h,c=M):(c=h,r=M);break}case"FlexibleBoth":{let{coin_amount_a:h,coin_amount_b:v}=e;r=h,c=v;break}case"OnlyCoinA":{if(e.re_balance){let h=await this.calculateBalanceSwapAmount(e),{swap_result:v,liquidity_info:M}=h,{coin_amount_a:C,coin_amount_b:A}=M;r=C,c=A,d={swap_result:v,coin_amount:e.coin_amount_a}}else r=e.coin_amount_a;break}case"OnlyCoinB":{if(e.re_balance){let h=await this.calculateBalanceSwapAmount(e),{swap_result:v,liquidity_info:M}=h,{coin_amount_a:C,coin_amount_b:A}=M;r=C,c=A,d={swap_result:v,coin_amount:e.coin_amount_b}}else c=e.coin_amount_b;break}default:throw new Error(`Unsupported deposit mode: ${n}`)}return t?this.calculateDepositLpAmountBoth(f,p,r,c).then(h=>{t?.onSuccess(h,s)}).catch(h=>{t?.onError(h,s)}):m=await this.calculateDepositLpAmountBoth(f,p,r,c),{deposit_amount_a:r,deposit_amount_b:c,mode:n,re_balance:d,lp_amount:m}}async getVaultAndPool(e,t=!1){let n=await this.getPool(e,t);if(n===void 0)throw new Error("get vaults pool failed");let o=await this._sdk.CetusClmmSDK.Pool.getPool(n.clmm_vault.clmm_pool_id,t);if(o===void 0)throw new Error("get vaults clmmPool failed");return{clmmPool:o,pool:n}}async calculateDepositOtherSide(e,t,n,o,s,r){let{clmm_vault:c}=e,{current_sqrt_price:d}=t,m=c.wrapped_position.tick_lower_index,f=c.wrapped_position.tick_upper_index,p=$t.estLiquidityAndCoinAmountFromOneAmounts(m,f,new Yt.default(n),o,!0,1,new Yt.default(d)),{coin_amount_a:h,coin_amount_b:v}=p;if(s)this.calculateDepositLpAmountBoth(e,t,h.toString(),v.toString()).then(M=>{s.onSuccess(M,r)}).catch(M=>{s.onError(M,r)});else{let M=await this.calculateDepositLpAmountBoth(e,t,h.toString(),v.toString());return{other_amount:o?v.toString():h.toString(),lp_amount:M}}return{other_amount:o?v.toString():h.toString(),lp_amount:void 0}}async calculateDepositLpAmountBoth(e,t,n,o){let{lp_token_treasury:s,hard_cap:r}=e,c=L(t.coin_type_a,!1),d=L(t.coin_type_b,!1),{rewarderList:m,feeList:f}=await this.getVaultsPositionRewarderAndFee(e.id),p=Ze(e.balances,f,m),h=await Qi(this,e,t,p,!0),v=await this.pythPrice.getLatestPrice([c,d],!0),M=v[c],C=v[d];if(!M)throw Error(`not find ${c} price`);if(!C)throw Error(`not find ${d} price`);let A={};A[c]={price:M,value:n.toString()},A[d]={price:C,value:o.toString()};let D=Ce(A,e.quote_type);return We(s,D,h)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:n}=e,o="0",s="0",r="0",c="0",d,{pool:m,clmmPool:f}=await this.getVaultAndPool(n,!1);switch(t){case"FixedOneSide":let p=await this.calculateWithdrawOtherSide(m,f,e.burn_lp_amount);r=p.burn_lp_amount,o=p.receive_amount_a,s=p.receive_amount_b,c=p.remove_liquidity;break;case"OnlyCoinA":{let h=await this.calculateWithdrawOnlyCoin(m,f,e.burn_lp_amount,!0);r=h.burn_lp_amount,o=h.receive_amount_a,s=h.receive_amount_b,c=h.remove_liquidity,d=h.swap;break}case"OnlyCoinB":{let h=await this.calculateWithdrawOnlyCoin(m,f,e.burn_lp_amount,!1);r=h.burn_lp_amount,o=h.receive_amount_a,s=h.receive_amount_b,c=h.remove_liquidity,d=h.swap;break}default:throw new Error(`Unsupported withdraw mode: ${t}`)}return{remove_liquidity:c,burn_lp_amount:r,receive_amount_a:o,receive_amount_b:s,mode:t,swap:d}}async calculateWithdrawOtherSide(e,t,n){let{clmm_vault:o,lp_token_treasury:s}=e,{current_sqrt_price:r}=t,{coin_type_a:c,coin_type_b:d}=e.clmm_vault.wrapped_position,m=o.wrapped_position.tick_lower_index,f=o.wrapped_position.tick_upper_index,p=o.wrapped_position.liquidity,h=tt.tickIndexToSqrtPriceX64(m),v=tt.tickIndexToSqrtPriceX64(f),M=Ae(s,n,p),{coin_amount_a:C,coin_amount_b:A}=$t.getCoinAmountFromLiquidity(new Yt.default(M),new Yt.default(r),h,v,!1),D=Oe(n,e.balances,s),V=S(C.toString()).add(D[c]?.value||"0").toFixed(0),O=S(A.toString()).add(D[d]?.value||"0").toFixed(0);return{receive_amount_a:V,receive_amount_b:O,burn_lp_amount:n,mode:"FixedOneSide",remove_liquidity:M}}async calculateWithdrawOnlyCoin(e,t,n,o){let{totalReceiveAmount:s,swapAmountIn:r,swapAmountOut:c,removeLiquidity:d,remove_amount_a:m,remove_amount_b:f}=await this.calculateWithdrawOnlyCoinByLpAmount(e,t,o,n);return{receive_amount_a:o?s:"0",receive_amount_b:o?"0":s,burn_lp_amount:n,remove_liquidity:d,swap:{swap_amount_in:r,swap_amount_out:c,remove_amount_a:m,remove_amount_b:f},mode:"FixedOneSide"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,n,o){let{clmm_vault:s,lp_token_treasury:r}=e,{current_sqrt_price:c}=t,{coin_type_a:d,coin_type_b:m}=s.wrapped_position,f=s.wrapped_position.tick_lower_index,p=s.wrapped_position.tick_upper_index,h=s.wrapped_position.liquidity,v=tt.tickIndexToSqrtPriceX64(f),M=tt.tickIndexToSqrtPriceX64(p),C=Ae(r,o,h),{coin_amount_a:A,coin_amount_b:D}=$t.getCoinAmountFromLiquidity(new Yt.default(C),new Yt.default(c),v,M,!1),V=await this.pythPrice.getLatestPrice([d,m],!0),O=V[d],B=V[m];if(!O)throw Error(`not find ${d} price`);if(!B)throw Error(`not find ${m} price`);let T=n?B:O,E=n?O:B,{quote_per_base:N}=Ke(T.price,E.price),F=Oe(o,e.balances,r),I=S(A.toString()).add(F[d]?.value||"0").toFixed(0),W=S(D.toString()).add(F[m]?.value||"0").toFixed(0),j=n?I:W,Q=n?W:I,$=Qt(S(ee(Q,n?B.coin_decimals:O.coin_decimals)).mul(N).toString(),n?O.coin_decimals:B.coin_decimals).toString(),K=S(j).add($).toFixed(0);return{remove_amount_a:I,remove_amount_b:W,burn_lp_amount:o,removeLiquidity:C,is_coin_a:n,originAmount:j,swapAmountIn:Q,swapAmountOut:S($).toFixed(0,wo.default.ROUND_DOWN),totalReceiveAmount:K}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,n=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),o=di(n);(await this._sdk.FullClient.queryEventsByPage({Transaction:o})).data.forEach(f=>{let p=f.parsedJson;if(f.type)switch((0,go.extractStructTagFromType)(f.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=p.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=p.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=p.global_config;break;default:break}});let r=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),c=ae(r);e.pools_handle=c.pools.fields.id.id;let d=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),m=ae(d);return e.oracle_infos_handle=m.oracle_infos.fields.id.id,e.prices_handle=m.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}};var yo=require("@mysten/sui/transactions");var He=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async vestNftIsAvailable(e,t){try{let n=await this._sdk.FullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}});return!ae(n).value.fields.is_pause}catch{return!0}}async getVestCreateEventList(){let{vest:e}=this._sdk.sdkOptions;if(e===void 0)throw new Error("vest is not set config in sdk options");try{let t=`${e.package_id}::hae_vester::CreateEvent`;return(await this._sdk.FullClient.queryEventsByPage({MoveEventType:t})).data.map(o=>{let s=o.parsedJson,r={clmm_vester_id:s.clmm_vester_id,lp_coin_type:L(s.lp_coin_type.name,!1),pool_id:s.pool_id,position_id:s.position_id,vault_id:s.vault_id,vault_vester_id:s.hae_vester_id},c=`${r.vault_id}-VestCreateEvent`;return this._sdk.updateCache(c,r),r})}catch(t){throw new Error(`getVestCreateEventList error: ${t}`)}return[]}async getVaultsVestInfoList(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let n=[];for(let r of e){let c=await this.getVaultVestEvent(r);n.push(c.vault_vester_id)}let o=[];return(await this._sdk.FullClient.batchGetObjects(n,{showContent:!0,showType:!0})).forEach(r=>{try{let c=fi(r);o.push(c);let d=`${c.id}-VaultsVestInfo`;this._sdk.updateCache(d,c)}catch{}}),o}async getVaultsVestInfo(e,t=!0){let n=(await this.getVaultVestEvent(e)).vault_vester_id,o=`${n}-VaultsVestInfo`,s=this._sdk.getCache(o,t);if(s)return s;try{let r=await this._sdk.FullClient.getObject({id:n,options:{showContent:!0,showType:!0}}),c=fi(r);return this._sdk.updateCache(o,c),c}catch(r){throw new Error(`getVaultsVestInfo error: ${r}`)}}async getVaultVestEvent(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let{create_event_list:n}=ce(t),o=n.find(s=>s.vault_id===e);if(!o){let s=`${e}-VestCreateEvent`,r=this._sdk.getCache(s,!1);r?o=r:(o=(await this.getVestCreateEventList()).find(d=>d.vault_id===e),this._sdk.updateCache(s,o))}if(!o)throw new Error("vault_id not found in vest_ids_map");return o}async getOwnerVaultVestNFT(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let n=await this._sdk.FullClient.getOwnedObjectsByPage(e,{filter:{StructType:`${t.package_id}::hae_vester::HaeVesterNFT`},options:{showContent:!0,showType:!0,showOwner:!0}}),o=[];return n.data.forEach(s=>{try{let r=en(s);o.push(r)}catch{}}),o}async buildRedeemPayload(e,t){let{vest:n}=this._sdk.sdkOptions,{clmm_vest:o}=this._sdk.CetusClmmSDK.sdkOptions;if(!n)throw new Error("vest is not set config in sdk options");if(!o)throw new Error("clmm_vest is not set config in clmm sdk options");let{versioned_id:s}=ce(n),{versioned_id:r,clmm_vest_id:c}=ce(o);t=t||new yo.Transaction;for(let d of e){let{vault_id:m,vesting_nft_id:f,period:p,coin_type_a:h,coin_type_b:v}=d,M=await this.getVaultVestEvent(m);t.moveCall({package:n.published_at,module:"hae_vester",function:"redeem_coin",arguments:[t.object(s),t.object(M.vault_vester_id),t.object(f),t.object(r),t.object(c),t.object(M.pool_id),t.pure.u16(p),t.object(rt)],typeArguments:[h,v]})}return t}};var wn=require("@mysten/sui/transactions"),ge=ie(require("bn.js")),vo=require("@cetusprotocol/aggregator-sdk"),Mo=require("@cetusprotocol/sui-clmm-sdk");var Co=require("@mysten/sui/utils"),Po=ie(require("decimal.js"));var Xt=require("@cetusprotocol/dlmm-sdk");var Qe=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:n}=e.sdkOptions;this.pythPrice=new De(e,n,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,t.configs.versioned_id,t.configs.oracle_infos_handle,!0)}get PythPrice(){return this.pythPrice}get sdk(){return this._sdk}async getOwnerVaultsBalance(e,t,n=!0){let{pool:o}=await this.getVaultAndPool(t,!1),r=(await this._sdk.FullClient.getBalance({owner:e,coinType:o.lp_token_type})).totalBalance;return await hi(this._sdk,r,t,e,n)}async getOwnerVaultsBalanceList(e){let{data:t}=await this.getPoolList(),n=[];for(let o=0;o<t.length;o++){let s=await this.getOwnerVaultsBalance(e,t[o].id);n.push(s)}return n}async buildCollectRewardAndFeePayload(e,t,n){let{pool:o,marketList:s}=await this.getVaultAndPool(e,!1),{lp_token_type:r,coin_type_a:c,coin_type_b:d}=o;for(let m of s)if(m.type==="DLMM"){let{position_list:f}=m;f.forEach(p=>{let{id:h,pool_id:v}=p.position,M=m.certified_pool_obj[v],{reward_manager:C,id:A}=M;this.buildDlmmCollectRewardPayload({reward_coin_types:[...C.rewards.map(D=>D.reward_coin)],lp_token_type:r,pool_id:e,certified_pool_id:A,position_id:h,coin_type_a:c,coin_type_b:d,withdraw_cert:n},t),this.buildDlmmCollectFeePayload({lp_token_type:r,pool_id:e,certified_pool_id:A,position_id:h,coin_type_a:c,coin_type_b:d,withdraw_cert:n},t)})}else if(m.type==="CLMM"){let{position_list:f}=m;f.forEach(p=>{let{id:h,pool_id:v}=p.position,M=m.certified_pool_obj[v],{rewarder_infos:C,id:A}=M;this.buildClmmCollectRewardPayload({reward_coin_types:[...C.map(D=>D.coin_type)],lp_token_type:r,pool_id:e,certified_pool_id:A,position_id:h,coin_type_a:c,coin_type_b:d,withdraw_cert:n},t),this.buildClmmCollectFeePayload({lp_token_type:r,pool_id:e,certified_pool_id:A,position_id:h,coin_type_a:c,coin_type_b:d,withdraw_cert:n},t)})}}async getVaultsPositionRewarderAndFee(e){let t=[],n=[],o=[],s=[];try{let{pool:r}=await this.getVaultAndPool(e,!1),c=`getVaultsV2PositionRewarderAndFee_${e}`,d=this._sdk.getCache(c);if(d)return d;let{coin_type_a:m,coin_type_b:f}=r,p=new wn.Transaction;await this.buildCollectRewardAndFeePayload(e,p),(await this._sdk.FullClient.sendSimulationTransaction(p,(0,Co.normalizeSuiAddress)("0x0")))?.events.forEach(v=>{let{parsedJson:M,type:C}=v;C.includes("CollectDlmmFeeEvent")&&(t.push({coin_type:L(m,!1),value:M.amount_a}),t.push({coin_type:L(f,!1),value:M.amount_b})),C.includes("CollectClmmFeeEvent")&&(n.push({coin_type:L(m,!1),value:M.amount_a}),n.push({coin_type:L(f,!1),value:M.amount_b})),C.includes("CollectClmmRewardEvent")&&s.push({coin_type:L(M.reward_type.name,!1),value:M.amount}),C.includes("CollectDlmmRewardEvent")&&o.push({coin_type:L(M.reward_type.name,!1),value:M.amount})}),this._sdk.updateCache(c,{dlmmFeeList:t,dlmmRewarderList:o,clmmFeeList:n,clmmRewarderList:s},10*1e3)}catch{}return{dlmmFeeList:t,dlmmRewarderList:o,clmmFeeList:n,clmmRewarderList:s}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaultsV2:n}=this._sdk.sdkOptions,{FullClient:o}=this._sdk,s=await o.getDynamicFieldsByPage(n.configs.pools_handle,e),r=s.data.map(c=>c.name.value);if(r.length>0){let c=await this.getAssignPoolList(r);t.data.push(...c),t.next_cursor=s.next_cursor,t.has_next_page=s.has_next_page}return t}async getPool(e,t=!0){let n=`getPool_${e}`,o=this._sdk.getCache(n,t);if(o)return o;let s=await this.getAssignPoolList([e]);if(s.length>0){let r=s[0];return this._sdk.updateCache(n,r),r}throw new Error(`get pool failed ${e}`)}async getAssignPoolList(e){let t=[];if(e.length>0){(await this._sdk.FullClient.batchGetObjects(e,{showContent:!0})).forEach(s=>{let r=pi(s.data.content);t.push(r)});let o=t.map(s=>s.id);if(o.length>0){let s=await this.geMarketList(o);t.forEach(r=>{let c=s[r.id];if(c){r.markets=c;let m=0;c.forEach(f=>{m+=f.position_list.length}),r.is_multiple_pool=m!==1}let d=`getPool_${r.id}`;this._sdk.updateCache(d,r)})}}return t}async getVaultsAggregatedDataByIds(e){let{vaultsV2:t,vaults:n}=this._sdk.sdkOptions,o=[],s=[],r={},c={};if(e.length>0){let p=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0});for(let h=0;h<p?.length;h++){let v=p[h],{type:M}=v.data.content;if(M.includes(`${t.package_id}::vault::Vault`)){let C=pi(v.data.content);o.push(C)}else if(M.includes(`${n.package_id}::pool::Pool`)){let C=Se(v.data.content);this._sdk.updateCache(`getPool_${C.id}`,C),s.push(C)}}}let d=o.map(p=>p.id);if(d.length>0){let p=await this.geMarketList(d);o.forEach(h=>{let v=p[h.id];if(v){h.markets=v;let C=0;v.forEach(A=>{C+=A.position_list.length}),h.is_multiple_pool=C!==1}let M=`getPool_${h.id}`;this._sdk.updateCache(M,h)})}let m=new Set;s.forEach(p=>{m.add(p.clmm_vault.clmm_pool_id)}),o.forEach(p=>{p.markets.forEach(h=>{h.position_list.forEach(v=>{let{pool_id:M}=v.position;m.add(M)})})});let f=Array.from(m);if(f.length>0){let{clmm_pool:p}=this._sdk.CetusClmmSDK.sdkOptions,{dlmm_pool:h}=this._sdk.CetusDlmmSDK.sdkOptions;(await this._sdk.FullClient.batchGetObjects(f,{showContent:!0})).forEach(M=>{let{type:C}=M.data.content;if(C.includes(`${p.package_id}::pool::Pool`)){let A=(0,Mo.buildPool)(M);r[A.id]=A;let D=`${A.id}_getPoolObject`;this._sdk.updateCache(D,A)}else if(C.includes(`${h.package_id}::pool::Pool`)){let A=(0,Xt.parseDlmmPool)(M);c[A.id]=A;let D=`${A.id}_getDlmmPool`;this._sdk.updateCache(D,A)}})}return{v1:s,v2:o,clmmPoolMap:r,dlmmPoolMap:c}}async geMarketList(e){let t={},n=[];e.forEach(s=>{let r=ln(s),c=cn(s);n.push(r,c)}),(await this._sdk.FullClient.batchGetObjects(n,{showContent:!0})).forEach(s=>{let r=on(s?.data?.content);if(r){let c=t[r.vault_id]||[];c.push(r),t[r.vault_id]=c}});for(let s in t){let r=t[s];for(let c of r){let d=await this.getMarketPositionList(c.positions_handle.id);c.position_list=d}}return t}async getMarketPositionList(e){let t=[],o=(await this._sdk.FullClient.getDynamicFieldsByPage(e)).data.map(s=>s.objectId);return o.length>0&&(await this._sdk.FullClient.batchGetObjects(o,{showContent:!0})).forEach(r=>{try{let{type:c}=r.data?.content;if(c){if(c.includes("DLMMPosition")){let d=rn(r?.data?.content);t.push(d)}else if(c?.includes("CLMMPosition")){let d=sn(r?.data?.content);t.push(d)}}}catch{}}),t}buildDlmmCollectRewardPayload(e,t){let{reward_coin_types:n,lp_token_type:o,pool_id:s,certified_pool_id:r,position_id:c,coin_type_a:d,coin_type_b:m,withdraw_cert:f}=e,{published_at:p,configs:h}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:v}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:M,global_config_id:C}=ce(v);f?n.forEach(A=>{t.moveCall({target:`${p}::vault::collect_dlmm_reward_on_withdraw`,typeArguments:[d,m,o,A],arguments:[t.object(s),f,t.object(r),t.object(c),t.object(C),t.object(M),t.object(h.versioned_id)]})}):n.forEach(A=>{t.moveCall({target:`${p}::vault::collect_dlmm_reward`,typeArguments:[d,m,o,A],arguments:[t.object(s),t.object(r),t.object(c),t.object(C),t.object(M),t.object(h.versioned_id)]})})}buildClmmCollectRewardPayload(e,t){let{reward_coin_types:n,lp_token_type:o,pool_id:s,certified_pool_id:r,position_id:c,coin_type_a:d,coin_type_b:m,withdraw_cert:f}=e,{published_at:p,configs:h}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:v}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:M,global_config_id:C}=ce(v);f?n.forEach(A=>{t.moveCall({target:`${p}::vault::collect_clmm_reward_on_withdraw`,typeArguments:[d,m,o,A],arguments:[t.object(s),f,t.object(r),t.object(c),t.object(C),t.object(M),t.object(h.versioned_id),t.object(rt)]})}):n.forEach(A=>{t.moveCall({target:`${p}::vault::collect_clmm_reward`,typeArguments:[d,m,o,A],arguments:[t.object(s),t.object(r),t.object(c),t.object(M),t.object(C),t.object(h.versioned_id),t.object(rt)]})})}buildDlmmCollectFeePayload(e,t){let{lp_token_type:n,pool_id:o,certified_pool_id:s,position_id:r,coin_type_a:c,coin_type_b:d,withdraw_cert:m}=e,{published_at:f,configs:p}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:h}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:v,global_config_id:M}=ce(h);m?t.moveCall({target:`${f}::vault::collect_dlmm_fee_on_withdraw`,typeArguments:[c,d,n],arguments:[t.object(o),m,t.object(s),t.object(r),t.object(M),t.object(v),t.object(p.versioned_id)]}):t.moveCall({target:`${f}::vault::collect_dlmm_fee`,typeArguments:[c,d,n],arguments:[t.object(o),t.object(s),t.object(r),t.object(M),t.object(v),t.object(p.versioned_id)]})}buildClmmCollectFeePayload(e,t){let{lp_token_type:n,pool_id:o,certified_pool_id:s,position_id:r,coin_type_a:c,coin_type_b:d,withdraw_cert:m}=e,{published_at:f,configs:p}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:h}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:v,global_config_id:M}=ce(h);m?t.moveCall({target:`${f}::vault::collect_clmm_fee_on_withdraw`,typeArguments:[c,d,n],arguments:[t.object(o),m,t.object(s),t.object(r),t.object(M),t.object(p.versioned_id)]}):t.moveCall({target:`${f}::vault::collect_clmm_fee`,typeArguments:[c,d,n],arguments:[t.object(o),t.object(s),t.object(r),t.object(M),t.object(p.versioned_id)]})}async buildDepositPayload(e,t){let{published_at:n,configs:o}=this._sdk.sdkOptions.vaultsV2,{pool_id:s,amount_a:r,amount_b:c,return_lp_coin:d,re_balance:m,coin_a_input:f,coin_b_input:p}=e,{pool:h,marketList:v}=await this.getVaultAndPool(s,!1),{coin_type_a:M,coin_type_b:C,lp_token_type:A}=h,D=[M,C];for(let T of v)T.type==="DLMM"?T.position_list.forEach(E=>{let{pool_id:N}=E.position,F=T.certified_pool_obj[N],{reward_manager:I}=F,W=I.rewards.map(j=>L(j.reward_coin,!1));D=Ee(W,M,C)}):T.type==="CLMM"&&T.position_list.forEach(E=>{let{pool_id:N}=E.position,F=T.certified_pool_obj[N],{rewarder_infos:I}=F,W=I.map(j=>L(j.coin_type,!1));D=Ee([...D,...W],M,C)});await this.pythPrice.buildUpdatePythPricePayloadV2(D,t);for(let T of v)if(T.type==="DLMM"){let{dlmm_pool:E}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:N}=ce(E),{position_list:F}=T;F.forEach(I=>{let{id:W,pool_id:j}=I.position;t.moveCall({target:`${n}::vault::calculate_dlmm_position_amounts`,typeArguments:[M,C,A],arguments:[t.object(s),t.object(o.pyth_oracle_id),t.object(j),t.object(W),t.object(N),t.object(o.versioned_id),t.object(rt)]})})}else if(T.type==="CLMM"){let{clmm_pool:E}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:N}=ce(E),{position_list:F}=T;F.forEach(I=>{let{id:W,pool_id:j}=I.position;t.moveCall({target:`${n}::vault::calculate_clmm_position_amounts`,typeArguments:[M,C,A],arguments:[t.object(s),t.object(o.pyth_oracle_id),t.object(j),t.object(W),t.object(N),t.object(o.versioned_id),t.object(rt)]})})}t.moveCall({target:`${n}::vault::calculate_aum`,typeArguments:[A],arguments:[t.object(s),t.object(o.pyth_oracle_id),t.object(o.versioned_id),t.object(rt)]});let V,O;if(m&&m.swap_result){let{swap_result:T,coin_amount:E,mode:N,swap_slippage:F}=m,{swap_in_amount:I,route_obj:W}=T,j=Jt.buildCoinWithBalance(BigInt(E),N==="OnlyCoinA"?M:C,t),Q=t.splitCoins(j,[I]),$={router:W,slippage:F,txb:t,inputCoin:Q},K=await this._sdk.AggregatorClient.fixableRouterSwapV3($);V=N==="OnlyCoinA"?j:K,O=N==="OnlyCoinA"?K:j}else V=f||Jt.buildCoinWithBalance(BigInt(r),M,t),O=p||Jt.buildCoinWithBalance(BigInt(c),C,t);let B=t.moveCall({target:`${n}::vault::deposit`,typeArguments:[M,C,A],arguments:[t.object(s),t.object(o.global_config_id),t.object(o.pyth_oracle_id),V,O,t.object(rt),t.object(o.versioned_id)]});if(d)return B;t.transferObjects([B],this._sdk.getVerifySenderAddress())}async buildWithdrawPayload(e,t){let{pool_id:n,burn_lp_amount:o,mode:s,slippage:r,partner:c,extra_burn:d}=e,{pool:m,marketList:f}=await this.getVaultAndPool(n,!1),{lp_token_type:p,coin_type_a:h,coin_type_b:v}=m;t=t||new wn.Transaction;let M,C=d?S(d.burn_lp_amount).add(S(o)).toFixed(0):S(o).toFixed(0),A=S(o).isZero();if(A&&!d)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");A?M=d.lp_burn_coin:(M=Jt.buildCoinWithBalance(BigInt(o),p,t),d&&d.lp_burn_coin&&t.mergeCoins(M,[d.lp_burn_coin]));let{published_at:D,configs:V}=this._sdk.sdkOptions.vaultsV2,{config:O}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:B}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,T=t.moveCall({target:`${D}::vault::new_withdraw_cert`,typeArguments:[p],arguments:[t.object(n),M,t.object(V.versioned_id)]}),E=[];for(let j of f)if(j.type==="DLMM"){let{position_list:Q}=j;Q.forEach($=>{let{id:K,pool_id:a}=$.position,u=j.certified_pool_obj[a],{reward_manager:_}=u,g=_.rewards.map(b=>L(b.reward_coin,!1));E.push(...g),t.moveCall({target:`${D}::vault::withdraw_dlmm`,typeArguments:[h,v,p],arguments:[t.object(n),T,t.object(a),t.object(K),t.object(O.global_config_id),t.object(O.versioned_id),t.object(V.versioned_id),t.object(rt)]})})}else if(j.type==="CLMM"){let{position_list:Q}=j;Q.forEach($=>{let{id:K,pool_id:a}=$.position,u=j.certified_pool_obj[a],{rewarder_infos:_}=u,g=_.map(b=>L(b.coin_type,!1));E.push(...g),t.moveCall({target:`${D}::vault::withdraw_clmm`,typeArguments:[h,v,p],arguments:[t.object(n),T,t.object(a),t.object(K),t.object(B.global_config_id),t.object(V.versioned_id),t.object(rt)]})})}await this.buildCollectRewardAndFeePayload(n,t,T),t.moveCall({target:`${D}::vault::finalize_buffer_assets`,typeArguments:[p],arguments:[t.object(n),T,t.object(V.versioned_id)]});let N=new Set;E.forEach(j=>N.add(j)),N.add(h),N.add(v);let F=Array.from(N),I=s!=="FixedOneSide"?[s==="OnlyCoinA"?v:h]:[],W=this.buildWithdrawBufferReward({reward_coin_types:F,pool_id:n,withdraw_cert:T,lp_token_type:p,not_transfer_coin_types:I},t);if(t.moveCall({target:`${D}::vault::destroy_withdraw_cert`,typeArguments:[p],arguments:[t.object(n),T,t.object(V.versioned_id)]}),s!=="FixedOneSide"){if(r===void 0)throw Error("the slippage is undefined");let j=s==="OnlyCoinA",Q=j?v:h,$=W.find(K=>K.coin_type===Q).reward_coin_object_id;await this.handleWithSwap(t,$,h,v,C,n,j,r,c)}}async handleWithSwap(e,t,n,o,s,r,c,d,m){let{receive_amount_a:f,receive_amount_b:p}=await this.preCalculateWithdrawAmount({pool_id:r,mode:"FixedOneSide",burn_lp_amount:s}),h=c?o:n,v=c?n:o,M=c?p:f;if(S(M).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let C={from:h,target:v,amount:new ge.default(M),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers},A=await this._sdk.AggregatorClient.findRouters(C);if(!A)throw Error("not find Router");if(A.error!==void 0)throw Error(`find Router error : ${A.error}`);let D={router:A,inputCoin:t,slippage:d,txb:e,partner:m},V=await this._sdk.AggregatorClient.fixableRouterSwapV3(D);e.transferObjects([V],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:n,lp_token_type:o,not_transfer_coin_types:s},r){let{published_at:c,configs:d}=this._sdk.sdkOptions.vaultsV2;return e.map(m=>{let f=r.moveCall({target:`${c}::vault::withdraw_asset`,typeArguments:[o,m],arguments:[r.object(t),n,r.object(d.versioned_id)]});return s.includes(m)||r.transferObjects([f],r.pure.address(this._sdk.getVerifySenderAddress())),{coin_type:m,reward_coin_object_id:f}})}async preCalculateDepositValue(e,t){let{amount_usd:n,pool_id:o,mode:s,uuid:r,re_balance:c,coin_decimals_a:d,coin_decimals_b:m}=e,{pool:f,marketList:p}=await this.getVaultAndPool(o,!1),{coin_type_a:h,coin_type_b:v}=f,M=await this.pythPrice.getLatestPrice([h,v],!0),C=M[h],A=M[v];if(!C)throw new Error(`get ${h} price failed`);if(!A)throw new Error(`get ${v} price failed`);let D="0",V="0";switch(s){case"FlexibleBoth":{let{position_amount_a_rate:B,position_amount_b_rate:T}=f.is_multiple_pool?{position_amount_a_rate:S(.5),position_amount_b_rate:S(.5)}:await this.calculatePositionValueRates(f,M),{amountA:E,amountB:N}=_e(B,T,n,C.price,A.price,C.coin_decimals,A.coin_decimals);D=E,V=N;break}case"OnlyCoinA":{let{amountA:B,amountB:T}=_e(S(1),S(0),n,C.price,A.price,C.coin_decimals,A.coin_decimals);D=B,V=T;break}case"OnlyCoinB":{let{amountA:B,amountB:T}=_e(S(0),S(1),n,C.price,A.price,C.coin_decimals,A.coin_decimals);D=B,V=T;break}}return await this.preCalculateDepositAmount({mode:s,pool_id:o,uuid:r,coin_amount_a:D,coin_amount_b:V,re_balance:c,coin_decimals_a:d,coin_decimals_b:m},t)}async calculateClmmBalanceSwapAmount(e,t){let{mode:n,pool_id:o}=e;if(n==="OnlyCoinA"||n==="OnlyCoinB"){let{certified_pool_obj:s,position_list:r}=t,c=r[0].position,{current_sqrt_price:d,coin_type_a:m,coin_type_b:f}=s[c.pool_id],{tick_lower_index:p,tick_upper_index:h}=c,v=p,M=h,C=n==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,A=n==="OnlyCoinA",D=$t.estLiquidityAndCoinAmountFromOneAmounts(v,M,new ge.default(C),A,!0,1,new ge.default(d)),V=A?S(D.coin_amount_b).div(D.coin_amount_a):S(D.coin_amount_a).div(D.coin_amount_b),O=A?S(d).toString():S(1).div(S(d)).toString();try{let I=await this._sdk.VaultsV2.findRouters(A?m:f,A?f:m,C);I&&(O=S(I.swap_out_amount).div(I.swap_in_amount).toString())}catch{}let{swap_amount:B}=je(C,A,O.toString(),V.toString()),T=S(C).sub(B).toFixed(0),E=await this._sdk.VaultsV2.findRouters(A?m:f,A?f:m,B),N=S(E.swap_out_amount).mul(.999).toFixed(0),F=$t.estLiquidityAndCoinAmountFromOneAmounts(v,M,new ge.default(T),A,!0,1,new ge.default(d));return A?F.coin_amount_b=N:F.coin_amount_a=N,{swap_result:E,liquidity_info:F}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${n}`)}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:n,coin_decimals_a:o,coin_decimals_b:s}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:r,marketList:c}=await this.getVaultAndPool(n,!1),{coin_type_a:d,coin_type_b:m}=r,f=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,p=t==="OnlyCoinA",h=c.find(C=>C.position_list.length>0);if(r.is_multiple_pool||!h){let C=await this.findRouters(p?d:m,p?m:d,f),{swap_out_amount:A,swap_in_amount:D}=C,V=p?o:s,O=p?s:o,B=ee(D,V),T=ee(A,O),E=S(T).div(B).toString(),N=await this.pythPrice.getLatestPrice([d,m],!0),F=N[d],I=N[m];if(!F||!I)throw new Error(`not find ${d} or ${m} price`);let W=un(p?B:"0",p?"0":B,F.price,I.price,E,p),j=S(Qt(W,V).toString()).toFixed(0),Q=S(f).sub(j).toFixed(0);if(S(Q).lt(1)||S(j).lt(1))throw new Error("amount is less than 1");let $=await this.findRouters(p?r.coin_type_a:r.coin_type_b,p?r.coin_type_b:r.coin_type_a,j),K=S($.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:p?Q:K,amount_b:p?K:Q},swap_result:$}}let v=c.find(C=>C.type==="CLMM");if(v){let{swap_result:C,liquidity_info:A}=await this.calculateClmmBalanceSwapAmount({...e},v);return{swap_result:C,liquidity_info:{bins:[],amount_a:A.coin_amount_a,amount_b:A.coin_amount_b}}}let M=c.find(C=>C.type==="DLMM");if(M){let C=M.certified_pool_obj[M.position_list[0].position.pool_id],A=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(C.bin_manager.bin_manager_handle,C.active_id,C.bin_step,!1),{active_id:D,bin_step:V}=C,O=Xt.BinUtils.getPricePerLamportFromBinId(C.active_id,C.bin_step),B=S(O).mul(1-.05),T=S(O).mul(1+.05),E=Xt.BinUtils.getBinIdFromLamportPrice(B.toString(),C.bin_step,!1),N=Xt.BinUtils.getBinIdFromLamportPrice(T.toString(),C.bin_step,!1),F=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:C.id,coin_amount:f,fix_amount_a:p,active_id:D,bin_step:V,lower_bin_id:E,upper_bin_id:N,active_bin_of_pool:A,strategy_type:Xt.StrategyType.Spot}),I=p?S(F.amount_b).div(F.amount_a):S(F.amount_a).div(F.amount_b),W=p?Xt.BinUtils.getPricePerLamportFromBinId(D,V):S(1).div(Xt.BinUtils.getPricePerLamportFromBinId(D,V)).toString();try{let P=await this.findRouters(p?r.coin_type_a:r.coin_type_b,p?r.coin_type_b:r.coin_type_a,f);P&&(W=S(P.swap_out_amount).div(P.swap_in_amount).toString())}catch{}let{swap_amount:j,final_amount_a:Q,final_amount_b:$}=je(f,p,W,I.toString()),K=S(f).sub(j).toFixed(0),a=await this.findRouters(p?r.coin_type_a:r.coin_type_b,p?r.coin_type_b:r.coin_type_a,j),u=S(a.swap_out_amount).mul(.999).toFixed(0),_=p?K:u,g=p?u:K,b=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:C.id,amount_a:_,amount_b:g,active_id:D,bin_step:V,lower_bin_id:E,upper_bin_id:N,active_bin_of_pool:A,strategy_type:Xt.StrategyType.Spot});return p?b.amount_b=a.swap_out_amount:b.amount_a=a.swap_out_amount,{swap_result:a,liquidity_info:b}}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:n,pool_id:o,uuid:s}=e,{pool:r,marketList:c}=await this.getVaultAndPool(o,!1);switch(n){case"FixedOneSide":{let{fixed_amount:d,fixed_coin_a:m,coin_decimals_a:f,coin_decimals_b:p}=e;return await this.calculateDepositOtherSide(r,c,d,m,f,p,t,s)}case"FlexibleBoth":{let{coin_amount_a:d,coin_amount_b:m}=e;return await this.calculateDepositFlexibleBoth(r,d,m,t,s)}case"OnlyCoinA":{let{coin_amount_a:d,re_balance:m}=e;if(m){let f=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:h}=f,{amount_a:v,amount_b:M}=h,C=await this.calculateDepositFlexibleBoth(r,v,M,t,s);return C.re_balance={swap_result:p,coin_amount:d,mode:"OnlyCoinA"},C}else return await this.calculateDepositFlexibleBoth(r,d,"0",t,s)}case"OnlyCoinB":{let{coin_amount_b:d,re_balance:m}=e;if(m){let f=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:h}=f,{amount_a:v,amount_b:M}=h,C=await this.calculateDepositFlexibleBoth(r,v,M,t,s);return C.re_balance={swap_result:p,coin_amount:d,mode:"OnlyCoinB"},C}else return await this.calculateDepositFlexibleBoth(r,"0",d,t,s)}}throw new Error(`Unsupported deposit mode: ${n}`)}async getVaultAndPool(e,t=!1){let n=await this.getPool(e,t);if(n===void 0)throw new Error("get vaults pool failed");let{markets:o}=n,s=[];for(let r of o){let c={};if(r.type==="DLMM"){for(let d of r.position_list){let{pool_id:m}=d.position,f=await this._sdk.CetusDlmmSDK.Pool.getPool(m,t);if(!f)throw new Error(`get vaults dlmmPool failed ${m}`);c[m]=f}s.push({certified_pool_obj:c,...r})}else{for(let d of r.position_list){let{pool_id:m}=d.position,f=await this._sdk.CetusClmmSDK.Pool.getPool(m,t);if(!f)throw new Error(`get vaults clmmPool failed ${m}`);c[m]=f}s.push({certified_pool_obj:c,...r})}}if(s.length===0)throw new Error(`get vaults marketList failed ${e}`);return{marketList:s,pool:n}}async calculatePositionValueRates(e,t){let{lp_token_treasury:n,coin_type_a:o,coin_type_b:s}=e;if(S(n).eq(0))return{position_amount_a_rate:S(.5),position_amount_b_rate:S(.5)};let{position_amount_a:r,position_amount_b:c}=await hi(this._sdk,n,e.id),d=t[o],m=t[s];if(!d)throw Error(`not find ${o} price`);if(!m)throw Error(`not find ${s} price`);let f=S(ee(r,d.coin_decimals)).mul(d.price),p=S(ee(c,m.coin_decimals)).mul(m.price),h=S(f).add(p),v=S(f).div(h),M=S(1).sub(v);return{position_amount_a_rate:v,position_amount_b_rate:M}}async calculateDepositAmountByValue(e,t,n,o,s,r){let c=await this.PythPrice.getLatestPrice([s,r],!0),d=c[s],m=c[r];if(!d)throw Error(`not find ${s} price`);if(!m)throw Error(`not find ${r} price`);let f="0",p="0";if(e){f=t;let h=S(ee(f,n)).mul(d.price);p=S(Qt(S(h).div(m.price).toString(),o)).toFixed(0)}else{p=t;let h=S(ee(p,o)).mul(m.price);f=S(Qt(S(h).div(d.price).toString(),n)).toFixed(0)}if(S(f).lt(1)||S(p).lt(1))throw new Error("is less than 1");return{deposit_amount_a:f,deposit_amount_b:p}}async calculateDepositDlmmAmountsV2(e,t,n,o){let{markets:s}=e,{coin_type_a:r,coin_type_b:c}=e,d=s[0].position_list[0].position,m=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(t.bin_manager.bin_manager_handle,t.active_id,t.bin_step,!1),f=Xt.BinUtils.getPricePerLamportFromBinId(t.active_id,t.bin_step),p=S(f).mul(1-.05),h=S(f).mul(1+.05),v=Xt.BinUtils.getBinIdFromLamportPrice(p.toString(),t.bin_step,!1),M=Xt.BinUtils.getBinIdFromLamportPrice(h.toString(),t.bin_step,!1),C={pool_id:d.pool_id,coin_amount:S(o).mul(1e5).toFixed(0),fix_amount_a:n,active_id:t.active_id,bin_step:t.bin_step,lower_bin_id:v,upper_bin_id:M,strategy_type:Xt.StrategyType.Spot,active_bin_of_pool:m},A=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo(C),{amount_a:D,amount_b:V}=A;return{deposit_amount_a:S(D).div(1e5).toFixed(0),deposit_amount_b:S(V).div(1e5).toFixed(0)}}async calculateDepositClmmAmounts(e,t,n,o){let{markets:s}=e,r=s[0].position_list[0].position,{tick_lower_index:c,tick_upper_index:d}=r,{current_sqrt_price:m,coin_type_a:f,coin_type_b:p}=t,{coin_amount_a:h,coin_amount_b:v}=$t.estLiquidityAndCoinAmountFromOneAmounts(c,d,new ge.default(o),n,!0,1,new ge.default(m));return{deposit_amount_a:h.toString(),deposit_amount_b:v.toString()}}async calculateDepositOtherSide(e,t,n,o,s,r,c,d){let m="0",f="0",{coin_type_a:p,coin_type_b:h}=e;if(e.is_multiple_pool){let v=await this.calculateDepositAmountByValue(o,n,s,r,p,h);m=v.deposit_amount_a,f=v.deposit_amount_b}else if(t[0].type==="DLMM"&&t[0].position_list.length>0){let v=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:M,deposit_amount_b:C}=await this.calculateDepositDlmmAmountsV2(e,v,o,n);m=M,f=C}else if(t[0].type==="CLMM"&&t[0].position_list.length>0){let v=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:M,deposit_amount_b:C}=await this.calculateDepositClmmAmounts(e,v,o,n);m=S(M).add(m).toFixed(0),f=S(C).add(f).toFixed(0)}else{let v=await this.calculateDepositAmountByValue(o,n,s,r,p,h);m=v.deposit_amount_a,f=v.deposit_amount_b}if(c)this.calculateDepositLpAmountBoth(e,m,f).then(v=>{c.onSuccess(v,d)}).catch(v=>{c.onError(v,d)});else{let v=await this.calculateDepositLpAmountBoth(e,m,f);return{deposit_amount_a:m,deposit_amount_b:f,lp_amount:v,uuid:d,mode:"FixedOneSide"}}return{deposit_amount_a:m,deposit_amount_b:f,lp_amount:void 0,uuid:d,mode:"FixedOneSide"}}async calculateDepositFlexibleBoth(e,t,n,o,s){if(o)this.calculateDepositLpAmountBoth(e,t,n).then(r=>{o.onSuccess(r,s)}).catch(r=>{o.onError(r,s)});else{let r=await this.calculateDepositLpAmountBoth(e,t,n);return{deposit_amount_a:t,deposit_amount_b:n,lp_amount:r,uuid:s,mode:"FlexibleBoth"}}return{deposit_amount_a:t,deposit_amount_b:n,lp_amount:void 0,uuid:s,mode:"FlexibleBoth"}}async calculateDepositLpAmountBoth(e,t,n){let{lp_token_treasury:o,markets:s,quote_type:r,coin_type_a:c,coin_type_b:d}=e,m=L(c,!1),f=L(d,!1),{dlmmRewarderList:p,dlmmFeeList:h,clmmRewarderList:v,clmmFeeList:M}=await this.getVaultsPositionRewarderAndFee(e.id),C=Ze(e.buffer_assets,[...h,...M],[...p,...v]),A=await an(this._sdk,e.id,C,!0),D=await this.pythPrice.getLatestPrice([m,f],!0),V=D[m],O=D[f];if(!V)throw Error(`not find ${m} price`);if(!O)throw Error(`not find ${f} price`);let B={};B[m]={price:V,value:t.toString()},B[f]={price:O,value:n.toString()};let T=Ce(B,r);return We(o,T,A)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:n}=e,{pool:o}=await this.getVaultAndPool(n,!1);switch(t){case"FixedOneSide":{let{burn_lp_amount:s}=e;return await this.calculateWithdrawOtherSide(n,s)}case"OnlyCoinA":return await this.calculateWithdrawOnlyCoin(o,e.burn_lp_amount,!0);case"OnlyCoinB":return await this.calculateWithdrawOnlyCoin(o,e.burn_lp_amount,!1)}throw new Error(`Unsupported withdraw mode: ${t}`)}async calculateWithdrawOtherSide(e,t){let{amount_a:n,amount_b:o}=await Xe(this._sdk,t,e);return{receive_amount_a:n,receive_amount_b:o,burn_lp_amount:t,mode:"FixedOneSide"}}async calculateWithdrawOnlyCoin(e,t,n){let{totalReceiveAmount:o,swapAmountIn:s,swapAmountOut:r,remove_amount_a:c,remove_amount_b:d}=await this.calculateWithdrawOnlyCoinByLpAmount(e,n,t);return{receive_amount_a:n?o:"0",receive_amount_b:n?"0":o,burn_lp_amount:t,swap:{swap_amount_in:s,swap_amount_out:r,remove_amount_a:c,remove_amount_b:d},mode:n?"OnlyCoinA":"OnlyCoinB"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,n){let{coin_type_a:o,coin_type_b:s}=e,{amount_a:r,amount_b:c}=await Xe(this._sdk,n,e.id),d=await this.pythPrice.getLatestPrice([o,s],!0),m=d[o],f=d[s];if(!m)throw Error(`not find ${o} price`);if(!f)throw Error(`not find ${s} price`);let p=t?f:m,h=t?m:f,{quote_per_base:v}=Ke(p.price,h.price),M=t?r:c,C=t?c:r,A=Qt(S(ee(C,t?f.coin_decimals:m.coin_decimals)).mul(v).toString(),t?m.coin_decimals:f.coin_decimals).toString(),D=S(M).add(A).toFixed(0);return{remove_amount_a:r,remove_amount_b:c,burn_lp_amount:n,is_coin_a:t,originAmount:M,swapAmountIn:C,swapAmountOut:S(A).toFixed(0,Po.default.ROUND_DOWN),totalReceiveAmount:D}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,n=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),o=di(n);(await this._sdk.FullClient.queryEventsByPage({Transaction:o})).data.forEach(f=>{let p=f.parsedJson;if(f.type)switch((0,vo.extractStructTagFromType)(f.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=p.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=p.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=p.global_config;break;default:break}});let r=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),c=ae(r);e.pools_handle=c.pools.fields.id.id;let d=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),m=ae(d);return e.oracle_infos_handle=m.oracle_infos.fields.id.id,e.prices_handle=m.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}async findRouters(e,t,n){let{providers:o}=this._sdk.sdkOptions,s=this._sdk.AggregatorClient;if(S(n).lt(1))throw new Error("amount is less than 1");try{let r={from:e,target:t,amount:new ge.default(n),byAmountIn:!0,depth:3,providers:o},c=await s.findRouters(r);if(c?.error)throw new Error(`Aggregator findRouters error: ${c?.error}`);if(!c?.paths||c?.paths?.length===0)throw new Error("Aggregator findRouters error: no router");let d=c.amountIn.toString(),m=c.amountOut.toString();return{swap_in_amount:d,swap_out_amount:m,route_obj:c}}catch(r){throw new Error(`Aggregator findRouters error: ${r}`)}}};var So=ie(require("@cetusprotocol/dlmm-sdk"));var gi=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async getVaultAndPool(e){return e.version==="v1"?await this.sdk.Vaults.getVaultAndPool(e.vault_id):await this.sdk.VaultsV2.getVaultAndPool(e.vault_id)}async buildMigrateWithdrawTx(e,t){let{withdraw_result:n,return_ft_coin:o,liquidity_slippage:s,extra_burn:r}=e,{deposit_amount_a:c,deposit_amount_b:d,from_vault:m,to_vault:f,burn_ft_amount:p,from_swap_result:h}=n;if(m.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(f.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:v,clmmPool:M}=await this.getVaultAndPool(m),{marketList:C,pool:A}=await this.getVaultAndPool(f),{coin_type_a:D,coin_type_b:V}=M,O=r?S(p).sub(r.burn_lp_amount).toFixed(0).toString():p,{return_coin_a:B,return_coin_b:T}=await this.sdk.Vaults.buildWithdrawPayload({pool_id:m.vault_id,burn_lp_amount:O,mode:"FixedOneSide",slippage:s,return_coin:!0,extra_burn:r},t),E={[L(D,!1)]:B,[L(V,!1)]:T},{coin_output_a:N,coin_output_b:F}=h,{from_coin_type:I,from_coin_amount:W,route_obj:j,to_coin_type:Q}=N;if(j){let{to_coin:K}=await this.buildSwapAssetsTx({from_coin_type:I,swap_in_amount:W,liquidity_slippage:s,route_obj:j.route_obj,tx:t,from_coin_object_id:E[L(I,!1)]});E[L(Q,!1)]=K}if(F.route_obj){let{from_coin_type:K,from_coin_amount:a,route_obj:u,to_coin_type:_}=F,{to_coin:g}=await this.buildSwapAssetsTx({from_coin_type:K,swap_in_amount:a,liquidity_slippage:s,route_obj:u.route_obj,tx:t,from_coin_object_id:E[L(K,!1)]});E[L(_,!1)]=g}return await this._sdk.VaultsV2.buildDepositPayload({pool_id:f.vault_id,amount_a:c,amount_b:d,return_lp_coin:o,coin_a_input:E[L(A.coin_type_a,!1)],coin_b_input:E[L(A.coin_type_b,!1)]},t)}async calculateMigrateWithdraw(e){let{from_vault:t,to_vault:n,burn_ft_amount:o}=e;if(t.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(n.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:s,clmmPool:r}=await this.getVaultAndPool(t),{marketList:c,pool:d}=await this.getVaultAndPool(n),m=await this.sdk.Vaults.preCalculateWithdrawAmount({pool_id:t.vault_id,mode:"FixedOneSide",burn_lp_amount:o}),{coin_type_a:f,coin_type_b:p}=r,{coin_type_a:h,coin_type_b:v}=d,M=await this.matchSwapCoins({from:{coin_type_a:f,coin_amount_a:m.receive_amount_a,coin_type_b:p,coin_amount_b:m.receive_amount_b},to:{coin_type_a:h,coin_type_b:v}}),{coin_output_a:C,coin_output_b:A}=M,D=await this.sdk.VaultsV2.calculateDepositLpAmountBoth(d,C.to_coin_amount,A.to_coin_amount);return{from_vault:t,to_vault:n,burn_ft_amount:o,deposit_amount_a:C.to_coin_amount,deposit_amount_b:A.to_coin_amount,obtained_ft_amount:D,from_swap_result:M}}async buildSwapAssetsTx(e){let{from_coin_type:t,liquidity_slippage:n,tx:o,from_coin_object_id:s,swap_in_amount:r,route_obj:c}=e,d=s||Jt.buildCoinWithBalance(BigInt(r),t,o),m={router:c,inputCoin:d,slippage:n,txb:o};return{to_coin:await this._sdk.AggregatorClient.fixableRouterSwapV3(m)}}async matchSwapCoins(e){let{from:t,to:n}=e,o=L(t.coin_type_a,!1),s=L(t.coin_type_b,!1),r=L(n.coin_type_a,!1),c=L(n.coin_type_b,!1),d=o===r,m=o===c,f=s===r,p=s===c,h,v;d&&p?(h="A",v="B"):m&&f?(h="B",v="A"):d?(h="A",v="B"):m||f?(h="B",v="A"):(h="A",v="B");let M={from_coin_type:h==="A"?o:s,from_coin_amount:h==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:r,to_coin_amount:"0"},C={from_coin_type:v==="A"?o:s,from_coin_amount:v==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:c,to_coin_amount:"0"};if(M.from_coin_type!==M.to_coin_type&&S(M.from_coin_amount).gt(0))try{let A=await this.sdk.VaultsV2.findRouters(M.from_coin_type,M.to_coin_type,M.from_coin_amount);if(A)M.to_coin_amount=A.swap_out_amount,M.route_obj={swap_in_amount:A.swap_in_amount,swap_out_amount:A.swap_out_amount,route_obj:A.route_obj};else throw Error("Aggregator no router")}catch(A){throw A}else M.to_coin_amount=M.from_coin_amount;if(C.from_coin_type!==C.to_coin_type&&S(C.from_coin_amount).gt(0))try{let A=await this.sdk.VaultsV2.findRouters(C.from_coin_type,C.to_coin_type,C.from_coin_amount);if(A)C.to_coin_amount=A.swap_out_amount,C.route_obj={swap_in_amount:A.swap_in_amount,swap_out_amount:A.swap_out_amount,route_obj:A.route_obj};else throw Error("Aggregator no router")}catch(A){throw A}else C.to_coin_amount=C.from_coin_amount;return{coin_output_a:M,coin_output_b:C}}};var he=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,n){(!e.providers||e.providers.length===0)&&(e.providers=gn),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||yn.CetusClmmSDK.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||yn.CetusClmmSDK.createSDK({env:"mainnet",full_rpc_url:e.fullRpcUrl}),this._cetusDlmmSDK=n||So.default.createSDK({env:e.env,full_rpc_url:e.fullRpcUrl}),this._vaults=new Ge(this),this._vaultsV2=new Qe(this),this._migrate=new gi(this);let{primary:o,secondary:s}=e.pythConfigs.hermes_service_urls,r=[o,s].filter(Boolean);this._aggregatorClient=new Je.AggregatorClient({endpoint:e.aggregatorUrl,signer:(0,bi.normalizeSuiAddress)("0x0"),client:new ko.SuiClient({url:e.fullRpcUrl}),env:e.env==="testnet"?Je.Env.Testnet:Je.Env.Mainnet,pythUrls:r}),this._vest=new He(this)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e,this.CetusClmmSDK.setSenderAddress(e)}get sdkOptions(){return this._sdkOptions}get Vaults(){return this._vaults}get VaultsV2(){return this._vaultsV2}get FullClient(){return this._cetusClmmSDK.FullClient}get AggregatorClient(){return this._aggregatorClient}get CetusClmmSDK(){return this._cetusClmmSDK}get CetusDlmmSDK(){return this._cetusDlmmSDK}get Vest(){return this._vest}get Migrate(){return this._migrate}getVerifySenderAddress(){if(this.senderAddress.length===0||!(0,bi.isValidSuiAddress)(this.senderAddress))throw Error("this sdk senderAddress is illegal");return this.senderAddress}async getOwnerCoinAssets(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinAssets(e,t)}async getOwnerCoinBalances(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinBalances(e,t)}updateCache(e,t,n=Gn){this.CetusClmmSDK.updateCache(e,t,n)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var ws=.2;var ys=he;0&&(module.exports={PythPriceModule,SdkEnv,VaultsModule,VaultsModuleV2,VestModule,VolatileVaultsSDK,buildCLMMMarketId,buildCLMMMarketPosition,buildDLMMMarketId,buildDLMMMarketPosition,buildDLMMPositionId,buildPoolData,buildPoolV2Data,buildVaultMarket,buildVaultsBalance,buildVaultsBalanceV2,calcExactSwapAmount,calcSingleSideSwap,calculateAum,calculateAumV2,calculateDepositRatioFixTokenA,calculateTotalAumBasedOnQuote,checkIsMinOrMaxIndex,convertU64BytesToDecimal,defaultProvider,dlmm_split_rate,estCoinAmountsFromTotalAmount,feed_map_mainnet,feed_map_testnet,getAmountBalanceByLpAmount,getCoinAmountsFromRatio,getPositionPriceRange,getPriceWithFormattedDecimals,getPrimitivePricesFromBaseQuote,getQuotePerBaseAndBasePerQuote,getShareBufferAssets,getUpdatePriceType,getVaultValidBalances,get_lp_amount_by_liquidity,get_lp_amount_by_tvl,get_share_liquidity_by_amount,initMainnetSDK,initTestnetSDK,initVaultSDK,oraclePriceMultiplierDecimal,parseVaultVestNFT,parseVaultsVestInfo,printTransaction,toSuiObjectId,vaults_mainnet,vaults_testnet});
|
|
2
|
-
/*! Bundled license information:
|
|
3
|
-
|
|
4
|
-
@cetusprotocol/common-sdk/dist/index.mjs:
|
|
5
|
-
(*! Bundled license information:
|
|
6
|
-
|
|
7
|
-
decimal.js/decimal.mjs:
|
|
8
|
-
(*!
|
|
9
|
-
* decimal.js v10.6.0
|
|
10
|
-
* An arbitrary-precision Decimal type for JavaScript.
|
|
11
|
-
* https://github.com/MikeMcl/decimal.js
|
|
12
|
-
* Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
|
|
13
|
-
* MIT Licence
|
|
14
|
-
*)
|
|
15
|
-
*)
|
|
16
|
-
*/
|
|
1
|
+
import{isValidSuiAddress as lo,normalizeSuiAddress as _o}from"@mysten/sui/utils";import{AggregatorClient as uo,Env as Oe}from"@cetusprotocol/aggregator-sdk";import{CACHE_TIME_24H as po}from"@cetusprotocol/common-sdk";import{CetusClmmSDK as Fe}from"@cetusprotocol/sui-clmm-sdk";import{Transaction as mt}from"@mysten/sui/transactions";import $ from"bn.js";import{extractStructTagFromType as He}from"@cetusprotocol/aggregator-sdk";import{ClmmPoolUtil as ft,TickMath as kt,d as M,fixCoinType as X,fromDecimalsAmount as ze,toDecimalsAmount as Xe,CLOCK_ADDRESS as Vt,getObjectPreviousTransactionDigest as Ge,getObjectFields as Ae}from"@cetusprotocol/common-sdk";import{CoinAssist as At}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as Qe}from"@mysten/sui/utils";import Je from"decimal.js";import I from"bn.js";import Et from"decimal.js";import{ClmmPoolUtil as Zt,TickMath as nt,MathUtil as xt,asIntN as bt,fixCoinType as z,extractStructTagFromType as Tt,d as R,getObjectFields as Yt,getObjectType as te}from"@cetusprotocol/common-sdk";import{ClmmPoolUtil as Le,d as ot,TickMath as xe,TickUtil as zt,toDecimalsAmount as Xt}from"@cetusprotocol/common-sdk";import Gt from"bn.js";import Qt from"decimal.js";var Lt=(b,e,t)=>{if(e==="min"){if(b===zt.getMinIndex(t))return!0}else if(b===zt.getMaxIndex(t))return!0;return!1};function yo(b){if(b.length!==8)throw new Error("Invalid u64 byte array length");let e=b.map(t=>t.toString(16).padStart(2,"0")).reverse().join("");return BigInt(`0x${e}`).toString()}function Te(b,e,t,o,i){let a=new Gt(10).pow(new Gt(o)),{coin_amount_b:n}=Le.estLiquidityAndCoinAmountFromOneAmounts(b,e,a,!0,!0,0,t),s=xe.sqrtPriceX64ToPrice(t,o,i),r=ot(a.toString()).mul(s).div(new Qt(10).pow(o)).mul(new Qt(10).pow(i)),c=r.add(n.toString()),l=r.div(c),_=ot(n.toString()).div(c);return{ratioA:l,ratioB:_}}function H(b,e,t,o,i,a,n){let s=ot(Xt(ot(t).mul(b).div(o).toString(),a)).toFixed(0),r=ot(Xt(ot(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function Jt(b,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=Te(b,e,t,n,s);return H(r,c,o,i,a,n,s)}var it=10n;function at(b){let{fields:e,type:t}=b,{liquidity_range:o,pool_id:i,wrapped_position:a}=e.clmm_vault.fields,n=a.fields,s={clmm_pool_id:i,liquidity_range:{lower_offset:o.fields.lower_offset,rebalance_threshold:o.fields.rebalance_threshold,upper_offset:o.fields.upper_offset},wrapped_position:{coin_type_a:z(n.coin_type_a.fields.name,!1),coin_type_b:z(n.coin_type_b.fields.name,!1),description:n.description,id:n.id.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:bt(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:bt(BigInt(n.tick_upper_index.fields.bits)),url:n.url}},{balances:r}=e.buffer_assets.fields,c=r.fields.contents.map(_=>{let{key:d,value:p}=_.fields;return{coin_type:z(d.fields.name,!1),value:p}});return{id:e.id.id,is_pause:e.is_pause,clmm_vault:s,lp_token_treasury:e.lp_token_treasury.fields.total_supply.fields.value,protocol_fees_handle:e.protocol_fees.fields.id.id,hard_cap:e.hard_cap,quote_type:Tt(e.quote_type.fields.name).full_address,lp_token_type:Tt(t).type_arguments[0],balances:c,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function Vo(b,e=!0){b.getData().commands.forEach((t,o)=>{})}function gt(b,e){let t=R(b).div(e).toString(),o=R(e).div(b).toString();return{quote_per_base:t,base_per_quote:o}}function Ee(b,e,t,o){let i=10n**(it+o-t),a=10n**(it+t-o),n=xt.checkMulDivFloor(new I(b.toString()),new I(i.toString()),new I(e.toString()),64),s=xt.checkMulDivFloor(new I(e.toString()),new I(a.toString()),new I(b.toString()),64);return{primitive_base_price:BigInt(n.toString()),primitive_quote_price:BigInt(s.toString())}}function Y(b,e){let t=e?b[e].price:{coin_type:"",price:"1",coin_decimals:6,oracle_price:1000000000000000000000000n},o=new I("0");for(let[i,{price:a,value:n}]of Object.entries(b)){let{primitive_quote_price:s}=Ee(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=xt.checkMulDivFloor(new I(s.toString()),new I(n),new I((BigInt(10)**it).toString()),64);o=o.add(r)}return o.toString()}async function ee(b,e,t,o,i=!1){let{clmm_vault:a,quote_type:n}=e,{wrapped_position:s}=a,{tick_lower_index:r,tick_upper_index:c,liquidity:l}=s,{current_sqrt_price:_,coin_type_a:d,coin_type_b:p}=t,u=[...o],m=n&&z(e.quote_type,!1),f=nt.tickIndexToSqrtPriceX64(r),y=nt.tickIndexToSqrtPriceX64(c),{coin_amount_a:g,coin_amount_b:h}=Zt.getCoinAmountFromLiquidity(new I(l),new I(_),new I(f),new I(y),!1);u.push({coin_type:d,value:g.toString()}),u.push({coin_type:p,value:h.toString()});let w={};u.forEach(k=>{let D=z(k.coin_type,!1),V=R(k.value),B=w[D]||0;w[D]=V.add(B).toString()});let v=Object.entries(w).filter(([k,D])=>R(D).gt(0)).map(([k])=>k);if(m&&!v.includes(m)&&v.push(m),v.length===0)return"0";let C=await b.PythPrice.getLatestPrice(v,i),A={};return v.forEach(k=>{let D=C[k];if(D)A[k]={price:D,value:w[k]||"0"};else throw Error(`find ${k} price fail `)}),Y(A,m).toString()}function ht(b,e,t){return R(b).eq(0)?e:R(b).mul(e).div(t).toFixed(0,Et.ROUND_HALF_UP)}function Ao(b,e,t){return R(b).eq(0)?"0":R(b).mul(e).div(t).toFixed(0,Et.ROUND_HALF_UP)}function st(b,e,t){return R(b).eq(0)?"0":R(e).mul(t).div(b).toFixed(0,Et.ROUND_HALF_UP)}function rt(b,e,t){let o={};return e.forEach(i=>{let a=st(t,b,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function oe(b,e,t,o,i=!0){let{tick_lower_index:a,tick_upper_index:n,coin_type_a:s,coin_type_b:r,liquidity:c}=t.clmm_vault.wrapped_position,l=st(t.lp_token_treasury,e,c),_=nt.tickIndexToSqrtPriceX64(a),d=nt.tickIndexToSqrtPriceX64(n),p=Zt.getCoinAmountFromLiquidity(new I(l),new I(o.current_sqrt_price),_,d,!0),u=p.coin_amount_a.toString(),m=p.coin_amount_b.toString(),f=rt(e,t.balances,t.lp_token_treasury),y=R(u).add(i&&f[s]?.value||"0").toFixed(0),g=R(m).add(i&&f[r]?.value||"0").toFixed(0),h=i?Object.values(f).filter(v=>v.coin_type!==s&&v.coin_type!==r):Object.values(f);return{vault_id:t.id,clmm_pool_id:o.id,owner:b,lp_token_type:t.lp_token_type,lp_token_balance:e,liquidity:l,tick_lower_index:a,tick_upper_index:n,amount_a:y,amount_b:g,coin_type_a:s,coin_type_b:r,share_buffer_assets:h}}function yt(b,e,t){let o=[];return e.forEach(i=>{R(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{R(i.value).gt(0)&&o.push(i)}),b.forEach(i=>{R(i.value).gt(0)&&o.push(i)}),o}function _t(b,e,t){let o=new Set;return b.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function ie(b,e){if(!it)throw new Error("oraclePriceMultiplierDecimal is required");if(b===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(it- -e);return b*t}return b/10n**(e+it)}function ne(b){return`0x${Buffer.from(b).toString("hex")}`}function So(b,e,t,o,i){let a="0",n="0";return Lt(b,"min",Number(t))?a="0":a=nt.tickIndexToPrice(Number(b),o,i).toString(),Lt(e,"max",Number(t))?n="\u221E":n=nt.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function It(b){let e=Yt(b),t=te(b),o=Tt(t),i=e.position.fields,a={id:i.id.id,pool_id:i.pool,index:i.index,liquidity:i.liquidity,tick_lower_index:bt(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:bt(BigInt(i.tick_upper_index.fields.bits)),coin_type_a:z(i.coin_type_a.fields.name,!1),coin_type_b:z(i.coin_type_b.fields.name,!1),name:i.name,description:i.description,url:i.url},n=e.global_vesting_periods.map(r=>({period:r.fields.period,release_time:r.fields.release_time,redeemed_amount:r.fields.redeemed_amount,cetus_amount:r.fields.cetus_amount}));return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_coin_type:e.lp_coin_type.fields.name,allocated_lp_amount:e.allocated_lp_amount,position:a,balance:e.balance,total_supply:e.total_supply,impaired_a:e.impaired_a,impaired_b:e.impaired_b,redeemed_amount:e.redeemed_amount,url:e.url,coin_type_a:z(e.coin_a.fields.name,!1),coin_type_b:z(e.coin_b.fields.name,!1),cetus_amount:e.cetus_amount,start_time:e.start_time,global_vesting_periods:n,vest_infos:{id:e.vester_infos.fields.id,size:e.vester_infos.fields.size}}}function ae(b){let e=Yt(b),t=te(b);return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_amount:e.lp_amount,url:e.url,redeemed_amount:e.redeemed_amount,impaired_a:e.impaired_a,impaired_b:e.impaired_b,period_infos:e.period_infos.map(i=>({period:i.fields.period,cetus_amount:i.fields.cetus_amount,is_redeemed:i.fields.is_redeemed})),name:e.name,vester_id:e.vester_id}}import{asIntN as wt,fixCoinType as q,extractStructTagFromType as Ie,d as F,TickMath as vt,ClmmPoolUtil as se}from"@cetusprotocol/common-sdk";import{parseLiquidityShares as re}from"@cetusprotocol/dlmm-sdk";import Re from"decimal.js";import{bcs as ut}from"@mysten/sui/bcs";import{deriveDynamicFieldID as qe,deriveObjectID as ce}from"@mysten/sui/utils";import ct from"bn.js";function le(b){try{let{fields:e,type:t}=b,{certified_pools:o,positions:i,id:a,coin_type_a:n,coin_type_b:s,vault_id:r,position_keys:c}=e;return{type:t.includes("CLMMMarket")?"CLMM":"DLMM",id:a.id,certified_pools:o.fields.contents.map(d=>d.fields.key),positions_handle:{id:i.fields.id.id,size:i.fields.size},position_list:[],coin_type_a:q(n.fields.name,!1),coin_type_b:q(s.fields.name,!1),vault_id:r,position_keys:c.fields.contents}}catch{return}}function Ke(b){return{uri:b.uri,index:b.index,id:b.id.id,name:b.name,pool_id:b.pool_id,lower_bin_id:wt(BigInt(b.lower_bin_id.fields.bits)),upper_bin_id:wt(BigInt(b.upper_bin_id.fields.bits)),liquidity_shares:b.liquidity_shares,description:b.description,coin_type_a:q(b.coin_type_a,!1),coin_type_b:q(b.coin_type_b,!1)}}function $e(b){return{id:b.id.id,pool_id:b.pool,index:b.index,description:b.description,uri:b.url,liquidity:b.liquidity,tick_lower_index:wt(BigInt(b.tick_lower_index.fields.bits)),tick_upper_index:wt(BigInt(b.tick_upper_index.fields.bits)),name:b.name,coin_type_a:q(b.coin_type_a.fields.name,!1),coin_type_b:q(b.coin_type_b.fields.name,!1)}}function de(b){let{fields:e}=b,{position:t,amounts:o,id:i}=e,a=o.fields.contents.map(d=>{let{key:p,value:u}=d.fields;return{coin_type:q(p.fields.name,!1),value:u}}),n=Ke(t.fields),s=n.lower_bin_id,r=n.liquidity_shares.map((d,p)=>({bin_id:s+p,liquidity:d})).filter(d=>F(d.liquidity).gt(0)),c=r.length>0?r[0].bin_id:s,l=r.length>0?r[r.length-1].bin_id:s+n.liquidity_shares.length-1;return{id:i.id,valid_lower_bin_id:c,valid_upper_bin_id:l,position:n,amounts:a}}function _e(b){let{fields:e}=b,{position:t,amounts:o,id:i}=e,a=o.fields.contents.map(r=>{let{key:c,value:l}=r.fields;return{coin_type:q(c.fields.name,!1),value:l}}),n=$e(t.fields);return{id:i.id,position:n,amounts:a}}function Rt(b){let{fields:e,type:t}=b,{action_status:o,buffer_assets:i,coin_type_a:a,coin_type_b:n,hard_cap:s,id:r,last_aum:c,lp_token_treasury:l,markets:_,protocol_fee_rate:d,protocol_fees:p,quote_type:u}=e,m=(Number(o)&1)!==0,f=(Number(o)&2)!==0,{balances:y}=i.fields,g=y.fields.contents.map(v=>{let{key:C,value:A}=v.fields;return{coin_type:q(C.fields.name,!1),value:A}}),h=u.fields.pos0.fields.name;return{id:r.id,lp_token_treasury:l.fields.total_supply.fields.value,hard_cap:s,quote_type:h?q(h,!1):void 0,protocol_fee_rate:d,buffer_assets:g,protocol_fees_handle:{id:p.fields.id.id,size:p.fields.size},markets_handle:{id:_.fields.id.id,size:_.fields.size},markets:[],action_status:{is_deposit_allowed:m,is_withdraw_allowed:f},is_multiple_pool:!1,last_aum:c,coin_type_a:q(a.fields.name,!1),coin_type_b:q(n.fields.name,!1),lp_token_type:Ie(t).type_arguments[0],version:"v2"}}async function ue(b,e,t,o=!1){let{pool:i,marketList:a}=await b.VaultsV2.getVaultAndPool(e),{quote_type:n,coin_type_a:s,coin_type_b:r}=i,c=[...t],l="0",_="0";for(let g of a)if(g.type==="DLMM"){let{position_list:h}=g;for(let w of h){let{lower_bin_id:v,liquidity_shares:C,pool_id:A}=w.position,S=g.certified_pool_obj[A],k=await b.CetusDlmmSDK.Pool.getBinInfo(S.bin_manager.bin_manager_handle,S.active_id,S.bin_step,!1),D=re(C,S.bin_step,v,k);l=F(l).add(D.amount_a.toString()).toFixed(0),_=F(_).add(D.amount_b.toString()).toFixed(0)}}else if(g.type==="CLMM"){let{position_list:h}=g;for(let w of h){let{tick_lower_index:v,tick_upper_index:C,liquidity:A,pool_id:S}=w.position,k=g.certified_pool_obj[S],D=vt.tickIndexToSqrtPriceX64(v),V=vt.tickIndexToSqrtPriceX64(C),{coin_amount_a:B,coin_amount_b:j}=se.getCoinAmountFromLiquidity(new ct(A),new ct(k.current_sqrt_price),new ct(D),new ct(V),!1);l=F(l).add(B.toString()).toFixed(0),_=F(_).add(j.toString()).toFixed(0)}}let d=n&&q(n,!1);c.push({coin_type:s,value:l}),c.push({coin_type:r,value:_});let p={};c.forEach(g=>{let h=q(g.coin_type,!1),w=F(g.value),v=p[h]||0;p[h]=w.add(v).toString()});let u=Object.entries(p).filter(([g,h])=>F(h).gt(0)).map(([g])=>g);if(d&&!u.includes(d)&&u.push(d),u.length===0)return"0";let m=await b.VaultsV2.PythPrice.getLatestPrice(u,o),f={};return u.forEach(g=>{let h=m[g];if(h)f[g]={price:h,value:p[g]||"0"};else throw Error(`find ${g} price fail `)}),Y(f,d).toString()}async function qt(b,e,t,o,i=!0){let a=await Pt(b,e,t,i);return a.owner=o||"0x0",a}async function Pt(b,e,t,o=!0){let{pool:i,marketList:a}=await b.VaultsV2.getVaultAndPool(t),{lp_token_type:n,lp_token_treasury:s,coin_type_a:r,coin_type_b:c}=i;if(F(s).isZero())return{vault_id:t,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:"0",amount_b:"0",position_amount_a:"0",position_amount_b:"0",dlmm_balances:[],clmm_balances:[],share_buffer_assets:[]};let l=F(e).div(s),_=[],d=[],p=F(0),u=F(0);for(let v of a)if(v.type==="DLMM"){let{position_list:C}=v;for(let A of C){let{lower_bin_id:S,upper_bin_id:k,liquidity_shares:D,id:V,pool_id:B}=A.position,j=v.certified_pool_obj[B],{bin_manager:O,bin_step:L,active_id:E}=j,x=await b.CetusDlmmSDK.Pool.getBinInfo(O.bin_manager_handle,E,L,!1),T=re(D.map(Mt=>F(Mt.toString()).mul(l).toFixed(0,Re.ROUND_HALF_UP).toString()),L,S,x),K=T.amount_a,N=T.amount_b,et=T.bins.filter(Mt=>F(Mt.liquidity).gt(0)),Be=et.length>0?et[0].bin_id:T.bins[0].bin_id,je=et.length>0?et[et.length-1].bin_id:T.bins[T.bins.length-1].bin_id,Me={position_id:V,certified_pool_id:j.id,liquidity_shares:D,valid_lower_bin_id:Be,valid_upper_bin_id:je,original_lower_bin_id:S,original_upper_bin_id:k,position_amount_a:K,position_amount_b:N,coin_type_a:r,coin_type_b:c,bin_infos:{bins:et,amount_a:T.amount_a,amount_b:T.amount_b}};_.push(Me),p=p.add(F(K)),u=u.add(F(N))}}else if(v.type==="CLMM"){let{position_list:C}=v;for(let A of C){let{tick_lower_index:S,tick_upper_index:k,liquidity:D,id:V,pool_id:B}=A.position,j=v.certified_pool_obj[B],O=F(D).mul(l).toFixed(0),L=vt.tickIndexToSqrtPriceX64(S),E=vt.tickIndexToSqrtPriceX64(k),x=se.getCoinAmountFromLiquidity(new ct(O),new ct(j.current_sqrt_price),L,E,!1),T=x.coin_amount_a.toString(),K=x.coin_amount_b.toString(),N={position_id:V,certified_pool_id:j.id,liquidity:O,tick_lower_index:S,tick_upper_index:k,position_amount_a:T,position_amount_b:K};d.push(N),p=p.add(F(T)),u=u.add(F(K))}}let m=rt(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",y=o&&m[c]?.value||"0",g=p.add(f).toFixed(0),h=u.add(y).toFixed(0),w=o?Object.values(m).filter(v=>v.coin_type!==r&&v.coin_type!==c):Object.values(m);return{vault_id:t,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:g,amount_b:h,position_amount_a:p.toFixed(0),position_amount_b:u.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:w}}function pe(b){let e=ut.vector(ut.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return ce(b,"vector<u8>",e)}function me(b){let e=ut.vector(ut.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return ce(b,"vector<u8>",e)}function qo(b,e){let t=ut.Address.serialize(e).toBytes();return qe(b,"0x2::object::ID",t)}function pt(b,e,t,o){let i=F(b),a=F(t),n=F(o),s=i,r=e?i:F(0),c=e?F(0):i,l=n,_=F(n).mul(.999),d=F(0),p=s,u=null;function m(g){if(e){let h=r.minus(g),w=c.plus(g.mul(a));return{A:h,B:w,R:w.div(h)}}else{let h=r.plus(g.mul(a)),w=c.minus(g);return{A:h,B:w,R:h.div(w)}}}for(let g=0;g<120;g++){let h=d.plus(p).div(2),{A:w,B:v,R:C}=m(h);if(w.lte(0)||v.lte(0)){p=h;continue}if(C.gt(l))p=h;else if(C.lt(_))d=h;else{if(u=h,F(_).eq(0))break;p=h}}if(!u)return{swap_amount:"0",final_amount_a:r.toFixed(0),final_amount_b:c.toFixed(0)};let{A:f,B:y}=m(u);return{swap_amount:u.toFixed(0),final_amount_a:f.toFixed(0),final_amount_b:y.toFixed(0),best:u.toString()}}function fe(b,e,t,o,i,a){if(a){let n=F(b).mul(t).sub(F(e).mul(o)),s=F(t).add(F(i).mul(o));return(F(s).eq(0)?F(0):F(n).div(s)).toString()}else{let n=F(e).mul(o).sub(F(b).mul(t)),s=F(i).mul(t).add(o);return(F(s).eq(0)?F(0):F(n).div(s)).toString()}}import{SuiPriceServiceConnection as Kt,SuiPythClient as We}from"@pythnetwork/pyth-sui-js";import{bcs as ke}from"@mysten/sui/bcs";import{CLOCK_ADDRESS as Ct,d as $t,fixCoinType as Ve}from"@cetusprotocol/common-sdk";var be={env:"mainnet",fullRpcUrl:"https://fullnode.mainnet.sui.io",vaults:{package_id:"0xc4ebf35be1478318d78c324342854dd2735a036139373a9d41a1aa3a46a01d05",published_at:"0x720f861bda572e891eb422c117fb7224c0f91aaf69b655f6e40bcd68f0edad41",configs:{registry_id:"0x23014734280164270fa4c58f973c00079651e730d6f46491678ea8858f3bd13a",pools_handle:"0x31c810b6fcf3bb8699384e7c61fe9f7db53a04c4c22d514b3f79b6caa86183a8",pyth_oracle_id:"0xaed73fd854dfceedb2522903feec8c0e251764f5945bd38f969473024c4fb4d0",oracle_infos_handle:"0x6951ab4b36639e79ddbd9ba4478d7f72d1c5396b9198d0864c00e796c5815b01",prices_handle:"0x20a65a0f747f4f1ad465bdb61d784bbc5080ee5d200d5dd6594a354723b8c171",global_config_id:"0x5f8371674cd8e1e9eef5542ffe8adb339e3ff3a67894b14c954c7a92e992e0c1"},clmm_configs:{global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b"}},vaultsV2:{package_id:"0xfbc91f75397ce25b3b1b01cab2bf494d2e3f9b9e89c97545d88bd616cbbfcc37",published_at:"0x4893ee6665ad7b1a83810c16e0151b9500a7296bba85f2571ba9e79115ce1a83",configs:{registry_id:"0xb6e0d2a2457af53a83b1435ea398f9460ba8abd98686387a4399fceefdfc22e2",pools_handle:"0xc88e97a3a3bb71dfcf8cc90e6383d7e3e1dee0170fa07c9365d233568659fc8f",global_config_id:"0x05bedfb68e6bf273946f8e1f2529e8f30acdf8b287dec524973c6bae9e979743",versioned_id:"0x70bea2f242b057cda9994e9fecee121cb35ee914c360cc86f061268110b6d9ec",oracle_infos_handle:"0x4631c11bfeae9461863d233285d03e3dba14f8dfb574781f1e2cbe9b58ba903e",pyth_oracle_id:"0xc08cdf8479075b0dae05aadc76f941038a25d74dcbedd9c339f7ce5da08fab92"}},pythConfigs:{pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",hermes_service_urls:{primary:"https://hermes.pyth.network"},wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91"},aggregatorUrl:"https://api-sui.cetus.zone/router_v3",providers:[],vest:{package_id:"0xd0587f397e47d31a79d1c36710c2c28f48ff8f1e8ea73b6a54fa2ec6fdfe0a7d",published_at:"0x57731e8bd3971eca68019afecb0e11699ece6301f0d4f255969f5b4227e0c5f8",version:1,config:{versioned_id:"0xee1e2214314737df6193cc4cf6815cf8dc3b4cc1c5cc0a078c6579dda19e8552",create_event_list:[{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xb2d502d4ef89395934de020b195ded323bfa86d7f40b65ed5b15d6b66c722a3d::lpcoin::LPCOIN",pool_id:"0x2fc6ee9183d0f1ca0d2dded02c416be6f4671bb82db55c26ce12b536812a4b8e",position_id:"0x99f7fbeaf18c88e8af7553ad2ef055772477a1851550a2e7c2d7a503420c6b05",vault_id:"0xbd6252e0d56ae5eaabf055fd6c518ee5f66c1114287ca957cc698a17c3d25b16",vault_vester_id:"0xe4196586ed151a38c7c9169c72b9e5e3f51bfea9afbc2d1f082d6bedb88b086f"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x0484a9162669957e1c1883fc2da59e3cce9afdc1eec3c72c983898dbc9e92b91::lpcoin::LPCOIN",pool_id:"0xaa020ad81e1621d98d4fb82c4acb80dc064722f24ef828ab633bef50fc28268b",position_id:"0x90918d035e37b4447e11c2043c4c4374baeb7c2cbd2729063d939d016b04770f",vault_id:"0x99db9a7d3320d31fe6e4dc4122b948162010e331c41dc279636ca75567b93497",vault_vester_id:"0xd891e4c866a67e6339d1539edd1c28db629c81d9fb8499ee029cfa3803a0819e"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x242ddc526b9cb75513bee2fc629e01d5b7dc6da4c02d39cdab0160794635334f::lpcoin::LPCOIN",pool_id:"0x2e041f3fd93646dcc877f783c1f2b7fa62d30271bdef1f21ef002cebf857bded",position_id:"0xf82ebf822b0a7eff84f0079f3998611c4fec2ae714fe627225640eb305dc5a7c",vault_id:"0xbbd2d4850e4f238d39c3aa24957d2dfbb5787fa43d6c7de306bf15abe27f29f2",vault_vester_id:"0x7cc6404b903542ff6410b8e85c9647005713f8a23166ef08a488fe267c81c8bb"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xd418945e16ef3db737df093d0827f5ce387b36f089523e13c16e50dec6bd2524::lpcoin::LPCOIN",pool_id:"0xe01243f37f712ef87e556afb9b1d03d0fae13f96d324ec912daffc339dfdcbd2",position_id:"0x1ea05f946e995edcda18ba9fdaefd1021eddfb8d62e4fa09da89753ffb5b90ee",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0xd67cd239a34852cbc2e530db2ef296bc3e4a977464309c21ce706d90a17a5d5d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xf21d82f767cac2e8892db252aa539c137dcf8a6d1e6ebd2d0a11c16362171df7::lpcoin::LPCOIN",pool_id:"0x72f5c6eef73d77de271886219a2543e7c29a33de19a6c69c5cf1899f729c3f17",position_id:"0x5bd93e30000eb9f3217a04c938c7f939ee33ac161f6fe7ea34bac268dbe36893",vault_id:"0x12ac7deea4b92b3e2c16687e2d2695fa8c045ec0a52844db7b2fc3876c9552aa",vault_vester_id:"0x5d87bb3db28e77604f9bd210cdde0916e95a9d37925ec3c466fa785bba3d63f9"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x2f46a040b9bc3a584a3be4d7bfbb02a5fb479da17a04c6d2860ed61d95e97f3f::lpcoin::LPCOIN",pool_id:"0xb8d7d9e66a60c239e7a60110efcf8de6c705580ed924d0dde141f4a0e2c90105",position_id:"0xa2141e99975e203172f62c97b1f314f845b94730f6dfdb8ab2d32d014c659bcf",vault_id:"0x41a4ab1e82f90f5965bbcd828b8ffa13bab7560bd2e352ab067e343db552f527",vault_vester_id:"0x0e4782ee96095af233a6c5219b50cd8c92bd79d84f1df7e629bcc7a094c5a09d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x5c79c0ab2c45682aba43b1acbe5c478d947f7c8397d47447906d6cc127e180fb::lpcoin::LPCOIN",pool_id:"0xea648440bd640d3530e8a5f02c0b56da82c2efe851156c39974b901bbb0eeab1",position_id:"0x896a01cc57ba25799ec320dc25d1969f3129f2591689ce8c8dbf380c7e00bf48",vault_id:"0x5525f5a70fffd93f616c39b59f3abdd2054fc2d19f09c8a4d94950d611a43b74",vault_vester_id:"0xe116bb120d2d91f85ee419cbff73fdd9d7f87e9b085dd4de781347b51361ae17"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x8275bc774497b319db110bb97a4812a19859ab6f19dc1574746097f06103c0f9::lpcoin::LPCOIN",pool_id:"0x9e59de50d9e5979fc03ac5bcacdb581c823dbd27d63a036131e17b391f2fac88",position_id:"0xd080bfb32b9c24f8875bd5a803a417b8ca0c02f2208d0b9058692f9013db3b52",vault_id:"0xedfb22d1bbe5045fd1888bb8bc1c4bc1823ab24d40f5a4bea9f6eb9758a4b820",vault_vester_id:"0x8bc7ccefae4db25873a0692bfb0d2c7cbdbbe644574a537789b98815960155a4"}]}}},ge={"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{coin_type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",price_feed_id:"0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",coin_decimals:6},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",price_feed_id:"0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",coin_decimals:9},"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS":{coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",price_feed_id:"0xe5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",coin_decimals:9},"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP":{coin_type:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",price_feed_id:"0x29bdd5248234e33bd93d3b81100b5fa32eaa5997843847e2c2cb16d7c6d9f7ff",coin_decimals:6},"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX":{coin_type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",price_feed_id:"0x88250f854c019ef4f88a5c073d52a18bb1c6ac437033f5932cd017d24917ab46",coin_decimals:9},"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN":{coin_type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",price_feed_id:"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",coin_decimals:9},"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI":{coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",price_feed_id:"0x6120ffcf96395c70aa77e72dcb900bf9d40dccab228efca59a17b90ce423d5e8",coin_decimals:9},"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH":{coin_type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",price_feed_id:"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",coin_decimals:8},"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL":{coin_type:"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL",price_feed_id:"0xeba0732395fae9dec4bae12e52760b35fc1c5671e2da8b449c9af4efe5d54341",coin_decimals:9},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{coin_type:"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC",price_feed_id:"0x8f257aab6e7698bb92b15511915e593d6f8eae914452f781874754b03d0c612b",coin_decimals:8},"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL":{coin_type:"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL",price_feed_id:"0xe67d98cc1fbd94f569d5ba6c3c3c759eb3ffc5d2b28e64538a53ae13efad8fd1",coin_decimals:9}};function he(b,e,t){return b&&(be.fullRpcUrl=b),new G(be,e,t)}var ye={env:"testnet",fullRpcUrl:"https://fullnode.testnet.sui.io",vaults:{package_id:"0x0a624f2dcafc9f7f381684b3d553a9837411925b6e8530b1f8f4e6ff3f1fde77",published_at:"0x36f9d8e6219e6ba4d8840165ec27676a1bcb43fc5712f87ca702ac7b5924507d",configs:{registry_id:"0xa2ebae3656c5fbdd2473caadfc077cd1780a881759a356f1a5bc0f9fd470adb9",pools_handle:"0x0df305d395f8e0359da0ac5717bc96e0e1da9792684ec8e8f6a20b7ab544f98e",pyth_oracle_id:"0x6c74aec8d4471d9b05f718c467204c9010c450b94a4e40b0b4031a7d6c386337",global_config_id:"0x8969b09cfdd72b1635263b569027ded4b91bbabd7d8cd91b21e355325e218b10",oracle_infos_handle:"0x8707c6665d202f277ffe8e7fd58684e232622a3e6826b94ba99f7569f253fa9d",prices_handle:"0x74230bb2c6a63235acbfe477ce16144afca7ccd16a458fa93f4605330b5d1c58"},clmm_configs:{global_config_id:"0x9774e359588ead122af1c7e7f64e14ade261cfeecdb5d0eb4a5b3b4c8ab8bd3e",global_vault_id:"0xf78d2ee3c312f298882cb680695e5e8c81b1d441a646caccc058006c2851ddea"}},pythConfigs:{pyth_state_id:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",wormhole_state_id:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",hermes_service_urls:{primary:"https://hermes-beta.pyth.network"},pyth_package_id:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837",pyth_published_at:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837"},vaultsV2:{package_id:"0x0000000000000000000000000000000000000000000000000000000000000000",published_at:"0x0000000000000000000000000000000000000000000000000000000000000000",configs:{registry_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pools_handle:"0x0000000000000000000000000000000000000000000000000000000000000000",global_config_id:"0x0000000000000000000000000000000000000000000000000000000000000000",versioned_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pyth_oracle_id:"0x0000000000000000000000000000000000000000000000000000000000000000",oracle_infos_handle:"0x0000000000000000000000000000000000000000000000000000000000000000"}},aggregatorUrl:"https://api-sui.devcetus.com/router_v2",providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"],vest:{package_id:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",published_at:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",config:{versioned_id:"0x2c5b6227da87ce840035955e0d82725178ce53c8cd2b01934d6540feccf2a8f7",create_event_list:[{clmm_vester_id:"0x308b24963e5992f699e32db2f7088b812566a0cae580317fd3b8bf61de7f5508",lp_coin_type:"0xb0c18dcd849d4b47528831c64707f2f7f6aa1b7fd9ed5e1ac2f8ab356e031f25::lp_token::LP_TOKEN",pool_id:"0x403c7d9c1e959c029f61d970286eac8ad5bca2db2edba358585abf4dbd4ed3cd",position_id:"0xd1dbcdb1789b92772b367bc1f68d7d078b4fd3326b8bfb53750bf28585463508",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0x6098c69613ed5d503ff2b81447e96408feab8f2e4bf582966a811b5b582d23e3"}]}}},we={};function ve(b,e,t){return b&&(ye.fullRpcUrl=b),new G(ye,e,t)}var Ue=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(Ue||{});function ti(b,e,t){let{env:o,fullNodeUrl:i}=b;return o==="mainnet"?he(i,e,t):ve(i,e,t)}var Pe=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];function Ce(b){try{let{request_time:e,error:t,request_params:o,request_url:i,action:a}=b;if(window?.gtag){let n=t.message==="Request Timeout";window.gtag("event","API_Error",{request_action:a,request_url:i,request_time:e,request_params:JSON.stringify(o),error_msg:String(t)})}}catch{}}var Ne=16*1024,lt=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;errorList=[];pythConfigs;global_config_id;pyth_oracle_id;oracle_infos_handle;vaults_published_at;versioned_id;isV2;constructor(e,t,o,i,a,n,s,r){this.vaults_published_at=o,this.pythConfigs=t,this.global_config_id=i,this.pyth_oracle_id=a,this.oracle_infos_handle=s,this.isV2=r,this.versioned_id=n;let{pyth_state_id:c,wormhole_state_id:l,hermes_service_urls:_}=t;this._sdk=e,this.hasChangeConnection=!1;let{primary:d}=_;if(d.length===0)throw new Error("primary url is empty");this.connection=new Kt(d),this.suiPythClient=new We(this._sdk.FullClient,c,l)}get sdk(){return this._sdk}recordError(e,t,o){let{secondary:i,primary:a}=this.pythConfigs.hermes_service_urls,n={error:e,request_params:t,request_url:this.hasChangeConnection&&i?i:a,action:o,request_time:Date.now()};Ce(n),this.errorList.push(n)}readErrorList(){let e=this.errorList;return this.errorList=[],e}async getFeedInfoList(e){let t=e.map(i=>this.getFeedInfo(i,!1));return await Promise.all(t)}priceCheck(e,t=60){let o=Math.floor(Date.now()/1e3);if(!(Math.abs(o-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let o={},i=[];if(t?e.forEach(s=>{let r=this._sdk.getCache(`getLatestPrice_${s}`);r&&this.priceCheck(r,60)?o[s]=r:i.push(s)}):i=[...e],i.length===0)return o;let a=await this.getFeedInfoList(i);return(await this.getLatestPriceFeeds(a.map(s=>s.price_feed_id)))?.parsed?.forEach((s,r)=>{if(s){let{price:c,expo:l,publish_time:_}=s.price,d=$t(c).mul($t(10).pow($t(l))).toString(),p=a[r],u={coin_type:p.coin_type,price:d,coin_decimals:p.coin_decimals,oracle_price:0n,last_update_time:_};u.oracle_price=ie(BigInt(c),BigInt(l)),o[i[r]]=u,this._sdk.updateCache(`getLatestPrice_${u.coin_type}`,u)}}),o}async getPriceFeedsUpdateData(e){try{return await this.connection.getPriceFeedsUpdateData(e)}catch(t){this.recordError(t,e,"getPriceFeedsUpdateData");let{secondary:o}=this.pythConfigs.hermes_service_urls;if(o){this.hasChangeConnection=!0,this.connection=new Kt(o);try{return await this.connection.getPriceFeedsUpdateData(e)}catch(i){this.recordError(i,e,"getPriceFeedsUpdateData")}}}}async getLatestPriceFeeds(e){try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(t){this.recordError(t,e,"getLatestPriceFeeds");let{secondary:o}=this.pythConfigs.hermes_service_urls;if(o){this.hasChangeConnection=!0,this.connection=new Kt(o);try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(i){this.recordError(i,e,"getLatestPriceFeeds")}}}}async buildUpdatePythPricePayload(e,t){let{pyth_state_id:o,pyth_published_at:i,pyth_package_id:a}=this.pythConfigs,n=(await this.getFeedInfoList(e)).map(d=>d.price_feed_id);if(e.length!==n.length)throw Error("find feed id fail");let s=await this.getPriceFeedsUpdateData(n);if(!s)throw new Error("get price update data fail");if(s.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.suiPythClient.extractVaaBytesFromAccumulatorMessage(s[0]),c=await this.suiPythClient.verifyVaas([r],t),[l]=t.moveCall({target:`${i}::pyth::create_authenticated_price_infos_using_accumulator`,typeArguments:[],arguments:[t.object(o),t.pure(ke.vector(ke.U8).serialize(Array.from(s[0]),{maxSize:Ne}).toBytes()),c[0],t.object(Ct)]}),_=0;for(let d of n){let p=await this.suiPythClient.getPriceFeedObjectId(d);if(!p)throw new Error(`Price feed ${d} not found, please create it first`);this.isV2?[l]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[_]],arguments:[t.object(this.pyth_oracle_id),t.object(o),l,t.object(p),t.object(Ct),t.object(this.versioned_id)]}):[l]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[_]],arguments:[t.object(this.pyth_oracle_id),t.object(this.global_config_id),t.object(o),l,t.object(p),t.object(Ct)]}),_+=1}return t.moveCall({target:`${i}::hot_potato_vector::destroy`,arguments:[l],typeArguments:[`${a}::price_info::PriceInfo`]}),t}async buildUpdatePythPricePayloadV2(e,t){if(e.length===0)return t;let o=(await this.getFeedInfoList(e)).map(s=>s.price_feed_id);if(e.length!==o.length)throw Error("find feed id fail");let i=await this.getPriceFeedsUpdateData(o);if(!i)throw new Error("get price update data fail");if(i.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let a=await this.suiPythClient.updatePriceFeeds(t,i,o),n=0;for(let s of a)t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price_into_pyth_oracle`,typeArguments:[e[n]],arguments:[t.object(this.pyth_oracle_id),t.object(s),t.object(Ct),t.object(this.versioned_id)]}),n+=1;return t}getFeedInfoByJson(e){let{env:t}=this._sdk.sdkOptions,o=Ve(e,!1);return t==="mainnet"?ge[o]:we[o]}async getFeedInfo(e,t){let o=`getFeedInfo_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=this.getFeedInfoByJson(e);if(a)return a;let n=await this._sdk.FullClient.getDynamicFieldObject({parentId:this.oracle_infos_handle,name:{type:"0x1::type_name::TypeName",value:Ve(e,!0)}}),{fields:s}=n.data.content.fields.value,r={coin_type:e,price_feed_id:ne(s.price_feed_id),coin_decimals:s.coin_decimals};return this._sdk.updateCache(o,r),r}};var St=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new lt(e,o,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,"",t.configs.oracle_infos_handle,!1)}get sdk(){return this._sdk}get PythPrice(){return this.pythPrice}async getProtocolFeeRate(){let e="getProtocolFeeRate",t=this._sdk.getCache(e);if(t)return t;let{configs:o}=this._sdk.sdkOptions.vaults,a=(await this._sdk.FullClient.getObject({id:o.global_config_id,options:{showContent:!0}})).data.content.fields.protocol_fee_rate;return this._sdk.updateCache(e,a),a}async getOwnerVaultsBalance(e,t,o=!0){let{pool:i,clmmPool:a}=await this.getVaultAndPool(t,!0),s=(await this._sdk.FullClient.getBalance({owner:e,coinType:i.lp_token_type})).totalBalance;return oe(e,s,i,a,o)}async getOwnerVaultsBalanceList(e,t=!0){let{data:o}=await this.getPoolList(),i=[];for(let a=0;a<o.length;a++){let n=await this.getOwnerVaultsBalance(e,o[a].id,t);i.push(n)}return i}async getVaultsPositionRewarderAndFee(e){try{let{package_id:t}=this._sdk.sdkOptions.vaults,{pool:o,clmmPool:i}=await this.getVaultAndPool(e,!1),a=`getVaultsPositionRewarderAndFee_${e}`,n=this._sdk.getCache(a);if(n)return n;let{lp_token_type:s}=o,{rewarder_infos:r,id:c,coin_type_a:l,coin_type_b:_}=i,d=new mt;this.buildCollectRewardPayload({reward_coin_types:[...r.map(g=>g.coin_type)],lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:_},d),this.buildCollectFeePayload({lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:_},d);let p=await this._sdk.FullClient.sendSimulationTransaction(d,Qe("0x0")),u=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,f=[],y=[];return p?.events.forEach(g=>{let{parsedJson:h,type:w}=g;w===u&&(f.push({coin_type:X(l,!1),value:h.amount_a}),f.push({coin_type:X(_,!1),value:h.amount_b})),w===m&&y.push({coin_type:X(h.reward_type.name,!1),value:h.amount})}),this._sdk.updateCache(a,{feeList:f,rewarderList:y},10*1e3),{feeList:f,rewarderList:y}}catch{}return{feeList:[],rewarderList:[]}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaults:o}=this._sdk.sdkOptions,{FullClient:i}=this._sdk,a=await i.getDynamicFieldsByPage(o.configs.pools_handle,e),n=a.data.map(s=>s.name.value);return n.length>0&&((await i.batchGetObjects(n,{showContent:!0})).forEach(r=>{let c=at(r.data.content);this._sdk.updateCache(`getPool_${c.id}`,c),t.data.push(c)}),t.next_cursor=a.next_cursor,t.has_next_page=a.has_next_page),t}async getAssignPoolList(e){if(e.length===0)return[];let t=[],o=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0,showType:!0});for(let i of o){let a=at(i.data.content);this._sdk.updateCache(`getPool_${a.id}`,a),t.push(a)}return t}async getPool(e,t=!0){let o=`getPool_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=await this._sdk.FullClient.getObject({id:e,options:{showContent:!0}}),n=at(a.data.content);return this._sdk.updateCache(o,n),n}buildCollectRewardPayload(e,t){let{coin_type_a:o,coin_type_b:i,pool_id:a,clmm_pool_id:n,lp_token_type:s,reward_coin_types:r}=e,{published_at:c,configs:l,clmm_configs:_}=this._sdk.sdkOptions.vaults;return t=t||new mt,r.forEach(d=>{t.moveCall({target:`${c}::pool::collect_reward`,typeArguments:[o,i,s,d],arguments:[t.object(a),t.object(l.global_config_id),t.object(_.global_config_id),t.object(n),t.object(_.global_vault_id),t.object(Vt)]})}),t}buildCollectFeePayload(e,t){let{coin_type_a:o,coin_type_b:i,pool_id:a,clmm_pool_id:n,lp_token_type:s}=e,{published_at:r,configs:c,clmm_configs:l}=this._sdk.sdkOptions.vaults;return t=t||new mt,t.moveCall({target:`${r}::pool::collect_fee`,typeArguments:[o,i,s],arguments:[t.object(a),t.object(c.global_config_id),t.object(l.global_config_id),t.object(n)]}),t}async buildDepositPayload(e,t){let{pool_id:o,amount_a:i,amount_b:a,return_lp_coin:n,re_balance:s}=e,{pool:r,clmmPool:c}=await this.getVaultAndPool(o,!0),{lp_token_type:l}=r,{rewarder_infos:_,id:d,coin_type_a:p,coin_type_b:u}=c,m=_.map(A=>X(A.coin_type,!1)),f=_t(m,c.coin_type_a,c.coin_type_b),{published_at:y,configs:g,clmm_configs:h}=this._sdk.sdkOptions.vaults;t=t||new mt,t=this.buildCollectRewardPayload({reward_coin_types:m,lp_token_type:l,pool_id:o,clmm_pool_id:d,coin_type_a:p,coin_type_b:u},t),t=this.buildCollectFeePayload({lp_token_type:l,pool_id:o,clmm_pool_id:d,coin_type_a:p,coin_type_b:u},t),t=await this.pythPrice.buildUpdatePythPricePayload(f,t),t.moveCall({target:`${y}::pool::calculate_aum`,typeArguments:[p,u,l],arguments:[t.object(o),t.object(g.global_config_id),t.object(g.pyth_oracle_id),t.object(h.global_config_id),t.object(d),t.object(Vt)]});let w,v;if(s&&s.swap_result){let{swap_result:A,coin_amount:S,mode:k,swap_slippage:D}=s,{swap_in_amount:V,swap_out_amount:B,route_obj:j}=A,O=At.buildCoinWithBalance(BigInt(S),k==="OnlyCoinA"?p:u,t),L=t.splitCoins(O,[V]),E={router:j,slippage:D,txb:t,inputCoin:L},x=await this._sdk.AggregatorClient.fixableRouterSwapV3(E);w=k==="OnlyCoinA"?O:x,v=k==="OnlyCoinA"?x:O}else w=At.buildCoinWithBalance(BigInt(i),p,t),v=At.buildCoinWithBalance(BigInt(a),u,t);let C=t.moveCall({target:`${y}::pool::${n?"deposit_for":"deposit"}`,typeArguments:[p,u,l],arguments:[t.object(o),t.object(g.global_config_id),t.object(g.pyth_oracle_id),t.object(h.global_config_id),t.object(d),w,v,t.object(Vt)]});return n?C:void 0}async buildWithdrawPayload(e,t){let{pool_id:o,burn_lp_amount:i,mode:a,slippage:n,partner:s,extra_burn:r,return_coin:c}=e,{pool:l,clmmPool:_}=await this.getVaultAndPool(o,!0),{published_at:d,configs:p,clmm_configs:u}=this._sdk.sdkOptions.vaults;t=t||new mt;let{lp_token_type:m,clmm_vault:f,lp_token_treasury:y}=l,{rewarder_infos:g,id:h,coin_type_a:w,coin_type_b:v,liquidity:C}=_,A=g.map(O=>X(O.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:A,lp_token_type:m,pool_id:o,clmm_pool_id:h,coin_type_a:w,coin_type_b:v},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:h,coin_type_a:w,coin_type_b:v},t);let S,k=r?M(r.burn_lp_amount).add(M(i)).toFixed(0):M(i).toFixed(0),D=M(i).isZero();if(D&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");D?S=r.lp_burn_coin:(S=At.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(S,[r.lp_burn_coin]));let[V,B,j]=t.moveCall({target:`${d}::pool::withdraw`,typeArguments:[w,v,m],arguments:[t.object(o),t.object(p.global_config_id),t.object(u.global_config_id),t.object(h),S,t.object(Vt)]});if(this.buildWithdrawBufferReward({reward_coin_types:A.filter(O=>![X(w,!1),X(v,!1)].includes(O)),pool_id:o,withdraw_cert:j,lp_token_type:m},t),t.moveCall({target:`${d}::pool::destory_withdraw_cert`,typeArguments:[m],arguments:[t.object(o),t.object(p.global_config_id),j]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let O=a==="OnlyCoinA",L=O?B:V,E=st(y,k,C.toString()),x=await this.handleWithSwap(t,L,w,v,k,o,O,n,s,[{poolID:h,ticklower:f.wrapped_position.tick_lower_index,tickUpper:f.wrapped_position.tick_upper_index,deltaLiquidity:Number(E)}],c);if(c&&x)return O?t.mergeCoins(x,[V]):t.mergeCoins(x,[B]),{return_coin_a:O?x:void 0,return_coin_b:O?void 0:x};t.transferObjects([O?V:B],this._sdk.senderAddress)}else{if(c)return{return_coin_a:V,return_coin_b:B};t.transferObjects([V,B],this._sdk.senderAddress)}return{return_coin_a:void 0,return_coin_b:void 0}}async handleWithSwap(e,t,o,i,a,n,s,r,c,l,_){let{receive_amount_a:d,receive_amount_b:p}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),u=s?i:o,m=s?o:i,f=s?p:d;if(M(f).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let y={from:u,target:m,amount:new $(f),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers,liquidityChanges:l},g=await this._sdk.AggregatorClient.findRouters(y);if(!g)throw Error("not find Router");if(g.error!==void 0)throw Error(`find Router error : ${g.error}`);let h={router:g,inputCoin:t,slippage:r,txb:e,partner:c},w=await this._sdk.AggregatorClient.fixableRouterSwapV3(h);if(_)return w;e.transferObjects([w],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:o,lp_token_type:i},a){let{published_at:n,configs:s}=this._sdk.sdkOptions.vaults;e.forEach(r=>{let c=a.moveCall({target:`${n}::pool::withdraw_buffer_reward`,typeArguments:[i,r],arguments:[a.object(t),a.object(s.global_config_id),o]});a.transferObjects([c],this._sdk.getVerifySenderAddress())})}async preCalculateDepositValue(e,t){let{amount_usd:o,pool_id:i,mode:a,uuid:n}=e,{pool:s,clmmPool:r}=await this.getVaultAndPool(i,!1),{current_sqrt_price:c}=r,{tick_lower_index:l,tick_upper_index:_,coin_type_a:d,coin_type_b:p}=s.clmm_vault.wrapped_position,u="0",m="0",f=await this.pythPrice.getLatestPrice([d,p],!0),y=f[d],g=f[p];if(!y||!g)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:h,amountB:w}=Jt(l,_,new $(c),o,y.price,g.price,y.coin_decimals,g.coin_decimals);u=h.toString(),m=w.toString();break}case"FlexibleBoth":{let{amountA:h,amountB:w}=H(M(.5),M(.5),o,y.price,g.price,y.coin_decimals,g.coin_decimals);u=h.toString(),m=w.toString();break}case"OnlyCoinA":{let{amountA:h,amountB:w}=H(M(1),M(0),o,y.price,g.price,y.coin_decimals,g.coin_decimals);u=h.toString(),m=w.toString();break}case"OnlyCoinB":{let{amountA:h,amountB:w}=H(M(0),M(1),o,y.price,g.price,y.coin_decimals,g.coin_decimals);u=h.toString(),m=w.toString();break}default:throw new Error(`Unsupported deposit mode: ${a}`)}return t&&this.calculateDepositLpAmountBoth(s,r,u,m).then(h=>{t.onSuccess(h,n)}).catch(h=>{t.onError(h,n)}),{deposit_amount_a:u,deposit_amount_b:m,mode:a}}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:o}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:i,clmmPool:a}=await this.getVaultAndPool(o,!1),{clmm_vault:n}=i,{current_sqrt_price:s,coin_type_a:r,coin_type_b:c}=a,l=n.wrapped_position.tick_lower_index,_=n.wrapped_position.tick_upper_index,d=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,p=t==="OnlyCoinA",u=ft.estLiquidityAndCoinAmountFromOneAmounts(l,_,new $(d),p,!0,1,new $(s)),m=p?M(u.coin_amount_b).div(u.coin_amount_a):M(u.coin_amount_a).div(u.coin_amount_b),f=p?M(s).toString():M(1).div(M(s)).toString();try{let C=await this._sdk.VaultsV2.findRouters(p?r:c,p?c:r,d);C&&(f=M(C.swap_out_amount).div(C.swap_in_amount).toString())}catch{}let{swap_amount:y}=pt(d,p,f.toString(),m.toString()),g=M(d).sub(y).toFixed(0),h=await this._sdk.VaultsV2.findRouters(p?r:c,p?c:r,y),w=M(h.swap_out_amount).mul(.999).toFixed(0),v=ft.estLiquidityAndCoinAmountFromOneAmounts(l,_,new $(g),p,!0,1,new $(s));return p?v.coin_amount_b=w:v.coin_amount_a=w,{swap_result:h,liquidity_info:v}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:o,pool_id:i,uuid:a}=e,n="0",s="0",r,c,{pool:l,clmmPool:_}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:d,fixed_coin_a:p}=e,{other_amount:u,lp_amount:m}=await this.calculateDepositOtherSide(l,_,d,p,t,a);c=m,p?(n=d,s=u):(s=d,n=u);break}case"FlexibleBoth":{let{coin_amount_a:d,coin_amount_b:p}=e;n=d,s=p;break}case"OnlyCoinA":{if(e.re_balance){let d=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:u}=d,{coin_amount_a:m,coin_amount_b:f}=u;n=m,s=f,r={swap_result:p,coin_amount:e.coin_amount_a}}else n=e.coin_amount_a;break}case"OnlyCoinB":{if(e.re_balance){let d=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:u}=d,{coin_amount_a:m,coin_amount_b:f}=u;n=m,s=f,r={swap_result:p,coin_amount:e.coin_amount_b}}else s=e.coin_amount_b;break}default:throw new Error(`Unsupported deposit mode: ${o}`)}return t?this.calculateDepositLpAmountBoth(l,_,n,s).then(d=>{t?.onSuccess(d,a)}).catch(d=>{t?.onError(d,a)}):c=await this.calculateDepositLpAmountBoth(l,_,n,s),{deposit_amount_a:n,deposit_amount_b:s,mode:o,re_balance:r,lp_amount:c}}async getVaultAndPool(e,t=!1){let o=await this.getPool(e,t);if(o===void 0)throw new Error("get vaults pool failed");let i=await this._sdk.CetusClmmSDK.Pool.getPool(o.clmm_vault.clmm_pool_id,t);if(i===void 0)throw new Error("get vaults clmmPool failed");return{clmmPool:i,pool:o}}async calculateDepositOtherSide(e,t,o,i,a,n){let{clmm_vault:s}=e,{current_sqrt_price:r}=t,c=s.wrapped_position.tick_lower_index,l=s.wrapped_position.tick_upper_index,_=ft.estLiquidityAndCoinAmountFromOneAmounts(c,l,new $(o),i,!0,1,new $(r)),{coin_amount_a:d,coin_amount_b:p}=_;if(a)this.calculateDepositLpAmountBoth(e,t,d.toString(),p.toString()).then(u=>{a.onSuccess(u,n)}).catch(u=>{a.onError(u,n)});else{let u=await this.calculateDepositLpAmountBoth(e,t,d.toString(),p.toString());return{other_amount:i?p.toString():d.toString(),lp_amount:u}}return{other_amount:i?p.toString():d.toString(),lp_amount:void 0}}async calculateDepositLpAmountBoth(e,t,o,i){let{lp_token_treasury:a,hard_cap:n}=e,s=X(t.coin_type_a,!1),r=X(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),_=yt(e.balances,l,c),d=await ee(this,e,t,_,!0),p=await this.pythPrice.getLatestPrice([s,r],!0),u=p[s],m=p[r];if(!u)throw Error(`not find ${s} price`);if(!m)throw Error(`not find ${r} price`);let f={};f[s]={price:u,value:o.toString()},f[r]={price:m,value:i.toString()};let y=Y(f,e.quote_type);return ht(a,y,d)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:o}=e,i="0",a="0",n="0",s="0",r,{pool:c,clmmPool:l}=await this.getVaultAndPool(o,!1);switch(t){case"FixedOneSide":let _=await this.calculateWithdrawOtherSide(c,l,e.burn_lp_amount);n=_.burn_lp_amount,i=_.receive_amount_a,a=_.receive_amount_b,s=_.remove_liquidity;break;case"OnlyCoinA":{let d=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!0);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity,r=d.swap;break}case"OnlyCoinB":{let d=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!1);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity,r=d.swap;break}default:throw new Error(`Unsupported withdraw mode: ${t}`)}return{remove_liquidity:s,burn_lp_amount:n,receive_amount_a:i,receive_amount_b:a,mode:t,swap:r}}async calculateWithdrawOtherSide(e,t,o){let{clmm_vault:i,lp_token_treasury:a}=e,{current_sqrt_price:n}=t,{coin_type_a:s,coin_type_b:r}=e.clmm_vault.wrapped_position,c=i.wrapped_position.tick_lower_index,l=i.wrapped_position.tick_upper_index,_=i.wrapped_position.liquidity,d=kt.tickIndexToSqrtPriceX64(c),p=kt.tickIndexToSqrtPriceX64(l),u=st(a,o,_),{coin_amount_a:m,coin_amount_b:f}=ft.getCoinAmountFromLiquidity(new $(u),new $(n),d,p,!1),y=rt(o,e.balances,a),g=M(m.toString()).add(y[s]?.value||"0").toFixed(0),h=M(f.toString()).add(y[r]?.value||"0").toFixed(0);return{receive_amount_a:g,receive_amount_b:h,burn_lp_amount:o,mode:"FixedOneSide",remove_liquidity:u}}async calculateWithdrawOnlyCoin(e,t,o,i){let{totalReceiveAmount:a,swapAmountIn:n,swapAmountOut:s,removeLiquidity:r,remove_amount_a:c,remove_amount_b:l}=await this.calculateWithdrawOnlyCoinByLpAmount(e,t,i,o);return{receive_amount_a:i?a:"0",receive_amount_b:i?"0":a,burn_lp_amount:o,remove_liquidity:r,swap:{swap_amount_in:n,swap_amount_out:s,remove_amount_a:c,remove_amount_b:l},mode:"FixedOneSide"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,o,i){let{clmm_vault:a,lp_token_treasury:n}=e,{current_sqrt_price:s}=t,{coin_type_a:r,coin_type_b:c}=a.wrapped_position,l=a.wrapped_position.tick_lower_index,_=a.wrapped_position.tick_upper_index,d=a.wrapped_position.liquidity,p=kt.tickIndexToSqrtPriceX64(l),u=kt.tickIndexToSqrtPriceX64(_),m=st(n,i,d),{coin_amount_a:f,coin_amount_b:y}=ft.getCoinAmountFromLiquidity(new $(m),new $(s),p,u,!1),g=await this.pythPrice.getLatestPrice([r,c],!0),h=g[r],w=g[c];if(!h)throw Error(`not find ${r} price`);if(!w)throw Error(`not find ${c} price`);let v=o?w:h,C=o?h:w,{quote_per_base:A}=gt(v.price,C.price),S=rt(i,e.balances,n),k=M(f.toString()).add(S[r]?.value||"0").toFixed(0),D=M(y.toString()).add(S[c]?.value||"0").toFixed(0),V=o?k:D,B=o?D:k,j=Xe(M(ze(B,o?w.coin_decimals:h.coin_decimals)).mul(A).toString(),o?h.coin_decimals:w.coin_decimals).toString(),O=M(V).add(j).toFixed(0);return{remove_amount_a:k,remove_amount_b:D,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:V,swapAmountIn:B,swapAmountOut:M(j).toFixed(0,Je.ROUND_DOWN),totalReceiveAmount:O}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,o=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),i=Ge(o);(await this._sdk.FullClient.queryEventsByPage({Transaction:i})).data.forEach(l=>{let _=l.parsedJson;if(l.type)switch(He(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=_.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=_.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=_.global_config;break;default:break}});let n=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),s=Ae(n);e.pools_handle=s.pools.fields.id.id;let r=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),c=Ae(r);return e.oracle_infos_handle=c.oracle_infos.fields.id.id,e.prices_handle=c.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}};import{CLOCK_ADDRESS as Ze,fixCoinType as Ye,getObjectFields as to,getPackagerConfigs as Ut}from"@cetusprotocol/common-sdk";import{Transaction as eo}from"@mysten/sui/transactions";var Dt=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async vestNftIsAvailable(e,t){try{let o=await this._sdk.FullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}});return!to(o).value.fields.is_pause}catch{return!0}}async getVestCreateEventList(){let{vest:e}=this._sdk.sdkOptions;if(e===void 0)throw new Error("vest is not set config in sdk options");try{let t=`${e.package_id}::hae_vester::CreateEvent`;return(await this._sdk.FullClient.queryEventsByPage({MoveEventType:t})).data.map(i=>{let a=i.parsedJson,n={clmm_vester_id:a.clmm_vester_id,lp_coin_type:Ye(a.lp_coin_type.name,!1),pool_id:a.pool_id,position_id:a.position_id,vault_id:a.vault_id,vault_vester_id:a.hae_vester_id},s=`${n.vault_id}-VestCreateEvent`;return this._sdk.updateCache(s,n),n})}catch(t){throw new Error(`getVestCreateEventList error: ${t}`)}return[]}async getVaultsVestInfoList(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let o=[];for(let n of e){let s=await this.getVaultVestEvent(n);o.push(s.vault_vester_id)}let i=[];return(await this._sdk.FullClient.batchGetObjects(o,{showContent:!0,showType:!0})).forEach(n=>{try{let s=It(n);i.push(s);let r=`${s.id}-VaultsVestInfo`;this._sdk.updateCache(r,s)}catch{}}),i}async getVaultsVestInfo(e,t=!0){let o=(await this.getVaultVestEvent(e)).vault_vester_id,i=`${o}-VaultsVestInfo`,a=this._sdk.getCache(i,t);if(a)return a;try{let n=await this._sdk.FullClient.getObject({id:o,options:{showContent:!0,showType:!0}}),s=It(n);return this._sdk.updateCache(i,s),s}catch(n){throw new Error(`getVaultsVestInfo error: ${n}`)}}async getVaultVestEvent(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let{create_event_list:o}=Ut(t),i=o.find(a=>a.vault_id===e);if(!i){let a=`${e}-VestCreateEvent`,n=this._sdk.getCache(a,!1);n?i=n:(i=(await this.getVestCreateEventList()).find(r=>r.vault_id===e),this._sdk.updateCache(a,i))}if(!i)throw new Error("vault_id not found in vest_ids_map");return i}async getOwnerVaultVestNFT(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let o=await this._sdk.FullClient.getOwnedObjectsByPage(e,{filter:{StructType:`${t.package_id}::hae_vester::HaeVesterNFT`},options:{showContent:!0,showType:!0,showOwner:!0}}),i=[];return o.data.forEach(a=>{try{let n=ae(a);i.push(n)}catch{}}),i}async buildRedeemPayload(e,t){let{vest:o}=this._sdk.sdkOptions,{clmm_vest:i}=this._sdk.CetusClmmSDK.sdkOptions;if(!o)throw new Error("vest is not set config in sdk options");if(!i)throw new Error("clmm_vest is not set config in clmm sdk options");let{versioned_id:a}=Ut(o),{versioned_id:n,clmm_vest_id:s}=Ut(i);t=t||new eo;for(let r of e){let{vault_id:c,vesting_nft_id:l,period:_,coin_type_a:d,coin_type_b:p}=r,u=await this.getVaultVestEvent(c);t.moveCall({package:o.published_at,module:"hae_vester",function:"redeem_coin",arguments:[t.object(a),t.object(u.vault_vester_id),t.object(l),t.object(n),t.object(s),t.object(u.pool_id),t.pure.u16(_),t.object(Ze)],typeArguments:[d,p]})}return t}};import{Transaction as Se}from"@mysten/sui/transactions";import Q from"bn.js";import{extractStructTagFromType as oo}from"@cetusprotocol/aggregator-sdk";import{buildPool as io}from"@cetusprotocol/sui-clmm-sdk";import{d as P,fixCoinType as U,fromDecimalsAmount as tt,toDecimalsAmount as Ot,CLOCK_ADDRESS as J,getObjectPreviousTransactionDigest as no,getObjectFields as De,getPackagerConfigs as dt,ClmmPoolUtil as Wt}from"@cetusprotocol/common-sdk";import{CoinAssist as Ft}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as ao}from"@mysten/sui/utils";import so from"decimal.js";import{BinUtils as Z,parseDlmmPool as ro,StrategyType as Nt}from"@cetusprotocol/dlmm-sdk";var Bt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new lt(e,o,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,t.configs.versioned_id,t.configs.oracle_infos_handle,!0)}get PythPrice(){return this.pythPrice}get sdk(){return this._sdk}async getOwnerVaultsBalance(e,t,o=!0){let{pool:i}=await this.getVaultAndPool(t,!1),n=(await this._sdk.FullClient.getBalance({owner:e,coinType:i.lp_token_type})).totalBalance;return await qt(this._sdk,n,t,e,o)}async getOwnerVaultsBalanceList(e){let{data:t}=await this.getPoolList(),o=[];for(let i=0;i<t.length;i++){let a=await this.getOwnerVaultsBalance(e,t[i].id);o.push(a)}return o}async buildCollectRewardAndFeePayload(e,t,o){let{pool:i,marketList:a}=await this.getVaultAndPool(e,!1),{lp_token_type:n,coin_type_a:s,coin_type_b:r}=i;for(let c of a)if(c.type==="DLMM"){let{position_list:l}=c;l.forEach(_=>{let{id:d,pool_id:p}=_.position,u=c.certified_pool_obj[p],{reward_manager:m,id:f}=u;this.buildDlmmCollectRewardPayload({reward_coin_types:[...m.rewards.map(y=>y.reward_coin)],lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t),this.buildDlmmCollectFeePayload({lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}else if(c.type==="CLMM"){let{position_list:l}=c;l.forEach(_=>{let{id:d,pool_id:p}=_.position,u=c.certified_pool_obj[p],{rewarder_infos:m,id:f}=u;this.buildClmmCollectRewardPayload({reward_coin_types:[...m.map(y=>y.coin_type)],lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t),this.buildClmmCollectFeePayload({lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}}async getVaultsPositionRewarderAndFee(e){let t=[],o=[],i=[],a=[];try{let{pool:n}=await this.getVaultAndPool(e,!1),s=`getVaultsV2PositionRewarderAndFee_${e}`,r=this._sdk.getCache(s);if(r)return r;let{coin_type_a:c,coin_type_b:l}=n,_=new Se;await this.buildCollectRewardAndFeePayload(e,_),(await this._sdk.FullClient.sendSimulationTransaction(_,ao("0x0")))?.events.forEach(p=>{let{parsedJson:u,type:m}=p;m.includes("CollectDlmmFeeEvent")&&(t.push({coin_type:U(c,!1),value:u.amount_a}),t.push({coin_type:U(l,!1),value:u.amount_b})),m.includes("CollectClmmFeeEvent")&&(o.push({coin_type:U(c,!1),value:u.amount_a}),o.push({coin_type:U(l,!1),value:u.amount_b})),m.includes("CollectClmmRewardEvent")&&a.push({coin_type:U(u.reward_type.name,!1),value:u.amount}),m.includes("CollectDlmmRewardEvent")&&i.push({coin_type:U(u.reward_type.name,!1),value:u.amount})}),this._sdk.updateCache(s,{dlmmFeeList:t,dlmmRewarderList:i,clmmFeeList:o,clmmRewarderList:a},10*1e3)}catch{}return{dlmmFeeList:t,dlmmRewarderList:i,clmmFeeList:o,clmmRewarderList:a}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaultsV2:o}=this._sdk.sdkOptions,{FullClient:i}=this._sdk,a=await i.getDynamicFieldsByPage(o.configs.pools_handle,e),n=a.data.map(s=>s.name.value);if(n.length>0){let s=await this.getAssignPoolList(n);t.data.push(...s),t.next_cursor=a.next_cursor,t.has_next_page=a.has_next_page}return t}async getPool(e,t=!0){let o=`getPool_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=await this.getAssignPoolList([e]);if(a.length>0){let n=a[0];return this._sdk.updateCache(o,n),n}throw new Error(`get pool failed ${e}`)}async getAssignPoolList(e){let t=[];if(e.length>0){(await this._sdk.FullClient.batchGetObjects(e,{showContent:!0})).forEach(a=>{let n=Rt(a.data.content);t.push(n)});let i=t.map(a=>a.id);if(i.length>0){let a=await this.geMarketList(i);t.forEach(n=>{let s=a[n.id];if(s){n.markets=s;let c=0;s.forEach(l=>{c+=l.position_list.length}),n.is_multiple_pool=c!==1}let r=`getPool_${n.id}`;this._sdk.updateCache(r,n)})}}return t}async getVaultsAggregatedDataByIds(e){let{vaultsV2:t,vaults:o}=this._sdk.sdkOptions,i=[],a=[],n={},s={};if(e.length>0){let _=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0});for(let d=0;d<_?.length;d++){let p=_[d],{type:u}=p.data.content;if(u.includes(`${t.package_id}::vault::Vault`)){let m=Rt(p.data.content);i.push(m)}else if(u.includes(`${o.package_id}::pool::Pool`)){let m=at(p.data.content);this._sdk.updateCache(`getPool_${m.id}`,m),a.push(m)}}}let r=i.map(_=>_.id);if(r.length>0){let _=await this.geMarketList(r);i.forEach(d=>{let p=_[d.id];if(p){d.markets=p;let m=0;p.forEach(f=>{m+=f.position_list.length}),d.is_multiple_pool=m!==1}let u=`getPool_${d.id}`;this._sdk.updateCache(u,d)})}let c=new Set;a.forEach(_=>{c.add(_.clmm_vault.clmm_pool_id)}),i.forEach(_=>{_.markets.forEach(d=>{d.position_list.forEach(p=>{let{pool_id:u}=p.position;c.add(u)})})});let l=Array.from(c);if(l.length>0){let{clmm_pool:_}=this._sdk.CetusClmmSDK.sdkOptions,{dlmm_pool:d}=this._sdk.CetusDlmmSDK.sdkOptions;(await this._sdk.FullClient.batchGetObjects(l,{showContent:!0})).forEach(u=>{let{type:m}=u.data.content;if(m.includes(`${_.package_id}::pool::Pool`)){let f=io(u);n[f.id]=f;let y=`${f.id}_getPoolObject`;this._sdk.CetusClmmSDK.updateCache(y,f)}else if(m.includes(`${d.package_id}::pool::Pool`)){let f=ro(u);s[f.id]=f;let y=`${f.id}_getDlmmPool`;this._sdk.CetusDlmmSDK.updateCache(y,f)}})}return{v1:a,v2:i,clmmPoolMap:n,dlmmPoolMap:s}}async geMarketList(e){let t={},o=[];e.forEach(a=>{let n=me(a),s=pe(a);o.push(n,s)}),(await this._sdk.FullClient.batchGetObjects(o,{showContent:!0})).forEach(a=>{let n=le(a?.data?.content);if(n){let s=t[n.vault_id]||[];s.push(n),t[n.vault_id]=s}});for(let a in t){let n=t[a];for(let s of n){let r=await this.getMarketPositionList(s.positions_handle.id);s.position_list=r}}return t}async getMarketPositionList(e){let t=[],i=(await this._sdk.FullClient.getDynamicFieldsByPage(e)).data.map(a=>a.objectId);return i.length>0&&(await this._sdk.FullClient.batchGetObjects(i,{showContent:!0})).forEach(n=>{try{let{type:s}=n.data?.content;if(s){if(s.includes("DLMMPosition")){let r=de(n?.data?.content);t.push(r)}else if(s?.includes("CLMMPosition")){let r=_e(n?.data?.content);t.push(r)}}}catch{}}),t}buildDlmmCollectRewardPayload(e,t){let{reward_coin_types:o,lp_token_type:i,pool_id:a,certified_pool_id:n,position_id:s,coin_type_a:r,coin_type_b:c,withdraw_cert:l}=e,{published_at:_,configs:d}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:p}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:u,global_config_id:m}=dt(p);l?o.forEach(f=>{t.moveCall({target:`${_}::vault::collect_dlmm_reward_on_withdraw`,typeArguments:[r,c,i,f],arguments:[t.object(a),l,t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id)]})}):o.forEach(f=>{t.moveCall({target:`${_}::vault::collect_dlmm_reward`,typeArguments:[r,c,i,f],arguments:[t.object(a),t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id)]})})}buildClmmCollectRewardPayload(e,t){let{reward_coin_types:o,lp_token_type:i,pool_id:a,certified_pool_id:n,position_id:s,coin_type_a:r,coin_type_b:c,withdraw_cert:l}=e,{published_at:_,configs:d}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:p}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:u,global_config_id:m}=dt(p);l?o.forEach(f=>{t.moveCall({target:`${_}::vault::collect_clmm_reward_on_withdraw`,typeArguments:[r,c,i,f],arguments:[t.object(a),l,t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id),t.object(J)]})}):o.forEach(f=>{t.moveCall({target:`${_}::vault::collect_clmm_reward`,typeArguments:[r,c,i,f],arguments:[t.object(a),t.object(n),t.object(s),t.object(u),t.object(m),t.object(d.versioned_id),t.object(J)]})})}buildDlmmCollectFeePayload(e,t){let{lp_token_type:o,pool_id:i,certified_pool_id:a,position_id:n,coin_type_a:s,coin_type_b:r,withdraw_cert:c}=e,{published_at:l,configs:_}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:d}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:p,global_config_id:u}=dt(d);c?t.moveCall({target:`${l}::vault::collect_dlmm_fee_on_withdraw`,typeArguments:[s,r,o],arguments:[t.object(i),c,t.object(a),t.object(n),t.object(u),t.object(p),t.object(_.versioned_id)]}):t.moveCall({target:`${l}::vault::collect_dlmm_fee`,typeArguments:[s,r,o],arguments:[t.object(i),t.object(a),t.object(n),t.object(u),t.object(p),t.object(_.versioned_id)]})}buildClmmCollectFeePayload(e,t){let{lp_token_type:o,pool_id:i,certified_pool_id:a,position_id:n,coin_type_a:s,coin_type_b:r,withdraw_cert:c}=e,{published_at:l,configs:_}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:d}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:p,global_config_id:u}=dt(d);c?t.moveCall({target:`${l}::vault::collect_clmm_fee_on_withdraw`,typeArguments:[s,r,o],arguments:[t.object(i),c,t.object(a),t.object(n),t.object(u),t.object(_.versioned_id)]}):t.moveCall({target:`${l}::vault::collect_clmm_fee`,typeArguments:[s,r,o],arguments:[t.object(i),t.object(a),t.object(n),t.object(u),t.object(_.versioned_id)]})}async buildDepositPayload(e,t){let{published_at:o,configs:i}=this._sdk.sdkOptions.vaultsV2,{pool_id:a,amount_a:n,amount_b:s,return_lp_coin:r,re_balance:c,coin_a_input:l,coin_b_input:_}=e,{pool:d,marketList:p}=await this.getVaultAndPool(a,!1),{coin_type_a:u,coin_type_b:m,lp_token_type:f}=d,y=[u,m];for(let v of p)v.type==="DLMM"?v.position_list.forEach(C=>{let{pool_id:A}=C.position,S=v.certified_pool_obj[A],{reward_manager:k}=S,D=k.rewards.map(V=>U(V.reward_coin,!1));y=_t(D,u,m)}):v.type==="CLMM"&&v.position_list.forEach(C=>{let{pool_id:A}=C.position,S=v.certified_pool_obj[A],{rewarder_infos:k}=S,D=k.map(V=>U(V.coin_type,!1));y=_t([...y,...D],u,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(y,t);for(let v of p)if(v.type==="DLMM"){let{dlmm_pool:C}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:A}=dt(C),{position_list:S}=v;S.forEach(k=>{let{id:D,pool_id:V}=k.position;t.moveCall({target:`${o}::vault::calculate_dlmm_position_amounts`,typeArguments:[u,m,f],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(V),t.object(D),t.object(A),t.object(i.versioned_id),t.object(J)]})})}else if(v.type==="CLMM"){let{clmm_pool:C}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:A}=dt(C),{position_list:S}=v;S.forEach(k=>{let{id:D,pool_id:V}=k.position;t.moveCall({target:`${o}::vault::calculate_clmm_position_amounts`,typeArguments:[u,m,f],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(V),t.object(D),t.object(A),t.object(i.versioned_id),t.object(J)]})})}t.moveCall({target:`${o}::vault::calculate_aum`,typeArguments:[f],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(i.versioned_id),t.object(J)]});let g,h;if(c&&c.swap_result){let{swap_result:v,coin_amount:C,mode:A,swap_slippage:S}=c,{swap_in_amount:k,route_obj:D}=v,V=Ft.buildCoinWithBalance(BigInt(C),A==="OnlyCoinA"?u:m,t),B=t.splitCoins(V,[k]),j={router:D,slippage:S,txb:t,inputCoin:B},O=await this._sdk.AggregatorClient.fixableRouterSwapV3(j);g=A==="OnlyCoinA"?V:O,h=A==="OnlyCoinA"?O:V}else g=l||Ft.buildCoinWithBalance(BigInt(n),u,t),h=_||Ft.buildCoinWithBalance(BigInt(s),m,t);let w=t.moveCall({target:`${o}::vault::deposit`,typeArguments:[u,m,f],arguments:[t.object(a),t.object(i.global_config_id),t.object(i.pyth_oracle_id),g,h,t.object(J),t.object(i.versioned_id)]});if(r)return w;t.transferObjects([w],this._sdk.getVerifySenderAddress())}async buildWithdrawPayload(e,t){let{pool_id:o,burn_lp_amount:i,mode:a,slippage:n,partner:s,extra_burn:r}=e,{pool:c,marketList:l}=await this.getVaultAndPool(o,!1),{lp_token_type:_,coin_type_a:d,coin_type_b:p}=c;t=t||new Se;let u,m=r?P(r.burn_lp_amount).add(P(i)).toFixed(0):P(i).toFixed(0),f=P(i).isZero();if(f&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");f?u=r.lp_burn_coin:(u=Ft.buildCoinWithBalance(BigInt(i),_,t),r&&r.lp_burn_coin&&t.mergeCoins(u,[r.lp_burn_coin]));let{published_at:y,configs:g}=this._sdk.sdkOptions.vaultsV2,{config:h}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:w}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,v=t.moveCall({target:`${y}::vault::new_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),u,t.object(g.versioned_id)]}),C=[];for(let V of l)if(V.type==="DLMM"){let{position_list:B}=V;B.forEach(j=>{let{id:O,pool_id:L}=j.position,E=V.certified_pool_obj[L],{reward_manager:x}=E,T=x.rewards.map(K=>U(K.reward_coin,!1));C.push(...T),t.moveCall({target:`${y}::vault::withdraw_dlmm`,typeArguments:[d,p,_],arguments:[t.object(o),v,t.object(L),t.object(O),t.object(h.global_config_id),t.object(h.versioned_id),t.object(g.versioned_id),t.object(J)]})})}else if(V.type==="CLMM"){let{position_list:B}=V;B.forEach(j=>{let{id:O,pool_id:L}=j.position,E=V.certified_pool_obj[L],{rewarder_infos:x}=E,T=x.map(K=>U(K.coin_type,!1));C.push(...T),t.moveCall({target:`${y}::vault::withdraw_clmm`,typeArguments:[d,p,_],arguments:[t.object(o),v,t.object(L),t.object(O),t.object(w.global_config_id),t.object(g.versioned_id),t.object(J)]})})}await this.buildCollectRewardAndFeePayload(o,t,v),t.moveCall({target:`${y}::vault::finalize_buffer_assets`,typeArguments:[_],arguments:[t.object(o),v,t.object(g.versioned_id)]});let A=new Set;C.forEach(V=>A.add(V)),A.add(d),A.add(p);let S=Array.from(A),k=a!=="FixedOneSide"?[a==="OnlyCoinA"?p:d]:[],D=this.buildWithdrawBufferReward({reward_coin_types:S,pool_id:o,withdraw_cert:v,lp_token_type:_,not_transfer_coin_types:k},t);if(t.moveCall({target:`${y}::vault::destroy_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),v,t.object(g.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let V=a==="OnlyCoinA",B=V?p:d,j=D.find(O=>O.coin_type===B).reward_coin_object_id;await this.handleWithSwap(t,j,d,p,m,o,V,n,s)}}async handleWithSwap(e,t,o,i,a,n,s,r,c){let{receive_amount_a:l,receive_amount_b:_}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),d=s?i:o,p=s?o:i,u=s?_:l;if(P(u).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let m={from:d,target:p,amount:new Q(u),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers},f=await this._sdk.AggregatorClient.findRouters(m);if(!f)throw Error("not find Router");if(f.error!==void 0)throw Error(`find Router error : ${f.error}`);let y={router:f,inputCoin:t,slippage:r,txb:e,partner:c},g=await this._sdk.AggregatorClient.fixableRouterSwapV3(y);e.transferObjects([g],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:o,lp_token_type:i,not_transfer_coin_types:a},n){let{published_at:s,configs:r}=this._sdk.sdkOptions.vaultsV2;return e.map(c=>{let l=n.moveCall({target:`${s}::vault::withdraw_asset`,typeArguments:[i,c],arguments:[n.object(t),o,n.object(r.versioned_id)]});return a.includes(c)||n.transferObjects([l],n.pure.address(this._sdk.getVerifySenderAddress())),{coin_type:c,reward_coin_object_id:l}})}async preCalculateDepositValue(e,t){let{amount_usd:o,pool_id:i,mode:a,uuid:n,re_balance:s,coin_decimals_a:r,coin_decimals_b:c}=e,{pool:l,marketList:_}=await this.getVaultAndPool(i,!1),{coin_type_a:d,coin_type_b:p}=l,u=await this.pythPrice.getLatestPrice([d,p],!0),m=u[d],f=u[p];if(!m)throw new Error(`get ${d} price failed`);if(!f)throw new Error(`get ${p} price failed`);let y="0",g="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:w,position_amount_b_rate:v}=l.is_multiple_pool?{position_amount_a_rate:P(.5),position_amount_b_rate:P(.5)}:await this.calculatePositionValueRates(l,u),{amountA:C,amountB:A}=H(w,v,o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=C,g=A;break}case"OnlyCoinA":{let{amountA:w,amountB:v}=H(P(1),P(0),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=w,g=v;break}case"OnlyCoinB":{let{amountA:w,amountB:v}=H(P(0),P(1),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=w,g=v;break}}return await this.preCalculateDepositAmount({mode:a,pool_id:i,uuid:n,coin_amount_a:y,coin_amount_b:g,re_balance:s,coin_decimals_a:r,coin_decimals_b:c},t)}async calculateClmmBalanceSwapAmount(e,t){let{mode:o,pool_id:i}=e;if(o==="OnlyCoinA"||o==="OnlyCoinB"){let{certified_pool_obj:a,position_list:n}=t,s=n[0].position,{current_sqrt_price:r,coin_type_a:c,coin_type_b:l}=a[s.pool_id],{tick_lower_index:_,tick_upper_index:d}=s,p=_,u=d,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,f=o==="OnlyCoinA",y=Wt.estLiquidityAndCoinAmountFromOneAmounts(p,u,new Q(m),f,!0,1,new Q(r)),g=f?P(y.coin_amount_b).div(y.coin_amount_a):P(y.coin_amount_a).div(y.coin_amount_b),h=f?P(r).toString():P(1).div(P(r)).toString();try{let k=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,m);k&&(h=P(k.swap_out_amount).div(k.swap_in_amount).toString())}catch{}let{swap_amount:w}=pt(m,f,h.toString(),g.toString()),v=P(m).sub(w).toFixed(0),C=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,w),A=P(C.swap_out_amount).mul(.999).toFixed(0),S=Wt.estLiquidityAndCoinAmountFromOneAmounts(p,u,new Q(v),f,!0,1,new Q(r));return f?S.coin_amount_b=A:S.coin_amount_a=A,{swap_result:C,liquidity_info:S}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${o}`)}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:o,coin_decimals_a:i,coin_decimals_b:a}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:n,marketList:s}=await this.getVaultAndPool(o,!1),{coin_type_a:r,coin_type_b:c}=n,l=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,_=t==="OnlyCoinA",d=s.find(m=>m.position_list.length>0);if(n.is_multiple_pool||!d){let m=await this.findRouters(_?r:c,_?c:r,l),{swap_out_amount:f,swap_in_amount:y}=m,g=_?i:a,h=_?a:i,w=tt(y,g),v=tt(f,h),C=P(v).div(w).toString(),A=await this.pythPrice.getLatestPrice([r,c],!0),S=A[r],k=A[c];if(!S||!k)throw new Error(`not find ${r} or ${c} price`);let D=fe(_?w:"0",_?"0":w,S.price,k.price,C,_),V=P(Ot(D,g).toString()).toFixed(0),B=P(l).sub(V).toFixed(0);if(P(B).lt(1)||P(V).lt(1))throw new Error("amount is less than 1");let j=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,V),O=P(j.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:_?B:O,amount_b:_?O:B},swap_result:j}}let p=s.find(m=>m.type==="CLMM");if(p){let{swap_result:m,liquidity_info:f}=await this.calculateClmmBalanceSwapAmount({...e},p);return{swap_result:m,liquidity_info:{bins:[],amount_a:f.coin_amount_a,amount_b:f.coin_amount_b}}}let u=s.find(m=>m.type==="DLMM");if(u){let m=u.certified_pool_obj[u.position_list[0].position.pool_id],f=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(m.bin_manager.bin_manager_handle,m.active_id,m.bin_step,!1),{active_id:y,bin_step:g}=m,h=Z.getPricePerLamportFromBinId(m.active_id,m.bin_step),w=P(h).mul(1-.05),v=P(h).mul(1+.05),C=Z.getBinIdFromLamportPrice(w.toString(),m.bin_step,!1),A=Z.getBinIdFromLamportPrice(v.toString(),m.bin_step,!1),S=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,coin_amount:l,fix_amount_a:_,active_id:y,bin_step:g,lower_bin_id:C,upper_bin_id:A,active_bin_of_pool:f,strategy_type:Nt.Spot}),k=_?P(S.amount_b).div(S.amount_a):P(S.amount_a).div(S.amount_b),D=_?Z.getPricePerLamportFromBinId(y,g):P(1).div(Z.getPricePerLamportFromBinId(y,g)).toString();try{let N=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,l);N&&(D=P(N.swap_out_amount).div(N.swap_in_amount).toString())}catch{}let{swap_amount:V,final_amount_a:B,final_amount_b:j}=pt(l,_,D,k.toString()),O=P(l).sub(V).toFixed(0),L=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,V),E=P(L.swap_out_amount).mul(.999).toFixed(0),x=_?O:E,T=_?E:O,K=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:x,amount_b:T,active_id:y,bin_step:g,lower_bin_id:C,upper_bin_id:A,active_bin_of_pool:f,strategy_type:Nt.Spot});return _?K.amount_b=L.swap_out_amount:K.amount_a=L.swap_out_amount,{swap_result:L,liquidity_info:K}}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:o,pool_id:i,uuid:a}=e,{pool:n,marketList:s}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:r,fixed_coin_a:c,coin_decimals_a:l,coin_decimals_b:_}=e;return await this.calculateDepositOtherSide(n,s,r,c,l,_,t,a)}case"FlexibleBoth":{let{coin_amount_a:r,coin_amount_b:c}=e;return await this.calculateDepositFlexibleBoth(n,r,c,t,a)}case"OnlyCoinA":{let{coin_amount_a:r,re_balance:c}=e;if(c){let l=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:d}=l,{amount_a:p,amount_b:u}=d,m=await this.calculateDepositFlexibleBoth(n,p,u,t,a);return m.re_balance={swap_result:_,coin_amount:r,mode:"OnlyCoinA"},m}else return await this.calculateDepositFlexibleBoth(n,r,"0",t,a)}case"OnlyCoinB":{let{coin_amount_b:r,re_balance:c}=e;if(c){let l=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:d}=l,{amount_a:p,amount_b:u}=d,m=await this.calculateDepositFlexibleBoth(n,p,u,t,a);return m.re_balance={swap_result:_,coin_amount:r,mode:"OnlyCoinB"},m}else return await this.calculateDepositFlexibleBoth(n,"0",r,t,a)}}throw new Error(`Unsupported deposit mode: ${o}`)}async getVaultAndPool(e,t=!1){let o=await this.getPool(e,t);if(o===void 0)throw new Error("get vaults pool failed");let{markets:i}=o,a=[];for(let n of i){let s={};if(n.type==="DLMM"){for(let r of n.position_list){let{pool_id:c}=r.position,l=await this._sdk.CetusDlmmSDK.Pool.getPool(c,t);if(!l)throw new Error(`get vaults dlmmPool failed ${c}`);s[c]=l}a.push({certified_pool_obj:s,...n})}else{for(let r of n.position_list){let{pool_id:c}=r.position,l=await this._sdk.CetusClmmSDK.Pool.getPool(c,t);if(!l)throw new Error(`get vaults clmmPool failed ${c}`);s[c]=l}a.push({certified_pool_obj:s,...n})}}if(a.length===0)throw new Error(`get vaults marketList failed ${e}`);return{marketList:a,pool:o}}async calculatePositionValueRates(e,t){let{lp_token_treasury:o,coin_type_a:i,coin_type_b:a}=e;if(P(o).eq(0))return{position_amount_a_rate:P(.5),position_amount_b_rate:P(.5)};let{position_amount_a:n,position_amount_b:s}=await qt(this._sdk,o,e.id),r=t[i],c=t[a];if(!r)throw Error(`not find ${i} price`);if(!c)throw Error(`not find ${a} price`);let l=P(tt(n,r.coin_decimals)).mul(r.price),_=P(tt(s,c.coin_decimals)).mul(c.price),d=P(l).add(_),p=P(l).div(d),u=P(1).sub(p);return{position_amount_a_rate:p,position_amount_b_rate:u}}async calculateDepositAmountByValue(e,t,o,i,a,n){let s=await this.PythPrice.getLatestPrice([a,n],!0),r=s[a],c=s[n];if(!r)throw Error(`not find ${a} price`);if(!c)throw Error(`not find ${n} price`);let l="0",_="0";if(e){l=t;let d=P(tt(l,o)).mul(r.price);_=P(Ot(P(d).div(c.price).toString(),i)).toFixed(0)}else{_=t;let d=P(tt(_,i)).mul(c.price);l=P(Ot(P(d).div(r.price).toString(),o)).toFixed(0)}if(P(l).lt(1)||P(_).lt(1))throw new Error("is less than 1");return{deposit_amount_a:l,deposit_amount_b:_}}async calculateDepositDlmmAmountsV2(e,t,o,i){let{markets:a}=e,{coin_type_a:n,coin_type_b:s}=e,r=a[0].position_list[0].position,c=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(t.bin_manager.bin_manager_handle,t.active_id,t.bin_step,!1),l=Z.getPricePerLamportFromBinId(t.active_id,t.bin_step),_=P(l).mul(1-.05),d=P(l).mul(1+.05),p=Z.getBinIdFromLamportPrice(_.toString(),t.bin_step,!1),u=Z.getBinIdFromLamportPrice(d.toString(),t.bin_step,!1),m={pool_id:r.pool_id,coin_amount:P(i).mul(1e5).toFixed(0),fix_amount_a:o,active_id:t.active_id,bin_step:t.bin_step,lower_bin_id:p,upper_bin_id:u,strategy_type:Nt.Spot,active_bin_of_pool:c},f=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo(m),{amount_a:y,amount_b:g}=f;return{deposit_amount_a:P(y).div(1e5).toFixed(0),deposit_amount_b:P(g).div(1e5).toFixed(0)}}async calculateDepositClmmAmounts(e,t,o,i){let{markets:a}=e,n=a[0].position_list[0].position,{tick_lower_index:s,tick_upper_index:r}=n,{current_sqrt_price:c,coin_type_a:l,coin_type_b:_}=t,{coin_amount_a:d,coin_amount_b:p}=Wt.estLiquidityAndCoinAmountFromOneAmounts(s,r,new Q(i),o,!0,1,new Q(c));return{deposit_amount_a:d.toString(),deposit_amount_b:p.toString()}}async calculateDepositOtherSide(e,t,o,i,a,n,s,r){let c="0",l="0",{coin_type_a:_,coin_type_b:d}=e;if(e.is_multiple_pool){let p=await this.calculateDepositAmountByValue(i,o,a,n,_,d);c=p.deposit_amount_a,l=p.deposit_amount_b}else if(t[0].type==="DLMM"&&t[0].position_list.length>0){let p=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:u,deposit_amount_b:m}=await this.calculateDepositDlmmAmountsV2(e,p,i,o);c=u,l=m}else if(t[0].type==="CLMM"&&t[0].position_list.length>0){let p=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:u,deposit_amount_b:m}=await this.calculateDepositClmmAmounts(e,p,i,o);c=P(u).add(c).toFixed(0),l=P(m).add(l).toFixed(0)}else{let p=await this.calculateDepositAmountByValue(i,o,a,n,_,d);c=p.deposit_amount_a,l=p.deposit_amount_b}if(s)this.calculateDepositLpAmountBoth(e,c,l).then(p=>{s.onSuccess(p,r)}).catch(p=>{s.onError(p,r)});else{let p=await this.calculateDepositLpAmountBoth(e,c,l);return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:p,uuid:r,mode:"FixedOneSide"}}return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:void 0,uuid:r,mode:"FixedOneSide"}}async calculateDepositFlexibleBoth(e,t,o,i,a){if(i)this.calculateDepositLpAmountBoth(e,t,o).then(n=>{i.onSuccess(n,a)}).catch(n=>{i.onError(n,a)});else{let n=await this.calculateDepositLpAmountBoth(e,t,o);return{deposit_amount_a:t,deposit_amount_b:o,lp_amount:n,uuid:a,mode:"FlexibleBoth"}}return{deposit_amount_a:t,deposit_amount_b:o,lp_amount:void 0,uuid:a,mode:"FlexibleBoth"}}async calculateDepositLpAmountBoth(e,t,o){let{lp_token_treasury:i,markets:a,quote_type:n,coin_type_a:s,coin_type_b:r}=e,c=U(s,!1),l=U(r,!1),{dlmmRewarderList:_,dlmmFeeList:d,clmmRewarderList:p,clmmFeeList:u}=await this.getVaultsPositionRewarderAndFee(e.id),m=yt(e.buffer_assets,[...d,...u],[..._,...p]),f=await ue(this._sdk,e.id,m,!0),y=await this.pythPrice.getLatestPrice([c,l],!0),g=y[c],h=y[l];if(!g)throw Error(`not find ${c} price`);if(!h)throw Error(`not find ${l} price`);let w={};w[c]={price:g,value:t.toString()},w[l]={price:h,value:o.toString()};let v=Y(w,n);return ht(i,v,f)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:o}=e,{pool:i}=await this.getVaultAndPool(o,!1);switch(t){case"FixedOneSide":{let{burn_lp_amount:a}=e;return await this.calculateWithdrawOtherSide(o,a)}case"OnlyCoinA":return await this.calculateWithdrawOnlyCoin(i,e.burn_lp_amount,!0);case"OnlyCoinB":return await this.calculateWithdrawOnlyCoin(i,e.burn_lp_amount,!1)}throw new Error(`Unsupported withdraw mode: ${t}`)}async calculateWithdrawOtherSide(e,t){let{amount_a:o,amount_b:i}=await Pt(this._sdk,t,e);return{receive_amount_a:o,receive_amount_b:i,burn_lp_amount:t,mode:"FixedOneSide"}}async calculateWithdrawOnlyCoin(e,t,o){let{totalReceiveAmount:i,swapAmountIn:a,swapAmountOut:n,remove_amount_a:s,remove_amount_b:r}=await this.calculateWithdrawOnlyCoinByLpAmount(e,o,t);return{receive_amount_a:o?i:"0",receive_amount_b:o?"0":i,burn_lp_amount:t,swap:{swap_amount_in:a,swap_amount_out:n,remove_amount_a:s,remove_amount_b:r},mode:o?"OnlyCoinA":"OnlyCoinB"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,o){let{coin_type_a:i,coin_type_b:a}=e,{amount_a:n,amount_b:s}=await Pt(this._sdk,o,e.id),r=await this.pythPrice.getLatestPrice([i,a],!0),c=r[i],l=r[a];if(!c)throw Error(`not find ${i} price`);if(!l)throw Error(`not find ${a} price`);let _=t?l:c,d=t?c:l,{quote_per_base:p}=gt(_.price,d.price),u=t?n:s,m=t?s:n,f=Ot(P(tt(m,t?l.coin_decimals:c.coin_decimals)).mul(p).toString(),t?c.coin_decimals:l.coin_decimals).toString(),y=P(u).add(f).toFixed(0);return{remove_amount_a:n,remove_amount_b:s,burn_lp_amount:o,is_coin_a:t,originAmount:u,swapAmountIn:m,swapAmountOut:P(f).toFixed(0,so.ROUND_DOWN),totalReceiveAmount:y}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,o=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),i=no(o);(await this._sdk.FullClient.queryEventsByPage({Transaction:i})).data.forEach(l=>{let _=l.parsedJson;if(l.type)switch(oo(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=_.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=_.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=_.global_config;break;default:break}});let n=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),s=De(n);e.pools_handle=s.pools.fields.id.id;let r=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),c=De(r);return e.oracle_infos_handle=c.oracle_infos.fields.id.id,e.prices_handle=c.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}async findRouters(e,t,o){let{providers:i}=this._sdk.sdkOptions,a=this._sdk.AggregatorClient;if(P(o).lt(1))throw new Error("amount is less than 1");try{let n={from:e,target:t,amount:new Q(o),byAmountIn:!0,depth:3,providers:i},s=await a.findRouters(n);if(s?.error)throw new Error(`Aggregator findRouters error: ${s?.error}`);if(!s?.paths||s?.paths?.length===0)throw new Error("Aggregator findRouters error: no router");let r=s.amountIn.toString(),c=s.amountOut.toString();return{swap_in_amount:r,swap_out_amount:c,route_obj:s}}catch(n){throw new Error(`Aggregator findRouters error: ${n}`)}}};import mo from"@cetusprotocol/dlmm-sdk";import{CoinAssist as co,d as Ht,fixCoinType as W}from"@cetusprotocol/common-sdk";var jt=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async getVaultAndPool(e){return e.version==="v1"?await this.sdk.Vaults.getVaultAndPool(e.vault_id):await this.sdk.VaultsV2.getVaultAndPool(e.vault_id)}async buildMigrateWithdrawTx(e,t){let{withdraw_result:o,return_ft_coin:i,liquidity_slippage:a,extra_burn:n}=e,{deposit_amount_a:s,deposit_amount_b:r,from_vault:c,to_vault:l,burn_ft_amount:_,from_swap_result:d}=o;if(c.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(l.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:p,clmmPool:u}=await this.getVaultAndPool(c),{marketList:m,pool:f}=await this.getVaultAndPool(l),{coin_type_a:y,coin_type_b:g}=u,h=n?Ht(_).sub(n.burn_lp_amount).toFixed(0).toString():_,{return_coin_a:w,return_coin_b:v}=await this.sdk.Vaults.buildWithdrawPayload({pool_id:c.vault_id,burn_lp_amount:h,mode:"FixedOneSide",slippage:a,return_coin:!0,extra_burn:n},t),C={[W(y,!1)]:w,[W(g,!1)]:v},{coin_output_a:A,coin_output_b:S}=d,{from_coin_type:k,from_coin_amount:D,route_obj:V,to_coin_type:B}=A;if(V){let{to_coin:O}=await this.buildSwapAssetsTx({from_coin_type:k,swap_in_amount:D,liquidity_slippage:a,route_obj:V.route_obj,tx:t,from_coin_object_id:C[W(k,!1)]});C[W(B,!1)]=O}if(S.route_obj){let{from_coin_type:O,from_coin_amount:L,route_obj:E,to_coin_type:x}=S,{to_coin:T}=await this.buildSwapAssetsTx({from_coin_type:O,swap_in_amount:L,liquidity_slippage:a,route_obj:E.route_obj,tx:t,from_coin_object_id:C[W(O,!1)]});C[W(x,!1)]=T}return await this._sdk.VaultsV2.buildDepositPayload({pool_id:l.vault_id,amount_a:s,amount_b:r,return_lp_coin:i,coin_a_input:C[W(f.coin_type_a,!1)],coin_b_input:C[W(f.coin_type_b,!1)]},t)}async calculateMigrateWithdraw(e){let{from_vault:t,to_vault:o,burn_ft_amount:i}=e;if(t.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(o.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:a,clmmPool:n}=await this.getVaultAndPool(t),{marketList:s,pool:r}=await this.getVaultAndPool(o),c=await this.sdk.Vaults.preCalculateWithdrawAmount({pool_id:t.vault_id,mode:"FixedOneSide",burn_lp_amount:i}),{coin_type_a:l,coin_type_b:_}=n,{coin_type_a:d,coin_type_b:p}=r,u=await this.matchSwapCoins({from:{coin_type_a:l,coin_amount_a:c.receive_amount_a,coin_type_b:_,coin_amount_b:c.receive_amount_b},to:{coin_type_a:d,coin_type_b:p}}),{coin_output_a:m,coin_output_b:f}=u,y=await this.sdk.VaultsV2.calculateDepositLpAmountBoth(r,m.to_coin_amount,f.to_coin_amount);return{from_vault:t,to_vault:o,burn_ft_amount:i,deposit_amount_a:m.to_coin_amount,deposit_amount_b:f.to_coin_amount,obtained_ft_amount:y,from_swap_result:u}}async buildSwapAssetsTx(e){let{from_coin_type:t,liquidity_slippage:o,tx:i,from_coin_object_id:a,swap_in_amount:n,route_obj:s}=e,r=a||co.buildCoinWithBalance(BigInt(n),t,i),c={router:s,inputCoin:r,slippage:o,txb:i};return{to_coin:await this._sdk.AggregatorClient.fixableRouterSwapV3(c)}}async matchSwapCoins(e){let{from:t,to:o}=e,i=W(t.coin_type_a,!1),a=W(t.coin_type_b,!1),n=W(o.coin_type_a,!1),s=W(o.coin_type_b,!1),r=i===n,c=i===s,l=a===n,_=a===s,d,p;r&&_?(d="A",p="B"):c&&l?(d="B",p="A"):r?(d="A",p="B"):c||l?(d="B",p="A"):(d="A",p="B");let u={from_coin_type:d==="A"?i:a,from_coin_amount:d==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:n,to_coin_amount:"0"},m={from_coin_type:p==="A"?i:a,from_coin_amount:p==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:s,to_coin_amount:"0"};if(u.from_coin_type!==u.to_coin_type&&Ht(u.from_coin_amount).gt(0))try{let f=await this.sdk.VaultsV2.findRouters(u.from_coin_type,u.to_coin_type,u.from_coin_amount);if(f)u.to_coin_amount=f.swap_out_amount,u.route_obj={swap_in_amount:f.swap_in_amount,swap_out_amount:f.swap_out_amount,route_obj:f.route_obj};else throw Error("Aggregator no router")}catch(f){throw f}else u.to_coin_amount=u.from_coin_amount;if(m.from_coin_type!==m.to_coin_type&&Ht(m.from_coin_amount).gt(0))try{let f=await this.sdk.VaultsV2.findRouters(m.from_coin_type,m.to_coin_type,m.from_coin_amount);if(f)m.to_coin_amount=f.swap_out_amount,m.route_obj={swap_in_amount:f.swap_in_amount,swap_out_amount:f.swap_out_amount,route_obj:f.route_obj};else throw Error("Aggregator no router")}catch(f){throw f}else m.to_coin_amount=m.from_coin_amount;return{coin_output_a:u,coin_output_b:m}}};var G=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=Pe),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||Fe.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||Fe.createSDK({env:"mainnet",full_rpc_url:e.fullRpcUrl}),this._cetusDlmmSDK=o||mo.createSDK({env:e.env,full_rpc_url:e.fullRpcUrl}),this._vaults=new St(this),this._vaultsV2=new Bt(this),this._migrate=new jt(this);let{primary:i,secondary:a}=e.pythConfigs.hermes_service_urls,n=[i,a].filter(Boolean);this._aggregatorClient=new uo({endpoint:e.aggregatorUrl,signer:_o("0x0"),client:this.FullClient,env:e.env==="testnet"?Oe.Testnet:Oe.Mainnet,pythUrls:n}),this._vest=new Dt(this)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e,this.CetusClmmSDK.setSenderAddress(e)}get sdkOptions(){return this._sdkOptions}get Vaults(){return this._vaults}get VaultsV2(){return this._vaultsV2}get FullClient(){return this._cetusClmmSDK.FullClient}get AggregatorClient(){return this._aggregatorClient}get CetusClmmSDK(){return this._cetusClmmSDK}get CetusDlmmSDK(){return this._cetusDlmmSDK}get Vest(){return this._vest}get Migrate(){return this._migrate}getVerifySenderAddress(){if(this.senderAddress.length===0||!lo(this.senderAddress))throw Error("this sdk senderAddress is illegal");return this.senderAddress}async getOwnerCoinAssets(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinAssets(e,t)}async getOwnerCoinBalances(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinBalances(e,t)}updateCache(e,t,o=po){this.CetusClmmSDK.updateCache(e,t,o)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var jn=.2;var Hn=G;export{lt as PythPriceModule,Ue as SdkEnv,St as VaultsModule,Bt as VaultsModuleV2,Dt as VestModule,G as VolatileVaultsSDK,me as buildCLMMMarketId,_e as buildCLMMMarketPosition,pe as buildDLMMMarketId,de as buildDLMMMarketPosition,qo as buildDLMMPositionId,at as buildPoolData,Rt as buildPoolV2Data,le as buildVaultMarket,oe as buildVaultsBalance,qt as buildVaultsBalanceV2,pt as calcExactSwapAmount,fe as calcSingleSideSwap,ee as calculateAum,ue as calculateAumV2,Te as calculateDepositRatioFixTokenA,Y as calculateTotalAumBasedOnQuote,Lt as checkIsMinOrMaxIndex,yo as convertU64BytesToDecimal,Hn as default,Pe as defaultProvider,jn as dlmm_split_rate,Jt as estCoinAmountsFromTotalAmount,ge as feed_map_mainnet,we as feed_map_testnet,Pt as getAmountBalanceByLpAmount,H as getCoinAmountsFromRatio,So as getPositionPriceRange,ie as getPriceWithFormattedDecimals,Ee as getPrimitivePricesFromBaseQuote,gt as getQuotePerBaseAndBasePerQuote,rt as getShareBufferAssets,_t as getUpdatePriceType,yt as getVaultValidBalances,Ao as get_lp_amount_by_liquidity,ht as get_lp_amount_by_tvl,st as get_share_liquidity_by_amount,he as initMainnetSDK,ve as initTestnetSDK,ti as initVaultSDK,it as oraclePriceMultiplierDecimal,ae as parseVaultVestNFT,It as parseVaultsVestInfo,Vo as printTransaction,ne as toSuiObjectId,be as vaults_mainnet,ye as vaults_testnet};
|