@mysten/deepbook-v3 1.1.5 → 1.2.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/client.d.mts +58 -763
  3. package/dist/client.d.mts.map +1 -1
  4. package/dist/client.mjs +253 -2127
  5. package/dist/client.mjs.map +1 -1
  6. package/dist/contracts/utils/index.mjs +1 -1
  7. package/dist/index.d.mts +4 -4
  8. package/dist/index.mjs +4 -4
  9. package/dist/pyth/pyth.mjs +1 -1
  10. package/dist/queries/accountQueries.mjs +104 -0
  11. package/dist/queries/accountQueries.mjs.map +1 -0
  12. package/dist/queries/balanceManagerQueries.mjs +113 -0
  13. package/dist/queries/balanceManagerQueries.mjs.map +1 -0
  14. package/dist/queries/context.mjs +15 -0
  15. package/dist/queries/context.mjs.map +1 -0
  16. package/dist/queries/marginManagerQueries.mjs +365 -0
  17. package/dist/queries/marginManagerQueries.mjs.map +1 -0
  18. package/dist/queries/marginPoolQueries.mjs +184 -0
  19. package/dist/queries/marginPoolQueries.mjs.map +1 -0
  20. package/dist/queries/orderQueries.mjs +165 -0
  21. package/dist/queries/orderQueries.mjs.map +1 -0
  22. package/dist/queries/poolQueries.mjs +234 -0
  23. package/dist/queries/poolQueries.mjs.map +1 -0
  24. package/dist/queries/priceFeedQueries.mjs +83 -0
  25. package/dist/queries/priceFeedQueries.mjs.map +1 -0
  26. package/dist/queries/quantityQueries.mjs +216 -0
  27. package/dist/queries/quantityQueries.mjs.map +1 -0
  28. package/dist/queries/referralQueries.mjs +96 -0
  29. package/dist/queries/referralQueries.mjs.map +1 -0
  30. package/dist/queries/registryQueries.mjs +162 -0
  31. package/dist/queries/registryQueries.mjs.map +1 -0
  32. package/dist/queries/tpslQueries.mjs +62 -0
  33. package/dist/queries/tpslQueries.mjs.map +1 -0
  34. package/dist/transactions/balanceManager.d.mts +12 -12
  35. package/dist/transactions/balanceManager.d.mts.map +1 -1
  36. package/dist/transactions/balanceManager.mjs +5 -4
  37. package/dist/transactions/balanceManager.mjs.map +1 -1
  38. package/dist/transactions/deepbook.d.mts +24 -24
  39. package/dist/transactions/deepbook.d.mts.map +1 -1
  40. package/dist/transactions/deepbook.mjs +48 -47
  41. package/dist/transactions/deepbook.mjs.map +1 -1
  42. package/dist/transactions/deepbookAdmin.d.mts +2 -2
  43. package/dist/transactions/deepbookAdmin.d.mts.map +1 -1
  44. package/dist/transactions/deepbookAdmin.mjs +10 -9
  45. package/dist/transactions/deepbookAdmin.mjs.map +1 -1
  46. package/dist/transactions/flashLoans.d.mts.map +1 -1
  47. package/dist/transactions/flashLoans.mjs +6 -4
  48. package/dist/transactions/flashLoans.mjs.map +1 -1
  49. package/dist/transactions/governance.d.mts.map +1 -1
  50. package/dist/transactions/governance.mjs +5 -4
  51. package/dist/transactions/governance.mjs.map +1 -1
  52. package/dist/transactions/marginAdmin.d.mts +7 -7
  53. package/dist/transactions/marginAdmin.d.mts.map +1 -1
  54. package/dist/transactions/marginAdmin.mjs +8 -7
  55. package/dist/transactions/marginAdmin.mjs.map +1 -1
  56. package/dist/transactions/marginLiquidations.d.mts.map +1 -1
  57. package/dist/transactions/marginLiquidations.mjs +5 -4
  58. package/dist/transactions/marginLiquidations.mjs.map +1 -1
  59. package/dist/transactions/marginMaintainer.d.mts +5 -5
  60. package/dist/transactions/marginMaintainer.d.mts.map +1 -1
  61. package/dist/transactions/marginMaintainer.mjs +15 -14
  62. package/dist/transactions/marginMaintainer.mjs.map +1 -1
  63. package/dist/transactions/marginManager.d.mts +23 -23
  64. package/dist/transactions/marginManager.d.mts.map +1 -1
  65. package/dist/transactions/marginManager.mjs +17 -12
  66. package/dist/transactions/marginManager.mjs.map +1 -1
  67. package/dist/transactions/marginPool.d.mts.map +1 -1
  68. package/dist/transactions/marginPool.mjs +3 -2
  69. package/dist/transactions/marginPool.mjs.map +1 -1
  70. package/dist/transactions/marginTPSL.d.mts +1 -1
  71. package/dist/transactions/marginTPSL.d.mts.map +1 -1
  72. package/dist/transactions/marginTPSL.mjs +6 -8
  73. package/dist/transactions/marginTPSL.mjs.map +1 -1
  74. package/dist/transactions/poolProxy.d.mts.map +1 -1
  75. package/dist/transactions/poolProxy.mjs +13 -13
  76. package/dist/transactions/poolProxy.mjs.map +1 -1
  77. package/dist/types/index.d.mts +189 -52
  78. package/dist/types/index.d.mts.map +1 -1
  79. package/dist/types/index.mjs.map +1 -1
  80. package/dist/utils/constants.d.mts +4 -0
  81. package/dist/utils/constants.d.mts.map +1 -1
  82. package/dist/utils/constants.mjs +12 -5
  83. package/dist/utils/constants.mjs.map +1 -1
  84. package/dist/utils/conversion.mjs +26 -0
  85. package/dist/utils/conversion.mjs.map +1 -0
  86. package/package.json +6 -5
  87. package/src/client.ts +421 -2662
  88. package/src/index.ts +27 -0
  89. package/src/queries/accountQueries.ts +117 -0
  90. package/src/queries/balanceManagerQueries.ts +156 -0
  91. package/src/queries/context.ts +44 -0
  92. package/src/queries/index.ts +16 -0
  93. package/src/queries/marginManagerQueries.ts +575 -0
  94. package/src/queries/marginPoolQueries.ts +226 -0
  95. package/src/queries/orderQueries.ts +202 -0
  96. package/src/queries/poolQueries.ts +266 -0
  97. package/src/queries/priceFeedQueries.ts +141 -0
  98. package/src/queries/quantityQueries.ts +266 -0
  99. package/src/queries/referralQueries.ts +112 -0
  100. package/src/queries/registryQueries.ts +185 -0
  101. package/src/queries/tpslQueries.ts +88 -0
  102. package/src/transactions/balanceManager.ts +5 -4
  103. package/src/transactions/deepbook.ts +98 -84
  104. package/src/transactions/deepbookAdmin.ts +10 -9
  105. package/src/transactions/flashLoans.ts +5 -4
  106. package/src/transactions/governance.ts +5 -4
  107. package/src/transactions/marginAdmin.ts +8 -7
  108. package/src/transactions/marginLiquidations.ts +5 -4
  109. package/src/transactions/marginMaintainer.ts +15 -14
  110. package/src/transactions/marginManager.ts +13 -12
  111. package/src/transactions/marginPool.ts +3 -2
  112. package/src/transactions/marginTPSL.ts +11 -6
  113. package/src/transactions/poolProxy.ts +12 -11
  114. package/src/types/index.ts +200 -53
  115. package/src/utils/constants.ts +12 -5
  116. package/src/utils/conversion.ts +33 -0
package/dist/client.mjs CHANGED
@@ -1,27 +1,29 @@
1
- import { VecSet } from "./contracts/deepbook/deps/sui/vec_set.mjs";
2
- import { Account } from "./contracts/deepbook/account.mjs";
3
- import { OrderDeepPrice } from "./contracts/deepbook/deep_price.mjs";
4
- import { Order } from "./contracts/deepbook/order.mjs";
5
- import "./types/bcs.mjs";
6
1
  import { BalanceManagerContract } from "./transactions/balanceManager.mjs";
7
- import { DEEP_SCALAR, DeepBookConfig, FLOAT_SCALAR, PRICE_INFO_OBJECT_MAX_AGE_MS } from "./utils/config.mjs";
2
+ import { DeepBookConfig } from "./utils/config.mjs";
3
+ import { AccountQueries } from "./queries/accountQueries.mjs";
4
+ import { BalanceManagerQueries } from "./queries/balanceManagerQueries.mjs";
5
+ import { MarginManagerQueries } from "./queries/marginManagerQueries.mjs";
6
+ import { MarginPoolQueries } from "./queries/marginPoolQueries.mjs";
7
+ import { OrderQueries } from "./queries/orderQueries.mjs";
8
+ import { PoolQueries } from "./queries/poolQueries.mjs";
9
+ import { PriceFeedQueries } from "./queries/priceFeedQueries.mjs";
10
+ import { QuantityQueries } from "./queries/quantityQueries.mjs";
11
+ import { ReferralQueries } from "./queries/referralQueries.mjs";
12
+ import { RegistryQueries } from "./queries/registryQueries.mjs";
13
+ import { TPSLQueries } from "./queries/tpslQueries.mjs";
8
14
  import { DeepBookContract } from "./transactions/deepbook.mjs";
9
15
  import { DeepBookAdminContract } from "./transactions/deepbookAdmin.mjs";
10
16
  import { FlashLoanContract } from "./transactions/flashLoans.mjs";
11
17
  import { GovernanceContract } from "./transactions/governance.mjs";
12
18
  import { MarginAdminContract } from "./transactions/marginAdmin.mjs";
19
+ import { MarginLiquidationsContract } from "./transactions/marginLiquidations.mjs";
13
20
  import { MarginMaintainerContract } from "./transactions/marginMaintainer.mjs";
14
- import { MarginPoolContract } from "./transactions/marginPool.mjs";
15
21
  import { MarginManagerContract } from "./transactions/marginManager.mjs";
22
+ import { MarginPoolContract } from "./transactions/marginPool.mjs";
16
23
  import { MarginRegistryContract } from "./transactions/marginRegistry.mjs";
17
- import { MarginLiquidationsContract } from "./transactions/marginLiquidations.mjs";
18
- import { SuiPriceServiceConnection, SuiPythClient } from "./pyth/pyth.mjs";
19
- import { PriceInfoObject } from "./contracts/pyth/price_info.mjs";
20
- import { PoolProxyContract } from "./transactions/poolProxy.mjs";
21
24
  import { MarginTPSLContract } from "./transactions/marginTPSL.mjs";
22
- import { bcs } from "@mysten/sui/bcs";
25
+ import { PoolProxyContract } from "./transactions/poolProxy.mjs";
23
26
  import { normalizeSuiAddress } from "@mysten/sui/utils";
24
- import { Transaction } from "@mysten/sui/transactions";
25
27
 
26
28
  //#region src/client.ts
27
29
  function deepbook({ name = "deepbook", ...options }) {
@@ -40,17 +42,24 @@ function deepbook({ name = "deepbook", ...options }) {
40
42
  * DeepBookClient class for managing DeepBook operations.
41
43
  */
42
44
  var DeepBookClient = class {
43
- #client;
44
- #config;
45
- #address;
45
+ #balanceManagerQueries;
46
+ #poolQueries;
47
+ #quantityQueries;
48
+ #orderQueries;
49
+ #accountQueries;
50
+ #referralQueries;
51
+ #priceFeedQueries;
52
+ #marginPoolQueries;
53
+ #marginManagerQueries;
54
+ #tpslQueries;
55
+ #registryQueries;
46
56
  /**
47
57
  * Creates a new DeepBookClient instance
48
58
  */
49
59
  constructor({ client, address, network, balanceManagers, marginManagers, coins, pools, adminCap, marginAdminCap, marginMaintainerCap, packageIds, pyth }) {
50
- this.#client = client;
51
- this.#address = normalizeSuiAddress(address);
52
- this.#config = new DeepBookConfig({
53
- address: this.#address,
60
+ const normalizedAddress = normalizeSuiAddress(address);
61
+ const config = new DeepBookConfig({
62
+ address: normalizedAddress,
54
63
  network,
55
64
  balanceManagers,
56
65
  marginManagers,
@@ -62,2207 +71,324 @@ var DeepBookClient = class {
62
71
  packageIds,
63
72
  pyth
64
73
  });
65
- this.balanceManager = new BalanceManagerContract(this.#config);
66
- this.deepBook = new DeepBookContract(this.#config);
67
- this.deepBookAdmin = new DeepBookAdminContract(this.#config);
68
- this.flashLoans = new FlashLoanContract(this.#config);
69
- this.governance = new GovernanceContract(this.#config);
70
- this.marginAdmin = new MarginAdminContract(this.#config);
71
- this.marginMaintainer = new MarginMaintainerContract(this.#config);
72
- this.marginPool = new MarginPoolContract(this.#config);
73
- this.marginManager = new MarginManagerContract(this.#config);
74
- this.marginRegistry = new MarginRegistryContract(this.#config);
75
- this.marginLiquidations = new MarginLiquidationsContract(this.#config);
76
- this.poolProxy = new PoolProxyContract(this.#config);
77
- this.marginTPSL = new MarginTPSLContract(this.#config);
78
- }
79
- /**
80
- * @description Check the balance of a balance manager for a specific coin
81
- * @param {string} managerKey Key of the balance manager
82
- * @param {string} coinKey Key of the coin
83
- * @returns {Promise<{ coinType: string, balance: number }>} An object with coin type and balance
84
- */
85
- async checkManagerBalance(managerKey, coinKey) {
86
- const tx = new Transaction();
87
- const coin = this.#config.getCoin(coinKey);
88
- tx.add(this.balanceManager.checkManagerBalance(managerKey, coinKey));
89
- const bytes = (await this.#client.core.simulateTransaction({
90
- transaction: tx,
91
- include: {
92
- commandResults: true,
93
- effects: true
94
- }
95
- })).commandResults[0].returnValues[0].bcs;
96
- const parsed_balance = bcs.U64.parse(bytes);
97
- const adjusted_balance = Number(parsed_balance) / coin.scalar;
98
- return {
99
- coinType: coin.type,
100
- balance: Number(adjusted_balance.toFixed(9))
74
+ this.balanceManager = new BalanceManagerContract(config);
75
+ this.deepBook = new DeepBookContract(config);
76
+ this.deepBookAdmin = new DeepBookAdminContract(config);
77
+ this.flashLoans = new FlashLoanContract(config);
78
+ this.governance = new GovernanceContract(config);
79
+ this.marginAdmin = new MarginAdminContract(config);
80
+ this.marginMaintainer = new MarginMaintainerContract(config);
81
+ this.marginPool = new MarginPoolContract(config);
82
+ this.marginManager = new MarginManagerContract(config);
83
+ this.marginRegistry = new MarginRegistryContract(config);
84
+ this.marginLiquidations = new MarginLiquidationsContract(config);
85
+ this.poolProxy = new PoolProxyContract(config);
86
+ this.marginTPSL = new MarginTPSLContract(config);
87
+ const ctx = {
88
+ client,
89
+ config,
90
+ address: normalizedAddress,
91
+ balanceManager: this.balanceManager,
92
+ deepBook: this.deepBook,
93
+ marginManager: this.marginManager,
94
+ marginPool: this.marginPool,
95
+ marginRegistry: this.marginRegistry,
96
+ marginTPSL: this.marginTPSL
101
97
  };
98
+ this.#balanceManagerQueries = new BalanceManagerQueries(ctx);
99
+ this.#poolQueries = new PoolQueries(ctx);
100
+ this.#quantityQueries = new QuantityQueries(ctx);
101
+ this.#orderQueries = new OrderQueries(ctx);
102
+ this.#accountQueries = new AccountQueries(ctx);
103
+ this.#referralQueries = new ReferralQueries(ctx);
104
+ this.#priceFeedQueries = new PriceFeedQueries(ctx);
105
+ this.#marginPoolQueries = new MarginPoolQueries(ctx);
106
+ this.#marginManagerQueries = new MarginManagerQueries(ctx);
107
+ this.#tpslQueries = new TPSLQueries(ctx);
108
+ this.#registryQueries = new RegistryQueries(ctx);
102
109
  }
103
- /**
104
- * @description Check the balance of a BalanceManager by its address directly
105
- * @param {string} managerAddress The on-chain address of the BalanceManager
106
- * @param {string} coinKey Key of the coin
107
- * @returns {Promise<{ coinType: string, balance: number }>} An object with coin type and balance
108
- */
109
- async checkManagerBalanceWithAddress(managerAddress, coinKey) {
110
- const tx = new Transaction();
111
- const coin = this.#config.getCoin(coinKey);
112
- tx.moveCall({
113
- target: `${this.#config.DEEPBOOK_PACKAGE_ID}::balance_manager::balance`,
114
- arguments: [tx.object(managerAddress)],
115
- typeArguments: [coin.type]
116
- });
117
- const bytes = (await this.#client.core.simulateTransaction({
118
- transaction: tx,
119
- include: {
120
- commandResults: true,
121
- effects: true
122
- }
123
- })).commandResults[0].returnValues[0].bcs;
124
- const parsed_balance = bcs.U64.parse(bytes);
125
- const adjusted_balance = Number(parsed_balance) / coin.scalar;
126
- return {
127
- coinType: coin.type,
128
- balance: Number(adjusted_balance.toFixed(9))
129
- };
110
+ checkManagerBalance(managerKey, coinKey) {
111
+ return this.#balanceManagerQueries.checkManagerBalance(managerKey, coinKey);
130
112
  }
131
- /**
132
- * @description Check multiple coin balances for multiple balance managers by address in a single dry run call
133
- * @param {string[]} managerAddresses The on-chain addresses of the BalanceManagers
134
- * @param {string[]} coinKeys Keys of the coins to check balances for
135
- * @returns {Promise<Record<string, Record<string, number>>>} Object keyed by manager address, mapping coinType to balance
136
- */
137
- async checkManagerBalancesWithAddress(managerAddresses, coinKeys) {
138
- if (managerAddresses.length === 0 || coinKeys.length === 0) return {};
139
- const tx = new Transaction();
140
- const coins = coinKeys.map((coinKey) => this.#config.getCoin(coinKey));
141
- for (const managerAddress of managerAddresses) for (const coin of coins) tx.moveCall({
142
- target: `${this.#config.DEEPBOOK_PACKAGE_ID}::balance_manager::balance`,
143
- arguments: [tx.object(managerAddress)],
144
- typeArguments: [coin.type]
145
- });
146
- const res = await this.#client.core.simulateTransaction({
147
- transaction: tx,
148
- include: {
149
- commandResults: true,
150
- effects: true
151
- }
152
- });
153
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
154
- if (!res.commandResults) throw new Error("Failed to get manager balances: No command results");
155
- const results = {};
156
- for (let m = 0; m < managerAddresses.length; m++) {
157
- const managerAddress = managerAddresses[m];
158
- const managerBalances = {};
159
- for (let c = 0; c < coins.length; c++) {
160
- const coin = coins[c];
161
- const commandResult = res.commandResults[m * coins.length + c];
162
- if (!commandResult || !commandResult.returnValues) throw new Error(`Failed to get balance for ${coin.type}: No return values`);
163
- const bytes = commandResult.returnValues[0].bcs;
164
- const parsed_balance = bcs.U64.parse(bytes);
165
- managerBalances[coin.type] = Number((Number(parsed_balance) / coin.scalar).toFixed(9));
166
- }
167
- results[managerAddress] = managerBalances;
168
- }
169
- return results;
113
+ checkManagerBalanceWithAddress(managerAddress, coinKey) {
114
+ return this.#balanceManagerQueries.checkManagerBalanceWithAddress(managerAddress, coinKey);
170
115
  }
171
- /**
172
- * @description Check if a pool is whitelisted
173
- * @param {string} poolKey Key of the pool
174
- * @returns {Promise<boolean>} Boolean indicating if the pool is whitelisted
175
- */
176
- async whitelisted(poolKey) {
177
- const tx = new Transaction();
178
- tx.add(this.deepBook.whitelisted(poolKey));
179
- const bytes = (await this.#client.core.simulateTransaction({
180
- transaction: tx,
181
- include: {
182
- commandResults: true,
183
- effects: true
184
- }
185
- })).commandResults[0].returnValues[0].bcs;
186
- return bcs.Bool.parse(bytes);
116
+ checkManagerBalancesWithAddress(managerAddresses, coinKeys) {
117
+ return this.#balanceManagerQueries.checkManagerBalancesWithAddress(managerAddresses, coinKeys);
187
118
  }
188
- /**
189
- * @description Get the quote quantity out for a given base quantity
190
- * @param {string} poolKey Key of the pool
191
- * @param {number} baseQuantity Base quantity to convert
192
- * @returns {Promise<{ baseQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
193
- * An object with base quantity, base out, quote out, and deep required for the dry run
194
- */
195
- async getQuoteQuantityOut(poolKey, baseQuantity) {
196
- const tx = new Transaction();
197
- const pool = this.#config.getPool(poolKey);
198
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
199
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
200
- tx.add(this.deepBook.getQuoteQuantityOut(poolKey, baseQuantity));
201
- const res = await this.#client.core.simulateTransaction({
202
- transaction: tx,
203
- include: {
204
- commandResults: true,
205
- effects: true
206
- }
207
- });
208
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
209
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
210
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
211
- return {
212
- baseQuantity,
213
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
214
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
215
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
216
- };
119
+ getBalanceManagerIds(owner) {
120
+ return this.#balanceManagerQueries.getBalanceManagerIds(owner);
217
121
  }
218
- /**
219
- * @description Get the base quantity out for a given quote quantity
220
- * @param {string} poolKey Key of the pool
221
- * @param {number} quoteQuantity Quote quantity to convert
222
- * @returns {Promise<{ quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
223
- * An object with quote quantity, base out, quote out, and deep required for the dry run
224
- */
225
- async getBaseQuantityOut(poolKey, quoteQuantity) {
226
- const tx = new Transaction();
227
- const pool = this.#config.getPool(poolKey);
228
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
229
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
230
- tx.add(this.deepBook.getBaseQuantityOut(poolKey, quoteQuantity));
231
- const res = await this.#client.core.simulateTransaction({
232
- transaction: tx,
233
- include: {
234
- commandResults: true,
235
- effects: true
236
- }
237
- });
238
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
239
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
240
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
241
- return {
242
- quoteQuantity,
243
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
244
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
245
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
246
- };
122
+ accountExists(poolKey, managerKey) {
123
+ return this.#balanceManagerQueries.accountExists(poolKey, managerKey);
247
124
  }
248
- /**
249
- * @description Get the output quantities for given base and quote quantities. Only one quantity can be non-zero
250
- * @param {string} poolKey Key of the pool
251
- * @param {number} baseQuantity Base quantity to convert
252
- * @param {number} quoteQuantity Quote quantity to convert
253
- * @returns {Promise<{ baseQuantity: number, quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number }>}
254
- * An object with base quantity, quote quantity, base out, quote out, and deep required for the dry run
255
- */
256
- async getQuantityOut(poolKey, baseQuantity, quoteQuantity) {
257
- const tx = new Transaction();
258
- const pool = this.#config.getPool(poolKey);
259
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
260
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
261
- tx.add(this.deepBook.getQuantityOut(poolKey, baseQuantity, quoteQuantity));
262
- const res = await this.#client.core.simulateTransaction({
263
- transaction: tx,
264
- include: {
265
- commandResults: true,
266
- effects: true
267
- }
268
- });
269
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
270
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
271
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
272
- return {
273
- baseQuantity,
274
- quoteQuantity,
275
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
276
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
277
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
278
- };
125
+ whitelisted(poolKey) {
126
+ return this.#poolQueries.whitelisted(poolKey);
279
127
  }
280
- /**
281
- * @description Get open orders for a balance manager in a pool
282
- * @param {string} poolKey Key of the pool
283
- * @param {string} managerKey Key of the balance manager
284
- * @returns {Promise<Array>} An array of open order IDs
285
- */
286
- async accountOpenOrders(poolKey, managerKey) {
287
- const tx = new Transaction();
288
- tx.add(this.deepBook.accountOpenOrders(poolKey, managerKey));
289
- const order_ids = (await this.#client.core.simulateTransaction({
290
- transaction: tx,
291
- include: {
292
- commandResults: true,
293
- effects: true
294
- }
295
- })).commandResults[0].returnValues[0].bcs;
296
- return VecSet(bcs.u128()).parse(new Uint8Array(order_ids)).contents;
128
+ vaultBalances(poolKey) {
129
+ return this.#poolQueries.vaultBalances(poolKey);
297
130
  }
298
- /**
299
- * @description Get the order information for a specific order in a pool
300
- * @param {string} poolKey Key of the pool
301
- * @param {string} orderId Order ID
302
- * @returns {Promise<Object>} A promise that resolves to an object containing the order information
303
- */
304
- async getOrder(poolKey, orderId) {
305
- const tx = new Transaction();
306
- tx.add(this.deepBook.getOrder(poolKey, orderId));
307
- const res = await this.#client.core.simulateTransaction({
308
- transaction: tx,
309
- include: {
310
- commandResults: true,
311
- effects: true
312
- }
313
- });
314
- try {
315
- const orderInformation = res.commandResults[0].returnValues[0].bcs;
316
- return Order.parse(new Uint8Array(orderInformation));
317
- } catch {
318
- return null;
319
- }
131
+ getPoolIdByAssets(baseType, quoteType) {
132
+ return this.#poolQueries.getPoolIdByAssets(baseType, quoteType);
320
133
  }
321
- /**
322
- * @description Get the order information for a specific order in a pool, with normalized price
323
- * @param {string} poolKey Key of the pool
324
- * @param {string} orderId Order ID
325
- * @returns {Promise<Object>} A promise that resolves to an object containing the order information with normalized price
326
- */
327
- async getOrderNormalized(poolKey, orderId) {
328
- const tx = new Transaction();
329
- tx.add(this.deepBook.getOrder(poolKey, orderId));
330
- const res = await this.#client.core.simulateTransaction({
331
- transaction: tx,
332
- include: {
333
- commandResults: true,
334
- effects: true
335
- }
336
- });
337
- try {
338
- const orderInformation = res.commandResults[0].returnValues[0].bcs;
339
- const orderInfo = Order.parse(new Uint8Array(orderInformation));
340
- if (!orderInfo) return null;
341
- const baseCoin = this.#config.getCoin(this.#config.getPool(poolKey).baseCoin);
342
- const quoteCoin = this.#config.getCoin(this.#config.getPool(poolKey).quoteCoin);
343
- const { isBid, price: rawPrice } = this.decodeOrderId(BigInt(orderInfo.order_id));
344
- const normalizedPrice = rawPrice * baseCoin.scalar / quoteCoin.scalar / FLOAT_SCALAR;
345
- return {
346
- ...orderInfo,
347
- quantity: String((Number(orderInfo.quantity) / baseCoin.scalar).toFixed(9)),
348
- filled_quantity: String((Number(orderInfo.filled_quantity) / baseCoin.scalar).toFixed(9)),
349
- order_deep_price: {
350
- ...orderInfo.order_deep_price,
351
- deep_per_asset: String((Number(orderInfo.order_deep_price.deep_per_asset) / DEEP_SCALAR).toFixed(9))
352
- },
353
- isBid,
354
- normalized_price: normalizedPrice.toFixed(9)
355
- };
356
- } catch {
357
- return null;
358
- }
134
+ midPrice(poolKey) {
135
+ return this.#poolQueries.midPrice(poolKey);
359
136
  }
360
- /**
361
- * @description Retrieves information for multiple specific orders in a pool.
362
- * @param {string} poolKey - The key identifying the pool from which to retrieve order information.
363
- * @param {string[]} orderIds - List of order IDs to retrieve information for.
364
- * @returns {Promise<Object[] | null>} A promise that resolves to an array of order objects, each containing details such as
365
- * balance manager ID, order ID, client order ID, quantity, filled quantity, fee information, order price, epoch, status,
366
- * and expiration timestamp. Returns `null` if the retrieval fails.
367
- */
368
- async getOrders(poolKey, orderIds) {
369
- const tx = new Transaction();
370
- tx.add(this.deepBook.getOrders(poolKey, orderIds));
371
- const res = await this.#client.core.simulateTransaction({
372
- transaction: tx,
373
- include: {
374
- commandResults: true,
375
- effects: true
376
- }
377
- });
378
- try {
379
- const orderInformation = res.commandResults[0].returnValues[0].bcs;
380
- return bcs.vector(Order).parse(new Uint8Array(orderInformation));
381
- } catch {
382
- return null;
383
- }
137
+ poolTradeParams(poolKey) {
138
+ return this.#poolQueries.poolTradeParams(poolKey);
384
139
  }
385
- /**
386
- * @description Get level 2 order book specifying range of price
387
- * @param {string} poolKey Key of the pool
388
- * @param {number} priceLow Lower bound of the price range
389
- * @param {number} priceHigh Upper bound of the price range
390
- * @param {boolean} isBid Whether to get bid or ask orders
391
- * @returns {Promise<{ prices: Array<number>, quantities: Array<number> }>}
392
- * An object with arrays of prices and quantities
393
- */
394
- async getLevel2Range(poolKey, priceLow, priceHigh, isBid) {
395
- const tx = new Transaction();
396
- const pool = this.#config.getPool(poolKey);
397
- const baseCoin = this.#config.getCoin(pool.baseCoin);
398
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
399
- tx.add(this.deepBook.getLevel2Range(poolKey, priceLow, priceHigh, isBid));
400
- const res = await this.#client.core.simulateTransaction({
401
- transaction: tx,
402
- include: {
403
- commandResults: true,
404
- effects: true
405
- }
406
- });
407
- const prices = res.commandResults[0].returnValues[0].bcs;
408
- const parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(prices));
409
- const quantities = res.commandResults[0].returnValues[1].bcs;
410
- const parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(quantities));
411
- return {
412
- prices: parsed_prices.map((price) => Number((Number(price) / FLOAT_SCALAR / quoteCoin.scalar * baseCoin.scalar).toFixed(9))),
413
- quantities: parsed_quantities.map((price) => Number((Number(price) / baseCoin.scalar).toFixed(9)))
414
- };
140
+ poolBookParams(poolKey) {
141
+ return this.#poolQueries.poolBookParams(poolKey);
415
142
  }
416
- /**
417
- * @description Get level 2 order book ticks from mid-price for a pool
418
- * @param {string} poolKey Key of the pool
419
- * @param {number} ticks Number of ticks from mid-price
420
- * @returns {Promise<{ bid_prices: Array<number>, bid_quantities: Array<number>, ask_prices: Array<number>, ask_quantities: Array<number> }>}
421
- * An object with arrays of prices and quantities
422
- */
423
- async getLevel2TicksFromMid(poolKey, ticks) {
424
- const tx = new Transaction();
425
- const pool = this.#config.getPool(poolKey);
426
- const baseCoin = this.#config.getCoin(pool.baseCoin);
427
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
428
- tx.add(this.deepBook.getLevel2TicksFromMid(poolKey, ticks));
429
- const res = await this.#client.core.simulateTransaction({
430
- transaction: tx,
431
- include: {
432
- commandResults: true,
433
- effects: true
434
- }
435
- });
436
- const bid_prices = res.commandResults[0].returnValues[0].bcs;
437
- const bid_parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(bid_prices));
438
- const bid_quantities = res.commandResults[0].returnValues[1].bcs;
439
- const bid_parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(bid_quantities));
440
- const ask_prices = res.commandResults[0].returnValues[2].bcs;
441
- const ask_parsed_prices = bcs.vector(bcs.u64()).parse(new Uint8Array(ask_prices));
442
- const ask_quantities = res.commandResults[0].returnValues[3].bcs;
443
- const ask_parsed_quantities = bcs.vector(bcs.u64()).parse(new Uint8Array(ask_quantities));
444
- return {
445
- bid_prices: bid_parsed_prices.map((price) => Number((Number(price) / FLOAT_SCALAR / quoteCoin.scalar * baseCoin.scalar).toFixed(9))),
446
- bid_quantities: bid_parsed_quantities.map((quantity) => Number((Number(quantity) / baseCoin.scalar).toFixed(9))),
447
- ask_prices: ask_parsed_prices.map((price) => Number((Number(price) / FLOAT_SCALAR / quoteCoin.scalar * baseCoin.scalar).toFixed(9))),
448
- ask_quantities: ask_parsed_quantities.map((quantity) => Number((Number(quantity) / baseCoin.scalar).toFixed(9)))
449
- };
143
+ stablePool(poolKey) {
144
+ return this.#poolQueries.stablePool(poolKey);
450
145
  }
451
- /**
452
- * @description Get the vault balances for a pool
453
- * @param {string} poolKey Key of the pool
454
- * @returns {Promise<{ base: number, quote: number, deep: number }>}
455
- * An object with base, quote, and deep balances in the vault
456
- */
457
- async vaultBalances(poolKey) {
458
- const tx = new Transaction();
459
- const pool = this.#config.getPool(poolKey);
460
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
461
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
462
- tx.add(this.deepBook.vaultBalances(poolKey));
463
- const res = await this.#client.core.simulateTransaction({
464
- transaction: tx,
465
- include: {
466
- commandResults: true,
467
- effects: true
468
- }
469
- });
470
- const baseInVault = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
471
- const quoteInVault = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
472
- const deepInVault = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
473
- return {
474
- base: Number((baseInVault / baseScalar).toFixed(9)),
475
- quote: Number((quoteInVault / quoteScalar).toFixed(9)),
476
- deep: Number((deepInVault / DEEP_SCALAR).toFixed(9))
477
- };
146
+ registeredPool(poolKey) {
147
+ return this.#poolQueries.registeredPool(poolKey);
478
148
  }
479
- /**
480
- * @description Get the pool ID by asset types
481
- * @param {string} baseType Type of the base asset
482
- * @param {string} quoteType Type of the quote asset
483
- * @returns {Promise<string>} The address of the pool
484
- */
485
- async getPoolIdByAssets(baseType, quoteType) {
486
- const tx = new Transaction();
487
- tx.add(this.deepBook.getPoolIdByAssets(baseType, quoteType));
488
- const res = await this.#client.core.simulateTransaction({
489
- transaction: tx,
490
- include: {
491
- commandResults: true,
492
- effects: true
493
- }
494
- });
495
- return bcs.Address.parse(res.commandResults[0].returnValues[0].bcs);
149
+ poolTradeParamsNext(poolKey) {
150
+ return this.#poolQueries.poolTradeParamsNext(poolKey);
496
151
  }
497
- /**
498
- * @description Get the mid price for a pool
499
- * @param {string} poolKey Key of the pool
500
- * @returns {Promise<number>} The mid price
501
- */
502
- async midPrice(poolKey) {
503
- const tx = new Transaction();
504
- const pool = this.#config.getPool(poolKey);
505
- tx.add(this.deepBook.midPrice(poolKey));
506
- const baseCoin = this.#config.getCoin(pool.baseCoin);
507
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
508
- const bytes = (await this.#client.core.simulateTransaction({
509
- transaction: tx,
510
- include: {
511
- commandResults: true,
512
- effects: true
513
- }
514
- })).commandResults[0].returnValues[0].bcs;
515
- const adjusted_mid_price = Number(bcs.U64.parse(bytes)) * baseCoin.scalar / quoteCoin.scalar / FLOAT_SCALAR;
516
- return Number(adjusted_mid_price.toFixed(9));
152
+ quorum(poolKey) {
153
+ return this.#poolQueries.quorum(poolKey);
517
154
  }
518
- /**
519
- * @description Get the trade parameters for a given pool, including taker fee, maker fee, and stake required.
520
- * @param {string} poolKey Key of the pool
521
- * @returns {Promise<{ takerFee: number, makerFee: number, stakeRequired: number }>}
522
- */
523
- async poolTradeParams(poolKey) {
524
- const tx = new Transaction();
525
- tx.add(this.deepBook.poolTradeParams(poolKey));
526
- const res = await this.#client.core.simulateTransaction({
527
- transaction: tx,
528
- include: {
529
- commandResults: true,
530
- effects: true
531
- }
532
- });
533
- const takerFee = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
534
- const makerFee = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
535
- const stakeRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
536
- return {
537
- takerFee: Number(takerFee / FLOAT_SCALAR),
538
- makerFee: Number(makerFee / FLOAT_SCALAR),
539
- stakeRequired: Number(stakeRequired / DEEP_SCALAR)
540
- };
155
+ poolId(poolKey) {
156
+ return this.#poolQueries.poolId(poolKey);
541
157
  }
542
- /**
543
- * @description Get the trade parameters for a given pool, including tick size, lot size, and min size.
544
- * @param {string} poolKey Key of the pool
545
- * @returns {Promise<{ tickSize: number, lotSize: number, minSize: number }>}
546
- */
547
- async poolBookParams(poolKey) {
548
- const tx = new Transaction();
549
- const pool = this.#config.getPool(poolKey);
550
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
551
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
552
- tx.add(this.deepBook.poolBookParams(poolKey));
553
- const res = await this.#client.core.simulateTransaction({
554
- transaction: tx,
555
- include: {
556
- commandResults: true,
557
- effects: true
558
- }
559
- });
560
- const tickSize = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
561
- const lotSize = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
562
- const minSize = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
563
- return {
564
- tickSize: Number(tickSize * baseScalar / quoteScalar / FLOAT_SCALAR),
565
- lotSize: Number(lotSize / baseScalar),
566
- minSize: Number(minSize / baseScalar)
567
- };
158
+ canPlaceLimitOrder(params) {
159
+ return this.#poolQueries.canPlaceLimitOrder(params);
568
160
  }
569
- /**
570
- * @description Get the account information for a given pool and balance manager
571
- * @param {string} poolKey Key of the pool
572
- * @param {string} managerKey The key of the BalanceManager
573
- * @returns {Promise<Object>} A promise that resolves to an object containing the account information
574
- */
575
- async account(poolKey, managerKey) {
576
- const tx = new Transaction();
577
- const pool = this.#config.getPool(poolKey);
578
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
579
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
580
- tx.add(this.deepBook.account(poolKey, managerKey));
581
- const accountInformation = (await this.#client.core.simulateTransaction({
582
- transaction: tx,
583
- include: {
584
- commandResults: true,
585
- effects: true
586
- }
587
- })).commandResults[0].returnValues[0].bcs;
588
- const accountInfo = Account.parse(new Uint8Array(accountInformation));
589
- return {
590
- epoch: accountInfo.epoch,
591
- open_orders: accountInfo.open_orders,
592
- taker_volume: Number(accountInfo.taker_volume) / baseScalar,
593
- maker_volume: Number(accountInfo.maker_volume) / baseScalar,
594
- active_stake: Number(accountInfo.active_stake) / DEEP_SCALAR,
595
- inactive_stake: Number(accountInfo.inactive_stake) / DEEP_SCALAR,
596
- created_proposal: accountInfo.created_proposal,
597
- voted_proposal: accountInfo.voted_proposal,
598
- unclaimed_rebates: {
599
- base: Number(accountInfo.unclaimed_rebates.base) / baseScalar,
600
- quote: Number(accountInfo.unclaimed_rebates.quote) / quoteScalar,
601
- deep: Number(accountInfo.unclaimed_rebates.deep) / DEEP_SCALAR
602
- },
603
- settled_balances: {
604
- base: Number(accountInfo.settled_balances.base) / baseScalar,
605
- quote: Number(accountInfo.settled_balances.quote) / quoteScalar,
606
- deep: Number(accountInfo.settled_balances.deep) / DEEP_SCALAR
607
- },
608
- owed_balances: {
609
- base: Number(accountInfo.owed_balances.base) / baseScalar,
610
- quote: Number(accountInfo.owed_balances.quote) / quoteScalar,
611
- deep: Number(accountInfo.owed_balances.deep) / DEEP_SCALAR
612
- }
613
- };
161
+ canPlaceMarketOrder(params) {
162
+ return this.#poolQueries.canPlaceMarketOrder(params);
614
163
  }
615
- /**
616
- * @description Get the locked balances for a pool and balance manager
617
- * @param {string} poolKey Key of the pool
618
- * @param {string} managerKey The key of the BalanceManager
619
- * @returns {Promise<{ base: number, quote: number, deep: number }>}
620
- * An object with base, quote, and deep locked for the balance manager in the pool
621
- */
622
- async lockedBalance(poolKey, balanceManagerKey) {
623
- const tx = new Transaction();
624
- const pool = this.#config.getPool(poolKey);
625
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
626
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
627
- tx.add(this.deepBook.lockedBalance(poolKey, balanceManagerKey));
628
- const res = await this.#client.core.simulateTransaction({
629
- transaction: tx,
630
- include: {
631
- commandResults: true,
632
- effects: true
633
- }
634
- });
635
- const baseLocked = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
636
- const quoteLocked = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
637
- const deepLocked = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
638
- return {
639
- base: Number((baseLocked / baseScalar).toFixed(9)),
640
- quote: Number((quoteLocked / quoteScalar).toFixed(9)),
641
- deep: Number((deepLocked / DEEP_SCALAR).toFixed(9))
642
- };
164
+ checkMarketOrderParams(poolKey, quantity) {
165
+ return this.#poolQueries.checkMarketOrderParams(poolKey, quantity);
643
166
  }
644
- /**
645
- * @description Get the DEEP price conversion for a pool
646
- * @param {string} poolKey Key of the pool
647
- * @returns {Promise<{ asset_is_base: bool, deep_per_quote: number }>} Deep price conversion
648
- */
649
- async getPoolDeepPrice(poolKey) {
650
- const tx = new Transaction();
651
- const pool = this.#config.getPool(poolKey);
652
- tx.add(this.deepBook.getPoolDeepPrice(poolKey));
653
- const baseCoin = this.#config.getCoin(pool.baseCoin);
654
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
655
- const deepCoin = this.#config.getCoin("DEEP");
656
- const poolDeepPriceBytes = (await this.#client.core.simulateTransaction({
657
- transaction: tx,
658
- include: {
659
- commandResults: true,
660
- effects: true
661
- }
662
- })).commandResults[0].returnValues[0].bcs;
663
- const poolDeepPrice = OrderDeepPrice.parse(new Uint8Array(poolDeepPriceBytes));
664
- if (poolDeepPrice.asset_is_base) return {
665
- asset_is_base: poolDeepPrice.asset_is_base,
666
- deep_per_base: Number(poolDeepPrice.deep_per_asset) / FLOAT_SCALAR * baseCoin.scalar / deepCoin.scalar
667
- };
668
- else return {
669
- asset_is_base: poolDeepPrice.asset_is_base,
670
- deep_per_quote: Number(poolDeepPrice.deep_per_asset) / FLOAT_SCALAR * quoteCoin.scalar / deepCoin.scalar
671
- };
167
+ checkLimitOrderParams(poolKey, price, quantity, expireTimestamp) {
168
+ return this.#poolQueries.checkLimitOrderParams(poolKey, price, quantity, expireTimestamp);
672
169
  }
673
- /**
674
- * @description Decode the order ID to get bid/ask status, price, and orderId
675
- * @param {bigint} encodedOrderId Encoded order ID
676
- * @returns {Object} Object containing isBid, price, and orderId
677
- */
678
- decodeOrderId(encodedOrderId) {
679
- return {
680
- isBid: encodedOrderId >> 127n === 0n,
681
- price: Number(encodedOrderId >> 64n & (1n << 63n) - 1n),
682
- orderId: Number(encodedOrderId & (1n << 64n) - 1n)
683
- };
170
+ getQuoteQuantityOut(poolKey, baseQuantity) {
171
+ return this.#quantityQueries.getQuoteQuantityOut(poolKey, baseQuantity);
684
172
  }
685
- /**
686
- * @description Get all balance manager IDs for a given owner
687
- * @param {string} owner The owner address to get balance manager IDs for
688
- * @returns {Promise<string[]>} Array of balance manager ID strings
689
- */
690
- async getBalanceManagerIds(owner) {
691
- const tx = new Transaction();
692
- tx.add(this.deepBook.getBalanceManagerIds(owner));
693
- const bytes = (await this.#client.core.simulateTransaction({
694
- transaction: tx,
695
- include: {
696
- commandResults: true,
697
- effects: true
698
- }
699
- })).commandResults[0].returnValues[0].bcs;
700
- return bcs.vector(bcs.Address).parse(bytes).map((id) => normalizeSuiAddress(id));
173
+ getBaseQuantityOut(poolKey, quoteQuantity) {
174
+ return this.#quantityQueries.getBaseQuantityOut(poolKey, quoteQuantity);
701
175
  }
702
- /**
703
- * @description Get the owner of the referral (DeepBookPoolReferral)
704
- * @param {string} referral The ID of the referral to get the owner of
705
- * @returns {Promise<string>} The owner of the referral
706
- */
707
- async balanceManagerReferralOwner(referral) {
708
- const tx = new Transaction();
709
- tx.add(this.balanceManager.balanceManagerReferralOwner(referral));
710
- const bytes = (await this.#client.core.simulateTransaction({
711
- transaction: tx,
712
- include: {
713
- commandResults: true,
714
- effects: true
715
- }
716
- })).commandResults[0].returnValues[0].bcs;
717
- return bcs.Address.parse(bytes);
176
+ getQuantityOut(poolKey, baseQuantity, quoteQuantity) {
177
+ return this.#quantityQueries.getQuantityOut(poolKey, baseQuantity, quoteQuantity);
718
178
  }
719
- /**
720
- * @description Get the referral balances for a pool and referral (DeepBookPoolReferral)
721
- * @param {string} poolKey Key of the pool
722
- * @param {string} referral The referral ID to get balances for
723
- * @returns {Promise<{ base: number, quote: number, deep: number }>} Object with base, quote, and deep balances
724
- */
725
- async getPoolReferralBalances(poolKey, referral) {
726
- const tx = new Transaction();
727
- const pool = this.#config.getPool(poolKey);
728
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
729
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
730
- tx.add(this.deepBook.getPoolReferralBalances(poolKey, referral));
731
- const res = await this.#client.core.simulateTransaction({
732
- transaction: tx,
733
- include: {
734
- commandResults: true,
735
- effects: true
736
- }
737
- });
738
- const baseBytes = res.commandResults[0].returnValues[0].bcs;
739
- const quoteBytes = res.commandResults[0].returnValues[1].bcs;
740
- const deepBytes = res.commandResults[0].returnValues[2].bcs;
741
- const baseBalance = Number(bcs.U64.parse(baseBytes));
742
- const quoteBalance = Number(bcs.U64.parse(quoteBytes));
743
- const deepBalance = Number(bcs.U64.parse(deepBytes));
744
- return {
745
- base: baseBalance / baseScalar,
746
- quote: quoteBalance / quoteScalar,
747
- deep: deepBalance / DEEP_SCALAR
748
- };
179
+ getQuoteQuantityOutInputFee(poolKey, baseQuantity) {
180
+ return this.#quantityQueries.getQuoteQuantityOutInputFee(poolKey, baseQuantity);
749
181
  }
750
- /**
751
- * @description Get the pool ID associated with a referral (DeepBookPoolReferral)
752
- * @param {string} referral The referral (DeepBookPoolReferral) to get the pool ID for
753
- * @returns {Promise<string>} The pool ID
754
- */
755
- async balanceManagerReferralPoolId(referral) {
756
- const tx = new Transaction();
757
- tx.add(this.balanceManager.balanceManagerReferralPoolId(referral));
758
- const bytes = (await this.#client.core.simulateTransaction({
759
- transaction: tx,
760
- include: {
761
- commandResults: true,
762
- effects: true
763
- }
764
- })).commandResults[0].returnValues[0].bcs;
765
- return normalizeSuiAddress(bcs.Address.parse(bytes));
182
+ getBaseQuantityOutInputFee(poolKey, quoteQuantity) {
183
+ return this.#quantityQueries.getBaseQuantityOutInputFee(poolKey, quoteQuantity);
766
184
  }
767
- /**
768
- * @description Get the multiplier for a referral (DeepBookPoolReferral)
769
- * @param {string} poolKey Key of the pool
770
- * @param {string} referral The referral (DeepBookPoolReferral) to get the multiplier for
771
- * @returns {Promise<number>} The multiplier value
772
- */
773
- async poolReferralMultiplier(poolKey, referral) {
774
- const tx = new Transaction();
775
- tx.add(this.deepBook.poolReferralMultiplier(poolKey, referral));
776
- const bytes = (await this.#client.core.simulateTransaction({
777
- transaction: tx,
778
- include: {
779
- commandResults: true,
780
- effects: true
781
- }
782
- })).commandResults[0].returnValues[0].bcs;
783
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
185
+ getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity) {
186
+ return this.#quantityQueries.getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity);
784
187
  }
785
- /**
786
- * @description Get the referral ID from a balance manager for a specific pool
787
- * @param {string} managerKey Key of the balance manager
788
- * @param {string} poolKey Key of the pool to get the referral for
789
- * @returns {Promise<string | null>} The referral ID or null if not set
790
- */
791
- async getBalanceManagerReferralId(managerKey, poolKey) {
792
- const tx = new Transaction();
793
- tx.add(this.balanceManager.getBalanceManagerReferralId(managerKey, poolKey));
794
- const res = await this.#client.core.simulateTransaction({
795
- transaction: tx,
796
- include: {
797
- commandResults: true,
798
- effects: true
799
- }
800
- });
801
- try {
802
- const bytes = res.commandResults[0].returnValues[0].bcs;
803
- const optionId = bcs.option(bcs.Address).parse(bytes);
804
- if (optionId === null) return null;
805
- return normalizeSuiAddress(optionId);
806
- } catch {
807
- return null;
808
- }
188
+ getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep) {
189
+ return this.#quantityQueries.getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep);
809
190
  }
810
- async getPriceInfoObject(tx, coinKey) {
811
- this.#config.requirePyth();
812
- const currentTime = Date.now();
813
- const priceInfoObjectAge = await this.getPriceInfoObjectAge(coinKey);
814
- if (priceInfoObjectAge && currentTime - priceInfoObjectAge * 1e3 < PRICE_INFO_OBJECT_MAX_AGE_MS) return await this.#config.getCoin(coinKey).priceInfoObjectId;
815
- const connection = new SuiPriceServiceConnection(this.#config.network === "testnet" ? "https://hermes-beta.pyth.network" : "https://hermes.pyth.network");
816
- const priceIDs = [this.#config.getCoin(coinKey).feed];
817
- const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIDs);
818
- const wormholeStateId = this.#config.pyth.wormholeStateId;
819
- const pythStateId = this.#config.pyth.pythStateId;
820
- return (await new SuiPythClient(this.#client, pythStateId, wormholeStateId).updatePriceFeeds(tx, priceUpdateData, priceIDs))[0];
191
+ getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep) {
192
+ return this.#quantityQueries.getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep);
821
193
  }
822
- /**
823
- * @description Batch update price info objects for multiple coins. Only updates stale feeds.
824
- * This is more efficient than calling getPriceInfoObject multiple times as it:
825
- * 1. Batch fetches all price info object ages in one RPC call
826
- * 2. Fetches all stale price updates from Pyth in a single API call
827
- * @param {Transaction} tx Transaction to add price update commands to
828
- * @param {string[]} coinKeys Array of coin keys to update prices for
829
- * @returns {Promise<Record<string, string>>} Map of coinKey -> priceInfoObjectId
830
- */
831
- async getPriceInfoObjects(tx, coinKeys) {
832
- this.#config.requirePyth();
833
- if (coinKeys.length === 0) return {};
834
- const currentTime = Date.now();
835
- const coinToObjectId = {};
836
- const objectIds = [];
837
- for (const coinKey of coinKeys) {
838
- const priceInfoObjectId = this.#config.getCoin(coinKey).priceInfoObjectId;
839
- coinToObjectId[coinKey] = priceInfoObjectId;
840
- objectIds.push(priceInfoObjectId);
841
- }
842
- const res = await this.#client.core.getObjects({
843
- objectIds,
844
- include: { content: true }
845
- });
846
- const staleCoinKeys = [];
847
- const result = {};
848
- for (let i = 0; i < coinKeys.length; i++) {
849
- const coinKey = coinKeys[i];
850
- const obj = res.objects[i];
851
- if (obj instanceof Error || !obj?.content) {
852
- staleCoinKeys.push(coinKey);
853
- continue;
854
- }
855
- const priceInfoObject = PriceInfoObject.parse(obj.content);
856
- if (currentTime - Number(priceInfoObject.price_info.arrival_time) * 1e3 >= PRICE_INFO_OBJECT_MAX_AGE_MS) staleCoinKeys.push(coinKey);
857
- else result[coinKey] = coinToObjectId[coinKey];
858
- }
859
- if (staleCoinKeys.length === 0) return result;
860
- const staleFeedIds = [];
861
- const feedIdToCoinKey = {};
862
- for (const coinKey of staleCoinKeys) {
863
- const feedId = this.#config.getCoin(coinKey).feed;
864
- staleFeedIds.push(feedId);
865
- feedIdToCoinKey[feedId] = coinKey;
866
- }
867
- const priceUpdateData = await new SuiPriceServiceConnection(this.#config.network === "testnet" ? "https://hermes-beta.pyth.network" : "https://hermes.pyth.network").getPriceFeedsUpdateData(staleFeedIds);
868
- const wormholeStateId = this.#config.pyth.wormholeStateId;
869
- const pythStateId = this.#config.pyth.pythStateId;
870
- const updatedObjectIds = await new SuiPythClient(this.#client, pythStateId, wormholeStateId).updatePriceFeeds(tx, priceUpdateData, staleFeedIds);
871
- for (let i = 0; i < staleFeedIds.length; i++) {
872
- const coinKey = feedIdToCoinKey[staleFeedIds[i]];
873
- result[coinKey] = updatedObjectIds[i];
874
- }
875
- return result;
194
+ getOrderDeepRequired(poolKey, baseQuantity, price) {
195
+ return this.#quantityQueries.getOrderDeepRequired(poolKey, baseQuantity, price);
876
196
  }
877
- /**
878
- * @description Get the age of the price info object for a specific coin
879
- * @param {string} coinKey Key of the coin
880
- * @returns {Promise<number>} The arrival time of the price info object
881
- */
882
- async getPriceInfoObjectAge(coinKey) {
883
- const priceInfoObjectId = this.#config.getCoin(coinKey).priceInfoObjectId;
884
- const res = await this.#client.core.getObject({
885
- objectId: priceInfoObjectId,
886
- include: { content: true }
887
- });
888
- if (!res.object?.content) throw new Error(`Price info object not found for ${coinKey}`);
889
- const priceInfoObject = PriceInfoObject.parse(res.object.content);
890
- return Number(priceInfoObject.price_info.arrival_time);
197
+ accountOpenOrders(poolKey, managerKey) {
198
+ return this.#orderQueries.accountOpenOrders(poolKey, managerKey);
891
199
  }
892
- /**
893
- * @description Get the margin pool ID
894
- * @param {string} coinKey The key to identify the margin pool
895
- * @returns {Promise<string>} The margin pool ID
896
- */
897
- async getMarginPoolId(coinKey) {
898
- const tx = new Transaction();
899
- tx.add(this.marginPool.getId(coinKey));
900
- const bytes = (await this.#client.core.simulateTransaction({
901
- transaction: tx,
902
- include: {
903
- commandResults: true,
904
- effects: true
905
- }
906
- })).commandResults[0].returnValues[0].bcs;
907
- return bcs.Address.parse(bytes);
200
+ getOrder(poolKey, orderId) {
201
+ return this.#orderQueries.getOrder(poolKey, orderId);
908
202
  }
909
- /**
910
- * @description Check if a deepbook pool is allowed for borrowing from margin pool
911
- * @param {string} coinKey The key to identify the margin pool
912
- * @param {string} deepbookPoolId The ID of the deepbook pool
913
- * @returns {Promise<boolean>} Whether the deepbook pool is allowed
914
- */
915
- async isDeepbookPoolAllowed(coinKey, deepbookPoolId) {
916
- const tx = new Transaction();
917
- tx.add(this.marginPool.deepbookPoolAllowed(coinKey, deepbookPoolId));
918
- const bytes = (await this.#client.core.simulateTransaction({
919
- transaction: tx,
920
- include: {
921
- commandResults: true,
922
- effects: true
923
- }
924
- })).commandResults[0].returnValues[0].bcs;
925
- return bcs.bool().parse(bytes);
203
+ getOrderNormalized(poolKey, orderId) {
204
+ return this.#orderQueries.getOrderNormalized(poolKey, orderId);
926
205
  }
927
- /**
928
- * @description Get the total supply amount in the margin pool
929
- * @param {string} coinKey The key to identify the margin pool
930
- * @param {number} decimals Number of decimal places to show (default: 6)
931
- * @returns {Promise<string>} The total supply amount as a string
932
- */
933
- async getMarginPoolTotalSupply(coinKey, decimals = 6) {
934
- const tx = new Transaction();
935
- tx.add(this.marginPool.totalSupply(coinKey));
936
- const bytes = (await this.#client.core.simulateTransaction({
937
- transaction: tx,
938
- include: {
939
- commandResults: true,
940
- effects: true
941
- }
942
- })).commandResults[0].returnValues[0].bcs;
943
- const rawAmount = BigInt(bcs.U64.parse(bytes));
944
- const coin = this.#config.getCoin(coinKey);
945
- return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
206
+ getOrders(poolKey, orderIds) {
207
+ return this.#orderQueries.getOrders(poolKey, orderIds);
946
208
  }
947
- /**
948
- * @description Get the total supply shares in the margin pool
949
- * @param {string} coinKey The key to identify the margin pool
950
- * @param {number} decimals Number of decimal places to show (default: 6)
951
- * @returns {Promise<string>} The total supply shares as a string
952
- */
953
- async getMarginPoolSupplyShares(coinKey, decimals = 6) {
954
- const tx = new Transaction();
955
- tx.add(this.marginPool.supplyShares(coinKey));
956
- const bytes = (await this.#client.core.simulateTransaction({
957
- transaction: tx,
958
- include: {
959
- commandResults: true,
960
- effects: true
961
- }
962
- })).commandResults[0].returnValues[0].bcs;
963
- const rawShares = BigInt(bcs.U64.parse(bytes));
964
- const coin = this.#config.getCoin(coinKey);
965
- return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
209
+ getLevel2Range(poolKey, priceLow, priceHigh, isBid) {
210
+ return this.#orderQueries.getLevel2Range(poolKey, priceLow, priceHigh, isBid);
966
211
  }
967
- /**
968
- * @description Get the total borrow amount in the margin pool
969
- * @param {string} coinKey The key to identify the margin pool
970
- * @param {number} decimals Number of decimal places to show (default: 6)
971
- * @returns {Promise<string>} The total borrow amount as a string
972
- */
973
- async getMarginPoolTotalBorrow(coinKey, decimals = 6) {
974
- const tx = new Transaction();
975
- tx.add(this.marginPool.totalBorrow(coinKey));
976
- const bytes = (await this.#client.core.simulateTransaction({
977
- transaction: tx,
978
- include: {
979
- commandResults: true,
980
- effects: true
981
- }
982
- })).commandResults[0].returnValues[0].bcs;
983
- const rawAmount = BigInt(bcs.U64.parse(bytes));
984
- const coin = this.#config.getCoin(coinKey);
985
- return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
212
+ getLevel2TicksFromMid(poolKey, ticks) {
213
+ return this.#orderQueries.getLevel2TicksFromMid(poolKey, ticks);
986
214
  }
987
- /**
988
- * @description Get the total borrow shares in the margin pool
989
- * @param {string} coinKey The key to identify the margin pool
990
- * @param {number} decimals Number of decimal places to show (default: 6)
991
- * @returns {Promise<string>} The total borrow shares as a string
992
- */
993
- async getMarginPoolBorrowShares(coinKey, decimals = 6) {
994
- const tx = new Transaction();
995
- tx.add(this.marginPool.borrowShares(coinKey));
996
- const bytes = (await this.#client.core.simulateTransaction({
997
- transaction: tx,
998
- include: {
999
- commandResults: true,
1000
- effects: true
1001
- }
1002
- })).commandResults[0].returnValues[0].bcs;
1003
- const rawShares = BigInt(bcs.U64.parse(bytes));
1004
- const coin = this.#config.getCoin(coinKey);
1005
- return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
215
+ getAccountOrderDetails(poolKey, managerKey) {
216
+ return this.#orderQueries.getAccountOrderDetails(poolKey, managerKey);
1006
217
  }
1007
- /**
1008
- * @description Get the last update timestamp of the margin pool
1009
- * @param {string} coinKey The key to identify the margin pool
1010
- * @returns {Promise<number>} The last update timestamp in milliseconds
1011
- */
1012
- async getMarginPoolLastUpdateTimestamp(coinKey) {
1013
- const tx = new Transaction();
1014
- tx.add(this.marginPool.lastUpdateTimestamp(coinKey));
1015
- const bytes = (await this.#client.core.simulateTransaction({
1016
- transaction: tx,
1017
- include: {
1018
- commandResults: true,
1019
- effects: true
1020
- }
1021
- })).commandResults[0].returnValues[0].bcs;
1022
- return Number(bcs.U64.parse(bytes));
218
+ account(poolKey, managerKey) {
219
+ return this.#accountQueries.account(poolKey, managerKey);
1023
220
  }
1024
- /**
1025
- * @description Get the supply cap of the margin pool
1026
- * @param {string} coinKey The key to identify the margin pool
1027
- * @param {number} decimals Number of decimal places to show (default: 6)
1028
- * @returns {Promise<string>} The supply cap as a string
1029
- */
1030
- async getMarginPoolSupplyCap(coinKey, decimals = 6) {
1031
- const tx = new Transaction();
1032
- tx.add(this.marginPool.supplyCap(coinKey));
1033
- const bytes = (await this.#client.core.simulateTransaction({
1034
- transaction: tx,
1035
- include: {
1036
- commandResults: true,
1037
- effects: true
1038
- }
1039
- })).commandResults[0].returnValues[0].bcs;
1040
- const rawAmount = BigInt(bcs.U64.parse(bytes));
1041
- const coin = this.#config.getCoin(coinKey);
1042
- return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
221
+ lockedBalance(poolKey, balanceManagerKey) {
222
+ return this.#accountQueries.lockedBalance(poolKey, balanceManagerKey);
1043
223
  }
1044
- /**
1045
- * @description Get the max utilization rate of the margin pool
1046
- * @param {string} coinKey The key to identify the margin pool
1047
- * @returns {Promise<number>} The max utilization rate (as a decimal, e.g., 0.95 for 95%)
1048
- */
1049
- async getMarginPoolMaxUtilizationRate(coinKey) {
1050
- const tx = new Transaction();
1051
- tx.add(this.marginPool.maxUtilizationRate(coinKey));
1052
- const bytes = (await this.#client.core.simulateTransaction({
1053
- transaction: tx,
1054
- include: {
1055
- commandResults: true,
1056
- effects: true
1057
- }
1058
- })).commandResults[0].returnValues[0].bcs;
1059
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
224
+ getPoolDeepPrice(poolKey) {
225
+ return this.#accountQueries.getPoolDeepPrice(poolKey);
1060
226
  }
1061
- /**
1062
- * @description Get the protocol spread of the margin pool
1063
- * @param {string} coinKey The key to identify the margin pool
1064
- * @returns {Promise<number>} The protocol spread (as a decimal)
1065
- */
1066
- async getMarginPoolProtocolSpread(coinKey) {
1067
- const tx = new Transaction();
1068
- tx.add(this.marginPool.protocolSpread(coinKey));
1069
- const bytes = (await this.#client.core.simulateTransaction({
1070
- transaction: tx,
1071
- include: {
1072
- commandResults: true,
1073
- effects: true
1074
- }
1075
- })).commandResults[0].returnValues[0].bcs;
1076
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
227
+ balanceManagerReferralOwner(referral) {
228
+ return this.#referralQueries.balanceManagerReferralOwner(referral);
1077
229
  }
1078
- /**
1079
- * @description Get the minimum borrow amount for the margin pool
1080
- * @param {string} coinKey The key to identify the margin pool
1081
- * @param {number} decimals Number of decimal places to show (default: 6)
1082
- * @returns {Promise<string>} The minimum borrow amount as a string
1083
- */
1084
- async getMarginPoolMinBorrow(coinKey, decimals = 6) {
1085
- const tx = new Transaction();
1086
- tx.add(this.marginPool.minBorrow(coinKey));
1087
- const bytes = (await this.#client.core.simulateTransaction({
1088
- transaction: tx,
1089
- include: {
1090
- commandResults: true,
1091
- effects: true
1092
- }
1093
- })).commandResults[0].returnValues[0].bcs;
1094
- const rawAmount = BigInt(bcs.U64.parse(bytes));
1095
- const coin = this.#config.getCoin(coinKey);
1096
- return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
230
+ getPoolReferralBalances(poolKey, referral) {
231
+ return this.#referralQueries.getPoolReferralBalances(poolKey, referral);
1097
232
  }
1098
- /**
1099
- * @description Get the current interest rate of the margin pool
1100
- * @param {string} coinKey The key to identify the margin pool
1101
- * @returns {Promise<number>} The current interest rate (as a decimal)
1102
- */
1103
- async getMarginPoolInterestRate(coinKey) {
1104
- const tx = new Transaction();
1105
- tx.add(this.marginPool.interestRate(coinKey));
1106
- const bytes = (await this.#client.core.simulateTransaction({
1107
- transaction: tx,
1108
- include: {
1109
- commandResults: true,
1110
- effects: true
1111
- }
1112
- })).commandResults[0].returnValues[0].bcs;
1113
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
233
+ balanceManagerReferralPoolId(referral) {
234
+ return this.#referralQueries.balanceManagerReferralPoolId(referral);
1114
235
  }
1115
- /**
1116
- * @description Get user supply shares for a supplier cap
1117
- * @param {string} coinKey The key to identify the margin pool
1118
- * @param {string} supplierCapId The ID of the supplier cap
1119
- * @param {number} decimals Number of decimal places to show (default: 6)
1120
- * @returns {Promise<string>} The user's supply shares as a string
1121
- */
1122
- async getUserSupplyShares(coinKey, supplierCapId, decimals = 6) {
1123
- const tx = new Transaction();
1124
- tx.add(this.marginPool.userSupplyShares(coinKey, supplierCapId));
1125
- const bytes = (await this.#client.core.simulateTransaction({
1126
- transaction: tx,
1127
- include: {
1128
- commandResults: true,
1129
- effects: true
1130
- }
1131
- })).commandResults[0].returnValues[0].bcs;
1132
- const rawShares = BigInt(bcs.U64.parse(bytes));
1133
- const coin = this.#config.getCoin(coinKey);
1134
- return this.#formatTokenAmount(rawShares, coin.scalar, decimals);
236
+ poolReferralMultiplier(poolKey, referral) {
237
+ return this.#referralQueries.poolReferralMultiplier(poolKey, referral);
1135
238
  }
1136
- /**
1137
- * @description Get user supply amount for a supplier cap
1138
- * @param {string} coinKey The key to identify the margin pool
1139
- * @param {string} supplierCapId The ID of the supplier cap
1140
- * @param {number} decimals Number of decimal places to show (default: 6)
1141
- * @returns {Promise<string>} The user's supply amount as a string
1142
- */
1143
- async getUserSupplyAmount(coinKey, supplierCapId, decimals = 6) {
1144
- const tx = new Transaction();
1145
- tx.add(this.marginPool.userSupplyAmount(coinKey, supplierCapId));
1146
- const bytes = (await this.#client.core.simulateTransaction({
1147
- transaction: tx,
1148
- include: {
1149
- commandResults: true,
1150
- effects: true
1151
- }
1152
- })).commandResults[0].returnValues[0].bcs;
1153
- const rawAmount = BigInt(bcs.U64.parse(bytes));
1154
- const coin = this.#config.getCoin(coinKey);
1155
- return this.#formatTokenAmount(rawAmount, coin.scalar, decimals);
239
+ getBalanceManagerReferralId(managerKey, poolKey) {
240
+ return this.#referralQueries.getBalanceManagerReferralId(managerKey, poolKey);
1156
241
  }
1157
- /**
1158
- * @description Get the owner address of a margin manager
1159
- * @param {string} marginManagerKey The key to identify the margin manager
1160
- * @returns {Promise<string>} The owner address
1161
- */
1162
- async getMarginManagerOwner(marginManagerKey) {
1163
- const manager = this.#config.getMarginManager(marginManagerKey);
1164
- const tx = new Transaction();
1165
- tx.add(this.marginManager.ownerByPoolKey(manager.poolKey, manager.address));
1166
- const bytes = (await this.#client.core.simulateTransaction({
1167
- transaction: tx,
1168
- include: {
1169
- commandResults: true,
1170
- effects: true
1171
- }
1172
- })).commandResults[0].returnValues[0].bcs;
1173
- return normalizeSuiAddress(bcs.Address.parse(bytes));
242
+ getPriceInfoObject(tx, coinKey) {
243
+ return this.#priceFeedQueries.getPriceInfoObject(tx, coinKey);
1174
244
  }
1175
- /**
1176
- * @description Get the DeepBook pool ID associated with a margin manager
1177
- * @param {string} marginManagerKey The key to identify the margin manager
1178
- * @returns {Promise<string>} The DeepBook pool ID
1179
- */
1180
- async getMarginManagerDeepbookPool(marginManagerKey) {
1181
- const manager = this.#config.getMarginManager(marginManagerKey);
1182
- const tx = new Transaction();
1183
- tx.add(this.marginManager.deepbookPool(manager.poolKey, manager.address));
1184
- const bytes = (await this.#client.core.simulateTransaction({
1185
- transaction: tx,
1186
- include: {
1187
- commandResults: true,
1188
- effects: true
1189
- }
1190
- })).commandResults[0].returnValues[0].bcs;
1191
- return normalizeSuiAddress(bcs.Address.parse(bytes));
245
+ getPriceInfoObjects(tx, coinKeys) {
246
+ return this.#priceFeedQueries.getPriceInfoObjects(tx, coinKeys);
1192
247
  }
1193
- /**
1194
- * @description Get the margin pool ID (if any) associated with a margin manager
1195
- * @param {string} marginManagerKey The key to identify the margin manager
1196
- * @returns {Promise<string | null>} The margin pool ID or null if no active loan
1197
- */
1198
- async getMarginManagerMarginPoolId(marginManagerKey) {
1199
- const manager = this.#config.getMarginManager(marginManagerKey);
1200
- const tx = new Transaction();
1201
- tx.add(this.marginManager.marginPoolId(manager.poolKey, manager.address));
1202
- const bytes = (await this.#client.core.simulateTransaction({
1203
- transaction: tx,
1204
- include: {
1205
- commandResults: true,
1206
- effects: true
1207
- }
1208
- })).commandResults[0].returnValues[0].bcs;
1209
- const option = bcs.option(bcs.Address).parse(bytes);
1210
- return option ? normalizeSuiAddress(option) : null;
248
+ getPriceInfoObjectAge(coinKey) {
249
+ return this.#priceFeedQueries.getPriceInfoObjectAge(coinKey);
1211
250
  }
1212
- /**
1213
- * @description Get borrowed shares for both base and quote assets
1214
- * @param {string} marginManagerKey The key to identify the margin manager
1215
- * @returns {Promise<{baseShares: string, quoteShares: string}>} The borrowed shares
1216
- */
1217
- async getMarginManagerBorrowedShares(marginManagerKey) {
1218
- const manager = this.#config.getMarginManager(marginManagerKey);
1219
- const tx = new Transaction();
1220
- tx.add(this.marginManager.borrowedShares(manager.poolKey, manager.address));
1221
- const res = await this.#client.core.simulateTransaction({
1222
- transaction: tx,
1223
- include: {
1224
- commandResults: true,
1225
- effects: true
1226
- }
1227
- });
1228
- const baseBytes = res.commandResults[0].returnValues[0].bcs;
1229
- const quoteBytes = res.commandResults[0].returnValues[1].bcs;
1230
- return {
1231
- baseShares: bcs.U64.parse(baseBytes).toString(),
1232
- quoteShares: bcs.U64.parse(quoteBytes).toString()
1233
- };
251
+ getMarginPoolId(coinKey) {
252
+ return this.#marginPoolQueries.getMarginPoolId(coinKey);
1234
253
  }
1235
- /**
1236
- * @description Get borrowed base shares
1237
- * @param {string} marginManagerKey The key to identify the margin manager
1238
- * @returns {Promise<string>} The borrowed base shares
1239
- */
1240
- async getMarginManagerBorrowedBaseShares(marginManagerKey) {
1241
- const manager = this.#config.getMarginManager(marginManagerKey);
1242
- const tx = new Transaction();
1243
- tx.add(this.marginManager.borrowedBaseShares(manager.poolKey, manager.address));
1244
- const bytes = (await this.#client.core.simulateTransaction({
1245
- transaction: tx,
1246
- include: {
1247
- commandResults: true,
1248
- effects: true
1249
- }
1250
- })).commandResults[0].returnValues[0].bcs;
1251
- return bcs.U64.parse(bytes).toString();
254
+ isDeepbookPoolAllowed(coinKey, deepbookPoolId) {
255
+ return this.#marginPoolQueries.isDeepbookPoolAllowed(coinKey, deepbookPoolId);
1252
256
  }
1253
- /**
1254
- * @description Get borrowed quote shares
1255
- * @param {string} marginManagerKey The key to identify the margin manager
1256
- * @returns {Promise<string>} The borrowed quote shares
1257
- */
1258
- async getMarginManagerBorrowedQuoteShares(marginManagerKey) {
1259
- const manager = this.#config.getMarginManager(marginManagerKey);
1260
- const tx = new Transaction();
1261
- tx.add(this.marginManager.borrowedQuoteShares(manager.poolKey, manager.address));
1262
- const bytes = (await this.#client.core.simulateTransaction({
1263
- transaction: tx,
1264
- include: {
1265
- commandResults: true,
1266
- effects: true
1267
- }
1268
- })).commandResults[0].returnValues[0].bcs;
1269
- return bcs.U64.parse(bytes).toString();
257
+ getMarginPoolTotalSupply(coinKey, decimals = 6) {
258
+ return this.#marginPoolQueries.getMarginPoolTotalSupply(coinKey, decimals);
1270
259
  }
1271
- /**
1272
- * @description Check if margin manager has base asset debt
1273
- * @param {string} marginManagerKey The key to identify the margin manager
1274
- * @returns {Promise<boolean>} True if has base debt, false otherwise
1275
- */
1276
- async getMarginManagerHasBaseDebt(marginManagerKey) {
1277
- const manager = this.#config.getMarginManager(marginManagerKey);
1278
- const tx = new Transaction();
1279
- tx.add(this.marginManager.hasBaseDebt(manager.poolKey, manager.address));
1280
- const bytes = (await this.#client.core.simulateTransaction({
1281
- transaction: tx,
1282
- include: {
1283
- commandResults: true,
1284
- effects: true
1285
- }
1286
- })).commandResults[0].returnValues[0].bcs;
1287
- return bcs.bool().parse(bytes);
260
+ getMarginPoolSupplyShares(coinKey, decimals = 6) {
261
+ return this.#marginPoolQueries.getMarginPoolSupplyShares(coinKey, decimals);
1288
262
  }
1289
- /**
1290
- * @description Get the balance manager ID for a margin manager
1291
- * @param {string} marginManagerAddress The object ID of the margin manager
1292
- * @returns {Promise<string>} The balance manager ID
1293
- */
1294
- async getMarginManagerBalanceManagerId(marginManagerAddress) {
1295
- const res = await this.#client.core.getObject({
1296
- objectId: marginManagerAddress,
1297
- include: { content: true }
1298
- });
1299
- if (!res.object?.content) throw new Error(`Margin manager not found: ${marginManagerAddress}`);
1300
- return normalizeSuiAddress(bcs.struct("MarginManagerBalanceManagerId", {
1301
- id: bcs.Address,
1302
- owner: bcs.Address,
1303
- deepbook_pool: bcs.Address,
1304
- margin_pool_id: bcs.option(bcs.Address),
1305
- balance_manager_id: bcs.Address
1306
- }).parse(res.object.content).balance_manager_id);
263
+ getMarginPoolTotalBorrow(coinKey, decimals = 6) {
264
+ return this.#marginPoolQueries.getMarginPoolTotalBorrow(coinKey, decimals);
1307
265
  }
1308
- /**
1309
- * @description Calculate assets (base and quote) for a margin manager
1310
- * @param {string} marginManagerKey The key to identify the margin manager
1311
- * @param {number} decimals Number of decimal places to show (default: 6)
1312
- * @returns {Promise<{baseAsset: string, quoteAsset: string}>} The base and quote assets
1313
- */
1314
- async getMarginManagerAssets(marginManagerKey, decimals = 6) {
1315
- const manager = this.#config.getMarginManager(marginManagerKey);
1316
- const tx = new Transaction();
1317
- tx.add(this.marginManager.calculateAssets(manager.poolKey, manager.address));
1318
- const res = await this.#client.core.simulateTransaction({
1319
- transaction: tx,
1320
- include: {
1321
- commandResults: true,
1322
- effects: true
1323
- }
1324
- });
1325
- const baseBytes = res.commandResults[0].returnValues[0].bcs;
1326
- const quoteBytes = res.commandResults[0].returnValues[1].bcs;
1327
- const pool = this.#config.getPool(manager.poolKey);
1328
- const baseCoin = this.#config.getCoin(pool.baseCoin);
1329
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1330
- return {
1331
- baseAsset: this.#formatTokenAmount(BigInt(bcs.U64.parse(baseBytes)), baseCoin.scalar, decimals),
1332
- quoteAsset: this.#formatTokenAmount(BigInt(bcs.U64.parse(quoteBytes)), quoteCoin.scalar, decimals)
1333
- };
266
+ getMarginPoolBorrowShares(coinKey, decimals = 6) {
267
+ return this.#marginPoolQueries.getMarginPoolBorrowShares(coinKey, decimals);
1334
268
  }
1335
- /**
1336
- * @description Calculate debts (base and quote) for a margin manager
1337
- * NOTE: This function automatically determines whether to use base or quote margin pool
1338
- * based on hasBaseDebt. You don't need to specify the debt coin type.
1339
- * @param {string} marginManagerKey The key to identify the margin manager
1340
- * @param {number} decimals Number of decimal places to show (default: 6)
1341
- * @returns {Promise<{baseDebt: string, quoteDebt: string}>} The base and quote debts
1342
- */
1343
- async getMarginManagerDebts(marginManagerKey, decimals = 6) {
1344
- const hasBaseDebt = await this.getMarginManagerHasBaseDebt(marginManagerKey);
1345
- const manager = this.#config.getMarginManager(marginManagerKey);
1346
- const pool = this.#config.getPool(manager.poolKey);
1347
- const debtCoinKey = hasBaseDebt ? pool.baseCoin : pool.quoteCoin;
1348
- const tx = new Transaction();
1349
- tx.add(this.marginManager.calculateDebts(manager.poolKey, debtCoinKey, manager.address));
1350
- const res = await this.#client.core.simulateTransaction({
1351
- transaction: tx,
1352
- include: {
1353
- commandResults: true,
1354
- effects: true
1355
- }
1356
- });
1357
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1358
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get margin manager debts: Unknown error`);
1359
- const baseBytes = res.commandResults[0].returnValues[0].bcs;
1360
- const quoteBytes = res.commandResults[0].returnValues[1].bcs;
1361
- const debtCoin = this.#config.getCoin(debtCoinKey);
1362
- return {
1363
- baseDebt: this.#formatTokenAmount(BigInt(bcs.U64.parse(baseBytes)), debtCoin.scalar, decimals),
1364
- quoteDebt: this.#formatTokenAmount(BigInt(bcs.U64.parse(quoteBytes)), debtCoin.scalar, decimals)
1365
- };
269
+ getMarginPoolLastUpdateTimestamp(coinKey) {
270
+ return this.#marginPoolQueries.getMarginPoolLastUpdateTimestamp(coinKey);
1366
271
  }
1367
- /**
1368
- * @description Get comprehensive state information for a margin manager
1369
- * @param {string} marginManagerKey The key to identify the margin manager
1370
- * @param {number} decimals Number of decimal places to show (default: 6)
1371
- * @returns {Promise<{
1372
- * managerId: string,
1373
- * deepbookPoolId: string,
1374
- * riskRatio: number,
1375
- * baseAsset: string,
1376
- * quoteAsset: string,
1377
- * baseDebt: string,
1378
- * quoteDebt: string,
1379
- * basePythPrice: string,
1380
- * basePythDecimals: number,
1381
- * quotePythPrice: string,
1382
- * quotePythDecimals: number
1383
- * }>} Comprehensive margin manager state
1384
- */
1385
- async getMarginManagerState(marginManagerKey, decimals = 6) {
1386
- const manager = this.#config.getMarginManager(marginManagerKey);
1387
- const tx = new Transaction();
1388
- tx.add(this.marginManager.managerState(manager.poolKey, manager.address));
1389
- const res = await this.#client.core.simulateTransaction({
1390
- transaction: tx,
1391
- include: {
1392
- commandResults: true,
1393
- effects: true
1394
- }
1395
- });
1396
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1397
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get margin manager state: Unknown error`);
1398
- const pool = this.#config.getPool(manager.poolKey);
1399
- const baseCoin = this.#config.getCoin(pool.baseCoin);
1400
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1401
- const managerId = normalizeSuiAddress(bcs.Address.parse(res.commandResults[0].returnValues[0].bcs));
1402
- const deepbookPoolId = normalizeSuiAddress(bcs.Address.parse(res.commandResults[0].returnValues[1].bcs));
1403
- const riskRatio = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs)) / FLOAT_SCALAR;
1404
- const baseAsset = this.#formatTokenAmount(BigInt(bcs.U64.parse(res.commandResults[0].returnValues[3].bcs)), baseCoin.scalar, decimals);
1405
- const quoteAsset = this.#formatTokenAmount(BigInt(bcs.U64.parse(res.commandResults[0].returnValues[4].bcs)), quoteCoin.scalar, decimals);
1406
- const baseDebt = this.#formatTokenAmount(BigInt(bcs.U64.parse(res.commandResults[0].returnValues[5].bcs)), baseCoin.scalar, decimals);
1407
- const quoteDebt = this.#formatTokenAmount(BigInt(bcs.U64.parse(res.commandResults[0].returnValues[6].bcs)), quoteCoin.scalar, decimals);
1408
- const basePythPrice = bcs.U64.parse(res.commandResults[0].returnValues[7].bcs);
1409
- const basePythDecimals = Number(bcs.u8().parse(new Uint8Array(res.commandResults[0].returnValues[8].bcs)));
1410
- const quotePythPrice = bcs.U64.parse(res.commandResults[0].returnValues[9].bcs);
1411
- const quotePythDecimals = Number(bcs.u8().parse(new Uint8Array(res.commandResults[0].returnValues[10].bcs)));
1412
- const currentPrice = BigInt(bcs.U64.parse(res.commandResults[0].returnValues[11].bcs));
1413
- const lowestTriggerAbovePrice = BigInt(bcs.U64.parse(res.commandResults[0].returnValues[12].bcs));
1414
- const highestTriggerBelowPrice = BigInt(bcs.U64.parse(res.commandResults[0].returnValues[13].bcs));
1415
- return {
1416
- managerId,
1417
- deepbookPoolId,
1418
- riskRatio,
1419
- baseAsset,
1420
- quoteAsset,
1421
- baseDebt,
1422
- quoteDebt,
1423
- basePythPrice: basePythPrice.toString(),
1424
- basePythDecimals,
1425
- quotePythPrice: quotePythPrice.toString(),
1426
- quotePythDecimals,
1427
- currentPrice,
1428
- lowestTriggerAbovePrice,
1429
- highestTriggerBelowPrice
1430
- };
272
+ getMarginPoolSupplyCap(coinKey, decimals = 6) {
273
+ return this.#marginPoolQueries.getMarginPoolSupplyCap(coinKey, decimals);
1431
274
  }
1432
- /**
1433
- * @description Get comprehensive state information for multiple margin managers.
1434
- * @param {Record<string, string>} marginManagers Map of marginManagerId -> poolKey
1435
- * @param {number} decimals Number of decimal places for formatting (default: 6)
1436
- * @returns {Promise<Record<string, {...}>>} Object keyed by managerId with state data
1437
- */
1438
- async getMarginManagerStates(marginManagers, decimals = 6) {
1439
- const entries = Object.entries(marginManagers);
1440
- if (entries.length === 0) return {};
1441
- const tx = new Transaction();
1442
- for (const [managerId, poolKey] of entries) tx.add(this.marginManager.managerState(poolKey, managerId));
1443
- const res = await this.#client.core.simulateTransaction({
1444
- transaction: tx,
1445
- include: {
1446
- commandResults: true,
1447
- effects: true
1448
- }
1449
- });
1450
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1451
- if (!res.commandResults) throw new Error(`Failed to get margin manager states: Unknown error`);
1452
- const results = {};
1453
- for (let i = 0; i < entries.length; i++) {
1454
- const commandResult = res.commandResults[i];
1455
- if (!commandResult || !commandResult.returnValues) throw new Error(`Failed to get margin manager state for index ${i}: No return values`);
1456
- const [, poolKey] = entries[i];
1457
- const pool = this.#config.getPool(poolKey);
1458
- const baseCoin = this.#config.getCoin(pool.baseCoin);
1459
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1460
- const managerId = normalizeSuiAddress(bcs.Address.parse(commandResult.returnValues[0].bcs));
1461
- const deepbookPoolId = normalizeSuiAddress(bcs.Address.parse(commandResult.returnValues[1].bcs));
1462
- const riskRatio = Number(bcs.U64.parse(commandResult.returnValues[2].bcs)) / FLOAT_SCALAR;
1463
- const baseAsset = this.#formatTokenAmount(BigInt(bcs.U64.parse(commandResult.returnValues[3].bcs)), baseCoin.scalar, decimals);
1464
- const quoteAsset = this.#formatTokenAmount(BigInt(bcs.U64.parse(commandResult.returnValues[4].bcs)), quoteCoin.scalar, decimals);
1465
- const baseDebt = this.#formatTokenAmount(BigInt(bcs.U64.parse(commandResult.returnValues[5].bcs)), baseCoin.scalar, decimals);
1466
- const quoteDebt = this.#formatTokenAmount(BigInt(bcs.U64.parse(commandResult.returnValues[6].bcs)), quoteCoin.scalar, decimals);
1467
- const basePythPrice = bcs.U64.parse(commandResult.returnValues[7].bcs);
1468
- const basePythDecimals = Number(bcs.u8().parse(new Uint8Array(commandResult.returnValues[8].bcs)));
1469
- const quotePythPrice = bcs.U64.parse(commandResult.returnValues[9].bcs);
1470
- const quotePythDecimals = Number(bcs.u8().parse(new Uint8Array(commandResult.returnValues[10].bcs)));
1471
- const currentPrice = BigInt(bcs.U64.parse(commandResult.returnValues[11].bcs));
1472
- const lowestTriggerAbovePrice = BigInt(bcs.U64.parse(commandResult.returnValues[12].bcs));
1473
- const highestTriggerBelowPrice = BigInt(bcs.U64.parse(commandResult.returnValues[13].bcs));
1474
- results[managerId] = {
1475
- managerId,
1476
- deepbookPoolId,
1477
- riskRatio,
1478
- baseAsset,
1479
- quoteAsset,
1480
- baseDebt,
1481
- quoteDebt,
1482
- basePythPrice: basePythPrice.toString(),
1483
- basePythDecimals,
1484
- quotePythPrice: quotePythPrice.toString(),
1485
- quotePythDecimals,
1486
- currentPrice,
1487
- lowestTriggerAbovePrice,
1488
- highestTriggerBelowPrice
1489
- };
1490
- }
1491
- return results;
275
+ getMarginPoolMaxUtilizationRate(coinKey) {
276
+ return this.#marginPoolQueries.getMarginPoolMaxUtilizationRate(coinKey);
1492
277
  }
1493
- /**
1494
- * @description Get the base asset balance of a margin manager
1495
- * @param {string} marginManagerKey The key to identify the margin manager
1496
- * @param {number} decimals Number of decimal places to show (default: 6)
1497
- * @returns {Promise<string>} The base asset balance
1498
- */
1499
- async getMarginManagerBaseBalance(marginManagerKey, decimals = 9) {
1500
- const manager = this.#config.getMarginManager(marginManagerKey);
1501
- const tx = new Transaction();
1502
- tx.add(this.marginManager.baseBalance(manager.poolKey, manager.address));
1503
- const res = await this.#client.core.simulateTransaction({
1504
- transaction: tx,
1505
- include: {
1506
- commandResults: true,
1507
- effects: true
1508
- }
1509
- });
1510
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1511
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get margin manager base balance: Unknown error`);
1512
- const bytes = res.commandResults[0].returnValues[0].bcs;
1513
- const pool = this.#config.getPool(manager.poolKey);
1514
- const baseCoin = this.#config.getCoin(pool.baseCoin);
1515
- return this.#formatTokenAmount(BigInt(bcs.U64.parse(bytes)), baseCoin.scalar, decimals);
278
+ getMarginPoolProtocolSpread(coinKey) {
279
+ return this.#marginPoolQueries.getMarginPoolProtocolSpread(coinKey);
1516
280
  }
1517
- /**
1518
- * @description Get the quote asset balance of a margin manager
1519
- * @param {string} marginManagerKey The key to identify the margin manager
1520
- * @param {number} decimals Number of decimal places to show (default: 6)
1521
- * @returns {Promise<string>} The quote asset balance
1522
- */
1523
- async getMarginManagerQuoteBalance(marginManagerKey, decimals = 9) {
1524
- const manager = this.#config.getMarginManager(marginManagerKey);
1525
- const tx = new Transaction();
1526
- tx.add(this.marginManager.quoteBalance(manager.poolKey, manager.address));
1527
- const res = await this.#client.core.simulateTransaction({
1528
- transaction: tx,
1529
- include: {
1530
- commandResults: true,
1531
- effects: true
1532
- }
1533
- });
1534
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1535
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get margin manager quote balance: Unknown error`);
1536
- const bytes = res.commandResults[0].returnValues[0].bcs;
1537
- const pool = this.#config.getPool(manager.poolKey);
1538
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1539
- return this.#formatTokenAmount(BigInt(bcs.U64.parse(bytes)), quoteCoin.scalar, decimals);
281
+ getMarginPoolMinBorrow(coinKey, decimals = 6) {
282
+ return this.#marginPoolQueries.getMarginPoolMinBorrow(coinKey, decimals);
1540
283
  }
1541
- /**
1542
- * @description Get the DEEP token balance of a margin manager
1543
- * @param {string} marginManagerKey The key to identify the margin manager
1544
- * @param {number} decimals Number of decimal places to show (default: 6)
1545
- * @returns {Promise<string>} The DEEP token balance
1546
- */
1547
- async getMarginManagerDeepBalance(marginManagerKey, decimals = 6) {
1548
- const manager = this.#config.getMarginManager(marginManagerKey);
1549
- const tx = new Transaction();
1550
- tx.add(this.marginManager.deepBalance(manager.poolKey, manager.address));
1551
- const res = await this.#client.core.simulateTransaction({
1552
- transaction: tx,
1553
- include: {
1554
- commandResults: true,
1555
- effects: true
1556
- }
1557
- });
1558
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1559
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get margin manager DEEP balance: Unknown error`);
1560
- const bytes = res.commandResults[0].returnValues[0].bcs;
1561
- const deepCoin = this.#config.getCoin("DEEP");
1562
- return this.#formatTokenAmount(BigInt(bcs.U64.parse(bytes)), deepCoin.scalar, decimals);
284
+ getMarginPoolInterestRate(coinKey) {
285
+ return this.#marginPoolQueries.getMarginPoolInterestRate(coinKey);
1563
286
  }
1564
- /**
1565
- * @description Get base, quote, and DEEP balances for multiple margin managers in a single dry run call
1566
- * @param {Record<string, string>} marginManagers Map of marginManagerId -> poolKey
1567
- * @param {number} decimals Number of decimal places for formatting (default: 9)
1568
- * @returns {Promise<Record<string, { base: string, quote: string, deep: string }>>} Object keyed by managerId
1569
- */
1570
- async getMarginManagerBalances(marginManagers, decimals = 9) {
1571
- const entries = Object.entries(marginManagers);
1572
- if (entries.length === 0) return {};
1573
- const tx = new Transaction();
1574
- for (const [managerId, poolKey] of entries) {
1575
- tx.add(this.marginManager.baseBalance(poolKey, managerId));
1576
- tx.add(this.marginManager.quoteBalance(poolKey, managerId));
1577
- tx.add(this.marginManager.deepBalance(poolKey, managerId));
1578
- }
1579
- const res = await this.#client.core.simulateTransaction({
1580
- transaction: tx,
1581
- include: {
1582
- commandResults: true,
1583
- effects: true
1584
- }
1585
- });
1586
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1587
- if (!res.commandResults) throw new Error("Failed to get margin manager balances: No command results");
1588
- const results = {};
1589
- const deepCoin = this.#config.getCoin("DEEP");
1590
- for (let i = 0; i < entries.length; i++) {
1591
- const [managerId, poolKey] = entries[i];
1592
- const pool = this.#config.getPool(poolKey);
1593
- const baseCoin = this.#config.getCoin(pool.baseCoin);
1594
- const quoteCoin = this.#config.getCoin(pool.quoteCoin);
1595
- const baseResult = res.commandResults[i * 3];
1596
- const quoteResult = res.commandResults[i * 3 + 1];
1597
- const deepResult = res.commandResults[i * 3 + 2];
1598
- if (!baseResult?.returnValues || !quoteResult?.returnValues || !deepResult?.returnValues) throw new Error(`Failed to get balances for margin manager ${managerId}: No return values`);
1599
- results[managerId] = {
1600
- base: this.#formatTokenAmount(BigInt(bcs.U64.parse(baseResult.returnValues[0].bcs)), baseCoin.scalar, decimals),
1601
- quote: this.#formatTokenAmount(BigInt(bcs.U64.parse(quoteResult.returnValues[0].bcs)), quoteCoin.scalar, decimals),
1602
- deep: this.#formatTokenAmount(BigInt(bcs.U64.parse(deepResult.returnValues[0].bcs)), deepCoin.scalar, decimals)
1603
- };
1604
- }
1605
- return results;
287
+ getUserSupplyShares(coinKey, supplierCapId, decimals = 6) {
288
+ return this.#marginPoolQueries.getUserSupplyShares(coinKey, supplierCapId, decimals);
1606
289
  }
1607
- /**
1608
- * @description Get all conditional order IDs for a margin manager
1609
- * @param {string} marginManagerKey The key to identify the margin manager
1610
- * @returns {Promise<string[]>} Array of conditional order IDs
1611
- */
1612
- async getConditionalOrderIds(marginManagerKey) {
1613
- const manager = this.#config.getMarginManager(marginManagerKey);
1614
- const tx = new Transaction();
1615
- tx.add(this.marginTPSL.conditionalOrderIds(manager.poolKey, manager.address));
1616
- const res = await this.#client.core.simulateTransaction({
1617
- transaction: tx,
1618
- include: {
1619
- commandResults: true,
1620
- effects: true
1621
- }
1622
- });
1623
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1624
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get conditional order IDs: Unknown error`);
1625
- const bytes = res.commandResults[0].returnValues[0].bcs;
1626
- return bcs.vector(bcs.u64()).parse(bytes).map((id) => id.toString());
290
+ getUserSupplyAmount(coinKey, supplierCapId, decimals = 6) {
291
+ return this.#marginPoolQueries.getUserSupplyAmount(coinKey, supplierCapId, decimals);
1627
292
  }
1628
- /**
1629
- * @description Get the lowest trigger price for trigger_above orders
1630
- * Returns MAX_U64 if there are no trigger_above orders
1631
- * @param {string} marginManagerKey The key to identify the margin manager
1632
- * @returns {Promise<bigint>} The lowest trigger above price
1633
- */
1634
- async getLowestTriggerAbovePrice(marginManagerKey) {
1635
- const manager = this.#config.getMarginManager(marginManagerKey);
1636
- const tx = new Transaction();
1637
- tx.add(this.marginTPSL.lowestTriggerAbovePrice(manager.poolKey, manager.address));
1638
- const res = await this.#client.core.simulateTransaction({
1639
- transaction: tx,
1640
- include: {
1641
- commandResults: true,
1642
- effects: true
1643
- }
1644
- });
1645
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1646
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get lowest trigger above price: Unknown error`);
1647
- const bytes = res.commandResults[0].returnValues[0].bcs;
1648
- return BigInt(bcs.U64.parse(bytes));
293
+ getMarginManagerOwner(marginManagerKey) {
294
+ return this.#marginManagerQueries.getMarginManagerOwner(marginManagerKey);
1649
295
  }
1650
- /**
1651
- * @description Get the highest trigger price for trigger_below orders
1652
- * Returns 0 if there are no trigger_below orders
1653
- * @param {string} marginManagerKey The key to identify the margin manager
1654
- * @returns {Promise<bigint>} The highest trigger below price
1655
- */
1656
- async getHighestTriggerBelowPrice(marginManagerKey) {
1657
- const manager = this.#config.getMarginManager(marginManagerKey);
1658
- const tx = new Transaction();
1659
- tx.add(this.marginTPSL.highestTriggerBelowPrice(manager.poolKey, manager.address));
1660
- const res = await this.#client.core.simulateTransaction({
1661
- transaction: tx,
1662
- include: {
1663
- commandResults: true,
1664
- effects: true
1665
- }
1666
- });
1667
- if (res.FailedTransaction) throw new Error(`Transaction failed: ${res.FailedTransaction.status.error?.message || "Unknown error"}`);
1668
- if (!res.commandResults || !res.commandResults[0] || !res.commandResults[0].returnValues) throw new Error(`Failed to get highest trigger below price: Unknown error`);
1669
- const bytes = res.commandResults[0].returnValues[0].bcs;
1670
- return BigInt(bcs.U64.parse(bytes));
296
+ getMarginManagerDeepbookPool(marginManagerKey) {
297
+ return this.#marginManagerQueries.getMarginManagerDeepbookPool(marginManagerKey);
1671
298
  }
1672
- /**
1673
- * @description Check if a deepbook pool is enabled for margin trading
1674
- * @param {string} poolKey The key to identify the pool
1675
- * @returns {Promise<boolean>} True if the pool is enabled for margin trading
1676
- */
1677
- async isPoolEnabledForMargin(poolKey) {
1678
- const tx = new Transaction();
1679
- tx.add(this.marginRegistry.poolEnabled(poolKey));
1680
- const bytes = (await this.#client.core.simulateTransaction({
1681
- transaction: tx,
1682
- include: {
1683
- commandResults: true,
1684
- effects: true
1685
- }
1686
- })).commandResults[0].returnValues[0].bcs;
1687
- return bcs.Bool.parse(bytes);
299
+ getMarginManagerMarginPoolId(marginManagerKey) {
300
+ return this.#marginManagerQueries.getMarginManagerMarginPoolId(marginManagerKey);
1688
301
  }
1689
- /**
1690
- * @description Get the margin manager IDs for a given owner address
1691
- * @param {string} owner The owner address
1692
- * @returns {Promise<string[]>} Array of margin manager IDs
1693
- */
1694
- async getMarginManagerIdsForOwner(owner) {
1695
- const tx = new Transaction();
1696
- tx.add(this.marginRegistry.getMarginManagerIds(owner));
1697
- const bytes = (await this.#client.core.simulateTransaction({
1698
- transaction: tx,
1699
- include: {
1700
- commandResults: true,
1701
- effects: true
1702
- }
1703
- })).commandResults[0].returnValues[0].bcs;
1704
- return VecSet(bcs.Address).parse(bytes).contents.map((id) => normalizeSuiAddress(id));
302
+ getMarginManagerBorrowedShares(marginManagerKey) {
303
+ return this.#marginManagerQueries.getMarginManagerBorrowedShares(marginManagerKey);
1705
304
  }
1706
- /**
1707
- * @description Get the base margin pool ID for a deepbook pool
1708
- * @param {string} poolKey The key to identify the pool
1709
- * @returns {Promise<string>} The base margin pool ID
1710
- */
1711
- async getBaseMarginPoolId(poolKey) {
1712
- const tx = new Transaction();
1713
- tx.add(this.marginRegistry.baseMarginPoolId(poolKey));
1714
- const bytes = (await this.#client.core.simulateTransaction({
1715
- transaction: tx,
1716
- include: {
1717
- commandResults: true,
1718
- effects: true
1719
- }
1720
- })).commandResults[0].returnValues[0].bcs;
1721
- return "0x" + bcs.Address.parse(bytes);
305
+ getMarginManagerBorrowedBaseShares(marginManagerKey) {
306
+ return this.#marginManagerQueries.getMarginManagerBorrowedBaseShares(marginManagerKey);
1722
307
  }
1723
- /**
1724
- * @description Get the quote margin pool ID for a deepbook pool
1725
- * @param {string} poolKey The key to identify the pool
1726
- * @returns {Promise<string>} The quote margin pool ID
1727
- */
1728
- async getQuoteMarginPoolId(poolKey) {
1729
- const tx = new Transaction();
1730
- tx.add(this.marginRegistry.quoteMarginPoolId(poolKey));
1731
- const bytes = (await this.#client.core.simulateTransaction({
1732
- transaction: tx,
1733
- include: {
1734
- commandResults: true,
1735
- effects: true
1736
- }
1737
- })).commandResults[0].returnValues[0].bcs;
1738
- return "0x" + bcs.Address.parse(bytes);
308
+ getMarginManagerBorrowedQuoteShares(marginManagerKey) {
309
+ return this.#marginManagerQueries.getMarginManagerBorrowedQuoteShares(marginManagerKey);
1739
310
  }
1740
- /**
1741
- * @description Get the minimum withdraw risk ratio for a deepbook pool
1742
- * @param {string} poolKey The key to identify the pool
1743
- * @returns {Promise<number>} The minimum withdraw risk ratio as a decimal (e.g., 1.5 for 150%)
1744
- */
1745
- async getMinWithdrawRiskRatio(poolKey) {
1746
- const tx = new Transaction();
1747
- tx.add(this.marginRegistry.minWithdrawRiskRatio(poolKey));
1748
- const bytes = (await this.#client.core.simulateTransaction({
1749
- transaction: tx,
1750
- include: {
1751
- commandResults: true,
1752
- effects: true
1753
- }
1754
- })).commandResults[0].returnValues[0].bcs;
1755
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
311
+ getMarginManagerHasBaseDebt(marginManagerKey) {
312
+ return this.#marginManagerQueries.getMarginManagerHasBaseDebt(marginManagerKey);
1756
313
  }
1757
- /**
1758
- * @description Get the minimum borrow risk ratio for a deepbook pool
1759
- * @param {string} poolKey The key to identify the pool
1760
- * @returns {Promise<number>} The minimum borrow risk ratio as a decimal (e.g., 1.25 for 125%)
1761
- */
1762
- async getMinBorrowRiskRatio(poolKey) {
1763
- const tx = new Transaction();
1764
- tx.add(this.marginRegistry.minBorrowRiskRatio(poolKey));
1765
- const bytes = (await this.#client.core.simulateTransaction({
1766
- transaction: tx,
1767
- include: {
1768
- commandResults: true,
1769
- effects: true
1770
- }
1771
- })).commandResults[0].returnValues[0].bcs;
1772
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
314
+ getMarginManagerBalanceManagerId(marginManagerAddress) {
315
+ return this.#marginManagerQueries.getMarginManagerBalanceManagerId(marginManagerAddress);
1773
316
  }
1774
- /**
1775
- * @description Get the liquidation risk ratio for a deepbook pool
1776
- * @param {string} poolKey The key to identify the pool
1777
- * @returns {Promise<number>} The liquidation risk ratio as a decimal (e.g., 1.125 for 112.5%)
1778
- */
1779
- async getLiquidationRiskRatio(poolKey) {
1780
- const tx = new Transaction();
1781
- tx.add(this.marginRegistry.liquidationRiskRatio(poolKey));
1782
- const bytes = (await this.#client.core.simulateTransaction({
1783
- transaction: tx,
1784
- include: {
1785
- commandResults: true,
1786
- effects: true
1787
- }
1788
- })).commandResults[0].returnValues[0].bcs;
1789
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
317
+ getMarginManagerAssets(marginManagerKey, decimals = 6) {
318
+ return this.#marginManagerQueries.getMarginManagerAssets(marginManagerKey, decimals);
1790
319
  }
1791
- /**
1792
- * @description Get the target liquidation risk ratio for a deepbook pool
1793
- * @param {string} poolKey The key to identify the pool
1794
- * @returns {Promise<number>} The target liquidation risk ratio as a decimal (e.g., 1.25 for 125%)
1795
- */
1796
- async getTargetLiquidationRiskRatio(poolKey) {
1797
- const tx = new Transaction();
1798
- tx.add(this.marginRegistry.targetLiquidationRiskRatio(poolKey));
1799
- const bytes = (await this.#client.core.simulateTransaction({
1800
- transaction: tx,
1801
- include: {
1802
- commandResults: true,
1803
- effects: true
1804
- }
1805
- })).commandResults[0].returnValues[0].bcs;
1806
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
320
+ getMarginManagerDebts(marginManagerKey, decimals = 6) {
321
+ return this.#marginManagerQueries.getMarginManagerDebts(marginManagerKey, decimals);
1807
322
  }
1808
- /**
1809
- * @description Get the user liquidation reward for a deepbook pool
1810
- * @param {string} poolKey The key to identify the pool
1811
- * @returns {Promise<number>} The user liquidation reward as a decimal (e.g., 0.05 for 5%)
1812
- */
1813
- async getUserLiquidationReward(poolKey) {
1814
- const tx = new Transaction();
1815
- tx.add(this.marginRegistry.userLiquidationReward(poolKey));
1816
- const bytes = (await this.#client.core.simulateTransaction({
1817
- transaction: tx,
1818
- include: {
1819
- commandResults: true,
1820
- effects: true
1821
- }
1822
- })).commandResults[0].returnValues[0].bcs;
1823
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
323
+ getMarginManagerState(marginManagerKey, decimals = 6) {
324
+ return this.#marginManagerQueries.getMarginManagerState(marginManagerKey, decimals);
1824
325
  }
1825
- /**
1826
- * @description Get the pool liquidation reward for a deepbook pool
1827
- * @param {string} poolKey The key to identify the pool
1828
- * @returns {Promise<number>} The pool liquidation reward as a decimal (e.g., 0.05 for 5%)
1829
- */
1830
- async getPoolLiquidationReward(poolKey) {
1831
- const tx = new Transaction();
1832
- tx.add(this.marginRegistry.poolLiquidationReward(poolKey));
1833
- const bytes = (await this.#client.core.simulateTransaction({
1834
- transaction: tx,
1835
- include: {
1836
- commandResults: true,
1837
- effects: true
1838
- }
1839
- })).commandResults[0].returnValues[0].bcs;
1840
- return Number(bcs.U64.parse(bytes)) / FLOAT_SCALAR;
326
+ getMarginManagerStates(marginManagers, decimals = 6) {
327
+ return this.#marginManagerQueries.getMarginManagerStates(marginManagers, decimals);
1841
328
  }
1842
- /**
1843
- * @description Get all allowed maintainer cap IDs
1844
- * @returns {Promise<string[]>} Array of allowed maintainer cap IDs
1845
- */
1846
- async getAllowedMaintainers() {
1847
- const tx = new Transaction();
1848
- tx.add(this.marginRegistry.allowedMaintainers());
1849
- const bytes = (await this.#client.core.simulateTransaction({
1850
- transaction: tx,
1851
- include: {
1852
- commandResults: true,
1853
- effects: true
1854
- }
1855
- })).commandResults[0].returnValues[0].bcs;
1856
- return VecSet(bcs.Address).parse(bytes).contents.map((id) => normalizeSuiAddress(id));
329
+ getMarginManagerBaseBalance(marginManagerKey, decimals = 9) {
330
+ return this.#marginManagerQueries.getMarginManagerBaseBalance(marginManagerKey, decimals);
1857
331
  }
1858
- /**
1859
- * @description Get all allowed pause cap IDs
1860
- * @returns {Promise<string[]>} Array of allowed pause cap IDs
1861
- */
1862
- async getAllowedPauseCaps() {
1863
- const tx = new Transaction();
1864
- tx.add(this.marginRegistry.allowedPauseCaps());
1865
- const bytes = (await this.#client.core.simulateTransaction({
1866
- transaction: tx,
1867
- include: {
1868
- commandResults: true,
1869
- effects: true
1870
- }
1871
- })).commandResults[0].returnValues[0].bcs;
1872
- return VecSet(bcs.Address).parse(bytes).contents.map((id) => normalizeSuiAddress(id));
332
+ getMarginManagerQuoteBalance(marginManagerKey, decimals = 9) {
333
+ return this.#marginManagerQueries.getMarginManagerQuoteBalance(marginManagerKey, decimals);
1873
334
  }
1874
- /**
1875
- * @description Check if a pool is a stable pool
1876
- * @param {string} poolKey Key of the pool
1877
- * @returns {Promise<boolean>} Whether the pool is a stable pool
1878
- */
1879
- async stablePool(poolKey) {
1880
- const tx = new Transaction();
1881
- tx.add(this.deepBook.stablePool(poolKey));
1882
- const bytes = (await this.#client.core.simulateTransaction({
1883
- transaction: tx,
1884
- include: {
1885
- commandResults: true,
1886
- effects: true
1887
- }
1888
- })).commandResults[0].returnValues[0].bcs;
1889
- return bcs.bool().parse(bytes);
335
+ getMarginManagerDeepBalance(marginManagerKey, decimals = 6) {
336
+ return this.#marginManagerQueries.getMarginManagerDeepBalance(marginManagerKey, decimals);
1890
337
  }
1891
- /**
1892
- * @description Check if a pool is registered
1893
- * @param {string} poolKey Key of the pool
1894
- * @returns {Promise<boolean>} Whether the pool is registered
1895
- */
1896
- async registeredPool(poolKey) {
1897
- const tx = new Transaction();
1898
- tx.add(this.deepBook.registeredPool(poolKey));
1899
- const bytes = (await this.#client.core.simulateTransaction({
1900
- transaction: tx,
1901
- include: {
1902
- commandResults: true,
1903
- effects: true
1904
- }
1905
- })).commandResults[0].returnValues[0].bcs;
1906
- return bcs.bool().parse(bytes);
338
+ getMarginManagerBalances(marginManagers, decimals = 9) {
339
+ return this.#marginManagerQueries.getMarginManagerBalances(marginManagers, decimals);
1907
340
  }
1908
- /**
1909
- * @description Get the quote quantity out using input token as fee
1910
- * @param {string} poolKey Key of the pool
1911
- * @param {number} baseQuantity Base quantity
1912
- * @returns {Promise<{baseQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
1913
- */
1914
- async getQuoteQuantityOutInputFee(poolKey, baseQuantity) {
1915
- const tx = new Transaction();
1916
- const pool = this.#config.getPool(poolKey);
1917
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
1918
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
1919
- tx.add(this.deepBook.getQuoteQuantityOutInputFee(poolKey, baseQuantity));
1920
- const res = await this.#client.core.simulateTransaction({
1921
- transaction: tx,
1922
- include: {
1923
- commandResults: true,
1924
- effects: true
1925
- }
1926
- });
1927
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
1928
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
1929
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
1930
- return {
1931
- baseQuantity,
1932
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
1933
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
1934
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
1935
- };
341
+ getConditionalOrderIds(marginManagerKey) {
342
+ return this.#tpslQueries.getConditionalOrderIds(marginManagerKey);
1936
343
  }
1937
- /**
1938
- * @description Get the base quantity out using input token as fee
1939
- * @param {string} poolKey Key of the pool
1940
- * @param {number} quoteQuantity Quote quantity
1941
- * @returns {Promise<{quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
1942
- */
1943
- async getBaseQuantityOutInputFee(poolKey, quoteQuantity) {
1944
- const tx = new Transaction();
1945
- const pool = this.#config.getPool(poolKey);
1946
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
1947
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
1948
- tx.add(this.deepBook.getBaseQuantityOutInputFee(poolKey, quoteQuantity));
1949
- const res = await this.#client.core.simulateTransaction({
1950
- transaction: tx,
1951
- include: {
1952
- commandResults: true,
1953
- effects: true
1954
- }
1955
- });
1956
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
1957
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
1958
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
1959
- return {
1960
- quoteQuantity,
1961
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
1962
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
1963
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
1964
- };
344
+ getLowestTriggerAbovePrice(marginManagerKey) {
345
+ return this.#tpslQueries.getLowestTriggerAbovePrice(marginManagerKey);
1965
346
  }
1966
- /**
1967
- * @description Get the quantity out using input token as fee
1968
- * @param {string} poolKey Key of the pool
1969
- * @param {number} baseQuantity Base quantity
1970
- * @param {number} quoteQuantity Quote quantity
1971
- * @returns {Promise<{baseQuantity: number, quoteQuantity: number, baseOut: number, quoteOut: number, deepRequired: number}>}
1972
- */
1973
- async getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity) {
1974
- const tx = new Transaction();
1975
- const pool = this.#config.getPool(poolKey);
1976
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
1977
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
1978
- tx.add(this.deepBook.getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity));
1979
- const res = await this.#client.core.simulateTransaction({
1980
- transaction: tx,
1981
- include: {
1982
- commandResults: true,
1983
- effects: true
1984
- }
1985
- });
1986
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
1987
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
1988
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
1989
- return {
1990
- baseQuantity,
1991
- quoteQuantity,
1992
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
1993
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
1994
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
1995
- };
347
+ getHighestTriggerBelowPrice(marginManagerKey) {
348
+ return this.#tpslQueries.getHighestTriggerBelowPrice(marginManagerKey);
1996
349
  }
1997
- /**
1998
- * @description Get the base quantity needed to receive target quote quantity
1999
- * @param {string} poolKey Key of the pool
2000
- * @param {number} targetQuoteQuantity Target quote quantity
2001
- * @param {boolean} payWithDeep Whether to pay fees with DEEP
2002
- * @returns {Promise<{baseIn: number, quoteOut: number, deepRequired: number}>}
2003
- */
2004
- async getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep) {
2005
- const tx = new Transaction();
2006
- const pool = this.#config.getPool(poolKey);
2007
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2008
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2009
- tx.add(this.deepBook.getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep));
2010
- const res = await this.#client.core.simulateTransaction({
2011
- transaction: tx,
2012
- include: {
2013
- commandResults: true,
2014
- effects: true
2015
- }
2016
- });
2017
- const baseIn = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
2018
- const quoteOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
2019
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
2020
- return {
2021
- baseIn: Number((baseIn / baseScalar).toFixed(9)),
2022
- quoteOut: Number((quoteOut / quoteScalar).toFixed(9)),
2023
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
2024
- };
350
+ isPoolEnabledForMargin(poolKey) {
351
+ return this.#registryQueries.isPoolEnabledForMargin(poolKey);
2025
352
  }
2026
- /**
2027
- * @description Get the quote quantity needed to receive target base quantity
2028
- * @param {string} poolKey Key of the pool
2029
- * @param {number} targetBaseQuantity Target base quantity
2030
- * @param {boolean} payWithDeep Whether to pay fees with DEEP
2031
- * @returns {Promise<{baseOut: number, quoteIn: number, deepRequired: number}>}
2032
- */
2033
- async getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep) {
2034
- const tx = new Transaction();
2035
- const pool = this.#config.getPool(poolKey);
2036
- const baseScalar = this.#config.getCoin(pool.baseCoin).scalar;
2037
- const quoteScalar = this.#config.getCoin(pool.quoteCoin).scalar;
2038
- tx.add(this.deepBook.getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep));
2039
- const res = await this.#client.core.simulateTransaction({
2040
- transaction: tx,
2041
- include: {
2042
- commandResults: true,
2043
- effects: true
2044
- }
2045
- });
2046
- const baseOut = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
2047
- const quoteIn = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
2048
- const deepRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
2049
- return {
2050
- baseOut: Number((baseOut / baseScalar).toFixed(9)),
2051
- quoteIn: Number((quoteIn / quoteScalar).toFixed(9)),
2052
- deepRequired: Number((deepRequired / DEEP_SCALAR).toFixed(9))
2053
- };
353
+ getMarginManagerIdsForOwner(owner) {
354
+ return this.#registryQueries.getMarginManagerIdsForOwner(owner);
2054
355
  }
2055
- /**
2056
- * @description Get account order details for a balance manager
2057
- * @param {string} poolKey Key of the pool
2058
- * @param {string} managerKey Key of the balance manager
2059
- * @returns {Promise<Array>} Array of order details
2060
- */
2061
- async getAccountOrderDetails(poolKey, managerKey) {
2062
- const tx = new Transaction();
2063
- tx.add(this.deepBook.getAccountOrderDetails(poolKey, managerKey));
2064
- const res = await this.#client.core.simulateTransaction({
2065
- transaction: tx,
2066
- include: {
2067
- commandResults: true,
2068
- effects: true
2069
- }
2070
- });
2071
- try {
2072
- const orderInformation = res.commandResults[0].returnValues[0].bcs;
2073
- return bcs.vector(Order).parse(new Uint8Array(orderInformation));
2074
- } catch {
2075
- return [];
2076
- }
356
+ getBaseMarginPoolId(poolKey) {
357
+ return this.#registryQueries.getBaseMarginPoolId(poolKey);
2077
358
  }
2078
- /**
2079
- * @description Get the DEEP required for an order
2080
- * @param {string} poolKey Key of the pool
2081
- * @param {number} baseQuantity Base quantity
2082
- * @param {number} price Price
2083
- * @returns {Promise<{deepRequiredTaker: number, deepRequiredMaker: number}>}
2084
- */
2085
- async getOrderDeepRequired(poolKey, baseQuantity, price) {
2086
- const tx = new Transaction();
2087
- tx.add(this.deepBook.getOrderDeepRequired(poolKey, baseQuantity, price));
2088
- const res = await this.#client.core.simulateTransaction({
2089
- transaction: tx,
2090
- include: {
2091
- commandResults: true,
2092
- effects: true
2093
- }
2094
- });
2095
- const deepRequiredTaker = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
2096
- const deepRequiredMaker = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
2097
- return {
2098
- deepRequiredTaker: Number((deepRequiredTaker / DEEP_SCALAR).toFixed(9)),
2099
- deepRequiredMaker: Number((deepRequiredMaker / DEEP_SCALAR).toFixed(9))
2100
- };
359
+ getQuoteMarginPoolId(poolKey) {
360
+ return this.#registryQueries.getQuoteMarginPoolId(poolKey);
2101
361
  }
2102
- /**
2103
- * @description Check if account exists for a balance manager
2104
- * @param {string} poolKey Key of the pool
2105
- * @param {string} managerKey Key of the balance manager
2106
- * @returns {Promise<boolean>} Whether account exists
2107
- */
2108
- async accountExists(poolKey, managerKey) {
2109
- const tx = new Transaction();
2110
- tx.add(this.deepBook.accountExists(poolKey, managerKey));
2111
- const bytes = (await this.#client.core.simulateTransaction({
2112
- transaction: tx,
2113
- include: {
2114
- commandResults: true,
2115
- effects: true
2116
- }
2117
- })).commandResults[0].returnValues[0].bcs;
2118
- return bcs.bool().parse(bytes);
362
+ getMinWithdrawRiskRatio(poolKey) {
363
+ return this.#registryQueries.getMinWithdrawRiskRatio(poolKey);
2119
364
  }
2120
- /**
2121
- * @description Get the next epoch trade parameters
2122
- * @param {string} poolKey Key of the pool
2123
- * @returns {Promise<{takerFee: number, makerFee: number, stakeRequired: number}>}
2124
- */
2125
- async poolTradeParamsNext(poolKey) {
2126
- const tx = new Transaction();
2127
- tx.add(this.deepBook.poolTradeParamsNext(poolKey));
2128
- const res = await this.#client.core.simulateTransaction({
2129
- transaction: tx,
2130
- include: {
2131
- commandResults: true,
2132
- effects: true
2133
- }
2134
- });
2135
- const takerFee = Number(bcs.U64.parse(res.commandResults[0].returnValues[0].bcs));
2136
- const makerFee = Number(bcs.U64.parse(res.commandResults[0].returnValues[1].bcs));
2137
- const stakeRequired = Number(bcs.U64.parse(res.commandResults[0].returnValues[2].bcs));
2138
- return {
2139
- takerFee: takerFee / FLOAT_SCALAR,
2140
- makerFee: makerFee / FLOAT_SCALAR,
2141
- stakeRequired: stakeRequired / DEEP_SCALAR
2142
- };
365
+ getMinBorrowRiskRatio(poolKey) {
366
+ return this.#registryQueries.getMinBorrowRiskRatio(poolKey);
2143
367
  }
2144
- /**
2145
- * @description Get the quorum for a pool
2146
- * @param {string} poolKey Key of the pool
2147
- * @returns {Promise<number>} The quorum amount in DEEP
2148
- */
2149
- async quorum(poolKey) {
2150
- const tx = new Transaction();
2151
- tx.add(this.deepBook.quorum(poolKey));
2152
- const bytes = (await this.#client.core.simulateTransaction({
2153
- transaction: tx,
2154
- include: {
2155
- commandResults: true,
2156
- effects: true
2157
- }
2158
- })).commandResults[0].returnValues[0].bcs;
2159
- return Number(bcs.U64.parse(bytes)) / DEEP_SCALAR;
368
+ getLiquidationRiskRatio(poolKey) {
369
+ return this.#registryQueries.getLiquidationRiskRatio(poolKey);
2160
370
  }
2161
- /**
2162
- * @description Get the pool ID
2163
- * @param {string} poolKey Key of the pool
2164
- * @returns {Promise<string>} The pool ID
2165
- */
2166
- async poolId(poolKey) {
2167
- const tx = new Transaction();
2168
- tx.add(this.deepBook.poolId(poolKey));
2169
- const bytes = (await this.#client.core.simulateTransaction({
2170
- transaction: tx,
2171
- include: {
2172
- commandResults: true,
2173
- effects: true
2174
- }
2175
- })).commandResults[0].returnValues[0].bcs;
2176
- return normalizeSuiAddress(bcs.Address.parse(bytes));
371
+ getTargetLiquidationRiskRatio(poolKey) {
372
+ return this.#registryQueries.getTargetLiquidationRiskRatio(poolKey);
2177
373
  }
2178
- /**
2179
- * @description Check if a limit order can be placed
2180
- * @param {CanPlaceLimitOrderParams} params Parameters for checking limit order placement
2181
- * @returns {Promise<boolean>} Whether order can be placed
2182
- */
2183
- async canPlaceLimitOrder(params) {
2184
- const tx = new Transaction();
2185
- tx.add(this.deepBook.canPlaceLimitOrder(params));
2186
- const bytes = (await this.#client.core.simulateTransaction({
2187
- transaction: tx,
2188
- include: {
2189
- commandResults: true,
2190
- effects: true
2191
- }
2192
- })).commandResults[0].returnValues[0].bcs;
2193
- return bcs.bool().parse(bytes);
374
+ getUserLiquidationReward(poolKey) {
375
+ return this.#registryQueries.getUserLiquidationReward(poolKey);
2194
376
  }
2195
- /**
2196
- * @description Check if a market order can be placed
2197
- * @param {CanPlaceMarketOrderParams} params Parameters for checking market order placement
2198
- * @returns {Promise<boolean>} Whether order can be placed
2199
- */
2200
- async canPlaceMarketOrder(params) {
2201
- const tx = new Transaction();
2202
- tx.add(this.deepBook.canPlaceMarketOrder(params));
2203
- const bytes = (await this.#client.core.simulateTransaction({
2204
- transaction: tx,
2205
- include: {
2206
- commandResults: true,
2207
- effects: true
2208
- }
2209
- })).commandResults[0].returnValues[0].bcs;
2210
- return bcs.bool().parse(bytes);
377
+ getPoolLiquidationReward(poolKey) {
378
+ return this.#registryQueries.getPoolLiquidationReward(poolKey);
2211
379
  }
2212
- /**
2213
- * @description Check if market order params are valid
2214
- * @param {string} poolKey Key of the pool
2215
- * @param {number} quantity Quantity
2216
- * @returns {Promise<boolean>} Whether params are valid
2217
- */
2218
- async checkMarketOrderParams(poolKey, quantity) {
2219
- const tx = new Transaction();
2220
- tx.add(this.deepBook.checkMarketOrderParams(poolKey, quantity));
2221
- const bytes = (await this.#client.core.simulateTransaction({
2222
- transaction: tx,
2223
- include: {
2224
- commandResults: true,
2225
- effects: true
2226
- }
2227
- })).commandResults[0].returnValues[0].bcs;
2228
- return bcs.bool().parse(bytes);
380
+ getAllowedMaintainers() {
381
+ return this.#registryQueries.getAllowedMaintainers();
2229
382
  }
2230
- /**
2231
- * @description Check if limit order params are valid
2232
- * @param {string} poolKey Key of the pool
2233
- * @param {number} price Price
2234
- * @param {number} quantity Quantity
2235
- * @param {number} expireTimestamp Expiration timestamp
2236
- * @returns {Promise<boolean>} Whether params are valid
2237
- */
2238
- async checkLimitOrderParams(poolKey, price, quantity, expireTimestamp) {
2239
- const tx = new Transaction();
2240
- tx.add(this.deepBook.checkLimitOrderParams(poolKey, price, quantity, expireTimestamp));
2241
- const bytes = (await this.#client.core.simulateTransaction({
2242
- transaction: tx,
2243
- include: {
2244
- commandResults: true,
2245
- effects: true
2246
- }
2247
- })).commandResults[0].returnValues[0].bcs;
2248
- return bcs.bool().parse(bytes);
383
+ getAllowedPauseCaps() {
384
+ return this.#registryQueries.getAllowedPauseCaps();
2249
385
  }
2250
- /**
2251
- * @description Helper function to format token amounts without floating point errors
2252
- * @param {bigint} rawAmount The raw amount as bigint
2253
- * @param {number} scalar The token scalar (e.g., 1000000000 for 9 decimals)
2254
- * @param {number} decimals Number of decimal places to show
2255
- * @returns {string} Formatted amount as string
2256
- */
2257
- #formatTokenAmount(rawAmount, scalar, decimals) {
2258
- const scalarBigInt = BigInt(scalar);
2259
- const integerPart = rawAmount / scalarBigInt;
2260
- const fractionalPart = rawAmount % scalarBigInt;
2261
- if (fractionalPart === 0n) return integerPart.toString();
2262
- const scalarDigits = scalar.toString().length - 1;
2263
- const trimmed = fractionalPart.toString().padStart(scalarDigits, "0").slice(0, decimals).replace(/0+$/, "");
2264
- if (!trimmed) return integerPart.toString();
2265
- return `${integerPart}.${trimmed}`;
386
+ decodeOrderId(encodedOrderId) {
387
+ return {
388
+ isBid: encodedOrderId >> 127n === 0n,
389
+ price: Number(encodedOrderId >> 64n & (1n << 63n) - 1n),
390
+ orderId: Number(encodedOrderId & (1n << 64n) - 1n)
391
+ };
2266
392
  }
2267
393
  };
2268
394