@cetusprotocol/deepbook-utils 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,16 @@
1
- import { CoinBalance } from '@mysten/sui/dist/cjs/client/types/coins';
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';
2
3
  import * as _mysten_sui_transactions from '@mysten/sui/transactions';
3
- import { TransactionArgument, Transaction } from '@mysten/sui/transactions';
4
- 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';
5
6
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
6
7
  import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1';
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,15 +360,15 @@ 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
- }): Transaction;
366
+ }, tx?: Transaction): Transaction;
399
367
  /**
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>;
@@ -419,7 +387,7 @@ declare class DeepbookUtilsModule implements IModule {
419
387
  /**
420
388
  * Queries on-chain events to retrieve known pools.
421
389
  */
422
- getPools(): Promise<any>;
390
+ getPools(forceRefresh?: boolean): Promise<any>;
423
391
  /**
424
392
  * Estimates quote quantity output for a given base amount.
425
393
  */
@@ -461,6 +429,8 @@ declare class DeepbookUtilsModule implements IModule {
461
429
  quoteOut: number;
462
430
  deepRequired: number;
463
431
  }>;
432
+ getReferencePool(poolInfo: any): Promise<any>;
433
+ updateDeepPrice(poolInfo: any, tx: any): Promise<any>;
464
434
  /**
465
435
  * Estimates taker and maker fees for a prospective trade.
466
436
  */
@@ -468,7 +438,7 @@ declare class DeepbookUtilsModule implements IModule {
468
438
  /**
469
439
  * Retrieves the deep price information required for fee calculation.
470
440
  */
471
- getOrderDeepPrice(poolInfo: any): Promise<OrderDeepPrice | null>;
441
+ getOrderDeepPrice(poolInfo: any, canUpdateDeepPrice?: boolean): Promise<OrderDeepPrice | null>;
472
442
  /**
473
443
  * Parses a serialized `OrderDeepPrice` struct from Move into a JS object.
474
444
  */
@@ -480,7 +450,7 @@ declare class DeepbookUtilsModule implements IModule {
480
450
  /**
481
451
  * Retrieves balances related to an upcoming transaction to determine deposit needs.
482
452
  */
483
- getTransactionRelatedBalance(poolInfo: any, baseAmount: string, quoteAmount: string, noDeep: boolean, account: string, payWithDeep: boolean, balanceManager: string): Promise<{
453
+ getTransactionRelatedBalance(poolInfo: any, baseCoinType: string, quoteCoinType: string, noDeep: boolean, account: string, payWithDeep: boolean, balanceManager: string): Promise<{
484
454
  baseManagerBlance: any;
485
455
  quoteManagerBlance: any;
486
456
  feeManaerBalance: any;
@@ -507,7 +477,10 @@ declare class DeepbookUtilsModule implements IModule {
507
477
  /**
508
478
  * Prepares assets necessary to execute a market order transaction.
509
479
  */
510
- getMarketTransactionRelatedAssets(poolInfo: any, baseAmount: string, quoteAmount: string, maxFee: string, isBid: boolean, account: string, payWithDeep: boolean, balanceManager: string, txb: Transaction): Promise<{
480
+ getMarketTransactionRelatedAssets(poolInfo: any, baseAmount: string, quoteAmount: string, maxFee: string, isBid: boolean, account: string, payWithDeep: boolean, balanceManager: string, txb: Transaction, settled_balances?: {
481
+ base: string;
482
+ quote: string;
483
+ }): Promise<{
511
484
  baseAsset: any;
512
485
  quoteAsset: any;
513
486
  feeAsset: any;
@@ -515,7 +488,7 @@ declare class DeepbookUtilsModule implements IModule {
515
488
  /**
516
489
  * Creates a transaction that deposits required assets and then places a limit order.
517
490
  */
518
- createDepositThenPlaceLimitOrder({ poolInfo, priceInput, quantity, orderType, isBid, maxFee, account, payWithDeep, expirationTimestamp }: {
491
+ createDepositThenPlaceLimitOrder({ poolInfo, priceInput, quantity, orderType, isBid, maxFee, account, payWithDeep, expirationTimestamp, }: {
519
492
  poolInfo: PoolInfo;
520
493
  priceInput: string;
521
494
  quantity: string;
@@ -530,7 +503,7 @@ declare class DeepbookUtilsModule implements IModule {
530
503
  /**
531
504
  * Creates a transaction that deposits necessary assets and places a market order.
532
505
  */
533
- createDepositThenPlaceMarketOrder({ poolInfo, quantity, isBid, maxFee, account, payWithDeep, slippage }: {
506
+ createDepositThenPlaceMarketOrder({ poolInfo, quantity, isBid, maxFee, account, payWithDeep, slippage, }: {
534
507
  poolInfo: any;
535
508
  quantity: string;
536
509
  isBid: boolean;
@@ -542,7 +515,7 @@ declare class DeepbookUtilsModule implements IModule {
542
515
  /**
543
516
  * Builds a transaction to place a limit order and handles required deposits.
544
517
  */
545
- placeLimitOrder({ balanceManager, poolInfo, priceInput, quantity, isBid, orderType, maxFee, account, payWithDeep, expirationTimestamp }: {
518
+ placeLimitOrder({ balanceManager, poolInfo, priceInput, quantity, isBid, orderType, maxFee, account, payWithDeep, expirationTimestamp, }: {
546
519
  balanceManager: string;
547
520
  poolInfo: any;
548
521
  priceInput: string;
@@ -569,7 +542,7 @@ declare class DeepbookUtilsModule implements IModule {
569
542
  /**
570
543
  * Builds a transaction to place a market order, handling deposits as needed.
571
544
  */
572
- placeMarketOrder({ balanceManager, poolInfo, baseQuantity, quoteQuantity, isBid, maxFee, account, payWithDeep, slippage }: {
545
+ placeMarketOrder({ balanceManager, poolInfo, baseQuantity, quoteQuantity, isBid, maxFee, account, payWithDeep, slippage, settled_balances, }: {
573
546
  balanceManager: string;
574
547
  poolInfo: PoolInfo;
575
548
  baseQuantity: string;
@@ -579,15 +552,23 @@ declare class DeepbookUtilsModule implements IModule {
579
552
  account: string;
580
553
  payWithDeep: boolean;
581
554
  slippage?: number;
555
+ settled_balances?: {
556
+ base: string;
557
+ quote: string;
558
+ };
582
559
  }): Promise<any>;
583
- getOrderInfoList(poolInfo: any, orderIds: string[], account: string): Promise<any>;
560
+ getOrderInfoList(baseOrderList: {
561
+ orderId: string;
562
+ pool: any;
563
+ }[], account: string): Promise<any>;
584
564
  decodeOrderId(encodedOrderId: bigint): {
585
565
  isBid: boolean;
586
566
  price: bigint;
587
567
  orderId: bigint;
588
568
  };
589
- getOpenOrder(poolInfo: any, account: string, balanceManager: string, orders?: string[]): Promise<any>;
590
- cancelOrders(orderList: any, balanceManager: string): Transaction;
569
+ getOpenOrder(poolInfo: any, account: string, balanceManager: string | TransactionArgument, orders?: string[], isMargin?: boolean, tx?: Transaction): Promise<any>;
570
+ getAllMarketsOpenOrders(account: string, balanceManager: string): Promise<any>;
571
+ cancelOrders(orderList: any, balanceManager: string, tx?: Transaction): Transaction;
591
572
  getDeepbookOrderBook(poolKey: string, priceLow: number, priceHigh: number, isBid: boolean, account: string, balanceManager: string): Promise<void>;
592
573
  /**
593
574
  * Processes raw level 2 order book data returned from dev-inspect into
@@ -623,7 +604,7 @@ declare class DeepbookUtilsModule implements IModule {
623
604
  getWalletBalance(account: string): Promise<{
624
605
  [k: string]: any;
625
606
  }>;
626
- getAccount(balanceManager: string, poolList: any): Promise<StateAccount[] | null>;
607
+ getAccount(balanceManager: string | TransactionArgument, poolList: any, txb?: Transaction): Promise<StateAccount[] | null>;
627
608
  /**
628
609
  * Gets the SUI transaction response for a given transaction digest.
629
610
  * @param digest - The digest of the transaction for which the SUI transaction response is requested.
@@ -662,6 +643,755 @@ declare class DeepbookUtilsModule implements IModule {
662
643
  * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
663
644
  */
664
645
  getCache<T>(key: string, forceRefresh?: boolean): T | undefined;
646
+ createPermissionlessPool({ tickSize, lotSize, minSize, baseCoinType, quoteCoinType, }: {
647
+ tickSize: string;
648
+ lotSize: string;
649
+ minSize: string;
650
+ baseCoinType: string;
651
+ quoteCoinType: string;
652
+ }): Promise<Transaction>;
653
+ }
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, }: {
1114
+ marginManager: string | TransactionArgument;
1115
+ poolInfo: MarginPoolInfo;
1116
+ selfMatchingOption: SelfMatchingOption;
1117
+ quantity: string;
1118
+ amountLimit: string;
1119
+ isBid: boolean;
1120
+ payWithDeep: boolean;
1121
+ }, tx?: Transaction): Promise<Transaction>;
1122
+ /**
1123
+ * Places a limit order for margin trading.
1124
+ * Limit orders are executed only when the market price reaches the specified limit price.
1125
+ *
1126
+ * @param {Object} params - Parameters object
1127
+ * @param {string} params.marginManager - The margin manager object ID
1128
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1129
+ * @param {OrderType} params.orderType - Order type (0=NO_RESTRICTION, 1=IMMEDIATE_OR_CANCEL, 2=FILL_OR_KILL, 3=POST_ONLY)
1130
+ * @param {SelfMatchingOption} params.selfMatchingOption - Self-matching behavior option (0=SELF_MATCHING_ALLOWED, 1=CANCEL_TAKER, 2=CANCEL_MAKER)
1131
+ * @param {string} params.priceInput - Limit price as a string
1132
+ * @param {string} params.quantity - Order quantity
1133
+ * @param {boolean} params.isBid - Whether this is a buy order (true) or sell order (false)
1134
+ * @param {boolean} params.payWithDeep - Whether to pay with DEEP tokens
1135
+ * @param {number} [params.expirationTimestamp] - Optional expiration timestamp (defaults to current time + default expiration)
1136
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1137
+ * @returns {Promise<Transaction>} The transaction object with limit order operation
1138
+ * @throws {Error} If parameters are invalid or decimals are missing
1139
+ */
1140
+ placeMarginLimitOrder({ marginManager, poolInfo, orderType, selfMatchingOption, priceInput, quantity, isBid, payWithDeep, expirationTimestamp, }: {
1141
+ marginManager: string;
1142
+ poolInfo: MarginPoolInfo;
1143
+ orderType: OrderType;
1144
+ selfMatchingOption: SelfMatchingOption;
1145
+ priceInput: string;
1146
+ quantity: string;
1147
+ isBid: boolean;
1148
+ payWithDeep: boolean;
1149
+ expirationTimestamp?: number;
1150
+ }, tx?: Transaction): Promise<Transaction>;
1151
+ /**
1152
+ * Modifies an existing margin order by updating its quantity.
1153
+ *
1154
+ * @param {Object} params - Parameters object
1155
+ * @param {string} params.marginManager - The margin manager object ID
1156
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1157
+ * @param {string} params.orderId - The order ID to modify
1158
+ * @param {string} params.newQuantity - New quantity for the order
1159
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1160
+ * @returns {Transaction} The transaction object with modify order operation
1161
+ * @throws {Error} If parameters are invalid or base coin decimals are missing
1162
+ */
1163
+ modifyMarginOrder({ marginManager, poolInfo, orderId, newQuantity, }: {
1164
+ marginManager: string;
1165
+ poolInfo: MarginPoolInfo;
1166
+ orderId: string;
1167
+ newQuantity: string;
1168
+ }, tx?: Transaction): Transaction;
1169
+ /**
1170
+ * Cancels a specific margin order.
1171
+ *
1172
+ * @param {Object} params - Parameters object
1173
+ * @param {string} params.marginManager - The margin manager object ID
1174
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1175
+ * @param {string} params.orderId - The order ID to cancel
1176
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1177
+ * @returns {Transaction} The transaction object with cancel order operation
1178
+ * @throws {Error} If parameters are invalid
1179
+ */
1180
+ cancelMarginOrder({ marginManager, poolInfo, orderId, }: {
1181
+ marginManager: string;
1182
+ poolInfo: MarginPoolInfo;
1183
+ orderId: string;
1184
+ }, tx?: Transaction): Transaction;
1185
+ /**
1186
+ * Cancels all margin orders for a specific pool.
1187
+ *
1188
+ * @param {Object} params - Parameters object
1189
+ * @param {string} params.marginManager - The margin manager object ID
1190
+ * @param {MarginPoolInfo} params.poolInfo - Pool information
1191
+ * @param {Transaction} [tx=new Transaction()] - Optional transaction object to append to
1192
+ * @returns {Transaction} The transaction object with cancel all orders operation
1193
+ * @throws {Error} If parameters are invalid
1194
+ */
1195
+ cancelAllMarginOrders({ marginManager, poolInfo, }: {
1196
+ marginManager: string;
1197
+ poolInfo: MarginPoolInfo;
1198
+ }, tx?: Transaction): Transaction;
1199
+ placeReduceOnlyLimitOrder({ marginManager, poolInfo, marginPoolId, orderType, selfMatchingOption, priceInput, quantity, isBid, payWithDeep, expirationTimestamp, }: {
1200
+ marginManager: string;
1201
+ poolInfo: MarginPoolInfo;
1202
+ marginPoolId: string;
1203
+ orderType: OrderType;
1204
+ selfMatchingOption: SelfMatchingOption;
1205
+ priceInput: string;
1206
+ quantity: string;
1207
+ isBid: boolean;
1208
+ payWithDeep: boolean;
1209
+ expirationTimestamp: number;
1210
+ }, tx?: Transaction): Transaction;
1211
+ placeReduceOnlyMarketOrder({ marginManager, poolInfo, marginPoolId, selfMatchingOption, quantity, isBid, payWithDeep, }: {
1212
+ marginManager: string;
1213
+ poolInfo: MarginPoolInfo;
1214
+ marginPoolId: string;
1215
+ orderType: OrderType;
1216
+ selfMatchingOption: SelfMatchingOption;
1217
+ quantity: string;
1218
+ isBid: boolean;
1219
+ payWithDeep: boolean;
1220
+ expirationTimestamp: number;
1221
+ }, tx?: Transaction): Transaction;
1222
+ getAccountOpenOrders({ poolInfo, marginManager }: {
1223
+ poolInfo: PoolInfo;
1224
+ marginManager: string;
1225
+ }): Promise<any>;
1226
+ getAccountAllMarketsOpenOrders(account: string, pools: any): Promise<any[]>;
1227
+ mintSupplierCap(tx: Transaction | undefined, hasTransfer: boolean): {
1228
+ tx: Transaction;
1229
+ supplierCap: TransactionResult;
1230
+ };
1231
+ querySupplierCap(): Promise<any>;
1232
+ mintSupplierCapAndSupply({ marginPool, supplyCoinType, amount }: {
1233
+ marginPool: string;
1234
+ supplyCoinType: string;
1235
+ amount: string;
1236
+ }): Transaction;
1237
+ supply({ marginPool, supplierCap, supplyCoinType, amount, tx, }: {
1238
+ marginPool: string;
1239
+ supplierCap?: TransactionResult | string;
1240
+ supplyCoinType: string;
1241
+ amount: string;
1242
+ tx?: Transaction;
1243
+ }): Transaction;
1244
+ supplierWithdraw({ marginPool, withdrawCoinType, amount, supplierCapId, hasSwap, withdrawAll, tx, }: {
1245
+ marginPool: string;
1246
+ supplierCapId?: string;
1247
+ withdrawCoinType: string;
1248
+ amount: string;
1249
+ hasSwap: boolean;
1250
+ withdrawAll: boolean;
1251
+ tx?: Transaction;
1252
+ }): Transaction | TransactionResult;
1253
+ withdrawReferralFees({ marginPool }: {
1254
+ marginPool: string;
1255
+ }): Transaction;
1256
+ getUserSupplyAmount({ marginPool, supplyCoin, supplierCapId, }: {
1257
+ marginPool: string;
1258
+ supplyCoin: MarginCoinInfo;
1259
+ supplierCapId: string;
1260
+ }): Promise<string>;
1261
+ getDeepBookMarginRegistry(): Promise<{
1262
+ pool_registry_table_id: any;
1263
+ margin_pool_table_id: any;
1264
+ }>;
1265
+ getDeepBookPool(): Promise<{
1266
+ id: any;
1267
+ name: any;
1268
+ base_margin_pool_id: any;
1269
+ quote_margin_pool_id: any;
1270
+ enabled: any;
1271
+ pool_liquidation_reward: any;
1272
+ user_liquidation_reward: any;
1273
+ liquidation_risk_ratio: any;
1274
+ min_borrow_risk_ratio: any;
1275
+ min_withdraw_risk_ratio: any;
1276
+ target_liquidation_risk_ratio: any;
1277
+ }[]>;
1278
+ getDeepBookMarginPool(): Promise<{
1279
+ deposit_coin_type: any;
1280
+ id: any;
1281
+ supply_cap: any;
1282
+ total_supply: any;
1283
+ total_borrow: any;
1284
+ available_supply: string;
1285
+ max_utilization_rate: any;
1286
+ min_borrow: any;
1287
+ protocol_spread: any;
1288
+ maintainer_fees: any;
1289
+ protocol_fees: any;
1290
+ }[]>;
1291
+ getBaseQuantityOutInput(poolInfo: any, quantity: string, payWithDeep: boolean): Promise<{
1292
+ base_amount: string;
1293
+ quote_amount: string;
1294
+ deep_fee_amount: string;
1295
+ }>;
1296
+ getQuoteQuantityOutInput(poolInfo: any, quantity: string): Promise<{
1297
+ base_amount: string;
1298
+ quote_amount: string;
1299
+ deep_fee_amount: string;
1300
+ }>;
1301
+ getAccount(marginManager: string, poolInfo: any): Promise<StateAccount[] | null>;
1302
+ withdrawSettledAmounts({ poolInfo, marginManager, }: {
1303
+ poolInfo: any;
1304
+ marginManager: string;
1305
+ }, tx?: Transaction): Promise<Transaction>;
1306
+ /**
1307
+ * Gets the margin pool state with all fields needed for interest calculation.
1308
+ * This method fetches the complete pool state including interest config, borrow/supply shares, and timestamps.
1309
+ *
1310
+ * @param {string} marginPoolId - The margin pool object ID
1311
+ * @returns {Promise<Object>} The complete margin pool state for interest calculation
1312
+ */
1313
+ getMarginPoolStateForInterest(marginPoolId: string): Promise<{
1314
+ poolState: {
1315
+ total_supply: bigint;
1316
+ total_borrow: bigint;
1317
+ supply_shares: bigint;
1318
+ borrow_shares: bigint;
1319
+ last_update_timestamp: bigint;
1320
+ };
1321
+ interestConfig: {
1322
+ base_rate: bigint;
1323
+ base_slope: bigint;
1324
+ optimal_utilization: bigint;
1325
+ excess_slope: bigint;
1326
+ };
1327
+ marginPoolConfig: {
1328
+ protocol_spread: bigint;
1329
+ max_utilization_rate: bigint;
1330
+ min_borrow: bigint;
1331
+ supply_cap: bigint;
1332
+ };
1333
+ }>;
1334
+ /**
1335
+ * Gets the current chain timestamp from the Sui network.
1336
+ * Use this timestamp for interest calculations instead of local Date.now().
1337
+ *
1338
+ * This method fetches the latest checkpoint and returns its timestamp,
1339
+ * which represents the most recent confirmed on-chain time.
1340
+ *
1341
+ * @returns {Promise<bigint>} The current chain timestamp in milliseconds
1342
+ */
1343
+ getChainTimestamp(): Promise<bigint>;
1344
+ }
1345
+
1346
+ /**
1347
+ * Represents a module for making RPC (Remote Procedure Call) requests.
1348
+ */
1349
+ declare class RpcModule extends SuiClient {
1350
+ /**
1351
+ * Get events for a given query criteria
1352
+ * @param query
1353
+ * @param paginationArgs
1354
+ * @returns
1355
+ */
1356
+ queryEventsByPage(query: SuiEventFilter, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1357
+ /**
1358
+ * Get all objects owned by an address
1359
+ * @param owner
1360
+ * @param query
1361
+ * @param paginationArgs
1362
+ * @returns
1363
+ */
1364
+ getOwnedObjectsByPage(owner: string, query: SuiObjectResponseQuery, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1365
+ /**
1366
+ * Return the list of dynamic field objects owned by an object
1367
+ * @param parentId
1368
+ * @param paginationArgs
1369
+ * @returns
1370
+ */
1371
+ getDynamicFieldsByPage(parentId: SuiObjectIdType, paginationArgs?: PaginationArgs): Promise<DataPage<any>>;
1372
+ /**
1373
+ * Batch get details about a list of objects. If any of the object ids are duplicates the call will fail
1374
+ * @param ids
1375
+ * @param options
1376
+ * @param limit
1377
+ * @returns
1378
+ */
1379
+ batchGetObjects(ids: SuiObjectIdType[], options?: SuiObjectDataOptions, limit?: number): Promise<any[]>;
1380
+ /**
1381
+ * Calculates the gas cost of a transaction block.
1382
+ * @param {Transaction} tx - The transaction block to calculate gas for.
1383
+ * @returns {Promise<number>} - The estimated gas cost of the transaction block.
1384
+ * @throws {Error} - Throws an error if the sender is empty.
1385
+ */
1386
+ calculationTxGas(tx: Transaction): Promise<number>;
1387
+ /**
1388
+ * Sends a transaction block after signing it with the provided keypair.
1389
+ *
1390
+ * @param {Ed25519Keypair | Secp256k1Keypair} keypair - The keypair used for signing the transaction.
1391
+ * @param {Transaction} tx - The transaction block to send.
1392
+ * @returns {Promise<SuiTransactionBlockResponse | undefined>} - The response of the sent transaction block.
1393
+ */
1394
+ sendTransaction(keypair: Ed25519Keypair | Secp256k1Keypair, tx: Transaction): Promise<SuiTransactionBlockResponse | undefined>;
665
1395
  }
666
1396
 
667
1397
  /**
@@ -673,6 +1403,8 @@ type SdkOptions = {
673
1403
  * The full URL for interacting with the RPC (Remote Procedure Call) service.
674
1404
  */
675
1405
  fullRpcUrl: string;
1406
+ graphqlUrl: string;
1407
+ pythUrl: string;
676
1408
  /**
677
1409
  * Configuration for the simulation account.
678
1410
  */
@@ -685,6 +1417,9 @@ type SdkOptions = {
685
1417
  deepbook: {
686
1418
  package_id: string;
687
1419
  published_at: string;
1420
+ margin_package_id: string;
1421
+ margin_published_at: string;
1422
+ registry_id: string;
688
1423
  };
689
1424
  deepbook_utils: {
690
1425
  package_id: string;
@@ -693,6 +1428,19 @@ type SdkOptions = {
693
1428
  cetus_balance_manager_indexer_id: string;
694
1429
  vault_global_config_id?: string;
695
1430
  };
1431
+ margin_utils: {
1432
+ package_id: string;
1433
+ published_at: string;
1434
+ registry_id: string;
1435
+ margin_registry_id: string;
1436
+ wormhole_state_id: string;
1437
+ pyth_state_id: string;
1438
+ global_config_id: string;
1439
+ versioned_id: string;
1440
+ admin_cap_id: string;
1441
+ pool_registry_table_id: string;
1442
+ margin_pool_table_id: string;
1443
+ };
696
1444
  DEEP_COIN: {
697
1445
  coinType: string;
698
1446
  decimals: number;
@@ -712,6 +1460,9 @@ declare class DeepbookUtilsSDK {
712
1460
  */
713
1461
  protected _rpcModule: RpcModule;
714
1462
  protected _deepbookUtils: any;
1463
+ protected _marginUtils: any;
1464
+ protected _pythPrice: PythPriceModule;
1465
+ protected _graphqlClient: SuiGraphQLClient;
715
1466
  /**
716
1467
  * Provide sdk options
717
1468
  */
@@ -732,11 +1483,14 @@ declare class DeepbookUtilsSDK {
732
1483
  */
733
1484
  set senderAddress(value: string);
734
1485
  get DeepbookUtils(): DeepbookUtilsModule;
1486
+ get MarginUtils(): MarginUtilsModule;
1487
+ get PythPrice(): PythPriceModule;
735
1488
  /**
736
1489
  * Getter for the fullClient property.
737
1490
  * @returns {RpcModule} The fullClient property value.
738
1491
  */
739
1492
  get fullClient(): RpcModule;
1493
+ get graphqlClient(): SuiGraphQLClient;
740
1494
  /**
741
1495
  * Getter for the sdkOptions property.
742
1496
  * @returns {SdkOptions} The sdkOptions property value.
@@ -776,6 +1530,7 @@ declare class DeepbookUtilsSDK {
776
1530
  getCache<T>(key: string, forceRefresh?: boolean): T | undefined;
777
1531
  }
778
1532
 
1533
+ declare const cacheTime1min: number;
779
1534
  declare const cacheTime5min: number;
780
1535
  declare const cacheTime24h: number;
781
1536
  declare function getFutureTime(interval: number): number;
@@ -942,6 +1697,124 @@ declare function secretKeyToEd25519Keypair(secretKey: string | Uint8Array, ecode
942
1697
  * @returns {Ed25519Keypair} - Returns the Secp256k1 key pair.
943
1698
  */
944
1699
  declare function secretKeyToSecp256k1Keypair(secretKey: string | Uint8Array, ecode?: 'hex' | 'base64'): Secp256k1Keypair;
1700
+ declare const sleepTime: (s: number) => Promise<unknown>;
1701
+
1702
+ declare const calculateRiskRatio: ({ totalAssetsValue, totalDebtValue }: {
1703
+ totalAssetsValue: string;
1704
+ totalDebtValue: string;
1705
+ }) => string;
1706
+ declare const wrapDeepBookPoolInfo: (poolInfo: any) => {
1707
+ id: any;
1708
+ name: any;
1709
+ base_margin_pool_id: any;
1710
+ quote_margin_pool_id: any;
1711
+ enabled: any;
1712
+ pool_liquidation_reward: any;
1713
+ user_liquidation_reward: any;
1714
+ liquidation_risk_ratio: any;
1715
+ min_borrow_risk_ratio: any;
1716
+ min_withdraw_risk_ratio: any;
1717
+ target_liquidation_risk_ratio: any;
1718
+ };
1719
+ declare const wrapDeepBookMarginPoolInfo: (marginPoolInfo: any, baseInfo: any) => {
1720
+ deposit_coin_type: any;
1721
+ id: any;
1722
+ supply_cap: any;
1723
+ total_supply: any;
1724
+ total_borrow: any;
1725
+ available_supply: string;
1726
+ max_utilization_rate: any;
1727
+ min_borrow: any;
1728
+ protocol_spread: any;
1729
+ maintainer_fees: any;
1730
+ protocol_fees: any;
1731
+ };
1732
+
1733
+ declare const FLOAT_SCALING = 1000000000n;
1734
+ declare const YEAR_MS: bigint;
1735
+ interface PoolState {
1736
+ total_supply: bigint;
1737
+ total_borrow: bigint;
1738
+ supply_shares: bigint;
1739
+ borrow_shares: bigint;
1740
+ last_update_timestamp: bigint;
1741
+ }
1742
+ interface InterestConfig {
1743
+ base_rate: bigint;
1744
+ base_slope: bigint;
1745
+ optimal_utilization: bigint;
1746
+ excess_slope: bigint;
1747
+ }
1748
+ interface MarginPoolConfig {
1749
+ protocol_spread: bigint;
1750
+ }
1751
+ interface UserBorrowInfo {
1752
+ borrow_shares: bigint;
1753
+ }
1754
+ interface DebtDetail {
1755
+ confirmedDebt: bigint;
1756
+ estimatedInterest: bigint;
1757
+ totalDebt: bigint;
1758
+ annualInterestRate: bigint;
1759
+ }
1760
+ /**
1761
+ * 计算资金利用率
1762
+ *
1763
+ * 公式: 利用率 = total_borrow / total_supply
1764
+ */
1765
+ declare function calcUtilizationRate(total_borrow: bigint, total_supply: bigint): bigint;
1766
+ /**
1767
+ * 计算利率(分段线性模型)
1768
+ *
1769
+ * 利率曲线:
1770
+ * - 当利用率 < optimal_utilization: base_rate + utilization_rate * base_slope / FLOAT_SCALING
1771
+ * - 当利用率 >= optimal_utilization: base_rate + base_portion + excess_portion
1772
+ */
1773
+ declare function calcInterestRate(utilization_rate: bigint, config: InterestConfig): bigint;
1774
+ /**
1775
+ * 乘法向上取整
1776
+ */
1777
+ declare function mulRoundUp(x: bigint, y: bigint): bigint;
1778
+ /**
1779
+ * 计算用户债务详情(核心函数)
1780
+ *
1781
+ * 将债务拆分为:已确认债务 + 预估利息
1782
+ *
1783
+ * 公式:
1784
+ * - 已确认债务 = user_borrow_shares × (total_borrow / borrow_shares)
1785
+ * - 全池预估利息 = total_borrow × 利率 × 时间间隔 / 一年毫秒数
1786
+ * - 用户预估利息 = 全池预估利息 × (user_borrow_shares / borrow_shares)
1787
+ * - 总债务 = 已确认债务 + 用户预估利息
1788
+ *
1789
+ * @param user_borrow_shares - 用户的借款份额
1790
+ * @param pool - 池子状态
1791
+ * @param interest_config - 利息配置
1792
+ * @param current_timestamp_ms - 当前时间戳(毫秒)
1793
+ * @returns DebtDetail - 债务详情
1794
+ */
1795
+ declare function calcDebtDetail(user_borrow_shares: bigint, pool: PoolState, interest_config: InterestConfig, current_timestamp_ms: bigint): DebtDetail;
1796
+ /**
1797
+ * 计算 100% 还款金额
1798
+ *
1799
+ * 通过额外计算一段时间的利息来确保还款充足(覆盖交易确认时间)
1800
+ *
1801
+ * 公式: 100% 还款金额 = calcDebtDetail(链上时间 + extra_time_ms).totalDebt
1802
+ *
1803
+ * 优势(相比旧方案 confirmedDebt + estimatedInterest × 1.2):
1804
+ * - 基于实际利率计算,而非固定的 1.2 倍系数
1805
+ * - 低利率时不会多收太多,高利率时能提供足够缓冲
1806
+ * - 1 分钟足够覆盖 Sui 网络的交易确认时间
1807
+ *
1808
+ * 注意:必须传入链上时间戳,不要使用 Date.now(),避免用户本地时间与链上时间不同步
1809
+ *
1810
+ * @param user_borrow_shares - 用户的借款份额
1811
+ * @param pool - 池子状态
1812
+ * @param interest_config - 利息配置
1813
+ * @param chain_timestamp_ms - 链上时间戳(毫秒),通过 SDK 的 getChainTimestamp() 获取
1814
+ * @param extra_time_ms - 额外计算的时间(毫秒),默认 1 分钟 (60_000n)
1815
+ * @returns bigint - 100% 还款金额
1816
+ */
1817
+ declare function calc100PercentRepay(user_borrow_shares: bigint, pool: PoolState, interest_config: InterestConfig, chain_timestamp_ms: bigint, extra_time_ms?: bigint): bigint;
945
1818
 
946
1819
  declare const DEFAULT_GAS_BUDGET_FOR_SPLIT = 1000;
947
1820
  declare const DEFAULT_GAS_BUDGET_FOR_MERGE = 500;
@@ -1068,6 +1941,7 @@ declare class CoinAssist {
1068
1941
  * @returns The total balance of the CoinAsset objects.
1069
1942
  */
1070
1943
  static calculateTotalBalance(coins: CoinAsset[]): bigint;
1944
+ static buildCoinWithBalance(amount: bigint, coin_type: string, tx: Transaction): TransactionObjectArgument;
1071
1945
  }
1072
1946
 
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 };
1947
+ 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 };