@cetusprotocol/deepbook-utils 0.0.0-experimental-20260205215421 → 0.0.0-experimental-20260210163200

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.d.ts CHANGED
@@ -270,6 +270,73 @@ type MarginPoolInfo = {
270
270
  baseCoin: MarginCoinInfo;
271
271
  quoteCoin: MarginCoinInfo;
272
272
  };
273
+ type PendingMarketOrderOptions = {
274
+ client_order_id: string;
275
+ self_matching_option: SelfMatchingOption;
276
+ quantity: string;
277
+ is_bid: boolean;
278
+ pay_with_deep: boolean;
279
+ };
280
+ type PendingLimitOrderOptions = {
281
+ client_order_id: string;
282
+ order_type: OrderType;
283
+ self_matching_option: SelfMatchingOption;
284
+ price: string;
285
+ quantity: string;
286
+ is_bid: boolean;
287
+ pay_with_deep: boolean;
288
+ expire_timestamp: string;
289
+ };
290
+ type AddConditionalOrderOptions = {
291
+ margin_manager_id: string;
292
+ pool_id: string;
293
+ base_coin: MarginCoinInfo;
294
+ quote_coin: MarginCoinInfo;
295
+ conditional_order_id: string;
296
+ is_trigger_below_price: boolean;
297
+ trigger_price: string;
298
+ pending_order: PendingMarketOrderOptions | PendingLimitOrderOptions;
299
+ };
300
+ type CancelAllConditionalOrdersOptions = {
301
+ margin_manager_id: string;
302
+ base_coin_type: string;
303
+ quote_coin_type: string;
304
+ };
305
+ type CancelConditionalOrdersOptions = {
306
+ margin_manager_id: string;
307
+ base_coin_type: string;
308
+ quote_coin_type: string;
309
+ conditional_order_id: string;
310
+ };
311
+ type GetConditionalOrdersOptions = {
312
+ margin_manager_id: string;
313
+ conditional_order_id: string;
314
+ base_coin_type: string;
315
+ quote_coin_type: string;
316
+ };
317
+ /** Condition for triggering a conditional order (trigger_below_price, trigger_price). */
318
+ type Condition = {
319
+ trigger_below_price: boolean;
320
+ trigger_price: string;
321
+ };
322
+ /** Pending order embedded in a conditional order (matches Move PendingOrder). */
323
+ type PendingOrder = {
324
+ is_limit_order: boolean;
325
+ client_order_id: string;
326
+ order_type?: OrderType;
327
+ self_matching_option: SelfMatchingOption;
328
+ price?: string;
329
+ quantity: string;
330
+ is_bid: boolean;
331
+ pay_with_deep: boolean;
332
+ expire_timestamp?: string;
333
+ };
334
+ /** Conditional order (matches Move ConditionalOrder). */
335
+ type ConditionalOrder = {
336
+ conditional_order_id: string;
337
+ condition: Condition;
338
+ pending_order: PendingOrder;
339
+ };
273
340
 
274
341
  type BigNumber = Decimal.Value | number | string;
275
342
 
@@ -1417,6 +1484,12 @@ declare class MarginUtilsModule implements IModule {
1417
1484
  quoteMarginPool: string;
1418
1485
  }[];
1419
1486
  }): Promise<any>;
1487
+ addConditionalOrder(options: AddConditionalOrderOptions, tx: Transaction): Promise<void>;
1488
+ private newPendingOrder;
1489
+ cancelAllConditionalOrders(options: CancelAllConditionalOrdersOptions, tx: Transaction): void;
1490
+ cancelConditionalOrders(options: CancelConditionalOrdersOptions, tx: Transaction): void;
1491
+ getConditionalOrders(options: GetConditionalOrdersOptions[], tx: Transaction): Promise<ConditionalOrder[]>;
1492
+ private normalizeConditionalOrder;
1420
1493
  }
1421
1494
 
1422
1495
  /**
@@ -2020,4 +2093,4 @@ declare class CoinAssist {
2020
2093
  static buildCoinWithBalance(amount: bigint, coin_type: string, tx: Transaction): TransactionObjectArgument;
2021
2094
  }
2022
2095
 
2023
- export { AdjustResult, Balances, BigNumber, BuildCoinResult, CLOCK_ADDRESS, CachedContent, DeepbookUtilsSDK as CetusClmmSDK, ClmmExpectSwapModule, ClmmFetcherModule, ClmmIntegratePoolModule, ClmmIntegratePoolV2Module, ClmmIntegrateRouterModule, ClmmIntegrateRouterWithPartnerModule, ClmmIntegrateUtilsModule, CoinAsset, CoinAssist, CoinConfig, CoinInfoAddress, CoinStoreAddress, DEEP_SCALAR, DEFAULT_GAS_BUDGET_FOR_MERGE, DEFAULT_GAS_BUDGET_FOR_SPLIT, DEFAULT_GAS_BUDGET_FOR_STAKE, DEFAULT_GAS_BUDGET_FOR_TRANSFER, DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI, DEFAULT_NFT_TRANSFER_GAS_FEE, DataPage, DebtDetail, DeepCoin, DeepbookClobV2Moudle, DeepbookCustodianV2Moudle, DeepbookEndpointsV2Moudle, DeepbookUtilsModule, FLOAT_SCALAR, FLOAT_SCALING, GAS_SYMBOL, GAS_TYPE_ARG, GAS_TYPE_ARG_LONG, InterestConfig, MarginCoinInfo, MarginPoolConfig, MarginPoolInfo, MarginUtilsModule, NFT, NORMALIZED_SUI_COIN_TYPE, OrderDeepPrice, OrderFee, OrderType, Package, PageQuery, PaginationArgs, PoolInfo, PoolState, RpcModule, SUI_SYSTEM_STATE_OBJECT_ID, SdkOptions, SelfMatchingOption, StateAccount, SuiAddressType, SuiBasicTypes, SuiInputTypes, SuiObjectDataWithContent, SuiObjectIdType, SuiResource, SuiStructTag, SuiTxArg, Token, TransactionUtil, UserBorrowInfo, YEAR_MS, addHexPrefix, asIntN, asUintN, bufferToHex, cacheTime1min, cacheTime24h, cacheTime5min, calc100PercentRepay, calcDebtDetail, calcInterestRate, calcUtilizationRate, calculateRiskRatio, checkAddress, composeType, d, decimalsMultiplier, DeepbookUtilsSDK as default, extractAddressFromType, extractStructTagFromType, fixCoinType, fixDown, fixSuiObjectId, fromDecimalsAmount, getDefaultSuiInputType, getFutureTime, getMoveObject, getMoveObjectType, getMovePackageContent, getObjectDeletedResponse, getObjectDisplay, getObjectFields, getObjectId, getObjectNotExistsResponse, getObjectOwner, getObjectPreviousTransactionDigest, getObjectReference, getObjectType, getObjectVersion, getSuiObjectData, hasPublicTransfer, hexToNumber, hexToString, isSortedSymbols, isSuiObjectResponse, maxDecimal, mulRoundUp, normalizeCoinType, patchFixSuiObjectId, printTransaction, removeHexPrefix, secretKeyToEd25519Keypair, secretKeyToSecp256k1Keypair, shortAddress, shortString, sleepTime, toBuffer, toDecimalsAmount, utf8to16, wrapDeepBookMarginPoolInfo, wrapDeepBookPoolInfo };
2096
+ export { AddConditionalOrderOptions, AdjustResult, Balances, BigNumber, BuildCoinResult, CLOCK_ADDRESS, CachedContent, CancelAllConditionalOrdersOptions, CancelConditionalOrdersOptions, DeepbookUtilsSDK as CetusClmmSDK, ClmmExpectSwapModule, ClmmFetcherModule, ClmmIntegratePoolModule, ClmmIntegratePoolV2Module, ClmmIntegrateRouterModule, ClmmIntegrateRouterWithPartnerModule, ClmmIntegrateUtilsModule, CoinAsset, CoinAssist, CoinConfig, CoinInfoAddress, CoinStoreAddress, Condition, ConditionalOrder, DEEP_SCALAR, DEFAULT_GAS_BUDGET_FOR_MERGE, DEFAULT_GAS_BUDGET_FOR_SPLIT, DEFAULT_GAS_BUDGET_FOR_STAKE, DEFAULT_GAS_BUDGET_FOR_TRANSFER, DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI, DEFAULT_NFT_TRANSFER_GAS_FEE, DataPage, DebtDetail, DeepCoin, DeepbookClobV2Moudle, DeepbookCustodianV2Moudle, DeepbookEndpointsV2Moudle, DeepbookUtilsModule, FLOAT_SCALAR, FLOAT_SCALING, GAS_SYMBOL, GAS_TYPE_ARG, GAS_TYPE_ARG_LONG, GetConditionalOrdersOptions, InterestConfig, MarginCoinInfo, MarginPoolConfig, MarginPoolInfo, MarginUtilsModule, NFT, NORMALIZED_SUI_COIN_TYPE, OrderDeepPrice, OrderFee, OrderType, Package, PageQuery, PaginationArgs, PendingLimitOrderOptions, PendingMarketOrderOptions, PendingOrder, PoolInfo, PoolState, RpcModule, SUI_SYSTEM_STATE_OBJECT_ID, SdkOptions, SelfMatchingOption, StateAccount, SuiAddressType, SuiBasicTypes, SuiInputTypes, SuiObjectDataWithContent, SuiObjectIdType, SuiResource, SuiStructTag, SuiTxArg, Token, TransactionUtil, UserBorrowInfo, YEAR_MS, addHexPrefix, asIntN, asUintN, bufferToHex, cacheTime1min, cacheTime24h, cacheTime5min, calc100PercentRepay, calcDebtDetail, calcInterestRate, calcUtilizationRate, calculateRiskRatio, checkAddress, composeType, d, decimalsMultiplier, DeepbookUtilsSDK as default, extractAddressFromType, extractStructTagFromType, fixCoinType, fixDown, fixSuiObjectId, fromDecimalsAmount, getDefaultSuiInputType, getFutureTime, getMoveObject, getMoveObjectType, getMovePackageContent, getObjectDeletedResponse, getObjectDisplay, getObjectFields, getObjectId, getObjectNotExistsResponse, getObjectOwner, getObjectPreviousTransactionDigest, getObjectReference, getObjectType, getObjectVersion, getSuiObjectData, hasPublicTransfer, hexToNumber, hexToString, isSortedSymbols, isSuiObjectResponse, maxDecimal, mulRoundUp, normalizeCoinType, patchFixSuiObjectId, printTransaction, removeHexPrefix, secretKeyToEd25519Keypair, secretKeyToSecp256k1Keypair, shortAddress, shortString, sleepTime, toBuffer, toDecimalsAmount, utf8to16, wrapDeepBookMarginPoolInfo, wrapDeepBookPoolInfo };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var it=Object.create;var Z=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var dt=(c,e,t)=>e in c?Z(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var lt=(c,e)=>{for(var t in e)Z(c,t,{get:e[t],enumerable:!0})},qe=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of at(e))!ut.call(c,n)&&n!==t&&Z(c,n,{get:()=>e[n],enumerable:!(r=ot(e,n))||r.enumerable});return c};var Pe=(c,e,t)=>(t=c!=null?it(ct(c)):{},qe(e||!c||!c.__esModule?Z(t,"default",{value:c,enumerable:!0}):t,c)),gt=c=>qe(Z({},"__esModule",{value:!0}),c);var Ie=(c,e,t)=>(dt(c,typeof e!="symbol"?e+"":e,t),t);var _r={};lt(_r,{CLOCK_ADDRESS:()=>tr,CachedContent:()=>K,CetusClmmSDK:()=>re,ClmmExpectSwapModule:()=>ar,ClmmFetcherModule:()=>or,ClmmIntegratePoolModule:()=>rr,ClmmIntegratePoolV2Module:()=>nr,ClmmIntegrateRouterModule:()=>sr,ClmmIntegrateRouterWithPartnerModule:()=>ir,ClmmIntegrateUtilsModule:()=>cr,CoinAssist:()=>E,CoinInfoAddress:()=>ur,CoinStoreAddress:()=>dr,DEEP_SCALAR:()=>le,DEFAULT_GAS_BUDGET_FOR_MERGE:()=>Et,DEFAULT_GAS_BUDGET_FOR_SPLIT:()=>Bt,DEFAULT_GAS_BUDGET_FOR_STAKE:()=>qt,DEFAULT_GAS_BUDGET_FOR_TRANSFER:()=>vt,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI:()=>Mt,DEFAULT_NFT_TRANSFER_GAS_FEE:()=>It,DeepbookClobV2Moudle:()=>gr,DeepbookCustodianV2Moudle:()=>lr,DeepbookEndpointsV2Moudle:()=>pr,DeepbookUtilsModule:()=>X,FLOAT_SCALAR:()=>U,FLOAT_SCALING:()=>R,GAS_SYMBOL:()=>Pt,GAS_TYPE_ARG:()=>ae,GAS_TYPE_ARG_LONG:()=>_e,MarginUtilsModule:()=>ee,NORMALIZED_SUI_COIN_TYPE:()=>Ot,OrderType:()=>nt,RpcModule:()=>te,SUI_SYSTEM_STATE_OBJECT_ID:()=>Dt,SelfMatchingOption:()=>st,TransactionUtil:()=>F,YEAR_MS:()=>Ye,addHexPrefix:()=>me,asIntN:()=>$t,asUintN:()=>Ut,bufferToHex:()=>_t,cacheTime1min:()=>ye,cacheTime24h:()=>V,cacheTime5min:()=>fe,calc100PercentRepay:()=>er,calcDebtDetail:()=>tt,calcInterestRate:()=>et,calcUtilizationRate:()=>Xe,calculateRiskRatio:()=>Zt,checkAddress:()=>bt,composeType:()=>be,d:()=>l,decimalsMultiplier:()=>ce,default:()=>br,extractAddressFromType:()=>Tt,extractStructTagFromType:()=>$,fixCoinType:()=>At,fixDown:()=>L,fixSuiObjectId:()=>Ve,fromDecimalsAmount:()=>G,getDefaultSuiInputType:()=>mr,getFutureTime:()=>Q,getMoveObject:()=>de,getMoveObjectType:()=>ze,getMovePackageContent:()=>xt,getObjectDeletedResponse:()=>Ge,getObjectDisplay:()=>Qt,getObjectFields:()=>Oe,getObjectId:()=>Ae,getObjectNotExistsResponse:()=>Ke,getObjectOwner:()=>Kt,getObjectPreviousTransactionDigest:()=>Gt,getObjectReference:()=>Te,getObjectType:()=>Lt,getObjectVersion:()=>Vt,getSuiObjectData:()=>z,hasPublicTransfer:()=>zt,hexToNumber:()=>ht,hexToString:()=>yt,isSortedSymbols:()=>Ct,isSuiObjectResponse:()=>Qe,maxDecimal:()=>ue,mulRoundUp:()=>Me,normalizeCoinType:()=>ie,patchFixSuiObjectId:()=>oe,printTransaction:()=>Ht,removeHexPrefix:()=>se,secretKeyToEd25519Keypair:()=>Rt,secretKeyToSecp256k1Keypair:()=>Ft,shortAddress:()=>mt,shortString:()=>De,sleepTime:()=>Ce,toBuffer:()=>Ue,toDecimalsAmount:()=>W,utf8to16:()=>$e,wrapDeepBookMarginPoolInfo:()=>je,wrapDeepBookPoolInfo:()=>Se});module.exports=gt(_r);var rt=require("@mysten/sui/graphql");var We=require("@mysten/deepbook-v3"),f=require("@mysten/sui/bcs"),S=require("@mysten/sui/transactions"),B=require("@mysten/sui/utils"),Je=require("js-base64");var he=require("@mysten/sui/transactions");var x=require("@mysten/sui/utils");var pt=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function me(c){return c.startsWith("0x")?c:`0x${c}`}function se(c){return c.startsWith("0x")?`${c.slice(2)}`:c}function De(c,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${c.slice(0,r+2)} ... ${c.slice(-n)}`}function mt(c,e=4,t=4){return De(me(c),e,t)}function bt(c,e={leadingZero:!0}){if(typeof c!="string")return!1;let t=c;if(e.leadingZero){if(!c.startsWith("0x"))return!1;t=t.substring(2)}return pt.test(t)}function Ue(c){if(!Buffer.isBuffer(c))if(Array.isArray(c))c=Buffer.from(c);else if(typeof c=="string")exports.isHexString(c)?c=Buffer.from(exports.padToEven(exports.stripHexPrefix(c)),"hex"):c=Buffer.from(c);else if(typeof c=="number")c=exports.intToBuffer(c);else if(c==null)c=Buffer.allocUnsafe(0);else if(c.toArray)c=Buffer.from(c.toArray());else throw new Error("invalid type");return c}function _t(c){return me(Ue(c).toString("hex"))}function ht(c){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<c.length;n++)t.setUint8(n,c.charCodeAt(n));return t.getUint32(0,!0)}function $e(c){let e,t,r,n,s;e="";let i=c.length;for(t=0;t<i;)switch(r=c.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=c.charAt(t-1);break;case 12:case 13:n=c.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=c.charCodeAt(t++),s=c.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function yt(c){let e="",t=se(c),r=t.length/2;for(let n=0;n<r;n++)e+=String.fromCharCode(Number.parseInt(t.substr(n*2,2),16));return $e(e)}var ft=0,Fe=1,kt=2;function Re(c,e){return c===e?ft:c<e?Fe:kt}function wt(c,e){let t=0,r=c.length<=e.length?c.length:e.length,n=Re(c.length,e.length);for(;t<r;){let s=Re(c.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function Ct(c,e){return wt(c,e)===Fe}function be(c,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[c,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function Tt(c){return c.split("::")[0]}function $(c){try{let e=c.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let a={...$(e),type_arguments:r.map(u=>$(u).source_address)};return a.type_arguments=a.type_arguments.map(u=>E.isSuiCoin(u)?u:$(u).source_address),a.source_address=be(a.full_address,a.type_arguments),a}let n=e.split("::"),i={full_address:e,address:e===ae||e===_e?"0x2":(0,x.normalizeSuiObjectId)(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return i.full_address=`${i.address}::${i.module}::${i.name}`,i.source_address=be(i.full_address,i.type_arguments),i}catch{return{full_address:c,address:"",module:"",name:"",type_arguments:[],source_address:c}}}function ie(c){return $(c).source_address}function Ve(c){return c.toLowerCase().startsWith("0x")?(0,x.normalizeSuiObjectId)(c):c}var At=(c,e=!0)=>{let t=c.split("::"),r=t.shift(),n=(0,x.normalizeSuiObjectId)(r);return e&&(n=se(n)),`${n}::${t.join("::")}`};function oe(c){for(let e in c){let t=typeof c[e];if(t==="object")oe(c[e]);else if(t==="string"){let r=c[e];c[e]=Ve(r)}}}var Ot=(0,x.normalizeStructTag)(x.SUI_TYPE_ARG);var St="0x2::coin::Coin",jt=/^0x2::coin::Coin<(.+)>$/,Bt=1e3,Et=500,vt=100,Mt=100,qt=1e3,ae="0x2::sui::SUI",_e="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Pt="SUI",It=450,Dt="0x0000000000000000000000000000000000000005",E=class{static getCoinTypeArg(e){let t=e.type.match(jt);return t?t[1]:null}static isSUI(e){let t=E.getCoinTypeArg(e);return t?E.getCoinSymbol(t)==="SUI":!1}static getCoinSymbol(e){return e.substring(e.lastIndexOf(":")+1)}static getBalance(e){return BigInt(e.fields.balance)}static totalBalance(e,t){let r=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${St}<${e}>`}static getCoinAssets(e,t){let r=[];return t.forEach(n=>{ie(n.coinAddress)===ie(e)&&r.push(n)}),r}static isSuiCoin(e){return $(e).full_address===ae}static selectCoinObjectIdGreaterThanOrEqual(e,t,r=[]){let n=E.selectCoinAssetGreaterThanOrEqual(e,t,r),s=n.selectedCoins.map(a=>a.coinObjectId),i=n.remainingCoins,o=n.selectedCoins.map(a=>a.balance.toString());return{objectArray:s,remainCoins:i,amountArray:o}}static selectCoinAssetGreaterThanOrEqual(e,t,r=[]){let n=E.sortByBalance(e.filter(u=>!r.includes(u.coinObjectId))),s=E.calculateTotalBalance(n);if(s<t)return{selectedCoins:[],remainingCoins:n};if(s===t)return{selectedCoins:n,remainingCoins:[]};let i=BigInt(0),o=[],a=[...n];for(;i<s;){let u=t-i,g=a.findIndex(p=>p.balance>=u);if(g!==-1){o.push(a[g]),a.splice(g,1);break}let d=a.pop();d.balance>0&&(o.push(d),i+=d.balance)}return{selectedCoins:E.sortByBalance(o),remainingCoins:E.sortByBalance(a)}}static sortByBalance(e){return e.sort((t,r)=>t.balance<r.balance?-1:t.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,r)=>t.balance>r.balance?-1:t.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,r)=>t+r.balance,BigInt(0))}static buildCoinWithBalance(e,t,r){return e===BigInt(0)&&E.isSuiCoin(t)?r.add((0,he.coinWithBalance)({balance:e,useGasCoin:!1})):r.add((0,he.coinWithBalance)({balance:e,type:t}))}};var ye=6e4,fe=3e5,V=864e5;function Q(c){return Date.parse(new Date().toString())+c}var K=class{overdueTime;value;constructor(e,t=0){this.overdueTime=t,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};var H=require("@mysten/bcs"),ke=require("@mysten/sui/keypairs/ed25519"),we=require("@mysten/sui/keypairs/secp256k1");var Y=Pe(require("decimal.js"));function l(c){return Y.default.isDecimal(c)?c:new Y.default(c===void 0?0:c)}function ce(c){return l(10).pow(l(c).abs())}var L=(c,e)=>{try{return l(c).toDP(e,Y.default.ROUND_DOWN).toString()}catch{return c}},ue=(c,e)=>Y.default.max(l(c),l(e));function W(c,e){let t=ce(l(e));return Number(l(c).mul(t))}function Ut(c,e=32){return BigInt.asUintN(e,BigInt(c)).toString()}function $t(c,e=32){return Number(BigInt.asIntN(e,BigInt(c)))}function G(c,e){let t=ce(l(e));return Number(l(c).div(t))}function Rt(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return ke.Ed25519Keypair.fromSecretKey(r)}let t=e==="hex"?(0,H.fromHEX)(c):(0,H.fromB64)(c);return ke.Ed25519Keypair.fromSecretKey(t)}function Ft(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return we.Secp256k1Keypair.fromSecretKey(r)}let t=e==="hex"?(0,H.fromHEX)(c):(0,H.fromB64)(c);return we.Secp256k1Keypair.fromSecretKey(t)}var Ce=async c=>new Promise(e=>{setTimeout(()=>{e(1)},c)});var Ne={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},xe={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function Le(...c){let e="DeepbookV3_Utils_Sdk###"}function z(c){return c.data}function Ge(c){if(c.error&&"object_id"in c.error&&"version"in c.error&&"digest"in c.error){let{error:e}=c;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Ke(c){if(c.error&&"object_id"in c.error&&!("version"in c.error)&&!("digest"in c.error))return c.error.object_id}function Te(c){if("reference"in c)return c.reference;let e=z(c);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Ge(c)}function Ae(c){return"objectId"in c?c.objectId:Te(c)?.objectId??Ke(c)}function Vt(c){return"version"in c?c.version:Te(c)?.version}function Qe(c){return c.data!==void 0}function Nt(c){return c.content!==void 0}function xt(c){let e=z(c);if(e?.content?.dataType==="package")return e.content.disassembled}function de(c){let e="data"in c?z(c):c;if(!(!e||!Nt(e)||e.content.dataType!=="moveObject"))return e.content}function ze(c){return de(c)?.type}function Lt(c){let e=Qe(c)?c.data:c;return!e?.type&&"data"in c?e?.content?.dataType==="package"?"package":ze(c):e?.type}function Gt(c){return z(c)?.previousTransaction}function Kt(c){return z(c)?.owner}function Qt(c){let e=z(c)?.display;return e||{data:null,error:null}}function Oe(c){let e=de(c)?.fields;if(e)return"fields"in e?e.fields:e}function zt(c){return de(c)?.hasPublicTransfer??!1}var He=require("@mysten/sui/transactions");async function Ht(c,e=!0){c.blockData.transactions.forEach((t,r)=>{})}var N=class{static async adjustTransactionForGas(e,t,r,n){n.setSender(e.senderAddress);let s=E.selectCoinAssetGreaterThanOrEqual(t,r).selectedCoins;if(s.length===0)throw new Error("Insufficient balance");let i=E.calculateTotalBalance(t);if(i-r>1e9)return{fixAmount:r};let o=await e.fullClient.calculationTxGas(n);if(E.selectCoinAssetGreaterThanOrEqual(t,BigInt(o),s.map(u=>u.coinObjectId)).selectedCoins.length===0){let u=BigInt(o)+BigInt(500);if(i-r<u){if(r-=u,r<0)throw new Error("gas Insufficient balance");let g=new He.Transaction;return{fixAmount:r,newTx:g}}}return{fixAmount:r}}static buildCoinForAmount(e,t,r,n,s=!0,i=!1){let o=E.getCoinAssets(n,t);if(r===BigInt(0)&&o.length===0)return N.buildZeroValueCoin(t,e,n,s);let a=E.calculateTotalBalance(o);if(a<r)throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${r} `);return N.buildCoin(e,t,o,r,n,s,i)}static buildCoin(e,t,r,n,s,i=!0,o=!1){if(E.isSuiCoin(s)){if(i){let h=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[h]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&r.length>1){let h=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.object(h.objectArray[0]),remainCoins:h.remainCoins,tragetCoinAmount:h.amountArray[0],isMintZeroCoin:!1}}let y=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:y.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let a=E.selectCoinObjectIdGreaterThanOrEqual(r,n),u=a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),g=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:g.map(y=>e.object(y))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...p]=g,b=e.object(d),m=b,_=a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),w;return p.length>0&&e.mergeCoins(b,p.map(y=>e.object(y))),o&&Number(u)>Number(n)&&(m=e.splitCoins(b,[e.pure.u64(n)]),_=n.toString(),w=b),{targetCoin:m,remainCoins:a.remainCoins,originalSplitedCoin:w,tragetCoinAmount:_,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,r,n=!0){let s=N.callMintZeroValueCoin(t,r),i;return n?i=t.makeMoveVec({elements:[s]}):i=s,{targetCoin:i,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,r,n,s=!0){let i=E.getCoinAssets(n,t);if(r.amountFirst===BigInt(0))return i.length>0?N.buildCoin(e,[...t],[...i],r.amountFirst,n,s):N.buildZeroValueCoin(t,e,n,s);let o=E.calculateTotalBalance(i);if(o>=r.amountFirst)return N.buildCoin(e,[...t],[...i],r.amountFirst,n,s);if(o<r.amountSecond)throw new Error(`The amount(${o}) is Insufficient balance for ${n} , expect ${r.amountSecond} `);return N.buildCoin(e,[...t],[...i],r.amountSecond,n,s)}static buildCoinTypePair(e,t){let r=[];if(e.length===2){let n=[];n.push(e[0],e[1]),r.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),r.push(n);for(let s=1;s<e.length-1;s+=1){if(t[s-1]===0)continue;let i=[];i.push(e[0],e[s],e[e.length-1]),r.push(i)}}return r}},F=N;Ie(F,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));var le=1e6,U=1e9,Wt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Jt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},X=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?Jt:Wt}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new S.Transaction,t=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),t],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[t],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:t,amountToDeposit:r}){let n=new S.Transaction;n.setSenderIfNotSet(e);let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),i=(0,S.coinWithBalance)({type:t.coinType,balance:BigInt(r)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[s,i],typeArguments:[t.coinType]}),n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[s],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:r,amountToDeposit:n,tx:s}){let i=s||new S.Transaction;if(t){i.setSenderIfNotSet(e);let o=(0,S.coinWithBalance)({type:r.coinType,balance:BigInt(n)});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i.object(t),o],typeArguments:[r.coinType]}),i}return null}withdrawFromManager({account:e,balanceManager:t,coin:r,amountToWithdraw:n,returnAssets:s,txb:i}){let o=i||new S.Transaction,a=o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[o.object(t),o.pure.u64(n)],typeArguments:[r.coinType]});return s?a:(o.transferObjects([a],e),o)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:r=new S.Transaction}){for(let n in t)t[n].forEach(i=>{let o=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(n),r.pure.u64(i.amount)],typeArguments:[i.coinType]});r.transferObjects([o],e)});return r}async getBalanceManager(e,t=!0){let r=`getBalanceManager_${e}`,n=this.getCache(r,t);if(!t&&n!==void 0)return n;try{let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s.pure.address(e)],typeArguments:[]});let a=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}))?.events?.filter(g=>g.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],u=[];return a.forEach(g=>{u.push({balanceManager:g,cetusBalanceManager:""})}),this.updateCache(r,u,864e5),u||[]}catch(s){throw s instanceof Error?s:new Error(String(s))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},r=new S.Transaction){let n=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(t)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(e.address),r.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:t,coins:r}){try{let n=new S.Transaction;r.forEach(o=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[o.coinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),i={};return s.results?.forEach((o,a)=>{let u=r[a],g=o.returnValues[0][0],d=f.bcs.U64.parse(new Uint8Array(g)),p=l(d),b=p.eq(0)?"0":p.div(Math.pow(10,u.decimals)).toString();i[u.coinType]={adjusted_balance:b,balance:p.toString()}}),i}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let r=new S.Transaction,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(o=>{t.forEach(a=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(o.balanceManager)],typeArguments:[a.coinType]})})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i={};return n.forEach((o,a)=>{let u={},g=a*t.length;t.forEach((d,p)=>{let b=g+p,m=s.results?.[b];if(m){let _=m.returnValues[0][0],w=f.bcs.U64.parse(new Uint8Array(_)),y=l(w),C=y.eq(0)?"0":y.div(Math.pow(10,d.decimals)).toString();u[d.coinType]={adjusted_balance:C,balance:y.toString()}}}),i[o.balanceManager]=u}),i}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let t=new S.Transaction;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let n=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],s=Number(f.bcs.U64.parse(new Uint8Array(n))),i=Math.pow(10,e.baseCoin.decimals).toString(),o=Math.pow(10,e.quoteCoin.decimals).toString();return l(s).mul(i).div(o).div(U).toString()}catch(t){return Le("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",r=this.getCache(t,e);if(r!==void 0)return r;let n=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),s=/<([^>]+)>/,i=[];return n?.data?.forEach(o=>{let a=o?.parsedJson,u=o.type.match(s);if(u){let d=u[1].split(", ");i.push({...a,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,i,864e5),i}async getQuoteQuantityOut(e,t,r){let n=new S.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),baseQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getBaseQuantityOut(e,t,r){let n=new S.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(f.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{quoteQuantityDisplay:l(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),quoteQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getQuantityOut(e,t,r,n){let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.pure.u64(r),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=Number(f.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),a=Number(f.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]))),u=Number(f.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:l(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(u).div(le).toString(),baseQuantity:t,quoteQuantity:r,baseOut:o,quoteOut:a,deepRequired:u}}async getReferencePool(e){let t=await this.getPools(),r=e.baseCoin.coinType,n=e.quoteCoin.coinType,s=this._deep.coinType;for(let i=0;i<t.length;i++){let o=t[i];if(o.address===e.address)continue;let a=[o.baseCoinType,o.quoteCoinType];if(o.baseCoinType===s&&(a.includes(r)||a.includes(n)))return o}return null}async updateDeepPrice(e,t){let r=await this.getReferencePool(e);return r?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(r.pool_id),t.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,r,n,s,i,o){let a=this.deepCoin;try{let{taker_fee:u,maker_fee:g}=e,d=l(u).div(U).toString(),p=l(g).div(U).toString(),b=await this.getMarketPrice(e),m=i?r:b!=="0"?b:o;if(m==="0")throw new Error("Cannot get market price");let _=Math.pow(10,e.baseCoin.decimals).toString(),w=Math.pow(10,e.quoteCoin.decimals).toString(),y=l(m).div(_).mul(w).mul(U).toString();if(n){let O=await this.getMarketPrice(e),A=l(i?r:O!=="0"?O:o).div(_).mul(w).mul(U).toString(),M=await this.getOrderDeepPrice(e);if(!M)throw new Error("Cannot get deep price");let q=ue(A,r),I=l(t).mul(l(d)).mul(l(M.deep_per_asset)).div(l(U)),P=l(t).mul(l(p)).mul(l(M.deep_per_asset)).div(l(U));M.asset_is_base||(I=I.mul(q).div(l(U)),P=P.mul(q).div(l(U)));let D=I.ceil().toString(),ne=P.ceil().toString();return{takerFee:D,makerFee:ne,takerFeeDisplay:G(D,a.decimals).toString(),makerFeeDisplay:G(ne,a.decimals).toString(),feeType:a.coinType}}if(s){let O=ue(y,i?r:b),j=l(t).mul(O).mul(l(d).mul(1.25)).div(l(U)).ceil().toFixed(0),A=l(t).mul(O).mul(l(p).mul(1.25)).div(l(U)).ceil().toFixed(0);return{takerFee:j,makerFee:A,takerFeeDisplay:G(j,e.quoteCoin.decimals).toString(),makerFeeDisplay:G(A,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=l(t).mul(l(d).mul(1.25)).ceil().toFixed(0),h=l(t).mul(l(p).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:h,takerFeeDisplay:G(C,e.baseCoin.decimals).toString(),makerFeeDisplay:G(h,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(e,t=!0){let r=`getOrderDeepPrice_${e.address}}`,n=this.getCache(r);if(n!==void 0)return n;try{let s=new S.Transaction,i=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,s)&&(i=!0),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[s.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),a=i?o.results[1]?.returnValues[0]?.[0]:o.results[0]?.returnValues[0]?.[0],u=this.parseOrderDeepPrice(new Uint8Array(a));return this.updateCache(r,u,6e4),u}catch{return await Ce(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),r=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:n}}getCoinAssets(e,t,r,n){return F.buildCoinForAmount(n,r,BigInt(l(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,r,n,s,i,o){let a=this.deepCoin;if(!o)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&u.push(a);let g=await this.getManagerBalance({account:s,balanceManager:o,coins:u}),d=g?.[t]?.balance||"0",p=g?.[r]?.balance||"0",b=i&&g?.[a.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:p,feeManaerBalance:b}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(e,t,r,n,s,i,o,a,u,g){let d=l(e).gt(0)&&u,p="0";if(!d)return{feeAsset:this.getEmptyCoin(g,t),haveDepositFee:"0"};if(i||o){let b=l(s).sub(i?n:r);p=b.lte(0)?e:b.sub(e).lt(0)?b.sub(e).toString():"0"}else p=l(s).sub(e).lt("0")?l(s).sub(e).abs().toString():"0";return{feeAsset:l(p).gt("0")?this.getCoinAssets(t,p,a,g):this.getEmptyCoin(g,t),haveDepositFee:p}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,u){try{let g=this.deepCoin,d=(0,B.normalizeStructTag)(e.baseCoin.coinType),p=(0,B.normalizeStructTag)(e.quoteCoin.coinType),b=d===g.coinType,m=p===g.coinType,_=!b&&!m,{baseManagerBlance:w,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,p,_,i,o,a);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:w,quoteManagerBlance:y});let h,O,j=!1,A=await this._sdk.getOwnerCoinAssets(i);if(s){o||(r=l(r).add(l(n)).toString());let q=l(y).sub(r).toString();l(q).lt(0)?(j=!0,O=this.getCoinAssets(p,q,A,u)):O=this.getEmptyCoin(u,p),h=this.getEmptyCoin(u,d)}else{o||(t=l(t).add(l(n)).toString());let q=l(w).sub(t).toString();l(q).lt(0)?(j=!0,h=this.getCoinAssets(d,q,A,u)):h=this.getEmptyCoin(u,d),O=this.getEmptyCoin(u,p)}let M=this.getFeeAsset(n,g.coinType,t,r,C,m,b,A,o,u);return{baseAsset:h,quoteAsset:O,feeAsset:M,haveDeposit:j}}catch(g){throw g instanceof Error?g:new Error(String(g))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,u,g){try{let d=this.deepCoin,p=(0,B.normalizeStructTag)(e.baseCoin.coinType),b=(0,B.normalizeStructTag)(e.quoteCoin.coinType),m=p===d.coinType,_=b===d.coinType,w=!m&&!_,y=await this.getTransactionRelatedBalance(e,p,b,w,i,o,a),{feeManaerBalance:C}=y,h=l(y.baseManagerBlance).add(l(g?.base||"0")).toString(),O=l(y.quoteManagerBlance).add(l(g?.quote||"0")).toString(),j=await this._sdk.getOwnerCoinAssets(i),A;o&&l(C).lt(n)?A=this.getCoinAssets(d.coinType,l(n).sub(C).toString(),j,u):A=this.getEmptyCoin(u,d.coinType);let M,q;if(s){o||(r=l(r).add(l(n)).toString());let I=l(O).sub(r).toString();if(l(I).lt(0)){let P;l(O).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:O,returnAssets:!0,txb:u}));let D=this.getCoinAssets(b,I,j,u);P&&u.mergeCoins(D,[P]),q=D}else q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});M=this.getEmptyCoin(u,p)}else{o||(t=l(t).add(l(n)).toString());let I=l(h).sub(t).toString();if(l(I).lt(0)){let P;l(h).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:u}));let D=this.getCoinAssets(p,I,j,u);P&&u.mergeCoins(D,[P]),M=D}else M=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,b)}return{baseAsset:M,quoteAsset:q,feeAsset:A}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:r,orderType:n,isBid:s,maxFee:i,account:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8}){try{let g=this.deepCoin,d=e.address,p=e.baseCoin.decimals,b=e.quoteCoin.decimals,m=e.baseCoin.coinType,_=e.quoteCoin.coinType,w=l(t).mul(10**(b-p+9)).toString(),y=(0,B.normalizeStructTag)(m),C=(0,B.normalizeStructTag)(_),h=new S.Transaction,O,j,A=await this._sdk.getOwnerCoinAssets(o);if(s){let P=l(t).mul(l(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(P=l(P).add(l(i)).toString()),j=F.buildCoinForAmount(h,A,BigInt(P),C,!1,!0)?.targetCoin}else{let P=r;a||(P=l(r).abs().add(l(i)).toString()),O=F.buildCoinForAmount(h,A,BigInt(l(P).abs().toString()),y,!1,!0)?.targetCoin}let M=a?l(i).gt(0)?F.buildCoinForAmount(h,A,BigInt(l(i).abs().ceil().toString()),g.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,g.coinType):this.getEmptyCoin(h,g.coinType),q=h.moveCall({typeArguments:[s?m:_],target:"0x2::coin::zero",arguments:[]}),I=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(d),s?q:O,s?j:q,M,h.pure.u8(n),h.pure.u8(0),h.pure.u64(w),h.pure.u64(r),h.pure.bool(s),h.pure.bool(!1),h.pure.u64(u),h.object(B.SUI_CLOCK_OBJECT_ID)];return h.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:I}),h}catch(g){throw g instanceof Error?g:new Error(String(g))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:r,maxFee:n,account:s,payWithDeep:i,slippage:o=.01}){try{let a=e.address,u=e.baseCoin.coinType,g=e.quoteCoin.coinType,d=(0,B.normalizeStructTag)(u),p=(0,B.normalizeStructTag)(g),b=new S.Transaction,m,_,w=t,y,C=await this.getOrderBook(e,"all",6);if(r){let A=C?.ask?.[0]?.price||"0",M=l(A).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=l(M).plus(l(M).mul(o)).ceil().toString()}else{let A=await C?.bid?.[0]?.price||"0",M=l(A).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=l(M).minus(l(M).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(y=l(y).add(l(n)).toString()),_=this.getCoinAssets(p,y,h,b),m=this.getEmptyCoin(b,d)):(i||(w=l(w).add(l(n)).toString()),_=this.getEmptyCoin(b,p),m=this.getCoinAssets(d,w,h,b));let O=i?l(n).gt(0)?F.buildCoinForAmount(b,h,BigInt(l(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(b,this.deepCoin.coinType):this.getEmptyCoin(b,this.deepCoin.coinType),j=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(a),m,_,O,b.pure.u8(0),b.pure.u64(t),b.pure.bool(r),b.pure.bool(i),b.pure.u64(y),b.object(B.SUI_CLOCK_OBJECT_ID)];return b.moveCall({typeArguments:[d,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:j}),b}catch(a){throw a instanceof Error?a:new Error(String(a))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:r,quantity:n,isBid:s,orderType:i,maxFee:o,account:a,payWithDeep:u,expirationTimestamp:g=Date.now()+31536e8}){try{let d=this.deepCoin,p=l(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),b=t.baseCoin.coinType,m=t.quoteCoin.coinType,_=new S.Transaction,w=s?l(r).mul(l(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=s?"0":n,{baseAsset:C,quoteAsset:h,feeAsset:O,haveDeposit:j}=await this.getTransactionRelatedAssets(t,y,w,o,s,a,u,e,_);if(j){let q=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(t.address),_.object(e),C,h,O.feeAsset,_.pure.u8(i),_.pure.u8(0),_.pure.u64(p),_.pure.u64(n),_.pure.bool(s),_.pure.bool(u),_.pure.u64(g),_.object(B.SUI_CLOCK_OBJECT_ID)];return _.moveCall({typeArguments:[b,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:q}),_}let A=new S.Transaction;l(O.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:d,amountToDeposit:O.haveDepositFee,tx:A});let M=[A.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),A.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),A.object(t.address),A.object(e),A.pure.u8(i),A.pure.u8(0),A.pure.u64(p),A.pure.u64(n),A.pure.bool(s),A.pure.bool(u),A.pure.u64(g),A.object(B.SUI_CLOCK_OBJECT_ID)];return A.moveCall({typeArguments:[b,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:M}),A}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:r,newOrderQuantity:n}){let s=new S.Transaction;return s.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(e),s.object(t.address),s.pure.u128(r),s.pure.u64(n),s.object(B.SUI_CLOCK_OBJECT_ID)]}),s}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new S.Transaction,s=await this.getMarketPrice(e),i=l(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(a),n.pure.u64(u),n.pure.bool(!1),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:n}),p=[],b=d.results[0].returnValues[0][0],m=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b)),_=d.results[0].returnValues[1][0],w=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(_));return m.forEach((y,C)=>{let h=l(y).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),O=l(w[C]).div(Math.pow(10,t.decimals)).toString();p.push({price:h,quantity:O})}),p?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new S.Transaction,s=await this.getMarketPrice(e),i=l(s).gt(0)?l(s).div(3).toNumber():Math.pow(10,-6),o=l(s).gt(0)?s:Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(L(a,0)),n.pure.u64(L(u,0)),n.pure.bool(!0),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:n}),p=[],b=d.results[0].returnValues[0][0],m=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b)),_=d.results[0].returnValues[1][0],w=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(_));return m.forEach((y,C)=>{let h=l(y).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),O=l(w[C]).div(Math.pow(10,t.decimals)).toString();p.push({price:h,quantity:O})}),p?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:r,quoteCoin:n}=e,s=new S.Transaction,i=await this.getMarketPrice(e),o,a;t?(o=l(i).gt(0)?l(i).div(3).toNumber():Math.pow(10,-6),a=l(i).gt(0)?i:Math.pow(10,6)):(o=l(i).gt(0)?i:Math.pow(10,-1),a=l(i).gt(0)?l(i).mul(3).toNumber():Math.pow(10,6));let u=l(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),g=l(a).mul(Math.pow(10,9+n.decimals-r.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(L(u,0)),s.pure.u64(L(g,0)),s.pure.bool(t),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:s}),b=[],m=p.results[0].returnValues[0][0],_=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m)),w=p.results[0].returnValues[1][0],y=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(w));return _.forEach((C,h)=>{let O=l(C).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),j=l(y[h]).div(Math.pow(10,r.decimals)).toString();b.push({price:O,quantity:j})}),b?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:r,quoteQuantity:n,isBid:s,maxFee:i,account:o,payWithDeep:a,slippage:u=.01,settled_balances:g={base:"0",quote:"0"}}){try{let d=(0,B.normalizeStructTag)(t.baseCoin.coinType),p=(0,B.normalizeStructTag)(t.quoteCoin.coinType),b=new S.Transaction;g&&(l(g.base).gt(0)||l(g.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},b);let{baseAsset:m,quoteAsset:_,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,b,g),y=await this.getOrderBook(t,"all",6);if(s){let O=y?.ask?.[0]?.price||"0",j=l(O).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(j).plus(l(j).mul(u)).ceil().toString()}else{let O=await y?.bid?.[0]?.price||"0",j=l(O).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(j).minus(l(j).mul(u)).floor().toString()}let C=n,h=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(t.address),b.object(e),m,_,w,b.pure.u8(0),b.pure.u64(r),b.pure.bool(s),b.pure.bool(a),b.pure.u64(C),b.object(B.SUI_CLOCK_OBJECT_ID)];return b.setSenderIfNotSet(o),b.moveCall({typeArguments:[d,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),b}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let r=new S.Transaction;e.forEach(u=>{let g=u?.pool,d=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(g.pool_id),r.pure.u128(BigInt(d))],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:r}),s=f.bcs.struct("ID",{bytes:f.bcs.Address}),i=f.bcs.struct("OrderDeepPrice",{asset_is_base:f.bcs.bool(),deep_per_asset:f.bcs.u64()}),o=f.bcs.struct("Order",{balance_manager_id:s,order_id:f.bcs.u128(),client_order_id:f.bcs.u64(),quantity:f.bcs.u64(),filled_quantity:f.bcs.u64(),fee_is_deep:f.bcs.bool(),order_deep_price:i,epoch:f.bcs.u64(),status:f.bcs.u8(),expire_timestamp:f.bcs.u64()}),a=[];return n?.results?.forEach(u=>{let g=u.returnValues[0][0],d=o.parse(new Uint8Array(g));a.push(d)}),a}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:r,orderId:n}}async getOpenOrder(e,t,r,n,s=!1,i=new S.Transaction){let o;if(n)o=n;else{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[i.object(e.address),s?r:i.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:i})).results[s?1:0].returnValues[0][0];o=f.bcs.struct("VecSet",{constants:f.bcs.vector(f.bcs.U128)}).parse(new Uint8Array(p)).constants}if(o.length===0)return[];let a=o.map(d=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:d})),u=await this.getOrderInfoList(a,t)||[],g=[];return u.forEach(d=>{let p=this.decodeOrderId(BigInt(d.order_id));g.push({...d,price:p.price,isBid:p.isBid,pool:e})}),g}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new S.Transaction;r.forEach(d=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(d.pool_id),n.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(d=>d.returnValues?.[0]?.[0])||[],o=f.bcs.struct("VecSet",{constants:f.bcs.vector(f.bcs.U128)}),a=[];i.forEach((d,p)=>{let b=o.parse(new Uint8Array(d)).constants;b.length>0&&b.forEach(m=>{a.push({pool:r[p],orderId:m})})});let u=await this.getOrderInfoList(a,e)||[],g=[];return a.forEach((d,p)=>{let b=this.decodeOrderId(BigInt(d.orderId)),m=u.find(_=>_.order_id===d.orderId)||{};g.push({...d,...m,price:b.price,isBid:b.isBid})}),g}catch{return[]}}cancelOrders(e,t,r=new S.Transaction){return e.forEach(n=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(t),r.object(n.poolInfo.address),r.pure.u128(n.orderId),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(e,t,r,n,s,i){let o=this._sdk.fullClient,u=await new We.DeepBookClient({client:o,address:s,env:"testnet",balanceManagers:{test1:{address:i,tradeCap:""}}}).getLevel2Range(e,t,r,n)}processOrderBookData(e,t,r,n){let s=e.returnValues[0][0],i=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(s)),o=e.returnValues[1][0],a=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(o)),u={};return i.forEach((d,p)=>{let b=l(d).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),m=l(a[p]).div(Math.pow(10,t.decimals)).toString();u[b]?u[b]={price:b,quantity:l(u[b].quantity).add(m).toString()}:u[b]={price:b,quantity:m}}),Object.values(u)}getLevel2RangeTx(e,t,r,n,s=new S.Transaction){let{baseCoin:i,quoteCoin:o}=e,a=L(l(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),u=L(l(n).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0);return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(a),s.pure.u64(u),s.pure.bool(t),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[i.coinType,o.coinType]}),s}async fetchOrderBook(e,t,r,n,s,i){let o=new S.Transaction,{baseCoin:a,quoteCoin:u}=e;try{if(t==="bid"||t==="all"){let m=n,_=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,m,_,o)}if(t==="ask"||t==="all"){let m=r==="0"?n:r,_=s;o=this.getLevel2RangeTx(e,!1,m,_,o)}let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:o}),p=[];(t==="bid"||t==="all")&&(p=d.results?.[0]?this.processOrderBookData(d.results[0],a,u,i):[]);let b=[];if(t==="ask"||t==="all"){let m=t==="ask"?0:1;b=d.results?.[m]?this.processOrderBookData(d.results[m],a,u,i):[]}return{bid:p.sort((m,_)=>_.price-m.price),ask:b.sort((m,_)=>m.price-_.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,p=[],b=[];try{let m=this.getLevel2RangeTx(e,!0,n,r),_=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});p=_.results?.[0]?this.processOrderBookData(_.results[0],a,u,i):[]}catch{p=[]}try{let m=this.getLevel2RangeTx(e,!1,n,r),_=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});b=_.results?.[0]?this.processOrderBookData(_.results[0],a,u,i):[]}catch{b=[]}return{bid:p,ask:b}}}async getOrderBook(e,t,r){let n={bid:[],ask:[]};try{let s=await this.getMarketPrice(e),i=t,o=Math.pow(10,-r),a=Math.pow(10,r),u=await this.fetchOrderBook(e,i,s,o,a,r);return{bid:u?.bid,ask:u?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let r=new S.Transaction,n=await this.getMarketPrice(e),{baseCoin:s,quoteCoin:i}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),p=n,b=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(p).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(b),r.pure.u64(m),r.pure.bool(!0),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let d=n,p=Math.pow(10,6),b=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(p).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(b),r.pure.u64(m),r.pure.bool(!1),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType]})}let o=this._sdk.sdkOptions.simulationAccount.address,a=await this._sdk.fullClient.devInspectTransactionBlock({sender:o,transactionBlock:r}),u=[];if(t==="bid"||t==="all"){let d=a.results[0]?.returnValues[0]?.[0],p=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(d)),b=a.results[0]?.returnValues[1]?.[0],m=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b));p.forEach((_,w)=>{let y=l(_).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),C=l(m[w]).div(Math.pow(10,s.decimals)).toString();u.push({price:y,quantity:C})})}let g=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,p=a.results[d]?.returnValues[0]?.[0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(p)),m=a.results[d]?.returnValues[1]?.[0],_=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m));b.forEach((w,y)=>{let C=l(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=l(_[y]).div(Math.pow(10,s.decimals)).toString();g.push({price:C,quantity:h})})}return{bid:u,ask:g}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,s)=>[(0,B.normalizeStructTag)(n.coinType),n]))}async getAccount(e,t,r=new S.Transaction){for(let o=0;o<t.length;o++){let a=t[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof e=="string"?r.object(e):e],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.senderAddress,transactionBlock:r}),s;if(n?.events.length===0)return null;let i=[];return n?.events?.forEach((o,a)=>{s=o?.parsedJson;let u=s.account.open_orders.contents,g=s.account.owed_balances,d=s.account.settled_balances,p=s.account.unclaimed_rebates,b=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:u,owed_balances:g,settled_balances:d,unclaimed_rebates:p,taker_volume:b,poolInfo:t[a]})}),i}async getSuiTransactionResponse(e,t=!1){let r=`${e}_getSuiTransactionResponse`,n=this.getCache(r,t);if(n!==void 0)return n;let s;try{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,s,864e5),s}transformExtensions(e,t,r=!0){let n=[];for(let s of t){let{key:i}=s.fields,{value:o}=s.fields;if(i==="labels")try{o=JSON.parse(decodeURIComponent(Je.Base64.decode(o)))}catch{}r&&(e[i]=o),n.push({key:i,value:o})}delete e.extension_fields,r||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let r=this.sdk.sdkOptions.coinlist.handle,n=`${r}_getCoinConfigs`,s=this.getCache(n,e);if(s)return s;let o=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(g=>g.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),u=[];return a.forEach(g=>{let d=this.buildCoinConfig(g,t);this.updateCache(`${r}_${d.address}_getCoinConfig`,d,864e5),u.push({...d})}),this.updateCache(n,u,864e5),u}buildCoinConfig(e,t=!0){let r=Oe(e);r=r.value.fields;let n={...r};return n.id=Ae(e),n.address=$(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=(0,B.normalizeSuiObjectId)(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,r=3e5){let n=this._cache[e];n?(n.overdueTime=Q(r),n.value=t):n=new K(t,Q(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:r,baseCoinType:n,quoteCoinType:s}){let i=new S.Transaction,o=E.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",i);i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[n,s],arguments:[i.object(this.sdk.sdkOptions.deepbook.registry_id),i.pure.u64(e),i.pure.u64(t),i.pure.u64(r),o]});try{let a=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:i});if(a.effects.status.status==="success")return i;if(a.effects.status.status==="failure"&&a.effects.status.error&&a.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(a){throw a instanceof Error?a:new Error(String(a))}return i}};var Ee=require("@cetusprotocol/common-sdk"),k=require("@mysten/sui/bcs"),T=require("@mysten/sui/transactions"),v=require("@mysten/sui/utils");var Zt=({totalAssetsValue:c,totalDebtValue:e})=>l(e).eq(0)||l(c).eq(0)?"0":l(c).div(l(e)).toString(),Se=c=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=c.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}=c.value.fields.risk_ratios.fields;return{id:c.id.id,name:c.name,base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s,liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}},je=(c,e)=>{let{deposit_coin_type:t}=e,r=c.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=c.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:u}=c.protocol_fees.fields,{total_supply:g,total_borrow:d}=c.state.fields,p=l(o).sub(g).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:g,total_borrow:d,available_supply:p,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:u}};var pe=require("@pythnetwork/pyth-sui-js");var Be=10n;function Yt(c,e){if(!Be)throw new Error("oraclePriceMultiplierDecimal is required");if(c===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(Be- -e);return c*t}return c/10n**(e+Be)}var J=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;_cache={};constructor(e){this._sdk=e,this.connection=new pe.SuiPriceServiceConnection(this.sdk.sdkOptions.pythUrl),this.suiPythClient=new pe.SuiPythClient(this._sdk.fullClient,this._sdk.sdkOptions.margin_utils.pyth_state_id,this._sdk.sdkOptions.margin_utils.wormhole_state_id)}get sdk(){return this._sdk}async updatePythPriceIDs(e,t){let r=null,n=null;try{r=await this.connection.getPriceFeedsUpdateData(e)}catch(o){n=o}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${n?.message}`);let s=[];try{s=await this.suiPythClient.updatePriceFeeds(t,r,e)}catch(o){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${o}`)}let i=new Map;for(let o=0;o<e.length;o++)i.set(e[o],s[o]);return i}priceCheck(e,t=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let r={},n=[];if(t?e.forEach(o=>{let a=this._sdk.getCache(`getLatestPrice_${o.coinType}`);a&&this.priceCheck(a,60)?r[o.coinType]=a:n.push(o.coinType)}):n=e.map(o=>o.coinType),n.length===0)return r;let s=e.map(o=>o.feed);return(await this.connection.getLatestPriceUpdates(s))?.parsed?.forEach((o,a)=>{let u=o.price;if(u){let{price:g,expo:d}=u,p=l(g).mul(l(10).pow(l(d))).toString(),m={coin_type:e[a].coinType,price:p,oracle_price:0n,last_update_time:u.publish_time};m.oracle_price=Yt(BigInt(g),BigInt(d)),r[n[a]]=m,this._sdk.updateCache(`getLatestPrice_${m.coin_type}`,m)}}),r}};var ee=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new J(e),this._deep=e.sdkOptions.network==="mainnet"?xe:Ne}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,t=new T.Transaction){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:n}=e;try{let{margin_manager:s,initializer:i}=this.createMarginManager(e,t);return this.shareMarginManager({marginManager:s,initializer:i,baseCoin:r,quoteCoin:n},t),{tx:t,margin_manager:s,initializer:i}}catch(s){throw new Error(`Failed to create and share margin manager: ${s instanceof Error?s.message:String(s)}`)}}createMarginManager(e,t=new T.Transaction){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:n,quoteCoin:s}=e;try{let[i,o]=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[t.object(this.sdk.sdkOptions.margin_utils.versioned_id),t.object(r),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,s.coinType]});return{tx:t,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create margin manager: ${i instanceof Error?i.message:String(i)}`)}}shareMarginManager({marginManager:e,initializer:t,baseCoin:r,quoteCoin:n},s=new T.Transaction){try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,t],typeArguments:[r.coinType,n.coinType]}),s}catch(i){throw new Error(`Failed to share margin manager: ${i instanceof Error?i.message:String(i)}`)}}async getBalanceManagerByMarginManager(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");let t=`
1
+ "use strict";var ot=Object.create;var Y=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var ut=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var lt=(c,e,t)=>e in c?Y(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var pt=(c,e)=>{for(var t in e)Y(c,t,{get:e[t],enumerable:!0})},qe=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ct(e))!dt.call(c,n)&&n!==t&&Y(c,n,{get:()=>e[n],enumerable:!(r=at(e,n))||r.enumerable});return c};var Pe=(c,e,t)=>(t=c!=null?ot(ut(c)):{},qe(e||!c||!c.__esModule?Y(t,"default",{value:c,enumerable:!0}):t,c)),gt=c=>qe(Y({},"__esModule",{value:!0}),c);var Ie=(c,e,t)=>(lt(c,typeof e!="symbol"?e+"":e,t),t);var br={};pt(br,{CLOCK_ADDRESS:()=>tr,CachedContent:()=>K,CetusClmmSDK:()=>ne,ClmmExpectSwapModule:()=>ar,ClmmFetcherModule:()=>or,ClmmIntegratePoolModule:()=>rr,ClmmIntegratePoolV2Module:()=>nr,ClmmIntegrateRouterModule:()=>sr,ClmmIntegrateRouterWithPartnerModule:()=>ir,ClmmIntegrateUtilsModule:()=>cr,CoinAssist:()=>v,CoinInfoAddress:()=>ur,CoinStoreAddress:()=>dr,DEEP_SCALAR:()=>pe,DEFAULT_GAS_BUDGET_FOR_MERGE:()=>vt,DEFAULT_GAS_BUDGET_FOR_SPLIT:()=>Et,DEFAULT_GAS_BUDGET_FOR_STAKE:()=>Pt,DEFAULT_GAS_BUDGET_FOR_TRANSFER:()=>Mt,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI:()=>qt,DEFAULT_NFT_TRANSFER_GAS_FEE:()=>Dt,DeepbookClobV2Moudle:()=>pr,DeepbookCustodianV2Moudle:()=>lr,DeepbookEndpointsV2Moudle:()=>gr,DeepbookUtilsModule:()=>ee,FLOAT_SCALAR:()=>U,FLOAT_SCALING:()=>R,GAS_SYMBOL:()=>It,GAS_TYPE_ARG:()=>ce,GAS_TYPE_ARG_LONG:()=>he,MarginUtilsModule:()=>te,NORMALIZED_SUI_COIN_TYPE:()=>St,OrderType:()=>st,RpcModule:()=>re,SUI_SYSTEM_STATE_OBJECT_ID:()=>Ut,SelfMatchingOption:()=>it,TransactionUtil:()=>F,YEAR_MS:()=>Xe,addHexPrefix:()=>_e,asIntN:()=>Rt,asUintN:()=>$t,bufferToHex:()=>ht,cacheTime1min:()=>fe,cacheTime24h:()=>V,cacheTime5min:()=>ke,calc100PercentRepay:()=>er,calcDebtDetail:()=>rt,calcInterestRate:()=>tt,calcUtilizationRate:()=>et,calculateRiskRatio:()=>Yt,checkAddress:()=>bt,composeType:()=>be,d:()=>l,decimalsMultiplier:()=>ue,default:()=>_r,extractAddressFromType:()=>Tt,extractStructTagFromType:()=>$,fixCoinType:()=>At,fixDown:()=>x,fixSuiObjectId:()=>Ve,fromDecimalsAmount:()=>G,getDefaultSuiInputType:()=>mr,getFutureTime:()=>z,getMoveObject:()=>le,getMoveObjectType:()=>Qe,getMovePackageContent:()=>xt,getObjectDeletedResponse:()=>Ge,getObjectDisplay:()=>Qt,getObjectFields:()=>Se,getObjectId:()=>Ae,getObjectNotExistsResponse:()=>Ke,getObjectOwner:()=>zt,getObjectPreviousTransactionDigest:()=>Kt,getObjectReference:()=>Te,getObjectType:()=>Gt,getObjectVersion:()=>Nt,getSuiObjectData:()=>Q,hasPublicTransfer:()=>Ht,hexToNumber:()=>yt,hexToString:()=>ft,isSortedSymbols:()=>Ot,isSuiObjectResponse:()=>ze,maxDecimal:()=>de,mulRoundUp:()=>Me,normalizeCoinType:()=>oe,patchFixSuiObjectId:()=>ae,printTransaction:()=>Wt,removeHexPrefix:()=>ie,secretKeyToEd25519Keypair:()=>Ft,secretKeyToSecp256k1Keypair:()=>Vt,shortAddress:()=>_t,shortString:()=>De,sleepTime:()=>Oe,toBuffer:()=>Ue,toDecimalsAmount:()=>J,utf8to16:()=>$e,wrapDeepBookMarginPoolInfo:()=>Be,wrapDeepBookPoolInfo:()=>je});module.exports=gt(br);var nt=require("@mysten/sui/graphql");var We=require("@mysten/deepbook-v3"),k=require("@mysten/sui/bcs"),S=require("@mysten/sui/transactions"),B=require("@mysten/sui/utils"),Je=require("js-base64");var ye=require("@mysten/sui/transactions");var L=require("@mysten/sui/utils");var mt=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function _e(c){return c.startsWith("0x")?c:`0x${c}`}function ie(c){return c.startsWith("0x")?`${c.slice(2)}`:c}function De(c,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${c.slice(0,r+2)} ... ${c.slice(-n)}`}function _t(c,e=4,t=4){return De(_e(c),e,t)}function bt(c,e={leadingZero:!0}){if(typeof c!="string")return!1;let t=c;if(e.leadingZero){if(!c.startsWith("0x"))return!1;t=t.substring(2)}return mt.test(t)}function Ue(c){if(!Buffer.isBuffer(c))if(Array.isArray(c))c=Buffer.from(c);else if(typeof c=="string")exports.isHexString(c)?c=Buffer.from(exports.padToEven(exports.stripHexPrefix(c)),"hex"):c=Buffer.from(c);else if(typeof c=="number")c=exports.intToBuffer(c);else if(c==null)c=Buffer.allocUnsafe(0);else if(c.toArray)c=Buffer.from(c.toArray());else throw new Error("invalid type");return c}function ht(c){return _e(Ue(c).toString("hex"))}function yt(c){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<c.length;n++)t.setUint8(n,c.charCodeAt(n));return t.getUint32(0,!0)}function $e(c){let e,t,r,n,s;e="";let i=c.length;for(t=0;t<i;)switch(r=c.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=c.charAt(t-1);break;case 12:case 13:n=c.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=c.charCodeAt(t++),s=c.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function ft(c){let e="",t=ie(c),r=t.length/2;for(let n=0;n<r;n++)e+=String.fromCharCode(Number.parseInt(t.substr(n*2,2),16));return $e(e)}var kt=0,Fe=1,wt=2;function Re(c,e){return c===e?kt:c<e?Fe:wt}function Ct(c,e){let t=0,r=c.length<=e.length?c.length:e.length,n=Re(c.length,e.length);for(;t<r;){let s=Re(c.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function Ot(c,e){return Ct(c,e)===Fe}function be(c,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[c,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function Tt(c){return c.split("::")[0]}function $(c){try{let e=c.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let a={...$(e),type_arguments:r.map(u=>$(u).source_address)};return a.type_arguments=a.type_arguments.map(u=>v.isSuiCoin(u)?u:$(u).source_address),a.source_address=be(a.full_address,a.type_arguments),a}let n=e.split("::"),i={full_address:e,address:e===ce||e===he?"0x2":(0,L.normalizeSuiObjectId)(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return i.full_address=`${i.address}::${i.module}::${i.name}`,i.source_address=be(i.full_address,i.type_arguments),i}catch{return{full_address:c,address:"",module:"",name:"",type_arguments:[],source_address:c}}}function oe(c){return $(c).source_address}function Ve(c){return c.toLowerCase().startsWith("0x")?(0,L.normalizeSuiObjectId)(c):c}var At=(c,e=!0)=>{let t=c.split("::"),r=t.shift(),n=(0,L.normalizeSuiObjectId)(r);return e&&(n=ie(n)),`${n}::${t.join("::")}`};function ae(c){for(let e in c){let t=typeof c[e];if(t==="object")ae(c[e]);else if(t==="string"){let r=c[e];c[e]=Ve(r)}}}var St=(0,L.normalizeStructTag)(L.SUI_TYPE_ARG);var jt="0x2::coin::Coin",Bt=/^0x2::coin::Coin<(.+)>$/,Et=1e3,vt=500,Mt=100,qt=100,Pt=1e3,ce="0x2::sui::SUI",he="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",It="SUI",Dt=450,Ut="0x0000000000000000000000000000000000000005",v=class{static getCoinTypeArg(e){let t=e.type.match(Bt);return t?t[1]:null}static isSUI(e){let t=v.getCoinTypeArg(e);return t?v.getCoinSymbol(t)==="SUI":!1}static getCoinSymbol(e){return e.substring(e.lastIndexOf(":")+1)}static getBalance(e){return BigInt(e.fields.balance)}static totalBalance(e,t){let r=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${jt}<${e}>`}static getCoinAssets(e,t){let r=[];return t.forEach(n=>{oe(n.coinAddress)===oe(e)&&r.push(n)}),r}static isSuiCoin(e){return $(e).full_address===ce}static selectCoinObjectIdGreaterThanOrEqual(e,t,r=[]){let n=v.selectCoinAssetGreaterThanOrEqual(e,t,r),s=n.selectedCoins.map(a=>a.coinObjectId),i=n.remainingCoins,o=n.selectedCoins.map(a=>a.balance.toString());return{objectArray:s,remainCoins:i,amountArray:o}}static selectCoinAssetGreaterThanOrEqual(e,t,r=[]){let n=v.sortByBalance(e.filter(u=>!r.includes(u.coinObjectId))),s=v.calculateTotalBalance(n);if(s<t)return{selectedCoins:[],remainingCoins:n};if(s===t)return{selectedCoins:n,remainingCoins:[]};let i=BigInt(0),o=[],a=[...n];for(;i<s;){let u=t-i,p=a.findIndex(g=>g.balance>=u);if(p!==-1){o.push(a[p]),a.splice(p,1);break}let d=a.pop();d.balance>0&&(o.push(d),i+=d.balance)}return{selectedCoins:v.sortByBalance(o),remainingCoins:v.sortByBalance(a)}}static sortByBalance(e){return e.sort((t,r)=>t.balance<r.balance?-1:t.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,r)=>t.balance>r.balance?-1:t.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,r)=>t+r.balance,BigInt(0))}static buildCoinWithBalance(e,t,r){return e===BigInt(0)&&v.isSuiCoin(t)?r.add((0,ye.coinWithBalance)({balance:e,useGasCoin:!1})):r.add((0,ye.coinWithBalance)({balance:e,type:t}))}};var fe=6e4,ke=3e5,V=864e5;function z(c){return Date.parse(new Date().toString())+c}var K=class{overdueTime;value;constructor(e,t=0){this.overdueTime=t,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};var W=require("@mysten/bcs"),we=require("@mysten/sui/keypairs/ed25519"),Ce=require("@mysten/sui/keypairs/secp256k1");var X=Pe(require("decimal.js"));function l(c){return X.default.isDecimal(c)?c:new X.default(c===void 0?0:c)}function ue(c){return l(10).pow(l(c).abs())}var x=(c,e)=>{try{return l(c).toDP(e,X.default.ROUND_DOWN).toString()}catch{return c}},de=(c,e)=>X.default.max(l(c),l(e));function J(c,e){let t=ue(l(e));return Number(l(c).mul(t))}function $t(c,e=32){return BigInt.asUintN(e,BigInt(c)).toString()}function Rt(c,e=32){return Number(BigInt.asIntN(e,BigInt(c)))}function G(c,e){let t=ue(l(e));return Number(l(c).div(t))}function Ft(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return we.Ed25519Keypair.fromSecretKey(r)}let t=e==="hex"?(0,W.fromHEX)(c):(0,W.fromB64)(c);return we.Ed25519Keypair.fromSecretKey(t)}function Vt(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return Ce.Secp256k1Keypair.fromSecretKey(r)}let t=e==="hex"?(0,W.fromHEX)(c):(0,W.fromB64)(c);return Ce.Secp256k1Keypair.fromSecretKey(t)}var Oe=async c=>new Promise(e=>{setTimeout(()=>{e(1)},c)});var Ne={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Le={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function xe(...c){let e="DeepbookV3_Utils_Sdk###"}function Q(c){return c.data}function Ge(c){if(c.error&&"object_id"in c.error&&"version"in c.error&&"digest"in c.error){let{error:e}=c;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Ke(c){if(c.error&&"object_id"in c.error&&!("version"in c.error)&&!("digest"in c.error))return c.error.object_id}function Te(c){if("reference"in c)return c.reference;let e=Q(c);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Ge(c)}function Ae(c){return"objectId"in c?c.objectId:Te(c)?.objectId??Ke(c)}function Nt(c){return"version"in c?c.version:Te(c)?.version}function ze(c){return c.data!==void 0}function Lt(c){return c.content!==void 0}function xt(c){let e=Q(c);if(e?.content?.dataType==="package")return e.content.disassembled}function le(c){let e="data"in c?Q(c):c;if(!(!e||!Lt(e)||e.content.dataType!=="moveObject"))return e.content}function Qe(c){return le(c)?.type}function Gt(c){let e=ze(c)?c.data:c;return!e?.type&&"data"in c?e?.content?.dataType==="package"?"package":Qe(c):e?.type}function Kt(c){return Q(c)?.previousTransaction}function zt(c){return Q(c)?.owner}function Qt(c){let e=Q(c)?.display;return e||{data:null,error:null}}function Se(c){let e=le(c)?.fields;if(e)return"fields"in e?e.fields:e}function Ht(c){return le(c)?.hasPublicTransfer??!1}var He=require("@mysten/sui/transactions");async function Wt(c,e=!0){c.blockData.transactions.forEach((t,r)=>{})}var N=class{static async adjustTransactionForGas(e,t,r,n){n.setSender(e.senderAddress);let s=v.selectCoinAssetGreaterThanOrEqual(t,r).selectedCoins;if(s.length===0)throw new Error("Insufficient balance");let i=v.calculateTotalBalance(t);if(i-r>1e9)return{fixAmount:r};let o=await e.fullClient.calculationTxGas(n);if(v.selectCoinAssetGreaterThanOrEqual(t,BigInt(o),s.map(u=>u.coinObjectId)).selectedCoins.length===0){let u=BigInt(o)+BigInt(500);if(i-r<u){if(r-=u,r<0)throw new Error("gas Insufficient balance");let p=new He.Transaction;return{fixAmount:r,newTx:p}}}return{fixAmount:r}}static buildCoinForAmount(e,t,r,n,s=!0,i=!1){let o=v.getCoinAssets(n,t);if(r===BigInt(0)&&o.length===0)return N.buildZeroValueCoin(t,e,n,s);let a=v.calculateTotalBalance(o);if(a<r)throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${r} `);return N.buildCoin(e,t,o,r,n,s,i)}static buildCoin(e,t,r,n,s,i=!0,o=!1){if(v.isSuiCoin(s)){if(i){let h=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[h]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&r.length>1){let h=v.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.object(h.objectArray[0]),remainCoins:h.remainCoins,tragetCoinAmount:h.amountArray[0],isMintZeroCoin:!1}}let f=v.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:f.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let a=v.selectCoinObjectIdGreaterThanOrEqual(r,n),u=a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),p=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:p.map(f=>e.object(f))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...g]=p,_=e.object(d),m=_,b=a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),w;return g.length>0&&e.mergeCoins(_,g.map(f=>e.object(f))),o&&Number(u)>Number(n)&&(m=e.splitCoins(_,[e.pure.u64(n)]),b=n.toString(),w=_),{targetCoin:m,remainCoins:a.remainCoins,originalSplitedCoin:w,tragetCoinAmount:b,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,r,n=!0){let s=N.callMintZeroValueCoin(t,r),i;return n?i=t.makeMoveVec({elements:[s]}):i=s,{targetCoin:i,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,r,n,s=!0){let i=v.getCoinAssets(n,t);if(r.amountFirst===BigInt(0))return i.length>0?N.buildCoin(e,[...t],[...i],r.amountFirst,n,s):N.buildZeroValueCoin(t,e,n,s);let o=v.calculateTotalBalance(i);if(o>=r.amountFirst)return N.buildCoin(e,[...t],[...i],r.amountFirst,n,s);if(o<r.amountSecond)throw new Error(`The amount(${o}) is Insufficient balance for ${n} , expect ${r.amountSecond} `);return N.buildCoin(e,[...t],[...i],r.amountSecond,n,s)}static buildCoinTypePair(e,t){let r=[];if(e.length===2){let n=[];n.push(e[0],e[1]),r.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),r.push(n);for(let s=1;s<e.length-1;s+=1){if(t[s-1]===0)continue;let i=[];i.push(e[0],e[s],e[e.length-1]),r.push(i)}}return r}},F=N;Ie(F,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));var pe=1e6,U=1e9,Jt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Zt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},ee=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?Zt:Jt}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new S.Transaction,t=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),t],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[t],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:t,amountToDeposit:r}){let n=new S.Transaction;n.setSenderIfNotSet(e);let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),i=(0,S.coinWithBalance)({type:t.coinType,balance:BigInt(r)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[s,i],typeArguments:[t.coinType]}),n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[s],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:r,amountToDeposit:n,tx:s}){let i=s||new S.Transaction;if(t){i.setSenderIfNotSet(e);let o=(0,S.coinWithBalance)({type:r.coinType,balance:BigInt(n)});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i.object(t),o],typeArguments:[r.coinType]}),i}return null}withdrawFromManager({account:e,balanceManager:t,coin:r,amountToWithdraw:n,returnAssets:s,txb:i}){let o=i||new S.Transaction,a=o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[o.object(t),o.pure.u64(n)],typeArguments:[r.coinType]});return s?a:(o.transferObjects([a],e),o)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:r=new S.Transaction}){for(let n in t)t[n].forEach(i=>{let o=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(n),r.pure.u64(i.amount)],typeArguments:[i.coinType]});r.transferObjects([o],e)});return r}async getBalanceManager(e,t=!0){let r=`getBalanceManager_${e}`,n=this.getCache(r,t);if(!t&&n!==void 0)return n;try{let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s.pure.address(e)],typeArguments:[]});let a=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}))?.events?.filter(p=>p.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],u=[];return a.forEach(p=>{u.push({balanceManager:p,cetusBalanceManager:""})}),this.updateCache(r,u,864e5),u||[]}catch(s){throw s instanceof Error?s:new Error(String(s))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},r=new S.Transaction){let n=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(t)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(e.address),r.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:t,coins:r}){try{let n=new S.Transaction;r.forEach(o=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[o.coinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),i={};return s.results?.forEach((o,a)=>{let u=r[a],p=o.returnValues[0][0],d=k.bcs.U64.parse(new Uint8Array(p)),g=l(d),_=g.eq(0)?"0":g.div(Math.pow(10,u.decimals)).toString();i[u.coinType]={adjusted_balance:_,balance:g.toString()}}),i}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let r=new S.Transaction,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(o=>{t.forEach(a=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(o.balanceManager)],typeArguments:[a.coinType]})})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i={};return n.forEach((o,a)=>{let u={},p=a*t.length;t.forEach((d,g)=>{let _=p+g,m=s.results?.[_];if(m){let b=m.returnValues[0][0],w=k.bcs.U64.parse(new Uint8Array(b)),f=l(w),C=f.eq(0)?"0":f.div(Math.pow(10,d.decimals)).toString();u[d.coinType]={adjusted_balance:C,balance:f.toString()}}}),i[o.balanceManager]=u}),i}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let t=new S.Transaction;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let n=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],s=Number(k.bcs.U64.parse(new Uint8Array(n))),i=Math.pow(10,e.baseCoin.decimals).toString(),o=Math.pow(10,e.quoteCoin.decimals).toString();return l(s).mul(i).div(o).div(U).toString()}catch(t){return xe("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",r=this.getCache(t,e);if(r!==void 0)return r;let n=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),s=/<([^>]+)>/,i=[];return n?.data?.forEach(o=>{let a=o?.parsedJson,u=o.type.match(s);if(u){let d=u[1].split(", ");i.push({...a,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,i,864e5),i}async getQuoteQuantityOut(e,t,r){let n=new S.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(pe).toString(),baseQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getBaseQuantityOut(e,t,r){let n=new S.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{quoteQuantityDisplay:l(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(pe).toString(),quoteQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getQuantityOut(e,t,r,n){let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.pure.u64(r),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=Number(k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),a=Number(k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]))),u=Number(k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:l(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(u).div(pe).toString(),baseQuantity:t,quoteQuantity:r,baseOut:o,quoteOut:a,deepRequired:u}}async getReferencePool(e){let t=await this.getPools(),r=e.baseCoin.coinType,n=e.quoteCoin.coinType,s=this._deep.coinType;for(let i=0;i<t.length;i++){let o=t[i];if(o.address===e.address)continue;let a=[o.baseCoinType,o.quoteCoinType];if(o.baseCoinType===s&&(a.includes(r)||a.includes(n)))return o}return null}async updateDeepPrice(e,t){let r=await this.getReferencePool(e);return r?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(r.pool_id),t.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,r,n,s,i,o){let a=this.deepCoin;try{let{taker_fee:u,maker_fee:p}=e,d=l(u).div(U).toString(),g=l(p).div(U).toString(),_=await this.getMarketPrice(e),m=i?r:_!=="0"?_:o;if(m==="0")throw new Error("Cannot get market price");let b=Math.pow(10,e.baseCoin.decimals).toString(),w=Math.pow(10,e.quoteCoin.decimals).toString(),f=l(m).div(b).mul(w).mul(U).toString();if(n){let A=await this.getMarketPrice(e),T=l(i?r:A!=="0"?A:o).div(b).mul(w).mul(U).toString(),M=await this.getOrderDeepPrice(e);if(!M)throw new Error("Cannot get deep price");let q=de(T,r),I=l(t).mul(l(d)).mul(l(M.deep_per_asset)).div(l(U)),P=l(t).mul(l(g)).mul(l(M.deep_per_asset)).div(l(U));M.asset_is_base||(I=I.mul(q).div(l(U)),P=P.mul(q).div(l(U)));let D=I.ceil().toString(),se=P.ceil().toString();return{takerFee:D,makerFee:se,takerFeeDisplay:G(D,a.decimals).toString(),makerFeeDisplay:G(se,a.decimals).toString(),feeType:a.coinType}}if(s){let A=de(f,i?r:_),j=l(t).mul(A).mul(l(d).mul(1.25)).div(l(U)).ceil().toFixed(0),T=l(t).mul(A).mul(l(g).mul(1.25)).div(l(U)).ceil().toFixed(0);return{takerFee:j,makerFee:T,takerFeeDisplay:G(j,e.quoteCoin.decimals).toString(),makerFeeDisplay:G(T,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=l(t).mul(l(d).mul(1.25)).ceil().toFixed(0),h=l(t).mul(l(g).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:h,takerFeeDisplay:G(C,e.baseCoin.decimals).toString(),makerFeeDisplay:G(h,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(e,t=!0){let r=`getOrderDeepPrice_${e.address}}`,n=this.getCache(r);if(n!==void 0)return n;try{let s=new S.Transaction,i=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,s)&&(i=!0),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[s.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),a=i?o.results[1]?.returnValues[0]?.[0]:o.results[0]?.returnValues[0]?.[0],u=this.parseOrderDeepPrice(new Uint8Array(a));return this.updateCache(r,u,6e4),u}catch{return await Oe(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),r=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:n}}getCoinAssets(e,t,r,n){return F.buildCoinForAmount(n,r,BigInt(l(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,r,n,s,i,o){let a=this.deepCoin;if(!o)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&u.push(a);let p=await this.getManagerBalance({account:s,balanceManager:o,coins:u}),d=p?.[t]?.balance||"0",g=p?.[r]?.balance||"0",_=i&&p?.[a.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:g,feeManaerBalance:_}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(e,t,r,n,s,i,o,a,u,p){let d=l(e).gt(0)&&u,g="0";if(!d)return{feeAsset:this.getEmptyCoin(p,t),haveDepositFee:"0"};if(i||o){let _=l(s).sub(i?n:r);g=_.lte(0)?e:_.sub(e).lt(0)?_.sub(e).toString():"0"}else g=l(s).sub(e).lt("0")?l(s).sub(e).abs().toString():"0";return{feeAsset:l(g).gt("0")?this.getCoinAssets(t,g,a,p):this.getEmptyCoin(p,t),haveDepositFee:g}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,u){try{let p=this.deepCoin,d=(0,B.normalizeStructTag)(e.baseCoin.coinType),g=(0,B.normalizeStructTag)(e.quoteCoin.coinType),_=d===p.coinType,m=g===p.coinType,b=!_&&!m,{baseManagerBlance:w,quoteManagerBlance:f,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,g,b,i,o,a);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:w,quoteManagerBlance:f});let h,A,j=!1,T=await this._sdk.getOwnerCoinAssets(i);if(s){o||(r=l(r).add(l(n)).toString());let q=l(f).sub(r).toString();l(q).lt(0)?(j=!0,A=this.getCoinAssets(g,q,T,u)):A=this.getEmptyCoin(u,g),h=this.getEmptyCoin(u,d)}else{o||(t=l(t).add(l(n)).toString());let q=l(w).sub(t).toString();l(q).lt(0)?(j=!0,h=this.getCoinAssets(d,q,T,u)):h=this.getEmptyCoin(u,d),A=this.getEmptyCoin(u,g)}let M=this.getFeeAsset(n,p.coinType,t,r,C,m,_,T,o,u);return{baseAsset:h,quoteAsset:A,feeAsset:M,haveDeposit:j}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,u,p){try{let d=this.deepCoin,g=(0,B.normalizeStructTag)(e.baseCoin.coinType),_=(0,B.normalizeStructTag)(e.quoteCoin.coinType),m=g===d.coinType,b=_===d.coinType,w=!m&&!b,f=await this.getTransactionRelatedBalance(e,g,_,w,i,o,a),{feeManaerBalance:C}=f,h=l(f.baseManagerBlance).add(l(p?.base||"0")).toString(),A=l(f.quoteManagerBlance).add(l(p?.quote||"0")).toString(),j=await this._sdk.getOwnerCoinAssets(i),T;o&&l(C).lt(n)?T=this.getCoinAssets(d.coinType,l(n).sub(C).toString(),j,u):T=this.getEmptyCoin(u,d.coinType);let M,q;if(s){o||(r=l(r).add(l(n)).toString());let I=l(A).sub(r).toString();if(l(I).lt(0)){let P;l(A).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:A,returnAssets:!0,txb:u}));let D=this.getCoinAssets(_,I,j,u);P&&u.mergeCoins(D,[P]),q=D}else q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});M=this.getEmptyCoin(u,g)}else{o||(t=l(t).add(l(n)).toString());let I=l(h).sub(t).toString();if(l(I).lt(0)){let P;l(h).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:u}));let D=this.getCoinAssets(g,I,j,u);P&&u.mergeCoins(D,[P]),M=D}else M=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:u});q=this.getEmptyCoin(u,_)}return{baseAsset:M,quoteAsset:q,feeAsset:T}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:r,orderType:n,isBid:s,maxFee:i,account:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8}){try{let p=this.deepCoin,d=e.address,g=e.baseCoin.decimals,_=e.quoteCoin.decimals,m=e.baseCoin.coinType,b=e.quoteCoin.coinType,w=l(t).mul(10**(_-g+9)).toString(),f=(0,B.normalizeStructTag)(m),C=(0,B.normalizeStructTag)(b),h=new S.Transaction,A,j,T=await this._sdk.getOwnerCoinAssets(o);if(s){let P=l(t).mul(l(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(P=l(P).add(l(i)).toString()),j=F.buildCoinForAmount(h,T,BigInt(P),C,!1,!0)?.targetCoin}else{let P=r;a||(P=l(r).abs().add(l(i)).toString()),A=F.buildCoinForAmount(h,T,BigInt(l(P).abs().toString()),f,!1,!0)?.targetCoin}let M=a?l(i).gt(0)?F.buildCoinForAmount(h,T,BigInt(l(i).abs().ceil().toString()),p.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,p.coinType):this.getEmptyCoin(h,p.coinType),q=h.moveCall({typeArguments:[s?m:b],target:"0x2::coin::zero",arguments:[]}),I=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(d),s?q:A,s?j:q,M,h.pure.u8(n),h.pure.u8(0),h.pure.u64(w),h.pure.u64(r),h.pure.bool(s),h.pure.bool(!1),h.pure.u64(u),h.object(B.SUI_CLOCK_OBJECT_ID)];return h.moveCall({typeArguments:[f,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:I}),h}catch(p){throw p instanceof Error?p:new Error(String(p))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:r,maxFee:n,account:s,payWithDeep:i,slippage:o=.01}){try{let a=e.address,u=e.baseCoin.coinType,p=e.quoteCoin.coinType,d=(0,B.normalizeStructTag)(u),g=(0,B.normalizeStructTag)(p),_=new S.Transaction,m,b,w=t,f,C=await this.getOrderBook(e,"all",6);if(r){let T=C?.ask?.[0]?.price||"0",M=l(T).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=l(M).plus(l(M).mul(o)).ceil().toString()}else{let T=await C?.bid?.[0]?.price||"0",M=l(T).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=l(M).minus(l(M).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(f=l(f).add(l(n)).toString()),b=this.getCoinAssets(g,f,h,_),m=this.getEmptyCoin(_,d)):(i||(w=l(w).add(l(n)).toString()),b=this.getEmptyCoin(_,g),m=this.getCoinAssets(d,w,h,_));let A=i?l(n).gt(0)?F.buildCoinForAmount(_,h,BigInt(l(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,this.deepCoin.coinType):this.getEmptyCoin(_,this.deepCoin.coinType),j=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(a),m,b,A,_.pure.u8(0),_.pure.u64(t),_.pure.bool(r),_.pure.bool(i),_.pure.u64(f),_.object(B.SUI_CLOCK_OBJECT_ID)];return _.moveCall({typeArguments:[d,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:j}),_}catch(a){throw a instanceof Error?a:new Error(String(a))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:r,quantity:n,isBid:s,orderType:i,maxFee:o,account:a,payWithDeep:u,expirationTimestamp:p=Date.now()+31536e8}){try{let d=this.deepCoin,g=l(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),_=t.baseCoin.coinType,m=t.quoteCoin.coinType,b=new S.Transaction,w=s?l(r).mul(l(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",f=s?"0":n,{baseAsset:C,quoteAsset:h,feeAsset:A,haveDeposit:j}=await this.getTransactionRelatedAssets(t,f,w,o,s,a,u,e,b);if(j){let q=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(t.address),b.object(e),C,h,A.feeAsset,b.pure.u8(i),b.pure.u8(0),b.pure.u64(g),b.pure.u64(n),b.pure.bool(s),b.pure.bool(u),b.pure.u64(p),b.object(B.SUI_CLOCK_OBJECT_ID)];return b.moveCall({typeArguments:[_,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:q}),b}let T=new S.Transaction;l(A.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:d,amountToDeposit:A.haveDepositFee,tx:T});let M=[T.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),T.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),T.object(t.address),T.object(e),T.pure.u8(i),T.pure.u8(0),T.pure.u64(g),T.pure.u64(n),T.pure.bool(s),T.pure.bool(u),T.pure.u64(p),T.object(B.SUI_CLOCK_OBJECT_ID)];return T.moveCall({typeArguments:[_,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:M}),T}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:r,newOrderQuantity:n}){let s=new S.Transaction;return s.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(e),s.object(t.address),s.pure.u128(r),s.pure.u64(n),s.object(B.SUI_CLOCK_OBJECT_ID)]}),s}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new S.Transaction,s=await this.getMarketPrice(e),i=l(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(a),n.pure.u64(u),n.pure.bool(!1),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),g=[],_=d.results[0].returnValues[0][0],m=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(_)),b=d.results[0].returnValues[1][0],w=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(b));return m.forEach((f,C)=>{let h=l(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=l(w[C]).div(Math.pow(10,t.decimals)).toString();g.push({price:h,quantity:A})}),g?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new S.Transaction,s=await this.getMarketPrice(e),i=l(s).gt(0)?l(s).div(3).toNumber():Math.pow(10,-6),o=l(s).gt(0)?s:Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(x(a,0)),n.pure.u64(x(u,0)),n.pure.bool(!0),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),g=[],_=d.results[0].returnValues[0][0],m=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(_)),b=d.results[0].returnValues[1][0],w=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(b));return m.forEach((f,C)=>{let h=l(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=l(w[C]).div(Math.pow(10,t.decimals)).toString();g.push({price:h,quantity:A})}),g?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:r,quoteCoin:n}=e,s=new S.Transaction,i=await this.getMarketPrice(e),o,a;t?(o=l(i).gt(0)?l(i).div(3).toNumber():Math.pow(10,-6),a=l(i).gt(0)?i:Math.pow(10,6)):(o=l(i).gt(0)?i:Math.pow(10,-1),a=l(i).gt(0)?l(i).mul(3).toNumber():Math.pow(10,6));let u=l(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),p=l(a).mul(Math.pow(10,9+n.decimals-r.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(x(u,0)),s.pure.u64(x(p,0)),s.pure.bool(t),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:s}),_=[],m=g.results[0].returnValues[0][0],b=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(m)),w=g.results[0].returnValues[1][0],f=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(w));return b.forEach((C,h)=>{let A=l(C).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),j=l(f[h]).div(Math.pow(10,r.decimals)).toString();_.push({price:A,quantity:j})}),_?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:r,quoteQuantity:n,isBid:s,maxFee:i,account:o,payWithDeep:a,slippage:u=.01,settled_balances:p={base:"0",quote:"0"}}){try{let d=(0,B.normalizeStructTag)(t.baseCoin.coinType),g=(0,B.normalizeStructTag)(t.quoteCoin.coinType),_=new S.Transaction;p&&(l(p.base).gt(0)||l(p.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},_);let{baseAsset:m,quoteAsset:b,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,_,p),f=await this.getOrderBook(t,"all",6);if(s){let A=f?.ask?.[0]?.price||"0",j=l(A).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(j).plus(l(j).mul(u)).ceil().toString()}else{let A=await f?.bid?.[0]?.price||"0",j=l(A).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(j).minus(l(j).mul(u)).floor().toString()}let C=n,h=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(t.address),_.object(e),m,b,w,_.pure.u8(0),_.pure.u64(r),_.pure.bool(s),_.pure.bool(a),_.pure.u64(C),_.object(B.SUI_CLOCK_OBJECT_ID)];return _.setSenderIfNotSet(o),_.moveCall({typeArguments:[d,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),_}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let r=new S.Transaction;e.forEach(u=>{let p=u?.pool,d=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(p.pool_id),r.pure.u128(BigInt(d))],typeArguments:[p.baseCoinType,p.quoteCoinType]})});let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:r}),s=k.bcs.struct("ID",{bytes:k.bcs.Address}),i=k.bcs.struct("OrderDeepPrice",{asset_is_base:k.bcs.bool(),deep_per_asset:k.bcs.u64()}),o=k.bcs.struct("Order",{balance_manager_id:s,order_id:k.bcs.u128(),client_order_id:k.bcs.u64(),quantity:k.bcs.u64(),filled_quantity:k.bcs.u64(),fee_is_deep:k.bcs.bool(),order_deep_price:i,epoch:k.bcs.u64(),status:k.bcs.u8(),expire_timestamp:k.bcs.u64()}),a=[];return n?.results?.forEach(u=>{let p=u.returnValues[0][0],d=o.parse(new Uint8Array(p));a.push(d)}),a}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:r,orderId:n}}async getOpenOrder(e,t,r,n,s=!1,i=new S.Transaction){let o;if(n)o=n;else{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[i.object(e.address),s?r:i.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let g=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:i})).results[s?1:0].returnValues[0][0];o=k.bcs.struct("VecSet",{constants:k.bcs.vector(k.bcs.U128)}).parse(new Uint8Array(g)).constants}if(o.length===0)return[];let a=o.map(d=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:d})),u=await this.getOrderInfoList(a,t)||[],p=[];return u.forEach(d=>{let g=this.decodeOrderId(BigInt(d.order_id));p.push({...d,price:g.price,isBid:g.isBid,pool:e})}),p}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new S.Transaction;r.forEach(d=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(d.pool_id),n.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(d=>d.returnValues?.[0]?.[0])||[],o=k.bcs.struct("VecSet",{constants:k.bcs.vector(k.bcs.U128)}),a=[];i.forEach((d,g)=>{let _=o.parse(new Uint8Array(d)).constants;_.length>0&&_.forEach(m=>{a.push({pool:r[g],orderId:m})})});let u=await this.getOrderInfoList(a,e)||[],p=[];return a.forEach((d,g)=>{let _=this.decodeOrderId(BigInt(d.orderId)),m=u.find(b=>b.order_id===d.orderId)||{};p.push({...d,...m,price:_.price,isBid:_.isBid})}),p}catch{return[]}}cancelOrders(e,t,r=new S.Transaction){return e.forEach(n=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(t),r.object(n.poolInfo.address),r.pure.u128(n.orderId),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(e,t,r,n,s,i){let o=this._sdk.fullClient,u=await new We.DeepBookClient({client:o,address:s,env:"testnet",balanceManagers:{test1:{address:i,tradeCap:""}}}).getLevel2Range(e,t,r,n)}processOrderBookData(e,t,r,n){let s=e.returnValues[0][0],i=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(s)),o=e.returnValues[1][0],a=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(o)),u={};return i.forEach((d,g)=>{let _=l(d).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),m=l(a[g]).div(Math.pow(10,t.decimals)).toString();u[_]?u[_]={price:_,quantity:l(u[_].quantity).add(m).toString()}:u[_]={price:_,quantity:m}}),Object.values(u)}getLevel2RangeTx(e,t,r,n,s=new S.Transaction){let{baseCoin:i,quoteCoin:o}=e,a=x(l(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),u=x(l(n).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0);return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(a),s.pure.u64(u),s.pure.bool(t),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[i.coinType,o.coinType]}),s}async fetchOrderBook(e,t,r,n,s,i){let o=new S.Transaction,{baseCoin:a,quoteCoin:u}=e;try{if(t==="bid"||t==="all"){let m=n,b=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,m,b,o)}if(t==="ask"||t==="all"){let m=r==="0"?n:r,b=s;o=this.getLevel2RangeTx(e,!1,m,b,o)}let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:o}),g=[];(t==="bid"||t==="all")&&(g=d.results?.[0]?this.processOrderBookData(d.results[0],a,u,i):[]);let _=[];if(t==="ask"||t==="all"){let m=t==="ask"?0:1;_=d.results?.[m]?this.processOrderBookData(d.results[m],a,u,i):[]}return{bid:g.sort((m,b)=>b.price-m.price),ask:_.sort((m,b)=>m.price-b.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,g=[],_=[];try{let m=this.getLevel2RangeTx(e,!0,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});g=b.results?.[0]?this.processOrderBookData(b.results[0],a,u,i):[]}catch{g=[]}try{let m=this.getLevel2RangeTx(e,!1,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});_=b.results?.[0]?this.processOrderBookData(b.results[0],a,u,i):[]}catch{_=[]}return{bid:g,ask:_}}}async getOrderBook(e,t,r){let n={bid:[],ask:[]};try{let s=await this.getMarketPrice(e),i=t,o=Math.pow(10,-r),a=Math.pow(10,r),u=await this.fetchOrderBook(e,i,s,o,a,r);return{bid:u?.bid,ask:u?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let r=new S.Transaction,n=await this.getMarketPrice(e),{baseCoin:s,quoteCoin:i}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),g=n,_=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(g).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(_),r.pure.u64(m),r.pure.bool(!0),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let d=n,g=Math.pow(10,6),_=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(g).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(_),r.pure.u64(m),r.pure.bool(!1),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType]})}let o=this._sdk.sdkOptions.simulationAccount.address,a=await this._sdk.fullClient.devInspectTransactionBlock({sender:o,transactionBlock:r}),u=[];if(t==="bid"||t==="all"){let d=a.results[0]?.returnValues[0]?.[0],g=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(d)),_=a.results[0]?.returnValues[1]?.[0],m=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(_));g.forEach((b,w)=>{let f=l(b).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),C=l(m[w]).div(Math.pow(10,s.decimals)).toString();u.push({price:f,quantity:C})})}let p=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,g=a.results[d]?.returnValues[0]?.[0],_=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(g)),m=a.results[d]?.returnValues[1]?.[0],b=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(m));_.forEach((w,f)=>{let C=l(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=l(b[f]).div(Math.pow(10,s.decimals)).toString();p.push({price:C,quantity:h})})}return{bid:u,ask:p}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,s)=>[(0,B.normalizeStructTag)(n.coinType),n]))}async getAccount(e,t,r=new S.Transaction){for(let o=0;o<t.length;o++){let a=t[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof e=="string"?r.object(e):e],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.senderAddress,transactionBlock:r}),s;if(n?.events.length===0)return null;let i=[];return n?.events?.forEach((o,a)=>{s=o?.parsedJson;let u=s.account.open_orders.contents,p=s.account.owed_balances,d=s.account.settled_balances,g=s.account.unclaimed_rebates,_=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:u,owed_balances:p,settled_balances:d,unclaimed_rebates:g,taker_volume:_,poolInfo:t[a]})}),i}async getSuiTransactionResponse(e,t=!1){let r=`${e}_getSuiTransactionResponse`,n=this.getCache(r,t);if(n!==void 0)return n;let s;try{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,s,864e5),s}transformExtensions(e,t,r=!0){let n=[];for(let s of t){let{key:i}=s.fields,{value:o}=s.fields;if(i==="labels")try{o=JSON.parse(decodeURIComponent(Je.Base64.decode(o)))}catch{}r&&(e[i]=o),n.push({key:i,value:o})}delete e.extension_fields,r||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let r=this.sdk.sdkOptions.coinlist.handle,n=`${r}_getCoinConfigs`,s=this.getCache(n,e);if(s)return s;let o=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(p=>p.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),u=[];return a.forEach(p=>{let d=this.buildCoinConfig(p,t);this.updateCache(`${r}_${d.address}_getCoinConfig`,d,864e5),u.push({...d})}),this.updateCache(n,u,864e5),u}buildCoinConfig(e,t=!0){let r=Se(e);r=r.value.fields;let n={...r};return n.id=Ae(e),n.address=$(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=(0,B.normalizeSuiObjectId)(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,r=3e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:r,baseCoinType:n,quoteCoinType:s}){let i=new S.Transaction,o=v.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",i);i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[n,s],arguments:[i.object(this.sdk.sdkOptions.deepbook.registry_id),i.pure.u64(e),i.pure.u64(t),i.pure.u64(r),o]});try{let a=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:i});if(a.effects.status.status==="success")return i;if(a.effects.status.status==="failure"&&a.effects.status.error&&a.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(a){throw a instanceof Error?a:new Error(String(a))}return i}};var H=require("@cetusprotocol/common-sdk"),y=require("@mysten/sui/bcs"),O=require("@mysten/sui/transactions"),E=require("@mysten/sui/utils");var Yt=({totalAssetsValue:c,totalDebtValue:e})=>l(e).eq(0)||l(c).eq(0)?"0":l(c).div(l(e)).toString(),je=c=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=c.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}=c.value.fields.risk_ratios.fields;return{id:c.id.id,name:c.name,base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s,liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}},Be=(c,e)=>{let{deposit_coin_type:t}=e,r=c.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=c.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:u}=c.protocol_fees.fields,{total_supply:p,total_borrow:d}=c.state.fields,g=l(o).sub(p).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:p,total_borrow:d,available_supply:g,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:u}};var me=require("@pythnetwork/pyth-sui-js");var Ee=10n;function Xt(c,e){if(!Ee)throw new Error("oraclePriceMultiplierDecimal is required");if(c===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(Ee- -e);return c*t}return c/10n**(e+Ee)}var Z=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;_cache={};constructor(e){this._sdk=e,this.connection=new me.SuiPriceServiceConnection(this.sdk.sdkOptions.pythUrl),this.suiPythClient=new me.SuiPythClient(this._sdk.fullClient,this._sdk.sdkOptions.margin_utils.pyth_state_id,this._sdk.sdkOptions.margin_utils.wormhole_state_id)}get sdk(){return this._sdk}async updatePythPriceIDs(e,t){let r=null,n=null;try{r=await this.connection.getPriceFeedsUpdateData(e)}catch(o){n=o}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${n?.message}`);let s=[];try{s=await this.suiPythClient.updatePriceFeeds(t,r,e)}catch(o){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${o}`)}let i=new Map;for(let o=0;o<e.length;o++)i.set(e[o],s[o]);return i}priceCheck(e,t=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let r={},n=[];if(t?e.forEach(o=>{let a=this._sdk.getCache(`getLatestPrice_${o.coinType}`);a&&this.priceCheck(a,60)?r[o.coinType]=a:n.push(o.coinType)}):n=e.map(o=>o.coinType),n.length===0)return r;let s=e.map(o=>o.feed);return(await this.connection.getLatestPriceUpdates(s))?.parsed?.forEach((o,a)=>{let u=o.price;if(u){let{price:p,expo:d}=u,g=l(p).mul(l(10).pow(l(d))).toString(),m={coin_type:e[a].coinType,price:g,oracle_price:0n,last_update_time:u.publish_time};m.oracle_price=Xt(BigInt(p),BigInt(d)),r[n[a]]=m,this._sdk.updateCache(`getLatestPrice_${m.coin_type}`,m)}}),r}};var te=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new Z(e),this._deep=e.sdkOptions.network==="mainnet"?Le:Ne}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,t=new O.Transaction){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:n}=e;try{let{margin_manager:s,initializer:i}=this.createMarginManager(e,t);return this.shareMarginManager({marginManager:s,initializer:i,baseCoin:r,quoteCoin:n},t),{tx:t,margin_manager:s,initializer:i}}catch(s){throw new Error(`Failed to create and share margin manager: ${s instanceof Error?s.message:String(s)}`)}}createMarginManager(e,t=new O.Transaction){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:n,quoteCoin:s}=e;try{let[i,o]=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[t.object(this.sdk.sdkOptions.margin_utils.versioned_id),t.object(r),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,s.coinType]});return{tx:t,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create margin manager: ${i instanceof Error?i.message:String(i)}`)}}shareMarginManager({marginManager:e,initializer:t,baseCoin:r,quoteCoin:n},s=new O.Transaction){try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,t],typeArguments:[r.coinType,n.coinType]}),s}catch(i){throw new Error(`Failed to share margin manager: ${i instanceof Error?i.message:String(i)}`)}}async getBalanceManagerByMarginManager(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");let t=`
2
2
  query Events($filter: EventFilter) {
3
3
  events(filter: $filter) {
4
4
  nodes {
@@ -12,4 +12,4 @@
12
12
  }
13
13
  }
14
14
  }
15
- `,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(i=>i?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===e).map(s=>s?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get quote balance: ${i instanceof Error?i.message:String(i)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getPoolMarginManagerBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let s=new T.Transaction,i=r===this.deepCoin.coinType,o=n===this.deepCoin.coinType,a=i||o;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),a||s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let u=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!u.results||!u.results[0]||!u.results[0].returnValues||!u.results[0].returnValues[0])throw new Error(`Transaction failed: ${u.effects?.status?.error||"Unknown error"}`);let g=k.bcs.U64.parse(new Uint8Array(u.results[0].returnValues[0][0])),d=k.bcs.U64.parse(new Uint8Array(u.results[1].returnValues[0][0])),p=a?i?g:d:k.bcs.U64.parse(new Uint8Array(u.results[2].returnValues[0][0]));return{[r]:g.toString(),[n]:d.toString(),[this.deepCoin.coinType]:p.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||i.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(i){throw new Error(`Failed to get borrowed shares: ${i instanceof Error?i.message:String(i)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:s,baseMarginPool:i,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:g})=>d=>{d.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(u),d.object(g),d.object(s),d.object(i),d.object(o),d.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new T.Transaction){let{account:r,marginManager:n,baseCoin:s,quoteCoin:i,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:g=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!s?.feed||!i?.feed)throw new Error("Base and quote coin feeds are required");if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),p=d.get(s.feed),b=d.get(i.feed);if(!p||!b)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:p,quotePriceFeedObjectId:b}));let m=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!m.results||!m.results[0]||!m.results[0].returnValues||m.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${m.effects?.status?.error||"Unknown error"}`);let _=(0,v.normalizeSuiAddress)(k.bcs.Address.parse(new Uint8Array(m.results[0].returnValues[0][0]))),w=(0,v.normalizeSuiAddress)(k.bcs.Address.parse(new Uint8Array(m.results[0].returnValues[1][0]))),y=Number(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[2][0])))/1e9,C=this.#e(BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[3][0]))),s.scalar,g),h=this.#e(BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[4][0]))),i.scalar,g),O=this.#e(BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[5][0]))),s.scalar,g),j=this.#e(BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[6][0]))),i.scalar,g),A=k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[7][0])),M=Number(k.bcs.u8().parse(new Uint8Array(m.results[0].returnValues[8][0]))),q=k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[9][0])),I=Number(k.bcs.u8().parse(new Uint8Array(m.results[0].returnValues[10][0]))),P=BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[11][0]))),D=BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[12][0]))),ne=BigInt(k.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:w,riskRatio:y,baseAsset:C,quoteAsset:h,baseDebt:O,quoteDebt:j,basePythPrice:A.toString(),basePythDecimals:M,quotePythPrice:q.toString(),quotePythDecimals:I,currentPrice:P,lowestTriggerAbovePrice:D,highestTriggerBelowPrice:ne}}catch(d){throw new Error(`Failed to get manager state: ${d instanceof Error?d.message:String(d)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:s,tx:i=new T.Transaction}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[i.object(t),i.object(r)],typeArguments:[n.coinType,s.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],u=o.results[0].returnValues[1][0];if(!n.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let g=k.bcs.U64.parse(new Uint8Array(a)),d=k.bcs.U64.parse(new Uint8Array(u));return{baseAsset:g.toString(),quoteAsset:d.toString(),tx:i}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:s,quoteMarginPool:i}){if(!e||!t||!r||!n||!s||!i)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!l(o).gt(l(a)),g=u?s:i,d=u?o:a,p=new T.Transaction;p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[p.object(g),p.pure.u64(BigInt(d)),p.object.clock()],typeArguments:[u?r:n]});let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:p});if(!b.results||!b.results[0]||!b.results[0].returnValues||!b.results[0].returnValues[0])throw new Error(`Transaction failed: ${b.effects?.status?.error||"Unknown error"}`);let m=k.bcs.U64.parse(new Uint8Array(b.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:m.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:m.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:s},i=new T.Transaction){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Ee.CoinAssist.buildCoinWithBalance(BigInt(n),s,i),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],i),u=a.get(t.feed),g=a.get(r.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?i.object(e):e,i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(u),i.object(g),o,i.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType,s]}),i}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:s,quoteCoin:i,pool:o,amount:a,withdrawCoinType:u},g=new T.Transaction){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!s.feed||!i.feed)throw new Error("Base and quote coin feeds are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],g),p=d.get(s.feed),b=d.get(i.feed);if(!p||!b)throw new Error("Failed to get price feed object IDs");let m=g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[g.object(this._sdk.sdkOptions.margin_utils.global_config_id),g.object(this._sdk.sdkOptions.margin_utils.versioned_id),g.object(t),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(r),g.object(n),g.object(p),g.object(b),g.object(o),g.pure.u64(BigInt(a)),g.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType,u]});return g.transferObjects([m],e),g}catch(d){throw new Error(`Failed to withdraw: ${d instanceof Error?d.message:String(d)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new T.Transaction){if(!e||!t||!s)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),g=a.get(n.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(g),o.object(s),o.pure.u64(BigInt(i)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new T.Transaction){if(!e||!t||!s)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),g=a.get(n.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(g),o.object(s),o.pure.u64(BigInt(i)),o.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new T.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:r.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new T.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:n.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:s,isBase:i,amount:o},a=new T.Transaction){try{let u=this.sdk.senderAddress,g,d=o;o||(g=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),d=i?g.baseBorrowedAmount:g.quoteBorrowedAmount);let p,b={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let m=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});p=l(d).sub(m).toString()}else{let m=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});p=l(d).sub(m).toString()}l(p).gt(0)&&await this.deposit({...b,amount:p},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${i?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(i?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,s.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:s,isBid:i,payWithDeep:o,exactBase:a},u=new T.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!s||BigInt(W(s,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:g,baseCoin:d,quoteCoin:p}=t;if(d.decimals===void 0||p.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(g),u.pure.u8(r),u.pure.u64(n),u.pure.bool(i),u.pure.bool(o),u.pure.bool(a===void 0?!i:a),u.pure.u64(s),u.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[d.coinType,p.coinType]}),u}catch(b){throw new Error(`Failed to place market order: ${b instanceof Error?b.message:String(b)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},g=new T.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!s||!i)throw new Error("Price and quantity are required");let{id:d,baseCoin:p,quoteCoin:b}=t;if(p.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let m=BigInt(l(s).mul(10**(b.decimals-p.decimals+9)).toString()),_=BigInt(W(i,p.decimals));if(m<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[g.object(this.sdk.sdkOptions.margin_utils.global_config_id),g.object(this.sdk.sdkOptions.margin_utils.versioned_id),g.object(e),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(d),g.pure.u8(r),g.pure.u8(n),g.pure.u64(m),g.pure.u64(_),g.pure.bool(o),g.pure.bool(a),g.pure.u64(u),g.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[p.coinType,b.coinType]}),g}catch(m){throw new Error(`Failed to place limit order: ${m instanceof Error?m.message:String(m)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},s=new T.Transaction){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let i=BigInt(W(n,t.baseCoin.decimals));if(i<=0n)throw new Error("New quantity must be greater than zero");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t.id),s.pure.u128(r),s.pure.u64(i),s.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to modify order: ${i instanceof Error?i.message:String(i)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new T.Transaction){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(s){throw new Error(`Failed to cancel order: ${s instanceof Error?s.message:String(s)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new T.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:s,priceInput:i,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:g},d=new T.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(t.id),d.object(r),d.pure.u8(n),d.pure.u8(s),d.pure.u64(i),d.pure.u64(o),d.pure.bool(a),d.pure.bool(u),d.pure.u64(g),d.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),d}catch(p){throw new Error(`Failed to place reduce only limit order: ${p instanceof Error?p.message:String(p)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:s,isBid:i,payWithDeep:o},a=new T.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(s),a.pure.bool(i),a.pure.bool(o),a.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,i?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new T.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let s=new T.Transaction,i=t[n];if(i.margin_manager_id){let o=await s.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[s.object(i.margin_manager_id)],typeArguments:[i.baseCoin.coinType,i.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(i,this.sdk.senderAddress,o,void 0,!0,s);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new T.Transaction,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v.SUI_CLOCK_OBJECT_ID)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new T.Transaction,{supplierCap:s}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:s,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([s],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:s}){let i=s??new T.Transaction;if(!t)throw new Error("Either supplierCap must be provided");let o=Ee.CoinAssist.buildCoinWithBalance(BigInt(n),r,i);return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),o,i.pure.option("address","0x0"),i.object(v.SUI_CLOCK_OBJECT_ID)]}),i}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:s,withdrawAll:i,tx:o=new T.Transaction}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?null:o.pure.u64(r)}),o.object(v.SUI_CLOCK_OBJECT_ID)]});return s?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new T.Transaction,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v.SUI_CLOCK_OBJECT_ID)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new T.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,s=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:s}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(s=>s.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let s=0;s<r.length;s++){let i=r[s].data.content.fields;n.push(Se(i))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],s=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;s.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let i=await this.sdk.fullClient.batchGetObjects(s,{showContent:!0}),o=[];for(let a=0;a<i.length;a++){let u=i[a].data.content.fields;o.push(je(u,n[a]))}return o}async getBaseQuantityIn(e,t,r,n=.01){let s=new T.Transaction;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),g=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:l(t).sub(a.toString()).toString(),quantityInLeft:l(o.toString()).add(g.takerFee).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(e,t,r,n=.01){let s=new T.Transaction;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_quote_quantity_out":"::pool::get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),g=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:l(t).sub(o).toString(),quantityInLeft:l(a.toString()).add(l(g.takerFee)).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(e,t,r){let n=new T.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t,r){let n=new T.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=k.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new T.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new T.Transaction){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),s=e/n,i=e%n;if(i===0n)return s.toString();let o=t.toString().length-1,g=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return g?`${s}.${g}`:s.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,s=r.config.fields,i=s.interest_config.fields,o=s.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(i.base_rate),base_slope:BigInt(i.base_slope),optimal_utilization:BigInt(i.optimal_utilization),excess_slope:BigInt(i.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}async batchGetBorrowedShares({account:e,marginManagerList:t}){let r=new T.Transaction;return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(s.marginManagerId)],typeArguments:[s.baseCoinType,s.quoteCoinType]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r})).results.map((s,i)=>{let o=k.bcs.U64.parse(new Uint8Array(s.returnValues[0][0])),a=k.bcs.U64.parse(new Uint8Array(s.returnValues[1][0]));return{marginManagerId:t[i].marginManagerId,baseBorrowedShare:o,quoteBorrowedShare:a}})}async betchGetOpenOrders({account:e,marginManagerList:t},r=new T.Transaction,n=!1){t.forEach(m=>{let _=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(_)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(m.poolId),_],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[r.object(m.poolId),_],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((m,_)=>({marginManagerId:t[_].marginManagerId,...m?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(m=>m?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=k.bcs.struct("VecSet",{constants:k.bcs.vector(k.bcs.U128)}),u=[];o.forEach((m,_)=>{let w=a.parse(new Uint8Array(m.returnValues[0][0])).constants;w.length>0&&w.forEach(y=>{u.push({pool:{pool_id:t[_].poolId,baseCoinType:t[_].baseCoinType,quoteCoinType:t[_].quoteCoinType},marginManagerId:t[_].marginManagerId,orderId:y})})});let g=await this.sdk.DeepbookUtils.getOrderInfoList(u,e)||[],d=s.results.filter(m=>m?.returnValues?.length===3),p=[];d.forEach((m,_)=>{p.push({marginManagerId:t[_].marginManagerId,base:k.bcs.U64.parse(new Uint8Array(m.returnValues[0][0])),quote:k.bcs.U64.parse(new Uint8Array(m.returnValues[1][0])),deep:k.bcs.U64.parse(new Uint8Array(m.returnValues[2][0]))})});let b=[];return u.forEach((m,_)=>{let w=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId)),y=g.find(C=>C.order_id===m.orderId)||{};b.push({...m,...y,price:w.price.toString(),isBid:w.isBid})}),{openOrders:b,settledBalances:i,lockedBalances:p}}async getSingleMarginManagerOpenOrders({account:e,marginManagerId:t,poolId:r,baseCoinType:n,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){let a=new T.Transaction,u=a.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[a.object(t)],typeArguments:[n,s]});a.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[a.object(r),u],typeArguments:[n,s]});let g=k.bcs.struct("VecSet",{constants:k.bcs.vector(k.bcs.U128)}),p=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),b=g.parse(new Uint8Array(p.returnValues[0][0])).constants,m=[];b.forEach(h=>{m.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let _=m?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(m,e)||[]:[],w=[];m.forEach((h,O)=>{let j=this.sdk.DeepbookUtils.decodeOrderId(BigInt(h.orderId)),A=_.find(M=>M.order_id===h.orderId)||{};w.push({...h,...A,price:j.price.toString(),isBid:j.isBid})});let y={marginManagerId:t,base:"0",quote:"0",deep:"0"};if(_?.length>0){let h=new T.Transaction,O=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[h.object(r),O],typeArguments:[n,s]});let A=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h})).results.find(M=>M?.returnValues?.length===3);y={...y,base:k.bcs.U64.parse(new Uint8Array(A.returnValues[0][0])),quote:k.bcs.U64.parse(new Uint8Array(A.returnValues[1][0])),deep:k.bcs.U64.parse(new Uint8Array(A.returnValues[2][0]))}}let C={base:"0",quote:"0",deep:"0"};try{let h=new T.Transaction,O=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[h.object(r),O],typeArguments:[n,s]});let j=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h});C={marginManagerId:t,...C,...j?.events?.parsedJson?.account?.settled_balances||{}}}catch{}return{openOrders:w,settledBalances:[C],lockedBalances:[y]}}async getAllPosRelevantData({account:e,marginManagerList:t}){try{let{openOrders:r,settledBalances:n,lockedBalances:s}=t?.length>1?await this.betchGetOpenOrders({account:e,marginManagerList:t}):await this.getSingleMarginManagerOpenOrders({account:e,...t[0]}),i=await this.batchGetBorrowedShares({account:e,marginManagerList:t}),o=new T.Transaction,a=0,u=[];t.forEach(p=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[a]={type:"base_balance",marginManagerId:p.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[a]={type:"quote_balance",marginManagerId:p.marginManagerId},a++;let b=i?.find(m=>m.marginManagerId===p.marginManagerId);if(b&&(Number(b.baseBorrowedShare)>0||Number(b.quoteBorrowedShare)>0)){let m=b.baseBorrowedShare,_=b.quoteBorrowedShare,w=!!l(m).gt(l(_)),y=w?p.baseMarginPool:p.quoteMarginPool,C=w?m:_;o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[o.object(y),o.pure.u64(BigInt(C)),o.object.clock()],typeArguments:[w?p?.baseCoinType:p?.quoteCoinType]}),u[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:p.marginManagerId},a++}});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),d=Object.fromEntries(t.map(p=>[p.marginManagerId,{...p,quote_balance:"0",base_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return g?.results?.forEach((p,b)=>{let m=u[b],_=k.bcs.U64.parse(new Uint8Array(p.returnValues[0][0]));d[m.marginManagerId]={...d[m.marginManagerId],[m.type]:_}}),r.forEach(p=>{d[p.marginManagerId].open_orders.push(p)}),n.forEach(p=>{d[p.marginManagerId].settled_balances=p}),s.forEach(p=>{d[p.marginManagerId].locked_balances=p}),d}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}};var Ze=require("@mysten/sui/client"),te=class extends Ze.SuiClient{async queryEventsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],s=!0,i=r==="all",o=i?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:i?null:r.limit});a.data?(n=[...n,...a.data],s=a.hasNextPage,o=a.nextCursor):s=!1}while(i&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let s=0;s<Math.ceil(e.length/r);s++){let i=await this.multiGetObjects({ids:e.slice(s*r,r*(s+1)),options:t});n=[...n,...i]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};var ve=Pe(require("decimal.js"));ve.default.config({precision:64,rounding:ve.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var R=1000000000n,Ye=365n*24n*60n*60n*1000n;function Xe(c,e){return e===0n?0n:c*R/e}function et(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(c<n)return t+c*r/R;{let i=c-n,o=n*r/R,a=i*s/R;return t+o+a}}function Me(c,e){let t=c*e,r=t/R;return t%R>0n?r+1n:r}function tt(c,e,t,r){let n=e.borrow_shares===0n?R:e.total_borrow*R/e.borrow_shares,s=Me(c,n),i=Xe(e.total_borrow,e.total_supply),o=et(i,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/R*a/Ye,g=e.borrow_shares===0n?0n:Me(u,c*R/e.borrow_shares),d=s+g;return{confirmedDebt:s,estimatedInterest:g,totalDebt:d,annualInterestRate:o}}function er(c,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=tt(c,e,t,s);return i}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new J(this),this._graphqlClient=new rt.SuiGraphQLClient({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],s=null,i=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(i,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:s}):this.fullClient.getAllCoins({owner:e,cursor:s}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:$(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),s=a.nextCursor,!a.hasNextPage)break}return this.updateCache(i,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=Q(r),n.value=t):n=new K(t,Q(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var tr="0x0000000000000000000000000000000000000000000000000000000000000006",rr="pool_script",nr="pool_script_v2",sr="router",ir="router_with_partner",or="fetcher_script",ar="expect_swap",cr="utils",ur="0x1::coin::CoinInfo",dr="0x1::coin::CoinStore",lr="custodian_v2",gr="clob_v2",pr="endpoints_v2",mr=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var nt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(nt||{}),st=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(st||{});var br=re;0&&(module.exports={CLOCK_ADDRESS,CachedContent,CetusClmmSDK,ClmmExpectSwapModule,ClmmFetcherModule,ClmmIntegratePoolModule,ClmmIntegratePoolV2Module,ClmmIntegrateRouterModule,ClmmIntegrateRouterWithPartnerModule,ClmmIntegrateUtilsModule,CoinAssist,CoinInfoAddress,CoinStoreAddress,DEEP_SCALAR,DEFAULT_GAS_BUDGET_FOR_MERGE,DEFAULT_GAS_BUDGET_FOR_SPLIT,DEFAULT_GAS_BUDGET_FOR_STAKE,DEFAULT_GAS_BUDGET_FOR_TRANSFER,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,DEFAULT_NFT_TRANSFER_GAS_FEE,DeepbookClobV2Moudle,DeepbookCustodianV2Moudle,DeepbookEndpointsV2Moudle,DeepbookUtilsModule,FLOAT_SCALAR,FLOAT_SCALING,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,MarginUtilsModule,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,SelfMatchingOption,TransactionUtil,YEAR_MS,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime1min,cacheTime24h,cacheTime5min,calc100PercentRepay,calcDebtDetail,calcInterestRate,calcUtilizationRate,calculateRiskRatio,checkAddress,composeType,d,decimalsMultiplier,extractAddressFromType,extractStructTagFromType,fixCoinType,fixDown,fixSuiObjectId,fromDecimalsAmount,getDefaultSuiInputType,getFutureTime,getMoveObject,getMoveObjectType,getMovePackageContent,getObjectDeletedResponse,getObjectDisplay,getObjectFields,getObjectId,getObjectNotExistsResponse,getObjectOwner,getObjectPreviousTransactionDigest,getObjectReference,getObjectType,getObjectVersion,getSuiObjectData,hasPublicTransfer,hexToNumber,hexToString,isSortedSymbols,isSuiObjectResponse,maxDecimal,mulRoundUp,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,sleepTime,toBuffer,toDecimalsAmount,utf8to16,wrapDeepBookMarginPoolInfo,wrapDeepBookPoolInfo});
15
+ `,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(i=>i?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===e).map(s=>s?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get quote balance: ${i instanceof Error?i.message:String(i)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getPoolMarginManagerBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let s=new O.Transaction,i=r===this.deepCoin.coinType,o=n===this.deepCoin.coinType,a=i||o;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),a||s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let u=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!u.results||!u.results[0]||!u.results[0].returnValues||!u.results[0].returnValues[0])throw new Error(`Transaction failed: ${u.effects?.status?.error||"Unknown error"}`);let p=y.bcs.U64.parse(new Uint8Array(u.results[0].returnValues[0][0])),d=y.bcs.U64.parse(new Uint8Array(u.results[1].returnValues[0][0])),g=a?i?p:d:y.bcs.U64.parse(new Uint8Array(u.results[2].returnValues[0][0]));return{[r]:p.toString(),[n]:d.toString(),[this.deepCoin.coinType]:g.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O.Transaction;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||i.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(i){throw new Error(`Failed to get borrowed shares: ${i instanceof Error?i.message:String(i)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:s,baseMarginPool:i,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:p})=>d=>{d.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(u),d.object(p),d.object(s),d.object(i),d.object(o),d.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new O.Transaction){let{account:r,marginManager:n,baseCoin:s,quoteCoin:i,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:p=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!s?.feed||!i?.feed)throw new Error("Base and quote coin feeds are required");if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),g=d.get(s.feed),_=d.get(i.feed);if(!g||!_)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:g,quotePriceFeedObjectId:_}));let m=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!m.results||!m.results[0]||!m.results[0].returnValues||m.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${m.effects?.status?.error||"Unknown error"}`);let b=(0,E.normalizeSuiAddress)(y.bcs.Address.parse(new Uint8Array(m.results[0].returnValues[0][0]))),w=(0,E.normalizeSuiAddress)(y.bcs.Address.parse(new Uint8Array(m.results[0].returnValues[1][0]))),f=Number(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[2][0])))/1e9,C=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[3][0]))),s.scalar,p),h=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[4][0]))),i.scalar,p),A=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[5][0]))),s.scalar,p),j=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[6][0]))),i.scalar,p),T=y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[7][0])),M=Number(y.bcs.u8().parse(new Uint8Array(m.results[0].returnValues[8][0]))),q=y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[9][0])),I=Number(y.bcs.u8().parse(new Uint8Array(m.results[0].returnValues[10][0]))),P=BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[11][0]))),D=BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[12][0]))),se=BigInt(y.bcs.U64.parse(new Uint8Array(m.results[0].returnValues[13][0])));return{managerId:b,deepbookPoolId:w,riskRatio:f,baseAsset:C,quoteAsset:h,baseDebt:A,quoteDebt:j,basePythPrice:T.toString(),basePythDecimals:M,quotePythPrice:q.toString(),quotePythDecimals:I,currentPrice:P,lowestTriggerAbovePrice:D,highestTriggerBelowPrice:se}}catch(d){throw new Error(`Failed to get manager state: ${d instanceof Error?d.message:String(d)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:s,tx:i=new O.Transaction}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[i.object(t),i.object(r)],typeArguments:[n.coinType,s.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],u=o.results[0].returnValues[1][0];if(!n.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let p=y.bcs.U64.parse(new Uint8Array(a)),d=y.bcs.U64.parse(new Uint8Array(u));return{baseAsset:p.toString(),quoteAsset:d.toString(),tx:i}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:s,quoteMarginPool:i}){if(!e||!t||!r||!n||!s||!i)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!l(o).gt(l(a)),p=u?s:i,d=u?o:a,g=new O.Transaction;g.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[g.object(p),g.pure.u64(BigInt(d)),g.object.clock()],typeArguments:[u?r:n]});let _=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:g});if(!_.results||!_.results[0]||!_.results[0].returnValues||!_.results[0].returnValues[0])throw new Error(`Transaction failed: ${_.effects?.status?.error||"Unknown error"}`);let m=y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:m.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:m.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:s},i=new O.Transaction){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=H.CoinAssist.buildCoinWithBalance(BigInt(n),s,i),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],i),u=a.get(t.feed),p=a.get(r.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?i.object(e):e,i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(u),i.object(p),o,i.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType,s]}),i}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:s,quoteCoin:i,pool:o,amount:a,withdrawCoinType:u},p=new O.Transaction){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!s.feed||!i.feed)throw new Error("Base and quote coin feeds are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],p),g=d.get(s.feed),_=d.get(i.feed);if(!g||!_)throw new Error("Failed to get price feed object IDs");let m=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(g),p.object(_),p.object(o),p.pure.u64(BigInt(a)),p.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType,u]});return p.transferObjects([m],e),p}catch(d){throw new Error(`Failed to withdraw: ${d instanceof Error?d.message:String(d)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new O.Transaction){if(!e||!t||!s)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(s),o.pure.u64(BigInt(i)),o.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new O.Transaction){if(!e||!t||!s)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),p=a.get(n.feed);if(!u||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(p),o.object(s),o.pure.u64(BigInt(i)),o.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new O.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:r.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new O.Transaction){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:n.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:s,isBase:i,amount:o},a=new O.Transaction){try{let u=this.sdk.senderAddress,p,d=o;o||(p=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),d=i?p.baseBorrowedAmount:p.quoteBorrowedAmount);let g,_={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let m=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});g=l(d).sub(m).toString()}else{let m=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});g=l(d).sub(m).toString()}l(g).gt(0)&&await this.deposit({..._,amount:g},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${i?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(i?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,s.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:s,isBid:i,payWithDeep:o,exactBase:a},u=new O.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(J(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!s||BigInt(J(s,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:d,quoteCoin:g}=t;if(d.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(p),u.pure.u8(r),u.pure.u64(n),u.pure.bool(i),u.pure.bool(o),u.pure.bool(a===void 0?!i:a),u.pure.u64(s),u.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[d.coinType,g.coinType]}),u}catch(_){throw new Error(`Failed to place market order: ${_ instanceof Error?_.message:String(_)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},p=new O.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!s||!i)throw new Error("Price and quantity are required");let{id:d,baseCoin:g,quoteCoin:_}=t;if(g.decimals===void 0||_.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let m=BigInt(l(s).mul(10**(_.decimals-g.decimals+9)).toString()),b=BigInt(J(i,g.decimals));if(m<=0n||b<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(d),p.pure.u8(r),p.pure.u8(n),p.pure.u64(m),p.pure.u64(b),p.pure.bool(o),p.pure.bool(a),p.pure.u64(u),p.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[g.coinType,_.coinType]}),p}catch(m){throw new Error(`Failed to place limit order: ${m instanceof Error?m.message:String(m)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},s=new O.Transaction){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let i=BigInt(J(n,t.baseCoin.decimals));if(i<=0n)throw new Error("New quantity must be greater than zero");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t.id),s.pure.u128(r),s.pure.u64(i),s.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to modify order: ${i instanceof Error?i.message:String(i)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new O.Transaction){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(s){throw new Error(`Failed to cancel order: ${s instanceof Error?s.message:String(s)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new O.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:s,priceInput:i,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:p},d=new O.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(t.id),d.object(r),d.pure.u8(n),d.pure.u8(s),d.pure.u64(i),d.pure.u64(o),d.pure.bool(a),d.pure.bool(u),d.pure.u64(p),d.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),d}catch(g){throw new Error(`Failed to place reduce only limit order: ${g instanceof Error?g.message:String(g)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:s,isBid:i,payWithDeep:o},a=new O.Transaction){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(s),a.pure.bool(i),a.pure.bool(o),a.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,i?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new O.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let s=new O.Transaction,i=t[n];if(i.margin_manager_id){let o=await s.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[s.object(i.margin_manager_id)],typeArguments:[i.baseCoin.coinType,i.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(i,this.sdk.senderAddress,o,void 0,!0,s);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new O.Transaction,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(E.SUI_CLOCK_OBJECT_ID)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new O.Transaction,{supplierCap:s}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:s,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([s],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:s}){let i=s??new O.Transaction;if(!t)throw new Error("Either supplierCap must be provided");let o=H.CoinAssist.buildCoinWithBalance(BigInt(n),r,i);return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),o,i.pure.option("address","0x0"),i.object(E.SUI_CLOCK_OBJECT_ID)]}),i}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:s,withdrawAll:i,tx:o=new O.Transaction}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?null:o.pure.u64(r)}),o.object(E.SUI_CLOCK_OBJECT_ID)]});return s?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new O.Transaction,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new O.Transaction;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(E.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,s=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:s}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(s=>s.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let s=0;s<r.length;s++){let i=r[s].data.content.fields;n.push(je(i))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],s=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;s.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let i=await this.sdk.fullClient.batchGetObjects(s,{showContent:!0}),o=[];for(let a=0;a<i.length;a++){let u=i[a].data.content.fields;o.push(Be(u,n[a]))}return o}async getBaseQuantityIn(e,t,r,n=.01){let s=new O.Transaction;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(E.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),p=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:l(t).sub(a.toString()).toString(),quantityInLeft:l(o.toString()).add(p.takerFee).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(e,t,r,n=.01){let s=new O.Transaction;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_quote_quantity_out":"::pool::get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(E.SUI_CLOCK_OBJECT_ID)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),p=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:l(t).sub(o).toString(),quantityInLeft:l(a.toString()).add(l(p.takerFee)).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(e,t,r){let n=new O.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(E.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t,r){let n=new O.Transaction;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(E.SUI_CLOCK_OBJECT_ID)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=y.bcs.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new O.Transaction,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new O.Transaction){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),s=e/n,i=e%n;if(i===0n)return s.toString();let o=t.toString().length-1,p=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${s}.${p}`:s.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,s=r.config.fields,i=s.interest_config.fields,o=s.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(i.base_rate),base_slope:BigInt(i.base_slope),optimal_utilization:BigInt(i.optimal_utilization),excess_slope:BigInt(i.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}async batchGetBorrowedShares({account:e,marginManagerList:t}){let r=new O.Transaction;return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(s.marginManagerId)],typeArguments:[s.baseCoinType,s.quoteCoinType]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r})).results.map((s,i)=>{let o=y.bcs.U64.parse(new Uint8Array(s.returnValues[0][0])),a=y.bcs.U64.parse(new Uint8Array(s.returnValues[1][0]));return{marginManagerId:t[i].marginManagerId,baseBorrowedShare:o,quoteBorrowedShare:a}})}async betchGetOpenOrders({account:e,marginManagerList:t},r=new O.Transaction,n=!1){t.forEach(m=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(b)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((m,b)=>({marginManagerId:t[b].marginManagerId,...m?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(m=>m?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=y.bcs.struct("VecSet",{constants:y.bcs.vector(y.bcs.U128)}),u=[];o.forEach((m,b)=>{let w=a.parse(new Uint8Array(m.returnValues[0][0])).constants;w.length>0&&w.forEach(f=>{u.push({pool:{pool_id:t[b].poolId,baseCoinType:t[b].baseCoinType,quoteCoinType:t[b].quoteCoinType},marginManagerId:t[b].marginManagerId,orderId:f})})});let p=await this.sdk.DeepbookUtils.getOrderInfoList(u,e)||[],d=s.results.filter(m=>m?.returnValues?.length===3),g=[];d.forEach((m,b)=>{g.push({marginManagerId:t[b].marginManagerId,base:y.bcs.U64.parse(new Uint8Array(m.returnValues[0][0])),quote:y.bcs.U64.parse(new Uint8Array(m.returnValues[1][0])),deep:y.bcs.U64.parse(new Uint8Array(m.returnValues[2][0]))})});let _=[];return u.forEach((m,b)=>{let w=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId)),f=p.find(C=>C.order_id===m.orderId)||{};_.push({...m,...f,price:w.price.toString(),isBid:w.isBid})}),{openOrders:_,settledBalances:i,lockedBalances:g}}async getSingleMarginManagerOpenOrders({account:e,marginManagerId:t,poolId:r,baseCoinType:n,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){let a=new O.Transaction,u=a.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[a.object(t)],typeArguments:[n,s]});a.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[a.object(r),u],typeArguments:[n,s]});let p=y.bcs.struct("VecSet",{constants:y.bcs.vector(y.bcs.U128)}),g=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),_=p.parse(new Uint8Array(g.returnValues[0][0])).constants,m=[];_.forEach(h=>{m.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let b=m?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(m,e)||[]:[],w=[];m.forEach((h,A)=>{let j=this.sdk.DeepbookUtils.decodeOrderId(BigInt(h.orderId)),T=b.find(M=>M.order_id===h.orderId)||{};w.push({...h,...T,price:j.price.toString(),isBid:j.isBid})});let f={marginManagerId:t,base:"0",quote:"0",deep:"0"};if(b?.length>0){let h=new O.Transaction,A=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[h.object(r),A],typeArguments:[n,s]});let T=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h})).results.find(M=>M?.returnValues?.length===3);f={...f,base:y.bcs.U64.parse(new Uint8Array(T.returnValues[0][0])),quote:y.bcs.U64.parse(new Uint8Array(T.returnValues[1][0])),deep:y.bcs.U64.parse(new Uint8Array(T.returnValues[2][0]))}}let C={base:"0",quote:"0",deep:"0"};try{let h=new O.Transaction,A=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[h.object(r),A],typeArguments:[n,s]});let j=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h});C={marginManagerId:t,...C,...j?.events?.parsedJson?.account?.settled_balances||{}}}catch{}return{openOrders:w,settledBalances:[C],lockedBalances:[f]}}async getAllPosRelevantData({account:e,marginManagerList:t}){try{let{openOrders:r,settledBalances:n,lockedBalances:s}=await this.betchGetOpenOrders({account:e,marginManagerList:t}),i=await this.batchGetBorrowedShares({account:e,marginManagerList:t}),o=new O.Transaction,a=0,u=[];t.forEach(g=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),u[a]={type:"base_balance",marginManagerId:g.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),u[a]={type:"quote_balance",marginManagerId:g.marginManagerId},a++;let _=i?.find(m=>m.marginManagerId===g.marginManagerId);if(_&&(Number(_.baseBorrowedShare)>0||Number(_.quoteBorrowedShare)>0)){let m=_.baseBorrowedShare,b=_.quoteBorrowedShare,w=!!l(m).gt(l(b)),f=w?g.baseMarginPool:g.quoteMarginPool,C=w?m:b;o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[o.object(f),o.pure.u64(BigInt(C)),o.object.clock()],typeArguments:[w?g?.baseCoinType:g?.quoteCoinType]}),u[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:g.marginManagerId},a++}});let p=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),d=Object.fromEntries(t.map(g=>[g.marginManagerId,{...g,quote_balance:"0",base_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return p?.results?.forEach((g,_)=>{let m=u[_],b=y.bcs.U64.parse(new Uint8Array(g.returnValues[0][0]));d[m.marginManagerId]={...d[m.marginManagerId],[m.type]:b}}),r.forEach(g=>{d[g.marginManagerId].open_orders.push(g)}),n.forEach(g=>{d[g.marginManagerId].settled_balances=g}),s.forEach(g=>{d[g.marginManagerId].locked_balances=g}),Object.values(d).forEach(g=>{g.locked_balances&&g.settled_balances&&(g.locked_balances={...g.locked_balances,base:l(g.locked_balances.base||"0").minus(l(g.settled_balances.base||"0")).toString(),quote:l(g.locked_balances.quote||"0").minus(l(g.settled_balances.quote||"0")).toString(),deep:l(g.locked_balances.deep||"0").minus(l(g.settled_balances.deep||"0")).toString()})}),d}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s,margin_registry_id:i}=r,{margin_manager_id:o,pool_id:a,base_coin:u,quote_coin:p,conditional_order_id:d,pending_order:g,is_trigger_below_price:_,trigger_price:m}=e,b=await this.pythPrice.updatePythPriceIDs([u.feed,p.feed],t),w=b.get(u.feed),f=b.get(p.feed);if(!w||!f)throw new Error("Failed to get price feed object IDs");let C=l(m).mul(1e9).mul(p.scalar).div(u.scalar).round().toString(),h=t.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[t.pure.bool(_),t.pure.u64(C)]}),A=this.newPendingOrder(g,t);t.moveCall({target:`${r.published_at}::margin_utils::add_conditional_order`,arguments:[t.object(n),t.object(s),t.object(o),t.object(a),t.object(w),t.object(f),t.object(i),typeof d=="string"?t.pure.u64(BigInt(d)):d,h,A,t.object(H.CLOCK_ADDRESS)],typeArguments:[u.coinType,p.coinType]})}newPendingOrder(e,t){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in e){let{client_order_id:n,order_type:s,self_matching_option:i,price:o,quantity:a,is_bid:u,pay_with_deep:p,expire_timestamp:d}=e;return t.moveCall({target:`${r.published_at}::margin_utils::new_pending_limit_order`,arguments:[t.pure.u64(n),t.pure.u8(s),t.pure.u8(i),t.pure.u64(o),t.pure.u64(a),t.pure.bool(u),t.pure.bool(p),t.pure.u64(d)]})}else{let{client_order_id:n,self_matching_option:s,quantity:i,is_bid:o,pay_with_deep:a}=e;return t.moveCall({target:`${r.published_at}::margin_utils::new_pending_market_order`,arguments:[t.pure.u64(n),t.pure.u8(s),t.pure.u64(i),t.pure.bool(o),t.pure.bool(a)]})}}cancelAllConditionalOrders(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s}=r,{margin_manager_id:i,base_coin_type:o,quote_coin_type:a}=e;t.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[t.object(n),t.object(s),t.object(i),t.object(H.CLOCK_ADDRESS)],typeArguments:[o,a]})}cancelConditionalOrders(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s}=r,{margin_manager_id:i,base_coin_type:o,quote_coin_type:a,conditional_order_id:u}=e;t.moveCall({target:`${r.published_at}::margin_utils::cancel_conditional_order`,arguments:[t.object(n),t.object(s),t.object(i),t.pure.u64(u),t.object(H.CLOCK_ADDRESS)],typeArguments:[o,a]})}async getConditionalOrders(e,t){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(a=>{let{margin_manager_id:u,base_coin_type:p,quote_coin_type:d,conditional_order_id:g}=a;t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[t.object(u),t.pure.u64(g)],typeArguments:[p,d]})});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:(0,E.normalizeSuiAddress)("0x0"),transactionBlock:t});if(!n?.results||n.results.length!==e.length)return[];let s=y.bcs.struct("Condition",{trigger_below_price:y.bcs.bool(),trigger_price:y.bcs.u64()}),i=y.bcs.struct("PendingOrder",{is_limit_order:y.bcs.bool(),client_order_id:y.bcs.u64(),order_type:y.bcs.option(y.bcs.u8()),self_matching_option:y.bcs.u8(),price:y.bcs.option(y.bcs.u64()),quantity:y.bcs.u64(),is_bid:y.bcs.bool(),pay_with_deep:y.bcs.bool(),expire_timestamp:y.bcs.option(y.bcs.u64())}),o=y.bcs.struct("ConditionalOrder",{conditional_order_id:y.bcs.u64(),condition:s,pending_order:i});return n.results.map(a=>{if(!a?.returnValues?.[0]?.[0])return null;try{let u=new Uint8Array(a.returnValues[0][0]);if(u.length===0)return null;let p;if(u[0]===0)return null;u[0]===1?p=u.subarray(1):p=u;let d=o.parse(p);return this.normalizeConditionalOrder(d)}catch{return null}})}normalizeConditionalOrder(e){let t=r=>typeof r=="bigint"?String(r):r;return{conditional_order_id:t(e.conditional_order_id),condition:{trigger_below_price:e.condition.trigger_below_price,trigger_price:t(e.condition.trigger_price)},pending_order:{is_limit_order:e.pending_order.is_limit_order,client_order_id:t(e.pending_order.client_order_id),order_type:e.pending_order.order_type,self_matching_option:e.pending_order.self_matching_option,price:e.pending_order.price,quantity:t(e.pending_order.quantity),is_bid:e.pending_order.is_bid,pay_with_deep:e.pending_order.pay_with_deep,expire_timestamp:e.pending_order.expire_timestamp}}}};var Ye=require("@mysten/sui/client"),re=class extends Ye.SuiClient{async queryEventsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],s=!0,i=r==="all",o=i?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:i?null:r.limit});a.data?(n=[...n,...a.data],s=a.hasNextPage,o=a.nextCursor):s=!1}while(i&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let s=0;s<Math.ceil(e.length/r);s++){let i=await this.multiGetObjects({ids:e.slice(s*r,r*(s+1)),options:t});n=[...n,...i]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};var ve=Pe(require("decimal.js"));ve.default.config({precision:64,rounding:ve.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var R=1000000000n,Xe=365n*24n*60n*60n*1000n;function et(c,e){return e===0n?0n:c*R/e}function tt(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(c<n)return t+c*r/R;{let i=c-n,o=n*r/R,a=i*s/R;return t+o+a}}function Me(c,e){let t=c*e,r=t/R;return t%R>0n?r+1n:r}function rt(c,e,t,r){let n=e.borrow_shares===0n?R:e.total_borrow*R/e.borrow_shares,s=Me(c,n),i=et(e.total_borrow,e.total_supply),o=tt(i,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/R*a/Xe,p=e.borrow_shares===0n?0n:Me(u,c*R/e.borrow_shares),d=s+p;return{confirmedDebt:s,estimatedInterest:p,totalDebt:d,annualInterestRate:o}}function er(c,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=rt(c,e,t,s);return i}var ne=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new re({url:e.fullRpcUrl}),this._deepbookUtils=new ee(this),this._marginUtils=new te(this),this._pythPrice=new Z(this),this._graphqlClient=new nt.SuiGraphQLClient({url:e.graphqlUrl}),ae(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],s=null,i=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(i,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:s}):this.fullClient.getAllCoins({owner:e,cursor:s}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:$(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),s=a.nextCursor,!a.hasNextPage)break}return this.updateCache(i,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var tr="0x0000000000000000000000000000000000000000000000000000000000000006",rr="pool_script",nr="pool_script_v2",sr="router",ir="router_with_partner",or="fetcher_script",ar="expect_swap",cr="utils",ur="0x1::coin::CoinInfo",dr="0x1::coin::CoinStore",lr="custodian_v2",pr="clob_v2",gr="endpoints_v2",mr=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var st=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(st||{}),it=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(it||{});var _r=ne;0&&(module.exports={CLOCK_ADDRESS,CachedContent,CetusClmmSDK,ClmmExpectSwapModule,ClmmFetcherModule,ClmmIntegratePoolModule,ClmmIntegratePoolV2Module,ClmmIntegrateRouterModule,ClmmIntegrateRouterWithPartnerModule,ClmmIntegrateUtilsModule,CoinAssist,CoinInfoAddress,CoinStoreAddress,DEEP_SCALAR,DEFAULT_GAS_BUDGET_FOR_MERGE,DEFAULT_GAS_BUDGET_FOR_SPLIT,DEFAULT_GAS_BUDGET_FOR_STAKE,DEFAULT_GAS_BUDGET_FOR_TRANSFER,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,DEFAULT_NFT_TRANSFER_GAS_FEE,DeepbookClobV2Moudle,DeepbookCustodianV2Moudle,DeepbookEndpointsV2Moudle,DeepbookUtilsModule,FLOAT_SCALAR,FLOAT_SCALING,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,MarginUtilsModule,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,SelfMatchingOption,TransactionUtil,YEAR_MS,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime1min,cacheTime24h,cacheTime5min,calc100PercentRepay,calcDebtDetail,calcInterestRate,calcUtilizationRate,calculateRiskRatio,checkAddress,composeType,d,decimalsMultiplier,extractAddressFromType,extractStructTagFromType,fixCoinType,fixDown,fixSuiObjectId,fromDecimalsAmount,getDefaultSuiInputType,getFutureTime,getMoveObject,getMoveObjectType,getMovePackageContent,getObjectDeletedResponse,getObjectDisplay,getObjectFields,getObjectId,getObjectNotExistsResponse,getObjectOwner,getObjectPreviousTransactionDigest,getObjectReference,getObjectType,getObjectVersion,getSuiObjectData,hasPublicTransfer,hexToNumber,hexToString,isSortedSymbols,isSuiObjectResponse,maxDecimal,mulRoundUp,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,sleepTime,toBuffer,toDecimalsAmount,utf8to16,wrapDeepBookMarginPoolInfo,wrapDeepBookPoolInfo});
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ve=Object.defineProperty;var Ne=(c,e,t)=>e in c?Ve(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var pe=(c,e,t)=>(Ne(c,typeof e!="symbol"?e+"":e,t),t);import{SuiGraphQLClient as kt}from"@mysten/sui/graphql";import{DeepBookClient as ot}from"@mysten/deepbook-v3";import{bcs as f}from"@mysten/sui/bcs";import{Transaction as j,coinWithBalance as Pe}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as P,normalizeStructTag as U,normalizeSuiObjectId as at}from"@mysten/sui/utils";import{Base64 as ct}from"js-base64";import{coinWithBalance as fe}from"@mysten/sui/transactions";import{SUI_TYPE_ARG as Qe,normalizeStructTag as ze,normalizeSuiObjectId as se}from"@mysten/sui/utils";var xe=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function me(c){return c.startsWith("0x")?c:`0x${c}`}function ne(c){return c.startsWith("0x")?`${c.slice(2)}`:c}function Le(c,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${c.slice(0,r+2)} ... ${c.slice(-n)}`}function At(c,e=4,t=4){return Le(me(c),e,t)}function Ot(c,e={leadingZero:!0}){if(typeof c!="string")return!1;let t=c;if(e.leadingZero){if(!c.startsWith("0x"))return!1;t=t.substring(2)}return xe.test(t)}function Ge(c){if(!Buffer.isBuffer(c))if(Array.isArray(c))c=Buffer.from(c);else if(typeof c=="string")exports.isHexString(c)?c=Buffer.from(exports.padToEven(exports.stripHexPrefix(c)),"hex"):c=Buffer.from(c);else if(typeof c=="number")c=exports.intToBuffer(c);else if(c==null)c=Buffer.allocUnsafe(0);else if(c.toArray)c=Buffer.from(c.toArray());else throw new Error("invalid type");return c}function St(c){return me(Ge(c).toString("hex"))}function jt(c){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<c.length;n++)t.setUint8(n,c.charCodeAt(n));return t.getUint32(0,!0)}function Ke(c){let e,t,r,n,s;e="";let i=c.length;for(t=0;t<i;)switch(r=c.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=c.charAt(t-1);break;case 12:case 13:n=c.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=c.charCodeAt(t++),s=c.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function Bt(c){let e="",t=ne(c),r=t.length/2;for(let n=0;n<r;n++)e+=String.fromCharCode(Number.parseInt(t.substr(n*2,2),16));return Ke(e)}var He=0,he=1,We=2;function be(c,e){return c===e?He:c<e?he:We}function Je(c,e){let t=0,r=c.length<=e.length?c.length:e.length,n=be(c.length,e.length);for(;t<r;){let s=be(c.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function Pt(c,e){return Je(c,e)===he}function _e(c,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[c,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function It(c){return c.split("::")[0]}function R(c){try{let e=c.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let a={...R(e),type_arguments:r.map(u=>R(u).source_address)};return a.type_arguments=a.type_arguments.map(u=>E.isSuiCoin(u)?u:R(u).source_address),a.source_address=_e(a.full_address,a.type_arguments),a}let n=e.split("::"),i={full_address:e,address:e===ae||e===ye?"0x2":se(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return i.full_address=`${i.address}::${i.module}::${i.name}`,i.source_address=_e(i.full_address,i.type_arguments),i}catch{return{full_address:c,address:"",module:"",name:"",type_arguments:[],source_address:c}}}function ie(c){return R(c).source_address}function Ze(c){return c.toLowerCase().startsWith("0x")?se(c):c}var Dt=(c,e=!0)=>{let t=c.split("::"),r=t.shift(),n=se(r);return e&&(n=ne(n)),`${n}::${t.join("::")}`};function oe(c){for(let e in c){let t=typeof c[e];if(t==="object")oe(c[e]);else if(t==="string"){let r=c[e];c[e]=Ze(r)}}}var Ut=ze(Qe);var Ye="0x2::coin::Coin",Xe=/^0x2::coin::Coin<(.+)>$/,Vt=1e3,Nt=500,xt=100,Lt=100,Gt=1e3,ae="0x2::sui::SUI",ye="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Kt="SUI",Qt=450,zt="0x0000000000000000000000000000000000000005",E=class{static getCoinTypeArg(e){let t=e.type.match(Xe);return t?t[1]:null}static isSUI(e){let t=E.getCoinTypeArg(e);return t?E.getCoinSymbol(t)==="SUI":!1}static getCoinSymbol(e){return e.substring(e.lastIndexOf(":")+1)}static getBalance(e){return BigInt(e.fields.balance)}static totalBalance(e,t){let r=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${Ye}<${e}>`}static getCoinAssets(e,t){let r=[];return t.forEach(n=>{ie(n.coinAddress)===ie(e)&&r.push(n)}),r}static isSuiCoin(e){return R(e).full_address===ae}static selectCoinObjectIdGreaterThanOrEqual(e,t,r=[]){let n=E.selectCoinAssetGreaterThanOrEqual(e,t,r),s=n.selectedCoins.map(a=>a.coinObjectId),i=n.remainingCoins,o=n.selectedCoins.map(a=>a.balance.toString());return{objectArray:s,remainCoins:i,amountArray:o}}static selectCoinAssetGreaterThanOrEqual(e,t,r=[]){let n=E.sortByBalance(e.filter(u=>!r.includes(u.coinObjectId))),s=E.calculateTotalBalance(n);if(s<t)return{selectedCoins:[],remainingCoins:n};if(s===t)return{selectedCoins:n,remainingCoins:[]};let i=BigInt(0),o=[],a=[...n];for(;i<s;){let u=t-i,g=a.findIndex(p=>p.balance>=u);if(g!==-1){o.push(a[g]),a.splice(g,1);break}let d=a.pop();d.balance>0&&(o.push(d),i+=d.balance)}return{selectedCoins:E.sortByBalance(o),remainingCoins:E.sortByBalance(a)}}static sortByBalance(e){return e.sort((t,r)=>t.balance<r.balance?-1:t.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,r)=>t.balance>r.balance?-1:t.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,r)=>t+r.balance,BigInt(0))}static buildCoinWithBalance(e,t,r){return e===BigInt(0)&&E.isSuiCoin(t)?r.add(fe({balance:e,useGasCoin:!1})):r.add(fe({balance:e,type:t}))}};var ke=6e4,we=3e5,x=864e5;function Q(c){return Date.parse(new Date().toString())+c}var K=class{overdueTime;value;constructor(e,t=0){this.overdueTime=t,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};import{fromB64 as Ae,fromHEX as Oe}from"@mysten/bcs";import{Ed25519Keypair as Ce}from"@mysten/sui/keypairs/ed25519";import{Secp256k1Keypair as Te}from"@mysten/sui/keypairs/secp256k1";import Z from"decimal.js";function l(c){return Z.isDecimal(c)?c:new Z(c===void 0?0:c)}function ce(c){return l(10).pow(l(c).abs())}var L=(c,e)=>{try{return l(c).toDP(e,Z.ROUND_DOWN).toString()}catch{return c}},ue=(c,e)=>Z.max(l(c),l(e));function W(c,e){let t=ce(l(e));return Number(l(c).mul(t))}function rr(c,e=32){return BigInt.asUintN(e,BigInt(c)).toString()}function nr(c,e=32){return Number(BigInt.asIntN(e,BigInt(c)))}function G(c,e){let t=ce(l(e));return Number(l(c).div(t))}function sr(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return Ce.fromSecretKey(r)}let t=e==="hex"?Oe(c):Ae(c);return Ce.fromSecretKey(t)}function ir(c,e="hex"){if(c instanceof Uint8Array){let r=Buffer.from(c);return Te.fromSecretKey(r)}let t=e==="hex"?Oe(c):Ae(c);return Te.fromSecretKey(t)}var Se=async c=>new Promise(e=>{setTimeout(()=>{e(1)},c)});var je={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Be={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function Ee(...c){let e="DeepbookV3_Utils_Sdk###"}function z(c){return c.data}function et(c){if(c.error&&"object_id"in c.error&&"version"in c.error&&"digest"in c.error){let{error:e}=c;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function tt(c){if(c.error&&"object_id"in c.error&&!("version"in c.error)&&!("digest"in c.error))return c.error.object_id}function ve(c){if("reference"in c)return c.reference;let e=z(c);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:et(c)}function Me(c){return"objectId"in c?c.objectId:ve(c)?.objectId??tt(c)}function ur(c){return"version"in c?c.version:ve(c)?.version}function rt(c){return c.data!==void 0}function nt(c){return c.content!==void 0}function dr(c){let e=z(c);if(e?.content?.dataType==="package")return e.content.disassembled}function de(c){let e="data"in c?z(c):c;if(!(!e||!nt(e)||e.content.dataType!=="moveObject"))return e.content}function st(c){return de(c)?.type}function lr(c){let e=rt(c)?c.data:c;return!e?.type&&"data"in c?e?.content?.dataType==="package"?"package":st(c):e?.type}function gr(c){return z(c)?.previousTransaction}function pr(c){return z(c)?.owner}function mr(c){let e=z(c)?.display;return e||{data:null,error:null}}function qe(c){let e=de(c)?.fields;if(e)return"fields"in e?e.fields:e}function br(c){return de(c)?.hasPublicTransfer??!1}import{Transaction as it}from"@mysten/sui/transactions";async function fr(c,e=!0){c.blockData.transactions.forEach((t,r)=>{})}var V=class{static async adjustTransactionForGas(e,t,r,n){n.setSender(e.senderAddress);let s=E.selectCoinAssetGreaterThanOrEqual(t,r).selectedCoins;if(s.length===0)throw new Error("Insufficient balance");let i=E.calculateTotalBalance(t);if(i-r>1e9)return{fixAmount:r};let o=await e.fullClient.calculationTxGas(n);if(E.selectCoinAssetGreaterThanOrEqual(t,BigInt(o),s.map(u=>u.coinObjectId)).selectedCoins.length===0){let u=BigInt(o)+BigInt(500);if(i-r<u){if(r-=u,r<0)throw new Error("gas Insufficient balance");let g=new it;return{fixAmount:r,newTx:g}}}return{fixAmount:r}}static buildCoinForAmount(e,t,r,n,s=!0,i=!1){let o=E.getCoinAssets(n,t);if(r===BigInt(0)&&o.length===0)return V.buildZeroValueCoin(t,e,n,s);let a=E.calculateTotalBalance(o);if(a<r)throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${r} `);return V.buildCoin(e,t,o,r,n,s,i)}static buildCoin(e,t,r,n,s,i=!0,o=!1){if(E.isSuiCoin(s)){if(i){let h=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[h]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&r.length>1){let h=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.object(h.objectArray[0]),remainCoins:h.remainCoins,tragetCoinAmount:h.amountArray[0],isMintZeroCoin:!1}}let y=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:y.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let a=E.selectCoinObjectIdGreaterThanOrEqual(r,n),u=a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),g=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:g.map(y=>e.object(y))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...p]=g,b=e.object(d),m=b,_=a.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),w;return p.length>0&&e.mergeCoins(b,p.map(y=>e.object(y))),o&&Number(u)>Number(n)&&(m=e.splitCoins(b,[e.pure.u64(n)]),_=n.toString(),w=b),{targetCoin:m,remainCoins:a.remainCoins,originalSplitedCoin:w,tragetCoinAmount:_,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,r,n=!0){let s=V.callMintZeroValueCoin(t,r),i;return n?i=t.makeMoveVec({elements:[s]}):i=s,{targetCoin:i,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,r,n,s=!0){let i=E.getCoinAssets(n,t);if(r.amountFirst===BigInt(0))return i.length>0?V.buildCoin(e,[...t],[...i],r.amountFirst,n,s):V.buildZeroValueCoin(t,e,n,s);let o=E.calculateTotalBalance(i);if(o>=r.amountFirst)return V.buildCoin(e,[...t],[...i],r.amountFirst,n,s);if(o<r.amountSecond)throw new Error(`The amount(${o}) is Insufficient balance for ${n} , expect ${r.amountSecond} `);return V.buildCoin(e,[...t],[...i],r.amountSecond,n,s)}static buildCoinTypePair(e,t){let r=[];if(e.length===2){let n=[];n.push(e[0],e[1]),r.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),r.push(n);for(let s=1;s<e.length-1;s+=1){if(t[s-1]===0)continue;let i=[];i.push(e[0],e[s],e[e.length-1]),r.push(i)}}return r}},N=V;pe(N,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));var le=1e6,$=1e9,ut={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},dt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},X=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?dt:ut}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new j,t=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),t],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[t],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:t,amountToDeposit:r}){let n=new j;n.setSenderIfNotSet(e);let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),i=Pe({type:t.coinType,balance:BigInt(r)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[s,i],typeArguments:[t.coinType]}),n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[s],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:r,amountToDeposit:n,tx:s}){let i=s||new j;if(t){i.setSenderIfNotSet(e);let o=Pe({type:r.coinType,balance:BigInt(n)});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i.object(t),o],typeArguments:[r.coinType]}),i}return null}withdrawFromManager({account:e,balanceManager:t,coin:r,amountToWithdraw:n,returnAssets:s,txb:i}){let o=i||new j,a=o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[o.object(t),o.pure.u64(n)],typeArguments:[r.coinType]});return s?a:(o.transferObjects([a],e),o)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:r=new j}){for(let n in t)t[n].forEach(i=>{let o=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(n),r.pure.u64(i.amount)],typeArguments:[i.coinType]});r.transferObjects([o],e)});return r}async getBalanceManager(e,t=!0){let r=`getBalanceManager_${e}`,n=this.getCache(r,t);if(!t&&n!==void 0)return n;try{let s=new j;s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s.pure.address(e)],typeArguments:[]});let a=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}))?.events?.filter(g=>g.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],u=[];return a.forEach(g=>{u.push({balanceManager:g,cetusBalanceManager:""})}),this.updateCache(r,u,864e5),u||[]}catch(s){throw s instanceof Error?s:new Error(String(s))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},r=new j){let n=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(t)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(e.address),r.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:t,coins:r}){try{let n=new j;r.forEach(o=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[o.coinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),i={};return s.results?.forEach((o,a)=>{let u=r[a],g=o.returnValues[0][0],d=f.U64.parse(new Uint8Array(g)),p=l(d),b=p.eq(0)?"0":p.div(Math.pow(10,u.decimals)).toString();i[u.coinType]={adjusted_balance:b,balance:p.toString()}}),i}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let r=new j,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(o=>{t.forEach(a=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(o.balanceManager)],typeArguments:[a.coinType]})})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i={};return n.forEach((o,a)=>{let u={},g=a*t.length;t.forEach((d,p)=>{let b=g+p,m=s.results?.[b];if(m){let _=m.returnValues[0][0],w=f.U64.parse(new Uint8Array(_)),y=l(w),C=y.eq(0)?"0":y.div(Math.pow(10,d.decimals)).toString();u[d.coinType]={adjusted_balance:C,balance:y.toString()}}}),i[o.balanceManager]=u}),i}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let t=new j;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let n=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],s=Number(f.U64.parse(new Uint8Array(n))),i=Math.pow(10,e.baseCoin.decimals).toString(),o=Math.pow(10,e.quoteCoin.decimals).toString();return l(s).mul(i).div(o).div($).toString()}catch(t){return Ee("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",r=this.getCache(t,e);if(r!==void 0)return r;let n=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),s=/<([^>]+)>/,i=[];return n?.data?.forEach(o=>{let a=o?.parsedJson,u=o.type.match(s);if(u){let d=u[1].split(", ");i.push({...a,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,i,864e5),i}async getQuoteQuantityOut(e,t,r){let n=new j;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),baseQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getBaseQuantityOut(e,t,r){let n=new j;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(f.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{quoteQuantityDisplay:l(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),quoteQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getQuantityOut(e,t,r,n){let s=new j;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.pure.u64(r),s.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=Number(f.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),a=Number(f.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]))),u=Number(f.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:l(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(u).div(le).toString(),baseQuantity:t,quoteQuantity:r,baseOut:o,quoteOut:a,deepRequired:u}}async getReferencePool(e){let t=await this.getPools(),r=e.baseCoin.coinType,n=e.quoteCoin.coinType,s=this._deep.coinType;for(let i=0;i<t.length;i++){let o=t[i];if(o.address===e.address)continue;let a=[o.baseCoinType,o.quoteCoinType];if(o.baseCoinType===s&&(a.includes(r)||a.includes(n)))return o}return null}async updateDeepPrice(e,t){let r=await this.getReferencePool(e);return r?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(r.pool_id),t.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,r,n,s,i,o){let a=this.deepCoin;try{let{taker_fee:u,maker_fee:g}=e,d=l(u).div($).toString(),p=l(g).div($).toString(),b=await this.getMarketPrice(e),m=i?r:b!=="0"?b:o;if(m==="0")throw new Error("Cannot get market price");let _=Math.pow(10,e.baseCoin.decimals).toString(),w=Math.pow(10,e.quoteCoin.decimals).toString(),y=l(m).div(_).mul(w).mul($).toString();if(n){let O=await this.getMarketPrice(e),A=l(i?r:O!=="0"?O:o).div(_).mul(w).mul($).toString(),B=await this.getOrderDeepPrice(e);if(!B)throw new Error("Cannot get deep price");let M=ue(A,r),I=l(t).mul(l(d)).mul(l(B.deep_per_asset)).div(l($)),q=l(t).mul(l(p)).mul(l(B.deep_per_asset)).div(l($));B.asset_is_base||(I=I.mul(M).div(l($)),q=q.mul(M).div(l($)));let D=I.ceil().toString(),J=q.ceil().toString();return{takerFee:D,makerFee:J,takerFeeDisplay:G(D,a.decimals).toString(),makerFeeDisplay:G(J,a.decimals).toString(),feeType:a.coinType}}if(s){let O=ue(y,i?r:b),S=l(t).mul(O).mul(l(d).mul(1.25)).div(l($)).ceil().toFixed(0),A=l(t).mul(O).mul(l(p).mul(1.25)).div(l($)).ceil().toFixed(0);return{takerFee:S,makerFee:A,takerFeeDisplay:G(S,e.quoteCoin.decimals).toString(),makerFeeDisplay:G(A,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=l(t).mul(l(d).mul(1.25)).ceil().toFixed(0),h=l(t).mul(l(p).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:h,takerFeeDisplay:G(C,e.baseCoin.decimals).toString(),makerFeeDisplay:G(h,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderDeepPrice(e,t=!0){let r=`getOrderDeepPrice_${e.address}}`,n=this.getCache(r);if(n!==void 0)return n;try{let s=new j,i=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,s)&&(i=!0),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[s.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),a=i?o.results[1]?.returnValues[0]?.[0]:o.results[0]?.returnValues[0]?.[0],u=this.parseOrderDeepPrice(new Uint8Array(a));return this.updateCache(r,u,6e4),u}catch{return await Se(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),r=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:n}}getCoinAssets(e,t,r,n){return N.buildCoinForAmount(n,r,BigInt(l(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,r,n,s,i,o){let a=this.deepCoin;if(!o)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let u=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&u.push(a);let g=await this.getManagerBalance({account:s,balanceManager:o,coins:u}),d=g?.[t]?.balance||"0",p=g?.[r]?.balance||"0",b=i&&g?.[a.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:p,feeManaerBalance:b}}catch(u){throw u instanceof Error?u:new Error(String(u))}}getFeeAsset(e,t,r,n,s,i,o,a,u,g){let d=l(e).gt(0)&&u,p="0";if(!d)return{feeAsset:this.getEmptyCoin(g,t),haveDepositFee:"0"};if(i||o){let b=l(s).sub(i?n:r);p=b.lte(0)?e:b.sub(e).lt(0)?b.sub(e).toString():"0"}else p=l(s).sub(e).lt("0")?l(s).sub(e).abs().toString():"0";return{feeAsset:l(p).gt("0")?this.getCoinAssets(t,p,a,g):this.getEmptyCoin(g,t),haveDepositFee:p}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,u){try{let g=this.deepCoin,d=U(e.baseCoin.coinType),p=U(e.quoteCoin.coinType),b=d===g.coinType,m=p===g.coinType,_=!b&&!m,{baseManagerBlance:w,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,p,_,i,o,a);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:w,quoteManagerBlance:y});let h,O,S=!1,A=await this._sdk.getOwnerCoinAssets(i);if(s){o||(r=l(r).add(l(n)).toString());let M=l(y).sub(r).toString();l(M).lt(0)?(S=!0,O=this.getCoinAssets(p,M,A,u)):O=this.getEmptyCoin(u,p),h=this.getEmptyCoin(u,d)}else{o||(t=l(t).add(l(n)).toString());let M=l(w).sub(t).toString();l(M).lt(0)?(S=!0,h=this.getCoinAssets(d,M,A,u)):h=this.getEmptyCoin(u,d),O=this.getEmptyCoin(u,p)}let B=this.getFeeAsset(n,g.coinType,t,r,C,m,b,A,o,u);return{baseAsset:h,quoteAsset:O,feeAsset:B,haveDeposit:S}}catch(g){throw g instanceof Error?g:new Error(String(g))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,u,g){try{let d=this.deepCoin,p=U(e.baseCoin.coinType),b=U(e.quoteCoin.coinType),m=p===d.coinType,_=b===d.coinType,w=!m&&!_,y=await this.getTransactionRelatedBalance(e,p,b,w,i,o,a),{feeManaerBalance:C}=y,h=l(y.baseManagerBlance).add(l(g?.base||"0")).toString(),O=l(y.quoteManagerBlance).add(l(g?.quote||"0")).toString(),S=await this._sdk.getOwnerCoinAssets(i),A;o&&l(C).lt(n)?A=this.getCoinAssets(d.coinType,l(n).sub(C).toString(),S,u):A=this.getEmptyCoin(u,d.coinType);let B,M;if(s){o||(r=l(r).add(l(n)).toString());let I=l(O).sub(r).toString();if(l(I).lt(0)){let q;l(O).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:O,returnAssets:!0,txb:u}));let D=this.getCoinAssets(b,I,S,u);q&&u.mergeCoins(D,[q]),M=D}else M=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:u});B=this.getEmptyCoin(u,p)}else{o||(t=l(t).add(l(n)).toString());let I=l(h).sub(t).toString();if(l(I).lt(0)){let q;l(h).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:u}));let D=this.getCoinAssets(p,I,S,u);q&&u.mergeCoins(D,[q]),B=D}else B=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:u});M=this.getEmptyCoin(u,b)}return{baseAsset:B,quoteAsset:M,feeAsset:A}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:r,orderType:n,isBid:s,maxFee:i,account:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8}){try{let g=this.deepCoin,d=e.address,p=e.baseCoin.decimals,b=e.quoteCoin.decimals,m=e.baseCoin.coinType,_=e.quoteCoin.coinType,w=l(t).mul(10**(b-p+9)).toString(),y=U(m),C=U(_),h=new j,O,S,A=await this._sdk.getOwnerCoinAssets(o);if(s){let q=l(t).mul(l(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(q=l(q).add(l(i)).toString()),S=N.buildCoinForAmount(h,A,BigInt(q),C,!1,!0)?.targetCoin}else{let q=r;a||(q=l(r).abs().add(l(i)).toString()),O=N.buildCoinForAmount(h,A,BigInt(l(q).abs().toString()),y,!1,!0)?.targetCoin}let B=a?l(i).gt(0)?N.buildCoinForAmount(h,A,BigInt(l(i).abs().ceil().toString()),g.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,g.coinType):this.getEmptyCoin(h,g.coinType),M=h.moveCall({typeArguments:[s?m:_],target:"0x2::coin::zero",arguments:[]}),I=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(d),s?M:O,s?S:M,B,h.pure.u8(n),h.pure.u8(0),h.pure.u64(w),h.pure.u64(r),h.pure.bool(s),h.pure.bool(!1),h.pure.u64(u),h.object(P)];return h.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:I}),h}catch(g){throw g instanceof Error?g:new Error(String(g))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:r,maxFee:n,account:s,payWithDeep:i,slippage:o=.01}){try{let a=e.address,u=e.baseCoin.coinType,g=e.quoteCoin.coinType,d=U(u),p=U(g),b=new j,m,_,w=t,y,C=await this.getOrderBook(e,"all",6);if(r){let A=C?.ask?.[0]?.price||"0",B=l(A).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=l(B).plus(l(B).mul(o)).ceil().toString()}else{let A=await C?.bid?.[0]?.price||"0",B=l(A).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=l(B).minus(l(B).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(y=l(y).add(l(n)).toString()),_=this.getCoinAssets(p,y,h,b),m=this.getEmptyCoin(b,d)):(i||(w=l(w).add(l(n)).toString()),_=this.getEmptyCoin(b,p),m=this.getCoinAssets(d,w,h,b));let O=i?l(n).gt(0)?N.buildCoinForAmount(b,h,BigInt(l(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(b,this.deepCoin.coinType):this.getEmptyCoin(b,this.deepCoin.coinType),S=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(a),m,_,O,b.pure.u8(0),b.pure.u64(t),b.pure.bool(r),b.pure.bool(i),b.pure.u64(y),b.object(P)];return b.moveCall({typeArguments:[d,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:S}),b}catch(a){throw a instanceof Error?a:new Error(String(a))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:r,quantity:n,isBid:s,orderType:i,maxFee:o,account:a,payWithDeep:u,expirationTimestamp:g=Date.now()+31536e8}){try{let d=this.deepCoin,p=l(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),b=t.baseCoin.coinType,m=t.quoteCoin.coinType,_=new j,w=s?l(r).mul(l(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=s?"0":n,{baseAsset:C,quoteAsset:h,feeAsset:O,haveDeposit:S}=await this.getTransactionRelatedAssets(t,y,w,o,s,a,u,e,_);if(S){let M=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(t.address),_.object(e),C,h,O.feeAsset,_.pure.u8(i),_.pure.u8(0),_.pure.u64(p),_.pure.u64(n),_.pure.bool(s),_.pure.bool(u),_.pure.u64(g),_.object(P)];return _.moveCall({typeArguments:[b,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:M}),_}let A=new j;l(O.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:d,amountToDeposit:O.haveDepositFee,tx:A});let B=[A.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),A.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),A.object(t.address),A.object(e),A.pure.u8(i),A.pure.u8(0),A.pure.u64(p),A.pure.u64(n),A.pure.bool(s),A.pure.bool(u),A.pure.u64(g),A.object(P)];return A.moveCall({typeArguments:[b,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:B}),A}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:r,newOrderQuantity:n}){let s=new j;return s.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(e),s.object(t.address),s.pure.u128(r),s.pure.u64(n),s.object(P)]}),s}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new j,s=await this.getMarketPrice(e),i=l(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(a),n.pure.u64(u),n.pure.bool(!1),n.object(P)],typeArguments:[t.coinType,r.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:n}),p=[],b=d.results[0].returnValues[0][0],m=f.vector(f.u64()).parse(new Uint8Array(b)),_=d.results[0].returnValues[1][0],w=f.vector(f.u64()).parse(new Uint8Array(_));return m.forEach((y,C)=>{let h=l(y).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),O=l(w[C]).div(Math.pow(10,t.decimals)).toString();p.push({price:h,quantity:O})}),p?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new j,s=await this.getMarketPrice(e),i=l(s).gt(0)?l(s).div(3).toNumber():Math.pow(10,-6),o=l(s).gt(0)?s:Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),u=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(L(a,0)),n.pure.u64(L(u,0)),n.pure.bool(!0),n.object(P)],typeArguments:[t.coinType,r.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:n}),p=[],b=d.results[0].returnValues[0][0],m=f.vector(f.u64()).parse(new Uint8Array(b)),_=d.results[0].returnValues[1][0],w=f.vector(f.u64()).parse(new Uint8Array(_));return m.forEach((y,C)=>{let h=l(y).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),O=l(w[C]).div(Math.pow(10,t.decimals)).toString();p.push({price:h,quantity:O})}),p?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:r,quoteCoin:n}=e,s=new j,i=await this.getMarketPrice(e),o,a;t?(o=l(i).gt(0)?l(i).div(3).toNumber():Math.pow(10,-6),a=l(i).gt(0)?i:Math.pow(10,6)):(o=l(i).gt(0)?i:Math.pow(10,-1),a=l(i).gt(0)?l(i).mul(3).toNumber():Math.pow(10,6));let u=l(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),g=l(a).mul(Math.pow(10,9+n.decimals-r.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(L(u,0)),s.pure.u64(L(g,0)),s.pure.bool(t),s.object(P)],typeArguments:[r.coinType,n.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,p=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:s}),b=[],m=p.results[0].returnValues[0][0],_=f.vector(f.u64()).parse(new Uint8Array(m)),w=p.results[0].returnValues[1][0],y=f.vector(f.u64()).parse(new Uint8Array(w));return _.forEach((C,h)=>{let O=l(C).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),S=l(y[h]).div(Math.pow(10,r.decimals)).toString();b.push({price:O,quantity:S})}),b?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:r,quoteQuantity:n,isBid:s,maxFee:i,account:o,payWithDeep:a,slippage:u=.01,settled_balances:g={base:"0",quote:"0"}}){try{let d=U(t.baseCoin.coinType),p=U(t.quoteCoin.coinType),b=new j;g&&(l(g.base).gt(0)||l(g.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},b);let{baseAsset:m,quoteAsset:_,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,b,g),y=await this.getOrderBook(t,"all",6);if(s){let O=y?.ask?.[0]?.price||"0",S=l(O).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(S).plus(l(S).mul(u)).ceil().toString()}else{let O=await y?.bid?.[0]?.price||"0",S=l(O).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(S).minus(l(S).mul(u)).floor().toString()}let C=n,h=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(t.address),b.object(e),m,_,w,b.pure.u8(0),b.pure.u64(r),b.pure.bool(s),b.pure.bool(a),b.pure.u64(C),b.object(P)];return b.setSenderIfNotSet(o),b.moveCall({typeArguments:[d,p],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),b}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let r=new j;e.forEach(u=>{let g=u?.pool,d=u?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(g.pool_id),r.pure.u128(BigInt(d))],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:r}),s=f.struct("ID",{bytes:f.Address}),i=f.struct("OrderDeepPrice",{asset_is_base:f.bool(),deep_per_asset:f.u64()}),o=f.struct("Order",{balance_manager_id:s,order_id:f.u128(),client_order_id:f.u64(),quantity:f.u64(),filled_quantity:f.u64(),fee_is_deep:f.bool(),order_deep_price:i,epoch:f.u64(),status:f.u8(),expire_timestamp:f.u64()}),a=[];return n?.results?.forEach(u=>{let g=u.returnValues[0][0],d=o.parse(new Uint8Array(g));a.push(d)}),a}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:r,orderId:n}}async getOpenOrder(e,t,r,n,s=!1,i=new j){let o;if(n)o=n;else{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[i.object(e.address),s?r:i.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:i})).results[s?1:0].returnValues[0][0];o=f.struct("VecSet",{constants:f.vector(f.U128)}).parse(new Uint8Array(p)).constants}if(o.length===0)return[];let a=o.map(d=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:d})),u=await this.getOrderInfoList(a,t)||[],g=[];return u.forEach(d=>{let p=this.decodeOrderId(BigInt(d.order_id));g.push({...d,price:p.price,isBid:p.isBid,pool:e})}),g}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new j;r.forEach(d=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(d.pool_id),n.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(d=>d.returnValues?.[0]?.[0])||[],o=f.struct("VecSet",{constants:f.vector(f.U128)}),a=[];i.forEach((d,p)=>{let b=o.parse(new Uint8Array(d)).constants;b.length>0&&b.forEach(m=>{a.push({pool:r[p],orderId:m})})});let u=await this.getOrderInfoList(a,e)||[],g=[];return a.forEach((d,p)=>{let b=this.decodeOrderId(BigInt(d.orderId)),m=u.find(_=>_.order_id===d.orderId)||{};g.push({...d,...m,price:b.price,isBid:b.isBid})}),g}catch{return[]}}cancelOrders(e,t,r=new j){return e.forEach(n=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(t),r.object(n.poolInfo.address),r.pure.u128(n.orderId),r.object(P)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(e,t,r,n,s,i){let o=this._sdk.fullClient,u=await new ot({client:o,address:s,env:"testnet",balanceManagers:{test1:{address:i,tradeCap:""}}}).getLevel2Range(e,t,r,n)}processOrderBookData(e,t,r,n){let s=e.returnValues[0][0],i=f.vector(f.u64()).parse(new Uint8Array(s)),o=e.returnValues[1][0],a=f.vector(f.u64()).parse(new Uint8Array(o)),u={};return i.forEach((d,p)=>{let b=l(d).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),m=l(a[p]).div(Math.pow(10,t.decimals)).toString();u[b]?u[b]={price:b,quantity:l(u[b].quantity).add(m).toString()}:u[b]={price:b,quantity:m}}),Object.values(u)}getLevel2RangeTx(e,t,r,n,s=new j){let{baseCoin:i,quoteCoin:o}=e,a=L(l(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),u=L(l(n).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0);return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(a),s.pure.u64(u),s.pure.bool(t),s.object(P)],typeArguments:[i.coinType,o.coinType]}),s}async fetchOrderBook(e,t,r,n,s,i){let o=new j,{baseCoin:a,quoteCoin:u}=e;try{if(t==="bid"||t==="all"){let m=n,_=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,m,_,o)}if(t==="ask"||t==="all"){let m=r==="0"?n:r,_=s;o=this.getLevel2RangeTx(e,!1,m,_,o)}let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:o}),p=[];(t==="bid"||t==="all")&&(p=d.results?.[0]?this.processOrderBookData(d.results[0],a,u,i):[]);let b=[];if(t==="ask"||t==="all"){let m=t==="ask"?0:1;b=d.results?.[m]?this.processOrderBookData(d.results[m],a,u,i):[]}return{bid:p.sort((m,_)=>_.price-m.price),ask:b.sort((m,_)=>m.price-_.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,p=[],b=[];try{let m=this.getLevel2RangeTx(e,!0,n,r),_=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});p=_.results?.[0]?this.processOrderBookData(_.results[0],a,u,i):[]}catch{p=[]}try{let m=this.getLevel2RangeTx(e,!1,n,r),_=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});b=_.results?.[0]?this.processOrderBookData(_.results[0],a,u,i):[]}catch{b=[]}return{bid:p,ask:b}}}async getOrderBook(e,t,r){let n={bid:[],ask:[]};try{let s=await this.getMarketPrice(e),i=t,o=Math.pow(10,-r),a=Math.pow(10,r),u=await this.fetchOrderBook(e,i,s,o,a,r);return{bid:u?.bid,ask:u?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let r=new j,n=await this.getMarketPrice(e),{baseCoin:s,quoteCoin:i}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),p=n,b=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(p).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(b),r.pure.u64(m),r.pure.bool(!0),r.object(P)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let d=n,p=Math.pow(10,6),b=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(p).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(b),r.pure.u64(m),r.pure.bool(!1),r.object(P)],typeArguments:[s.coinType,i.coinType]})}let o=this._sdk.sdkOptions.simulationAccount.address,a=await this._sdk.fullClient.devInspectTransactionBlock({sender:o,transactionBlock:r}),u=[];if(t==="bid"||t==="all"){let d=a.results[0]?.returnValues[0]?.[0],p=f.vector(f.u64()).parse(new Uint8Array(d)),b=a.results[0]?.returnValues[1]?.[0],m=f.vector(f.u64()).parse(new Uint8Array(b));p.forEach((_,w)=>{let y=l(_).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),C=l(m[w]).div(Math.pow(10,s.decimals)).toString();u.push({price:y,quantity:C})})}let g=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,p=a.results[d]?.returnValues[0]?.[0],b=f.vector(f.u64()).parse(new Uint8Array(p)),m=a.results[d]?.returnValues[1]?.[0],_=f.vector(f.u64()).parse(new Uint8Array(m));b.forEach((w,y)=>{let C=l(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=l(_[y]).div(Math.pow(10,s.decimals)).toString();g.push({price:C,quantity:h})})}return{bid:u,ask:g}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,s)=>[U(n.coinType),n]))}async getAccount(e,t,r=new j){for(let o=0;o<t.length;o++){let a=t[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof e=="string"?r.object(e):e],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.senderAddress,transactionBlock:r}),s;if(n?.events.length===0)return null;let i=[];return n?.events?.forEach((o,a)=>{s=o?.parsedJson;let u=s.account.open_orders.contents,g=s.account.owed_balances,d=s.account.settled_balances,p=s.account.unclaimed_rebates,b=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:u,owed_balances:g,settled_balances:d,unclaimed_rebates:p,taker_volume:b,poolInfo:t[a]})}),i}async getSuiTransactionResponse(e,t=!1){let r=`${e}_getSuiTransactionResponse`,n=this.getCache(r,t);if(n!==void 0)return n;let s;try{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,s,864e5),s}transformExtensions(e,t,r=!0){let n=[];for(let s of t){let{key:i}=s.fields,{value:o}=s.fields;if(i==="labels")try{o=JSON.parse(decodeURIComponent(ct.decode(o)))}catch{}r&&(e[i]=o),n.push({key:i,value:o})}delete e.extension_fields,r||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let r=this.sdk.sdkOptions.coinlist.handle,n=`${r}_getCoinConfigs`,s=this.getCache(n,e);if(s)return s;let o=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(g=>g.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),u=[];return a.forEach(g=>{let d=this.buildCoinConfig(g,t);this.updateCache(`${r}_${d.address}_getCoinConfig`,d,864e5),u.push({...d})}),this.updateCache(n,u,864e5),u}buildCoinConfig(e,t=!0){let r=qe(e);r=r.value.fields;let n={...r};return n.id=Me(e),n.address=R(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=at(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,r=3e5){let n=this._cache[e];n?(n.overdueTime=Q(r),n.value=t):n=new K(t,Q(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:r,baseCoinType:n,quoteCoinType:s}){let i=new j,o=E.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",i);i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[n,s],arguments:[i.object(this.sdk.sdkOptions.deepbook.registry_id),i.pure.u64(e),i.pure.u64(t),i.pure.u64(r),o]});try{let a=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:i});if(a.effects.status.status==="success")return i;if(a.effects.status.status==="failure"&&a.effects.status.error&&a.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(a){throw a instanceof Error?a:new Error(String(a))}return i}};import{CoinAssist as Ue}from"@cetusprotocol/common-sdk";import{bcs as k}from"@mysten/sui/bcs";import{Transaction as T}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as v,normalizeSuiAddress as $e}from"@mysten/sui/utils";var Fr=({totalAssetsValue:c,totalDebtValue:e})=>l(e).eq(0)||l(c).eq(0)?"0":l(c).div(l(e)).toString(),Ie=c=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=c.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}=c.value.fields.risk_ratios.fields;return{id:c.id.id,name:c.name,base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s,liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:u}},De=(c,e)=>{let{deposit_coin_type:t}=e,r=c.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=c.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:u}=c.protocol_fees.fields,{total_supply:g,total_borrow:d}=c.state.fields,p=l(o).sub(g).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:g,total_borrow:d,available_supply:p,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:u}};import{SuiPriceServiceConnection as lt,SuiPythClient as gt}from"@pythnetwork/pyth-sui-js";var ge=10n;function pt(c,e){if(!ge)throw new Error("oraclePriceMultiplierDecimal is required");if(c===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(ge- -e);return c*t}return c/10n**(e+ge)}var H=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;_cache={};constructor(e){this._sdk=e,this.connection=new lt(this.sdk.sdkOptions.pythUrl),this.suiPythClient=new gt(this._sdk.fullClient,this._sdk.sdkOptions.margin_utils.pyth_state_id,this._sdk.sdkOptions.margin_utils.wormhole_state_id)}get sdk(){return this._sdk}async updatePythPriceIDs(e,t){let r=null,n=null;try{r=await this.connection.getPriceFeedsUpdateData(e)}catch(o){n=o}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${n?.message}`);let s=[];try{s=await this.suiPythClient.updatePriceFeeds(t,r,e)}catch(o){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${o}`)}let i=new Map;for(let o=0;o<e.length;o++)i.set(e[o],s[o]);return i}priceCheck(e,t=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let r={},n=[];if(t?e.forEach(o=>{let a=this._sdk.getCache(`getLatestPrice_${o.coinType}`);a&&this.priceCheck(a,60)?r[o.coinType]=a:n.push(o.coinType)}):n=e.map(o=>o.coinType),n.length===0)return r;let s=e.map(o=>o.feed);return(await this.connection.getLatestPriceUpdates(s))?.parsed?.forEach((o,a)=>{let u=o.price;if(u){let{price:g,expo:d}=u,p=l(g).mul(l(10).pow(l(d))).toString(),m={coin_type:e[a].coinType,price:p,oracle_price:0n,last_update_time:u.publish_time};m.oracle_price=pt(BigInt(g),BigInt(d)),r[n[a]]=m,this._sdk.updateCache(`getLatestPrice_${m.coin_type}`,m)}}),r}};var ee=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new H(e),this._deep=e.sdkOptions.network==="mainnet"?Be:je}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,t=new T){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:n}=e;try{let{margin_manager:s,initializer:i}=this.createMarginManager(e,t);return this.shareMarginManager({marginManager:s,initializer:i,baseCoin:r,quoteCoin:n},t),{tx:t,margin_manager:s,initializer:i}}catch(s){throw new Error(`Failed to create and share margin manager: ${s instanceof Error?s.message:String(s)}`)}}createMarginManager(e,t=new T){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:n,quoteCoin:s}=e;try{let[i,o]=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[t.object(this.sdk.sdkOptions.margin_utils.versioned_id),t.object(r),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(v)],typeArguments:[n.coinType,s.coinType]});return{tx:t,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create margin manager: ${i instanceof Error?i.message:String(i)}`)}}shareMarginManager({marginManager:e,initializer:t,baseCoin:r,quoteCoin:n},s=new T){try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,t],typeArguments:[r.coinType,n.coinType]}),s}catch(i){throw new Error(`Failed to share margin manager: ${i instanceof Error?i.message:String(i)}`)}}async getBalanceManagerByMarginManager(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");let t=`
1
+ var Le=Object.defineProperty;var xe=(u,e,t)=>e in u?Le(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var _e=(u,e,t)=>(xe(u,typeof e!="symbol"?e+"":e,t),t);import{SuiGraphQLClient as wt}from"@mysten/sui/graphql";import{DeepBookClient as ct}from"@mysten/deepbook-v3";import{bcs as k}from"@mysten/sui/bcs";import{Transaction as j,coinWithBalance as De}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as P,normalizeStructTag as U,normalizeSuiObjectId as ut}from"@mysten/sui/utils";import{Base64 as dt}from"js-base64";import{coinWithBalance as we}from"@mysten/sui/transactions";import{SUI_TYPE_ARG as He,normalizeStructTag as We,normalizeSuiObjectId as se}from"@mysten/sui/utils";var Ge=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function be(u){return u.startsWith("0x")?u:`0x${u}`}function ne(u){return u.startsWith("0x")?`${u.slice(2)}`:u}function Ke(u,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${u.slice(0,r+2)} ... ${u.slice(-n)}`}function At(u,e=4,t=4){return Ke(be(u),e,t)}function St(u,e={leadingZero:!0}){if(typeof u!="string")return!1;let t=u;if(e.leadingZero){if(!u.startsWith("0x"))return!1;t=t.substring(2)}return Ge.test(t)}function ze(u){if(!Buffer.isBuffer(u))if(Array.isArray(u))u=Buffer.from(u);else if(typeof u=="string")exports.isHexString(u)?u=Buffer.from(exports.padToEven(exports.stripHexPrefix(u)),"hex"):u=Buffer.from(u);else if(typeof u=="number")u=exports.intToBuffer(u);else if(u==null)u=Buffer.allocUnsafe(0);else if(u.toArray)u=Buffer.from(u.toArray());else throw new Error("invalid type");return u}function jt(u){return be(ze(u).toString("hex"))}function Bt(u){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<u.length;n++)t.setUint8(n,u.charCodeAt(n));return t.getUint32(0,!0)}function Qe(u){let e,t,r,n,s;e="";let i=u.length;for(t=0;t<i;)switch(r=u.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=u.charAt(t-1);break;case 12:case 13:n=u.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=u.charCodeAt(t++),s=u.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function Et(u){let e="",t=ne(u),r=t.length/2;for(let n=0;n<r;n++)e+=String.fromCharCode(Number.parseInt(t.substr(n*2,2),16));return Qe(e)}var Je=0,fe=1,Ze=2;function he(u,e){return u===e?Je:u<e?fe:Ze}function Ye(u,e){let t=0,r=u.length<=e.length?u.length:e.length,n=he(u.length,e.length);for(;t<r;){let s=he(u.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function It(u,e){return Ye(u,e)===fe}function ye(u,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[u,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function Dt(u){return u.split("::")[0]}function R(u){try{let e=u.replace(/\s/g,""),r=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(r){e=e.slice(0,e.indexOf("<"));let a={...R(e),type_arguments:r.map(c=>R(c).source_address)};return a.type_arguments=a.type_arguments.map(c=>E.isSuiCoin(c)?c:R(c).source_address),a.source_address=ye(a.full_address,a.type_arguments),a}let n=e.split("::"),i={full_address:e,address:e===ae||e===ke?"0x2":se(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return i.full_address=`${i.address}::${i.module}::${i.name}`,i.source_address=ye(i.full_address,i.type_arguments),i}catch{return{full_address:u,address:"",module:"",name:"",type_arguments:[],source_address:u}}}function ie(u){return R(u).source_address}function Xe(u){return u.toLowerCase().startsWith("0x")?se(u):u}var Ut=(u,e=!0)=>{let t=u.split("::"),r=t.shift(),n=se(r);return e&&(n=ne(n)),`${n}::${t.join("::")}`};function oe(u){for(let e in u){let t=typeof u[e];if(t==="object")oe(u[e]);else if(t==="string"){let r=u[e];u[e]=Xe(r)}}}var $t=We(He);var et="0x2::coin::Coin",tt=/^0x2::coin::Coin<(.+)>$/,Nt=1e3,Lt=500,xt=100,Gt=100,Kt=1e3,ae="0x2::sui::SUI",ke="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",zt="SUI",Qt=450,Ht="0x0000000000000000000000000000000000000005",E=class{static getCoinTypeArg(e){let t=e.type.match(tt);return t?t[1]:null}static isSUI(e){let t=E.getCoinTypeArg(e);return t?E.getCoinSymbol(t)==="SUI":!1}static getCoinSymbol(e){return e.substring(e.lastIndexOf(":")+1)}static getBalance(e){return BigInt(e.fields.balance)}static totalBalance(e,t){let r=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(r+=BigInt(n.balance))}),r}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${et}<${e}>`}static getCoinAssets(e,t){let r=[];return t.forEach(n=>{ie(n.coinAddress)===ie(e)&&r.push(n)}),r}static isSuiCoin(e){return R(e).full_address===ae}static selectCoinObjectIdGreaterThanOrEqual(e,t,r=[]){let n=E.selectCoinAssetGreaterThanOrEqual(e,t,r),s=n.selectedCoins.map(a=>a.coinObjectId),i=n.remainingCoins,o=n.selectedCoins.map(a=>a.balance.toString());return{objectArray:s,remainCoins:i,amountArray:o}}static selectCoinAssetGreaterThanOrEqual(e,t,r=[]){let n=E.sortByBalance(e.filter(c=>!r.includes(c.coinObjectId))),s=E.calculateTotalBalance(n);if(s<t)return{selectedCoins:[],remainingCoins:n};if(s===t)return{selectedCoins:n,remainingCoins:[]};let i=BigInt(0),o=[],a=[...n];for(;i<s;){let c=t-i,p=a.findIndex(g=>g.balance>=c);if(p!==-1){o.push(a[p]),a.splice(p,1);break}let d=a.pop();d.balance>0&&(o.push(d),i+=d.balance)}return{selectedCoins:E.sortByBalance(o),remainingCoins:E.sortByBalance(a)}}static sortByBalance(e){return e.sort((t,r)=>t.balance<r.balance?-1:t.balance>r.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,r)=>t.balance>r.balance?-1:t.balance<r.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,r)=>t+r.balance,BigInt(0))}static buildCoinWithBalance(e,t,r){return e===BigInt(0)&&E.isSuiCoin(t)?r.add(we({balance:e,useGasCoin:!1})):r.add(we({balance:e,type:t}))}};var Ce=6e4,Oe=3e5,L=864e5;function z(u){return Date.parse(new Date().toString())+u}var K=class{overdueTime;value;constructor(e,t=0){this.overdueTime=t,this.value=e}isValid(){return this.value===null?!1:this.overdueTime===0?!0:!(Date.parse(new Date().toString())>this.overdueTime)}};import{fromB64 as Se,fromHEX as je}from"@mysten/bcs";import{Ed25519Keypair as Te}from"@mysten/sui/keypairs/ed25519";import{Secp256k1Keypair as Ae}from"@mysten/sui/keypairs/secp256k1";import Z from"decimal.js";function l(u){return Z.isDecimal(u)?u:new Z(u===void 0?0:u)}function ce(u){return l(10).pow(l(u).abs())}var x=(u,e)=>{try{return l(u).toDP(e,Z.ROUND_DOWN).toString()}catch{return u}},ue=(u,e)=>Z.max(l(u),l(e));function W(u,e){let t=ce(l(e));return Number(l(u).mul(t))}function nr(u,e=32){return BigInt.asUintN(e,BigInt(u)).toString()}function sr(u,e=32){return Number(BigInt.asIntN(e,BigInt(u)))}function G(u,e){let t=ce(l(e));return Number(l(u).div(t))}function ir(u,e="hex"){if(u instanceof Uint8Array){let r=Buffer.from(u);return Te.fromSecretKey(r)}let t=e==="hex"?je(u):Se(u);return Te.fromSecretKey(t)}function or(u,e="hex"){if(u instanceof Uint8Array){let r=Buffer.from(u);return Ae.fromSecretKey(r)}let t=e==="hex"?je(u):Se(u);return Ae.fromSecretKey(t)}var Be=async u=>new Promise(e=>{setTimeout(()=>{e(1)},u)});var Ee={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},ve={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function Me(...u){let e="DeepbookV3_Utils_Sdk###"}function Q(u){return u.data}function rt(u){if(u.error&&"object_id"in u.error&&"version"in u.error&&"digest"in u.error){let{error:e}=u;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function nt(u){if(u.error&&"object_id"in u.error&&!("version"in u.error)&&!("digest"in u.error))return u.error.object_id}function qe(u){if("reference"in u)return u.reference;let e=Q(u);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:rt(u)}function Pe(u){return"objectId"in u?u.objectId:qe(u)?.objectId??nt(u)}function dr(u){return"version"in u?u.version:qe(u)?.version}function st(u){return u.data!==void 0}function it(u){return u.content!==void 0}function lr(u){let e=Q(u);if(e?.content?.dataType==="package")return e.content.disassembled}function de(u){let e="data"in u?Q(u):u;if(!(!e||!it(e)||e.content.dataType!=="moveObject"))return e.content}function ot(u){return de(u)?.type}function pr(u){let e=st(u)?u.data:u;return!e?.type&&"data"in u?e?.content?.dataType==="package"?"package":ot(u):e?.type}function gr(u){return Q(u)?.previousTransaction}function mr(u){return Q(u)?.owner}function _r(u){let e=Q(u)?.display;return e||{data:null,error:null}}function Ie(u){let e=de(u)?.fields;if(e)return"fields"in e?e.fields:e}function br(u){return de(u)?.hasPublicTransfer??!1}import{Transaction as at}from"@mysten/sui/transactions";async function kr(u,e=!0){u.blockData.transactions.forEach((t,r)=>{})}var V=class{static async adjustTransactionForGas(e,t,r,n){n.setSender(e.senderAddress);let s=E.selectCoinAssetGreaterThanOrEqual(t,r).selectedCoins;if(s.length===0)throw new Error("Insufficient balance");let i=E.calculateTotalBalance(t);if(i-r>1e9)return{fixAmount:r};let o=await e.fullClient.calculationTxGas(n);if(E.selectCoinAssetGreaterThanOrEqual(t,BigInt(o),s.map(c=>c.coinObjectId)).selectedCoins.length===0){let c=BigInt(o)+BigInt(500);if(i-r<c){if(r-=c,r<0)throw new Error("gas Insufficient balance");let p=new at;return{fixAmount:r,newTx:p}}}return{fixAmount:r}}static buildCoinForAmount(e,t,r,n,s=!0,i=!1){let o=E.getCoinAssets(n,t);if(r===BigInt(0)&&o.length===0)return V.buildZeroValueCoin(t,e,n,s);let a=E.calculateTotalBalance(o);if(a<r)throw new Error(`The amount(${a}) is Insufficient balance for ${n} , expect ${r} `);return V.buildCoin(e,t,o,r,n,s,i)}static buildCoin(e,t,r,n,s,i=!0,o=!1){if(E.isSuiCoin(s)){if(i){let h=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[h]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&r.length>1){let h=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.object(h.objectArray[0]),remainCoins:h.remainCoins,tragetCoinAmount:h.amountArray[0],isMintZeroCoin:!1}}let f=E.selectCoinObjectIdGreaterThanOrEqual(r,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:f.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let a=E.selectCoinObjectIdGreaterThanOrEqual(r,n),c=a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),p=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:p.map(f=>e.object(f))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...g]=p,_=e.object(d),m=_,b=a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),w;return g.length>0&&e.mergeCoins(_,g.map(f=>e.object(f))),o&&Number(c)>Number(n)&&(m=e.splitCoins(_,[e.pure.u64(n)]),b=n.toString(),w=_),{targetCoin:m,remainCoins:a.remainCoins,originalSplitedCoin:w,tragetCoinAmount:b,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,r,n=!0){let s=V.callMintZeroValueCoin(t,r),i;return n?i=t.makeMoveVec({elements:[s]}):i=s,{targetCoin:i,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,r,n,s=!0){let i=E.getCoinAssets(n,t);if(r.amountFirst===BigInt(0))return i.length>0?V.buildCoin(e,[...t],[...i],r.amountFirst,n,s):V.buildZeroValueCoin(t,e,n,s);let o=E.calculateTotalBalance(i);if(o>=r.amountFirst)return V.buildCoin(e,[...t],[...i],r.amountFirst,n,s);if(o<r.amountSecond)throw new Error(`The amount(${o}) is Insufficient balance for ${n} , expect ${r.amountSecond} `);return V.buildCoin(e,[...t],[...i],r.amountSecond,n,s)}static buildCoinTypePair(e,t){let r=[];if(e.length===2){let n=[];n.push(e[0],e[1]),r.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),r.push(n);for(let s=1;s<e.length-1;s+=1){if(t[s-1]===0)continue;let i=[];i.push(e[0],e[s],e[e.length-1]),r.push(i)}}return r}},N=V;_e(N,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));var le=1e6,$=1e9,lt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},pt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},X=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?pt:lt}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new j,t=e.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`});return e.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[e.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),t],typeArguments:[]}),e.moveCall({target:"0x2::transfer::public_share_object",arguments:[t],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),e}createAndDepsit({account:e,coin:t,amountToDeposit:r}){let n=new j;n.setSenderIfNotSet(e);let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),i=De({type:t.coinType,balance:BigInt(r)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[s,i],typeArguments:[t.coinType]}),n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[s],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:r,amountToDeposit:n,tx:s}){let i=s||new j;if(t){i.setSenderIfNotSet(e);let o=De({type:r.coinType,balance:BigInt(n)});return i.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[i.object(t),o],typeArguments:[r.coinType]}),i}return null}withdrawFromManager({account:e,balanceManager:t,coin:r,amountToWithdraw:n,returnAssets:s,txb:i}){let o=i||new j,a=o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[o.object(t),o.pure.u64(n)],typeArguments:[r.coinType]});return s?a:(o.transferObjects([a],e),o)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:r=new j}){for(let n in t)t[n].forEach(i=>{let o=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[r.object(n),r.pure.u64(i.amount)],typeArguments:[i.coinType]});r.transferObjects([o],e)});return r}async getBalanceManager(e,t=!0){let r=`getBalanceManager_${e}`,n=this.getCache(r,t);if(!t&&n!==void 0)return n;try{let s=new j;s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),s.pure.address(e)],typeArguments:[]});let a=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}))?.events?.filter(p=>p.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],c=[];return a.forEach(p=>{c.push({balanceManager:p,cetusBalanceManager:""})}),this.updateCache(r,c,864e5),c||[]}catch(s){throw s instanceof Error?s:new Error(String(s))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},r=new j){let n=r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[r.object(t)]});return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[r.object(e.address),r.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}async getManagerBalance({account:e,balanceManager:t,coins:r}){try{let n=new j;r.forEach(o=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[o.coinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),i={};return s.results?.forEach((o,a)=>{let c=r[a],p=o.returnValues[0][0],d=k.U64.parse(new Uint8Array(p)),g=l(d),_=g.eq(0)?"0":g.div(Math.pow(10,c.decimals)).toString();i[c.coinType]={adjusted_balance:_,balance:g.toString()}}),i}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let r=new j,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(o=>{t.forEach(a=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[r.object(o.balanceManager)],typeArguments:[a.coinType]})})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i={};return n.forEach((o,a)=>{let c={},p=a*t.length;t.forEach((d,g)=>{let _=p+g,m=s.results?.[_];if(m){let b=m.returnValues[0][0],w=k.U64.parse(new Uint8Array(b)),f=l(w),C=f.eq(0)?"0":f.div(Math.pow(10,d.decimals)).toString();c[d.coinType]={adjusted_balance:C,balance:f.toString()}}}),i[o.balanceManager]=c}),i}catch(r){throw r instanceof Error?r:new Error(String(r))}}async getMarketPrice(e){try{let t=new j;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let n=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],s=Number(k.U64.parse(new Uint8Array(n))),i=Math.pow(10,e.baseCoin.decimals).toString(),o=Math.pow(10,e.quoteCoin.decimals).toString();return l(s).mul(i).div(o).div($).toString()}catch(t){return Me("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",r=this.getCache(t,e);if(r!==void 0)return r;let n=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),s=/<([^>]+)>/,i=[];return n?.data?.forEach(o=>{let a=o?.parsedJson,c=o.type.match(s);if(c){let d=c[1].split(", ");i.push({...a,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,i,864e5),i}async getQuoteQuantityOut(e,t,r){let n=new j;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),baseQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getBaseQuantityOut(e,t,r){let n=new j;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[n.object(e.address),n.pure.u64(t),n.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:n}),i=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),o=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[1][0]))),a=String(k.U64.parse(new Uint8Array(s.results[0].returnValues[2][0])));return{quoteQuantityDisplay:l(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(a).div(le).toString(),quoteQuantity:t,baseOut:i,quoteOut:o,deepRequired:a}}async getQuantityOut(e,t,r,n){let s=new j;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.pure.u64(r),s.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let i=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=Number(k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0]))),a=Number(k.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]))),c=Number(k.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])));return{baseQuantityDisplay:l(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:l(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:l(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:l(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:l(c).div(le).toString(),baseQuantity:t,quoteQuantity:r,baseOut:o,quoteOut:a,deepRequired:c}}async getReferencePool(e){let t=await this.getPools(),r=e.baseCoin.coinType,n=e.quoteCoin.coinType,s=this._deep.coinType;for(let i=0;i<t.length;i++){let o=t[i];if(o.address===e.address)continue;let a=[o.baseCoinType,o.quoteCoinType];if(o.baseCoinType===s&&(a.includes(r)||a.includes(n)))return o}return null}async updateDeepPrice(e,t){let r=await this.getReferencePool(e);return r?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(r.pool_id),t.object(P)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,r.baseCoinType,r.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,r,n,s,i,o){let a=this.deepCoin;try{let{taker_fee:c,maker_fee:p}=e,d=l(c).div($).toString(),g=l(p).div($).toString(),_=await this.getMarketPrice(e),m=i?r:_!=="0"?_:o;if(m==="0")throw new Error("Cannot get market price");let b=Math.pow(10,e.baseCoin.decimals).toString(),w=Math.pow(10,e.quoteCoin.decimals).toString(),f=l(m).div(b).mul(w).mul($).toString();if(n){let A=await this.getMarketPrice(e),T=l(i?r:A!=="0"?A:o).div(b).mul(w).mul($).toString(),B=await this.getOrderDeepPrice(e);if(!B)throw new Error("Cannot get deep price");let M=ue(T,r),I=l(t).mul(l(d)).mul(l(B.deep_per_asset)).div(l($)),q=l(t).mul(l(g)).mul(l(B.deep_per_asset)).div(l($));B.asset_is_base||(I=I.mul(M).div(l($)),q=q.mul(M).div(l($)));let D=I.ceil().toString(),J=q.ceil().toString();return{takerFee:D,makerFee:J,takerFeeDisplay:G(D,a.decimals).toString(),makerFeeDisplay:G(J,a.decimals).toString(),feeType:a.coinType}}if(s){let A=ue(f,i?r:_),S=l(t).mul(A).mul(l(d).mul(1.25)).div(l($)).ceil().toFixed(0),T=l(t).mul(A).mul(l(g).mul(1.25)).div(l($)).ceil().toFixed(0);return{takerFee:S,makerFee:T,takerFeeDisplay:G(S,e.quoteCoin.decimals).toString(),makerFeeDisplay:G(T,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=l(t).mul(l(d).mul(1.25)).ceil().toFixed(0),h=l(t).mul(l(g).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:h,takerFeeDisplay:G(C,e.baseCoin.decimals).toString(),makerFeeDisplay:G(h,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(c){throw c instanceof Error?c:new Error(String(c))}}async getOrderDeepPrice(e,t=!0){let r=`getOrderDeepPrice_${e.address}}`,n=this.getCache(r);if(n!==void 0)return n;try{let s=new j,i=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,s)&&(i=!0),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[s.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),a=i?o.results[1]?.returnValues[0]?.[0]:o.results[0]?.returnValues[0]?.[0],c=this.parseOrderDeepPrice(new Uint8Array(a));return this.updateCache(r,c,6e4),c}catch{return await Be(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),r=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:r,deep_per_asset:n}}getCoinAssets(e,t,r,n){return N.buildCoinForAmount(n,r,BigInt(l(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,r,n,s,i,o){let a=this.deepCoin;if(!o)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let c=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&c.push(a);let p=await this.getManagerBalance({account:s,balanceManager:o,coins:c}),d=p?.[t]?.balance||"0",g=p?.[r]?.balance||"0",_=i&&p?.[a.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:g,feeManaerBalance:_}}catch(c){throw c instanceof Error?c:new Error(String(c))}}getFeeAsset(e,t,r,n,s,i,o,a,c,p){let d=l(e).gt(0)&&c,g="0";if(!d)return{feeAsset:this.getEmptyCoin(p,t),haveDepositFee:"0"};if(i||o){let _=l(s).sub(i?n:r);g=_.lte(0)?e:_.sub(e).lt(0)?_.sub(e).toString():"0"}else g=l(s).sub(e).lt("0")?l(s).sub(e).abs().toString():"0";return{feeAsset:l(g).gt("0")?this.getCoinAssets(t,g,a,p):this.getEmptyCoin(p,t),haveDepositFee:g}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,c){try{let p=this.deepCoin,d=U(e.baseCoin.coinType),g=U(e.quoteCoin.coinType),_=d===p.coinType,m=g===p.coinType,b=!_&&!m,{baseManagerBlance:w,quoteManagerBlance:f,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,g,b,i,o,a);console.log("\u{1F680}\u{1F680}\u{1F680} ~ deepbookUtilsModule.ts:897 ~ DeepbookUtilsModule ~ getTransactionRelatedAssets ~ quoteManagerBlance:",{baseManagerBlance:w,quoteManagerBlance:f});let h,A,S=!1,T=await this._sdk.getOwnerCoinAssets(i);if(s){o||(r=l(r).add(l(n)).toString());let M=l(f).sub(r).toString();l(M).lt(0)?(S=!0,A=this.getCoinAssets(g,M,T,c)):A=this.getEmptyCoin(c,g),h=this.getEmptyCoin(c,d)}else{o||(t=l(t).add(l(n)).toString());let M=l(w).sub(t).toString();l(M).lt(0)?(S=!0,h=this.getCoinAssets(d,M,T,c)):h=this.getEmptyCoin(c,d),A=this.getEmptyCoin(c,g)}let B=this.getFeeAsset(n,p.coinType,t,r,C,m,_,T,o,c);return{baseAsset:h,quoteAsset:A,feeAsset:B,haveDeposit:S}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,c,p){try{let d=this.deepCoin,g=U(e.baseCoin.coinType),_=U(e.quoteCoin.coinType),m=g===d.coinType,b=_===d.coinType,w=!m&&!b,f=await this.getTransactionRelatedBalance(e,g,_,w,i,o,a),{feeManaerBalance:C}=f,h=l(f.baseManagerBlance).add(l(p?.base||"0")).toString(),A=l(f.quoteManagerBlance).add(l(p?.quote||"0")).toString(),S=await this._sdk.getOwnerCoinAssets(i),T;o&&l(C).lt(n)?T=this.getCoinAssets(d.coinType,l(n).sub(C).toString(),S,c):T=this.getEmptyCoin(c,d.coinType);let B,M;if(s){o||(r=l(r).add(l(n)).toString());let I=l(A).sub(r).toString();if(l(I).lt(0)){let q;l(A).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:A,returnAssets:!0,txb:c}));let D=this.getCoinAssets(_,I,S,c);q&&c.mergeCoins(D,[q]),M=D}else M=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:c});B=this.getEmptyCoin(c,g)}else{o||(t=l(t).add(l(n)).toString());let I=l(h).sub(t).toString();if(l(I).lt(0)){let q;l(h).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:c}));let D=this.getCoinAssets(g,I,S,c);q&&c.mergeCoins(D,[q]),B=D}else B=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:c});M=this.getEmptyCoin(c,_)}return{baseAsset:B,quoteAsset:M,feeAsset:T}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:r,orderType:n,isBid:s,maxFee:i,account:o,payWithDeep:a,expirationTimestamp:c=Date.now()+31536e8}){try{let p=this.deepCoin,d=e.address,g=e.baseCoin.decimals,_=e.quoteCoin.decimals,m=e.baseCoin.coinType,b=e.quoteCoin.coinType,w=l(t).mul(10**(_-g+9)).toString(),f=U(m),C=U(b),h=new j,A,S,T=await this._sdk.getOwnerCoinAssets(o);if(s){let q=l(t).mul(l(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(q=l(q).add(l(i)).toString()),S=N.buildCoinForAmount(h,T,BigInt(q),C,!1,!0)?.targetCoin}else{let q=r;a||(q=l(r).abs().add(l(i)).toString()),A=N.buildCoinForAmount(h,T,BigInt(l(q).abs().toString()),f,!1,!0)?.targetCoin}let B=a?l(i).gt(0)?N.buildCoinForAmount(h,T,BigInt(l(i).abs().ceil().toString()),p.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,p.coinType):this.getEmptyCoin(h,p.coinType),M=h.moveCall({typeArguments:[s?m:b],target:"0x2::coin::zero",arguments:[]}),I=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(d),s?M:A,s?S:M,B,h.pure.u8(n),h.pure.u8(0),h.pure.u64(w),h.pure.u64(r),h.pure.bool(s),h.pure.bool(!1),h.pure.u64(c),h.object(P)];return h.moveCall({typeArguments:[f,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:I}),h}catch(p){throw p instanceof Error?p:new Error(String(p))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:r,maxFee:n,account:s,payWithDeep:i,slippage:o=.01}){try{let a=e.address,c=e.baseCoin.coinType,p=e.quoteCoin.coinType,d=U(c),g=U(p),_=new j,m,b,w=t,f,C=await this.getOrderBook(e,"all",6);if(r){let T=C?.ask?.[0]?.price||"0",B=l(T).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=l(B).plus(l(B).mul(o)).ceil().toString()}else{let T=await C?.bid?.[0]?.price||"0",B=l(T).mul(l(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=l(B).minus(l(B).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(f=l(f).add(l(n)).toString()),b=this.getCoinAssets(g,f,h,_),m=this.getEmptyCoin(_,d)):(i||(w=l(w).add(l(n)).toString()),b=this.getEmptyCoin(_,g),m=this.getCoinAssets(d,w,h,_));let A=i?l(n).gt(0)?N.buildCoinForAmount(_,h,BigInt(l(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,this.deepCoin.coinType):this.getEmptyCoin(_,this.deepCoin.coinType),S=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(a),m,b,A,_.pure.u8(0),_.pure.u64(t),_.pure.bool(r),_.pure.bool(i),_.pure.u64(f),_.object(P)];return _.moveCall({typeArguments:[d,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:S}),_}catch(a){throw a instanceof Error?a:new Error(String(a))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:r,quantity:n,isBid:s,orderType:i,maxFee:o,account:a,payWithDeep:c,expirationTimestamp:p=Date.now()+31536e8}){try{let d=this.deepCoin,g=l(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),_=t.baseCoin.coinType,m=t.quoteCoin.coinType,b=new j,w=s?l(r).mul(l(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",f=s?"0":n,{baseAsset:C,quoteAsset:h,feeAsset:A,haveDeposit:S}=await this.getTransactionRelatedAssets(t,f,w,o,s,a,c,e,b);if(S){let M=[b.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),b.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),b.object(t.address),b.object(e),C,h,A.feeAsset,b.pure.u8(i),b.pure.u8(0),b.pure.u64(g),b.pure.u64(n),b.pure.bool(s),b.pure.bool(c),b.pure.u64(p),b.object(P)];return b.moveCall({typeArguments:[_,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:M}),b}let T=new j;l(A.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:d,amountToDeposit:A.haveDepositFee,tx:T});let B=[T.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),T.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),T.object(t.address),T.object(e),T.pure.u8(i),T.pure.u8(0),T.pure.u64(g),T.pure.u64(n),T.pure.bool(s),T.pure.bool(c),T.pure.u64(p),T.object(P)];return T.moveCall({typeArguments:[_,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:B}),T}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:r,newOrderQuantity:n}){let s=new j;return s.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(e),s.object(t.address),s.pure.u128(r),s.pure.u64(n),s.object(P)]}),s}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new j,s=await this.getMarketPrice(e),i=l(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(a),n.pure.u64(c),n.pure.bool(!1),n.object(P)],typeArguments:[t.coinType,r.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),g=[],_=d.results[0].returnValues[0][0],m=k.vector(k.u64()).parse(new Uint8Array(_)),b=d.results[0].returnValues[1][0],w=k.vector(k.u64()).parse(new Uint8Array(b));return m.forEach((f,C)=>{let h=l(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=l(w[C]).div(Math.pow(10,t.decimals)).toString();g.push({price:h,quantity:A})}),g?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:r}=e,n=new j,s=await this.getMarketPrice(e),i=l(s).gt(0)?l(s).div(3).toNumber():Math.pow(10,-6),o=l(s).gt(0)?s:Math.pow(10,6),a=l(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=l(o).mul(Math.pow(10,9+r.decimals-t.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(x(a,0)),n.pure.u64(x(c,0)),n.pure.bool(!0),n.object(P)],typeArguments:[t.coinType,r.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),g=[],_=d.results[0].returnValues[0][0],m=k.vector(k.u64()).parse(new Uint8Array(_)),b=d.results[0].returnValues[1][0],w=k.vector(k.u64()).parse(new Uint8Array(b));return m.forEach((f,C)=>{let h=l(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=l(w[C]).div(Math.pow(10,t.decimals)).toString();g.push({price:h,quantity:A})}),g?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:r,quoteCoin:n}=e,s=new j,i=await this.getMarketPrice(e),o,a;t?(o=l(i).gt(0)?l(i).div(3).toNumber():Math.pow(10,-6),a=l(i).gt(0)?i:Math.pow(10,6)):(o=l(i).gt(0)?i:Math.pow(10,-1),a=l(i).gt(0)?l(i).mul(3).toNumber():Math.pow(10,6));let c=l(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),p=l(a).mul(Math.pow(10,9+n.decimals-r.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(x(c,0)),s.pure.u64(x(p,0)),s.pure.bool(t),s.object(P)],typeArguments:[r.coinType,n.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:s}),_=[],m=g.results[0].returnValues[0][0],b=k.vector(k.u64()).parse(new Uint8Array(m)),w=g.results[0].returnValues[1][0],f=k.vector(k.u64()).parse(new Uint8Array(w));return b.forEach((C,h)=>{let A=l(C).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),S=l(f[h]).div(Math.pow(10,r.decimals)).toString();_.push({price:A,quantity:S})}),_?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:r,quoteQuantity:n,isBid:s,maxFee:i,account:o,payWithDeep:a,slippage:c=.01,settled_balances:p={base:"0",quote:"0"}}){try{let d=U(t.baseCoin.coinType),g=U(t.quoteCoin.coinType),_=new j;p&&(l(p.base).gt(0)||l(p.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},_);let{baseAsset:m,quoteAsset:b,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,_,p),f=await this.getOrderBook(t,"all",6);if(s){let A=f?.ask?.[0]?.price||"0",S=l(A).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(S).plus(l(S).mul(c)).ceil().toString()}else{let A=await f?.bid?.[0]?.price||"0",S=l(A).mul(l(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=l(S).minus(l(S).mul(c)).floor().toString()}let C=n,h=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(t.address),_.object(e),m,b,w,_.pure.u8(0),_.pure.u64(r),_.pure.bool(s),_.pure.bool(a),_.pure.u64(C),_.object(P)];return _.setSenderIfNotSet(o),_.moveCall({typeArguments:[d,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),_}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let r=new j;e.forEach(c=>{let p=c?.pool,d=c?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(p.pool_id),r.pure.u128(BigInt(d))],typeArguments:[p.baseCoinType,p.quoteCoinType]})});let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:r}),s=k.struct("ID",{bytes:k.Address}),i=k.struct("OrderDeepPrice",{asset_is_base:k.bool(),deep_per_asset:k.u64()}),o=k.struct("Order",{balance_manager_id:s,order_id:k.u128(),client_order_id:k.u64(),quantity:k.u64(),filled_quantity:k.u64(),fee_is_deep:k.bool(),order_deep_price:i,epoch:k.u64(),status:k.u8(),expire_timestamp:k.u64()}),a=[];return n?.results?.forEach(c=>{let p=c.returnValues[0][0],d=o.parse(new Uint8Array(p));a.push(d)}),a}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),r=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:r,orderId:n}}async getOpenOrder(e,t,r,n,s=!1,i=new j){let o;if(n)o=n;else{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[i.object(e.address),s?r:i.object(r)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let g=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:i})).results[s?1:0].returnValues[0][0];o=k.struct("VecSet",{constants:k.vector(k.U128)}).parse(new Uint8Array(g)).constants}if(o.length===0)return[];let a=o.map(d=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:d})),c=await this.getOrderInfoList(a,t)||[],p=[];return c.forEach(d=>{let g=this.decodeOrderId(BigInt(d.order_id));p.push({...d,price:g.price,isBid:g.isBid,pool:e})}),p}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new j;r.forEach(d=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(d.pool_id),n.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(d=>d.returnValues?.[0]?.[0])||[],o=k.struct("VecSet",{constants:k.vector(k.U128)}),a=[];i.forEach((d,g)=>{let _=o.parse(new Uint8Array(d)).constants;_.length>0&&_.forEach(m=>{a.push({pool:r[g],orderId:m})})});let c=await this.getOrderInfoList(a,e)||[],p=[];return a.forEach((d,g)=>{let _=this.decodeOrderId(BigInt(d.orderId)),m=c.find(b=>b.order_id===d.orderId)||{};p.push({...d,...m,price:_.price,isBid:_.isBid})}),p}catch{return[]}}cancelOrders(e,t,r=new j){return e.forEach(n=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(t),r.object(n.poolInfo.address),r.pure.u128(n.orderId),r.object(P)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),r}async getDeepbookOrderBook(e,t,r,n,s,i){let o=this._sdk.fullClient,c=await new ct({client:o,address:s,env:"testnet",balanceManagers:{test1:{address:i,tradeCap:""}}}).getLevel2Range(e,t,r,n)}processOrderBookData(e,t,r,n){let s=e.returnValues[0][0],i=k.vector(k.u64()).parse(new Uint8Array(s)),o=e.returnValues[1][0],a=k.vector(k.u64()).parse(new Uint8Array(o)),c={};return i.forEach((d,g)=>{let _=l(d).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),m=l(a[g]).div(Math.pow(10,t.decimals)).toString();c[_]?c[_]={price:_,quantity:l(c[_].quantity).add(m).toString()}:c[_]={price:_,quantity:m}}),Object.values(c)}getLevel2RangeTx(e,t,r,n,s=new j){let{baseCoin:i,quoteCoin:o}=e,a=x(l(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),c=x(l(n).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0);return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(a),s.pure.u64(c),s.pure.bool(t),s.object(P)],typeArguments:[i.coinType,o.coinType]}),s}async fetchOrderBook(e,t,r,n,s,i){let o=new j,{baseCoin:a,quoteCoin:c}=e;try{if(t==="bid"||t==="all"){let m=n,b=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,m,b,o)}if(t==="ask"||t==="all"){let m=r==="0"?n:r,b=s;o=this.getLevel2RangeTx(e,!1,m,b,o)}let p=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:o}),g=[];(t==="bid"||t==="all")&&(g=d.results?.[0]?this.processOrderBookData(d.results[0],a,c,i):[]);let _=[];if(t==="ask"||t==="all"){let m=t==="ask"?0:1;_=d.results?.[m]?this.processOrderBookData(d.results[m],a,c,i):[]}return{bid:g.sort((m,b)=>b.price-m.price),ask:_.sort((m,b)=>m.price-b.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,g=[],_=[];try{let m=this.getLevel2RangeTx(e,!0,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});g=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{g=[]}try{let m=this.getLevel2RangeTx(e,!1,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:m});_=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{_=[]}return{bid:g,ask:_}}}async getOrderBook(e,t,r){let n={bid:[],ask:[]};try{let s=await this.getMarketPrice(e),i=t,o=Math.pow(10,-r),a=Math.pow(10,r),c=await this.fetchOrderBook(e,i,s,o,a,r);return{bid:c?.bid,ask:c?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let r=new j,n=await this.getMarketPrice(e),{baseCoin:s,quoteCoin:i}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),g=n,_=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(g).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(_),r.pure.u64(m),r.pure.bool(!0),r.object(P)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let d=n,g=Math.pow(10,6),_=l(d).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),m=l(g).mul(Math.pow(10,9+i.decimals-s.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(_),r.pure.u64(m),r.pure.bool(!1),r.object(P)],typeArguments:[s.coinType,i.coinType]})}let o=this._sdk.sdkOptions.simulationAccount.address,a=await this._sdk.fullClient.devInspectTransactionBlock({sender:o,transactionBlock:r}),c=[];if(t==="bid"||t==="all"){let d=a.results[0]?.returnValues[0]?.[0],g=k.vector(k.u64()).parse(new Uint8Array(d)),_=a.results[0]?.returnValues[1]?.[0],m=k.vector(k.u64()).parse(new Uint8Array(_));g.forEach((b,w)=>{let f=l(b).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),C=l(m[w]).div(Math.pow(10,s.decimals)).toString();c.push({price:f,quantity:C})})}let p=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,g=a.results[d]?.returnValues[0]?.[0],_=k.vector(k.u64()).parse(new Uint8Array(g)),m=a.results[d]?.returnValues[1]?.[0],b=k.vector(k.u64()).parse(new Uint8Array(m));_.forEach((w,f)=>{let C=l(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=l(b[f]).div(Math.pow(10,s.decimals)).toString();p.push({price:C,quantity:h})})}return{bid:c,ask:p}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,s)=>[U(n.coinType),n]))}async getAccount(e,t,r=new j){for(let o=0;o<t.length;o++){let a=t[o];r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(a.address),typeof e=="string"?r.object(e):e],typeArguments:[a.baseCoin.coinType,a.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.senderAddress,transactionBlock:r}),s;if(n?.events.length===0)return null;let i=[];return n?.events?.forEach((o,a)=>{s=o?.parsedJson;let c=s.account.open_orders.contents,p=s.account.owed_balances,d=s.account.settled_balances,g=s.account.unclaimed_rebates,_=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:c,owed_balances:p,settled_balances:d,unclaimed_rebates:g,taker_volume:_,poolInfo:t[a]})}),i}async getSuiTransactionResponse(e,t=!1){let r=`${e}_getSuiTransactionResponse`,n=this.getCache(r,t);if(n!==void 0)return n;let s;try{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{s=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(r,s,864e5),s}transformExtensions(e,t,r=!0){let n=[];for(let s of t){let{key:i}=s.fields,{value:o}=s.fields;if(i==="labels")try{o=JSON.parse(decodeURIComponent(dt.decode(o)))}catch{}r&&(e[i]=o),n.push({key:i,value:o})}delete e.extension_fields,r||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let r=this.sdk.sdkOptions.coinlist.handle,n=`${r}_getCoinConfigs`,s=this.getCache(n,e);if(s)return s;let o=(await this._sdk.fullClient.getDynamicFieldsByPage(r)).data.map(p=>p.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),c=[];return a.forEach(p=>{let d=this.buildCoinConfig(p,t);this.updateCache(`${r}_${d.address}_getCoinConfig`,d,864e5),c.push({...d})}),this.updateCache(n,c,864e5),c}buildCoinConfig(e,t=!0){let r=Ie(e);r=r.value.fields;let n={...r};return n.id=Pe(e),n.address=R(r.coin_type.fields.name).full_address,r.pyth_id&&(n.pyth_id=ut(r.pyth_id)),this.transformExtensions(n,r.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,r=3e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:r,baseCoinType:n,quoteCoinType:s}){let i=new j,o=E.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",i);i.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[n,s],arguments:[i.object(this.sdk.sdkOptions.deepbook.registry_id),i.pure.u64(e),i.pure.u64(t),i.pure.u64(r),o]});try{let a=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:i});if(a.effects.status.status==="success")return i;if(a.effects.status.status==="failure"&&a.effects.status.error&&a.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(a){throw a instanceof Error?a:new Error(String(a))}return i}};import{CLOCK_ADDRESS as ge,CoinAssist as Fe}from"@cetusprotocol/common-sdk";import{bcs as y}from"@mysten/sui/bcs";import{Transaction as O}from"@mysten/sui/transactions";import{SUI_CLOCK_OBJECT_ID as v,normalizeSuiAddress as me}from"@mysten/sui/utils";var Vr=({totalAssetsValue:u,totalDebtValue:e})=>l(e).eq(0)||l(u).eq(0)?"0":l(u).div(l(e)).toString(),Ue=u=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=u.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:c}=u.value.fields.risk_ratios.fields;return{id:u.id.id,name:u.name,base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s,liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:c}},$e=(u,e)=>{let{deposit_coin_type:t}=e,r=u.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=u.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:c}=u.protocol_fees.fields,{total_supply:p,total_borrow:d}=u.state.fields,g=l(o).sub(p).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:p,total_borrow:d,available_supply:g,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:c}};import{SuiPriceServiceConnection as gt,SuiPythClient as mt}from"@pythnetwork/pyth-sui-js";var pe=10n;function _t(u,e){if(!pe)throw new Error("oraclePriceMultiplierDecimal is required");if(u===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(pe- -e);return u*t}return u/10n**(e+pe)}var H=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;_cache={};constructor(e){this._sdk=e,this.connection=new gt(this.sdk.sdkOptions.pythUrl),this.suiPythClient=new mt(this._sdk.fullClient,this._sdk.sdkOptions.margin_utils.pyth_state_id,this._sdk.sdkOptions.margin_utils.wormhole_state_id)}get sdk(){return this._sdk}async updatePythPriceIDs(e,t){let r=null,n=null;try{r=await this.connection.getPriceFeedsUpdateData(e)}catch(o){n=o}if(r==null)throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: ${n?.message}`);let s=[];try{s=await this.suiPythClient.updatePriceFeeds(t,r,e)}catch(o){throw new Error(`All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes in the pythUrls parameter when initializing AggregatorClient, for example: new AggregatorClient({ pythUrls: ["https://your-pyth-node-url"] }). Detailed error: ${o}`)}let i=new Map;for(let o=0;o<e.length;o++)i.set(e[o],s[o]);return i}priceCheck(e,t=60){let r=Math.floor(Date.now()/1e3);if(!(Math.abs(r-e.last_update_time)>t))return e}async getLatestPrice(e,t=!1){let r={},n=[];if(t?e.forEach(o=>{let a=this._sdk.getCache(`getLatestPrice_${o.coinType}`);a&&this.priceCheck(a,60)?r[o.coinType]=a:n.push(o.coinType)}):n=e.map(o=>o.coinType),n.length===0)return r;let s=e.map(o=>o.feed);return(await this.connection.getLatestPriceUpdates(s))?.parsed?.forEach((o,a)=>{let c=o.price;if(c){let{price:p,expo:d}=c,g=l(p).mul(l(10).pow(l(d))).toString(),m={coin_type:e[a].coinType,price:g,oracle_price:0n,last_update_time:c.publish_time};m.oracle_price=_t(BigInt(p),BigInt(d)),r[n[a]]=m,this._sdk.updateCache(`getLatestPrice_${m.coin_type}`,m)}}),r}};var ee=class{_sdk;pythPrice;_deep;_cache={};constructor(e){if(!e)throw new Error("SDK instance is required");this._sdk=e,this.pythPrice=new H(e),this._deep=e.sdkOptions.network==="mainnet"?ve:Ee}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareMarginManager(e,t=new O){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");if(!e.baseCoin?.coinType||!e.quoteCoin?.coinType)throw new Error("Base and quote coin types are required");let{baseCoin:r,quoteCoin:n}=e;try{let{margin_manager:s,initializer:i}=this.createMarginManager(e,t);return this.shareMarginManager({marginManager:s,initializer:i,baseCoin:r,quoteCoin:n},t),{tx:t,margin_manager:s,initializer:i}}catch(s){throw new Error(`Failed to create and share margin manager: ${s instanceof Error?s.message:String(s)}`)}}createMarginManager(e,t=new O){if(!e)throw new Error("Pool info is required");if(!e.id)throw new Error("Pool ID is required");let{id:r,baseCoin:n,quoteCoin:s}=e;try{let[i,o]=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::create_margin_manager`,arguments:[t.object(this.sdk.sdkOptions.margin_utils.versioned_id),t.object(r),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),t.object(v)],typeArguments:[n.coinType,s.coinType]});return{tx:t,margin_manager:i,initializer:o}}catch(i){throw new Error(`Failed to create margin manager: ${i instanceof Error?i.message:String(i)}`)}}shareMarginManager({marginManager:e,initializer:t,baseCoin:r,quoteCoin:n},s=new O){try{return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::share_margin_manager`,arguments:[e,t],typeArguments:[r.coinType,n.coinType]}),s}catch(i){throw new Error(`Failed to share margin manager: ${i instanceof Error?i.message:String(i)}`)}}async getBalanceManagerByMarginManager(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");let t=`
2
2
  query Events($filter: EventFilter) {
3
3
  events(filter: $filter) {
4
4
  nodes {
@@ -12,4 +12,4 @@ var Ve=Object.defineProperty;var Ne=(c,e,t)=>e in c?Ve(c,e,{enumerable:!0,config
12
12
  }
13
13
  }
14
14
  }
15
- `,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(i=>i?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===e).map(s=>s?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get quote balance: ${i instanceof Error?i.message:String(i)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getPoolMarginManagerBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let s=new T,i=r===this.deepCoin.coinType,o=n===this.deepCoin.coinType,a=i||o;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),a||s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let u=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!u.results||!u.results[0]||!u.results[0].returnValues||!u.results[0].returnValues[0])throw new Error(`Transaction failed: ${u.effects?.status?.error||"Unknown error"}`);let g=k.U64.parse(new Uint8Array(u.results[0].returnValues[0][0])),d=k.U64.parse(new Uint8Array(u.results[1].returnValues[0][0])),p=a?i?g:d:k.U64.parse(new Uint8Array(u.results[2].returnValues[0][0]));return{[r]:g.toString(),[n]:d.toString(),[this.deepCoin.coinType]:p.toString()}}catch(u){throw new Error(`Failed to getPoolMarginManagerBalance: ${u instanceof Error?u.message:String(u)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new T;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||i.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(i){throw new Error(`Failed to get borrowed shares: ${i instanceof Error?i.message:String(i)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:s,baseMarginPool:i,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:u,quotePriceFeedObjectId:g})=>d=>{d.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(u),d.object(g),d.object(s),d.object(i),d.object(o),d.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new T){let{account:r,marginManager:n,baseCoin:s,quoteCoin:i,pool:o,baseMarginPool:a,quoteMarginPool:u,decimals:g=6}=e;if(!r||!n||!o||!a||!u)throw new Error("All required parameters must be provided");if(!s?.feed||!i?.feed)throw new Error("Base and quote coin feeds are required");if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),p=d.get(s.feed),b=d.get(i.feed);if(!p||!b)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:p,quotePriceFeedObjectId:b}));let m=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!m.results||!m.results[0]||!m.results[0].returnValues||m.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${m.effects?.status?.error||"Unknown error"}`);let _=$e(k.Address.parse(new Uint8Array(m.results[0].returnValues[0][0]))),w=$e(k.Address.parse(new Uint8Array(m.results[0].returnValues[1][0]))),y=Number(k.U64.parse(new Uint8Array(m.results[0].returnValues[2][0])))/1e9,C=this.#e(BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[3][0]))),s.scalar,g),h=this.#e(BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[4][0]))),i.scalar,g),O=this.#e(BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[5][0]))),s.scalar,g),S=this.#e(BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[6][0]))),i.scalar,g),A=k.U64.parse(new Uint8Array(m.results[0].returnValues[7][0])),B=Number(k.u8().parse(new Uint8Array(m.results[0].returnValues[8][0]))),M=k.U64.parse(new Uint8Array(m.results[0].returnValues[9][0])),I=Number(k.u8().parse(new Uint8Array(m.results[0].returnValues[10][0]))),q=BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[11][0]))),D=BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[12][0]))),J=BigInt(k.U64.parse(new Uint8Array(m.results[0].returnValues[13][0])));return{managerId:_,deepbookPoolId:w,riskRatio:y,baseAsset:C,quoteAsset:h,baseDebt:O,quoteDebt:S,basePythPrice:A.toString(),basePythDecimals:B,quotePythPrice:M.toString(),quotePythDecimals:I,currentPrice:q,lowestTriggerAbovePrice:D,highestTriggerBelowPrice:J}}catch(d){throw new Error(`Failed to get manager state: ${d instanceof Error?d.message:String(d)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:s,tx:i=new T}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[i.object(t),i.object(r)],typeArguments:[n.coinType,s.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],u=o.results[0].returnValues[1][0];if(!n.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let g=k.U64.parse(new Uint8Array(a)),d=k.U64.parse(new Uint8Array(u));return{baseAsset:g.toString(),quoteAsset:d.toString(),tx:i}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:s,quoteMarginPool:i}){if(!e||!t||!r||!n||!s||!i)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),u=!!l(o).gt(l(a)),g=u?s:i,d=u?o:a,p=new T;p.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[p.object(g),p.pure.u64(BigInt(d)),p.object.clock()],typeArguments:[u?r:n]});let b=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:p});if(!b.results||!b.results[0]||!b.results[0].returnValues||!b.results[0].returnValues[0])throw new Error(`Transaction failed: ${b.effects?.status?.error||"Unknown error"}`);let m=k.U64.parse(new Uint8Array(b.results[0].returnValues[0][0]));return u?{baseBorrowedAmount:m.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:m.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:s},i=new T){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Ue.buildCoinWithBalance(BigInt(n),s,i),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],i),u=a.get(t.feed),g=a.get(r.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?i.object(e):e,i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(u),i.object(g),o,i.object(v)],typeArguments:[t.coinType,r.coinType,s]}),i}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:s,quoteCoin:i,pool:o,amount:a,withdrawCoinType:u},g=new T){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!s.feed||!i.feed)throw new Error("Base and quote coin feeds are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],g),p=d.get(s.feed),b=d.get(i.feed);if(!p||!b)throw new Error("Failed to get price feed object IDs");let m=g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[g.object(this._sdk.sdkOptions.margin_utils.global_config_id),g.object(this._sdk.sdkOptions.margin_utils.versioned_id),g.object(t),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(r),g.object(n),g.object(p),g.object(b),g.object(o),g.pure.u64(BigInt(a)),g.object(v)],typeArguments:[s.coinType,i.coinType,u]});return g.transferObjects([m],e),g}catch(d){throw new Error(`Failed to withdraw: ${d instanceof Error?d.message:String(d)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new T){if(!e||!t||!s)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),g=a.get(n.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(g),o.object(s),o.pure.u64(BigInt(i)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new T){if(!e||!t||!s)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),u=a.get(r.feed),g=a.get(n.feed);if(!u||!g)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(u),o.object(g),o.object(s),o.pure.u64(BigInt(i)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new T){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:r.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new T){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:n.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:s,isBase:i,amount:o},a=new T){try{let u=this.sdk.senderAddress,g,d=o;o||(g=await this.getBorrowedAmount({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),d=i?g.baseBorrowedAmount:g.quoteBorrowedAmount);let p,b={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let m=await this.getBaseBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});p=l(d).sub(m).toString()}else{let m=await this.getQuoteBalance({account:u,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});p=l(d).sub(m).toString()}l(p).gt(0)&&await this.deposit({...b,amount:p},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${i?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(i?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v)],typeArguments:[n.coinType,s.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:s,isBid:i,payWithDeep:o,exactBase:a},u=new T){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!s||BigInt(W(s,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:g,baseCoin:d,quoteCoin:p}=t;if(d.decimals===void 0||p.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?u.object(e):e,u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(g),u.pure.u8(r),u.pure.u64(n),u.pure.bool(i),u.pure.bool(o),u.pure.bool(a===void 0?!i:a),u.pure.u64(s),u.object(v)],typeArguments:[d.coinType,p.coinType]}),u}catch(b){throw new Error(`Failed to place market order: ${b instanceof Error?b.message:String(b)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:u=Date.now()+31536e8},g=new T){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!s||!i)throw new Error("Price and quantity are required");let{id:d,baseCoin:p,quoteCoin:b}=t;if(p.decimals===void 0||b.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let m=BigInt(l(s).mul(10**(b.decimals-p.decimals+9)).toString()),_=BigInt(W(i,p.decimals));if(m<=0n||_<=0n)throw new Error("Price and quantity must be greater than zero");return g.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[g.object(this.sdk.sdkOptions.margin_utils.global_config_id),g.object(this.sdk.sdkOptions.margin_utils.versioned_id),g.object(e),g.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),g.object(d),g.pure.u8(r),g.pure.u8(n),g.pure.u64(m),g.pure.u64(_),g.pure.bool(o),g.pure.bool(a),g.pure.u64(u),g.object(v)],typeArguments:[p.coinType,b.coinType]}),g}catch(m){throw new Error(`Failed to place limit order: ${m instanceof Error?m.message:String(m)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},s=new T){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let i=BigInt(W(n,t.baseCoin.decimals));if(i<=0n)throw new Error("New quantity must be greater than zero");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t.id),s.pure.u128(r),s.pure.u64(i),s.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to modify order: ${i instanceof Error?i.message:String(i)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new T){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(s){throw new Error(`Failed to cancel order: ${s instanceof Error?s.message:String(s)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new T){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:s,priceInput:i,quantity:o,isBid:a,payWithDeep:u,expirationTimestamp:g},d=new T){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(t.id),d.object(r),d.pure.u8(n),d.pure.u8(s),d.pure.u64(i),d.pure.u64(o),d.pure.bool(a),d.pure.bool(u),d.pure.u64(g),d.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),d}catch(p){throw new Error(`Failed to place reduce only limit order: ${p instanceof Error?p.message:String(p)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:s,isBid:i,payWithDeep:o},a=new T){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(s),a.pure.bool(i),a.pure.bool(o),a.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,i?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(u){throw new Error(`Failed to place reduce only market order: ${u instanceof Error?u.message:String(u)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new T,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let s=new T,i=t[n];if(i.margin_manager_id){let o=await s.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[s.object(i.margin_manager_id)],typeArguments:[i.baseCoin.coinType,i.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(i,this.sdk.senderAddress,o,void 0,!0,s);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new T,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new T,{supplierCap:s}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:s,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([s],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:s}){let i=s??new T;if(!t)throw new Error("Either supplierCap must be provided");let o=Ue.buildCoinWithBalance(BigInt(n),r,i);return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),o,i.pure.option("address","0x0"),i.object(v)]}),i}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:s,withdrawAll:i,tx:o=new T}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?null:o.pure.u64(r)}),o.object(v)]});return s?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new T,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new T;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(k.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,s=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:s}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(s=>s.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let s=0;s<r.length;s++){let i=r[s].data.content.fields;n.push(Ie(i))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],s=[];for(let a=0;a<r.length;a++){let u=r[a].data.content.fields;s.push(u.value),n.push({deposit_coin_type:u.name.fields.name,id:u.id.id})}let i=await this.sdk.fullClient.batchGetObjects(s,{showContent:!0}),o=[];for(let a=0;a<i.length;a++){let u=i[a].data.content.fields;o.push(De(u,n[a]))}return o}async getBaseQuantityIn(e,t,r,n=.01){let s=new T;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=k.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),g=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:l(t).sub(a.toString()).toString(),quantityInLeft:l(o.toString()).add(g.takerFee).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getQuoteQuantityIn(e,t,r,n=.01){let s=new T;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_quote_quantity_out":"::pool::get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=k.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=k.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),u=k.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),g=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:l(t).sub(o).toString(),quantityInLeft:l(a.toString()).add(l(g.takerFee)).mul(l(1+n)).ceil().toString(),deep_fee_amount:u.toString()}}async getBaseQuantityOutInput(e,t,r){let n=new T;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=k.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=k.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=k.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t,r){let n=new T;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=k.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=k.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=k.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new T,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new T){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),s=e/n,i=e%n;if(i===0n)return s.toString();let o=t.toString().length-1,g=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return g?`${s}.${g}`:s.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,s=r.config.fields,i=s.interest_config.fields,o=s.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(i.base_rate),base_slope:BigInt(i.base_slope),optimal_utilization:BigInt(i.optimal_utilization),excess_slope:BigInt(i.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}async batchGetBorrowedShares({account:e,marginManagerList:t}){let r=new T;return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(s.marginManagerId)],typeArguments:[s.baseCoinType,s.quoteCoinType]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r})).results.map((s,i)=>{let o=k.U64.parse(new Uint8Array(s.returnValues[0][0])),a=k.U64.parse(new Uint8Array(s.returnValues[1][0]));return{marginManagerId:t[i].marginManagerId,baseBorrowedShare:o,quoteBorrowedShare:a}})}async betchGetOpenOrders({account:e,marginManagerList:t},r=new T,n=!1){t.forEach(m=>{let _=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(_)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[r.object(m.poolId),_],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[r.object(m.poolId),_],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((m,_)=>({marginManagerId:t[_].marginManagerId,...m?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(m=>m?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=k.struct("VecSet",{constants:k.vector(k.U128)}),u=[];o.forEach((m,_)=>{let w=a.parse(new Uint8Array(m.returnValues[0][0])).constants;w.length>0&&w.forEach(y=>{u.push({pool:{pool_id:t[_].poolId,baseCoinType:t[_].baseCoinType,quoteCoinType:t[_].quoteCoinType},marginManagerId:t[_].marginManagerId,orderId:y})})});let g=await this.sdk.DeepbookUtils.getOrderInfoList(u,e)||[],d=s.results.filter(m=>m?.returnValues?.length===3),p=[];d.forEach((m,_)=>{p.push({marginManagerId:t[_].marginManagerId,base:k.U64.parse(new Uint8Array(m.returnValues[0][0])),quote:k.U64.parse(new Uint8Array(m.returnValues[1][0])),deep:k.U64.parse(new Uint8Array(m.returnValues[2][0]))})});let b=[];return u.forEach((m,_)=>{let w=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId)),y=g.find(C=>C.order_id===m.orderId)||{};b.push({...m,...y,price:w.price.toString(),isBid:w.isBid})}),{openOrders:b,settledBalances:i,lockedBalances:p}}async getSingleMarginManagerOpenOrders({account:e,marginManagerId:t,poolId:r,baseCoinType:n,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){let a=new T,u=a.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[a.object(t)],typeArguments:[n,s]});a.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[a.object(r),u],typeArguments:[n,s]});let g=k.struct("VecSet",{constants:k.vector(k.U128)}),p=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),b=g.parse(new Uint8Array(p.returnValues[0][0])).constants,m=[];b.forEach(h=>{m.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let _=m?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(m,e)||[]:[],w=[];m.forEach((h,O)=>{let S=this.sdk.DeepbookUtils.decodeOrderId(BigInt(h.orderId)),A=_.find(B=>B.order_id===h.orderId)||{};w.push({...h,...A,price:S.price.toString(),isBid:S.isBid})});let y={marginManagerId:t,base:"0",quote:"0",deep:"0"};if(_?.length>0){let h=new T,O=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[h.object(r),O],typeArguments:[n,s]});let A=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h})).results.find(B=>B?.returnValues?.length===3);y={...y,base:k.U64.parse(new Uint8Array(A.returnValues[0][0])),quote:k.U64.parse(new Uint8Array(A.returnValues[1][0])),deep:k.U64.parse(new Uint8Array(A.returnValues[2][0]))}}let C={base:"0",quote:"0",deep:"0"};try{let h=new T,O=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[h.object(r),O],typeArguments:[n,s]});let S=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h});C={marginManagerId:t,...C,...S?.events?.parsedJson?.account?.settled_balances||{}}}catch{}return{openOrders:w,settledBalances:[C],lockedBalances:[y]}}async getAllPosRelevantData({account:e,marginManagerList:t}){try{let{openOrders:r,settledBalances:n,lockedBalances:s}=t?.length>1?await this.betchGetOpenOrders({account:e,marginManagerList:t}):await this.getSingleMarginManagerOpenOrders({account:e,...t[0]}),i=await this.batchGetBorrowedShares({account:e,marginManagerList:t}),o=new T,a=0,u=[];t.forEach(p=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[a]={type:"base_balance",marginManagerId:p.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(p.marginManagerId)],typeArguments:[p.baseCoinType,p.quoteCoinType]}),u[a]={type:"quote_balance",marginManagerId:p.marginManagerId},a++;let b=i?.find(m=>m.marginManagerId===p.marginManagerId);if(b&&(Number(b.baseBorrowedShare)>0||Number(b.quoteBorrowedShare)>0)){let m=b.baseBorrowedShare,_=b.quoteBorrowedShare,w=!!l(m).gt(l(_)),y=w?p.baseMarginPool:p.quoteMarginPool,C=w?m:_;o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[o.object(y),o.pure.u64(BigInt(C)),o.object.clock()],typeArguments:[w?p?.baseCoinType:p?.quoteCoinType]}),u[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:p.marginManagerId},a++}});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),d=Object.fromEntries(t.map(p=>[p.marginManagerId,{...p,quote_balance:"0",base_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return g?.results?.forEach((p,b)=>{let m=u[b],_=k.U64.parse(new Uint8Array(p.returnValues[0][0]));d[m.marginManagerId]={...d[m.marginManagerId],[m.type]:_}}),r.forEach(p=>{d[p.marginManagerId].open_orders.push(p)}),n.forEach(p=>{d[p.marginManagerId].settled_balances=p}),s.forEach(p=>{d[p.marginManagerId].locked_balances=p}),d}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}};import{SuiClient as bt}from"@mysten/sui/client";var te=class extends bt{async queryEventsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],s=!0,i=r==="all",o=i?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:i?null:r.limit});a.data?(n=[...n,...a.data],s=a.hasNextPage,o=a.nextCursor):s=!1}while(i&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let s=0;s<Math.ceil(e.length/r);s++){let i=await this.multiGetObjects({ids:e.slice(s*r,r*(s+1)),options:t});n=[...n,...i]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};import Re from"decimal.js";Re.config({precision:64,rounding:Re.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var F=1000000000n,_t=365n*24n*60n*60n*1000n;function ht(c,e){return e===0n?0n:c*F/e}function yt(c,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(c<n)return t+c*r/F;{let i=c-n,o=n*r/F,a=i*s/F;return t+o+a}}function Fe(c,e){let t=c*e,r=t/F;return t%F>0n?r+1n:r}function ft(c,e,t,r){let n=e.borrow_shares===0n?F:e.total_borrow*F/e.borrow_shares,s=Fe(c,n),i=ht(e.total_borrow,e.total_supply),o=yt(i,t),a=r-e.last_update_timestamp,u=e.total_borrow*o/F*a/_t,g=e.borrow_shares===0n?0n:Fe(u,c*F/e.borrow_shares),d=s+g;return{confirmedDebt:s,estimatedInterest:g,totalDebt:d,annualInterestRate:o}}function sn(c,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=ft(c,e,t,s);return i}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new H(this),this._graphqlClient=new kt({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],s=null,i=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(i,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:s}):this.fullClient.getAllCoins({owner:e,cursor:s}));if(a.data.forEach(u=>{BigInt(u.balance)>0&&n.push({coinAddress:R(u.coinType).source_address,coinObjectId:u.coinObjectId,balance:BigInt(u.balance)})}),s=a.nextCursor,!a.hasNextPage)break}return this.updateCache(i,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=Q(r),n.value=t):n=new K(t,Q(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var jn="0x0000000000000000000000000000000000000000000000000000000000000006",Bn="pool_script",En="pool_script_v2",vn="router",Mn="router_with_partner",qn="fetcher_script",Pn="expect_swap",In="utils",Dn="0x1::coin::CoinInfo",Un="0x1::coin::CoinStore",$n="custodian_v2",Rn="clob_v2",Fn="endpoints_v2",Vn=c=>{if(typeof c=="string"&&c.startsWith("0x"))return"object";if(typeof c=="number"||typeof c=="bigint")return"u64";if(typeof c=="boolean")return"bool";throw new Error(`Unknown type for value: ${c}`)};var wt=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(wt||{}),Ct=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(Ct||{});var es=re;export{jn as CLOCK_ADDRESS,K as CachedContent,re as CetusClmmSDK,Pn as ClmmExpectSwapModule,qn as ClmmFetcherModule,Bn as ClmmIntegratePoolModule,En as ClmmIntegratePoolV2Module,vn as ClmmIntegrateRouterModule,Mn as ClmmIntegrateRouterWithPartnerModule,In as ClmmIntegrateUtilsModule,E as CoinAssist,Dn as CoinInfoAddress,Un as CoinStoreAddress,le as DEEP_SCALAR,Nt as DEFAULT_GAS_BUDGET_FOR_MERGE,Vt as DEFAULT_GAS_BUDGET_FOR_SPLIT,Gt as DEFAULT_GAS_BUDGET_FOR_STAKE,xt as DEFAULT_GAS_BUDGET_FOR_TRANSFER,Lt as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,Qt as DEFAULT_NFT_TRANSFER_GAS_FEE,Rn as DeepbookClobV2Moudle,$n as DeepbookCustodianV2Moudle,Fn as DeepbookEndpointsV2Moudle,X as DeepbookUtilsModule,$ as FLOAT_SCALAR,F as FLOAT_SCALING,Kt as GAS_SYMBOL,ae as GAS_TYPE_ARG,ye as GAS_TYPE_ARG_LONG,ee as MarginUtilsModule,Ut as NORMALIZED_SUI_COIN_TYPE,wt as OrderType,te as RpcModule,zt as SUI_SYSTEM_STATE_OBJECT_ID,Ct as SelfMatchingOption,N as TransactionUtil,_t as YEAR_MS,me as addHexPrefix,nr as asIntN,rr as asUintN,St as bufferToHex,ke as cacheTime1min,x as cacheTime24h,we as cacheTime5min,sn as calc100PercentRepay,ft as calcDebtDetail,yt as calcInterestRate,ht as calcUtilizationRate,Fr as calculateRiskRatio,Ot as checkAddress,_e as composeType,l as d,ce as decimalsMultiplier,es as default,It as extractAddressFromType,R as extractStructTagFromType,Dt as fixCoinType,L as fixDown,Ze as fixSuiObjectId,G as fromDecimalsAmount,Vn as getDefaultSuiInputType,Q as getFutureTime,de as getMoveObject,st as getMoveObjectType,dr as getMovePackageContent,et as getObjectDeletedResponse,mr as getObjectDisplay,qe as getObjectFields,Me as getObjectId,tt as getObjectNotExistsResponse,pr as getObjectOwner,gr as getObjectPreviousTransactionDigest,ve as getObjectReference,lr as getObjectType,ur as getObjectVersion,z as getSuiObjectData,br as hasPublicTransfer,jt as hexToNumber,Bt as hexToString,Pt as isSortedSymbols,rt as isSuiObjectResponse,ue as maxDecimal,Fe as mulRoundUp,ie as normalizeCoinType,oe as patchFixSuiObjectId,fr as printTransaction,ne as removeHexPrefix,sr as secretKeyToEd25519Keypair,ir as secretKeyToSecp256k1Keypair,At as shortAddress,Le as shortString,Se as sleepTime,Ge as toBuffer,W as toDecimalsAmount,Ke as utf8to16,De as wrapDeepBookMarginPoolInfo,Ie as wrapDeepBookPoolInfo};
15
+ `,r={filter:{sender:e,type:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::BalanceManagerEvent`}};try{let n=await this.sdk.graphqlClient.query({query:t,variables:r});return n?.data?.events?.nodes?n.data.events.nodes.map(i=>i?.contents?.json):[]}catch(n){throw new Error(`Failed to query balance managers: ${n instanceof Error?n.message:String(n)}`)}}async getMarginManagerByAccount(e){if(!e||typeof e!="string")throw new Error("Valid account address is required");try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::CreateMarginManagerEvent`}))?.data||[]).filter(s=>s.parsedJson?.owner===e).map(s=>s?.parsedJson)}catch(t){throw new Error(`Failed to get margin managers by account: ${t instanceof Error?t.message:String(t)}`)}}async getBaseBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getQuoteBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get quote balance: ${i instanceof Error?i.message:String(i)}`)}}async getDeepBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);return y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])).toString()}catch(i){throw new Error(`Failed to get base balance: ${i instanceof Error?i.message:String(i)}`)}}async getPoolMarginManagerBalance({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManagers, baseCoinType, quoteCoinType) are required");let s=new O,i=r===this.deepCoin.coinType,o=n===this.deepCoin.coinType,a=i||o;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[s.object(t)],typeArguments:[r,n]}),a||s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::deep_balance`,arguments:[s.object(t)],typeArguments:[r,n]});let c=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!c.results||!c.results[0]||!c.results[0].returnValues||!c.results[0].returnValues[0])throw new Error(`Transaction failed: ${c.effects?.status?.error||"Unknown error"}`);let p=y.U64.parse(new Uint8Array(c.results[0].returnValues[0][0])),d=y.U64.parse(new Uint8Array(c.results[1].returnValues[0][0])),g=a?i?p:d:y.U64.parse(new Uint8Array(c.results[2].returnValues[0][0]));return{[r]:p.toString(),[n]:d.toString(),[this.deepCoin.coinType]:g.toString()}}catch(c){throw new Error(`Failed to getPoolMarginManagerBalance: ${c instanceof Error?c.message:String(c)}`)}}async getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}){if(!e||!t||!r||!n)throw new Error("All parameters (account, marginManager, baseCoinType, quoteCoinType) are required");let s=new O;try{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[s.object(t)],typeArguments:[r,n]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||i.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.U64.parse(new Uint8Array(i.results[0].returnValues[1][0]));return{baseBorrowedShare:o,quoteBorrowedShare:a}}catch(i){throw new Error(`Failed to get borrowed shares: ${i instanceof Error?i.message:String(i)}`)}}managerState=({account:e,marginManager:t,baseCoin:r,quoteCoin:n,pool:s,baseMarginPool:i,quoteMarginPool:o,decimals:a=6,basePriceFeedObjectId:c,quotePriceFeedObjectId:p})=>d=>{d.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[d.object(t),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(c),d.object(p),d.object(s),d.object(i),d.object(o),d.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new O){let{account:r,marginManager:n,baseCoin:s,quoteCoin:i,pool:o,baseMarginPool:a,quoteMarginPool:c,decimals:p=6}=e;if(!r||!n||!o||!a||!c)throw new Error("All required parameters must be provided");if(!s?.feed||!i?.feed)throw new Error("Base and quote coin feeds are required");if(!s.scalar||!i.scalar)throw new Error("Base and quote coin scalars are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),g=d.get(s.feed),_=d.get(i.feed);if(!g||!_)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:g,quotePriceFeedObjectId:_}));let m=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!m.results||!m.results[0]||!m.results[0].returnValues||m.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${m.effects?.status?.error||"Unknown error"}`);let b=me(y.Address.parse(new Uint8Array(m.results[0].returnValues[0][0]))),w=me(y.Address.parse(new Uint8Array(m.results[0].returnValues[1][0]))),f=Number(y.U64.parse(new Uint8Array(m.results[0].returnValues[2][0])))/1e9,C=this.#e(BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[3][0]))),s.scalar,p),h=this.#e(BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[4][0]))),i.scalar,p),A=this.#e(BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[5][0]))),s.scalar,p),S=this.#e(BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[6][0]))),i.scalar,p),T=y.U64.parse(new Uint8Array(m.results[0].returnValues[7][0])),B=Number(y.u8().parse(new Uint8Array(m.results[0].returnValues[8][0]))),M=y.U64.parse(new Uint8Array(m.results[0].returnValues[9][0])),I=Number(y.u8().parse(new Uint8Array(m.results[0].returnValues[10][0]))),q=BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[11][0]))),D=BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[12][0]))),J=BigInt(y.U64.parse(new Uint8Array(m.results[0].returnValues[13][0])));return{managerId:b,deepbookPoolId:w,riskRatio:f,baseAsset:C,quoteAsset:h,baseDebt:A,quoteDebt:S,basePythPrice:T.toString(),basePythDecimals:B,quotePythPrice:M.toString(),quotePythDecimals:I,currentPrice:q,lowestTriggerAbovePrice:D,highestTriggerBelowPrice:J}}catch(d){throw new Error(`Failed to get manager state: ${d instanceof Error?d.message:String(d)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:s,tx:i=new O}){if(!e||!t||!r)throw new Error("Account, marginManager, and pool are required");if(!n?.coinType||!s?.coinType)throw new Error("Base and quote coin types are required");try{i.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::calculate_assets`,arguments:[i.object(t),i.object(r)],typeArguments:[n.coinType,s.coinType]});let o=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:i});if(!o.results||!o.results[0]||!o.results[0].returnValues||o.results[0].returnValues.length<2)throw new Error(`Transaction failed: ${o.effects?.status?.error||"Unknown error"}`);let a=o.results[0].returnValues[0][0],c=o.results[0].returnValues[1][0];if(!n.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let p=y.U64.parse(new Uint8Array(a)),d=y.U64.parse(new Uint8Array(c));return{baseAsset:p.toString(),quoteAsset:d.toString(),tx:i}}catch(o){throw new Error(`Failed to calculate assets: ${o instanceof Error?o.message:String(o)}`)}}async getBorrowedAmount({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n,baseMarginPool:s,quoteMarginPool:i}){if(!e||!t||!r||!n||!s||!i)throw new Error("All parameters are required");try{let{baseBorrowedShare:o,quoteBorrowedShare:a}=await this.getBorrowedShares({account:e,marginManager:t,baseCoinType:r,quoteCoinType:n}),c=!!l(o).gt(l(a)),p=c?s:i,d=c?o:a,g=new O;g.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[g.object(p),g.pure.u64(BigInt(d)),g.object.clock()],typeArguments:[c?r:n]});let _=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:g});if(!_.results||!_.results[0]||!_.results[0].returnValues||!_.results[0].returnValues[0])throw new Error(`Transaction failed: ${_.effects?.status?.error||"Unknown error"}`);let m=y.U64.parse(new Uint8Array(_.results[0].returnValues[0][0]));return c?{baseBorrowedAmount:m.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:m.toString()}}catch(o){throw new Error(`Failed to get borrowed amount: ${o instanceof Error?o.message:String(o)}`)}}async deposit({marginManager:e,baseCoin:t,quoteCoin:r,amount:n,depositCoinType:s},i=new O){if(!e)throw new Error("Margin manager is required");if(!t?.coinType||!r?.coinType)throw new Error("Base and quote coin types are required");if(!n||BigInt(n)<=0n)throw new Error("Valid deposit amount is required");if(!t.feed||!r.feed)throw new Error("Base and quote coin feeds are required");try{let o=Fe.buildCoinWithBalance(BigInt(n),s,i),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],i),c=a.get(t.feed),p=a.get(r.feed);if(!c||!p)throw new Error("Failed to get price feed object IDs");return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::deposit`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?i.object(e):e,i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(c),i.object(p),o,i.object(v)],typeArguments:[t.coinType,r.coinType,s]}),i}catch(o){throw new Error(`Failed to deposit: ${o instanceof Error?o.message:String(o)}`)}}async withdraw({account:e,marginManager:t,baseMarginPool:r,quoteMarginPool:n,baseCoin:s,quoteCoin:i,pool:o,amount:a,withdrawCoinType:c},p=new O){if(!e||!t||!r||!n||!o)throw new Error("All required parameters must be provided");if(!s?.coinType||!i?.coinType)throw new Error("Base and quote coin types are required");if(!a||BigInt(a)<=0n)throw new Error("Valid withdraw amount is required");if(!s.feed||!i.feed)throw new Error("Base and quote coin feeds are required");try{let d=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],p),g=d.get(s.feed),_=d.get(i.feed);if(!g||!_)throw new Error("Failed to get price feed object IDs");let m=p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[p.object(this._sdk.sdkOptions.margin_utils.global_config_id),p.object(this._sdk.sdkOptions.margin_utils.versioned_id),p.object(t),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(r),p.object(n),p.object(g),p.object(_),p.object(o),p.pure.u64(BigInt(a)),p.object(v)],typeArguments:[s.coinType,i.coinType,c]});return p.transferObjects([m],e),p}catch(d){throw new Error(`Failed to withdraw: ${d instanceof Error?d.message:String(d)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new O){if(!e||!t||!s)throw new Error("Margin manager, base margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),c=a.get(r.feed),p=a.get(n.feed);if(!c||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_base`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(c),o.object(p),o.object(s),o.pure.u64(BigInt(i)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow base: ${a instanceof Error?a.message:String(a)}`)}}async borrowQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new O){if(!e||!t||!s)throw new Error("Margin manager, quote margin pool, and pool are required");if(!r?.coinType||!n?.coinType)throw new Error("Base and quote coin types are required");if(!i||BigInt(i)<=0n)throw new Error("Valid borrow amount is required");if(!r.feed||!n.feed)throw new Error("Base and quote coin feeds are required");try{let a=await this.pythPrice.updatePythPriceIDs([r.feed,n.feed],o),c=a.get(r.feed),p=a.get(n.feed);if(!c||!p)throw new Error("Failed to get price feed object IDs");return o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::borrow_quote`,arguments:[o.object(this.sdk.sdkOptions.margin_utils.global_config_id),o.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?o.object(e):e,o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(t),o.object(c),o.object(p),o.object(s),o.pure.u64(BigInt(i)),o.object(v)],typeArguments:[r.coinType,n.coinType]}),o}catch(a){throw new Error(`Failed to borrow quote: ${a instanceof Error?a.message:String(a)}`)}}async repayBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new O){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, baseMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:r.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_base`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay base: ${a instanceof Error?a.message:String(a)}`)}}async repayQuote({marginManager:e,quoteMarginPool:t,baseCoin:r,quoteCoin:n,amount:s},i=new O){if(!e||!t||!r||!n)throw new Error("All required parameters (marginManager, quoteMarginPool, baseCoin, quoteCoin) are required");if(s&&BigInt(s)<=0n)throw new Error("Repay amount must be greater than zero if provided");let o={marginManager:e,baseCoin:r,quoteCoin:n,amount:s,depositCoinType:n.coinType};await this.deposit(o,i);try{return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::repay_quote`,arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),i.object.option({type:"u64",value:s?i.pure.u64(s):null}),i.object(v)],typeArguments:[r.coinType,n.coinType]}),i}catch(a){throw new Error(`Failed to repay quote: ${a instanceof Error?a.message:String(a)}`)}}async repay({marginManager:e,baseMarginPool:t,quoteMarginPool:r,baseCoin:n,quoteCoin:s,isBase:i,amount:o},a=new O){try{let c=this.sdk.senderAddress,p,d=o;o||(p=await this.getBorrowedAmount({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),d=i?p.baseBorrowedAmount:p.quoteBorrowedAmount);let g,_={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let m=await this.getBaseBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});g=l(d).sub(m).toString()}else{let m=await this.getQuoteBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});g=l(d).sub(m).toString()}l(g).gt(0)&&await this.deposit({..._,amount:g},a),a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::${i?"repay_base":"repay_quote"}`,arguments:[a.object(this._sdk.sdkOptions.margin_utils.global_config_id),a.object(this._sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(i?t:r),a.object.option({type:"u64",value:o?a.pure.u64(o):null}),a.object(v)],typeArguments:[n.coinType,s.coinType]})}catch{}return a}async placeMarginMarketOrder({marginManager:e,poolInfo:t,selfMatchingOption:r,quantity:n,amountLimit:s,isBid:i,payWithDeep:o,exactBase:a},c=new O){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!n||BigInt(W(n,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order quantity is required");if(!s||BigInt(W(s,t.baseCoin.decimals||0))<=0n)throw new Error("Valid order amount limit is required");let{id:p,baseCoin:d,quoteCoin:g}=t;if(d.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{return c.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_market_order`,arguments:[c.object(this.sdk.sdkOptions.margin_utils.global_config_id),c.object(this.sdk.sdkOptions.margin_utils.versioned_id),typeof e=="string"?c.object(e):e,c.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),c.object(p),c.pure.u8(r),c.pure.u64(n),c.pure.bool(i),c.pure.bool(o),c.pure.bool(a===void 0?!i:a),c.pure.u64(s),c.object(v)],typeArguments:[d.coinType,g.coinType]}),c}catch(_){throw new Error(`Failed to place market order: ${_ instanceof Error?_.message:String(_)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:c=Date.now()+31536e8},p=new O){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!s||!i)throw new Error("Price and quantity are required");let{id:d,baseCoin:g,quoteCoin:_}=t;if(g.decimals===void 0||_.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let m=BigInt(l(s).mul(10**(_.decimals-g.decimals+9)).toString()),b=BigInt(W(i,g.decimals));if(m<=0n||b<=0n)throw new Error("Price and quantity must be greater than zero");return p.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[p.object(this.sdk.sdkOptions.margin_utils.global_config_id),p.object(this.sdk.sdkOptions.margin_utils.versioned_id),p.object(e),p.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),p.object(d),p.pure.u8(r),p.pure.u8(n),p.pure.u64(m),p.pure.u64(b),p.pure.bool(o),p.pure.bool(a),p.pure.u64(c),p.object(v)],typeArguments:[g.coinType,_.coinType]}),p}catch(m){throw new Error(`Failed to place limit order: ${m instanceof Error?m.message:String(m)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},s=new O){if(!e||!t||!r||!n)throw new Error("All parameters (marginManager, poolInfo, orderId, newQuantity) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(t.baseCoin.decimals===void 0)throw new Error("Base coin decimals are required");try{let i=BigInt(W(n,t.baseCoin.decimals));if(i<=0n)throw new Error("New quantity must be greater than zero");return s.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::modify_margin_order`,arguments:[s.object(this.sdk.sdkOptions.margin_utils.global_config_id),s.object(this.sdk.sdkOptions.margin_utils.versioned_id),s.object(e),s.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),s.object(t.id),s.pure.u128(r),s.pure.u64(i),s.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),s}catch(i){throw new Error(`Failed to modify order: ${i instanceof Error?i.message:String(i)}`)}}cancelMarginOrder({marginManager:e,poolInfo:t,orderId:r},n=new O){if(!e||!t||!r)throw new Error("All parameters (marginManager, poolInfo, orderId) are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_margin_order`,arguments:[n.object(this.sdk.sdkOptions.margin_utils.global_config_id),n.object(this.sdk.sdkOptions.margin_utils.versioned_id),n.object(e),n.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),n.object(t.id),n.pure.u128(r),n.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),n}catch(s){throw new Error(`Failed to cancel order: ${s instanceof Error?s.message:String(s)}`)}}cancelAllMarginOrders({marginManager:e,poolInfo:t},r=new O){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");try{return r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::cancel_all_margin_orders`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.global_config_id),r.object(this.sdk.sdkOptions.margin_utils.versioned_id),r.object(e),r.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t.id),r.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]}),r}catch(n){throw new Error(`Failed to cancel all orders: ${n instanceof Error?n.message:String(n)}`)}}placeReduceOnlyLimitOrder({marginManager:e,poolInfo:t,marginPoolId:r,orderType:n,selfMatchingOption:s,priceInput:i,quantity:o,isBid:a,payWithDeep:c,expirationTimestamp:p},d=new O){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return d.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[d.object(this.sdk.sdkOptions.margin_utils.global_config_id),d.object(this.sdk.sdkOptions.margin_utils.versioned_id),d.object(e),d.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),d.object(t.id),d.object(r),d.pure.u8(n),d.pure.u8(s),d.pure.u64(i),d.pure.u64(o),d.pure.bool(a),d.pure.bool(c),d.pure.u64(p),d.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),d}catch(g){throw new Error(`Failed to place reduce only limit order: ${g instanceof Error?g.message:String(g)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:s,isBid:i,payWithDeep:o},a=new O){if(!e||!t)throw new Error("Margin manager and pool info are required");if(!t.id||!t.baseCoin?.coinType||!t.quoteCoin?.coinType)throw new Error("Pool info must contain valid id, baseCoin, and quoteCoin");if(!r)throw new Error("Margin pool id is required");try{return a.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_market_order`,arguments:[a.object(this.sdk.sdkOptions.margin_utils.global_config_id),a.object(this.sdk.sdkOptions.margin_utils.versioned_id),a.object(e),a.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),a.object(t.id),a.object(r),a.pure.u8(n),a.pure.u64(s),a.pure.bool(i),a.pure.bool(o),a.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,i?t.quoteCoin.coinType:t.baseCoin.coinType]}),a}catch(c){throw new Error(`Failed to place reduce only market order: ${c instanceof Error?c.message:String(c)}`)}}async getAccountOpenOrders({poolInfo:e,marginManager:t}){try{let r=new O,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(t)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getOpenOrder(e,this.sdk.senderAddress,n,void 0,!0,r)}catch(r){throw new Error(`Failed to get account open orders: ${r instanceof Error?r.message:String(r)}`)}}async getAccountAllMarketsOpenOrders(e,t){try{if(!e||!t||t.length===0)throw new Error("Account or pools are required");let r=[];for(let n=0;n<t.length;n++){let s=new O,i=t[n];if(i.margin_manager_id){let o=await s.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[s.object(i.margin_manager_id)],typeArguments:[i.baseCoin.coinType,i.quoteCoin.coinType]}),a=await this.sdk.DeepbookUtils.getOpenOrder(i,this.sdk.senderAddress,o,void 0,!0,s);r.push(...a)}}return r}catch(r){throw new Error(`Failed to get account all markets open orders: ${r instanceof Error?r.message:String(r)}`)}}mintSupplierCap(e=new O,t){let r=e.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::mint_supplier_cap`,arguments:[e.object(this._sdk.sdkOptions.margin_utils.versioned_id),e.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),e.object(v)]});return t&&e.transferObjects([r],this.sdk.senderAddress),{tx:e,supplierCap:r}}async querySupplierCap(){try{return((await this.sdk.fullClient.queryEventsByPage({MoveEventType:`${this._sdk.sdkOptions.margin_utils.package_id}::margin_utils::SupplierCapCreatedEvent`}))?.data||[]).filter(n=>n.parsedJson?.owner===this.sdk.senderAddress)[0].parsedJson.supplier_cap_id}catch(e){throw new Error(`Failed to get account supplyCap: ${e instanceof Error?e.message:String(e)}`)}}mintSupplierCapAndSupply({marginPool:e,supplyCoinType:t,amount:r}){let n=new O,{supplierCap:s}=this.mintSupplierCap(n,!1);return this.supply({marginPool:e,supplierCap:s,supplyCoinType:t,amount:r,tx:n}),n.transferObjects([s],this.sdk.senderAddress),n}supply({marginPool:e,supplierCap:t,supplyCoinType:r,amount:n,tx:s}){let i=s??new O;if(!t)throw new Error("Either supplierCap must be provided");let o=Fe.buildCoinWithBalance(BigInt(n),r,i);return i.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supply`,typeArguments:[r],arguments:[i.object(this._sdk.sdkOptions.margin_utils.global_config_id),i.object(this._sdk.sdkOptions.margin_utils.versioned_id),i.object(e),i.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),i.object(t),o,i.pure.option("address","0x0"),i.object(v)]}),i}supplierWithdraw({marginPool:e,withdrawCoinType:t,amount:r,supplierCapId:n,hasSwap:s,withdrawAll:i,tx:o=new O}){let a=o.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::supplier_withdraw`,typeArguments:[t],arguments:[o.object(this._sdk.sdkOptions.margin_utils.global_config_id),o.object(this._sdk.sdkOptions.margin_utils.versioned_id),o.object(e),o.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),o.object(n),o.object.option({type:"u64",value:i?null:o.pure.u64(r)}),o.object(v)]});return s?a:(o.transferObjects([a],this.sdk.senderAddress),o)}withdrawReferralFees({marginPool:e}){let t=new O,r=t.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw_referral_fees`,arguments:[t.object(this._sdk.sdkOptions.margin_utils.versioned_id),t.object(e),t.object(this._sdk.sdkOptions.margin_utils.registry_id),t.object.option({type:"0x1",value:null}),t.object(v)],typeArguments:[this.deepCoin.coinType]});return t.transferObjects([r],this.sdk.senderAddress),t}async getUserSupplyAmount({marginPool:e,supplyCoin:t,supplierCapId:r}){let n=new O;n.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_user_supply_amount`,typeArguments:[t.coinType],arguments:[n.object(e),n.object(r),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);return this.#e(BigInt(y.U64.parse(new Uint8Array(s.results[0].returnValues[0][0]))),t.scalar,t.decimals)}async getDeepBookMarginRegistry(){let t=(await this.sdk.fullClient.getObject({id:this._sdk.sdkOptions.margin_utils.margin_registry_id,options:{showContent:!0}})).data.content.fields.inner.fields.id.id,r=await this.sdk.fullClient.getDynamicFieldObject({parentId:t,name:{type:"u64",value:"1"}}),n=r.data.content.fields.value.fields.pool_registry.fields.id.id,s=r.data.content.fields.value.fields.margin_pools.fields.id.id;return{pool_registry_table_id:n,margin_pool_table_id:s}}async getDeepBookPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.pool_registry_table_id}),t=e.map(s=>s.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[];for(let s=0;s<r.length;s++){let i=r[s].data.content.fields;n.push(Ue(i))}return n}async getDeepBookMarginPool(){let{data:e}=await this.sdk.fullClient.getDynamicFields({parentId:this.sdk.sdkOptions.margin_utils.margin_pool_table_id}),t=e.map(a=>a.objectId),r=await this.sdk.fullClient.batchGetObjects(t,{showContent:!0}),n=[],s=[];for(let a=0;a<r.length;a++){let c=r[a].data.content.fields;s.push(c.value),n.push({deposit_coin_type:c.name.fields.name,id:c.id.id})}let i=await this.sdk.fullClient.batchGetObjects(s,{showContent:!0}),o=[];for(let a=0;a<i.length;a++){let c=i[a].data.content.fields;o.push($e(c,n[a]))}return o}async getBaseQuantityIn(e,t,r,n=.01){let s=new O;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),c=y.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),p=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:l(t).sub(a.toString()).toString(),quantityInLeft:l(o.toString()).add(p.takerFee).mul(l(1+n)).ceil().toString(),deep_fee_amount:c.toString()}}async getQuoteQuantityIn(e,t,r,n=.01){let s=new O;s.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_quote_quantity_out":"::pool::get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[s.object(e.address),s.pure.u64(t),s.object(v)]});let i=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:s});if(!i.results||!i.results[0]||!i.results[0].returnValues||!i.results[0].returnValues[0])throw new Error(`Transaction failed: ${i.effects?.status?.error||"Unknown error"}`);let o=y.U64.parse(new Uint8Array(i.results[0].returnValues[0][0])),a=y.U64.parse(new Uint8Array(i.results[0].returnValues[1][0])),c=y.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),p=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:l(t).sub(o).toString(),quantityInLeft:l(a.toString()).add(l(p.takerFee)).mul(l(1+n)).ceil().toString(),deep_fee_amount:c.toString()}}async getBaseQuantityOutInput(e,t,r){let n=new O;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}${r?"::pool::get_base_quantity_out":"::pool::get_base_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=y.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=y.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=y.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getQuoteQuantityOutInput(e,t,r){let n=new O;n.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::${r?"get_quote_quantity_out":"get_quote_quantity_out_input_fee"}`,typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType],arguments:[n.object(e.address),n.pure.u64(t),n.object(v)]});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:n});if(!s.results||!s.results[0]||!s.results[0].returnValues||!s.results[0].returnValues[0])throw new Error(`Transaction failed: ${s.effects?.status?.error||"Unknown error"}`);let i=y.U64.parse(new Uint8Array(s.results[0].returnValues[0][0])),o=y.U64.parse(new Uint8Array(s.results[0].returnValues[1][0])),a=y.U64.parse(new Uint8Array(s.results[0].returnValues[2][0]));return{base_amount:i.toString(),quote_amount:o.toString(),deep_fee_amount:a.toString()}}async getAccount(e,t){if(!e||!t)throw new Error("marginManager and poolInfo are required");let r=new O,n=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(e)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType]});return await this.sdk.DeepbookUtils.getAccount(n,[t],r)}async withdrawSettledAmounts({poolInfo:e,marginManager:t},r=new O){return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::pool_proxy::withdraw_settled_amounts`,arguments:[r.object(this.sdk.sdkOptions.margin_utils.margin_registry_id),r.object(t),r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),r}#e(e,t,r){if(t<=0||r<0)throw new Error("Scalar must be positive and decimals must be non-negative");let n=BigInt(t),s=e/n,i=e%n;if(i===0n)return s.toString();let o=t.toString().length-1,p=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return p?`${s}.${p}`:s.toString()}async getMarginPoolStateForInterest(e){if(!e)throw new Error("marginPoolId is required");let t=await this.sdk.fullClient.getObject({id:e,options:{showContent:!0}});if(!t.data?.content?.fields)throw new Error(`Failed to fetch margin pool: ${e}`);let r=t.data.content.fields,n=r.state.fields,s=r.config.fields,i=s.interest_config.fields,o=s.margin_pool_config.fields;return{poolState:{total_supply:BigInt(n.total_supply),total_borrow:BigInt(n.total_borrow),supply_shares:BigInt(n.supply_shares),borrow_shares:BigInt(n.borrow_shares),last_update_timestamp:BigInt(n.last_update_timestamp)},interestConfig:{base_rate:BigInt(i.base_rate),base_slope:BigInt(i.base_slope),optimal_utilization:BigInt(i.optimal_utilization),excess_slope:BigInt(i.excess_slope)},marginPoolConfig:{protocol_spread:BigInt(o.protocol_spread),max_utilization_rate:BigInt(o.max_utilization_rate),min_borrow:BigInt(o.min_borrow),supply_cap:BigInt(o.supply_cap)}}}async getChainTimestamp(){let e=await this.sdk.fullClient.getLatestCheckpointSequenceNumber(),t=await this.sdk.fullClient.getCheckpoint({id:e});return BigInt(t.timestampMs)}async batchGetBorrowedShares({account:e,marginManagerList:t}){let r=new O;return t.forEach(s=>{r.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::borrowed_shares`,arguments:[r.object(s.marginManagerId)],typeArguments:[s.baseCoinType,s.quoteCoinType]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r})).results.map((s,i)=>{let o=y.U64.parse(new Uint8Array(s.returnValues[0][0])),a=y.U64.parse(new Uint8Array(s.returnValues[1][0]));return{marginManagerId:t[i].marginManagerId,baseBorrowedShare:o,quoteBorrowedShare:a}})}async betchGetOpenOrders({account:e,marginManagerList:t},r=new O,n=!1){t.forEach(m=>{let b=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(m.poolId),r.object(b)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(m.marginManagerId),r.object(m.poolId)],typeArguments:[m.baseCoinType,m.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((m,b)=>({marginManagerId:t[b].marginManagerId,...m?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(m=>m?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=y.struct("VecSet",{constants:y.vector(y.U128)}),c=[];o.forEach((m,b)=>{let w=a.parse(new Uint8Array(m.returnValues[0][0])).constants;w.length>0&&w.forEach(f=>{c.push({pool:{pool_id:t[b].poolId,baseCoinType:t[b].baseCoinType,quoteCoinType:t[b].quoteCoinType},marginManagerId:t[b].marginManagerId,orderId:f})})});let p=await this.sdk.DeepbookUtils.getOrderInfoList(c,e)||[],d=s.results.filter(m=>m?.returnValues?.length===3),g=[];d.forEach((m,b)=>{g.push({marginManagerId:t[b].marginManagerId,base:y.U64.parse(new Uint8Array(m.returnValues[0][0])),quote:y.U64.parse(new Uint8Array(m.returnValues[1][0])),deep:y.U64.parse(new Uint8Array(m.returnValues[2][0]))})});let _=[];return c.forEach((m,b)=>{let w=this.sdk.DeepbookUtils.decodeOrderId(BigInt(m.orderId)),f=p.find(C=>C.order_id===m.orderId)||{};_.push({...m,...f,price:w.price.toString(),isBid:w.isBid})}),{openOrders:_,settledBalances:i,lockedBalances:g}}async getSingleMarginManagerOpenOrders({account:e,marginManagerId:t,poolId:r,baseCoinType:n,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){let a=new O,c=a.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[a.object(t)],typeArguments:[n,s]});a.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[a.object(r),c],typeArguments:[n,s]});let p=y.struct("VecSet",{constants:y.vector(y.U128)}),g=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),_=p.parse(new Uint8Array(g.returnValues[0][0])).constants,m=[];_.forEach(h=>{m.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let b=m?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(m,e)||[]:[],w=[];m.forEach((h,A)=>{let S=this.sdk.DeepbookUtils.decodeOrderId(BigInt(h.orderId)),T=b.find(B=>B.order_id===h.orderId)||{};w.push({...h,...T,price:S.price.toString(),isBid:S.isBid})});let f={marginManagerId:t,base:"0",quote:"0",deep:"0"};if(b?.length>0){let h=new O,A=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::locked_balance`,arguments:[h.object(r),A],typeArguments:[n,s]});let T=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h})).results.find(B=>B?.returnValues?.length===3);f={...f,base:y.U64.parse(new Uint8Array(T.returnValues[0][0])),quote:y.U64.parse(new Uint8Array(T.returnValues[1][0])),deep:y.U64.parse(new Uint8Array(T.returnValues[2][0]))}}let C={base:"0",quote:"0",deep:"0"};try{let h=new O,A=h.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[h.object(t)],typeArguments:[n,s]});h.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[h.object(r),A],typeArguments:[n,s]});let S=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:h});C={marginManagerId:t,...C,...S?.events?.parsedJson?.account?.settled_balances||{}}}catch{}return{openOrders:w,settledBalances:[C],lockedBalances:[f]}}async getAllPosRelevantData({account:e,marginManagerList:t}){try{let{openOrders:r,settledBalances:n,lockedBalances:s}=await this.betchGetOpenOrders({account:e,marginManagerList:t}),i=await this.batchGetBorrowedShares({account:e,marginManagerList:t}),o=new O,a=0,c=[];t.forEach(g=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),c[a]={type:"base_balance",marginManagerId:g.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),c[a]={type:"quote_balance",marginManagerId:g.marginManagerId},a++;let _=i?.find(m=>m.marginManagerId===g.marginManagerId);if(_&&(Number(_.baseBorrowedShare)>0||Number(_.quoteBorrowedShare)>0)){let m=_.baseBorrowedShare,b=_.quoteBorrowedShare,w=!!l(m).gt(l(b)),f=w?g.baseMarginPool:g.quoteMarginPool,C=w?m:b;o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[o.object(f),o.pure.u64(BigInt(C)),o.object.clock()],typeArguments:[w?g?.baseCoinType:g?.quoteCoinType]}),c[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:g.marginManagerId},a++}});let p=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),d=Object.fromEntries(t.map(g=>[g.marginManagerId,{...g,quote_balance:"0",base_balance:"0",borrow_base_amount:"0",borrow_quote_amount:"0",open_orders:[],settled_balances:{base:"0",quote:"0",deep:"0"}}]));return p?.results?.forEach((g,_)=>{let m=c[_],b=y.U64.parse(new Uint8Array(g.returnValues[0][0]));d[m.marginManagerId]={...d[m.marginManagerId],[m.type]:b}}),r.forEach(g=>{d[g.marginManagerId].open_orders.push(g)}),n.forEach(g=>{d[g.marginManagerId].settled_balances=g}),s.forEach(g=>{d[g.marginManagerId].locked_balances=g}),Object.values(d).forEach(g=>{g.locked_balances&&g.settled_balances&&(g.locked_balances={...g.locked_balances,base:l(g.locked_balances.base||"0").minus(l(g.settled_balances.base||"0")).toString(),quote:l(g.locked_balances.quote||"0").minus(l(g.settled_balances.quote||"0")).toString(),deep:l(g.locked_balances.deep||"0").minus(l(g.settled_balances.deep||"0")).toString()})}),d}catch(r){throw new Error(`Failed to get all pos relevant data: ${r instanceof Error?r.message:String(r)}`)}}async addConditionalOrder(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s,margin_registry_id:i}=r,{margin_manager_id:o,pool_id:a,base_coin:c,quote_coin:p,conditional_order_id:d,pending_order:g,is_trigger_below_price:_,trigger_price:m}=e,b=await this.pythPrice.updatePythPriceIDs([c.feed,p.feed],t),w=b.get(c.feed),f=b.get(p.feed);if(!w||!f)throw new Error("Failed to get price feed object IDs");let C=l(m).mul(1e9).mul(p.scalar).div(c.scalar).round().toString(),h=t.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[t.pure.bool(_),t.pure.u64(C)]}),A=this.newPendingOrder(g,t);t.moveCall({target:`${r.published_at}::margin_utils::add_conditional_order`,arguments:[t.object(n),t.object(s),t.object(o),t.object(a),t.object(w),t.object(f),t.object(i),typeof d=="string"?t.pure.u64(BigInt(d)):d,h,A,t.object(ge)],typeArguments:[c.coinType,p.coinType]})}newPendingOrder(e,t){let{margin_utils:r}=this.sdk.sdkOptions;if("price"in e){let{client_order_id:n,order_type:s,self_matching_option:i,price:o,quantity:a,is_bid:c,pay_with_deep:p,expire_timestamp:d}=e;return t.moveCall({target:`${r.published_at}::margin_utils::new_pending_limit_order`,arguments:[t.pure.u64(n),t.pure.u8(s),t.pure.u8(i),t.pure.u64(o),t.pure.u64(a),t.pure.bool(c),t.pure.bool(p),t.pure.u64(d)]})}else{let{client_order_id:n,self_matching_option:s,quantity:i,is_bid:o,pay_with_deep:a}=e;return t.moveCall({target:`${r.published_at}::margin_utils::new_pending_market_order`,arguments:[t.pure.u64(n),t.pure.u8(s),t.pure.u64(i),t.pure.bool(o),t.pure.bool(a)]})}}cancelAllConditionalOrders(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s}=r,{margin_manager_id:i,base_coin_type:o,quote_coin_type:a}=e;t.moveCall({target:`${r.published_at}::margin_utils::cancel_all_conditional_orders`,arguments:[t.object(n),t.object(s),t.object(i),t.object(ge)],typeArguments:[o,a]})}cancelConditionalOrders(e,t){let{margin_utils:r}=this.sdk.sdkOptions,{global_config_id:n,versioned_id:s}=r,{margin_manager_id:i,base_coin_type:o,quote_coin_type:a,conditional_order_id:c}=e;t.moveCall({target:`${r.published_at}::margin_utils::cancel_conditional_order`,arguments:[t.object(n),t.object(s),t.object(i),t.pure.u64(c),t.object(ge)],typeArguments:[o,a]})}async getConditionalOrders(e,t){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(a=>{let{margin_manager_id:c,base_coin_type:p,quote_coin_type:d,conditional_order_id:g}=a;t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[t.object(c),t.pure.u64(g)],typeArguments:[p,d]})});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:me("0x0"),transactionBlock:t});if(!n?.results||n.results.length!==e.length)return[];let s=y.struct("Condition",{trigger_below_price:y.bool(),trigger_price:y.u64()}),i=y.struct("PendingOrder",{is_limit_order:y.bool(),client_order_id:y.u64(),order_type:y.option(y.u8()),self_matching_option:y.u8(),price:y.option(y.u64()),quantity:y.u64(),is_bid:y.bool(),pay_with_deep:y.bool(),expire_timestamp:y.option(y.u64())}),o=y.struct("ConditionalOrder",{conditional_order_id:y.u64(),condition:s,pending_order:i});return n.results.map(a=>{if(!a?.returnValues?.[0]?.[0])return null;try{let c=new Uint8Array(a.returnValues[0][0]);if(c.length===0)return null;let p;if(c[0]===0)return null;c[0]===1?p=c.subarray(1):p=c;let d=o.parse(p);return this.normalizeConditionalOrder(d)}catch{return null}})}normalizeConditionalOrder(e){let t=r=>typeof r=="bigint"?String(r):r;return{conditional_order_id:t(e.conditional_order_id),condition:{trigger_below_price:e.condition.trigger_below_price,trigger_price:t(e.condition.trigger_price)},pending_order:{is_limit_order:e.pending_order.is_limit_order,client_order_id:t(e.pending_order.client_order_id),order_type:e.pending_order.order_type,self_matching_option:e.pending_order.self_matching_option,price:e.pending_order.price,quantity:t(e.pending_order.quantity),is_bid:e.pending_order.is_bid,pay_with_deep:e.pending_order.pay_with_deep,expire_timestamp:e.pending_order.expire_timestamp}}}};import{SuiClient as bt}from"@mysten/sui/client";var te=class extends bt{async queryEventsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.queryEvents({query:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async getOwnedObjectsByPage(e,t,r="all"){let n=[],s=!0,i=r==="all",o=i?null:r.cursor;do{let a=await this.getOwnedObjects({owner:e,...t,cursor:o,limit:i?null:r.limit});a.data?(n=[...n,...a.data],s=a.hasNextPage,o=a.nextCursor):s=!1}while(i&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getDynamicFieldsByPage(e,t="all"){let r=[],n=!0,s=t==="all",i=s?null:t.cursor;do{let o=await this.getDynamicFields({parentId:e,cursor:i,limit:s?null:t.limit});o.data?(r=[...r,...o.data],n=o.hasNextPage,i=o.nextCursor):n=!1}while(s&&n);return{data:r,nextCursor:i,hasNextPage:n}}async batchGetObjects(e,t,r=50){let n=[];try{for(let s=0;s<Math.ceil(e.length/r);s++){let i=await this.multiGetObjects({ids:e.slice(s*r,r*(s+1)),options:t});n=[...n,...i]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let r=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=r.effects;return Number(n.computationCost)+Number(n.storageCost)-Number(n.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};import Ve from"decimal.js";Ve.config({precision:64,rounding:Ve.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var F=1000000000n,ht=365n*24n*60n*60n*1000n;function yt(u,e){return e===0n?0n:u*F/e}function ft(u,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(u<n)return t+u*r/F;{let i=u-n,o=n*r/F,a=i*s/F;return t+o+a}}function Ne(u,e){let t=u*e,r=t/F;return t%F>0n?r+1n:r}function kt(u,e,t,r){let n=e.borrow_shares===0n?F:e.total_borrow*F/e.borrow_shares,s=Ne(u,n),i=yt(e.total_borrow,e.total_supply),o=ft(i,t),a=r-e.last_update_timestamp,c=e.total_borrow*o/F*a/ht,p=e.borrow_shares===0n?0n:Ne(c,u*F/e.borrow_shares),d=s+p;return{confirmedDebt:s,estimatedInterest:p,totalDebt:d,annualInterestRate:o}}function on(u,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=kt(u,e,t,s);return i}var re=class{_cache={};_rpcModule;_deepbookUtils;_marginUtils;_pythPrice;_graphqlClient;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new te({url:e.fullRpcUrl}),this._deepbookUtils=new X(this),this._marginUtils=new ee(this),this._pythPrice=new H(this),this._graphqlClient=new wt({url:e.graphqlUrl}),oe(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get MarginUtils(){return this._marginUtils}get PythPrice(){return this._pythPrice}get fullClient(){return this._rpcModule}get graphqlClient(){return this._graphqlClient}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,r=!0){let n=[],s=null,i=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,o=this.getCache(i,r);if(o)return o;for(;;){let a=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:s}):this.fullClient.getAllCoins({owner:e,cursor:s}));if(a.data.forEach(c=>{BigInt(c.balance)>0&&n.push({coinAddress:R(c.coinType).source_address,coinObjectId:c.coinObjectId,balance:BigInt(c.balance)})}),s=a.nextCursor,!a.hasNextPage)break}return this.updateCache(i,n,30*1e3),n}async getOwnerCoinBalances(e,t){let r=[];return t?r=[await this.fullClient.getBalance({owner:e,coinType:t})]:r=[...await this.fullClient.getAllBalances({owner:e})],r}updateCache(e,t,r=864e5){let n=this._cache[e];n?(n.overdueTime=z(r),n.value=t):n=new K(t,z(r)),this._cache[e]=n}getCache(e,t=!1){let r=this._cache[e],n=r?.isValid();if(!t&&n)return r.value;n||delete this._cache[e]}};var Bn="0x0000000000000000000000000000000000000000000000000000000000000006",En="pool_script",vn="pool_script_v2",Mn="router",qn="router_with_partner",Pn="fetcher_script",In="expect_swap",Dn="utils",Un="0x1::coin::CoinInfo",$n="0x1::coin::CoinStore",Rn="custodian_v2",Fn="clob_v2",Vn="endpoints_v2",Nn=u=>{if(typeof u=="string"&&u.startsWith("0x"))return"object";if(typeof u=="number"||typeof u=="bigint")return"u64";if(typeof u=="boolean")return"bool";throw new Error(`Unknown type for value: ${u}`)};var Ct=(n=>(n[n.NO_RESTRICTION=0]="NO_RESTRICTION",n[n.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",n[n.FILL_OR_KILL=2]="FILL_OR_KILL",n[n.POST_ONLY=3]="POST_ONLY",n))(Ct||{}),Ot=(r=>(r[r.SELF_MATCHING_ALLOWED=0]="SELF_MATCHING_ALLOWED",r[r.CANCEL_TAKER=1]="CANCEL_TAKER",r[r.CANCEL_MAKER=2]="CANCEL_MAKER",r))(Ot||{});var ts=re;export{Bn as CLOCK_ADDRESS,K as CachedContent,re as CetusClmmSDK,In as ClmmExpectSwapModule,Pn as ClmmFetcherModule,En as ClmmIntegratePoolModule,vn as ClmmIntegratePoolV2Module,Mn as ClmmIntegrateRouterModule,qn as ClmmIntegrateRouterWithPartnerModule,Dn as ClmmIntegrateUtilsModule,E as CoinAssist,Un as CoinInfoAddress,$n as CoinStoreAddress,le as DEEP_SCALAR,Lt as DEFAULT_GAS_BUDGET_FOR_MERGE,Nt as DEFAULT_GAS_BUDGET_FOR_SPLIT,Kt as DEFAULT_GAS_BUDGET_FOR_STAKE,xt as DEFAULT_GAS_BUDGET_FOR_TRANSFER,Gt as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,Qt as DEFAULT_NFT_TRANSFER_GAS_FEE,Fn as DeepbookClobV2Moudle,Rn as DeepbookCustodianV2Moudle,Vn as DeepbookEndpointsV2Moudle,X as DeepbookUtilsModule,$ as FLOAT_SCALAR,F as FLOAT_SCALING,zt as GAS_SYMBOL,ae as GAS_TYPE_ARG,ke as GAS_TYPE_ARG_LONG,ee as MarginUtilsModule,$t as NORMALIZED_SUI_COIN_TYPE,Ct as OrderType,te as RpcModule,Ht as SUI_SYSTEM_STATE_OBJECT_ID,Ot as SelfMatchingOption,N as TransactionUtil,ht as YEAR_MS,be as addHexPrefix,sr as asIntN,nr as asUintN,jt as bufferToHex,Ce as cacheTime1min,L as cacheTime24h,Oe as cacheTime5min,on as calc100PercentRepay,kt as calcDebtDetail,ft as calcInterestRate,yt as calcUtilizationRate,Vr as calculateRiskRatio,St as checkAddress,ye as composeType,l as d,ce as decimalsMultiplier,ts as default,Dt as extractAddressFromType,R as extractStructTagFromType,Ut as fixCoinType,x as fixDown,Xe as fixSuiObjectId,G as fromDecimalsAmount,Nn as getDefaultSuiInputType,z as getFutureTime,de as getMoveObject,ot as getMoveObjectType,lr as getMovePackageContent,rt as getObjectDeletedResponse,_r as getObjectDisplay,Ie as getObjectFields,Pe as getObjectId,nt as getObjectNotExistsResponse,mr as getObjectOwner,gr as getObjectPreviousTransactionDigest,qe as getObjectReference,pr as getObjectType,dr as getObjectVersion,Q as getSuiObjectData,br as hasPublicTransfer,Bt as hexToNumber,Et as hexToString,It as isSortedSymbols,st as isSuiObjectResponse,ue as maxDecimal,Ne as mulRoundUp,ie as normalizeCoinType,oe as patchFixSuiObjectId,kr as printTransaction,ne as removeHexPrefix,ir as secretKeyToEd25519Keypair,or as secretKeyToSecp256k1Keypair,At as shortAddress,Ke as shortString,Be as sleepTime,ze as toBuffer,W as toDecimalsAmount,Qe as utf8to16,$e as wrapDeepBookMarginPoolInfo,Ue as wrapDeepBookPoolInfo};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cetusprotocol/deepbook-utils",
3
- "version": "0.0.0-experimental-20260205215421",
3
+ "version": "0.0.0-experimental-20260210163200",
4
4
  "description": "cetus deepbook utils sdk",
5
5
  "typings": "dist/index.d.ts",
6
6
  "main": "dist/index.js",