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