@cetusprotocol/deepbook-utils 1.0.6 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,16 @@
1
+ import { SuiTransactionBlockResponse, SuiClient, SuiEventFilter, SuiObjectResponseQuery, SuiObjectDataOptions, CoinBalance, SuiObjectResponse, SuiObjectData, SuiObjectRef, OwnedObjectRef, SuiMoveObject, ObjectOwner, DisplayFieldsResponse, SuiParsedData } from '@mysten/sui/client';
2
+ import { SuiGraphQLClient } from '@mysten/sui/graphql';
1
3
  import * as _mysten_sui_transactions from '@mysten/sui/transactions';
2
- import { TransactionArgument, Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
3
- import { SuiClient, SuiEventFilter, SuiObjectResponseQuery, SuiObjectDataOptions, SuiTransactionBlockResponse, SuiObjectResponse, SuiObjectData, SuiObjectRef, OwnedObjectRef, SuiMoveObject, ObjectOwner, DisplayFieldsResponse, SuiParsedData } from '@mysten/sui/client';
4
+ import { TransactionArgument, Transaction, TransactionResult, TransactionObjectArgument } from '@mysten/sui/transactions';
5
+ import { SuiPriceServiceConnection, SuiPythClient } from '@pythnetwork/pyth-sui-js';
4
6
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
5
7
  import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1';
6
- import { CoinBalance } from '@mysten/sui/dist/cjs/client';
7
8
  import Decimal from 'decimal.js';
8
9
 
10
+ interface IModule {
11
+ readonly sdk: DeepbookUtilsSDK;
12
+ }
13
+
9
14
  /**
10
15
  * Represents a SUI address, which is a string.
11
16
  */
@@ -237,6 +242,11 @@ declare enum OrderType {
237
242
  FILL_OR_KILL = 2,
238
243
  POST_ONLY = 3
239
244
  }
245
+ declare enum SelfMatchingOption {
246
+ SELF_MATCHING_ALLOWED = 0,
247
+ CANCEL_TAKER = 1,
248
+ CANCEL_MAKER = 2
249
+ }
240
250
  type Token = {
241
251
  coinType: string;
242
252
  decimals: number;
@@ -248,62 +258,20 @@ type PoolInfo = {
248
258
  [key: string]: any;
249
259
  };
250
260
 
251
- type BigNumber = Decimal.Value | number | string;
252
-
253
- /**
254
- * Represents a module for making RPC (Remote Procedure Call) requests.
255
- */
256
- declare class RpcModule extends SuiClient {
257
- /**
258
- * Get events for a given query criteria
259
- * @param query
260
- * @param paginationArgs
261
- * @returns
262
- */
263
- queryEventsByPage(query: SuiEventFilter, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
264
- /**
265
- * Get all objects owned by an address
266
- * @param owner
267
- * @param query
268
- * @param paginationArgs
269
- * @returns
270
- */
271
- getOwnedObjectsByPage(owner: string, query: SuiObjectResponseQuery, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
272
- /**
273
- * Return the list of dynamic field objects owned by an object
274
- * @param parentId
275
- * @param paginationArgs
276
- * @returns
277
- */
278
- getDynamicFieldsByPage(parentId: SuiObjectIdType, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
279
- /**
280
- * Batch get details about a list of objects. If any of the object ids are duplicates the call will fail
281
- * @param ids
282
- * @param options
283
- * @param limit
284
- * @returns
285
- */
286
- batchGetObjects(ids: SuiObjectIdType[], options?: SuiObjectDataOptions, limit?: number): Promise<any[]>;
287
- /**
288
- * Calculates the gas cost of a transaction block.
289
- * @param {Transaction} tx - The transaction block to calculate gas for.
290
- * @returns {Promise<number>} - The estimated gas cost of the transaction block.
291
- * @throws {Error} - Throws an error if the sender is empty.
292
- */
293
- calculationTxGas(tx: Transaction): Promise<number>;
294
- /**
295
- * Sends a transaction block after signing it with the provided keypair.
296
- *
297
- * @param {Ed25519Keypair | Secp256k1Keypair} keypair - The keypair used for signing the transaction.
298
- * @param {Transaction} tx - The transaction block to send.
299
- * @returns {Promise<SuiTransactionBlockResponse | undefined>} - The response of the sent transaction block.
300
- */
301
- sendTransaction(keypair: Ed25519Keypair | Secp256k1Keypair, tx: Transaction): Promise<SuiTransactionBlockResponse | undefined>;
302
- }
261
+ type MarginCoinInfo = {
262
+ coinType: string;
263
+ feed?: string;
264
+ decimals?: number;
265
+ scalar?: number;
266
+ priceInfoObjectId?: string;
267
+ };
268
+ type MarginPoolInfo = {
269
+ id: string;
270
+ baseCoin: MarginCoinInfo;
271
+ quoteCoin: MarginCoinInfo;
272
+ };
303
273
 
304
- interface IModule {
305
- readonly sdk: DeepbookUtilsSDK;
306
- }
274
+ type BigNumber = Decimal.Value | number | string;
307
275
 
308
276
  declare const DEEP_SCALAR = 1000000;
309
277
  declare const FLOAT_SCALAR = 1000000000;
@@ -316,7 +284,7 @@ type DeepCoin = {
316
284
  decimals: number;
317
285
  };
318
286
  type StateAccount = {
319
- balance_manager_id: string;
287
+ balance_manager_id: string | TransactionArgument;
320
288
  open_orders: string[];
321
289
  owed_balances: Balances;
322
290
  settled_balances: Balances;
@@ -348,7 +316,7 @@ declare class DeepbookUtilsModule implements IModule {
348
316
  /**
349
317
  * Creates a new balance manager and deposits the specified coin amount into it.
350
318
  */
351
- createAndDepsit({ account, coin, amountToDeposit }: {
319
+ createAndDepsit({ account, coin, amountToDeposit, }: {
352
320
  account: string;
353
321
  coin: CoinItem;
354
322
  amountToDeposit: string;
@@ -379,7 +347,7 @@ declare class DeepbookUtilsModule implements IModule {
379
347
  /**
380
348
  * Withdraws free balances from multiple managers into the owner account.
381
349
  */
382
- withdrawManagersFreeBalance({ account, balanceManagers, tx }: {
350
+ withdrawManagersFreeBalance({ account, balanceManagers, tx, }: {
383
351
  account: string;
384
352
  balanceManagers: Record<string, {
385
353
  coinType: string;
@@ -392,7 +360,7 @@ declare class DeepbookUtilsModule implements IModule {
392
360
  * result when it is still valid.
393
361
  */
394
362
  getBalanceManager(account: string, forceRefresh?: boolean): Promise<any>;
395
- withdrawSettledAmounts({ poolInfo, balanceManager }: {
363
+ withdrawSettledAmounts({ poolInfo, balanceManager, }: {
396
364
  poolInfo: any;
397
365
  balanceManager: string;
398
366
  }, tx?: Transaction): Transaction;
@@ -400,7 +368,7 @@ declare class DeepbookUtilsModule implements IModule {
400
368
  * Retrieves balances for the provided coins tracked by a specific balance
401
369
  * manager.
402
370
  */
403
- getManagerBalance({ account, balanceManager, coins }: {
371
+ getManagerBalance({ account, balanceManager, coins, }: {
404
372
  account: string;
405
373
  balanceManager: string;
406
374
  coins: CoinItem[];
@@ -408,7 +376,7 @@ declare class DeepbookUtilsModule implements IModule {
408
376
  /**
409
377
  * Retrieves balances for all balance managers owned by the account.
410
378
  */
411
- getAccountAllManagerBalance({ account, coins }: {
379
+ getAccountAllManagerBalance({ account, coins, }: {
412
380
  account: string;
413
381
  coins: CoinItem[];
414
382
  }): Promise<any>;
@@ -520,7 +488,7 @@ declare class DeepbookUtilsModule implements IModule {
520
488
  /**
521
489
  * Creates a transaction that deposits required assets and then places a limit order.
522
490
  */
523
- createDepositThenPlaceLimitOrder({ poolInfo, priceInput, quantity, orderType, isBid, maxFee, account, payWithDeep, expirationTimestamp }: {
491
+ createDepositThenPlaceLimitOrder({ poolInfo, priceInput, quantity, orderType, isBid, maxFee, account, payWithDeep, expirationTimestamp, }: {
524
492
  poolInfo: PoolInfo;
525
493
  priceInput: string;
526
494
  quantity: string;
@@ -535,7 +503,7 @@ declare class DeepbookUtilsModule implements IModule {
535
503
  /**
536
504
  * Creates a transaction that deposits necessary assets and places a market order.
537
505
  */
538
- createDepositThenPlaceMarketOrder({ poolInfo, quantity, isBid, maxFee, account, payWithDeep, slippage }: {
506
+ createDepositThenPlaceMarketOrder({ poolInfo, quantity, isBid, maxFee, account, payWithDeep, slippage, }: {
539
507
  poolInfo: any;
540
508
  quantity: string;
541
509
  isBid: boolean;
@@ -547,7 +515,7 @@ declare class DeepbookUtilsModule implements IModule {
547
515
  /**
548
516
  * Builds a transaction to place a limit order and handles required deposits.
549
517
  */
550
- placeLimitOrder({ balanceManager, poolInfo, priceInput, quantity, isBid, orderType, maxFee, account, payWithDeep, expirationTimestamp }: {
518
+ placeLimitOrder({ balanceManager, poolInfo, priceInput, quantity, isBid, orderType, maxFee, account, payWithDeep, expirationTimestamp, }: {
551
519
  balanceManager: string;
552
520
  poolInfo: any;
553
521
  priceInput: string;
@@ -598,9 +566,9 @@ declare class DeepbookUtilsModule implements IModule {
598
566
  price: bigint;
599
567
  orderId: bigint;
600
568
  };
601
- getOpenOrder(poolInfo: any, account: string, balanceManager: string, orders?: string[]): Promise<any>;
569
+ getOpenOrder(poolInfo: any, account: string, balanceManager: string | TransactionArgument, orders?: string[], isMargin?: boolean, tx?: Transaction): Promise<any>;
602
570
  getAllMarketsOpenOrders(account: string, balanceManager: string): Promise<any>;
603
- cancelOrders(orderList: any, balanceManager: string): Transaction;
571
+ cancelOrders(orderList: any, balanceManager: string, tx?: Transaction): Transaction;
604
572
  getDeepbookOrderBook(poolKey: string, priceLow: number, priceHigh: number, isBid: boolean, account: string, balanceManager: string): Promise<void>;
605
573
  /**
606
574
  * Processes raw level 2 order book data returned from dev-inspect into
@@ -636,7 +604,7 @@ declare class DeepbookUtilsModule implements IModule {
636
604
  getWalletBalance(account: string): Promise<{
637
605
  [k: string]: any;
638
606
  }>;
639
- getAccount(balanceManager: string, poolList: any): Promise<StateAccount[] | null>;
607
+ getAccount(balanceManager: string | TransactionArgument, poolList: any, txb?: Transaction): Promise<StateAccount[] | null>;
640
608
  /**
641
609
  * Gets the SUI transaction response for a given transaction digest.
642
610
  * @param digest - The digest of the transaction for which the SUI transaction response is requested.
@@ -675,7 +643,7 @@ declare class DeepbookUtilsModule implements IModule {
675
643
  * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
676
644
  */
677
645
  getCache<T>(key: string, forceRefresh?: boolean): T | undefined;
678
- createPermissionlessPool({ tickSize, lotSize, minSize, baseCoinType, quoteCoinType }: {
646
+ createPermissionlessPool({ tickSize, lotSize, minSize, baseCoinType, quoteCoinType, }: {
679
647
  tickSize: string;
680
648
  lotSize: string;
681
649
  minSize: string;
@@ -684,6 +652,749 @@ declare class DeepbookUtilsModule implements IModule {
684
652
  }): Promise<Transaction>;
685
653
  }
686
654
 
655
+ type Price = {
656
+ coin_type: string;
657
+ price: string;
658
+ oracle_price: bigint;
659
+ last_update_time: number;
660
+ };
661
+ declare class PythPriceModule implements IModule {
662
+ protected _sdk: DeepbookUtilsSDK;
663
+ protected connection: SuiPriceServiceConnection;
664
+ protected suiPythClient: SuiPythClient;
665
+ protected hasChangeConnection: boolean;
666
+ private readonly _cache;
667
+ constructor(sdk: DeepbookUtilsSDK);
668
+ get sdk(): DeepbookUtilsSDK;
669
+ updatePythPriceIDs(priceIDs: string[], txb: Transaction): Promise<Map<string, string>>;
670
+ /**
671
+ * Checks if the price has been updated within the last 60 seconds.
672
+ *
673
+ * @param price - The price object to check.
674
+ * @returns The price object if it has been updated within the last 60 seconds, otherwise undefined.
675
+ */
676
+ priceCheck(price: Price, age?: number): Price | undefined;
677
+ /**
678
+ * Fetches the latest prices for a list of coin types.
679
+ * Optionally uses cached prices if available.
680
+ *
681
+ * @param coinTypeList - The list of coin types for which prices are required.
682
+ * @param useCache - A flag to indicate whether to use cached prices (default: false).
683
+ * @returns A promise that resolves to a record mapping coin types to their respective price information.
684
+ */
685
+ getLatestPrice(coinList: {
686
+ feed: string;
687
+ coinType: string;
688
+ }[], useCache?: boolean): Promise<Record<string, Price>>;
689
+ }
690
+
691
+ /**
692
+ * MarginUtilsModule provides utilities for managing margin trading operations
693
+ * including deposits, withdrawals, borrowing, repaying, and order management.
694
+ *
695
+ * @class MarginUtilsModule
696
+ * @implements {IModule}
697
+ */
698
+ declare class MarginUtilsModule implements IModule {
699
+ #private;
700
+ protected _sdk: DeepbookUtilsSDK;
701
+ protected pythPrice: PythPriceModule;
702
+ protected _deep: DeepCoin;
703
+ private readonly _cache;
704
+ /**
705
+ * Creates an instance of MarginUtilsModule.
706
+ *
707
+ * @param {DeepbookUtilsSDK} sdk - The SDK instance
708
+ */
709
+ constructor(sdk: DeepbookUtilsSDK);
710
+ /**
711
+ * Gets the SDK instance.
712
+ *
713
+ * @returns {DeepbookUtilsSDK} The SDK instance
714
+ */
715
+ get sdk(): DeepbookUtilsSDK;
716
+ get deepCoin(): DeepCoin;
717
+ /**
718
+ * Creates a margin manager and shares it with the caller account.
719
+ * This is the first step to enable margin trading for a specific pool.
720
+ *
721
+ * @param {MarginPoolInfo} poolInfo - The pool information containing base and quote coin details
722
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
723
+ * @returns {Transaction} The transaction object with margin manager creation and sharing operations
724
+ * @throws {Error} If poolInfo is invalid or missing required fields
725
+ */
726
+ createAndShareMarginManager(poolInfo: MarginPoolInfo, tx?: Transaction): {
727
+ tx: Transaction;
728
+ margin_manager: {
729
+ $kind: "NestedResult";
730
+ NestedResult: [number, number];
731
+ };
732
+ initializer: {
733
+ $kind: "NestedResult";
734
+ NestedResult: [number, number];
735
+ };
736
+ };
737
+ createMarginManager(poolInfo: MarginPoolInfo, tx?: Transaction): {
738
+ tx: Transaction;
739
+ margin_manager: {
740
+ $kind: "NestedResult";
741
+ NestedResult: [number, number];
742
+ };
743
+ initializer: {
744
+ $kind: "NestedResult";
745
+ NestedResult: [number, number];
746
+ };
747
+ };
748
+ shareMarginManager({ marginManager, initializer, baseCoin, quoteCoin, }: {
749
+ marginManager: TransactionArgument;
750
+ initializer: TransactionArgument;
751
+ baseCoin: MarginCoinInfo;
752
+ quoteCoin: MarginCoinInfo;
753
+ }, tx?: Transaction): Transaction;
754
+ /**
755
+ * Gets all balance managers for an account using GraphQL query.
756
+ * NOTE: This method has known issues and should not be used in production.
757
+ *
758
+ * @deprecated This method has issues and should not be used
759
+ * @param {string} account - The account address to query
760
+ * @returns {Promise<any[]>} Array of balance manager event data
761
+ * @throws {Error} If account is invalid or query fails
762
+ */
763
+ getBalanceManagerByMarginManager(account: string): Promise<any>;
764
+ /**
765
+ * Gets all margin managers created by a specific account.
766
+ *
767
+ * @param {string} account - The account address to query
768
+ * @returns {Promise<any[]>} Array of margin manager information
769
+ * @throws {Error} If account is invalid or query fails
770
+ */
771
+ getMarginManagerByAccount(account: string): Promise<any[]>;
772
+ /**
773
+ * Gets the base coin balance for a margin manager.
774
+ *
775
+ * @param {Object} params - Parameters object
776
+ * @param {string} params.account - The account address
777
+ * @param {string} params.marginManager - The margin manager object ID
778
+ * @param {string} params.baseCoinType - The base coin type
779
+ * @param {string} params.quoteCoinType - The quote coin type
780
+ * @returns {Promise<string>} The base balance as a string
781
+ * @throws {Error} If parameters are invalid or transaction fails
782
+ */
783
+ getBaseBalance({ account, marginManager, baseCoinType, quoteCoinType, }: {
784
+ account: string;
785
+ marginManager: string;
786
+ baseCoinType: string;
787
+ quoteCoinType: string;
788
+ }): Promise<string>;
789
+ /**
790
+ * Gets the quote coin balance for a margin manager.
791
+ *
792
+ * @param {Object} params - Parameters object
793
+ * @param {string} params.account - The account address
794
+ * @param {string} params.marginManager - The margin manager object ID
795
+ * @param {string} params.baseCoinType - The base coin type
796
+ * @param {string} params.quoteCoinType - The quote coin type
797
+ * @returns {Promise<string>} The quote balance as a string
798
+ * @throws {Error} If parameters are invalid or transaction fails
799
+ */
800
+ getQuoteBalance({ account, marginManager, baseCoinType, quoteCoinType, }: {
801
+ account: string;
802
+ marginManager: string;
803
+ baseCoinType: string;
804
+ quoteCoinType: string;
805
+ }): Promise<string>;
806
+ /**
807
+ * Gets the deep coin balance for a margin manager.
808
+ *
809
+ * @param {Object} params - Parameters object
810
+ * @param {string} params.account - The account address
811
+ * @param {string} params.marginManager - The margin manager object ID
812
+ * @param {string} params.baseCoinType - The base coin type
813
+ * @param {string} params.quoteCoinType - The quote coin type
814
+ * @returns {Promise<string>} The base balance as a string
815
+ * @throws {Error} If parameters are invalid or transaction fails
816
+ */
817
+ getDeepBalance({ account, marginManager, baseCoinType, quoteCoinType, }: {
818
+ account: string;
819
+ marginManager: string;
820
+ baseCoinType: string;
821
+ quoteCoinType: string;
822
+ }): Promise<string>;
823
+ /**
824
+ * Gets the borrowed shares (debt) for both base and quote coins.
825
+ *
826
+ * @param {Object} params - Parameters object
827
+ * @param {string} params.account - The account address
828
+ * @param {string} params.marginManager - The margin manager object ID
829
+ * @param {string} params.baseCoinType - The base coin type
830
+ * @param {string} params.quoteCoinType - The quote coin type
831
+ * @returns {Promise<{baseBorrowedShare: bigint, quoteBorrowedShare: bigint}>} Object containing borrowed shares
832
+ * @throws {Error} If parameters are invalid or transaction fails
833
+ */
834
+ getBorrowedShares({ account, marginManager, baseCoinType, quoteCoinType, }: {
835
+ account: string;
836
+ marginManager: string;
837
+ baseCoinType: string;
838
+ quoteCoinType: string;
839
+ }): Promise<{
840
+ baseBorrowedShare: string;
841
+ quoteBorrowedShare: string;
842
+ }>;
843
+ /**
844
+ * Creates a transaction builder function for getting margin manager state.
845
+ * NOTE: This is currently not used in production.
846
+ *
847
+ * @deprecated This method is not currently used
848
+ * @param {Object} params - Parameters object
849
+ * @returns {Function} A function that takes a Transaction and adds the manager state call
850
+ */
851
+ managerState: ({ account, marginManager, baseCoin, quoteCoin, pool, baseMarginPool, quoteMarginPool, decimals, basePriceFeedObjectId, quotePriceFeedObjectId, }: {
852
+ account: string;
853
+ marginManager: string;
854
+ baseCoin: MarginCoinInfo;
855
+ quoteCoin: MarginCoinInfo;
856
+ pool: string;
857
+ baseMarginPool: string;
858
+ quoteMarginPool: string;
859
+ decimals?: number;
860
+ basePriceFeedObjectId: string;
861
+ quotePriceFeedObjectId: string;
862
+ }) => (tx: Transaction) => void;
863
+ /**
864
+ * Gets the complete state of a margin manager including assets, debts, and risk ratio.
865
+ * NOTE: This method is currently not used in production.
866
+ *
867
+ * @deprecated This method is not currently used
868
+ * @param {Object} params - Parameters object
869
+ * @param {string} params.account - The account address
870
+ * @param {string} params.marginManager - The margin manager object ID
871
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
872
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
873
+ * @param {string} params.pool - Pool address
874
+ * @param {string} params.baseMarginPool - Base margin pool address
875
+ * @param {string} params.quoteMarginPool - Quote margin pool address
876
+ * @param {number} [params.decimals=6] - Number of decimal places for formatting
877
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object
878
+ * @returns {Promise<Object>} Manager state object with all financial metrics
879
+ * @throws {Error} If parameters are invalid, feeds are missing, or transaction fails
880
+ */
881
+ getManagerState(params: {
882
+ account: string;
883
+ marginManager: string;
884
+ baseCoin: MarginCoinInfo;
885
+ quoteCoin: MarginCoinInfo;
886
+ pool: string;
887
+ baseMarginPool: string;
888
+ quoteMarginPool: string;
889
+ decimals?: number;
890
+ }, tx?: Transaction): Promise<{
891
+ managerId: string;
892
+ deepbookPoolId: string;
893
+ riskRatio: number;
894
+ baseAsset: string;
895
+ quoteAsset: string;
896
+ baseDebt: string;
897
+ quoteDebt: string;
898
+ basePythPrice: string;
899
+ basePythDecimals: number;
900
+ quotePythPrice: string;
901
+ quotePythDecimals: number;
902
+ currentPrice: bigint;
903
+ lowestTriggerAbovePrice: bigint;
904
+ highestTriggerBelowPrice: bigint;
905
+ }>;
906
+ /**
907
+ * Calculates the current assets (base and quote) for a margin manager.
908
+ *
909
+ * @param {Object} params - Parameters object
910
+ * @param {string} params.account - The account address
911
+ * @param {string} params.marginManager - The margin manager object ID
912
+ * @param {string} params.pool - Pool address
913
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
914
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
915
+ * @param {number} [params.decimals=6] - Number of decimal places (not currently used)
916
+ * @returns {Promise<{baseAsset: string, quoteAsset: string}>} Object containing asset amounts
917
+ * @throws {Error} If parameters are invalid, scalars are missing, or transaction fails
918
+ */
919
+ calculateAssets({ account, marginManager, pool, baseCoin, quoteCoin, decimals, }: {
920
+ account: string;
921
+ marginManager: string;
922
+ pool: string;
923
+ baseCoin: MarginCoinInfo;
924
+ quoteCoin: MarginCoinInfo;
925
+ decimals?: number;
926
+ }): Promise<{
927
+ baseAsset: string;
928
+ quoteAsset: string;
929
+ }>;
930
+ /**
931
+ * Gets the borrowed amount (in tokens, not shares) for a margin manager.
932
+ * Determines whether base or quote has more debt and returns the corresponding amount.
933
+ *
934
+ * @param {Object} params - Parameters object
935
+ * @param {string} params.account - The account address
936
+ * @param {string} params.marginManager - The margin manager object ID
937
+ * @param {string} params.baseCoinType - The base coin type
938
+ * @param {string} params.quoteCoinType - The quote coin type
939
+ * @param {string} params.baseMarginPool - Base margin pool address
940
+ * @param {string} params.quoteMarginPool - Quote margin pool address
941
+ * @returns {Promise<{baseBorrowedAmount: string, quoteBorrowedAmount: string}>} Object containing borrowed amounts
942
+ * @throws {Error} If parameters are invalid or transaction fails
943
+ */
944
+ getBorrowedAmount({ account, marginManager, baseCoinType, quoteCoinType, baseMarginPool, quoteMarginPool, }: {
945
+ account: string;
946
+ marginManager: string;
947
+ baseCoinType: string;
948
+ quoteCoinType: string;
949
+ baseMarginPool: string;
950
+ quoteMarginPool: string;
951
+ }): Promise<{
952
+ baseBorrowedAmount: string;
953
+ quoteBorrowedAmount: string;
954
+ }>;
955
+ /**
956
+ * Deposits tokens (base or quote) into a margin manager.
957
+ *
958
+ * @param {Object} params - Parameters object
959
+ * @param {string} params.marginManager - The margin manager object ID
960
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
961
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
962
+ * @param {boolean} params.isBase - Whether to deposit base coin (true) or quote coin (false)
963
+ * @param {string} params.amount - Amount to deposit (as string to avoid precision loss)
964
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
965
+ * @returns {Promise<Transaction>} The transaction object with deposit operation
966
+ * @throws {Error} If parameters are invalid, feeds are missing, or price feed IDs cannot be obtained
967
+ */
968
+ deposit({ marginManager, baseCoin, quoteCoin, amount, depositCoinType, }: {
969
+ marginManager: string | TransactionArgument;
970
+ baseCoin: MarginCoinInfo;
971
+ quoteCoin: MarginCoinInfo;
972
+ amount: string;
973
+ depositCoinType: string;
974
+ }, tx?: Transaction): Promise<Transaction>;
975
+ /**
976
+ * Withdraws tokens (base or quote) from a margin manager.
977
+ *
978
+ * @param {Object} params - Parameters object
979
+ * @param {string} params.account - The account address to receive the withdrawn tokens
980
+ * @param {string} params.marginManager - The margin manager object ID
981
+ * @param {string} params.baseMarginPool - Base margin pool address
982
+ * @param {string} params.quoteMarginPool - Quote margin pool address
983
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
984
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
985
+ * @param {string} params.pool - Pool address
986
+ * @param {boolean} params.isBase - Whether to withdraw base coin (true) or quote coin (false)
987
+ * @param {string} params.amount - Amount to withdraw (as string to avoid precision loss)
988
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
989
+ * @returns {Promise<Transaction>} The transaction object with withdraw operation
990
+ * @throws {Error} If parameters are invalid, feeds are missing, or price feed IDs cannot be obtained
991
+ */
992
+ withdraw({ account, marginManager, baseMarginPool, quoteMarginPool, baseCoin, quoteCoin, pool, amount, withdrawCoinType, }: {
993
+ account: string;
994
+ marginManager: string;
995
+ baseMarginPool: string;
996
+ quoteMarginPool: string;
997
+ baseCoin: MarginCoinInfo;
998
+ quoteCoin: MarginCoinInfo;
999
+ pool: string;
1000
+ amount: string;
1001
+ withdrawCoinType: string;
1002
+ }, tx?: Transaction): Promise<Transaction>;
1003
+ /**
1004
+ * Borrows base coins from the margin pool.
1005
+ *
1006
+ * @param {Object} params - Parameters object
1007
+ * @param {string} params.marginManager - The margin manager object ID
1008
+ * @param {string} params.baseMarginPool - Base margin pool address
1009
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
1010
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
1011
+ * @param {string} params.pool - Pool address
1012
+ * @param {string} params.amount - Amount to borrow (as string to avoid precision loss)
1013
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1014
+ * @returns {Promise<Transaction>} The transaction object with borrow base operation
1015
+ * @throws {Error} If parameters are invalid, feeds are missing, or price feed IDs cannot be obtained
1016
+ */
1017
+ borrowBase({ marginManager, baseMarginPool, baseCoin, quoteCoin, pool, amount, }: {
1018
+ marginManager: string;
1019
+ baseMarginPool: string;
1020
+ baseCoin: MarginCoinInfo;
1021
+ quoteCoin: MarginCoinInfo;
1022
+ pool: string;
1023
+ amount: string;
1024
+ }, tx?: Transaction): Promise<Transaction>;
1025
+ /**
1026
+ * Borrows quote coins from the margin pool.
1027
+ *
1028
+ * @param {Object} params - Parameters object
1029
+ * @param {string} params.marginManager - The margin manager object ID
1030
+ * @param {string} params.quoteMarginPool - Quote margin pool address
1031
+ * @param {MarginCoinInfo} params.baseCoin - Base coin information
1032
+ * @param {MarginCoinInfo} params.quoteCoin - Quote coin information
1033
+ * @param {string} params.pool - Pool address
1034
+ * @param {string} params.amount - Amount to borrow (as string to avoid precision loss)
1035
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1036
+ * @returns {Promise<Transaction>} The transaction object with borrow quote operation
1037
+ * @throws {Error} If parameters are invalid, feeds are missing, or price feed IDs cannot be obtained
1038
+ */
1039
+ borrowQuote({ marginManager, quoteMarginPool, baseCoin, quoteCoin, pool, amount, }: {
1040
+ marginManager: string | TransactionArgument;
1041
+ quoteMarginPool: string;
1042
+ baseCoin: MarginCoinInfo;
1043
+ quoteCoin: MarginCoinInfo;
1044
+ pool: string;
1045
+ amount: string;
1046
+ }, tx?: Transaction): Promise<Transaction>;
1047
+ /**
1048
+ * Repays borrowed base coins to the margin pool.
1049
+ * If amount is not specified, repays all debt.
1050
+ *
1051
+ * @param {Object} params - Parameters object
1052
+ * @param {string} params.marginManager - The margin manager object ID
1053
+ * @param {string} params.baseMarginPool - Base margin pool address
1054
+ * @param {string} params.baseCoinType - The base coin type
1055
+ * @param {string} params.quoteCoinType - The quote coin type
1056
+ * @param {string} [params.amount] - Optional amount to repay (if not provided, repays all)
1057
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1058
+ * @returns {Transaction} The transaction object with repay base operation
1059
+ * @throws {Error} If parameters are invalid
1060
+ */
1061
+ repayBase({ marginManager, baseMarginPool, baseCoin, quoteCoin, amount, }: {
1062
+ marginManager: string;
1063
+ baseMarginPool: string;
1064
+ baseCoin: MarginCoinInfo;
1065
+ quoteCoin: MarginCoinInfo;
1066
+ amount?: string;
1067
+ }, tx?: Transaction): Promise<Transaction>;
1068
+ /**
1069
+ * Repays borrowed quote coins to the margin pool.
1070
+ * If amount is not specified, repays all debt.
1071
+ *
1072
+ * @param {Object} params - Parameters object
1073
+ * @param {string} params.marginManager - The margin manager object ID
1074
+ * @param {string} params.quoteMarginPool - Quote margin pool address
1075
+ * @param {string} params.baseCoinType - The base coin type
1076
+ * @param {string} params.quoteCoinType - The quote coin type
1077
+ * @param {string} [params.amount] - Optional amount to repay (if not provided, repays all)
1078
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1079
+ * @returns {Transaction} The transaction object with repay quote operation
1080
+ * @throws {Error} If parameters are invalid
1081
+ */
1082
+ repayQuote({ marginManager, quoteMarginPool, baseCoin, quoteCoin, amount, }: {
1083
+ marginManager: string;
1084
+ quoteMarginPool: string;
1085
+ baseCoin: MarginCoinInfo;
1086
+ quoteCoin: MarginCoinInfo;
1087
+ amount?: string;
1088
+ }, tx?: Transaction): Promise<Transaction>;
1089
+ repay({ marginManager, baseMarginPool, quoteMarginPool, baseCoin, quoteCoin, isBase, amount, }: {
1090
+ marginManager: string;
1091
+ baseMarginPool: string;
1092
+ quoteMarginPool: string;
1093
+ baseCoin: MarginCoinInfo;
1094
+ quoteCoin: MarginCoinInfo;
1095
+ isBase: boolean;
1096
+ amount?: string;
1097
+ }, tx?: Transaction): Promise<Transaction>;
1098
+ /**
1099
+ * Places a market order for margin trading.
1100
+ * Market orders are executed immediately at the current market price.
1101
+ *
1102
+ * @param {Object} params - Parameters object
1103
+ * @param {string} params.marginManager - The margin manager object ID
1104
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1105
+ * @param {SelfMatchingOption} params.selfMatchingOption - Self-matching behavior option
1106
+ * @param {string} params.quantity - Order quantity
1107
+ * @param {boolean} params.isBid - Whether this is a buy order (true) or sell order (false)
1108
+ * @param {boolean} params.payWithDeep - Whether to pay with DEEP tokens
1109
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1110
+ * @returns {Promise<Transaction>} The transaction object with market order operation
1111
+ * @throws {Error} If parameters are invalid or decimals are missing
1112
+ */
1113
+ placeMarginMarketOrder({ marginManager, poolInfo, selfMatchingOption, quantity, amountLimit, isBid, payWithDeep, exactBase }: {
1114
+ marginManager: string | TransactionArgument;
1115
+ poolInfo: MarginPoolInfo;
1116
+ selfMatchingOption: SelfMatchingOption;
1117
+ quantity: string;
1118
+ amountLimit: string;
1119
+ isBid: boolean;
1120
+ payWithDeep: boolean;
1121
+ exactBase?: boolean;
1122
+ }, tx?: Transaction): Promise<Transaction>;
1123
+ /**
1124
+ * Places a limit order for margin trading.
1125
+ * Limit orders are executed only when the market price reaches the specified limit price.
1126
+ *
1127
+ * @param {Object} params - Parameters object
1128
+ * @param {string} params.marginManager - The margin manager object ID
1129
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1130
+ * @param {OrderType} params.orderType - Order type (0=NO_RESTRICTION, 1=IMMEDIATE_OR_CANCEL, 2=FILL_OR_KILL, 3=POST_ONLY)
1131
+ * @param {SelfMatchingOption} params.selfMatchingOption - Self-matching behavior option (0=SELF_MATCHING_ALLOWED, 1=CANCEL_TAKER, 2=CANCEL_MAKER)
1132
+ * @param {string} params.priceInput - Limit price as a string
1133
+ * @param {string} params.quantity - Order quantity
1134
+ * @param {boolean} params.isBid - Whether this is a buy order (true) or sell order (false)
1135
+ * @param {boolean} params.payWithDeep - Whether to pay with DEEP tokens
1136
+ * @param {number} [params.expirationTimestamp] - Optional expiration timestamp (defaults to current time + default expiration)
1137
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1138
+ * @returns {Promise<Transaction>} The transaction object with limit order operation
1139
+ * @throws {Error} If parameters are invalid or decimals are missing
1140
+ */
1141
+ placeMarginLimitOrder({ marginManager, poolInfo, orderType, selfMatchingOption, priceInput, quantity, isBid, payWithDeep, expirationTimestamp, }: {
1142
+ marginManager: string;
1143
+ poolInfo: MarginPoolInfo;
1144
+ orderType: OrderType;
1145
+ selfMatchingOption: SelfMatchingOption;
1146
+ priceInput: string;
1147
+ quantity: string;
1148
+ isBid: boolean;
1149
+ payWithDeep: boolean;
1150
+ expirationTimestamp?: number;
1151
+ }, tx?: Transaction): Promise<Transaction>;
1152
+ /**
1153
+ * Modifies an existing margin order by updating its quantity.
1154
+ *
1155
+ * @param {Object} params - Parameters object
1156
+ * @param {string} params.marginManager - The margin manager object ID
1157
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1158
+ * @param {string} params.orderId - The order ID to modify
1159
+ * @param {string} params.newQuantity - New quantity for the order
1160
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1161
+ * @returns {Transaction} The transaction object with modify order operation
1162
+ * @throws {Error} If parameters are invalid or base coin decimals are missing
1163
+ */
1164
+ modifyMarginOrder({ marginManager, poolInfo, orderId, newQuantity, }: {
1165
+ marginManager: string;
1166
+ poolInfo: MarginPoolInfo;
1167
+ orderId: string;
1168
+ newQuantity: string;
1169
+ }, tx?: Transaction): Transaction;
1170
+ /**
1171
+ * Cancels a specific margin order.
1172
+ *
1173
+ * @param {Object} params - Parameters object
1174
+ * @param {string} params.marginManager - The margin manager object ID
1175
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1176
+ * @param {string} params.orderId - The order ID to cancel
1177
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1178
+ * @returns {Transaction} The transaction object with cancel order operation
1179
+ * @throws {Error} If parameters are invalid
1180
+ */
1181
+ cancelMarginOrder({ marginManager, poolInfo, orderId, }: {
1182
+ marginManager: string;
1183
+ poolInfo: MarginPoolInfo;
1184
+ orderId: string;
1185
+ }, tx?: Transaction): Transaction;
1186
+ /**
1187
+ * Cancels all margin orders for a specific pool.
1188
+ *
1189
+ * @param {Object} params - Parameters object
1190
+ * @param {string} params.marginManager - The margin manager object ID
1191
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1192
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1193
+ * @returns {Transaction} The transaction object with cancel all orders operation
1194
+ * @throws {Error} If parameters are invalid
1195
+ */
1196
+ cancelAllMarginOrders({ marginManager, poolInfo, }: {
1197
+ marginManager: string;
1198
+ poolInfo: MarginPoolInfo;
1199
+ }, tx?: Transaction): Transaction;
1200
+ placeReduceOnlyLimitOrder({ marginManager, poolInfo, marginPoolId, orderType, selfMatchingOption, priceInput, quantity, isBid, payWithDeep, expirationTimestamp, }: {
1201
+ marginManager: string;
1202
+ poolInfo: MarginPoolInfo;
1203
+ marginPoolId: string;
1204
+ orderType: OrderType;
1205
+ selfMatchingOption: SelfMatchingOption;
1206
+ priceInput: string;
1207
+ quantity: string;
1208
+ isBid: boolean;
1209
+ payWithDeep: boolean;
1210
+ expirationTimestamp: number;
1211
+ }, tx?: Transaction): Transaction;
1212
+ placeReduceOnlyMarketOrder({ marginManager, poolInfo, marginPoolId, selfMatchingOption, quantity, isBid, payWithDeep, }: {
1213
+ marginManager: string;
1214
+ poolInfo: MarginPoolInfo;
1215
+ marginPoolId: string;
1216
+ orderType: OrderType;
1217
+ selfMatchingOption: SelfMatchingOption;
1218
+ quantity: string;
1219
+ isBid: boolean;
1220
+ payWithDeep: boolean;
1221
+ expirationTimestamp: number;
1222
+ }, tx?: Transaction): Transaction;
1223
+ getAccountOpenOrders({ poolInfo, marginManager }: {
1224
+ poolInfo: PoolInfo;
1225
+ marginManager: string;
1226
+ }): Promise<any>;
1227
+ getAccountAllMarketsOpenOrders(account: string, pools: any): Promise<any[]>;
1228
+ mintSupplierCap(tx: Transaction | undefined, hasTransfer: boolean): {
1229
+ tx: Transaction;
1230
+ supplierCap: TransactionResult;
1231
+ };
1232
+ querySupplierCap(): Promise<any>;
1233
+ mintSupplierCapAndSupply({ marginPool, supplyCoinType, amount }: {
1234
+ marginPool: string;
1235
+ supplyCoinType: string;
1236
+ amount: string;
1237
+ }): Transaction;
1238
+ supply({ marginPool, supplierCap, supplyCoinType, amount, tx, }: {
1239
+ marginPool: string;
1240
+ supplierCap?: TransactionResult | string;
1241
+ supplyCoinType: string;
1242
+ amount: string;
1243
+ tx?: Transaction;
1244
+ }): Transaction;
1245
+ supplierWithdraw({ marginPool, withdrawCoinType, amount, supplierCapId, hasSwap, withdrawAll, tx, }: {
1246
+ marginPool: string;
1247
+ supplierCapId?: string;
1248
+ withdrawCoinType: string;
1249
+ amount: string;
1250
+ hasSwap: boolean;
1251
+ withdrawAll: boolean;
1252
+ tx?: Transaction;
1253
+ }): Transaction | TransactionResult;
1254
+ withdrawReferralFees({ marginPool }: {
1255
+ marginPool: string;
1256
+ }): Transaction;
1257
+ getUserSupplyAmount({ marginPool, supplyCoin, supplierCapId, }: {
1258
+ marginPool: string;
1259
+ supplyCoin: MarginCoinInfo;
1260
+ supplierCapId: string;
1261
+ }): Promise<string>;
1262
+ getDeepBookMarginRegistry(): Promise<{
1263
+ pool_registry_table_id: any;
1264
+ margin_pool_table_id: any;
1265
+ }>;
1266
+ getDeepBookPool(): Promise<{
1267
+ id: any;
1268
+ name: any;
1269
+ base_margin_pool_id: any;
1270
+ quote_margin_pool_id: any;
1271
+ enabled: any;
1272
+ pool_liquidation_reward: any;
1273
+ user_liquidation_reward: any;
1274
+ liquidation_risk_ratio: any;
1275
+ min_borrow_risk_ratio: any;
1276
+ min_withdraw_risk_ratio: any;
1277
+ target_liquidation_risk_ratio: any;
1278
+ }[]>;
1279
+ getDeepBookMarginPool(): Promise<{
1280
+ deposit_coin_type: any;
1281
+ id: any;
1282
+ supply_cap: any;
1283
+ total_supply: any;
1284
+ total_borrow: any;
1285
+ available_supply: string;
1286
+ max_utilization_rate: any;
1287
+ min_borrow: any;
1288
+ protocol_spread: any;
1289
+ maintainer_fees: any;
1290
+ protocol_fees: any;
1291
+ }[]>;
1292
+ getBaseQuantityOutInput(poolInfo: any, quantity: string, payWithDeep: boolean): Promise<{
1293
+ base_amount: string;
1294
+ quote_amount: string;
1295
+ deep_fee_amount: string;
1296
+ }>;
1297
+ getQuoteQuantityOutInput(poolInfo: any, quantity: string): Promise<{
1298
+ base_amount: string;
1299
+ quote_amount: string;
1300
+ deep_fee_amount: string;
1301
+ }>;
1302
+ getAccount(marginManager: string, poolInfo: any): Promise<StateAccount[] | null>;
1303
+ withdrawSettledAmounts({ poolInfo, marginManager, }: {
1304
+ poolInfo: any;
1305
+ marginManager: string;
1306
+ }, tx?: Transaction): Promise<Transaction>;
1307
+ /**
1308
+ * Gets the margin pool state with all fields needed for interest calculation.
1309
+ * This method fetches the complete pool state including interest config, borrow/supply shares, and timestamps.
1310
+ *
1311
+ * @param {string} marginPoolId - The margin pool object ID
1312
+ * @returns {Promise<Object>} The complete margin pool state for interest calculation
1313
+ */
1314
+ getMarginPoolStateForInterest(marginPoolId: string): Promise<{
1315
+ poolState: {
1316
+ total_supply: bigint;
1317
+ total_borrow: bigint;
1318
+ supply_shares: bigint;
1319
+ borrow_shares: bigint;
1320
+ last_update_timestamp: bigint;
1321
+ };
1322
+ interestConfig: {
1323
+ base_rate: bigint;
1324
+ base_slope: bigint;
1325
+ optimal_utilization: bigint;
1326
+ excess_slope: bigint;
1327
+ };
1328
+ marginPoolConfig: {
1329
+ protocol_spread: bigint;
1330
+ max_utilization_rate: bigint;
1331
+ min_borrow: bigint;
1332
+ supply_cap: bigint;
1333
+ };
1334
+ }>;
1335
+ /**
1336
+ * Gets the current chain timestamp from the Sui network.
1337
+ * Use this timestamp for interest calculations instead of local Date.now().
1338
+ *
1339
+ * This method fetches the latest checkpoint and returns its timestamp,
1340
+ * which represents the most recent confirmed on-chain time.
1341
+ *
1342
+ * @returns {Promise<bigint>} The current chain timestamp in milliseconds
1343
+ */
1344
+ getChainTimestamp(): Promise<bigint>;
1345
+ }
1346
+
1347
+ /**
1348
+ * Represents a module for making RPC (Remote Procedure Call) requests.
1349
+ */
1350
+ declare class RpcModule extends SuiClient {
1351
+ /**
1352
+ * Get events for a given query criteria
1353
+ * @param query
1354
+ * @param paginationArgs
1355
+ * @returns
1356
+ */
1357
+ queryEventsByPage(query: SuiEventFilter, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1358
+ /**
1359
+ * Get all objects owned by an address
1360
+ * @param owner
1361
+ * @param query
1362
+ * @param paginationArgs
1363
+ * @returns
1364
+ */
1365
+ getOwnedObjectsByPage(owner: string, query: SuiObjectResponseQuery, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1366
+ /**
1367
+ * Return the list of dynamic field objects owned by an object
1368
+ * @param parentId
1369
+ * @param paginationArgs
1370
+ * @returns
1371
+ */
1372
+ getDynamicFieldsByPage(parentId: SuiObjectIdType, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1373
+ /**
1374
+ * Batch get details about a list of objects. If any of the object ids are duplicates the call will fail
1375
+ * @param ids
1376
+ * @param options
1377
+ * @param limit
1378
+ * @returns
1379
+ */
1380
+ batchGetObjects(ids: SuiObjectIdType[], options?: SuiObjectDataOptions, limit?: number): Promise<any[]>;
1381
+ /**
1382
+ * Calculates the gas cost of a transaction block.
1383
+ * @param {Transaction} tx - The transaction block to calculate gas for.
1384
+ * @returns {Promise<number>} - The estimated gas cost of the transaction block.
1385
+ * @throws {Error} - Throws an error if the sender is empty.
1386
+ */
1387
+ calculationTxGas(tx: Transaction): Promise<number>;
1388
+ /**
1389
+ * Sends a transaction block after signing it with the provided keypair.
1390
+ *
1391
+ * @param {Ed25519Keypair | Secp256k1Keypair} keypair - The keypair used for signing the transaction.
1392
+ * @param {Transaction} tx - The transaction block to send.
1393
+ * @returns {Promise<SuiTransactionBlockResponse | undefined>} - The response of the sent transaction block.
1394
+ */
1395
+ sendTransaction(keypair: Ed25519Keypair | Secp256k1Keypair, tx: Transaction): Promise<SuiTransactionBlockResponse | undefined>;
1396
+ }
1397
+
687
1398
  /**
688
1399
  * Represents options and configurations for an SDK.
689
1400
  */
@@ -693,6 +1404,8 @@ type SdkOptions = {
693
1404
  * The full URL for interacting with the RPC (Remote Procedure Call) service.
694
1405
  */
695
1406
  fullRpcUrl: string;
1407
+ graphqlUrl: string;
1408
+ pythUrl: string;
696
1409
  /**
697
1410
  * Configuration for the simulation account.
698
1411
  */
@@ -705,6 +1418,8 @@ type SdkOptions = {
705
1418
  deepbook: {
706
1419
  package_id: string;
707
1420
  published_at: string;
1421
+ margin_package_id: string;
1422
+ margin_published_at: string;
708
1423
  registry_id: string;
709
1424
  };
710
1425
  deepbook_utils: {
@@ -714,6 +1429,19 @@ type SdkOptions = {
714
1429
  cetus_balance_manager_indexer_id: string;
715
1430
  vault_global_config_id?: string;
716
1431
  };
1432
+ margin_utils: {
1433
+ package_id: string;
1434
+ published_at: string;
1435
+ registry_id: string;
1436
+ margin_registry_id: string;
1437
+ wormhole_state_id: string;
1438
+ pyth_state_id: string;
1439
+ global_config_id: string;
1440
+ versioned_id: string;
1441
+ admin_cap_id: string;
1442
+ pool_registry_table_id: string;
1443
+ margin_pool_table_id: string;
1444
+ };
717
1445
  DEEP_COIN: {
718
1446
  coinType: string;
719
1447
  decimals: number;
@@ -733,6 +1461,9 @@ declare class DeepbookUtilsSDK {
733
1461
  */
734
1462
  protected _rpcModule: RpcModule;
735
1463
  protected _deepbookUtils: any;
1464
+ protected _marginUtils: any;
1465
+ protected _pythPrice: PythPriceModule;
1466
+ protected _graphqlClient: SuiGraphQLClient;
736
1467
  /**
737
1468
  * Provide sdk options
738
1469
  */
@@ -753,11 +1484,14 @@ declare class DeepbookUtilsSDK {
753
1484
  */
754
1485
  set senderAddress(value: string);
755
1486
  get DeepbookUtils(): DeepbookUtilsModule;
1487
+ get MarginUtils(): MarginUtilsModule;
1488
+ get PythPrice(): PythPriceModule;
756
1489
  /**
757
1490
  * Getter for the fullClient property.
758
1491
  * @returns {RpcModule} The fullClient property value.
759
1492
  */
760
1493
  get fullClient(): RpcModule;
1494
+ get graphqlClient(): SuiGraphQLClient;
761
1495
  /**
762
1496
  * Getter for the sdkOptions property.
763
1497
  * @returns {SdkOptions} The sdkOptions property value.
@@ -966,6 +1700,123 @@ declare function secretKeyToEd25519Keypair(secretKey: string | Uint8Array, ecode
966
1700
  declare function secretKeyToSecp256k1Keypair(secretKey: string | Uint8Array, ecode?: 'hex' | 'base64'): Secp256k1Keypair;
967
1701
  declare const sleepTime: (s: number) => Promise<unknown>;
968
1702
 
1703
+ declare const calculateRiskRatio: ({ totalAssetsValue, totalDebtValue }: {
1704
+ totalAssetsValue: string;
1705
+ totalDebtValue: string;
1706
+ }) => string;
1707
+ declare const wrapDeepBookPoolInfo: (poolInfo: any) => {
1708
+ id: any;
1709
+ name: any;
1710
+ base_margin_pool_id: any;
1711
+ quote_margin_pool_id: any;
1712
+ enabled: any;
1713
+ pool_liquidation_reward: any;
1714
+ user_liquidation_reward: any;
1715
+ liquidation_risk_ratio: any;
1716
+ min_borrow_risk_ratio: any;
1717
+ min_withdraw_risk_ratio: any;
1718
+ target_liquidation_risk_ratio: any;
1719
+ };
1720
+ declare const wrapDeepBookMarginPoolInfo: (marginPoolInfo: any, baseInfo: any) => {
1721
+ deposit_coin_type: any;
1722
+ id: any;
1723
+ supply_cap: any;
1724
+ total_supply: any;
1725
+ total_borrow: any;
1726
+ available_supply: string;
1727
+ max_utilization_rate: any;
1728
+ min_borrow: any;
1729
+ protocol_spread: any;
1730
+ maintainer_fees: any;
1731
+ protocol_fees: any;
1732
+ };
1733
+
1734
+ declare const FLOAT_SCALING = 1000000000n;
1735
+ declare const YEAR_MS: bigint;
1736
+ interface PoolState {
1737
+ total_supply: bigint;
1738
+ total_borrow: bigint;
1739
+ supply_shares: bigint;
1740
+ borrow_shares: bigint;
1741
+ last_update_timestamp: bigint;
1742
+ }
1743
+ interface InterestConfig {
1744
+ base_rate: bigint;
1745
+ base_slope: bigint;
1746
+ optimal_utilization: bigint;
1747
+ excess_slope: bigint;
1748
+ }
1749
+ interface MarginPoolConfig {
1750
+ protocol_spread: bigint;
1751
+ }
1752
+ interface UserBorrowInfo {
1753
+ borrow_shares: bigint;
1754
+ }
1755
+ interface DebtDetail {
1756
+ confirmedDebt: bigint;
1757
+ estimatedInterest: bigint;
1758
+ totalDebt: bigint;
1759
+ annualInterestRate: bigint;
1760
+ }
1761
+ /**
1762
+ * 计算资金利用率
1763
+ *
1764
+ * 公式: 利用率 = total_borrow / total_supply
1765
+ */
1766
+ declare function calcUtilizationRate(total_borrow: bigint, total_supply: bigint): bigint;
1767
+ /**
1768
+ * 计算利率(分段线性模型)
1769
+ *
1770
+ * 利率曲线:
1771
+ * - 当利用率 < optimal_utilization: base_rate + utilization_rate * base_slope / FLOAT_SCALING
1772
+ * - 当利用率 >= optimal_utilization: base_rate + base_portion + excess_portion
1773
+ */
1774
+ declare function calcInterestRate(utilization_rate: bigint, config: InterestConfig): bigint;
1775
+ /**
1776
+ * 乘法向上取整
1777
+ */
1778
+ declare function mulRoundUp(x: bigint, y: bigint): bigint;
1779
+ /**
1780
+ * 计算用户债务详情(核心函数)
1781
+ *
1782
+ * 将债务拆分为:已确认债务 + 预估利息
1783
+ *
1784
+ * 公式:
1785
+ * - 已确认债务 = user_borrow_shares × (total_borrow / borrow_shares)
1786
+ * - 全池预估利息 = total_borrow × 利率 × 时间间隔 / 一年毫秒数
1787
+ * - 用户预估利息 = 全池预估利息 × (user_borrow_shares / borrow_shares)
1788
+ * - 总债务 = 已确认债务 + 用户预估利息
1789
+ *
1790
+ * @param user_borrow_shares - 用户的借款份额
1791
+ * @param pool - 池子状态
1792
+ * @param interest_config - 利息配置
1793
+ * @param current_timestamp_ms - 当前时间戳(毫秒)
1794
+ * @returns DebtDetail - 债务详情
1795
+ */
1796
+ declare function calcDebtDetail(user_borrow_shares: bigint, pool: PoolState, interest_config: InterestConfig, current_timestamp_ms: bigint): DebtDetail;
1797
+ /**
1798
+ * 计算 100% 还款金额
1799
+ *
1800
+ * 通过额外计算一段时间的利息来确保还款充足(覆盖交易确认时间)
1801
+ *
1802
+ * 公式: 100% 还款金额 = calcDebtDetail(链上时间 + extra_time_ms).totalDebt
1803
+ *
1804
+ * 优势(相比旧方案 confirmedDebt + estimatedInterest × 1.2):
1805
+ * - 基于实际利率计算,而非固定的 1.2 倍系数
1806
+ * - 低利率时不会多收太多,高利率时能提供足够缓冲
1807
+ * - 1 分钟足够覆盖 Sui 网络的交易确认时间
1808
+ *
1809
+ * 注意:必须传入链上时间戳,不要使用 Date.now(),避免用户本地时间与链上时间不同步
1810
+ *
1811
+ * @param user_borrow_shares - 用户的借款份额
1812
+ * @param pool - 池子状态
1813
+ * @param interest_config - 利息配置
1814
+ * @param chain_timestamp_ms - 链上时间戳(毫秒),通过 SDK 的 getChainTimestamp() 获取
1815
+ * @param extra_time_ms - 额外计算的时间(毫秒),默认 1 分钟 (60_000n)
1816
+ * @returns bigint - 100% 还款金额
1817
+ */
1818
+ declare function calc100PercentRepay(user_borrow_shares: bigint, pool: PoolState, interest_config: InterestConfig, chain_timestamp_ms: bigint, extra_time_ms?: bigint): bigint;
1819
+
969
1820
  declare const DEFAULT_GAS_BUDGET_FOR_SPLIT = 1000;
970
1821
  declare const DEFAULT_GAS_BUDGET_FOR_MERGE = 500;
971
1822
  declare const DEFAULT_GAS_BUDGET_FOR_TRANSFER = 100;
@@ -1094,4 +1945,4 @@ declare class CoinAssist {
1094
1945
  static buildCoinWithBalance(amount: bigint, coin_type: string, tx: Transaction): TransactionObjectArgument;
1095
1946
  }
1096
1947
 
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 };
1948
+ export { AdjustResult, Balances, BigNumber, BuildCoinResult, CLOCK_ADDRESS, CachedContent, DeepbookUtilsSDK as CetusClmmSDK, ClmmExpectSwapModule, ClmmFetcherModule, ClmmIntegratePoolModule, ClmmIntegratePoolV2Module, ClmmIntegrateRouterModule, ClmmIntegrateRouterWithPartnerModule, ClmmIntegrateUtilsModule, CoinAsset, CoinAssist, CoinConfig, CoinInfoAddress, CoinStoreAddress, DEEP_SCALAR, DEFAULT_GAS_BUDGET_FOR_MERGE, DEFAULT_GAS_BUDGET_FOR_SPLIT, DEFAULT_GAS_BUDGET_FOR_STAKE, DEFAULT_GAS_BUDGET_FOR_TRANSFER, DEFAULT_GAS_BUDGET_FOR_TRANSFER_SUI, DEFAULT_NFT_TRANSFER_GAS_FEE, DataPage, DebtDetail, DeepCoin, DeepbookClobV2Moudle, DeepbookCustodianV2Moudle, DeepbookEndpointsV2Moudle, DeepbookUtilsModule, FLOAT_SCALAR, FLOAT_SCALING, GAS_SYMBOL, GAS_TYPE_ARG, GAS_TYPE_ARG_LONG, InterestConfig, MarginCoinInfo, MarginPoolConfig, MarginPoolInfo, MarginUtilsModule, NFT, NORMALIZED_SUI_COIN_TYPE, OrderDeepPrice, OrderFee, OrderType, Package, PageQuery, PaginationArgs, PoolInfo, PoolState, RpcModule, SUI_SYSTEM_STATE_OBJECT_ID, SdkOptions, SelfMatchingOption, StateAccount, SuiAddressType, SuiBasicTypes, SuiInputTypes, SuiObjectDataWithContent, SuiObjectIdType, SuiResource, SuiStructTag, SuiTxArg, Token, TransactionUtil, UserBorrowInfo, YEAR_MS, addHexPrefix, asIntN, asUintN, bufferToHex, cacheTime1min, cacheTime24h, cacheTime5min, calc100PercentRepay, calcDebtDetail, calcInterestRate, calcUtilizationRate, calculateRiskRatio, checkAddress, composeType, d, decimalsMultiplier, DeepbookUtilsSDK as default, extractAddressFromType, extractStructTagFromType, fixCoinType, fixDown, fixSuiObjectId, fromDecimalsAmount, getDefaultSuiInputType, getFutureTime, getMoveObject, getMoveObjectType, getMovePackageContent, getObjectDeletedResponse, getObjectDisplay, getObjectFields, getObjectId, getObjectNotExistsResponse, getObjectOwner, getObjectPreviousTransactionDigest, getObjectReference, getObjectType, getObjectVersion, getSuiObjectData, hasPublicTransfer, hexToNumber, hexToString, isSortedSymbols, isSuiObjectResponse, maxDecimal, mulRoundUp, normalizeCoinType, patchFixSuiObjectId, printTransaction, removeHexPrefix, secretKeyToEd25519Keypair, secretKeyToSecp256k1Keypair, shortAddress, shortString, sleepTime, toBuffer, toDecimalsAmount, utf8to16, wrapDeepBookMarginPoolInfo, wrapDeepBookPoolInfo };