@cetusprotocol/deepbook-utils 1.0.5 → 1.0.6
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 +34 -10
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +5 -4
- package/version.mjs +28 -0
- package/.env +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { CoinBalance } from '@mysten/sui/dist/cjs/client/types/coins';
|
|
2
1
|
import * as _mysten_sui_transactions from '@mysten/sui/transactions';
|
|
3
|
-
import { TransactionArgument, Transaction } from '@mysten/sui/transactions';
|
|
2
|
+
import { TransactionArgument, Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
|
|
4
3
|
import { SuiClient, SuiEventFilter, SuiObjectResponseQuery, SuiObjectDataOptions, SuiTransactionBlockResponse, SuiObjectResponse, SuiObjectData, SuiObjectRef, OwnedObjectRef, SuiMoveObject, ObjectOwner, DisplayFieldsResponse, SuiParsedData } from '@mysten/sui/client';
|
|
5
4
|
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
|
|
6
5
|
import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1';
|
|
6
|
+
import { CoinBalance } from '@mysten/sui/dist/cjs/client';
|
|
7
7
|
import Decimal from 'decimal.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -395,7 +395,7 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
395
395
|
withdrawSettledAmounts({ poolInfo, balanceManager }: {
|
|
396
396
|
poolInfo: any;
|
|
397
397
|
balanceManager: string;
|
|
398
|
-
}): Transaction;
|
|
398
|
+
}, tx?: Transaction): Transaction;
|
|
399
399
|
/**
|
|
400
400
|
* Retrieves balances for the provided coins tracked by a specific balance
|
|
401
401
|
* manager.
|
|
@@ -419,7 +419,7 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
419
419
|
/**
|
|
420
420
|
* Queries on-chain events to retrieve known pools.
|
|
421
421
|
*/
|
|
422
|
-
getPools(): Promise<any>;
|
|
422
|
+
getPools(forceRefresh?: boolean): Promise<any>;
|
|
423
423
|
/**
|
|
424
424
|
* Estimates quote quantity output for a given base amount.
|
|
425
425
|
*/
|
|
@@ -461,6 +461,8 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
461
461
|
quoteOut: number;
|
|
462
462
|
deepRequired: number;
|
|
463
463
|
}>;
|
|
464
|
+
getReferencePool(poolInfo: any): Promise<any>;
|
|
465
|
+
updateDeepPrice(poolInfo: any, tx: any): Promise<any>;
|
|
464
466
|
/**
|
|
465
467
|
* Estimates taker and maker fees for a prospective trade.
|
|
466
468
|
*/
|
|
@@ -468,7 +470,7 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
468
470
|
/**
|
|
469
471
|
* Retrieves the deep price information required for fee calculation.
|
|
470
472
|
*/
|
|
471
|
-
getOrderDeepPrice(poolInfo: any): Promise<OrderDeepPrice | null>;
|
|
473
|
+
getOrderDeepPrice(poolInfo: any, canUpdateDeepPrice?: boolean): Promise<OrderDeepPrice | null>;
|
|
472
474
|
/**
|
|
473
475
|
* Parses a serialized `OrderDeepPrice` struct from Move into a JS object.
|
|
474
476
|
*/
|
|
@@ -480,7 +482,7 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
480
482
|
/**
|
|
481
483
|
* Retrieves balances related to an upcoming transaction to determine deposit needs.
|
|
482
484
|
*/
|
|
483
|
-
getTransactionRelatedBalance(poolInfo: any,
|
|
485
|
+
getTransactionRelatedBalance(poolInfo: any, baseCoinType: string, quoteCoinType: string, noDeep: boolean, account: string, payWithDeep: boolean, balanceManager: string): Promise<{
|
|
484
486
|
baseManagerBlance: any;
|
|
485
487
|
quoteManagerBlance: any;
|
|
486
488
|
feeManaerBalance: any;
|
|
@@ -507,7 +509,10 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
507
509
|
/**
|
|
508
510
|
* Prepares assets necessary to execute a market order transaction.
|
|
509
511
|
*/
|
|
510
|
-
getMarketTransactionRelatedAssets(poolInfo: any, baseAmount: string, quoteAmount: string, maxFee: string, isBid: boolean, account: string, payWithDeep: boolean, balanceManager: string, txb: Transaction
|
|
512
|
+
getMarketTransactionRelatedAssets(poolInfo: any, baseAmount: string, quoteAmount: string, maxFee: string, isBid: boolean, account: string, payWithDeep: boolean, balanceManager: string, txb: Transaction, settled_balances?: {
|
|
513
|
+
base: string;
|
|
514
|
+
quote: string;
|
|
515
|
+
}): Promise<{
|
|
511
516
|
baseAsset: any;
|
|
512
517
|
quoteAsset: any;
|
|
513
518
|
feeAsset: any;
|
|
@@ -569,7 +574,7 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
569
574
|
/**
|
|
570
575
|
* Builds a transaction to place a market order, handling deposits as needed.
|
|
571
576
|
*/
|
|
572
|
-
placeMarketOrder({ balanceManager, poolInfo, baseQuantity, quoteQuantity, isBid, maxFee, account, payWithDeep, slippage }: {
|
|
577
|
+
placeMarketOrder({ balanceManager, poolInfo, baseQuantity, quoteQuantity, isBid, maxFee, account, payWithDeep, slippage, settled_balances, }: {
|
|
573
578
|
balanceManager: string;
|
|
574
579
|
poolInfo: PoolInfo;
|
|
575
580
|
baseQuantity: string;
|
|
@@ -579,14 +584,22 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
579
584
|
account: string;
|
|
580
585
|
payWithDeep: boolean;
|
|
581
586
|
slippage?: number;
|
|
587
|
+
settled_balances?: {
|
|
588
|
+
base: string;
|
|
589
|
+
quote: string;
|
|
590
|
+
};
|
|
582
591
|
}): Promise<any>;
|
|
583
|
-
getOrderInfoList(
|
|
592
|
+
getOrderInfoList(baseOrderList: {
|
|
593
|
+
orderId: string;
|
|
594
|
+
pool: any;
|
|
595
|
+
}[], account: string): Promise<any>;
|
|
584
596
|
decodeOrderId(encodedOrderId: bigint): {
|
|
585
597
|
isBid: boolean;
|
|
586
598
|
price: bigint;
|
|
587
599
|
orderId: bigint;
|
|
588
600
|
};
|
|
589
601
|
getOpenOrder(poolInfo: any, account: string, balanceManager: string, orders?: string[]): Promise<any>;
|
|
602
|
+
getAllMarketsOpenOrders(account: string, balanceManager: string): Promise<any>;
|
|
590
603
|
cancelOrders(orderList: any, balanceManager: string): Transaction;
|
|
591
604
|
getDeepbookOrderBook(poolKey: string, priceLow: number, priceHigh: number, isBid: boolean, account: string, balanceManager: string): Promise<void>;
|
|
592
605
|
/**
|
|
@@ -662,6 +675,13 @@ declare class DeepbookUtilsModule implements IModule {
|
|
|
662
675
|
* @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
|
|
663
676
|
*/
|
|
664
677
|
getCache<T>(key: string, forceRefresh?: boolean): T | undefined;
|
|
678
|
+
createPermissionlessPool({ tickSize, lotSize, minSize, baseCoinType, quoteCoinType }: {
|
|
679
|
+
tickSize: string;
|
|
680
|
+
lotSize: string;
|
|
681
|
+
minSize: string;
|
|
682
|
+
baseCoinType: string;
|
|
683
|
+
quoteCoinType: string;
|
|
684
|
+
}): Promise<Transaction>;
|
|
665
685
|
}
|
|
666
686
|
|
|
667
687
|
/**
|
|
@@ -685,6 +705,7 @@ type SdkOptions = {
|
|
|
685
705
|
deepbook: {
|
|
686
706
|
package_id: string;
|
|
687
707
|
published_at: string;
|
|
708
|
+
registry_id: string;
|
|
688
709
|
};
|
|
689
710
|
deepbook_utils: {
|
|
690
711
|
package_id: string;
|
|
@@ -776,6 +797,7 @@ declare class DeepbookUtilsSDK {
|
|
|
776
797
|
getCache<T>(key: string, forceRefresh?: boolean): T | undefined;
|
|
777
798
|
}
|
|
778
799
|
|
|
800
|
+
declare const cacheTime1min: number;
|
|
779
801
|
declare const cacheTime5min: number;
|
|
780
802
|
declare const cacheTime24h: number;
|
|
781
803
|
declare function getFutureTime(interval: number): number;
|
|
@@ -942,6 +964,7 @@ declare function secretKeyToEd25519Keypair(secretKey: string | Uint8Array, ecode
|
|
|
942
964
|
* @returns {Ed25519Keypair} - Returns the Secp256k1 key pair.
|
|
943
965
|
*/
|
|
944
966
|
declare function secretKeyToSecp256k1Keypair(secretKey: string | Uint8Array, ecode?: 'hex' | 'base64'): Secp256k1Keypair;
|
|
967
|
+
declare const sleepTime: (s: number) => Promise<unknown>;
|
|
945
968
|
|
|
946
969
|
declare const DEFAULT_GAS_BUDGET_FOR_SPLIT = 1000;
|
|
947
970
|
declare const DEFAULT_GAS_BUDGET_FOR_MERGE = 500;
|
|
@@ -1068,6 +1091,7 @@ declare class CoinAssist {
|
|
|
1068
1091
|
* @returns The total balance of the CoinAsset objects.
|
|
1069
1092
|
*/
|
|
1070
1093
|
static calculateTotalBalance(coins: CoinAsset[]): bigint;
|
|
1094
|
+
static buildCoinWithBalance(amount: bigint, coin_type: string, tx: Transaction): TransactionObjectArgument;
|
|
1071
1095
|
}
|
|
1072
1096
|
|
|
1073
|
-
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, DeepbookClobV2Moudle, DeepbookCustodianV2Moudle, DeepbookEndpointsV2Moudle, DeepbookUtilsModule, FLOAT_SCALAR, GAS_SYMBOL, GAS_TYPE_ARG, GAS_TYPE_ARG_LONG, NFT, NORMALIZED_SUI_COIN_TYPE, OrderDeepPrice, OrderFee, OrderType, Package, PageQuery, PaginationArgs, PoolInfo, RpcModule, SUI_SYSTEM_STATE_OBJECT_ID, SdkOptions, StateAccount, SuiAddressType, SuiBasicTypes, SuiInputTypes, SuiObjectDataWithContent, SuiObjectIdType, SuiResource, SuiStructTag, SuiTxArg, Token, TransactionUtil, addHexPrefix, asIntN, asUintN, bufferToHex, cacheTime24h, cacheTime5min, 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, normalizeCoinType, patchFixSuiObjectId, printTransaction, removeHexPrefix, secretKeyToEd25519Keypair, secretKeyToSecp256k1Keypair, shortAddress, shortString, toBuffer, toDecimalsAmount, utf8to16 };
|
|
1097
|
+
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, DeepbookClobV2Moudle, DeepbookCustodianV2Moudle, DeepbookEndpointsV2Moudle, DeepbookUtilsModule, FLOAT_SCALAR, GAS_SYMBOL, GAS_TYPE_ARG, GAS_TYPE_ARG_LONG, NFT, NORMALIZED_SUI_COIN_TYPE, OrderDeepPrice, OrderFee, OrderType, Package, PageQuery, PaginationArgs, PoolInfo, RpcModule, SUI_SYSTEM_STATE_OBJECT_ID, SdkOptions, StateAccount, SuiAddressType, SuiBasicTypes, SuiInputTypes, SuiObjectDataWithContent, SuiObjectIdType, SuiResource, SuiStructTag, SuiTxArg, Token, TransactionUtil, addHexPrefix, asIntN, asUintN, bufferToHex, cacheTime1min, cacheTime24h, cacheTime5min, 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, normalizeCoinType, patchFixSuiObjectId, printTransaction, removeHexPrefix, secretKeyToEd25519Keypair, secretKeyToSecp256k1Keypair, shortAddress, shortString, sleepTime, toBuffer, toDecimalsAmount, utf8to16 };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Pe=Object.create;var G=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ue=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ne=(i,e,t)=>e in i?G(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var $e=(i,e)=>{for(var t in e)G(i,t,{get:e[t],enumerable:!0})},be=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qe(e))!Fe.call(i,n)&&n!==t&&G(i,n,{get:()=>e[n],enumerable:!(s=Ie(e,n))||s.enumerable});return i};var he=(i,e,t)=>(t=i!=null?Pe(Ue(i)):{},be(e||!i||!i.__esModule?G(t,"default",{value:i,enumerable:!0}):t,i)),Ve=i=>be(G({},"__esModule",{value:!0}),i);var _e=(i,e,t)=>(Ne(i,typeof e!="symbol"?e+"":e,t),t);var Lt={};$e(Lt,{CLOCK_ADDRESS:()=>jt,CachedContent:()=>F,CetusClmmSDK:()=>Z,ClmmExpectSwapModule:()=>Rt,ClmmFetcherModule:()=>Mt,ClmmIntegratePoolModule:()=>Bt,ClmmIntegratePoolV2Module:()=>vt,ClmmIntegrateRouterModule:()=>Dt,ClmmIntegrateRouterWithPartnerModule:()=>Et,ClmmIntegrateUtilsModule:()=>Pt,CoinAssist:()=>T,CoinInfoAddress:()=>It,CoinStoreAddress:()=>qt,DEEP_SCALAR:()=>ne,DEFAULT_GAS_BUDGET_FOR_MERGE:()=>He,DEFAULT_GAS_BUDGET_FOR_SPLIT:()=>Ke,DEFAULT_GAS_BUDGET_FOR_STAKE:()=>ze,DEFAULT_GAS_BUDGET_FOR_TRANSFER:()=>Qe,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI:()=>Ze,DEFAULT_NFT_TRANSFER_GAS_FEE:()=>Je,DeepbookClobV2Moudle:()=>Ft,DeepbookCustodianV2Moudle:()=>Ut,DeepbookEndpointsV2Moudle:()=>Nt,DeepbookUtilsModule:()=>Q,FLOAT_SCALAR:()=>v,GAS_SYMBOL:()=>We,GAS_TYPE_ARG:()=>W,GAS_TYPE_ARG_LONG:()=>re,NORMALIZED_SUI_COIN_TYPE:()=>dt,OrderType:()=>Re,RpcModule:()=>H,SUI_SYSTEM_STATE_OBJECT_ID:()=>Ye,TransactionUtil:()=>M,addHexPrefix:()=>ie,asIntN:()=>wt,asUintN:()=>St,bufferToHex:()=>nt,cacheTime24h:()=>P,cacheTime5min:()=>se,checkAddress:()=>tt,composeType:()=>oe,d:()=>a,decimalsMultiplier:()=>X,default:()=>Vt,extractAddressFromType:()=>ut,extractStructTagFromType:()=>D,fixCoinType:()=>lt,fixDown:()=>q,fixSuiObjectId:()=>we,fromDecimalsAmount:()=>U,getDefaultSuiInputType:()=>$t,getFutureTime:()=>N,getMoveObject:()=>te,getMoveObjectType:()=>je,getMovePackageContent:()=>bt,getObjectDeletedResponse:()=>Oe,getObjectDisplay:()=>yt,getObjectFields:()=>le,getObjectId:()=>ue,getObjectNotExistsResponse:()=>Te,getObjectOwner:()=>ft,getObjectPreviousTransactionDigest:()=>_t,getObjectReference:()=>ce,getObjectType:()=>ht,getObjectVersion:()=>gt,getSuiObjectData:()=>$,hasPublicTransfer:()=>Ct,hexToNumber:()=>st,hexToString:()=>rt,isSortedSymbols:()=>ct,isSuiObjectResponse:()=>xe,maxDecimal:()=>ee,normalizeCoinType:()=>z,patchFixSuiObjectId:()=>Y,printTransaction:()=>pt,removeHexPrefix:()=>J,secretKeyToEd25519Keypair:()=>At,secretKeyToSecp256k1Keypair:()=>Ot,shortAddress:()=>et,shortString:()=>fe,toBuffer:()=>ye,toDecimalsAmount:()=>kt,utf8to16:()=>Ce});module.exports=Ve(Lt);var se=5*60*1e3,P=24*60*60*1e3;function N(i){return Date.parse(new Date().toString())+i}var F=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 I=require("@mysten/sui/utils");var Le="0x2::coin::Coin",Ge=/^0x2::coin::Coin<(.+)>$/,Ke=1e3,He=500,Qe=100,Ze=100,ze=1e3,W="0x2::sui::SUI",re="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",We="SUI",Je=450,Ye="0x0000000000000000000000000000000000000005",T=class{static getCoinTypeArg(e){let t=e.type.match(Ge);return t?t[1]:null}static isSUI(e){let t=T.getCoinTypeArg(e);return t?T.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 s=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(s+=BigInt(n.balance))}),s}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${Le}<${e}>`}static getCoinAssets(e,t){let s=[];return t.forEach(n=>{z(n.coinAddress)===z(e)&&s.push(n)}),s}static isSuiCoin(e){return D(e).full_address===W}static selectCoinObjectIdGreaterThanOrEqual(e,t,s=[]){let n=T.selectCoinAssetGreaterThanOrEqual(e,t,s),r=n.selectedCoins.map(u=>u.coinObjectId),o=n.remainingCoins,c=n.selectedCoins.map(u=>u.balance.toString());return{objectArray:r,remainCoins:o,amountArray:c}}static selectCoinAssetGreaterThanOrEqual(e,t,s=[]){let n=T.sortByBalance(e.filter(l=>!s.includes(l.coinObjectId))),r=T.calculateTotalBalance(n);if(r<t)return{selectedCoins:[],remainingCoins:n};if(r===t)return{selectedCoins:n,remainingCoins:[]};let o=BigInt(0),c=[],u=[...n];for(;o<r;){let l=t-o,p=u.findIndex(d=>d.balance>=l);if(p!==-1){c.push(u[p]),u.splice(p,1);break}let g=u.pop();g.balance>0&&(c.push(g),o+=g.balance)}return{selectedCoins:T.sortByBalance(c),remainingCoins:T.sortByBalance(u)}}static sortByBalance(e){return e.sort((t,s)=>t.balance<s.balance?-1:t.balance>s.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,s)=>t.balance>s.balance?-1:t.balance<s.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,s)=>t+s.balance,BigInt(0))}};var Xe=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function ie(i){return i.startsWith("0x")?i:`0x${i}`}function J(i){return i.startsWith("0x")?`${i.slice(2)}`:i}function fe(i,e=4,t=4){let s=Math.max(e,1),n=Math.max(t,1);return`${i.slice(0,s+2)} ... ${i.slice(-n)}`}function et(i,e=4,t=4){return fe(ie(i),e,t)}function tt(i,e={leadingZero:!0}){if(typeof i!="string")return!1;let t=i;if(e.leadingZero){if(!i.startsWith("0x"))return!1;t=t.substring(2)}return Xe.test(t)}function ye(i){if(!Buffer.isBuffer(i))if(Array.isArray(i))i=Buffer.from(i);else if(typeof i=="string")exports.isHexString(i)?i=Buffer.from(exports.padToEven(exports.stripHexPrefix(i)),"hex"):i=Buffer.from(i);else if(typeof i=="number")i=exports.intToBuffer(i);else if(i==null)i=Buffer.allocUnsafe(0);else if(i.toArray)i=Buffer.from(i.toArray());else throw new Error("invalid type");return i}function nt(i){return ie(ye(i).toString("hex"))}function st(i){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<i.length;n++)t.setUint8(n,i.charCodeAt(n));return t.getUint32(0,!0)}function Ce(i){let e,t,s,n,r;e="";let o=i.length;for(t=0;t<o;)switch(s=i.charCodeAt(t++),s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=i.charAt(t-1);break;case 12:case 13:n=i.charCodeAt(t++),e+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=i.charCodeAt(t++),r=i.charCodeAt(t++),e+=String.fromCharCode((s&15)<<12|(n&63)<<6|(r&63)<<0);break}return e}function rt(i){let e="",t=J(i),s=t.length/2;for(let n=0;n<s;n++)e+=String.fromCharCode(parseInt(t.substr(n*2,2),16));return Ce(e)}var it=0,Se=1,ot=2;function ke(i,e){return i===e?it:i<e?Se:ot}function at(i,e){let t=0,s=i.length<=e.length?i.length:e.length,n=ke(i.length,e.length);for(;t<s;){let r=ke(i.charCodeAt(t),e.charCodeAt(t));if(t+=1,r!==0)return r}return n}function ct(i,e){return at(i,e)===Se}function oe(i,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[i,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function ut(i){return i.split("::")[0]}function D(i){try{let e=i.replace(/\s/g,""),s=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(s){e=e.slice(0,e.indexOf("<"));let u={...D(e),type_arguments:s.map(l=>D(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>T.isSuiCoin(l)?l:D(l).source_address),u.source_address=oe(u.full_address,u.type_arguments),u}let n=e.split("::"),o={full_address:e,address:e===W||e===re?"0x2":(0,I.normalizeSuiObjectId)(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=oe(o.full_address,o.type_arguments),o}catch{return{full_address:i,address:"",module:"",name:"",type_arguments:[],source_address:i}}}function z(i){return D(i).source_address}function we(i){return i.toLowerCase().startsWith("0x")?(0,I.normalizeSuiObjectId)(i):i}var lt=(i,e=!0)=>{let t=i.split("::"),s=t.shift(),n=(0,I.normalizeSuiObjectId)(s);return e&&(n=J(n)),`${n}::${t.join("::")}`};function Y(i){for(let e in i){let t=typeof i[e];if(t==="object")Y(i[e]);else if(t==="string"){let s=i[e];i[e]=we(s)}}}var dt=(0,I.normalizeStructTag)(I.SUI_TYPE_ARG);var ae=he(require("decimal.js"));ae.default.config({precision:64,rounding:ae.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var K=he(require("decimal.js"));function a(i){return K.default.isDecimal(i)?i:new K.default(i===void 0?0:i)}function X(i){return a(10).pow(a(i).abs())}var q=(i,e)=>{try{return a(i).toDP(e,K.default.ROUND_DOWN).toString()}catch{return i}},ee=(i,e)=>K.default.max(a(i),a(e));var Ae=require("@mysten/sui/transactions");async function pt(i,e=!0){i.blockData.transactions.forEach((t,s)=>{})}var R=class{static async adjustTransactionForGas(e,t,s,n){n.setSender(e.senderAddress);let r=T.selectCoinAssetGreaterThanOrEqual(t,s).selectedCoins;if(r.length===0)throw new Error("Insufficient balance");let o=T.calculateTotalBalance(t);if(o-s>1e9)return{fixAmount:s};let c=await e.fullClient.calculationTxGas(n);if(T.selectCoinAssetGreaterThanOrEqual(t,BigInt(c),r.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(c)+BigInt(500);if(o-s<l){if(s-=l,s<0)throw new Error("gas Insufficient balance");let p=new Ae.Transaction;return{fixAmount:s,newTx:p}}}return{fixAmount:s}}static buildCoinForAmount(e,t,s,n,r=!0,o=!1){let c=T.getCoinAssets(n,t);if(s===BigInt(0)&&c.length===0)return R.buildZeroValueCoin(t,e,n,r);let u=T.calculateTotalBalance(c);if(u<s)throw new Error(`The amount(${u}) is Insufficient balance for ${n} , expect ${s} `);return R.buildCoin(e,t,c,s,n,r,o)}static buildCoin(e,t,s,n,r,o=!0,c=!1){if(T.isSuiCoin(r)){if(o){let _=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[_]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&s.length>1){let _=T.selectCoinObjectIdGreaterThanOrEqual(s,n);return{targetCoin:e.object(_.objectArray[0]),remainCoins:_.remainCoins,tragetCoinAmount:_.amountArray[0],isMintZeroCoin:!1}}let y=T.selectCoinObjectIdGreaterThanOrEqual(s,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:y.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let u=T.selectCoinObjectIdGreaterThanOrEqual(s,n),l=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),p=u.objectArray;if(o)return{targetCoin:e.makeMoveVec({elements:p.map(y=>e.object(y))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[g,...d]=p,m=e.object(g),h=m,b=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),S;return d.length>0&&e.mergeCoins(m,d.map(y=>e.object(y))),c&&Number(l)>Number(n)&&(h=e.splitCoins(m,[e.pure.u64(n)]),b=n.toString(),S=m),{targetCoin:h,remainCoins:u.remainCoins,originalSplitedCoin:S,tragetCoinAmount:b,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,s,n=!0){let r=R.callMintZeroValueCoin(t,s),o;return n?o=t.makeMoveVec({elements:[r]}):o=r,{targetCoin:o,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,s,n,r=!0){let o=T.getCoinAssets(n,t);if(s.amountFirst===BigInt(0))return o.length>0?R.buildCoin(e,[...t],[...o],s.amountFirst,n,r):R.buildZeroValueCoin(t,e,n,r);let c=T.calculateTotalBalance(o);if(c>=s.amountFirst)return R.buildCoin(e,[...t],[...o],s.amountFirst,n,r);if(c<s.amountSecond)throw new Error(`The amount(${c}) is Insufficient balance for ${n} , expect ${s.amountSecond} `);return R.buildCoin(e,[...t],[...o],s.amountSecond,n,r)}static buildCoinTypePair(e,t){let s=[];if(e.length===2){let n=[];n.push(e[0],e[1]),s.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),s.push(n);for(let r=1;r<e.length-1;r+=1){if(t[r-1]===0)continue;let o=[];o.push(e[0],e[r],e[e.length-1]),s.push(o)}}return s}},M=R;_e(M,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));function $(i){return i.data}function Oe(i){if(i.error&&"object_id"in i.error&&"version"in i.error&&"digest"in i.error){let{error:e}=i;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Te(i){if(i.error&&"object_id"in i.error&&!("version"in i.error)&&!("digest"in i.error))return i.error.object_id}function ce(i){if("reference"in i)return i.reference;let e=$(i);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Oe(i)}function ue(i){return"objectId"in i?i.objectId:ce(i)?.objectId??Te(i)}function gt(i){return"version"in i?i.version:ce(i)?.version}function xe(i){return i.data!==void 0}function mt(i){return i.content!==void 0}function bt(i){let e=$(i);if(e?.content?.dataType==="package")return e.content.disassembled}function te(i){let e="data"in i?$(i):i;if(!(!e||!mt(e)||e.content.dataType!=="moveObject"))return e.content}function je(i){return te(i)?.type}function ht(i){let e=xe(i)?i.data:i;return!e?.type&&"data"in i?e?.content?.dataType==="package"?"package":je(i):e?.type}function _t(i){return $(i)?.previousTransaction}function ft(i){return $(i)?.owner}function yt(i){let e=$(i)?.display;return e||{data:null,error:null}}function le(i){let e=te(i)?.fields;if(e)return"fields"in e?e.fields:e}function Ct(i){return te(i)?.hasPublicTransfer??!1}var V=require("@mysten/bcs"),de=require("@mysten/sui/keypairs/ed25519"),pe=require("@mysten/sui/keypairs/secp256k1");function kt(i,e){let t=X(a(e));return Number(a(i).mul(t))}function St(i,e=32){return BigInt.asUintN(e,BigInt(i)).toString()}function wt(i,e=32){return Number(BigInt.asIntN(e,BigInt(i)))}function U(i,e){let t=X(a(e));return Number(a(i).div(t))}function At(i,e="hex"){if(i instanceof Uint8Array){let s=Buffer.from(i);return de.Ed25519Keypair.fromSecretKey(s)}let t=e==="hex"?(0,V.fromHEX)(i):(0,V.fromB64)(i);return de.Ed25519Keypair.fromSecretKey(t)}function Ot(i,e="hex"){if(i instanceof Uint8Array){let s=Buffer.from(i);return pe.Secp256k1Keypair.fromSecretKey(s)}let t=e==="hex"?(0,V.fromHEX)(i):(0,V.fromB64)(i);return pe.Secp256k1Keypair.fromSecretKey(t)}var Be=require("@mysten/sui/client"),H=class extends Be.SuiClient{async queryEventsByPage(e,t="all"){let s=[],n=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.queryEvents({query:e,cursor:o,limit:r?null:t.limit});c.data?(s=[...s,...c.data],n=c.hasNextPage,o=c.nextCursor):n=!1}while(r&&n);return{data:s,nextCursor:o,hasNextPage:n}}async getOwnedObjectsByPage(e,t,s="all"){let n=[],r=!0,o=s==="all",c=o?null:s.cursor;do{let u=await this.getOwnedObjects({owner:e,...t,cursor:c,limit:o?null:s.limit});u.data?(n=[...n,...u.data],r=u.hasNextPage,c=u.nextCursor):r=!1}while(o&&r);return{data:n,nextCursor:c,hasNextPage:r}}async getDynamicFieldsByPage(e,t="all"){let s=[],n=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.getDynamicFields({parentId:e,cursor:o,limit:r?null:t.limit});c.data?(s=[...s,...c.data],n=c.hasNextPage,o=c.nextCursor):n=!1}while(r&&n);return{data:s,nextCursor:o,hasNextPage:n}}async batchGetObjects(e,t,s=50){let n=[];try{for(let r=0;r<Math.ceil(e.length/s);r++){let o=await this.multiGetObjects({ids:e.slice(r*s,s*(r+1)),options:t});n=[...n,...o]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let s=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=s.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 Ee=require("@mysten/deepbook-v3"),f=require("@mysten/sui/bcs"),Me=require("js-base64"),A=require("@mysten/sui/transactions"),O=require("@mysten/sui/utils");function ve(...i){let e="DeepbookV3_Utils_Sdk###"}var ne=1e6,v=1e9,Tt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},xt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},De=1e3*60*60*24*365*100,Q=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?xt:Tt}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new A.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:s}){let n=new A.Transaction;n.setSenderIfNotSet(e);let r=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=(0,A.coinWithBalance)({type:t.coinType,balance:BigInt(s)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[r,o],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),r],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[r],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:s,amountToDeposit:n,tx:r}){let o=r||new A.Transaction;if(t){o.setSenderIfNotSet(e);let c=(0,A.coinWithBalance)({type:s.coinType,balance:BigInt(n)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(t),c],typeArguments:[s.coinType]}),o}return null}withdrawFromManager({account:e,balanceManager:t,coin:s,amountToWithdraw:n,returnAssets:r,txb:o}){let c=o||new A.Transaction,u=c.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[c.object(t),c.pure.u64(n)],typeArguments:[s.coinType]});return r?u:(c.transferObjects([u],e),c)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:s=new A.Transaction}){for(let n in t)t[n].forEach(o=>{let c=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[s.object(n),s.pure.u64(o.amount)],typeArguments:[o.coinType]});s.transferObjects([c],e)});return s}async getBalanceManager(e,t=!0){let s=`getBalanceManager_${e}`,n=this.getCache(s,t);if(!t&&n!==void 0)return n;try{let r=new A.Transaction;r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r.pure.address(e)],typeArguments:[]});let u=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}))?.events?.filter(p=>p.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],l=[];return u.forEach(p=>{l.push({balanceManager:p,cetusBalanceManager:""})}),this.updateCache(s,l,P),l||[]}catch(r){throw r instanceof Error?r:new Error(String(r))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t}){let s=new A.Transaction,n=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[s.object(t)]});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[s.object(e.address),s.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),s}async getManagerBalance({account:e,balanceManager:t,coins:s}){try{let n=new A.Transaction;s.forEach(c=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[c.coinType]})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),o={};return r.results?.forEach((c,u)=>{let l=s[u],p=c.returnValues[0][0],g=f.bcs.U64.parse(new Uint8Array(p)),d=a(g),m=d.eq(0)?"0":d.div(Math.pow(10,l.decimals)).toString();o[l.coinType]={adjusted_balance:m,balance:d.toString()}}),o}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let s=new A.Transaction,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(c=>{t.forEach(u=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(c.balanceManager)],typeArguments:[u.coinType]})})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}),o={};return n.forEach((c,u)=>{let l={},p=u*t.length;t.forEach((g,d)=>{let m=p+d,h=r.results?.[m];if(h){let b=h.returnValues[0][0],S=f.bcs.U64.parse(new Uint8Array(b)),y=a(S),C=y.eq(0)?"0":y.div(Math.pow(10,g.decimals)).toString();l[g.coinType]={adjusted_balance:C,balance:y.toString()}}}),o[c.balanceManager]=l}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getMarketPrice(e){try{let t=new A.Transaction;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(O.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],r=Number(f.bcs.U64.parse(new Uint8Array(n))),o=Math.pow(10,e.baseCoin.decimals).toString(),c=Math.pow(10,e.quoteCoin.decimals).toString();return a(r).mul(o).div(c).div(v).toString()}catch(t){return ve("getMarketPrice ~ error:",t),"0"}}async getPools(){let e=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),t=/<([^>]+)>/,s=[];return e?.data?.forEach(n=>{let r=n?.parsedJson,o=n.type.match(t);if(o){let u=o[1].split(", ");s.push({...r,baseCoinType:u[0],quoteCoinType:u[1]})}}),s}async getQuoteQuantityOut(e,t,s){let n=new A.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(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(ne).toString(),baseQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getBaseQuantityOut(e,t,s){let n=new A.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(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{quoteQuantityDisplay:a(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(ne).toString(),quoteQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getQuantityOut(e,t,s,n){let r=new A.Transaction;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[r.object(e.address),r.pure.u64(t),r.pure.u64(s),r.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:r}),c=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[0][0]))),u=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[1][0]))),l=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:a(s).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(c).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(u).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(l).div(ne).toString(),baseQuantity:t,quoteQuantity:s,baseOut:c,quoteOut:u,deepRequired:l}}async estimatedMaxFee(e,t,s,n,r,o,c){let u=this.deepCoin;try{let{taker_fee:l,maker_fee:p}=e,g=a(l).div(v).toString(),d=a(p).div(v).toString(),m=await this.getMarketPrice(e),h=o?s:m!=="0"?m:c;if(h==="0")throw new Error("Cannot get market price");let b=Math.pow(10,e.baseCoin.decimals).toString(),S=Math.pow(10,e.quoteCoin.decimals).toString(),y=a(h).div(b).mul(S).mul(v).toString();if(n){let w=await this.getMarketPrice(e),k=a(o?s:w!=="0"?w:c).div(b).mul(S).mul(v).toString(),x=await this.getOrderDeepPrice(e);if(!x)throw new Error("Cannot get deep price");let j=ee(k,s),L=a(t).mul(a(g)).mul(a(x.deep_per_asset)).div(a(v)),E=a(t).mul(a(d)).mul(a(x.deep_per_asset)).div(a(v));x.asset_is_base||(L=L.mul(j).div(a(v)),E=E.mul(j).div(a(v)));let ge=L.ceil().toString(),me=E.ceil().toString();return{takerFee:ge,makerFee:me,takerFeeDisplay:U(ge,u.decimals).toString(),makerFeeDisplay:U(me,u.decimals).toString(),feeType:u.coinType}}if(r){let w=ee(y,s),B=a(t).mul(w).mul(a(g).mul(1.25)).div(a(v)).ceil().toFixed(0),k=a(t).mul(w).mul(a(d).mul(1.25)).div(a(v)).ceil().toFixed(0);return{takerFee:B,makerFee:k,takerFeeDisplay:U(B,e.quoteCoin.decimals).toString(),makerFeeDisplay:U(k,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=a(t).mul(a(g).mul(1.25)).ceil().toFixed(0),_=a(t).mul(a(d).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:_,takerFeeDisplay:U(C,e.baseCoin.decimals).toString(),makerFeeDisplay:U(_,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getOrderDeepPrice(e){try{let t=new A.Transaction;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[t.object(e.address)],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];return this.parseOrderDeepPrice(new Uint8Array(n))}catch{return null}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),s=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:s,deep_per_asset:n}}getCoinAssets(e,t,s,n){return M.buildCoinForAmount(n,s,BigInt(a(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,s,n,r,o,c){let u=this.deepCoin;if(!c)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let l=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&l.push(u);let p=await this.getManagerBalance({account:r,balanceManager:c,coins:l}),g=p?.[t]?.balance||"0",d=p?.[s]?.balance||"0",m=o&&p?.[u.coinType]?.balance||"0";return{baseManagerBlance:g,quoteManagerBlance:d,feeManaerBalance:m}}catch(l){throw l instanceof Error?l:new Error(String(l))}}getFeeAsset(e,t,s,n,r,o,c,u,l,p){let g=a(e).gt(0)&&l,d="0";if(!g)return{feeAsset:this.getEmptyCoin(p,t),haveDepositFee:"0"};if(o||c){let m=a(r).sub(o?n:s);d=m.lte(0)?e:m.sub(e).lt(0)?m.sub(e).toString():"0"}else d=a(r).sub(e).lt("0")?a(r).sub(e).abs().toString():"0";return{feeAsset:a(d).gt("0")?this.getCoinAssets(t,d,u,p):this.getEmptyCoin(p,t),haveDepositFee:d}}async getTransactionRelatedAssets(e,t,s,n,r,o,c,u,l){try{let p=this.deepCoin,g=(0,O.normalizeStructTag)(e.baseCoin.coinType),d=(0,O.normalizeStructTag)(e.quoteCoin.coinType),m=g===p.coinType,h=d===p.coinType,b=!m&&!h,{baseManagerBlance:S,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,g,d,b,o,c,u),_,w,B=!1,k=await this._sdk.getOwnerCoinAssets(o);if(r){c||(s=a(s).add(a(n)).toString());let j=a(y).sub(s).toString();a(j).lt(0)?(B=!0,w=this.getCoinAssets(d,j,k,l)):w=this.getEmptyCoin(l,d),_=this.getEmptyCoin(l,g)}else{c||(t=a(t).add(a(n)).toString());let j=a(S).sub(t).toString();a(j).lt(0)?(B=!0,_=this.getCoinAssets(g,j,k,l)):_=this.getEmptyCoin(l,g),w=this.getEmptyCoin(l,d)}let x=this.getFeeAsset(n,p.coinType,t,s,C,h,m,k,c,l);return{baseAsset:_,quoteAsset:w,feeAsset:x,haveDeposit:B}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getMarketTransactionRelatedAssets(e,t,s,n,r,o,c,u,l){try{let p=this.deepCoin,g=(0,O.normalizeStructTag)(e.baseCoin.coinType),d=(0,O.normalizeStructTag)(e.quoteCoin.coinType),m=g===p.coinType,h=d===p.coinType,b=!m&&!h,{baseManagerBlance:S,quoteManagerBlance:y}=await this.getTransactionRelatedBalance(e,g,d,b,o,c,u),C,_,w=await this._sdk.getOwnerCoinAssets(o);if(r){c||(s=a(s).add(a(n)).toString());let k=a(y).sub(s).toString();if(a(k).lt(0)){let x;a(y).gt(0)&&(x=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:y,returnAssets:!0,txb:l}));let j=this.getCoinAssets(d,k,w,l);x&&l.mergeCoins(j,[x]),_=j}else _=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:s,returnAssets:!0,txb:l});C=this.getEmptyCoin(l,g)}else{c||(t=a(t).add(a(n)).toString());let k=a(S).sub(t).toString();if(a(k).lt(0)){let x;a(S).gt(0)&&(x=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:S,returnAssets:!0,txb:l}));let j=this.getCoinAssets(g,k,w,l);x&&l.mergeCoins(j,[x]),C=j}else C=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:l});_=this.getEmptyCoin(l,d)}let B=this.getEmptyCoin(l,p.coinType);return{baseAsset:C,quoteAsset:_,feeAsset:B}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:s,orderType:n,isBid:r,maxFee:o,account:c,payWithDeep:u,expirationTimestamp:l=Date.now()+De}){try{let p=this.deepCoin,g=e.address,d=e.baseCoin.decimals,m=e.quoteCoin.decimals,h=e.baseCoin.coinType,b=e.quoteCoin.coinType,S=a(t).mul(10**(m-d+9)).toString(),y=(0,O.normalizeStructTag)(h),C=(0,O.normalizeStructTag)(b),_=new A.Transaction,w,B,k=await this._sdk.getOwnerCoinAssets(c);if(r){let E=a(t).mul(a(s).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();u||(E=a(E).add(a(o)).toString()),B=M.buildCoinForAmount(_,k,BigInt(E),C,!1,!0)?.targetCoin}else{let E=s;u||(E=a(s).abs().add(a(o)).toString()),w=M.buildCoinForAmount(_,k,BigInt(a(E).abs().toString()),y,!1,!0)?.targetCoin}let x=u?a(o).gt(0)?M.buildCoinForAmount(_,k,BigInt(a(o).abs().ceil().toString()),p.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,p.coinType):this.getEmptyCoin(_,p.coinType),j=_.moveCall({typeArguments:[r?h:b],target:"0x2::coin::zero",arguments:[]}),L=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(g),r?j:w,r?B:j,x,_.pure.u8(n),_.pure.u8(0),_.pure.u64(S),_.pure.u64(s),_.pure.bool(r),_.pure.bool(!1),_.pure.u64(l),_.object(O.SUI_CLOCK_OBJECT_ID)];return _.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:L}),_}catch(p){throw p instanceof Error?p:new Error(String(p))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:s,maxFee:n,account:r,payWithDeep:o,slippage:c=.01}){try{let u=e.address,l=e.baseCoin.coinType,p=e.quoteCoin.coinType,g=(0,O.normalizeStructTag)(l),d=(0,O.normalizeStructTag)(p),m=new A.Transaction,h,b,S=t,y,C=await this.getOrderBook(e,"all",6);if(s){let k=C?.ask?.[0]?.price||"0",x=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(x).plus(a(x).mul(c)).ceil().toString()}else{let k=await C?.bid?.[0]?.price||"0",x=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(x).minus(a(x).mul(c)).floor().toString()}let _=await this._sdk.getOwnerCoinAssets(r);s?(o||(y=a(y).add(a(n)).toString()),b=this.getCoinAssets(d,y,_,m),h=this.getEmptyCoin(m,g)):(o||(S=a(S).add(a(n)).toString()),b=this.getEmptyCoin(m,d),h=this.getCoinAssets(g,S,_,m));let w=o?a(n).gt(0)?M.buildCoinForAmount(m,_,BigInt(a(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(m,this.deepCoin.coinType):this.getEmptyCoin(m,this.deepCoin.coinType),B=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(u),h,b,w,m.pure.u8(0),m.pure.u64(t),m.pure.bool(s),m.pure.bool(o),m.pure.u64(y),m.object(O.SUI_CLOCK_OBJECT_ID)];return m.moveCall({typeArguments:[g,d],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:B}),m}catch(u){throw u instanceof Error?u:new Error(String(u))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:s,quantity:n,isBid:r,orderType:o,maxFee:c,account:u,payWithDeep:l,expirationTimestamp:p=Date.now()+De}){try{let g=this.deepCoin,d=a(s).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),m=t.baseCoin.coinType,h=t.quoteCoin.coinType,b=new A.Transaction,S=r?a(s).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=r?"0":n,{baseAsset:C,quoteAsset:_,feeAsset:w,haveDeposit:B}=await this.getTransactionRelatedAssets(t,y,S,c,r,u,l,e,b);if(B){let 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(t.address),b.object(e),C,_,w.feeAsset,b.pure.u8(o),b.pure.u8(0),b.pure.u64(d),b.pure.u64(n),b.pure.bool(r),b.pure.bool(l),b.pure.u64(p),b.object(O.SUI_CLOCK_OBJECT_ID)];return b.moveCall({typeArguments:[m,h],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:j}),b}let k=new A.Transaction;a(w.haveDepositFee).gt(0)&&this.depositIntoManager({account:u,balanceManager:e,coin:g,amountToDeposit:w.haveDepositFee,tx:k});let x=[k.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),k.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),k.object(t.address),k.object(e),k.pure.u8(o),k.pure.u8(0),k.pure.u64(d),k.pure.u64(n),k.pure.bool(r),k.pure.bool(l),k.pure.u64(p),k.object(O.SUI_CLOCK_OBJECT_ID)];return k.moveCall({typeArguments:[m,h],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:x}),k}catch(g){throw g instanceof Error?g:new Error(String(g))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:s,newOrderQuantity:n}){let r=new A.Transaction;return r.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(e),r.object(t.address),r.pure.u128(s),r.pure.u64(n),r.object(O.SUI_CLOCK_OBJECT_ID)]}),r}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:s}=e,n=new A.Transaction,r=await this.getMarketPrice(e),o=a(r).gt(0)?r:Math.pow(10,-1),c=Math.pow(10,6),u=a(o).mul(Math.pow(10,9+s.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+s.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(u),n.pure.u64(l),n.pure.bool(!1),n.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),d=[],m=g.results[0].returnValues[0][0],h=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m)),b=g.results[0].returnValues[1][0],S=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b));return h.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),w=a(S[C]).div(Math.pow(10,t.decimals)).toString();d.push({price:_,quantity:w})}),d?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:s}=e,n=new A.Transaction,r=await this.getMarketPrice(e),o=a(r).gt(0)?a(r).div(3).toNumber():Math.pow(10,-6),c=a(r).gt(0)?r:Math.pow(10,6),u=a(o).mul(Math.pow(10,9+s.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+s.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(q(u,0)),n.pure.u64(q(l,0)),n.pure.bool(!0),n.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),d=[],m=g.results[0].returnValues[0][0],h=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m)),b=g.results[0].returnValues[1][0],S=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b));return h.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),w=a(S[C]).div(Math.pow(10,t.decimals)).toString();d.push({price:_,quantity:w})}),d?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:s,quoteCoin:n}=e,r=new A.Transaction,o=await this.getMarketPrice(e),c,u;t?(c=a(o).gt(0)?a(o).div(3).toNumber():Math.pow(10,-6),u=a(o).gt(0)?o:Math.pow(10,6)):(c=a(o).gt(0)?o:Math.pow(10,-1),u=a(o).gt(0)?a(o).mul(3).toNumber():Math.pow(10,6));let l=a(c).mul(Math.pow(10,9+n.decimals-s.decimals)).toString(),p=a(u).mul(Math.pow(10,9+n.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(q(l,0)),r.pure.u64(q(p,0)),r.pure.bool(t),r.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:r}),m=[],h=d.results[0].returnValues[0][0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(h)),S=d.results[0].returnValues[1][0],y=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(S));return b.forEach((C,_)=>{let w=a(C).div(Math.pow(10,9+n.decimals-s.decimals)).toString(),B=a(y[_]).div(Math.pow(10,s.decimals)).toString();m.push({price:w,quantity:B})}),m?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:s,quoteQuantity:n,isBid:r,maxFee:o,account:c,payWithDeep:u,slippage:l=.01}){try{let p=(0,O.normalizeStructTag)(t.baseCoin.coinType),g=(0,O.normalizeStructTag)(t.quoteCoin.coinType),d=new A.Transaction,{baseAsset:m,quoteAsset:h,feeAsset:b}=await this.getMarketTransactionRelatedAssets(t,s,n,o,r,c,u,e,d),S=await this.getOrderBook(t,"all",6);if(r){let _=S?.ask?.[0]?.price||"0",w=a(_).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=a(w).plus(a(w).mul(l)).ceil().toString()}else{let _=await S?.bid?.[0]?.price||"0",w=a(_).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=a(w).minus(a(w).mul(l)).floor().toString()}let y=n,C=[d.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),d.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),d.object(t.address),d.object(e),m,h,b,d.pure.u8(0),d.pure.u64(s),d.pure.bool(r),d.pure.bool(u),d.pure.u64(y),d.object(O.SUI_CLOCK_OBJECT_ID)];return d.setSenderIfNotSet(c),d.moveCall({typeArguments:[p,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),d}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getOrderInfoList(e,t,s){try{let n=new A.Transaction;t.forEach(p=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[n.object(e.address),n.pure.u128(p)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]})});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=f.bcs.struct("ID",{bytes:f.bcs.Address}),c=f.bcs.struct("OrderDeepPrice",{asset_is_base:f.bcs.bool(),deep_per_asset:f.bcs.u64()}),u=f.bcs.struct("Order",{balance_manager_id:o,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:c,epoch:f.bcs.u64(),status:f.bcs.u8(),expire_timestamp:f.bcs.u64()}),l=[];return r?.results?.forEach(p=>{let g=p.returnValues[0][0],d=u.parse(new Uint8Array(g));l.push(d)}),l}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),s=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:s,orderId:n}}async getOpenOrder(e,t,s,n){let r;if(n)r=n;else{let u=new A.Transaction;u.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[u.object(e.address),u.object(s)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:u})).results[0].returnValues[0][0];r=f.bcs.struct("VecSet",{constants:f.bcs.vector(f.bcs.U128)}).parse(new Uint8Array(p)).constants}let o=await this.getOrderInfoList(e,r,t)||[],c=[];return o.forEach(u=>{let l=this.decodeOrderId(BigInt(u.order_id));c.push({...u,price:l.price,isBid:l.isBid})}),c}cancelOrders(e,t){let s=new A.Transaction;return e.forEach(n=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(t),s.object(n.poolInfo.address),s.pure.u128(n.orderId),s.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),s}async getDeepbookOrderBook(e,t,s,n,r,o){let c=this._sdk.fullClient,l=await new Ee.DeepBookClient({client:c,address:r,env:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,t,s,n)}processOrderBookData(e,t,s,n){let r=e.returnValues[0][0],o=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(r)),c=e.returnValues[1][0],u=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(c)),l={};return o.forEach((g,d)=>{let m=a(g).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),h=a(u[d]).div(Math.pow(10,t.decimals)).toString();l[m]?l[m]={price:m,quantity:a(l[m].quantity).add(h).toString()}:l[m]={price:m,quantity:h}}),Object.values(l)}getLevel2RangeTx(e,t,s,n,r=new A.Transaction){let{baseCoin:o,quoteCoin:c}=e,u=q(a(s).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0),l=q(a(n).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0);return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(u),r.pure.u64(l),r.pure.bool(t),r.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[o.coinType,c.coinType]}),r}async fetchOrderBook(e,t,s,n,r,o){let c=new A.Transaction,{baseCoin:u,quoteCoin:l}=e;try{if(t==="bid"||t==="all"){let h=n,b=s==="0"?r:s;c=this.getLevel2RangeTx(e,!0,h,b,c)}if(t==="ask"||t==="all"){let h=s==="0"?n:s,b=r;c=this.getLevel2RangeTx(e,!1,h,b,c)}let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:c}),d=[];(t==="bid"||t==="all")&&(d=g.results?.[0]?this.processOrderBookData(g.results[0],u,l,o):[]);let m=[];if(t==="ask"||t==="all"){let h=t==="ask"?0:1;m=g.results?.[h]?this.processOrderBookData(g.results[h],u,l,o):[]}return{bid:d.sort((h,b)=>b.price-h.price),ask:m.sort((h,b)=>h.price-b.price)}}catch{let g=this._sdk.sdkOptions.simulationAccount.address,d=[],m=[];try{let h=this.getLevel2RangeTx(e,!0,n,s),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:h});d=b.results?.[0]?this.processOrderBookData(b.results[0],u,l,o):[]}catch{d=[]}try{let h=this.getLevel2RangeTx(e,!1,n,s),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:h});m=b.results?.[0]?this.processOrderBookData(b.results[0],u,l,o):[]}catch{m=[]}return{bid:d,ask:m}}}async getOrderBook(e,t,s){let n={bid:[],ask:[]};try{let r=await this.getMarketPrice(e),o=t,c=Math.pow(10,-s),u=Math.pow(10,s),l=await this.fetchOrderBook(e,o,r,c,u,s);return{bid:l?.bid,ask:l?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let s=new A.Transaction,n=await this.getMarketPrice(e),{baseCoin:r,quoteCoin:o}=e;if(t==="bid"||t==="all"){let g=Math.pow(10,-6),d=n,m=a(g).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),h=a(d).mul(Math.pow(10,9+o.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(m),s.pure.u64(h),s.pure.bool(!0),s.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,o.coinType]})}if(t==="ask"||t==="all"){let g=n,d=Math.pow(10,6),m=a(g).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),h=a(d).mul(Math.pow(10,9+o.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(m),s.pure.u64(h),s.pure.bool(!1),s.object(O.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,o.coinType]})}let c=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:c,transactionBlock:s}),l=[];if(t==="bid"||t==="all"){let g=u.results[0]?.returnValues[0]?.[0],d=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(g)),m=u.results[0]?.returnValues[1]?.[0],h=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m));d.forEach((b,S)=>{let y=a(b).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),C=a(h[S]).div(Math.pow(10,r.decimals)).toString();l.push({price:y,quantity:C})})}let p=[];if(t==="ask"||t==="all"){let g=t==="ask"?0:1,d=u.results[g]?.returnValues[0]?.[0],m=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(d)),h=u.results[g]?.returnValues[1]?.[0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(h));m.forEach((S,y)=>{let C=a(S).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),_=a(b[y]).div(Math.pow(10,r.decimals)).toString();p.push({price:C,quantity:_})})}return{bid:l,ask:p}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,r)=>[(0,O.normalizeStructTag)(n.coinType),n]))}async getAccount(e,t){let s=new A.Transaction;for(let c=0;c<t.length;c++){let u=t[c];s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[s.object(u.address),s.object(e)],typeArguments:[u.baseCoin.coinType,u.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),r;if(n?.events.length===0)return null;let o=[];return n?.events?.forEach((c,u)=>{r=c?.parsedJson;let l=r.account.open_orders.contents,p=r.account.owed_balances,g=r.account.settled_balances,d=r.account.unclaimed_rebates,m=r.account.taker_volume;o.push({balance_manager_id:e,open_orders:l,owed_balances:p,settled_balances:g,unclaimed_rebates:d,taker_volume:m,poolInfo:t[u]})}),o}async getSuiTransactionResponse(e,t=!1){let s=`${e}_getSuiTransactionResponse`,n=this.getCache(s,t);if(n!==void 0)return n;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(s,r,P),r}transformExtensions(e,t,s=!0){let n=[];for(let r of t){let{key:o}=r.fields,{value:c}=r.fields;if(o==="labels")try{c=JSON.parse(decodeURIComponent(Me.Base64.decode(c)))}catch{}s&&(e[o]=c),n.push({key:o,value:c})}delete e.extension_fields,s||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let s=this.sdk.sdkOptions.coinlist.handle,n=`${s}_getCoinConfigs`,r=this.getCache(n,e);if(r)return r;let c=(await this._sdk.fullClient.getDynamicFieldsByPage(s)).data.map(p=>p.objectId),u=await this._sdk.fullClient.batchGetObjects(c,{showContent:!0}),l=[];return u.forEach(p=>{let g=this.buildCoinConfig(p,t);this.updateCache(`${s}_${g.address}_getCoinConfig`,g,P),l.push({...g})}),this.updateCache(n,l,P),l}buildCoinConfig(e,t=!0){let s=le(e);s=s.value.fields;let n={...s};return n.id=ue(e),n.address=D(s.coin_type.fields.name).full_address,s.pyth_id&&(n.pyth_id=(0,O.normalizeSuiObjectId)(s.pyth_id)),this.transformExtensions(n,s.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,s=se){let n=this._cache[e];n?(n.overdueTime=N(s),n.value=t):n=new F(t,N(s)),this._cache[e]=n}getCache(e,t=!1){let s=this._cache[e],n=s?.isValid();if(!t&&n)return s.value;n||delete this._cache[e]}};var Z=class{_cache={};_rpcModule;_deepbookUtils;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new H({url:e.fullRpcUrl}),this._deepbookUtils=new Q(this),Y(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,s=!0){let n=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,c=this.getCache(o,s);if(c)return c;for(;;){let u=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:r}):this.fullClient.getAllCoins({owner:e,cursor:r}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&n.push({coinAddress:D(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),r=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,n,30*1e3),n}async getOwnerCoinBalances(e,t){let s=[];return t?s=[await this.fullClient.getBalance({owner:e,coinType:t})]:s=[...await this.fullClient.getAllBalances({owner:e})],s}updateCache(e,t,s=P){let n=this._cache[e];n?(n.overdueTime=N(s),n.value=t):n=new F(t,N(s)),this._cache[e]=n}getCache(e,t=!1){let s=this._cache[e],n=s?.isValid();if(!t&&n)return s.value;n||delete this._cache[e]}};var jt="0x0000000000000000000000000000000000000000000000000000000000000006",Bt="pool_script",vt="pool_script_v2",Dt="router",Et="router_with_partner",Mt="fetcher_script",Rt="expect_swap",Pt="utils",It="0x1::coin::CoinInfo",qt="0x1::coin::CoinStore",Ut="custodian_v2",Ft="clob_v2",Nt="endpoints_v2",$t=i=>{if(typeof i=="string"&&i.startsWith("0x"))return"object";if(typeof i=="number"||typeof i=="bigint")return"u64";if(typeof i=="boolean")return"bool";throw new Error(`Unknown type for value: ${i}`)};var Re=(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))(Re||{});var Vt=Z;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,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,TransactionUtil,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime24h,cacheTime5min,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,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,toBuffer,toDecimalsAmount,utf8to16});
|
|
1
|
+
"use strict";var Ue=Object.create;var K=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Le=(i,e,t)=>e in i?K(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Ge=(i,e)=>{for(var t in e)K(i,t,{get:e[t],enumerable:!0})},_e=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ne(e))!Ve.call(i,s)&&s!==t&&K(i,s,{get:()=>e[s],enumerable:!(n=Fe(e,s))||n.enumerable});return i};var ye=(i,e,t)=>(t=i!=null?Ue($e(i)):{},_e(e||!i||!i.__esModule?K(t,"default",{value:i,enumerable:!0}):t,i)),Ke=i=>_e(K({},"__esModule",{value:!0}),i);var Ce=(i,e,t)=>(Le(i,typeof e!="symbol"?e+"":e,t),t);var Ht={};Ge(Ht,{CLOCK_ADDRESS:()=>Dt,CachedContent:()=>$,CetusClmmSDK:()=>z,ClmmExpectSwapModule:()=>It,ClmmFetcherModule:()=>qt,ClmmIntegratePoolModule:()=>Et,ClmmIntegratePoolV2Module:()=>Mt,ClmmIntegrateRouterModule:()=>Pt,ClmmIntegrateRouterWithPartnerModule:()=>Rt,ClmmIntegrateUtilsModule:()=>Ut,CoinAssist:()=>O,CoinInfoAddress:()=>Ft,CoinStoreAddress:()=>Nt,DEEP_SCALAR:()=>se,DEFAULT_GAS_BUDGET_FOR_MERGE:()=>ze,DEFAULT_GAS_BUDGET_FOR_SPLIT:()=>Ze,DEFAULT_GAS_BUDGET_FOR_STAKE:()=>Ye,DEFAULT_GAS_BUDGET_FOR_TRANSFER:()=>We,DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI:()=>Je,DEFAULT_NFT_TRANSFER_GAS_FEE:()=>et,DeepbookClobV2Moudle:()=>Vt,DeepbookCustodianV2Moudle:()=>$t,DeepbookEndpointsV2Moudle:()=>Lt,DeepbookUtilsModule:()=>Z,FLOAT_SCALAR:()=>D,GAS_SYMBOL:()=>Xe,GAS_TYPE_ARG:()=>J,GAS_TYPE_ARG_LONG:()=>ae,NORMALIZED_SUI_COIN_TYPE:()=>mt,OrderType:()=>Ie,RpcModule:()=>Q,SUI_SYSTEM_STATE_OBJECT_ID:()=>tt,TransactionUtil:()=>R,addHexPrefix:()=>ce,asIntN:()=>Ot,asUintN:()=>At,bufferToHex:()=>it,cacheTime1min:()=>re,cacheTime24h:()=>q,cacheTime5min:()=>ie,checkAddress:()=>rt,composeType:()=>ue,d:()=>a,decimalsMultiplier:()=>ee,default:()=>Kt,extractAddressFromType:()=>pt,extractStructTagFromType:()=>M,fixCoinType:()=>gt,fixDown:()=>F,fixSuiObjectId:()=>Oe,fromDecimalsAmount:()=>N,getDefaultSuiInputType:()=>Gt,getFutureTime:()=>V,getMoveObject:()=>ne,getMoveObjectType:()=>De,getMovePackageContent:()=>_t,getObjectDeletedResponse:()=>je,getObjectDisplay:()=>St,getObjectFields:()=>ge,getObjectId:()=>pe,getObjectNotExistsResponse:()=>Be,getObjectOwner:()=>kt,getObjectPreviousTransactionDigest:()=>Ct,getObjectReference:()=>de,getObjectType:()=>yt,getObjectVersion:()=>ht,getSuiObjectData:()=>L,hasPublicTransfer:()=>wt,hexToNumber:()=>ot,hexToString:()=>at,isSortedSymbols:()=>dt,isSuiObjectResponse:()=>ve,maxDecimal:()=>te,normalizeCoinType:()=>W,patchFixSuiObjectId:()=>X,printTransaction:()=>bt,removeHexPrefix:()=>Y,secretKeyToEd25519Keypair:()=>xt,secretKeyToSecp256k1Keypair:()=>jt,shortAddress:()=>st,shortString:()=>ke,sleepTime:()=>he,toBuffer:()=>Se,toDecimalsAmount:()=>Tt,utf8to16:()=>we});module.exports=Ke(Ht);var re=60*1e3,ie=5*60*1e3,q=24*60*60*1e3;function V(i){return Date.parse(new Date().toString())+i}var $=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 U=require("@mysten/sui/utils");var oe=require("@mysten/sui/transactions"),He="0x2::coin::Coin",Qe=/^0x2::coin::Coin<(.+)>$/,Ze=1e3,ze=500,We=100,Je=100,Ye=1e3,J="0x2::sui::SUI",ae="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",Xe="SUI",et=450,tt="0x0000000000000000000000000000000000000005",O=class{static getCoinTypeArg(e){let t=e.type.match(Qe);return t?t[1]:null}static isSUI(e){let t=O.getCoinTypeArg(e);return t?O.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 n=BigInt(0);return e.forEach(s=>{t===s.coinAddress&&(n+=BigInt(s.balance))}),n}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${He}<${e}>`}static getCoinAssets(e,t){let n=[];return t.forEach(s=>{W(s.coinAddress)===W(e)&&n.push(s)}),n}static isSuiCoin(e){return M(e).full_address===J}static selectCoinObjectIdGreaterThanOrEqual(e,t,n=[]){let s=O.selectCoinAssetGreaterThanOrEqual(e,t,n),r=s.selectedCoins.map(u=>u.coinObjectId),o=s.remainingCoins,c=s.selectedCoins.map(u=>u.balance.toString());return{objectArray:r,remainCoins:o,amountArray:c}}static selectCoinAssetGreaterThanOrEqual(e,t,n=[]){let s=O.sortByBalance(e.filter(l=>!n.includes(l.coinObjectId))),r=O.calculateTotalBalance(s);if(r<t)return{selectedCoins:[],remainingCoins:s};if(r===t)return{selectedCoins:s,remainingCoins:[]};let o=BigInt(0),c=[],u=[...s];for(;o<r;){let l=t-o,g=u.findIndex(m=>m.balance>=l);if(g!==-1){c.push(u[g]),u.splice(g,1);break}let d=u.pop();d.balance>0&&(c.push(d),o+=d.balance)}return{selectedCoins:O.sortByBalance(c),remainingCoins:O.sortByBalance(u)}}static sortByBalance(e){return e.sort((t,n)=>t.balance<n.balance?-1:t.balance>n.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,n)=>t.balance>n.balance?-1:t.balance<n.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,n)=>t+n.balance,BigInt(0))}static buildCoinWithBalance(e,t,n){return e===BigInt(0)&&O.isSuiCoin(t)?n.add((0,oe.coinWithBalance)({balance:e,useGasCoin:!1})):n.add((0,oe.coinWithBalance)({balance:e,type:t}))}};var nt=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function ce(i){return i.startsWith("0x")?i:`0x${i}`}function Y(i){return i.startsWith("0x")?`${i.slice(2)}`:i}function ke(i,e=4,t=4){let n=Math.max(e,1),s=Math.max(t,1);return`${i.slice(0,n+2)} ... ${i.slice(-s)}`}function st(i,e=4,t=4){return ke(ce(i),e,t)}function rt(i,e={leadingZero:!0}){if(typeof i!="string")return!1;let t=i;if(e.leadingZero){if(!i.startsWith("0x"))return!1;t=t.substring(2)}return nt.test(t)}function Se(i){if(!Buffer.isBuffer(i))if(Array.isArray(i))i=Buffer.from(i);else if(typeof i=="string")exports.isHexString(i)?i=Buffer.from(exports.padToEven(exports.stripHexPrefix(i)),"hex"):i=Buffer.from(i);else if(typeof i=="number")i=exports.intToBuffer(i);else if(i==null)i=Buffer.allocUnsafe(0);else if(i.toArray)i=Buffer.from(i.toArray());else throw new Error("invalid type");return i}function it(i){return ce(Se(i).toString("hex"))}function ot(i){let e=new ArrayBuffer(4),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint8(s,i.charCodeAt(s));return t.getUint32(0,!0)}function we(i){let e,t,n,s,r;e="";let o=i.length;for(t=0;t<o;)switch(n=i.charCodeAt(t++),n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=i.charAt(t-1);break;case 12:case 13:s=i.charCodeAt(t++),e+=String.fromCharCode((n&31)<<6|s&63);break;case 14:s=i.charCodeAt(t++),r=i.charCodeAt(t++),e+=String.fromCharCode((n&15)<<12|(s&63)<<6|(r&63)<<0);break}return e}function at(i){let e="",t=Y(i),n=t.length/2;for(let s=0;s<n;s++)e+=String.fromCharCode(parseInt(t.substr(s*2,2),16));return we(e)}var ct=0,Ae=1,ut=2;function Te(i,e){return i===e?ct:i<e?Ae:ut}function lt(i,e){let t=0,n=i.length<=e.length?i.length:e.length,s=Te(i.length,e.length);for(;t<n;){let r=Te(i.charCodeAt(t),e.charCodeAt(t));if(t+=1,r!==0)return r}return s}function dt(i,e){return lt(i,e)===Ae}function ue(i,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],s=[i,...e].filter(Boolean).join("::");return t&&t.length&&(s+=`<${t.join(", ")}>`),s}function pt(i){return i.split("::")[0]}function M(i){try{let e=i.replace(/\s/g,""),n=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){e=e.slice(0,e.indexOf("<"));let u={...M(e),type_arguments:n.map(l=>M(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>O.isSuiCoin(l)?l:M(l).source_address),u.source_address=ue(u.full_address,u.type_arguments),u}let s=e.split("::"),o={full_address:e,address:e===J||e===ae?"0x2":(0,U.normalizeSuiObjectId)(s[0]),module:s[1],name:s[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=ue(o.full_address,o.type_arguments),o}catch{return{full_address:i,address:"",module:"",name:"",type_arguments:[],source_address:i}}}function W(i){return M(i).source_address}function Oe(i){return i.toLowerCase().startsWith("0x")?(0,U.normalizeSuiObjectId)(i):i}var gt=(i,e=!0)=>{let t=i.split("::"),n=t.shift(),s=(0,U.normalizeSuiObjectId)(n);return e&&(s=Y(s)),`${s}::${t.join("::")}`};function X(i){for(let e in i){let t=typeof i[e];if(t==="object")X(i[e]);else if(t==="string"){let n=i[e];i[e]=Oe(n)}}}var mt=(0,U.normalizeStructTag)(U.SUI_TYPE_ARG);var le=ye(require("decimal.js"));le.default.config({precision:64,rounding:le.default.ROUND_DOWN,toExpNeg:-64,toExpPos:64});var H=ye(require("decimal.js"));function a(i){return H.default.isDecimal(i)?i:new H.default(i===void 0?0:i)}function ee(i){return a(10).pow(a(i).abs())}var F=(i,e)=>{try{return a(i).toDP(e,H.default.ROUND_DOWN).toString()}catch{return i}},te=(i,e)=>H.default.max(a(i),a(e));var xe=require("@mysten/sui/transactions");async function bt(i,e=!0){i.blockData.transactions.forEach((t,n)=>{})}var I=class{static async adjustTransactionForGas(e,t,n,s){s.setSender(e.senderAddress);let r=O.selectCoinAssetGreaterThanOrEqual(t,n).selectedCoins;if(r.length===0)throw new Error("Insufficient balance");let o=O.calculateTotalBalance(t);if(o-n>1e9)return{fixAmount:n};let c=await e.fullClient.calculationTxGas(s);if(O.selectCoinAssetGreaterThanOrEqual(t,BigInt(c),r.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(c)+BigInt(500);if(o-n<l){if(n-=l,n<0)throw new Error("gas Insufficient balance");let g=new xe.Transaction;return{fixAmount:n,newTx:g}}}return{fixAmount:n}}static buildCoinForAmount(e,t,n,s,r=!0,o=!1){let c=O.getCoinAssets(s,t);if(n===BigInt(0)&&c.length===0)return I.buildZeroValueCoin(t,e,s,r);let u=O.calculateTotalBalance(c);if(u<n)throw new Error(`The amount(${u}) is Insufficient balance for ${s} , expect ${n} `);return I.buildCoin(e,t,c,n,s,r,o)}static buildCoin(e,t,n,s,r,o=!0,c=!1){if(O.isSuiCoin(r)){if(o){let _=e.splitCoins(e.gas,[e.pure.u64(s)]);return{targetCoin:e.makeMoveVec({elements:[_]}),remainCoins:t,tragetCoinAmount:s.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(s===0n&&n.length>1){let _=O.selectCoinObjectIdGreaterThanOrEqual(n,s);return{targetCoin:e.object(_.objectArray[0]),remainCoins:_.remainCoins,tragetCoinAmount:_.amountArray[0],isMintZeroCoin:!1}}let y=O.selectCoinObjectIdGreaterThanOrEqual(n,s);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(s)]),remainCoins:y.remainCoins,tragetCoinAmount:s.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let u=O.selectCoinObjectIdGreaterThanOrEqual(n,s),l=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),g=u.objectArray;if(o)return{targetCoin:e.makeMoveVec({elements:g.map(y=>e.object(y))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...m]=g,p=e.object(d),b=p,h=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),A;return m.length>0&&e.mergeCoins(p,m.map(y=>e.object(y))),c&&Number(l)>Number(s)&&(b=e.splitCoins(p,[e.pure.u64(s)]),h=s.toString(),A=p),{targetCoin:b,remainCoins:u.remainCoins,originalSplitedCoin:A,tragetCoinAmount:h,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,n,s=!0){let r=I.callMintZeroValueCoin(t,n),o;return s?o=t.makeMoveVec({elements:[r]}):o=r,{targetCoin:o,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,n,s,r=!0){let o=O.getCoinAssets(s,t);if(n.amountFirst===BigInt(0))return o.length>0?I.buildCoin(e,[...t],[...o],n.amountFirst,s,r):I.buildZeroValueCoin(t,e,s,r);let c=O.calculateTotalBalance(o);if(c>=n.amountFirst)return I.buildCoin(e,[...t],[...o],n.amountFirst,s,r);if(c<n.amountSecond)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${n.amountSecond} `);return I.buildCoin(e,[...t],[...o],n.amountSecond,s,r)}static buildCoinTypePair(e,t){let n=[];if(e.length===2){let s=[];s.push(e[0],e[1]),n.push(s)}else{let s=[];s.push(e[0],e[e.length-1]),n.push(s);for(let r=1;r<e.length-1;r+=1){if(t[r-1]===0)continue;let o=[];o.push(e[0],e[r],e[e.length-1]),n.push(o)}}return n}},R=I;Ce(R,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));function L(i){return i.data}function je(i){if(i.error&&"object_id"in i.error&&"version"in i.error&&"digest"in i.error){let{error:e}=i;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Be(i){if(i.error&&"object_id"in i.error&&!("version"in i.error)&&!("digest"in i.error))return i.error.object_id}function de(i){if("reference"in i)return i.reference;let e=L(i);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:je(i)}function pe(i){return"objectId"in i?i.objectId:de(i)?.objectId??Be(i)}function ht(i){return"version"in i?i.version:de(i)?.version}function ve(i){return i.data!==void 0}function ft(i){return i.content!==void 0}function _t(i){let e=L(i);if(e?.content?.dataType==="package")return e.content.disassembled}function ne(i){let e="data"in i?L(i):i;if(!(!e||!ft(e)||e.content.dataType!=="moveObject"))return e.content}function De(i){return ne(i)?.type}function yt(i){let e=ve(i)?i.data:i;return!e?.type&&"data"in i?e?.content?.dataType==="package"?"package":De(i):e?.type}function Ct(i){return L(i)?.previousTransaction}function kt(i){return L(i)?.owner}function St(i){let e=L(i)?.display;return e||{data:null,error:null}}function ge(i){let e=ne(i)?.fields;if(e)return"fields"in e?e.fields:e}function wt(i){return ne(i)?.hasPublicTransfer??!1}var G=require("@mysten/bcs"),me=require("@mysten/sui/keypairs/ed25519"),be=require("@mysten/sui/keypairs/secp256k1");function Tt(i,e){let t=ee(a(e));return Number(a(i).mul(t))}function At(i,e=32){return BigInt.asUintN(e,BigInt(i)).toString()}function Ot(i,e=32){return Number(BigInt.asIntN(e,BigInt(i)))}function N(i,e){let t=ee(a(e));return Number(a(i).div(t))}function xt(i,e="hex"){if(i instanceof Uint8Array){let n=Buffer.from(i);return me.Ed25519Keypair.fromSecretKey(n)}let t=e==="hex"?(0,G.fromHEX)(i):(0,G.fromB64)(i);return me.Ed25519Keypair.fromSecretKey(t)}function jt(i,e="hex"){if(i instanceof Uint8Array){let n=Buffer.from(i);return be.Secp256k1Keypair.fromSecretKey(n)}let t=e==="hex"?(0,G.fromHEX)(i):(0,G.fromB64)(i);return be.Secp256k1Keypair.fromSecretKey(t)}var he=async i=>new Promise(e=>{setTimeout(()=>{e(1)},i)});var Ee=require("@mysten/sui/client"),Q=class extends Ee.SuiClient{async queryEventsByPage(e,t="all"){let n=[],s=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.queryEvents({query:e,cursor:o,limit:r?null:t.limit});c.data?(n=[...n,...c.data],s=c.hasNextPage,o=c.nextCursor):s=!1}while(r&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getOwnedObjectsByPage(e,t,n="all"){let s=[],r=!0,o=n==="all",c=o?null:n.cursor;do{let u=await this.getOwnedObjects({owner:e,...t,cursor:c,limit:o?null:n.limit});u.data?(s=[...s,...u.data],r=u.hasNextPage,c=u.nextCursor):r=!1}while(o&&r);return{data:s,nextCursor:c,hasNextPage:r}}async getDynamicFieldsByPage(e,t="all"){let n=[],s=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.getDynamicFields({parentId:e,cursor:o,limit:r?null:t.limit});c.data?(n=[...n,...c.data],s=c.hasNextPage,o=c.nextCursor):s=!1}while(r&&s);return{data:n,nextCursor:o,hasNextPage:s}}async batchGetObjects(e,t,n=50){let s=[];try{for(let r=0;r<Math.ceil(e.length/n);r++){let o=await this.multiGetObjects({ids:e.slice(r*n,n*(r+1)),options:t});s=[...s,...o]}}catch{}return s}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let n=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:s}=n.effects;return Number(s.computationCost)+Number(s.storageCost)-Number(s.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};var Re=require("@mysten/deepbook-v3"),f=require("@mysten/sui/bcs"),qe=require("js-base64"),S=require("@mysten/sui/transactions"),T=require("@mysten/sui/utils");function Me(...i){let e="DeepbookV3_Utils_Sdk###"}var se=1e6,D=1e9,Bt={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},vt={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},Pe=1e3*60*60*24*365*100,Z=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?vt:Bt}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:n}){let s=new S.Transaction;s.setSenderIfNotSet(e);let r=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=(0,S.coinWithBalance)({type:t.coinType,balance:BigInt(n)});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[r,o],typeArguments:[t.coinType]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r],typeArguments:[]}),s.moveCall({target:"0x2::transfer::public_share_object",arguments:[r],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),s}depositIntoManager({account:e,balanceManager:t,coin:n,amountToDeposit:s,tx:r}){let o=r||new S.Transaction;if(t){o.setSenderIfNotSet(e);let c=(0,S.coinWithBalance)({type:n.coinType,balance:BigInt(s)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(t),c],typeArguments:[n.coinType]}),o}return null}withdrawFromManager({account:e,balanceManager:t,coin:n,amountToWithdraw:s,returnAssets:r,txb:o}){let c=o||new S.Transaction,u=c.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[c.object(t),c.pure.u64(s)],typeArguments:[n.coinType]});return r?u:(c.transferObjects([u],e),c)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:n=new S.Transaction}){for(let s in t)t[s].forEach(o=>{let c=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[n.object(s),n.pure.u64(o.amount)],typeArguments:[o.coinType]});n.transferObjects([c],e)});return n}async getBalanceManager(e,t=!0){let n=`getBalanceManager_${e}`,s=this.getCache(n,t);if(!t&&s!==void 0)return s;try{let r=new S.Transaction;r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r.pure.address(e)],typeArguments:[]});let u=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}))?.events?.filter(g=>g.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],l=[];return u.forEach(g=>{l.push({balanceManager:g,cetusBalanceManager:""})}),this.updateCache(n,l,q),l||[]}catch(r){throw r instanceof Error?r:new Error(String(r))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},n=new S.Transaction){let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[n.object(t)]});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[n.object(e.address),n.object(t),s],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),n}async getManagerBalance({account:e,balanceManager:t,coins:n}){try{let s=new S.Transaction;n.forEach(c=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(t)],typeArguments:[c.coinType]})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}),o={};return r.results?.forEach((c,u)=>{let l=n[u],g=c.returnValues[0][0],d=f.bcs.U64.parse(new Uint8Array(g)),m=a(d),p=m.eq(0)?"0":m.div(Math.pow(10,l.decimals)).toString();o[l.coinType]={adjusted_balance:p,balance:m.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let n=new S.Transaction,s=await this.getBalanceManager(e,!0);if(!Array.isArray(s)||s.length===0)return{};s.forEach(c=>{t.forEach(u=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(c.balanceManager)],typeArguments:[u.coinType]})})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),o={};return s.forEach((c,u)=>{let l={},g=u*t.length;t.forEach((d,m)=>{let p=g+m,b=r.results?.[p];if(b){let h=b.returnValues[0][0],A=f.bcs.U64.parse(new Uint8Array(h)),y=a(A),C=y.eq(0)?"0":y.div(Math.pow(10,d.decimals)).toString();l[d.coinType]={adjusted_balance:C,balance:y.toString()}}}),o[c.balanceManager]=l}),o}catch(n){throw n instanceof Error?n:new Error(String(n))}}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(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],r=Number(f.bcs.U64.parse(new Uint8Array(s))),o=Math.pow(10,e.baseCoin.decimals).toString(),c=Math.pow(10,e.quoteCoin.decimals).toString();return a(r).mul(o).div(c).div(D).toString()}catch(t){return Me("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",n=this.getCache(t,e);if(n!==void 0)return n;let s=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),r=/<([^>]+)>/,o=[];return s?.data?.forEach(c=>{let u=c?.parsedJson,l=c.type.match(r);if(l){let d=l[1].split(", ");o.push({...u,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,o,q),o}async getQuoteQuantityOut(e,t,n){let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(se).toString(),baseQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getBaseQuantityOut(e,t,n){let s=new S.Transaction;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.bcs.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{quoteQuantityDisplay:a(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(se).toString(),quoteQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getQuantityOut(e,t,n,s){let r=new S.Transaction;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[r.object(e.address),r.pure.u64(t),r.pure.u64(n),r.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:r}),c=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[0][0]))),u=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[1][0]))),l=Number(f.bcs.U64.parse(new Uint8Array(o.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:a(n).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(c).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(u).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(l).div(se).toString(),baseQuantity:t,quoteQuantity:n,baseOut:c,quoteOut:u,deepRequired:l}}async getReferencePool(e){let t=await this.getPools(),n=e.baseCoin.coinType,s=e.quoteCoin.coinType,r=this._deep.coinType;for(let o=0;o<t.length;o++){let c=t[o];if(c.address===e.address)continue;let u=[c.baseCoinType,c.quoteCoinType];if(c.baseCoinType===r&&(u.includes(n)||u.includes(s)))return c}return null}async updateDeepPrice(e,t){let n=await this.getReferencePool(e);return n?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(n.pool_id),t.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,n.baseCoinType,n.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,n,s,r,o,c){let u=this.deepCoin;try{let{taker_fee:l,maker_fee:g}=e,d=a(l).div(D).toString(),m=a(g).div(D).toString(),p=await this.getMarketPrice(e),b=o?n:p!=="0"?p:c;if(b==="0")throw new Error("Cannot get market price");let h=Math.pow(10,e.baseCoin.decimals).toString(),A=Math.pow(10,e.quoteCoin.decimals).toString(),y=a(b).div(h).mul(A).mul(D).toString();if(s){let w=await this.getMarketPrice(e),k=a(o?n:w!=="0"?w:c).div(h).mul(A).mul(D).toString(),j=await this.getOrderDeepPrice(e);if(!j)throw new Error("Cannot get deep price");let B=te(k,n),E=a(t).mul(a(d)).mul(a(j.deep_per_asset)).div(a(D)),v=a(t).mul(a(m)).mul(a(j.deep_per_asset)).div(a(D));j.asset_is_base||(E=E.mul(B).div(a(D)),v=v.mul(B).div(a(D)));let P=E.ceil().toString(),fe=v.ceil().toString();return{takerFee:P,makerFee:fe,takerFeeDisplay:N(P,u.decimals).toString(),makerFeeDisplay:N(fe,u.decimals).toString(),feeType:u.coinType}}if(r){let w=te(y,n),x=a(t).mul(w).mul(a(d).mul(1.25)).div(a(D)).ceil().toFixed(0),k=a(t).mul(w).mul(a(m).mul(1.25)).div(a(D)).ceil().toFixed(0);return{takerFee:x,makerFee:k,takerFeeDisplay:N(x,e.quoteCoin.decimals).toString(),makerFeeDisplay:N(k,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=a(t).mul(a(d).mul(1.25)).ceil().toFixed(0),_=a(t).mul(a(m).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:_,takerFeeDisplay:N(C,e.baseCoin.decimals).toString(),makerFeeDisplay:N(_,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getOrderDeepPrice(e,t=!0){let n=`getOrderDeepPrice_${e.address}}`,s=this.getCache(n);if(s!==void 0)return s;try{let r=new S.Transaction,o=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,r)&&(o=!0),r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let c=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:r}),u=o?c.results[1]?.returnValues[0]?.[0]:c.results[0]?.returnValues[0]?.[0],l=this.parseOrderDeepPrice(new Uint8Array(u));return this.updateCache(n,l,re),l}catch{return await he(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),n=t.getUint8(0)!==0,s=Number(t.getBigUint64(1,!0));return{asset_is_base:n,deep_per_asset:s}}getCoinAssets(e,t,n,s){return R.buildCoinForAmount(s,n,BigInt(a(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,n,s,r,o,c){let u=this.deepCoin;if(!c)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let l=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];s&&l.push(u);let g=await this.getManagerBalance({account:r,balanceManager:c,coins:l}),d=g?.[t]?.balance||"0",m=g?.[n]?.balance||"0",p=o&&g?.[u.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:m,feeManaerBalance:p}}catch(l){throw l instanceof Error?l:new Error(String(l))}}getFeeAsset(e,t,n,s,r,o,c,u,l,g){let d=a(e).gt(0)&&l,m="0";if(!d)return{feeAsset:this.getEmptyCoin(g,t),haveDepositFee:"0"};if(o||c){let p=a(r).sub(o?s:n);m=p.lte(0)?e:p.sub(e).lt(0)?p.sub(e).toString():"0"}else m=a(r).sub(e).lt("0")?a(r).sub(e).abs().toString():"0";return{feeAsset:a(m).gt("0")?this.getCoinAssets(t,m,u,g):this.getEmptyCoin(g,t),haveDepositFee:m}}async getTransactionRelatedAssets(e,t,n,s,r,o,c,u,l){try{let g=this.deepCoin,d=(0,T.normalizeStructTag)(e.baseCoin.coinType),m=(0,T.normalizeStructTag)(e.quoteCoin.coinType),p=d===g.coinType,b=m===g.coinType,h=!p&&!b,{baseManagerBlance:A,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,m,h,o,c,u),_,w,x=!1,k=await this._sdk.getOwnerCoinAssets(o);if(r){c||(n=a(n).add(a(s)).toString());let B=a(y).sub(n).toString();a(B).lt(0)?(x=!0,w=this.getCoinAssets(m,B,k,l)):w=this.getEmptyCoin(l,m),_=this.getEmptyCoin(l,d)}else{c||(t=a(t).add(a(s)).toString());let B=a(A).sub(t).toString();a(B).lt(0)?(x=!0,_=this.getCoinAssets(d,B,k,l)):_=this.getEmptyCoin(l,d),w=this.getEmptyCoin(l,m)}let j=this.getFeeAsset(s,g.coinType,t,n,C,b,p,k,c,l);return{baseAsset:_,quoteAsset:w,feeAsset:j,haveDeposit:x}}catch(g){throw g instanceof Error?g:new Error(String(g))}}async getMarketTransactionRelatedAssets(e,t,n,s,r,o,c,u,l,g){try{let d=this.deepCoin,m=(0,T.normalizeStructTag)(e.baseCoin.coinType),p=(0,T.normalizeStructTag)(e.quoteCoin.coinType),b=m===d.coinType,h=p===d.coinType,A=!b&&!h,y=await this.getTransactionRelatedBalance(e,m,p,A,o,c,u),{feeManaerBalance:C}=y,_=a(y.baseManagerBlance).add(a(g?.base||"0")).toString(),w=a(y.quoteManagerBlance).add(a(g?.quote||"0")).toString(),x=await this._sdk.getOwnerCoinAssets(o),k;c&&a(C).lt(s)?k=this.getCoinAssets(d.coinType,a(s).sub(C).toString(),x,l):k=this.getEmptyCoin(l,d.coinType);let j,B;if(r){c||(n=a(n).add(a(s)).toString());let E=a(w).sub(n).toString();if(a(E).lt(0)){let v;a(w).gt(0)&&(v=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:w,returnAssets:!0,txb:l}));let P=this.getCoinAssets(p,E,x,l);v&&l.mergeCoins(P,[v]),B=P}else B=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:n,returnAssets:!0,txb:l});j=this.getEmptyCoin(l,m)}else{c||(t=a(t).add(a(s)).toString());let E=a(_).sub(t).toString();if(a(E).lt(0)){let v;a(_).gt(0)&&(v=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:_,returnAssets:!0,txb:l}));let P=this.getCoinAssets(m,E,x,l);v&&l.mergeCoins(P,[v]),j=P}else j=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:l});B=this.getEmptyCoin(l,p)}return{baseAsset:j,quoteAsset:B,feeAsset:k}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:n,orderType:s,isBid:r,maxFee:o,account:c,payWithDeep:u,expirationTimestamp:l=Date.now()+Pe}){try{let g=this.deepCoin,d=e.address,m=e.baseCoin.decimals,p=e.quoteCoin.decimals,b=e.baseCoin.coinType,h=e.quoteCoin.coinType,A=a(t).mul(10**(p-m+9)).toString(),y=(0,T.normalizeStructTag)(b),C=(0,T.normalizeStructTag)(h),_=new S.Transaction,w,x,k=await this._sdk.getOwnerCoinAssets(c);if(r){let v=a(t).mul(a(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();u||(v=a(v).add(a(o)).toString()),x=R.buildCoinForAmount(_,k,BigInt(v),C,!1,!0)?.targetCoin}else{let v=n;u||(v=a(n).abs().add(a(o)).toString()),w=R.buildCoinForAmount(_,k,BigInt(a(v).abs().toString()),y,!1,!0)?.targetCoin}let j=u?a(o).gt(0)?R.buildCoinForAmount(_,k,BigInt(a(o).abs().ceil().toString()),g.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,g.coinType):this.getEmptyCoin(_,g.coinType),B=_.moveCall({typeArguments:[r?b:h],target:"0x2::coin::zero",arguments:[]}),E=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(d),r?B:w,r?x:B,j,_.pure.u8(s),_.pure.u8(0),_.pure.u64(A),_.pure.u64(n),_.pure.bool(r),_.pure.bool(!1),_.pure.u64(l),_.object(T.SUI_CLOCK_OBJECT_ID)];return _.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:E}),_}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:n,maxFee:s,account:r,payWithDeep:o,slippage:c=.01}){try{let u=e.address,l=e.baseCoin.coinType,g=e.quoteCoin.coinType,d=(0,T.normalizeStructTag)(l),m=(0,T.normalizeStructTag)(g),p=new S.Transaction,b,h,A=t,y,C=await this.getOrderBook(e,"all",6);if(n){let k=C?.ask?.[0]?.price||"0",j=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(j).plus(a(j).mul(c)).ceil().toString()}else{let k=await C?.bid?.[0]?.price||"0",j=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(j).minus(a(j).mul(c)).floor().toString()}let _=await this._sdk.getOwnerCoinAssets(r);n?(o||(y=a(y).add(a(s)).toString()),h=this.getCoinAssets(m,y,_,p),b=this.getEmptyCoin(p,d)):(o||(A=a(A).add(a(s)).toString()),h=this.getEmptyCoin(p,m),b=this.getCoinAssets(d,A,_,p));let w=o?a(s).gt(0)?R.buildCoinForAmount(p,_,BigInt(a(s).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(p,this.deepCoin.coinType):this.getEmptyCoin(p,this.deepCoin.coinType),x=[p.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),p.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),p.object(u),b,h,w,p.pure.u8(0),p.pure.u64(t),p.pure.bool(n),p.pure.bool(o),p.pure.u64(y),p.object(T.SUI_CLOCK_OBJECT_ID)];return p.moveCall({typeArguments:[d,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:x}),p}catch(u){throw u instanceof Error?u:new Error(String(u))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:n,quantity:s,isBid:r,orderType:o,maxFee:c,account:u,payWithDeep:l,expirationTimestamp:g=Date.now()+Pe}){try{let d=this.deepCoin,m=a(n).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),p=t.baseCoin.coinType,b=t.quoteCoin.coinType,h=new S.Transaction,A=r?a(n).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=r?"0":s,{baseAsset:C,quoteAsset:_,feeAsset:w,haveDeposit:x}=await this.getTransactionRelatedAssets(t,y,A,c,r,u,l,e,h);if(x){let B=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(t.address),h.object(e),C,_,w.feeAsset,h.pure.u8(o),h.pure.u8(0),h.pure.u64(m),h.pure.u64(s),h.pure.bool(r),h.pure.bool(l),h.pure.u64(g),h.object(T.SUI_CLOCK_OBJECT_ID)];return h.moveCall({typeArguments:[p,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:B}),h}let k=new S.Transaction;a(w.haveDepositFee).gt(0)&&this.depositIntoManager({account:u,balanceManager:e,coin:d,amountToDeposit:w.haveDepositFee,tx:k});let j=[k.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),k.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),k.object(t.address),k.object(e),k.pure.u8(o),k.pure.u8(0),k.pure.u64(m),k.pure.u64(s),k.pure.bool(r),k.pure.bool(l),k.pure.u64(g),k.object(T.SUI_CLOCK_OBJECT_ID)];return k.moveCall({typeArguments:[p,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:j}),k}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:n,newOrderQuantity:s}){let r=new S.Transaction;return r.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(e),r.object(t.address),r.pure.u128(n),r.pure.u64(s),r.object(T.SUI_CLOCK_OBJECT_ID)]}),r}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:n}=e,s=new S.Transaction,r=await this.getMarketPrice(e),o=a(r).gt(0)?r:Math.pow(10,-1),c=Math.pow(10,6),u=a(o).mul(Math.pow(10,9+n.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+n.decimals-t.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(u),s.pure.u64(l),s.pure.bool(!1),s.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:s}),m=[],p=d.results[0].returnValues[0][0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(p)),h=d.results[0].returnValues[1][0],A=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(h));return b.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),w=a(A[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:_,quantity:w})}),m?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:n}=e,s=new S.Transaction,r=await this.getMarketPrice(e),o=a(r).gt(0)?a(r).div(3).toNumber():Math.pow(10,-6),c=a(r).gt(0)?r:Math.pow(10,6),u=a(o).mul(Math.pow(10,9+n.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+n.decimals-t.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(F(u,0)),s.pure.u64(F(l,0)),s.pure.bool(!0),s.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[t.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:s}),m=[],p=d.results[0].returnValues[0][0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(p)),h=d.results[0].returnValues[1][0],A=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(h));return b.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),w=a(A[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:_,quantity:w})}),m?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:n,quoteCoin:s}=e,r=new S.Transaction,o=await this.getMarketPrice(e),c,u;t?(c=a(o).gt(0)?a(o).div(3).toNumber():Math.pow(10,-6),u=a(o).gt(0)?o:Math.pow(10,6)):(c=a(o).gt(0)?o:Math.pow(10,-1),u=a(o).gt(0)?a(o).mul(3).toNumber():Math.pow(10,6));let l=a(c).mul(Math.pow(10,9+s.decimals-n.decimals)).toString(),g=a(u).mul(Math.pow(10,9+s.decimals-n.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(F(l,0)),r.pure.u64(F(g,0)),r.pure.bool(t),r.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[n.coinType,s.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,m=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:r}),p=[],b=m.results[0].returnValues[0][0],h=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b)),A=m.results[0].returnValues[1][0],y=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(A));return h.forEach((C,_)=>{let w=a(C).div(Math.pow(10,9+s.decimals-n.decimals)).toString(),x=a(y[_]).div(Math.pow(10,n.decimals)).toString();p.push({price:w,quantity:x})}),p?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:n,quoteQuantity:s,isBid:r,maxFee:o,account:c,payWithDeep:u,slippage:l=.01,settled_balances:g={base:"0",quote:"0"}}){try{let d=(0,T.normalizeStructTag)(t.baseCoin.coinType),m=(0,T.normalizeStructTag)(t.quoteCoin.coinType),p=new S.Transaction;g&&(a(g.base).gt(0)||a(g.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},p);let{baseAsset:b,quoteAsset:h,feeAsset:A}=await this.getMarketTransactionRelatedAssets(t,n,s,o,r,c,u,e,p,g),y=await this.getOrderBook(t,"all",6);if(r){let w=y?.ask?.[0]?.price||"0",x=a(w).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();s=a(x).plus(a(x).mul(l)).ceil().toString()}else{let w=await y?.bid?.[0]?.price||"0",x=a(w).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();s=a(x).minus(a(x).mul(l)).floor().toString()}let C=s,_=[p.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),p.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),p.object(t.address),p.object(e),b,h,A,p.pure.u8(0),p.pure.u64(n),p.pure.bool(r),p.pure.bool(u),p.pure.u64(C),p.object(T.SUI_CLOCK_OBJECT_ID)];return p.setSenderIfNotSet(c),p.moveCall({typeArguments:[d,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:_}),p}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let n=new S.Transaction;e.forEach(l=>{let g=l?.pool,d=l?.orderId;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[n.object(g.pool_id),n.pure.u128(BigInt(d))],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:n}),r=f.bcs.struct("ID",{bytes:f.bcs.Address}),o=f.bcs.struct("OrderDeepPrice",{asset_is_base:f.bcs.bool(),deep_per_asset:f.bcs.u64()}),c=f.bcs.struct("Order",{balance_manager_id:r,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:o,epoch:f.bcs.u64(),status:f.bcs.u8(),expire_timestamp:f.bcs.u64()}),u=[];return s?.results?.forEach(l=>{let g=l.returnValues[0][0],d=c.parse(new Uint8Array(g));u.push(d)}),u}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),n=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:n,orderId:s}}async getOpenOrder(e,t,n,s){let r;if(s)r=s;else{let l=new S.Transaction;l.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[l.object(e.address),l.object(n)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let d=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:l})).results[0].returnValues[0][0];r=f.bcs.struct("VecSet",{constants:f.bcs.vector(f.bcs.U128)}).parse(new Uint8Array(d)).constants}let o=r.map(l=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:l})),c=await this.getOrderInfoList(o,t)||[],u=[];return c.forEach(l=>{let g=this.decodeOrderId(BigInt(l.order_id));u.push({...l,price:g.price,isBid:g.isBid})}),u}async getAllMarketsOpenOrders(e,t){try{let n=await this.getPools(),s=new S.Transaction;n.forEach(d=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(d.pool_id),s.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let o=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s})).results?.map(d=>d.returnValues?.[0]?.[0])||[],c=f.bcs.struct("VecSet",{constants:f.bcs.vector(f.bcs.U128)}),u=[];o.forEach((d,m)=>{let p=c.parse(new Uint8Array(d)).constants;p.length>0&&p.forEach(b=>{u.push({pool:n[m],orderId:b})})});let l=await this.getOrderInfoList(u,e)||[],g=[];return u.forEach((d,m)=>{let p=this.decodeOrderId(BigInt(d.orderId)),b=l.find(h=>h.order_id===d.orderId)||{};g.push({...d,...b,price:p.price,isBid:p.isBid})}),g}catch{return[]}}cancelOrders(e,t){let n=new S.Transaction;return e.forEach(s=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),n.object(t),n.object(s.poolInfo.address),n.pure.u128(s.orderId),n.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[s.poolInfo.baseCoin.coinType,s.poolInfo.quoteCoin.coinType]})}),n}async getDeepbookOrderBook(e,t,n,s,r,o){let c=this._sdk.fullClient,l=await new Re.DeepBookClient({client:c,address:r,env:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,t,n,s)}processOrderBookData(e,t,n,s){let r=e.returnValues[0][0],o=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(r)),c=e.returnValues[1][0],u=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(c)),l={};return o.forEach((d,m)=>{let p=a(d).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),b=a(u[m]).div(Math.pow(10,t.decimals)).toString();l[p]?l[p]={price:p,quantity:a(l[p].quantity).add(b).toString()}:l[p]={price:p,quantity:b}}),Object.values(l)}getLevel2RangeTx(e,t,n,s,r=new S.Transaction){let{baseCoin:o,quoteCoin:c}=e,u=F(a(n).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0),l=F(a(s).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0);return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(u),r.pure.u64(l),r.pure.bool(t),r.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[o.coinType,c.coinType]}),r}async fetchOrderBook(e,t,n,s,r,o){let c=new S.Transaction,{baseCoin:u,quoteCoin:l}=e;try{if(t==="bid"||t==="all"){let b=s,h=n==="0"?r:n;c=this.getLevel2RangeTx(e,!0,b,h,c)}if(t==="ask"||t==="all"){let b=n==="0"?s:n,h=r;c=this.getLevel2RangeTx(e,!1,b,h,c)}let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:c}),m=[];(t==="bid"||t==="all")&&(m=d.results?.[0]?this.processOrderBookData(d.results[0],u,l,o):[]);let p=[];if(t==="ask"||t==="all"){let b=t==="ask"?0:1;p=d.results?.[b]?this.processOrderBookData(d.results[b],u,l,o):[]}return{bid:m.sort((b,h)=>h.price-b.price),ask:p.sort((b,h)=>b.price-h.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,m=[],p=[];try{let b=this.getLevel2RangeTx(e,!0,s,n),h=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:b});m=h.results?.[0]?this.processOrderBookData(h.results[0],u,l,o):[]}catch{m=[]}try{let b=this.getLevel2RangeTx(e,!1,s,n),h=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:b});p=h.results?.[0]?this.processOrderBookData(h.results[0],u,l,o):[]}catch{p=[]}return{bid:m,ask:p}}}async getOrderBook(e,t,n){let s={bid:[],ask:[]};try{let r=await this.getMarketPrice(e),o=t,c=Math.pow(10,-n),u=Math.pow(10,n),l=await this.fetchOrderBook(e,o,r,c,u,n);return{bid:l?.bid,ask:l?.ask}}catch{return s}}async getOrderBookOrigin(e,t){try{let n=new S.Transaction,s=await this.getMarketPrice(e),{baseCoin:r,quoteCoin:o}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),m=s,p=a(d).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),b=a(m).mul(Math.pow(10,9+o.decimals-r.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(p),n.pure.u64(b),n.pure.bool(!0),n.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,o.coinType]})}if(t==="ask"||t==="all"){let d=s,m=Math.pow(10,6),p=a(d).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),b=a(m).mul(Math.pow(10,9+o.decimals-r.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(p),n.pure.u64(b),n.pure.bool(!1),n.object(T.SUI_CLOCK_OBJECT_ID)],typeArguments:[r.coinType,o.coinType]})}let c=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:c,transactionBlock:n}),l=[];if(t==="bid"||t==="all"){let d=u.results[0]?.returnValues[0]?.[0],m=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(d)),p=u.results[0]?.returnValues[1]?.[0],b=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(p));m.forEach((h,A)=>{let y=a(h).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),C=a(b[A]).div(Math.pow(10,r.decimals)).toString();l.push({price:y,quantity:C})})}let g=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,m=u.results[d]?.returnValues[0]?.[0],p=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(m)),b=u.results[d]?.returnValues[1]?.[0],h=f.bcs.vector(f.bcs.u64()).parse(new Uint8Array(b));p.forEach((A,y)=>{let C=a(A).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),_=a(h[y]).div(Math.pow(10,r.decimals)).toString();g.push({price:C,quantity:_})})}return{bid:l,ask:g}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((s,r)=>[(0,T.normalizeStructTag)(s.coinType),s]))}async getAccount(e,t){let n=new S.Transaction;for(let c=0;c<t.length;c++){let u=t[c];n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[n.object(u.address),n.object(e)],typeArguments:[u.baseCoin.coinType,u.quoteCoin.coinType]})}let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:n}),r;if(s?.events.length===0)return null;let o=[];return s?.events?.forEach((c,u)=>{r=c?.parsedJson;let l=r.account.open_orders.contents,g=r.account.owed_balances,d=r.account.settled_balances,m=r.account.unclaimed_rebates,p=r.account.taker_volume;o.push({balance_manager_id:e,open_orders:l,owed_balances:g,settled_balances:d,unclaimed_rebates:m,taker_volume:p,poolInfo:t[u]})}),o}async getSuiTransactionResponse(e,t=!1){let n=`${e}_getSuiTransactionResponse`,s=this.getCache(n,t);if(s!==void 0)return s;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(n,r,q),r}transformExtensions(e,t,n=!0){let s=[];for(let r of t){let{key:o}=r.fields,{value:c}=r.fields;if(o==="labels")try{c=JSON.parse(decodeURIComponent(qe.Base64.decode(c)))}catch{}n&&(e[o]=c),s.push({key:o,value:c})}delete e.extension_fields,n||(e.extensions=s)}async getCoinConfigs(e=!1,t=!0){let n=this.sdk.sdkOptions.coinlist.handle,s=`${n}_getCoinConfigs`,r=this.getCache(s,e);if(r)return r;let c=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(g=>g.objectId),u=await this._sdk.fullClient.batchGetObjects(c,{showContent:!0}),l=[];return u.forEach(g=>{let d=this.buildCoinConfig(g,t);this.updateCache(`${n}_${d.address}_getCoinConfig`,d,q),l.push({...d})}),this.updateCache(s,l,q),l}buildCoinConfig(e,t=!0){let n=ge(e);n=n.value.fields;let s={...n};return s.id=pe(e),s.address=M(n.coin_type.fields.name).full_address,n.pyth_id&&(s.pyth_id=(0,T.normalizeSuiObjectId)(n.pyth_id)),this.transformExtensions(s,n.extension_fields.fields.contents,t),delete s.coin_type,s}updateCache(e,t,n=ie){let s=this._cache[e];s?(s.overdueTime=V(n),s.value=t):s=new $(t,V(n)),this._cache[e]=s}getCache(e,t=!1){let n=this._cache[e],s=n?.isValid();if(!t&&s)return n.value;s||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:n,baseCoinType:s,quoteCoinType:r}){let o=new S.Transaction,c=O.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",o);o.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[s,r],arguments:[o.object(this.sdk.sdkOptions.deepbook.registry_id),o.pure.u64(e),o.pure.u64(t),o.pure.u64(n),c]});try{let u=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:o});if(u.effects.status.status==="success")return o;if(u.effects.status.status==="failure"&&u.effects.status.error&&u.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(u){throw u instanceof Error?u:new Error(String(u))}return o}};var z=class{_cache={};_rpcModule;_deepbookUtils;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new Q({url:e.fullRpcUrl}),this._deepbookUtils=new Z(this),X(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,n=!0){let s=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,c=this.getCache(o,n);if(c)return c;for(;;){let u=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:r}):this.fullClient.getAllCoins({owner:e,cursor:r}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&s.push({coinAddress:M(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),r=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,s,30*1e3),s}async getOwnerCoinBalances(e,t){let n=[];return t?n=[await this.fullClient.getBalance({owner:e,coinType:t})]:n=[...await this.fullClient.getAllBalances({owner:e})],n}updateCache(e,t,n=q){let s=this._cache[e];s?(s.overdueTime=V(n),s.value=t):s=new $(t,V(n)),this._cache[e]=s}getCache(e,t=!1){let n=this._cache[e],s=n?.isValid();if(!t&&s)return n.value;s||delete this._cache[e]}};var Dt="0x0000000000000000000000000000000000000000000000000000000000000006",Et="pool_script",Mt="pool_script_v2",Pt="router",Rt="router_with_partner",qt="fetcher_script",It="expect_swap",Ut="utils",Ft="0x1::coin::CoinInfo",Nt="0x1::coin::CoinStore",$t="custodian_v2",Vt="clob_v2",Lt="endpoints_v2",Gt=i=>{if(typeof i=="string"&&i.startsWith("0x"))return"object";if(typeof i=="number"||typeof i=="bigint")return"u64";if(typeof i=="boolean")return"bool";throw new Error(`Unknown type for value: ${i}`)};var Ie=(s=>(s[s.NO_RESTRICTION=0]="NO_RESTRICTION",s[s.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",s[s.FILL_OR_KILL=2]="FILL_OR_KILL",s[s.POST_ONLY=3]="POST_ONLY",s))(Ie||{});var Kt=z;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,GAS_SYMBOL,GAS_TYPE_ARG,GAS_TYPE_ARG_LONG,NORMALIZED_SUI_COIN_TYPE,OrderType,RpcModule,SUI_SYSTEM_STATE_OBJECT_ID,TransactionUtil,addHexPrefix,asIntN,asUintN,bufferToHex,cacheTime1min,cacheTime24h,cacheTime5min,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,normalizeCoinType,patchFixSuiObjectId,printTransaction,removeHexPrefix,secretKeyToEd25519Keypair,secretKeyToSecp256k1Keypair,shortAddress,shortString,sleepTime,toBuffer,toDecimalsAmount,utf8to16});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Se=Object.defineProperty;var we=(i,e,t)=>e in i?Se(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var re=(i,e,t)=>(we(i,typeof e!="symbol"?e+"":e,t),t);var ie=5*60*1e3,I=24*60*60*1e3;function N(i){return Date.parse(new Date().toString())+i}var F=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{normalizeSuiObjectId as W,normalizeStructTag as ve,SUI_TYPE_ARG as De}from"@mysten/sui/utils";var Ae="0x2::coin::Coin",Oe=/^0x2::coin::Coin<(.+)>$/,Ye=1e3,Xe=500,et=100,tt=100,nt=1e3,Z="0x2::sui::SUI",oe="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",st="SUI",rt=450,it="0x0000000000000000000000000000000000000005",T=class{static getCoinTypeArg(e){let t=e.type.match(Oe);return t?t[1]:null}static isSUI(e){let t=T.getCoinTypeArg(e);return t?T.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 s=BigInt(0);return e.forEach(n=>{t===n.coinAddress&&(s+=BigInt(n.balance))}),s}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${Ae}<${e}>`}static getCoinAssets(e,t){let s=[];return t.forEach(n=>{Q(n.coinAddress)===Q(e)&&s.push(n)}),s}static isSuiCoin(e){return M(e).full_address===Z}static selectCoinObjectIdGreaterThanOrEqual(e,t,s=[]){let n=T.selectCoinAssetGreaterThanOrEqual(e,t,s),r=n.selectedCoins.map(u=>u.coinObjectId),o=n.remainingCoins,c=n.selectedCoins.map(u=>u.balance.toString());return{objectArray:r,remainCoins:o,amountArray:c}}static selectCoinAssetGreaterThanOrEqual(e,t,s=[]){let n=T.sortByBalance(e.filter(l=>!s.includes(l.coinObjectId))),r=T.calculateTotalBalance(n);if(r<t)return{selectedCoins:[],remainingCoins:n};if(r===t)return{selectedCoins:n,remainingCoins:[]};let o=BigInt(0),c=[],u=[...n];for(;o<r;){let l=t-o,p=u.findIndex(d=>d.balance>=l);if(p!==-1){c.push(u[p]),u.splice(p,1);break}let g=u.pop();g.balance>0&&(c.push(g),o+=g.balance)}return{selectedCoins:T.sortByBalance(c),remainingCoins:T.sortByBalance(u)}}static sortByBalance(e){return e.sort((t,s)=>t.balance<s.balance?-1:t.balance>s.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,s)=>t.balance>s.balance?-1:t.balance<s.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,s)=>t+s.balance,BigInt(0))}};var Te=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function ae(i){return i.startsWith("0x")?i:`0x${i}`}function z(i){return i.startsWith("0x")?`${i.slice(2)}`:i}function xe(i,e=4,t=4){let s=Math.max(e,1),n=Math.max(t,1);return`${i.slice(0,s+2)} ... ${i.slice(-n)}`}function at(i,e=4,t=4){return xe(ae(i),e,t)}function ct(i,e={leadingZero:!0}){if(typeof i!="string")return!1;let t=i;if(e.leadingZero){if(!i.startsWith("0x"))return!1;t=t.substring(2)}return Te.test(t)}function je(i){if(!Buffer.isBuffer(i))if(Array.isArray(i))i=Buffer.from(i);else if(typeof i=="string")exports.isHexString(i)?i=Buffer.from(exports.padToEven(exports.stripHexPrefix(i)),"hex"):i=Buffer.from(i);else if(typeof i=="number")i=exports.intToBuffer(i);else if(i==null)i=Buffer.allocUnsafe(0);else if(i.toArray)i=Buffer.from(i.toArray());else throw new Error("invalid type");return i}function ut(i){return ae(je(i).toString("hex"))}function lt(i){let e=new ArrayBuffer(4),t=new DataView(e);for(let n=0;n<i.length;n++)t.setUint8(n,i.charCodeAt(n));return t.getUint32(0,!0)}function Be(i){let e,t,s,n,r;e="";let o=i.length;for(t=0;t<o;)switch(s=i.charCodeAt(t++),s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=i.charAt(t-1);break;case 12:case 13:n=i.charCodeAt(t++),e+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=i.charCodeAt(t++),r=i.charCodeAt(t++),e+=String.fromCharCode((s&15)<<12|(n&63)<<6|(r&63)<<0);break}return e}function dt(i){let e="",t=z(i),s=t.length/2;for(let n=0;n<s;n++)e+=String.fromCharCode(parseInt(t.substr(n*2,2),16));return Be(e)}var Ee=0,le=1,Me=2;function ce(i,e){return i===e?Ee:i<e?le:Me}function Re(i,e){let t=0,s=i.length<=e.length?i.length:e.length,n=ce(i.length,e.length);for(;t<s;){let r=ce(i.charCodeAt(t),e.charCodeAt(t));if(t+=1,r!==0)return r}return n}function ht(i,e){return Re(i,e)===le}function ue(i,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],n=[i,...e].filter(Boolean).join("::");return t&&t.length&&(n+=`<${t.join(", ")}>`),n}function _t(i){return i.split("::")[0]}function M(i){try{let e=i.replace(/\s/g,""),s=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(s){e=e.slice(0,e.indexOf("<"));let u={...M(e),type_arguments:s.map(l=>M(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>T.isSuiCoin(l)?l:M(l).source_address),u.source_address=ue(u.full_address,u.type_arguments),u}let n=e.split("::"),o={full_address:e,address:e===Z||e===oe?"0x2":W(n[0]),module:n[1],name:n[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=ue(o.full_address,o.type_arguments),o}catch{return{full_address:i,address:"",module:"",name:"",type_arguments:[],source_address:i}}}function Q(i){return M(i).source_address}function Pe(i){return i.toLowerCase().startsWith("0x")?W(i):i}var ft=(i,e=!0)=>{let t=i.split("::"),s=t.shift(),n=W(s);return e&&(n=z(n)),`${n}::${t.join("::")}`};function J(i){for(let e in i){let t=typeof i[e];if(t==="object")J(i[e]);else if(t==="string"){let s=i[e];i[e]=Pe(s)}}}var yt=ve(De);import de from"decimal.js";de.config({precision:64,rounding:de.ROUND_DOWN,toExpNeg:-64,toExpPos:64});import L from"decimal.js";function a(i){return L.isDecimal(i)?i:new L(i===void 0?0:i)}function Y(i){return a(10).pow(a(i).abs())}var q=(i,e)=>{try{return a(i).toDP(e,L.ROUND_DOWN).toString()}catch{return i}},X=(i,e)=>L.max(a(i),a(e));import{Transaction as Ie}from"@mysten/sui/transactions";async function jt(i,e=!0){i.blockData.transactions.forEach((t,s)=>{})}var R=class{static async adjustTransactionForGas(e,t,s,n){n.setSender(e.senderAddress);let r=T.selectCoinAssetGreaterThanOrEqual(t,s).selectedCoins;if(r.length===0)throw new Error("Insufficient balance");let o=T.calculateTotalBalance(t);if(o-s>1e9)return{fixAmount:s};let c=await e.fullClient.calculationTxGas(n);if(T.selectCoinAssetGreaterThanOrEqual(t,BigInt(c),r.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(c)+BigInt(500);if(o-s<l){if(s-=l,s<0)throw new Error("gas Insufficient balance");let p=new Ie;return{fixAmount:s,newTx:p}}}return{fixAmount:s}}static buildCoinForAmount(e,t,s,n,r=!0,o=!1){let c=T.getCoinAssets(n,t);if(s===BigInt(0)&&c.length===0)return R.buildZeroValueCoin(t,e,n,r);let u=T.calculateTotalBalance(c);if(u<s)throw new Error(`The amount(${u}) is Insufficient balance for ${n} , expect ${s} `);return R.buildCoin(e,t,c,s,n,r,o)}static buildCoin(e,t,s,n,r,o=!0,c=!1){if(T.isSuiCoin(r)){if(o){let _=e.splitCoins(e.gas,[e.pure.u64(n)]);return{targetCoin:e.makeMoveVec({elements:[_]}),remainCoins:t,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(n===0n&&s.length>1){let _=T.selectCoinObjectIdGreaterThanOrEqual(s,n);return{targetCoin:e.object(_.objectArray[0]),remainCoins:_.remainCoins,tragetCoinAmount:_.amountArray[0],isMintZeroCoin:!1}}let y=T.selectCoinObjectIdGreaterThanOrEqual(s,n);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(n)]),remainCoins:y.remainCoins,tragetCoinAmount:n.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let u=T.selectCoinObjectIdGreaterThanOrEqual(s,n),l=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),p=u.objectArray;if(o)return{targetCoin:e.makeMoveVec({elements:p.map(y=>e.object(y))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[g,...d]=p,m=e.object(g),h=m,b=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),S;return d.length>0&&e.mergeCoins(m,d.map(y=>e.object(y))),c&&Number(l)>Number(n)&&(h=e.splitCoins(m,[e.pure.u64(n)]),b=n.toString(),S=m),{targetCoin:h,remainCoins:u.remainCoins,originalSplitedCoin:S,tragetCoinAmount:b,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,s,n=!0){let r=R.callMintZeroValueCoin(t,s),o;return n?o=t.makeMoveVec({elements:[r]}):o=r,{targetCoin:o,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,s,n,r=!0){let o=T.getCoinAssets(n,t);if(s.amountFirst===BigInt(0))return o.length>0?R.buildCoin(e,[...t],[...o],s.amountFirst,n,r):R.buildZeroValueCoin(t,e,n,r);let c=T.calculateTotalBalance(o);if(c>=s.amountFirst)return R.buildCoin(e,[...t],[...o],s.amountFirst,n,r);if(c<s.amountSecond)throw new Error(`The amount(${c}) is Insufficient balance for ${n} , expect ${s.amountSecond} `);return R.buildCoin(e,[...t],[...o],s.amountSecond,n,r)}static buildCoinTypePair(e,t){let s=[];if(e.length===2){let n=[];n.push(e[0],e[1]),s.push(n)}else{let n=[];n.push(e[0],e[e.length-1]),s.push(n);for(let r=1;r<e.length-1;r+=1){if(t[r-1]===0)continue;let o=[];o.push(e[0],e[r],e[e.length-1]),s.push(o)}}return s}},P=R;re(P,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));function $(i){return i.data}function qe(i){if(i.error&&"object_id"in i.error&&"version"in i.error&&"digest"in i.error){let{error:e}=i;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function Ue(i){if(i.error&&"object_id"in i.error&&!("version"in i.error)&&!("digest"in i.error))return i.error.object_id}function pe(i){if("reference"in i)return i.reference;let e=$(i);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:qe(i)}function ge(i){return"objectId"in i?i.objectId:pe(i)?.objectId??Ue(i)}function Dt(i){return"version"in i?i.version:pe(i)?.version}function Fe(i){return i.data!==void 0}function Ne(i){return i.content!==void 0}function Et(i){let e=$(i);if(e?.content?.dataType==="package")return e.content.disassembled}function ee(i){let e="data"in i?$(i):i;if(!(!e||!Ne(e)||e.content.dataType!=="moveObject"))return e.content}function $e(i){return ee(i)?.type}function Mt(i){let e=Fe(i)?i.data:i;return!e?.type&&"data"in i?e?.content?.dataType==="package"?"package":$e(i):e?.type}function Rt(i){return $(i)?.previousTransaction}function Pt(i){return $(i)?.owner}function It(i){let e=$(i)?.display;return e||{data:null,error:null}}function me(i){let e=ee(i)?.fields;if(e)return"fields"in e?e.fields:e}function qt(i){return ee(i)?.hasPublicTransfer??!1}import{fromB64 as _e,fromHEX as fe}from"@mysten/bcs";import{Ed25519Keypair as be}from"@mysten/sui/keypairs/ed25519";import{Secp256k1Keypair as he}from"@mysten/sui/keypairs/secp256k1";function Lt(i,e){let t=Y(a(e));return Number(a(i).mul(t))}function Gt(i,e=32){return BigInt.asUintN(e,BigInt(i)).toString()}function Kt(i,e=32){return Number(BigInt.asIntN(e,BigInt(i)))}function U(i,e){let t=Y(a(e));return Number(a(i).div(t))}function Ht(i,e="hex"){if(i instanceof Uint8Array){let s=Buffer.from(i);return be.fromSecretKey(s)}let t=e==="hex"?fe(i):_e(i);return be.fromSecretKey(t)}function Qt(i,e="hex"){if(i instanceof Uint8Array){let s=Buffer.from(i);return he.fromSecretKey(s)}let t=e==="hex"?fe(i):_e(i);return he.fromSecretKey(t)}import{SuiClient as Ve}from"@mysten/sui/client";var G=class extends Ve{async queryEventsByPage(e,t="all"){let s=[],n=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.queryEvents({query:e,cursor:o,limit:r?null:t.limit});c.data?(s=[...s,...c.data],n=c.hasNextPage,o=c.nextCursor):n=!1}while(r&&n);return{data:s,nextCursor:o,hasNextPage:n}}async getOwnedObjectsByPage(e,t,s="all"){let n=[],r=!0,o=s==="all",c=o?null:s.cursor;do{let u=await this.getOwnedObjects({owner:e,...t,cursor:c,limit:o?null:s.limit});u.data?(n=[...n,...u.data],r=u.hasNextPage,c=u.nextCursor):r=!1}while(o&&r);return{data:n,nextCursor:c,hasNextPage:r}}async getDynamicFieldsByPage(e,t="all"){let s=[],n=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.getDynamicFields({parentId:e,cursor:o,limit:r?null:t.limit});c.data?(s=[...s,...c.data],n=c.hasNextPage,o=c.nextCursor):n=!1}while(r&&n);return{data:s,nextCursor:o,hasNextPage:n}}async batchGetObjects(e,t,s=50){let n=[];try{for(let r=0;r<Math.ceil(e.length/s);r++){let o=await this.multiGetObjects({ids:e.slice(r*s,s*(r+1)),options:t});n=[...n,...o]}}catch{}return n}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let s=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:n}=s.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{DeepBookClient as Le}from"@mysten/deepbook-v3";import{bcs as f}from"@mysten/sui/bcs";import{Base64 as Ge}from"js-base64";import{Transaction as A,coinWithBalance as Ce}from"@mysten/sui/transactions";import{normalizeStructTag as v,SUI_CLOCK_OBJECT_ID as B,normalizeSuiObjectId as Ke}from"@mysten/sui/utils";function ye(...i){let e="DeepbookV3_Utils_Sdk###"}var te=1e6,D=1e9,He={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},Qe={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},ke=1e3*60*60*24*365*100,K=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?Qe:He}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new A,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:s}){let n=new A;n.setSenderIfNotSet(e);let r=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=Ce({type:t.coinType,balance:BigInt(s)});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[r,o],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),r],typeArguments:[]}),n.moveCall({target:"0x2::transfer::public_share_object",arguments:[r],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),n}depositIntoManager({account:e,balanceManager:t,coin:s,amountToDeposit:n,tx:r}){let o=r||new A;if(t){o.setSenderIfNotSet(e);let c=Ce({type:s.coinType,balance:BigInt(n)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(t),c],typeArguments:[s.coinType]}),o}return null}withdrawFromManager({account:e,balanceManager:t,coin:s,amountToWithdraw:n,returnAssets:r,txb:o}){let c=o||new A,u=c.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[c.object(t),c.pure.u64(n)],typeArguments:[s.coinType]});return r?u:(c.transferObjects([u],e),c)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:s=new A}){for(let n in t)t[n].forEach(o=>{let c=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[s.object(n),s.pure.u64(o.amount)],typeArguments:[o.coinType]});s.transferObjects([c],e)});return s}async getBalanceManager(e,t=!0){let s=`getBalanceManager_${e}`,n=this.getCache(s,t);if(!t&&n!==void 0)return n;try{let r=new A;r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r.pure.address(e)],typeArguments:[]});let u=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}))?.events?.filter(p=>p.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],l=[];return u.forEach(p=>{l.push({balanceManager:p,cetusBalanceManager:""})}),this.updateCache(s,l,I),l||[]}catch(r){throw r instanceof Error?r:new Error(String(r))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t}){let s=new A,n=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[s.object(t)]});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[s.object(e.address),s.object(t),n],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),s}async getManagerBalance({account:e,balanceManager:t,coins:s}){try{let n=new A;s.forEach(c=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(t)],typeArguments:[c.coinType]})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),o={};return r.results?.forEach((c,u)=>{let l=s[u],p=c.returnValues[0][0],g=f.U64.parse(new Uint8Array(p)),d=a(g),m=d.eq(0)?"0":d.div(Math.pow(10,l.decimals)).toString();o[l.coinType]={adjusted_balance:m,balance:d.toString()}}),o}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let s=new A,n=await this.getBalanceManager(e,!0);if(!Array.isArray(n)||n.length===0)return{};n.forEach(c=>{t.forEach(u=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(c.balanceManager)],typeArguments:[u.coinType]})})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}),o={};return n.forEach((c,u)=>{let l={},p=u*t.length;t.forEach((g,d)=>{let m=p+d,h=r.results?.[m];if(h){let b=h.returnValues[0][0],S=f.U64.parse(new Uint8Array(b)),y=a(S),C=y.eq(0)?"0":y.div(Math.pow(10,g.decimals)).toString();l[g.coinType]={adjusted_balance:C,balance:y.toString()}}}),o[c.balanceManager]=l}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getMarketPrice(e){try{let t=new A;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(B)],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],r=Number(f.U64.parse(new Uint8Array(n))),o=Math.pow(10,e.baseCoin.decimals).toString(),c=Math.pow(10,e.quoteCoin.decimals).toString();return a(r).mul(o).div(c).div(D).toString()}catch(t){return ye("getMarketPrice ~ error:",t),"0"}}async getPools(){let e=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),t=/<([^>]+)>/,s=[];return e?.data?.forEach(n=>{let r=n?.parsedJson,o=n.type.match(t);if(o){let u=o[1].split(", ");s.push({...r,baseCoinType:u[0],quoteCoinType:u[1]})}}),s}async getQuoteQuantityOut(e,t,s){let n=new A;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)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(te).toString(),baseQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getBaseQuantityOut(e,t,s){let n=new A;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)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{quoteQuantityDisplay:a(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(te).toString(),quoteQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getQuantityOut(e,t,s,n){let r=new A;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[r.object(e.address),r.pure.u64(t),r.pure.u64(s),r.object(B)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:r}),c=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[0][0]))),u=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[1][0]))),l=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:a(s).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(c).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(u).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(l).div(te).toString(),baseQuantity:t,quoteQuantity:s,baseOut:c,quoteOut:u,deepRequired:l}}async estimatedMaxFee(e,t,s,n,r,o,c){let u=this.deepCoin;try{let{taker_fee:l,maker_fee:p}=e,g=a(l).div(D).toString(),d=a(p).div(D).toString(),m=await this.getMarketPrice(e),h=o?s:m!=="0"?m:c;if(h==="0")throw new Error("Cannot get market price");let b=Math.pow(10,e.baseCoin.decimals).toString(),S=Math.pow(10,e.quoteCoin.decimals).toString(),y=a(h).div(b).mul(S).mul(D).toString();if(n){let w=await this.getMarketPrice(e),k=a(o?s:w!=="0"?w:c).div(b).mul(S).mul(D).toString(),O=await this.getOrderDeepPrice(e);if(!O)throw new Error("Cannot get deep price");let x=X(k,s),V=a(t).mul(a(g)).mul(a(O.deep_per_asset)).div(a(D)),E=a(t).mul(a(d)).mul(a(O.deep_per_asset)).div(a(D));O.asset_is_base||(V=V.mul(x).div(a(D)),E=E.mul(x).div(a(D)));let ne=V.ceil().toString(),se=E.ceil().toString();return{takerFee:ne,makerFee:se,takerFeeDisplay:U(ne,u.decimals).toString(),makerFeeDisplay:U(se,u.decimals).toString(),feeType:u.coinType}}if(r){let w=X(y,s),j=a(t).mul(w).mul(a(g).mul(1.25)).div(a(D)).ceil().toFixed(0),k=a(t).mul(w).mul(a(d).mul(1.25)).div(a(D)).ceil().toFixed(0);return{takerFee:j,makerFee:k,takerFeeDisplay:U(j,e.quoteCoin.decimals).toString(),makerFeeDisplay:U(k,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=a(t).mul(a(g).mul(1.25)).ceil().toFixed(0),_=a(t).mul(a(d).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:_,takerFeeDisplay:U(C,e.baseCoin.decimals).toString(),makerFeeDisplay:U(_,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getOrderDeepPrice(e){try{let t=new A;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[t.object(e.address)],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];return this.parseOrderDeepPrice(new Uint8Array(n))}catch{return null}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),s=t.getUint8(0)!==0,n=Number(t.getBigUint64(1,!0));return{asset_is_base:s,deep_per_asset:n}}getCoinAssets(e,t,s,n){return P.buildCoinForAmount(n,s,BigInt(a(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,s,n,r,o,c){let u=this.deepCoin;if(!c)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let l=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];n&&l.push(u);let p=await this.getManagerBalance({account:r,balanceManager:c,coins:l}),g=p?.[t]?.balance||"0",d=p?.[s]?.balance||"0",m=o&&p?.[u.coinType]?.balance||"0";return{baseManagerBlance:g,quoteManagerBlance:d,feeManaerBalance:m}}catch(l){throw l instanceof Error?l:new Error(String(l))}}getFeeAsset(e,t,s,n,r,o,c,u,l,p){let g=a(e).gt(0)&&l,d="0";if(!g)return{feeAsset:this.getEmptyCoin(p,t),haveDepositFee:"0"};if(o||c){let m=a(r).sub(o?n:s);d=m.lte(0)?e:m.sub(e).lt(0)?m.sub(e).toString():"0"}else d=a(r).sub(e).lt("0")?a(r).sub(e).abs().toString():"0";return{feeAsset:a(d).gt("0")?this.getCoinAssets(t,d,u,p):this.getEmptyCoin(p,t),haveDepositFee:d}}async getTransactionRelatedAssets(e,t,s,n,r,o,c,u,l){try{let p=this.deepCoin,g=v(e.baseCoin.coinType),d=v(e.quoteCoin.coinType),m=g===p.coinType,h=d===p.coinType,b=!m&&!h,{baseManagerBlance:S,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,g,d,b,o,c,u),_,w,j=!1,k=await this._sdk.getOwnerCoinAssets(o);if(r){c||(s=a(s).add(a(n)).toString());let x=a(y).sub(s).toString();a(x).lt(0)?(j=!0,w=this.getCoinAssets(d,x,k,l)):w=this.getEmptyCoin(l,d),_=this.getEmptyCoin(l,g)}else{c||(t=a(t).add(a(n)).toString());let x=a(S).sub(t).toString();a(x).lt(0)?(j=!0,_=this.getCoinAssets(g,x,k,l)):_=this.getEmptyCoin(l,g),w=this.getEmptyCoin(l,d)}let O=this.getFeeAsset(n,p.coinType,t,s,C,h,m,k,c,l);return{baseAsset:_,quoteAsset:w,feeAsset:O,haveDeposit:j}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getMarketTransactionRelatedAssets(e,t,s,n,r,o,c,u,l){try{let p=this.deepCoin,g=v(e.baseCoin.coinType),d=v(e.quoteCoin.coinType),m=g===p.coinType,h=d===p.coinType,b=!m&&!h,{baseManagerBlance:S,quoteManagerBlance:y}=await this.getTransactionRelatedBalance(e,g,d,b,o,c,u),C,_,w=await this._sdk.getOwnerCoinAssets(o);if(r){c||(s=a(s).add(a(n)).toString());let k=a(y).sub(s).toString();if(a(k).lt(0)){let O;a(y).gt(0)&&(O=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:y,returnAssets:!0,txb:l}));let x=this.getCoinAssets(d,k,w,l);O&&l.mergeCoins(x,[O]),_=x}else _=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:s,returnAssets:!0,txb:l});C=this.getEmptyCoin(l,g)}else{c||(t=a(t).add(a(n)).toString());let k=a(S).sub(t).toString();if(a(k).lt(0)){let O;a(S).gt(0)&&(O=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:S,returnAssets:!0,txb:l}));let x=this.getCoinAssets(g,k,w,l);O&&l.mergeCoins(x,[O]),C=x}else C=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:l});_=this.getEmptyCoin(l,d)}let j=this.getEmptyCoin(l,p.coinType);return{baseAsset:C,quoteAsset:_,feeAsset:j}}catch(p){throw p instanceof Error?p:new Error(String(p))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:s,orderType:n,isBid:r,maxFee:o,account:c,payWithDeep:u,expirationTimestamp:l=Date.now()+ke}){try{let p=this.deepCoin,g=e.address,d=e.baseCoin.decimals,m=e.quoteCoin.decimals,h=e.baseCoin.coinType,b=e.quoteCoin.coinType,S=a(t).mul(10**(m-d+9)).toString(),y=v(h),C=v(b),_=new A,w,j,k=await this._sdk.getOwnerCoinAssets(c);if(r){let E=a(t).mul(a(s).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();u||(E=a(E).add(a(o)).toString()),j=P.buildCoinForAmount(_,k,BigInt(E),C,!1,!0)?.targetCoin}else{let E=s;u||(E=a(s).abs().add(a(o)).toString()),w=P.buildCoinForAmount(_,k,BigInt(a(E).abs().toString()),y,!1,!0)?.targetCoin}let O=u?a(o).gt(0)?P.buildCoinForAmount(_,k,BigInt(a(o).abs().ceil().toString()),p.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,p.coinType):this.getEmptyCoin(_,p.coinType),x=_.moveCall({typeArguments:[r?h:b],target:"0x2::coin::zero",arguments:[]}),V=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(g),r?x:w,r?j:x,O,_.pure.u8(n),_.pure.u8(0),_.pure.u64(S),_.pure.u64(s),_.pure.bool(r),_.pure.bool(!1),_.pure.u64(l),_.object(B)];return _.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:V}),_}catch(p){throw p instanceof Error?p:new Error(String(p))}}getEmptyCoin(e,t){return e.moveCall({typeArguments:[t],target:"0x2::coin::zero",arguments:[]})}async createDepositThenPlaceMarketOrder({poolInfo:e,quantity:t,isBid:s,maxFee:n,account:r,payWithDeep:o,slippage:c=.01}){try{let u=e.address,l=e.baseCoin.coinType,p=e.quoteCoin.coinType,g=v(l),d=v(p),m=new A,h,b,S=t,y,C=await this.getOrderBook(e,"all",6);if(s){let k=C?.ask?.[0]?.price||"0",O=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(O).plus(a(O).mul(c)).ceil().toString()}else{let k=await C?.bid?.[0]?.price||"0",O=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(O).minus(a(O).mul(c)).floor().toString()}let _=await this._sdk.getOwnerCoinAssets(r);s?(o||(y=a(y).add(a(n)).toString()),b=this.getCoinAssets(d,y,_,m),h=this.getEmptyCoin(m,g)):(o||(S=a(S).add(a(n)).toString()),b=this.getEmptyCoin(m,d),h=this.getCoinAssets(g,S,_,m));let w=o?a(n).gt(0)?P.buildCoinForAmount(m,_,BigInt(a(n).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(m,this.deepCoin.coinType):this.getEmptyCoin(m,this.deepCoin.coinType),j=[m.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),m.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),m.object(u),h,b,w,m.pure.u8(0),m.pure.u64(t),m.pure.bool(s),m.pure.bool(o),m.pure.u64(y),m.object(B)];return m.moveCall({typeArguments:[g,d],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:j}),m}catch(u){throw u instanceof Error?u:new Error(String(u))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:s,quantity:n,isBid:r,orderType:o,maxFee:c,account:u,payWithDeep:l,expirationTimestamp:p=Date.now()+ke}){try{let g=this.deepCoin,d=a(s).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),m=t.baseCoin.coinType,h=t.quoteCoin.coinType,b=new A,S=r?a(s).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=r?"0":n,{baseAsset:C,quoteAsset:_,feeAsset:w,haveDeposit:j}=await this.getTransactionRelatedAssets(t,y,S,c,r,u,l,e,b);if(j){let x=[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,_,w.feeAsset,b.pure.u8(o),b.pure.u8(0),b.pure.u64(d),b.pure.u64(n),b.pure.bool(r),b.pure.bool(l),b.pure.u64(p),b.object(B)];return b.moveCall({typeArguments:[m,h],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:x}),b}let k=new A;a(w.haveDepositFee).gt(0)&&this.depositIntoManager({account:u,balanceManager:e,coin:g,amountToDeposit:w.haveDepositFee,tx:k});let O=[k.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),k.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),k.object(t.address),k.object(e),k.pure.u8(o),k.pure.u8(0),k.pure.u64(d),k.pure.u64(n),k.pure.bool(r),k.pure.bool(l),k.pure.u64(p),k.object(B)];return k.moveCall({typeArguments:[m,h],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:O}),k}catch(g){throw g instanceof Error?g:new Error(String(g))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:s,newOrderQuantity:n}){let r=new A;return r.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(e),r.object(t.address),r.pure.u128(s),r.pure.u64(n),r.object(B)]}),r}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:s}=e,n=new A,r=await this.getMarketPrice(e),o=a(r).gt(0)?r:Math.pow(10,-1),c=Math.pow(10,6),u=a(o).mul(Math.pow(10,9+s.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+s.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(u),n.pure.u64(l),n.pure.bool(!1),n.object(B)],typeArguments:[t.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),d=[],m=g.results[0].returnValues[0][0],h=f.vector(f.u64()).parse(new Uint8Array(m)),b=g.results[0].returnValues[1][0],S=f.vector(f.u64()).parse(new Uint8Array(b));return h.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),w=a(S[C]).div(Math.pow(10,t.decimals)).toString();d.push({price:_,quantity:w})}),d?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:s}=e,n=new A,r=await this.getMarketPrice(e),o=a(r).gt(0)?a(r).div(3).toNumber():Math.pow(10,-6),c=a(r).gt(0)?r:Math.pow(10,6),u=a(o).mul(Math.pow(10,9+s.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+s.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(q(u,0)),n.pure.u64(q(l,0)),n.pure.bool(!0),n.object(B)],typeArguments:[t.coinType,s.coinType]});let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:n}),d=[],m=g.results[0].returnValues[0][0],h=f.vector(f.u64()).parse(new Uint8Array(m)),b=g.results[0].returnValues[1][0],S=f.vector(f.u64()).parse(new Uint8Array(b));return h.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),w=a(S[C]).div(Math.pow(10,t.decimals)).toString();d.push({price:_,quantity:w})}),d?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:s,quoteCoin:n}=e,r=new A,o=await this.getMarketPrice(e),c,u;t?(c=a(o).gt(0)?a(o).div(3).toNumber():Math.pow(10,-6),u=a(o).gt(0)?o:Math.pow(10,6)):(c=a(o).gt(0)?o:Math.pow(10,-1),u=a(o).gt(0)?a(o).mul(3).toNumber():Math.pow(10,6));let l=a(c).mul(Math.pow(10,9+n.decimals-s.decimals)).toString(),p=a(u).mul(Math.pow(10,9+n.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(q(l,0)),r.pure.u64(q(p,0)),r.pure.bool(t),r.object(B)],typeArguments:[s.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:r}),m=[],h=d.results[0].returnValues[0][0],b=f.vector(f.u64()).parse(new Uint8Array(h)),S=d.results[0].returnValues[1][0],y=f.vector(f.u64()).parse(new Uint8Array(S));return b.forEach((C,_)=>{let w=a(C).div(Math.pow(10,9+n.decimals-s.decimals)).toString(),j=a(y[_]).div(Math.pow(10,s.decimals)).toString();m.push({price:w,quantity:j})}),m?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:s,quoteQuantity:n,isBid:r,maxFee:o,account:c,payWithDeep:u,slippage:l=.01}){try{let p=v(t.baseCoin.coinType),g=v(t.quoteCoin.coinType),d=new A,{baseAsset:m,quoteAsset:h,feeAsset:b}=await this.getMarketTransactionRelatedAssets(t,s,n,o,r,c,u,e,d),S=await this.getOrderBook(t,"all",6);if(r){let _=S?.ask?.[0]?.price||"0",w=a(_).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=a(w).plus(a(w).mul(l)).ceil().toString()}else{let _=await S?.bid?.[0]?.price||"0",w=a(_).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();n=a(w).minus(a(w).mul(l)).floor().toString()}let y=n,C=[d.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),d.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),d.object(t.address),d.object(e),m,h,b,d.pure.u8(0),d.pure.u64(s),d.pure.bool(r),d.pure.bool(u),d.pure.u64(y),d.object(B)];return d.setSenderIfNotSet(c),d.moveCall({typeArguments:[p,g],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:C}),d}catch(p){throw p instanceof Error?p:new Error(String(p))}}async getOrderInfoList(e,t,s){try{let n=new A;t.forEach(p=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[n.object(e.address),n.pure.u128(p)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]})});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:n}),o=f.struct("ID",{bytes:f.Address}),c=f.struct("OrderDeepPrice",{asset_is_base:f.bool(),deep_per_asset:f.u64()}),u=f.struct("Order",{balance_manager_id:o,order_id:f.u128(),client_order_id:f.u64(),quantity:f.u64(),filled_quantity:f.u64(),fee_is_deep:f.bool(),order_deep_price:c,epoch:f.u64(),status:f.u8(),expire_timestamp:f.u64()}),l=[];return r?.results?.forEach(p=>{let g=p.returnValues[0][0],d=u.parse(new Uint8Array(g));l.push(d)}),l}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),s=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),n=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:s,orderId:n}}async getOpenOrder(e,t,s,n){let r;if(n)r=n;else{let u=new A;u.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[u.object(e.address),u.object(s)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let p=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:u})).results[0].returnValues[0][0];r=f.struct("VecSet",{constants:f.vector(f.U128)}).parse(new Uint8Array(p)).constants}let o=await this.getOrderInfoList(e,r,t)||[],c=[];return o.forEach(u=>{let l=this.decodeOrderId(BigInt(u.order_id));c.push({...u,price:l.price,isBid:l.isBid})}),c}cancelOrders(e,t){let s=new A;return e.forEach(n=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),s.object(t),s.object(n.poolInfo.address),s.pure.u128(n.orderId),s.object(B)],typeArguments:[n.poolInfo.baseCoin.coinType,n.poolInfo.quoteCoin.coinType]})}),s}async getDeepbookOrderBook(e,t,s,n,r,o){let c=this._sdk.fullClient,l=await new Le({client:c,address:r,env:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,t,s,n)}processOrderBookData(e,t,s,n){let r=e.returnValues[0][0],o=f.vector(f.u64()).parse(new Uint8Array(r)),c=e.returnValues[1][0],u=f.vector(f.u64()).parse(new Uint8Array(c)),l={};return o.forEach((g,d)=>{let m=a(g).div(Math.pow(10,9+s.decimals-t.decimals)).toString(),h=a(u[d]).div(Math.pow(10,t.decimals)).toString();l[m]?l[m]={price:m,quantity:a(l[m].quantity).add(h).toString()}:l[m]={price:m,quantity:h}}),Object.values(l)}getLevel2RangeTx(e,t,s,n,r=new A){let{baseCoin:o,quoteCoin:c}=e,u=q(a(s).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0),l=q(a(n).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0);return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(u),r.pure.u64(l),r.pure.bool(t),r.object(B)],typeArguments:[o.coinType,c.coinType]}),r}async fetchOrderBook(e,t,s,n,r,o){let c=new A,{baseCoin:u,quoteCoin:l}=e;try{if(t==="bid"||t==="all"){let h=n,b=s==="0"?r:s;c=this.getLevel2RangeTx(e,!0,h,b,c)}if(t==="ask"||t==="all"){let h=s==="0"?n:s,b=r;c=this.getLevel2RangeTx(e,!1,h,b,c)}let p=this._sdk.sdkOptions.simulationAccount.address,g=await this._sdk.fullClient.devInspectTransactionBlock({sender:p,transactionBlock:c}),d=[];(t==="bid"||t==="all")&&(d=g.results?.[0]?this.processOrderBookData(g.results[0],u,l,o):[]);let m=[];if(t==="ask"||t==="all"){let h=t==="ask"?0:1;m=g.results?.[h]?this.processOrderBookData(g.results[h],u,l,o):[]}return{bid:d.sort((h,b)=>b.price-h.price),ask:m.sort((h,b)=>h.price-b.price)}}catch{let g=this._sdk.sdkOptions.simulationAccount.address,d=[],m=[];try{let h=this.getLevel2RangeTx(e,!0,n,s),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:h});d=b.results?.[0]?this.processOrderBookData(b.results[0],u,l,o):[]}catch{d=[]}try{let h=this.getLevel2RangeTx(e,!1,n,s),b=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:h});m=b.results?.[0]?this.processOrderBookData(b.results[0],u,l,o):[]}catch{m=[]}return{bid:d,ask:m}}}async getOrderBook(e,t,s){let n={bid:[],ask:[]};try{let r=await this.getMarketPrice(e),o=t,c=Math.pow(10,-s),u=Math.pow(10,s),l=await this.fetchOrderBook(e,o,r,c,u,s);return{bid:l?.bid,ask:l?.ask}}catch{return n}}async getOrderBookOrigin(e,t){try{let s=new A,n=await this.getMarketPrice(e),{baseCoin:r,quoteCoin:o}=e;if(t==="bid"||t==="all"){let g=Math.pow(10,-6),d=n,m=a(g).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),h=a(d).mul(Math.pow(10,9+o.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(m),s.pure.u64(h),s.pure.bool(!0),s.object(B)],typeArguments:[r.coinType,o.coinType]})}if(t==="ask"||t==="all"){let g=n,d=Math.pow(10,6),m=a(g).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),h=a(d).mul(Math.pow(10,9+o.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(m),s.pure.u64(h),s.pure.bool(!1),s.object(B)],typeArguments:[r.coinType,o.coinType]})}let c=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:c,transactionBlock:s}),l=[];if(t==="bid"||t==="all"){let g=u.results[0]?.returnValues[0]?.[0],d=f.vector(f.u64()).parse(new Uint8Array(g)),m=u.results[0]?.returnValues[1]?.[0],h=f.vector(f.u64()).parse(new Uint8Array(m));d.forEach((b,S)=>{let y=a(b).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),C=a(h[S]).div(Math.pow(10,r.decimals)).toString();l.push({price:y,quantity:C})})}let p=[];if(t==="ask"||t==="all"){let g=t==="ask"?0:1,d=u.results[g]?.returnValues[0]?.[0],m=f.vector(f.u64()).parse(new Uint8Array(d)),h=u.results[g]?.returnValues[1]?.[0],b=f.vector(f.u64()).parse(new Uint8Array(h));m.forEach((S,y)=>{let C=a(S).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),_=a(b[y]).div(Math.pow(10,r.decimals)).toString();p.push({price:C,quantity:_})})}return{bid:l,ask:p}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((n,r)=>[v(n.coinType),n]))}async getAccount(e,t){let s=new A;for(let c=0;c<t.length;c++){let u=t[c];s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[s.object(u.address),s.object(e)],typeArguments:[u.baseCoin.coinType,u.quoteCoin.coinType]})}let n=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:s}),r;if(n?.events.length===0)return null;let o=[];return n?.events?.forEach((c,u)=>{r=c?.parsedJson;let l=r.account.open_orders.contents,p=r.account.owed_balances,g=r.account.settled_balances,d=r.account.unclaimed_rebates,m=r.account.taker_volume;o.push({balance_manager_id:e,open_orders:l,owed_balances:p,settled_balances:g,unclaimed_rebates:d,taker_volume:m,poolInfo:t[u]})}),o}async getSuiTransactionResponse(e,t=!1){let s=`${e}_getSuiTransactionResponse`,n=this.getCache(s,t);if(n!==void 0)return n;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(s,r,I),r}transformExtensions(e,t,s=!0){let n=[];for(let r of t){let{key:o}=r.fields,{value:c}=r.fields;if(o==="labels")try{c=JSON.parse(decodeURIComponent(Ge.decode(c)))}catch{}s&&(e[o]=c),n.push({key:o,value:c})}delete e.extension_fields,s||(e.extensions=n)}async getCoinConfigs(e=!1,t=!0){let s=this.sdk.sdkOptions.coinlist.handle,n=`${s}_getCoinConfigs`,r=this.getCache(n,e);if(r)return r;let c=(await this._sdk.fullClient.getDynamicFieldsByPage(s)).data.map(p=>p.objectId),u=await this._sdk.fullClient.batchGetObjects(c,{showContent:!0}),l=[];return u.forEach(p=>{let g=this.buildCoinConfig(p,t);this.updateCache(`${s}_${g.address}_getCoinConfig`,g,I),l.push({...g})}),this.updateCache(n,l,I),l}buildCoinConfig(e,t=!0){let s=me(e);s=s.value.fields;let n={...s};return n.id=ge(e),n.address=M(s.coin_type.fields.name).full_address,s.pyth_id&&(n.pyth_id=Ke(s.pyth_id)),this.transformExtensions(n,s.extension_fields.fields.contents,t),delete n.coin_type,n}updateCache(e,t,s=ie){let n=this._cache[e];n?(n.overdueTime=N(s),n.value=t):n=new F(t,N(s)),this._cache[e]=n}getCache(e,t=!1){let s=this._cache[e],n=s?.isValid();if(!t&&n)return s.value;n||delete this._cache[e]}};var H=class{_cache={};_rpcModule;_deepbookUtils;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new G({url:e.fullRpcUrl}),this._deepbookUtils=new K(this),J(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,s=!0){let n=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,c=this.getCache(o,s);if(c)return c;for(;;){let u=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:r}):this.fullClient.getAllCoins({owner:e,cursor:r}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&n.push({coinAddress:M(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),r=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,n,30*1e3),n}async getOwnerCoinBalances(e,t){let s=[];return t?s=[await this.fullClient.getBalance({owner:e,coinType:t})]:s=[...await this.fullClient.getAllBalances({owner:e})],s}updateCache(e,t,s=I){let n=this._cache[e];n?(n.overdueTime=N(s),n.value=t):n=new F(t,N(s)),this._cache[e]=n}getCache(e,t=!1){let s=this._cache[e],n=s?.isValid();if(!t&&n)return s.value;n||delete this._cache[e]}};var qn="0x0000000000000000000000000000000000000000000000000000000000000006",Un="pool_script",Fn="pool_script_v2",Nn="router",$n="router_with_partner",Vn="fetcher_script",Ln="expect_swap",Gn="utils",Kn="0x1::coin::CoinInfo",Hn="0x1::coin::CoinStore",Qn="custodian_v2",Zn="clob_v2",zn="endpoints_v2",Wn=i=>{if(typeof i=="string"&&i.startsWith("0x"))return"object";if(typeof i=="number"||typeof i=="bigint")return"u64";if(typeof i=="boolean")return"bool";throw new Error(`Unknown type for value: ${i}`)};var Ze=(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))(Ze||{});var cs=H;export{qn as CLOCK_ADDRESS,F as CachedContent,H as CetusClmmSDK,Ln as ClmmExpectSwapModule,Vn as ClmmFetcherModule,Un as ClmmIntegratePoolModule,Fn as ClmmIntegratePoolV2Module,Nn as ClmmIntegrateRouterModule,$n as ClmmIntegrateRouterWithPartnerModule,Gn as ClmmIntegrateUtilsModule,T as CoinAssist,Kn as CoinInfoAddress,Hn as CoinStoreAddress,te as DEEP_SCALAR,Xe as DEFAULT_GAS_BUDGET_FOR_MERGE,Ye as DEFAULT_GAS_BUDGET_FOR_SPLIT,nt as DEFAULT_GAS_BUDGET_FOR_STAKE,et as DEFAULT_GAS_BUDGET_FOR_TRANSFER,tt as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,rt as DEFAULT_NFT_TRANSFER_GAS_FEE,Zn as DeepbookClobV2Moudle,Qn as DeepbookCustodianV2Moudle,zn as DeepbookEndpointsV2Moudle,K as DeepbookUtilsModule,D as FLOAT_SCALAR,st as GAS_SYMBOL,Z as GAS_TYPE_ARG,oe as GAS_TYPE_ARG_LONG,yt as NORMALIZED_SUI_COIN_TYPE,Ze as OrderType,G as RpcModule,it as SUI_SYSTEM_STATE_OBJECT_ID,P as TransactionUtil,ae as addHexPrefix,Kt as asIntN,Gt as asUintN,ut as bufferToHex,I as cacheTime24h,ie as cacheTime5min,ct as checkAddress,ue as composeType,a as d,Y as decimalsMultiplier,cs as default,_t as extractAddressFromType,M as extractStructTagFromType,ft as fixCoinType,q as fixDown,Pe as fixSuiObjectId,U as fromDecimalsAmount,Wn as getDefaultSuiInputType,N as getFutureTime,ee as getMoveObject,$e as getMoveObjectType,Et as getMovePackageContent,qe as getObjectDeletedResponse,It as getObjectDisplay,me as getObjectFields,ge as getObjectId,Ue as getObjectNotExistsResponse,Pt as getObjectOwner,Rt as getObjectPreviousTransactionDigest,pe as getObjectReference,Mt as getObjectType,Dt as getObjectVersion,$ as getSuiObjectData,qt as hasPublicTransfer,lt as hexToNumber,dt as hexToString,ht as isSortedSymbols,Fe as isSuiObjectResponse,X as maxDecimal,Q as normalizeCoinType,J as patchFixSuiObjectId,jt as printTransaction,z as removeHexPrefix,Ht as secretKeyToEd25519Keypair,Qt as secretKeyToSecp256k1Keypair,at as shortAddress,xe as shortString,je as toBuffer,Lt as toDecimalsAmount,Be as utf8to16};
|
|
1
|
+
var Ae=Object.defineProperty;var Oe=(i,e,t)=>e in i?Ae(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var re=(i,e,t)=>(Oe(i,typeof e!="symbol"?e+"":e,t),t);var ie=60*1e3,oe=5*60*1e3,U=24*60*60*1e3;function V(i){return Date.parse(new Date().toString())+i}var $=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{normalizeSuiObjectId as J,normalizeStructTag as Me,SUI_TYPE_ARG as Pe}from"@mysten/sui/utils";import{coinWithBalance as ae}from"@mysten/sui/transactions";var xe="0x2::coin::Coin",je=/^0x2::coin::Coin<(.+)>$/,rt=1e3,it=500,ot=100,at=100,ct=1e3,z="0x2::sui::SUI",ce="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",ut="SUI",lt=450,dt="0x0000000000000000000000000000000000000005",A=class{static getCoinTypeArg(e){let t=e.type.match(je);return t?t[1]:null}static isSUI(e){let t=A.getCoinTypeArg(e);return t?A.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 n=BigInt(0);return e.forEach(s=>{t===s.coinAddress&&(n+=BigInt(s.balance))}),n}static getID(e){return e.fields.id.id}static getCoinTypeFromArg(e){return`${xe}<${e}>`}static getCoinAssets(e,t){let n=[];return t.forEach(s=>{Z(s.coinAddress)===Z(e)&&n.push(s)}),n}static isSuiCoin(e){return R(e).full_address===z}static selectCoinObjectIdGreaterThanOrEqual(e,t,n=[]){let s=A.selectCoinAssetGreaterThanOrEqual(e,t,n),r=s.selectedCoins.map(u=>u.coinObjectId),o=s.remainingCoins,c=s.selectedCoins.map(u=>u.balance.toString());return{objectArray:r,remainCoins:o,amountArray:c}}static selectCoinAssetGreaterThanOrEqual(e,t,n=[]){let s=A.sortByBalance(e.filter(l=>!n.includes(l.coinObjectId))),r=A.calculateTotalBalance(s);if(r<t)return{selectedCoins:[],remainingCoins:s};if(r===t)return{selectedCoins:s,remainingCoins:[]};let o=BigInt(0),c=[],u=[...s];for(;o<r;){let l=t-o,g=u.findIndex(m=>m.balance>=l);if(g!==-1){c.push(u[g]),u.splice(g,1);break}let d=u.pop();d.balance>0&&(c.push(d),o+=d.balance)}return{selectedCoins:A.sortByBalance(c),remainingCoins:A.sortByBalance(u)}}static sortByBalance(e){return e.sort((t,n)=>t.balance<n.balance?-1:t.balance>n.balance?1:0)}static sortByBalanceDes(e){return e.sort((t,n)=>t.balance>n.balance?-1:t.balance<n.balance?0:1)}static calculateTotalBalance(e){return e.reduce((t,n)=>t+n.balance,BigInt(0))}static buildCoinWithBalance(e,t,n){return e===BigInt(0)&&A.isSuiCoin(t)?n.add(ae({balance:e,useGasCoin:!1})):n.add(ae({balance:e,type:t}))}};var Be=/^[-+]?[0-9A-Fa-f]+\.?[0-9A-Fa-f]*?$/;function ue(i){return i.startsWith("0x")?i:`0x${i}`}function W(i){return i.startsWith("0x")?`${i.slice(2)}`:i}function ve(i,e=4,t=4){let n=Math.max(e,1),s=Math.max(t,1);return`${i.slice(0,n+2)} ... ${i.slice(-s)}`}function gt(i,e=4,t=4){return ve(ue(i),e,t)}function mt(i,e={leadingZero:!0}){if(typeof i!="string")return!1;let t=i;if(e.leadingZero){if(!i.startsWith("0x"))return!1;t=t.substring(2)}return Be.test(t)}function De(i){if(!Buffer.isBuffer(i))if(Array.isArray(i))i=Buffer.from(i);else if(typeof i=="string")exports.isHexString(i)?i=Buffer.from(exports.padToEven(exports.stripHexPrefix(i)),"hex"):i=Buffer.from(i);else if(typeof i=="number")i=exports.intToBuffer(i);else if(i==null)i=Buffer.allocUnsafe(0);else if(i.toArray)i=Buffer.from(i.toArray());else throw new Error("invalid type");return i}function bt(i){return ue(De(i).toString("hex"))}function ht(i){let e=new ArrayBuffer(4),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint8(s,i.charCodeAt(s));return t.getUint32(0,!0)}function Ee(i){let e,t,n,s,r;e="";let o=i.length;for(t=0;t<o;)switch(n=i.charCodeAt(t++),n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:e+=i.charAt(t-1);break;case 12:case 13:s=i.charCodeAt(t++),e+=String.fromCharCode((n&31)<<6|s&63);break;case 14:s=i.charCodeAt(t++),r=i.charCodeAt(t++),e+=String.fromCharCode((n&15)<<12|(s&63)<<6|(r&63)<<0);break}return e}function ft(i){let e="",t=W(i),n=t.length/2;for(let s=0;s<n;s++)e+=String.fromCharCode(parseInt(t.substr(s*2,2),16));return Ee(e)}var Re=0,pe=1,qe=2;function le(i,e){return i===e?Re:i<e?pe:qe}function Ie(i,e){let t=0,n=i.length<=e.length?i.length:e.length,s=le(i.length,e.length);for(;t<n;){let r=le(i.charCodeAt(t),e.charCodeAt(t));if(t+=1,r!==0)return r}return s}function St(i,e){return Ie(i,e)===pe}function de(i,...e){let t=Array.isArray(e[e.length-1])?e.pop():[],s=[i,...e].filter(Boolean).join("::");return t&&t.length&&(s+=`<${t.join(", ")}>`),s}function wt(i){return i.split("::")[0]}function R(i){try{let e=i.replace(/\s/g,""),n=e.match(/(<.+>)$/)?.[0]?.match(/(\w+::\w+::\w+)(?:<.*?>(?!>))?/g);if(n){e=e.slice(0,e.indexOf("<"));let u={...R(e),type_arguments:n.map(l=>R(l).source_address)};return u.type_arguments=u.type_arguments.map(l=>A.isSuiCoin(l)?l:R(l).source_address),u.source_address=de(u.full_address,u.type_arguments),u}let s=e.split("::"),o={full_address:e,address:e===z||e===ce?"0x2":J(s[0]),module:s[1],name:s[2],type_arguments:[],source_address:""};return o.full_address=`${o.address}::${o.module}::${o.name}`,o.source_address=de(o.full_address,o.type_arguments),o}catch{return{full_address:i,address:"",module:"",name:"",type_arguments:[],source_address:i}}}function Z(i){return R(i).source_address}function Ue(i){return i.toLowerCase().startsWith("0x")?J(i):i}var Tt=(i,e=!0)=>{let t=i.split("::"),n=t.shift(),s=J(n);return e&&(s=W(s)),`${s}::${t.join("::")}`};function Y(i){for(let e in i){let t=typeof i[e];if(t==="object")Y(i[e]);else if(t==="string"){let n=i[e];i[e]=Ue(n)}}}var At=Me(Pe);import ge from"decimal.js";ge.config({precision:64,rounding:ge.ROUND_DOWN,toExpNeg:-64,toExpPos:64});import G from"decimal.js";function a(i){return G.isDecimal(i)?i:new G(i===void 0?0:i)}function X(i){return a(10).pow(a(i).abs())}var F=(i,e)=>{try{return a(i).toDP(e,G.ROUND_DOWN).toString()}catch{return i}},ee=(i,e)=>G.max(a(i),a(e));import{Transaction as Fe}from"@mysten/sui/transactions";async function Pt(i,e=!0){i.blockData.transactions.forEach((t,n)=>{})}var q=class{static async adjustTransactionForGas(e,t,n,s){s.setSender(e.senderAddress);let r=A.selectCoinAssetGreaterThanOrEqual(t,n).selectedCoins;if(r.length===0)throw new Error("Insufficient balance");let o=A.calculateTotalBalance(t);if(o-n>1e9)return{fixAmount:n};let c=await e.fullClient.calculationTxGas(s);if(A.selectCoinAssetGreaterThanOrEqual(t,BigInt(c),r.map(l=>l.coinObjectId)).selectedCoins.length===0){let l=BigInt(c)+BigInt(500);if(o-n<l){if(n-=l,n<0)throw new Error("gas Insufficient balance");let g=new Fe;return{fixAmount:n,newTx:g}}}return{fixAmount:n}}static buildCoinForAmount(e,t,n,s,r=!0,o=!1){let c=A.getCoinAssets(s,t);if(n===BigInt(0)&&c.length===0)return q.buildZeroValueCoin(t,e,s,r);let u=A.calculateTotalBalance(c);if(u<n)throw new Error(`The amount(${u}) is Insufficient balance for ${s} , expect ${n} `);return q.buildCoin(e,t,c,n,s,r,o)}static buildCoin(e,t,n,s,r,o=!0,c=!1){if(A.isSuiCoin(r)){if(o){let _=e.splitCoins(e.gas,[e.pure.u64(s)]);return{targetCoin:e.makeMoveVec({elements:[_]}),remainCoins:t,tragetCoinAmount:s.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}if(s===0n&&n.length>1){let _=A.selectCoinObjectIdGreaterThanOrEqual(n,s);return{targetCoin:e.object(_.objectArray[0]),remainCoins:_.remainCoins,tragetCoinAmount:_.amountArray[0],isMintZeroCoin:!1}}let y=A.selectCoinObjectIdGreaterThanOrEqual(n,s);return{targetCoin:e.splitCoins(e.gas,[e.pure.u64(s)]),remainCoins:y.remainCoins,tragetCoinAmount:s.toString(),isMintZeroCoin:!1,originalSplitedCoin:e.gas}}let u=A.selectCoinObjectIdGreaterThanOrEqual(n,s),l=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),g=u.objectArray;if(o)return{targetCoin:e.makeMoveVec({elements:g.map(y=>e.object(y))}),remainCoins:u.remainCoins,tragetCoinAmount:u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),isMintZeroCoin:!1};let[d,...m]=g,p=e.object(d),b=p,h=u.amountArray.reduce((y,C)=>Number(y)+Number(C),0).toString(),T;return m.length>0&&e.mergeCoins(p,m.map(y=>e.object(y))),c&&Number(l)>Number(s)&&(b=e.splitCoins(p,[e.pure.u64(s)]),h=s.toString(),T=p),{targetCoin:b,remainCoins:u.remainCoins,originalSplitedCoin:T,tragetCoinAmount:h,isMintZeroCoin:!1}}static buildZeroValueCoin(e,t,n,s=!0){let r=q.callMintZeroValueCoin(t,n),o;return s?o=t.makeMoveVec({elements:[r]}):o=r,{targetCoin:o,remainCoins:e,isMintZeroCoin:!0,tragetCoinAmount:"0"}}static buildCoinForAmountInterval(e,t,n,s,r=!0){let o=A.getCoinAssets(s,t);if(n.amountFirst===BigInt(0))return o.length>0?q.buildCoin(e,[...t],[...o],n.amountFirst,s,r):q.buildZeroValueCoin(t,e,s,r);let c=A.calculateTotalBalance(o);if(c>=n.amountFirst)return q.buildCoin(e,[...t],[...o],n.amountFirst,s,r);if(c<n.amountSecond)throw new Error(`The amount(${c}) is Insufficient balance for ${s} , expect ${n.amountSecond} `);return q.buildCoin(e,[...t],[...o],n.amountSecond,s,r)}static buildCoinTypePair(e,t){let n=[];if(e.length===2){let s=[];s.push(e[0],e[1]),n.push(s)}else{let s=[];s.push(e[0],e[e.length-1]),n.push(s);for(let r=1;r<e.length-1;r+=1){if(t[r-1]===0)continue;let o=[];o.push(e[0],e[r],e[e.length-1]),n.push(o)}}return n}},I=q;re(I,"callMintZeroValueCoin",(e,t)=>e.moveCall({target:"0x2::coin::zero",typeArguments:[t]}));function L(i){return i.data}function Ne(i){if(i.error&&"object_id"in i.error&&"version"in i.error&&"digest"in i.error){let{error:e}=i;return{objectId:e.object_id,version:e.version,digest:e.digest}}}function $e(i){if(i.error&&"object_id"in i.error&&!("version"in i.error)&&!("digest"in i.error))return i.error.object_id}function me(i){if("reference"in i)return i.reference;let e=L(i);return e?{objectId:e.objectId,version:e.version,digest:e.digest}:Ne(i)}function be(i){return"objectId"in i?i.objectId:me(i)?.objectId??$e(i)}function It(i){return"version"in i?i.version:me(i)?.version}function Ve(i){return i.data!==void 0}function Le(i){return i.content!==void 0}function Ut(i){let e=L(i);if(e?.content?.dataType==="package")return e.content.disassembled}function te(i){let e="data"in i?L(i):i;if(!(!e||!Le(e)||e.content.dataType!=="moveObject"))return e.content}function Ge(i){return te(i)?.type}function Ft(i){let e=Ve(i)?i.data:i;return!e?.type&&"data"in i?e?.content?.dataType==="package"?"package":Ge(i):e?.type}function Nt(i){return L(i)?.previousTransaction}function $t(i){return L(i)?.owner}function Vt(i){let e=L(i)?.display;return e||{data:null,error:null}}function he(i){let e=te(i)?.fields;if(e)return"fields"in e?e.fields:e}function Lt(i){return te(i)?.hasPublicTransfer??!1}import{fromB64 as ye,fromHEX as Ce}from"@mysten/bcs";import{Ed25519Keypair as fe}from"@mysten/sui/keypairs/ed25519";import{Secp256k1Keypair as _e}from"@mysten/sui/keypairs/secp256k1";function zt(i,e){let t=X(a(e));return Number(a(i).mul(t))}function Wt(i,e=32){return BigInt.asUintN(e,BigInt(i)).toString()}function Jt(i,e=32){return Number(BigInt.asIntN(e,BigInt(i)))}function N(i,e){let t=X(a(e));return Number(a(i).div(t))}function Yt(i,e="hex"){if(i instanceof Uint8Array){let n=Buffer.from(i);return fe.fromSecretKey(n)}let t=e==="hex"?Ce(i):ye(i);return fe.fromSecretKey(t)}function Xt(i,e="hex"){if(i instanceof Uint8Array){let n=Buffer.from(i);return _e.fromSecretKey(n)}let t=e==="hex"?Ce(i):ye(i);return _e.fromSecretKey(t)}var ke=async i=>new Promise(e=>{setTimeout(()=>{e(1)},i)});import{SuiClient as Ke}from"@mysten/sui/client";var K=class extends Ke{async queryEventsByPage(e,t="all"){let n=[],s=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.queryEvents({query:e,cursor:o,limit:r?null:t.limit});c.data?(n=[...n,...c.data],s=c.hasNextPage,o=c.nextCursor):s=!1}while(r&&s);return{data:n,nextCursor:o,hasNextPage:s}}async getOwnedObjectsByPage(e,t,n="all"){let s=[],r=!0,o=n==="all",c=o?null:n.cursor;do{let u=await this.getOwnedObjects({owner:e,...t,cursor:c,limit:o?null:n.limit});u.data?(s=[...s,...u.data],r=u.hasNextPage,c=u.nextCursor):r=!1}while(o&&r);return{data:s,nextCursor:c,hasNextPage:r}}async getDynamicFieldsByPage(e,t="all"){let n=[],s=!0,r=t==="all",o=r?null:t.cursor;do{let c=await this.getDynamicFields({parentId:e,cursor:o,limit:r?null:t.limit});c.data?(n=[...n,...c.data],s=c.hasNextPage,o=c.nextCursor):s=!1}while(r&&s);return{data:n,nextCursor:o,hasNextPage:s}}async batchGetObjects(e,t,n=50){let s=[];try{for(let r=0;r<Math.ceil(e.length/n);r++){let o=await this.multiGetObjects({ids:e.slice(r*n,n*(r+1)),options:t});s=[...s,...o]}}catch{}return s}async calculationTxGas(e){let{sender:t}=e.blockData;if(t===void 0)throw Error("sdk sender is empty");let n=await this.devInspectTransactionBlock({transactionBlock:e,sender:t}),{gasUsed:s}=n.effects;return Number(s.computationCost)+Number(s.storageCost)-Number(s.storageRebate)}async sendTransaction(e,t){try{return await this.signAndExecuteTransaction({transaction:t,signer:e,options:{showEffects:!0,showEvents:!0}})}catch{}}};import{DeepBookClient as He}from"@mysten/deepbook-v3";import{bcs as f}from"@mysten/sui/bcs";import{Base64 as Qe}from"js-base64";import{Transaction as w,coinWithBalance as we}from"@mysten/sui/transactions";import{normalizeStructTag as E,SUI_CLOCK_OBJECT_ID as v,normalizeSuiObjectId as Ze}from"@mysten/sui/utils";function Se(...i){let e="DeepbookV3_Utils_Sdk###"}var ne=1e6,M=1e9,ze={coinType:"0x36dbef866a1d62bf7328989a10fb2f07d769f4ee587c0de4a0a256e57e0a58a8::deep::DEEP",decimals:6},We={coinType:"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",decimals:6},Te=1e3*60*60*24*365*100,H=class{_sdk;_deep;_cache={};constructor(e){this._sdk=e,this._deep=e.sdkOptions.network==="mainnet"?We:ze}get sdk(){return this._sdk}get deepCoin(){return this._deep}createAndShareBalanceManager(){let e=new w,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:n}){let s=new w;s.setSenderIfNotSet(e);let r=s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::new`}),o=we({type:t.coinType,balance:BigInt(n)});return s.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[r,o],typeArguments:[t.coinType]}),s.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::cetus_balance_manager::check_and_add_deepbook_balance_manager_indexer`,arguments:[s.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r],typeArguments:[]}),s.moveCall({target:"0x2::transfer::public_share_object",arguments:[r],typeArguments:[`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::BalanceManager`]}),s}depositIntoManager({account:e,balanceManager:t,coin:n,amountToDeposit:s,tx:r}){let o=r||new w;if(t){o.setSenderIfNotSet(e);let c=we({type:n.coinType,balance:BigInt(s)});return o.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::deposit`,arguments:[o.object(t),c],typeArguments:[n.coinType]}),o}return null}withdrawFromManager({account:e,balanceManager:t,coin:n,amountToWithdraw:s,returnAssets:r,txb:o}){let c=o||new w,u=c.moveCall({target:`${this._sdk.sdkOptions.deepbook.published_at}::balance_manager::withdraw`,arguments:[c.object(t),c.pure.u64(s)],typeArguments:[n.coinType]});return r?u:(c.transferObjects([u],e),c)}withdrawManagersFreeBalance({account:e,balanceManagers:t,tx:n=new w}){for(let s in t)t[s].forEach(o=>{let c=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::withdraw`,arguments:[n.object(s),n.pure.u64(o.amount)],typeArguments:[o.coinType]});n.transferObjects([c],e)});return n}async getBalanceManager(e,t=!0){let n=`getBalanceManager_${e}`,s=this.getCache(n,t);if(!t&&s!==void 0)return s;try{let r=new w;r.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::get_balance_managers_by_owner`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),r.pure.address(e)],typeArguments:[]});let u=(await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:r}))?.events?.filter(g=>g.type===`${this._sdk.sdkOptions.deepbook_utils.package_id}::cetus_balance_manager::GetCetusBalanceManagerList`)?.[0]?.parsedJson?.deepbook_balance_managers||[],l=[];return u.forEach(g=>{l.push({balanceManager:g,cetusBalanceManager:""})}),this.updateCache(n,l,U),l||[]}catch(r){throw r instanceof Error?r:new Error(String(r))}}withdrawSettledAmounts({poolInfo:e,balanceManager:t},n=new w){let s=n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::generate_proof_as_owner`,arguments:[n.object(t)]});return n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::withdraw_settled_amounts`,arguments:[n.object(e.address),n.object(t),s],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]}),n}async getManagerBalance({account:e,balanceManager:t,coins:n}){try{let s=new w;n.forEach(c=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[s.object(t)],typeArguments:[c.coinType]})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s}),o={};return r.results?.forEach((c,u)=>{let l=n[u],g=c.returnValues[0][0],d=f.U64.parse(new Uint8Array(g)),m=a(d),p=m.eq(0)?"0":m.div(Math.pow(10,l.decimals)).toString();o[l.coinType]={adjusted_balance:p,balance:m.toString()}}),o}catch(s){throw s instanceof Error?s:new Error(String(s))}}async getAccountAllManagerBalance({account:e,coins:t}){try{let n=new w,s=await this.getBalanceManager(e,!0);if(!Array.isArray(s)||s.length===0)return{};s.forEach(c=>{t.forEach(u=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::balance_manager::balance`,arguments:[n.object(c.balanceManager)],typeArguments:[u.coinType]})})});let r=await this.sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:n}),o={};return s.forEach((c,u)=>{let l={},g=u*t.length;t.forEach((d,m)=>{let p=g+m,b=r.results?.[p];if(b){let h=b.returnValues[0][0],T=f.U64.parse(new Uint8Array(h)),y=a(T),C=y.eq(0)?"0":y.div(Math.pow(10,d.decimals)).toString();l[d.coinType]={adjusted_balance:C,balance:y.toString()}}}),o[c.balanceManager]=l}),o}catch(n){throw n instanceof Error?n:new Error(String(n))}}async getMarketPrice(e){try{let t=new w;t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::mid_price`,arguments:[t.object(e.address),t.object(v)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let s=(await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:t})).results[0]?.returnValues[0]?.[0],r=Number(f.U64.parse(new Uint8Array(s))),o=Math.pow(10,e.baseCoin.decimals).toString(),c=Math.pow(10,e.quoteCoin.decimals).toString();return a(r).mul(o).div(c).div(M).toString()}catch(t){return Se("getMarketPrice ~ error:",t),"0"}}async getPools(e=!1){let t="Deepbook_getPools",n=this.getCache(t,e);if(n!==void 0)return n;let s=await this._sdk.fullClient?.queryEventsByPage({MoveEventModule:{module:"pool",package:this._sdk.sdkOptions.deepbook.package_id}}),r=/<([^>]+)>/,o=[];return s?.data?.forEach(c=>{let u=c?.parsedJson,l=c.type.match(r);if(l){let d=l[1].split(", ");o.push({...u,baseCoinType:d[0],quoteCoinType:d[1]})}}),this.updateCache(t,o,U),o}async getQuoteQuantityOut(e,t,n){let s=new w;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quote_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.object(v)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(ne).toString(),baseQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getBaseQuantityOut(e,t,n){let s=new w;s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_base_quantity_out`,arguments:[s.object(e.address),s.pure.u64(t),s.object(v)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let r=await this._sdk.fullClient.devInspectTransactionBlock({sender:n,transactionBlock:s}),o=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[0][0]))),c=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[1][0]))),u=String(f.U64.parse(new Uint8Array(r.results[0].returnValues[2][0])));return{quoteQuantityDisplay:a(t).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(o).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(c).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(u).div(ne).toString(),quoteQuantity:t,baseOut:o,quoteOut:c,deepRequired:u}}async getQuantityOut(e,t,n,s){let r=new w;r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_quantity_out`,arguments:[r.object(e.address),r.pure.u64(t),r.pure.u64(n),r.object(v)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let o=await this._sdk.fullClient.devInspectTransactionBlock({sender:s,transactionBlock:r}),c=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[0][0]))),u=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[1][0]))),l=Number(f.U64.parse(new Uint8Array(o.results[0].returnValues[2][0])));return{baseQuantityDisplay:a(t).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteQuantityDisplay:a(n).div(Math.pow(10,e.quoteCoin.decimals)).toString(),baseOutDisplay:a(c).div(Math.pow(10,e.baseCoin.decimals)).toString(),quoteOutDisplay:a(u).div(Math.pow(10,e.quoteCoin.decimals)).toString(),deepRequiredDisplay:a(l).div(ne).toString(),baseQuantity:t,quoteQuantity:n,baseOut:c,quoteOut:u,deepRequired:l}}async getReferencePool(e){let t=await this.getPools(),n=e.baseCoin.coinType,s=e.quoteCoin.coinType,r=this._deep.coinType;for(let o=0;o<t.length;o++){let c=t[o];if(c.address===e.address)continue;let u=[c.baseCoinType,c.quoteCoinType];if(c.baseCoinType===r&&(u.includes(n)||u.includes(s)))return c}return null}async updateDeepPrice(e,t){let n=await this.getReferencePool(e);return n?(t.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::add_deep_price_point`,arguments:[t.object(e.address),t.object(n.pool_id),t.object(v)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType,n.baseCoinType,n.quoteCoinType]}),t):null}async estimatedMaxFee(e,t,n,s,r,o,c){let u=this.deepCoin;try{let{taker_fee:l,maker_fee:g}=e,d=a(l).div(M).toString(),m=a(g).div(M).toString(),p=await this.getMarketPrice(e),b=o?n:p!=="0"?p:c;if(b==="0")throw new Error("Cannot get market price");let h=Math.pow(10,e.baseCoin.decimals).toString(),T=Math.pow(10,e.quoteCoin.decimals).toString(),y=a(b).div(h).mul(T).mul(M).toString();if(s){let S=await this.getMarketPrice(e),k=a(o?n:S!=="0"?S:c).div(h).mul(T).mul(M).toString(),x=await this.getOrderDeepPrice(e);if(!x)throw new Error("Cannot get deep price");let j=ee(k,n),D=a(t).mul(a(d)).mul(a(x.deep_per_asset)).div(a(M)),B=a(t).mul(a(m)).mul(a(x.deep_per_asset)).div(a(M));x.asset_is_base||(D=D.mul(j).div(a(M)),B=B.mul(j).div(a(M)));let P=D.ceil().toString(),se=B.ceil().toString();return{takerFee:P,makerFee:se,takerFeeDisplay:N(P,u.decimals).toString(),makerFeeDisplay:N(se,u.decimals).toString(),feeType:u.coinType}}if(r){let S=ee(y,n),O=a(t).mul(S).mul(a(d).mul(1.25)).div(a(M)).ceil().toFixed(0),k=a(t).mul(S).mul(a(m).mul(1.25)).div(a(M)).ceil().toFixed(0);return{takerFee:O,makerFee:k,takerFeeDisplay:N(O,e.quoteCoin.decimals).toString(),makerFeeDisplay:N(k,e.quoteCoin.decimals).toString(),feeType:e.quoteCoin.coinType}}let C=a(t).mul(a(d).mul(1.25)).ceil().toFixed(0),_=a(t).mul(a(m).mul(1.25)).ceil().toFixed(0);return{takerFee:C,makerFee:_,takerFeeDisplay:N(C,e.baseCoin.decimals).toString(),makerFeeDisplay:N(_,e.baseCoin.decimals).toString(),feeType:e.baseCoin.coinType}}catch(l){throw l instanceof Error?l:new Error(String(l))}}async getOrderDeepPrice(e,t=!0){let n=`getOrderDeepPrice_${e.address}}`,s=this.getCache(n);if(s!==void 0)return s;try{let r=new w,o=!1;t&&e?.baseCoin?.coinType!==this._deep.coinType&&e?.quoteCoin?.coinType!==this._deep.coinType&&await this.updateDeepPrice(e,r)&&(o=!0),r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order_deep_price`,arguments:[r.object(e.address)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let c=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:r}),u=o?c.results[1]?.returnValues[0]?.[0]:c.results[0]?.returnValues[0]?.[0],l=this.parseOrderDeepPrice(new Uint8Array(u));return this.updateCache(n,l,ie),l}catch{return await ke(2e3),this.getOrderDeepPrice(e,!1)}}parseOrderDeepPrice(e){let t=new DataView(e.buffer),n=t.getUint8(0)!==0,s=Number(t.getBigUint64(1,!0));return{asset_is_base:n,deep_per_asset:s}}getCoinAssets(e,t,n,s){return I.buildCoinForAmount(s,n,BigInt(a(t).abs().ceil().toString()),e,!1,!0).targetCoin}async getTransactionRelatedBalance(e,t,n,s,r,o,c){let u=this.deepCoin;if(!c)return{baseManagerBlance:"0",quoteManagerBlance:"0",feeManaerBalance:"0"};try{let l=[{coinType:e.baseCoin.coinType,decimals:e.baseCoin.decimals},{coinType:e.quoteCoin.coinType,decimals:e.quoteCoin.decimals}];s&&l.push(u);let g=await this.getManagerBalance({account:r,balanceManager:c,coins:l}),d=g?.[t]?.balance||"0",m=g?.[n]?.balance||"0",p=o&&g?.[u.coinType]?.balance||"0";return{baseManagerBlance:d,quoteManagerBlance:m,feeManaerBalance:p}}catch(l){throw l instanceof Error?l:new Error(String(l))}}getFeeAsset(e,t,n,s,r,o,c,u,l,g){let d=a(e).gt(0)&&l,m="0";if(!d)return{feeAsset:this.getEmptyCoin(g,t),haveDepositFee:"0"};if(o||c){let p=a(r).sub(o?s:n);m=p.lte(0)?e:p.sub(e).lt(0)?p.sub(e).toString():"0"}else m=a(r).sub(e).lt("0")?a(r).sub(e).abs().toString():"0";return{feeAsset:a(m).gt("0")?this.getCoinAssets(t,m,u,g):this.getEmptyCoin(g,t),haveDepositFee:m}}async getTransactionRelatedAssets(e,t,n,s,r,o,c,u,l){try{let g=this.deepCoin,d=E(e.baseCoin.coinType),m=E(e.quoteCoin.coinType),p=d===g.coinType,b=m===g.coinType,h=!p&&!b,{baseManagerBlance:T,quoteManagerBlance:y,feeManaerBalance:C}=await this.getTransactionRelatedBalance(e,d,m,h,o,c,u),_,S,O=!1,k=await this._sdk.getOwnerCoinAssets(o);if(r){c||(n=a(n).add(a(s)).toString());let j=a(y).sub(n).toString();a(j).lt(0)?(O=!0,S=this.getCoinAssets(m,j,k,l)):S=this.getEmptyCoin(l,m),_=this.getEmptyCoin(l,d)}else{c||(t=a(t).add(a(s)).toString());let j=a(T).sub(t).toString();a(j).lt(0)?(O=!0,_=this.getCoinAssets(d,j,k,l)):_=this.getEmptyCoin(l,d),S=this.getEmptyCoin(l,m)}let x=this.getFeeAsset(s,g.coinType,t,n,C,b,p,k,c,l);return{baseAsset:_,quoteAsset:S,feeAsset:x,haveDeposit:O}}catch(g){throw g instanceof Error?g:new Error(String(g))}}async getMarketTransactionRelatedAssets(e,t,n,s,r,o,c,u,l,g){try{let d=this.deepCoin,m=E(e.baseCoin.coinType),p=E(e.quoteCoin.coinType),b=m===d.coinType,h=p===d.coinType,T=!b&&!h,y=await this.getTransactionRelatedBalance(e,m,p,T,o,c,u),{feeManaerBalance:C}=y,_=a(y.baseManagerBlance).add(a(g?.base||"0")).toString(),S=a(y.quoteManagerBlance).add(a(g?.quote||"0")).toString(),O=await this._sdk.getOwnerCoinAssets(o),k;c&&a(C).lt(s)?k=this.getCoinAssets(d.coinType,a(s).sub(C).toString(),O,l):k=this.getEmptyCoin(l,d.coinType);let x,j;if(r){c||(n=a(n).add(a(s)).toString());let D=a(S).sub(n).toString();if(a(D).lt(0)){let B;a(S).gt(0)&&(B=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:S,returnAssets:!0,txb:l}));let P=this.getCoinAssets(p,D,O,l);B&&l.mergeCoins(P,[B]),j=P}else j=this.withdrawFromManager({account:o,balanceManager:u,coin:e.quoteCoin,amountToWithdraw:n,returnAssets:!0,txb:l});x=this.getEmptyCoin(l,m)}else{c||(t=a(t).add(a(s)).toString());let D=a(_).sub(t).toString();if(a(D).lt(0)){let B;a(_).gt(0)&&(B=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:_,returnAssets:!0,txb:l}));let P=this.getCoinAssets(m,D,O,l);B&&l.mergeCoins(P,[B]),x=P}else x=this.withdrawFromManager({account:o,balanceManager:u,coin:e.baseCoin,amountToWithdraw:t,returnAssets:!0,txb:l});j=this.getEmptyCoin(l,p)}return{baseAsset:x,quoteAsset:j,feeAsset:k}}catch(d){throw d instanceof Error?d:new Error(String(d))}}async createDepositThenPlaceLimitOrder({poolInfo:e,priceInput:t,quantity:n,orderType:s,isBid:r,maxFee:o,account:c,payWithDeep:u,expirationTimestamp:l=Date.now()+Te}){try{let g=this.deepCoin,d=e.address,m=e.baseCoin.decimals,p=e.quoteCoin.decimals,b=e.baseCoin.coinType,h=e.quoteCoin.coinType,T=a(t).mul(10**(p-m+9)).toString(),y=E(b),C=E(h),_=new w,S,O,k=await this._sdk.getOwnerCoinAssets(c);if(r){let B=a(t).mul(a(n).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();u||(B=a(B).add(a(o)).toString()),O=I.buildCoinForAmount(_,k,BigInt(B),C,!1,!0)?.targetCoin}else{let B=n;u||(B=a(n).abs().add(a(o)).toString()),S=I.buildCoinForAmount(_,k,BigInt(a(B).abs().toString()),y,!1,!0)?.targetCoin}let x=u?a(o).gt(0)?I.buildCoinForAmount(_,k,BigInt(a(o).abs().ceil().toString()),g.coinType,!1,!0).targetCoin:this.getEmptyCoin(_,g.coinType):this.getEmptyCoin(_,g.coinType),j=_.moveCall({typeArguments:[r?b:h],target:"0x2::coin::zero",arguments:[]}),D=[_.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),_.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),_.object(d),r?j:S,r?O:j,x,_.pure.u8(s),_.pure.u8(0),_.pure.u64(T),_.pure.u64(n),_.pure.bool(r),_.pure.bool(!1),_.pure.u64(l),_.object(v)];return _.moveCall({typeArguments:[y,C],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_limit_order`,arguments:D}),_}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:n,maxFee:s,account:r,payWithDeep:o,slippage:c=.01}){try{let u=e.address,l=e.baseCoin.coinType,g=e.quoteCoin.coinType,d=E(l),m=E(g),p=new w,b,h,T=t,y,C=await this.getOrderBook(e,"all",6);if(n){let k=C?.ask?.[0]?.price||"0",x=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(x).plus(a(x).mul(c)).ceil().toString()}else{let k=await C?.bid?.[0]?.price||"0",x=a(k).mul(a(t).div(Math.pow(10,e.baseCoin.decimals))).mul(Math.pow(10,e.quoteCoin.decimals)).toString();y=a(x).minus(a(x).mul(c)).floor().toString()}let _=await this._sdk.getOwnerCoinAssets(r);n?(o||(y=a(y).add(a(s)).toString()),h=this.getCoinAssets(m,y,_,p),b=this.getEmptyCoin(p,d)):(o||(T=a(T).add(a(s)).toString()),h=this.getEmptyCoin(p,m),b=this.getCoinAssets(d,T,_,p));let S=o?a(s).gt(0)?I.buildCoinForAmount(p,_,BigInt(a(s).abs().ceil().toString()),this.deepCoin.coinType,!1,!0).targetCoin:this.getEmptyCoin(p,this.deepCoin.coinType):this.getEmptyCoin(p,this.deepCoin.coinType),O=[p.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),p.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),p.object(u),b,h,S,p.pure.u8(0),p.pure.u64(t),p.pure.bool(n),p.pure.bool(o),p.pure.u64(y),p.object(v)];return p.moveCall({typeArguments:[d,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::create_deposit_then_place_market_order_v2`,arguments:O}),p}catch(u){throw u instanceof Error?u:new Error(String(u))}}async placeLimitOrder({balanceManager:e,poolInfo:t,priceInput:n,quantity:s,isBid:r,orderType:o,maxFee:c,account:u,payWithDeep:l,expirationTimestamp:g=Date.now()+Te}){try{let d=this.deepCoin,m=a(n).mul(10**(t.quoteCoin.decimals-t.baseCoin.decimals+9)).toString(),p=t.baseCoin.coinType,b=t.quoteCoin.coinType,h=new w,T=r?a(n).mul(a(s).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString():"0",y=r?"0":s,{baseAsset:C,quoteAsset:_,feeAsset:S,haveDeposit:O}=await this.getTransactionRelatedAssets(t,y,T,c,r,u,l,e,h);if(O){let j=[h.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),h.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),h.object(t.address),h.object(e),C,_,S.feeAsset,h.pure.u8(o),h.pure.u8(0),h.pure.u64(m),h.pure.u64(s),h.pure.bool(r),h.pure.bool(l),h.pure.u64(g),h.object(v)];return h.moveCall({typeArguments:[p,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_limit_order_by_owner`,arguments:j}),h}let k=new w;a(S.haveDepositFee).gt(0)&&this.depositIntoManager({account:u,balanceManager:e,coin:d,amountToDeposit:S.haveDepositFee,tx:k});let x=[k.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),k.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),k.object(t.address),k.object(e),k.pure.u8(o),k.pure.u8(0),k.pure.u64(m),k.pure.u64(s),k.pure.bool(r),k.pure.bool(l),k.pure.u64(g),k.object(v)];return k.moveCall({typeArguments:[p,b],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::place_limit_order`,arguments:x}),k}catch(d){throw d instanceof Error?d:new Error(String(d))}}modifyOrder({balanceManager:e,poolInfo:t,orderId:n,newOrderQuantity:s}){let r=new w;return r.moveCall({typeArguments:[t.baseCoin.coinType,t.quoteCoin.coinType],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::modify_order`,arguments:[r.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),r.object(e),r.object(t.address),r.pure.u128(n),r.pure.u64(s),r.object(v)]}),r}async getBestAskprice(e){try{let{baseCoin:t,quoteCoin:n}=e,s=new w,r=await this.getMarketPrice(e),o=a(r).gt(0)?r:Math.pow(10,-1),c=Math.pow(10,6),u=a(o).mul(Math.pow(10,9+n.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+n.decimals-t.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(u),s.pure.u64(l),s.pure.bool(!1),s.object(v)],typeArguments:[t.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:s}),m=[],p=d.results[0].returnValues[0][0],b=f.vector(f.u64()).parse(new Uint8Array(p)),h=d.results[0].returnValues[1][0],T=f.vector(f.u64()).parse(new Uint8Array(h));return b.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),S=a(T[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:_,quantity:S})}),m?.[0]?.price||0}catch{return 0}}async getBestBidprice(e){try{let{baseCoin:t,quoteCoin:n}=e,s=new w,r=await this.getMarketPrice(e),o=a(r).gt(0)?a(r).div(3).toNumber():Math.pow(10,-6),c=a(r).gt(0)?r:Math.pow(10,6),u=a(o).mul(Math.pow(10,9+n.decimals-t.decimals)).toString(),l=a(c).mul(Math.pow(10,9+n.decimals-t.decimals)).toString();s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[s.object(e.address),s.pure.u64(F(u,0)),s.pure.u64(F(l,0)),s.pure.bool(!0),s.object(v)],typeArguments:[t.coinType,n.coinType]});let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:s}),m=[],p=d.results[0].returnValues[0][0],b=f.vector(f.u64()).parse(new Uint8Array(p)),h=d.results[0].returnValues[1][0],T=f.vector(f.u64()).parse(new Uint8Array(h));return b.forEach((y,C)=>{let _=a(y).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),S=a(T[C]).div(Math.pow(10,t.decimals)).toString();m.push({price:_,quantity:S})}),m?.[0]?.price||0}catch{return 0}}async getBestAskOrBidPrice(e,t){try{let{baseCoin:n,quoteCoin:s}=e,r=new w,o=await this.getMarketPrice(e),c,u;t?(c=a(o).gt(0)?a(o).div(3).toNumber():Math.pow(10,-6),u=a(o).gt(0)?o:Math.pow(10,6)):(c=a(o).gt(0)?o:Math.pow(10,-1),u=a(o).gt(0)?a(o).mul(3).toNumber():Math.pow(10,6));let l=a(c).mul(Math.pow(10,9+s.decimals-n.decimals)).toString(),g=a(u).mul(Math.pow(10,9+s.decimals-n.decimals)).toString();r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(F(l,0)),r.pure.u64(F(g,0)),r.pure.bool(t),r.object(v)],typeArguments:[n.coinType,s.coinType]});let d=this._sdk.sdkOptions.simulationAccount.address,m=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:r}),p=[],b=m.results[0].returnValues[0][0],h=f.vector(f.u64()).parse(new Uint8Array(b)),T=m.results[0].returnValues[1][0],y=f.vector(f.u64()).parse(new Uint8Array(T));return h.forEach((C,_)=>{let S=a(C).div(Math.pow(10,9+s.decimals-n.decimals)).toString(),O=a(y[_]).div(Math.pow(10,n.decimals)).toString();p.push({price:S,quantity:O})}),p?.[0]?.price||0}catch{return 0}}async placeMarketOrder({balanceManager:e,poolInfo:t,baseQuantity:n,quoteQuantity:s,isBid:r,maxFee:o,account:c,payWithDeep:u,slippage:l=.01,settled_balances:g={base:"0",quote:"0"}}){try{let d=E(t.baseCoin.coinType),m=E(t.quoteCoin.coinType),p=new w;g&&(a(g.base).gt(0)||a(g.quote).gt(0))&&this.withdrawSettledAmounts({poolInfo:t,balanceManager:e},p);let{baseAsset:b,quoteAsset:h,feeAsset:T}=await this.getMarketTransactionRelatedAssets(t,n,s,o,r,c,u,e,p,g),y=await this.getOrderBook(t,"all",6);if(r){let S=y?.ask?.[0]?.price||"0",O=a(S).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();s=a(O).plus(a(O).mul(l)).ceil().toString()}else{let S=await y?.bid?.[0]?.price||"0",O=a(S).mul(a(n).div(Math.pow(10,t.baseCoin.decimals))).mul(Math.pow(10,t.quoteCoin.decimals)).toString();s=a(O).minus(a(O).mul(l)).floor().toString()}let C=s,_=[p.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),p.object(this._sdk.sdkOptions.deepbook_utils.cetus_balance_manager_indexer_id),p.object(t.address),p.object(e),b,h,T,p.pure.u8(0),p.pure.u64(n),p.pure.bool(r),p.pure.bool(u),p.pure.u64(C),p.object(v)];return p.setSenderIfNotSet(c),p.moveCall({typeArguments:[d,m],target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::deposit_then_place_market_order_by_owner_v2`,arguments:_}),p}catch(d){throw d instanceof Error?d:new Error(String(d))}}async getOrderInfoList(e,t){try{let n=new w;e.forEach(l=>{let g=l?.pool,d=l?.orderId;n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_order`,arguments:[n.object(g.pool_id),n.pure.u128(BigInt(d))],typeArguments:[g.baseCoinType,g.quoteCoinType]})});let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:n}),r=f.struct("ID",{bytes:f.Address}),o=f.struct("OrderDeepPrice",{asset_is_base:f.bool(),deep_per_asset:f.u64()}),c=f.struct("Order",{balance_manager_id:r,order_id:f.u128(),client_order_id:f.u64(),quantity:f.u64(),filled_quantity:f.u64(),fee_is_deep:f.bool(),order_deep_price:o,epoch:f.u64(),status:f.u8(),expire_timestamp:f.u64()}),u=[];return s?.results?.forEach(l=>{let g=l.returnValues[0][0],d=c.parse(new Uint8Array(g));u.push(d)}),u}catch{return[]}}decodeOrderId(e){let t=e>>BigInt(127)===BigInt(0),n=e>>BigInt(64)&(BigInt(1)<<BigInt(63))-BigInt(1),s=e&(BigInt(1)<<BigInt(64))-BigInt(1);return{isBid:t,price:n,orderId:s}}async getOpenOrder(e,t,n,s){let r;if(s)r=s;else{let l=new w;l.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[l.object(e.address),l.object(n)],typeArguments:[e.baseCoin.coinType,e.quoteCoin.coinType]});let d=(await this._sdk.fullClient.devInspectTransactionBlock({sender:t,transactionBlock:l})).results[0].returnValues[0][0];r=f.struct("VecSet",{constants:f.vector(f.U128)}).parse(new Uint8Array(d)).constants}let o=r.map(l=>({pool:{pool_id:e.address,baseCoinType:e.baseCoin.coinType,quoteCoinType:e.quoteCoin.coinType},orderId:l})),c=await this.getOrderInfoList(o,t)||[],u=[];return c.forEach(l=>{let g=this.decodeOrderId(BigInt(l.order_id));u.push({...l,price:g.price,isBid:g.isBid})}),u}async getAllMarketsOpenOrders(e,t){try{let n=await this.getPools(),s=new w;n.forEach(d=>{s.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::account_open_orders`,arguments:[s.object(d.pool_id),s.object(t)],typeArguments:[d.baseCoinType,d.quoteCoinType]})});let o=(await this._sdk.fullClient.devInspectTransactionBlock({sender:e,transactionBlock:s})).results?.map(d=>d.returnValues?.[0]?.[0])||[],c=f.struct("VecSet",{constants:f.vector(f.U128)}),u=[];o.forEach((d,m)=>{let p=c.parse(new Uint8Array(d)).constants;p.length>0&&p.forEach(b=>{u.push({pool:n[m],orderId:b})})});let l=await this.getOrderInfoList(u,e)||[],g=[];return u.forEach((d,m)=>{let p=this.decodeOrderId(BigInt(d.orderId)),b=l.find(h=>h.order_id===d.orderId)||{};g.push({...d,...b,price:p.price,isBid:p.isBid})}),g}catch{return[]}}cancelOrders(e,t){let n=new w;return e.forEach(s=>{n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::deepbookv3_utils::cancel_order`,arguments:[n.object(this._sdk.sdkOptions.deepbook_utils.global_config_id),n.object(t),n.object(s.poolInfo.address),n.pure.u128(s.orderId),n.object(v)],typeArguments:[s.poolInfo.baseCoin.coinType,s.poolInfo.quoteCoin.coinType]})}),n}async getDeepbookOrderBook(e,t,n,s,r,o){let c=this._sdk.fullClient,l=await new He({client:c,address:r,env:"testnet",balanceManagers:{test1:{address:o,tradeCap:""}}}).getLevel2Range(e,t,n,s)}processOrderBookData(e,t,n,s){let r=e.returnValues[0][0],o=f.vector(f.u64()).parse(new Uint8Array(r)),c=e.returnValues[1][0],u=f.vector(f.u64()).parse(new Uint8Array(c)),l={};return o.forEach((d,m)=>{let p=a(d).div(Math.pow(10,9+n.decimals-t.decimals)).toString(),b=a(u[m]).div(Math.pow(10,t.decimals)).toString();l[p]?l[p]={price:p,quantity:a(l[p].quantity).add(b).toString()}:l[p]={price:p,quantity:b}}),Object.values(l)}getLevel2RangeTx(e,t,n,s,r=new w){let{baseCoin:o,quoteCoin:c}=e,u=F(a(n).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0),l=F(a(s).mul(Math.pow(10,9+c.decimals-o.decimals)).toString(),0);return r.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[r.object(e.address),r.pure.u64(u),r.pure.u64(l),r.pure.bool(t),r.object(v)],typeArguments:[o.coinType,c.coinType]}),r}async fetchOrderBook(e,t,n,s,r,o){let c=new w,{baseCoin:u,quoteCoin:l}=e;try{if(t==="bid"||t==="all"){let b=s,h=n==="0"?r:n;c=this.getLevel2RangeTx(e,!0,b,h,c)}if(t==="ask"||t==="all"){let b=n==="0"?s:n,h=r;c=this.getLevel2RangeTx(e,!1,b,h,c)}let g=this._sdk.sdkOptions.simulationAccount.address,d=await this._sdk.fullClient.devInspectTransactionBlock({sender:g,transactionBlock:c}),m=[];(t==="bid"||t==="all")&&(m=d.results?.[0]?this.processOrderBookData(d.results[0],u,l,o):[]);let p=[];if(t==="ask"||t==="all"){let b=t==="ask"?0:1;p=d.results?.[b]?this.processOrderBookData(d.results[b],u,l,o):[]}return{bid:m.sort((b,h)=>h.price-b.price),ask:p.sort((b,h)=>b.price-h.price)}}catch{let d=this._sdk.sdkOptions.simulationAccount.address,m=[],p=[];try{let b=this.getLevel2RangeTx(e,!0,s,n),h=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:b});m=h.results?.[0]?this.processOrderBookData(h.results[0],u,l,o):[]}catch{m=[]}try{let b=this.getLevel2RangeTx(e,!1,s,n),h=await this._sdk.fullClient.devInspectTransactionBlock({sender:d,transactionBlock:b});p=h.results?.[0]?this.processOrderBookData(h.results[0],u,l,o):[]}catch{p=[]}return{bid:m,ask:p}}}async getOrderBook(e,t,n){let s={bid:[],ask:[]};try{let r=await this.getMarketPrice(e),o=t,c=Math.pow(10,-n),u=Math.pow(10,n),l=await this.fetchOrderBook(e,o,r,c,u,n);return{bid:l?.bid,ask:l?.ask}}catch{return s}}async getOrderBookOrigin(e,t){try{let n=new w,s=await this.getMarketPrice(e),{baseCoin:r,quoteCoin:o}=e;if(t==="bid"||t==="all"){let d=Math.pow(10,-6),m=s,p=a(d).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),b=a(m).mul(Math.pow(10,9+o.decimals-r.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(p),n.pure.u64(b),n.pure.bool(!0),n.object(v)],typeArguments:[r.coinType,o.coinType]})}if(t==="ask"||t==="all"){let d=s,m=Math.pow(10,6),p=a(d).mul(Math.pow(10,9+o.decimals-r.decimals)).toString(),b=a(m).mul(Math.pow(10,9+o.decimals-r.decimals)).toString();n.moveCall({target:`${this._sdk.sdkOptions.deepbook.package_id}::pool::get_level2_range`,arguments:[n.object(e.address),n.pure.u64(p),n.pure.u64(b),n.pure.bool(!1),n.object(v)],typeArguments:[r.coinType,o.coinType]})}let c=this._sdk.sdkOptions.simulationAccount.address,u=await this._sdk.fullClient.devInspectTransactionBlock({sender:c,transactionBlock:n}),l=[];if(t==="bid"||t==="all"){let d=u.results[0]?.returnValues[0]?.[0],m=f.vector(f.u64()).parse(new Uint8Array(d)),p=u.results[0]?.returnValues[1]?.[0],b=f.vector(f.u64()).parse(new Uint8Array(p));m.forEach((h,T)=>{let y=a(h).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),C=a(b[T]).div(Math.pow(10,r.decimals)).toString();l.push({price:y,quantity:C})})}let g=[];if(t==="ask"||t==="all"){let d=t==="ask"?0:1,m=u.results[d]?.returnValues[0]?.[0],p=f.vector(f.u64()).parse(new Uint8Array(m)),b=u.results[d]?.returnValues[1]?.[0],h=f.vector(f.u64()).parse(new Uint8Array(b));p.forEach((T,y)=>{let C=a(T).div(Math.pow(10,9+o.decimals-r.decimals)).toString(),_=a(h[y]).div(Math.pow(10,r.decimals)).toString();g.push({price:C,quantity:_})})}return{bid:l,ask:g}}catch{return{bids:[],asks:[]}}}async getWalletBalance(e){let t=await this._sdk.fullClient?.getAllBalances({owner:e});return Object.fromEntries(t.map((s,r)=>[E(s.coinType),s]))}async getAccount(e,t){let n=new w;for(let c=0;c<t.length;c++){let u=t[c];n.moveCall({target:`${this._sdk.sdkOptions.deepbook_utils.published_at}::order_trader::get_account_id`,arguments:[n.object(u.address),n.object(e)],typeArguments:[u.baseCoin.coinType,u.quoteCoin.coinType]})}let s=await this._sdk.fullClient.devInspectTransactionBlock({sender:this._sdk.sdkOptions.simulationAccount.address,transactionBlock:n}),r;if(s?.events.length===0)return null;let o=[];return s?.events?.forEach((c,u)=>{r=c?.parsedJson;let l=r.account.open_orders.contents,g=r.account.owed_balances,d=r.account.settled_balances,m=r.account.unclaimed_rebates,p=r.account.taker_volume;o.push({balance_manager_id:e,open_orders:l,owed_balances:g,settled_balances:d,unclaimed_rebates:m,taker_volume:p,poolInfo:t[u]})}),o}async getSuiTransactionResponse(e,t=!1){let n=`${e}_getSuiTransactionResponse`,s=this.getCache(n,t);if(s!==void 0)return s;let r;try{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0,showBalanceChanges:!0,showInput:!0,showObjectChanges:!0}})}catch{r=await this._sdk.fullClient.getTransactionBlock({digest:e,options:{showEvents:!0,showEffects:!0}})}return this.updateCache(n,r,U),r}transformExtensions(e,t,n=!0){let s=[];for(let r of t){let{key:o}=r.fields,{value:c}=r.fields;if(o==="labels")try{c=JSON.parse(decodeURIComponent(Qe.decode(c)))}catch{}n&&(e[o]=c),s.push({key:o,value:c})}delete e.extension_fields,n||(e.extensions=s)}async getCoinConfigs(e=!1,t=!0){let n=this.sdk.sdkOptions.coinlist.handle,s=`${n}_getCoinConfigs`,r=this.getCache(s,e);if(r)return r;let c=(await this._sdk.fullClient.getDynamicFieldsByPage(n)).data.map(g=>g.objectId),u=await this._sdk.fullClient.batchGetObjects(c,{showContent:!0}),l=[];return u.forEach(g=>{let d=this.buildCoinConfig(g,t);this.updateCache(`${n}_${d.address}_getCoinConfig`,d,U),l.push({...d})}),this.updateCache(s,l,U),l}buildCoinConfig(e,t=!0){let n=he(e);n=n.value.fields;let s={...n};return s.id=be(e),s.address=R(n.coin_type.fields.name).full_address,n.pyth_id&&(s.pyth_id=Ze(n.pyth_id)),this.transformExtensions(s,n.extension_fields.fields.contents,t),delete s.coin_type,s}updateCache(e,t,n=oe){let s=this._cache[e];s?(s.overdueTime=V(n),s.value=t):s=new $(t,V(n)),this._cache[e]=s}getCache(e,t=!1){let n=this._cache[e],s=n?.isValid();if(!t&&s)return n.value;s||delete this._cache[e]}async createPermissionlessPool({tickSize:e,lotSize:t,minSize:n,baseCoinType:s,quoteCoinType:r}){let o=new w,c=A.buildCoinWithBalance(BigInt(500*10**6),"0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",o);o.moveCall({target:`${this.sdk.sdkOptions.deepbook.published_at}::pool::create_permissionless_pool`,typeArguments:[s,r],arguments:[o.object(this.sdk.sdkOptions.deepbook.registry_id),o.pure.u64(e),o.pure.u64(t),o.pure.u64(n),c]});try{let u=await this._sdk.fullClient.devInspectTransactionBlock({sender:this.sdk.senderAddress,transactionBlock:o});if(u.effects.status.status==="success")return o;if(u.effects.status.status==="failure"&&u.effects.status.error&&u.effects.status.error.indexOf('Some("register_pool") }, 1)')>-1)throw new Error("Pool already exists")}catch(u){throw u instanceof Error?u:new Error(String(u))}return o}};var Q=class{_cache={};_rpcModule;_deepbookUtils;_sdkOptions;_senderAddress="";constructor(e){this._sdkOptions=e,this._rpcModule=new K({url:e.fullRpcUrl}),this._deepbookUtils=new H(this),Y(this._sdkOptions)}get senderAddress(){return this._senderAddress}set senderAddress(e){this._senderAddress=e}get DeepbookUtils(){return this._deepbookUtils}get fullClient(){return this._rpcModule}get sdkOptions(){return this._sdkOptions}async getOwnerCoinAssets(e,t,n=!0){let s=[],r=null,o=`${this.sdkOptions.fullRpcUrl}_${e}_${t}_getOwnerCoinAssets`,c=this.getCache(o,n);if(c)return c;for(;;){let u=await(t?this.fullClient.getCoins({owner:e,coinType:t,cursor:r}):this.fullClient.getAllCoins({owner:e,cursor:r}));if(u.data.forEach(l=>{BigInt(l.balance)>0&&s.push({coinAddress:R(l.coinType).source_address,coinObjectId:l.coinObjectId,balance:BigInt(l.balance)})}),r=u.nextCursor,!u.hasNextPage)break}return this.updateCache(o,s,30*1e3),s}async getOwnerCoinBalances(e,t){let n=[];return t?n=[await this.fullClient.getBalance({owner:e,coinType:t})]:n=[...await this.fullClient.getAllBalances({owner:e})],n}updateCache(e,t,n=U){let s=this._cache[e];s?(s.overdueTime=V(n),s.value=t):s=new $(t,V(n)),this._cache[e]=s}getCache(e,t=!1){let n=this._cache[e],s=n?.isValid();if(!t&&s)return n.value;s||delete this._cache[e]}};var Kn="0x0000000000000000000000000000000000000000000000000000000000000006",Hn="pool_script",Qn="pool_script_v2",Zn="router",zn="router_with_partner",Wn="fetcher_script",Jn="expect_swap",Yn="utils",Xn="0x1::coin::CoinInfo",es="0x1::coin::CoinStore",ts="custodian_v2",ns="clob_v2",ss="endpoints_v2",rs=i=>{if(typeof i=="string"&&i.startsWith("0x"))return"object";if(typeof i=="number"||typeof i=="bigint")return"u64";if(typeof i=="boolean")return"bool";throw new Error(`Unknown type for value: ${i}`)};var Je=(s=>(s[s.NO_RESTRICTION=0]="NO_RESTRICTION",s[s.IMMEDIATE_OR_CANCEL=1]="IMMEDIATE_OR_CANCEL",s[s.FILL_OR_KILL=2]="FILL_OR_KILL",s[s.POST_ONLY=3]="POST_ONLY",s))(Je||{});var hs=Q;export{Kn as CLOCK_ADDRESS,$ as CachedContent,Q as CetusClmmSDK,Jn as ClmmExpectSwapModule,Wn as ClmmFetcherModule,Hn as ClmmIntegratePoolModule,Qn as ClmmIntegratePoolV2Module,Zn as ClmmIntegrateRouterModule,zn as ClmmIntegrateRouterWithPartnerModule,Yn as ClmmIntegrateUtilsModule,A as CoinAssist,Xn as CoinInfoAddress,es as CoinStoreAddress,ne as DEEP_SCALAR,it as DEFAULT_GAS_BUDGET_FOR_MERGE,rt as DEFAULT_GAS_BUDGET_FOR_SPLIT,ct as DEFAULT_GAS_BUDGET_FOR_STAKE,ot as DEFAULT_GAS_BUDGET_FOR_TRANSFER,at as DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI,lt as DEFAULT_NFT_TRANSFER_GAS_FEE,ns as DeepbookClobV2Moudle,ts as DeepbookCustodianV2Moudle,ss as DeepbookEndpointsV2Moudle,H as DeepbookUtilsModule,M as FLOAT_SCALAR,ut as GAS_SYMBOL,z as GAS_TYPE_ARG,ce as GAS_TYPE_ARG_LONG,At as NORMALIZED_SUI_COIN_TYPE,Je as OrderType,K as RpcModule,dt as SUI_SYSTEM_STATE_OBJECT_ID,I as TransactionUtil,ue as addHexPrefix,Jt as asIntN,Wt as asUintN,bt as bufferToHex,ie as cacheTime1min,U as cacheTime24h,oe as cacheTime5min,mt as checkAddress,de as composeType,a as d,X as decimalsMultiplier,hs as default,wt as extractAddressFromType,R as extractStructTagFromType,Tt as fixCoinType,F as fixDown,Ue as fixSuiObjectId,N as fromDecimalsAmount,rs as getDefaultSuiInputType,V as getFutureTime,te as getMoveObject,Ge as getMoveObjectType,Ut as getMovePackageContent,Ne as getObjectDeletedResponse,Vt as getObjectDisplay,he as getObjectFields,be as getObjectId,$e as getObjectNotExistsResponse,$t as getObjectOwner,Nt as getObjectPreviousTransactionDigest,me as getObjectReference,Ft as getObjectType,It as getObjectVersion,L as getSuiObjectData,Lt as hasPublicTransfer,ht as hexToNumber,ft as hexToString,St as isSortedSymbols,Ve as isSuiObjectResponse,ee as maxDecimal,Z as normalizeCoinType,Y as patchFixSuiObjectId,Pt as printTransaction,W as removeHexPrefix,Yt as secretKeyToEd25519Keypair,Xt as secretKeyToSecp256k1Keypair,gt as shortAddress,ve as shortString,ke as sleepTime,De as toBuffer,zt as toDecimalsAmount,Ee as utf8to16};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cetusprotocol/deepbook-utils",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "cetus deepbook utils sdk",
|
|
5
5
|
"typings": "dist/index.d.ts",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -15,7 +15,8 @@
|
|
|
15
15
|
"build:clean": "rm -rf dist",
|
|
16
16
|
"_build:browser": "tsup --platform browser --format iife --global-name cetusAptosSDK --minify",
|
|
17
17
|
"_build:node": "tsup --format cjs,esm --dts",
|
|
18
|
-
"build:doc": "npx typedoc"
|
|
18
|
+
"build:doc": "npx typedoc",
|
|
19
|
+
"publish:test": "node version.mjs && npm publish --tag experimental"
|
|
19
20
|
},
|
|
20
21
|
"repository": {
|
|
21
22
|
"type": "git",
|
|
@@ -80,10 +81,10 @@
|
|
|
80
81
|
},
|
|
81
82
|
"overrides": {
|
|
82
83
|
"chalk": "5.3.0",
|
|
83
|
-
"strip-ansi": "
|
|
84
|
+
"strip-ansi": "7.1.0",
|
|
84
85
|
"color-convert": "2.0.1",
|
|
85
86
|
"color-name": "1.1.4",
|
|
86
87
|
"is-core-module": "2.13.1",
|
|
87
88
|
"error-ex": "1.3.2"
|
|
88
89
|
}
|
|
89
|
-
}
|
|
90
|
+
}
|
package/version.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Don't sync to github
|
|
2
|
+
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
|
|
5
|
+
const packageJsonPath = './package.json';
|
|
6
|
+
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
|
7
|
+
|
|
8
|
+
const newVersion = `0.0.0-experimental-${getCurrentDateTimeString()}`;
|
|
9
|
+
packageJson.version = newVersion;
|
|
10
|
+
|
|
11
|
+
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');
|
|
12
|
+
|
|
13
|
+
console.log(`Version updated to ${newVersion}`);
|
|
14
|
+
|
|
15
|
+
function getCurrentDateTimeString() {
|
|
16
|
+
const now = new Date();
|
|
17
|
+
|
|
18
|
+
const year = now.getFullYear();
|
|
19
|
+
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
20
|
+
const day = String(now.getDate()).padStart(2, '0');
|
|
21
|
+
const hours = String(now.getHours()).padStart(2, '0');
|
|
22
|
+
const minutes = String(now.getMinutes()).padStart(2, '0');
|
|
23
|
+
const seconds = String(now.getSeconds()).padStart(2, '0');
|
|
24
|
+
|
|
25
|
+
const dateTimeString = `${year}${month}${day}${hours}${minutes}${seconds}`;
|
|
26
|
+
|
|
27
|
+
return dateTimeString;
|
|
28
|
+
}
|
package/.env
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
MNEMONIC_PHRASE='fall drum inflict stem bean girl start wife afraid sight forget slot'
|