UNPKG

@nemoprotocol/vaults-sdk

Version:

A TypeScript SDK for interacting with Nemo Vaults on the Sui blockchain

1 lines 72.6 kB
var Re=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Rt=(a,t,e,n)=>{for(var i=n>1?void 0:n?Ne(t,e):t,o=a.length-1,r;o>=0;o--)(r=a[o])&&(i=(n?r(t,e,i):r(i))||i);return n&&i&&Re(t,e,i),i};var Nt=(i=>(i.Mmt="Mmt",i.Haedal="Haedal",i.Volo="Volo",i.Aftermath="aftermath",i))(Nt||{}),Zt=(e=>(e.Both="both",e.OneSide="oneSide",e))(Zt||{});import{getFullnodeUrl as tn,SuiClient as Se}from"@mysten/sui/client";var Et=class a extends Error{constructor(e,n,i){super(e);this.code=n;this.details=i;this.name=this.constructor.name}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details}}toString(){return JSON.stringify(this.toJSON())}static isErrorCode(e,n){return e instanceof a&&e.code===n}},ht=class extends Et{constructor(t,e,n){super(t,e||"UnknownError",n)}},Jt=(a,t,e)=>{throw new ht(t.message,a,e)},g=(a,t,e)=>{throw new ht(t,a,e)};import Mt from"bn.js";import f from"bn.js";import Bt from"decimal.js";Bt.config({precision:64,rounding:Bt.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var c=Bt;import k from"bn.js";var W=new k(0),pt=new k(1),yt=new k(2),mn=yt.pow(new k(128)),Qt=yt.pow(new k(64)).sub(pt),Ee=yt.pow(new k(128)).sub(pt),b=class a{static toX64BN(t){return t.mul(new k(2).pow(new k(64)))}static toX64Decimal(t){return t.mul(c.pow(2,64))}static toX64(t){return new k(t.mul(c.pow(2,64)).floor().toFixed())}static fromX64(t){return new c(t.toString()).mul(c.pow(2,-64))}static fromX64Decimal(t){return t.mul(c.pow(2,-64))}static fromX64BN(t){return t.div(new k(2).pow(new k(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(Qt).gt(W)&&(e=e.add(pt)),e}static divRoundUp(t,e){return t.mod(e).eq(W)?t.div(e):t.div(e).add(new k(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(Ee):t.sub(e)}static checkUnsignedSub(t,e){let n=t.sub(e);if(n.isNeg())throw new Error("Unsigned integer sub overflow");return n}static checkMul(t,e,n){let i=t.mul(e);return this.isOverflow(i,n)&&g("MultiplicationOverflow","Multiplication overflow"),i}static checkMulDivFloor(t,e,n,i){n.eq(W)&&g("DivisionByZero","Divide by zero");let o=t.mul(e).div(n);return this.isOverflow(o,i)&&g("MultiplicationOverflow","Multiplication div overflow"),o}static checkMulDivCeil(t,e,n,i){if(n.eq(W))throw new Error("Divide by zero");let o=t.mul(e).add(n.sub(pt)).div(n);if(this.isOverflow(o,i))throw new Error("Multiplication div overflow");return o}static checkMulDivRound(t,e,n,i){n.eq(W)&&g("DivisionByZero","Divide by zero");let o=t.mul(e.add(n.shrn(1))).div(n);return this.isOverflow(o,i)&&g("MultiplicationOverflow","Multiplication div overflow"),o}static checkMulShiftRight(t,e,n,i){let o=t.mul(e).div(new k(2).pow(new k(n)));return this.isOverflow(o,i)&&g("MultiplicationOverflow","Multiplication shift right overflow"),o}static checkMulShiftRight64RoundUpIf(t,e,n,i){let o=t.mul(e),s=i&&o.and(Qt).gt(W)?o.shrn(64).add(pt):o.shrn(64);return this.isOverflow(s,n)&&g("MultiplicationOverflow","Multiplication shift right overflow"),s}static checkMulShiftLeft(t,e,n,i){let o=t.mul(e).shln(n);return this.isOverflow(o,i)&&g("MultiplicationOverflow","Multiplication shift left overflow"),o}static checkDivRoundUpIf(t,e,n){return e.eq(W)&&g("DivisionByZero","Divide by zero"),n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(yt.pow(new k(e)))}static sign(t){return t.testn(127)?1:0}static is_neg(t){return this.sign(t)===1}static abs_u128(t){return t.gt(W)?t:this.u128Neg(t.subn(1))}static u128Neg(t){return t.uxor(new k("ffffffffffffffffffffffffffffffff",16))}static neg(t){return this.is_neg(t)?t.abs():this.negFrom(t)}static abs(t){return this.sign(t)===0?t:this.u128Neg(t.sub(new k(1)))}static negFrom(t){return t.eq(W)?t:this.u128Neg(t).add(new k(1)).or(new k(1).shln(127))}static u64ToRatio(t){return new c(t).div(new c(2).pow(64))}static getPriceFromSqrtPrice(t,e,n){let i=a.u64ToRatio(t).pow(2);return c(1).div(i).div(c(10).pow(e-n))}static u32ToI32(t){let e=Buffer.alloc(4);return e.writeUInt32LE(t,0),e.readInt32LE(0)}};var oe="79226673515401279992447579055",re="4295048016",te=14,ee="59543866431248",Be="184467440737095516",ne="15793534762490258745";function w(a){return c.isDecimal(a)?a:new c(a===void 0?0:a)}function ie(a,t,e){let n=a.toTwos(e).shln(t);return n.imaskn(e+1),n.fromTwos(e)}function C(a,t,e){let n=a.toTwos(e).shrn(t);return n.imaskn(e-t+1),n.fromTwos(e-t)}function qe(a){let t;return(a&1)!==0?t=new f("79232123823359799118286999567"):t=new f("79228162514264337593543950336"),(a&2)!==0&&(t=C(t.mul(new f("79236085330515764027303304731")),96,256)),(a&4)!==0&&(t=C(t.mul(new f("79244008939048815603706035061")),96,256)),(a&8)!==0&&(t=C(t.mul(new f("79259858533276714757314932305")),96,256)),(a&16)!==0&&(t=C(t.mul(new f("79291567232598584799939703904")),96,256)),(a&32)!==0&&(t=C(t.mul(new f("79355022692464371645785046466")),96,256)),(a&64)!==0&&(t=C(t.mul(new f("79482085999252804386437311141")),96,256)),(a&128)!==0&&(t=C(t.mul(new f("79736823300114093921829183326")),96,256)),(a&256)!==0&&(t=C(t.mul(new f("80248749790819932309965073892")),96,256)),(a&512)!==0&&(t=C(t.mul(new f("81282483887344747381513967011")),96,256)),(a&1024)!==0&&(t=C(t.mul(new f("83390072131320151908154831281")),96,256)),(a&2048)!==0&&(t=C(t.mul(new f("87770609709833776024991924138")),96,256)),(a&4096)!==0&&(t=C(t.mul(new f("97234110755111693312479820773")),96,256)),(a&8192)!==0&&(t=C(t.mul(new f("119332217159966728226237229890")),96,256)),(a&16384)!==0&&(t=C(t.mul(new f("179736315981702064433883588727")),96,256)),(a&32768)!==0&&(t=C(t.mul(new f("407748233172238350107850275304")),96,256)),(a&65536)!==0&&(t=C(t.mul(new f("2098478828474011932436660412517")),96,256)),(a&131072)!==0&&(t=C(t.mul(new f("55581415166113811149459800483533")),96,256)),(a&262144)!==0&&(t=C(t.mul(new f("38992368544603139932233054999993551")),96,256)),C(t,32,256)}function Fe(a){let t=Math.abs(a),e;return(t&1)!==0?e=new f("18445821805675392311"):e=new f("18446744073709551616"),(t&2)!==0&&(e=C(e.mul(new f("18444899583751176498")),64,256)),(t&4)!==0&&(e=C(e.mul(new f("18443055278223354162")),64,256)),(t&8)!==0&&(e=C(e.mul(new f("18439367220385604838")),64,256)),(t&16)!==0&&(e=C(e.mul(new f("18431993317065449817")),64,256)),(t&32)!==0&&(e=C(e.mul(new f("18417254355718160513")),64,256)),(t&64)!==0&&(e=C(e.mul(new f("18387811781193591352")),64,256)),(t&128)!==0&&(e=C(e.mul(new f("18329067761203520168")),64,256)),(t&256)!==0&&(e=C(e.mul(new f("18212142134806087854")),64,256)),(t&512)!==0&&(e=C(e.mul(new f("17980523815641551639")),64,256)),(t&1024)!==0&&(e=C(e.mul(new f("17526086738831147013")),64,256)),(t&2048)!==0&&(e=C(e.mul(new f("16651378430235024244")),64,256)),(t&4096)!==0&&(e=C(e.mul(new f("15030750278693429944")),64,256)),(t&8192)!==0&&(e=C(e.mul(new f("12247334978882834399")),64,256)),(t&16384)!==0&&(e=C(e.mul(new f("8131365268884726200")),64,256)),(t&32768)!==0&&(e=C(e.mul(new f("3584323654723342297")),64,256)),(t&65536)!==0&&(e=C(e.mul(new f("696457651847595233")),64,256)),(t&131072)!==0&&(e=C(e.mul(new f("26294789957452057")),64,256)),(t&262144)!==0&&(e=C(e.mul(new f("37481735321082")),64,256)),e}var D=class a{static priceToSqrtPriceX64(t,e,n){return b.toX64(t.mul(c.pow(10,n-e)).sqrt())}static sqrtPriceX64ToPrice(t,e,n){return b.fromX64(t).pow(2).mul(c.pow(10,e-n))}static tickIndexToSqrtPriceX64(t){return t>0?new f(qe(t)):new f(Fe(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new f(oe))||t.lt(new f(re)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new f(e-64),i=ie(n,32,128),o=new f("8000000000000000","hex"),r=0,s=new f(0),u=e>=64?t.shrn(e-63):t.shln(63-e);for(;o.gt(new f(0))&&r<te;){u=u.mul(u);let v=u.shrn(127);u=u.shrn(63+v.toNumber()),s=s.add(o.mul(v)),o=o.shrn(1),r+=1}let l=s.shrn(32),p=i.add(l).mul(new f(ee)),m=C(p.sub(new f(Be)),64,128).toNumber(),d=C(p.add(new f(ne)),64,128).toNumber();return m===d?m:a.tickIndexToSqrtPriceX64(d).lte(t)?d:m}static tickIndexToPrice(t,e,n){return a.sqrtPriceX64ToPrice(a.tickIndexToSqrtPriceX64(t),e,n)}static priceToTickIndex(t,e,n){return a.sqrtPriceX64ToTickIndex(a.priceToSqrtPriceX64(t,e,n))}static priceToInitializeTickIndex(t,e,n,i){return a.getInitializeTickIndex(a.priceToTickIndex(t,e,n),i)}static getInitializeTickIndex(t,e){return t-t%e}static getNextInitializeTickIndex(t,e){return a.getInitializeTickIndex(t,e)+e}static getPrevInitializeTickIndex(t,e){return a.getInitializeTickIndex(t,e)-e}static priceToTickIndexWithTickSpacingUnsafe(t,e,n,i){return a.sqrtPriceX64ToTickIndexWithTickSpacingUnsafe(a.priceToSqrtPriceX64(t,e,n),i)}static sqrtPriceX64ToTickIndexWithTickSpacingUnsafe(t,e){let n=t.bitLength()-1,i=new f(n-64),o=ie(i,32,128),r=new f("8000000000000000","hex"),s=0,u=new f(0),l=n>=64?t.shrn(n-63):t.shln(63-n);for(;r.gt(new f(0))&&s<te;){l=l.mul(l);let T=l.shrn(127);l=l.shrn(63+T.toNumber()),u=u.add(r.mul(T)),r=r.shrn(1),s+=1}let _=u.shrn(32),m=o.add(_).mul(new f(ee)),d=C(m.add(new f(ne)),64,128).toNumber(),y=d%e,v=y===0?d:d+(e-y);return Ve(v)}};function qt(a){return a?re:oe}function Ve(a){if(a<-2147483648||a>2147483647)throw new RangeError("The number is out of range for a 32-bit signed integer.");return a<0?4294967296+a:a}import Q from"decimal.js";import{normalizeSuiObjectId as Me}from"@mysten/sui/utils";var Y="0x0000000000000000000000000000000000000000000000000000000000000006",nt="0x2::sui::SUI",ae="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",G=process.env.MMT_ORACLE_PACKAGE_ID||"0x45fe3ef1ed2d9b444b8041a84e426242ad129483bf56000cdd514b8065967f4d",Ft=process.env.ORACLE_ADMIN_CAP_ID||"0xf5ca46bf4d4c087766118f143dea81d0ef3af9c2704635ece9d3af18f22aacb8",se=process.env.REGISTRY_ADMIN_CAP_ID||"0x77659bd055091b9d3d193263af964fbd0c47d75601a247f6e4777f70cf82450f",ce=process.env.COIN_DECIMALS_REGISTRY||"0x04a645616e229f986b0b4c15def3ef46c4d84ad51d1d6419d567498de0dba564",wt=process.env.SET_PRICE_CAP_REGISTRY||"0xd088d1eaf09dfda03c989acf3063fd0e3e14432a2d21bf9fd2be30bf76373bfd",M=process.env.MMT_ORACLE_ID||"0x6cc485157712b67d3bbc71110947084aad0d23d7661add04e13038cfa765e80a",h=process.env.VAULT_PACKAGE_ID||"0x8e5c2564d9e8a6d2687eb6f1d7322fd0ed7c66d3bd57c9664d74814f148a314e",L=process.env.VAULT_VERSION_ID||"0xef1aff44bb19bb1d0908b1fee334b680df8f1175e31e49a821ac7942913efd09",dt=process.env.MMT_CLMM_VERSION_ID||"0x2375a0b1ec12010aaea3b2545acfa2ad34cfbba03ce4b59f4c39e1e25eed1b2a",Vt="deposit",ue="withdraw",z=process.env.PRICE_ADAPTER_PACKAGE_ID||"0x1bf70849bc2b14361b30c1b10809d9b592224de25114798dca4a5891e011426a",it=process.env.REGISTRY_ID||"0x6f8c395de3f250e08c01a25500c185d74cb182002d76750189c7e20a514befa8",le=process.env.PRICE_ADAPTER_ADMIN_CAP||"0x9eec84b9c46c4087fe2f2261084092dd9835a9c81dfe6ff711beb306385d3a59",P=process.env.VAULT_ADMIN_CAP||"0xb3320d9cd09d23f0c7be41fcbe88ef6da9613ae097bd53d510b3ad91bad62378",wn=process.env.VAULT_ACL||"0x77d3b63065b24fff2c934853b9670c848680712977a66c4494e630d76ff097d5",vn=process.env.ROUTER_ACL||"0x253fb8c10c2f7be045f28b67cf72cbb58f6a21cc0cf38dd9d213d02468d9e829",ot=process.env.MMT_ROUTER_PACKAGE_ID||"0x5f9b325644ed096907becd7349a901623dbf604f7217fd8d521a06072aa32602",vt=process.env.PYTH_STATE_ID||"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",$=process.env.NEMO_API_URL||"https://api.nemoprotocol.com/api/v1",Tn=process.env.MMT_CLMM_PACKAGE_ID||"0xcf60a40f45d46fc1e828871a647c1e25a0915dec860d2662eb10fdb382c3c1d1",rt={"0x2::sui::SUI":{priceInfoObjectId:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{priceInfoObjectId:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"},"0x375f70cf2ae4c00bf37117d0c85a2c71545e6ee05c4a5c7d282cd66a4504b068::usdt::USDT":{priceInfoObjectId:"0x985e3db9f93f76ee8bace7c3dd5cc676a096accd5d9e09e9ae0fb6e492b14572"},"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{priceInfoObjectId:"0x5dec622733a204ca27f5a90d8c2fad453cc6665186fd5dff13a83d0b6c9027ab"},"0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI":{priceInfoObjectId:"0x801dbc2f0053d34734814b2d6df491ce7807a725fe9a01ad74a07e9c51396c37"},"0x876a4b7bce8aeaef60464c11f4026903e9afacab79b9b142686158aa86560b50::xbtc::XBTC":{priceInfoObjectId:"0x9a62b4863bdeaabdc9500fce769cf7e72d5585eeb28a6d26e4cafadc13f76ab2"},"0xaafb102dd0902f5055cadecd687fb5b71ca82ef0e0285d90afde828ec58ca96b::btc::BTC":{priceInfoObjectId:"0x9a62b4863bdeaabdc9500fce769cf7e72d5585eeb28a6d26e4cafadc13f76ab2"},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{priceInfoObjectId:"0x9a62b4863bdeaabdc9500fce769cf7e72d5585eeb28a6d26e4cafadc13f76ab2"}},_e=["0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI","0x876a4b7bce8aeaef60464c11f4026903e9afacab79b9b142686158aa86560b50::xbtc::XBTC","0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC"],X={config:{haedal:{package_id:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",published_at:"0xaabf0856070391df81fad9240049d69c5a51c3d376cc0885eeedd516526cc79b",version:1,config:{staking_id:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"}},volo:{package_id:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",published_at:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",version:1,config:{native_pool:"0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf",vsui_metadata:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coin_type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"}},aftermath:{package_id:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",published_at:"0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6",version:1,config:{staked_sui_vault:"0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d",referral_vault:"0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef",safe:"0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610",validator_address:"0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2",coin_type:"0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI"}}}};import{coinWithBalance as me,Transaction as Ue}from"@mysten/sui/transactions";import K from"bn.js";import{TickMath as mt}from"@mmt-finance/clmm-sdk";import Tt from"decimal.js";async function Ct(a){let{input_ft_amount:t,slippage:e,vault:n}=a,i=n.pool,{position:o}=n,r=o.tick_lower_index,s=o.tick_upper_index,u=mt.tickIndexToSqrtPriceX64(r),l=mt.tickIndexToSqrtPriceX64(s),_=new K(t),p=at(n,_.toString()),m=new K(i.currentSqrtPrice),d=J(new K(p),m,u,l,!1),y=w(d.coin_amount_a.toString()).mul(w(1-e)),v=w(d.coin_amount_b.toString()).mul(w(1-e));return{amount_a:d.coin_amount_a.toString(),amount_b:d.coin_amount_b.toString(),amount_limit_a:y.toFixed(0),amount_limit_b:v.toFixed(0)}}function Z(a,t,e,n,i,o,r){let s=mt.sqrtPriceX64ToTickIndex(r),u=mt.tickIndexToSqrtPriceX64(a),l=mt.tickIndexToSqrtPriceX64(t),_;s<a?_=pe(u,l,e):s>t?_=de(l,u,e):n?_=pe(r,l,e):_=de(r,u,e);let p=J(_,r,u,l,i),m=i?w(p.coin_amount_a.toString()).mul(1+o).toString():w(p.coin_amount_a.toString()).mul(1-o).toString(),d=i?w(p.coin_amount_b.toString()).mul(1+o).toString():w(p.coin_amount_b.toString()).mul(1-o).toString();return{coin_amount_a:p.coin_amount_a,coin_amount_b:p.coin_amount_b,coin_amount_limit_a:i?Tt.ceil(m).toString():Tt.floor(m).toString(),coin_amount_limit_b:i?Tt.ceil(d).toString():Tt.floor(d).toString(),liquidity_amount:_.toString(),is_amount_a:n}}function pe(a,t,e){let n=K.min(a,t),i=K.max(a,t),o=b.fromX64BN(e.mul(i).mul(n)),r=i.sub(n);return!o.isZero()&&!r.isZero()?o.div(r):new K(0)}function de(a,t,e){let n=K.min(a,t),o=K.max(a,t).sub(n);return o.isZero()?new K(0):e.shln(64).div(o)}function J(a,t,e,n,i){let o=new Q(a.toString()),r=new Q(t.toString()),s=new Q(e.toString()),u=new Q(n.toString()),l,_;return t.lt(e)?(l=b.toX64Decimal(o).mul(u.sub(s)).div(s.mul(u)),_=new Q(0)):t.lt(n)?(l=b.toX64Decimal(o).mul(u.sub(r)).div(r.mul(u)),_=b.fromX64Decimal(o.mul(r.sub(s)))):(l=new Q(0),_=b.fromX64Decimal(o.mul(u.sub(s)))),i?{coin_amount_a:l.ceil().toString(),coin_amount_b:_.ceil().toString()}:{coin_amount_a:l.floor().toString(),coin_amount_b:_.floor().toString()}}function at(a,t){return a.total_supply==="0"?"0":w(t).mul(a.liquidity).div(a.total_supply).toFixed(0,Q.ROUND_DOWN).toString()}function N(a){try{let t=a.replace(/\s/g,""),n=t.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){t=t.slice(0,t.indexOf("<"));let u={...N(t),type_arguments:n.map(l=>N(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>N(l).full_address===nt?l:N(l).source_address),u.source_address=ge(u.full_address,u.type_arguments),u}let i=t.split("::"),r={full_address:t,address:t===nt||t===ae?"0x2":Me(i[0]),module:i[1],name:i[2],type_arguments:[],source_address:""};return r.full_address=`${r.address}::${r.module}::${r.name}`,r.source_address=ge(r.full_address,r.type_arguments),r}catch{return{full_address:a,address:"",module:"",name:"",type_arguments:[],source_address:a}}}function ge(a,...t){let e=Array.isArray(t[t.length-1])?t.pop():[],i=[a,...t].filter(Boolean).join("::");return e&&e.length&&(i+=`<${e.join(", ")}>`),i}function st(a,t,e){return a===BigInt(0)&&N(t).full_address===nt?e.add(me({balance:a,useGasCoin:!1})):e.add(me({balance:a,type:t}))}function Ut(a,t=32){return Number(BigInt.asIntN(t,BigInt(a)))}function Lt(a,t,e){let n=new Mt(1e8),{coin_amount_b:i}=Z(a,t,n,!0,!0,0,e),o=D.sqrtPriceX64ToPrice(e,0,0),r=w(n.toString()).mul(o),s=r.add(i.toString()),u=r.div(s),l=w(i.toString()).div(s);return{ratio_a:u,ratio_b:l}}function $t(a){return N(a).full_address===nt}async function fe(a,t,e,n){let i=await Le(a,e,nt);i.length===0&&g("InsufficientCoins","No SUI coin objects found in wallet"),i.reduce((l,_)=>l+BigInt(_.balance),BigInt(0))<BigInt(t)&&g("InsufficientCoins","Insufficient SUI balance"),n=n||new Ue;let[r,...s]=i;return s.length>0&&n.mergeCoins(n.object(r.coin_object_id),s.map(l=>n.object(l.coin_object_id))),n.splitCoins(n.object(r.coin_object_id),[t])}async function Le(a,t,e){let n=[],i=null;for(;;){let o=await(e?a.getConfig().suiClient.getCoins({owner:t,coinType:e,cursor:i}):a.getConfig().suiClient.getAllCoins({owner:t,cursor:i}));if(o.data.forEach(r=>{BigInt(r.balance)>0&&n.push({coin_type:N(r.coinType).source_address,coin_object_id:r.coinObjectId,balance:BigInt(r.balance)})}),i=o.nextCursor,!o.hasNextPage)break}return n}function gt(a,t,e,n,i){let o=at(t,e.totalBalance),{tick_lower_index:r,tick_upper_index:s,type_x:u,type_y:l}=t.position,_=D.tickIndexToSqrtPriceX64(r),p=D.tickIndexToSqrtPriceX64(s),m=J(new Mt(o),new Mt(i),_,p,!0);return{vault_id:t.id,clmm_pool_id:t.clmm_pool_id,owner:a,lp_token_type:t.lp_token_type,lp_token_balance:e.totalBalance,lp_token_decimals:n?.decimals??9,liquidity:o,tick_lower_index:r,tick_upper_index:s,amount_a:m.coin_amount_a.toString(),amount_b:m.coin_amount_b.toString(),coin_type_a:u,coin_type_b:l,decimal_a:t.decimals_a,decimal_b:t.decimals_b}}import B from"bn.js";import{coinWithBalance as en,Transaction as je}from"@mysten/sui/transactions";function ct(a){let t=be(a)?.fields;if(t)return"fields"in t?t.fields:t}function be(a){let t="data"in a?$e(a):a;if(!(!t||!Xe(t)||t.content.dataType!=="moveObject"))return t.content}function $e(a){return a.data}function Xe(a){return a.content!==void 0}function ft(a){let t=We(a)?a.data:a;return!t?.type&&"data"in a?t?.content?.dataType==="package"?"package":Ge(a):t?.type}function We(a){return a.data!==void 0}function Ge(a){return be(a)?.type}async function he(a,t,e,n=50){let i=[];try{for(let o=0;o<Math.ceil(t.length/n);o++){let r=await a.multiGetObjects({ids:t.slice(o*n,n*(o+1)),options:e});i=[...i,...r]}}catch(o){console.log(o)}return i}import{MmtSDK as Yt}from"@mmt-finance/clmm-sdk";import{bcs as nn}from"@mysten/sui/bcs";import Ke from"bn.js";async function ye(a,t,e,n){let i=!1;(!c(a.lock_threshold_a).equals(0)||!c(a.lock_threshold_b).equals(0))&&(i=c(a.free_balance_a).greaterThanOrEqualTo(c(a.lock_threshold_a))||c(a.free_balance_b).greaterThanOrEqualTo(a.lock_threshold_b));let o=!1,r=null,s=null,u=await t.getDynamicFields({parentId:a.id.id}),l={};for(let v of u.data){let T=v.name.value,A=new TextDecoder().decode(new Uint8Array(T));A==="deposit_enabled"?l.deposit_enabled=v.objectId:A==="position"&&(l.position=v.objectId)}let _=await t.multiGetObjects({ids:Object.values(l),options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});for(let v of _){let T=v.data;!T||!T.content||!T.content.dataType||T.content.dataType!=="moveObject"||(l.deposit_enabled&&l.deposit_enabled===T.objectId?o=T.content.fields.value:l.position&&l.position===T.objectId&&(r=T.content.fields.value.fields.liquidity,s=He(T.content.fields,a.decimals_a,a.decimals_b)))}if(r==null||s==null)return g("BuildError","buildVault error, liquidity or position is null");let p=N(e),m=D.sqrtPriceX64ToPrice(new Ke(n.currentSqrtPrice),a.decimals_a,a.decimals_b),d=m.mul(b.u64ToRatio(a.upper_price_scalling)),y=m.mul(b.u64ToRatio(a.lower_price_scalling));return{id:a.id.id,clmm_pool_id:a.clmm_pool_id,free_balance_a:a.free_balance_a,free_balance_b:a.free_balance_b,fee_a:a.fee_a,fee_b:a.fee_b,seed_balance:a.seed_balance,upper_price_scalling:a.upper_price_scalling,lower_price_scalling:a.lower_price_scalling,upper_trigger_price_scalling_dec:d,lower_trigger_price_scalling_dec:y,upper_price_scalling_dec:b.u64ToRatio(a.upper_price_scalling),lower_price_scalling_dec:b.u64ToRatio(a.lower_price_scalling),lower_trigger_price:a.config.fields.t.fields.lower_trigger_price,upper_trigger_price:a.config.fields.t.fields.upper_trigger_price,last_rebalance_sqrt_price:a.last_rebalance_sqrt_price,last_rebalance_sqrt_price_dec:b.u64ToRatio(a.last_rebalance_sqrt_price),last_rebalance_time:a.last_rebalance_time,deposit_limit:a.deposit_limit,free_threshold_a:a.free_threshold_a,free_threshold_b:a.free_threshold_b,lock_threshold_a:a.lock_threshold_a,lock_threshold_b:a.lock_threshold_b,slippage_up:a.slippage_up,slippage_down:a.slippage_down,slippage_up_dec:b.u64ToRatio(a.slippage_up),slippage_down_dec:b.u64ToRatio(a.slippage_down),fee_val:a.fee_val,withdraw_fee_val:a.withdraw_fee_val,decimals_a:a.decimals_a,decimals_b:a.decimals_b,coin_type_a:p.type_arguments[0],coin_type_b:p.type_arguments[1],lp_token_type:p.type_arguments[2],config_type:p.type_arguments[3],is_lock:i,is_deposit_enabled:o,pool_sqrt_price:n.currentSqrtPrice,total_supply:a.treasury_cap.fields.total_supply.fields.value,liquidity:r,position:s,pool:n}}async function we(a,t,e){let n=ct(e),i=ft(e);if(n){let o=n.clmm_pool_id,r=await a.Pool.getPool(o);return await ye(n,t,i,r)}return g("BuildError","buildVault error")}async function ve(a,t,e){let n=ct(e),i=ft(e);if(n){let o=n.clmm_pool_id,r=a[o];return await ye(n,t,i,r)}return g("BuildError","buildVault error")}function He(a,t,e){let n=a.value.fields,i=Ut(BigInt(n.tick_lower_index.fields.bits)),o=Ut(BigInt(n.tick_upper_index.fields.bits));return{id:a.id.id,pool_id:n.pool_id,type_x:n.type_x.fields.name,type_y:n.type_y.fields.name,name:n.name,liquidity:n.liquidity,clmm_position_id:n.id.id,clmm_pool_id:n.pool,tick_lower_index:i,tick_upper_index:o,price_lower_tick_dec:D.tickIndexToPrice(i,t,e),price_upper_tick_dec:D.tickIndexToPrice(o,t,e)}}function At(a,t){return a.total_supply==="0"?"0":w(a.total_supply).mul(t).div(a.liquidity).toFixed(0,c.ROUND_DOWN).toString()}import{normalizeSuiObjectId as Te}from"@mysten/sui/utils";var St=class{static requestStakeCoin(t,e){let n=X.config.haedal;return t.moveCall({target:`${n.published_at}::staking::request_stake_coin`,typeArguments:[],arguments:[t.object(Te("0x5")),t.object(n.config.staking_id),e,t.pure.address(Te("0x0"))]})}};import{Transaction as Ye}from"@mysten/sui/transactions";import{normalizeSuiObjectId as xe}from"@mysten/sui/utils";var jt=class{static requestStakeCoin(t,e){let n=X.config.volo;if(n===void 0)return g("StakeProtocolNotFound","the volo config is undefined");t=t||new Ye;let{native_pool:i,vsui_metadata:o}=n.config;return t.moveCall({target:`${n.published_at}::native_pool::stake_non_entry`,typeArguments:[],arguments:[t.object(i),t.object(o),t.object(xe("0x5")),e]})}};import{Transaction as Xt}from"@mysten/sui/transactions";import{normalizeSuiAddress as ze,normalizeSuiObjectId as Pt}from"@mysten/sui/utils";import{bcs as Ze}from"@mysten/sui/bcs";var bt=class{static async getExchangeRateForStake(t,e,n,i){let o=X.config.aftermath;if(o===void 0)return g("StakeProtocolNotFound","the aftermath config is undefined");let{staked_sui_vault:r,safe:s}=o.config;try{let u=new Xt;n?await this.requestStake(t,i||1e9,e,u):u.moveCall({target:`${o.published_at}::staked_sui_vault::afsui_to_sui_exchange_rate`,typeArguments:[],arguments:[u.object(r),u.object(s)]});let l=await t.getConfig().suiClient.devInspectTransactionBlock({transactionBlock:u,sender:ze("0x0")});if(n){let m=l.events.find(v=>v.type.includes("StakedEvent")),{afsui_amount:d,sui_amount:y}=m.parsedJson;return w(y).div(d).toString()}let _=l.results[0].return_values[0][0];return w(Ze.u128().parse(Uint8Array.from(_))).div(1e18).toString()}catch(u){return Jt("FetchError",u,{methodName:"getExchangeRateForStake"})}return"0"}static async requestStake(t,e,n,i){let o=X.config.aftermath;if(o===void 0)return g("StakeProtocolNotFound","the aftermath config is undefined",{methodName:"requestStake"});i=i||new Xt;let{staked_sui_vault:r,referral_vault:s,safe:u,validator_address:l}=o.config,_=await fe(t,e,n,i);return i.moveCall({target:`${o.published_at}::staked_sui_vault::request_stake_and_keep`,typeArguments:[],arguments:[i.object(r),i.object(u),i.object(Pt("0x5")),i.object(s),_,i.pure.address(Pt(l))]}),i}static requestStakeCoin(t,e){let n=X.config.aftermath;if(n===void 0)return g("StakeProtocolNotFound","the aftermath config is undefined");t=t||new Xt;let{staked_sui_vault:i,referral_vault:o,safe:r,validator_address:s}=n.config;return t.moveCall({target:`${n.published_at}::staked_sui_vault::request_stake`,typeArguments:[],arguments:[t.object(i),t.object(r),t.object(Pt("0x5")),t.object(o),e,t.pure.address(Pt(s))]})}};function Ce(a,t,e){if(a==="Haedal")return St.requestStakeCoin(t,e);if(a==="Volo")return jt.requestStakeCoin(t,e);if(a==="aftermath")return bt.requestStakeCoin(t,e)}async function Wt(a,t,e,n,i){return t==="aftermath"?await bt.getExchangeRateForStake(a,e,n,i):"0"}function Ae(a,t,e){let{haedal:n,volo:i,aftermath:o}=X.config,r=N(a).full_address,s=N(t).full_address;if($t(r)&&e||$t(s)&&!e){if(n){let u=N(n.config.coin_type).full_address;if(r===u||s===u)return"Haedal"}if(i){let u=N(i.config.coin_type).full_address;if(r===u||s===u)return"Volo"}if(o){let u=N(o.config.coin_type).full_address;if(r===u||s===u)return"aftermath"}}return"Mmt"}function Gt(a){return Date.parse(new Date().toString())+a}var Ot=class{constructor(t,e=0){this.overdue_time=e,this.value=t}isValid(){return this.value===null?!1:this.overdue_time===0?!0:!(Date.parse(new Date().toString())>this.overdue_time)}};var ut=class a{constructor(){this._cache={}}static getInstance(){return this.instance||(this.instance=new a),this.instance}updateCache(t,e,n=864e5){let i=this._cache[t];i?(i.overdue_time=Gt(n),i.value=e):i=new Ot(e,Gt(n)),this._cache[t]=i}getCache(t,e=!1){let n=this._cache[t],i=n?.isValid();if(!e&&i)return n.value;i||delete this._cache[t]}};var Kt={VAULT:"mirror_vault_",TOKEN_SCHEMA:"mirror_token_schema_"};function Ht(a,t="",e=0,n=-1){return function(i,o,r){let s=r.value;r.value=async function(...u){let l=ut.getInstance(),_=a+u[e];if(t!==""&&(_=a+u[e][t]),n===-1||!u[n]){let m=l.getCache(_);if(m)return m}let p=await s.apply(this,u);return p&&l.updateCache(_,p,15e3),p}}}var lt=class lt{constructor(t){this._config=t,this._cache=ut.getInstance(),this._default_sender_address="0xf55cc609b13e87470d3da78d39ad6f84458a8059eb06aa66f94103d775e8a663"}getConfig(){return this._config}static createSDK(t){let e,n;return t.client?(e=t.client,n=Yt.NEW({network:"mainnet",client:t.client}),new lt({suiClient:e,mmtClmmSDK:n})):(t.fullNodeUrl?(e=new Se({url:t.fullNodeUrl}),n=Yt.NEW({network:"mainnet",suiClientUrl:t.fullNodeUrl,customHeaders:t.headers})):(e=new Se({url:tn("mainnet")}),n=Yt.NEW({network:"mainnet"})),new lt({suiClient:e,mmtClmmSDK:n}))}async getOwnerVaultBalance(t,e){let n=await this.getVault(e);if(n===void 0)return g("ObjectNotFound",`vault not found, vault_id: ${e}`);let[i,o]=await Promise.all([this._config.suiClient.getBalance({owner:t,coinType:n.lp_token_type}),this._config.suiClient.getCoinMetadata({coinType:n.lp_token_type})]);if(i.totalBalance==="0")return null;let r=await this._config.mmtClmmSDK.Pool.getPool(n.clmm_pool_id),s=gt(t,n,i,o,r.currentSqrtPrice);return s||null}async getPositionAssets(t){let e=await this.getVault(t);if(e===void 0)return g("ObjectNotFound",`vault not found, vault_id: ${t}`);let n=e.pool,{tick_lower_index:i,tick_upper_index:o,type_x:r,type_y:s}=e.position,u=D.tickIndexToSqrtPriceX64(i),l=D.tickIndexToSqrtPriceX64(o),_=J(new B(e.liquidity),new B(n.currentSqrtPrice),u,l,!0),p,m,d,y,v,T;try{let[A,S,j]=await this.getTokenSchemas(e);if(p=parseFloat(A.price),m=parseFloat(S.price),p!==void 0&&m!==void 0){let I=parseInt(e.decimals_a),O=parseInt(e.decimals_b),F=parseFloat(_.coin_amount_a)/Math.pow(10,I),H=parseFloat(_.coin_amount_b)/Math.pow(10,O);if(d=F*p,y=H*m,v=d+y,v!==void 0&&e.total_supply!=="0"){let q=j?.decimals??9,U=parseFloat(e.total_supply)/Math.pow(10,q);T=v/U}}}catch(A){throw console.error(`Failed to fetch token prices for vault ${t}:`,A),A}return{amount_a:_.coin_amount_a.toString(),amount_b:_.coin_amount_b.toString(),decimal_a:parseInt(e.decimals_a),decimal_b:parseInt(e.decimals_b),coin_type_a:r,coin_type_b:s,price_a:p,price_b:m,value_usd_a:d,value_usd_b:y,total_value_usd:v,lp_usd_price:T}}async getTokenSchemas(t){let[e,n,i]=await Promise.all([this._config.mmtClmmSDK.Pool.getToken(t.coin_type_a),this._config.mmtClmmSDK.Pool.getToken(t.coin_type_b),this._config.suiClient.getCoinMetadata({coinType:t.lp_token_type})]);return[e,n,i]}async getRemainingCap(t){let e=await this.getVault(t);if(e===void 0)return g("ObjectNotFound",`vault not found, vault_id: ${t}`);let n=await this.getPositionAssets(t);if(!n)return null;let i=parseFloat(e.deposit_limit);if(i===0)return{deposit_limit_usd:Number.MAX_SAFE_INTEGER,current_position_value_usd:n.total_value_usd||0,remaining_cap_usd:Number.MAX_SAFE_INTEGER};let o=n.total_value_usd||0,r=i/Math.pow(10,9),s=Math.max(0,r-o);return{deposit_limit_usd:r,current_position_value_usd:o,remaining_cap_usd:s}}async getOwnerVaultsBalance(t){let e=await this.getVaultList(),n=[];for(let i=0;i<e.length;i++){let o=e[i],r=await this._config.suiClient.getBalance({owner:t,coinType:o.lp_token_type});if(r.totalBalance==="0")continue;let s=await this._config.suiClient.getCoinMetadata({coinType:o.lp_token_type}),u=await this._config.mmtClmmSDK.Pool.getPool(o.clmm_pool_id),l=gt(t,o,r,s,u.currentSqrtPrice);l&&n.push(l)}return n}async getOwnerVaultsBalanceObj(t){let e,n;try{let _=await fetch(`${$}/market/vaultIdList`);if(!_.ok)return g("FetchError",`Failed to fetch vault IDs: ${_.statusText}`);let p=await _.json();e=p.data.map(m=>m.vaultId),n=p.data.map(m=>m.coinMetadataId)}catch(_){return g("FetchError",`Failed to fetch vault IDs: ${_}`)}let i=await this.getVaultByIds(e),o={},r=await this._config.suiClient.getAllBalances({owner:t}),s=Object.fromEntries(r.map(_=>[_.coinType,_.totalBalance])),u=await this._config.suiClient.multiGetObjects({ids:n,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}}),l={};for(let _ of u){let p=_.data?.content,m=_.data?.type;if(p&&m){let d=m.match(/<([^>]+)>/);d&&(l[d[1]]=p.fields.decimals)}}for(let _=0;_<i.length;_++){let p=i[_],m=s[p.lp_token_type];if(m==="0")continue;let d=l[p.lp_token_type];if(!d)return g("FetchError",`Coin metadata not found for type: ${p.lp_token_type}`);let y=gt(t,p,{totalBalance:m},{decimals:d},p.pool.currentSqrtPrice);y&&(o[y.vault_id]=y)}return o}async getVaultHolders(t){try{let e=await fetch(`${$}/market/vault/holderList?vaultId=${t}`);if(!e.ok)return g("FetchError",`Failed to fetch vault holders: ${e.statusText}`);let n=await e.json();return!n.data||typeof n.data!="object"?g("FetchError","Invalid response format for vault holders"):n}catch(e){return g("FetchError",`Failed to fetch vault holders: ${e}`)}}async getVaultInfo(t){try{let e=new URLSearchParams({vaultId:t}),n=await fetch(`${$}/market/user/vaultInfo?${e}`);if(!n.ok)return g("FetchError",`Failed to fetch vault info: ${n.statusText}`);let i=await n.json();return!i.data||!Array.isArray(i.data)?g("FetchError","Invalid response format for vault info"):i.data[0]}catch(e){return g("FetchError",`Failed to fetch vault info: ${e}`)}}async getYtHoldDetail(t){try{let e=new URLSearchParams({address:t}),n=await fetch(`${$}/ytHold/detail?${e}`);if(!n.ok)return g("FetchError",`Failed to fetch YT hold detail: ${n.statusText}`);let i=await n.json();return!i.data||typeof i.data!="object"?g("FetchError","Invalid response format for YT hold detail"):i}catch(e){return g("FetchError",`Failed to fetch YT hold detail: ${e}`)}}async getOwnerVaultsBalanceByVaultId(t,e){let n=await this.getVault(e);if(n===void 0)return g("ObjectNotFound",`vault not found, vault_id: ${e}`);let i=await this._config.suiClient.getBalance({owner:t,coinType:n.lp_token_type});if(i.totalBalance==="0")return;let o=await this._config.mmtClmmSDK.Pool.getPool(n.clmm_pool_id),r=await this._config.suiClient.getCoinMetadata({coinType:n.lp_token_type});return gt(t,n,i,r,o.currentSqrtPrice)}async getAllVaultObj(t="all"){let e=await this.getVaultList(),n={};for(let i of e)n[i.id]=i;return n}async getVaultList(t="all"){let e;try{let n=await fetch(`${$}/market/vaultIdList`);if(!n.ok)return g("FetchError",`Failed to fetch vault IDs: ${n.statusText}`);e=(await n.json()).data.map(o=>o.vaultId)}catch(n){return g("FetchError",`Failed to fetch vault IDs: ${n}`)}return await this.getVaultByIds(e)}async getVaultByIds(t){let e=await he(this._config.suiClient,t,{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}),n=await this._config.mmtClmmSDK.Pool.getAllPools(),i=Object.fromEntries(n.map(r=>[r.poolId,r])),o=[];for(let r of e)try{let s=await ve(i,this._config.suiClient,r);s&&o.push(s)}catch(s){return g("BuildError",`Failed to build vault: ${JSON.stringify(r)}, ${s}`)}return o}async getVault(t,e=!1){try{let n=await this._config.suiClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}}),[i,o]=await Promise.all([we(this._config.mmtClmmSDK,this._config.suiClient,n),this.getVaultInfo(t)]);if(i)return{...i,vault_info:o};g("ObjectNotFound",`vault not found, vault info:${n}`)}catch(n){g("FetchError",String(n))}}async getVaultAndPool(t){let e=await this.getVault(t);return e===void 0?g("ObjectNotFound","vault not found"):{vault:e,pool:e.pool}}isVaultRebalancing(t){let n=t.pool.currentSqrtPrice,i=t.upper_trigger_price,o=t.lower_trigger_price,r=c(n).lte(c(o))||c(n).gte(c(i)),s=D.sqrtPriceX64ToTickIndex(new B(n)),u=t.position.tick_lower_index,l=t.position.tick_upper_index,_=s<=u||s>=l;return r||_}async calculateDepositAmount(t,e=!0,n=!1){return t.side==="both"?await this.calculateAmountFromBoth(t,!0):await this.calculateDepositAmountFromOneSide(t,e,n)}async calculateAmountFromBoth(t,e){let{vault_id:n,input_amount:i,is_amount_a:o,slippage:r}=t,{vault:s,pool:u}=await this.getVaultAndPool(n),l=s.position,_=l.tick_lower_index,p=l.tick_upper_index,m=Z(_,p,new B(i),o,e,r,new B(u.currentSqrtPrice)),d=At(s,m.liquidity_amount.toString());return{request_id:t.input_amount,side:"both",amount_a:m.coin_amount_a.toString(),amount_b:m.coin_amount_b.toString(),amount_limit_a:m.coin_amount_limit_a.toString(),amount_limit_b:m.coin_amount_limit_b.toString(),original_input_amount:t.input_amount,ft_amount:d,is_amount_a:o}}async calculateDepositAmountFromOneSide(t,e,n=!1,i=!0,o=5,r=.02){try{let{vault_id:s,input_amount:u,is_amount_a:l,slippage:_}=t,{vault:p,pool:m}=await this.getVaultAndPool(s),{position:d}=p,y=d.tick_lower_index,v=d.tick_upper_index,{ratio_a:T,ratio_b:A}=Lt(y,v,new B(m.currentSqrtPrice)),S=w(u).mul(l?T:A),j=w(u).sub(S),I=l;if(j.toFixed(0)==="0")return await this.calculateAmountFromBoth(t,!0);let O,F,H,q,U,_t,tt,E=Ae(p.coin_type_a,p.coin_type_b,l);if(E!=="Mmt")F=await this.calculateStakeDepositFixSui({input_sui_amount:w(t.input_amount),swap_sui_amount:j,lower_tick:y,upper_tick:v,cur_sqrt_price:m.currentSqrtPrice.toString(),remain_rate:.01,fix_coin_a:t.is_amount_a,rebalance_count:0,should_request_stake:e,left_sui_amount:I?new c(j.toFixed(0)):new c(0),right_sui_amount:I?new c(t.input_amount):new c(j.toFixed(0)),slippage:_,stake_protocol:E}),q=m.currentSqrtPrice.toString(),O=F.fix_amount_a,U=F.swap_in_amount,_t=F.swap_out_amount,tt=F.swap_out_amount_limit;else{let x=new je;x.moveCall({target:`${h}::vault::get_optimal_swap_amount_for_single_sided_liquidity`,arguments:[x.object(s),x.object(p.clmm_pool_id),x.pure.u64(u),x.pure.bool(t.is_amount_a),x.pure.u64(20)],typeArguments:[p.coin_type_a,p.coin_type_b,p.lp_token_type,p.config_type]});let xt=await this._config.suiClient.devInspectTransactionBlock({sender:this._default_sender_address,transactionBlock:await x.build({client:this._config.suiClient,onlyTransactionKind:!0})});if(!xt?.results?.[0]?.returnValues?.[0])return g("FetchError","Failed to get swap amount");let zt=c(nn.U64.parse(new Uint8Array(xt.results[0].returnValues[0][0])));tt=zt,O=t.is_amount_a,U=zt,q=m.currentSqrtPrice.toString()}let V=O===l?w(u).sub(U).toFixed(0):tt,R=Z(y,v,new B(V),O,!0,_,new B(q)),Dt=R.coin_amount_a.toString(),It=R.coin_amount_b.toString(),Ie=At(p,R.liquidity_amount.toString());return{request_id:t.input_amount,side:"oneSide",amount_a:Dt,amount_b:It,amount_limit_a:R.coin_amount_limit_a.toString(),amount_limit_b:R.coin_amount_limit_b.toString(),ft_amount:Ie,original_input_amount:t.input_amount,is_amount_a:O,swap_result:{swap_in_amount:U.toString(),swap_out_amount:It.toString(),a2b:l,sui_stake_protocol:E,is_exceed:!0,after_sqrt_price:q}}}catch(s){if(i&&(String(s)==="Error: route unavailable"||String(s)==="Error: router timeout"))return await this.calculateDepositAmountFromOneSide(t,e,!1);throw s}}async calculateStakeDepositFixSui(t){let e=t.input_sui_amount.mul(t.remain_rate),n=t.input_sui_amount.sub(t.swap_sui_amount),i;t.should_request_stake?i=await Wt(this,t.stake_protocol,this._default_sender_address,t.should_request_stake,Number(t.swap_sui_amount.toFixed(0))):i=t.exchange_rate?t.exchange_rate:await Wt(this,t.stake_protocol,this._default_sender_address,t.should_request_stake,Number(t.swap_sui_amount.toFixed(0)));let o=t.swap_sui_amount.div(i).toFixed(0,c.ROUND_DOWN),r=Z(t.lower_tick,t.upper_tick,new B(o.toString()),!t.fix_coin_a,!0,0,new B(t.cur_sqrt_price)),s=t.fix_coin_a?r.coin_amount_a.toString():r.coin_amount_b.toString(),u=w(n).sub(s);return u.greaterThanOrEqualTo(0)&&u.lessThanOrEqualTo(e)||t.rebalance_count>12||t.left_sui_amount.greaterThanOrEqualTo(t.right_sui_amount)?{swap_in_amount:t.swap_sui_amount.toFixed(0),swap_out_amount:o,swap_out_amount_limit:w(o).mul(1-t.slippage).toFixed(0),after_sqrt_price:t.cur_sqrt_price,fix_amount_a:!t.fix_coin_a,is_exceed:!0,request_id:"",stake_protocol:t.stake_protocol}:u.lessThan(0)?await this.calculateStakeDepositFixSui({...t,right_sui_amount:t.swap_sui_amount,swap_sui_amount:t.swap_sui_amount.add(t.left_sui_amount).div(2),exchange_rate:i,rebalance_count:t.rebalance_count+1}):u.greaterThan(e)?await this.calculateStakeDepositFixSui({...t,left_sui_amount:t.swap_sui_amount,swap_sui_amount:t.swap_sui_amount.add(t.right_sui_amount).div(2),exchange_rate:i,rebalance_count:t.rebalance_count+1}):null}async deposit(t,e,n){let{vault_id:i,slippage:o,coin_object_a:r,coin_object_b:s,return_coin:u,deposit_result:l}=t,{swap_result:_,amount_a:p,amount_b:m,is_amount_a:d,partner:y,side:v,original_input_amount:T}=l,{vault:A,pool:S}=await this.getVaultAndPool(i),j,I,O;if(v==="oneSide"&&_){O=(_.a2b?r:s)||n.add(en({balance:BigInt(T),type:_.a2b?S.tokenXType:S.tokenYType}));let _t=[_.swap_in_amount,w(T).sub(w(_.swap_in_amount)).toFixed(0,c.ROUND_DOWN)],[tt,E]=n.splitCoins(O,_t),{swap_out_coin:V}=await this.handleDepositSwap({coin_type_a:S.tokenXType,coin_type_b:S.tokenYType,slippage:o,clmm_pool_address:S.poolId,partner:y,swap_in_amount:_.swap_in_amount,swap_in_coin:tt,a2b:_.a2b,sui_stake_protocol:_.sui_stake_protocol,route_obj:_.route_obj},e,n);_.a2b?(j=E,I=V):(j=V,I=E)}let F=w(p).mul(w(1).add(o)).toFixed(0,c.ROUND_DOWN).toString(),H=w(m).mul(w(1).add(o)).toFixed(0,c.ROUND_DOWN).toString(),q=d?p:m;if(v==="oneSide"&&_?(F="18446744073709551615",H="18446744073709551615",_.a2b?(q=w(q).mul(w(1).sub(.001)).toFixed(0,c.ROUND_DOWN).toString(),j=j||st(BigInt(d?p:l.amount_limit_a),S.tokenXType,n)):(q=w(q).mul(w(1).sub(.001)).toFixed(0,c.ROUND_DOWN).toString(),I=I||st(BigInt(d?l.amount_limit_b:l.amount_b),S.tokenYType,n))):(j=r||st(BigInt(d?p:F),S.tokenXType,n),I=s||st(BigInt(d?H:m),S.tokenYType,n)),j===void 0||I===void 0)return g("InsufficientCoins","Insufficient coins for deposit");let U=await this.depositInternal({coin_type_a:S.tokenXType,coin_type_b:S.tokenYType,lp_token_type:A.lp_token_type,config_type:A.config_type,clmm_pool_id:S.poolId,primary_coin_a_inputs:j,primary_coin_b_inputs:I,vault_id:i,slippage:t.slippage,amount_a:d?q:F,amount_b:d?H:q,is_amount_a:d,return_coin:u},n);if(_&&O&&n.transferObjects([O],n.pure.address(e)),u)return U}async depositInternal(t,e){let{primary_coin_a_inputs:n,primary_coin_b_inputs:i}=t,o=e.moveCall({target:`${G}::oracle::get_price_receipt`,typeArguments:[t.coin_type_a],arguments:[e.object(M)]});_e.includes(t.coin_type_a)?e.moveCall({target:`${z}::price_source::set_mmt_oracle`,typeArguments:[t.coin_type_a,t.coin_type_b],arguments:[o,e.object(t.clmm_pool_id),e.object(M),e.object(vt),e.object(it),e.object(rt[t.coin_type_b].priceInfoObjectId),e.object(wt),e.object(Y),e.pure.bool(!0)]}):e.moveCall({target:`${z}::price_source::set_k_oracle_price`,typeArguments:[t.coin_type_a],arguments:[o,e.object(M),e.object(it),e.pure.bool(!0),e.object(vt),e.object(rt[t.coin_type_a].priceInfoObjectId),e.object(wt),e.object(Y)]}),e.moveCall({target:`${G}::oracle::update_price`,typeArguments:[t.coin_type_a],arguments:[o,e.object(M)]});let r=e.moveCall({target:`${G}::oracle::get_price_receipt`,typeArguments:[t.coin_type_b],arguments:[e.object(M)]});e.moveCall({target:`${z}::price_source::set_k_oracle_price`,typeArguments:[t.coin_type_b],arguments:[r,e.object(M),e.object(it),e.pure.bool(!0),e.object(vt),e.object(rt[t.coin_type_b].priceInfoObjectId),e.object(wt),e.object(Y)]}),e.moveCall({target:`${G}::oracle::update_price`,typeArguments:[t.coin_type_b],arguments:[r,e.object(M)]});let s=[e.object(t.vault_id),e.object(t.clmm_pool_id),n,i,e.pure.u64(0),e.pure.u64(0),e.object(M),e.object(Y),e.object(L),e.object(dt)],u=[t.coin_type_a,t.coin_type_b,t.lp_token_type,t.config_type];if(t.return_coin)return e.moveCall({target:`${h}::${Vt}::deposit_non_entry`,typeArguments:u,arguments:s});e.moveCall({target:`${h}::${Vt}::deposit_entry`,typeArguments:u,arguments:s})}async handleDepositSwap(t,e,n){let{partner:i,coin_type_a:o,coin_type_b:r,slippage:s,clmm_pool_address:u,swap_in_amount:l,a2b:_,sui_stake_protocol:p,route_obj:m,swap_in_coin:d}=t,y=d;if(p!=="Mmt")return{swap_out_coin:Ce(p,n,y)};let v=qt(_),A=this._config.mmtClmmSDK.Pool.swap(n,{objectId:u,tokenXType:o,tokenYType:r},BigInt(l),y,_,void 0,BigInt(v),!0);return n.transferObjects([y],n.pure.address(e)),{swap_out_coin:A}}async withdraw(t,e,n){let i="is_ft_input"in t,{vault:o,pool:r}=await this.getVaultAndPool(t.vault_id),s=t.return_coin??!1,l=this.isVaultRebalancing(o)?0:t.slippage,_,p,m,d;if(i)d=await this.calculateWithdrawAmount({...t,slippage:l,side:"oneSide"}),p=d.amount_limit_a,m=d.amount_limit_b,_=t.is_ft_input?t.input_amount:d.burn_ft_amount;else{let{vault_id:T,ft_amount:A}=t;_=A;let S=await this.getVault(T,!0);if(S===void 0)return g("ObjectNotFound","Vault not found");let j=await Ct({input_ft_amount:A,slippage:l,vault:S});p=j.amount_limit_a,m=j.amount_limit_b}let{receive_coin_a:y,receive_coin_b:v}=await this.withdrawInternal({coin_type_a:r.tokenXType,coin_type_b:r.tokenYType,lp_token_type:o.lp_token_type,config_type:o.config_type,clmm_pool:r.poolId,min_amount_a:p,min_amount_b:m,vault_id:t.vault_id,ft_amount:_,primary_coin_inputs:"primary_coin_inputs"in t?t.primary_coin_inputs:void 0},n);if(i&&d){let{a2b:T,swap_in_amount:A,route_obj:S}=d.swap_result;if(!S){let j=qt(T),I=n.moveCall({target:"0x2::coin::value",arguments:[T?y:v],typeArguments:[T?r.tokenXType:r.tokenYType]}),O=this._config.mmtClmmSDK.Pool.swap(n,{objectId:r.poolId,tokenXType:r.tokenXType,tokenYType:r.tokenYType},I,T?y:v,T,void 0,BigInt(j),!0);if(T?n.mergeCoins(v,[O]):n.mergeCoins(y,[O]),s)return{return_coin_a:y,return_coin_b:v};n.transferObjects([y,v],n.pure.address(e))}}else{if(s)return{return_coin_a:y,return_coin_b:v};n.transferObjects([y,v],n.pure.address(e))}return{}}async calculateWithdrawAmount(t){let e=await this.getVault(t.vault_id);if(e===void 0)return g("ObjectNotFound","Vault not found");let i=this.isVaultRebalancing(e)?0:t.slippage;if(t.side==="both"){if(t.is_ft_input)return{...await Ct({input_ft_amount:t.input_amount,slippage:i,vault:e}),request_id:t.input_amount,burn_ft_amount:t.input_amount,side:t.side};let r=await this.calculateAmountFromBoth({vault_id:t.vault_id,is_amount_a:t.is_amount_a,input_amount:t.input_amount,slippage:i,side:t.side},!1);return{...r,request_id:t.input_amount,burn_ft_amount:r.ft_amount,side:t.side}}if(!+t.max_ft_amount)return g("InvalidMaxFtAmount","max_ft_amount input is invalid");let o=at(e,t.max_ft_amount);return await this.calculateWithdrawAmountFromOneSide({fix_amount_a:t.is_amount_a,vault_id:t.vault_id,receive_amount:t.is_ft_input?"0":t.input_amount,slippage:i,max_liquidity:o,remove_liquidity:t.is_ft_input?at(e,t.input_amount):void 0},!0)}async calculateWithdrawAmountFromOneSide(t,e,n){try{let{vault_id:i,remove_liquidity:o,max_liquidity:r}=t,{vault:s,pool:u}=await this.getVaultAndPool(i),{position:l}=s,_=l.tick_lower_index,p=l.tick_upper_index,m=o===r,d=Lt(_,p,new B(u.currentSqrtPrice)),y=t.fix_amount_a?d.ratio_a:d.ratio_b,v=w(t.receive_amount).mul(y),T,A;if(o){let E=D.tickIndexToSqrtPriceX64(_),V=D.tickIndexToSqrtPriceX64(p),R=J(new B(o),new B(u.currentSqrtPrice),E,V,!1);A=o,T=t.fix_amount_a?R.coin_amount_b.toString():R.coin_amount_a.toString(),v=t.fix_amount_a?w(R.coin_amount_a.toString()):w(R.coin_amount_b.toString())}else{let E=Z(_,p,new B(v.toFixed(0)),t.fix_amount_a,!1,t.slippage,new B(u.currentSqrtPrice));A=E.liquidity_amount.toString(),T=t.fix_amount_a?E.coin_amount_b.toString():E.coin_amount_a.toString()}let S=!t.fix_amount_a,j=await this._config.mmtClmmSDK.Pool.preSwap(new je,[{tokenXType:u.tokenXType,tokenYType:u.tokenYType,poolId:u.poolId,isXtoY:S}],T),I=v.add(c(j.toString())),O=w(t.receive_amount),F=O.sub(I);if(!m&&(!t.remove_liquidity||t.remove_liquidity&&n)&&F.abs().greaterThan(O.mul(.01))){let E=I.lessThan(O),V,R;n?E?(V=w(A),R=n.right):(V=n.left,R=w(A)):(V=E?w(A):w(0),R=E?w(t.max_liquidity):w(A));let Dt=w(V).add(R).div(2).toFixed(0);if(!n||n&&n.count<15&&V.lessThan(R))return await this.calculateWithdrawAmountFromOneSide({...t,remove_liquidity:Dt},e,{left:V,right:R,count:n?n.count+1:0})}let H=T,q=j.toString(),U=At(s,A.toString()),_t=await Ct({input_ft_amount:U,slippage:t.slippage,vault:s});return{side:"oneSide",..._t,burn_ft_amount:U,request_id:t.receive_amount,swap_result:{swap_in_amount:H,swap_out_amount:q,a2b:S,is_exceed:!1,sui_stake_protocol:"Mmt"}}}catch(i){if(e&&(String(i)==="Error: route unavailable"||String(i)==="Error: router timeout"))return await this.calculateWithdrawAmountFromOneSide(t,!1);throw i}}async withdrawInternal(t,e){let{primary_coin_inputs:n}=t;if(n===void 0&&(n=st(BigInt(t.ft_amount),t.lp_token_type,e)),n===void 0)return g("InsufficientCoins","Insufficient coins for deposit");let i=[e.object(t.vault_id),e.object(t.clmm_pool),n,e.pure.u64(t.min_amount_a),e.pure.u64(t.min_amount_b),e.object(Y),e.object(L),e.object(dt)],o=[t.coin_type_a,t.coin_type_b,t.lp_token_type,t.config_type],[r,s]=e.moveCall({target:`${h}::${ue}::withdraw`,typeArguments:o,arguments:i});return{receive_coin_a:r,receive_coin_b:s}}async getVaultMarketHolders(t){let e=await fetch(`${$}/market/coinInfo`);if(!e.ok)return g("FetchError",`Failed to fetch coinInfo: ${e.statusText}`);let n=await e.json(),i;if(t&&(i=await this.getVault(t),!i))return g("ObjectNotFound","Vault not found");let o=n.data,r={};for(let s of o){if(!s.provider||s.provider!=="Nemo"||i&&s.coinType!==i.lp_token_type)continue;let u=new URLSearchParams({coinType:s.coinType,maturity:s.maturity}),l=await fetch(`${$}/market/market/lpHolderList?${u}`);if(!l.ok)return g("FetchError",`Failed to fetch vault market holders: ${e.statusText}`);let _=await l.json();for(let p of _.data.holderData)r[p.address]?r[p.address]=r[p.address].add(c(p.usdValue)):r[p.address]=c(p.usdValue)}return Object.entries(r).map(([s,u])=>({address:s,usdValue:u.toNumber().toFixed(16)}))}async getVaultStatus(){console.log(`${$}/market/vaultShowList`);let t=await fetch(`${$}/market/vaultShowListV2`);if(!t.ok)return g("FetchError",`Failed to fetch vault status: ${t.statusText}`);let n=(await t.json()).data,i=await this.getAllVaultObj(),o=[];for(let r of n){let s=i[r.vaultId];if(s===void 0)throw new Error(`Vault not found for vault: ${r.vaultId}`);let u=s.pool;if(!u)throw new Error(`Pool not found for vault: ${s.id}`);if(!s.config_type.includes("Uncorrelated"))throw new Error(`Invalid lp token type: ${s.id} ${s.lp_token_type}`);let l=u.currentSqrtPrice,_=s.upper_trigger_price,p=s.lower_trigger_price,m=c(l).lte(c(p))||c(l).gte(c(_)),d=D.sqrtPriceX64ToTickIndex(new B(l)),y=s.position.tick_lower_index,v=s.position.tick_upper_index,T=d<=y||d>=v,A=!1;(m||T)&&(A=!0),o.push({vaultId:r.vaultId,isRebalancing:A,vaultName:r.vaultName,disable:r.disable})}return o}};Rt([Ht(Kt.TOKEN_SCHEMA,"id")],lt.prototype,"getTokenSchemas",1),Rt([Ht(Kt.VAU