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