haedal-vault-sdk 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var Pe=Object.create;var Pt=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Se=(f,e)=>{for(var t in e)Pt(f,t,{get:e[t],enumerable:!0})},ie=(f,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ke(e))!Ae.call(f,i)&&i!==t&&Pt(f,i,{get:()=>e[i],enumerable:!(o=Ce(e,i))||o.enumerable});return f};var H=(f,e,t)=>(t=f!=null?Pe(Ve(f)):{},ie(e||!f||!f.__esModule?Pt(t,"default",{value:f,enumerable:!0}):t,f)),De=f=>ie(Pt({},"__esModule",{value:!0}),f);var qe={};Se(qe,{PythPriceModule:()=>nt,SdkEnv:()=>re,VaultsModule:()=>gt,VaultsModuleV2:()=>wt,VestModule:()=>ht,VolatileVaultsSDK:()=>Q,buildCLMMMarketId:()=>Nt,buildCLMMMarketPosition:()=>$t,buildDLMMMarketId:()=>Wt,buildDLMMMarketPosition:()=>Kt,buildDLMMPositionId:()=>xe,buildPoolData:()=>tt,buildPoolV2Data:()=>At,buildVaultMarket:()=>qt,buildVaultsBalance:()=>xt,buildVaultsBalanceV2:()=>St,calcExactSwapAmount:()=>ct,calcSingleSideSwap:()=>Ht,calculateAum:()=>Lt,calculateAumV2:()=>Ut,calculateDepositRatioFixTokenA:()=>ne,calculateTotalAumBasedOnQuote:()=>Z,checkIsMinOrMaxIndex:()=>Ct,convertU64BytesToDecimal:()=>Oe,default:()=>Re,defaultProvider:()=>Yt,dlmm_split_rate:()=>Ie,estCoinAmountsFromTotalAmount:()=>Mt,feed_map_mainnet:()=>Xt,feed_map_testnet:()=>Jt,getAmountBalanceByLpAmount:()=>ft,getCoinAmountsFromRatio:()=>z,getPositionPriceRange:()=>je,getPriceWithFormattedDecimals:()=>Tt,getPrimitivePricesFromBaseQuote:()=>ae,getQuotePerBaseAndBasePerQuote:()=>_t,getShareBufferAssets:()=>ot,getUpdatePriceType:()=>st,getVaultValidBalances:()=>pt,get_lp_amount_by_liquidity:()=>Be,get_lp_amount_by_tvl:()=>ut,get_share_liquidity_by_amount:()=>et,initMainnetSDK:()=>Gt,initTestnetSDK:()=>Zt,initVaultSDK:()=>Te,oraclePriceMultiplierDecimal:()=>Y,parseVaultVestNFT:()=>It,parseVaultsVestInfo:()=>Vt,printTransaction:()=>Fe,toSuiObjectId:()=>Et,vaults_mainnet:()=>zt,vaults_testnet:()=>Qt});module.exports=De(qe);var Ot=require("@mysten/sui/utils"),vt=require("@cetusprotocol/aggregator-sdk"),ge=require("@cetusprotocol/common-sdk"),oe=require("@cetusprotocol/sui-clmm-sdk");var dt=require("@mysten/sui/transactions"),W=H(require("bn.js"),1),le=require("@cetusprotocol/aggregator-sdk"),k=require("@cetusprotocol/common-sdk"),bt=require("@cetusprotocol/common-sdk"),de=require("@mysten/sui/utils"),_e=H(require("decimal.js"),1);var K=H(require("bn.js"),1),kt=H(require("decimal.js"),1),S=require("@cetusprotocol/common-sdk");var q=require("@cetusprotocol/common-sdk"),Bt=H(require("bn.js"),1),jt=H(require("decimal.js"),1),Ct=(f,e,t)=>{if(e==="min"){if(f===q.TickUtil.getMinIndex(t))return!0}else if(f===q.TickUtil.getMaxIndex(t))return!0;return!1};function Oe(f){if(f.length!==8)throw new Error("Invalid u64 byte array length");let e=f.map(t=>t.toString(16).padStart(2,"0")).reverse().join("");return BigInt(`0x${e}`).toString()}function ne(f,e,t,o,i){let a=new Bt.default(10).pow(new Bt.default(o)),{coin_amount_b:n}=q.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(f,e,a,!0,!0,0,t),s=q.TickMath.sqrtPriceX64ToPrice(t,o,i),r=(0,q.d)(a.toString()).mul(s).div(new jt.default(10).pow(o)).mul(new jt.default(10).pow(i)),c=r.add(n.toString()),l=r.div(c),_=(0,q.d)(n.toString()).div(c);return{ratioA:l,ratioB:_}}function z(f,e,t,o,i,a,n){let s=(0,q.d)((0,q.toDecimalsAmount)((0,q.d)(t).mul(f).div(o).toString(),a)).toFixed(0),r=(0,q.d)((0,q.toDecimalsAmount)((0,q.d)(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function Mt(f,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=ne(f,e,t,n,s);return z(r,c,o,i,a,n,s)}var Y=10n;function tt(f){let{fields:e,type:t}=f,{liquidity_range:o,pool_id:i,wrapped_position:a}=e.clmm_vault.fields,n=a.fields,s={clmm_pool_id:i,liquidity_range:{lower_offset:o.fields.lower_offset,rebalance_threshold:o.fields.rebalance_threshold,upper_offset:o.fields.upper_offset},wrapped_position:{coin_type_a:(0,S.fixCoinType)(n.coin_type_a.fields.name,!1),coin_type_b:(0,S.fixCoinType)(n.coin_type_b.fields.name,!1),description:n.description,id:n.id.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:(0,S.asIntN)(BigInt(n.tick_lower_index.fields.bits)),tick_upper_index:(0,S.asIntN)(BigInt(n.tick_upper_index.fields.bits)),url:n.url}},{balances:r}=e.buffer_assets.fields,c=r.fields.contents.map(_=>{let{key:d,value:p}=_.fields;return{coin_type:(0,S.fixCoinType)(d.fields.name,!1),value:p}});return{id:e.id.id,is_pause:e.is_pause,clmm_vault:s,lp_token_treasury:e.lp_token_treasury.fields.total_supply.fields.value,protocol_fees_handle:e.protocol_fees.fields.id.id,hard_cap:e.hard_cap,quote_type:(0,S.extractStructTagFromType)(e.quote_type.fields.name).full_address,lp_token_type:(0,S.extractStructTagFromType)(t).type_arguments[0],balances:c,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function Fe(f,e=!0){f.getData().commands.forEach((t,o)=>{})}function _t(f,e){let t=(0,S.d)(f).div(e).toString(),o=(0,S.d)(e).div(f).toString();return{quote_per_base:t,base_per_quote:o}}function ae(f,e,t,o){let i=10n**(Y+o-t),a=10n**(Y+t-o),n=S.MathUtil.checkMulDivFloor(new K.default(f.toString()),new K.default(i.toString()),new K.default(e.toString()),64),s=S.MathUtil.checkMulDivFloor(new K.default(e.toString()),new K.default(a.toString()),new K.default(f.toString()),64);return{primitive_base_price:BigInt(n.toString()),primitive_quote_price:BigInt(s.toString())}}function Z(f,e){let t=e?f[e].price:{coin_type:"",price:"1",coin_decimals:6,oracle_price:1000000000000000000000000n},o=new K.default("0");for(let[i,{price:a,value:n}]of Object.entries(f)){let{primitive_quote_price:s}=ae(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=S.MathUtil.checkMulDivFloor(new K.default(s.toString()),new K.default(n),new K.default((BigInt(10)**Y).toString()),64);o=o.add(r)}return o.toString()}async function Lt(f,e,t,o,i=!1){let{clmm_vault:a,quote_type:n}=e,{wrapped_position:s}=a,{tick_lower_index:r,tick_upper_index:c,liquidity:l}=s,{current_sqrt_price:_,coin_type_a:d,coin_type_b:p}=t,u=[...o],m=n&&(0,S.fixCoinType)(e.quote_type,!1),b=S.TickMath.tickIndexToSqrtPriceX64(r),w=S.TickMath.tickIndexToSqrtPriceX64(c),{coin_amount_a:h,coin_amount_b:y}=S.ClmmPoolUtil.getCoinAmountFromLiquidity(new K.default(l),new K.default(_),new K.default(b),new K.default(w),!1);u.push({coin_type:d,value:h.toString()}),u.push({coin_type:p,value:y.toString()});let v={};u.forEach(A=>{let B=(0,S.fixCoinType)(A.coin_type,!1),D=(0,S.d)(A.value),M=v[B]||0;v[B]=D.add(M).toString()});let P=Object.entries(v).filter(([A,B])=>(0,S.d)(B).gt(0)).map(([A])=>A);if(m&&!P.includes(m)&&P.push(m),P.length===0)return"0";let V=await f.PythPrice.getLatestPrice(P,i),O={};return P.forEach(A=>{let B=V[A];if(B)O[A]={price:B,value:v[A]||"0"};else throw Error(`find ${A} price fail `)}),Z(O,m).toString()}function ut(f,e,t){return(0,S.d)(f).eq(0)?e:(0,S.d)(f).mul(e).div(t).toFixed(0,kt.default.ROUND_HALF_UP)}function Be(f,e,t){return(0,S.d)(f).eq(0)?"0":(0,S.d)(f).mul(e).div(t).toFixed(0,kt.default.ROUND_HALF_UP)}function et(f,e,t){return(0,S.d)(f).eq(0)?"0":(0,S.d)(e).mul(t).div(f).toFixed(0,kt.default.ROUND_HALF_UP)}function ot(f,e,t){let o={};return e.forEach(i=>{let a=et(t,f,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function xt(f,e,t,o,i=!0){let{tick_lower_index:a,tick_upper_index:n,coin_type_a:s,coin_type_b:r,liquidity:c}=t.clmm_vault.wrapped_position,l=et(t.lp_token_treasury,e,c),_=S.TickMath.tickIndexToSqrtPriceX64(a),d=S.TickMath.tickIndexToSqrtPriceX64(n),p=S.ClmmPoolUtil.getCoinAmountFromLiquidity(new K.default(l),new K.default(o.current_sqrt_price),_,d,!0),u=p.coin_amount_a.toString(),m=p.coin_amount_b.toString(),b=ot(e,t.balances,t.lp_token_treasury),w=(0,S.d)(u).add(i&&b[s]?.value||"0").toFixed(0),h=(0,S.d)(m).add(i&&b[r]?.value||"0").toFixed(0),y=i?Object.values(b).filter(P=>P.coin_type!==s&&P.coin_type!==r):Object.values(b);return{vault_id:t.id,clmm_pool_id:o.id,owner:f,lp_token_type:t.lp_token_type,lp_token_balance:e,liquidity:l,tick_lower_index:a,tick_upper_index:n,amount_a:w,amount_b:h,coin_type_a:s,coin_type_b:r,share_buffer_assets:y}}function pt(f,e,t){let o=[];return e.forEach(i=>{(0,S.d)(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{(0,S.d)(i.value).gt(0)&&o.push(i)}),f.forEach(i=>{(0,S.d)(i.value).gt(0)&&o.push(i)}),o}function st(f,e,t){let o=new Set;return f.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function Tt(f,e){if(!Y)throw new Error("oraclePriceMultiplierDecimal is required");if(f===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(Y- -e);return f*t}return f/10n**(e+Y)}function Et(f){return`0x${Buffer.from(f).toString("hex")}`}function je(f,e,t,o,i){let a="0",n="0";return Ct(f,"min",Number(t))?a="0":a=S.TickMath.tickIndexToPrice(Number(f),o,i).toString(),Ct(e,"max",Number(t))?n="\u221E":n=S.TickMath.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function Vt(f){let e=(0,S.getObjectFields)(f),t=(0,S.getObjectType)(f),o=(0,S.extractStructTagFromType)(t),i=e.position.fields,a={id:i.id.id,pool_id:i.pool,index:i.index,liquidity:i.liquidity,tick_lower_index:(0,S.asIntN)(BigInt(i.tick_lower_index.fields.bits)),tick_upper_index:(0,S.asIntN)(BigInt(i.tick_upper_index.fields.bits)),coin_type_a:(0,S.fixCoinType)(i.coin_type_a.fields.name,!1),coin_type_b:(0,S.fixCoinType)(i.coin_type_b.fields.name,!1),name:i.name,description:i.description,url:i.url},n=e.global_vesting_periods.map(r=>({period:r.fields.period,release_time:r.fields.release_time,redeemed_amount:r.fields.redeemed_amount,cetus_amount:r.fields.cetus_amount}));return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_coin_type:e.lp_coin_type.fields.name,allocated_lp_amount:e.allocated_lp_amount,position:a,balance:e.balance,total_supply:e.total_supply,impaired_a:e.impaired_a,impaired_b:e.impaired_b,redeemed_amount:e.redeemed_amount,url:e.url,coin_type_a:(0,S.fixCoinType)(e.coin_a.fields.name,!1),coin_type_b:(0,S.fixCoinType)(e.coin_b.fields.name,!1),cetus_amount:e.cetus_amount,start_time:e.start_time,global_vesting_periods:n,vest_infos:{id:e.vester_infos.fields.id,size:e.vester_infos.fields.size}}}function It(f){let e=(0,S.getObjectFields)(f),t=(0,S.getObjectType)(f);return{id:e.id.id,vault_id:e.vault_id,index:e.index,lp_amount:e.lp_amount,url:e.url,redeemed_amount:e.redeemed_amount,impaired_a:e.impaired_a,impaired_b:e.impaired_b,period_infos:e.period_infos.map(i=>({period:i.fields.period,cetus_amount:i.fields.cetus_amount,is_redeemed:i.fields.is_redeemed})),name:e.name,vester_id:e.vester_id}}var C=require("@cetusprotocol/common-sdk"),Rt=require("@cetusprotocol/dlmm-sdk");var se=H(require("decimal.js"),1),rt=require("@mysten/sui/bcs"),mt=require("@mysten/sui/utils"),it=H(require("bn.js"),1);function qt(f){try{let{fields:e,type:t}=f,{certified_pools:o,positions:i,id:a,coin_type_a:n,coin_type_b:s,vault_id:r,position_keys:c}=e;return{type:t.includes("CLMMMarket")?"CLMM":"DLMM",id:a.id,certified_pools:o.fields.contents.map(d=>d.fields.key),positions_handle:{id:i.fields.id.id,size:i.fields.size},position_list:[],coin_type_a:(0,C.fixCoinType)(n.fields.name,!1),coin_type_b:(0,C.fixCoinType)(s.fields.name,!1),vault_id:r,position_keys:c.fields.contents}}catch{return}}function Me(f){return{uri:f.uri,index:f.index,id:f.id.id,name:f.name,pool_id:f.pool_id,lower_bin_id:(0,C.asIntN)(BigInt(f.lower_bin_id.fields.bits)),upper_bin_id:(0,C.asIntN)(BigInt(f.upper_bin_id.fields.bits)),liquidity_shares:f.liquidity_shares,description:f.description,coin_type_a:(0,C.fixCoinType)(f.coin_type_a,!1),coin_type_b:(0,C.fixCoinType)(f.coin_type_b,!1)}}function Le(f){return{id:f.id.id,pool_id:f.pool,index:f.index,description:f.description,uri:f.url,liquidity:f.liquidity,tick_lower_index:(0,C.asIntN)(BigInt(f.tick_lower_index.fields.bits)),tick_upper_index:(0,C.asIntN)(BigInt(f.tick_upper_index.fields.bits)),name:f.name,coin_type_a:(0,C.fixCoinType)(f.coin_type_a.fields.name,!1),coin_type_b:(0,C.fixCoinType)(f.coin_type_b.fields.name,!1)}}function Kt(f){let{fields:e}=f,{position:t,amounts:o,id:i}=e,a=o.fields.contents.map(d=>{let{key:p,value:u}=d.fields;return{coin_type:(0,C.fixCoinType)(p.fields.name,!1),value:u}}),n=Me(t.fields),s=n.lower_bin_id,r=n.liquidity_shares.map((d,p)=>({bin_id:s+p,liquidity:d})).filter(d=>(0,C.d)(d.liquidity).gt(0)),c=r.length>0?r[0].bin_id:s,l=r.length>0?r[r.length-1].bin_id:s+n.liquidity_shares.length-1;return{id:i.id,valid_lower_bin_id:c,valid_upper_bin_id:l,position:n,amounts:a}}function $t(f){let{fields:e}=f,{position:t,amounts:o,id:i}=e,a=o.fields.contents.map(r=>{let{key:c,value:l}=r.fields;return{coin_type:(0,C.fixCoinType)(c.fields.name,!1),value:l}}),n=Le(t.fields);return{id:i.id,position:n,amounts:a}}function At(f){let{fields:e,type:t}=f,{action_status:o,buffer_assets:i,coin_type_a:a,coin_type_b:n,hard_cap:s,id:r,last_aum:c,lp_token_treasury:l,markets:_,protocol_fee_rate:d,protocol_fees:p,quote_type:u}=e,m=(Number(o)&1)!==0,b=(Number(o)&2)!==0,{balances:w}=i.fields,h=w.fields.contents.map(P=>{let{key:V,value:O}=P.fields;return{coin_type:(0,C.fixCoinType)(V.fields.name,!1),value:O}}),y=u.fields.pos0.fields.name;return{id:r.id,lp_token_treasury:l.fields.total_supply.fields.value,hard_cap:s,quote_type:y?(0,C.fixCoinType)(y,!1):void 0,protocol_fee_rate:d,buffer_assets:h,protocol_fees_handle:{id:p.fields.id.id,size:p.fields.size},markets_handle:{id:_.fields.id.id,size:_.fields.size},markets:[],action_status:{is_deposit_allowed:m,is_withdraw_allowed:b},is_multiple_pool:!1,last_aum:c,coin_type_a:(0,C.fixCoinType)(a.fields.name,!1),coin_type_b:(0,C.fixCoinType)(n.fields.name,!1),lp_token_type:(0,C.extractStructTagFromType)(t).type_arguments[0],version:"v2"}}async function Ut(f,e,t,o=!1){let{pool:i,marketList:a}=await f.VaultsV2.getVaultAndPool(e),{quote_type:n,coin_type_a:s,coin_type_b:r}=i,c=[...t],l="0",_="0";for(let h of a)if(h.type==="DLMM"){let{position_list:y}=h;for(let v of y){let{lower_bin_id:P,liquidity_shares:V,pool_id:O}=v.position,F=h.certified_pool_obj[O],A=await f.CetusDlmmSDK.Pool.getBinInfo(F.bin_manager.bin_manager_handle,F.active_id,F.bin_step,!1),B=(0,Rt.parseLiquidityShares)(V,F.bin_step,P,A);l=(0,C.d)(l).add(B.amount_a.toString()).toFixed(0),_=(0,C.d)(_).add(B.amount_b.toString()).toFixed(0)}}else if(h.type==="CLMM"){let{position_list:y}=h;for(let v of y){let{tick_lower_index:P,tick_upper_index:V,liquidity:O,pool_id:F}=v.position,A=h.certified_pool_obj[F],B=C.TickMath.tickIndexToSqrtPriceX64(P),D=C.TickMath.tickIndexToSqrtPriceX64(V),{coin_amount_a:M,coin_amount_b:L}=C.ClmmPoolUtil.getCoinAmountFromLiquidity(new it.default(O),new it.default(A.current_sqrt_price),new it.default(B),new it.default(D),!1);l=(0,C.d)(l).add(M.toString()).toFixed(0),_=(0,C.d)(_).add(L.toString()).toFixed(0)}}let d=n&&(0,C.fixCoinType)(n,!1);c.push({coin_type:s,value:l}),c.push({coin_type:r,value:_});let p={};c.forEach(h=>{let y=(0,C.fixCoinType)(h.coin_type,!1),v=(0,C.d)(h.value),P=p[y]||0;p[y]=v.add(P).toString()});let u=Object.entries(p).filter(([h,y])=>(0,C.d)(y).gt(0)).map(([h])=>h);if(d&&!u.includes(d)&&u.push(d),u.length===0)return"0";let m=await f.VaultsV2.PythPrice.getLatestPrice(u,o),b={};return u.forEach(h=>{let y=m[h];if(y)b[h]={price:y,value:p[h]||"0"};else throw Error(`find ${h} price fail `)}),Z(b,d).toString()}async function St(f,e,t,o,i=!0){let a=await ft(f,e,t,i);return a.owner=o||"0x0",a}async function ft(f,e,t,o=!0){let{pool:i,marketList:a}=await f.VaultsV2.getVaultAndPool(t),{lp_token_type:n,lp_token_treasury:s,coin_type_a:r,coin_type_b:c}=i;if((0,C.d)(s).isZero())return{vault_id:t,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:"0",amount_b:"0",position_amount_a:"0",position_amount_b:"0",dlmm_balances:[],clmm_balances:[],share_buffer_assets:[]};let l=(0,C.d)(e).div(s),_=[],d=[],p=(0,C.d)(0),u=(0,C.d)(0);for(let P of a)if(P.type==="DLMM"){let{position_list:V}=P;for(let O of V){let{lower_bin_id:F,upper_bin_id:A,liquidity_shares:B,id:D,pool_id:M}=O.position,L=P.certified_pool_obj[M],{bin_manager:j,bin_step:x,active_id:R}=L,T=await f.CetusDlmmSDK.Pool.getBinInfo(j.bin_manager_handle,R,x,!1),E=(0,Rt.parseLiquidityShares)(B.map(Ft=>(0,C.d)(Ft.toString()).mul(l).toFixed(0,se.default.ROUND_HALF_UP).toString()),x,F,T),U=E.amount_a,G=E.amount_b,at=E.bins.filter(Ft=>(0,C.d)(Ft.liquidity).gt(0)),ye=at.length>0?at[0].bin_id:E.bins[0].bin_id,we=at.length>0?at[at.length-1].bin_id:E.bins[E.bins.length-1].bin_id,ve={position_id:D,certified_pool_id:L.id,liquidity_shares:B,valid_lower_bin_id:ye,valid_upper_bin_id:we,original_lower_bin_id:F,original_upper_bin_id:A,position_amount_a:U,position_amount_b:G,coin_type_a:r,coin_type_b:c,bin_infos:{bins:at,amount_a:E.amount_a,amount_b:E.amount_b}};_.push(ve),p=p.add((0,C.d)(U)),u=u.add((0,C.d)(G))}}else if(P.type==="CLMM"){let{position_list:V}=P;for(let O of V){let{tick_lower_index:F,tick_upper_index:A,liquidity:B,id:D,pool_id:M}=O.position,L=P.certified_pool_obj[M],j=(0,C.d)(B).mul(l).toFixed(0),x=C.TickMath.tickIndexToSqrtPriceX64(F),R=C.TickMath.tickIndexToSqrtPriceX64(A),T=C.ClmmPoolUtil.getCoinAmountFromLiquidity(new it.default(j),new it.default(L.current_sqrt_price),x,R,!1),E=T.coin_amount_a.toString(),U=T.coin_amount_b.toString(),G={position_id:D,certified_pool_id:L.id,liquidity:j,tick_lower_index:F,tick_upper_index:A,position_amount_a:E,position_amount_b:U};d.push(G),p=p.add((0,C.d)(E)),u=u.add((0,C.d)(U))}}let m=ot(e,i.buffer_assets,s),b=o&&m[r]?.value||"0",w=o&&m[c]?.value||"0",h=p.add(b).toFixed(0),y=u.add(w).toFixed(0),v=o?Object.values(m).filter(P=>P.coin_type!==r&&P.coin_type!==c):Object.values(m);return{vault_id:t,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:h,amount_b:y,position_amount_a:p.toFixed(0),position_amount_b:u.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:v}}function Wt(f){let e=rt.bcs.vector(rt.bcs.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return(0,mt.deriveObjectID)(f,"vector<u8>",e)}function Nt(f){let e=rt.bcs.vector(rt.bcs.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return(0,mt.deriveObjectID)(f,"vector<u8>",e)}function xe(f,e){let t=rt.bcs.Address.serialize(e).toBytes();return(0,mt.deriveDynamicFieldID)(f,"0x2::object::ID",t)}function ct(f,e,t,o){let i=(0,C.d)(f),a=(0,C.d)(t),n=(0,C.d)(o),s=i,r=e?i:(0,C.d)(0),c=e?(0,C.d)(0):i,l=n,_=(0,C.d)(n).mul(.999),d=(0,C.d)(0),p=s,u=null;function m(h){if(e){let y=r.minus(h),v=c.plus(h.mul(a));return{A:y,B:v,R:v.div(y)}}else{let y=r.plus(h.mul(a)),v=c.minus(h);return{A:y,B:v,R:y.div(v)}}}for(let h=0;h<120;h++){let y=d.plus(p).div(2),{A:v,B:P,R:V}=m(y);if(v.lte(0)||P.lte(0)){p=y;continue}if(V.gt(l))p=y;else if(V.lt(_))d=y;else{if(u=y,(0,C.d)(_).eq(0))break;p=y}}if(!u)return{swap_amount:"0",final_amount_a:r.toFixed(0),final_amount_b:c.toFixed(0)};let{A:b,B:w}=m(u);return{swap_amount:u.toFixed(0),final_amount_a:b.toFixed(0),final_amount_b:w.toFixed(0),best:u.toString()}}function Ht(f,e,t,o,i,a){if(a){let n=(0,C.d)(f).mul(t).sub((0,C.d)(e).mul(o)),s=(0,C.d)(t).add((0,C.d)(i).mul(o));return((0,C.d)(s).eq(0)?(0,C.d)(0):(0,C.d)(n).div(s)).toString()}else{let n=(0,C.d)(e).mul(o).sub((0,C.d)(f).mul(t)),s=(0,C.d)(i).mul(t).add(o);return((0,C.d)(s).eq(0)?(0,C.d)(0):(0,C.d)(n).div(s)).toString()}}var lt=require("@pythnetwork/pyth-sui-js"),te=require("@mysten/sui/bcs"),N=require("@cetusprotocol/common-sdk");var zt={env:"mainnet",fullRpcUrl:"https://fullnode.mainnet.sui.io",vaults:{package_id:"0xc4ebf35be1478318d78c324342854dd2735a036139373a9d41a1aa3a46a01d05",published_at:"0x720f861bda572e891eb422c117fb7224c0f91aaf69b655f6e40bcd68f0edad41",configs:{registry_id:"0x23014734280164270fa4c58f973c00079651e730d6f46491678ea8858f3bd13a",pools_handle:"0x31c810b6fcf3bb8699384e7c61fe9f7db53a04c4c22d514b3f79b6caa86183a8",pyth_oracle_id:"0xaed73fd854dfceedb2522903feec8c0e251764f5945bd38f969473024c4fb4d0",oracle_infos_handle:"0x6951ab4b36639e79ddbd9ba4478d7f72d1c5396b9198d0864c00e796c5815b01",prices_handle:"0x20a65a0f747f4f1ad465bdb61d784bbc5080ee5d200d5dd6594a354723b8c171",global_config_id:"0x5f8371674cd8e1e9eef5542ffe8adb339e3ff3a67894b14c954c7a92e992e0c1"},clmm_configs:{global_config_id:"0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",global_vault_id:"0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b"}},vaultsV2:{package_id:"0xfbc91f75397ce25b3b1b01cab2bf494d2e3f9b9e89c97545d88bd616cbbfcc37",published_at:"0x4893ee6665ad7b1a83810c16e0151b9500a7296bba85f2571ba9e79115ce1a83",configs:{registry_id:"0xb6e0d2a2457af53a83b1435ea398f9460ba8abd98686387a4399fceefdfc22e2",pools_handle:"0xc88e97a3a3bb71dfcf8cc90e6383d7e3e1dee0170fa07c9365d233568659fc8f",global_config_id:"0x05bedfb68e6bf273946f8e1f2529e8f30acdf8b287dec524973c6bae9e979743",versioned_id:"0x70bea2f242b057cda9994e9fecee121cb35ee914c360cc86f061268110b6d9ec",oracle_infos_handle:"0x4631c11bfeae9461863d233285d03e3dba14f8dfb574781f1e2cbe9b58ba903e",pyth_oracle_id:"0xc08cdf8479075b0dae05aadc76f941038a25d74dcbedd9c339f7ce5da08fab92"}},pythConfigs:{pyth_state_id:"0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8",hermes_service_urls:{primary:"https://hermes.pyth.network"},wormhole_state_id:"0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c",pyth_package_id:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91",pyth_published_at:"0x04e20ddf36af412a4096f9014f4a565af9e812db9a05cc40254846cf6ed0ad91"},aggregatorUrl:"https://api-sui.cetus.zone/router_v3",providers:[],vest:{package_id:"0xd0587f397e47d31a79d1c36710c2c28f48ff8f1e8ea73b6a54fa2ec6fdfe0a7d",published_at:"0x57731e8bd3971eca68019afecb0e11699ece6301f0d4f255969f5b4227e0c5f8",version:1,config:{versioned_id:"0xee1e2214314737df6193cc4cf6815cf8dc3b4cc1c5cc0a078c6579dda19e8552",create_event_list:[{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xb2d502d4ef89395934de020b195ded323bfa86d7f40b65ed5b15d6b66c722a3d::lpcoin::LPCOIN",pool_id:"0x2fc6ee9183d0f1ca0d2dded02c416be6f4671bb82db55c26ce12b536812a4b8e",position_id:"0x99f7fbeaf18c88e8af7553ad2ef055772477a1851550a2e7c2d7a503420c6b05",vault_id:"0xbd6252e0d56ae5eaabf055fd6c518ee5f66c1114287ca957cc698a17c3d25b16",vault_vester_id:"0xe4196586ed151a38c7c9169c72b9e5e3f51bfea9afbc2d1f082d6bedb88b086f"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x0484a9162669957e1c1883fc2da59e3cce9afdc1eec3c72c983898dbc9e92b91::lpcoin::LPCOIN",pool_id:"0xaa020ad81e1621d98d4fb82c4acb80dc064722f24ef828ab633bef50fc28268b",position_id:"0x90918d035e37b4447e11c2043c4c4374baeb7c2cbd2729063d939d016b04770f",vault_id:"0x99db9a7d3320d31fe6e4dc4122b948162010e331c41dc279636ca75567b93497",vault_vester_id:"0xd891e4c866a67e6339d1539edd1c28db629c81d9fb8499ee029cfa3803a0819e"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x242ddc526b9cb75513bee2fc629e01d5b7dc6da4c02d39cdab0160794635334f::lpcoin::LPCOIN",pool_id:"0x2e041f3fd93646dcc877f783c1f2b7fa62d30271bdef1f21ef002cebf857bded",position_id:"0xf82ebf822b0a7eff84f0079f3998611c4fec2ae714fe627225640eb305dc5a7c",vault_id:"0xbbd2d4850e4f238d39c3aa24957d2dfbb5787fa43d6c7de306bf15abe27f29f2",vault_vester_id:"0x7cc6404b903542ff6410b8e85c9647005713f8a23166ef08a488fe267c81c8bb"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xd418945e16ef3db737df093d0827f5ce387b36f089523e13c16e50dec6bd2524::lpcoin::LPCOIN",pool_id:"0xe01243f37f712ef87e556afb9b1d03d0fae13f96d324ec912daffc339dfdcbd2",position_id:"0x1ea05f946e995edcda18ba9fdaefd1021eddfb8d62e4fa09da89753ffb5b90ee",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0xd67cd239a34852cbc2e530db2ef296bc3e4a977464309c21ce706d90a17a5d5d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0xf21d82f767cac2e8892db252aa539c137dcf8a6d1e6ebd2d0a11c16362171df7::lpcoin::LPCOIN",pool_id:"0x72f5c6eef73d77de271886219a2543e7c29a33de19a6c69c5cf1899f729c3f17",position_id:"0x5bd93e30000eb9f3217a04c938c7f939ee33ac161f6fe7ea34bac268dbe36893",vault_id:"0x12ac7deea4b92b3e2c16687e2d2695fa8c045ec0a52844db7b2fc3876c9552aa",vault_vester_id:"0x5d87bb3db28e77604f9bd210cdde0916e95a9d37925ec3c466fa785bba3d63f9"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x2f46a040b9bc3a584a3be4d7bfbb02a5fb479da17a04c6d2860ed61d95e97f3f::lpcoin::LPCOIN",pool_id:"0xb8d7d9e66a60c239e7a60110efcf8de6c705580ed924d0dde141f4a0e2c90105",position_id:"0xa2141e99975e203172f62c97b1f314f845b94730f6dfdb8ab2d32d014c659bcf",vault_id:"0x41a4ab1e82f90f5965bbcd828b8ffa13bab7560bd2e352ab067e343db552f527",vault_vester_id:"0x0e4782ee96095af233a6c5219b50cd8c92bd79d84f1df7e629bcc7a094c5a09d"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x5c79c0ab2c45682aba43b1acbe5c478d947f7c8397d47447906d6cc127e180fb::lpcoin::LPCOIN",pool_id:"0xea648440bd640d3530e8a5f02c0b56da82c2efe851156c39974b901bbb0eeab1",position_id:"0x896a01cc57ba25799ec320dc25d1969f3129f2591689ce8c8dbf380c7e00bf48",vault_id:"0x5525f5a70fffd93f616c39b59f3abdd2054fc2d19f09c8a4d94950d611a43b74",vault_vester_id:"0xe116bb120d2d91f85ee419cbff73fdd9d7f87e9b085dd4de781347b51361ae17"},{clmm_vester_id:"0xe255c47472470c03bbefb1fc883459c2b978d3ad29aa8ee0c8c1ec9753fa7d01",lp_coin_type:"0x8275bc774497b319db110bb97a4812a19859ab6f19dc1574746097f06103c0f9::lpcoin::LPCOIN",pool_id:"0x9e59de50d9e5979fc03ac5bcacdb581c823dbd27d63a036131e17b391f2fac88",position_id:"0xd080bfb32b9c24f8875bd5a803a417b8ca0c02f2208d0b9058692f9013db3b52",vault_id:"0xedfb22d1bbe5045fd1888bb8bc1c4bc1823ab24d40f5a4bea9f6eb9758a4b820",vault_vester_id:"0x8bc7ccefae4db25873a0692bfb0d2c7cbdbbe644574a537789b98815960155a4"}]}}},Xt={"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC":{coin_type:"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",price_feed_id:"0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",coin_decimals:6},"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI":{coin_type:"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",price_feed_id:"0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744",coin_decimals:9},"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS":{coin_type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",price_feed_id:"0xe5b274b2611143df055d6e7cd8d93fe1961716bcd4dca1cad87a83bc1e78c1ef",coin_decimals:9},"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP":{coin_type:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",price_feed_id:"0x29bdd5248234e33bd93d3b81100b5fa32eaa5997843847e2c2cb16d7c6d9f7ff",coin_decimals:6},"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX":{coin_type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",price_feed_id:"0x88250f854c019ef4f88a5c073d52a18bb1c6ac437033f5932cd017d24917ab46",coin_decimals:9},"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN":{coin_type:"0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN",price_feed_id:"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43",coin_decimals:9},"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI":{coin_type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",price_feed_id:"0x6120ffcf96395c70aa77e72dcb900bf9d40dccab228efca59a17b90ce423d5e8",coin_decimals:9},"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH":{coin_type:"0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH",price_feed_id:"0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace",coin_decimals:8},"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL":{coin_type:"0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL",price_feed_id:"0xeba0732395fae9dec4bae12e52760b35fc1c5671e2da8b449c9af4efe5d54341",coin_decimals:9},"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC":{coin_type:"0x3e8e9423d80e1774a7ca128fccd8bf5f1f7753be658c5e645929037f7c819040::lbtc::LBTC",price_feed_id:"0x8f257aab6e7698bb92b15511915e593d6f8eae914452f781874754b03d0c612b",coin_decimals:8},"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL":{coin_type:"0x3a304c7feba2d819ea57c3542d68439ca2c386ba02159c740f7b406e592c62ea::haedal::HAEDAL",price_feed_id:"0xe67d98cc1fbd94f569d5ba6c3c3c759eb3ffc5d2b28e64538a53ae13efad8fd1",coin_decimals:9}};function Gt(f,e,t){return f&&(zt.fullRpcUrl=f),new Q(zt,e,t)}var Qt={env:"testnet",fullRpcUrl:"https://fullnode.testnet.sui.io",vaults:{package_id:"0x0a624f2dcafc9f7f381684b3d553a9837411925b6e8530b1f8f4e6ff3f1fde77",published_at:"0x36f9d8e6219e6ba4d8840165ec27676a1bcb43fc5712f87ca702ac7b5924507d",configs:{registry_id:"0xa2ebae3656c5fbdd2473caadfc077cd1780a881759a356f1a5bc0f9fd470adb9",pools_handle:"0x0df305d395f8e0359da0ac5717bc96e0e1da9792684ec8e8f6a20b7ab544f98e",pyth_oracle_id:"0x6c74aec8d4471d9b05f718c467204c9010c450b94a4e40b0b4031a7d6c386337",global_config_id:"0x8969b09cfdd72b1635263b569027ded4b91bbabd7d8cd91b21e355325e218b10",oracle_infos_handle:"0x8707c6665d202f277ffe8e7fd58684e232622a3e6826b94ba99f7569f253fa9d",prices_handle:"0x74230bb2c6a63235acbfe477ce16144afca7ccd16a458fa93f4605330b5d1c58"},clmm_configs:{global_config_id:"0x9774e359588ead122af1c7e7f64e14ade261cfeecdb5d0eb4a5b3b4c8ab8bd3e",global_vault_id:"0xf78d2ee3c312f298882cb680695e5e8c81b1d441a646caccc058006c2851ddea"}},pythConfigs:{pyth_state_id:"0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c",wormhole_state_id:"0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790",hermes_service_urls:{primary:"https://hermes-beta.pyth.network"},pyth_package_id:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837",pyth_published_at:"0xabf837e98c26087cba0883c0a7a28326b1fa3c5e1e2c5abdb486f9e8f594c837"},vaultsV2:{package_id:"0x0000000000000000000000000000000000000000000000000000000000000000",published_at:"0x0000000000000000000000000000000000000000000000000000000000000000",configs:{registry_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pools_handle:"0x0000000000000000000000000000000000000000000000000000000000000000",global_config_id:"0x0000000000000000000000000000000000000000000000000000000000000000",versioned_id:"0x0000000000000000000000000000000000000000000000000000000000000000",pyth_oracle_id:"0x0000000000000000000000000000000000000000000000000000000000000000",oracle_infos_handle:"0x0000000000000000000000000000000000000000000000000000000000000000"}},aggregatorUrl:"https://api-sui.devcetus.com/router_v2",providers:["CETUS","DEEPBOOK","KRIYA","KRIYAV3","FLOWX","FLOWXV3","AFTERMATH","TURBOS","HAEDAL","VOLO","AFSUI"],vest:{package_id:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",published_at:"0x76ccc11581265c821a666af3baee1c4162165aed504674621a39d474bb32513b",config:{versioned_id:"0x2c5b6227da87ce840035955e0d82725178ce53c8cd2b01934d6540feccf2a8f7",create_event_list:[{clmm_vester_id:"0x308b24963e5992f699e32db2f7088b812566a0cae580317fd3b8bf61de7f5508",lp_coin_type:"0xb0c18dcd849d4b47528831c64707f2f7f6aa1b7fd9ed5e1ac2f8ab356e031f25::lp_token::LP_TOKEN",pool_id:"0x403c7d9c1e959c029f61d970286eac8ad5bca2db2edba358585abf4dbd4ed3cd",position_id:"0xd1dbcdb1789b92772b367bc1f68d7d078b4fd3326b8bfb53750bf28585463508",vault_id:"0xed754b6a3a6c7549c3d734cb7b464bccf9c805814b9e47b0cb99f43b4efcb4a6",vault_vester_id:"0x6098c69613ed5d503ff2b81447e96408feab8f2e4bf582966a811b5b582d23e3"}]}}},Jt={};function Zt(f,e,t){return f&&(Qt.fullRpcUrl=f),new Q(Qt,e,t)}var re=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(re||{});function Te(f,e,t){let{env:o,fullNodeUrl:i}=f;return o==="mainnet"?Gt(i,e,t):Zt(i,e,t)}var Yt=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];function ce(f){try{let{request_time:e,error:t,request_params:o,request_url:i,action:a}=f;if(window?.gtag){let n=t.message==="Request Timeout";window.gtag("event","API_Error",{request_action:a,request_url:i,request_time:e,request_params:JSON.stringify(o),error_msg:String(t)})}}catch{}}var Ee=16*1024,nt=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;errorList=[];pythConfigs;global_config_id;pyth_oracle_id;oracle_infos_handle;vaults_published_at;versioned_id;isV2;constructor(e,t,o,i,a,n,s,r){this.vaults_published_at=o,this.pythConfigs=t,this.global_config_id=i,this.pyth_oracle_id=a,this.oracle_infos_handle=s,this.isV2=r,this.versioned_id=n;let{pyth_state_id:c,wormhole_state_id:l,hermes_service_urls:_}=t;this._sdk=e,this.hasChangeConnection=!1;let{primary:d}=_;if(d.length===0)throw new Error("primary url is empty");this.connection=new lt.SuiPriceServiceConnection(d),this.suiPythClient=new lt.SuiPythClient(this._sdk.FullClient,c,l)}get sdk(){return this._sdk}recordError(e,t,o){let{secondary:i,primary:a}=this.pythConfigs.hermes_service_urls,n={error:e,request_params:t,request_url:this.hasChangeConnection&&i?i:a,action:o,request_time:Date.now()};ce(n),this.errorList.push(n)}readErrorList(){let e=this.errorList;return this.errorList=[],e}async getFeedInfoList(e){let t=e.map(i=>this.getFeedInfo(i,!1));return await Promise.all(t)}priceCheck(e,t=60){let o=Math.floor(Date.now()/1e3);if(!(Math.abs(o-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let o={},i=[];if(t?e.forEach(s=>{let r=this._sdk.getCache(`getLatestPrice_${s}`);r&&this.priceCheck(r,60)?o[s]=r:i.push(s)}):i=[...e],i.length===0)return o;let a=await this.getFeedInfoList(i);return(await this.getLatestPriceFeeds(a.map(s=>s.price_feed_id)))?.parsed?.forEach((s,r)=>{if(s){let{price:c,expo:l,publish_time:_}=s.price,d=(0,N.d)(c).mul((0,N.d)(10).pow((0,N.d)(l))).toString(),p=a[r],u={coin_type:p.coin_type,price:d,coin_decimals:p.coin_decimals,oracle_price:0n,last_update_time:_};u.oracle_price=Tt(BigInt(c),BigInt(l)),o[i[r]]=u,this._sdk.updateCache(`getLatestPrice_${u.coin_type}`,u)}}),o}async getPriceFeedsUpdateData(e){try{return await this.connection.getPriceFeedsUpdateData(e)}catch(t){this.recordError(t,e,"getPriceFeedsUpdateData");let{secondary:o}=this.pythConfigs.hermes_service_urls;if(o){this.hasChangeConnection=!0,this.connection=new lt.SuiPriceServiceConnection(o);try{return await this.connection.getPriceFeedsUpdateData(e)}catch(i){this.recordError(i,e,"getPriceFeedsUpdateData")}}}}async getLatestPriceFeeds(e){try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(t){this.recordError(t,e,"getLatestPriceFeeds");let{secondary:o}=this.pythConfigs.hermes_service_urls;if(o){this.hasChangeConnection=!0,this.connection=new lt.SuiPriceServiceConnection(o);try{return await this.connection.getLatestPriceUpdates(e,{parsed:!0})}catch(i){this.recordError(i,e,"getLatestPriceFeeds")}}}}async buildUpdatePythPricePayload(e,t){let{pyth_state_id:o,pyth_published_at:i,pyth_package_id:a}=this.pythConfigs,n=(await this.getFeedInfoList(e)).map(d=>d.price_feed_id);if(e.length!==n.length)throw Error("find feed id fail");let s=await this.getPriceFeedsUpdateData(n);if(!s)throw new Error("get price update data fail");if(s.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let r=this.suiPythClient.extractVaaBytesFromAccumulatorMessage(s[0]),c=await this.suiPythClient.verifyVaas([r],t),[l]=t.moveCall({target:`${i}::pyth::create_authenticated_price_infos_using_accumulator`,typeArguments:[],arguments:[t.object(o),t.pure(te.bcs.vector(te.bcs.U8).serialize(Array.from(s[0]),{maxSize:Ee}).toBytes()),c[0],t.object(N.CLOCK_ADDRESS)]}),_=0;for(let d of n){let p=await this.suiPythClient.getPriceFeedObjectId(d);if(!p)throw new Error(`Price feed ${d} not found, please create it first`);this.isV2?[l]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[_]],arguments:[t.object(this.pyth_oracle_id),t.object(o),l,t.object(p),t.object(N.CLOCK_ADDRESS),t.object(this.versioned_id)]}):[l]=t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[e[_]],arguments:[t.object(this.pyth_oracle_id),t.object(this.global_config_id),t.object(o),l,t.object(p),t.object(N.CLOCK_ADDRESS)]}),_+=1}return t.moveCall({target:`${i}::hot_potato_vector::destroy`,arguments:[l],typeArguments:[`${a}::price_info::PriceInfo`]}),t}async buildUpdatePythPricePayloadV2(e,t){if(e.length===0)return t;let o=(await this.getFeedInfoList(e)).map(s=>s.price_feed_id);if(e.length!==o.length)throw Error("find feed id fail");let i=await this.getPriceFeedsUpdateData(o);if(!i)throw new Error("get price update data fail");if(i.length>1)throw new Error("SDK does not support sending multiple accumulator messages in a single transaction");let a=await this.suiPythClient.updatePriceFeeds(t,i,o),n=0;for(let s of a)t.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price_into_pyth_oracle`,typeArguments:[e[n]],arguments:[t.object(this.pyth_oracle_id),t.object(s),t.object(N.CLOCK_ADDRESS),t.object(this.versioned_id)]}),n+=1;return t}getFeedInfoByJson(e){let{env:t}=this._sdk.sdkOptions,o=(0,N.fixCoinType)(e,!1);return t==="mainnet"?Xt[o]:Jt[o]}async getFeedInfo(e,t){let o=`getFeedInfo_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=this.getFeedInfoByJson(e);if(a)return a;let n=await this._sdk.FullClient.getDynamicFieldObject({parentId:this.oracle_infos_handle,name:{type:"0x1::type_name::TypeName",value:(0,N.fixCoinType)(e,!0)}}),{fields:s}=n.data.content.fields.value,r={coin_type:e,price_feed_id:Et(s.price_feed_id),coin_decimals:s.coin_decimals};return this._sdk.updateCache(o,r),r}};var gt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new nt(e,o,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,"",t.configs.oracle_infos_handle,!1)}get sdk(){return this._sdk}get PythPrice(){return this.pythPrice}async getProtocolFeeRate(){let e="getProtocolFeeRate",t=this._sdk.getCache(e);if(t)return t;let{configs:o}=this._sdk.sdkOptions.vaults,a=(await this._sdk.FullClient.getObject({id:o.global_config_id,options:{showContent:!0}})).data.content.fields.protocol_fee_rate;return this._sdk.updateCache(e,a),a}async getOwnerVaultsBalance(e,t,o=!0){let{pool:i,clmmPool:a}=await this.getVaultAndPool(t,!0),s=(await this._sdk.FullClient.getBalance({owner:e,coinType:i.lp_token_type})).totalBalance;return xt(e,s,i,a,o)}async getOwnerVaultsBalanceList(e,t=!0){let{data:o}=await this.getPoolList(),i=[];for(let a=0;a<o.length;a++){let n=await this.getOwnerVaultsBalance(e,o[a].id,t);i.push(n)}return i}async getVaultsPositionRewarderAndFee(e){try{let{package_id:t}=this._sdk.sdkOptions.vaults,{pool:o,clmmPool:i}=await this.getVaultAndPool(e,!1),a=`getVaultsPositionRewarderAndFee_${e}`,n=this._sdk.getCache(a);if(n)return n;let{lp_token_type:s}=o,{rewarder_infos:r,id:c,coin_type_a:l,coin_type_b:_}=i,d=new dt.Transaction;this.buildCollectRewardPayload({reward_coin_types:[...r.map(h=>h.coin_type)],lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:_},d),this.buildCollectFeePayload({lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:_},d);let p=await this._sdk.FullClient.sendSimulationTransaction(d,(0,de.normalizeSuiAddress)("0x0")),u=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,b=[],w=[];return p?.events.forEach(h=>{let{parsedJson:y,type:v}=h;v===u&&(b.push({coin_type:(0,k.fixCoinType)(l,!1),value:y.amount_a}),b.push({coin_type:(0,k.fixCoinType)(_,!1),value:y.amount_b})),v===m&&w.push({coin_type:(0,k.fixCoinType)(y.reward_type.name,!1),value:y.amount})}),this._sdk.updateCache(a,{feeList:b,rewarderList:w},10*1e3),{feeList:b,rewarderList:w}}catch{}return{feeList:[],rewarderList:[]}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaults:o}=this._sdk.sdkOptions,{FullClient:i}=this._sdk,a=await i.getDynamicFieldsByPage(o.configs.pools_handle,e),n=a.data.map(s=>s.name.value);return n.length>0&&((await i.batchGetObjects(n,{showContent:!0})).forEach(r=>{let c=tt(r.data.content);this._sdk.updateCache(`getPool_${c.id}`,c),t.data.push(c)}),t.next_cursor=a.next_cursor,t.has_next_page=a.has_next_page),t}async getAssignPoolList(e){if(e.length===0)return[];let t=[],o=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0,showType:!0});for(let i of o){let a=tt(i.data.content);this._sdk.updateCache(`getPool_${a.id}`,a),t.push(a)}return t}async getPool(e,t=!0){let o=`getPool_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=await this._sdk.FullClient.getObject({id:e,options:{showContent:!0}}),n=tt(a.data.content);return this._sdk.updateCache(o,n),n}buildCollectRewardPayload(e,t){let{coin_type_a:o,coin_type_b:i,pool_id:a,clmm_pool_id:n,lp_token_type:s,reward_coin_types:r}=e,{published_at:c,configs:l,clmm_configs:_}=this._sdk.sdkOptions.vaults;return t=t||new dt.Transaction,r.forEach(d=>{t.moveCall({target:`${c}::pool::collect_reward`,typeArguments:[o,i,s,d],arguments:[t.object(a),t.object(l.global_config_id),t.object(_.global_config_id),t.object(n),t.object(_.global_vault_id),t.object(k.CLOCK_ADDRESS)]})}),t}buildCollectFeePayload(e,t){let{coin_type_a:o,coin_type_b:i,pool_id:a,clmm_pool_id:n,lp_token_type:s}=e,{published_at:r,configs:c,clmm_configs:l}=this._sdk.sdkOptions.vaults;return t=t||new dt.Transaction,t.moveCall({target:`${r}::pool::collect_fee`,typeArguments:[o,i,s],arguments:[t.object(a),t.object(c.global_config_id),t.object(l.global_config_id),t.object(n)]}),t}async buildDepositPayload(e,t){let{pool_id:o,amount_a:i,amount_b:a,return_lp_coin:n,re_balance:s}=e,{pool:r,clmmPool:c}=await this.getVaultAndPool(o,!0),{lp_token_type:l}=r,{rewarder_infos:_,id:d,coin_type_a:p,coin_type_b:u}=c,m=_.map(O=>(0,k.fixCoinType)(O.coin_type,!1)),b=st(m,c.coin_type_a,c.coin_type_b),{published_at:w,configs:h,clmm_configs:y}=this._sdk.sdkOptions.vaults;t=t||new dt.Transaction,t=this.buildCollectRewardPayload({reward_coin_types:m,lp_token_type:l,pool_id:o,clmm_pool_id:d,coin_type_a:p,coin_type_b:u},t),t=this.buildCollectFeePayload({lp_token_type:l,pool_id:o,clmm_pool_id:d,coin_type_a:p,coin_type_b:u},t),t=await this.pythPrice.buildUpdatePythPricePayload(b,t),t.moveCall({target:`${w}::pool::calculate_aum`,typeArguments:[p,u,l],arguments:[t.object(o),t.object(h.global_config_id),t.object(h.pyth_oracle_id),t.object(y.global_config_id),t.object(d),t.object(k.CLOCK_ADDRESS)]});let v,P;if(s&&s.swap_result){let{swap_result:O,coin_amount:F,mode:A,swap_slippage:B}=s,{swap_in_amount:D,swap_out_amount:M,route_obj:L}=O,j=bt.CoinAssist.buildCoinWithBalance(BigInt(F),A==="OnlyCoinA"?p:u,t),x=t.splitCoins(j,[D]),R={router:L,slippage:B,txb:t,inputCoin:x},T=await this._sdk.AggregatorClient.fixableRouterSwapV3(R);v=A==="OnlyCoinA"?j:T,P=A==="OnlyCoinA"?T:j}else v=bt.CoinAssist.buildCoinWithBalance(BigInt(i),p,t),P=bt.CoinAssist.buildCoinWithBalance(BigInt(a),u,t);let V=t.moveCall({target:`${w}::pool::${n?"deposit_for":"deposit"}`,typeArguments:[p,u,l],arguments:[t.object(o),t.object(h.global_config_id),t.object(h.pyth_oracle_id),t.object(y.global_config_id),t.object(d),v,P,t.object(k.CLOCK_ADDRESS)]});return n?V:void 0}async buildWithdrawPayload(e,t){let{pool_id:o,burn_lp_amount:i,mode:a,slippage:n,partner:s,extra_burn:r,return_coin:c}=e,{pool:l,clmmPool:_}=await this.getVaultAndPool(o,!0),{published_at:d,configs:p,clmm_configs:u}=this._sdk.sdkOptions.vaults;t=t||new dt.Transaction;let{lp_token_type:m,clmm_vault:b,lp_token_treasury:w}=l,{rewarder_infos:h,id:y,coin_type_a:v,coin_type_b:P,liquidity:V}=_,O=h.map(j=>(0,k.fixCoinType)(j.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:O,lp_token_type:m,pool_id:o,clmm_pool_id:y,coin_type_a:v,coin_type_b:P},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:y,coin_type_a:v,coin_type_b:P},t);let F,A=r?(0,k.d)(r.burn_lp_amount).add((0,k.d)(i)).toFixed(0):(0,k.d)(i).toFixed(0),B=(0,k.d)(i).isZero();if(B&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");B?F=r.lp_burn_coin:(F=bt.CoinAssist.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(F,[r.lp_burn_coin]));let[D,M,L]=t.moveCall({target:`${d}::pool::withdraw`,typeArguments:[v,P,m],arguments:[t.object(o),t.object(p.global_config_id),t.object(u.global_config_id),t.object(y),F,t.object(k.CLOCK_ADDRESS)]});if(this.buildWithdrawBufferReward({reward_coin_types:O.filter(j=>![(0,k.fixCoinType)(v,!1),(0,k.fixCoinType)(P,!1)].includes(j)),pool_id:o,withdraw_cert:L,lp_token_type:m},t),t.moveCall({target:`${d}::pool::destory_withdraw_cert`,typeArguments:[m],arguments:[t.object(o),t.object(p.global_config_id),L]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let j=a==="OnlyCoinA",x=j?M:D,R=et(w,A,V.toString()),T=await this.handleWithSwap(t,x,v,P,A,o,j,n,s,[{poolID:y,ticklower:b.wrapped_position.tick_lower_index,tickUpper:b.wrapped_position.tick_upper_index,deltaLiquidity:Number(R)}],c);if(c&&T)return j?t.mergeCoins(T,[D]):t.mergeCoins(T,[M]),{return_coin_a:j?T:void 0,return_coin_b:j?void 0:T};t.transferObjects([j?D:M],this._sdk.senderAddress)}else{if(c)return{return_coin_a:D,return_coin_b:M};t.transferObjects([D,M],this._sdk.senderAddress)}return{return_coin_a:void 0,return_coin_b:void 0}}async handleWithSwap(e,t,o,i,a,n,s,r,c,l,_){let{receive_amount_a:d,receive_amount_b:p}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),u=s?i:o,m=s?o:i,b=s?p:d;if((0,k.d)(b).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let w={from:u,target:m,amount:new W.default(b),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers,liquidityChanges:l},h=await this._sdk.AggregatorClient.findRouters(w);if(!h)throw Error("not find Router");if(h.error!==void 0)throw Error(`find Router error : ${h.error}`);let y={router:h,inputCoin:t,slippage:r,txb:e,partner:c},v=await this._sdk.AggregatorClient.fixableRouterSwapV3(y);if(_)return v;e.transferObjects([v],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:o,lp_token_type:i},a){let{published_at:n,configs:s}=this._sdk.sdkOptions.vaults;e.forEach(r=>{let c=a.moveCall({target:`${n}::pool::withdraw_buffer_reward`,typeArguments:[i,r],arguments:[a.object(t),a.object(s.global_config_id),o]});a.transferObjects([c],this._sdk.getVerifySenderAddress())})}async preCalculateDepositValue(e,t){let{amount_usd:o,pool_id:i,mode:a,uuid:n}=e,{pool:s,clmmPool:r}=await this.getVaultAndPool(i,!1),{current_sqrt_price:c}=r,{tick_lower_index:l,tick_upper_index:_,coin_type_a:d,coin_type_b:p}=s.clmm_vault.wrapped_position,u="0",m="0",b=await this.pythPrice.getLatestPrice([d,p],!0),w=b[d],h=b[p];if(!w||!h)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:y,amountB:v}=Mt(l,_,new W.default(c),o,w.price,h.price,w.coin_decimals,h.coin_decimals);u=y.toString(),m=v.toString();break}case"FlexibleBoth":{let{amountA:y,amountB:v}=z((0,k.d)(.5),(0,k.d)(.5),o,w.price,h.price,w.coin_decimals,h.coin_decimals);u=y.toString(),m=v.toString();break}case"OnlyCoinA":{let{amountA:y,amountB:v}=z((0,k.d)(1),(0,k.d)(0),o,w.price,h.price,w.coin_decimals,h.coin_decimals);u=y.toString(),m=v.toString();break}case"OnlyCoinB":{let{amountA:y,amountB:v}=z((0,k.d)(0),(0,k.d)(1),o,w.price,h.price,w.coin_decimals,h.coin_decimals);u=y.toString(),m=v.toString();break}default:throw new Error(`Unsupported deposit mode: ${a}`)}return t&&this.calculateDepositLpAmountBoth(s,r,u,m).then(y=>{t.onSuccess(y,n)}).catch(y=>{t.onError(y,n)}),{deposit_amount_a:u,deposit_amount_b:m,mode:a}}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:o}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:i,clmmPool:a}=await this.getVaultAndPool(o,!1),{clmm_vault:n}=i,{current_sqrt_price:s,coin_type_a:r,coin_type_b:c}=a,l=n.wrapped_position.tick_lower_index,_=n.wrapped_position.tick_upper_index,d=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,p=t==="OnlyCoinA",u=k.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,_,new W.default(d),p,!0,1,new W.default(s)),m=p?(0,k.d)(u.coin_amount_b).div(u.coin_amount_a):(0,k.d)(u.coin_amount_a).div(u.coin_amount_b),b=p?(0,k.d)(s).toString():(0,k.d)(1).div((0,k.d)(s)).toString();try{let V=await this._sdk.VaultsV2.findRouters(p?r:c,p?c:r,d);V&&(b=(0,k.d)(V.swap_out_amount).div(V.swap_in_amount).toString())}catch{}let{swap_amount:w}=ct(d,p,b.toString(),m.toString()),h=(0,k.d)(d).sub(w).toFixed(0),y=await this._sdk.VaultsV2.findRouters(p?r:c,p?c:r,w),v=(0,k.d)(y.swap_out_amount).mul(.999).toFixed(0),P=k.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,_,new W.default(h),p,!0,1,new W.default(s));return p?P.coin_amount_b=v:P.coin_amount_a=v,{swap_result:y,liquidity_info:P}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:o,pool_id:i,uuid:a}=e,n="0",s="0",r,c,{pool:l,clmmPool:_}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:d,fixed_coin_a:p}=e,{other_amount:u,lp_amount:m}=await this.calculateDepositOtherSide(l,_,d,p,t,a);c=m,p?(n=d,s=u):(s=d,n=u);break}case"FlexibleBoth":{let{coin_amount_a:d,coin_amount_b:p}=e;n=d,s=p;break}case"OnlyCoinA":{if(e.re_balance){let d=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:u}=d,{coin_amount_a:m,coin_amount_b:b}=u;n=m,s=b,r={swap_result:p,coin_amount:e.coin_amount_a}}else n=e.coin_amount_a;break}case"OnlyCoinB":{if(e.re_balance){let d=await this.calculateBalanceSwapAmount(e),{swap_result:p,liquidity_info:u}=d,{coin_amount_a:m,coin_amount_b:b}=u;n=m,s=b,r={swap_result:p,coin_amount:e.coin_amount_b}}else s=e.coin_amount_b;break}default:throw new Error(`Unsupported deposit mode: ${o}`)}return t?this.calculateDepositLpAmountBoth(l,_,n,s).then(d=>{t?.onSuccess(d,a)}).catch(d=>{t?.onError(d,a)}):c=await this.calculateDepositLpAmountBoth(l,_,n,s),{deposit_amount_a:n,deposit_amount_b:s,mode:o,re_balance:r,lp_amount:c}}async getVaultAndPool(e,t=!1){let o=await this.getPool(e,t);if(o===void 0)throw new Error("get vaults pool failed");let i=await this._sdk.CetusClmmSDK.Pool.getPool(o.clmm_vault.clmm_pool_id,t);if(i===void 0)throw new Error("get vaults clmmPool failed");return{clmmPool:i,pool:o}}async calculateDepositOtherSide(e,t,o,i,a,n){let{clmm_vault:s}=e,{current_sqrt_price:r}=t,c=s.wrapped_position.tick_lower_index,l=s.wrapped_position.tick_upper_index,_=k.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(c,l,new W.default(o),i,!0,1,new W.default(r)),{coin_amount_a:d,coin_amount_b:p}=_;if(a)this.calculateDepositLpAmountBoth(e,t,d.toString(),p.toString()).then(u=>{a.onSuccess(u,n)}).catch(u=>{a.onError(u,n)});else{let u=await this.calculateDepositLpAmountBoth(e,t,d.toString(),p.toString());return{other_amount:i?p.toString():d.toString(),lp_amount:u}}return{other_amount:i?p.toString():d.toString(),lp_amount:void 0}}async calculateDepositLpAmountBoth(e,t,o,i){let{lp_token_treasury:a,hard_cap:n}=e,s=(0,k.fixCoinType)(t.coin_type_a,!1),r=(0,k.fixCoinType)(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),_=pt(e.balances,l,c),d=await Lt(this,e,t,_,!0),p=await this.pythPrice.getLatestPrice([s,r],!0),u=p[s],m=p[r];if(!u)throw Error(`not find ${s} price`);if(!m)throw Error(`not find ${r} price`);let b={};b[s]={price:u,value:o.toString()},b[r]={price:m,value:i.toString()};let w=Z(b,e.quote_type);return ut(a,w,d)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:o}=e,i="0",a="0",n="0",s="0",r,{pool:c,clmmPool:l}=await this.getVaultAndPool(o,!1);switch(t){case"FixedOneSide":let _=await this.calculateWithdrawOtherSide(c,l,e.burn_lp_amount);n=_.burn_lp_amount,i=_.receive_amount_a,a=_.receive_amount_b,s=_.remove_liquidity;break;case"OnlyCoinA":{let d=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!0);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity,r=d.swap;break}case"OnlyCoinB":{let d=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!1);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity,r=d.swap;break}default:throw new Error(`Unsupported withdraw mode: ${t}`)}return{remove_liquidity:s,burn_lp_amount:n,receive_amount_a:i,receive_amount_b:a,mode:t,swap:r}}async calculateWithdrawOtherSide(e,t,o){let{clmm_vault:i,lp_token_treasury:a}=e,{current_sqrt_price:n}=t,{coin_type_a:s,coin_type_b:r}=e.clmm_vault.wrapped_position,c=i.wrapped_position.tick_lower_index,l=i.wrapped_position.tick_upper_index,_=i.wrapped_position.liquidity,d=k.TickMath.tickIndexToSqrtPriceX64(c),p=k.TickMath.tickIndexToSqrtPriceX64(l),u=et(a,o,_),{coin_amount_a:m,coin_amount_b:b}=k.ClmmPoolUtil.getCoinAmountFromLiquidity(new W.default(u),new W.default(n),d,p,!1),w=ot(o,e.balances,a),h=(0,k.d)(m.toString()).add(w[s]?.value||"0").toFixed(0),y=(0,k.d)(b.toString()).add(w[r]?.value||"0").toFixed(0);return{receive_amount_a:h,receive_amount_b:y,burn_lp_amount:o,mode:"FixedOneSide",remove_liquidity:u}}async calculateWithdrawOnlyCoin(e,t,o,i){let{totalReceiveAmount:a,swapAmountIn:n,swapAmountOut:s,removeLiquidity:r,remove_amount_a:c,remove_amount_b:l}=await this.calculateWithdrawOnlyCoinByLpAmount(e,t,i,o);return{receive_amount_a:i?a:"0",receive_amount_b:i?"0":a,burn_lp_amount:o,remove_liquidity:r,swap:{swap_amount_in:n,swap_amount_out:s,remove_amount_a:c,remove_amount_b:l},mode:"FixedOneSide"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,o,i){let{clmm_vault:a,lp_token_treasury:n}=e,{current_sqrt_price:s}=t,{coin_type_a:r,coin_type_b:c}=a.wrapped_position,l=a.wrapped_position.tick_lower_index,_=a.wrapped_position.tick_upper_index,d=a.wrapped_position.liquidity,p=k.TickMath.tickIndexToSqrtPriceX64(l),u=k.TickMath.tickIndexToSqrtPriceX64(_),m=et(n,i,d),{coin_amount_a:b,coin_amount_b:w}=k.ClmmPoolUtil.getCoinAmountFromLiquidity(new W.default(m),new W.default(s),p,u,!1),h=await this.pythPrice.getLatestPrice([r,c],!0),y=h[r],v=h[c];if(!y)throw Error(`not find ${r} price`);if(!v)throw Error(`not find ${c} price`);let P=o?v:y,V=o?y:v,{quote_per_base:O}=_t(P.price,V.price),F=ot(i,e.balances,n),A=(0,k.d)(b.toString()).add(F[r]?.value||"0").toFixed(0),B=(0,k.d)(w.toString()).add(F[c]?.value||"0").toFixed(0),D=o?A:B,M=o?B:A,L=(0,k.toDecimalsAmount)((0,k.d)((0,k.fromDecimalsAmount)(M,o?v.coin_decimals:y.coin_decimals)).mul(O).toString(),o?y.coin_decimals:v.coin_decimals).toString(),j=(0,k.d)(D).add(L).toFixed(0);return{remove_amount_a:A,remove_amount_b:B,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:D,swapAmountIn:M,swapAmountOut:(0,k.d)(L).toFixed(0,_e.default.ROUND_DOWN),totalReceiveAmount:j}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,o=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),i=(0,k.getObjectPreviousTransactionDigest)(o);(await this._sdk.FullClient.queryEventsByPage({Transaction:i})).data.forEach(l=>{let _=l.parsedJson;if(l.type)switch((0,le.extractStructTagFromType)(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=_.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=_.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=_.global_config;break;default:break}});let n=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),s=(0,k.getObjectFields)(n);e.pools_handle=s.pools.fields.id.id;let r=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),c=(0,k.getObjectFields)(r);return e.oracle_infos_handle=c.oracle_infos.fields.id.id,e.prices_handle=c.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}};var X=require("@cetusprotocol/common-sdk"),ue=require("@mysten/sui/transactions");var ht=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async vestNftIsAvailable(e,t){try{let o=await this._sdk.FullClient.getDynamicFieldObject({parentId:t,name:{type:"0x2::object::ID",value:e}});return!(0,X.getObjectFields)(o).value.fields.is_pause}catch{return!0}}async getVestCreateEventList(){let{vest:e}=this._sdk.sdkOptions;if(e===void 0)throw new Error("vest is not set config in sdk options");try{let t=`${e.package_id}::hae_vester::CreateEvent`;return(await this._sdk.FullClient.queryEventsByPage({MoveEventType:t})).data.map(i=>{let a=i.parsedJson,n={clmm_vester_id:a.clmm_vester_id,lp_coin_type:(0,X.fixCoinType)(a.lp_coin_type.name,!1),pool_id:a.pool_id,position_id:a.position_id,vault_id:a.vault_id,vault_vester_id:a.hae_vester_id},s=`${n.vault_id}-VestCreateEvent`;return this._sdk.updateCache(s,n),n})}catch(t){throw new Error(`getVestCreateEventList error: ${t}`)}return[]}async getVaultsVestInfoList(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let o=[];for(let n of e){let s=await this.getVaultVestEvent(n);o.push(s.vault_vester_id)}let i=[];return(await this._sdk.FullClient.batchGetObjects(o,{showContent:!0,showType:!0})).forEach(n=>{try{let s=Vt(n);i.push(s);let r=`${s.id}-VaultsVestInfo`;this._sdk.updateCache(r,s)}catch{}}),i}async getVaultsVestInfo(e,t=!0){let o=(await this.getVaultVestEvent(e)).vault_vester_id,i=`${o}-VaultsVestInfo`,a=this._sdk.getCache(i,t);if(a)return a;try{let n=await this._sdk.FullClient.getObject({id:o,options:{showContent:!0,showType:!0}}),s=Vt(n);return this._sdk.updateCache(i,s),s}catch(n){throw new Error(`getVaultsVestInfo error: ${n}`)}}async getVaultVestEvent(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let{create_event_list:o}=(0,X.getPackagerConfigs)(t),i=o.find(a=>a.vault_id===e);if(!i){let a=`${e}-VestCreateEvent`,n=this._sdk.getCache(a,!1);n?i=n:(i=(await this.getVestCreateEventList()).find(r=>r.vault_id===e),this._sdk.updateCache(a,i))}if(!i)throw new Error("vault_id not found in vest_ids_map");return i}async getOwnerVaultVestNFT(e){let{vest:t}=this._sdk.sdkOptions;if(!t)throw new Error("vest is not set config in sdk options");let o=await this._sdk.FullClient.getOwnedObjectsByPage(e,{filter:{StructType:`${t.package_id}::hae_vester::HaeVesterNFT`},options:{showContent:!0,showType:!0,showOwner:!0}}),i=[];return o.data.forEach(a=>{try{let n=It(a);i.push(n)}catch{}}),i}async buildRedeemPayload(e,t){let{vest:o}=this._sdk.sdkOptions,{clmm_vest:i}=this._sdk.CetusClmmSDK.sdkOptions;if(!o)throw new Error("vest is not set config in sdk options");if(!i)throw new Error("clmm_vest is not set config in clmm sdk options");let{versioned_id:a}=(0,X.getPackagerConfigs)(o),{versioned_id:n,clmm_vest_id:s}=(0,X.getPackagerConfigs)(i);t=t||new ue.Transaction;for(let r of e){let{vault_id:c,vesting_nft_id:l,period:_,coin_type_a:d,coin_type_b:p}=r,u=await this.getVaultVestEvent(c);t.moveCall({package:o.published_at,module:"hae_vester",function:"redeem_coin",arguments:[t.object(a),t.object(u.vault_vester_id),t.object(l),t.object(n),t.object(s),t.object(u.pool_id),t.pure.u16(_),t.object(X.CLOCK_ADDRESS)],typeArguments:[d,p]})}return t}};var ee=require("@mysten/sui/transactions"),J=H(require("bn.js"),1),pe=require("@cetusprotocol/aggregator-sdk"),me=require("@cetusprotocol/sui-clmm-sdk"),g=require("@cetusprotocol/common-sdk"),yt=require("@cetusprotocol/common-sdk"),fe=require("@mysten/sui/utils"),be=H(require("decimal.js"),1);var $=require("@cetusprotocol/dlmm-sdk");var wt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new nt(e,o,t.published_at,t.configs.global_config_id,t.configs.pyth_oracle_id,t.configs.versioned_id,t.configs.oracle_infos_handle,!0)}get PythPrice(){return this.pythPrice}get sdk(){return this._sdk}async getOwnerVaultsBalance(e,t,o=!0){let{pool:i}=await this.getVaultAndPool(t,!1),n=(await this._sdk.FullClient.getBalance({owner:e,coinType:i.lp_token_type})).totalBalance;return await St(this._sdk,n,t,e,o)}async getOwnerVaultsBalanceList(e){let{data:t}=await this.getPoolList(),o=[];for(let i=0;i<t.length;i++){let a=await this.getOwnerVaultsBalance(e,t[i].id);o.push(a)}return o}async buildCollectRewardAndFeePayload(e,t,o){let{pool:i,marketList:a}=await this.getVaultAndPool(e,!1),{lp_token_type:n,coin_type_a:s,coin_type_b:r}=i;for(let c of a)if(c.type==="DLMM"){let{position_list:l}=c;l.forEach(_=>{let{id:d,pool_id:p}=_.position,u=c.certified_pool_obj[p],{reward_manager:m,id:b}=u;this.buildDlmmCollectRewardPayload({reward_coin_types:[...m.rewards.map(w=>w.reward_coin)],lp_token_type:n,pool_id:e,certified_pool_id:b,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t),this.buildDlmmCollectFeePayload({lp_token_type:n,pool_id:e,certified_pool_id:b,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}else if(c.type==="CLMM"){let{position_list:l}=c;l.forEach(_=>{let{id:d,pool_id:p}=_.position,u=c.certified_pool_obj[p],{rewarder_infos:m,id:b}=u;this.buildClmmCollectRewardPayload({reward_coin_types:[...m.map(w=>w.coin_type)],lp_token_type:n,pool_id:e,certified_pool_id:b,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t),this.buildClmmCollectFeePayload({lp_token_type:n,pool_id:e,certified_pool_id:b,position_id:d,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}}async getVaultsPositionRewarderAndFee(e){let t=[],o=[],i=[],a=[];try{let{pool:n}=await this.getVaultAndPool(e,!1),s=`getVaultsV2PositionRewarderAndFee_${e}`,r=this._sdk.getCache(s);if(r)return r;let{coin_type_a:c,coin_type_b:l}=n,_=new ee.Transaction;await this.buildCollectRewardAndFeePayload(e,_),(await this._sdk.FullClient.sendSimulationTransaction(_,(0,fe.normalizeSuiAddress)("0x0")))?.events.forEach(p=>{let{parsedJson:u,type:m}=p;m.includes("CollectDlmmFeeEvent")&&(t.push({coin_type:(0,g.fixCoinType)(c,!1),value:u.amount_a}),t.push({coin_type:(0,g.fixCoinType)(l,!1),value:u.amount_b})),m.includes("CollectClmmFeeEvent")&&(o.push({coin_type:(0,g.fixCoinType)(c,!1),value:u.amount_a}),o.push({coin_type:(0,g.fixCoinType)(l,!1),value:u.amount_b})),m.includes("CollectClmmRewardEvent")&&a.push({coin_type:(0,g.fixCoinType)(u.reward_type.name,!1),value:u.amount}),m.includes("CollectDlmmRewardEvent")&&i.push({coin_type:(0,g.fixCoinType)(u.reward_type.name,!1),value:u.amount})}),this._sdk.updateCache(s,{dlmmFeeList:t,dlmmRewarderList:i,clmmFeeList:o,clmmRewarderList:a},10*1e3)}catch{}return{dlmmFeeList:t,dlmmRewarderList:i,clmmFeeList:o,clmmRewarderList:a}}async getPoolList(e="all"){let t={data:[],has_next_page:!1},{vaultsV2:o}=this._sdk.sdkOptions,{FullClient:i}=this._sdk,a=await i.getDynamicFieldsByPage(o.configs.pools_handle,e),n=a.data.map(s=>s.name.value);if(n.length>0){let s=await this.getAssignPoolList(n);t.data.push(...s),t.next_cursor=a.next_cursor,t.has_next_page=a.has_next_page}return t}async getPool(e,t=!0){let o=`getPool_${e}`,i=this._sdk.getCache(o,t);if(i)return i;let a=await this.getAssignPoolList([e]);if(a.length>0){let n=a[0];return this._sdk.updateCache(o,n),n}throw new Error(`get pool failed ${e}`)}async getAssignPoolList(e){let t=[];if(e.length>0){(await this._sdk.FullClient.batchGetObjects(e,{showContent:!0})).forEach(a=>{let n=At(a.data.content);t.push(n)});let i=t.map(a=>a.id);if(i.length>0){let a=await this.geMarketList(i);t.forEach(n=>{let s=a[n.id];if(s){n.markets=s;let c=0;s.forEach(l=>{c+=l.position_list.length}),n.is_multiple_pool=c!==1}let r=`getPool_${n.id}`;this._sdk.updateCache(r,n)})}}return t}async getVaultsAggregatedDataByIds(e){let{vaultsV2:t,vaults:o}=this._sdk.sdkOptions,i=[],a=[],n={},s={};if(e.length>0){let _=await this._sdk.FullClient.batchGetObjects(e,{showContent:!0});for(let d=0;d<_?.length;d++){let p=_[d],{type:u}=p.data.content;if(u.includes(`${t.package_id}::vault::Vault`)){let m=At(p.data.content);i.push(m)}else if(u.includes(`${o.package_id}::pool::Pool`)){let m=tt(p.data.content);this._sdk.updateCache(`getPool_${m.id}`,m),a.push(m)}}}let r=i.map(_=>_.id);if(r.length>0){let _=await this.geMarketList(r);i.forEach(d=>{let p=_[d.id];if(p){d.markets=p;let m=0;p.forEach(b=>{m+=b.position_list.length}),d.is_multiple_pool=m!==1}let u=`getPool_${d.id}`;this._sdk.updateCache(u,d)})}let c=new Set;a.forEach(_=>{c.add(_.clmm_vault.clmm_pool_id)}),i.forEach(_=>{_.markets.forEach(d=>{d.position_list.forEach(p=>{let{pool_id:u}=p.position;c.add(u)})})});let l=Array.from(c);if(l.length>0){let{clmm_pool:_}=this._sdk.CetusClmmSDK.sdkOptions,{dlmm_pool:d}=this._sdk.CetusDlmmSDK.sdkOptions;(await this._sdk.FullClient.batchGetObjects(l,{showContent:!0})).forEach(u=>{let{type:m}=u.data.content;if(m.includes(`${_.package_id}::pool::Pool`)){let b=(0,me.buildPool)(u);n[b.id]=b;let w=`${b.id}_getPoolObject`;this._sdk.CetusClmmSDK.updateCache(w,b)}else if(m.includes(`${d.package_id}::pool::Pool`)){let b=(0,$.parseDlmmPool)(u);s[b.id]=b;let w=`${b.id}_getDlmmPool`;this._sdk.CetusDlmmSDK.updateCache(w,b)}})}return{v1:a,v2:i,clmmPoolMap:n,dlmmPoolMap:s}}async geMarketList(e){let t={},o=[];e.forEach(a=>{let n=Nt(a),s=Wt(a);o.push(n,s)}),(await this._sdk.FullClient.batchGetObjects(o,{showContent:!0})).forEach(a=>{let n=qt(a?.data?.content);if(n){let s=t[n.vault_id]||[];s.push(n),t[n.vault_id]=s}});for(let a in t){let n=t[a];for(let s of n){let r=await this.getMarketPositionList(s.positions_handle.id);s.position_list=r}}return t}async getMarketPositionList(e){let t=[],i=(await this._sdk.FullClient.getDynamicFieldsByPage(e)).data.map(a=>a.objectId);return i.length>0&&(await this._sdk.FullClient.batchGetObjects(i,{showContent:!0})).forEach(n=>{try{let{type:s}=n.data?.content;if(s){if(s.includes("DLMMPosition")){let r=Kt(n?.data?.content);t.push(r)}else if(s?.includes("CLMMPosition")){let r=$t(n?.data?.content);t.push(r)}}}catch{}}),t}buildDlmmCollectRewardPayload(e,t){let{reward_coin_types:o,lp_token_type:i,pool_id:a,certified_pool_id:n,position_id:s,coin_type_a:r,coin_type_b:c,withdraw_cert:l}=e,{published_at:_,configs:d}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:p}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:u,global_config_id:m}=(0,g.getPackagerConfigs)(p);l?o.forEach(b=>{t.moveCall({target:`${_}::vault::collect_dlmm_reward_on_withdraw`,typeArguments:[r,c,i,b],arguments:[t.object(a),l,t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id)]})}):o.forEach(b=>{t.moveCall({target:`${_}::vault::collect_dlmm_reward`,typeArguments:[r,c,i,b],arguments:[t.object(a),t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id)]})})}buildClmmCollectRewardPayload(e,t){let{reward_coin_types:o,lp_token_type:i,pool_id:a,certified_pool_id:n,position_id:s,coin_type_a:r,coin_type_b:c,withdraw_cert:l}=e,{published_at:_,configs:d}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:p}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:u,global_config_id:m}=(0,g.getPackagerConfigs)(p);l?o.forEach(b=>{t.moveCall({target:`${_}::vault::collect_clmm_reward_on_withdraw`,typeArguments:[r,c,i,b],arguments:[t.object(a),l,t.object(n),t.object(s),t.object(m),t.object(u),t.object(d.versioned_id),t.object(g.CLOCK_ADDRESS)]})}):o.forEach(b=>{t.moveCall({target:`${_}::vault::collect_clmm_reward`,typeArguments:[r,c,i,b],arguments:[t.object(a),t.object(n),t.object(s),t.object(u),t.object(m),t.object(d.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}buildDlmmCollectFeePayload(e,t){let{lp_token_type:o,pool_id:i,certified_pool_id:a,position_id:n,coin_type_a:s,coin_type_b:r,withdraw_cert:c}=e,{published_at:l,configs:_}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:d}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:p,global_config_id:u}=(0,g.getPackagerConfigs)(d);c?t.moveCall({target:`${l}::vault::collect_dlmm_fee_on_withdraw`,typeArguments:[s,r,o],arguments:[t.object(i),c,t.object(a),t.object(n),t.object(u),t.object(p),t.object(_.versioned_id)]}):t.moveCall({target:`${l}::vault::collect_dlmm_fee`,typeArguments:[s,r,o],arguments:[t.object(i),t.object(a),t.object(n),t.object(u),t.object(p),t.object(_.versioned_id)]})}buildClmmCollectFeePayload(e,t){let{lp_token_type:o,pool_id:i,certified_pool_id:a,position_id:n,coin_type_a:s,coin_type_b:r,withdraw_cert:c}=e,{published_at:l,configs:_}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:d}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:p,global_config_id:u}=(0,g.getPackagerConfigs)(d);c?t.moveCall({target:`${l}::vault::collect_clmm_fee_on_withdraw`,typeArguments:[s,r,o],arguments:[t.object(i),c,t.object(a),t.object(n),t.object(u),t.object(_.versioned_id)]}):t.moveCall({target:`${l}::vault::collect_clmm_fee`,typeArguments:[s,r,o],arguments:[t.object(i),t.object(a),t.object(n),t.object(u),t.object(_.versioned_id)]})}async buildDepositPayload(e,t){let{published_at:o,configs:i}=this._sdk.sdkOptions.vaultsV2,{pool_id:a,amount_a:n,amount_b:s,return_lp_coin:r,re_balance:c,coin_a_input:l,coin_b_input:_}=e,{pool:d,marketList:p}=await this.getVaultAndPool(a,!1),{coin_type_a:u,coin_type_b:m,lp_token_type:b}=d,w=[u,m];for(let P of p)P.type==="DLMM"?P.position_list.forEach(V=>{let{pool_id:O}=V.position,F=P.certified_pool_obj[O],{reward_manager:A}=F,B=A.rewards.map(D=>(0,g.fixCoinType)(D.reward_coin,!1));w=st(B,u,m)}):P.type==="CLMM"&&P.position_list.forEach(V=>{let{pool_id:O}=V.position,F=P.certified_pool_obj[O],{rewarder_infos:A}=F,B=A.map(D=>(0,g.fixCoinType)(D.coin_type,!1));w=st([...w,...B],u,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(w,t);for(let P of p)if(P.type==="DLMM"){let{dlmm_pool:V}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:O}=(0,g.getPackagerConfigs)(V),{position_list:F}=P;F.forEach(A=>{let{id:B,pool_id:D}=A.position;t.moveCall({target:`${o}::vault::calculate_dlmm_position_amounts`,typeArguments:[u,m,b],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(D),t.object(B),t.object(O),t.object(i.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}else if(P.type==="CLMM"){let{clmm_pool:V}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:O}=(0,g.getPackagerConfigs)(V),{position_list:F}=P;F.forEach(A=>{let{id:B,pool_id:D}=A.position;t.moveCall({target:`${o}::vault::calculate_clmm_position_amounts`,typeArguments:[u,m,b],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(D),t.object(B),t.object(O),t.object(i.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}t.moveCall({target:`${o}::vault::calculate_aum`,typeArguments:[b],arguments:[t.object(a),t.object(i.pyth_oracle_id),t.object(i.versioned_id),t.object(g.CLOCK_ADDRESS)]});let h,y;if(c&&c.swap_result){let{swap_result:P,coin_amount:V,mode:O,swap_slippage:F}=c,{swap_in_amount:A,route_obj:B}=P,D=yt.CoinAssist.buildCoinWithBalance(BigInt(V),O==="OnlyCoinA"?u:m,t),M=t.splitCoins(D,[A]),L={router:B,slippage:F,txb:t,inputCoin:M},j=await this._sdk.AggregatorClient.fixableRouterSwapV3(L);h=O==="OnlyCoinA"?D:j,y=O==="OnlyCoinA"?j:D}else h=l||yt.CoinAssist.buildCoinWithBalance(BigInt(n),u,t),y=_||yt.CoinAssist.buildCoinWithBalance(BigInt(s),m,t);let v=t.moveCall({target:`${o}::vault::deposit`,typeArguments:[u,m,b],arguments:[t.object(a),t.object(i.global_config_id),t.object(i.pyth_oracle_id),h,y,t.object(g.CLOCK_ADDRESS),t.object(i.versioned_id)]});if(r)return v;t.transferObjects([v],this._sdk.getVerifySenderAddress())}async buildWithdrawPayload(e,t){let{pool_id:o,burn_lp_amount:i,mode:a,slippage:n,partner:s,extra_burn:r}=e,{pool:c,marketList:l}=await this.getVaultAndPool(o,!1),{lp_token_type:_,coin_type_a:d,coin_type_b:p}=c;t=t||new ee.Transaction;let u,m=r?(0,g.d)(r.burn_lp_amount).add((0,g.d)(i)).toFixed(0):(0,g.d)(i).toFixed(0),b=(0,g.d)(i).isZero();if(b&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");b?u=r.lp_burn_coin:(u=yt.CoinAssist.buildCoinWithBalance(BigInt(i),_,t),r&&r.lp_burn_coin&&t.mergeCoins(u,[r.lp_burn_coin]));let{published_at:w,configs:h}=this._sdk.sdkOptions.vaultsV2,{config:y}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:v}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,P=t.moveCall({target:`${w}::vault::new_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),u,t.object(h.versioned_id)]}),V=[];for(let D of l)if(D.type==="DLMM"){let{position_list:M}=D;M.forEach(L=>{let{id:j,pool_id:x}=L.position,R=D.certified_pool_obj[x],{reward_manager:T}=R,E=T.rewards.map(U=>(0,g.fixCoinType)(U.reward_coin,!1));V.push(...E),t.moveCall({target:`${w}::vault::withdraw_dlmm`,typeArguments:[d,p,_],arguments:[t.object(o),P,t.object(x),t.object(j),t.object(y.global_config_id),t.object(y.versioned_id),t.object(h.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}else if(D.type==="CLMM"){let{position_list:M}=D;M.forEach(L=>{let{id:j,pool_id:x}=L.position,R=D.certified_pool_obj[x],{rewarder_infos:T}=R,E=T.map(U=>(0,g.fixCoinType)(U.coin_type,!1));V.push(...E),t.moveCall({target:`${w}::vault::withdraw_clmm`,typeArguments:[d,p,_],arguments:[t.object(o),P,t.object(x),t.object(j),t.object(v.global_config_id),t.object(h.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}await this.buildCollectRewardAndFeePayload(o,t,P),t.moveCall({target:`${w}::vault::finalize_buffer_assets`,typeArguments:[_],arguments:[t.object(o),P,t.object(h.versioned_id)]});let O=new Set;V.forEach(D=>O.add(D)),O.add(d),O.add(p);let F=Array.from(O),A=a!=="FixedOneSide"?[a==="OnlyCoinA"?p:d]:[],B=this.buildWithdrawBufferReward({reward_coin_types:F,pool_id:o,withdraw_cert:P,lp_token_type:_,not_transfer_coin_types:A},t);if(t.moveCall({target:`${w}::vault::destroy_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),P,t.object(h.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let D=a==="OnlyCoinA",M=D?p:d,L=B.find(j=>j.coin_type===M).reward_coin_object_id;await this.handleWithSwap(t,L,d,p,m,o,D,n,s)}}async handleWithSwap(e,t,o,i,a,n,s,r,c){let{receive_amount_a:l,receive_amount_b:_}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),d=s?i:o,p=s?o:i,u=s?_:l;if((0,g.d)(u).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let m={from:d,target:p,amount:new J.default(u),byAmountIn:!0,depth:3,splitAlgorithm:void 0,splitFactor:void 0,splitCount:void 0,providers:this._sdk.sdkOptions.providers},b=await this._sdk.AggregatorClient.findRouters(m);if(!b)throw Error("not find Router");if(b.error!==void 0)throw Error(`find Router error : ${b.error}`);let w={router:b,inputCoin:t,slippage:r,txb:e,partner:c},h=await this._sdk.AggregatorClient.fixableRouterSwapV3(w);e.transferObjects([h],e.pure.address(this._sdk.getVerifySenderAddress()))}buildWithdrawBufferReward({reward_coin_types:e,pool_id:t,withdraw_cert:o,lp_token_type:i,not_transfer_coin_types:a},n){let{published_at:s,configs:r}=this._sdk.sdkOptions.vaultsV2;return e.map(c=>{let l=n.moveCall({target:`${s}::vault::withdraw_asset`,typeArguments:[i,c],arguments:[n.object(t),o,n.object(r.versioned_id)]});return a.includes(c)||n.transferObjects([l],n.pure.address(this._sdk.getVerifySenderAddress())),{coin_type:c,reward_coin_object_id:l}})}async preCalculateDepositValue(e,t){let{amount_usd:o,pool_id:i,mode:a,uuid:n,re_balance:s,coin_decimals_a:r,coin_decimals_b:c}=e,{pool:l,marketList:_}=await this.getVaultAndPool(i,!1),{coin_type_a:d,coin_type_b:p}=l,u=await this.pythPrice.getLatestPrice([d,p],!0),m=u[d],b=u[p];if(!m)throw new Error(`get ${d} price failed`);if(!b)throw new Error(`get ${p} price failed`);let w="0",h="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:v,position_amount_b_rate:P}=l.is_multiple_pool?{position_amount_a_rate:(0,g.d)(.5),position_amount_b_rate:(0,g.d)(.5)}:await this.calculatePositionValueRates(l,u),{amountA:V,amountB:O}=z(v,P,o,m.price,b.price,m.coin_decimals,b.coin_decimals);w=V,h=O;break}case"OnlyCoinA":{let{amountA:v,amountB:P}=z((0,g.d)(1),(0,g.d)(0),o,m.price,b.price,m.coin_decimals,b.coin_decimals);w=v,h=P;break}case"OnlyCoinB":{let{amountA:v,amountB:P}=z((0,g.d)(0),(0,g.d)(1),o,m.price,b.price,m.coin_decimals,b.coin_decimals);w=v,h=P;break}}return await this.preCalculateDepositAmount({mode:a,pool_id:i,uuid:n,coin_amount_a:w,coin_amount_b:h,re_balance:s,coin_decimals_a:r,coin_decimals_b:c},t)}async calculateClmmBalanceSwapAmount(e,t){let{mode:o,pool_id:i}=e;if(o==="OnlyCoinA"||o==="OnlyCoinB"){let{certified_pool_obj:a,position_list:n}=t,s=n[0].position,{current_sqrt_price:r,coin_type_a:c,coin_type_b:l}=a[s.pool_id],{tick_lower_index:_,tick_upper_index:d}=s,p=_,u=d,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,b=o==="OnlyCoinA",w=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(p,u,new J.default(m),b,!0,1,new J.default(r)),h=b?(0,g.d)(w.coin_amount_b).div(w.coin_amount_a):(0,g.d)(w.coin_amount_a).div(w.coin_amount_b),y=b?(0,g.d)(r).toString():(0,g.d)(1).div((0,g.d)(r)).toString();try{let A=await this._sdk.VaultsV2.findRouters(b?c:l,b?l:c,m);A&&(y=(0,g.d)(A.swap_out_amount).div(A.swap_in_amount).toString())}catch{}let{swap_amount:v}=ct(m,b,y.toString(),h.toString()),P=(0,g.d)(m).sub(v).toFixed(0),V=await this._sdk.VaultsV2.findRouters(b?c:l,b?l:c,v),O=(0,g.d)(V.swap_out_amount).mul(.999).toFixed(0),F=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(p,u,new J.default(P),b,!0,1,new J.default(r));return b?F.coin_amount_b=O:F.coin_amount_a=O,{swap_result:V,liquidity_info:F}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${o}`)}async calculateBalanceSwapAmount(e){let{mode:t,pool_id:o,coin_decimals_a:i,coin_decimals_b:a}=e;if(t==="OnlyCoinA"||t==="OnlyCoinB"){let{pool:n,marketList:s}=await this.getVaultAndPool(o,!1),{coin_type_a:r,coin_type_b:c}=n,l=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,_=t==="OnlyCoinA",d=s.find(m=>m.position_list.length>0);if(n.is_multiple_pool||!d){let m=await this.findRouters(_?r:c,_?c:r,l),{swap_out_amount:b,swap_in_amount:w}=m,h=_?i:a,y=_?a:i,v=(0,g.fromDecimalsAmount)(w,h),P=(0,g.fromDecimalsAmount)(b,y),V=(0,g.d)(P).div(v).toString(),O=await this.pythPrice.getLatestPrice([r,c],!0),F=O[r],A=O[c];if(!F||!A)throw new Error(`not find ${r} or ${c} price`);let B=Ht(_?v:"0",_?"0":v,F.price,A.price,V,_),D=(0,g.d)((0,g.toDecimalsAmount)(B,h).toString()).toFixed(0),M=(0,g.d)(l).sub(D).toFixed(0);if((0,g.d)(M).lt(1)||(0,g.d)(D).lt(1))throw new Error("amount is less than 1");let L=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,D),j=(0,g.d)(L.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:_?M:j,amount_b:_?j:M},swap_result:L}}let p=s.find(m=>m.type==="CLMM");if(p){let{swap_result:m,liquidity_info:b}=await this.calculateClmmBalanceSwapAmount({...e},p);return{swap_result:m,liquidity_info:{bins:[],amount_a:b.coin_amount_a,amount_b:b.coin_amount_b}}}let u=s.find(m=>m.type==="DLMM");if(u){let m=u.certified_pool_obj[u.position_list[0].position.pool_id],b=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(m.bin_manager.bin_manager_handle,m.active_id,m.bin_step,!1),{active_id:w,bin_step:h}=m,y=$.BinUtils.getPricePerLamportFromBinId(m.active_id,m.bin_step),v=(0,g.d)(y).mul(1-.05),P=(0,g.d)(y).mul(1+.05),V=$.BinUtils.getBinIdFromLamportPrice(v.toString(),m.bin_step,!1),O=$.BinUtils.getBinIdFromLamportPrice(P.toString(),m.bin_step,!1),F=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,coin_amount:l,fix_amount_a:_,active_id:w,bin_step:h,lower_bin_id:V,upper_bin_id:O,active_bin_of_pool:b,strategy_type:$.StrategyType.Spot}),A=_?(0,g.d)(F.amount_b).div(F.amount_a):(0,g.d)(F.amount_a).div(F.amount_b),B=_?$.BinUtils.getPricePerLamportFromBinId(w,h):(0,g.d)(1).div($.BinUtils.getPricePerLamportFromBinId(w,h)).toString();try{let G=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,l);G&&(B=(0,g.d)(G.swap_out_amount).div(G.swap_in_amount).toString())}catch{}let{swap_amount:D,final_amount_a:M,final_amount_b:L}=ct(l,_,B,A.toString()),j=(0,g.d)(l).sub(D).toFixed(0),x=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,D),R=(0,g.d)(x.swap_out_amount).mul(.999).toFixed(0),T=_?j:R,E=_?R:j,U=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:T,amount_b:E,active_id:w,bin_step:h,lower_bin_id:V,upper_bin_id:O,active_bin_of_pool:b,strategy_type:$.StrategyType.Spot});return _?U.amount_b=x.swap_out_amount:U.amount_a=x.swap_out_amount,{swap_result:x,liquidity_info:U}}}throw new Error(`calculateBalanceSwapAmount Unsupported deposit mode: ${t}`)}async preCalculateDepositAmount(e,t){let{mode:o,pool_id:i,uuid:a}=e,{pool:n,marketList:s}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:r,fixed_coin_a:c,coin_decimals_a:l,coin_decimals_b:_}=e;return await this.calculateDepositOtherSide(n,s,r,c,l,_,t,a)}case"FlexibleBoth":{let{coin_amount_a:r,coin_amount_b:c}=e;return await this.calculateDepositFlexibleBoth(n,r,c,t,a)}case"OnlyCoinA":{let{coin_amount_a:r,re_balance:c}=e;if(c){let l=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:d}=l,{amount_a:p,amount_b:u}=d,m=await this.calculateDepositFlexibleBoth(n,p,u,t,a);return m.re_balance={swap_result:_,coin_amount:r,mode:"OnlyCoinA"},m}else return await this.calculateDepositFlexibleBoth(n,r,"0",t,a)}case"OnlyCoinB":{let{coin_amount_b:r,re_balance:c}=e;if(c){let l=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:d}=l,{amount_a:p,amount_b:u}=d,m=await this.calculateDepositFlexibleBoth(n,p,u,t,a);return m.re_balance={swap_result:_,coin_amount:r,mode:"OnlyCoinB"},m}else return await this.calculateDepositFlexibleBoth(n,"0",r,t,a)}}throw new Error(`Unsupported deposit mode: ${o}`)}async getVaultAndPool(e,t=!1){let o=await this.getPool(e,t);if(o===void 0)throw new Error("get vaults pool failed");let{markets:i}=o,a=[];for(let n of i){let s={};if(n.type==="DLMM"){for(let r of n.position_list){let{pool_id:c}=r.position,l=await this._sdk.CetusDlmmSDK.Pool.getPool(c,t);if(!l)throw new Error(`get vaults dlmmPool failed ${c}`);s[c]=l}a.push({certified_pool_obj:s,...n})}else{for(let r of n.position_list){let{pool_id:c}=r.position,l=await this._sdk.CetusClmmSDK.Pool.getPool(c,t);if(!l)throw new Error(`get vaults clmmPool failed ${c}`);s[c]=l}a.push({certified_pool_obj:s,...n})}}if(a.length===0)throw new Error(`get vaults marketList failed ${e}`);return{marketList:a,pool:o}}async calculatePositionValueRates(e,t){let{lp_token_treasury:o,coin_type_a:i,coin_type_b:a}=e;if((0,g.d)(o).eq(0))return{position_amount_a_rate:(0,g.d)(.5),position_amount_b_rate:(0,g.d)(.5)};let{position_amount_a:n,position_amount_b:s}=await St(this._sdk,o,e.id),r=t[i],c=t[a];if(!r)throw Error(`not find ${i} price`);if(!c)throw Error(`not find ${a} price`);let l=(0,g.d)((0,g.fromDecimalsAmount)(n,r.coin_decimals)).mul(r.price),_=(0,g.d)((0,g.fromDecimalsAmount)(s,c.coin_decimals)).mul(c.price),d=(0,g.d)(l).add(_),p=(0,g.d)(l).div(d),u=(0,g.d)(1).sub(p);return{position_amount_a_rate:p,position_amount_b_rate:u}}async calculateDepositAmountByValue(e,t,o,i,a,n){let s=await this.PythPrice.getLatestPrice([a,n],!0),r=s[a],c=s[n];if(!r)throw Error(`not find ${a} price`);if(!c)throw Error(`not find ${n} price`);let l="0",_="0";if(e){l=t;let d=(0,g.d)((0,g.fromDecimalsAmount)(l,o)).mul(r.price);_=(0,g.d)((0,g.toDecimalsAmount)((0,g.d)(d).div(c.price).toString(),i)).toFixed(0)}else{_=t;let d=(0,g.d)((0,g.fromDecimalsAmount)(_,i)).mul(c.price);l=(0,g.d)((0,g.toDecimalsAmount)((0,g.d)(d).div(r.price).toString(),o)).toFixed(0)}if((0,g.d)(l).lt(1)||(0,g.d)(_).lt(1))throw new Error("is less than 1");return{deposit_amount_a:l,deposit_amount_b:_}}async calculateDepositDlmmAmountsV2(e,t,o,i){let{markets:a}=e,{coin_type_a:n,coin_type_b:s}=e,r=a[0].position_list[0].position,c=await this._sdk.CetusDlmmSDK.Pool.getBinInfo(t.bin_manager.bin_manager_handle,t.active_id,t.bin_step,!1),l=$.BinUtils.getPricePerLamportFromBinId(t.active_id,t.bin_step),_=(0,g.d)(l).mul(1-.05),d=(0,g.d)(l).mul(1+.05),p=$.BinUtils.getBinIdFromLamportPrice(_.toString(),t.bin_step,!1),u=$.BinUtils.getBinIdFromLamportPrice(d.toString(),t.bin_step,!1),m={pool_id:r.pool_id,coin_amount:(0,g.d)(i).mul(1e5).toFixed(0),fix_amount_a:o,active_id:t.active_id,bin_step:t.bin_step,lower_bin_id:p,upper_bin_id:u,strategy_type:$.StrategyType.Spot,active_bin_of_pool:c},b=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo(m),{amount_a:w,amount_b:h}=b;return{deposit_amount_a:(0,g.d)(w).div(1e5).toFixed(0),deposit_amount_b:(0,g.d)(h).div(1e5).toFixed(0)}}async calculateDepositClmmAmounts(e,t,o,i){let{markets:a}=e,n=a[0].position_list[0].position,{tick_lower_index:s,tick_upper_index:r}=n,{current_sqrt_price:c,coin_type_a:l,coin_type_b:_}=t,{coin_amount_a:d,coin_amount_b:p}=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(s,r,new J.default(i),o,!0,1,new J.default(c));return{deposit_amount_a:d.toString(),deposit_amount_b:p.toString()}}async calculateDepositOtherSide(e,t,o,i,a,n,s,r){let c="0",l="0",{coin_type_a:_,coin_type_b:d}=e;if(e.is_multiple_pool){let p=await this.calculateDepositAmountByValue(i,o,a,n,_,d);c=p.deposit_amount_a,l=p.deposit_amount_b}else if(t[0].type==="DLMM"&&t[0].position_list.length>0){let p=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:u,deposit_amount_b:m}=await this.calculateDepositDlmmAmountsV2(e,p,i,o);c=u,l=m}else if(t[0].type==="CLMM"&&t[0].position_list.length>0){let p=t[0].certified_pool_obj[t[0].position_list[0].position.pool_id],{deposit_amount_a:u,deposit_amount_b:m}=await this.calculateDepositClmmAmounts(e,p,i,o);c=(0,g.d)(u).add(c).toFixed(0),l=(0,g.d)(m).add(l).toFixed(0)}else{let p=await this.calculateDepositAmountByValue(i,o,a,n,_,d);c=p.deposit_amount_a,l=p.deposit_amount_b}if(s)this.calculateDepositLpAmountBoth(e,c,l).then(p=>{s.onSuccess(p,r)}).catch(p=>{s.onError(p,r)});else{let p=await this.calculateDepositLpAmountBoth(e,c,l);return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:p,uuid:r,mode:"FixedOneSide"}}return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:void 0,uuid:r,mode:"FixedOneSide"}}async calculateDepositFlexibleBoth(e,t,o,i,a){if(i)this.calculateDepositLpAmountBoth(e,t,o).then(n=>{i.onSuccess(n,a)}).catch(n=>{i.onError(n,a)});else{let n=await this.calculateDepositLpAmountBoth(e,t,o);return{deposit_amount_a:t,deposit_amount_b:o,lp_amount:n,uuid:a,mode:"FlexibleBoth"}}return{deposit_amount_a:t,deposit_amount_b:o,lp_amount:void 0,uuid:a,mode:"FlexibleBoth"}}async calculateDepositLpAmountBoth(e,t,o){let{lp_token_treasury:i,markets:a,quote_type:n,coin_type_a:s,coin_type_b:r}=e,c=(0,g.fixCoinType)(s,!1),l=(0,g.fixCoinType)(r,!1),{dlmmRewarderList:_,dlmmFeeList:d,clmmRewarderList:p,clmmFeeList:u}=await this.getVaultsPositionRewarderAndFee(e.id),m=pt(e.buffer_assets,[...d,...u],[..._,...p]),b=await Ut(this._sdk,e.id,m,!0),w=await this.pythPrice.getLatestPrice([c,l],!0),h=w[c],y=w[l];if(!h)throw Error(`not find ${c} price`);if(!y)throw Error(`not find ${l} price`);let v={};v[c]={price:h,value:t.toString()},v[l]={price:y,value:o.toString()};let P=Z(v,n);return ut(i,P,b)}async preCalculateWithdrawAmount(e){let{mode:t,pool_id:o}=e,{pool:i}=await this.getVaultAndPool(o,!1);switch(t){case"FixedOneSide":{let{burn_lp_amount:a}=e;return await this.calculateWithdrawOtherSide(o,a)}case"OnlyCoinA":return await this.calculateWithdrawOnlyCoin(i,e.burn_lp_amount,!0);case"OnlyCoinB":return await this.calculateWithdrawOnlyCoin(i,e.burn_lp_amount,!1)}throw new Error(`Unsupported withdraw mode: ${t}`)}async calculateWithdrawOtherSide(e,t){let{amount_a:o,amount_b:i}=await ft(this._sdk,t,e);return{receive_amount_a:o,receive_amount_b:i,burn_lp_amount:t,mode:"FixedOneSide"}}async calculateWithdrawOnlyCoin(e,t,o){let{totalReceiveAmount:i,swapAmountIn:a,swapAmountOut:n,remove_amount_a:s,remove_amount_b:r}=await this.calculateWithdrawOnlyCoinByLpAmount(e,o,t);return{receive_amount_a:o?i:"0",receive_amount_b:o?"0":i,burn_lp_amount:t,swap:{swap_amount_in:a,swap_amount_out:n,remove_amount_a:s,remove_amount_b:r},mode:o?"OnlyCoinA":"OnlyCoinB"}}async calculateWithdrawOnlyCoinByLpAmount(e,t,o){let{coin_type_a:i,coin_type_b:a}=e,{amount_a:n,amount_b:s}=await ft(this._sdk,o,e.id),r=await this.pythPrice.getLatestPrice([i,a],!0),c=r[i],l=r[a];if(!c)throw Error(`not find ${i} price`);if(!l)throw Error(`not find ${a} price`);let _=t?l:c,d=t?c:l,{quote_per_base:p}=_t(_.price,d.price),u=t?n:s,m=t?s:n,b=(0,g.toDecimalsAmount)((0,g.d)((0,g.fromDecimalsAmount)(m,t?l.coin_decimals:c.coin_decimals)).mul(p).toString(),t?c.coin_decimals:l.coin_decimals).toString(),w=(0,g.d)(u).add(b).toFixed(0);return{remove_amount_a:n,remove_amount_b:s,burn_lp_amount:o,is_coin_a:t,originAmount:u,swapAmountIn:m,swapAmountOut:(0,g.d)(b).toFixed(0,be.default.ROUND_DOWN),totalReceiveAmount:w}}async getPackageConfigs(){let e={registry_id:"1",pools_handle:"",pyth_oracle_id:"1",oracle_infos_handle:"",prices_handle:"1",global_config_id:"1"},{package_id:t}=this._sdk.sdkOptions.vaults,o=await this._sdk.FullClient.getObject({id:t,options:{showPreviousTransaction:!0}}),i=(0,g.getObjectPreviousTransactionDigest)(o);(await this._sdk.FullClient.queryEventsByPage({Transaction:i})).data.forEach(l=>{let _=l.parsedJson;if(l.type)switch((0,pe.extractStructTagFromType)(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=_.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=_.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=_.global_config;break;default:break}});let n=await this._sdk.FullClient.getObject({id:e.registry_id,options:{showContent:!0}}),s=(0,g.getObjectFields)(n);e.pools_handle=s.pools.fields.id.id;let r=await this._sdk.FullClient.getObject({id:e.pyth_oracle_id,options:{showContent:!0}}),c=(0,g.getObjectFields)(r);return e.oracle_infos_handle=c.oracle_infos.fields.id.id,e.prices_handle=c.prices.fields.id.id,this._sdk.sdkOptions.vaults.configs=e,this._sdk.sdkOptions}async findRouters(e,t,o){let{providers:i}=this._sdk.sdkOptions,a=this._sdk.AggregatorClient;if((0,g.d)(o).lt(1))throw new Error("amount is less than 1");try{let n={from:e,target:t,amount:new J.default(o),byAmountIn:!0,depth:3,providers:i},s=await a.findRouters(n);if(s?.error)throw new Error(`Aggregator findRouters error: ${s?.error}`);if(!s?.paths||s?.paths?.length===0)throw new Error("Aggregator findRouters error: no router");let r=s.amountIn.toString(),c=s.amountOut.toString();return{swap_in_amount:r,swap_out_amount:c,route_obj:s}}catch(n){throw new Error(`Aggregator findRouters error: ${n}`)}}};var he=H(require("@cetusprotocol/dlmm-sdk"),1);var I=require("@cetusprotocol/common-sdk"),Dt=class{_sdk;constructor(e){this._sdk=e}get sdk(){return this._sdk}async getVaultAndPool(e){return e.version==="v1"?await this.sdk.Vaults.getVaultAndPool(e.vault_id):await this.sdk.VaultsV2.getVaultAndPool(e.vault_id)}async buildMigrateWithdrawTx(e,t){let{withdraw_result:o,return_ft_coin:i,liquidity_slippage:a,extra_burn:n}=e,{deposit_amount_a:s,deposit_amount_b:r,from_vault:c,to_vault:l,burn_ft_amount:_,from_swap_result:d}=o;if(c.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(l.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:p,clmmPool:u}=await this.getVaultAndPool(c),{marketList:m,pool:b}=await this.getVaultAndPool(l),{coin_type_a:w,coin_type_b:h}=u,y=n?(0,I.d)(_).sub(n.burn_lp_amount).toFixed(0).toString():_,{return_coin_a:v,return_coin_b:P}=await this.sdk.Vaults.buildWithdrawPayload({pool_id:c.vault_id,burn_lp_amount:y,mode:"FixedOneSide",slippage:a,return_coin:!0,extra_burn:n},t),V={[(0,I.fixCoinType)(w,!1)]:v,[(0,I.fixCoinType)(h,!1)]:P},{coin_output_a:O,coin_output_b:F}=d,{from_coin_type:A,from_coin_amount:B,route_obj:D,to_coin_type:M}=O;if(D){let{to_coin:j}=await this.buildSwapAssetsTx({from_coin_type:A,swap_in_amount:B,liquidity_slippage:a,route_obj:D.route_obj,tx:t,from_coin_object_id:V[(0,I.fixCoinType)(A,!1)]});V[(0,I.fixCoinType)(M,!1)]=j}if(F.route_obj){let{from_coin_type:j,from_coin_amount:x,route_obj:R,to_coin_type:T}=F,{to_coin:E}=await this.buildSwapAssetsTx({from_coin_type:j,swap_in_amount:x,liquidity_slippage:a,route_obj:R.route_obj,tx:t,from_coin_object_id:V[(0,I.fixCoinType)(j,!1)]});V[(0,I.fixCoinType)(T,!1)]=E}return await this._sdk.VaultsV2.buildDepositPayload({pool_id:l.vault_id,amount_a:s,amount_b:r,return_lp_coin:i,coin_a_input:V[(0,I.fixCoinType)(b.coin_type_a,!1)],coin_b_input:V[(0,I.fixCoinType)(b.coin_type_b,!1)]},t)}async calculateMigrateWithdraw(e){let{from_vault:t,to_vault:o,burn_ft_amount:i}=e;if(t.version!=="v1")throw new Error("From vault version is not supported, only v1 is supported");if(o.version!=="v2")throw new Error("To vault version is not supported, only v2 is supported");let{pool:a,clmmPool:n}=await this.getVaultAndPool(t),{marketList:s,pool:r}=await this.getVaultAndPool(o),c=await this.sdk.Vaults.preCalculateWithdrawAmount({pool_id:t.vault_id,mode:"FixedOneSide",burn_lp_amount:i}),{coin_type_a:l,coin_type_b:_}=n,{coin_type_a:d,coin_type_b:p}=r,u=await this.matchSwapCoins({from:{coin_type_a:l,coin_amount_a:c.receive_amount_a,coin_type_b:_,coin_amount_b:c.receive_amount_b},to:{coin_type_a:d,coin_type_b:p}}),{coin_output_a:m,coin_output_b:b}=u,w=await this.sdk.VaultsV2.calculateDepositLpAmountBoth(r,m.to_coin_amount,b.to_coin_amount);return{from_vault:t,to_vault:o,burn_ft_amount:i,deposit_amount_a:m.to_coin_amount,deposit_amount_b:b.to_coin_amount,obtained_ft_amount:w,from_swap_result:u}}async buildSwapAssetsTx(e){let{from_coin_type:t,liquidity_slippage:o,tx:i,from_coin_object_id:a,swap_in_amount:n,route_obj:s}=e,r=a||I.CoinAssist.buildCoinWithBalance(BigInt(n),t,i),c={router:s,inputCoin:r,slippage:o,txb:i};return{to_coin:await this._sdk.AggregatorClient.fixableRouterSwapV3(c)}}async matchSwapCoins(e){let{from:t,to:o}=e,i=(0,I.fixCoinType)(t.coin_type_a,!1),a=(0,I.fixCoinType)(t.coin_type_b,!1),n=(0,I.fixCoinType)(o.coin_type_a,!1),s=(0,I.fixCoinType)(o.coin_type_b,!1),r=i===n,c=i===s,l=a===n,_=a===s,d,p;r&&_?(d="A",p="B"):c&&l?(d="B",p="A"):r?(d="A",p="B"):c||l?(d="B",p="A"):(d="A",p="B");let u={from_coin_type:d==="A"?i:a,from_coin_amount:d==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:n,to_coin_amount:"0"},m={from_coin_type:p==="A"?i:a,from_coin_amount:p==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:s,to_coin_amount:"0"};if(u.from_coin_type!==u.to_coin_type&&(0,I.d)(u.from_coin_amount).gt(0))try{let b=await this.sdk.VaultsV2.findRouters(u.from_coin_type,u.to_coin_type,u.from_coin_amount);if(b)u.to_coin_amount=b.swap_out_amount,u.route_obj={swap_in_amount:b.swap_in_amount,swap_out_amount:b.swap_out_amount,route_obj:b.route_obj};else throw Error("Aggregator no router")}catch(b){throw b}else u.to_coin_amount=u.from_coin_amount;if(m.from_coin_type!==m.to_coin_type&&(0,I.d)(m.from_coin_amount).gt(0))try{let b=await this.sdk.VaultsV2.findRouters(m.from_coin_type,m.to_coin_type,m.from_coin_amount);if(b)m.to_coin_amount=b.swap_out_amount,m.route_obj={swap_in_amount:b.swap_in_amount,swap_out_amount:b.swap_out_amount,route_obj:b.route_obj};else throw Error("Aggregator no router")}catch(b){throw b}else m.to_coin_amount=m.from_coin_amount;return{coin_output_a:u,coin_output_b:m}}};var Q=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=Yt),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||oe.CetusClmmSDK.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||oe.CetusClmmSDK.createSDK({env:"mainnet",full_rpc_url:e.fullRpcUrl}),this._cetusDlmmSDK=o||he.default.createSDK({env:e.env,full_rpc_url:e.fullRpcUrl}),this._vaults=new gt(this),this._vaultsV2=new wt(this),this._migrate=new Dt(this);let{primary:i,secondary:a}=e.pythConfigs.hermes_service_urls,n=[i,a].filter(Boolean);this._aggregatorClient=new vt.AggregatorClient({endpoint:e.aggregatorUrl,signer:(0,Ot.normalizeSuiAddress)("0x0"),client:this.FullClient,env:e.env==="testnet"?vt.Env.Testnet:vt.Env.Mainnet,pythUrls:n}),this._vest=new ht(this)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e,this.CetusClmmSDK.setSenderAddress(e)}get sdkOptions(){return this._sdkOptions}get Vaults(){return this._vaults}get VaultsV2(){return this._vaultsV2}get FullClient(){return this._cetusClmmSDK.FullClient}get AggregatorClient(){return this._aggregatorClient}get CetusClmmSDK(){return this._cetusClmmSDK}get CetusDlmmSDK(){return this._cetusDlmmSDK}get Vest(){return this._vest}get Migrate(){return this._migrate}getVerifySenderAddress(){if(this.senderAddress.length===0||!(0,Ot.isValidSuiAddress)(this.senderAddress))throw Error("this sdk senderAddress is illegal");return this.senderAddress}async getOwnerCoinAssets(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinAssets(e,t)}async getOwnerCoinBalances(e,t){return await this._cetusClmmSDK.FullClient.getOwnerCoinBalances(e,t)}updateCache(e,t,o=ge.CACHE_TIME_24H){this.CetusClmmSDK.updateCache(e,t,o)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var Ie=.2;var Re=Q;0&&(module.exports={PythPriceModule,SdkEnv,VaultsModule,VaultsModuleV2,VestModule,VolatileVaultsSDK,buildCLMMMarketId,buildCLMMMarketPosition,buildDLMMMarketId,buildDLMMMarketPosition,buildDLMMPositionId,buildPoolData,buildPoolV2Data,buildVaultMarket,buildVaultsBalance,buildVaultsBalanceV2,calcExactSwapAmount,calcSingleSideSwap,calculateAum,calculateAumV2,calculateDepositRatioFixTokenA,calculateTotalAumBasedOnQuote,checkIsMinOrMaxIndex,convertU64BytesToDecimal,defaultProvider,dlmm_split_rate,estCoinAmountsFromTotalAmount,feed_map_mainnet,feed_map_testnet,getAmountBalanceByLpAmount,getCoinAmountsFromRatio,getPositionPriceRange,getPriceWithFormattedDecimals,getPrimitivePricesFromBaseQuote,getQuotePerBaseAndBasePerQuote,getShareBufferAssets,getUpdatePriceType,getVaultValidBalances,get_lp_amount_by_liquidity,get_lp_amount_by_tvl,get_share_liquidity_by_amount,initMainnetSDK,initTestnetSDK,initVaultSDK,oraclePriceMultiplierDecimal,parseVaultVestNFT,parseVaultsVestInfo,printTransaction,toSuiObjectId,vaults_mainnet,vaults_testnet});
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { CoinBalance, SuiObjectResponse } from '@mysten/sui/client';
2
1
  import { PreSwapLpChangeParams, AggregatorClient } from '@cetusprotocol/aggregator-sdk';
3
2
  import * as _cetusprotocol_common_sdk from '@cetusprotocol/common-sdk';
4
3
  import { CoinPairType, TableHandle, PaginationArgs, DataPage, IModule as IModule$1, Package, SuiAddressType, FullClient, CoinAsset, SuiResource } from '@cetusprotocol/common-sdk';
@@ -475,7 +474,7 @@ declare class PythPriceModule implements IModule {
475
474
  * @returns A promise that resolves to a record mapping coin types to their respective price information.
476
475
  */
477
476
  getLatestPrice(coinTypeList: string[], useCache?: boolean): Promise<Record<string, Price>>;
478
- getPriceFeedsUpdateData(feedIds: string[]): Promise<Buffer[] | undefined>;
477
+ getPriceFeedsUpdateData(feedIds: string[]): Promise<Buffer<ArrayBufferLike>[] | undefined>;
479
478
  getLatestPriceFeeds(feedIds: string[]): Promise<PriceUpdate | undefined>;
480
479
  /**
481
480
  * Builds the payload to update Pyth price feeds with the provided coin types and transaction.
@@ -654,8 +653,8 @@ declare class VaultsModule implements IModule {
654
653
  * @returns The updated transaction object.
655
654
  */
656
655
  buildWithdrawPayload(options: WithdrawOptions, tx: Transaction): Promise<{
657
- return_coin_a?: TransactionObjectArgument;
658
- return_coin_b?: TransactionObjectArgument;
656
+ return_coin_a?: any;
657
+ return_coin_b?: any;
659
658
  }>;
660
659
  /**
661
660
  * Handles the swap operation for liquidity pool tokens, calculates the amounts to be received after withdrawal,
@@ -684,7 +683,7 @@ declare class VaultsModule implements IModule {
684
683
  is_receive_coin_a: boolean, // Boolean flag to determine if the user is receiving coin A or coin B.
685
684
  slippage: number, // The slippage tolerance for the swap.
686
685
  partner?: string, // Optional partner address for the swap.
687
- liquidityChanges?: PreSwapLpChangeParams[], return_coin?: boolean): Promise<TransactionObjectArgument | undefined>;
686
+ liquidityChanges?: PreSwapLpChangeParams[], return_coin?: boolean): Promise<any>;
688
687
  /**
689
688
  * Builds a list of transaction objects to withdraw rewards from a liquidity pool.
690
689
  * The method generates multiple `moveCall` transaction objects for each reward coin type,
@@ -1283,7 +1282,7 @@ declare class VolatileVaultsSDK {
1283
1282
  * @param coinType The type of the coin.
1284
1283
  * @returns an array of coin balances.
1285
1284
  */
1286
- getOwnerCoinBalances(suiAddress: string, coinType?: string | null): Promise<CoinBalance[]>;
1285
+ getOwnerCoinBalances(suiAddress: string, coinType?: string | null): Promise<any[]>;
1287
1286
  /**
1288
1287
  * Updates the cache for the given key.
1289
1288
  *
@@ -1452,13 +1451,13 @@ declare function getPositionPriceRange(tick_lower_index: number, tick_upper_inde
1452
1451
  * @param res - The Sui object response containing the vault vest info.
1453
1452
  * @returns The parsed vault vest info.
1454
1453
  */
1455
- declare function parseVaultsVestInfo(res: SuiObjectResponse): VaultsVestInfo;
1454
+ declare function parseVaultsVestInfo(res: any): VaultsVestInfo;
1456
1455
  /**
1457
1456
  * Parses the vault vest NFT from the Sui object response.
1458
1457
  * @param res - The Sui object response containing the vault vest NFT.
1459
1458
  * @returns The parsed vault vest NFT.
1460
1459
  */
1461
- declare function parseVaultVestNFT(res: SuiObjectResponse): VaultVestNFT;
1460
+ declare function parseVaultVestNFT(res: any): VaultVestNFT;
1462
1461
 
1463
1462
  declare function buildVaultMarket(data: any): VaultMarket | undefined;
1464
1463
  declare function buildDLMMMarketPosition(data: any): DLMMMarketPosition;