UNPKG

@nemoprotocol/vaults-sdk

Version:

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

1 lines 72 kB
var Rt=(i=>(i.Mmt="Mmt",i.Haedal="Haedal",i.Volo="Volo",i.Aftermath="aftermath",i))(Rt||{}),Ht=(e=>(e.Both="both",e.OneSide="oneSide",e))(Ht||{});import{getFullnodeUrl as ze,SuiClient as Ce}from"@mysten/sui/client";var Nt=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}},ft=class extends Nt{constructor(t,e,n){super(t,e||"UnknownError",n)}},Yt=(a,t,e)=>{throw new ft(t.message,a,e)},g=(a,t,e)=>{throw new ft(t,a,e)};import Vt from"bn.js";import f from"bn.js";import Et from"decimal.js";Et.config({precision:64,rounding:Et.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var c=Et;import P from"bn.js";var X=new P(0),lt=new P(1),bt=new P(2),cn=bt.pow(new P(128)),zt=bt.pow(new P(64)).sub(lt),ke=bt.pow(new P(128)).sub(lt),b=class a{static toX64BN(t){return t.mul(new P(2).pow(new P(64)))}static toX64Decimal(t){return t.mul(c.pow(2,64))}static toX64(t){return new P(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 P(2).pow(new P(64)))}static shiftRightRoundUp(t){let e=t.shrn(64);return t.mod(zt).gt(X)&&(e=e.add(lt)),e}static divRoundUp(t,e){return t.mod(e).eq(X)?t.div(e):t.div(e).add(new P(1))}static subUnderflowU128(t,e){return t.lt(e)?t.sub(e).add(ke):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(X)&&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(X))throw new Error("Divide by zero");let o=t.mul(e).add(n.sub(lt)).div(n);if(this.isOverflow(o,i))throw new Error("Multiplication div overflow");return o}static checkMulDivRound(t,e,n,i){n.eq(X)&&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 P(2).pow(new P(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(zt).gt(X)?o.shrn(64).add(lt):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(X)&&g("DivisionByZero","Divide by zero"),n?this.divRoundUp(t,e):t.div(e)}static isOverflow(t,e){return t.gte(bt.pow(new P(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(X)?t:this.u128Neg(t.subn(1))}static u128Neg(t){return t.uxor(new P("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 P(1)))}static negFrom(t){return t.eq(X)?t:this.u128Neg(t).add(new P(1)).or(new P(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 te="79226673515401279992447579055",ee="4295048016",xt=14,Zt="59543866431248",De="184467440737095516",Jt="15793534762490258745";function w(a){return c.isDecimal(a)?a:new c(a===void 0?0:a)}function Qt(a,t,e){let n=a.toTwos(e).shln(t);return n.imaskn(e+1),n.fromTwos(e)}function v(a,t,e){let n=a.toTwos(e).shrn(t);return n.imaskn(e-t+1),n.fromTwos(e-t)}function Ie(a){let t;return(a&1)!==0?t=new f("79232123823359799118286999567"):t=new f("79228162514264337593543950336"),(a&2)!==0&&(t=v(t.mul(new f("79236085330515764027303304731")),96,256)),(a&4)!==0&&(t=v(t.mul(new f("79244008939048815603706035061")),96,256)),(a&8)!==0&&(t=v(t.mul(new f("79259858533276714757314932305")),96,256)),(a&16)!==0&&(t=v(t.mul(new f("79291567232598584799939703904")),96,256)),(a&32)!==0&&(t=v(t.mul(new f("79355022692464371645785046466")),96,256)),(a&64)!==0&&(t=v(t.mul(new f("79482085999252804386437311141")),96,256)),(a&128)!==0&&(t=v(t.mul(new f("79736823300114093921829183326")),96,256)),(a&256)!==0&&(t=v(t.mul(new f("80248749790819932309965073892")),96,256)),(a&512)!==0&&(t=v(t.mul(new f("81282483887344747381513967011")),96,256)),(a&1024)!==0&&(t=v(t.mul(new f("83390072131320151908154831281")),96,256)),(a&2048)!==0&&(t=v(t.mul(new f("87770609709833776024991924138")),96,256)),(a&4096)!==0&&(t=v(t.mul(new f("97234110755111693312479820773")),96,256)),(a&8192)!==0&&(t=v(t.mul(new f("119332217159966728226237229890")),96,256)),(a&16384)!==0&&(t=v(t.mul(new f("179736315981702064433883588727")),96,256)),(a&32768)!==0&&(t=v(t.mul(new f("407748233172238350107850275304")),96,256)),(a&65536)!==0&&(t=v(t.mul(new f("2098478828474011932436660412517")),96,256)),(a&131072)!==0&&(t=v(t.mul(new f("55581415166113811149459800483533")),96,256)),(a&262144)!==0&&(t=v(t.mul(new f("38992368544603139932233054999993551")),96,256)),v(t,32,256)}function Re(a){let t=Math.abs(a),e;return(t&1)!==0?e=new f("18445821805675392311"):e=new f("18446744073709551616"),(t&2)!==0&&(e=v(e.mul(new f("18444899583751176498")),64,256)),(t&4)!==0&&(e=v(e.mul(new f("18443055278223354162")),64,256)),(t&8)!==0&&(e=v(e.mul(new f("18439367220385604838")),64,256)),(t&16)!==0&&(e=v(e.mul(new f("18431993317065449817")),64,256)),(t&32)!==0&&(e=v(e.mul(new f("18417254355718160513")),64,256)),(t&64)!==0&&(e=v(e.mul(new f("18387811781193591352")),64,256)),(t&128)!==0&&(e=v(e.mul(new f("18329067761203520168")),64,256)),(t&256)!==0&&(e=v(e.mul(new f("18212142134806087854")),64,256)),(t&512)!==0&&(e=v(e.mul(new f("17980523815641551639")),64,256)),(t&1024)!==0&&(e=v(e.mul(new f("17526086738831147013")),64,256)),(t&2048)!==0&&(e=v(e.mul(new f("16651378430235024244")),64,256)),(t&4096)!==0&&(e=v(e.mul(new f("15030750278693429944")),64,256)),(t&8192)!==0&&(e=v(e.mul(new f("12247334978882834399")),64,256)),(t&16384)!==0&&(e=v(e.mul(new f("8131365268884726200")),64,256)),(t&32768)!==0&&(e=v(e.mul(new f("3584323654723342297")),64,256)),(t&65536)!==0&&(e=v(e.mul(new f("696457651847595233")),64,256)),(t&131072)!==0&&(e=v(e.mul(new f("26294789957452057")),64,256)),(t&262144)!==0&&(e=v(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(Ie(t)):new f(Re(t))}static sqrtPriceX64ToTickIndex(t){if(t.gt(new f(te))||t.lt(new f(ee)))throw new Error("Provided sqrtPrice is not within the supported sqrtPrice range.");let e=t.bitLength()-1,n=new f(e-64),i=Qt(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<xt;){u=u.mul(u);let C=u.shrn(127);u=u.shrn(63+C.toNumber()),s=s.add(o.mul(C)),o=o.shrn(1),r+=1}let l=s.shrn(32),p=i.add(l).mul(new f(Zt)),m=v(p.sub(new f(De)),64,128).toNumber(),d=v(p.add(new f(Jt)),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=Qt(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<xt;){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(Zt)),d=v(m.add(new f(Jt)),64,128).toNumber(),y=d%e,C=y===0?d:d+(e-y);return Ne(C)}};function Ft(a){return a?ee:te}function Ne(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 Ee}from"@mysten/sui/utils";var H="0x0000000000000000000000000000000000000000000000000000000000000006",it="0x2::sui::SUI",ne="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",W=process.env.MMT_ORACLE_PACKAGE_ID||"0x45fe3ef1ed2d9b444b8041a84e426242ad129483bf56000cdd514b8065967f4d",Bt=process.env.ORACLE_ADMIN_CAP_ID||"0xf5ca46bf4d4c087766118f143dea81d0ef3af9c2704635ece9d3af18f22aacb8",ie=process.env.REGISTRY_ADMIN_CAP_ID||"0x77659bd055091b9d3d193263af964fbd0c47d75601a247f6e4777f70cf82450f",oe=process.env.COIN_DECIMALS_REGISTRY||"0x04a645616e229f986b0b4c15def3ef46c4d84ad51d1d6419d567498de0dba564",ht=process.env.SET_PRICE_CAP_REGISTRY||"0xd088d1eaf09dfda03c989acf3063fd0e3e14432a2d21bf9fd2be30bf76373bfd",M=process.env.MMT_ORACLE_ID||"0x6cc485157712b67d3bbc71110947084aad0d23d7661add04e13038cfa765e80a",h=process.env.VAULT_PACKAGE_ID||"0x78a3ecb19e5000a9c246396b295a7e2971ba973524ec991ce4268b759448b033",L=process.env.VAULT_VERSION_ID||"0xef1aff44bb19bb1d0908b1fee334b680df8f1175e31e49a821ac7942913efd09",_t=process.env.MMT_CLMM_VERSION_ID||"0x2375a0b1ec12010aaea3b2545acfa2ad34cfbba03ce4b59f4c39e1e25eed1b2a",qt="deposit",re="withdraw",x=process.env.PRICE_ADAPTER_PACKAGE_ID||"0x1bf70849bc2b14361b30c1b10809d9b592224de25114798dca4a5891e011426a",ot=process.env.REGISTRY_ID||"0x6f8c395de3f250e08c01a25500c185d74cb182002d76750189c7e20a514befa8",ae=process.env.PRICE_ADAPTER_ADMIN_CAP||"0x9eec84b9c46c4087fe2f2261084092dd9835a9c81dfe6ff711beb306385d3a59",O=process.env.VAULT_ADMIN_CAP||"0xb3320d9cd09d23f0c7be41fcbe88ef6da9613ae097bd53d510b3ad91bad62378",mn=process.env.VAULT_ACL||"0x77d3b63065b24fff2c934853b9670c848680712977a66c4494e630d76ff097d5",gn=process.env.ROUTER_ACL||"0x253fb8c10c2f7be045f28b67cf72cbb58f6a21cc0cf38dd9d213d02468d9e829",rt=process.env.MMT_ROUTER_PACKAGE_ID||"0x5f9b325644ed096907becd7349a901623dbf604f7217fd8d521a06072aa32602",yt=process.env.PYTH_STATE_ID||"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",Y=process.env.NEMO_API_URL||"https://api.nemoprotocol.com/api/v1",fn=process.env.MMT_CLMM_PACKAGE_ID||"0xcf60a40f45d46fc1e828871a647c1e25a0915dec860d2662eb10fdb382c3c1d1",at={"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"}},se=["0x2b6602099970374cf58a2a1b9d96f005fccceb81e92eb059873baf420eb6c717::x_sui::X_SUI","0x876a4b7bce8aeaef60464c11f4026903e9afacab79b9b142686158aa86560b50::xbtc::XBTC","0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC"],$={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 le,Transaction as Fe}from"@mysten/sui/transactions";import G from"bn.js";import{TickMath as pt}from"@mmt-finance/clmm-sdk";import wt from"decimal.js";async function vt(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=pt.tickIndexToSqrtPriceX64(r),l=pt.tickIndexToSqrtPriceX64(s),_=new G(t),p=st(n,_.toString()),m=new G(i.currentSqrtPrice),d=J(new G(p),m,u,l,!1),y=w(d.coin_amount_a.toString()).mul(w(1-e)),C=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:C.toFixed(0)}}function Z(a,t,e,n,i,o,r){let s=pt.sqrtPriceX64ToTickIndex(r),u=pt.tickIndexToSqrtPriceX64(a),l=pt.tickIndexToSqrtPriceX64(t),_;if(s<a){if(!n)throw new Error("lower tick cannot calculate liquidity by coinB");_=ce(u,l,e)}else if(s>t){if(n)throw new Error("upper tick cannot calculate liquidity by coinA");_=ue(l,u,e)}else n?_=ce(r,l,e):_=ue(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?wt.ceil(m).toString():wt.floor(m).toString(),coin_amount_limit_b:i?wt.ceil(d).toString():wt.floor(d).toString(),liquidity_amount:_.toString(),is_amount_a:n}}function ce(a,t,e){let n=G.min(a,t),i=G.max(a,t),o=b.fromX64BN(e.mul(i).mul(n)),r=i.sub(n);return!o.isZero()&&!r.isZero()?o.div(r):new G(0)}function ue(a,t,e){let n=G.min(a,t),o=G.max(a,t).sub(n);return o.isZero()?new G(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 st(a,t){return a.total_supply==="0"?"0":w(t).mul(a.liquidity).div(a.total_supply).toFixed(0,Q.ROUND_DOWN).toString()}function I(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={...I(t),type_arguments:n.map(l=>I(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>I(l).full_address===it?l:I(l).source_address),u.source_address=_e(u.full_address,u.type_arguments),u}let i=t.split("::"),r={full_address:t,address:t===it||t===ne?"0x2":Ee(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=_e(r.full_address,r.type_arguments),r}catch{return{full_address:a,address:"",module:"",name:"",type_arguments:[],source_address:a}}}function _e(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 ct(a,t,e){return a===BigInt(0)&&I(t).full_address===it?e.add(le({balance:a,useGasCoin:!1})):e.add(le({balance:a,type:t}))}function Mt(a,t=32){return Number(BigInt.asIntN(t,BigInt(a)))}function Ut(a,t,e){let n=new Vt(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 Lt(a){return I(a).full_address===it}async function pe(a,t,e,n){let i=await Be(a,e,it);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 Fe;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 Be(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:I(r.coinType).source_address,coin_object_id:r.coinObjectId,balance:BigInt(r.balance)})}),i=o.nextCursor,!o.hasNextPage)break}return n}function dt(a,t,e,n,i){let o=st(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 Vt(o),new Vt(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 xe,Transaction as Te}from"@mysten/sui/transactions";function ut(a){let t=de(a)?.fields;if(t)return"fields"in t?t.fields:t}function de(a){let t="data"in a?qe(a):a;if(!(!t||!Ve(t)||t.content.dataType!=="moveObject"))return t.content}function qe(a){return a.data}function Ve(a){return a.content!==void 0}function mt(a){let t=Me(a)?a.data:a;return!t?.type&&"data"in a?t?.content?.dataType==="package"?"package":Ue(a):t?.type}function Me(a){return a.data!==void 0}function Ue(a){return de(a)?.type}async function me(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 Gt}from"@mmt-finance/clmm-sdk";import{bcs as Ze}from"@mysten/sui/bcs";import Le from"bn.js";async function ge(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 C of u.data){let T=C.name.value,A=new TextDecoder().decode(new Uint8Array(T));A==="deposit_enabled"?l.deposit_enabled=C.objectId:A==="position"&&(l.position=C.objectId)}let _=await t.multiGetObjects({ids:Object.values(l),options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}});for(let C of _){let T=C.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=$e(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=I(e),m=D.sqrtPriceX64ToPrice(new Le(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 fe(a,t,e){let n=ut(e),i=mt(e);if(n){let o=n.clmm_pool_id,r=await a.Pool.getPool(o);return await ge(n,t,i,r)}return g("BuildError","buildVault error")}async function be(a,t,e){let n=ut(e),i=mt(e);if(n){let o=n.clmm_pool_id,r=a[o];return await ge(n,t,i,r)}return g("BuildError","buildVault error")}function $e(a,t,e){let n=a.value.fields,i=Mt(BigInt(n.tick_lower_index.fields.bits)),o=Mt(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 Ct(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 he}from"@mysten/sui/utils";var Tt=class{static requestStakeCoin(t,e){let n=$.config.haedal;return t.moveCall({target:`${n.published_at}::staking::request_stake_coin`,typeArguments:[],arguments:[t.object(he("0x5")),t.object(n.config.staking_id),e,t.pure.address(he("0x0"))]})}};import{Transaction as Xe}from"@mysten/sui/transactions";import{normalizeSuiObjectId as We}from"@mysten/sui/utils";var At=class{static requestStakeCoin(t,e){let n=$.config.volo;if(n===void 0)return g("StakeProtocolNotFound","the volo config is undefined");t=t||new Xe;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(We("0x5")),e]})}};import{Transaction as $t}from"@mysten/sui/transactions";import{normalizeSuiAddress as Ge,normalizeSuiObjectId as St}from"@mysten/sui/utils";import{bcs as Ke}from"@mysten/sui/bcs";var gt=class{static async getExchangeRateForStake(t,e,n,i){let o=$.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 $t;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:Ge("0x0")});if(n){let m=l.events.find(C=>C.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(Ke.u128().parse(Uint8Array.from(_))).div(1e18).toString()}catch(u){return Yt("FetchError",u,{methodName:"getExchangeRateForStake"})}return"0"}static async requestStake(t,e,n,i){let o=$.config.aftermath;if(o===void 0)return g("StakeProtocolNotFound","the aftermath config is undefined",{methodName:"requestStake"});i=i||new $t;let{staked_sui_vault:r,referral_vault:s,safe:u,validator_address:l}=o.config,_=await pe(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(St("0x5")),i.object(s),_,i.pure.address(St(l))]}),i}static requestStakeCoin(t,e){let n=$.config.aftermath;if(n===void 0)return g("StakeProtocolNotFound","the aftermath config is undefined");t=t||new $t;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(St("0x5")),t.object(o),e,t.pure.address(St(s))]})}};function ye(a,t,e){if(a==="Haedal")return Tt.requestStakeCoin(t,e);if(a==="Volo")return At.requestStakeCoin(t,e);if(a==="aftermath")return gt.requestStakeCoin(t,e)}async function Xt(a,t,e,n,i){return t==="aftermath"?await gt.getExchangeRateForStake(a,e,n,i):"0"}function we(a,t,e){let{haedal:n,volo:i,aftermath:o}=$.config,r=I(a).full_address,s=I(t).full_address;if(Lt(r)&&e||Lt(s)&&!e){if(n){let u=I(n.config.coin_type).full_address;if(r===u||s===u)return"Haedal"}if(i){let u=I(i.config.coin_type).full_address;if(r===u||s===u)return"Volo"}if(o){let u=I(o.config.coin_type).full_address;if(r===u||s===u)return"aftermath"}}return"Mmt"}function Wt(a){return Date.parse(new Date().toString())+a}var jt=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 Ot=class{constructor(){this._cache={};this._cache={}}updateCache(t,e,n=864e5){let i=this._cache[t];i?(i.overdue_time=Wt(n),i.value=e):i=new jt(e,Wt(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 Ae=class a{constructor(t){this._config=t,this._cache=new Ot,this._default_sender_address="0xf55cc609b13e87470d3da78d39ad6f84458a8059eb06aa66f94103d775e8a663"}getConfig(){return this._config}static createSDK(t){let e,n;return t.client?(e=t.client,n=Gt.NEW({network:"mainnet",client:t.client}),new a({suiClient:e,mmtClmmSDK:n})):(t.fullNodeUrl?(e=new Ce({url:t.fullNodeUrl}),n=Gt.NEW({network:"mainnet",suiClientUrl:t.fullNodeUrl,customHeaders:t.headers})):(e=new Ce({url:ze("mainnet")}),n=Gt.NEW({network:"mainnet"})),new a({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=dt(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,C,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 E=parseInt(e.decimals_a),R=parseInt(e.decimals_b),q=parseFloat(_.coin_amount_a)/Math.pow(10,E),K=parseFloat(_.coin_amount_b)/Math.pow(10,R);if(d=q*p,y=K*m,C=d+y,C!==void 0&&e.total_supply!=="0"){let F=j?.decimals??9,U=parseFloat(e.total_supply)/Math.pow(10,F);T=C/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:C,lp_usd_price:T}}async getTokenSchemas(t){let e=this.readTokenFromCache(t.coin_type_a),n=this.readTokenFromCache(t.coin_type_b),i=this.readCoinMetadataFromCache(t.lp_token_type);if(e!==void 0&&n!==void 0&&i!==void 0)return[e,n,i];{let[o,r,s]=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 this.saveTokenToCache(o),this.saveTokenToCache(r),s&&this.saveCoinMetadataToCache(t.lp_token_type,s),[o,r,s]}}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=dt(t,o,r,s,u.currentSqrtPrice);l&&n.push(l)}return n}async getOwnerVaultsBalanceObj(t){let e,n;try{let _=await fetch(`${Y}/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}});console.log("coinMetadatas",JSON.stringify(u));let 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=dt(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(`${Y}/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(`${Y}/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(`${Y}/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 dt(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(`${Y}/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 me(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 be(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){let n=this.readVaultFromCache(t,e);if(n)return n;try{let i=await this._config.suiClient.getObject({id:t,options:{showType:!0,showContent:!0,showDisplay:!0,showOwner:!0}}),[o,r]=await Promise.all([fe(this._config.mmtClmmSDK,this._config.suiClient,i),this.getVaultInfo(t)]);if(o){let s={...o,vault_info:r};return this.saveVaultToCache(s),s}else return g("ObjectNotFound",`vault not found, vault info:${i}`)}catch(i){return g("FetchError",String(i))}}saveVaultToCache(t){let e=`${t.id}_mirror_vault`;this._cache.updateCache(e,t,3e5)}readVaultFromCache(t,e=!1){let n=`${t}_mirror_vault`;return this._cache.getCache(n,e)}saveTokenToCache(t){let e=`${t.coinType}_mirror_token`;this._cache.updateCache(e,t,15e3)}readTokenFromCache(t,e=!1){let n=`${t}_mirror_token`;return this._cache.getCache(n,e)}saveCoinMetadataToCache(t,e){let n=`${t}_mirror_coin_metadata`;this._cache.updateCache(n,e,15e3)}readCoinMetadataFromCache(t,e=!1){let n=`${t}_mirror_coin_metadata`;return this._cache.getCache(n,e)}async getVaultAndPool(t){let e=await this.getVault(t);return e===void 0?g("ObjectNotFound","vault not found"):{vault:e,pool:e.pool}}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=Ct(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,C=d.tick_upper_index,{ratio_a:T,ratio_b:A}=Ut(y,C,new B(m.currentSqrtPrice)),S=w(u).mul(l?T:A),j=w(u).sub(S),E=l;if(j.toFixed(0)==="0")return await this.calculateAmountFromBoth(t,!0);let R,q,K,F,U,tt,et,N=we(p.coin_type_a,p.coin_type_b,l);if(N!=="Mmt")q=await this.calculateStakeDepositFixSui({input_sui_amount:w(t.input_amount),swap_sui_amount:j,lower_tick:y,upper_tick:C,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:E?new c(j.toFixed(0)):new c(0),right_sui_amount:E?new c(t.input_amount):new c(j.toFixed(0)),slippage:_,stake_protocol:N}),F=m.currentSqrtPrice.toString(),R=q.fix_amount_a,U=q.swap_in_amount,tt=q.swap_out_amount,et=q.swap_out_amount_limit;else{let z=new Te;z.moveCall({target:`${h}::vault::get_optimal_swap_amount_for_single_sided_liquidity`,arguments:[z.object(s),z.object(p.clmm_pool_id),z.pure.u64(u),z.pure.bool(t.is_amount_a),z.pure.u64(20)],typeArguments:[p.coin_type_a,p.coin_type_b,p.lp_token_type,p.config_type]});let Kt=await this._config.suiClient.devInspectTransactionBlock({sender:this._default_sender_address,transactionBlock:await z.build({client:this._config.suiClient,onlyTransactionKind:!0})});if(!Kt?.results?.[0]?.returnValues?.[0])return g("FetchError","Failed to get swap amount");let It=c(Ze.U64.parse(new Uint8Array(Kt.results[0].returnValues[0][0])));console.log("get_optimal_swap_amount_for_single_sided_liquidity out_amount:",u,t.is_amount_a,It.toString()),et=It,R=t.is_amount_a,U=It,F=m.currentSqrtPrice.toString()}let V=R===l?w(u).sub(U).toFixed(0):et,k=Z(y,C,new B(V),R,!0,_,new B(F)),kt=k.coin_amount_a.toString(),Dt=k.coin_amount_b.toString(),Pe=Ct(p,k.liquidity_amount.toString());return{request_id:t.input_amount,side:"oneSide",amount_a:kt,amount_b:Dt,amount_limit_a:k.coin_amount_limit_a.toString(),amount_limit_b:k.coin_amount_limit_b.toString(),ft_amount:Pe,original_input_amount:t.input_amount,is_amount_a:R,swap_result:{swap_in_amount:U.toString(),swap_out_amount:Dt.toString(),a2b:l,sui_stake_protocol:N,is_exceed:!0,after_sqrt_price:F}}}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 Xt(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 Xt(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:C,original_input_amount:T}=l,{vault:A,pool:S}=await this.getVaultAndPool(i),j,E,R;if(C==="oneSide"&&_){R=(_.a2b?r:s)||n.add(xe({balance:BigInt(T),type:_.a2b?S.tokenXType:S.tokenYType}));let tt=[_.swap_in_amount,w(T).sub(w(_.swap_in_amount)).toFixed(0,c.ROUND_DOWN)],[et,N]=n.splitCoins(R,tt);console.log("spitCoins spitAmounts:",tt);let{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:et,a2b:_.a2b,sui_stake_protocol:_.sui_stake_protocol,route_obj:_.route_obj},e,n);_.a2b?(j=N,E=V):(j=V,E=N)}let q=w(p).mul(w(1).add(o)).toFixed(0,c.ROUND_DOWN).toString(),K=w(m).mul(w(1).add(o)).toFixed(0,c.ROUND_DOWN).toString(),F=d?p:m;if(C==="oneSide"&&_?(q="18446744073709551615",K="18446744073709551615",_.a2b?(F=w(F).mul(w(1).sub(.001)).toFixed(0,c.ROUND_DOWN).toString(),j=j||ct(BigInt(d?p:l.amount_limit_a),S.tokenXType,n)):(F=w(F).mul(w(1).sub(.001)).toFixed(0,c.ROUND_DOWN).toString(),E=E||ct(BigInt(d?l.amount_limit_b:l.amount_b),S.tokenYType,n))):(j=r||ct(BigInt(d?p:q),S.tokenXType,n),E=s||ct(BigInt(d?K:m),S.tokenYType,n)),j===void 0||E===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:E,vault_id:i,slippage:t.slippage,amount_a:d?F:q,amount_b:d?K:F,is_amount_a:d,return_coin:u},n);if(_&&R&&n.transferObjects([R],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:`${W}::oracle::get_price_receipt`,typeArguments:[t.coin_type_a],arguments:[e.object(M)]});se.includes(t.coin_type_a)?e.moveCall({target:`${x}::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(yt),e.object(ot),e.object(at[t.coin_type_b].priceInfoObjectId),e.object(ht),e.object(H),e.pure.bool(!0)]}):e.moveCall({target:`${x}::price_source::set_k_oracle_price`,typeArguments:[t.coin_type_a],arguments:[o,e.object(M),e.object(ot),e.pure.bool(!0),e.object(yt),e.object(at[t.coin_type_a].priceInfoObjectId),e.object(ht),e.object(H)]}),e.moveCall({target:`${W}::oracle::update_price`,typeArguments:[t.coin_type_a],arguments:[o,e.object(M)]});let r=e.moveCall({target:`${W}::oracle::get_price_receipt`,typeArguments:[t.coin_type_b],arguments:[e.object(M)]});e.moveCall({target:`${x}::price_source::set_k_oracle_price`,typeArguments:[t.coin_type_b],arguments:[r,e.object(M),e.object(ot),e.pure.bool(!0),e.object(yt),e.object(at[t.coin_type_b].priceInfoObjectId),e.object(ht),e.object(H)]}),e.moveCall({target:`${W}::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(H),e.object(L),e.object(_t)],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}::${qt}::deposit_non_entry`,typeArguments:u,arguments:s});e.moveCall({target:`${h}::${qt}::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:ye(p,n,y)};let C=Ft(_),A=this._config.mmtClmmSDK.Pool.swap(n,{objectId:u,tokenXType:o,tokenYType:r},BigInt(l),y,_,void 0,BigInt(C),!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,u,l,_,p;if(i)p=await this.calculateWithdrawAmount({...t,side:"oneSide"}),l=p.amount_limit_a,_=p.amount_limit_b,u=t.is_ft_input?t.input_amount:p.burn_ft_amount;else{let{vault_id:y,ft_amount:C,slippage:T}=t;u=C;let A=await this.getVault(y,!0);if(A===void 0)return g("ObjectNotFound","Vault not found");let S=await vt({input_ft_amount:C,slippage:T,vault:A});l=S.amount_limit_a,_=S.amount_limit_b}let{receive_coin_a:m,receive_coin_b:d}=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:l,min_amount_b:_,vault_id:t.vault_id,ft_amount:u,primary_coin_inputs:"primary_coin_inputs"in t?t.primary_coin_inputs:void 0},n);if(i&&p){let{a2b:y,swap_in_amount:C,route_obj:T}=p.swap_result;if(!T){let A=Ft(y),S=n.moveCall({target:"0x2::coin::value",arguments:[y?m:d],typeArguments:[y?r.tokenXType:r.tokenYType]}),j=this._config.mmtClmmSDK.Pool.swap(n,{objectId:r.poolId,tokenXType:r.tokenXType,tokenYType:r.tokenYType},S,y?m:d,y,void 0,BigInt(A),!0);if(y?n.mergeCoins(d,[j]):n.mergeCoins(m,[j]),s)return{return_coin_a:m,return_coin_b:d};n.transferObjects([m,d],n.pure.address(e))}}else{if(s)return{return_coin_a:m,return_coin_b:d};n.transferObjects([m,d],n.pure.address(e))}return{}}async calculateWithdrawAmount(t){if(t.side==="both"){if(t.is_ft_input){let o=await this.getVault(t.vault_id);return o===void 0?g("ObjectNotFound","Vault not found"):{...await vt({input_ft_amount:t.input_amount,slippage:t.slippage,vault:o}),request_id:t.input_amount,burn_ft_amount:t.input_amount,side:t.side}}let i=await this.calculateAmountFromBoth({vault_id:t.vault_id,is_amount_a:t.is_amount_a,input_amount:t.input_amount,slippage:t.slippage,side:t.side},!1);return{...i,request_id:t.input_amount,burn_ft_amount:i.ft_amount,side:t.side}}let{vault:e}=await this.getVaultAndPool(t.vault_id);if(!+t.max_ft_amount)return g("InvalidMaxFtAmount","max_ft_amount input is invalid");let n=st(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:t.slippage,max_liquidity:n,remove_liquidity:t.is_ft_input?st(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=Ut(_,p,new B(u.currentSqrtPrice)),y=t.fix_amount_a?d.ratio_a:d.ratio_b,C=w(t.receive_amount).mul(y),T,A;if(o){let N=D.tickIndexToSqrtPriceX64(_),V=D.tickIndexToSqrtPriceX64(p),k=J(new B(o),new B(u.currentSqrtPrice),N,V,!1);A=o,T=t.fix_amount_a?k.coin_amount_b.toString():k.coin_amount_a.toString(),C=t.fix_amount_a?w(k.coin_amount_a.toString()):w(k.coin_amount_b.toString())}else{let N=Z(_,p,new B(C.toFixed(0)),t.fix_amount_a,!1,t.slippage,new B(u.currentSqrtPrice));A=N.liquidity_amount.toString(),T=t.fix_amount_a?N.coin_amount_b.toString():N.coin_amount_a.toString()}let S=!t.fix_amount_a,j=await this._config.mmtClmmSDK.Pool.preSwap(new Te,[{tokenXType:u.tokenXType,tokenYType:u.tokenYType,poolId:u.poolId,isXtoY:S}],T),E=C.add(c(j.toString())),R=w(t.receive_amount),q=R.sub(E);if(!m&&(!t.remove_liquidity||t.remove_liquidity&&n)&&q.abs().greaterThan(R.mul(.01))){let N=E.lessThan(R),V,k;n?N?(V=w(A),k=n.right):(V=n.left,k=w(A)):(V=N?w(A):w(0),k=N?w(t.max_liquidity):w(A));let kt=w(V).add(k).div(2).toFixed(0);if(!n||n&&n.count<15&&V.lessThan(k))return await this.calculateWithdrawAmountFromOneSide({...t,remove_liquidity:kt},e,{left:V,right:k,count:n?n.count+1:0})}let K=T,F=j.toString(),U=Ct(s,A.toString()),tt=await vt({input_ft_amount:U,slippage:t.slippage,vault:s});return{side:"oneSide",...tt,burn_ft_amount:U,request_id:t.receive_amount,swap_result:{swap_in_amount:K,swap_out_amount:F,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=ct(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(H),e.object(L),e.object(_t)],o=[t.coin_type_a,t.coin_type_b,t.lp_token_type,t.config_type],[r,s]=e.moveCall({target:`${h}::${re}::withdraw`,typeArguments:o,arguments:i});return{receive_coin_a:r,receive_coin_b:s}}async getVaultMarketHolders(t){let e=await fetch(`${Y}/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(`${Y}/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)}))}};import{getFullnodeUrl as Je,SuiClient as Se}from"@mysten/sui/client";import{MmtSDK as je}from"@mmt-finance/clmm-sdk";import{Transaction as Pt}from"@mysten/sui/transactions";import Qe from"bn.js";var Oe=class a{static{this.FEE_FACTOR=1e6}constructor(t,e){this._config=t,this._senderAddress=e}setSenderAddress(t){this._senderAddress=t}getSenderAddress(){return this._senderAddress}getConfig(){return this._config}static createSDK(t){let e,n;return t.fullNodeUrl?(e=new Se({url:t.fullNodeUrl}),n=je.NEW({network:"mainnet",suiClientUrl:t.fullNodeUrl}