@haneullabs/deepbook 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +974 -0
  2. package/README.md +11 -0
  3. package/dist/cjs/client.d.ts +198 -0
  4. package/dist/cjs/client.js +630 -0
  5. package/dist/cjs/client.js.map +7 -0
  6. package/dist/cjs/index.d.ts +1 -0
  7. package/dist/cjs/index.js +19 -0
  8. package/dist/cjs/index.js.map +7 -0
  9. package/dist/cjs/package.json +4 -0
  10. package/dist/cjs/types/bcs.d.ts +11 -0
  11. package/dist/cjs/types/bcs.js +36 -0
  12. package/dist/cjs/types/bcs.js.map +7 -0
  13. package/dist/cjs/types/index.d.ts +51 -0
  14. package/dist/cjs/types/index.js +38 -0
  15. package/dist/cjs/types/index.js.map +7 -0
  16. package/dist/cjs/utils/constants.d.ts +7 -0
  17. package/dist/cjs/utils/constants.js +38 -0
  18. package/dist/cjs/utils/constants.js.map +7 -0
  19. package/dist/cjs/utils/index.d.ts +1 -0
  20. package/dist/cjs/utils/index.js +19 -0
  21. package/dist/cjs/utils/index.js.map +7 -0
  22. package/dist/esm/client.d.ts +198 -0
  23. package/dist/esm/client.js +623 -0
  24. package/dist/esm/client.js.map +7 -0
  25. package/dist/esm/index.d.ts +1 -0
  26. package/dist/esm/index.js +2 -0
  27. package/dist/esm/index.js.map +7 -0
  28. package/dist/esm/package.json +4 -0
  29. package/dist/esm/types/bcs.d.ts +11 -0
  30. package/dist/esm/types/bcs.js +16 -0
  31. package/dist/esm/types/bcs.js.map +7 -0
  32. package/dist/esm/types/index.d.ts +51 -0
  33. package/dist/esm/types/index.js +17 -0
  34. package/dist/esm/types/index.js.map +7 -0
  35. package/dist/esm/utils/constants.d.ts +7 -0
  36. package/dist/esm/utils/constants.js +18 -0
  37. package/dist/esm/utils/constants.js.map +7 -0
  38. package/dist/esm/utils/index.d.ts +1 -0
  39. package/dist/esm/utils/index.js +2 -0
  40. package/dist/esm/utils/index.js.map +7 -0
  41. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  42. package/dist/tsconfig.tsbuildinfo +1 -0
  43. package/package.json +56 -0
  44. package/src/client.ts +786 -0
  45. package/src/index.ts +4 -0
  46. package/src/types/bcs.ts +16 -0
  47. package/src/types/index.ts +71 -0
  48. package/src/utils/constants.ts +18 -0
  49. package/src/utils/index.ts +4 -0
@@ -0,0 +1,630 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __typeError = (msg) => {
7
+ throw TypeError(msg);
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
22
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
23
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
24
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
26
+ var client_exports = {};
27
+ __export(client_exports, {
28
+ DeepBookClient: () => DeepBookClient
29
+ });
30
+ module.exports = __toCommonJS(client_exports);
31
+ var import_bcs = require("@haneullabs/haneul/bcs");
32
+ var import_client = require("@haneullabs/haneul/client");
33
+ var import_transactions = require("@haneullabs/haneul/transactions");
34
+ var import_utils = require("@haneullabs/haneul/utils");
35
+ var import_bcs2 = require("./types/bcs.js");
36
+ var import_types = require("./types/index.js");
37
+ var import_utils2 = require("./utils/index.js");
38
+ var _poolTypeArgsCache, _DeepBookClient_instances, checkAccountCap_fn, checkAddress_fn, nextClientOrderId_fn;
39
+ const DUMMY_ADDRESS = (0, import_utils.normalizeHaneulAddress)("0x0");
40
+ class DeepBookClient {
41
+ /**
42
+ *
43
+ * @param haneulClient connection to fullnode
44
+ * @param accountCap (optional) only required for wrting operations
45
+ * @param currentAddress (optional) address of the current user (default: DUMMY_ADDRESS)
46
+ */
47
+ constructor(haneulClient = new import_client.HaneulClient({ url: (0, import_client.getFullnodeUrl)("testnet") }), accountCap = void 0, currentAddress = DUMMY_ADDRESS, clientOrderId = 0) {
48
+ this.haneulClient = haneulClient;
49
+ this.accountCap = accountCap;
50
+ this.currentAddress = currentAddress;
51
+ this.clientOrderId = clientOrderId;
52
+ __privateAdd(this, _DeepBookClient_instances);
53
+ __privateAdd(this, _poolTypeArgsCache, /* @__PURE__ */ new Map());
54
+ }
55
+ /**
56
+ * @param cap set the account cap for interacting with DeepBook
57
+ */
58
+ async setAccountCap(cap) {
59
+ this.accountCap = cap;
60
+ }
61
+ /**
62
+ * @description Create pool for trading pair
63
+ * @param baseAssetType Full coin type of the base asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::wbtc::WBTC"
64
+ * @param quoteAssetType Full coin type of quote asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::usdt::USDT"
65
+ * @param tickSize Minimal Price Change Accuracy of this pool, eg: 10000000. The number must be an integer float scaled by `FLOAT_SCALING_FACTOR`.
66
+ * @param lotSize Minimal Lot Change Accuracy of this pool, eg: 10000.
67
+ */
68
+ createPool(baseAssetType, quoteAssetType, tickSize, lotSize) {
69
+ const tx = new import_transactions.Transaction();
70
+ const [coin] = tx.splitCoins(tx.gas, [import_utils2.CREATION_FEE]);
71
+ tx.moveCall({
72
+ typeArguments: [baseAssetType, quoteAssetType],
73
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::create_pool`,
74
+ arguments: [tx.pure.u64(tickSize), tx.pure.u64(lotSize), coin]
75
+ });
76
+ return tx;
77
+ }
78
+ /**
79
+ * @description Create pool for trading pair
80
+ * @param baseAssetType Full coin type of the base asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::wbtc::WBTC"
81
+ * @param quoteAssetType Full coin type of quote asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::usdt::USDT"
82
+ * @param tickSize Minimal Price Change Accuracy of this pool, eg: 10000000. The number must be an interger float scaled by `FLOAT_SCALING_FACTOR`.
83
+ * @param lotSize Minimal Lot Change Accuracy of this pool, eg: 10000.
84
+ * @param takerFeeRate Customized taker fee rate, float scaled by `FLOAT_SCALING_FACTOR`, Taker_fee_rate of 0.25% should be 2_500_000 for example
85
+ * @param makerRebateRate Customized maker rebate rate, float scaled by `FLOAT_SCALING_FACTOR`, should be less than or equal to the taker_rebate_rate
86
+ */
87
+ createCustomizedPool(baseAssetType, quoteAssetType, tickSize, lotSize, takerFeeRate, makerRebateRate) {
88
+ const tx = new import_transactions.Transaction();
89
+ const [coin] = tx.splitCoins(tx.gas, [import_utils2.CREATION_FEE]);
90
+ tx.moveCall({
91
+ typeArguments: [baseAssetType, quoteAssetType],
92
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::create_customized_pool`,
93
+ arguments: [
94
+ tx.pure.u64(tickSize),
95
+ tx.pure.u64(lotSize),
96
+ tx.pure.u64(takerFeeRate),
97
+ tx.pure.u64(makerRebateRate),
98
+ coin
99
+ ]
100
+ });
101
+ return tx;
102
+ }
103
+ /**
104
+ * @description Create Account Cap
105
+ * @param tx
106
+ */
107
+ createAccountCap(tx) {
108
+ const [cap] = tx.moveCall({
109
+ typeArguments: [],
110
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::create_account`,
111
+ arguments: []
112
+ });
113
+ return cap;
114
+ }
115
+ /**
116
+ * @description Create and Transfer custodian account to user
117
+ * @param currentAddress current address of the user
118
+ * @param tx
119
+ */
120
+ createAccount(currentAddress = this.currentAddress, tx = new import_transactions.Transaction()) {
121
+ const cap = this.createAccountCap(tx);
122
+ tx.transferObjects([cap], __privateMethod(this, _DeepBookClient_instances, checkAddress_fn).call(this, currentAddress));
123
+ return tx;
124
+ }
125
+ /**
126
+ * @description Create and Transfer custodian account to user
127
+ * @param currentAddress: current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
128
+ * @param accountCap: Object id of Account Capacity under user address, created after invoking createAccount, eg: "0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3"
129
+ */
130
+ createChildAccountCap(currentAddress = this.currentAddress, accountCap = this.accountCap) {
131
+ const tx = new import_transactions.Transaction();
132
+ const [childCap] = tx.moveCall({
133
+ typeArguments: [],
134
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CUSTODIAN}::create_child_account_cap`,
135
+ arguments: [tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this, accountCap))]
136
+ });
137
+ tx.transferObjects([childCap], __privateMethod(this, _DeepBookClient_instances, checkAddress_fn).call(this, currentAddress));
138
+ return tx;
139
+ }
140
+ /**
141
+ * @description construct transaction for depositing asset into a pool.
142
+ * @param poolId the pool id for the deposit
143
+ * @param coinId the coin used for the deposit. You can omit this argument if you are depositing SUI, in which case
144
+ * gas coin will be used
145
+ * @param amount the amount of coin to deposit. If omitted, the entire balance of the coin will be deposited
146
+ */
147
+ async deposit(poolId, coinId = void 0, quantity = void 0) {
148
+ const tx = new import_transactions.Transaction();
149
+ const [baseAsset, quoteAsset] = await this.getPoolTypeArgs(poolId);
150
+ const hasSui = baseAsset === import_utils2.NORMALIZED_HANEUL_COIN_TYPE || quoteAsset === import_utils2.NORMALIZED_HANEUL_COIN_TYPE;
151
+ if (coinId === void 0 && !hasSui) {
152
+ throw new Error("coinId must be specified if neither baseAsset nor quoteAsset is SUI");
153
+ }
154
+ const inputCoin = coinId ? tx.object(coinId) : tx.gas;
155
+ const [coin] = quantity ? tx.splitCoins(inputCoin, [quantity]) : [inputCoin];
156
+ const coinType = coinId ? await this.getCoinType(coinId) : import_utils2.NORMALIZED_HANEUL_COIN_TYPE;
157
+ if (coinType !== baseAsset && coinType !== quoteAsset) {
158
+ throw new Error(
159
+ `coin ${coinId} of ${coinType} type is not a valid asset for pool ${poolId}, which supports ${baseAsset} and ${quoteAsset}`
160
+ );
161
+ }
162
+ const functionName = coinType === baseAsset ? "deposit_base" : "deposit_quote";
163
+ tx.moveCall({
164
+ typeArguments: [baseAsset, quoteAsset],
165
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::${functionName}`,
166
+ arguments: [tx.object(poolId), coin, tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))]
167
+ });
168
+ return tx;
169
+ }
170
+ /**
171
+ * @description construct transaction for withdrawing asset from a pool.
172
+ * @param poolId the pool id for the withdraw
173
+ * @param amount the amount of coin to withdraw
174
+ * @param assetType Base or Quote
175
+ * @param recipientAddress the address to receive the withdrawn asset. If omitted, `this.currentAddress` will be used. The function
176
+ * will throw if the `recipientAddress === DUMMY_ADDRESS`
177
+ */
178
+ async withdraw(poolId, quantity, assetType, recipientAddress = this.currentAddress) {
179
+ const tx = new import_transactions.Transaction();
180
+ const functionName = assetType === "base" ? "withdraw_base" : "withdraw_quote";
181
+ const [withdraw] = tx.moveCall({
182
+ typeArguments: await this.getPoolTypeArgs(poolId),
183
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::${functionName}`,
184
+ arguments: [tx.object(poolId), tx.pure.u64(quantity), tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))]
185
+ });
186
+ tx.transferObjects([withdraw], __privateMethod(this, _DeepBookClient_instances, checkAddress_fn).call(this, recipientAddress));
187
+ return tx;
188
+ }
189
+ /**
190
+ * @description place a limit order
191
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
192
+ * @param price: price of the limit order. The number must be an interger float scaled by `FLOAT_SCALING_FACTOR`.
193
+ * @param quantity: quantity of the limit order in BASE ASSET, eg: 100000000.
194
+ * @param orderType: bid for buying base with quote, ask for selling base for quote
195
+ * @param expirationTimestamp: expiration timestamp of the limit order in ms, eg: 1620000000000. If omitted, the order will expire in 1 day
196
+ * from the time this function is called(not the time the transaction is executed)
197
+ * @param restriction restrictions on limit orders, explain in doc for more details, eg: 0
198
+ * @param clientOrderId a client side defined order number for bookkeeping purpose, e.g., "1", "2", etc. If omitted, the sdk will
199
+ * assign a increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
200
+ * @param selfMatchingPrevention: Options for self-match prevention. Right now only support `CANCEL_OLDEST`
201
+ */
202
+ async placeLimitOrder(poolId, price, quantity, orderType, expirationTimestamp = Date.now() + import_utils2.ORDER_DEFAULT_EXPIRATION_IN_MS, restriction = import_types.LimitOrderType.NO_RESTRICTION, clientOrderId = void 0, selfMatchingPrevention = import_types.SelfMatchingPreventionStyle.CANCEL_OLDEST) {
203
+ const tx = new import_transactions.Transaction();
204
+ const args = [
205
+ tx.object(poolId),
206
+ tx.pure.u64(clientOrderId ?? __privateMethod(this, _DeepBookClient_instances, nextClientOrderId_fn).call(this)),
207
+ tx.pure.u64(price),
208
+ tx.pure.u64(quantity),
209
+ tx.pure.u8(selfMatchingPrevention),
210
+ tx.pure.bool(orderType === "bid"),
211
+ tx.pure.u64(expirationTimestamp),
212
+ tx.pure.u8(restriction),
213
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID),
214
+ tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))
215
+ ];
216
+ tx.moveCall({
217
+ typeArguments: await this.getPoolTypeArgs(poolId),
218
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::place_limit_order`,
219
+ arguments: args
220
+ });
221
+ return tx;
222
+ }
223
+ /**
224
+ * @description place a market order
225
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
226
+ * @param quantity Amount of quote asset to swap in base asset
227
+ * @param orderType bid for buying base with quote, ask for selling base for quote
228
+ * @param baseCoin the objectId or the coin object of the base coin
229
+ * @param quoteCoin the objectId or the coin object of the quote coin
230
+ * @param clientOrderId a client side defined order id for bookkeeping purpose. eg: "1" , "2", ... If omitted, the sdk will
231
+ * assign an increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
232
+ * @param accountCap
233
+ * @param recipientAddress the address to receive the swapped asset. If omitted, `this.currentAddress` will be used. The function
234
+ * @param tx
235
+ */
236
+ async placeMarketOrder(accountCap, poolId, quantity, orderType, baseCoin = void 0, quoteCoin = void 0, clientOrderId = void 0, recipientAddress = this.currentAddress, tx = new import_transactions.Transaction()) {
237
+ const [baseAssetType, quoteAssetType] = await this.getPoolTypeArgs(poolId);
238
+ if (!baseCoin && orderType === "ask") {
239
+ throw new Error("Must specify a valid base coin for an ask order");
240
+ } else if (!quoteCoin && orderType === "bid") {
241
+ throw new Error("Must specify a valid quote coin for a bid order");
242
+ }
243
+ const emptyCoin = tx.moveCall({
244
+ typeArguments: [baseCoin ? quoteAssetType : baseAssetType],
245
+ target: `0x2::coin::zero`,
246
+ arguments: []
247
+ });
248
+ const [base_coin_ret, quote_coin_ret] = tx.moveCall({
249
+ typeArguments: [baseAssetType, quoteAssetType],
250
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::place_market_order`,
251
+ arguments: [
252
+ tx.object(poolId),
253
+ typeof accountCap === "string" ? tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this, accountCap)) : accountCap,
254
+ tx.pure.u64(clientOrderId ?? __privateMethod(this, _DeepBookClient_instances, nextClientOrderId_fn).call(this)),
255
+ tx.pure.u64(quantity),
256
+ tx.pure.bool(orderType === "bid"),
257
+ baseCoin ? tx.object(baseCoin) : emptyCoin,
258
+ quoteCoin ? tx.object(quoteCoin) : emptyCoin,
259
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID)
260
+ ]
261
+ });
262
+ const recipient = __privateMethod(this, _DeepBookClient_instances, checkAddress_fn).call(this, recipientAddress);
263
+ tx.transferObjects([base_coin_ret], recipient);
264
+ tx.transferObjects([quote_coin_ret], recipient);
265
+ return tx;
266
+ }
267
+ /**
268
+ * @description swap exact quote for base
269
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
270
+ * @param tokenObjectIn Object id of the token to swap: eg: "0x6e566fec4c388eeb78a7dab832c9f0212eb2ac7e8699500e203def5b41b9c70d"
271
+ * @param amountIn amount of token to buy or sell, eg: 10000000.
272
+ * @param currentAddress current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
273
+ * @param clientOrderId a client side defined order id for bookkeeping purpose, eg: "1" , "2", ... If omitted, the sdk will
274
+ * assign an increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
275
+ * @param tx
276
+ */
277
+ async swapExactQuoteForBase(poolId, tokenObjectIn, amountIn, currentAddress, clientOrderId, tx = new import_transactions.Transaction()) {
278
+ const [base_coin_ret, quote_coin_ret, _amount] = tx.moveCall({
279
+ typeArguments: await this.getPoolTypeArgs(poolId),
280
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::swap_exact_quote_for_base`,
281
+ arguments: [
282
+ tx.object(poolId),
283
+ tx.pure.u64(clientOrderId ?? __privateMethod(this, _DeepBookClient_instances, nextClientOrderId_fn).call(this)),
284
+ tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this)),
285
+ tx.pure.u64(String(amountIn)),
286
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID),
287
+ tx.object(tokenObjectIn)
288
+ ]
289
+ });
290
+ tx.transferObjects([base_coin_ret], currentAddress);
291
+ tx.transferObjects([quote_coin_ret], currentAddress);
292
+ return tx;
293
+ }
294
+ /**
295
+ * @description swap exact base for quote
296
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
297
+ * @param tokenObjectIn Object id of the token to swap: eg: "0x6e566fec4c388eeb78a7dab832c9f0212eb2ac7e8699500e203def5b41b9c70d"
298
+ * @param amountIn amount of token to buy or sell, eg: 10000000
299
+ * @param currentAddress current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
300
+ * @param clientOrderId a client side defined order number for bookkeeping purpose. eg: "1" , "2", ...
301
+ */
302
+ async swapExactBaseForQuote(poolId, tokenObjectIn, amountIn, currentAddress, clientOrderId = void 0) {
303
+ const tx = new import_transactions.Transaction();
304
+ const [baseAsset, quoteAsset] = await this.getPoolTypeArgs(poolId);
305
+ const [base_coin_ret, quote_coin_ret, _amount] = tx.moveCall({
306
+ typeArguments: [baseAsset, quoteAsset],
307
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::swap_exact_base_for_quote`,
308
+ arguments: [
309
+ tx.object(poolId),
310
+ tx.pure.u64(clientOrderId ?? __privateMethod(this, _DeepBookClient_instances, nextClientOrderId_fn).call(this)),
311
+ tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this)),
312
+ tx.object(String(amountIn)),
313
+ tx.object(tokenObjectIn),
314
+ tx.moveCall({
315
+ typeArguments: [quoteAsset],
316
+ target: `0x2::coin::zero`,
317
+ arguments: []
318
+ }),
319
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID)
320
+ ]
321
+ });
322
+ tx.transferObjects([base_coin_ret], currentAddress);
323
+ tx.transferObjects([quote_coin_ret], currentAddress);
324
+ return tx;
325
+ }
326
+ /**
327
+ * @description cancel an order
328
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
329
+ * @param orderId orderId of a limit order, you can find them through function query.list_open_orders eg: "0"
330
+ */
331
+ async cancelOrder(poolId, orderId) {
332
+ const tx = new import_transactions.Transaction();
333
+ tx.moveCall({
334
+ typeArguments: await this.getPoolTypeArgs(poolId),
335
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::cancel_order`,
336
+ arguments: [tx.object(poolId), tx.pure.u64(orderId), tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))]
337
+ });
338
+ return tx;
339
+ }
340
+ /**
341
+ * @description Cancel all limit orders under a certain account capacity
342
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
343
+ */
344
+ async cancelAllOrders(poolId) {
345
+ const tx = new import_transactions.Transaction();
346
+ tx.moveCall({
347
+ typeArguments: await this.getPoolTypeArgs(poolId),
348
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::cancel_all_orders`,
349
+ arguments: [tx.object(poolId), tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))]
350
+ });
351
+ return tx;
352
+ }
353
+ /**
354
+ * @description batch cancel order
355
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
356
+ * @param orderIds array of order ids you want to cancel, you can find your open orders by query.list_open_orders eg: ["0", "1", "2"]
357
+ */
358
+ async batchCancelOrder(poolId, orderIds) {
359
+ const tx = new import_transactions.Transaction();
360
+ tx.moveCall({
361
+ typeArguments: await this.getPoolTypeArgs(poolId),
362
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::batch_cancel_order`,
363
+ arguments: [
364
+ tx.object(poolId),
365
+ import_bcs.bcs.vector(import_bcs.bcs.U64).serialize(orderIds),
366
+ tx.object(__privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this))
367
+ ]
368
+ });
369
+ return tx;
370
+ }
371
+ /**
372
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
373
+ * @param orderIds array of expired order ids to clean, eg: ["0", "1", "2"]
374
+ * @param orderOwners array of Order owners, should be the owner addresses from the account capacities which placed the orders
375
+ */
376
+ async cleanUpExpiredOrders(poolId, orderIds, orderOwners) {
377
+ const tx = new import_transactions.Transaction();
378
+ tx.moveCall({
379
+ typeArguments: await this.getPoolTypeArgs(poolId),
380
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::clean_up_expired_orders`,
381
+ arguments: [
382
+ tx.object(poolId),
383
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID),
384
+ import_bcs.bcs.vector(import_bcs.bcs.U64).serialize(orderIds),
385
+ import_bcs.bcs.vector(import_bcs.bcs.Address).serialize(orderOwners)
386
+ ]
387
+ });
388
+ return tx;
389
+ }
390
+ /**
391
+ * @description returns paginated list of pools created in DeepBook by querying for the
392
+ * `PoolCreated` event. Warning: this method can return incomplete results if the upstream data source
393
+ * is pruned.
394
+ */
395
+ async getAllPools(input) {
396
+ const resp = await this.haneulClient.queryEvents({
397
+ query: { MoveEventType: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::PoolCreated` },
398
+ ...input
399
+ });
400
+ const pools = resp.data.map((event) => {
401
+ const rawEvent = event.parsedJson;
402
+ return {
403
+ poolId: rawEvent.pool_id,
404
+ baseAsset: (0, import_utils.normalizeStructTag)(rawEvent.base_asset.name),
405
+ quoteAsset: (0, import_utils.normalizeStructTag)(rawEvent.quote_asset.name)
406
+ };
407
+ });
408
+ return {
409
+ data: pools,
410
+ nextCursor: resp.nextCursor,
411
+ hasNextPage: resp.hasNextPage
412
+ };
413
+ }
414
+ /**
415
+ * @description Fetch metadata for a pool
416
+ * @param poolId object id of the pool
417
+ * @returns Metadata for the Pool
418
+ */
419
+ async getPoolInfo(poolId) {
420
+ const resp = await this.haneulClient.getObject({
421
+ id: poolId,
422
+ options: { showContent: true }
423
+ });
424
+ if (resp?.data?.content?.dataType !== "moveObject") {
425
+ throw new Error(`pool ${poolId} does not exist`);
426
+ }
427
+ const [baseAsset, quoteAsset] = (0, import_utils.parseStructTag)(resp.data.content.type).typeParams.map(
428
+ (t) => (0, import_utils.normalizeStructTag)(t)
429
+ );
430
+ return {
431
+ poolId,
432
+ baseAsset,
433
+ quoteAsset
434
+ };
435
+ }
436
+ async getPoolTypeArgs(poolId) {
437
+ if (!__privateGet(this, _poolTypeArgsCache).has(poolId)) {
438
+ const { baseAsset, quoteAsset } = await this.getPoolInfo(poolId);
439
+ const typeArgs = [baseAsset, quoteAsset];
440
+ __privateGet(this, _poolTypeArgsCache).set(poolId, typeArgs);
441
+ }
442
+ return __privateGet(this, _poolTypeArgsCache).get(poolId);
443
+ }
444
+ /**
445
+ * @description get the order status
446
+ * @param poolId: the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
447
+ * @param orderId the order id, eg: "1"
448
+ */
449
+ async getOrderStatus(poolId, orderId, accountCap = this.accountCap) {
450
+ const tx = new import_transactions.Transaction();
451
+ const cap = __privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this, accountCap);
452
+ tx.moveCall({
453
+ typeArguments: await this.getPoolTypeArgs(poolId),
454
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::get_order_status`,
455
+ arguments: [tx.object(poolId), tx.pure.u64(orderId), tx.object(cap)]
456
+ });
457
+ const results = (await this.haneulClient.devInspectTransactionBlock({
458
+ transactionBlock: tx,
459
+ sender: this.currentAddress
460
+ })).results;
461
+ if (!results) {
462
+ return void 0;
463
+ }
464
+ return import_bcs2.BcsOrder.parse(Uint8Array.from(results[0].returnValues[0][0]));
465
+ }
466
+ /**
467
+ * @description get the base and quote token in custodian account
468
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
469
+ * @param accountCap your accountCap, eg: 0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3. If not provided, `this.accountCap` will be used.
470
+ */
471
+ async getUserPosition(poolId, accountCap = void 0) {
472
+ const tx = new import_transactions.Transaction();
473
+ const cap = __privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this, accountCap);
474
+ tx.moveCall({
475
+ typeArguments: await this.getPoolTypeArgs(poolId),
476
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::account_balance`,
477
+ arguments: [tx.object((0, import_utils.normalizeHaneulObjectId)(poolId)), tx.object(cap)]
478
+ });
479
+ const [availableBaseAmount, lockedBaseAmount, availableQuoteAmount, lockedQuoteAmount] = (await this.haneulClient.devInspectTransactionBlock({
480
+ transactionBlock: tx,
481
+ sender: this.currentAddress
482
+ })).results[0].returnValues.map(([bytes, _]) => BigInt(import_bcs.bcs.U64.parse(Uint8Array.from(bytes))));
483
+ return {
484
+ availableBaseAmount,
485
+ lockedBaseAmount,
486
+ availableQuoteAmount,
487
+ lockedQuoteAmount
488
+ };
489
+ }
490
+ /**
491
+ * @description get the open orders of the current user
492
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
493
+ * @param accountCap your accountCap, eg: 0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3. If not provided, `this.accountCap` will be used.
494
+ */
495
+ async listOpenOrders(poolId, accountCap = void 0) {
496
+ const tx = new import_transactions.Transaction();
497
+ const cap = __privateMethod(this, _DeepBookClient_instances, checkAccountCap_fn).call(this, accountCap);
498
+ tx.moveCall({
499
+ typeArguments: await this.getPoolTypeArgs(poolId),
500
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::list_open_orders`,
501
+ arguments: [tx.object(poolId), tx.object(cap)]
502
+ });
503
+ const results = (await this.haneulClient.devInspectTransactionBlock({
504
+ transactionBlock: tx,
505
+ sender: this.currentAddress
506
+ })).results;
507
+ if (!results) {
508
+ return [];
509
+ }
510
+ return import_bcs.bcs.vector(import_bcs2.BcsOrder).parse(Uint8Array.from(results[0].returnValues[0][0]));
511
+ }
512
+ /**
513
+ * @description get the market price {bestBidPrice, bestAskPrice}
514
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
515
+ */
516
+ async getMarketPrice(poolId) {
517
+ const tx = new import_transactions.Transaction();
518
+ tx.moveCall({
519
+ typeArguments: await this.getPoolTypeArgs(poolId),
520
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::get_market_price`,
521
+ arguments: [tx.object(poolId)]
522
+ });
523
+ const resp = (await this.haneulClient.devInspectTransactionBlock({
524
+ transactionBlock: tx,
525
+ sender: this.currentAddress
526
+ })).results[0].returnValues.map(([bytes, _]) => {
527
+ const opt = import_bcs.bcs.option(import_bcs.bcs.U64).parse(Uint8Array.from(bytes));
528
+ return opt == null ? void 0 : BigInt(opt);
529
+ });
530
+ return { bestBidPrice: resp[0], bestAskPrice: resp[1] };
531
+ }
532
+ /**
533
+ * @description get level2 book status
534
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
535
+ * @param lowerPrice lower price you want to query in the level2 book, eg: 18000000000. The number must be an integer float scaled by `FLOAT_SCALING_FACTOR`.
536
+ * @param higherPrice higher price you want to query in the level2 book, eg: 20000000000. The number must be an integer float scaled by `FLOAT_SCALING_FACTOR`.
537
+ * @param side { 'bid' | 'ask' | 'both' } bid or ask or both sides.
538
+ */
539
+ async getLevel2BookStatus(poolId, lowerPrice, higherPrice, side) {
540
+ const tx = new import_transactions.Transaction();
541
+ if (side === "both") {
542
+ tx.moveCall({
543
+ typeArguments: await this.getPoolTypeArgs(poolId),
544
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::get_level2_book_status_bid_side`,
545
+ arguments: [
546
+ tx.object(poolId),
547
+ tx.pure.u64(lowerPrice),
548
+ tx.pure.u64(higherPrice),
549
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID)
550
+ ]
551
+ });
552
+ tx.moveCall({
553
+ typeArguments: await this.getPoolTypeArgs(poolId),
554
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::get_level2_book_status_ask_side`,
555
+ arguments: [
556
+ tx.object(poolId),
557
+ tx.pure.u64(lowerPrice),
558
+ tx.pure.u64(higherPrice),
559
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID)
560
+ ]
561
+ });
562
+ } else {
563
+ tx.moveCall({
564
+ typeArguments: await this.getPoolTypeArgs(poolId),
565
+ target: `${import_utils2.PACKAGE_ID}::${import_utils2.MODULE_CLOB}::get_level2_book_status_${side}_side`,
566
+ arguments: [
567
+ tx.object(poolId),
568
+ tx.pure.u64(lowerPrice),
569
+ tx.pure.u64(higherPrice),
570
+ tx.object(import_utils.HANEUL_CLOCK_OBJECT_ID)
571
+ ]
572
+ });
573
+ }
574
+ const results = await this.haneulClient.devInspectTransactionBlock({
575
+ transactionBlock: tx,
576
+ sender: this.currentAddress
577
+ });
578
+ if (side === "both") {
579
+ const bidSide = results.results[0].returnValues.map(
580
+ ([bytes, _]) => import_bcs.bcs.vector(import_bcs.bcs.U64).parse(Uint8Array.from(bytes)).map((s) => BigInt(s))
581
+ );
582
+ const askSide = results.results[1].returnValues.map(
583
+ ([bytes, _]) => import_bcs.bcs.vector(import_bcs.bcs.U64).parse(Uint8Array.from(bytes)).map((s) => BigInt(s))
584
+ );
585
+ return [
586
+ bidSide[0].map((price, i) => ({ price, depth: bidSide[1][i] })),
587
+ askSide[0].map((price, i) => ({ price, depth: askSide[1][i] }))
588
+ ];
589
+ } else {
590
+ const result = results.results[0].returnValues.map(
591
+ ([bytes, _]) => import_bcs.bcs.vector(import_bcs.bcs.U64).parse(Uint8Array.from(bytes)).map((s) => BigInt(s))
592
+ );
593
+ return result[0].map((price, i) => ({ price, depth: result[1][i] }));
594
+ }
595
+ }
596
+ async getCoinType(coinId) {
597
+ const resp = await this.haneulClient.getObject({
598
+ id: coinId,
599
+ options: { showType: true }
600
+ });
601
+ const parsed = resp.data?.type != null ? (0, import_utils.parseStructTag)(resp.data.type) : null;
602
+ if (parsed?.address === import_utils2.NORMALIZED_HANEUL_COIN_TYPE.split("::")[0] && parsed.module === "coin" && parsed.name === "Coin" && parsed.typeParams.length > 0) {
603
+ const firstTypeParam = parsed.typeParams[0];
604
+ return typeof firstTypeParam === "object" ? firstTypeParam.address + "::" + firstTypeParam.module + "::" + firstTypeParam.name : null;
605
+ } else {
606
+ return null;
607
+ }
608
+ }
609
+ }
610
+ _poolTypeArgsCache = new WeakMap();
611
+ _DeepBookClient_instances = new WeakSet();
612
+ checkAccountCap_fn = function(accountCap = void 0) {
613
+ const cap = accountCap ?? this.accountCap;
614
+ if (cap === void 0) {
615
+ throw new Error("accountCap is undefined, please call setAccountCap() first");
616
+ }
617
+ return (0, import_utils.normalizeHaneulObjectId)(cap);
618
+ };
619
+ checkAddress_fn = function(recipientAddress) {
620
+ if (recipientAddress === DUMMY_ADDRESS) {
621
+ throw new Error("Current address cannot be DUMMY_ADDRESS");
622
+ }
623
+ return (0, import_utils.normalizeHaneulAddress)(recipientAddress);
624
+ };
625
+ nextClientOrderId_fn = function() {
626
+ const id = this.clientOrderId;
627
+ this.clientOrderId += 1;
628
+ return id;
629
+ };
630
+ //# sourceMappingURL=client.js.map