@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
package/src/client.ts ADDED
@@ -0,0 +1,786 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { bcs } from '@haneullabs/haneul/bcs';
5
+ import type { OrderArguments, PaginatedEvents, PaginationArguments } from '@haneullabs/haneul/client';
6
+ import { getFullnodeUrl, HaneulClient } from '@haneullabs/haneul/client';
7
+ import type { Argument, TransactionObjectInput, TransactionResult } from '@haneullabs/haneul/transactions';
8
+ import { Transaction } from '@haneullabs/haneul/transactions';
9
+ import {
10
+ normalizeStructTag,
11
+ normalizeHaneulAddress,
12
+ normalizeHaneulObjectId,
13
+ parseStructTag,
14
+ HANEUL_CLOCK_OBJECT_ID,
15
+ } from '@haneullabs/haneul/utils';
16
+
17
+ import { BcsOrder } from './types/bcs.js';
18
+ import type {
19
+ Level2BookStatusPoint,
20
+ MarketPrice,
21
+ Order,
22
+ PaginatedPoolSummary,
23
+ PoolSummary,
24
+ UserPosition,
25
+ } from './types/index.js';
26
+ import { LimitOrderType, SelfMatchingPreventionStyle } from './types/index.js';
27
+ import {
28
+ CREATION_FEE,
29
+ MODULE_CLOB,
30
+ MODULE_CUSTODIAN,
31
+ NORMALIZED_HANEUL_COIN_TYPE,
32
+ ORDER_DEFAULT_EXPIRATION_IN_MS,
33
+ PACKAGE_ID,
34
+ } from './utils/index.js';
35
+
36
+ const DUMMY_ADDRESS = normalizeHaneulAddress('0x0');
37
+
38
+ export class DeepBookClient {
39
+ #poolTypeArgsCache: Map<string, string[]> = new Map();
40
+ /**
41
+ *
42
+ * @param haneulClient connection to fullnode
43
+ * @param accountCap (optional) only required for wrting operations
44
+ * @param currentAddress (optional) address of the current user (default: DUMMY_ADDRESS)
45
+ */
46
+ constructor(
47
+ public haneulClient: HaneulClient = new HaneulClient({ url: getFullnodeUrl('testnet') }),
48
+ public accountCap: string | undefined = undefined,
49
+ public currentAddress: string = DUMMY_ADDRESS,
50
+ private clientOrderId: number = 0,
51
+ ) {}
52
+
53
+ /**
54
+ * @param cap set the account cap for interacting with DeepBook
55
+ */
56
+ async setAccountCap(cap: string) {
57
+ this.accountCap = cap;
58
+ }
59
+
60
+ /**
61
+ * @description Create pool for trading pair
62
+ * @param baseAssetType Full coin type of the base asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::wbtc::WBTC"
63
+ * @param quoteAssetType Full coin type of quote asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::usdt::USDT"
64
+ * @param tickSize Minimal Price Change Accuracy of this pool, eg: 10000000. The number must be an integer float scaled by `FLOAT_SCALING_FACTOR`.
65
+ * @param lotSize Minimal Lot Change Accuracy of this pool, eg: 10000.
66
+ */
67
+ createPool(
68
+ baseAssetType: string,
69
+ quoteAssetType: string,
70
+ tickSize: bigint,
71
+ lotSize: bigint,
72
+ ): Transaction {
73
+ const tx = new Transaction();
74
+ // create a pool with CREATION_FEE
75
+ const [coin] = tx.splitCoins(tx.gas, [CREATION_FEE]);
76
+ tx.moveCall({
77
+ typeArguments: [baseAssetType, quoteAssetType],
78
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::create_pool`,
79
+ arguments: [tx.pure.u64(tickSize), tx.pure.u64(lotSize), coin],
80
+ });
81
+ return tx;
82
+ }
83
+
84
+ /**
85
+ * @description Create pool for trading pair
86
+ * @param baseAssetType Full coin type of the base asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::wbtc::WBTC"
87
+ * @param quoteAssetType Full coin type of quote asset, eg: "0x3d0d0ce17dcd3b40c2d839d96ce66871ffb40e1154a8dd99af72292b3d10d7fc::usdt::USDT"
88
+ * @param tickSize Minimal Price Change Accuracy of this pool, eg: 10000000. The number must be an interger float scaled by `FLOAT_SCALING_FACTOR`.
89
+ * @param lotSize Minimal Lot Change Accuracy of this pool, eg: 10000.
90
+ * @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
91
+ * @param makerRebateRate Customized maker rebate rate, float scaled by `FLOAT_SCALING_FACTOR`, should be less than or equal to the taker_rebate_rate
92
+ */
93
+ createCustomizedPool(
94
+ baseAssetType: string,
95
+ quoteAssetType: string,
96
+ tickSize: bigint,
97
+ lotSize: bigint,
98
+ takerFeeRate: bigint,
99
+ makerRebateRate: bigint,
100
+ ): Transaction {
101
+ const tx = new Transaction();
102
+ // create a pool with CREATION_FEE
103
+ const [coin] = tx.splitCoins(tx.gas, [CREATION_FEE]);
104
+ tx.moveCall({
105
+ typeArguments: [baseAssetType, quoteAssetType],
106
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::create_customized_pool`,
107
+ arguments: [
108
+ tx.pure.u64(tickSize),
109
+ tx.pure.u64(lotSize),
110
+ tx.pure.u64(takerFeeRate),
111
+ tx.pure.u64(makerRebateRate),
112
+ coin,
113
+ ],
114
+ });
115
+ return tx;
116
+ }
117
+
118
+ /**
119
+ * @description Create Account Cap
120
+ * @param tx
121
+ */
122
+ createAccountCap(tx: Transaction) {
123
+ const [cap] = tx.moveCall({
124
+ typeArguments: [],
125
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::create_account`,
126
+ arguments: [],
127
+ });
128
+ return cap;
129
+ }
130
+
131
+ /**
132
+ * @description Create and Transfer custodian account to user
133
+ * @param currentAddress current address of the user
134
+ * @param tx
135
+ */
136
+ createAccount(
137
+ currentAddress: string = this.currentAddress,
138
+ tx: Transaction = new Transaction(),
139
+ ): Transaction {
140
+ const cap = this.createAccountCap(tx);
141
+ tx.transferObjects([cap], this.#checkAddress(currentAddress));
142
+ return tx;
143
+ }
144
+
145
+ /**
146
+ * @description Create and Transfer custodian account to user
147
+ * @param currentAddress: current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
148
+ * @param accountCap: Object id of Account Capacity under user address, created after invoking createAccount, eg: "0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3"
149
+ */
150
+ createChildAccountCap(
151
+ currentAddress: string = this.currentAddress,
152
+ accountCap: string | undefined = this.accountCap,
153
+ ): Transaction {
154
+ const tx = new Transaction();
155
+ const [childCap] = tx.moveCall({
156
+ typeArguments: [],
157
+ target: `${PACKAGE_ID}::${MODULE_CUSTODIAN}::create_child_account_cap`,
158
+ arguments: [tx.object(this.#checkAccountCap(accountCap))],
159
+ });
160
+ tx.transferObjects([childCap], this.#checkAddress(currentAddress));
161
+ return tx;
162
+ }
163
+
164
+ /**
165
+ * @description construct transaction for depositing asset into a pool.
166
+ * @param poolId the pool id for the deposit
167
+ * @param coinId the coin used for the deposit. You can omit this argument if you are depositing SUI, in which case
168
+ * gas coin will be used
169
+ * @param amount the amount of coin to deposit. If omitted, the entire balance of the coin will be deposited
170
+ */
171
+ async deposit(
172
+ poolId: string,
173
+ coinId: string | undefined = undefined,
174
+ quantity: bigint | undefined = undefined,
175
+ ): Promise<Transaction> {
176
+ const tx = new Transaction();
177
+
178
+ const [baseAsset, quoteAsset] = await this.getPoolTypeArgs(poolId);
179
+ const hasSui =
180
+ baseAsset === NORMALIZED_HANEUL_COIN_TYPE || quoteAsset === NORMALIZED_HANEUL_COIN_TYPE;
181
+
182
+ if (coinId === undefined && !hasSui) {
183
+ throw new Error('coinId must be specified if neither baseAsset nor quoteAsset is SUI');
184
+ }
185
+
186
+ const inputCoin = coinId ? tx.object(coinId) : tx.gas;
187
+
188
+ const [coin] = quantity ? tx.splitCoins(inputCoin, [quantity]) : [inputCoin];
189
+
190
+ const coinType = coinId ? await this.getCoinType(coinId) : NORMALIZED_HANEUL_COIN_TYPE;
191
+ if (coinType !== baseAsset && coinType !== quoteAsset) {
192
+ throw new Error(
193
+ `coin ${coinId} of ${coinType} type is not a valid asset for pool ${poolId}, which supports ${baseAsset} and ${quoteAsset}`,
194
+ );
195
+ }
196
+ const functionName = coinType === baseAsset ? 'deposit_base' : 'deposit_quote';
197
+
198
+ tx.moveCall({
199
+ typeArguments: [baseAsset, quoteAsset],
200
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::${functionName}`,
201
+ arguments: [tx.object(poolId), coin, tx.object(this.#checkAccountCap())],
202
+ });
203
+ return tx;
204
+ }
205
+
206
+ /**
207
+ * @description construct transaction for withdrawing asset from a pool.
208
+ * @param poolId the pool id for the withdraw
209
+ * @param amount the amount of coin to withdraw
210
+ * @param assetType Base or Quote
211
+ * @param recipientAddress the address to receive the withdrawn asset. If omitted, `this.currentAddress` will be used. The function
212
+ * will throw if the `recipientAddress === DUMMY_ADDRESS`
213
+ */
214
+ async withdraw(
215
+ poolId: string,
216
+ // TODO: implement withdraw all
217
+ quantity: bigint,
218
+ assetType: 'base' | 'quote',
219
+ recipientAddress: string = this.currentAddress,
220
+ ): Promise<Transaction> {
221
+ const tx = new Transaction();
222
+ const functionName = assetType === 'base' ? 'withdraw_base' : 'withdraw_quote';
223
+ const [withdraw] = tx.moveCall({
224
+ typeArguments: await this.getPoolTypeArgs(poolId),
225
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::${functionName}`,
226
+ arguments: [tx.object(poolId), tx.pure.u64(quantity), tx.object(this.#checkAccountCap())],
227
+ });
228
+ tx.transferObjects([withdraw], this.#checkAddress(recipientAddress));
229
+ return tx;
230
+ }
231
+
232
+ /**
233
+ * @description place a limit order
234
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
235
+ * @param price: price of the limit order. The number must be an interger float scaled by `FLOAT_SCALING_FACTOR`.
236
+ * @param quantity: quantity of the limit order in BASE ASSET, eg: 100000000.
237
+ * @param orderType: bid for buying base with quote, ask for selling base for quote
238
+ * @param expirationTimestamp: expiration timestamp of the limit order in ms, eg: 1620000000000. If omitted, the order will expire in 1 day
239
+ * from the time this function is called(not the time the transaction is executed)
240
+ * @param restriction restrictions on limit orders, explain in doc for more details, eg: 0
241
+ * @param clientOrderId a client side defined order number for bookkeeping purpose, e.g., "1", "2", etc. If omitted, the sdk will
242
+ * assign a increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
243
+ * @param selfMatchingPrevention: Options for self-match prevention. Right now only support `CANCEL_OLDEST`
244
+ */
245
+ async placeLimitOrder(
246
+ poolId: string,
247
+ price: bigint,
248
+ quantity: bigint,
249
+ orderType: 'bid' | 'ask',
250
+ expirationTimestamp: number = Date.now() + ORDER_DEFAULT_EXPIRATION_IN_MS,
251
+ restriction: LimitOrderType = LimitOrderType.NO_RESTRICTION,
252
+ clientOrderId: string | undefined = undefined,
253
+ selfMatchingPrevention: SelfMatchingPreventionStyle = SelfMatchingPreventionStyle.CANCEL_OLDEST,
254
+ ): Promise<Transaction> {
255
+ const tx = new Transaction();
256
+ const args = [
257
+ tx.object(poolId),
258
+ tx.pure.u64(clientOrderId ?? this.#nextClientOrderId()),
259
+ tx.pure.u64(price),
260
+ tx.pure.u64(quantity),
261
+ tx.pure.u8(selfMatchingPrevention),
262
+ tx.pure.bool(orderType === 'bid'),
263
+ tx.pure.u64(expirationTimestamp),
264
+ tx.pure.u8(restriction),
265
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
266
+ tx.object(this.#checkAccountCap()),
267
+ ];
268
+ tx.moveCall({
269
+ typeArguments: await this.getPoolTypeArgs(poolId),
270
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::place_limit_order`,
271
+ arguments: args,
272
+ });
273
+ return tx;
274
+ }
275
+
276
+ /**
277
+ * @description place a market order
278
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
279
+ * @param quantity Amount of quote asset to swap in base asset
280
+ * @param orderType bid for buying base with quote, ask for selling base for quote
281
+ * @param baseCoin the objectId or the coin object of the base coin
282
+ * @param quoteCoin the objectId or the coin object of the quote coin
283
+ * @param clientOrderId a client side defined order id for bookkeeping purpose. eg: "1" , "2", ... If omitted, the sdk will
284
+ * assign an increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
285
+ * @param accountCap
286
+ * @param recipientAddress the address to receive the swapped asset. If omitted, `this.currentAddress` will be used. The function
287
+ * @param tx
288
+ */
289
+ async placeMarketOrder(
290
+ accountCap: string | Extract<Argument, { $kind: 'NestedResult' }>,
291
+ poolId: string,
292
+ quantity: bigint,
293
+ orderType: 'bid' | 'ask',
294
+ baseCoin: TransactionResult | string | undefined = undefined,
295
+ quoteCoin: TransactionResult | string | undefined = undefined,
296
+ clientOrderId: string | undefined = undefined,
297
+ recipientAddress: string | undefined = this.currentAddress,
298
+ tx: Transaction = new Transaction(),
299
+ ): Promise<Transaction> {
300
+ const [baseAssetType, quoteAssetType] = await this.getPoolTypeArgs(poolId);
301
+ if (!baseCoin && orderType === 'ask') {
302
+ throw new Error('Must specify a valid base coin for an ask order');
303
+ } else if (!quoteCoin && orderType === 'bid') {
304
+ throw new Error('Must specify a valid quote coin for a bid order');
305
+ }
306
+ const emptyCoin = tx.moveCall({
307
+ typeArguments: [baseCoin ? quoteAssetType : baseAssetType],
308
+ target: `0x2::coin::zero`,
309
+ arguments: [],
310
+ });
311
+
312
+ const [base_coin_ret, quote_coin_ret] = tx.moveCall({
313
+ typeArguments: [baseAssetType, quoteAssetType],
314
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::place_market_order`,
315
+ arguments: [
316
+ tx.object(poolId),
317
+ typeof accountCap === 'string' ? tx.object(this.#checkAccountCap(accountCap)) : accountCap,
318
+ tx.pure.u64(clientOrderId ?? this.#nextClientOrderId()),
319
+ tx.pure.u64(quantity),
320
+ tx.pure.bool(orderType === 'bid'),
321
+ baseCoin ? tx.object(baseCoin) : emptyCoin,
322
+ quoteCoin ? tx.object(quoteCoin) : emptyCoin,
323
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
324
+ ],
325
+ });
326
+ const recipient = this.#checkAddress(recipientAddress);
327
+ tx.transferObjects([base_coin_ret], recipient);
328
+ tx.transferObjects([quote_coin_ret], recipient);
329
+
330
+ return tx;
331
+ }
332
+
333
+ /**
334
+ * @description swap exact quote for base
335
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
336
+ * @param tokenObjectIn Object id of the token to swap: eg: "0x6e566fec4c388eeb78a7dab832c9f0212eb2ac7e8699500e203def5b41b9c70d"
337
+ * @param amountIn amount of token to buy or sell, eg: 10000000.
338
+ * @param currentAddress current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
339
+ * @param clientOrderId a client side defined order id for bookkeeping purpose, eg: "1" , "2", ... If omitted, the sdk will
340
+ * assign an increasing number starting from 0. But this number might be duplicated if you are using multiple sdk instances
341
+ * @param tx
342
+ */
343
+ async swapExactQuoteForBase(
344
+ poolId: string,
345
+ tokenObjectIn: TransactionObjectInput,
346
+ amountIn: bigint, // quantity of USDC
347
+ currentAddress: string,
348
+ clientOrderId?: string,
349
+ tx: Transaction = new Transaction(),
350
+ ): Promise<Transaction> {
351
+ // in this case, we assume that the tokenIn--tokenOut always exists.
352
+ const [base_coin_ret, quote_coin_ret, _amount] = tx.moveCall({
353
+ typeArguments: await this.getPoolTypeArgs(poolId),
354
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::swap_exact_quote_for_base`,
355
+ arguments: [
356
+ tx.object(poolId),
357
+ tx.pure.u64(clientOrderId ?? this.#nextClientOrderId()),
358
+ tx.object(this.#checkAccountCap()),
359
+ tx.pure.u64(String(amountIn)),
360
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
361
+ tx.object(tokenObjectIn),
362
+ ],
363
+ });
364
+ tx.transferObjects([base_coin_ret], currentAddress);
365
+ tx.transferObjects([quote_coin_ret], currentAddress);
366
+ return tx;
367
+ }
368
+
369
+ /**
370
+ * @description swap exact base for quote
371
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
372
+ * @param tokenObjectIn Object id of the token to swap: eg: "0x6e566fec4c388eeb78a7dab832c9f0212eb2ac7e8699500e203def5b41b9c70d"
373
+ * @param amountIn amount of token to buy or sell, eg: 10000000
374
+ * @param currentAddress current user address, eg: "0xbddc9d4961b46a130c2e1f38585bbc6fa8077ce54bcb206b26874ac08d607966"
375
+ * @param clientOrderId a client side defined order number for bookkeeping purpose. eg: "1" , "2", ...
376
+ */
377
+ async swapExactBaseForQuote(
378
+ poolId: string,
379
+ tokenObjectIn: string,
380
+ amountIn: bigint,
381
+ currentAddress: string,
382
+ clientOrderId: string | undefined = undefined,
383
+ ): Promise<Transaction> {
384
+ const tx = new Transaction();
385
+ const [baseAsset, quoteAsset] = await this.getPoolTypeArgs(poolId);
386
+ // in this case, we assume that the tokenIn--tokenOut always exists.
387
+ const [base_coin_ret, quote_coin_ret, _amount] = tx.moveCall({
388
+ typeArguments: [baseAsset, quoteAsset],
389
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::swap_exact_base_for_quote`,
390
+ arguments: [
391
+ tx.object(poolId),
392
+ tx.pure.u64(clientOrderId ?? this.#nextClientOrderId()),
393
+ tx.object(this.#checkAccountCap()),
394
+ tx.object(String(amountIn)),
395
+ tx.object(tokenObjectIn),
396
+ tx.moveCall({
397
+ typeArguments: [quoteAsset],
398
+ target: `0x2::coin::zero`,
399
+ arguments: [],
400
+ }),
401
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
402
+ ],
403
+ });
404
+ tx.transferObjects([base_coin_ret], currentAddress);
405
+ tx.transferObjects([quote_coin_ret], currentAddress);
406
+ return tx;
407
+ }
408
+
409
+ /**
410
+ * @description cancel an order
411
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
412
+ * @param orderId orderId of a limit order, you can find them through function query.list_open_orders eg: "0"
413
+ */
414
+ async cancelOrder(poolId: string, orderId: string): Promise<Transaction> {
415
+ const tx = new Transaction();
416
+ tx.moveCall({
417
+ typeArguments: await this.getPoolTypeArgs(poolId),
418
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::cancel_order`,
419
+ arguments: [tx.object(poolId), tx.pure.u64(orderId), tx.object(this.#checkAccountCap())],
420
+ });
421
+ return tx;
422
+ }
423
+
424
+ /**
425
+ * @description Cancel all limit orders under a certain account capacity
426
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
427
+ */
428
+ async cancelAllOrders(poolId: string): Promise<Transaction> {
429
+ const tx = new Transaction();
430
+ tx.moveCall({
431
+ typeArguments: await this.getPoolTypeArgs(poolId),
432
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::cancel_all_orders`,
433
+ arguments: [tx.object(poolId), tx.object(this.#checkAccountCap())],
434
+ });
435
+ return tx;
436
+ }
437
+
438
+ /**
439
+ * @description batch cancel order
440
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
441
+ * @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"]
442
+ */
443
+ async batchCancelOrder(poolId: string, orderIds: string[]): Promise<Transaction> {
444
+ const tx = new Transaction();
445
+ tx.moveCall({
446
+ typeArguments: await this.getPoolTypeArgs(poolId),
447
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::batch_cancel_order`,
448
+ arguments: [
449
+ tx.object(poolId),
450
+ bcs.vector(bcs.U64).serialize(orderIds),
451
+ tx.object(this.#checkAccountCap()),
452
+ ],
453
+ });
454
+ return tx;
455
+ }
456
+
457
+ /**
458
+ * @param poolId Object id of pool, created after invoking createPool, eg: "0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4"
459
+ * @param orderIds array of expired order ids to clean, eg: ["0", "1", "2"]
460
+ * @param orderOwners array of Order owners, should be the owner addresses from the account capacities which placed the orders
461
+ */
462
+ async cleanUpExpiredOrders(
463
+ poolId: string,
464
+ orderIds: string[],
465
+ orderOwners: string[],
466
+ ): Promise<Transaction> {
467
+ const tx = new Transaction();
468
+ tx.moveCall({
469
+ typeArguments: await this.getPoolTypeArgs(poolId),
470
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::clean_up_expired_orders`,
471
+ arguments: [
472
+ tx.object(poolId),
473
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
474
+ bcs.vector(bcs.U64).serialize(orderIds),
475
+ bcs.vector(bcs.Address).serialize(orderOwners),
476
+ ],
477
+ });
478
+ return tx;
479
+ }
480
+
481
+ /**
482
+ * @description returns paginated list of pools created in DeepBook by querying for the
483
+ * `PoolCreated` event. Warning: this method can return incomplete results if the upstream data source
484
+ * is pruned.
485
+ */
486
+ async getAllPools(
487
+ input: PaginationArguments<PaginatedEvents['nextCursor']> & OrderArguments,
488
+ ): Promise<PaginatedPoolSummary> {
489
+ const resp = await this.haneulClient.queryEvents({
490
+ query: { MoveEventType: `${PACKAGE_ID}::${MODULE_CLOB}::PoolCreated` },
491
+ ...input,
492
+ });
493
+ const pools = resp.data.map((event) => {
494
+ const rawEvent = event.parsedJson as any;
495
+ return {
496
+ poolId: rawEvent.pool_id as string,
497
+ baseAsset: normalizeStructTag(rawEvent.base_asset.name),
498
+ quoteAsset: normalizeStructTag(rawEvent.quote_asset.name),
499
+ };
500
+ });
501
+ return {
502
+ data: pools,
503
+ nextCursor: resp.nextCursor,
504
+ hasNextPage: resp.hasNextPage,
505
+ };
506
+ }
507
+
508
+ /**
509
+ * @description Fetch metadata for a pool
510
+ * @param poolId object id of the pool
511
+ * @returns Metadata for the Pool
512
+ */
513
+ async getPoolInfo(poolId: string): Promise<PoolSummary> {
514
+ const resp = await this.haneulClient.getObject({
515
+ id: poolId,
516
+ options: { showContent: true },
517
+ });
518
+ if (resp?.data?.content?.dataType !== 'moveObject') {
519
+ throw new Error(`pool ${poolId} does not exist`);
520
+ }
521
+
522
+ const [baseAsset, quoteAsset] = parseStructTag(resp!.data!.content!.type).typeParams.map((t) =>
523
+ normalizeStructTag(t),
524
+ );
525
+
526
+ return {
527
+ poolId,
528
+ baseAsset,
529
+ quoteAsset,
530
+ };
531
+ }
532
+
533
+ async getPoolTypeArgs(poolId: string): Promise<string[]> {
534
+ if (!this.#poolTypeArgsCache.has(poolId)) {
535
+ const { baseAsset, quoteAsset } = await this.getPoolInfo(poolId);
536
+ const typeArgs = [baseAsset, quoteAsset];
537
+ this.#poolTypeArgsCache.set(poolId, typeArgs);
538
+ }
539
+
540
+ return this.#poolTypeArgsCache.get(poolId)!;
541
+ }
542
+
543
+ /**
544
+ * @description get the order status
545
+ * @param poolId: the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
546
+ * @param orderId the order id, eg: "1"
547
+ */
548
+ async getOrderStatus(
549
+ poolId: string,
550
+ orderId: string,
551
+ accountCap: string | undefined = this.accountCap,
552
+ ): Promise<Order | undefined> {
553
+ const tx = new Transaction();
554
+ const cap = this.#checkAccountCap(accountCap);
555
+ tx.moveCall({
556
+ typeArguments: await this.getPoolTypeArgs(poolId),
557
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::get_order_status`,
558
+ arguments: [tx.object(poolId), tx.pure.u64(orderId), tx.object(cap)],
559
+ });
560
+ const results = (
561
+ await this.haneulClient.devInspectTransactionBlock({
562
+ transactionBlock: tx,
563
+ sender: this.currentAddress,
564
+ })
565
+ ).results;
566
+
567
+ if (!results) {
568
+ return undefined;
569
+ }
570
+
571
+ return BcsOrder.parse(Uint8Array.from(results![0].returnValues![0][0]));
572
+ }
573
+
574
+ /**
575
+ * @description get the base and quote token in custodian account
576
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
577
+ * @param accountCap your accountCap, eg: 0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3. If not provided, `this.accountCap` will be used.
578
+ */
579
+ async getUserPosition(
580
+ poolId: string,
581
+ accountCap: string | undefined = undefined,
582
+ ): Promise<UserPosition> {
583
+ const tx = new Transaction();
584
+ const cap = this.#checkAccountCap(accountCap);
585
+
586
+ tx.moveCall({
587
+ typeArguments: await this.getPoolTypeArgs(poolId),
588
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::account_balance`,
589
+ arguments: [tx.object(normalizeHaneulObjectId(poolId)), tx.object(cap)],
590
+ });
591
+ const [availableBaseAmount, lockedBaseAmount, availableQuoteAmount, lockedQuoteAmount] = (
592
+ await this.haneulClient.devInspectTransactionBlock({
593
+ transactionBlock: tx,
594
+ sender: this.currentAddress,
595
+ })
596
+ ).results![0].returnValues!.map(([bytes, _]) => BigInt(bcs.U64.parse(Uint8Array.from(bytes))));
597
+ return {
598
+ availableBaseAmount,
599
+ lockedBaseAmount,
600
+ availableQuoteAmount,
601
+ lockedQuoteAmount,
602
+ };
603
+ }
604
+
605
+ /**
606
+ * @description get the open orders of the current user
607
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
608
+ * @param accountCap your accountCap, eg: 0x6f699fef193723277559c8f499ca3706121a65ac96d273151b8e52deb29135d3. If not provided, `this.accountCap` will be used.
609
+ */
610
+ async listOpenOrders(
611
+ poolId: string,
612
+ accountCap: string | undefined = undefined,
613
+ ): Promise<Order[]> {
614
+ const tx = new Transaction();
615
+ const cap = this.#checkAccountCap(accountCap);
616
+
617
+ tx.moveCall({
618
+ typeArguments: await this.getPoolTypeArgs(poolId),
619
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::list_open_orders`,
620
+ arguments: [tx.object(poolId), tx.object(cap)],
621
+ });
622
+
623
+ const results = (
624
+ await this.haneulClient.devInspectTransactionBlock({
625
+ transactionBlock: tx,
626
+ sender: this.currentAddress,
627
+ })
628
+ ).results;
629
+
630
+ if (!results) {
631
+ return [];
632
+ }
633
+
634
+ return bcs.vector(BcsOrder).parse(Uint8Array.from(results![0].returnValues![0][0]));
635
+ }
636
+
637
+ /**
638
+ * @description get the market price {bestBidPrice, bestAskPrice}
639
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
640
+ */
641
+ async getMarketPrice(poolId: string): Promise<MarketPrice> {
642
+ const tx = new Transaction();
643
+ tx.moveCall({
644
+ typeArguments: await this.getPoolTypeArgs(poolId),
645
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::get_market_price`,
646
+ arguments: [tx.object(poolId)],
647
+ });
648
+ const resp = (
649
+ await this.haneulClient.devInspectTransactionBlock({
650
+ transactionBlock: tx,
651
+ sender: this.currentAddress,
652
+ })
653
+ ).results![0].returnValues!.map(([bytes, _]) => {
654
+ const opt = bcs.option(bcs.U64).parse(Uint8Array.from(bytes));
655
+ return opt == null ? undefined : BigInt(opt);
656
+ });
657
+
658
+ return { bestBidPrice: resp[0], bestAskPrice: resp[1] };
659
+ }
660
+
661
+ /**
662
+ * @description get level2 book status
663
+ * @param poolId the pool id, eg: 0xcaee8e1c046b58e55196105f1436a2337dcaa0c340a7a8c8baf65e4afb8823a4
664
+ * @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`.
665
+ * @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`.
666
+ * @param side { 'bid' | 'ask' | 'both' } bid or ask or both sides.
667
+ */
668
+ async getLevel2BookStatus(
669
+ poolId: string,
670
+ lowerPrice: bigint,
671
+ higherPrice: bigint,
672
+ side: 'bid' | 'ask' | 'both',
673
+ ): Promise<Level2BookStatusPoint[] | Level2BookStatusPoint[][]> {
674
+ const tx = new Transaction();
675
+ if (side === 'both') {
676
+ tx.moveCall({
677
+ typeArguments: await this.getPoolTypeArgs(poolId),
678
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::get_level2_book_status_bid_side`,
679
+ arguments: [
680
+ tx.object(poolId),
681
+ tx.pure.u64(lowerPrice),
682
+ tx.pure.u64(higherPrice),
683
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
684
+ ],
685
+ });
686
+ tx.moveCall({
687
+ typeArguments: await this.getPoolTypeArgs(poolId),
688
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::get_level2_book_status_ask_side`,
689
+ arguments: [
690
+ tx.object(poolId),
691
+ tx.pure.u64(lowerPrice),
692
+ tx.pure.u64(higherPrice),
693
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
694
+ ],
695
+ });
696
+ } else {
697
+ tx.moveCall({
698
+ typeArguments: await this.getPoolTypeArgs(poolId),
699
+ target: `${PACKAGE_ID}::${MODULE_CLOB}::get_level2_book_status_${side}_side`,
700
+ arguments: [
701
+ tx.object(poolId),
702
+ tx.pure.u64(lowerPrice),
703
+ tx.pure.u64(higherPrice),
704
+ tx.object(HANEUL_CLOCK_OBJECT_ID),
705
+ ],
706
+ });
707
+ }
708
+
709
+ const results = await this.haneulClient.devInspectTransactionBlock({
710
+ transactionBlock: tx,
711
+ sender: this.currentAddress,
712
+ });
713
+
714
+ if (side === 'both') {
715
+ const bidSide = results.results![0].returnValues!.map(([bytes, _]) =>
716
+ bcs
717
+ .vector(bcs.U64)
718
+ .parse(Uint8Array.from(bytes))
719
+ .map((s: string) => BigInt(s)),
720
+ );
721
+ const askSide = results.results![1].returnValues!.map(([bytes, _]) =>
722
+ bcs
723
+ .vector(bcs.U64)
724
+ .parse(Uint8Array.from(bytes))
725
+ .map((s: string) => BigInt(s)),
726
+ );
727
+ return [
728
+ bidSide[0].map((price: bigint, i: number) => ({ price, depth: bidSide[1][i] })),
729
+ askSide[0].map((price: bigint, i: number) => ({ price, depth: askSide[1][i] })),
730
+ ];
731
+ } else {
732
+ const result = results.results![0].returnValues!.map(([bytes, _]) =>
733
+ bcs
734
+ .vector(bcs.U64)
735
+ .parse(Uint8Array.from(bytes))
736
+ .map((s) => BigInt(s)),
737
+ );
738
+ return result[0].map((price: bigint, i: number) => ({ price, depth: result[1][i] }));
739
+ }
740
+ }
741
+
742
+ #checkAccountCap(accountCap: string | undefined = undefined): string {
743
+ const cap = accountCap ?? this.accountCap;
744
+ if (cap === undefined) {
745
+ throw new Error('accountCap is undefined, please call setAccountCap() first');
746
+ }
747
+ return normalizeHaneulObjectId(cap);
748
+ }
749
+
750
+ #checkAddress(recipientAddress: string): string {
751
+ if (recipientAddress === DUMMY_ADDRESS) {
752
+ throw new Error('Current address cannot be DUMMY_ADDRESS');
753
+ }
754
+ return normalizeHaneulAddress(recipientAddress);
755
+ }
756
+
757
+ public async getCoinType(coinId: string) {
758
+ const resp = await this.haneulClient.getObject({
759
+ id: coinId,
760
+ options: { showType: true },
761
+ });
762
+
763
+ const parsed = resp.data?.type != null ? parseStructTag(resp.data.type) : null;
764
+
765
+ // Modification handle case like 0x2::coin::Coin<0xf398b9ecb31aed96c345538fb59ca5a1a2c247c5e60087411ead6c637129f1c4::fish::FISH>
766
+ if (
767
+ parsed?.address === NORMALIZED_HANEUL_COIN_TYPE.split('::')[0] &&
768
+ parsed.module === 'coin' &&
769
+ parsed.name === 'Coin' &&
770
+ parsed.typeParams.length > 0
771
+ ) {
772
+ const firstTypeParam = parsed.typeParams[0];
773
+ return typeof firstTypeParam === 'object'
774
+ ? firstTypeParam.address + '::' + firstTypeParam.module + '::' + firstTypeParam.name
775
+ : null;
776
+ } else {
777
+ return null;
778
+ }
779
+ }
780
+
781
+ #nextClientOrderId() {
782
+ const id = this.clientOrderId;
783
+ this.clientOrderId += 1;
784
+ return id;
785
+ }
786
+ }