@cetusprotocol/deepbook-utils 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +89 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -270,6 +270,87 @@ 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_ids: string[];
|
|
314
|
+
base_coin_type: string;
|
|
315
|
+
quote_coin_type: string;
|
|
316
|
+
};
|
|
317
|
+
type GetConditionalIdsOptions = {
|
|
318
|
+
margin_manager_id: string;
|
|
319
|
+
base_coin_type: string;
|
|
320
|
+
quote_coin_type: string;
|
|
321
|
+
};
|
|
322
|
+
type GetConditionalOrderIdsResponse = {
|
|
323
|
+
margin_manager_id: string;
|
|
324
|
+
base_coin_type: string;
|
|
325
|
+
quote_coin_type: string;
|
|
326
|
+
conditional_order_ids: string[];
|
|
327
|
+
};
|
|
328
|
+
/** Condition for triggering a conditional order (trigger_below_price, trigger_price). */
|
|
329
|
+
type Condition = {
|
|
330
|
+
trigger_below_price: boolean;
|
|
331
|
+
trigger_price: string;
|
|
332
|
+
};
|
|
333
|
+
/** Pending order embedded in a conditional order (matches Move PendingOrder). */
|
|
334
|
+
type PendingOrder = {
|
|
335
|
+
is_limit_order: boolean;
|
|
336
|
+
client_order_id: string;
|
|
337
|
+
order_type?: OrderType;
|
|
338
|
+
self_matching_option: SelfMatchingOption;
|
|
339
|
+
price?: string;
|
|
340
|
+
quantity: string;
|
|
341
|
+
is_bid: boolean;
|
|
342
|
+
pay_with_deep: boolean;
|
|
343
|
+
expire_timestamp?: string;
|
|
344
|
+
};
|
|
345
|
+
/** Conditional order (matches Move ConditionalOrder). */
|
|
346
|
+
type ConditionalOrder = {
|
|
347
|
+
margin_manager_id: string;
|
|
348
|
+
base_coin_type: string;
|
|
349
|
+
quote_coin_type: string;
|
|
350
|
+
conditional_order_id: string;
|
|
351
|
+
condition: Condition;
|
|
352
|
+
pending_order: PendingOrder;
|
|
353
|
+
};
|
|
273
354
|
|
|
274
355
|
type BigNumber = Decimal.Value | number | string;
|
|
275
356
|
|
|
@@ -1417,6 +1498,13 @@ declare class MarginUtilsModule implements IModule {
|
|
|
1417
1498
|
quoteMarginPool: string;
|
|
1418
1499
|
}[];
|
|
1419
1500
|
}): Promise<any>;
|
|
1501
|
+
addConditionalOrder(options: AddConditionalOrderOptions, tx: Transaction): Promise<void>;
|
|
1502
|
+
private newPendingOrder;
|
|
1503
|
+
cancelAllConditionalOrders(options: CancelAllConditionalOrdersOptions, tx: Transaction): void;
|
|
1504
|
+
cancelConditionalOrders(options: CancelConditionalOrdersOptions, tx: Transaction): void;
|
|
1505
|
+
getConditionalOrders(options: GetConditionalOrdersOptions[], tx: Transaction): Promise<ConditionalOrder[]>;
|
|
1506
|
+
getConditionalOrderIds(options: GetConditionalIdsOptions[], tx?: Transaction): Promise<Record<string, GetConditionalOrderIdsResponse>>;
|
|
1507
|
+
private normalizeConditionalOrder;
|
|
1420
1508
|
}
|
|
1421
1509
|
|
|
1422
1510
|
/**
|
|
@@ -2020,4 +2108,4 @@ declare class CoinAssist {
|
|
|
2020
2108
|
static buildCoinWithBalance(amount: bigint, coin_type: string, tx: Transaction): TransactionObjectArgument;
|
|
2021
2109
|
}
|
|
2022
2110
|
|
|
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 };
|
|
2111
|
+
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, GetConditionalIdsOptions, GetConditionalOrderIdsResponse, 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 lt=(c,e,t)=>e in c?Z(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var dt=(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)=>(lt(c,typeof e!="symbol"?e+"":e,t),t);var _r={};dt(_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:()=>lr,DEEP_SCALAR:()=>de,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:()=>dr,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:()=>le,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 le(c){let e="data"in c?z(c):c;if(!(!e||!Nt(e)||e.content.dataType!=="moveObject"))return e.content}function ze(c){return le(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=le(c)?.fields;if(e)return"fields"in e?e.fields:e}function zt(c){return le(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 de=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(de).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(de).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(de).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 it=Object.create;var Y=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ut=(d,e,t)=>e in d?Y(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var lt=(d,e)=>{for(var t in e)Y(d,t,{get:e[t],enumerable:!0})},qe=(d,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of at(e))!dt.call(d,n)&&n!==t&&Y(d,n,{get:()=>e[n],enumerable:!(r=ot(e,n))||r.enumerable});return d};var Pe=(d,e,t)=>(t=d!=null?it(ct(d)):{},qe(e||!d||!d.__esModule?Y(t,"default",{value:d,enumerable:!0}):t,d)),pt=d=>qe(Y({},"__esModule",{value:!0}),d);var Ie=(d,e,t)=>(ut(d,typeof e!="symbol"?e+"":e,t),t);var br={};lt(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:()=>dr,CoinStoreAddress:()=>ur,DEEP_SCALAR:()=>pe,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:()=>pr,DeepbookCustodianV2Moudle:()=>lr,DeepbookEndpointsV2Moudle:()=>gr,DeepbookUtilsModule:()=>ee,FLOAT_SCALAR:()=>U,FLOAT_SCALING:()=>R,GAS_SYMBOL:()=>Pt,GAS_TYPE_ARG:()=>ce,GAS_TYPE_ARG_LONG:()=>he,MarginUtilsModule:()=>te,NORMALIZED_SUI_COIN_TYPE:()=>At,OrderType:()=>nt,RpcModule:()=>re,SUI_SYSTEM_STATE_OBJECT_ID:()=>Dt,SelfMatchingOption:()=>st,TransactionUtil:()=>F,YEAR_MS:()=>Ye,addHexPrefix:()=>_e,asIntN:()=>$t,asUintN:()=>Ut,bufferToHex:()=>bt,cacheTime1min:()=>fe,cacheTime24h:()=>V,cacheTime5min:()=>ke,calc100PercentRepay:()=>er,calcDebtDetail:()=>tt,calcInterestRate:()=>et,calcUtilizationRate:()=>Xe,calculateRiskRatio:()=>Zt,checkAddress:()=>_t,composeType:()=>be,d:()=>p,decimalsMultiplier:()=>de,default:()=>_r,extractAddressFromType:()=>Ot,extractStructTagFromType:()=>$,fixCoinType:()=>Tt,fixDown:()=>G,fixSuiObjectId:()=>Ve,fromDecimalsAmount:()=>x,getDefaultSuiInputType:()=>mr,getFutureTime:()=>z,getMoveObject:()=>le,getMoveObjectType:()=>Qe,getMovePackageContent:()=>Lt,getObjectDeletedResponse:()=>xe,getObjectDisplay:()=>zt,getObjectFields:()=>Se,getObjectId:()=>Ae,getObjectNotExistsResponse:()=>Ke,getObjectOwner:()=>Kt,getObjectPreviousTransactionDigest:()=>xt,getObjectReference:()=>Te,getObjectType:()=>Gt,getObjectVersion:()=>Vt,getSuiObjectData:()=>Q,hasPublicTransfer:()=>Qt,hexToNumber:()=>ht,hexToString:()=>yt,isSortedSymbols:()=>Ct,isSuiObjectResponse:()=>ze,maxDecimal:()=>ue,mulRoundUp:()=>Me,normalizeCoinType:()=>oe,patchFixSuiObjectId:()=>ae,printTransaction:()=>Ht,removeHexPrefix:()=>ie,secretKeyToEd25519Keypair:()=>Rt,secretKeyToSecp256k1Keypair:()=>Ft,shortAddress:()=>mt,shortString:()=>De,sleepTime:()=>Oe,toBuffer:()=>Ue,toDecimalsAmount:()=>J,utf8to16:()=>$e,wrapDeepBookMarginPoolInfo:()=>Be,wrapDeepBookPoolInfo:()=>je});module.exports=pt(br);var rt=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 gt=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function _e(d){return d.startsWith("0x")?d:`0x${d}`}function ie(d){return d.startsWith("0x")?`${d.slice(2)}`:d}function De(d,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${d.slice(0,r+2)} ... ${d.slice(-n)}`}function mt(d,e=4,t=4){return De(_e(d),e,t)}function _t(d,e={leadingZero:!0}){if(typeof d!="string")return!1;let t=d;if(e.leadingZero){if(!d.startsWith("0x"))return!1;t=t.substring(2)}return gt.test(t)}function Ue(d){if(!Buffer.isBuffer(d))if(Array.isArray(d))d=Buffer.from(d);else if(typeof d=="string")exports.isHexString(d)?d=Buffer.from(exports.padToEven(exports.stripHexPrefix(d)),"hex"):d=Buffer.from(d);else if(typeof d=="number")d=exports.intToBuffer(d);else if(d==null)d=Buffer.allocUnsafe(0);else if(d.toArray)d=Buffer.from(d.toArray());else throw new Error("invalid type");return d}function bt(d){return _e(Ue(d).toString("hex"))}function ht(d){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<d.length;n++)t.setUint8(n,d.charCodeAt(n));return t.getUint32(0,!0)}function $e(d){let e,t,r,n,s;e="";let i=d.length;for(t=0;t<i;)switch(r=d.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=d.charAt(t-1);break;case 12:case 13:n=d.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=d.charCodeAt(t++),s=d.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function yt(d){let e="",t=ie(d),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(d,e){return d===e?ft:d<e?Fe:kt}function wt(d,e){let t=0,r=d.length<=e.length?d.length:e.length,n=Re(d.length,e.length);for(;t<r;){let s=Re(d.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function Ct(d,e){return wt(d,e)===Fe}function be(d,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[d,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function Ot(d){return d.split("::")[0]}function $(d){try{let e=d.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(c=>$(c).source_address)};return a.type_arguments=a.type_arguments.map(c=>v.isSuiCoin(c)?c:$(c).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:d,address:"",module:"",name:"",type_arguments:[],source_address:d}}}function oe(d){return $(d).source_address}function Ve(d){return d.toLowerCase().startsWith("0x")?(0,L.normalizeSuiObjectId)(d):d}var Tt=(d,e=!0)=>{let t=d.split("::"),r=t.shift(),n=(0,L.normalizeSuiObjectId)(r);return e&&(n=ie(n)),`${n}::${t.join("::")}`};function ae(d){for(let e in d){let t=typeof d[e];if(t==="object")ae(d[e]);else if(t==="string"){let r=d[e];d[e]=Ve(r)}}}var At=(0,L.normalizeStructTag)(L.SUI_TYPE_ARG);var St="0x2::coin::Coin",jt=/^0x2::coin::Coin<(.+)>$/,Bt=1e3,Et=500,vt=100,Mt=100,qt=1e3,ce="0x2::sui::SUI",he="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Pt="SUI",It=450,Dt="0x0000000000000000000000000000000000000005",v=class{static getCoinTypeArg(e){let t=e.type.match(jt);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`${St}<${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(c=>!r.includes(c.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 c=t-i,l=a.findIndex(m=>m.balance>=c);if(l!==-1){o.push(a[l]),a.splice(l,1);break}let u=a.pop();u.balance>0&&(o.push(u),i+=u.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(d){return Date.parse(new Date().toString())+d}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 p(d){return X.default.isDecimal(d)?d:new X.default(d===void 0?0:d)}function de(d){return p(10).pow(p(d).abs())}var G=(d,e)=>{try{return p(d).toDP(e,X.default.ROUND_DOWN).toString()}catch{return d}},ue=(d,e)=>X.default.max(p(d),p(e));function J(d,e){let t=de(p(e));return Number(p(d).mul(t))}function Ut(d,e=32){return BigInt.asUintN(e,BigInt(d)).toString()}function $t(d,e=32){return Number(BigInt.asIntN(e,BigInt(d)))}function x(d,e){let t=de(p(e));return Number(p(d).div(t))}function Rt(d,e="hex"){if(d instanceof Uint8Array){let r=Buffer.from(d);return we.Ed25519Keypair.fromSecretKey(r)}let t=e==="hex"?(0,W.fromHEX)(d):(0,W.fromB64)(d);return we.Ed25519Keypair.fromSecretKey(t)}function Ft(d,e="hex"){if(d instanceof Uint8Array){let r=Buffer.from(d);return Ce.Secp256k1Keypair.fromSecretKey(r)}let t=e==="hex"?(0,W.fromHEX)(d):(0,W.fromB64)(d);return Ce.Secp256k1Keypair.fromSecretKey(t)}var Oe=async d=>new Promise(e=>{setTimeout(()=>{e(1)},d)});var Ne={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Le={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function Ge(...d){let e="DeepbookV3_Utils_Sdk###"}function Q(d){return d.data}function xe(d){if(d.error&&"object_id"in d.error&&"version"in d.error&&"digest"in d.error){let{error:e}=d;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Ke(d){if(d.error&&"object_id"in d.error&&!("version"in d.error)&&!("digest"in d.error))return d.error.object_id}function Te(d){if("reference"in d)return d.reference;let e=Q(d);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:xe(d)}function Ae(d){return"objectId"in d?d.objectId:Te(d)?.objectId??Ke(d)}function Vt(d){return"version"in d?d.version:Te(d)?.version}function ze(d){return d.data!==void 0}function Nt(d){return d.content!==void 0}function Lt(d){let e=Q(d);if(e?.content?.dataType==="package")return e.content.disassembled}function le(d){let e="data"in d?Q(d):d;if(!(!e||!Nt(e)||e.content.dataType!=="moveObject"))return e.content}function Qe(d){return le(d)?.type}function Gt(d){let e=ze(d)?d.data:d;return!e?.type&&"data"in d?e?.content?.dataType==="package"?"package":Qe(d):e?.type}function xt(d){return Q(d)?.previousTransaction}function Kt(d){return Q(d)?.owner}function zt(d){let e=Q(d)?.display;return e||{data:null,error:null}}function Se(d){let e=le(d)?.fields;if(e)return"fields"in e?e.fields:e}function Qt(d){return le(d)?.hasPublicTransfer??!1}var He=require("@mysten/sui/transactions");async function Ht(d,e=!0){d.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(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 l=new He.Transaction;return{fixAmount:r,newTx:l}}}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),c=a.amountArray.reduce((f,O)=>Number(f)+Number(O),0).toString(),l=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:l.map(f=>e.object(f))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((f,O)=>Number(f)+Number(O),0).toString(),isMintZeroCoin:!1};let[u,...m]=l,g=e.object(u),_=g,b=a.amountArray.reduce((f,O)=>Number(f)+Number(O),0).toString(),w;return m.length>0&&e.mergeCoins(g,m.map(f=>e.object(f))),o&&Number(c)>Number(n)&&(_=e.splitCoins(g,[e.pure.u64(n)]),b=n.toString(),w=g),{targetCoin:_,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,Wt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Jt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},ee=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(l=>l.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],c=[];return a.forEach(l=>{c.push({balanceManager:l,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 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 c=r[a],l=o.returnValues[0][0],u=k.bcs.U64.parse(new Uint8Array(l)),m=p(u),g=m.eq(0)?"0":m.div(Math.pow(10,c.decimals)).toString();i[c.coinType]={adjusted_balance:g,balance:m.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 c={},l=a*t.length;t.forEach((u,m)=>{let g=l+m,_=s.results?.[g];if(_){let b=_.returnValues[0][0],w=k.bcs.U64.parse(new Uint8Array(b)),f=p(w),O=f.eq(0)?"0":f.div(Math.pow(10,u.decimals)).toString();c[u.coinType]={adjusted_balance:O,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 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 p(s).mul(i).div(o).div(U).toString()}catch(t){return Ge("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 u=c[1].split(", ");i.push({...a,baseCoinType:u[0],quoteCoinType:u[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:p(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:p(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(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:p(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:p(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(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]))),c=Number(k.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])));return{baseQuantityDisplay:p(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:p(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:p(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(c).div(pe).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(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:c,maker_fee:l}=e,u=p(c).div(U).toString(),m=p(l).div(U).toString(),g=await this.getMarketPrice(e),_=i?r:g!=="0"?g:o;if(_==="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=p(_).div(b).mul(w).mul(U).toString();if(n){let A=await this.getMarketPrice(e),T=p(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=ue(T,r),I=p(t).mul(p(u)).mul(p(M.deep_per_asset)).div(p(U)),P=p(t).mul(p(m)).mul(p(M.deep_per_asset)).div(p(U));M.asset_is_base||(I=I.mul(q).div(p(U)),P=P.mul(q).div(p(U)));let D=I.ceil().toString(),se=P.ceil().toString();return{takerFee:D,makerFee:se,takerFeeDisplay:x(D,a.decimals).toString(),makerFeeDisplay:x(se,a.decimals).toString(),feeType:a.coinType}}if(s){let A=ue(f,i?r:g),j=p(t).mul(A).mul(p(u).mul(1.25)).div(p(U)).ceil().toFixed(0),T=p(t).mul(A).mul(p(m).mul(1.25)).div(p(U)).ceil().toFixed(0);return{takerFee:j,makerFee:T,takerFeeDisplay:x(j,e.quoteCoin.decimals).toString(),makerFeeDisplay:x(T,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let O=p(t).mul(p(u).mul(1.25)).ceil().toFixed(0),h=p(t).mul(p(m).mul(1.25)).ceil().toFixed(0);return{takerFee:O,makerFee:h,takerFeeDisplay:x(O,e.baseCoin.decimals).toString(),makerFeeDisplay:x(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 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],c=this.parseOrderDeepPrice(new Uint8Array(a));return this.updateCache(r,c,6e4),c}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(p(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 l=await this.getManagerBalance({account:s,balanceManager:o,coins:c}),u=l?.[t]?.balance||"0",m=l?.[r]?.balance||"0",g=i&&l?.[a.coinType]?.balance||"0";return{baseManagerBlance:u,quoteManagerBlance:m,feeManaerBalance:g}}catch(c){throw c instanceof Error?c:new Error(String(c))}}getFeeAsset(e,t,r,n,s,i,o,a,c,l){let u=p(e).gt(0)&&c,m="0";if(!u)return{feeAsset:this.getEmptyCoin(l,t),haveDepositFee:"0"};if(i||o){let g=p(s).sub(i?n:r);m=g.lte(0)?e:g.sub(e).lt(0)?g.sub(e).toString():"0"}else m=p(s).sub(e).lt("0")?p(s).sub(e).abs().toString():"0";return{feeAsset:p(m).gt("0")?this.getCoinAssets(t,m,a,l):this.getEmptyCoin(l,t),haveDepositFee:m}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,c){try{let l=this.deepCoin,u=(0,B.normalizeStructTag)(e.baseCoin.coinType),m=(0,B.normalizeStructTag)(e.quoteCoin.coinType),g=u===l.coinType,_=m===l.coinType,b=!g&&!_,{baseManagerBlance:w,quoteManagerBlance:f,feeManaerBalance:O}=await this.getTransactionRelatedBalance(e,u,m,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=p(r).add(p(n)).toString());let q=p(f).sub(r).toString();p(q).lt(0)?(j=!0,A=this.getCoinAssets(m,q,T,c)):A=this.getEmptyCoin(c,m),h=this.getEmptyCoin(c,u)}else{o||(t=p(t).add(p(n)).toString());let q=p(w).sub(t).toString();p(q).lt(0)?(j=!0,h=this.getCoinAssets(u,q,T,c)):h=this.getEmptyCoin(c,u),A=this.getEmptyCoin(c,m)}let M=this.getFeeAsset(n,l.coinType,t,r,O,_,g,T,o,c);return{baseAsset:h,quoteAsset:A,feeAsset:M,haveDeposit:j}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,c,l){try{let u=this.deepCoin,m=(0,B.normalizeStructTag)(e.baseCoin.coinType),g=(0,B.normalizeStructTag)(e.quoteCoin.coinType),_=m===u.coinType,b=g===u.coinType,w=!_&&!b,f=await this.getTransactionRelatedBalance(e,m,g,w,i,o,a),{feeManaerBalance:O}=f,h=p(f.baseManagerBlance).add(p(l?.base||"0")).toString(),A=p(f.quoteManagerBlance).add(p(l?.quote||"0")).toString(),j=await this._sdk.getOwnerCoinAssets(i),T;o&&p(O).lt(n)?T=this.getCoinAssets(u.coinType,p(n).sub(O).toString(),j,c):T=this.getEmptyCoin(c,u.coinType);let M,q;if(s){o||(r=p(r).add(p(n)).toString());let I=p(A).sub(r).toString();if(p(I).lt(0)){let P;p(A).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:A,returnAssets:!0,txb:c}));let D=this.getCoinAssets(g,I,j,c);P&&c.mergeCoins(D,[P]),q=D}else q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:r,returnAssets:!0,txb:c});M=this.getEmptyCoin(c,m)}else{o||(t=p(t).add(p(n)).toString());let I=p(h).sub(t).toString();if(p(I).lt(0)){let P;p(h).gt(0)&&(P=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:c}));let D=this.getCoinAssets(m,I,j,c);P&&c.mergeCoins(D,[P]),M=D}else M=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:c});q=this.getEmptyCoin(c,g)}return{baseAsset:M,quoteAsset:q,feeAsset:T}}catch(u){throw u instanceof Error?u:new Error(String(u))}}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 l=this.deepCoin,u=e.address,m=e.baseCoin.decimals,g=e.quoteCoin.decimals,_=e.baseCoin.coinType,b=e.quoteCoin.coinType,w=p(t).mul(10**(g-m+9)).toString(),f=(0,B.normalizeStructTag)(_),O=(0,B.normalizeStructTag)(b),h=new S.Transaction,A,j,T=await this._sdk.getOwnerCoinAssets(o);if(s){let P=p(t).mul(p(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(P=p(P).add(p(i)).toString()),j=F.buildCoinForAmount(h,T,BigInt(P),O,!1,!0)?.targetCoin}else{let P=r;a||(P=p(r).abs().add(p(i)).toString()),A=F.buildCoinForAmount(h,T,BigInt(p(P).abs().toString()),f,!1,!0)?.targetCoin}let M=a?p(i).gt(0)?F.buildCoinForAmount(h,T,BigInt(p(i).abs().ceil().toString()),l.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,l.coinType):this.getEmptyCoin(h,l.coinType),q=h.moveCall({typeArguments:[s?_: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(u),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(c),h.object(B.SUI_CLOCK_OBJECT_ID)];return h.moveCall({typeArguments:[f,O],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:I}),h}catch(l){throw l instanceof Error?l:new Error(String(l))}}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,l=e.quoteCoin.coinType,u=(0,B.normalizeStructTag)(c),m=(0,B.normalizeStructTag)(l),g=new S.Transaction,_,b,w=t,f,O=await this.getOrderBook(e,"all",6);if(r){let T=O?.ask?.[0]?.price||"0",M=p(T).mul(p(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=p(M).plus(p(M).mul(o)).ceil().toString()}else{let T=await O?.bid?.[0]?.price||"0",M=p(T).mul(p(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=p(M).minus(p(M).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(f=p(f).add(p(n)).toString()),b=this.getCoinAssets(m,f,h,g),_=this.getEmptyCoin(g,u)):(i||(w=p(w).add(p(n)).toString()),b=this.getEmptyCoin(g,m),_=this.getCoinAssets(u,w,h,g));let A=i?p(n).gt(0)?F.buildCoinForAmount(g,h,BigInt(p(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(g,this.deepCoin.coinType):this.getEmptyCoin(g,this.deepCoin.coinType),j=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(a),_,b,A,g.pure.u8(0),g.pure.u64(t),g.pure.bool(r),g.pure.bool(i),g.pure.u64(f),g.object(B.SUI_CLOCK_OBJECT_ID)];return g.moveCall({typeArguments:[u,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:j}),g}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:l=Date.now()+31536e8}){try{let u=this.deepCoin,m=p(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),g=t.baseCoin.coinType,_=t.quoteCoin.coinType,b=new S.Transaction,w=s?p(r).mul(p(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",f=s?"0":n,{baseAsset:O,quoteAsset:h,feeAsset:A,haveDeposit:j}=await this.getTransactionRelatedAssets(t,f,w,o,s,a,c,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),O,h,A.feeAsset,b.pure.u8(i),b.pure.u8(0),b.pure.u64(m),b.pure.u64(n),b.pure.bool(s),b.pure.bool(c),b.pure.u64(l),b.object(B.SUI_CLOCK_OBJECT_ID)];return b.moveCall({typeArguments:[g,_],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;p(A.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:u,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(m),T.pure.u64(n),T.pure.bool(s),T.pure.bool(c),T.pure.u64(l),T.object(B.SUI_CLOCK_OBJECT_ID)];return T.moveCall({typeArguments:[g,_],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:M}),T}catch(u){throw u instanceof Error?u:new Error(String(u))}}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=p(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=p(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=p(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(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:n}),m=[],g=u.results[0].returnValues[0][0],_=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(g)),b=u.results[0].returnValues[1][0],w=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(b));return _.forEach((f,O)=>{let h=p(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=p(w[O]).div(Math.pow(10,t.decimals)).toString();m.push({price:h,quantity:A})}),m?.[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=p(s).gt(0)?p(s).div(3).toNumber():Math.pow(10,-6),o=p(s).gt(0)?s:Math.pow(10,6),a=p(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=p(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(G(a,0)),n.pure.u64(G(c,0)),n.pure.bool(!0),n.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,r.coinType]});let l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:n}),m=[],g=u.results[0].returnValues[0][0],_=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(g)),b=u.results[0].returnValues[1][0],w=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(b));return _.forEach((f,O)=>{let h=p(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=p(w[O]).div(Math.pow(10,t.decimals)).toString();m.push({price:h,quantity:A})}),m?.[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=p(i).gt(0)?p(i).div(3).toNumber():Math.pow(10,-6),a=p(i).gt(0)?i:Math.pow(10,6)):(o=p(i).gt(0)?i:Math.pow(10,-1),a=p(i).gt(0)?p(i).mul(3).toNumber():Math.pow(10,6));let c=p(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),l=p(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(G(c,0)),s.pure.u64(G(l,0)),s.pure.bool(t),s.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,n.coinType]});let u=this._sdk.sdkOptions.simulationAccount.address,m=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:s}),g=[],_=m.results[0].returnValues[0][0],b=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(_)),w=m.results[0].returnValues[1][0],f=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(w));return b.forEach((O,h)=>{let A=p(O).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),j=p(f[h]).div(Math.pow(10,r.decimals)).toString();g.push({price:A,quantity:j})}),g?.[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:l={base:"0",quote:"0"}}){try{let u=(0,B.normalizeStructTag)(t.baseCoin.coinType),m=(0,B.normalizeStructTag)(t.quoteCoin.coinType),g=new S.Transaction;l&&(p(l.base).gt(0)||p(l.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},g);let{baseAsset:_,quoteAsset:b,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,g,l),f=await this.getOrderBook(t,"all",6);if(s){let A=f?.ask?.[0]?.price||"0",j=p(A).mul(p(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=p(j).plus(p(j).mul(c)).ceil().toString()}else{let A=await f?.bid?.[0]?.price||"0",j=p(A).mul(p(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=p(j).minus(p(j).mul(c)).floor().toString()}let O=n,h=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(t.address),g.object(e),_,b,w,g.pure.u8(0),g.pure.u64(r),g.pure.bool(s),g.pure.bool(a),g.pure.u64(O),g.object(B.SUI_CLOCK_OBJECT_ID)];return g.setSenderIfNotSet(o),g.moveCall({typeArguments:[u,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),g}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderInfoList(e,t){try{let r=new S.Transaction;e.forEach(c=>{let l=c?.pool,u=c?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(l.pool_id),r.pure.u128(BigInt(u))],typeArguments:[l.baseCoinType,l.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(c=>{let l=c.returnValues[0][0],u=o.parse(new Uint8Array(l));a.push(u)}),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 m=(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(m)).constants}if(o.length===0)return[];let a=o.map(u=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:u})),c=await this.getOrderInfoList(a,t)||[],l=[];return c.forEach(u=>{let m=this.decodeOrderId(BigInt(u.order_id));l.push({...u,price:m.price,isBid:m.isBid,pool:e})}),l}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new S.Transaction;r.forEach(u=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(u.pool_id),n.object(t)],typeArguments:[u.baseCoinType,u.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(u=>u.returnValues?.[0]?.[0])||[],o=k.bcs.struct("VecSet",{constants:k.bcs.vector(k.bcs.U128)}),a=[];i.forEach((u,m)=>{let g=o.parse(new Uint8Array(u)).constants;g.length>0&&g.forEach(_=>{a.push({pool:r[m],orderId:_})})});let c=await this.getOrderInfoList(a,e)||[],l=[];return a.forEach((u,m)=>{let g=this.decodeOrderId(BigInt(u.orderId)),_=c.find(b=>b.order_id===u.orderId)||{};l.push({...u,..._,price:g.price,isBid:g.isBid})}),l}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,c=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)),c={};return i.forEach((u,m)=>{let g=p(u).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),_=p(a[m]).div(Math.pow(10,t.decimals)).toString();c[g]?c[g]={price:g,quantity:p(c[g].quantity).add(_).toString()}:c[g]={price:g,quantity:_}}),Object.values(c)}getLevel2RangeTx(e,t,r,n,s=new S.Transaction){let{baseCoin:i,quoteCoin:o}=e,a=G(p(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),c=G(p(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(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:c}=e;try{if(t==="bid"||t==="all"){let _=n,b=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,_,b,o)}if(t==="ask"||t==="all"){let _=r==="0"?n:r,b=s;o=this.getLevel2RangeTx(e,!1,_,b,o)}let l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:o}),m=[];(t==="bid"||t==="all")&&(m=u.results?.[0]?this.processOrderBookData(u.results[0],a,c,i):[]);let g=[];if(t==="ask"||t==="all"){let _=t==="ask"?0:1;g=u.results?.[_]?this.processOrderBookData(u.results[_],a,c,i):[]}return{bid:m.sort((_,b)=>b.price-_.price),ask:g.sort((_,b)=>_.price-b.price)}}catch{let u=this._sdk.sdkOptions.simulationAccount.address,m=[],g=[];try{let _=this.getLevel2RangeTx(e,!0,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:_});m=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{m=[]}try{let _=this.getLevel2RangeTx(e,!1,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:_});g=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{g=[]}return{bid:m,ask:g}}}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 S.Transaction,n=await this.getMarketPrice(e),{baseCoin:s,quoteCoin:i}=e;if(t==="bid"||t==="all"){let u=Math.pow(10,-6),m=n,g=p(u).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),_=p(m).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(g),r.pure.u64(_),r.pure.bool(!0),r.object(B.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let u=n,m=Math.pow(10,6),g=p(u).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),_=p(m).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(g),r.pure.u64(_),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}),c=[];if(t==="bid"||t==="all"){let u=a.results[0]?.returnValues[0]?.[0],m=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(u)),g=a.results[0]?.returnValues[1]?.[0],_=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(g));m.forEach((b,w)=>{let f=p(b).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),O=p(_[w]).div(Math.pow(10,s.decimals)).toString();c.push({price:f,quantity:O})})}let l=[];if(t==="ask"||t==="all"){let u=t==="ask"?0:1,m=a.results[u]?.returnValues[0]?.[0],g=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(m)),_=a.results[u]?.returnValues[1]?.[0],b=k.bcs.vector(k.bcs.u64()).parse(new Uint8Array(_));g.forEach((w,f)=>{let O=p(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=p(b[f]).div(Math.pow(10,s.decimals)).toString();l.push({price:O,quantity:h})})}return{bid:c,ask:l}}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 c=s.account.open_orders.contents,l=s.account.owed_balances,u=s.account.settled_balances,m=s.account.unclaimed_rebates,g=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:c,owed_balances:l,settled_balances:u,unclaimed_rebates:m,taker_volume:g,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(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),c=[];return a.forEach(l=>{let u=this.buildCoinConfig(l,t);this.updateCache(`${r}_${u.address}_getCoinConfig`,u,864e5),c.push({...u})}),this.updateCache(n,c,864e5),c}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"),C=require("@mysten/sui/transactions"),E=require("@mysten/sui/utils");var Zt=({totalAssetsValue:d,totalDebtValue:e})=>p(e).eq(0)||p(d).eq(0)?"0":p(d).div(p(e)).toString(),je=d=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=d.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:c}=d.value.fields.risk_ratios.fields;return{id:d.id.id,name:d.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}},Be=(d,e)=>{let{deposit_coin_type:t}=e,r=d.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=d.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:c}=d.protocol_fees.fields,{total_supply:l,total_borrow:u}=d.state.fields,m=p(o).sub(l).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:l,total_borrow:u,available_supply:m,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:c}};var me=require("@pythnetwork/pyth-sui-js");var Ee=10n;function Yt(d,e){if(!Ee)throw new Error("oraclePriceMultiplierDecimal is required");if(d===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(Ee- -e);return d*t}return d/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 c=o.price;if(c){let{price:l,expo:u}=c,m=p(l).mul(p(10).pow(p(u))).toString(),_={coin_type:e[a].coinType,price:m,oracle_price:0n,last_update_time:c.publish_time};_.oracle_price=Yt(BigInt(l),BigInt(u)),r[n[a]]=_,this._sdk.updateCache(`getLatestPrice_${_.coin_type}`,_)}}),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 C.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 C.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 C.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.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,_)=>({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}=await this.betchGetOpenOrders({account:e,marginManagerList:t}),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}),Object.values(d).forEach(p=>{p.locked_balances&&p.settled_balances&&(p.locked_balances={...p.locked_balances,base:l(p.locked_balances.base||"0").minus(l(p.settled_balances.base||"0")).toString(),quote:l(p.locked_balances.quote||"0").minus(l(p.settled_balances.quote||"0")).toString(),deep:l(p.locked_balances.deep||"0").minus(l(p.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)}`)}}};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",lr="0x1::coin::CoinStore",dr="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 C.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 C.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 C.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 C.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 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 l=y.bcs.U64.parse(new Uint8Array(c.results[0].returnValues[0][0])),u=y.bcs.U64.parse(new Uint8Array(c.results[1].returnValues[0][0])),m=a?i?l:u:y.bcs.U64.parse(new Uint8Array(c.results[2].returnValues[0][0]));return{[r]:l.toString(),[n]:u.toString(),[this.deepCoin.coinType]:m.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 C.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:c,quotePriceFeedObjectId:l})=>u=>{u.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[u.object(t),u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(c),u.object(l),u.object(s),u.object(i),u.object(o),u.object.clock()],typeArguments:[r.coinType,n.coinType]})};async getManagerState(e,t=new C.Transaction){let{account:r,marginManager:n,baseCoin:s,quoteCoin:i,pool:o,baseMarginPool:a,quoteMarginPool:c,decimals:l=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 u=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),m=u.get(s.feed),g=u.get(i.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let _=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!_.results||!_.results[0]||!_.results[0].returnValues||_.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${_.effects?.status?.error||"Unknown error"}`);let b=(0,E.normalizeSuiAddress)(y.bcs.Address.parse(new Uint8Array(_.results[0].returnValues[0][0]))),w=(0,E.normalizeSuiAddress)(y.bcs.Address.parse(new Uint8Array(_.results[0].returnValues[1][0]))),f=Number(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[2][0])))/1e9,O=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[3][0]))),s.scalar,l),h=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[4][0]))),i.scalar,l),A=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[5][0]))),s.scalar,l),j=this.#e(BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[6][0]))),i.scalar,l),T=y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[7][0])),M=Number(y.bcs.u8().parse(new Uint8Array(_.results[0].returnValues[8][0]))),q=y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[9][0])),I=Number(y.bcs.u8().parse(new Uint8Array(_.results[0].returnValues[10][0]))),P=BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[11][0]))),D=BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[12][0]))),se=BigInt(y.bcs.U64.parse(new Uint8Array(_.results[0].returnValues[13][0])));return{managerId:b,deepbookPoolId:w,riskRatio:f,baseAsset:O,quoteAsset:h,baseDebt:A,quoteDebt:j,basePythPrice:T.toString(),basePythDecimals:M,quotePythPrice:q.toString(),quotePythDecimals:I,currentPrice:P,lowestTriggerAbovePrice:D,highestTriggerBelowPrice:se}}catch(u){throw new Error(`Failed to get manager state: ${u instanceof Error?u.message:String(u)}`)}}async calculateAssets({account:e,marginManager:t,pool:r,baseCoin:n,quoteCoin:s,tx:i=new C.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],c=o.results[0].returnValues[1][0];if(!n.scalar||!s.scalar)throw new Error("Base and quote coin scalars are required");let l=y.bcs.U64.parse(new Uint8Array(a)),u=y.bcs.U64.parse(new Uint8Array(c));return{baseAsset:l.toString(),quoteAsset:u.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=!!p(o).gt(p(a)),l=c?s:i,u=c?o:a,m=new C.Transaction;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(l),m.pure.u64(BigInt(u)),m.object.clock()],typeArguments:[c?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let _=y.bcs.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return c?{baseBorrowedAmount:_.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:_.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 C.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),c=a.get(t.feed),l=a.get(r.feed);if(!c||!l)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(l),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:c},l=new C.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 u=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],l),m=u.get(s.feed),g=u.get(i.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let _=l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[l.object(this._sdk.sdkOptions.margin_utils.global_config_id),l.object(this._sdk.sdkOptions.margin_utils.versioned_id),l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(r),l.object(n),l.object(m),l.object(g),l.object(o),l.pure.u64(BigInt(a)),l.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,i.coinType,c]});return l.transferObjects([_],e),l}catch(u){throw new Error(`Failed to withdraw: ${u instanceof Error?u.message:String(u)}`)}}async borrowBase({marginManager:e,baseMarginPool:t,baseCoin:r,quoteCoin:n,pool:s,amount:i},o=new C.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),c=a.get(r.feed),l=a.get(n.feed);if(!c||!l)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(l),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 C.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),c=a.get(r.feed),l=a.get(n.feed);if(!c||!l)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(l),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 C.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 C.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 C.Transaction){try{let c=this.sdk.senderAddress,l,u=o;o||(l=await this.getBorrowedAmount({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),u=i?l.baseBorrowedAmount:l.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let _=await this.getBaseBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});m=p(u).sub(_).toString()}else{let _=await this.getQuoteBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});m=p(u).sub(_).toString()}p(m).gt(0)&&await this.deposit({...g,amount:m},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},c=new C.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:l,baseCoin:u,quoteCoin:m}=t;if(u.decimals===void 0||m.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(l),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(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[u.coinType,m.coinType]}),c}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:c=Date.now()+31536e8},l=new C.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:u,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let _=BigInt(p(s).mul(10**(g.decimals-m.decimals+9)).toString()),b=BigInt(J(i,m.decimals));if(_<=0n||b<=0n)throw new Error("Price and quantity must be greater than zero");return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.pure.u8(r),l.pure.u8(n),l.pure.u64(_),l.pure.u64(b),l.pure.bool(o),l.pure.bool(a),l.pure.u64(c),l.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[m.coinType,g.coinType]}),l}catch(_){throw new Error(`Failed to place limit order: ${_ instanceof Error?_.message:String(_)}`)}}modifyMarginOrder({marginManager:e,poolInfo:t,orderId:r,newQuantity:n},s=new C.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 C.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 C.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:c,expirationTimestamp:l},u=new C.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 u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),u.object(e),u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(t.id),u.object(r),u.pure.u8(n),u.pure.u8(s),u.pure.u64(i),u.pure.u64(o),u.pure.bool(a),u.pure.bool(c),u.pure.u64(l),u.object(E.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),u}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}placeReduceOnlyMarketOrder({marginManager:e,poolInfo:t,marginPoolId:r,selfMatchingOption:n,quantity:s,isBid:i,payWithDeep:o},a=new C.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(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 C.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 C.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 C.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 C.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 C.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 C.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 C.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 C.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 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(Be(c,n[a]))}return o}async getBaseQuantityIn(e,t,r,n=.01){let s=new C.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])),c=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),l=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:p(t).sub(a.toString()).toString(),quantityInLeft:p(o.toString()).add(l.takerFee).mul(p(1+n)).ceil().toString(),deep_fee_amount:c.toString()}}async getQuoteQuantityIn(e,t,r,n=.01){let s=new C.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])),c=y.bcs.U64.parse(new Uint8Array(i.results[0].returnValues[2][0])),l=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:p(t).sub(o).toString(),quantityInLeft:p(a.toString()).add(p(l.takerFee)).mul(p(1+n)).ceil().toString(),deep_fee_amount:c.toString()}}async getBaseQuantityOutInput(e,t,r){let n=new C.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 C.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 C.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 C.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,l=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return l?`${s}.${l}`: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 C.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 C.Transaction,n=!1){t.forEach(g=>{let _=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(g.poolId),r.object(_)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((g,_)=>({marginManagerId:t[_].marginManagerId,...g?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(g=>g?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=y.bcs.struct("VecSet",{constants:y.bcs.vector(y.bcs.U128)}),c=[];o.forEach((g,_)=>{let b=a.parse(new Uint8Array(g.returnValues[0][0])).constants;b.length>0&&b.forEach(w=>{c.push({pool:{pool_id:t[_].poolId,baseCoinType:t[_].baseCoinType,quoteCoinType:t[_].quoteCoinType},marginManagerId:t[_].marginManagerId,orderId:w})})});let l=s.results.filter(g=>g?.returnValues?.length===3),u=[];l.forEach((g,_)=>{u.push({marginManagerId:t[_].marginManagerId,base:y.bcs.U64.parse(new Uint8Array(g.returnValues[0][0])),quote:y.bcs.U64.parse(new Uint8Array(g.returnValues[1][0])),deep:y.bcs.U64.parse(new Uint8Array(g.returnValues[2][0]))})});let m=[];return c.forEach((g,_)=>{let b=this.sdk.DeepbookUtils.decodeOrderId(BigInt(g.orderId));m.push({...g,price:b.price.toString(),isBid:b.isBid})}),{openOrders:m,settledBalances:i,lockedBalances:u}}async getSingleMarginManagerOpenOrders({account:e,marginManagerId:t,poolId:r,baseCoinType:n,quoteCoinType:s,baseMarginPool:i,quoteMarginPool:o}){let a=new C.Transaction,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 l=y.bcs.struct("VecSet",{constants:y.bcs.vector(y.bcs.U128)}),m=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),g=l.parse(new Uint8Array(m.returnValues[0][0])).constants,_=[];g.forEach(h=>{_.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let b=_?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(_,e)||[]:[],w=[];_.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 C.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 O={base:"0",quote:"0",deep:"0"};try{let h=new C.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});O={marginManagerId:t,...O,...j?.events?.parsedJson?.account?.settled_balances||{}}}catch{}return{openOrders:w,settledBalances:[O],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 C.Transaction,a=0,c=[];t.forEach(m=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),c[a]={type:"base_balance",marginManagerId:m.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),c[a]={type:"quote_balance",marginManagerId:m.marginManagerId},a++;let g=i?.find(_=>_.marginManagerId===m.marginManagerId);if(g&&(Number(g.baseBorrowedShare)>0||Number(g.quoteBorrowedShare)>0)){let _=g.baseBorrowedShare,b=g.quoteBorrowedShare,w=!!p(_).gt(p(b)),f=w?m.baseMarginPool:m.quoteMarginPool,O=w?_: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(O)),o.object.clock()],typeArguments:[w?m?.baseCoinType:m?.quoteCoinType]}),c[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:m.marginManagerId},a++}});let l=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),u=Object.fromEntries(t.map(m=>[m.marginManagerId,{...m,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 l?.results?.forEach((m,g)=>{let _=c[g],b=y.bcs.U64.parse(new Uint8Array(m.returnValues[0][0]));u[_.marginManagerId]={...u[_.marginManagerId],[_.type]:b}}),r.forEach(m=>{u[m.marginManagerId].open_orders.push(m)}),n.forEach(m=>{u[m.marginManagerId].settled_balances=m}),s.forEach(m=>{u[m.marginManagerId].locked_balances=m}),Object.values(u).forEach(m=>{m.locked_balances&&m.settled_balances&&(m.locked_balances={...m.locked_balances,base:p(m.locked_balances.base||"0").minus(p(m.settled_balances.base||"0")).toString(),quote:p(m.locked_balances.quote||"0").minus(p(m.settled_balances.quote||"0")).toString(),deep:p(m.locked_balances.deep||"0").minus(p(m.settled_balances.deep||"0")).toString()})}),u}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:l,conditional_order_id:u,pending_order:m,is_trigger_below_price:g,trigger_price:_}=e,b=await this.pythPrice.updatePythPriceIDs([c.feed,l.feed],t),w=b.get(c.feed),f=b.get(l.feed);if(!w||!f)throw new Error("Failed to get price feed object IDs");let O=t.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[t.pure.bool(g),t.pure.u64(_)]}),h=this.newPendingOrder(m,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 u=="string"?t.pure.u64(BigInt(u)):u,O,h,t.object(H.CLOCK_ADDRESS)],typeArguments:[c.coinType,l.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:l,expire_timestamp:u}=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(l),t.pure.u64(u)]})}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: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(H.CLOCK_ADDRESS)],typeArguments:[o,a]})}async getConditionalOrders(e,t){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(a=>{let{margin_manager_id:c,base_coin_type:l,quote_coin_type:u,conditional_order_ids:m}=a;m.forEach(g=>{t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[t.object(c),t.pure.u64(g)],typeArguments:[l,u]})})});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:(0,E.normalizeSuiAddress)("0x0"),transactionBlock:t});if(!n?.results)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 c=new Uint8Array(a.returnValues[0][0]);if(c.length===0)return null;let l;if(c[0]===0)return null;c[0]===1?l=c.subarray(1):l=c;let u=o.parse(l),m=this.normalizeConditionalOrder(u);return e.forEach(g=>{g.conditional_order_ids.find(b=>b===m.conditional_order_id)&&(m.margin_manager_id=g.margin_manager_id,m.base_coin_type=g.base_coin_type,m.quote_coin_type=g.quote_coin_type)}),m}catch{return null}})}async getConditionalOrderIds(e,t){t=t||new C.Transaction;let{deepbook:r}=this.sdk.sdkOptions,n={};return e.forEach(i=>{let{margin_manager_id:o,base_coin_type:a,quote_coin_type:c}=i;t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order_ids`,arguments:[t.object(o)],typeArguments:[a,c]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:(0,E.normalizeSuiAddress)("0x0"),transactionBlock:t})).results.forEach((i,o)=>{if(i?.returnValues?.[0]?.[0]){let a=new Uint8Array(i.returnValues[0][0]),c=y.bcs.vector(y.bcs.u64()).parse(a),l={margin_manager_id:e[o].margin_manager_id,base_coin_type:e[o].base_coin_type,quote_coin_type:e[o].quote_coin_type,conditional_order_ids:c.map(u=>u.toString())};n[e[o].margin_manager_id]=l}}),n}normalizeConditionalOrder(e){let t=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",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 Ze=require("@mysten/sui/client"),re=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(d,e){return e===0n?0n:d*R/e}function et(d,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(d<n)return t+d*r/R;{let i=d-n,o=n*r/R,a=i*s/R;return t+o+a}}function Me(d,e){let t=d*e,r=t/R;return t%R>0n?r+1n:r}function tt(d,e,t,r){let n=e.borrow_shares===0n?R:e.total_borrow*R/e.borrow_shares,s=Me(d,n),i=Xe(e.total_borrow,e.total_supply),o=et(i,t),a=r-e.last_update_timestamp,c=e.total_borrow*o/R*a/Ye,l=e.borrow_shares===0n?0n:Me(c,d*R/e.borrow_shares),u=s+l;return{confirmedDebt:s,estimatedInterest:l,totalDebt:u,annualInterestRate:o}}function er(d,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=tt(d,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 rt.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(c=>{BigInt(c.balance)>0&&n.push({coinAddress:$(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 tr="0x0000000000000000000000000000000000000000000000000000000000000006",rr="pool_script",nr="pool_script_v2",sr="router",ir="router_with_partner",or="fetcher_script",ar="expect_swap",cr="utils",dr="0x1::coin::CoinInfo",ur="0x1::coin::CoinStore",lr="custodian_v2",pr="clob_v2",gr="endpoints_v2",mr=d=>{if(typeof d=="string"&&d.startsWith("0x"))return"object";if(typeof d=="number"||typeof d=="bigint")return"u64";if(typeof d=="boolean")return"bool";throw new Error(`Unknown type for value: ${d}`)};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 _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 lr(c){let e=z(c);if(e?.content?.dataType==="package")return e.content.disassembled}function le(c){let e="data"in c?z(c):c;if(!(!e||!nt(e)||e.content.dataType!=="moveObject"))return e.content}function st(c){return le(c)?.type}function dr(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=le(c)?.fields;if(e)return"fields"in e?e.fields:e}function br(c){return le(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 de=1e6,$=1e9,ut={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},lt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},X=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?lt: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(de).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(de).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(de).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 dt,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 dt(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 Ne=Object.defineProperty;var Le=(d,e,t)=>e in d?Ne(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var _e=(d,e,t)=>(Le(d,typeof e!="symbol"?e+"":e,t),t);import{SuiGraphQLClient as wt}from"@mysten/sui/graphql";import{DeepBookClient as at}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 ct}from"@mysten/sui/utils";import{Base64 as dt}from"js-base64";import{coinWithBalance as we}from"@mysten/sui/transactions";import{SUI_TYPE_ARG as Qe,normalizeStructTag as He,normalizeSuiObjectId as ie}from"@mysten/sui/utils";var Ge=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function be(d){return d.startsWith("0x")?d:`0x${d}`}function se(d){return d.startsWith("0x")?`${d.slice(2)}`:d}function xe(d,e=4,t=4){let r=Math.max(e,1),n=Math.max(t,1);return`${d.slice(0,r+2)} ... ${d.slice(-n)}`}function At(d,e=4,t=4){return xe(be(d),e,t)}function St(d,e={leadingZero:!0}){if(typeof d!="string")return!1;let t=d;if(e.leadingZero){if(!d.startsWith("0x"))return!1;t=t.substring(2)}return Ge.test(t)}function Ke(d){if(!Buffer.isBuffer(d))if(Array.isArray(d))d=Buffer.from(d);else if(typeof d=="string")exports.isHexString(d)?d=Buffer.from(exports.padToEven(exports.stripHexPrefix(d)),"hex"):d=Buffer.from(d);else if(typeof d=="number")d=exports.intToBuffer(d);else if(d==null)d=Buffer.allocUnsafe(0);else if(d.toArray)d=Buffer.from(d.toArray());else throw new Error("invalid type");return d}function jt(d){return be(Ke(d).toString("hex"))}function Bt(d){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<d.length;n++)t.setUint8(n,d.charCodeAt(n));return t.getUint32(0,!0)}function ze(d){let e,t,r,n,s;e="";let i=d.length;for(t=0;t<i;)switch(r=d.charCodeAt(t++),r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=d.charAt(t-1);break;case 12:case 13:n=d.charCodeAt(t++),e+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=d.charCodeAt(t++),s=d.charCodeAt(t++),e+=String.fromCharCode((r&15)<<12|(n&63)<<6|(s&63)<<0);break}return e}function Et(d){let e="",t=se(d),r=t.length/2;for(let n=0;n<r;n++)e+=String.fromCharCode(Number.parseInt(t.substr(n*2,2),16));return ze(e)}var We=0,fe=1,Je=2;function he(d,e){return d===e?We:d<e?fe:Je}function Ze(d,e){let t=0,r=d.length<=e.length?d.length:e.length,n=he(d.length,e.length);for(;t<r;){let s=he(d.charCodeAt(t),e.charCodeAt(t));if(t+=1,s!==0)return s}return n}function It(d,e){return Ze(d,e)===fe}function ye(d,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[d,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function Dt(d){return d.split("::")[0]}function R(d){try{let e=d.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===ce||e===ke?"0x2":ie(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:d,address:"",module:"",name:"",type_arguments:[],source_address:d}}}function oe(d){return R(d).source_address}function Ye(d){return d.toLowerCase().startsWith("0x")?ie(d):d}var Ut=(d,e=!0)=>{let t=d.split("::"),r=t.shift(),n=ie(r);return e&&(n=se(n)),`${n}::${t.join("::")}`};function ae(d){for(let e in d){let t=typeof d[e];if(t==="object")ae(d[e]);else if(t==="string"){let r=d[e];d[e]=Ye(r)}}}var $t=He(Qe);var Xe="0x2::coin::Coin",et=/^0x2::coin::Coin<(.+)>$/,Nt=1e3,Lt=500,Gt=100,xt=100,Kt=1e3,ce="0x2::sui::SUI",ke="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",zt="SUI",Qt=450,Ht="0x0000000000000000000000000000000000000005",E=class{static getCoinTypeArg(e){let t=e.type.match(et);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`${Xe}<${e}>`}static getCoinAssets(e,t){let r=[];return t.forEach(n=>{oe(n.coinAddress)===oe(e)&&r.push(n)}),r}static isSuiCoin(e){return R(e).full_address===ce}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,l=a.findIndex(m=>m.balance>=c);if(l!==-1){o.push(a[l]),a.splice(l,1);break}let u=a.pop();u.balance>0&&(o.push(u),i+=u.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(d){return Date.parse(new Date().toString())+d}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 p(d){return Z.isDecimal(d)?d:new Z(d===void 0?0:d)}function de(d){return p(10).pow(p(d).abs())}var G=(d,e)=>{try{return p(d).toDP(e,Z.ROUND_DOWN).toString()}catch{return d}},ue=(d,e)=>Z.max(p(d),p(e));function W(d,e){let t=de(p(e));return Number(p(d).mul(t))}function nr(d,e=32){return BigInt.asUintN(e,BigInt(d)).toString()}function sr(d,e=32){return Number(BigInt.asIntN(e,BigInt(d)))}function x(d,e){let t=de(p(e));return Number(p(d).div(t))}function ir(d,e="hex"){if(d instanceof Uint8Array){let r=Buffer.from(d);return Te.fromSecretKey(r)}let t=e==="hex"?je(d):Se(d);return Te.fromSecretKey(t)}function or(d,e="hex"){if(d instanceof Uint8Array){let r=Buffer.from(d);return Ae.fromSecretKey(r)}let t=e==="hex"?je(d):Se(d);return Ae.fromSecretKey(t)}var Be=async d=>new Promise(e=>{setTimeout(()=>{e(1)},d)});var Ee={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},ve={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6};function Me(...d){let e="DeepbookV3_Utils_Sdk###"}function Q(d){return d.data}function tt(d){if(d.error&&"object_id"in d.error&&"version"in d.error&&"digest"in d.error){let{error:e}=d;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function rt(d){if(d.error&&"object_id"in d.error&&!("version"in d.error)&&!("digest"in d.error))return d.error.object_id}function qe(d){if("reference"in d)return d.reference;let e=Q(d);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:tt(d)}function Pe(d){return"objectId"in d?d.objectId:qe(d)?.objectId??rt(d)}function ur(d){return"version"in d?d.version:qe(d)?.version}function nt(d){return d.data!==void 0}function st(d){return d.content!==void 0}function lr(d){let e=Q(d);if(e?.content?.dataType==="package")return e.content.disassembled}function le(d){let e="data"in d?Q(d):d;if(!(!e||!st(e)||e.content.dataType!=="moveObject"))return e.content}function it(d){return le(d)?.type}function pr(d){let e=nt(d)?d.data:d;return!e?.type&&"data"in d?e?.content?.dataType==="package"?"package":it(d):e?.type}function gr(d){return Q(d)?.previousTransaction}function mr(d){return Q(d)?.owner}function _r(d){let e=Q(d)?.display;return e||{data:null,error:null}}function Ie(d){let e=le(d)?.fields;if(e)return"fields"in e?e.fields:e}function br(d){return le(d)?.hasPublicTransfer??!1}import{Transaction as ot}from"@mysten/sui/transactions";async function kr(d,e=!0){d.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 l=new ot;return{fixAmount:r,newTx:l}}}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(),l=a.objectArray;if(i)return{targetCoin:e.makeMoveVec({elements:l.map(f=>e.object(f))}),remainCoins:a.remainCoins,tragetCoinAmount:a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),isMintZeroCoin:!1};let[u,...m]=l,g=e.object(u),_=g,b=a.amountArray.reduce((f,C)=>Number(f)+Number(C),0).toString(),w;return m.length>0&&e.mergeCoins(g,m.map(f=>e.object(f))),o&&Number(c)>Number(n)&&(_=e.splitCoins(g,[e.pure.u64(n)]),b=n.toString(),w=g),{targetCoin:_,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 pe=1e6,$=1e9,ut={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},lt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},X=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?lt: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=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(l=>l.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],c=[];return a.forEach(l=>{c.push({balanceManager:l,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],l=o.returnValues[0][0],u=k.U64.parse(new Uint8Array(l)),m=p(u),g=m.eq(0)?"0":m.div(Math.pow(10,c.decimals)).toString();i[c.coinType]={adjusted_balance:g,balance:m.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={},l=a*t.length;t.forEach((u,m)=>{let g=l+m,_=s.results?.[g];if(_){let b=_.returnValues[0][0],w=k.U64.parse(new Uint8Array(b)),f=p(w),C=f.eq(0)?"0":f.div(Math.pow(10,u.decimals)).toString();c[u.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 p(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 u=c[1].split(", ");i.push({...a,baseCoinType:u[0],quoteCoinType:u[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:p(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:p(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(a).div(pe).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:p(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:p(i).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(o).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(a).div(pe).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:p(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:p(r).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:p(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:p(a).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:p(c).div(pe).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:l}=e,u=p(c).div($).toString(),m=p(l).div($).toString(),g=await this.getMarketPrice(e),_=i?r:g!=="0"?g:o;if(_==="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=p(_).div(b).mul(w).mul($).toString();if(n){let A=await this.getMarketPrice(e),T=p(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=p(t).mul(p(u)).mul(p(B.deep_per_asset)).div(p($)),q=p(t).mul(p(m)).mul(p(B.deep_per_asset)).div(p($));B.asset_is_base||(I=I.mul(M).div(p($)),q=q.mul(M).div(p($)));let D=I.ceil().toString(),J=q.ceil().toString();return{takerFee:D,makerFee:J,takerFeeDisplay:x(D,a.decimals).toString(),makerFeeDisplay:x(J,a.decimals).toString(),feeType:a.coinType}}if(s){let A=ue(f,i?r:g),S=p(t).mul(A).mul(p(u).mul(1.25)).div(p($)).ceil().toFixed(0),T=p(t).mul(A).mul(p(m).mul(1.25)).div(p($)).ceil().toFixed(0);return{takerFee:S,makerFee:T,takerFeeDisplay:x(S,e.quoteCoin.decimals).toString(),makerFeeDisplay:x(T,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=p(t).mul(p(u).mul(1.25)).ceil().toFixed(0),h=p(t).mul(p(m).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:h,takerFeeDisplay:x(C,e.baseCoin.decimals).toString(),makerFeeDisplay:x(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(p(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 l=await this.getManagerBalance({account:s,balanceManager:o,coins:c}),u=l?.[t]?.balance||"0",m=l?.[r]?.balance||"0",g=i&&l?.[a.coinType]?.balance||"0";return{baseManagerBlance:u,quoteManagerBlance:m,feeManaerBalance:g}}catch(c){throw c instanceof Error?c:new Error(String(c))}}getFeeAsset(e,t,r,n,s,i,o,a,c,l){let u=p(e).gt(0)&&c,m="0";if(!u)return{feeAsset:this.getEmptyCoin(l,t),haveDepositFee:"0"};if(i||o){let g=p(s).sub(i?n:r);m=g.lte(0)?e:g.sub(e).lt(0)?g.sub(e).toString():"0"}else m=p(s).sub(e).lt("0")?p(s).sub(e).abs().toString():"0";return{feeAsset:p(m).gt("0")?this.getCoinAssets(t,m,a,l):this.getEmptyCoin(l,t),haveDepositFee:m}}async getTransactionRelatedAssets(e,t,r,n,s,i,o,a,c){try{let l=this.deepCoin,u=U(e.baseCoin.coinType),m=U(e.quoteCoin.coinType),g=u===l.coinType,_=m===l.coinType,b=!g&&!_,{baseManagerBlance:w,quoteManagerBlance:f,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,u,m,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=p(r).add(p(n)).toString());let M=p(f).sub(r).toString();p(M).lt(0)?(S=!0,A=this.getCoinAssets(m,M,T,c)):A=this.getEmptyCoin(c,m),h=this.getEmptyCoin(c,u)}else{o||(t=p(t).add(p(n)).toString());let M=p(w).sub(t).toString();p(M).lt(0)?(S=!0,h=this.getCoinAssets(u,M,T,c)):h=this.getEmptyCoin(c,u),A=this.getEmptyCoin(c,m)}let B=this.getFeeAsset(n,l.coinType,t,r,C,_,g,T,o,c);return{baseAsset:h,quoteAsset:A,feeAsset:B,haveDeposit:S}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getMarketTransactionRelatedAssets(e,t,r,n,s,i,o,a,c,l){try{let u=this.deepCoin,m=U(e.baseCoin.coinType),g=U(e.quoteCoin.coinType),_=m===u.coinType,b=g===u.coinType,w=!_&&!b,f=await this.getTransactionRelatedBalance(e,m,g,w,i,o,a),{feeManaerBalance:C}=f,h=p(f.baseManagerBlance).add(p(l?.base||"0")).toString(),A=p(f.quoteManagerBlance).add(p(l?.quote||"0")).toString(),S=await this._sdk.getOwnerCoinAssets(i),T;o&&p(C).lt(n)?T=this.getCoinAssets(u.coinType,p(n).sub(C).toString(),S,c):T=this.getEmptyCoin(c,u.coinType);let B,M;if(s){o||(r=p(r).add(p(n)).toString());let I=p(A).sub(r).toString();if(p(I).lt(0)){let q;p(A).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.quoteCoin,amountToWithdraw:A,returnAssets:!0,txb:c}));let D=this.getCoinAssets(g,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,m)}else{o||(t=p(t).add(p(n)).toString());let I=p(h).sub(t).toString();if(p(I).lt(0)){let q;p(h).gt(0)&&(q=this.withdrawFromManager({account:i,balanceManager:a,coin:e.baseCoin,amountToWithdraw:h,returnAssets:!0,txb:c}));let D=this.getCoinAssets(m,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,g)}return{baseAsset:B,quoteAsset:M,feeAsset:T}}catch(u){throw u instanceof Error?u:new Error(String(u))}}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 l=this.deepCoin,u=e.address,m=e.baseCoin.decimals,g=e.quoteCoin.decimals,_=e.baseCoin.coinType,b=e.quoteCoin.coinType,w=p(t).mul(10**(g-m+9)).toString(),f=U(_),C=U(b),h=new j,A,S,T=await this._sdk.getOwnerCoinAssets(o);if(s){let q=p(t).mul(p(r).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();a||(q=p(q).add(p(i)).toString()),S=N.buildCoinForAmount(h,T,BigInt(q),C,!1,!0)?.targetCoin}else{let q=r;a||(q=p(r).abs().add(p(i)).toString()),A=N.buildCoinForAmount(h,T,BigInt(p(q).abs().toString()),f,!1,!0)?.targetCoin}let B=a?p(i).gt(0)?N.buildCoinForAmount(h,T,BigInt(p(i).abs().ceil().toString()),l.coinType,!1,!0).targetCoin:this.getEmptyCoin(h,l.coinType):this.getEmptyCoin(h,l.coinType),M=h.moveCall({typeArguments:[s?_: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(u),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(l){throw l instanceof Error?l:new Error(String(l))}}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,l=e.quoteCoin.coinType,u=U(c),m=U(l),g=new j,_,b,w=t,f,C=await this.getOrderBook(e,"all",6);if(r){let T=C?.ask?.[0]?.price||"0",B=p(T).mul(p(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=p(B).plus(p(B).mul(o)).ceil().toString()}else{let T=await C?.bid?.[0]?.price||"0",B=p(T).mul(p(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();f=p(B).minus(p(B).mul(o)).floor().toString()}let h=await this._sdk.getOwnerCoinAssets(s);r?(i||(f=p(f).add(p(n)).toString()),b=this.getCoinAssets(m,f,h,g),_=this.getEmptyCoin(g,u)):(i||(w=p(w).add(p(n)).toString()),b=this.getEmptyCoin(g,m),_=this.getCoinAssets(u,w,h,g));let A=i?p(n).gt(0)?N.buildCoinForAmount(g,h,BigInt(p(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(g,this.deepCoin.coinType):this.getEmptyCoin(g,this.deepCoin.coinType),S=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(a),_,b,A,g.pure.u8(0),g.pure.u64(t),g.pure.bool(r),g.pure.bool(i),g.pure.u64(f),g.object(P)];return g.moveCall({typeArguments:[u,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:S}),g}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:l=Date.now()+31536e8}){try{let u=this.deepCoin,m=p(r).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),g=t.baseCoin.coinType,_=t.quoteCoin.coinType,b=new j,w=s?p(r).mul(p(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(m),b.pure.u64(n),b.pure.bool(s),b.pure.bool(c),b.pure.u64(l),b.object(P)];return b.moveCall({typeArguments:[g,_],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:M}),b}let T=new j;p(A.haveDepositFee).gt(0)&&this.depositIntoManager({account:a,balanceManager:e,coin:u,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(m),T.pure.u64(n),T.pure.bool(s),T.pure.bool(c),T.pure.u64(l),T.object(P)];return T.moveCall({typeArguments:[g,_],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:B}),T}catch(u){throw u instanceof Error?u:new Error(String(u))}}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=p(s).gt(0)?s:Math.pow(10,-1),o=Math.pow(10,6),a=p(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=p(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 l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:n}),m=[],g=u.results[0].returnValues[0][0],_=k.vector(k.u64()).parse(new Uint8Array(g)),b=u.results[0].returnValues[1][0],w=k.vector(k.u64()).parse(new Uint8Array(b));return _.forEach((f,C)=>{let h=p(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=p(w[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:h,quantity:A})}),m?.[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=p(s).gt(0)?p(s).div(3).toNumber():Math.pow(10,-6),o=p(s).gt(0)?s:Math.pow(10,6),a=p(i).mul(Math.pow(10,9+r.decimals-t.decimals)).toString(),c=p(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(G(a,0)),n.pure.u64(G(c,0)),n.pure.bool(!0),n.object(P)],typeArguments:[t.coinType,r.coinType]});let l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:n}),m=[],g=u.results[0].returnValues[0][0],_=k.vector(k.u64()).parse(new Uint8Array(g)),b=u.results[0].returnValues[1][0],w=k.vector(k.u64()).parse(new Uint8Array(b));return _.forEach((f,C)=>{let h=p(f).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),A=p(w[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:h,quantity:A})}),m?.[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=p(i).gt(0)?p(i).div(3).toNumber():Math.pow(10,-6),a=p(i).gt(0)?i:Math.pow(10,6)):(o=p(i).gt(0)?i:Math.pow(10,-1),a=p(i).gt(0)?p(i).mul(3).toNumber():Math.pow(10,6));let c=p(o).mul(Math.pow(10,9+n.decimals-r.decimals)).toString(),l=p(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(G(c,0)),s.pure.u64(G(l,0)),s.pure.bool(t),s.object(P)],typeArguments:[r.coinType,n.coinType]});let u=this._sdk.sdkOptions.simulationAccount.address,m=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:s}),g=[],_=m.results[0].returnValues[0][0],b=k.vector(k.u64()).parse(new Uint8Array(_)),w=m.results[0].returnValues[1][0],f=k.vector(k.u64()).parse(new Uint8Array(w));return b.forEach((C,h)=>{let A=p(C).div(Math.pow(10,9+n.decimals-r.decimals)).toString(),S=p(f[h]).div(Math.pow(10,r.decimals)).toString();g.push({price:A,quantity:S})}),g?.[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:l={base:"0",quote:"0"}}){try{let u=U(t.baseCoin.coinType),m=U(t.quoteCoin.coinType),g=new j;l&&(p(l.base).gt(0)||p(l.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},g);let{baseAsset:_,quoteAsset:b,feeAsset:w}=await this.getMarketTransactionRelatedAssets(t,r,n,i,s,o,a,e,g,l),f=await this.getOrderBook(t,"all",6);if(s){let A=f?.ask?.[0]?.price||"0",S=p(A).mul(p(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=p(S).plus(p(S).mul(c)).ceil().toString()}else{let A=await f?.bid?.[0]?.price||"0",S=p(A).mul(p(r).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=p(S).minus(p(S).mul(c)).floor().toString()}let C=n,h=[g.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),g.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),g.object(t.address),g.object(e),_,b,w,g.pure.u8(0),g.pure.u64(r),g.pure.bool(s),g.pure.bool(a),g.pure.u64(C),g.object(P)];return g.setSenderIfNotSet(o),g.moveCall({typeArguments:[u,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:h}),g}catch(u){throw u instanceof Error?u:new Error(String(u))}}async getOrderInfoList(e,t){try{let r=new j;e.forEach(c=>{let l=c?.pool,u=c?.orderId;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[r.object(l.pool_id),r.pure.u128(BigInt(u))],typeArguments:[l.baseCoinType,l.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 l=c.returnValues[0][0],u=o.parse(new Uint8Array(l));a.push(u)}),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 m=(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(m)).constants}if(o.length===0)return[];let a=o.map(u=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:u})),c=await this.getOrderInfoList(a,t)||[],l=[];return c.forEach(u=>{let m=this.decodeOrderId(BigInt(u.order_id));l.push({...u,price:m.price,isBid:m.isBid,pool:e})}),l}async getAllMarketsOpenOrders(e,t){try{let r=await this.getPools(),n=new j;r.forEach(u=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[n.object(u.pool_id),n.object(t)],typeArguments:[u.baseCoinType,u.quoteCoinType]})});let i=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n})).results?.map(u=>u.returnValues?.[0]?.[0])||[],o=k.struct("VecSet",{constants:k.vector(k.U128)}),a=[];i.forEach((u,m)=>{let g=o.parse(new Uint8Array(u)).constants;g.length>0&&g.forEach(_=>{a.push({pool:r[m],orderId:_})})});let c=await this.getOrderInfoList(a,e)||[],l=[];return a.forEach((u,m)=>{let g=this.decodeOrderId(BigInt(u.orderId)),_=c.find(b=>b.order_id===u.orderId)||{};l.push({...u,..._,price:g.price,isBid:g.isBid})}),l}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 at({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((u,m)=>{let g=p(u).div(Math.pow(10,9+r.decimals-t.decimals)).toString(),_=p(a[m]).div(Math.pow(10,t.decimals)).toString();c[g]?c[g]={price:g,quantity:p(c[g].quantity).add(_).toString()}:c[g]={price:g,quantity:_}}),Object.values(c)}getLevel2RangeTx(e,t,r,n,s=new j){let{baseCoin:i,quoteCoin:o}=e,a=G(p(r).mul(Math.pow(10,9+o.decimals-i.decimals)).toString(),0),c=G(p(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 _=n,b=r==="0"?s:r;o=this.getLevel2RangeTx(e,!0,_,b,o)}if(t==="ask"||t==="all"){let _=r==="0"?n:r,b=s;o=this.getLevel2RangeTx(e,!1,_,b,o)}let l=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:l,transactionBlock:o}),m=[];(t==="bid"||t==="all")&&(m=u.results?.[0]?this.processOrderBookData(u.results[0],a,c,i):[]);let g=[];if(t==="ask"||t==="all"){let _=t==="ask"?0:1;g=u.results?.[_]?this.processOrderBookData(u.results[_],a,c,i):[]}return{bid:m.sort((_,b)=>b.price-_.price),ask:g.sort((_,b)=>_.price-b.price)}}catch{let u=this._sdk.sdkOptions.simulationAccount.address,m=[],g=[];try{let _=this.getLevel2RangeTx(e,!0,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:_});m=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{m=[]}try{let _=this.getLevel2RangeTx(e,!1,n,r),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:u,transactionBlock:_});g=b.results?.[0]?this.processOrderBookData(b.results[0],a,c,i):[]}catch{g=[]}return{bid:m,ask:g}}}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 u=Math.pow(10,-6),m=n,g=p(u).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),_=p(m).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(g),r.pure.u64(_),r.pure.bool(!0),r.object(P)],typeArguments:[s.coinType,i.coinType]})}if(t==="ask"||t==="all"){let u=n,m=Math.pow(10,6),g=p(u).mul(Math.pow(10,9+i.decimals-s.decimals)).toString(),_=p(m).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(g),r.pure.u64(_),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 u=a.results[0]?.returnValues[0]?.[0],m=k.vector(k.u64()).parse(new Uint8Array(u)),g=a.results[0]?.returnValues[1]?.[0],_=k.vector(k.u64()).parse(new Uint8Array(g));m.forEach((b,w)=>{let f=p(b).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),C=p(_[w]).div(Math.pow(10,s.decimals)).toString();c.push({price:f,quantity:C})})}let l=[];if(t==="ask"||t==="all"){let u=t==="ask"?0:1,m=a.results[u]?.returnValues[0]?.[0],g=k.vector(k.u64()).parse(new Uint8Array(m)),_=a.results[u]?.returnValues[1]?.[0],b=k.vector(k.u64()).parse(new Uint8Array(_));g.forEach((w,f)=>{let C=p(w).div(Math.pow(10,9+i.decimals-s.decimals)).toString(),h=p(b[f]).div(Math.pow(10,s.decimals)).toString();l.push({price:C,quantity:h})})}return{bid:c,ask:l}}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,l=s.account.owed_balances,u=s.account.settled_balances,m=s.account.unclaimed_rebates,g=s.account.taker_volume;i.push({balance_manager_id:e,open_orders:c,owed_balances:l,settled_balances:u,unclaimed_rebates:m,taker_volume:g,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(l=>l.objectId),a=await this._sdk.fullClient.batchGetObjects(o,{showContent:!0}),c=[];return a.forEach(l=>{let u=this.buildCoinConfig(l,t);this.updateCache(`${r}_${u.address}_getCoinConfig`,u,864e5),c.push({...u})}),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=ct(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 me,CoinAssist as Re}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 ee}from"@mysten/sui/utils";var Vr=({totalAssetsValue:d,totalDebtValue:e})=>p(e).eq(0)||p(d).eq(0)?"0":p(d).div(p(e)).toString(),Ue=d=>{let{base_margin_pool_id:e,quote_margin_pool_id:t,enabled:r,pool_liquidation_reward:n,user_liquidation_reward:s}=d.value.fields,{liquidation_risk_ratio:i,min_borrow_risk_ratio:o,min_withdraw_risk_ratio:a,target_liquidation_risk_ratio:c}=d.value.fields.risk_ratios.fields;return{id:d.id.id,name:d.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=(d,e)=>{let{deposit_coin_type:t}=e,r=d.id.id,{max_utilization_rate:n,min_borrow:s,protocol_spread:i,supply_cap:o}=d.config.fields.margin_pool_config.fields,{maintainer_fees:a,protocol_fees:c}=d.protocol_fees.fields,{total_supply:l,total_borrow:u}=d.state.fields,m=p(o).sub(l).toString();return{deposit_coin_type:t,id:r,supply_cap:o,total_supply:l,total_borrow:u,available_supply:m,max_utilization_rate:n,min_borrow:s,protocol_spread:i,maintainer_fees:a,protocol_fees:c}};import{SuiPriceServiceConnection as pt,SuiPythClient as gt}from"@pythnetwork/pyth-sui-js";var ge=10n;function mt(d,e){if(!ge)throw new Error("oraclePriceMultiplierDecimal is required");if(d===0n)throw new Error("Invalid oracle price");if(e<0n){let t=10n**(ge- -e);return d*t}return d/10n**(e+ge)}var H=class{_sdk;connection;suiPythClient;hasChangeConnection=!1;_cache={};constructor(e){this._sdk=e,this.connection=new pt(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 c=o.price;if(c){let{price:l,expo:u}=c,m=p(l).mul(p(10).pow(p(u))).toString(),_={coin_type:e[a].coinType,price:m,oracle_price:0n,last_update_time:c.publish_time};_.oracle_price=mt(BigInt(l),BigInt(u)),r[n[a]]=_,this._sdk.updateCache(`getLatestPrice_${_.coin_type}`,_)}}),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 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.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,_)=>({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}=await this.betchGetOpenOrders({account:e,marginManagerList:t}),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}),Object.values(d).forEach(p=>{p.locked_balances&&p.settled_balances&&(p.locked_balances={...p.locked_balances,base:l(p.locked_balances.base||"0").minus(l(p.settled_balances.base||"0")).toString(),quote:l(p.locked_balances.quote||"0").minus(l(p.settled_balances.quote||"0")).toString(),deep:l(p.locked_balances.deep||"0").minus(l(p.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)}`)}}};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,de 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,le as getMoveObject,st as getMoveObjectType,lr 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,dr 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 l=y.U64.parse(new Uint8Array(c.results[0].returnValues[0][0])),u=y.U64.parse(new Uint8Array(c.results[1].returnValues[0][0])),m=a?i?l:u:y.U64.parse(new Uint8Array(c.results[2].returnValues[0][0]));return{[r]:l.toString(),[n]:u.toString(),[this.deepCoin.coinType]:m.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:l})=>u=>{u.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_manager::manager_state`,arguments:[u.object(t),u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(c),u.object(l),u.object(s),u.object(i),u.object(o),u.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:l=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 u=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],t),m=u.get(s.feed),g=u.get(i.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");t.add(this.managerState({...e,basePriceFeedObjectId:m,quotePriceFeedObjectId:g}));let _=await this.sdk.fullClient.devInspectTransactionBlock({sender:r,transactionBlock:t});if(!_.results||!_.results[0]||!_.results[0].returnValues||_.results[0].returnValues.length<14)throw new Error(`Failed to get margin manager state: ${_.effects?.status?.error||"Unknown error"}`);let b=ee(y.Address.parse(new Uint8Array(_.results[0].returnValues[0][0]))),w=ee(y.Address.parse(new Uint8Array(_.results[0].returnValues[1][0]))),f=Number(y.U64.parse(new Uint8Array(_.results[0].returnValues[2][0])))/1e9,C=this.#e(BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[3][0]))),s.scalar,l),h=this.#e(BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[4][0]))),i.scalar,l),A=this.#e(BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[5][0]))),s.scalar,l),S=this.#e(BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[6][0]))),i.scalar,l),T=y.U64.parse(new Uint8Array(_.results[0].returnValues[7][0])),B=Number(y.u8().parse(new Uint8Array(_.results[0].returnValues[8][0]))),M=y.U64.parse(new Uint8Array(_.results[0].returnValues[9][0])),I=Number(y.u8().parse(new Uint8Array(_.results[0].returnValues[10][0]))),q=BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[11][0]))),D=BigInt(y.U64.parse(new Uint8Array(_.results[0].returnValues[12][0]))),J=BigInt(y.U64.parse(new Uint8Array(_.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(u){throw new Error(`Failed to get manager state: ${u instanceof Error?u.message:String(u)}`)}}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 l=y.U64.parse(new Uint8Array(a)),u=y.U64.parse(new Uint8Array(c));return{baseAsset:l.toString(),quoteAsset:u.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=!!p(o).gt(p(a)),l=c?s:i,u=c?o:a,m=new O;m.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_package_id}::margin_pool::borrow_shares_to_amount`,arguments:[m.object(l),m.pure.u64(BigInt(u)),m.object.clock()],typeArguments:[c?r:n]});let g=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:m});if(!g.results||!g.results[0]||!g.results[0].returnValues||!g.results[0].returnValues[0])throw new Error(`Transaction failed: ${g.effects?.status?.error||"Unknown error"}`);let _=y.U64.parse(new Uint8Array(g.results[0].returnValues[0][0]));return c?{baseBorrowedAmount:_.toString(),quoteBorrowedAmount:"0"}:{baseBorrowedAmount:"0",quoteBorrowedAmount:_.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=Re.buildCoinWithBalance(BigInt(n),s,i),a=await this.pythPrice.updatePythPriceIDs([t.feed,r.feed],i),c=a.get(t.feed),l=a.get(r.feed);if(!c||!l)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(l),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},l=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 u=await this.pythPrice.updatePythPriceIDs([s.feed,i.feed],l),m=u.get(s.feed),g=u.get(i.feed);if(!m||!g)throw new Error("Failed to get price feed object IDs");let _=l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::withdraw`,arguments:[l.object(this._sdk.sdkOptions.margin_utils.global_config_id),l.object(this._sdk.sdkOptions.margin_utils.versioned_id),l.object(t),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(r),l.object(n),l.object(m),l.object(g),l.object(o),l.pure.u64(BigInt(a)),l.object(v)],typeArguments:[s.coinType,i.coinType,c]});return l.transferObjects([_],e),l}catch(u){throw new Error(`Failed to withdraw: ${u instanceof Error?u.message:String(u)}`)}}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),l=a.get(n.feed);if(!c||!l)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(l),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),l=a.get(n.feed);if(!c||!l)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(l),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,l,u=o;o||(l=await this.getBorrowedAmount({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType,baseMarginPool:t,quoteMarginPool:r}),u=i?l.baseBorrowedAmount:l.quoteBorrowedAmount);let m,g={marginManager:e,baseCoin:n,quoteCoin:s,depositCoinType:i?n.coinType:s.coinType};if(i){let _=await this.getBaseBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});m=p(u).sub(_).toString()}else{let _=await this.getQuoteBalance({account:c,marginManager:e,baseCoinType:n?.coinType,quoteCoinType:s?.coinType});m=p(u).sub(_).toString()}p(m).gt(0)&&await this.deposit({...g,amount:m},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:l,baseCoin:u,quoteCoin:m}=t;if(u.decimals===void 0||m.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(l),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:[u.coinType,m.coinType]}),c}catch(g){throw new Error(`Failed to place market order: ${g instanceof Error?g.message:String(g)}`)}}async placeMarginLimitOrder({marginManager:e,poolInfo:t,orderType:r,selfMatchingOption:n,priceInput:s,quantity:i,isBid:o,payWithDeep:a,expirationTimestamp:c=Date.now()+31536e8},l=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:u,baseCoin:m,quoteCoin:g}=t;if(m.decimals===void 0||g.decimals===void 0)throw new Error("Base and quote coin decimals are required");try{let _=BigInt(p(s).mul(10**(g.decimals-m.decimals+9)).toString()),b=BigInt(W(i,m.decimals));if(_<=0n||b<=0n)throw new Error("Price and quantity must be greater than zero");return l.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_margin_limit_order`,arguments:[l.object(this.sdk.sdkOptions.margin_utils.global_config_id),l.object(this.sdk.sdkOptions.margin_utils.versioned_id),l.object(e),l.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),l.object(u),l.pure.u8(r),l.pure.u8(n),l.pure.u64(_),l.pure.u64(b),l.pure.bool(o),l.pure.bool(a),l.pure.u64(c),l.object(v)],typeArguments:[m.coinType,g.coinType]}),l}catch(_){throw new Error(`Failed to place limit order: ${_ instanceof Error?_.message:String(_)}`)}}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:l},u=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 u.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::place_reduce_only_limit_order`,arguments:[u.object(this.sdk.sdkOptions.margin_utils.global_config_id),u.object(this.sdk.sdkOptions.margin_utils.versioned_id),u.object(e),u.object(this._sdk.sdkOptions.margin_utils.margin_registry_id),u.object(t.id),u.object(r),u.pure.u8(n),u.pure.u8(s),u.pure.u64(i),u.pure.u64(o),u.pure.bool(a),u.pure.bool(c),u.pure.u64(l),u.object(v)],typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType,a?t.quoteCoin.coinType:t.baseCoin.coinType]}),u}catch(m){throw new Error(`Failed to place reduce only limit order: ${m instanceof Error?m.message:String(m)}`)}}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=Re.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])),l=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!1,!1);return{quantityOut:p(t).sub(a.toString()).toString(),quantityInLeft:p(o.toString()).add(l.takerFee).mul(p(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])),l=await this.sdk.DeepbookUtils.estimatedMaxFee(e,a.toString(),"",!1,!0,!1);return{quantityOut:p(t).sub(o).toString(),quantityInLeft:p(a.toString()).add(p(l.takerFee)).mul(p(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,l=i.toString().padStart(o,"0").slice(0,r).replace(/0+$/,"");return l?`${s}.${l}`: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(g=>{let _=r.moveCall({target:`${this.sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::balance_manager`,arguments:[r.object(g.marginManagerId)],typeArguments:[g.baseCoinType,g.quoteCoinType]});r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[r.object(g.poolId),r.object(_)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::get_account_id_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]}),r.moveCall({target:`${this._sdk.sdkOptions.margin_utils.published_at}::margin_utils::locked_balance_with_margin_manager`,arguments:[r.object(g.marginManagerId),r.object(g.poolId)],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let s=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}),i=s.events.map((g,_)=>({marginManagerId:t[_].marginManagerId,...g?.parsedJson?.account?.settled_balances||{}})),o=s.results.filter(g=>g?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),a=y.struct("VecSet",{constants:y.vector(y.U128)}),c=[];o.forEach((g,_)=>{let b=a.parse(new Uint8Array(g.returnValues[0][0])).constants;b.length>0&&b.forEach(w=>{c.push({pool:{pool_id:t[_].poolId,baseCoinType:t[_].baseCoinType,quoteCoinType:t[_].quoteCoinType},marginManagerId:t[_].marginManagerId,orderId:w})})});let l=s.results.filter(g=>g?.returnValues?.length===3),u=[];l.forEach((g,_)=>{u.push({marginManagerId:t[_].marginManagerId,base:y.U64.parse(new Uint8Array(g.returnValues[0][0])),quote:y.U64.parse(new Uint8Array(g.returnValues[1][0])),deep:y.U64.parse(new Uint8Array(g.returnValues[2][0]))})});let m=[];return c.forEach((g,_)=>{let b=this.sdk.DeepbookUtils.decodeOrderId(BigInt(g.orderId));m.push({...g,price:b.price.toString(),isBid:b.isBid})}),{openOrders:m,settledBalances:i,lockedBalances:u}}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 l=y.struct("VecSet",{constants:y.vector(y.U128)}),m=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:a})).results.find(h=>h?.returnValues?.[0]?.[1]==="0x2::vec_set::VecSet<u128>"),g=l.parse(new Uint8Array(m.returnValues[0][0])).constants,_=[];g.forEach(h=>{_.push({pool:{pool_id:r,baseCoinType:n,quoteCoinType:s},marginManagerId:t,orderId:h})});let b=_?.length>0?await this.sdk.DeepbookUtils.getOrderInfoList(_,e)||[]:[],w=[];_.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(m=>{o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::base_balance`,arguments:[o.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),c[a]={type:"base_balance",marginManagerId:m.marginManagerId},a++,o.moveCall({target:`${this._sdk.sdkOptions.deepbook.margin_published_at}::margin_manager::quote_balance`,arguments:[o.object(m.marginManagerId)],typeArguments:[m.baseCoinType,m.quoteCoinType]}),c[a]={type:"quote_balance",marginManagerId:m.marginManagerId},a++;let g=i?.find(_=>_.marginManagerId===m.marginManagerId);if(g&&(Number(g.baseBorrowedShare)>0||Number(g.quoteBorrowedShare)>0)){let _=g.baseBorrowedShare,b=g.quoteBorrowedShare,w=!!p(_).gt(p(b)),f=w?m.baseMarginPool:m.quoteMarginPool,C=w?_: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?m?.baseCoinType:m?.quoteCoinType]}),c[a]={type:w?"borrow_base_amount":"borrow_quote_amount",marginManagerId:m.marginManagerId},a++}});let l=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:o}),u=Object.fromEntries(t.map(m=>[m.marginManagerId,{...m,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 l?.results?.forEach((m,g)=>{let _=c[g],b=y.U64.parse(new Uint8Array(m.returnValues[0][0]));u[_.marginManagerId]={...u[_.marginManagerId],[_.type]:b}}),r.forEach(m=>{u[m.marginManagerId].open_orders.push(m)}),n.forEach(m=>{u[m.marginManagerId].settled_balances=m}),s.forEach(m=>{u[m.marginManagerId].locked_balances=m}),Object.values(u).forEach(m=>{m.locked_balances&&m.settled_balances&&(m.locked_balances={...m.locked_balances,base:p(m.locked_balances.base||"0").minus(p(m.settled_balances.base||"0")).toString(),quote:p(m.locked_balances.quote||"0").minus(p(m.settled_balances.quote||"0")).toString(),deep:p(m.locked_balances.deep||"0").minus(p(m.settled_balances.deep||"0")).toString()})}),u}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:l,conditional_order_id:u,pending_order:m,is_trigger_below_price:g,trigger_price:_}=e,b=await this.pythPrice.updatePythPriceIDs([c.feed,l.feed],t),w=b.get(c.feed),f=b.get(l.feed);if(!w||!f)throw new Error("Failed to get price feed object IDs");let C=t.moveCall({target:`${r.published_at}::margin_utils::new_condition`,arguments:[t.pure.bool(g),t.pure.u64(_)]}),h=this.newPendingOrder(m,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 u=="string"?t.pure.u64(BigInt(u)):u,C,h,t.object(me)],typeArguments:[c.coinType,l.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:l,expire_timestamp:u}=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(l),t.pure.u64(u)]})}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(me)],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(me)],typeArguments:[o,a]})}async getConditionalOrders(e,t){let{deepbook:r}=this.sdk.sdkOptions;e.forEach(a=>{let{margin_manager_id:c,base_coin_type:l,quote_coin_type:u,conditional_order_ids:m}=a;m.forEach(g=>{t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order`,arguments:[t.object(c),t.pure.u64(g)],typeArguments:[l,u]})})});let n=await this.sdk.fullClient.devInspectTransactionBlock({sender:ee("0x0"),transactionBlock:t});if(!n?.results)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 l;if(c[0]===0)return null;c[0]===1?l=c.subarray(1):l=c;let u=o.parse(l),m=this.normalizeConditionalOrder(u);return e.forEach(g=>{g.conditional_order_ids.find(b=>b===m.conditional_order_id)&&(m.margin_manager_id=g.margin_manager_id,m.base_coin_type=g.base_coin_type,m.quote_coin_type=g.quote_coin_type)}),m}catch{return null}})}async getConditionalOrderIds(e,t){t=t||new O;let{deepbook:r}=this.sdk.sdkOptions,n={};return e.forEach(i=>{let{margin_manager_id:o,base_coin_type:a,quote_coin_type:c}=i;t.moveCall({target:`${r.margin_package_id}::margin_manager::conditional_order_ids`,arguments:[t.object(o)],typeArguments:[a,c]})}),(await this.sdk.fullClient.devInspectTransactionBlock({sender:ee("0x0"),transactionBlock:t})).results.forEach((i,o)=>{if(i?.returnValues?.[0]?.[0]){let a=new Uint8Array(i.returnValues[0][0]),c=y.vector(y.u64()).parse(a),l={margin_manager_id:e[o].margin_manager_id,base_coin_type:e[o].base_coin_type,quote_coin_type:e[o].quote_coin_type,conditional_order_ids:c.map(u=>u.toString())};n[e[o].margin_manager_id]=l}}),n}normalizeConditionalOrder(e){let t=r=>typeof r=="bigint"?String(r):r;return{margin_manager_id:"",base_coin_type:"",quote_coin_type:"",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 re=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 Fe from"decimal.js";Fe.config({precision:64,rounding:Fe.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var F=1000000000n,ht=365n*24n*60n*60n*1000n;function yt(d,e){return e===0n?0n:d*F/e}function ft(d,e){let{base_rate:t,base_slope:r,optimal_utilization:n,excess_slope:s}=e;if(d<n)return t+d*r/F;{let i=d-n,o=n*r/F,a=i*s/F;return t+o+a}}function Ve(d,e){let t=d*e,r=t/F;return t%F>0n?r+1n:r}function kt(d,e,t,r){let n=e.borrow_shares===0n?F:e.total_borrow*F/e.borrow_shares,s=Ve(d,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,l=e.borrow_shares===0n?0n:Ve(c,d*F/e.borrow_shares),u=s+l;return{confirmedDebt:s,estimatedInterest:l,totalDebt:u,annualInterestRate:o}}function on(d,e,t,r,n=60000n){let s=r+n,{totalDebt:i}=kt(d,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 X(this),this._marginUtils=new te(this),this._pythPrice=new H(this),this._graphqlClient=new wt({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(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=d=>{if(typeof d=="string"&&d.startsWith("0x"))return"object";if(typeof d=="number"||typeof d=="bigint")return"u64";if(typeof d=="boolean")return"bool";throw new Error(`Unknown type for value: ${d}`)};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=ne;export{Bn as CLOCK_ADDRESS,K as CachedContent,ne 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,pe as DEEP_SCALAR,Lt as DEFAULT_GAS_BUDGET_FOR_MERGE,Nt as DEFAULT_GAS_BUDGET_FOR_SPLIT,Kt as DEFAULT_GAS_BUDGET_FOR_STAKE,Gt as DEFAULT_GAS_BUDGET_FOR_TRANSFER,xt 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,ce as GAS_TYPE_ARG,ke as GAS_TYPE_ARG_LONG,te as MarginUtilsModule,$t as NORMALIZED_SUI_COIN_TYPE,Ct as OrderType,re 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,p as d,de as decimalsMultiplier,ts as default,Dt as extractAddressFromType,R as extractStructTagFromType,Ut as fixCoinType,G as fixDown,Ye as fixSuiObjectId,x as fromDecimalsAmount,Nn as getDefaultSuiInputType,z as getFutureTime,le as getMoveObject,it as getMoveObjectType,lr as getMovePackageContent,tt as getObjectDeletedResponse,_r as getObjectDisplay,Ie as getObjectFields,Pe as getObjectId,rt as getObjectNotExistsResponse,mr as getObjectOwner,gr as getObjectPreviousTransactionDigest,qe as getObjectReference,pr as getObjectType,ur as getObjectVersion,Q as getSuiObjectData,br as hasPublicTransfer,Bt as hexToNumber,Et as hexToString,It as isSortedSymbols,nt as isSuiObjectResponse,ue as maxDecimal,Ve as mulRoundUp,oe as normalizeCoinType,ae as patchFixSuiObjectId,kr as printTransaction,se as removeHexPrefix,ir as secretKeyToEd25519Keypair,or as secretKeyToSecp256k1Keypair,At as shortAddress,xe as shortString,Be as sleepTime,Ke as toBuffer,W as toDecimalsAmount,ze as utf8to16,$e as wrapDeepBookMarginPoolInfo,Ue as wrapDeepBookPoolInfo};
|