haedal-vault-sdk 2.5.3 → 2.5.4

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 Se=Object.create;var At=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var je=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Fe=(b,e)=>{for(var t in e)At(b,t,{get:e[t],enumerable:!0})},de=(b,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oe(e))!Be.call(b,i)&&i!==t&&At(b,i,{get:()=>e[i],enumerable:!(o=De(e,i))||o.enumerable});return b};var G=(b,e,t)=>(t=b!=null?Se(je(b)):{},de(e||!b||!b.__esModule?At(t,"default",{value:b,enumerable:!0}):t,b)),Me=b=>de(At({},"__esModule",{value:!0}),b);var ze={};Fe(ze,{PythPriceModule:()=>ct,SdkEnv:()=>me,VaultsModule:()=>vt,VaultsModuleV2:()=>kt,VestModule:()=>Pt,VolatileVaultsSDK:()=>Z,buildCLMMMarketId:()=>Yt,buildCLMMMarketPosition:()=>Jt,buildDLMMMarketId:()=>Zt,buildDLMMMarketPosition:()=>Gt,buildDLMMPositionId:()=>Ke,buildPoolData:()=>st,buildPoolV2Data:()=>Bt,buildVaultMarket:()=>Xt,buildVaultsBalance:()=>Ut,buildVaultsBalanceV2:()=>Ft,buildVaultsBalanceV3:()=>qe,calcExactSwapAmount:()=>ut,calcSingleSideSwap:()=>te,calculateAum:()=>$t,calculateAumV2:()=>Qt,calculateDepositRatioFixTokenA:()=>_e,calculateTotalAumBasedOnQuote:()=>et,checkIsMinOrMaxIndex:()=>St,convertU64BytesToDecimal:()=>Le,default:()=>Ne,defaultProvider:()=>re,dlmm_split_rate:()=>We,estCoinAmountsFromTotalAmount:()=>Kt,feed_map_mainnet:()=>oe,feed_map_testnet:()=>ae,getAmountBalanceByLpAmount:()=>yt,getAmountBalanceByLpAmountV2:()=>pe,getCoinAmountsFromRatio:()=>J,getPositionPriceRange:()=>Ie,getPriceWithFormattedDecimals:()=>Wt,getPrimitivePricesFromBaseQuote:()=>ue,getQuotePerBaseAndBasePerQuote:()=>ft,getShareBufferAssets:()=>ot,getUpdatePriceType:()=>dt,getVaultValidBalances:()=>gt,get_lp_amount_by_liquidity:()=>Te,get_lp_amount_by_tvl:()=>bt,get_share_liquidity_by_amount:()=>rt,initMainnetSDK:()=>ie,initTestnetSDK:()=>se,initVaultSDK:()=>$e,oraclePriceMultiplierDecimal:()=>at,parseVaultVestNFT:()=>zt,parseVaultsVestInfo:()=>Ot,printTransaction:()=>xe,toSuiObjectId:()=>Nt,vaults_mainnet:()=>ee,vaults_testnet:()=>ne});module.exports=Me(ze);var xt=require("@mysten/sui/utils"),Vt=require("@cetusprotocol/aggregator-sdk"),ke=require("@cetusprotocol/common-sdk"),le=require("@cetusprotocol/sui-clmm-sdk");var mt=require("@mysten/sui/transactions"),X=G(require("bn.js"),1),be=require("@cetusprotocol/aggregator-sdk"),A=require("@cetusprotocol/common-sdk"),wt=require("@cetusprotocol/common-sdk"),ge=require("@mysten/sui/utils"),he=G(require("decimal.js"),1);var U=G(require("bn.js"),1),Dt=G(require("decimal.js"),1),B=require("@cetusprotocol/common-sdk");var $=require("@cetusprotocol/common-sdk"),Rt=G(require("bn.js"),1),qt=G(require("decimal.js"),1),St=(b,e,t)=>{if(e==="min"){if(b===$.TickUtil.getMinIndex(t))return!0}else if(b===$.TickUtil.getMaxIndex(t))return!0;return!1};function Le(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 _e(b,e,t,o,i){let a=new Rt.default(10).pow(new Rt.default(o)),{coin_amount_b:n}=$.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(b,e,a,!0,!0,0,t),s=$.TickMath.sqrtPriceX64ToPrice(t,o,i),r=(0,$.d)(a.toString()).mul(s).div(new qt.default(10).pow(o)).mul(new qt.default(10).pow(i)),c=r.add(n.toString()),l=r.div(c),_=(0,$.d)(n.toString()).div(c);return{ratioA:l,ratioB:_}}function J(b,e,t,o,i,a,n){let s=(0,$.d)((0,$.toDecimalsAmount)((0,$.d)(t).mul(b).div(o).toString(),a)).toFixed(0),r=(0,$.d)((0,$.toDecimalsAmount)((0,$.d)(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function Kt(b,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=_e(b,e,t,n,s);return J(r,c,o,i,a,n,s)}var at=10n;function st(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,B.fixCoinType)(n.coin_type_a,!1),coin_type_b:(0,B.fixCoinType)(n.coin_type_b,!1),description:n.description,id:n.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:(0,B.asIntN)(BigInt(n.tick_lower_index.bits)),tick_upper_index:(0,B.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,B.fixCoinType)(d,!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,B.extractStructTagFromType)(e.quote_type).full_address,lp_token_type:(0,B.extractStructTagFromType)(t).type_arguments[0],balances:c,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function xe(b,e=!0){b.getData().commands.forEach((t,o)=>{})}function ft(b,e){let t=(0,B.d)(b).div(e).toString(),o=(0,B.d)(e).div(b).toString();return{quote_per_base:t,base_per_quote:o}}function ue(b,e,t,o){let i=10n**(at+o-t),a=10n**(at+t-o),n=B.MathUtil.checkMulDivFloor(new U.default(b.toString()),new U.default(i.toString()),new U.default(e.toString()),64),s=B.MathUtil.checkMulDivFloor(new U.default(e.toString()),new U.default(a.toString()),new U.default(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 U.default("0");for(let[i,{price:a,value:n}]of Object.entries(b)){let{primitive_quote_price:s}=ue(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=B.MathUtil.checkMulDivFloor(new U.default(s.toString()),new U.default(n),new U.default((BigInt(10)**at).toString()),64);o=o.add(r)}return o.toString()}async function $t(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,B.fixCoinType)(e.quote_type,!1),f=B.TickMath.tickIndexToSqrtPriceX64(r),w=B.TickMath.tickIndexToSqrtPriceX64(c),{coin_amount_a:h,coin_amount_b:v}=B.ClmmPoolUtil.getCoinAmountFromLiquidity(new U.default(l),new U.default(_),new U.default(f),new U.default(w),!1);p.push({coin_type:d,value:h.toString()}),p.push({coin_type:u,value:v.toString()});let C={};p.forEach(V=>{let j=(0,B.fixCoinType)(V.coin_type,!1),D=(0,B.d)(V.value),M=C[j]||0;C[j]=D.add(M).toString()});let y=Object.entries(C).filter(([V,j])=>(0,B.d)(j).gt(0)).map(([V])=>V);if(m&&!y.includes(m)&&y.push(m),y.length===0)return"0";let k=await b.PythPrice.getLatestPrice(y,i),O={};return y.forEach(V=>{let j=k[V];if(j)O[V]={price:j,value:C[V]||"0"};else throw Error(`find ${V} price fail `)}),et(O,m).toString()}function bt(b,e,t){return(0,B.d)(b).eq(0)?e:(0,B.d)(b).mul(e).div(t).toFixed(0,Dt.default.ROUND_HALF_UP)}function Te(b,e,t){return(0,B.d)(b).eq(0)?"0":(0,B.d)(b).mul(e).div(t).toFixed(0,Dt.default.ROUND_HALF_UP)}function rt(b,e,t){return(0,B.d)(b).eq(0)?"0":(0,B.d)(e).mul(t).div(b).toFixed(0,Dt.default.ROUND_HALF_UP)}function ot(b,e,t){let o={};return e.forEach(i=>{let a=rt(t,b,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function Ut(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=rt(t.lp_token_treasury,e,c),_=B.TickMath.tickIndexToSqrtPriceX64(a),d=B.TickMath.tickIndexToSqrtPriceX64(n),u=B.ClmmPoolUtil.getCoinAmountFromLiquidity(new U.default(l),new U.default(o.current_sqrt_price),_,d,!0),p=u.coin_amount_a.toString(),m=u.coin_amount_b.toString(),f=ot(e,t.balances,t.lp_token_treasury),w=(0,B.d)(p).add(i&&f[s]?.value||"0").toFixed(0),h=(0,B.d)(m).add(i&&f[r]?.value||"0").toFixed(0),v=i?Object.values(f).filter(y=>y.coin_type!==s&&y.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:w,amount_b:h,coin_type_a:s,coin_type_b:r,share_buffer_assets:v}}function gt(b,e,t){let o=[];return e.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),b.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),o}function dt(b,e,t){let o=new Set;return b.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function Wt(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 Nt(b){return`0x${Buffer.from(b).toString("hex")}`}function Ie(b,e,t,o,i){let a="0",n="0";return St(b,"min",Number(t))?a="0":a=B.TickMath.tickIndexToPrice(Number(b),o,i).toString(),St(e,"max",Number(t))?n="\u221E":n=B.TickMath.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function Ot(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,B.asIntN)(BigInt(t.tick_lower_index.bits)),tick_upper_index:(0,B.asIntN)(BigInt(t.tick_upper_index.bits)),coin_type_a:(0,B.fixCoinType)(t.coin_type_a.name,!1),coin_type_b:(0,B.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,B.fixCoinType)(e.coin_a.name,!1),coin_type_b:(0,B.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 zt(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"),jt=require("@cetusprotocol/dlmm-sdk");var Ht=G(require("decimal.js"),1),_t=require("@mysten/sui/bcs"),ht=require("@mysten/sui/utils"),Q=G(require("bn.js"),1);function Xt(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,!1),coin_type_b:(0,P.fixCoinType)(s,!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 Re(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,!1),coin_type_b:(0,P.fixCoinType)(b.coin_type_b,!1)}}function Gt(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,!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 Jt(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,!1),value:c}}),a=Re(e);return{id:o,position:a,amounts:i}}function Bt(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:w}=i,h=w.contents.map(y=>{let{key:k,value:O}=y;return{coin_type:(0,P.fixCoinType)(k,!1),value:O}}),v=p.pos0;return{id:r,lp_token_treasury:l.total_supply.value,hard_cap:s,quote_type:v?(0,P.fixCoinType)(v,!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,!1),coin_type_b:(0,P.fixCoinType)(n,!1),lp_token_type:(0,P.extractStructTagFromType)(t).type_arguments[0],version:"v2"}}async function Qt(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:v}=h;for(let C of v){let{lower_bin_id:y,liquidity_shares:k,pool_id:O}=C.position,S=h.certified_pool_obj[O],V=await b.CetusDlmmSDK.Pool.getBinInfo(S.bin_manager.bin_manager_handle,S.active_id,S.bin_step,!1),j=(0,jt.parseLiquidityShares)(k,S.bin_step,y,V);l=(0,P.d)(l).add(j.amount_a.toString()).toFixed(0),_=(0,P.d)(_).add(j.amount_b.toString()).toFixed(0)}}else if(h.type==="CLMM"){let{position_list:v}=h;for(let C of v){let{tick_lower_index:y,tick_upper_index:k,liquidity:O,pool_id:S}=C.position,V=h.certified_pool_obj[S],j=P.TickMath.tickIndexToSqrtPriceX64(y),D=P.TickMath.tickIndexToSqrtPriceX64(k),{coin_amount_a:M,coin_amount_b:L}=P.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(O),new Q.default(V.current_sqrt_price),new Q.default(j),new Q.default(D),!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 v=(0,P.fixCoinType)(h.coin_type,!1),C=(0,P.d)(h.value),y=u[v]||0;u[v]=C.add(y).toString()});let p=Object.entries(u).filter(([h,v])=>(0,P.d)(v).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 v=m[h];if(v)f[h]={price:v,value:u[h]||"0"};else throw Error(`find ${h} price fail `)}),et(f,d).toString()}async function Ft(b,e,t,o,i=!0){let a=await yt(b,e,t,i);return a.owner=o||"0x0",a}async function qe(b,e,t,o,i=!0){let a=await pe(b,e,t,i);return a.owner=o||"0x0",a}async function yt(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 y of a)if(y.type==="DLMM"){let{position_list:k}=y;for(let O of k){let{lower_bin_id:S,upper_bin_id:V,liquidity_shares:j,id:D,pool_id:M}=O.position,L=y.certified_pool_obj[M],{bin_manager:F,bin_step:I,active_id:R}=L,E=await b.CetusDlmmSDK.Pool.getBinInfo(F.bin_manager_handle,R,I,!1),x=(0,jt.parseLiquidityShares)(j.map(nt=>(0,P.d)(nt.toString()).mul(l).toFixed(0,Ht.default.ROUND_HALF_UP).toString()),I,S,E),q=x.amount_a,N=x.amount_b,H=x.bins.filter(nt=>(0,P.d)(nt.liquidity).gt(0)),Tt=H.length>0?H[0].bin_id:x.bins[0].bin_id,It=H.length>0?H[H.length-1].bin_id:x.bins[x.bins.length-1].bin_id,Et={position_id:D,certified_pool_id:L.id,liquidity_shares:j,valid_lower_bin_id:Tt,valid_upper_bin_id:It,original_lower_bin_id:S,original_upper_bin_id:V,position_amount_a:q,position_amount_b:N,coin_type_a:r,coin_type_b:c,bin_infos:{bins:H,amount_a:x.amount_a,amount_b:x.amount_b}};_.push(Et),u=u.add((0,P.d)(q)),p=p.add((0,P.d)(N))}}else if(y.type==="CLMM"){let{position_list:k}=y;for(let O of k){let{tick_lower_index:S,tick_upper_index:V,liquidity:j,id:D,pool_id:M}=O.position,L=y.certified_pool_obj[M],F=(0,P.d)(j).mul(l).toFixed(0),I=P.TickMath.tickIndexToSqrtPriceX64(S),R=P.TickMath.tickIndexToSqrtPriceX64(V),E=P.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(F),new Q.default(L.current_sqrt_price),I,R,!1),x=E.coin_amount_a.toString(),q=E.coin_amount_b.toString(),N={position_id:D,certified_pool_id:L.id,liquidity:F,tick_lower_index:S,tick_upper_index:V,position_amount_a:x,position_amount_b:q};d.push(N),u=u.add((0,P.d)(x)),p=p.add((0,P.d)(q))}}let m=ot(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",w=o&&m[c]?.value||"0",h=u.add(f).toFixed(0),v=p.add(w).toFixed(0),C=o?Object.values(m).filter(y=>y.coin_type!==r&&y.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:v,position_amount_a:u.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:C}}async function pe(b,e,t,o=!0){let{pool:i,markets:a}=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:i.id,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 y of a)if(y.type==="DLMM"){let{position_list:k}=y;for(let O of k){let{lower_bin_id:S,upper_bin_id:V,liquidity_shares:j,id:D,pool_id:M}=O.position,L=y[M],{bin_manager:F,bin_step:I,active_id:R}=L,E=await b.CetusDlmmSDK.Pool.getBinInfo(F.bin_manager_handle,R,I,!1),x=(0,jt.parseLiquidityShares)(j.map(nt=>(0,P.d)(nt.toString()).mul(l).toFixed(0,Ht.default.ROUND_HALF_UP).toString()),I,S,E),q=x.amount_a,N=x.amount_b,H=x.bins.filter(nt=>(0,P.d)(nt.liquidity).gt(0)),Tt=H.length>0?H[0].bin_id:x.bins[0].bin_id,It=H.length>0?H[H.length-1].bin_id:x.bins[x.bins.length-1].bin_id,Et={position_id:D,certified_pool_id:L.id,liquidity_shares:j,valid_lower_bin_id:Tt,valid_upper_bin_id:It,original_lower_bin_id:S,original_upper_bin_id:V,position_amount_a:q,position_amount_b:N,coin_type_a:r,coin_type_b:c,bin_infos:{bins:H,amount_a:x.amount_a,amount_b:x.amount_b}};_.push(Et),u=u.add((0,P.d)(q)),p=p.add((0,P.d)(N))}}else if(y.type==="CLMM"){let{position_list:k}=y;for(let O of k){let{tick_lower_index:S,tick_upper_index:V,liquidity:j,id:D,pool_id:M}=O.position,L=y[M],F=(0,P.d)(j).mul(l).toFixed(0),I=P.TickMath.tickIndexToSqrtPriceX64(S),R=P.TickMath.tickIndexToSqrtPriceX64(V),E=P.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(F),new Q.default(L.current_sqrt_price),I,R,!1),x=E.coin_amount_a.toString(),q=E.coin_amount_b.toString(),N={position_id:D,certified_pool_id:L.id,liquidity:F,tick_lower_index:S,tick_upper_index:V,position_amount_a:x,position_amount_b:q};d.push(N),u=u.add((0,P.d)(x)),p=p.add((0,P.d)(q))}}let m=ot(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",w=o&&m[c]?.value||"0",h=u.add(f).toFixed(0),v=p.add(w).toFixed(0),C=o?Object.values(m).filter(y=>y.coin_type!==r&&y.coin_type!==c):Object.values(m);return{vault_id:i.id,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:h,amount_b:v,position_amount_a:u.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:C}}function Zt(b){let e=_t.bcs.vector(_t.bcs.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return(0,ht.deriveObjectID)(b,"vector<u8>",e)}function Yt(b){let e=_t.bcs.vector(_t.bcs.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return(0,ht.deriveObjectID)(b,"vector<u8>",e)}function Ke(b,e){let t=_t.bcs.Address.serialize(e).toBytes();return(0,ht.deriveDynamicFieldID)(b,"0x2::object::ID",t)}function ut(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 v=r.minus(h),C=c.plus(h.mul(a));return{A:v,B:C,R:C.div(v)}}else{let v=r.plus(h.mul(a)),C=c.minus(h);return{A:v,B:C,R:v.div(C)}}}for(let h=0;h<120;h++){let v=d.plus(u).div(2),{A:C,B:y,R:k}=m(v);if(C.lte(0)||y.lte(0)){u=v;continue}if(k.gt(l))u=v;else if(k.lt(_))d=v;else{if(p=v,(0,P.d)(_).eq(0))break;u=v}}if(!p)return{swap_amount:"0",final_amount_a:r.toFixed(0),final_amount_b:c.toFixed(0)};let{A:f,B:w}=m(p);return{swap_amount:p.toFixed(0),final_amount_a:f.toFixed(0),final_amount_b:w.toFixed(0),best:p.toString()}}function te(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 pt=require("@pythnetwork/pyth-sui-js"),Y=require("@mysten/sui/bcs"),z=require("@cetusprotocol/common-sdk");var ee={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"}]}}},oe={"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 ie(b,e,t){return b&&(ee.fullRpcUrl=b),new Z(ee,e,t)}var ne={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"}]}}},ae={};function se(b,e,t){return b&&(ne.fullRpcUrl=b),new Z(ne,e,t)}var me=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(me||{});function $e(b,e,t){let{env:o,fullNodeUrl:i}=b;return o==="mainnet"?ie(i,e,t):se(i,e,t)}var re=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];function fe(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 Ue=16*1024,ct=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 pt.SuiPriceServiceConnection(d),this.suiPythClient=new pt.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()};fe(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,z.d)(c).mul((0,z.d)(10).pow((0,z.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=Wt(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 pt.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 pt.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(Y.bcs.vector(Y.bcs.U8).serialize(Array.from(s[0]),{maxSize:Ue}).toBytes()),c[0],t.object(z.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(z.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(z.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(z.CLOCK_ADDRESS),t.object(this.versioned_id)]}),n+=1;return t}getFeedInfoByJson(e){let{env:t}=this._sdk.sdkOptions,o=(0,z.fixCoinType)(e,!1);return t==="mainnet"?oe[o]:ae[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:z.TypeNameRaw.serialize({name:(0,z.fixCoinType)(e,!0)}).toBytes()}}),s=Y.bcs.struct("OracleInfo",{price_feed_id:Y.bcs.vector(Y.bcs.U8),price_info_object_id:Y.bcs.Address,last_update_time:Y.bcs.u64(),coin_decimals:Y.bcs.u8()}).parse(n.dynamicField.value.bcs),r={coin_type:e,price_feed_id:Nt(s.price_feed_id),coin_decimals:s.coin_decimals};return this._sdk.updateCache(o,r),r}};var lt=require("@mysten/sui/bcs"),vt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new ct(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 Ut(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 mt.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,ge.normalizeSuiAddress)("0x0")),p=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,f=[],w=[];return u.Transaction?.events?.forEach(h=>{let{bcs:v,eventType:C}=h;if(C===p){let y=lt.bcs.struct("FeeClaimedEvent",{amount_a:lt.bcs.u64(),amount_b:lt.bcs.u64()}).parse(v);f.push({coin_type:(0,A.fixCoinType)(l,!1),value:y.amount_a}),f.push({coin_type:(0,A.fixCoinType)(_,!1),value:y.amount_b})}if(C===m){let y=lt.bcs.struct("RewardClaimedEvent",{amount:lt.bcs.u64(),reward_type:A.TypeNameRaw}).parse(v);w.push({coin_type:(0,A.fixCoinType)(y.reward_type.name,!1),value:y.amount})}}),this._sdk.updateCache(a,{feeList:f,rewarderList:w},10*1e3),{feeList:f,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=>lt.bcs.Address.parse(s.name.bcs));return n.length>0&&((await i.batchGetObjects(n,{json:!0})).forEach(r=>{let c=st(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=st(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=st(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 mt.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(A.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 mt.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(O=>(0,A.fixCoinType)(O.coin_type,!1)),f=dt(m,c.coin_type_a,c.coin_type_b),{published_at:w,configs:h,clmm_configs:v}=this._sdk.sdkOptions.vaults;t=t||new mt.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:`${w}::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(v.global_config_id),t.object(d),t.object(A.CLOCK_ADDRESS)]});let C,y;if(s&&s.swap_result){let{swap_result:O,coin_amount:S,mode:V,swap_slippage:j}=s,{swap_in_amount:D,swap_out_amount:M,route_obj:L}=O,F=wt.CoinAssist.buildCoinWithBalance(BigInt(S),V==="OnlyCoinA"?u:p,t),I=t.splitCoins(F,[D]),R={router:L,slippage:j,txb:t,inputCoin:I},E=await this._sdk.AggregatorClient.fixableRouterSwapV3(R);C=V==="OnlyCoinA"?F:E,y=V==="OnlyCoinA"?E:F}else C=wt.CoinAssist.buildCoinWithBalance(BigInt(i),u,t),y=wt.CoinAssist.buildCoinWithBalance(BigInt(a),p,t);let k=t.moveCall({target:`${w}::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(v.global_config_id),t.object(d),C,y,t.object(A.CLOCK_ADDRESS)]});return n?k: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 mt.Transaction;let{lp_token_type:m,clmm_vault:f,lp_token_treasury:w}=l,{rewarder_infos:h,id:v,coin_type_a:C,coin_type_b:y,liquidity:k}=_,O=h.map(F=>(0,A.fixCoinType)(F.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:O,lp_token_type:m,pool_id:o,clmm_pool_id:v,coin_type_a:C,coin_type_b:y},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:v,coin_type_a:C,coin_type_b:y},t);let S,V=r?(0,A.d)(r.burn_lp_amount).add((0,A.d)(i)).toFixed(0):(0,A.d)(i).toFixed(0),j=(0,A.d)(i).isZero();if(j&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");j?S=r.lp_burn_coin:(S=wt.CoinAssist.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(S,[r.lp_burn_coin]));let[D,M,L]=t.moveCall({target:`${d}::pool::withdraw`,typeArguments:[C,y,m],arguments:[t.object(o),t.object(u.global_config_id),t.object(p.global_config_id),t.object(v),S,t.object(A.CLOCK_ADDRESS)]});if(this.buildWithdrawBufferReward({reward_coin_types:O.filter(F=>![(0,A.fixCoinType)(C,!1),(0,A.fixCoinType)(y,!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",I=F?M:D,R=rt(w,V,k.toString()),E=await this.handleWithSwap(t,I,C,y,V,o,F,n,s,[{poolID:v,ticklower:f.wrapped_position.tick_lower_index,tickUpper:f.wrapped_position.tick_upper_index,deltaLiquidity:Number(R)}],c);if(c&&E)return F?t.mergeCoins(E,[D]):t.mergeCoins(E,[M]),{return_coin_a:F?E:void 0,return_coin_b:F?void 0:E};t.transferObjects([F?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: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,A.d)(f).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let w={from:p,target:m,amount:new X.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(w);if(!h)throw Error("not find Router");if(h.error!==void 0)throw Error(`find Router error : ${h.error}`);let v={router:h,inputCoin:t,slippage:r,txb:e,partner:c},C=await this._sdk.AggregatorClient.fixableRouterSwapV3(v);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),w=f[d],h=f[u];if(!w||!h)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:v,amountB:C}=Kt(l,_,new X.default(c),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=C.toString();break}case"FlexibleBoth":{let{amountA:v,amountB:C}=J((0,A.d)(.5),(0,A.d)(.5),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=C.toString();break}case"OnlyCoinA":{let{amountA:v,amountB:C}=J((0,A.d)(1),(0,A.d)(0),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=C.toString();break}case"OnlyCoinB":{let{amountA:v,amountB:C}=J((0,A.d)(0),(0,A.d)(1),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=C.toString();break}default:throw new Error(`Unsupported deposit mode: ${a}`)}return t&&this.calculateDepositLpAmountBoth(s,r,p,m).then(v=>{t.onSuccess(v,n)}).catch(v=>{t.onError(v,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=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,_,new X.default(d),u,!0,1,new X.default(s)),m=u?(0,A.d)(p.coin_amount_b).div(p.coin_amount_a):(0,A.d)(p.coin_amount_a).div(p.coin_amount_b),f=u?(0,A.d)(s).toString():(0,A.d)(1).div((0,A.d)(s)).toString();try{let k=await this._sdk.VaultsV2.findRouters(u?r:c,u?c:r,d);k&&(f=(0,A.d)(k.swap_out_amount).div(k.swap_in_amount).toString())}catch{}let{swap_amount:w}=ut(d,u,f.toString(),m.toString()),h=(0,A.d)(d).sub(w).toFixed(0),v=await this._sdk.VaultsV2.findRouters(u?r:c,u?c:r,w),C=(0,A.d)(v.swap_out_amount).mul(.999).toFixed(0),y=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,_,new X.default(h),u,!0,1,new X.default(s));return u?y.coin_amount_b=C:y.coin_amount_a=C,{swap_result:v,liquidity_info:y}}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,_=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(c,l,new X.default(o),i,!0,1,new X.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,A.fixCoinType)(t.coin_type_a,!1),r=(0,A.fixCoinType)(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),_=gt(e.balances,l,c),d=await $t(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 w=et(f,e.quote_type);return bt(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=A.TickMath.tickIndexToSqrtPriceX64(c),u=A.TickMath.tickIndexToSqrtPriceX64(l),p=rt(a,o,_),{coin_amount_a:m,coin_amount_b:f}=A.ClmmPoolUtil.getCoinAmountFromLiquidity(new X.default(p),new X.default(n),d,u,!1),w=ot(o,e.balances,a),h=(0,A.d)(m.toString()).add(w[s]?.value||"0").toFixed(0),v=(0,A.d)(f.toString()).add(w[r]?.value||"0").toFixed(0);return{receive_amount_a:h,receive_amount_b:v,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=A.TickMath.tickIndexToSqrtPriceX64(l),p=A.TickMath.tickIndexToSqrtPriceX64(_),m=rt(n,i,d),{coin_amount_a:f,coin_amount_b:w}=A.ClmmPoolUtil.getCoinAmountFromLiquidity(new X.default(m),new X.default(s),u,p,!1),h=await this.pythPrice.getLatestPrice([r,c],!0),v=h[r],C=h[c];if(!v)throw Error(`not find ${r} price`);if(!C)throw Error(`not find ${c} price`);let y=o?C:v,k=o?v:C,{quote_per_base:O}=ft(y.price,k.price),S=ot(i,e.balances,n),V=(0,A.d)(f.toString()).add(S[r]?.value||"0").toFixed(0),j=(0,A.d)(w.toString()).add(S[c]?.value||"0").toFixed(0),D=o?V:j,M=o?j:V,L=(0,A.toDecimalsAmount)((0,A.d)((0,A.fromDecimalsAmount)(M,o?C.coin_decimals:v.coin_decimals)).mul(O).toString(),o?v.coin_decimals:C.coin_decimals).toString(),F=(0,A.d)(D).add(L).toFixed(0);return{remove_amount_a:V,remove_amount_b:j,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:D,swapAmountIn:M,swapAmountOut:(0,A.d)(L).toFixed(0,he.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,be.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 it=require("@cetusprotocol/common-sdk"),ye=require("@mysten/sui/transactions");var Mt=require("@mysten/sui/bcs"),Pt=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:Mt.bcs.Address.serialize(e).toBytes()}});return!Mt.bcs.struct("CetusVaultVesterInfo",{is_pause:Mt.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,it.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=Ot(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=Ot(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,it.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=zt(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,it.getPackagerConfigs)(o),{versioned_id:n,clmm_vest_id:s}=(0,it.getPackagerConfigs)(i);t=t||new ye.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(it.CLOCK_ADDRESS)],typeArguments:[d,u]})}return t}};var ce=require("@mysten/sui/transactions"),tt=G(require("bn.js"),1),we=require("@cetusprotocol/aggregator-sdk"),ve=require("@cetusprotocol/sui-clmm-sdk"),g=require("@cetusprotocol/common-sdk"),Ct=require("@cetusprotocol/common-sdk"),Pe=require("@mysten/sui/utils"),Ce=G(require("decimal.js"),1);var W=require("@cetusprotocol/dlmm-sdk");var T=require("@mysten/sui/bcs"),kt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new ct(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 Ft(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(w=>w.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(w=>w.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 ce.Transaction;await this.buildCollectRewardAndFeePayload(e,_),(await this._sdk.FullClient.sendSimulationTransaction(_,(0,Pe.normalizeSuiAddress)("0x0")))?.Transaction?.events?.forEach(u=>{let{bcs:p,eventType:m}=u;if(m.includes("CollectDlmmFeeEvent")){let f=T.bcs.struct("CollectDlmmFeeEvent",{vault_id:T.bcs.Address,position_id:T.bcs.Address,amount_a:T.bcs.u64(),amount_b:T.bcs.u64(),protocol_fee_a:T.bcs.u64(),protocol_fee_b:T.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=T.bcs.struct("CollectClmmFeeEvent",{vault_id:T.bcs.Address,pool_id:T.bcs.Address,position_id:T.bcs.Address,amount_a:T.bcs.u64(),amount_b:T.bcs.u64(),protocol_fee_a:T.bcs.u64(),protocol_fee_b:T.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=T.bcs.struct("CollectClmmRewardEvent",{vault_id:T.bcs.Address,pool_id:T.bcs.Address,position_id:T.bcs.Address,reward_type:g.TypeNameRaw,amount:T.bcs.u64(),protocol_fee:T.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=T.bcs.struct("CollectDlmmRewardEvent",{vault_id:T.bcs.Address,position_id:T.bcs.Address,reward_type:g.TypeNameRaw,amount:T.bcs.u64(),protocol_fee:T.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=>T.bcs.Address.parse(s.name.bcs));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=Bt(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=Bt(u);i.push(m)}else if(p.includes(`${o.package_id}::pool::Pool`)){let m=st(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,ve.buildPool)(p);n[f.id]=f;let w=`${f.id}_getPoolObject`;this._sdk.CetusClmmSDK.updateCache(w,f)}else if(m.includes(`${d.package_id}::pool::Pool`)){let f=(0,W.parseDlmmPool)(p);s[f.id]=f;let w=`${f.id}_getDlmmPool`;this._sdk.CetusDlmmSDK.updateCache(w,f)}})}return{v1:a,v2:i,clmmPoolMap:n,dlmmPoolMap:s}}async geMarketList(e){let t={},o=[];e.forEach(a=>{let n=Yt(a),s=Zt(a);o.push(n,s)}),(await this._sdk.FullClient.batchGetObjects(o,{json:!0})).forEach(a=>{let n=Xt(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=Gt(n.json);t.push(r)}else if(s?.includes("CLMMPosition")){let r=Jt(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,w=[p,m];for(let y of u)y.type==="DLMM"?y.position_list.forEach(k=>{let{pool_id:O}=k.position,S=y.certified_pool_obj[O],{reward_manager:V}=S,j=V.rewards.map(D=>(0,g.fixCoinType)(D.reward_coin,!1));w=dt(j,p,m)}):y.type==="CLMM"&&y.position_list.forEach(k=>{let{pool_id:O}=k.position,S=y.certified_pool_obj[O],{rewarder_infos:V}=S,j=V.map(D=>(0,g.fixCoinType)(D.coin_type,!1));w=dt([...w,...j],p,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(w,t);for(let y of u)if(y.type==="DLMM"){let{dlmm_pool:k}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:O}=(0,g.getPackagerConfigs)(k),{position_list:S}=y;S.forEach(V=>{let{id:j,pool_id:D}=V.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(D),t.pure.address(j),t.object(O),t.object(i.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}else if(y.type==="CLMM"){let{clmm_pool:k}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:O}=(0,g.getPackagerConfigs)(k),{position_list:S}=y;S.forEach(V=>{let{id:j,pool_id:D}=V.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(D),t.pure.address(j),t.object(O),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,v;if(c&&c.swap_result){let{swap_result:y,coin_amount:k,mode:O,swap_slippage:S}=c,{swap_in_amount:V,route_obj:j}=y,D=Ct.CoinAssist.buildCoinWithBalance(BigInt(k),O==="OnlyCoinA"?p:m,t),M=t.splitCoins(D,[V]),L={router:j,slippage:S,txb:t,inputCoin:M},F=await this._sdk.AggregatorClient.fixableRouterSwapV3(L);h=O==="OnlyCoinA"?D:F,v=O==="OnlyCoinA"?F:D}else h=l||Ct.CoinAssist.buildCoinWithBalance(BigInt(n),p,t),v=_||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,v,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 ce.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:w,configs:h}=this._sdk.sdkOptions.vaultsV2,{config:v}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:C}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,y=t.moveCall({target:`${w}::vault::new_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),p,t.object(h.versioned_id)]}),k=[];for(let D of l)if(D.type==="DLMM"){let{position_list:M}=D;M.forEach(L=>{let{id:F,pool_id:I}=L.position,R=D.certified_pool_obj[I],{reward_manager:E}=R,x=E.rewards.map(q=>(0,g.fixCoinType)(q.reward_coin,!1));k.push(...x),t.moveCall({target:`${w}::vault::withdraw_dlmm`,typeArguments:[d,u,_],arguments:[t.object(o),y,t.object(I),t.pure.address(F),t.object(v.global_config_id),t.object(v.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:F,pool_id:I}=L.position,R=D.certified_pool_obj[I],{rewarder_infos:E}=R,x=E.map(q=>(0,g.fixCoinType)(q.coin_type,!1));k.push(...x),t.moveCall({target:`${w}::vault::withdraw_clmm`,typeArguments:[d,u,_],arguments:[t.object(o),y,t.object(I),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,y),t.moveCall({target:`${w}::vault::finalize_buffer_assets`,typeArguments:[_],arguments:[t.object(o),y,t.object(h.versioned_id)]});let O=new Set;k.forEach(D=>O.add(D)),O.add(d),O.add(u);let S=Array.from(O),V=a!=="FixedOneSide"?[a==="OnlyCoinA"?u:d]:[],j=this.buildWithdrawBufferReward({reward_coin_types:S,pool_id:o,withdraw_cert:y,lp_token_type:_,not_transfer_coin_types:V},t);if(t.moveCall({target:`${w}::vault::destroy_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),y,t.object(h.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let D=a==="OnlyCoinA",M=D?u:d,L=j.find(F=>F.coin_type===M).reward_coin_object_id;await this.handleWithSwap(t,L,d,u,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,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 tt.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 w={router:f,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: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 w="0",h="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:C,position_amount_b_rate:y}=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:k,amountB:O}=J(C,y,o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=k,h=O;break}case"OnlyCoinA":{let{amountA:C,amountB:y}=J((0,g.d)(1),(0,g.d)(0),o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=C,h=y;break}case"OnlyCoinB":{let{amountA:C,amountB:y}=J((0,g.d)(0),(0,g.d)(1),o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=C,h=y;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,u=_,p=d,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,f=o==="OnlyCoinA",w=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(u,p,new tt.default(m),f,!0,1,new tt.default(r)),h=f?(0,g.d)(w.coin_amount_b).div(w.coin_amount_a):(0,g.d)(w.coin_amount_a).div(w.coin_amount_b),v=f?(0,g.d)(r).toString():(0,g.d)(1).div((0,g.d)(r)).toString();try{let V=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,m);V&&(v=(0,g.d)(V.swap_out_amount).div(V.swap_in_amount).toString())}catch{}let{swap_amount:C}=ut(m,f,v.toString(),h.toString()),y=(0,g.d)(m).sub(C).toFixed(0),k=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,C),O=(0,g.d)(k.swap_out_amount).mul(.999).toFixed(0),S=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(u,p,new tt.default(y),f,!0,1,new tt.default(r));return f?S.coin_amount_b=O:S.coin_amount_a=O,{swap_result:k,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:w}=m,h=_?i:a,v=_?a:i,C=(0,g.fromDecimalsAmount)(w,h),y=(0,g.fromDecimalsAmount)(f,v),k=(0,g.d)(y).div(C).toString(),O=await this.pythPrice.getLatestPrice([r,c],!0),S=O[r],V=O[c];if(!S||!V)throw new Error(`not find ${r} or ${c} price`);let j=te(_?C:"0",_?"0":C,S.price,V.price,k,_),D=(0,g.d)((0,g.toDecimalsAmount)(j,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),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:w,bin_step:h}=m,v=W.BinUtils.getPricePerLamportFromBinId(m.active_id,m.bin_step),C=(0,g.d)(v).mul(1-.05),y=(0,g.d)(v).mul(1+.05),k=W.BinUtils.getBinIdFromLamportPrice(C.toString(),m.bin_step,!1),O=W.BinUtils.getBinIdFromLamportPrice(y.toString(),m.bin_step,!1),S=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:k,upper_bin_id:O,active_bin_of_pool:f,strategy_type:W.StrategyType.Spot}),V=_?(0,g.d)(S.amount_b).div(S.amount_a):(0,g.d)(S.amount_a).div(S.amount_b),j=_?W.BinUtils.getPricePerLamportFromBinId(w,h):(0,g.d)(1).div(W.BinUtils.getPricePerLamportFromBinId(w,h)).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&&(j=(0,g.d)(N.swap_out_amount).div(N.swap_in_amount).toString())}catch{}let{swap_amount:D,final_amount_a:M,final_amount_b:L}=ut(l,_,j,V.toString()),F=(0,g.d)(l).sub(D).toFixed(0),I=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,D),R=(0,g.d)(I.swap_out_amount).mul(.999).toFixed(0),E=_?F:R,x=_?R:F,q=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:E,amount_b:x,active_id:w,bin_step:h,lower_bin_id:k,upper_bin_id:O,active_bin_of_pool:f,strategy_type:W.StrategyType.Spot});return _?q.amount_b=I.swap_out_amount:q.amount_a=I.swap_out_amount,{swap_result:I,liquidity_info:q}}}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 Ft(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=W.BinUtils.getPricePerLamportFromBinId(t.active_id,t.bin_step),_=(0,g.d)(l).mul(1-.05),d=(0,g.d)(l).mul(1+.05),u=W.BinUtils.getBinIdFromLamportPrice(_.toString(),t.bin_step,!1),p=W.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:W.StrategyType.Spot,active_bin_of_pool:c},f=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo(m),{amount_a:w,amount_b:h}=f;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:u}=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(s,r,new tt.default(i),o,!0,1,new tt.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=gt(e.buffer_assets,[...d,...p],[..._,...u]),f=await Qt(this._sdk,e.id,m,!0),w=await this.pythPrice.getLatestPrice([c,l],!0),h=w[c],v=w[l];if(!h)throw Error(`not find ${c} price`);if(!v)throw Error(`not find ${l} price`);let C={};C[c]={price:h,value:t.toString()},C[l]={price:v,value:o.toString()};let y=et(C,n);return bt(i,y,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 yt(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 yt(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}=ft(_.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(),w=(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,Ce.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,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,we.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 tt.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=G(require("@cetusprotocol/dlmm-sdk"),1);var K=require("@cetusprotocol/common-sdk"),Lt=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:w,coin_type_b:h}=p,v=n?(0,K.d)(_).sub(n.burn_lp_amount).toFixed(0).toString():_,{return_coin_a:C,return_coin_b:y}=await this.sdk.Vaults.buildWithdrawPayload({pool_id:c.vault_id,burn_lp_amount:v,mode:"FixedOneSide",slippage:a,return_coin:!0,extra_burn:n},t),k={[(0,K.fixCoinType)(w,!1)]:C,[(0,K.fixCoinType)(h,!1)]:y},{coin_output_a:O,coin_output_b:S}=d,{from_coin_type:V,from_coin_amount:j,route_obj:D,to_coin_type:M}=O;if(D){let{to_coin:F}=await this.buildSwapAssetsTx({from_coin_type:V,swap_in_amount:j,liquidity_slippage:a,route_obj:D.route_obj,tx:t,from_coin_object_id:k[(0,K.fixCoinType)(V,!1)]});k[(0,K.fixCoinType)(M,!1)]=F}if(S.route_obj){let{from_coin_type:F,from_coin_amount:I,route_obj:R,to_coin_type:E}=S,{to_coin:x}=await this.buildSwapAssetsTx({from_coin_type:F,swap_in_amount:I,liquidity_slippage:a,route_obj:R.route_obj,tx:t,from_coin_object_id:k[(0,K.fixCoinType)(F,!1)]});k[(0,K.fixCoinType)(E,!1)]=x}return await this._sdk.VaultsV2.buildDepositPayload({pool_id:l.vault_id,amount_a:s,amount_b:r,return_lp_coin:i,coin_a_input:k[(0,K.fixCoinType)(f.coin_type_a,!1)],coin_b_input:k[(0,K.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,w=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:w,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||K.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,K.fixCoinType)(t.coin_type_a,!1),a=(0,K.fixCoinType)(t.coin_type_b,!1),n=(0,K.fixCoinType)(o.coin_type_a,!1),s=(0,K.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,K.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,K.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 Z=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=re),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||le.CetusClmmSDK.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||le.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 vt(this),this._vaultsV2=new kt(this),this._migrate=new Lt(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,xt.normalizeSuiAddress)("0x0"),client:this.FullClient,env:e.env==="testnet"?Vt.Env.Testnet:Vt.Env.Mainnet,pythUrls:n}),this._vest=new Pt(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,xt.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=ke.CACHE_TIME_24H){this.CetusClmmSDK.updateCache(e,t,o)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var We=.2;var Ne=Z;0&&(module.exports={PythPriceModule,SdkEnv,VaultsModule,VaultsModuleV2,VestModule,VolatileVaultsSDK,buildCLMMMarketId,buildCLMMMarketPosition,buildDLMMMarketId,buildDLMMMarketPosition,buildDLMMPositionId,buildPoolData,buildPoolV2Data,buildVaultMarket,buildVaultsBalance,buildVaultsBalanceV2,buildVaultsBalanceV3,calcExactSwapAmount,calcSingleSideSwap,calculateAum,calculateAumV2,calculateDepositRatioFixTokenA,calculateTotalAumBasedOnQuote,checkIsMinOrMaxIndex,convertU64BytesToDecimal,defaultProvider,dlmm_split_rate,estCoinAmountsFromTotalAmount,feed_map_mainnet,feed_map_testnet,getAmountBalanceByLpAmount,getAmountBalanceByLpAmountV2,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 we=Object.create;var kt=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var Ve=(b,e)=>{for(var t in e)kt(b,t,{get:e[t],enumerable:!0})},ne=(b,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ce(e))!ke.call(b,i)&&i!==t&&kt(b,i,{get:()=>e[i],enumerable:!(o=ve(e,i))||o.enumerable});return b};var z=(b,e,t)=>(t=b!=null?we(Pe(b)):{},ne(e||!b||!b.__esModule?kt(t,"default",{value:b,enumerable:!0}):t,b)),Ae=b=>ne(kt({},"__esModule",{value:!0}),b);var We={};Ve(We,{PythPriceModule:()=>st,SdkEnv:()=>de,VaultsModule:()=>yt,VaultsModuleV2:()=>Ct,VestModule:()=>wt,VolatileVaultsSDK:()=>G,buildCLMMMarketId:()=>Jt,buildCLMMMarketPosition:()=>Ht,buildDLMMMarketId:()=>zt,buildDLMMMarketPosition:()=>Nt,buildDLMMPositionId:()=>Te,buildPoolData:()=>nt,buildPoolV2Data:()=>Ot,buildVaultMarket:()=>Ut,buildVaultsBalance:()=>Kt,buildVaultsBalanceV2:()=>jt,buildVaultsBalanceV3:()=>xe,calcExactSwapAmount:()=>_t,calcSingleSideSwap:()=>Qt,calculateAum:()=>qt,calculateAumV2:()=>Xt,calculateDepositRatioFixTokenA:()=>ae,calculateTotalAumBasedOnQuote:()=>Y,checkIsMinOrMaxIndex:()=>Vt,convertU64BytesToDecimal:()=>Se,default:()=>$e,defaultProvider:()=>ee,dlmm_split_rate:()=>Ke,estCoinAmountsFromTotalAmount:()=>Et,feed_map_mainnet:()=>Ie,feed_map_testnet:()=>Ee,getAmountBalanceByLpAmount:()=>gt,getAmountBalanceByLpAmountV2:()=>re,getCoinAmountsFromRatio:()=>J,getPositionPriceRange:()=>Me,getPriceWithFormattedDecimals:()=>je,getPrimitivePricesFromBaseQuote:()=>se,getQuotePerBaseAndBasePerQuote:()=>pt,getShareBufferAssets:()=>tt,getUpdatePriceType:()=>ct,getVaultValidBalances:()=>ft,get_lp_amount_by_liquidity:()=>Oe,get_lp_amount_by_tvl:()=>mt,get_share_liquidity_by_amount:()=>at,initMainnetSDK:()=>Zt,initTestnetSDK:()=>te,initVaultSDK:()=>qe,oraclePriceMultiplierDecimal:()=>it,parseVaultVestNFT:()=>$t,parseVaultsVestInfo:()=>St,printTransaction:()=>De,toSuiObjectId:()=>Be,vaults_mainnet:()=>Gt,vaults_testnet:()=>Yt});module.exports=Ae(We);var Ft=require("@mysten/sui/utils"),Pt=require("@cetusprotocol/aggregator-sdk"),ge=require("@cetusprotocol/common-sdk"),ie=require("@cetusprotocol/sui-clmm-sdk");var ut=require("@mysten/sui/transactions"),X=z(require("bn.js"),1),ce=require("@cetusprotocol/aggregator-sdk"),A=require("@cetusprotocol/common-sdk"),ht=require("@cetusprotocol/common-sdk"),le=require("@mysten/sui/utils"),_e=z(require("decimal.js"),1);var W=z(require("bn.js"),1),At=z(require("decimal.js"),1),B=require("@cetusprotocol/common-sdk");var $=require("@cetusprotocol/common-sdk"),Rt=z(require("bn.js"),1),It=z(require("decimal.js"),1),Vt=(b,e,t)=>{if(e==="min"){if(b===$.TickUtil.getMinIndex(t))return!0}else if(b===$.TickUtil.getMaxIndex(t))return!0;return!1};function Se(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 ae(b,e,t,o,i){let a=new Rt.default(10).pow(new Rt.default(o)),{coin_amount_b:n}=$.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(b,e,a,!0,!0,0,t),s=$.TickMath.sqrtPriceX64ToPrice(t,o,i),r=(0,$.d)(a.toString()).mul(s).div(new It.default(10).pow(o)).mul(new It.default(10).pow(i)),c=r.add(n.toString()),l=r.div(c),d=(0,$.d)(n.toString()).div(c);return{ratioA:l,ratioB:d}}function J(b,e,t,o,i,a,n){let s=(0,$.d)((0,$.toDecimalsAmount)((0,$.d)(t).mul(b).div(o).toString(),a)).toFixed(0),r=(0,$.d)((0,$.toDecimalsAmount)((0,$.d)(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function Et(b,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=ae(b,e,t,n,s);return J(r,c,o,i,a,n,s)}var it=10n;function nt(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,B.fixCoinType)(n.coin_type_a,!1),coin_type_b:(0,B.fixCoinType)(n.coin_type_b,!1),description:n.description,id:n.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:(0,B.asIntN)(BigInt(n.tick_lower_index.bits)),tick_upper_index:(0,B.asIntN)(BigInt(n.tick_upper_index.bits)),url:n.url}},{balances:r}=e.buffer_assets,c=r.contents.map(d=>{let{key:u,value:_}=d;return{coin_type:(0,B.fixCoinType)(u,!1),value:_}});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,B.extractStructTagFromType)(e.quote_type).full_address,lp_token_type:(0,B.extractStructTagFromType)(t).type_arguments[0],balances:c,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function De(b,e=!0){b.getData().commands.forEach((t,o)=>{})}function pt(b,e){let t=(0,B.d)(b).div(e).toString(),o=(0,B.d)(e).div(b).toString();return{quote_per_base:t,base_per_quote:o}}function se(b,e,t,o){let i=10n**(it+o-t),a=10n**(it+t-o),n=B.MathUtil.checkMulDivFloor(new W.default(b.toString()),new W.default(i.toString()),new W.default(e.toString()),64),s=B.MathUtil.checkMulDivFloor(new W.default(e.toString()),new W.default(a.toString()),new W.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 W.default("0");for(let[i,{price:a,value:n}]of Object.entries(b)){let{primitive_quote_price:s}=se(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=B.MathUtil.checkMulDivFloor(new W.default(s.toString()),new W.default(n),new W.default((BigInt(10)**it).toString()),64);o=o.add(r)}return o.toString()}async function qt(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:d,coin_type_a:u,coin_type_b:_}=t,p=[...o],m=n&&(0,B.fixCoinType)(e.quote_type,!1),f=B.TickMath.tickIndexToSqrtPriceX64(r),w=B.TickMath.tickIndexToSqrtPriceX64(c),{coin_amount_a:h,coin_amount_b:v}=B.ClmmPoolUtil.getCoinAmountFromLiquidity(new W.default(l),new W.default(d),new W.default(f),new W.default(w),!1);p.push({coin_type:u,value:h.toString()}),p.push({coin_type:_,value:v.toString()});let P={};p.forEach(V=>{let j=(0,B.fixCoinType)(V.coin_type,!1),D=(0,B.d)(V.value),F=P[j]||0;P[j]=D.add(F).toString()});let y=Object.entries(P).filter(([V,j])=>(0,B.d)(j).gt(0)).map(([V])=>V);if(m&&!y.includes(m)&&y.push(m),y.length===0)return"0";let k=await b.PythPrice.getLatestPrice(y,i),O={};return y.forEach(V=>{let j=k[V];if(j)O[V]={price:j,value:P[V]||"0"};else throw Error(`find ${V} price fail `)}),Y(O,m).toString()}function mt(b,e,t){return(0,B.d)(b).eq(0)?e:(0,B.d)(b).mul(e).div(t).toFixed(0,At.default.ROUND_HALF_UP)}function Oe(b,e,t){return(0,B.d)(b).eq(0)?"0":(0,B.d)(b).mul(e).div(t).toFixed(0,At.default.ROUND_HALF_UP)}function at(b,e,t){return(0,B.d)(b).eq(0)?"0":(0,B.d)(e).mul(t).div(b).toFixed(0,At.default.ROUND_HALF_UP)}function tt(b,e,t){let o={};return e.forEach(i=>{let a=at(t,b,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function Kt(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=at(t.lp_token_treasury,e,c),d=B.TickMath.tickIndexToSqrtPriceX64(a),u=B.TickMath.tickIndexToSqrtPriceX64(n),_=B.ClmmPoolUtil.getCoinAmountFromLiquidity(new W.default(l),new W.default(o.current_sqrt_price),d,u,!0),p=_.coin_amount_a.toString(),m=_.coin_amount_b.toString(),f=tt(e,t.balances,t.lp_token_treasury),w=(0,B.d)(p).add(i&&f[s]?.value||"0").toFixed(0),h=(0,B.d)(m).add(i&&f[r]?.value||"0").toFixed(0),v=i?Object.values(f).filter(y=>y.coin_type!==s&&y.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:w,amount_b:h,coin_type_a:s,coin_type_b:r,share_buffer_assets:v}}function ft(b,e,t){let o=[];return e.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),b.forEach(i=>{(0,B.d)(i.value).gt(0)&&o.push(i)}),o}function ct(b,e,t){let o=new Set;return b.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function je(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 Be(b){return`0x${Buffer.from(b).toString("hex")}`}function Me(b,e,t,o,i){let a="0",n="0";return Vt(b,"min",Number(t))?a="0":a=B.TickMath.tickIndexToPrice(Number(b),o,i).toString(),Vt(e,"max",Number(t))?n="\u221E":n=B.TickMath.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function St(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,B.asIntN)(BigInt(t.tick_lower_index.bits)),tick_upper_index:(0,B.asIntN)(BigInt(t.tick_upper_index.bits)),coin_type_a:(0,B.fixCoinType)(t.coin_type_a.name,!1),coin_type_b:(0,B.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,B.fixCoinType)(e.coin_a.name,!1),coin_type_b:(0,B.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 C=require("@cetusprotocol/common-sdk"),Dt=require("@cetusprotocol/dlmm-sdk");var Wt=z(require("decimal.js"),1),lt=require("@mysten/sui/bcs"),bt=require("@mysten/sui/utils"),Q=z(require("bn.js"),1);function Ut(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(u=>u.key),positions_handle:{id:i.id,size:i.size},position_list:[],coin_type_a:(0,C.fixCoinType)(n,!1),coin_type_b:(0,C.fixCoinType)(s,!1),vault_id:r,position_keys:c.contents}}catch{return}}function Fe(b){return{uri:b.uri,index:b.index,id:b.id,name:b.name,pool_id:b.pool_id,lower_bin_id:(0,C.asIntN)(BigInt(b.lower_bin_id.bits)),upper_bin_id:(0,C.asIntN)(BigInt(b.upper_bin_id.bits)),liquidity_shares:b.liquidity_shares,description:b.description,coin_type_a:(0,C.fixCoinType)(b.coin_type_a,!1),coin_type_b:(0,C.fixCoinType)(b.coin_type_b,!1)}}function Le(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,C.asIntN)(BigInt(b.tick_lower_index.bits)),tick_upper_index:(0,C.asIntN)(BigInt(b.tick_upper_index.bits)),name:b.name,coin_type_a:(0,C.fixCoinType)(b.coin_type_a,!1),coin_type_b:(0,C.fixCoinType)(b.coin_type_b,!1)}}function Nt(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(d=>{let{key:u,value:_}=d;return{coin_type:(0,C.fixCoinType)(u,!1),value:_}}),a=Fe(e),n=a.lower_bin_id,s=a.liquidity_shares.map((d,u)=>({bin_id:n+u,liquidity:d})).filter(d=>(0,C.d)(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 Ht(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(s=>{let{key:r,value:c}=s;return{coin_type:(0,C.fixCoinType)(r,!1),value:c}}),a=Le(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:d,protocol_fee_rate:u,protocol_fees:_,quote_type:p}=e,m=(Number(o)&1)!==0,f=(Number(o)&2)!==0,{balances:w}=i,h=w.contents.map(y=>{let{key:k,value:O}=y;return{coin_type:(0,C.fixCoinType)(k,!1),value:O}}),v=p.pos0;return{id:r,lp_token_treasury:l.total_supply.value,hard_cap:s,quote_type:v?(0,C.fixCoinType)(v,!1):void 0,protocol_fee_rate:u,buffer_assets:h,protocol_fees_handle:{id:_.id,size:_.size},markets_handle:{id:d.id,size:d.size},markets:[],action_status:{is_deposit_allowed:m,is_withdraw_allowed:f},is_multiple_pool:!1,last_aum:c,coin_type_a:(0,C.fixCoinType)(a,!1),coin_type_b:(0,C.fixCoinType)(n,!1),lp_token_type:(0,C.extractStructTagFromType)(t).type_arguments[0],version:"v2"}}async function Xt(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",d="0";for(let h of a)if(h.type==="DLMM"){let{position_list:v}=h;for(let P of v){let{lower_bin_id:y,liquidity_shares:k,pool_id:O}=P.position,S=h.certified_pool_obj[O],V=await b.CetusDlmmSDK.Pool.getBinInfo(S.bin_manager.bin_manager_handle,S.active_id,S.bin_step,!1),j=(0,Dt.parseLiquidityShares)(k,S.bin_step,y,V);l=(0,C.d)(l).add(j.amount_a.toString()).toFixed(0),d=(0,C.d)(d).add(j.amount_b.toString()).toFixed(0)}}else if(h.type==="CLMM"){let{position_list:v}=h;for(let P of v){let{tick_lower_index:y,tick_upper_index:k,liquidity:O,pool_id:S}=P.position,V=h.certified_pool_obj[S],j=C.TickMath.tickIndexToSqrtPriceX64(y),D=C.TickMath.tickIndexToSqrtPriceX64(k),{coin_amount_a:F,coin_amount_b:L}=C.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(O),new Q.default(V.current_sqrt_price),new Q.default(j),new Q.default(D),!1);l=(0,C.d)(l).add(F.toString()).toFixed(0),d=(0,C.d)(d).add(L.toString()).toFixed(0)}}let u=n&&(0,C.fixCoinType)(n,!1);c.push({coin_type:s,value:l}),c.push({coin_type:r,value:d});let _={};c.forEach(h=>{let v=(0,C.fixCoinType)(h.coin_type,!1),P=(0,C.d)(h.value),y=_[v]||0;_[v]=P.add(y).toString()});let p=Object.entries(_).filter(([h,v])=>(0,C.d)(v).gt(0)).map(([h])=>h);if(u&&!p.includes(u)&&p.push(u),p.length===0)return"0";let m=await b.VaultsV2.PythPrice.getLatestPrice(p,o),f={};return p.forEach(h=>{let v=m[h];if(v)f[h]={price:v,value:_[h]||"0"};else throw Error(`find ${h} price fail `)}),Y(f,u).toString()}async function jt(b,e,t,o,i=!0){let a=await gt(b,e,t,i);return a.owner=o||"0x0",a}async function xe(b,e,t,o,i=!0){let a=await re(b,e,t,i);return a.owner=o||"0x0",a}async function gt(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,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=[],u=[],_=(0,C.d)(0),p=(0,C.d)(0);for(let y of a)if(y.type==="DLMM"){let{position_list:k}=y;for(let O of k){let{lower_bin_id:S,upper_bin_id:V,liquidity_shares:j,id:D,pool_id:F}=O.position,L=y.certified_pool_obj[F],{bin_manager:M,bin_step:R,active_id:E}=L,I=await b.CetusDlmmSDK.Pool.getBinInfo(M.bin_manager_handle,E,R,!1),x=(0,Dt.parseLiquidityShares)(j.map(ot=>(0,C.d)(ot.toString()).mul(l).toFixed(0,Wt.default.ROUND_HALF_UP).toString()),R,S,I),q=x.amount_a,N=x.amount_b,H=x.bins.filter(ot=>(0,C.d)(ot.liquidity).gt(0)),Lt=H.length>0?H[0].bin_id:x.bins[0].bin_id,xt=H.length>0?H[H.length-1].bin_id:x.bins[x.bins.length-1].bin_id,Tt={position_id:D,certified_pool_id:L.id,liquidity_shares:j,valid_lower_bin_id:Lt,valid_upper_bin_id:xt,original_lower_bin_id:S,original_upper_bin_id:V,position_amount_a:q,position_amount_b:N,coin_type_a:r,coin_type_b:c,bin_infos:{bins:H,amount_a:x.amount_a,amount_b:x.amount_b}};d.push(Tt),_=_.add((0,C.d)(q)),p=p.add((0,C.d)(N))}}else if(y.type==="CLMM"){let{position_list:k}=y;for(let O of k){let{tick_lower_index:S,tick_upper_index:V,liquidity:j,id:D,pool_id:F}=O.position,L=y.certified_pool_obj[F],M=(0,C.d)(j).mul(l).toFixed(0),R=C.TickMath.tickIndexToSqrtPriceX64(S),E=C.TickMath.tickIndexToSqrtPriceX64(V),I=C.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(M),new Q.default(L.current_sqrt_price),R,E,!1),x=I.coin_amount_a.toString(),q=I.coin_amount_b.toString(),N={position_id:D,certified_pool_id:L.id,liquidity:M,tick_lower_index:S,tick_upper_index:V,position_amount_a:x,position_amount_b:q};u.push(N),_=_.add((0,C.d)(x)),p=p.add((0,C.d)(q))}}let m=tt(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",w=o&&m[c]?.value||"0",h=_.add(f).toFixed(0),v=p.add(w).toFixed(0),P=o?Object.values(m).filter(y=>y.coin_type!==r&&y.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:v,position_amount_a:_.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:d,clmm_balances:u,share_buffer_assets:P}}async function re(b,e,t,o=!0){let{pool:i,markets:a}=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:i.id,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=[],u=[],_=(0,C.d)(0),p=(0,C.d)(0);for(let y of a)if(y.type==="DLMM"){let{position_list:k}=y;for(let O of k){let{lower_bin_id:S,upper_bin_id:V,liquidity_shares:j,id:D,pool_id:F}=O.position,L=y[F],{bin_manager:M,bin_step:R,active_id:E}=L,I=await b.CetusDlmmSDK.Pool.getBinInfo(M.bin_manager_handle,E,R,!1),x=(0,Dt.parseLiquidityShares)(j.map(ot=>(0,C.d)(ot.toString()).mul(l).toFixed(0,Wt.default.ROUND_HALF_UP).toString()),R,S,I),q=x.amount_a,N=x.amount_b,H=x.bins.filter(ot=>(0,C.d)(ot.liquidity).gt(0)),Lt=H.length>0?H[0].bin_id:x.bins[0].bin_id,xt=H.length>0?H[H.length-1].bin_id:x.bins[x.bins.length-1].bin_id,Tt={position_id:D,certified_pool_id:L.id,liquidity_shares:j,valid_lower_bin_id:Lt,valid_upper_bin_id:xt,original_lower_bin_id:S,original_upper_bin_id:V,position_amount_a:q,position_amount_b:N,coin_type_a:r,coin_type_b:c,bin_infos:{bins:H,amount_a:x.amount_a,amount_b:x.amount_b}};d.push(Tt),_=_.add((0,C.d)(q)),p=p.add((0,C.d)(N))}}else if(y.type==="CLMM"){let{position_list:k}=y;for(let O of k){let{tick_lower_index:S,tick_upper_index:V,liquidity:j,id:D,pool_id:F}=O.position,L=y[F],M=(0,C.d)(j).mul(l).toFixed(0),R=C.TickMath.tickIndexToSqrtPriceX64(S),E=C.TickMath.tickIndexToSqrtPriceX64(V),I=C.ClmmPoolUtil.getCoinAmountFromLiquidity(new Q.default(M),new Q.default(L.current_sqrt_price),R,E,!1),x=I.coin_amount_a.toString(),q=I.coin_amount_b.toString(),N={position_id:D,certified_pool_id:L.id,liquidity:M,tick_lower_index:S,tick_upper_index:V,position_amount_a:x,position_amount_b:q};u.push(N),_=_.add((0,C.d)(x)),p=p.add((0,C.d)(q))}}let m=tt(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",w=o&&m[c]?.value||"0",h=_.add(f).toFixed(0),v=p.add(w).toFixed(0),P=o?Object.values(m).filter(y=>y.coin_type!==r&&y.coin_type!==c):Object.values(m);return{vault_id:i.id,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:h,amount_b:v,position_amount_a:_.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:d,clmm_balances:u,share_buffer_assets:P}}function zt(b){let e=lt.bcs.vector(lt.bcs.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return(0,bt.deriveObjectID)(b,"vector<u8>",e)}function Jt(b){let e=lt.bcs.vector(lt.bcs.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return(0,bt.deriveObjectID)(b,"vector<u8>",e)}function Te(b,e){let t=lt.bcs.Address.serialize(e).toBytes();return(0,bt.deriveDynamicFieldID)(b,"0x2::object::ID",t)}function _t(b,e,t,o){let i=(0,C.d)(b),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,d=(0,C.d)(n).mul(.999),u=(0,C.d)(0),_=s,p=null;function m(h){if(e){let v=r.minus(h),P=c.plus(h.mul(a));return{A:v,B:P,R:P.div(v)}}else{let v=r.plus(h.mul(a)),P=c.minus(h);return{A:v,B:P,R:v.div(P)}}}for(let h=0;h<120;h++){let v=u.plus(_).div(2),{A:P,B:y,R:k}=m(v);if(P.lte(0)||y.lte(0)){_=v;continue}if(k.gt(l))_=v;else if(k.lt(d))u=v;else{if(p=v,(0,C.d)(d).eq(0))break;_=v}}if(!p)return{swap_amount:"0",final_amount_a:r.toFixed(0),final_amount_b:c.toFixed(0)};let{A:f,B:w}=m(p);return{swap_amount:p.toFixed(0),final_amount_a:f.toFixed(0),final_amount_b:w.toFixed(0),best:p.toString()}}function Qt(b,e,t,o,i,a){if(a){let n=(0,C.d)(b).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)(b).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 dt=require("@cetusprotocol/common-sdk");function Re(b,e){let{primary:t,secondary:o}=b.hermes_service_urls,i=[t,o].filter(Boolean);return{pyth_package_id:b.pyth_package_id,pyth_published_at:b.pyth_published_at,pyth_state_id:b.pyth_state_id,wormhole_state_id:b.wormhole_state_id,hermes_service_urls:i,feed_info_handle:e}}var st=class{_sdk;_pyth;pythConfigs;global_config_id;pyth_oracle_id;vaults_published_at;versioned_id;isV2;constructor(e,t,o,i,a,n,s,r){this._sdk=e,this.pythConfigs=t,this.vaults_published_at=o,this.global_config_id=i,this.pyth_oracle_id=a,this.versioned_id=n,this.isV2=r,this._pyth=new dt.PythPriceModule(e.FullClient,Re(t,s))}get sdk(){return this._sdk}getFeedInfoList(e){return this._pyth.getFeedInfoList(e)}priceCheck(e,t=60){return this._pyth.priceCheck(e,t)}getLatestPrice(e,t=!1){return this._pyth.getLatestPrice(e,t)}getFeedInfo(e,t){return this._pyth.getFeedInfo(e,t)}getFeedInfoByJson(e){return this._pyth.getFeedInfoByJson(e)}async buildUpdatePythPricePayload(e,t){let{pyth_state_id:o}=this.pythConfigs;return this._pyth.buildUpdatePythPricePayload(e,t,({tx:i,coinType:a,priceUpdatesHotPotato:n,priceInfoObjectId:s})=>{if(this.isV2){let[c]=i.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[a],arguments:[i.object(this.pyth_oracle_id),i.object(o),n,i.object(s),i.object(dt.CLOCK_ADDRESS),i.object(this.versioned_id)]});return c}let[r]=i.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[a],arguments:[i.object(this.pyth_oracle_id),i.object(this.global_config_id),i.object(o),n,i.object(s),i.object(dt.CLOCK_ADDRESS)]});return r})}async buildUpdatePythPricePayloadV2(e,t){return this._pyth.buildUpdatePythPricePayloadV2(e,t,({tx:o,coinType:i,priceInfoObjectId:a})=>{o.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price_into_pyth_oracle`,typeArguments:[i],arguments:[o.object(this.pyth_oracle_id),o.object(a),o.object(dt.CLOCK_ADDRESS),o.object(this.versioned_id)]})})}};var rt=require("@mysten/sui/bcs"),yt=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 Kt(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:d}=i,u=new ut.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},u),this.buildCollectFeePayload({lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:d},u);let _=await this._sdk.FullClient.sendSimulationTransaction(u,(0,le.normalizeSuiAddress)("0x0")),p=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,f=[],w=[];return _.Transaction?.events?.forEach(h=>{let{bcs:v,eventType:P}=h;if(P===p){let y=rt.bcs.struct("FeeClaimedEvent",{amount_a:rt.bcs.u64(),amount_b:rt.bcs.u64()}).parse(v);f.push({coin_type:(0,A.fixCoinType)(l,!1),value:y.amount_a}),f.push({coin_type:(0,A.fixCoinType)(d,!1),value:y.amount_b})}if(P===m){let y=rt.bcs.struct("RewardClaimedEvent",{amount:rt.bcs.u64(),reward_type:A.TypeNameRaw}).parse(v);w.push({coin_type:(0,A.fixCoinType)(y.reward_type.name,!1),value:y.amount})}}),this._sdk.updateCache(a,{feeList:f,rewarderList:w},10*1e3),{feeList:f,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=>rt.bcs.Address.parse(s.name.bcs));return n.length>0&&((await i.batchGetObjects(n,{json:!0})).forEach(r=>{let c=nt(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=nt(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=nt(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:d}=this._sdk.sdkOptions.vaults;return t=t||new ut.Transaction,r.forEach(u=>{t.moveCall({target:`${c}::pool::collect_reward`,typeArguments:[o,i,s,u],arguments:[t.object(a),t.object(l.global_config_id),t.object(d.global_config_id),t.object(n),t.object(d.global_vault_id),t.object(A.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 ut.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:d,id:u,coin_type_a:_,coin_type_b:p}=c,m=d.map(O=>(0,A.fixCoinType)(O.coin_type,!1)),f=ct(m,c.coin_type_a,c.coin_type_b),{published_at:w,configs:h,clmm_configs:v}=this._sdk.sdkOptions.vaults;t=t||new ut.Transaction,t=this.buildCollectRewardPayload({reward_coin_types:m,lp_token_type:l,pool_id:o,clmm_pool_id:u,coin_type_a:_,coin_type_b:p},t),t=this.buildCollectFeePayload({lp_token_type:l,pool_id:o,clmm_pool_id:u,coin_type_a:_,coin_type_b:p},t),t=await this.pythPrice.buildUpdatePythPricePayload(f,t),t.moveCall({target:`${w}::pool::calculate_aum`,typeArguments:[_,p,l],arguments:[t.object(o),t.object(h.global_config_id),t.object(h.pyth_oracle_id),t.object(v.global_config_id),t.object(u),t.object(A.CLOCK_ADDRESS)]});let P,y;if(s&&s.swap_result){let{swap_result:O,coin_amount:S,mode:V,swap_slippage:j}=s,{swap_in_amount:D,swap_out_amount:F,route_obj:L}=O,M=ht.CoinAssist.buildCoinWithBalance(BigInt(S),V==="OnlyCoinA"?_:p,t),R=t.splitCoins(M,[D]),E={router:L,slippage:j,txb:t,inputCoin:R},I=await this._sdk.AggregatorClient.fixableRouterSwapV3(E);P=V==="OnlyCoinA"?M:I,y=V==="OnlyCoinA"?I:M}else P=ht.CoinAssist.buildCoinWithBalance(BigInt(i),_,t),y=ht.CoinAssist.buildCoinWithBalance(BigInt(a),p,t);let k=t.moveCall({target:`${w}::pool::${n?"deposit_for":"deposit"}`,typeArguments:[_,p,l],arguments:[t.object(o),t.object(h.global_config_id),t.object(h.pyth_oracle_id),t.object(v.global_config_id),t.object(u),P,y,t.object(A.CLOCK_ADDRESS)]});return n?k: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:d}=await this.getVaultAndPool(o,!0),{published_at:u,configs:_,clmm_configs:p}=this._sdk.sdkOptions.vaults;t=t||new ut.Transaction;let{lp_token_type:m,clmm_vault:f,lp_token_treasury:w}=l,{rewarder_infos:h,id:v,coin_type_a:P,coin_type_b:y,liquidity:k}=d,O=h.map(M=>(0,A.fixCoinType)(M.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:O,lp_token_type:m,pool_id:o,clmm_pool_id:v,coin_type_a:P,coin_type_b:y},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:v,coin_type_a:P,coin_type_b:y},t);let S,V=r?(0,A.d)(r.burn_lp_amount).add((0,A.d)(i)).toFixed(0):(0,A.d)(i).toFixed(0),j=(0,A.d)(i).isZero();if(j&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");j?S=r.lp_burn_coin:(S=ht.CoinAssist.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(S,[r.lp_burn_coin]));let[D,F,L]=t.moveCall({target:`${u}::pool::withdraw`,typeArguments:[P,y,m],arguments:[t.object(o),t.object(_.global_config_id),t.object(p.global_config_id),t.object(v),S,t.object(A.CLOCK_ADDRESS)]});if(this.buildWithdrawBufferReward({reward_coin_types:O.filter(M=>![(0,A.fixCoinType)(P,!1),(0,A.fixCoinType)(y,!1)].includes(M)),pool_id:o,withdraw_cert:L,lp_token_type:m},t),t.moveCall({target:`${u}::pool::destory_withdraw_cert`,typeArguments:[m],arguments:[t.object(o),t.object(_.global_config_id),L]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let M=a==="OnlyCoinA",R=M?F:D,E=at(w,V,k.toString()),I=await this.handleWithSwap(t,R,P,y,V,o,M,n,s,[{poolID:v,ticklower:f.wrapped_position.tick_lower_index,tickUpper:f.wrapped_position.tick_upper_index,deltaLiquidity:Number(E)}],c);if(c&&I)return M?t.mergeCoins(I,[D]):t.mergeCoins(I,[F]),{return_coin_a:M?I:void 0,return_coin_b:M?void 0:I};t.transferObjects([M?D:F],this._sdk.senderAddress)}else{if(c)return{return_coin_a:D,return_coin_b:F};t.transferObjects([D,F],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,d){let{receive_amount_a:u,receive_amount_b:_}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),p=s?i:o,m=s?o:i,f=s?_:u;if((0,A.d)(f).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let w={from:p,target:m,amount:new X.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(w);if(!h)throw Error("not find Router");if(h.error!==void 0)throw Error(`find Router error : ${h.error}`);let v={router:h,inputCoin:t,slippage:r,txb:e,partner:c},P=await this._sdk.AggregatorClient.fixableRouterSwapV3(v);if(d)return P;e.transferObjects([P],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:d,coin_type_a:u,coin_type_b:_}=s.clmm_vault.wrapped_position,p="0",m="0",f=await this.pythPrice.getLatestPrice([u,_],!0),w=f[u],h=f[_];if(!w||!h)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:v,amountB:P}=Et(l,d,new X.default(c),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=P.toString();break}case"FlexibleBoth":{let{amountA:v,amountB:P}=J((0,A.d)(.5),(0,A.d)(.5),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=P.toString();break}case"OnlyCoinA":{let{amountA:v,amountB:P}=J((0,A.d)(1),(0,A.d)(0),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=P.toString();break}case"OnlyCoinB":{let{amountA:v,amountB:P}=J((0,A.d)(0),(0,A.d)(1),o,w.price,h.price,w.coin_decimals,h.coin_decimals);p=v.toString(),m=P.toString();break}default:throw new Error(`Unsupported deposit mode: ${a}`)}return t&&this.calculateDepositLpAmountBoth(s,r,p,m).then(v=>{t.onSuccess(v,n)}).catch(v=>{t.onError(v,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,d=n.wrapped_position.tick_upper_index,u=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,_=t==="OnlyCoinA",p=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,d,new X.default(u),_,!0,1,new X.default(s)),m=_?(0,A.d)(p.coin_amount_b).div(p.coin_amount_a):(0,A.d)(p.coin_amount_a).div(p.coin_amount_b),f=_?(0,A.d)(s).toString():(0,A.d)(1).div((0,A.d)(s)).toString();try{let k=await this._sdk.VaultsV2.findRouters(_?r:c,_?c:r,u);k&&(f=(0,A.d)(k.swap_out_amount).div(k.swap_in_amount).toString())}catch{}let{swap_amount:w}=_t(u,_,f.toString(),m.toString()),h=(0,A.d)(u).sub(w).toFixed(0),v=await this._sdk.VaultsV2.findRouters(_?r:c,_?c:r,w),P=(0,A.d)(v.swap_out_amount).mul(.999).toFixed(0),y=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(l,d,new X.default(h),_,!0,1,new X.default(s));return _?y.coin_amount_b=P:y.coin_amount_a=P,{swap_result:v,liquidity_info:y}}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:d}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:u,fixed_coin_a:_}=e,{other_amount:p,lp_amount:m}=await this.calculateDepositOtherSide(l,d,u,_,t,a);c=m,_?(n=u,s=p):(s=u,n=p);break}case"FlexibleBoth":{let{coin_amount_a:u,coin_amount_b:_}=e;n=u,s=_;break}case"OnlyCoinA":{if(e.re_balance){let u=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:p}=u,{coin_amount_a:m,coin_amount_b:f}=p;n=m,s=f,r={swap_result:_,coin_amount:e.coin_amount_a}}else n=e.coin_amount_a;break}case"OnlyCoinB":{if(e.re_balance){let u=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:p}=u,{coin_amount_a:m,coin_amount_b:f}=p;n=m,s=f,r={swap_result:_,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,d,n,s).then(u=>{t?.onSuccess(u,a)}).catch(u=>{t?.onError(u,a)}):c=await this.calculateDepositLpAmountBoth(l,d,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,d=A.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(c,l,new X.default(o),i,!0,1,new X.default(r)),{coin_amount_a:u,coin_amount_b:_}=d;if(a)this.calculateDepositLpAmountBoth(e,t,u.toString(),_.toString()).then(p=>{a.onSuccess(p,n)}).catch(p=>{a.onError(p,n)});else{let p=await this.calculateDepositLpAmountBoth(e,t,u.toString(),_.toString());return{other_amount:i?_.toString():u.toString(),lp_amount:p}}return{other_amount:i?_.toString():u.toString(),lp_amount:void 0}}async calculateDepositLpAmountBoth(e,t,o,i){let{lp_token_treasury:a,hard_cap:n}=e,s=(0,A.fixCoinType)(t.coin_type_a,!1),r=(0,A.fixCoinType)(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),d=ft(e.balances,l,c),u=await qt(this,e,t,d,!0),_=await this.pythPrice.getLatestPrice([s,r],!0),p=_[s],m=_[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 w=Y(f,e.quote_type);return mt(a,w,u)}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 d=await this.calculateWithdrawOtherSide(c,l,e.burn_lp_amount);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity;break;case"OnlyCoinA":{let u=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!0);n=u.burn_lp_amount,i=u.receive_amount_a,a=u.receive_amount_b,s=u.remove_liquidity,r=u.swap;break}case"OnlyCoinB":{let u=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!1);n=u.burn_lp_amount,i=u.receive_amount_a,a=u.receive_amount_b,s=u.remove_liquidity,r=u.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,d=i.wrapped_position.liquidity,u=A.TickMath.tickIndexToSqrtPriceX64(c),_=A.TickMath.tickIndexToSqrtPriceX64(l),p=at(a,o,d),{coin_amount_a:m,coin_amount_b:f}=A.ClmmPoolUtil.getCoinAmountFromLiquidity(new X.default(p),new X.default(n),u,_,!1),w=tt(o,e.balances,a),h=(0,A.d)(m.toString()).add(w[s]?.value||"0").toFixed(0),v=(0,A.d)(f.toString()).add(w[r]?.value||"0").toFixed(0);return{receive_amount_a:h,receive_amount_b:v,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,d=a.wrapped_position.tick_upper_index,u=a.wrapped_position.liquidity,_=A.TickMath.tickIndexToSqrtPriceX64(l),p=A.TickMath.tickIndexToSqrtPriceX64(d),m=at(n,i,u),{coin_amount_a:f,coin_amount_b:w}=A.ClmmPoolUtil.getCoinAmountFromLiquidity(new X.default(m),new X.default(s),_,p,!1),h=await this.pythPrice.getLatestPrice([r,c],!0),v=h[r],P=h[c];if(!v)throw Error(`not find ${r} price`);if(!P)throw Error(`not find ${c} price`);let y=o?P:v,k=o?v:P,{quote_per_base:O}=pt(y.price,k.price),S=tt(i,e.balances,n),V=(0,A.d)(f.toString()).add(S[r]?.value||"0").toFixed(0),j=(0,A.d)(w.toString()).add(S[c]?.value||"0").toFixed(0),D=o?V:j,F=o?j:V,L=(0,A.toDecimalsAmount)((0,A.d)((0,A.fromDecimalsAmount)(F,o?P.coin_decimals:v.coin_decimals)).mul(O).toString(),o?v.coin_decimals:P.coin_decimals).toString(),M=(0,A.d)(D).add(L).toFixed(0);return{remove_amount_a:V,remove_amount_b:j,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:D,swapAmountIn:F,swapAmountOut:(0,A.d)(L).toFixed(0,_e.default.ROUND_DOWN),totalReceiveAmount:M}}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,ce.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 Gt={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"}]}}},Ie={"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 Zt(b,e,t){return b&&(Gt.fullRpcUrl=b),new G(Gt,e,t)}var Yt={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 te(b,e,t){return b&&(Yt.fullRpcUrl=b),new G(Yt,e,t)}var de=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(de||{});function qe(b,e,t){let{env:o,fullNodeUrl:i}=b;return o==="mainnet"?Zt(i,e,t):te(i,e,t)}var ee=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];var et=require("@cetusprotocol/common-sdk"),ue=require("@mysten/sui/transactions");var Bt=require("@mysten/sui/bcs"),wt=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,et.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=St(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=St(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,et.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,et.getPackagerConfigs)(o),{versioned_id:n,clmm_vest_id:s}=(0,et.getPackagerConfigs)(i);t=t||new ue.Transaction;for(let r of e){let{vault_id:c,vesting_nft_id:l,period:d,coin_type_a:u,coin_type_b:_}=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(d),t.object(et.CLOCK_ADDRESS)],typeArguments:[u,_]})}return t}};var oe=require("@mysten/sui/transactions"),Z=z(require("bn.js"),1),pe=require("@cetusprotocol/aggregator-sdk"),me=require("@cetusprotocol/sui-clmm-sdk"),g=require("@cetusprotocol/common-sdk"),vt=require("@cetusprotocol/common-sdk"),fe=require("@mysten/sui/utils"),be=z(require("decimal.js"),1);var U=require("@cetusprotocol/dlmm-sdk");var T=require("@mysten/sui/bcs"),Ct=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(d=>{let{id:u,pool_id:_}=d.position,p=c.certified_pool_obj[_],{reward_manager:m,id:f}=p;this.buildDlmmCollectRewardPayload({reward_coin_types:[...m.rewards.map(w=>w.reward_coin)],lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:u,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:u,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}else if(c.type==="CLMM"){let{position_list:l}=c;l.forEach(d=>{let{id:u,pool_id:_}=d.position,p=c.certified_pool_obj[_],{rewarder_infos:m,id:f}=p;this.buildClmmCollectRewardPayload({reward_coin_types:[...m.map(w=>w.coin_type)],lp_token_type:n,pool_id:e,certified_pool_id:f,position_id:u,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:u,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,d=new oe.Transaction;await this.buildCollectRewardAndFeePayload(e,d),(await this._sdk.FullClient.sendSimulationTransaction(d,(0,fe.normalizeSuiAddress)("0x0")))?.Transaction?.events?.forEach(_=>{let{bcs:p,eventType:m}=_;if(m.includes("CollectDlmmFeeEvent")){let f=T.bcs.struct("CollectDlmmFeeEvent",{vault_id:T.bcs.Address,position_id:T.bcs.Address,amount_a:T.bcs.u64(),amount_b:T.bcs.u64(),protocol_fee_a:T.bcs.u64(),protocol_fee_b:T.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=T.bcs.struct("CollectClmmFeeEvent",{vault_id:T.bcs.Address,pool_id:T.bcs.Address,position_id:T.bcs.Address,amount_a:T.bcs.u64(),amount_b:T.bcs.u64(),protocol_fee_a:T.bcs.u64(),protocol_fee_b:T.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=T.bcs.struct("CollectClmmRewardEvent",{vault_id:T.bcs.Address,pool_id:T.bcs.Address,position_id:T.bcs.Address,reward_type:g.TypeNameRaw,amount:T.bcs.u64(),protocol_fee:T.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=T.bcs.struct("CollectDlmmRewardEvent",{vault_id:T.bcs.Address,position_id:T.bcs.Address,reward_type:g.TypeNameRaw,amount:T.bcs.u64(),protocol_fee:T.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=>T.bcs.Address.parse(s.name.bcs));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 d=await this._sdk.FullClient.batchGetObjects(e,{json:!0});for(let u=0;u<d?.length;u++){let _=d[u],{type:p}=_;if(p.includes(`${t.package_id}::vault::Vault`)){let m=Ot(_);i.push(m)}else if(p.includes(`${o.package_id}::pool::Pool`)){let m=nt(_);this._sdk.updateCache(`getPool_${m.id}`,m),a.push(m)}}}let r=i.map(d=>d.id);if(r.length>0){let d=await this.geMarketList(r);i.forEach(u=>{let _=d[u.id];if(_){u.markets=_;let m=0;_.forEach(f=>{m+=f.position_list.length}),u.is_multiple_pool=m!==1}let p=`getPool_${u.id}`;this._sdk.updateCache(p,u)})}let c=new Set;a.forEach(d=>{c.add(d.clmm_vault.clmm_pool_id)}),i.forEach(d=>{d.markets.forEach(u=>{u.position_list.forEach(_=>{let{pool_id:p}=_.position;c.add(p)})})});let l=Array.from(c);if(l.length>0){let{clmm_pool:d}=this._sdk.CetusClmmSDK.sdkOptions,{dlmm_pool:u}=this._sdk.CetusDlmmSDK.sdkOptions;(await this._sdk.FullClient.batchGetObjects(l,{json:!0})).forEach(p=>{let{type:m}=p;if(m.includes(`${d.package_id}::pool::Pool`)){let f=(0,me.buildPool)(p);n[f.id]=f;let w=`${f.id}_getPoolObject`;this._sdk.CetusClmmSDK.updateCache(w,f)}else if(m.includes(`${u.package_id}::pool::Pool`)){let f=(0,U.parseDlmmPool)(p);s[f.id]=f;let w=`${f.id}_getDlmmPool`;this._sdk.CetusDlmmSDK.updateCache(w,f)}})}return{v1:a,v2:i,clmmPoolMap:n,dlmmPoolMap:s}}async geMarketList(e){let t={},o=[];e.forEach(a=>{let n=Jt(a),s=zt(a);o.push(n,s)}),(await this._sdk.FullClient.batchGetObjects(o,{json:!0})).forEach(a=>{let n=Ut(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=Ht(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:d,configs:u}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:_}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:p,global_config_id:m}=(0,g.getPackagerConfigs)(_);l?o.forEach(f=>{t.moveCall({target:`${d}::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(u.versioned_id)]})}):o.forEach(f=>{t.moveCall({target:`${d}::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(u.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:d,configs:u}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:_}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:p,global_config_id:m}=(0,g.getPackagerConfigs)(_);l?o.forEach(f=>{t.moveCall({target:`${d}::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(u.versioned_id),t.object(g.CLOCK_ADDRESS)]})}):o.forEach(f=>{t.moveCall({target:`${d}::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(u.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:d}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:u}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:_,global_config_id:p}=(0,g.getPackagerConfigs)(u);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(_),t.object(d.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(_),t.object(d.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:d}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:u}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:_,global_config_id:p}=(0,g.getPackagerConfigs)(u);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(d.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(d.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:d}=e,{pool:u,marketList:_}=await this.getVaultAndPool(a,!1),{coin_type_a:p,coin_type_b:m,lp_token_type:f}=u,w=[p,m];for(let y of _)y.type==="DLMM"?y.position_list.forEach(k=>{let{pool_id:O}=k.position,S=y.certified_pool_obj[O],{reward_manager:V}=S,j=V.rewards.map(D=>(0,g.fixCoinType)(D.reward_coin,!1));w=ct(j,p,m)}):y.type==="CLMM"&&y.position_list.forEach(k=>{let{pool_id:O}=k.position,S=y.certified_pool_obj[O],{rewarder_infos:V}=S,j=V.map(D=>(0,g.fixCoinType)(D.coin_type,!1));w=ct([...w,...j],p,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(w,t);for(let y of _)if(y.type==="DLMM"){let{dlmm_pool:k}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:O}=(0,g.getPackagerConfigs)(k),{position_list:S}=y;S.forEach(V=>{let{id:j,pool_id:D}=V.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(D),t.pure.address(j),t.object(O),t.object(i.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}else if(y.type==="CLMM"){let{clmm_pool:k}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:O}=(0,g.getPackagerConfigs)(k),{position_list:S}=y;S.forEach(V=>{let{id:j,pool_id:D}=V.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(D),t.pure.address(j),t.object(O),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,v;if(c&&c.swap_result){let{swap_result:y,coin_amount:k,mode:O,swap_slippage:S}=c,{swap_in_amount:V,route_obj:j}=y,D=vt.CoinAssist.buildCoinWithBalance(BigInt(k),O==="OnlyCoinA"?p:m,t),F=t.splitCoins(D,[V]),L={router:j,slippage:S,txb:t,inputCoin:F},M=await this._sdk.AggregatorClient.fixableRouterSwapV3(L);h=O==="OnlyCoinA"?D:M,v=O==="OnlyCoinA"?M:D}else h=l||vt.CoinAssist.buildCoinWithBalance(BigInt(n),p,t),v=d||vt.CoinAssist.buildCoinWithBalance(BigInt(s),m,t);let P=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,v,t.object(g.CLOCK_ADDRESS),t.object(i.versioned_id)]});if(r)return P;t.transferObjects([P],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:d,coin_type_a:u,coin_type_b:_}=c;t=t||new oe.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=vt.CoinAssist.buildCoinWithBalance(BigInt(i),d,t),r&&r.lp_burn_coin&&t.mergeCoins(p,[r.lp_burn_coin]));let{published_at:w,configs:h}=this._sdk.sdkOptions.vaultsV2,{config:v}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:P}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,y=t.moveCall({target:`${w}::vault::new_withdraw_cert`,typeArguments:[d],arguments:[t.object(o),p,t.object(h.versioned_id)]}),k=[];for(let D of l)if(D.type==="DLMM"){let{position_list:F}=D;F.forEach(L=>{let{id:M,pool_id:R}=L.position,E=D.certified_pool_obj[R],{reward_manager:I}=E,x=I.rewards.map(q=>(0,g.fixCoinType)(q.reward_coin,!1));k.push(...x),t.moveCall({target:`${w}::vault::withdraw_dlmm`,typeArguments:[u,_,d],arguments:[t.object(o),y,t.object(R),t.pure.address(M),t.object(v.global_config_id),t.object(v.versioned_id),t.object(h.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}else if(D.type==="CLMM"){let{position_list:F}=D;F.forEach(L=>{let{id:M,pool_id:R}=L.position,E=D.certified_pool_obj[R],{rewarder_infos:I}=E,x=I.map(q=>(0,g.fixCoinType)(q.coin_type,!1));k.push(...x),t.moveCall({target:`${w}::vault::withdraw_clmm`,typeArguments:[u,_,d],arguments:[t.object(o),y,t.object(R),t.pure.address(M),t.object(P.global_config_id),t.object(h.versioned_id),t.object(g.CLOCK_ADDRESS)]})})}await this.buildCollectRewardAndFeePayload(o,t,y),t.moveCall({target:`${w}::vault::finalize_buffer_assets`,typeArguments:[d],arguments:[t.object(o),y,t.object(h.versioned_id)]});let O=new Set;k.forEach(D=>O.add(D)),O.add(u),O.add(_);let S=Array.from(O),V=a!=="FixedOneSide"?[a==="OnlyCoinA"?_:u]:[],j=this.buildWithdrawBufferReward({reward_coin_types:S,pool_id:o,withdraw_cert:y,lp_token_type:d,not_transfer_coin_types:V},t);if(t.moveCall({target:`${w}::vault::destroy_withdraw_cert`,typeArguments:[d],arguments:[t.object(o),y,t.object(h.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let D=a==="OnlyCoinA",F=D?_:u,L=j.find(M=>M.coin_type===F).reward_coin_object_id;await this.handleWithSwap(t,L,u,_,m,o,D,n,s)}}async handleWithSwap(e,t,o,i,a,n,s,r,c){let{receive_amount_a:l,receive_amount_b:d}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),u=s?i:o,_=s?o:i,p=s?d:l;if((0,g.d)(p).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let m={from:u,target:_,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 w={router:f,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:d}=await this.getVaultAndPool(i,!1),{coin_type_a:u,coin_type_b:_}=l,p=await this.pythPrice.getLatestPrice([u,_],!0),m=p[u],f=p[_];if(!m)throw new Error(`get ${u} price failed`);if(!f)throw new Error(`get ${_} price failed`);let w="0",h="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:P,position_amount_b_rate:y}=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:k,amountB:O}=J(P,y,o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=k,h=O;break}case"OnlyCoinA":{let{amountA:P,amountB:y}=J((0,g.d)(1),(0,g.d)(0),o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=P,h=y;break}case"OnlyCoinB":{let{amountA:P,amountB:y}=J((0,g.d)(0),(0,g.d)(1),o,m.price,f.price,m.coin_decimals,f.coin_decimals);w=P,h=y;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:d,tick_upper_index:u}=s,_=d,p=u,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,f=o==="OnlyCoinA",w=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(_,p,new Z.default(m),f,!0,1,new Z.default(r)),h=f?(0,g.d)(w.coin_amount_b).div(w.coin_amount_a):(0,g.d)(w.coin_amount_a).div(w.coin_amount_b),v=f?(0,g.d)(r).toString():(0,g.d)(1).div((0,g.d)(r)).toString();try{let V=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,m);V&&(v=(0,g.d)(V.swap_out_amount).div(V.swap_in_amount).toString())}catch{}let{swap_amount:P}=_t(m,f,v.toString(),h.toString()),y=(0,g.d)(m).sub(P).toFixed(0),k=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,P),O=(0,g.d)(k.swap_out_amount).mul(.999).toFixed(0),S=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(_,p,new Z.default(y),f,!0,1,new Z.default(r));return f?S.coin_amount_b=O:S.coin_amount_a=O,{swap_result:k,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,d=t==="OnlyCoinA",u=s.find(m=>m.position_list.length>0);if(n.is_multiple_pool||!u){let m=await this.findRouters(d?r:c,d?c:r,l),{swap_out_amount:f,swap_in_amount:w}=m,h=d?i:a,v=d?a:i,P=(0,g.fromDecimalsAmount)(w,h),y=(0,g.fromDecimalsAmount)(f,v),k=(0,g.d)(y).div(P).toString(),O=await this.pythPrice.getLatestPrice([r,c],!0),S=O[r],V=O[c];if(!S||!V)throw new Error(`not find ${r} or ${c} price`);let j=Qt(d?P:"0",d?"0":P,S.price,V.price,k,d),D=(0,g.d)((0,g.toDecimalsAmount)(j,h).toString()).toFixed(0),F=(0,g.d)(l).sub(D).toFixed(0);if((0,g.d)(F).lt(1)||(0,g.d)(D).lt(1))throw new Error("amount is less than 1");let L=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,D),M=(0,g.d)(L.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:d?F:M,amount_b:d?M:F},swap_result:L}}let _=s.find(m=>m.type==="CLMM");if(_){let{swap_result:m,liquidity_info:f}=await this.calculateClmmBalanceSwapAmount({...e},_);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:w,bin_step:h}=m,v=U.BinUtils.getPricePerLamportFromBinId(m.active_id,m.bin_step),P=(0,g.d)(v).mul(1-.05),y=(0,g.d)(v).mul(1+.05),k=U.BinUtils.getBinIdFromLamportPrice(P.toString(),m.bin_step,!1),O=U.BinUtils.getBinIdFromLamportPrice(y.toString(),m.bin_step,!1),S=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,coin_amount:l,fix_amount_a:d,active_id:w,bin_step:h,lower_bin_id:k,upper_bin_id:O,active_bin_of_pool:f,strategy_type:U.StrategyType.Spot}),V=d?(0,g.d)(S.amount_b).div(S.amount_a):(0,g.d)(S.amount_a).div(S.amount_b),j=d?U.BinUtils.getPricePerLamportFromBinId(w,h):(0,g.d)(1).div(U.BinUtils.getPricePerLamportFromBinId(w,h)).toString();try{let N=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,l);N&&(j=(0,g.d)(N.swap_out_amount).div(N.swap_in_amount).toString())}catch{}let{swap_amount:D,final_amount_a:F,final_amount_b:L}=_t(l,d,j,V.toString()),M=(0,g.d)(l).sub(D).toFixed(0),R=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,D),E=(0,g.d)(R.swap_out_amount).mul(.999).toFixed(0),I=d?M:E,x=d?E:M,q=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:I,amount_b:x,active_id:w,bin_step:h,lower_bin_id:k,upper_bin_id:O,active_bin_of_pool:f,strategy_type:U.StrategyType.Spot});return d?q.amount_b=R.swap_out_amount:q.amount_a=R.swap_out_amount,{swap_result:R,liquidity_info:q}}}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:d}=e;return await this.calculateDepositOtherSide(n,s,r,c,l,d,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:d,liquidity_info:u}=l,{amount_a:_,amount_b:p}=u,m=await this.calculateDepositFlexibleBoth(n,_,p,t,a);return m.re_balance={swap_result:d,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:d,liquidity_info:u}=l,{amount_a:_,amount_b:p}=u,m=await this.calculateDepositFlexibleBoth(n,_,p,t,a);return m.re_balance={swap_result:d,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),d=(0,g.d)((0,g.fromDecimalsAmount)(s,c.coin_decimals)).mul(c.price),u=(0,g.d)(l).add(d),_=(0,g.d)(l).div(u),p=(0,g.d)(1).sub(_);return{position_amount_a_rate:_,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",d="0";if(e){l=t;let u=(0,g.d)((0,g.fromDecimalsAmount)(l,o)).mul(r.price);d=(0,g.d)((0,g.toDecimalsAmount)((0,g.d)(u).div(c.price).toString(),i)).toFixed(0)}else{d=t;let u=(0,g.d)((0,g.fromDecimalsAmount)(d,i)).mul(c.price);l=(0,g.d)((0,g.toDecimalsAmount)((0,g.d)(u).div(r.price).toString(),o)).toFixed(0)}if((0,g.d)(l).lt(1)||(0,g.d)(d).lt(1))throw new Error("is less than 1");return{deposit_amount_a:l,deposit_amount_b:d}}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),d=(0,g.d)(l).mul(1-.05),u=(0,g.d)(l).mul(1+.05),_=U.BinUtils.getBinIdFromLamportPrice(d.toString(),t.bin_step,!1),p=U.BinUtils.getBinIdFromLamportPrice(u.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:_,upper_bin_id:p,strategy_type:U.StrategyType.Spot,active_bin_of_pool:c},f=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo(m),{amount_a:w,amount_b:h}=f;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:d}=t,{coin_amount_a:u,coin_amount_b:_}=g.ClmmPoolUtil.estLiquidityAndCoinAmountFromOneAmounts(s,r,new Z.default(i),o,!0,1,new Z.default(c));return{deposit_amount_a:u.toString(),deposit_amount_b:_.toString()}}async calculateDepositOtherSide(e,t,o,i,a,n,s,r){let c="0",l="0",{coin_type_a:d,coin_type_b:u}=e;if(e.is_multiple_pool){let _=await this.calculateDepositAmountByValue(i,o,a,n,d,u);c=_.deposit_amount_a,l=_.deposit_amount_b}else if(t[0].type==="DLMM"&&t[0].position_list.length>0){let _=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,_,i,o);c=p,l=m}else if(t[0].type==="CLMM"&&t[0].position_list.length>0){let _=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,_,i,o);c=(0,g.d)(p).add(c).toFixed(0),l=(0,g.d)(m).add(l).toFixed(0)}else{let _=await this.calculateDepositAmountByValue(i,o,a,n,d,u);c=_.deposit_amount_a,l=_.deposit_amount_b}if(s)this.calculateDepositLpAmountBoth(e,c,l).then(_=>{s.onSuccess(_,r)}).catch(_=>{s.onError(_,r)});else{let _=await this.calculateDepositLpAmountBoth(e,c,l);return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:_,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:d,dlmmFeeList:u,clmmRewarderList:_,clmmFeeList:p}=await this.getVaultsPositionRewarderAndFee(e.id),m=ft(e.buffer_assets,[...u,...p],[...d,..._]),f=await Xt(this._sdk,e.id,m,!0),w=await this.pythPrice.getLatestPrice([c,l],!0),h=w[c],v=w[l];if(!h)throw Error(`not find ${c} price`);if(!v)throw Error(`not find ${l} price`);let P={};P[c]={price:h,value:t.toString()},P[l]={price:v,value:o.toString()};let y=Y(P,n);return mt(i,y,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 gt(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 gt(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 d=t?l:c,u=t?c:l,{quote_per_base:_}=pt(d.price,u.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(_).toString(),t?c.coin_decimals:l.coin_decimals).toString(),w=(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,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,i=(await this._sdk.FullClient.getObject({objectId:t,include:{previousTransaction:!0}})).object.previousTransaction;(await this._sdk.FullClient.queryEventsByPage({Transaction:i})).data.forEach(l=>{let d=l.parsedJson;if(l.type)switch((0,pe.extractStructTagFromType)(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=d.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=d.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=d.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 he=z(require("@cetusprotocol/dlmm-sdk"),1);var K=require("@cetusprotocol/common-sdk"),Mt=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:d,from_swap_result:u}=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:_,clmmPool:p}=await this.getVaultAndPool(c),{marketList:m,pool:f}=await this.getVaultAndPool(l),{coin_type_a:w,coin_type_b:h}=p,v=n?(0,K.d)(d).sub(n.burn_lp_amount).toFixed(0).toString():d,{return_coin_a:P,return_coin_b:y}=await this.sdk.Vaults.buildWithdrawPayload({pool_id:c.vault_id,burn_lp_amount:v,mode:"FixedOneSide",slippage:a,return_coin:!0,extra_burn:n},t),k={[(0,K.fixCoinType)(w,!1)]:P,[(0,K.fixCoinType)(h,!1)]:y},{coin_output_a:O,coin_output_b:S}=u,{from_coin_type:V,from_coin_amount:j,route_obj:D,to_coin_type:F}=O;if(D){let{to_coin:M}=await this.buildSwapAssetsTx({from_coin_type:V,swap_in_amount:j,liquidity_slippage:a,route_obj:D.route_obj,tx:t,from_coin_object_id:k[(0,K.fixCoinType)(V,!1)]});k[(0,K.fixCoinType)(F,!1)]=M}if(S.route_obj){let{from_coin_type:M,from_coin_amount:R,route_obj:E,to_coin_type:I}=S,{to_coin:x}=await this.buildSwapAssetsTx({from_coin_type:M,swap_in_amount:R,liquidity_slippage:a,route_obj:E.route_obj,tx:t,from_coin_object_id:k[(0,K.fixCoinType)(M,!1)]});k[(0,K.fixCoinType)(I,!1)]=x}return await this._sdk.VaultsV2.buildDepositPayload({pool_id:l.vault_id,amount_a:s,amount_b:r,return_lp_coin:i,coin_a_input:k[(0,K.fixCoinType)(f.coin_type_a,!1)],coin_b_input:k[(0,K.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:d}=n,{coin_type_a:u,coin_type_b:_}=r,p=await this.matchSwapCoins({from:{coin_type_a:l,coin_amount_a:c.receive_amount_a,coin_type_b:d,coin_amount_b:c.receive_amount_b},to:{coin_type_a:u,coin_type_b:_}}),{coin_output_a:m,coin_output_b:f}=p,w=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:w,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||K.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,K.fixCoinType)(t.coin_type_a,!1),a=(0,K.fixCoinType)(t.coin_type_b,!1),n=(0,K.fixCoinType)(o.coin_type_a,!1),s=(0,K.fixCoinType)(o.coin_type_b,!1),r=i===n,c=i===s,l=a===n,d=a===s,u,_;r&&d?(u="A",_="B"):c&&l?(u="B",_="A"):r?(u="A",_="B"):c||l?(u="B",_="A"):(u="A",_="B");let p={from_coin_type:u==="A"?i:a,from_coin_amount:u==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:n,to_coin_amount:"0"},m={from_coin_type:_==="A"?i:a,from_coin_amount:_==="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,K.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,K.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 G=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=ee),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||ie.CetusClmmSDK.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||ie.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 yt(this),this._vaultsV2=new Ct(this),this._migrate=new Mt(this);let{primary:i,secondary:a}=e.pythConfigs.hermes_service_urls,n=[i,a].filter(Boolean);this._aggregatorClient=new Pt.AggregatorClient({endpoint:e.aggregatorUrl,signer:(0,Ft.normalizeSuiAddress)("0x0"),client:this.FullClient,env:e.env==="testnet"?Pt.Env.Testnet:Pt.Env.Mainnet,pythUrls:n}),this._vest=new wt(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,Ft.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 Ke=.2;var $e=G;0&&(module.exports={PythPriceModule,SdkEnv,VaultsModule,VaultsModuleV2,VestModule,VolatileVaultsSDK,buildCLMMMarketId,buildCLMMMarketPosition,buildDLMMMarketId,buildDLMMMarketPosition,buildDLMMPositionId,buildPoolData,buildPoolV2Data,buildVaultMarket,buildVaultsBalance,buildVaultsBalanceV2,buildVaultsBalanceV3,calcExactSwapAmount,calcSingleSideSwap,calculateAum,calculateAumV2,calculateDepositRatioFixTokenA,calculateTotalAumBasedOnQuote,checkIsMinOrMaxIndex,convertU64BytesToDecimal,defaultProvider,dlmm_split_rate,estCoinAmountsFromTotalAmount,feed_map_mainnet,feed_map_testnet,getAmountBalanceByLpAmount,getAmountBalanceByLpAmountV2,getCoinAmountsFromRatio,getPositionPriceRange,getPriceWithFormattedDecimals,getPrimitivePricesFromBaseQuote,getQuotePerBaseAndBasePerQuote,getShareBufferAssets,getUpdatePriceType,getVaultValidBalances,get_lp_amount_by_liquidity,get_lp_amount_by_tvl,get_share_liquidity_by_amount,initMainnetSDK,initTestnetSDK,initVaultSDK,oraclePriceMultiplierDecimal,parseVaultVestNFT,parseVaultsVestInfo,printTransaction,toSuiObjectId,vaults_mainnet,vaults_testnet});
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  import { PreSwapLpChangeParams, AggregatorClient } from '@cetusprotocol/aggregator-sdk';
2
2
  import * as _cetusprotocol_common_sdk from '@cetusprotocol/common-sdk';
3
- import { CoinPairType, TableHandle, PaginationArgs, DataPage, IModule as IModule$1, Package, SuiAddressType, FullClient, CoinAsset, SuiResource } from '@cetusprotocol/common-sdk';
3
+ import { CoinPairType, TableHandle, PythPriceModule as PythPriceModule$1, FeedInfo as FeedInfo$1, Price as Price$1, PaginationArgs, DataPage, IModule as IModule$1, Package, SuiAddressType, FullClient, CoinAsset, SuiResource } from '@cetusprotocol/common-sdk';
4
4
  import CetusClmmSDK$1, { Pool as Pool$1, CetusClmmSDK } from '@cetusprotocol/sui-clmm-sdk';
5
5
  import { TransactionObjectArgument, Transaction } from '@mysten/sui/transactions';
6
6
  import CetusDlmmSDK, { DlmmPosition, DlmmPool, BinLiquidityInfo } from '@cetusprotocol/dlmm-sdk';
7
- import { SuiPriceServiceConnection, SuiPythClient, PriceUpdate } from '@pythnetwork/pyth-sui-js';
8
7
  import BN from 'bn.js';
9
8
  import Decimal from 'decimal.js';
10
9
 
@@ -423,84 +422,27 @@ type PythNodeError = {
423
422
  };
424
423
 
425
424
  /**
426
- * The PythPriceModule handles interactions with the Pyth Price Service.
427
- * It allows fetching price data for different coin types and performing updates on Pyth price feeds.
425
+ * Vault-specific wrapper around common-sdk PythPriceModule.
426
+ * Delegates price fetching to common-sdk and injects vault oracle update move calls.
428
427
  */
429
428
  declare class PythPriceModule implements IModule {
430
429
  protected _sdk: VolatileVaultsSDK;
431
- protected connection: SuiPriceServiceConnection;
432
- protected suiPythClient: SuiPythClient;
433
- protected hasChangeConnection: boolean;
434
- protected errorList: PythNodeError[];
430
+ protected _pyth: PythPriceModule$1;
435
431
  protected pythConfigs: PythConfigs;
436
432
  protected global_config_id: string;
437
433
  protected pyth_oracle_id: string;
438
- protected oracle_infos_handle: string;
439
434
  protected vaults_published_at: string;
440
435
  protected versioned_id: string;
441
436
  protected isV2: boolean;
442
- /**
443
- * Constructs a PythPriceModule instance with the provided SDK.
444
- *
445
- * @param sdk - The VolatileVaultsSDK instance to be used for interacting with the service.
446
- */
447
437
  constructor(sdk: VolatileVaultsSDK, pythConfigs: PythConfigs, vaults_published_at: string, global_config_id: string, pyth_oracle_id: string, versioned_id: string, oracle_infos_handle: string, isV2: boolean);
448
- /**
449
- * Returns the associated SDK instance
450
- */
451
438
  get sdk(): VolatileVaultsSDK;
452
- recordError(error: any, request_params: any, action: 'getLatestPriceFeeds' | 'getPriceFeedsUpdateData'): void;
453
- readErrorList(): PythNodeError[];
454
- /**
455
- * Fetches the feed information for a list of coin types.
456
- *
457
- * @param coinTypeList - The list of coin types for which feed information is required.
458
- * @returns A promise that resolves to a list of FeedInfo objects.
459
- */
460
- getFeedInfoList(coinTypeList: string[]): Promise<FeedInfo[]>;
461
- /**
462
- * Checks if the price has been updated within the last 60 seconds.
463
- *
464
- * @param price - The price object to check.
465
- * @returns The price object if it has been updated within the last 60 seconds, otherwise undefined.
466
- */
467
- priceCheck(price: Price, age?: number): Price | undefined;
468
- /**
469
- * Fetches the latest prices for a list of coin types.
470
- * Optionally uses cached prices if available.
471
- *
472
- * @param coinTypeList - The list of coin types for which prices are required.
473
- * @param useCache - A flag to indicate whether to use cached prices (default: false).
474
- * @returns A promise that resolves to a record mapping coin types to their respective price information.
475
- */
476
- getLatestPrice(coinTypeList: string[], useCache?: boolean): Promise<Record<string, Price>>;
477
- getPriceFeedsUpdateData(feedIds: string[]): Promise<Buffer<ArrayBufferLike>[] | undefined>;
478
- getLatestPriceFeeds(feedIds: string[]): Promise<PriceUpdate | undefined>;
479
- /**
480
- * Builds the payload to update Pyth price feeds with the provided coin types and transaction.
481
- *
482
- * @param coinTypeList - The list of coin types to update the price feeds for.
483
- * @param tx - The transaction object to include in the payload.
484
- * @returns The transaction object with the Pyth price update payload.
485
- */
439
+ getFeedInfoList(coinTypeList: string[]): Promise<FeedInfo$1[]>;
440
+ priceCheck(price: Price$1, age?: number): Price$1 | undefined;
441
+ getLatestPrice(coinTypeList: string[], useCache?: boolean): Promise<Record<string, Price$1>>;
442
+ getFeedInfo(coinType: string, forceRefresh: boolean): Promise<FeedInfo$1>;
443
+ getFeedInfoByJson(coinType: string): FeedInfo$1;
486
444
  buildUpdatePythPricePayload(coinTypeList: string[], tx: Transaction): Promise<Transaction>;
487
445
  buildUpdatePythPricePayloadV2(coinTypeList: string[], tx: Transaction): Promise<Transaction>;
488
- /**
489
- * Retrieves feed information by parsing JSON data based on the environment and coin type.
490
- *
491
- * @param coinType - The coin type for which feed info is required.
492
- * @returns The feed info corresponding to the given coin type.
493
- */
494
- getFeedInfoByJson(coinType: string): FeedInfo;
495
- /**
496
- * Retrieves feed information for a specific coin type.
497
- * If not found in the cache, it will fetch the data from an external source.
498
- *
499
- * @param coinType - The coin type for which feed info is required.
500
- * @param forceRefresh - A flag to indicate whether to force a refresh and skip the cache.
501
- * @returns A promise that resolves to the FeedInfo for the specified coin type.
502
- */
503
- getFeedInfo(coinType: string, forceRefresh: boolean): Promise<FeedInfo>;
504
446
  }
505
447
 
506
448
  type VaultVersionRef = {
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{isValidSuiAddress as _o,normalizeSuiAddress as uo}from"@mysten/sui/utils";import{AggregatorClient as po,Env as Me}from"@cetusprotocol/aggregator-sdk";import{CACHE_TIME_24H as mo}from"@cetusprotocol/common-sdk";import{CetusClmmSDK as Le}from"@cetusprotocol/sui-clmm-sdk";import{Transaction as yt}from"@mysten/sui/transactions";import N from"bn.js";import{extractStructTagFromType as Ge}from"@cetusprotocol/aggregator-sdk";import{ClmmPoolUtil as wt,TickMath as Dt,d as I,fixCoinType as J,fromDecimalsAmount as Je,toDecimalsAmount as Qe,CLOCK_ADDRESS as Ot,TypeNameRaw as Ze}from"@cetusprotocol/common-sdk";import{CoinAssist as jt}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as Ye}from"@mysten/sui/utils";import to from"decimal.js";import q from"bn.js";import $t from"decimal.js";import{ClmmPoolUtil as re,TickMath as lt,MathUtil as Kt,asIntN as vt,fixCoinType as G,extractStructTagFromType as se,d as K}from"@cetusprotocol/common-sdk";import{ClmmPoolUtil as Te,d as rt,TickMath as Ie,TickUtil as ee,toDecimalsAmount as oe}from"@cetusprotocol/common-sdk";import ie from"bn.js";import ne from"decimal.js";var qt=(b,e,t)=>{if(e==="min"){if(b===ee.getMinIndex(t))return!0}else if(b===ee.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 Ee(b,e,t,o,i){let a=new ie(10).pow(new ie(o)),{coin_amount_b:n}=Te.estLiquidityAndCoinAmountFromOneAmounts(b,e,a,!0,!0,0,t),s=Ie.sqrtPriceX64ToPrice(t,o,i),r=rt(a.toString()).mul(s).div(new ne(10).pow(o)).mul(new ne(10).pow(i)),c=r.add(n.toString()),l=r.div(c),_=rt(n.toString()).div(c);return{ratioA:l,ratioB:_}}function X(b,e,t,o,i,a,n){let s=rt(oe(rt(t).mul(b).div(o).toString(),a)).toFixed(0),r=rt(oe(rt(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function ae(b,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=Ee(b,e,t,n,s);return X(r,c,o,i,a,n,s)}var ct=10n;function dt(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:G(n.coin_type_a,!1),coin_type_b:G(n.coin_type_b,!1),description:n.description,id:n.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:vt(BigInt(n.tick_lower_index.bits)),tick_upper_index:vt(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:G(d,!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:se(e.quote_type).full_address,lp_token_type:se(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 Pt(b,e){let t=K(b).div(e).toString(),o=K(e).div(b).toString();return{quote_per_base:t,base_per_quote:o}}function Re(b,e,t,o){let i=10n**(ct+o-t),a=10n**(ct+t-o),n=Kt.checkMulDivFloor(new q(b.toString()),new q(i.toString()),new q(e.toString()),64),s=Kt.checkMulDivFloor(new q(e.toString()),new q(a.toString()),new q(b.toString()),64);return{primitive_base_price:BigInt(n.toString()),primitive_quote_price:BigInt(s.toString())}}function nt(b,e){let t=e?b[e].price:{coin_type:"",price:"1",coin_decimals:6,oracle_price:1000000000000000000000000n},o=new q("0");for(let[i,{price:a,value:n}]of Object.entries(b)){let{primitive_quote_price:s}=Re(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=Kt.checkMulDivFloor(new q(s.toString()),new q(n),new q((BigInt(10)**ct).toString()),64);o=o.add(r)}return o.toString()}async function ce(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&&G(e.quote_type,!1),f=lt.tickIndexToSqrtPriceX64(r),y=lt.tickIndexToSqrtPriceX64(c),{coin_amount_a:g,coin_amount_b:w}=re.getCoinAmountFromLiquidity(new q(l),new q(_),new q(f),new q(y),!1);p.push({coin_type:d,value:g.toString()}),p.push({coin_type:u,value:w.toString()});let v={};p.forEach(C=>{let D=G(C.coin_type,!1),A=K(C.value),B=v[D]||0;v[D]=A.add(B).toString()});let h=Object.entries(v).filter(([C,D])=>K(D).gt(0)).map(([C])=>C);if(m&&!h.includes(m)&&h.push(m),h.length===0)return"0";let P=await b.PythPrice.getLatestPrice(h,i),S={};return h.forEach(C=>{let D=P[C];if(D)S[C]={price:D,value:v[C]||"0"};else throw Error(`find ${C} price fail `)}),nt(S,m).toString()}function Ct(b,e,t){return K(b).eq(0)?e:K(b).mul(e).div(t).toFixed(0,$t.ROUND_HALF_UP)}function Ao(b,e,t){return K(b).eq(0)?"0":K(b).mul(e).div(t).toFixed(0,$t.ROUND_HALF_UP)}function _t(b,e,t){return K(b).eq(0)?"0":K(e).mul(t).div(b).toFixed(0,$t.ROUND_HALF_UP)}function at(b,e,t){let o={};return e.forEach(i=>{let a=_t(t,b,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function le(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=_t(t.lp_token_treasury,e,c),_=lt.tickIndexToSqrtPriceX64(a),d=lt.tickIndexToSqrtPriceX64(n),u=re.getCoinAmountFromLiquidity(new q(l),new q(o.current_sqrt_price),_,d,!0),p=u.coin_amount_a.toString(),m=u.coin_amount_b.toString(),f=at(e,t.balances,t.lp_token_treasury),y=K(p).add(i&&f[s]?.value||"0").toFixed(0),g=K(m).add(i&&f[r]?.value||"0").toFixed(0),w=i?Object.values(f).filter(h=>h.coin_type!==s&&h.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:w}}function kt(b,e,t){let o=[];return e.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),b.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),o}function bt(b,e,t){let o=new Set;return b.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function de(b,e){if(!ct)throw new Error("oraclePriceMultiplierDecimal is required");if(b===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(ct- -e);return b*t}return b/10n**(e+ct)}function _e(b){return`0x${Buffer.from(b).toString("hex")}`}function So(b,e,t,o,i){let a="0",n="0";return qt(b,"min",Number(t))?a="0":a=lt.tickIndexToPrice(Number(b),o,i).toString(),qt(e,"max",Number(t))?n="\u221E":n=lt.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function Ut(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:vt(BigInt(t.tick_lower_index.bits)),tick_upper_index:vt(BigInt(t.tick_upper_index.bits)),coin_type_a:G(t.coin_type_a.name,!1),coin_type_b:G(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:G(e.coin_a.name,!1),coin_type_b:G(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 ue(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 Vt,fixCoinType as U,extractStructTagFromType as qe,d as O,TickMath as ut,ClmmPoolUtil as Wt}from"@cetusprotocol/common-sdk";import{parseLiquidityShares as Nt}from"@cetusprotocol/dlmm-sdk";import pe from"decimal.js";import{bcs as gt}from"@mysten/sui/bcs";import{deriveDynamicFieldID as Ke,deriveObjectID as me}from"@mysten/sui/utils";import Q from"bn.js";function fe(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:U(n,!1),coin_type_b:U(s,!1),vault_id:r,position_keys:c.contents}}catch{return}}function $e(b){return{uri:b.uri,index:b.index,id:b.id,name:b.name,pool_id:b.pool_id,lower_bin_id:Vt(BigInt(b.lower_bin_id.bits)),upper_bin_id:Vt(BigInt(b.upper_bin_id.bits)),liquidity_shares:b.liquidity_shares,description:b.description,coin_type_a:U(b.coin_type_a,!1),coin_type_b:U(b.coin_type_b,!1)}}function Ue(b){return{id:b.id,pool_id:b.pool,index:b.index,description:b.description,uri:b.url,liquidity:b.liquidity,tick_lower_index:Vt(BigInt(b.tick_lower_index.bits)),tick_upper_index:Vt(BigInt(b.tick_upper_index.bits)),name:b.name,coin_type_a:U(b.coin_type_a,!1),coin_type_b:U(b.coin_type_b,!1)}}function be(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(_=>{let{key:d,value:u}=_;return{coin_type:U(d,!1),value:u}}),a=$e(e),n=a.lower_bin_id,s=a.liquidity_shares.map((_,d)=>({bin_id:n+d,liquidity:_})).filter(_=>O(_.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 ge(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(s=>{let{key:r,value:c}=s;return{coin_type:U(r,!1),value:c}}),a=Ue(e);return{id:o,position:a,amounts:i}}function zt(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,g=y.contents.map(h=>{let{key:P,value:S}=h;return{coin_type:U(P,!1),value:S}}),w=p.pos0;return{id:r,lp_token_treasury:l.total_supply.value,hard_cap:s,quote_type:w?U(w,!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:U(a,!1),coin_type_b:U(n,!1),lp_token_type:qe(t).type_arguments[0],version:"v2"}}async function he(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:w}=g;for(let v of w){let{lower_bin_id:h,liquidity_shares:P,pool_id:S}=v.position,V=g.certified_pool_obj[S],C=await b.CetusDlmmSDK.Pool.getBinInfo(V.bin_manager.bin_manager_handle,V.active_id,V.bin_step,!1),D=Nt(P,V.bin_step,h,C);l=O(l).add(D.amount_a.toString()).toFixed(0),_=O(_).add(D.amount_b.toString()).toFixed(0)}}else if(g.type==="CLMM"){let{position_list:w}=g;for(let v of w){let{tick_lower_index:h,tick_upper_index:P,liquidity:S,pool_id:V}=v.position,C=g.certified_pool_obj[V],D=ut.tickIndexToSqrtPriceX64(h),A=ut.tickIndexToSqrtPriceX64(P),{coin_amount_a:B,coin_amount_b:F}=Wt.getCoinAmountFromLiquidity(new Q(S),new Q(C.current_sqrt_price),new Q(D),new Q(A),!1);l=O(l).add(B.toString()).toFixed(0),_=O(_).add(F.toString()).toFixed(0)}}let d=n&&U(n,!1);c.push({coin_type:s,value:l}),c.push({coin_type:r,value:_});let u={};c.forEach(g=>{let w=U(g.coin_type,!1),v=O(g.value),h=u[w]||0;u[w]=v.add(h).toString()});let p=Object.entries(u).filter(([g,w])=>O(w).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 w=m[g];if(w)f[g]={price:w,value:u[g]||"0"};else throw Error(`find ${g} price fail `)}),nt(f,d).toString()}async function Ht(b,e,t,o,i=!0){let a=await At(b,e,t,i);return a.owner=o||"0x0",a}async function qo(b,e,t,o,i=!0){let a=await We(b,e,t,i);return a.owner=o||"0x0",a}async function At(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(O(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=O(e).div(s),_=[],d=[],u=O(0),p=O(0);for(let h of a)if(h.type==="DLMM"){let{position_list:P}=h;for(let S of P){let{lower_bin_id:V,upper_bin_id:C,liquidity_shares:D,id:A,pool_id:B}=S.position,F=h.certified_pool_obj[B],{bin_manager:j,bin_step:L,active_id:E}=F,T=await b.CetusDlmmSDK.Pool.getBinInfo(j.bin_manager_handle,E,L,!1),M=Nt(D.map(it=>O(it.toString()).mul(l).toFixed(0,pe.ROUND_HALF_UP).toString()),L,V,T),R=M.amount_a,$=M.amount_b,W=M.bins.filter(it=>O(it.liquidity).gt(0)),It=W.length>0?W[0].bin_id:M.bins[0].bin_id,Et=W.length>0?W[W.length-1].bin_id:M.bins[M.bins.length-1].bin_id,Rt={position_id:A,certified_pool_id:F.id,liquidity_shares:D,valid_lower_bin_id:It,valid_upper_bin_id:Et,original_lower_bin_id:V,original_upper_bin_id:C,position_amount_a:R,position_amount_b:$,coin_type_a:r,coin_type_b:c,bin_infos:{bins:W,amount_a:M.amount_a,amount_b:M.amount_b}};_.push(Rt),u=u.add(O(R)),p=p.add(O($))}}else if(h.type==="CLMM"){let{position_list:P}=h;for(let S of P){let{tick_lower_index:V,tick_upper_index:C,liquidity:D,id:A,pool_id:B}=S.position,F=h.certified_pool_obj[B],j=O(D).mul(l).toFixed(0),L=ut.tickIndexToSqrtPriceX64(V),E=ut.tickIndexToSqrtPriceX64(C),T=Wt.getCoinAmountFromLiquidity(new Q(j),new Q(F.current_sqrt_price),L,E,!1),M=T.coin_amount_a.toString(),R=T.coin_amount_b.toString(),$={position_id:A,certified_pool_id:F.id,liquidity:j,tick_lower_index:V,tick_upper_index:C,position_amount_a:M,position_amount_b:R};d.push($),u=u.add(O(M)),p=p.add(O(R))}}let m=at(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",y=o&&m[c]?.value||"0",g=u.add(f).toFixed(0),w=p.add(y).toFixed(0),v=o?Object.values(m).filter(h=>h.coin_type!==r&&h.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:w,position_amount_a:u.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:v}}async function We(b,e,t,o=!0){let{pool:i,markets:a}=t,{lp_token_type:n,lp_token_treasury:s,coin_type_a:r,coin_type_b:c}=i;if(O(s).isZero())return{vault_id:i.id,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=O(e).div(s),_=[],d=[],u=O(0),p=O(0);for(let h of a)if(h.type==="DLMM"){let{position_list:P}=h;for(let S of P){let{lower_bin_id:V,upper_bin_id:C,liquidity_shares:D,id:A,pool_id:B}=S.position,F=h[B],{bin_manager:j,bin_step:L,active_id:E}=F,T=await b.CetusDlmmSDK.Pool.getBinInfo(j.bin_manager_handle,E,L,!1),M=Nt(D.map(it=>O(it.toString()).mul(l).toFixed(0,pe.ROUND_HALF_UP).toString()),L,V,T),R=M.amount_a,$=M.amount_b,W=M.bins.filter(it=>O(it.liquidity).gt(0)),It=W.length>0?W[0].bin_id:M.bins[0].bin_id,Et=W.length>0?W[W.length-1].bin_id:M.bins[M.bins.length-1].bin_id,Rt={position_id:A,certified_pool_id:F.id,liquidity_shares:D,valid_lower_bin_id:It,valid_upper_bin_id:Et,original_lower_bin_id:V,original_upper_bin_id:C,position_amount_a:R,position_amount_b:$,coin_type_a:r,coin_type_b:c,bin_infos:{bins:W,amount_a:M.amount_a,amount_b:M.amount_b}};_.push(Rt),u=u.add(O(R)),p=p.add(O($))}}else if(h.type==="CLMM"){let{position_list:P}=h;for(let S of P){let{tick_lower_index:V,tick_upper_index:C,liquidity:D,id:A,pool_id:B}=S.position,F=h[B],j=O(D).mul(l).toFixed(0),L=ut.tickIndexToSqrtPriceX64(V),E=ut.tickIndexToSqrtPriceX64(C),T=Wt.getCoinAmountFromLiquidity(new Q(j),new Q(F.current_sqrt_price),L,E,!1),M=T.coin_amount_a.toString(),R=T.coin_amount_b.toString(),$={position_id:A,certified_pool_id:F.id,liquidity:j,tick_lower_index:V,tick_upper_index:C,position_amount_a:M,position_amount_b:R};d.push($),u=u.add(O(M)),p=p.add(O(R))}}let m=at(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",y=o&&m[c]?.value||"0",g=u.add(f).toFixed(0),w=p.add(y).toFixed(0),v=o?Object.values(m).filter(h=>h.coin_type!==r&&h.coin_type!==c):Object.values(m);return{vault_id:i.id,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:g,amount_b:w,position_amount_a:u.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:_,clmm_balances:d,share_buffer_assets:v}}function ye(b){let e=gt.vector(gt.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return me(b,"vector<u8>",e)}function we(b){let e=gt.vector(gt.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return me(b,"vector<u8>",e)}function Ko(b,e){let t=gt.Address.serialize(e).toBytes();return Ke(b,"0x2::object::ID",t)}function ht(b,e,t,o){let i=O(b),a=O(t),n=O(o),s=i,r=e?i:O(0),c=e?O(0):i,l=n,_=O(n).mul(.999),d=O(0),u=s,p=null;function m(g){if(e){let w=r.minus(g),v=c.plus(g.mul(a));return{A:w,B:v,R:v.div(w)}}else{let w=r.plus(g.mul(a)),v=c.minus(g);return{A:w,B:v,R:w.div(v)}}}for(let g=0;g<120;g++){let w=d.plus(u).div(2),{A:v,B:h,R:P}=m(w);if(v.lte(0)||h.lte(0)){u=w;continue}if(P.gt(l))u=w;else if(P.lt(_))d=w;else{if(p=w,O(_).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 ve(b,e,t,o,i,a){if(a){let n=O(b).mul(t).sub(O(e).mul(o)),s=O(t).add(O(i).mul(o));return(O(s).eq(0)?O(0):O(n).div(s)).toString()}else{let n=O(e).mul(o).sub(O(b).mul(t)),s=O(i).mul(t).add(o);return(O(s).eq(0)?O(0):O(n).div(s)).toString()}}import{SuiPriceServiceConnection as Xt,SuiPythClient as ze}from"@pythnetwork/pyth-sui-js";import{bcs as Y}from"@mysten/sui/bcs";import{CLOCK_ADDRESS as St,d as Gt,fixCoinType as je,TypeNameRaw as He}from"@cetusprotocol/common-sdk";var Pe={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"}]}}},Ce={"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 ke(b,e,t){return b&&(Pe.fullRpcUrl=b),new Z(Pe,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"}]}}},Ae={};function Se(b,e,t){return b&&(Ve.fullRpcUrl=b),new Z(Ve,e,t)}var Ne=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(Ne||{});function ei(b,e,t){let{env:o,fullNodeUrl:i}=b;return o==="mainnet"?ke(i,e,t):Se(i,e,t)}var De=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];function Oe(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 Xe=16*1024,pt=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 Xt(d),this.suiPythClient=new ze(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()};Oe(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=Gt(c).mul(Gt(10).pow(Gt(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=de(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 Xt(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 Xt(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(Y.vector(Y.U8).serialize(Array.from(s[0]),{maxSize:Xe}).toBytes()),c[0],t.object(St)]}),_=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(St),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(St)]}),_+=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(St),t.object(this.versioned_id)]}),n+=1;return t}getFeedInfoByJson(e){let{env:t}=this._sdk.sdkOptions,o=je(e,!1);return t==="mainnet"?Ce[o]:Ae[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:He.serialize({name:je(e,!0)}).toBytes()}}),s=Y.struct("OracleInfo",{price_feed_id:Y.vector(Y.U8),price_info_object_id:Y.Address,last_update_time:Y.u64(),coin_decimals:Y.u8()}).parse(n.dynamicField.value.bcs),r={coin_type:e,price_feed_id:_e(s.price_feed_id),coin_decimals:s.coin_decimals};return this._sdk.updateCache(o,r),r}};import{bcs as mt}from"@mysten/sui/bcs";var Bt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new pt(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 le(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 yt;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,Ye("0x0")),p=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,f=[],y=[];return u.Transaction?.events?.forEach(g=>{let{bcs:w,eventType:v}=g;if(v===p){let h=mt.struct("FeeClaimedEvent",{amount_a:mt.u64(),amount_b:mt.u64()}).parse(w);f.push({coin_type:J(l,!1),value:h.amount_a}),f.push({coin_type:J(_,!1),value:h.amount_b})}if(v===m){let h=mt.struct("RewardClaimedEvent",{amount:mt.u64(),reward_type:Ze}).parse(w);y.push({coin_type:J(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=>mt.Address.parse(s.name.bcs));return n.length>0&&((await i.batchGetObjects(n,{json:!0})).forEach(r=>{let c=dt(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=dt(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=dt(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 yt,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(Ot)]})}),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 yt,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(S=>J(S.coin_type,!1)),f=bt(m,c.coin_type_a,c.coin_type_b),{published_at:y,configs:g,clmm_configs:w}=this._sdk.sdkOptions.vaults;t=t||new yt,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(g.global_config_id),t.object(g.pyth_oracle_id),t.object(w.global_config_id),t.object(d),t.object(Ot)]});let v,h;if(s&&s.swap_result){let{swap_result:S,coin_amount:V,mode:C,swap_slippage:D}=s,{swap_in_amount:A,swap_out_amount:B,route_obj:F}=S,j=jt.buildCoinWithBalance(BigInt(V),C==="OnlyCoinA"?u:p,t),L=t.splitCoins(j,[A]),E={router:F,slippage:D,txb:t,inputCoin:L},T=await this._sdk.AggregatorClient.fixableRouterSwapV3(E);v=C==="OnlyCoinA"?j:T,h=C==="OnlyCoinA"?T:j}else v=jt.buildCoinWithBalance(BigInt(i),u,t),h=jt.buildCoinWithBalance(BigInt(a),p,t);let P=t.moveCall({target:`${y}::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(w.global_config_id),t.object(d),v,h,t.object(Ot)]});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 yt;let{lp_token_type:m,clmm_vault:f,lp_token_treasury:y}=l,{rewarder_infos:g,id:w,coin_type_a:v,coin_type_b:h,liquidity:P}=_,S=g.map(j=>J(j.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:S,lp_token_type:m,pool_id:o,clmm_pool_id:w,coin_type_a:v,coin_type_b:h},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:w,coin_type_a:v,coin_type_b:h},t);let V,C=r?I(r.burn_lp_amount).add(I(i)).toFixed(0):I(i).toFixed(0),D=I(i).isZero();if(D&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");D?V=r.lp_burn_coin:(V=jt.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(V,[r.lp_burn_coin]));let[A,B,F]=t.moveCall({target:`${d}::pool::withdraw`,typeArguments:[v,h,m],arguments:[t.object(o),t.object(u.global_config_id),t.object(p.global_config_id),t.object(w),V,t.object(Ot)]});if(this.buildWithdrawBufferReward({reward_coin_types:S.filter(j=>![J(v,!1),J(h,!1)].includes(j)),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 j=a==="OnlyCoinA",L=j?B:A,E=_t(y,C,P.toString()),T=await this.handleWithSwap(t,L,v,h,C,o,j,n,s,[{poolID:w,ticklower:f.wrapped_position.tick_lower_index,tickUpper:f.wrapped_position.tick_upper_index,deltaLiquidity:Number(E)}],c);if(c&&T)return j?t.mergeCoins(T,[A]):t.mergeCoins(T,[B]),{return_coin_a:j?T:void 0,return_coin_b:j?void 0:T};t.transferObjects([j?A:B],this._sdk.senderAddress)}else{if(c)return{return_coin_a:A,return_coin_b:B};t.transferObjects([A,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(I(f).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let y={from:p,target:m,amount:new N(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 w={router:g,inputCoin:t,slippage:r,txb:e,partner:c},v=await this._sdk.AggregatorClient.fixableRouterSwapV3(w);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),y=f[d],g=f[u];if(!y||!g)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:w,amountB:v}=ae(l,_,new N(c),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"FlexibleBoth":{let{amountA:w,amountB:v}=X(I(.5),I(.5),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"OnlyCoinA":{let{amountA:w,amountB:v}=X(I(1),I(0),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"OnlyCoinB":{let{amountA:w,amountB:v}=X(I(0),I(1),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.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=wt.estLiquidityAndCoinAmountFromOneAmounts(l,_,new N(d),u,!0,1,new N(s)),m=u?I(p.coin_amount_b).div(p.coin_amount_a):I(p.coin_amount_a).div(p.coin_amount_b),f=u?I(s).toString():I(1).div(I(s)).toString();try{let P=await this._sdk.VaultsV2.findRouters(u?r:c,u?c:r,d);P&&(f=I(P.swap_out_amount).div(P.swap_in_amount).toString())}catch{}let{swap_amount:y}=ht(d,u,f.toString(),m.toString()),g=I(d).sub(y).toFixed(0),w=await this._sdk.VaultsV2.findRouters(u?r:c,u?c:r,y),v=I(w.swap_out_amount).mul(.999).toFixed(0),h=wt.estLiquidityAndCoinAmountFromOneAmounts(l,_,new N(g),u,!0,1,new N(s));return u?h.coin_amount_b=v:h.coin_amount_a=v,{swap_result:w,liquidity_info:h}}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,_=wt.estLiquidityAndCoinAmountFromOneAmounts(c,l,new N(o),i,!0,1,new N(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=J(t.coin_type_a,!1),r=J(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),_=kt(e.balances,l,c),d=await ce(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=nt(f,e.quote_type);return Ct(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=Dt.tickIndexToSqrtPriceX64(c),u=Dt.tickIndexToSqrtPriceX64(l),p=_t(a,o,_),{coin_amount_a:m,coin_amount_b:f}=wt.getCoinAmountFromLiquidity(new N(p),new N(n),d,u,!1),y=at(o,e.balances,a),g=I(m.toString()).add(y[s]?.value||"0").toFixed(0),w=I(f.toString()).add(y[r]?.value||"0").toFixed(0);return{receive_amount_a:g,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=Dt.tickIndexToSqrtPriceX64(l),p=Dt.tickIndexToSqrtPriceX64(_),m=_t(n,i,d),{coin_amount_a:f,coin_amount_b:y}=wt.getCoinAmountFromLiquidity(new N(m),new N(s),u,p,!1),g=await this.pythPrice.getLatestPrice([r,c],!0),w=g[r],v=g[c];if(!w)throw Error(`not find ${r} price`);if(!v)throw Error(`not find ${c} price`);let h=o?v:w,P=o?w:v,{quote_per_base:S}=Pt(h.price,P.price),V=at(i,e.balances,n),C=I(f.toString()).add(V[r]?.value||"0").toFixed(0),D=I(y.toString()).add(V[c]?.value||"0").toFixed(0),A=o?C:D,B=o?D:C,F=Qe(I(Je(B,o?v.coin_decimals:w.coin_decimals)).mul(S).toString(),o?w.coin_decimals:v.coin_decimals).toString(),j=I(A).add(F).toFixed(0);return{remove_amount_a:C,remove_amount_b:D,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:A,swapAmountIn:B,swapAmountOut:I(F).toFixed(0,to.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,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(Ge(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 eo,fixCoinType as oo,getPackagerConfigs as Jt}from"@cetusprotocol/common-sdk";import{Transaction as io}from"@mysten/sui/transactions";import{bcs as Qt}from"@mysten/sui/bcs";var Ft=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:Qt.Address.serialize(e).toBytes()}});return!Qt.struct("CetusVaultVesterInfo",{is_pause:Qt.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:oo(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=Ut(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=Ut(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}=Jt(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=ue(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}=Jt(o),{versioned_id:n,clmm_vest_id:s}=Jt(i);t=t||new io;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(eo)],typeArguments:[d,u]})}return t}};import{Transaction as Be}from"@mysten/sui/transactions";import tt from"bn.js";import{extractStructTagFromType as no}from"@cetusprotocol/aggregator-sdk";import{buildPool as ao}from"@cetusprotocol/sui-clmm-sdk";import{d as k,fixCoinType as z,fromDecimalsAmount as st,toDecimalsAmount as Mt,CLOCK_ADDRESS as et,getPackagerConfigs as ft,ClmmPoolUtil as Zt,TypeNameRaw as Fe}from"@cetusprotocol/common-sdk";import{CoinAssist as Lt}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as so}from"@mysten/sui/utils";import ro from"decimal.js";import{BinUtils as ot,parseDlmmPool as co,StrategyType as Yt}from"@cetusprotocol/dlmm-sdk";import{bcs as x}from"@mysten/sui/bcs";var xt=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new pt(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 Ht(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 Be;await this.buildCollectRewardAndFeePayload(e,_),(await this._sdk.FullClient.sendSimulationTransaction(_,so("0x0")))?.Transaction?.events?.forEach(u=>{let{bcs:p,eventType:m}=u;if(m.includes("CollectDlmmFeeEvent")){let f=x.struct("CollectDlmmFeeEvent",{vault_id:x.Address,position_id:x.Address,amount_a:x.u64(),amount_b:x.u64(),protocol_fee_a:x.u64(),protocol_fee_b:x.u64()}).parse(p);t.push({coin_type:z(c,!1),value:f.amount_a}),t.push({coin_type:z(l,!1),value:f.amount_b})}if(m.includes("CollectClmmFeeEvent")){let f=x.struct("CollectClmmFeeEvent",{vault_id:x.Address,pool_id:x.Address,position_id:x.Address,amount_a:x.u64(),amount_b:x.u64(),protocol_fee_a:x.u64(),protocol_fee_b:x.u64()}).parse(p);o.push({coin_type:z(c,!1),value:f.amount_a}),o.push({coin_type:z(l,!1),value:f.amount_b})}if(m.includes("CollectClmmRewardEvent")){let f=x.struct("CollectClmmRewardEvent",{vault_id:x.Address,pool_id:x.Address,position_id:x.Address,reward_type:Fe,amount:x.u64(),protocol_fee:x.u64()}).parse(p);a.push({coin_type:z(f.reward_type.name,!1),value:f.amount})}if(m.includes("CollectDlmmRewardEvent")){let f=x.struct("CollectDlmmRewardEvent",{vault_id:x.Address,position_id:x.Address,reward_type:Fe,amount:x.u64(),protocol_fee:x.u64()}).parse(p);i.push({coin_type:z(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=>x.Address.parse(s.name.bcs));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=zt(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=zt(u);i.push(m)}else if(p.includes(`${o.package_id}::pool::Pool`)){let m=dt(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=ao(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=co(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=we(a),s=ye(a);o.push(n,s)}),(await this._sdk.FullClient.batchGetObjects(o,{json:!0})).forEach(a=>{let n=fe(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=be(n.json);t.push(r)}else if(s?.includes("CLMMPosition")){let r=ge(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}=ft(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}=ft(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(et)]})}):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(et)]})})}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}=ft(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}=ft(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 h of u)h.type==="DLMM"?h.position_list.forEach(P=>{let{pool_id:S}=P.position,V=h.certified_pool_obj[S],{reward_manager:C}=V,D=C.rewards.map(A=>z(A.reward_coin,!1));y=bt(D,p,m)}):h.type==="CLMM"&&h.position_list.forEach(P=>{let{pool_id:S}=P.position,V=h.certified_pool_obj[S],{rewarder_infos:C}=V,D=C.map(A=>z(A.coin_type,!1));y=bt([...y,...D],p,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(y,t);for(let h of u)if(h.type==="DLMM"){let{dlmm_pool:P}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:S}=ft(P),{position_list:V}=h;V.forEach(C=>{let{id:D,pool_id:A}=C.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(A),t.pure.address(D),t.object(S),t.object(i.versioned_id),t.object(et)]})})}else if(h.type==="CLMM"){let{clmm_pool:P}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:S}=ft(P),{position_list:V}=h;V.forEach(C=>{let{id:D,pool_id:A}=C.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(A),t.pure.address(D),t.object(S),t.object(i.versioned_id),t.object(et)]})})}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(et)]});let g,w;if(c&&c.swap_result){let{swap_result:h,coin_amount:P,mode:S,swap_slippage:V}=c,{swap_in_amount:C,route_obj:D}=h,A=Lt.buildCoinWithBalance(BigInt(P),S==="OnlyCoinA"?p:m,t),B=t.splitCoins(A,[C]),F={router:D,slippage:V,txb:t,inputCoin:B},j=await this._sdk.AggregatorClient.fixableRouterSwapV3(F);g=S==="OnlyCoinA"?A:j,w=S==="OnlyCoinA"?j:A}else g=l||Lt.buildCoinWithBalance(BigInt(n),p,t),w=_||Lt.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,w,t.object(et),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 Be;let p,m=r?k(r.burn_lp_amount).add(k(i)).toFixed(0):k(i).toFixed(0),f=k(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=Lt.buildCoinWithBalance(BigInt(i),_,t),r&&r.lp_burn_coin&&t.mergeCoins(p,[r.lp_burn_coin]));let{published_at:y,configs:g}=this._sdk.sdkOptions.vaultsV2,{config:w}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:v}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,h=t.moveCall({target:`${y}::vault::new_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),p,t.object(g.versioned_id)]}),P=[];for(let A of l)if(A.type==="DLMM"){let{position_list:B}=A;B.forEach(F=>{let{id:j,pool_id:L}=F.position,E=A.certified_pool_obj[L],{reward_manager:T}=E,M=T.rewards.map(R=>z(R.reward_coin,!1));P.push(...M),t.moveCall({target:`${y}::vault::withdraw_dlmm`,typeArguments:[d,u,_],arguments:[t.object(o),h,t.object(L),t.pure.address(j),t.object(w.global_config_id),t.object(w.versioned_id),t.object(g.versioned_id),t.object(et)]})})}else if(A.type==="CLMM"){let{position_list:B}=A;B.forEach(F=>{let{id:j,pool_id:L}=F.position,E=A.certified_pool_obj[L],{rewarder_infos:T}=E,M=T.map(R=>z(R.coin_type,!1));P.push(...M),t.moveCall({target:`${y}::vault::withdraw_clmm`,typeArguments:[d,u,_],arguments:[t.object(o),h,t.object(L),t.pure.address(j),t.object(v.global_config_id),t.object(g.versioned_id),t.object(et)]})})}await this.buildCollectRewardAndFeePayload(o,t,h),t.moveCall({target:`${y}::vault::finalize_buffer_assets`,typeArguments:[_],arguments:[t.object(o),h,t.object(g.versioned_id)]});let S=new Set;P.forEach(A=>S.add(A)),S.add(d),S.add(u);let V=Array.from(S),C=a!=="FixedOneSide"?[a==="OnlyCoinA"?u:d]:[],D=this.buildWithdrawBufferReward({reward_coin_types:V,pool_id:o,withdraw_cert:h,lp_token_type:_,not_transfer_coin_types:C},t);if(t.moveCall({target:`${y}::vault::destroy_withdraw_cert`,typeArguments:[_],arguments:[t.object(o),h,t.object(g.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let A=a==="OnlyCoinA",B=A?u:d,F=D.find(j=>j.coin_type===B).reward_coin_object_id;await this.handleWithSwap(t,F,d,u,m,o,A,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(k(p).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let m={from:d,target:u,amount:new tt(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},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: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",g="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:v,position_amount_b_rate:h}=l.is_multiple_pool?{position_amount_a_rate:k(.5),position_amount_b_rate:k(.5)}:await this.calculatePositionValueRates(l,p),{amountA:P,amountB:S}=X(v,h,o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=P,g=S;break}case"OnlyCoinA":{let{amountA:v,amountB:h}=X(k(1),k(0),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=v,g=h;break}case"OnlyCoinB":{let{amountA:v,amountB:h}=X(k(0),k(1),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=v,g=h;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,u=_,p=d,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,f=o==="OnlyCoinA",y=Zt.estLiquidityAndCoinAmountFromOneAmounts(u,p,new tt(m),f,!0,1,new tt(r)),g=f?k(y.coin_amount_b).div(y.coin_amount_a):k(y.coin_amount_a).div(y.coin_amount_b),w=f?k(r).toString():k(1).div(k(r)).toString();try{let C=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,m);C&&(w=k(C.swap_out_amount).div(C.swap_in_amount).toString())}catch{}let{swap_amount:v}=ht(m,f,w.toString(),g.toString()),h=k(m).sub(v).toFixed(0),P=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,v),S=k(P.swap_out_amount).mul(.999).toFixed(0),V=Zt.estLiquidityAndCoinAmountFromOneAmounts(u,p,new tt(h),f,!0,1,new tt(r));return f?V.coin_amount_b=S:V.coin_amount_a=S,{swap_result:P,liquidity_info:V}}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,w=_?a:i,v=st(y,g),h=st(f,w),P=k(h).div(v).toString(),S=await this.pythPrice.getLatestPrice([r,c],!0),V=S[r],C=S[c];if(!V||!C)throw new Error(`not find ${r} or ${c} price`);let D=ve(_?v:"0",_?"0":v,V.price,C.price,P,_),A=k(Mt(D,g).toString()).toFixed(0),B=k(l).sub(A).toFixed(0);if(k(B).lt(1)||k(A).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,A),j=k(F.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:_?B:j,amount_b:_?j: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:y,bin_step:g}=m,w=ot.getPricePerLamportFromBinId(m.active_id,m.bin_step),v=k(w).mul(1-.05),h=k(w).mul(1+.05),P=ot.getBinIdFromLamportPrice(v.toString(),m.bin_step,!1),S=ot.getBinIdFromLamportPrice(h.toString(),m.bin_step,!1),V=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:P,upper_bin_id:S,active_bin_of_pool:f,strategy_type:Yt.Spot}),C=_?k(V.amount_b).div(V.amount_a):k(V.amount_a).div(V.amount_b),D=_?ot.getPricePerLamportFromBinId(y,g):k(1).div(ot.getPricePerLamportFromBinId(y,g)).toString();try{let $=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,l);$&&(D=k($.swap_out_amount).div($.swap_in_amount).toString())}catch{}let{swap_amount:A,final_amount_a:B,final_amount_b:F}=ht(l,_,D,C.toString()),j=k(l).sub(A).toFixed(0),L=await this.findRouters(_?n.coin_type_a:n.coin_type_b,_?n.coin_type_b:n.coin_type_a,A),E=k(L.swap_out_amount).mul(.999).toFixed(0),T=_?j:E,M=_?E:j,R=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:T,amount_b:M,active_id:y,bin_step:g,lower_bin_id:P,upper_bin_id:S,active_bin_of_pool:f,strategy_type:Yt.Spot});return _?R.amount_b=L.swap_out_amount:R.amount_a=L.swap_out_amount,{swap_result:L,liquidity_info:R}}}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(k(o).eq(0))return{position_amount_a_rate:k(.5),position_amount_b_rate:k(.5)};let{position_amount_a:n,position_amount_b:s}=await Ht(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=k(st(n,r.coin_decimals)).mul(r.price),_=k(st(s,c.coin_decimals)).mul(c.price),d=k(l).add(_),u=k(l).div(d),p=k(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=k(st(l,o)).mul(r.price);_=k(Mt(k(d).div(c.price).toString(),i)).toFixed(0)}else{_=t;let d=k(st(_,i)).mul(c.price);l=k(Mt(k(d).div(r.price).toString(),o)).toFixed(0)}if(k(l).lt(1)||k(_).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=ot.getPricePerLamportFromBinId(t.active_id,t.bin_step),_=k(l).mul(1-.05),d=k(l).mul(1+.05),u=ot.getBinIdFromLamportPrice(_.toString(),t.bin_step,!1),p=ot.getBinIdFromLamportPrice(d.toString(),t.bin_step,!1),m={pool_id:r.pool_id,coin_amount:k(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:Yt.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:k(y).div(1e5).toFixed(0),deposit_amount_b:k(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}=Zt.estLiquidityAndCoinAmountFromOneAmounts(s,r,new tt(i),o,!0,1,new tt(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=k(p).add(c).toFixed(0),l=k(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=z(s,!1),l=z(r,!1),{dlmmRewarderList:_,dlmmFeeList:d,clmmRewarderList:u,clmmFeeList:p}=await this.getVaultsPositionRewarderAndFee(e.id),m=kt(e.buffer_assets,[...d,...p],[..._,...u]),f=await he(this._sdk,e.id,m,!0),y=await this.pythPrice.getLatestPrice([c,l],!0),g=y[c],w=y[l];if(!g)throw Error(`not find ${c} price`);if(!w)throw Error(`not find ${l} price`);let v={};v[c]={price:g,value:t.toString()},v[l]={price:w,value:o.toString()};let h=nt(v,n);return Ct(i,h,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 At(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 At(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}=Pt(_.price,d.price),p=t?n:s,m=t?s:n,f=Mt(k(st(m,t?l.coin_decimals:c.coin_decimals)).mul(u).toString(),t?c.coin_decimals:l.coin_decimals).toString(),y=k(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:k(f).toFixed(0,ro.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(no(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(k(o).lt(1))throw new Error("amount is less than 1");try{let n={from:e,target:t,amount:new tt(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 fo from"@cetusprotocol/dlmm-sdk";import{CoinAssist as lo,d as te,fixCoinType as H}from"@cetusprotocol/common-sdk";var Tt=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:g}=p,w=n?te(_).sub(n.burn_lp_amount).toFixed(0).toString():_,{return_coin_a:v,return_coin_b:h}=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),P={[H(y,!1)]:v,[H(g,!1)]:h},{coin_output_a:S,coin_output_b:V}=d,{from_coin_type:C,from_coin_amount:D,route_obj:A,to_coin_type:B}=S;if(A){let{to_coin:j}=await this.buildSwapAssetsTx({from_coin_type:C,swap_in_amount:D,liquidity_slippage:a,route_obj:A.route_obj,tx:t,from_coin_object_id:P[H(C,!1)]});P[H(B,!1)]=j}if(V.route_obj){let{from_coin_type:j,from_coin_amount:L,route_obj:E,to_coin_type:T}=V,{to_coin:M}=await this.buildSwapAssetsTx({from_coin_type:j,swap_in_amount:L,liquidity_slippage:a,route_obj:E.route_obj,tx:t,from_coin_object_id:P[H(j,!1)]});P[H(T,!1)]=M}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[H(f.coin_type_a,!1)],coin_b_input:P[H(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||lo.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=H(t.coin_type_a,!1),a=H(t.coin_type_b,!1),n=H(o.coin_type_a,!1),s=H(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&&te(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&&te(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 Z=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=De),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||Le.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||Le.createSDK({env:"mainnet",full_rpc_url:e.fullRpcUrl}),this._cetusDlmmSDK=o||fo.createSDK({env:e.env,full_rpc_url:e.fullRpcUrl}),this._vaults=new Bt(this),this._vaultsV2=new xt(this),this._migrate=new Tt(this);let{primary:i,secondary:a}=e.pythConfigs.hermes_service_urls,n=[i,a].filter(Boolean);this._aggregatorClient=new po({endpoint:e.aggregatorUrl,signer:uo("0x0"),client:this.FullClient,env:e.env==="testnet"?Me.Testnet:Me.Mainnet,pythUrls:n}),this._vest=new Ft(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||!_o(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=mo){this.CetusClmmSDK.updateCache(e,t,o)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var In=.2;var Qn=Z;export{pt as PythPriceModule,Ne as SdkEnv,Bt as VaultsModule,xt as VaultsModuleV2,Ft as VestModule,Z as VolatileVaultsSDK,we as buildCLMMMarketId,ge as buildCLMMMarketPosition,ye as buildDLMMMarketId,be as buildDLMMMarketPosition,Ko as buildDLMMPositionId,dt as buildPoolData,zt as buildPoolV2Data,fe as buildVaultMarket,le as buildVaultsBalance,Ht as buildVaultsBalanceV2,qo as buildVaultsBalanceV3,ht as calcExactSwapAmount,ve as calcSingleSideSwap,ce as calculateAum,he as calculateAumV2,Ee as calculateDepositRatioFixTokenA,nt as calculateTotalAumBasedOnQuote,qt as checkIsMinOrMaxIndex,yo as convertU64BytesToDecimal,Qn as default,De as defaultProvider,In as dlmm_split_rate,ae as estCoinAmountsFromTotalAmount,Ce as feed_map_mainnet,Ae as feed_map_testnet,At as getAmountBalanceByLpAmount,We as getAmountBalanceByLpAmountV2,X as getCoinAmountsFromRatio,So as getPositionPriceRange,de as getPriceWithFormattedDecimals,Re as getPrimitivePricesFromBaseQuote,Pt as getQuotePerBaseAndBasePerQuote,at as getShareBufferAssets,bt as getUpdatePriceType,kt as getVaultValidBalances,Ao as get_lp_amount_by_liquidity,Ct as get_lp_amount_by_tvl,_t as get_share_liquidity_by_amount,ke as initMainnetSDK,Se as initTestnetSDK,ei as initVaultSDK,ct as oraclePriceMultiplierDecimal,ue as parseVaultVestNFT,Ut as parseVaultsVestInfo,Vo as printTransaction,_e as toSuiObjectId,Pe as vaults_mainnet,Ve as vaults_testnet};
1
+ import{isValidSuiAddress as to,normalizeSuiAddress as eo}from"@mysten/sui/utils";import{AggregatorClient as oo,Env as ke}from"@cetusprotocol/aggregator-sdk";import{CACHE_TIME_24H as io}from"@cetusprotocol/common-sdk";import{CetusClmmSDK as Ve}from"@cetusprotocol/sui-clmm-sdk";import{Transaction as ht}from"@mysten/sui/transactions";import N from"bn.js";import{extractStructTagFromType as Ie}from"@cetusprotocol/aggregator-sdk";import{ClmmPoolUtil as yt,TickMath as At,d as R,fixCoinType as Q,fromDecimalsAmount as Ee,toDecimalsAmount as qe,CLOCK_ADDRESS as St,TypeNameRaw as Ke}from"@cetusprotocol/common-sdk";import{CoinAssist as Dt}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as $e}from"@mysten/sui/utils";import We from"decimal.js";import q from"bn.js";import qt from"decimal.js";import{ClmmPoolUtil as ne,TickMath as ct,MathUtil as Et,asIntN as wt,fixCoinType as J,extractStructTagFromType as ie,d as K}from"@cetusprotocol/common-sdk";import{ClmmPoolUtil as Se,d as st,TickMath as De,TickUtil as Zt,toDecimalsAmount as Yt}from"@cetusprotocol/common-sdk";import te from"bn.js";import ee from"decimal.js";var It=(b,e,t)=>{if(e==="min"){if(b===Zt.getMinIndex(t))return!0}else if(b===Zt.getMaxIndex(t))return!0;return!1};function co(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 Oe(b,e,t,o,i){let a=new te(10).pow(new te(o)),{coin_amount_b:n}=Se.estLiquidityAndCoinAmountFromOneAmounts(b,e,a,!0,!0,0,t),s=De.sqrtPriceX64ToPrice(t,o,i),r=st(a.toString()).mul(s).div(new ee(10).pow(o)).mul(new ee(10).pow(i)),c=r.add(n.toString()),l=r.div(c),d=st(n.toString()).div(c);return{ratioA:l,ratioB:d}}function z(b,e,t,o,i,a,n){let s=st(Yt(st(t).mul(b).div(o).toString(),a)).toFixed(0),r=st(Yt(st(t).mul(e).div(i).toString(),n)).toFixed(0);return{amountA:s,amountB:r}}function oe(b,e,t,o,i,a,n,s){let{ratioA:r,ratioB:c}=Oe(b,e,t,n,s);return z(r,c,o,i,a,n,s)}var rt=10n;function lt(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:J(n.coin_type_a,!1),coin_type_b:J(n.coin_type_b,!1),description:n.description,id:n.id,index:n.index,liquidity:n.liquidity,name:n.name,pool:n.pool,tick_lower_index:wt(BigInt(n.tick_lower_index.bits)),tick_upper_index:wt(BigInt(n.tick_upper_index.bits)),url:n.url}},{balances:r}=e.buffer_assets,c=r.contents.map(d=>{let{key:u,value:_}=d;return{coin_type:J(u,!1),value:_}});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:ie(e.quote_type).full_address,lp_token_type:ie(t).type_arguments[0],balances:c,protocol_fee_rate:e.protocol_fee_rate,version:"v1"}}async function fo(b,e=!0){b.getData().commands.forEach((t,o)=>{})}function vt(b,e){let t=K(b).div(e).toString(),o=K(e).div(b).toString();return{quote_per_base:t,base_per_quote:o}}function je(b,e,t,o){let i=10n**(rt+o-t),a=10n**(rt+t-o),n=Et.checkMulDivFloor(new q(b.toString()),new q(i.toString()),new q(e.toString()),64),s=Et.checkMulDivFloor(new q(e.toString()),new q(a.toString()),new q(b.toString()),64);return{primitive_base_price:BigInt(n.toString()),primitive_quote_price:BigInt(s.toString())}}function it(b,e){let t=e?b[e].price:{coin_type:"",price:"1",coin_decimals:6,oracle_price:1000000000000000000000000n},o=new q("0");for(let[i,{price:a,value:n}]of Object.entries(b)){let{primitive_quote_price:s}=je(BigInt(t.oracle_price),BigInt(a.oracle_price),BigInt(t.coin_decimals),BigInt(a.coin_decimals)),r=Et.checkMulDivFloor(new q(s.toString()),new q(n),new q((BigInt(10)**rt).toString()),64);o=o.add(r)}return o.toString()}async function ae(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:d,coin_type_a:u,coin_type_b:_}=t,p=[...o],m=n&&J(e.quote_type,!1),f=ct.tickIndexToSqrtPriceX64(r),y=ct.tickIndexToSqrtPriceX64(c),{coin_amount_a:g,coin_amount_b:w}=ne.getCoinAmountFromLiquidity(new q(l),new q(d),new q(f),new q(y),!1);p.push({coin_type:u,value:g.toString()}),p.push({coin_type:_,value:w.toString()});let v={};p.forEach(P=>{let D=J(P.coin_type,!1),A=K(P.value),B=v[D]||0;v[D]=A.add(B).toString()});let h=Object.entries(v).filter(([P,D])=>K(D).gt(0)).map(([P])=>P);if(m&&!h.includes(m)&&h.push(m),h.length===0)return"0";let C=await b.PythPrice.getLatestPrice(h,i),S={};return h.forEach(P=>{let D=C[P];if(D)S[P]={price:D,value:v[P]||"0"};else throw Error(`find ${P} price fail `)}),it(S,m).toString()}function Ct(b,e,t){return K(b).eq(0)?e:K(b).mul(e).div(t).toFixed(0,qt.ROUND_HALF_UP)}function bo(b,e,t){return K(b).eq(0)?"0":K(b).mul(e).div(t).toFixed(0,qt.ROUND_HALF_UP)}function _t(b,e,t){return K(b).eq(0)?"0":K(e).mul(t).div(b).toFixed(0,qt.ROUND_HALF_UP)}function nt(b,e,t){let o={};return e.forEach(i=>{let a=_t(t,b,i.value),n={coin_type:i.coin_type,value:a};o[n.coin_type]=n}),o}function se(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=_t(t.lp_token_treasury,e,c),d=ct.tickIndexToSqrtPriceX64(a),u=ct.tickIndexToSqrtPriceX64(n),_=ne.getCoinAmountFromLiquidity(new q(l),new q(o.current_sqrt_price),d,u,!0),p=_.coin_amount_a.toString(),m=_.coin_amount_b.toString(),f=nt(e,t.balances,t.lp_token_treasury),y=K(p).add(i&&f[s]?.value||"0").toFixed(0),g=K(m).add(i&&f[r]?.value||"0").toFixed(0),w=i?Object.values(f).filter(h=>h.coin_type!==s&&h.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:w}}function Pt(b,e,t){let o=[];return e.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),t.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),b.forEach(i=>{K(i.value).gt(0)&&o.push(i)}),o}function ft(b,e,t){let o=new Set;return b.forEach(i=>o.add(i)),o.add(e),o.add(t),Array.from(o)}function go(b,e){if(!rt)throw new Error("oraclePriceMultiplierDecimal is required");if(b===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(rt- -e);return b*t}return b/10n**(e+rt)}function ho(b){return`0x${Buffer.from(b).toString("hex")}`}function yo(b,e,t,o,i){let a="0",n="0";return It(b,"min",Number(t))?a="0":a=ct.tickIndexToPrice(Number(b),o,i).toString(),It(e,"max",Number(t))?n="\u221E":n=ct.tickIndexToPrice(Number(e),o,i).toString(),{minPrice:a,maxPrice:n}}function Kt(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:wt(BigInt(t.tick_lower_index.bits)),tick_upper_index:wt(BigInt(t.tick_upper_index.bits)),coin_type_a:J(t.coin_type_a.name,!1),coin_type_b:J(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:J(e.coin_a.name,!1),coin_type_b:J(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 kt,fixCoinType as W,extractStructTagFromType as Be,d as O,TickMath as dt,ClmmPoolUtil as $t}from"@cetusprotocol/common-sdk";import{parseLiquidityShares as Wt}from"@cetusprotocol/dlmm-sdk";import ce from"decimal.js";import{bcs as bt}from"@mysten/sui/bcs";import{deriveDynamicFieldID as Me,deriveObjectID as le}from"@mysten/sui/utils";import G 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(u=>u.key),positions_handle:{id:i.id,size:i.size},position_list:[],coin_type_a:W(n,!1),coin_type_b:W(s,!1),vault_id:r,position_keys:c.contents}}catch{return}}function Fe(b){return{uri:b.uri,index:b.index,id:b.id,name:b.name,pool_id:b.pool_id,lower_bin_id:kt(BigInt(b.lower_bin_id.bits)),upper_bin_id:kt(BigInt(b.upper_bin_id.bits)),liquidity_shares:b.liquidity_shares,description:b.description,coin_type_a:W(b.coin_type_a,!1),coin_type_b:W(b.coin_type_b,!1)}}function Le(b){return{id:b.id,pool_id:b.pool,index:b.index,description:b.description,uri:b.url,liquidity:b.liquidity,tick_lower_index:kt(BigInt(b.tick_lower_index.bits)),tick_upper_index:kt(BigInt(b.tick_upper_index.bits)),name:b.name,coin_type_a:W(b.coin_type_a,!1),coin_type_b:W(b.coin_type_b,!1)}}function de(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(d=>{let{key:u,value:_}=d;return{coin_type:W(u,!1),value:_}}),a=Fe(e),n=a.lower_bin_id,s=a.liquidity_shares.map((d,u)=>({bin_id:n+u,liquidity:d})).filter(d=>O(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 ue(b){let{position:e,amounts:t,id:o}=b,i=t.contents.map(s=>{let{key:r,value:c}=s;return{coin_type:W(r,!1),value:c}}),a=Le(e);return{id:o,position:a,amounts:i}}function Ut(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:d,protocol_fee_rate:u,protocol_fees:_,quote_type:p}=e,m=(Number(o)&1)!==0,f=(Number(o)&2)!==0,{balances:y}=i,g=y.contents.map(h=>{let{key:C,value:S}=h;return{coin_type:W(C,!1),value:S}}),w=p.pos0;return{id:r,lp_token_treasury:l.total_supply.value,hard_cap:s,quote_type:w?W(w,!1):void 0,protocol_fee_rate:u,buffer_assets:g,protocol_fees_handle:{id:_.id,size:_.size},markets_handle:{id:d.id,size:d.size},markets:[],action_status:{is_deposit_allowed:m,is_withdraw_allowed:f},is_multiple_pool:!1,last_aum:c,coin_type_a:W(a,!1),coin_type_b:W(n,!1),lp_token_type:Be(t).type_arguments[0],version:"v2"}}async function pe(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",d="0";for(let g of a)if(g.type==="DLMM"){let{position_list:w}=g;for(let v of w){let{lower_bin_id:h,liquidity_shares:C,pool_id:S}=v.position,V=g.certified_pool_obj[S],P=await b.CetusDlmmSDK.Pool.getBinInfo(V.bin_manager.bin_manager_handle,V.active_id,V.bin_step,!1),D=Wt(C,V.bin_step,h,P);l=O(l).add(D.amount_a.toString()).toFixed(0),d=O(d).add(D.amount_b.toString()).toFixed(0)}}else if(g.type==="CLMM"){let{position_list:w}=g;for(let v of w){let{tick_lower_index:h,tick_upper_index:C,liquidity:S,pool_id:V}=v.position,P=g.certified_pool_obj[V],D=dt.tickIndexToSqrtPriceX64(h),A=dt.tickIndexToSqrtPriceX64(C),{coin_amount_a:B,coin_amount_b:M}=$t.getCoinAmountFromLiquidity(new G(S),new G(P.current_sqrt_price),new G(D),new G(A),!1);l=O(l).add(B.toString()).toFixed(0),d=O(d).add(M.toString()).toFixed(0)}}let u=n&&W(n,!1);c.push({coin_type:s,value:l}),c.push({coin_type:r,value:d});let _={};c.forEach(g=>{let w=W(g.coin_type,!1),v=O(g.value),h=_[w]||0;_[w]=v.add(h).toString()});let p=Object.entries(_).filter(([g,w])=>O(w).gt(0)).map(([g])=>g);if(u&&!p.includes(u)&&p.push(u),p.length===0)return"0";let m=await b.VaultsV2.PythPrice.getLatestPrice(p,o),f={};return p.forEach(g=>{let w=m[g];if(w)f[g]={price:w,value:_[g]||"0"};else throw Error(`find ${g} price fail `)}),it(f,u).toString()}async function Nt(b,e,t,o,i=!0){let a=await Vt(b,e,t,i);return a.owner=o||"0x0",a}async function Mo(b,e,t,o,i=!0){let a=await xe(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(O(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=O(e).div(s),d=[],u=[],_=O(0),p=O(0);for(let h of a)if(h.type==="DLMM"){let{position_list:C}=h;for(let S of C){let{lower_bin_id:V,upper_bin_id:P,liquidity_shares:D,id:A,pool_id:B}=S.position,M=h.certified_pool_obj[B],{bin_manager:j,bin_step:L,active_id:I}=M,T=await b.CetusDlmmSDK.Pool.getBinInfo(j.bin_manager_handle,I,L,!1),F=Wt(D.map(ot=>O(ot.toString()).mul(l).toFixed(0,ce.ROUND_HALF_UP).toString()),L,V,T),E=F.amount_a,$=F.amount_b,U=F.bins.filter(ot=>O(ot.liquidity).gt(0)),xt=U.length>0?U[0].bin_id:F.bins[0].bin_id,Tt=U.length>0?U[U.length-1].bin_id:F.bins[F.bins.length-1].bin_id,Rt={position_id:A,certified_pool_id:M.id,liquidity_shares:D,valid_lower_bin_id:xt,valid_upper_bin_id:Tt,original_lower_bin_id:V,original_upper_bin_id:P,position_amount_a:E,position_amount_b:$,coin_type_a:r,coin_type_b:c,bin_infos:{bins:U,amount_a:F.amount_a,amount_b:F.amount_b}};d.push(Rt),_=_.add(O(E)),p=p.add(O($))}}else if(h.type==="CLMM"){let{position_list:C}=h;for(let S of C){let{tick_lower_index:V,tick_upper_index:P,liquidity:D,id:A,pool_id:B}=S.position,M=h.certified_pool_obj[B],j=O(D).mul(l).toFixed(0),L=dt.tickIndexToSqrtPriceX64(V),I=dt.tickIndexToSqrtPriceX64(P),T=$t.getCoinAmountFromLiquidity(new G(j),new G(M.current_sqrt_price),L,I,!1),F=T.coin_amount_a.toString(),E=T.coin_amount_b.toString(),$={position_id:A,certified_pool_id:M.id,liquidity:j,tick_lower_index:V,tick_upper_index:P,position_amount_a:F,position_amount_b:E};u.push($),_=_.add(O(F)),p=p.add(O(E))}}let m=nt(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",y=o&&m[c]?.value||"0",g=_.add(f).toFixed(0),w=p.add(y).toFixed(0),v=o?Object.values(m).filter(h=>h.coin_type!==r&&h.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:w,position_amount_a:_.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:d,clmm_balances:u,share_buffer_assets:v}}async function xe(b,e,t,o=!0){let{pool:i,markets:a}=t,{lp_token_type:n,lp_token_treasury:s,coin_type_a:r,coin_type_b:c}=i;if(O(s).isZero())return{vault_id:i.id,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=O(e).div(s),d=[],u=[],_=O(0),p=O(0);for(let h of a)if(h.type==="DLMM"){let{position_list:C}=h;for(let S of C){let{lower_bin_id:V,upper_bin_id:P,liquidity_shares:D,id:A,pool_id:B}=S.position,M=h[B],{bin_manager:j,bin_step:L,active_id:I}=M,T=await b.CetusDlmmSDK.Pool.getBinInfo(j.bin_manager_handle,I,L,!1),F=Wt(D.map(ot=>O(ot.toString()).mul(l).toFixed(0,ce.ROUND_HALF_UP).toString()),L,V,T),E=F.amount_a,$=F.amount_b,U=F.bins.filter(ot=>O(ot.liquidity).gt(0)),xt=U.length>0?U[0].bin_id:F.bins[0].bin_id,Tt=U.length>0?U[U.length-1].bin_id:F.bins[F.bins.length-1].bin_id,Rt={position_id:A,certified_pool_id:M.id,liquidity_shares:D,valid_lower_bin_id:xt,valid_upper_bin_id:Tt,original_lower_bin_id:V,original_upper_bin_id:P,position_amount_a:E,position_amount_b:$,coin_type_a:r,coin_type_b:c,bin_infos:{bins:U,amount_a:F.amount_a,amount_b:F.amount_b}};d.push(Rt),_=_.add(O(E)),p=p.add(O($))}}else if(h.type==="CLMM"){let{position_list:C}=h;for(let S of C){let{tick_lower_index:V,tick_upper_index:P,liquidity:D,id:A,pool_id:B}=S.position,M=h[B],j=O(D).mul(l).toFixed(0),L=dt.tickIndexToSqrtPriceX64(V),I=dt.tickIndexToSqrtPriceX64(P),T=$t.getCoinAmountFromLiquidity(new G(j),new G(M.current_sqrt_price),L,I,!1),F=T.coin_amount_a.toString(),E=T.coin_amount_b.toString(),$={position_id:A,certified_pool_id:M.id,liquidity:j,tick_lower_index:V,tick_upper_index:P,position_amount_a:F,position_amount_b:E};u.push($),_=_.add(O(F)),p=p.add(O(E))}}let m=nt(e,i.buffer_assets,s),f=o&&m[r]?.value||"0",y=o&&m[c]?.value||"0",g=_.add(f).toFixed(0),w=p.add(y).toFixed(0),v=o?Object.values(m).filter(h=>h.coin_type!==r&&h.coin_type!==c):Object.values(m);return{vault_id:i.id,lp_token_type:n,lp_token_balance:e,owner:"0x0",coin_type_a:r,coin_type_b:c,amount_a:g,amount_b:w,position_amount_a:_.toFixed(0),position_amount_b:p.toFixed(0),dlmm_balances:d,clmm_balances:u,share_buffer_assets:v}}function me(b){let e=bt.vector(bt.u8()).serialize(new TextEncoder().encode("DLMM_MARKET")).toBytes();return le(b,"vector<u8>",e)}function fe(b){let e=bt.vector(bt.u8()).serialize(new TextEncoder().encode("CLMM_MARKET")).toBytes();return le(b,"vector<u8>",e)}function Fo(b,e){let t=bt.Address.serialize(e).toBytes();return Me(b,"0x2::object::ID",t)}function gt(b,e,t,o){let i=O(b),a=O(t),n=O(o),s=i,r=e?i:O(0),c=e?O(0):i,l=n,d=O(n).mul(.999),u=O(0),_=s,p=null;function m(g){if(e){let w=r.minus(g),v=c.plus(g.mul(a));return{A:w,B:v,R:v.div(w)}}else{let w=r.plus(g.mul(a)),v=c.minus(g);return{A:w,B:v,R:w.div(v)}}}for(let g=0;g<120;g++){let w=u.plus(_).div(2),{A:v,B:h,R:C}=m(w);if(v.lte(0)||h.lte(0)){_=w;continue}if(C.gt(l))_=w;else if(C.lt(d))u=w;else{if(p=w,O(d).eq(0))break;_=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 be(b,e,t,o,i,a){if(a){let n=O(b).mul(t).sub(O(e).mul(o)),s=O(t).add(O(i).mul(o));return(O(s).eq(0)?O(0):O(n).div(s)).toString()}else{let n=O(e).mul(o).sub(O(b).mul(t)),s=O(i).mul(t).add(o);return(O(s).eq(0)?O(0):O(n).div(s)).toString()}}import{CLOCK_ADDRESS as Ht,PythPriceModule as Te}from"@cetusprotocol/common-sdk";function Re(b,e){let{primary:t,secondary:o}=b.hermes_service_urls,i=[t,o].filter(Boolean);return{pyth_package_id:b.pyth_package_id,pyth_published_at:b.pyth_published_at,pyth_state_id:b.pyth_state_id,wormhole_state_id:b.wormhole_state_id,hermes_service_urls:i,feed_info_handle:e}}var ut=class{_sdk;_pyth;pythConfigs;global_config_id;pyth_oracle_id;vaults_published_at;versioned_id;isV2;constructor(e,t,o,i,a,n,s,r){this._sdk=e,this.pythConfigs=t,this.vaults_published_at=o,this.global_config_id=i,this.pyth_oracle_id=a,this.versioned_id=n,this.isV2=r,this._pyth=new Te(e.FullClient,Re(t,s))}get sdk(){return this._sdk}getFeedInfoList(e){return this._pyth.getFeedInfoList(e)}priceCheck(e,t=60){return this._pyth.priceCheck(e,t)}getLatestPrice(e,t=!1){return this._pyth.getLatestPrice(e,t)}getFeedInfo(e,t){return this._pyth.getFeedInfo(e,t)}getFeedInfoByJson(e){return this._pyth.getFeedInfoByJson(e)}async buildUpdatePythPricePayload(e,t){let{pyth_state_id:o}=this.pythConfigs;return this._pyth.buildUpdatePythPricePayload(e,t,({tx:i,coinType:a,priceUpdatesHotPotato:n,priceInfoObjectId:s})=>{if(this.isV2){let[c]=i.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[a],arguments:[i.object(this.pyth_oracle_id),i.object(o),n,i.object(s),i.object(Ht),i.object(this.versioned_id)]});return c}let[r]=i.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price`,typeArguments:[a],arguments:[i.object(this.pyth_oracle_id),i.object(this.global_config_id),i.object(o),n,i.object(s),i.object(Ht)]});return r})}async buildUpdatePythPricePayloadV2(e,t){return this._pyth.buildUpdatePythPricePayloadV2(e,t,({tx:o,coinType:i,priceInfoObjectId:a})=>{o.moveCall({target:`${this.vaults_published_at}::pyth_oracle::update_price_into_pyth_oracle`,typeArguments:[i],arguments:[o.object(this.pyth_oracle_id),o.object(a),o.object(Ht),o.object(this.versioned_id)]})})}};import{bcs as pt}from"@mysten/sui/bcs";var Ot=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaults:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new ut(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 se(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:d}=i,u=new ht;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},u),this.buildCollectFeePayload({lp_token_type:s,pool_id:e,clmm_pool_id:c,coin_type_a:l,coin_type_b:d},u);let _=await this._sdk.FullClient.sendSimulationTransaction(u,$e("0x0")),p=`${t}::pool::FeeClaimedEvent`,m=`${t}::pool::RewardClaimedEvent`,f=[],y=[];return _.Transaction?.events?.forEach(g=>{let{bcs:w,eventType:v}=g;if(v===p){let h=pt.struct("FeeClaimedEvent",{amount_a:pt.u64(),amount_b:pt.u64()}).parse(w);f.push({coin_type:Q(l,!1),value:h.amount_a}),f.push({coin_type:Q(d,!1),value:h.amount_b})}if(v===m){let h=pt.struct("RewardClaimedEvent",{amount:pt.u64(),reward_type:Ke}).parse(w);y.push({coin_type:Q(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=>pt.Address.parse(s.name.bcs));return n.length>0&&((await i.batchGetObjects(n,{json:!0})).forEach(r=>{let c=lt(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=lt(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=lt(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:d}=this._sdk.sdkOptions.vaults;return t=t||new ht,r.forEach(u=>{t.moveCall({target:`${c}::pool::collect_reward`,typeArguments:[o,i,s,u],arguments:[t.object(a),t.object(l.global_config_id),t.object(d.global_config_id),t.object(n),t.object(d.global_vault_id),t.object(St)]})}),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 ht,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:d,id:u,coin_type_a:_,coin_type_b:p}=c,m=d.map(S=>Q(S.coin_type,!1)),f=ft(m,c.coin_type_a,c.coin_type_b),{published_at:y,configs:g,clmm_configs:w}=this._sdk.sdkOptions.vaults;t=t||new ht,t=this.buildCollectRewardPayload({reward_coin_types:m,lp_token_type:l,pool_id:o,clmm_pool_id:u,coin_type_a:_,coin_type_b:p},t),t=this.buildCollectFeePayload({lp_token_type:l,pool_id:o,clmm_pool_id:u,coin_type_a:_,coin_type_b:p},t),t=await this.pythPrice.buildUpdatePythPricePayload(f,t),t.moveCall({target:`${y}::pool::calculate_aum`,typeArguments:[_,p,l],arguments:[t.object(o),t.object(g.global_config_id),t.object(g.pyth_oracle_id),t.object(w.global_config_id),t.object(u),t.object(St)]});let v,h;if(s&&s.swap_result){let{swap_result:S,coin_amount:V,mode:P,swap_slippage:D}=s,{swap_in_amount:A,swap_out_amount:B,route_obj:M}=S,j=Dt.buildCoinWithBalance(BigInt(V),P==="OnlyCoinA"?_:p,t),L=t.splitCoins(j,[A]),I={router:M,slippage:D,txb:t,inputCoin:L},T=await this._sdk.AggregatorClient.fixableRouterSwapV3(I);v=P==="OnlyCoinA"?j:T,h=P==="OnlyCoinA"?T:j}else v=Dt.buildCoinWithBalance(BigInt(i),_,t),h=Dt.buildCoinWithBalance(BigInt(a),p,t);let C=t.moveCall({target:`${y}::pool::${n?"deposit_for":"deposit"}`,typeArguments:[_,p,l],arguments:[t.object(o),t.object(g.global_config_id),t.object(g.pyth_oracle_id),t.object(w.global_config_id),t.object(u),v,h,t.object(St)]});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:d}=await this.getVaultAndPool(o,!0),{published_at:u,configs:_,clmm_configs:p}=this._sdk.sdkOptions.vaults;t=t||new ht;let{lp_token_type:m,clmm_vault:f,lp_token_treasury:y}=l,{rewarder_infos:g,id:w,coin_type_a:v,coin_type_b:h,liquidity:C}=d,S=g.map(j=>Q(j.coin_type,!1));t=this.buildCollectRewardPayload({reward_coin_types:S,lp_token_type:m,pool_id:o,clmm_pool_id:w,coin_type_a:v,coin_type_b:h},t),t=this.buildCollectFeePayload({lp_token_type:m,pool_id:o,clmm_pool_id:w,coin_type_a:v,coin_type_b:h},t);let V,P=r?R(r.burn_lp_amount).add(R(i)).toFixed(0):R(i).toFixed(0),D=R(i).isZero();if(D&&!r)throw new Error("burn_lp_amount or extra_burn_lp_coin is zero");D?V=r.lp_burn_coin:(V=Dt.buildCoinWithBalance(BigInt(i),m,t),r&&t.mergeCoins(V,[r.lp_burn_coin]));let[A,B,M]=t.moveCall({target:`${u}::pool::withdraw`,typeArguments:[v,h,m],arguments:[t.object(o),t.object(_.global_config_id),t.object(p.global_config_id),t.object(w),V,t.object(St)]});if(this.buildWithdrawBufferReward({reward_coin_types:S.filter(j=>![Q(v,!1),Q(h,!1)].includes(j)),pool_id:o,withdraw_cert:M,lp_token_type:m},t),t.moveCall({target:`${u}::pool::destory_withdraw_cert`,typeArguments:[m],arguments:[t.object(o),t.object(_.global_config_id),M]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let j=a==="OnlyCoinA",L=j?B:A,I=_t(y,P,C.toString()),T=await this.handleWithSwap(t,L,v,h,P,o,j,n,s,[{poolID:w,ticklower:f.wrapped_position.tick_lower_index,tickUpper:f.wrapped_position.tick_upper_index,deltaLiquidity:Number(I)}],c);if(c&&T)return j?t.mergeCoins(T,[A]):t.mergeCoins(T,[B]),{return_coin_a:j?T:void 0,return_coin_b:j?void 0:T};t.transferObjects([j?A:B],this._sdk.senderAddress)}else{if(c)return{return_coin_a:A,return_coin_b:B};t.transferObjects([A,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,d){let{receive_amount_a:u,receive_amount_b:_}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),p=s?i:o,m=s?o:i,f=s?_:u;if(R(f).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let y={from:p,target:m,amount:new N(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 w={router:g,inputCoin:t,slippage:r,txb:e,partner:c},v=await this._sdk.AggregatorClient.fixableRouterSwapV3(w);if(d)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:d,coin_type_a:u,coin_type_b:_}=s.clmm_vault.wrapped_position,p="0",m="0",f=await this.pythPrice.getLatestPrice([u,_],!0),y=f[u],g=f[_];if(!y||!g)throw new Error("get coin price failed");switch(a){case"FixedOneSide":{let{amountA:w,amountB:v}=oe(l,d,new N(c),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"FlexibleBoth":{let{amountA:w,amountB:v}=z(R(.5),R(.5),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"OnlyCoinA":{let{amountA:w,amountB:v}=z(R(1),R(0),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.toString();break}case"OnlyCoinB":{let{amountA:w,amountB:v}=z(R(0),R(1),o,y.price,g.price,y.coin_decimals,g.coin_decimals);p=w.toString(),m=v.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,d=n.wrapped_position.tick_upper_index,u=t==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,_=t==="OnlyCoinA",p=yt.estLiquidityAndCoinAmountFromOneAmounts(l,d,new N(u),_,!0,1,new N(s)),m=_?R(p.coin_amount_b).div(p.coin_amount_a):R(p.coin_amount_a).div(p.coin_amount_b),f=_?R(s).toString():R(1).div(R(s)).toString();try{let C=await this._sdk.VaultsV2.findRouters(_?r:c,_?c:r,u);C&&(f=R(C.swap_out_amount).div(C.swap_in_amount).toString())}catch{}let{swap_amount:y}=gt(u,_,f.toString(),m.toString()),g=R(u).sub(y).toFixed(0),w=await this._sdk.VaultsV2.findRouters(_?r:c,_?c:r,y),v=R(w.swap_out_amount).mul(.999).toFixed(0),h=yt.estLiquidityAndCoinAmountFromOneAmounts(l,d,new N(g),_,!0,1,new N(s));return _?h.coin_amount_b=v:h.coin_amount_a=v,{swap_result:w,liquidity_info:h}}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:d}=await this.getVaultAndPool(i,!1);switch(o){case"FixedOneSide":{let{fixed_amount:u,fixed_coin_a:_}=e,{other_amount:p,lp_amount:m}=await this.calculateDepositOtherSide(l,d,u,_,t,a);c=m,_?(n=u,s=p):(s=u,n=p);break}case"FlexibleBoth":{let{coin_amount_a:u,coin_amount_b:_}=e;n=u,s=_;break}case"OnlyCoinA":{if(e.re_balance){let u=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:p}=u,{coin_amount_a:m,coin_amount_b:f}=p;n=m,s=f,r={swap_result:_,coin_amount:e.coin_amount_a}}else n=e.coin_amount_a;break}case"OnlyCoinB":{if(e.re_balance){let u=await this.calculateBalanceSwapAmount(e),{swap_result:_,liquidity_info:p}=u,{coin_amount_a:m,coin_amount_b:f}=p;n=m,s=f,r={swap_result:_,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,d,n,s).then(u=>{t?.onSuccess(u,a)}).catch(u=>{t?.onError(u,a)}):c=await this.calculateDepositLpAmountBoth(l,d,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,d=yt.estLiquidityAndCoinAmountFromOneAmounts(c,l,new N(o),i,!0,1,new N(r)),{coin_amount_a:u,coin_amount_b:_}=d;if(a)this.calculateDepositLpAmountBoth(e,t,u.toString(),_.toString()).then(p=>{a.onSuccess(p,n)}).catch(p=>{a.onError(p,n)});else{let p=await this.calculateDepositLpAmountBoth(e,t,u.toString(),_.toString());return{other_amount:i?_.toString():u.toString(),lp_amount:p}}return{other_amount:i?_.toString():u.toString(),lp_amount:void 0}}async calculateDepositLpAmountBoth(e,t,o,i){let{lp_token_treasury:a,hard_cap:n}=e,s=Q(t.coin_type_a,!1),r=Q(t.coin_type_b,!1),{rewarderList:c,feeList:l}=await this.getVaultsPositionRewarderAndFee(e.id),d=Pt(e.balances,l,c),u=await ae(this,e,t,d,!0),_=await this.pythPrice.getLatestPrice([s,r],!0),p=_[s],m=_[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=it(f,e.quote_type);return Ct(a,y,u)}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 d=await this.calculateWithdrawOtherSide(c,l,e.burn_lp_amount);n=d.burn_lp_amount,i=d.receive_amount_a,a=d.receive_amount_b,s=d.remove_liquidity;break;case"OnlyCoinA":{let u=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!0);n=u.burn_lp_amount,i=u.receive_amount_a,a=u.receive_amount_b,s=u.remove_liquidity,r=u.swap;break}case"OnlyCoinB":{let u=await this.calculateWithdrawOnlyCoin(c,l,e.burn_lp_amount,!1);n=u.burn_lp_amount,i=u.receive_amount_a,a=u.receive_amount_b,s=u.remove_liquidity,r=u.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,d=i.wrapped_position.liquidity,u=At.tickIndexToSqrtPriceX64(c),_=At.tickIndexToSqrtPriceX64(l),p=_t(a,o,d),{coin_amount_a:m,coin_amount_b:f}=yt.getCoinAmountFromLiquidity(new N(p),new N(n),u,_,!1),y=nt(o,e.balances,a),g=R(m.toString()).add(y[s]?.value||"0").toFixed(0),w=R(f.toString()).add(y[r]?.value||"0").toFixed(0);return{receive_amount_a:g,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,d=a.wrapped_position.tick_upper_index,u=a.wrapped_position.liquidity,_=At.tickIndexToSqrtPriceX64(l),p=At.tickIndexToSqrtPriceX64(d),m=_t(n,i,u),{coin_amount_a:f,coin_amount_b:y}=yt.getCoinAmountFromLiquidity(new N(m),new N(s),_,p,!1),g=await this.pythPrice.getLatestPrice([r,c],!0),w=g[r],v=g[c];if(!w)throw Error(`not find ${r} price`);if(!v)throw Error(`not find ${c} price`);let h=o?v:w,C=o?w:v,{quote_per_base:S}=vt(h.price,C.price),V=nt(i,e.balances,n),P=R(f.toString()).add(V[r]?.value||"0").toFixed(0),D=R(y.toString()).add(V[c]?.value||"0").toFixed(0),A=o?P:D,B=o?D:P,M=qe(R(Ee(B,o?v.coin_decimals:w.coin_decimals)).mul(S).toString(),o?w.coin_decimals:v.coin_decimals).toString(),j=R(A).add(M).toFixed(0);return{remove_amount_a:P,remove_amount_b:D,burn_lp_amount:i,removeLiquidity:m,is_coin_a:o,originAmount:A,swapAmountIn:B,swapAmountOut:R(M).toFixed(0,We.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,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(Ie(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 ge={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"}]}}},_i={"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&&(ge.fullRpcUrl=b),new Z(ge,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"}]}}},mi={};function we(b,e,t){return b&&(ye.fullRpcUrl=b),new Z(ye,e,t)}var Ue=(t=>(t.mainnet="mainnet",t.testnet="testnet",t))(Ue||{});function hi(b,e,t){let{env:o,fullNodeUrl:i}=b;return o==="mainnet"?he(i,e,t):we(i,e,t)}var ve=["CETUS","TURBOS","STEAMM","SPRINGSUI","HAEDAL","FLOWX","AFTERMATH","ALPHAFI","BLUEFIN","METASTABLE","VOLO","SCALLOP","KRIYA","FLOWXV3","DEEPBOOKV3","AFSUI","BLUEMOVE","KRIYAV3","HAEDALPMM","OBRIC"];import{CLOCK_ADDRESS as Ne,fixCoinType as He,getPackagerConfigs as Xt}from"@cetusprotocol/common-sdk";import{Transaction as Xe}from"@mysten/sui/transactions";import{bcs as zt}from"@mysten/sui/bcs";var jt=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:He(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=Kt(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=Kt(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}=Xt(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}=Xt(o),{versioned_id:n,clmm_vest_id:s}=Xt(i);t=t||new Xe;for(let r of e){let{vault_id:c,vesting_nft_id:l,period:d,coin_type_a:u,coin_type_b:_}=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(d),t.object(Ne)],typeArguments:[u,_]})}return t}};import{Transaction as Ce}from"@mysten/sui/transactions";import Y from"bn.js";import{extractStructTagFromType as ze}from"@cetusprotocol/aggregator-sdk";import{buildPool as Je}from"@cetusprotocol/sui-clmm-sdk";import{d as k,fixCoinType as H,fromDecimalsAmount as at,toDecimalsAmount as Bt,CLOCK_ADDRESS as tt,getPackagerConfigs as mt,ClmmPoolUtil as Jt,TypeNameRaw as Pe}from"@cetusprotocol/common-sdk";import{CoinAssist as Mt}from"@cetusprotocol/common-sdk";import{normalizeSuiAddress as Qe}from"@mysten/sui/utils";import Ge from"decimal.js";import{BinUtils as et,parseDlmmPool as Ze,StrategyType as Qt}from"@cetusprotocol/dlmm-sdk";import{bcs as x}from"@mysten/sui/bcs";var Ft=class{_sdk;pythPrice;constructor(e){this._sdk=e;let{vaultsV2:t,pythConfigs:o}=e.sdkOptions;this.pythPrice=new ut(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 Nt(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(d=>{let{id:u,pool_id:_}=d.position,p=c.certified_pool_obj[_],{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:u,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:u,coin_type_a:s,coin_type_b:r,withdraw_cert:o},t)})}else if(c.type==="CLMM"){let{position_list:l}=c;l.forEach(d=>{let{id:u,pool_id:_}=d.position,p=c.certified_pool_obj[_],{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:u,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:u,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,d=new Ce;await this.buildCollectRewardAndFeePayload(e,d),(await this._sdk.FullClient.sendSimulationTransaction(d,Qe("0x0")))?.Transaction?.events?.forEach(_=>{let{bcs:p,eventType:m}=_;if(m.includes("CollectDlmmFeeEvent")){let f=x.struct("CollectDlmmFeeEvent",{vault_id:x.Address,position_id:x.Address,amount_a:x.u64(),amount_b:x.u64(),protocol_fee_a:x.u64(),protocol_fee_b:x.u64()}).parse(p);t.push({coin_type:H(c,!1),value:f.amount_a}),t.push({coin_type:H(l,!1),value:f.amount_b})}if(m.includes("CollectClmmFeeEvent")){let f=x.struct("CollectClmmFeeEvent",{vault_id:x.Address,pool_id:x.Address,position_id:x.Address,amount_a:x.u64(),amount_b:x.u64(),protocol_fee_a:x.u64(),protocol_fee_b:x.u64()}).parse(p);o.push({coin_type:H(c,!1),value:f.amount_a}),o.push({coin_type:H(l,!1),value:f.amount_b})}if(m.includes("CollectClmmRewardEvent")){let f=x.struct("CollectClmmRewardEvent",{vault_id:x.Address,pool_id:x.Address,position_id:x.Address,reward_type:Pe,amount:x.u64(),protocol_fee:x.u64()}).parse(p);a.push({coin_type:H(f.reward_type.name,!1),value:f.amount})}if(m.includes("CollectDlmmRewardEvent")){let f=x.struct("CollectDlmmRewardEvent",{vault_id:x.Address,position_id:x.Address,reward_type:Pe,amount:x.u64(),protocol_fee:x.u64()}).parse(p);i.push({coin_type:H(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=>x.Address.parse(s.name.bcs));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=Ut(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 d=await this._sdk.FullClient.batchGetObjects(e,{json:!0});for(let u=0;u<d?.length;u++){let _=d[u],{type:p}=_;if(p.includes(`${t.package_id}::vault::Vault`)){let m=Ut(_);i.push(m)}else if(p.includes(`${o.package_id}::pool::Pool`)){let m=lt(_);this._sdk.updateCache(`getPool_${m.id}`,m),a.push(m)}}}let r=i.map(d=>d.id);if(r.length>0){let d=await this.geMarketList(r);i.forEach(u=>{let _=d[u.id];if(_){u.markets=_;let m=0;_.forEach(f=>{m+=f.position_list.length}),u.is_multiple_pool=m!==1}let p=`getPool_${u.id}`;this._sdk.updateCache(p,u)})}let c=new Set;a.forEach(d=>{c.add(d.clmm_vault.clmm_pool_id)}),i.forEach(d=>{d.markets.forEach(u=>{u.position_list.forEach(_=>{let{pool_id:p}=_.position;c.add(p)})})});let l=Array.from(c);if(l.length>0){let{clmm_pool:d}=this._sdk.CetusClmmSDK.sdkOptions,{dlmm_pool:u}=this._sdk.CetusDlmmSDK.sdkOptions;(await this._sdk.FullClient.batchGetObjects(l,{json:!0})).forEach(p=>{let{type:m}=p;if(m.includes(`${d.package_id}::pool::Pool`)){let f=Je(p);n[f.id]=f;let y=`${f.id}_getPoolObject`;this._sdk.CetusClmmSDK.updateCache(y,f)}else if(m.includes(`${u.package_id}::pool::Pool`)){let f=Ze(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=fe(a),s=me(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=de(n.json);t.push(r)}else if(s?.includes("CLMMPosition")){let r=ue(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:d,configs:u}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:_}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:p,global_config_id:m}=mt(_);l?o.forEach(f=>{t.moveCall({target:`${d}::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(u.versioned_id)]})}):o.forEach(f=>{t.moveCall({target:`${d}::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(u.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:d,configs:u}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:_}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:p,global_config_id:m}=mt(_);l?o.forEach(f=>{t.moveCall({target:`${d}::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(u.versioned_id),t.object(tt)]})}):o.forEach(f=>{t.moveCall({target:`${d}::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(u.versioned_id),t.object(tt)]})})}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:d}=this._sdk.sdkOptions.vaultsV2,{dlmm_pool:u}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:_,global_config_id:p}=mt(u);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(_),t.object(d.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(_),t.object(d.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:d}=this._sdk.sdkOptions.vaultsV2,{clmm_pool:u}=this._sdk.CetusClmmSDK.sdkOptions,{global_vault_id:_,global_config_id:p}=mt(u);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(d.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(d.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:d}=e,{pool:u,marketList:_}=await this.getVaultAndPool(a,!1),{coin_type_a:p,coin_type_b:m,lp_token_type:f}=u,y=[p,m];for(let h of _)h.type==="DLMM"?h.position_list.forEach(C=>{let{pool_id:S}=C.position,V=h.certified_pool_obj[S],{reward_manager:P}=V,D=P.rewards.map(A=>H(A.reward_coin,!1));y=ft(D,p,m)}):h.type==="CLMM"&&h.position_list.forEach(C=>{let{pool_id:S}=C.position,V=h.certified_pool_obj[S],{rewarder_infos:P}=V,D=P.map(A=>H(A.coin_type,!1));y=ft([...y,...D],p,m)});await this.pythPrice.buildUpdatePythPricePayloadV2(y,t);for(let h of _)if(h.type==="DLMM"){let{dlmm_pool:C}=this._sdk.CetusDlmmSDK.sdkOptions,{versioned_id:S}=mt(C),{position_list:V}=h;V.forEach(P=>{let{id:D,pool_id:A}=P.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(A),t.pure.address(D),t.object(S),t.object(i.versioned_id),t.object(tt)]})})}else if(h.type==="CLMM"){let{clmm_pool:C}=this._sdk.CetusClmmSDK.sdkOptions,{global_config_id:S}=mt(C),{position_list:V}=h;V.forEach(P=>{let{id:D,pool_id:A}=P.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(A),t.pure.address(D),t.object(S),t.object(i.versioned_id),t.object(tt)]})})}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(tt)]});let g,w;if(c&&c.swap_result){let{swap_result:h,coin_amount:C,mode:S,swap_slippage:V}=c,{swap_in_amount:P,route_obj:D}=h,A=Mt.buildCoinWithBalance(BigInt(C),S==="OnlyCoinA"?p:m,t),B=t.splitCoins(A,[P]),M={router:D,slippage:V,txb:t,inputCoin:B},j=await this._sdk.AggregatorClient.fixableRouterSwapV3(M);g=S==="OnlyCoinA"?A:j,w=S==="OnlyCoinA"?j:A}else g=l||Mt.buildCoinWithBalance(BigInt(n),p,t),w=d||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,w,t.object(tt),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:d,coin_type_a:u,coin_type_b:_}=c;t=t||new Ce;let p,m=r?k(r.burn_lp_amount).add(k(i)).toFixed(0):k(i).toFixed(0),f=k(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),d,t),r&&r.lp_burn_coin&&t.mergeCoins(p,[r.lp_burn_coin]));let{published_at:y,configs:g}=this._sdk.sdkOptions.vaultsV2,{config:w}=this._sdk.CetusDlmmSDK.sdkOptions.dlmm_pool,{config:v}=this._sdk.CetusClmmSDK.sdkOptions.clmm_pool,h=t.moveCall({target:`${y}::vault::new_withdraw_cert`,typeArguments:[d],arguments:[t.object(o),p,t.object(g.versioned_id)]}),C=[];for(let A of l)if(A.type==="DLMM"){let{position_list:B}=A;B.forEach(M=>{let{id:j,pool_id:L}=M.position,I=A.certified_pool_obj[L],{reward_manager:T}=I,F=T.rewards.map(E=>H(E.reward_coin,!1));C.push(...F),t.moveCall({target:`${y}::vault::withdraw_dlmm`,typeArguments:[u,_,d],arguments:[t.object(o),h,t.object(L),t.pure.address(j),t.object(w.global_config_id),t.object(w.versioned_id),t.object(g.versioned_id),t.object(tt)]})})}else if(A.type==="CLMM"){let{position_list:B}=A;B.forEach(M=>{let{id:j,pool_id:L}=M.position,I=A.certified_pool_obj[L],{rewarder_infos:T}=I,F=T.map(E=>H(E.coin_type,!1));C.push(...F),t.moveCall({target:`${y}::vault::withdraw_clmm`,typeArguments:[u,_,d],arguments:[t.object(o),h,t.object(L),t.pure.address(j),t.object(v.global_config_id),t.object(g.versioned_id),t.object(tt)]})})}await this.buildCollectRewardAndFeePayload(o,t,h),t.moveCall({target:`${y}::vault::finalize_buffer_assets`,typeArguments:[d],arguments:[t.object(o),h,t.object(g.versioned_id)]});let S=new Set;C.forEach(A=>S.add(A)),S.add(u),S.add(_);let V=Array.from(S),P=a!=="FixedOneSide"?[a==="OnlyCoinA"?_:u]:[],D=this.buildWithdrawBufferReward({reward_coin_types:V,pool_id:o,withdraw_cert:h,lp_token_type:d,not_transfer_coin_types:P},t);if(t.moveCall({target:`${y}::vault::destroy_withdraw_cert`,typeArguments:[d],arguments:[t.object(o),h,t.object(g.versioned_id)]}),a!=="FixedOneSide"){if(n===void 0)throw Error("the slippage is undefined");let A=a==="OnlyCoinA",B=A?_:u,M=D.find(j=>j.coin_type===B).reward_coin_object_id;await this.handleWithSwap(t,M,u,_,m,o,A,n,s)}}async handleWithSwap(e,t,o,i,a,n,s,r,c){let{receive_amount_a:l,receive_amount_b:d}=await this.preCalculateWithdrawAmount({pool_id:n,mode:"FixedOneSide",burn_lp_amount:a}),u=s?i:o,_=s?o:i,p=s?d:l;if(k(p).isZero()){e.transferObjects([t],e.pure.address(this._sdk.getVerifySenderAddress()));return}let m={from:u,target:_,amount:new Y(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},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:d}=await this.getVaultAndPool(i,!1),{coin_type_a:u,coin_type_b:_}=l,p=await this.pythPrice.getLatestPrice([u,_],!0),m=p[u],f=p[_];if(!m)throw new Error(`get ${u} price failed`);if(!f)throw new Error(`get ${_} price failed`);let y="0",g="0";switch(a){case"FlexibleBoth":{let{position_amount_a_rate:v,position_amount_b_rate:h}=l.is_multiple_pool?{position_amount_a_rate:k(.5),position_amount_b_rate:k(.5)}:await this.calculatePositionValueRates(l,p),{amountA:C,amountB:S}=z(v,h,o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=C,g=S;break}case"OnlyCoinA":{let{amountA:v,amountB:h}=z(k(1),k(0),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=v,g=h;break}case"OnlyCoinB":{let{amountA:v,amountB:h}=z(k(0),k(1),o,m.price,f.price,m.coin_decimals,f.coin_decimals);y=v,g=h;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:d,tick_upper_index:u}=s,_=d,p=u,m=o==="OnlyCoinA"?e.coin_amount_a:e.coin_amount_b,f=o==="OnlyCoinA",y=Jt.estLiquidityAndCoinAmountFromOneAmounts(_,p,new Y(m),f,!0,1,new Y(r)),g=f?k(y.coin_amount_b).div(y.coin_amount_a):k(y.coin_amount_a).div(y.coin_amount_b),w=f?k(r).toString():k(1).div(k(r)).toString();try{let P=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,m);P&&(w=k(P.swap_out_amount).div(P.swap_in_amount).toString())}catch{}let{swap_amount:v}=gt(m,f,w.toString(),g.toString()),h=k(m).sub(v).toFixed(0),C=await this._sdk.VaultsV2.findRouters(f?c:l,f?l:c,v),S=k(C.swap_out_amount).mul(.999).toFixed(0),V=Jt.estLiquidityAndCoinAmountFromOneAmounts(_,p,new Y(h),f,!0,1,new Y(r));return f?V.coin_amount_b=S:V.coin_amount_a=S,{swap_result:C,liquidity_info:V}}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,d=t==="OnlyCoinA",u=s.find(m=>m.position_list.length>0);if(n.is_multiple_pool||!u){let m=await this.findRouters(d?r:c,d?c:r,l),{swap_out_amount:f,swap_in_amount:y}=m,g=d?i:a,w=d?a:i,v=at(y,g),h=at(f,w),C=k(h).div(v).toString(),S=await this.pythPrice.getLatestPrice([r,c],!0),V=S[r],P=S[c];if(!V||!P)throw new Error(`not find ${r} or ${c} price`);let D=be(d?v:"0",d?"0":v,V.price,P.price,C,d),A=k(Bt(D,g).toString()).toFixed(0),B=k(l).sub(A).toFixed(0);if(k(B).lt(1)||k(A).lt(1))throw new Error("amount is less than 1");let M=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,A),j=k(M.swap_out_amount).mul(.999).toFixed(0);return{liquidity_info:{bins:[],amount_a:d?B:j,amount_b:d?j:B},swap_result:M}}let _=s.find(m=>m.type==="CLMM");if(_){let{swap_result:m,liquidity_info:f}=await this.calculateClmmBalanceSwapAmount({...e},_);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:g}=m,w=et.getPricePerLamportFromBinId(m.active_id,m.bin_step),v=k(w).mul(1-.05),h=k(w).mul(1+.05),C=et.getBinIdFromLamportPrice(v.toString(),m.bin_step,!1),S=et.getBinIdFromLamportPrice(h.toString(),m.bin_step,!1),V=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,coin_amount:l,fix_amount_a:d,active_id:y,bin_step:g,lower_bin_id:C,upper_bin_id:S,active_bin_of_pool:f,strategy_type:Qt.Spot}),P=d?k(V.amount_b).div(V.amount_a):k(V.amount_a).div(V.amount_b),D=d?et.getPricePerLamportFromBinId(y,g):k(1).div(et.getPricePerLamportFromBinId(y,g)).toString();try{let $=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,l);$&&(D=k($.swap_out_amount).div($.swap_in_amount).toString())}catch{}let{swap_amount:A,final_amount_a:B,final_amount_b:M}=gt(l,d,D,P.toString()),j=k(l).sub(A).toFixed(0),L=await this.findRouters(d?n.coin_type_a:n.coin_type_b,d?n.coin_type_b:n.coin_type_a,A),I=k(L.swap_out_amount).mul(.999).toFixed(0),T=d?j:I,F=d?I:j,E=await this._sdk.CetusDlmmSDK.Position.calculateAddLiquidityInfo({pool_id:m.id,amount_a:T,amount_b:F,active_id:y,bin_step:g,lower_bin_id:C,upper_bin_id:S,active_bin_of_pool:f,strategy_type:Qt.Spot});return d?E.amount_b=L.swap_out_amount:E.amount_a=L.swap_out_amount,{swap_result:L,liquidity_info:E}}}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:d}=e;return await this.calculateDepositOtherSide(n,s,r,c,l,d,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:d,liquidity_info:u}=l,{amount_a:_,amount_b:p}=u,m=await this.calculateDepositFlexibleBoth(n,_,p,t,a);return m.re_balance={swap_result:d,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:d,liquidity_info:u}=l,{amount_a:_,amount_b:p}=u,m=await this.calculateDepositFlexibleBoth(n,_,p,t,a);return m.re_balance={swap_result:d,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(k(o).eq(0))return{position_amount_a_rate:k(.5),position_amount_b_rate:k(.5)};let{position_amount_a:n,position_amount_b:s}=await Nt(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=k(at(n,r.coin_decimals)).mul(r.price),d=k(at(s,c.coin_decimals)).mul(c.price),u=k(l).add(d),_=k(l).div(u),p=k(1).sub(_);return{position_amount_a_rate:_,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",d="0";if(e){l=t;let u=k(at(l,o)).mul(r.price);d=k(Bt(k(u).div(c.price).toString(),i)).toFixed(0)}else{d=t;let u=k(at(d,i)).mul(c.price);l=k(Bt(k(u).div(r.price).toString(),o)).toFixed(0)}if(k(l).lt(1)||k(d).lt(1))throw new Error("is less than 1");return{deposit_amount_a:l,deposit_amount_b:d}}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=et.getPricePerLamportFromBinId(t.active_id,t.bin_step),d=k(l).mul(1-.05),u=k(l).mul(1+.05),_=et.getBinIdFromLamportPrice(d.toString(),t.bin_step,!1),p=et.getBinIdFromLamportPrice(u.toString(),t.bin_step,!1),m={pool_id:r.pool_id,coin_amount:k(i).mul(1e5).toFixed(0),fix_amount_a:o,active_id:t.active_id,bin_step:t.bin_step,lower_bin_id:_,upper_bin_id:p,strategy_type:Qt.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:k(y).div(1e5).toFixed(0),deposit_amount_b:k(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:d}=t,{coin_amount_a:u,coin_amount_b:_}=Jt.estLiquidityAndCoinAmountFromOneAmounts(s,r,new Y(i),o,!0,1,new Y(c));return{deposit_amount_a:u.toString(),deposit_amount_b:_.toString()}}async calculateDepositOtherSide(e,t,o,i,a,n,s,r){let c="0",l="0",{coin_type_a:d,coin_type_b:u}=e;if(e.is_multiple_pool){let _=await this.calculateDepositAmountByValue(i,o,a,n,d,u);c=_.deposit_amount_a,l=_.deposit_amount_b}else if(t[0].type==="DLMM"&&t[0].position_list.length>0){let _=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,_,i,o);c=p,l=m}else if(t[0].type==="CLMM"&&t[0].position_list.length>0){let _=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,_,i,o);c=k(p).add(c).toFixed(0),l=k(m).add(l).toFixed(0)}else{let _=await this.calculateDepositAmountByValue(i,o,a,n,d,u);c=_.deposit_amount_a,l=_.deposit_amount_b}if(s)this.calculateDepositLpAmountBoth(e,c,l).then(_=>{s.onSuccess(_,r)}).catch(_=>{s.onError(_,r)});else{let _=await this.calculateDepositLpAmountBoth(e,c,l);return{deposit_amount_a:c,deposit_amount_b:l,lp_amount:_,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=H(s,!1),l=H(r,!1),{dlmmRewarderList:d,dlmmFeeList:u,clmmRewarderList:_,clmmFeeList:p}=await this.getVaultsPositionRewarderAndFee(e.id),m=Pt(e.buffer_assets,[...u,...p],[...d,..._]),f=await pe(this._sdk,e.id,m,!0),y=await this.pythPrice.getLatestPrice([c,l],!0),g=y[c],w=y[l];if(!g)throw Error(`not find ${c} price`);if(!w)throw Error(`not find ${l} price`);let v={};v[c]={price:g,value:t.toString()},v[l]={price:w,value:o.toString()};let h=it(v,n);return Ct(i,h,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 d=t?l:c,u=t?c:l,{quote_per_base:_}=vt(d.price,u.price),p=t?n:s,m=t?s:n,f=Bt(k(at(m,t?l.coin_decimals:c.coin_decimals)).mul(_).toString(),t?c.coin_decimals:l.coin_decimals).toString(),y=k(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:k(f).toFixed(0,Ge.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 d=l.parsedJson;if(l.type)switch(ze(l.type).full_address){case`${t}::pool::InitEvent`:e.registry_id=d.registry_id;break;case`${t}::pyth_oracle::InitEvent`:e.pyth_oracle_id=d.pyth_oracle_id;break;case`${t}::config::InitConfigEvent`:e.global_config_id=d.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(k(o).lt(1))throw new Error("amount is less than 1");try{let n={from:e,target:t,amount:new Y(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 no from"@cetusprotocol/dlmm-sdk";import{CoinAssist as Ye,d as Gt,fixCoinType as X}from"@cetusprotocol/common-sdk";var Lt=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:d,from_swap_result:u}=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:_,clmmPool:p}=await this.getVaultAndPool(c),{marketList:m,pool:f}=await this.getVaultAndPool(l),{coin_type_a:y,coin_type_b:g}=p,w=n?Gt(d).sub(n.burn_lp_amount).toFixed(0).toString():d,{return_coin_a:v,return_coin_b:h}=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),C={[X(y,!1)]:v,[X(g,!1)]:h},{coin_output_a:S,coin_output_b:V}=u,{from_coin_type:P,from_coin_amount:D,route_obj:A,to_coin_type:B}=S;if(A){let{to_coin:j}=await this.buildSwapAssetsTx({from_coin_type:P,swap_in_amount:D,liquidity_slippage:a,route_obj:A.route_obj,tx:t,from_coin_object_id:C[X(P,!1)]});C[X(B,!1)]=j}if(V.route_obj){let{from_coin_type:j,from_coin_amount:L,route_obj:I,to_coin_type:T}=V,{to_coin:F}=await this.buildSwapAssetsTx({from_coin_type:j,swap_in_amount:L,liquidity_slippage:a,route_obj:I.route_obj,tx:t,from_coin_object_id:C[X(j,!1)]});C[X(T,!1)]=F}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[X(f.coin_type_a,!1)],coin_b_input:C[X(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:d}=n,{coin_type_a:u,coin_type_b:_}=r,p=await this.matchSwapCoins({from:{coin_type_a:l,coin_amount_a:c.receive_amount_a,coin_type_b:d,coin_amount_b:c.receive_amount_b},to:{coin_type_a:u,coin_type_b:_}}),{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||Ye.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=X(t.coin_type_a,!1),a=X(t.coin_type_b,!1),n=X(o.coin_type_a,!1),s=X(o.coin_type_b,!1),r=i===n,c=i===s,l=a===n,d=a===s,u,_;r&&d?(u="A",_="B"):c&&l?(u="B",_="A"):r?(u="A",_="B"):c||l?(u="B",_="A"):(u="A",_="B");let p={from_coin_type:u==="A"?i:a,from_coin_amount:u==="A"?t.coin_amount_a:t.coin_amount_b,to_coin_type:n,to_coin_amount:"0"},m={from_coin_type:_==="A"?i:a,from_coin_amount:_==="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 Z=class{_sdkOptions;_senderAddress="";_vaults;_vaultsV2;_migrate;_aggregatorClient;_vest;_cetusClmmSDK;_cetusDlmmSDK;constructor(e,t,o){(!e.providers||e.providers.length===0)&&(e.providers=ve),this._sdkOptions=e,this._cetusClmmSDK=e.env==="testnet"?t||Ve.createSDK({env:"testnet",full_rpc_url:e.fullRpcUrl}):t||Ve.createSDK({env:"mainnet",full_rpc_url:e.fullRpcUrl}),this._cetusDlmmSDK=o||no.createSDK({env:e.env,full_rpc_url:e.fullRpcUrl}),this._vaults=new Ot(this),this._vaultsV2=new Ft(this),this._migrate=new Lt(this);let{primary:i,secondary:a}=e.pythConfigs.hermes_service_urls,n=[i,a].filter(Boolean);this._aggregatorClient=new oo({endpoint:e.aggregatorUrl,signer:eo("0x0"),client:this.FullClient,env:e.env==="testnet"?ke.Testnet:ke.Mainnet,pythUrls:n}),this._vest=new jt(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||!to(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=io){this.CetusClmmSDK.updateCache(e,t,o)}getCache(e,t=!1){return this.CetusClmmSDK.getCache(e,t)}};var An=.2;var qn=Z;export{ut as PythPriceModule,Ue as SdkEnv,Ot as VaultsModule,Ft as VaultsModuleV2,jt as VestModule,Z as VolatileVaultsSDK,fe as buildCLMMMarketId,ue as buildCLMMMarketPosition,me as buildDLMMMarketId,de as buildDLMMMarketPosition,Fo as buildDLMMPositionId,lt as buildPoolData,Ut as buildPoolV2Data,_e as buildVaultMarket,se as buildVaultsBalance,Nt as buildVaultsBalanceV2,Mo as buildVaultsBalanceV3,gt as calcExactSwapAmount,be as calcSingleSideSwap,ae as calculateAum,pe as calculateAumV2,Oe as calculateDepositRatioFixTokenA,it as calculateTotalAumBasedOnQuote,It as checkIsMinOrMaxIndex,co as convertU64BytesToDecimal,qn as default,ve as defaultProvider,An as dlmm_split_rate,oe as estCoinAmountsFromTotalAmount,_i as feed_map_mainnet,mi as feed_map_testnet,Vt as getAmountBalanceByLpAmount,xe as getAmountBalanceByLpAmountV2,z as getCoinAmountsFromRatio,yo as getPositionPriceRange,go as getPriceWithFormattedDecimals,je as getPrimitivePricesFromBaseQuote,vt as getQuotePerBaseAndBasePerQuote,nt as getShareBufferAssets,ft as getUpdatePriceType,Pt as getVaultValidBalances,bo as get_lp_amount_by_liquidity,Ct as get_lp_amount_by_tvl,_t as get_share_liquidity_by_amount,he as initMainnetSDK,we as initTestnetSDK,hi as initVaultSDK,rt as oraclePriceMultiplierDecimal,re as parseVaultVestNFT,Kt as parseVaultsVestInfo,fo as printTransaction,ho as toSuiObjectId,ge as vaults_mainnet,ye as vaults_testnet};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haedal-vault-sdk",
3
- "version": "2.5.3",
3
+ "version": "2.5.4",
4
4
  "description": "Haedal Vault SDK",
5
5
  "typings": "dist/index.d.ts",
6
6
  "main": "dist/index.js",
@@ -42,8 +42,7 @@
42
42
  "js-sha3": "^0.8.0",
43
43
  "superstruct": "^1.0.3",
44
44
  "tiny-invariant": "^1.1.0",
45
- "tweetnacl": "^1.0.3",
46
- "@pythnetwork/pyth-sui-js": "2.4.0"
45
+ "tweetnacl": "^1.0.3"
47
46
  },
48
47
  "devDependencies": {
49
48
  "@commitlint/cli": "^17.1.2",
package/bun.lockb DELETED
Binary file