Repository navigation
Expand file tree
/
Copy pathclob_v2.move
More file actions
3228 lines (3033 loc) · 131 KB
/
Copy pathclob_v2.move
File metadata and controls
3228 lines (3033 loc) · 131 KB
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
module deepbook::clob_v2 {
use std::type_name::{Self, TypeName};
use sui::balance::{Self, Balance};
use sui::clock::{Self, Clock};
use sui::coin::{Self, Coin, join};
use sui::event;
use sui::linked_table::{Self, LinkedTable};
use sui::sui::SUI;
use sui::table::{Self, Table, contains, add, borrow_mut};
use deepbook::critbit::{Self, CritbitTree, is_empty, borrow_mut_leaf_by_index, min_leaf, remove_leaf_by_index, max_leaf, next_leaf, previous_leaf, borrow_leaf_by_index, borrow_leaf_by_key, find_leaf, insert_leaf};
use deepbook::custodian_v2::{Self as custodian, Custodian, AccountCap, mint_account_cap, account_owner};
use deepbook::math::Self as clob_math;
// <<<<<<<<<<<<<<<<<<<<<<<< Error codes <<<<<<<<<<<<<<<<<<<<<<<<
const EIncorrectPoolOwner: u64 = 1;
const EInvalidFeeRateRebateRate: u64 = 2;
const EInvalidOrderId: u64 = 3;
const EUnauthorizedCancel: u64 = 4;
const EInvalidPrice: u64 = 5;
const EInvalidQuantity: u64 = 6;
// Insufficient amount of base coin.
const EInsufficientBaseCoin: u64 = 7;
// Insufficient amount of quote coin.
const EInsufficientQuoteCoin: u64 = 8;
const EOrderCannotBeFullyFilled: u64 = 9;
const EOrderCannotBeFullyPassive: u64 = 10;
const EInvalidTickPrice: u64 = 11;
const EInvalidUser: u64 = 12;
const ENotEqual: u64 = 13;
const EInvalidRestriction: u64 = 14;
const EInvalidPair: u64 = 16;
const EInvalidFee: u64 = 18;
const EInvalidExpireTimestamp: u64 = 19;
const EInvalidTickSizeLotSize: u64 = 20;
const EInvalidSelfMatchingPreventionArg: u64 = 21;
// <<<<<<<<<<<<<<<<<<<<<<<< Error codes <<<<<<<<<<<<<<<<<<<<<<<<
// <<<<<<<<<<<<<<<<<<<<<<<< Constants <<<<<<<<<<<<<<<<<<<<<<<<
const FLOAT_SCALING: u64 = 1_000_000_000;
// Self-Trade Prevention option
// Cancel older (resting) order in full. Continue to execute the newer taking order.
const CANCEL_OLDEST: u8 = 0;
// Restrictions on limit orders.
const NO_RESTRICTION: u8 = 0;
// Mandates that whatever amount of an order that can be executed in the current transaction, be filled and then the rest of the order canceled.
const IMMEDIATE_OR_CANCEL: u8 = 1;
// Mandates that the entire order size be filled in the current transaction. Otherwise, the order is canceled.
const FILL_OR_KILL: u8 = 2;
// Mandates that the entire order be passive. Otherwise, cancel the order.
const POST_OR_ABORT: u8 = 3;
const MIN_BID_ORDER_ID: u64 = 1;
const MIN_ASK_ORDER_ID: u64 = 1 << 63;
const MIN_PRICE: u64 = 0;
const MAX_PRICE: u64 = (1u128 << 64 - 1) as u64;
#[test_only]
const TIMESTAMP_INF: u64 = (1u128 << 64 - 1) as u64;
const REFERENCE_TAKER_FEE_RATE: u64 = 2_500_000;
const REFERENCE_MAKER_REBATE_RATE: u64 = 1_500_000;
const FEE_AMOUNT_FOR_CREATE_POOL: u64 = 100 * 1_000_000_000; // 100 SUI
#[test_only]
const PREVENT_SELF_MATCHING_DEFAULT: u8 = 0;
// <<<<<<<<<<<<<<<<<<<<<<<< Constants <<<<<<<<<<<<<<<<<<<<<<<<
// <<<<<<<<<<<<<<<<<<<<<<<< Events <<<<<<<<<<<<<<<<<<<<<<<<
/// Emitted when a new pool is created
public struct PoolCreated has copy, store, drop {
/// object ID of the newly created pool
pool_id: ID,
base_asset: TypeName,
quote_asset: TypeName,
taker_fee_rate: u64,
// 10^9 scaling
maker_rebate_rate: u64,
tick_size: u64,
lot_size: u64,
}
/// Emitted when a maker order is injected into the order book.
public struct OrderPlaced<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// object ID of the pool the order was placed on
pool_id: ID,
/// ID of the order within the pool
order_id: u64,
/// ID of the order defined by client
client_order_id: u64,
is_bid: bool,
/// owner ID of the `AccountCap` that placed the order
owner: address,
original_quantity: u64,
base_asset_quantity_placed: u64,
price: u64,
expire_timestamp: u64
}
/// Emitted when a maker order is canceled.
public struct OrderCanceled<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// object ID of the pool the order was placed on
pool_id: ID,
/// ID of the order within the pool
order_id: u64,
/// ID of the order defined by client
client_order_id: u64,
is_bid: bool,
/// owner ID of the `AccountCap` that canceled the order
owner: address,
original_quantity: u64,
base_asset_quantity_canceled: u64,
price: u64
}
/// A struct to make all orders canceled a more effifient struct
public struct AllOrdersCanceledComponent<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// ID of the order within the pool
order_id: u64,
/// ID of the order defined by client
client_order_id: u64,
is_bid: bool,
/// owner ID of the `AccountCap` that canceled the order
owner: address,
original_quantity: u64,
base_asset_quantity_canceled: u64,
price: u64
}
/// Emitted when batch of orders are canceled.
public struct AllOrdersCanceled<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// object ID of the pool the order was placed on
pool_id: ID,
orders_canceled: vector<AllOrdersCanceledComponent<BaseAsset, QuoteAsset>>,
}
/// Emitted only when a maker order is filled.
public struct OrderFilled<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// object ID of the pool the order was placed on
pool_id: ID,
/// ID of the order within the pool
order_id: u64,
/// ID of the order defined by taker client
taker_client_order_id: u64,
/// ID of the order defined by maker client
maker_client_order_id: u64,
is_bid: bool,
/// owner ID of the `AccountCap` that filled the order
taker_address: address,
/// owner ID of the `AccountCap` that placed the order
maker_address: address,
original_quantity: u64,
base_asset_quantity_filled: u64,
base_asset_quantity_remaining: u64,
price: u64,
taker_commission: u64,
maker_rebates: u64
}
/// Emitted when user deposit asset to custodian
public struct DepositAsset<phantom Asset> has copy, store, drop {
/// object id of the pool that asset deposit to
pool_id: ID,
/// quantity of the asset deposited
quantity: u64,
/// owner address of the `AccountCap` that deposit the asset
owner: address
}
/// Emitted when user withdraw asset from custodian
public struct WithdrawAsset<phantom Asset> has copy, store, drop {
/// object id of the pool that asset withdraw from
pool_id: ID,
/// quantity of the asset user withdrew
quantity: u64,
/// owner ID of the `AccountCap` that withdrew the asset
owner: address
}
/// Returned as metadata only when a maker order is filled from place order functions.
public struct MatchedOrderMetadata<phantom BaseAsset, phantom QuoteAsset> has copy, store, drop {
/// object ID of the pool the order was placed on
pool_id: ID,
/// ID of the order within the pool
order_id: u64,
/// Direction of order.
is_bid: bool,
/// owner ID of the `AccountCap` that filled the order
taker_address: address,
/// owner ID of the `AccountCap` that placed the order
maker_address: address,
/// qty of base asset filled.
base_asset_quantity_filled: u64,
/// price at which basset asset filled.
price: u64,
taker_commission: u64,
maker_rebates: u64
}
// <<<<<<<<<<<<<<<<<<<<<<<< Events <<<<<<<<<<<<<<<<<<<<<<<<
public struct Order has store, drop {
// For each pool, order id is incremental and unique for each opening order.
// Orders that are submitted earlier has lower order ids.
// 64 bits are sufficient for order ids whereas 32 bits are not.
// Assuming a maximum TPS of 100K/s of Sui chain, it would take (1<<63) / 100000 / 3600 / 24 / 365 = 2924712 years to reach the full capacity.
// The highest bit of the order id is used to denote the order type, 0 for bid, 1 for ask.
order_id: u64,
client_order_id: u64,
// Only used for limit orders.
price: u64,
// quantity when the order first placed in
original_quantity: u64,
// quantity of the order currently held
quantity: u64,
is_bid: bool,
/// Order can only be canceled by the `AccountCap` with this owner ID
owner: address,
// Expiration timestamp in ms.
expire_timestamp: u64,
// reserved field for prevent self_matching
self_matching_prevention: u8
}
public struct TickLevel has store {
price: u64,
// The key is order's order_id.
open_orders: LinkedTable<u64, Order>,
}
public struct Pool<phantom BaseAsset, phantom QuoteAsset> has key, store {
// The key to the following Critbit Tree are order prices.
id: UID,
// All open bid orders.
bids: CritbitTree<TickLevel>,
// All open ask orders.
asks: CritbitTree<TickLevel>,
// Order id of the next bid order, starting from 0.
next_bid_order_id: u64,
// Order id of the next ask order, starting from 1<<63.
next_ask_order_id: u64,
// Map from AccountCap owner ID -> (map from order id -> order price)
usr_open_orders: Table<address, LinkedTable<u64, u64>>,
// taker_fee_rate should be strictly greater than maker_rebate_rate.
// The difference between taker_fee_rate and maker_rabate_rate goes to the protocol.
// 10^9 scaling
taker_fee_rate: u64,
// 10^9 scaling
maker_rebate_rate: u64,
tick_size: u64,
lot_size: u64,
// other pool info
base_custodian: Custodian<BaseAsset>,
quote_custodian: Custodian<QuoteAsset>,
// Stores the fee paid to create this pool. These funds are not accessible.
creation_fee: Balance<SUI>,
// Deprecated.
base_asset_trading_fees: Balance<BaseAsset>,
// Stores the trading fees paid in `QuoteAsset`. These funds are not accessible in the V1 of the Pools, but V2 Pools are accessible.
quote_asset_trading_fees: Balance<QuoteAsset>,
}
/// Capability granting permission to access an entry in `Pool.quote_asset_trading_fees`.
/// The pool objects created for older pools do not have a PoolOwnerCap because they were created
/// prior to the addition of this feature. Here is a list of 11 pools on mainnet that
/// do not have this capability:
/// 0x31d1790e617eef7f516555124155b28d663e5c600317c769a75ee6336a54c07f
/// 0x6e417ee1c12ad5f2600a66bc80c7bd52ff3cb7c072d508700d17cf1325324527
/// 0x17625f1a241d34d2da0dc113086f67a2b832e3e8cd8006887c195cd24d3598a3
/// 0x276ff4d99ecb3175091ba4baffa9b07590f84e2344e3f16e95d30d2c1678b84c
/// 0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238
/// 0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33
/// 0xf0f663cf87f1eb124da2fc9be813e0ce262146f3df60bc2052d738eb41a25899
/// 0xd9e45ab5440d61cc52e3b2bd915cdd643146f7593d587c715bc7bfa48311d826
/// 0x5deafda22b6b86127ea4299503362638bea0ca33bb212ea3a67b029356b8b955
/// 0x7f526b1263c4b91b43c9e646419b5696f424de28dda3c1e6658cc0a54558baa7
/// 0x18d871e3c3da99046dfc0d3de612c5d88859bc03b8f0568bd127d0e70dbc58be
public struct PoolOwnerCap has key, store {
id: UID,
/// The owner of this AccountCap. Note: this is
/// derived from an object ID, not a user address
owner: address
}
/// Accessor functions
public fun usr_open_orders_exist<BaseAsset, QuoteAsset>(
pool: &Pool<BaseAsset, QuoteAsset>,
owner: address
): bool {
table::contains(&pool.usr_open_orders, owner)
}
public fun usr_open_orders_for_address<BaseAsset, QuoteAsset>(
pool: &Pool<BaseAsset, QuoteAsset>,
owner: address
): &LinkedTable<u64, u64> {
table::borrow(&pool.usr_open_orders, owner)
}
public fun usr_open_orders<BaseAsset, QuoteAsset>(
pool: &Pool<BaseAsset, QuoteAsset>,
): &Table<address, LinkedTable<u64, u64>> {
&pool.usr_open_orders
}
/// Function to withdraw fees created from a pool
public fun withdraw_fees<BaseAsset, QuoteAsset>(
pool_owner_cap: &PoolOwnerCap,
pool: &mut Pool<BaseAsset, QuoteAsset>,
ctx: &mut TxContext,
): Coin<QuoteAsset> {
assert!(pool_owner_cap.owner == object::uid_to_address(&pool.id), EIncorrectPoolOwner);
let quantity = quote_asset_trading_fees_value(pool);
let to_withdraw = balance::split(&mut pool.quote_asset_trading_fees, quantity);
coin::from_balance(to_withdraw, ctx)
}
/// Destroy the given `pool_owner_cap` object
public fun delete_pool_owner_cap(pool_owner_cap: PoolOwnerCap) {
let PoolOwnerCap { id, owner: _ } = pool_owner_cap;
object::delete(id)
}
fun destroy_empty_level(level: TickLevel) {
let TickLevel {
price: _,
open_orders: orders,
} = level;
linked_table::destroy_empty(orders);
}
public fun create_account(ctx: &mut TxContext): AccountCap {
mint_account_cap(ctx)
}
#[allow(lint(self_transfer, share_owned))]
fun create_pool_<BaseAsset, QuoteAsset>(
taker_fee_rate: u64,
maker_rebate_rate: u64,
tick_size: u64,
lot_size: u64,
creation_fee: Balance<SUI>,
ctx: &mut TxContext,
) {
let (pool, pool_owner_cap) = create_pool_with_return_<BaseAsset, QuoteAsset>(
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
creation_fee,
ctx
);
transfer::public_transfer(pool_owner_cap, tx_context::sender(ctx));
transfer::share_object(pool);
}
public fun create_pool<BaseAsset, QuoteAsset>(
tick_size: u64,
lot_size: u64,
creation_fee: Coin<SUI>,
ctx: &mut TxContext,
) {
create_customized_pool<BaseAsset, QuoteAsset>(
tick_size,
lot_size,
REFERENCE_TAKER_FEE_RATE,
REFERENCE_MAKER_REBATE_RATE,
creation_fee,
ctx,
);
}
/// Function for creating pool with customized taker fee rate and maker rebate rate.
/// The taker_fee_rate should be greater than or equal to the maker_rebate_rate, and both should have a scaling of 10^9.
/// Taker_fee_rate of 0.25% should be 2_500_000 for example
public fun create_customized_pool<BaseAsset, QuoteAsset>(
tick_size: u64,
lot_size: u64,
taker_fee_rate: u64,
maker_rebate_rate: u64,
creation_fee: Coin<SUI>,
ctx: &mut TxContext,
) {
create_pool_<BaseAsset, QuoteAsset>(
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
coin::into_balance(creation_fee),
ctx
)
}
/// Helper function that all the create pools now call to create pools.
fun create_pool_with_return_<BaseAsset, QuoteAsset>(
taker_fee_rate: u64,
maker_rebate_rate: u64,
tick_size: u64,
lot_size: u64,
creation_fee: Balance<SUI>,
ctx: &mut TxContext,
): (Pool<BaseAsset, QuoteAsset>, PoolOwnerCap) {
assert!(balance::value(&creation_fee) == FEE_AMOUNT_FOR_CREATE_POOL, EInvalidFee);
let base_type_name = type_name::get<BaseAsset>();
let quote_type_name = type_name::get<QuoteAsset>();
assert!(clob_math::unsafe_mul(lot_size, tick_size) > 0, EInvalidTickSizeLotSize);
assert!(base_type_name != quote_type_name, EInvalidPair);
assert!(taker_fee_rate >= maker_rebate_rate, EInvalidFeeRateRebateRate);
let pool_uid = object::new(ctx);
let pool_id = *object::uid_as_inner(&pool_uid);
// Creates the capability to mark a pool owner.
let id = object::new(ctx);
let owner = object::uid_to_address(&pool_uid);
let pool_owner_cap = PoolOwnerCap { id, owner };
event::emit(PoolCreated {
pool_id,
base_asset: base_type_name,
quote_asset: quote_type_name,
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
});
(Pool<BaseAsset, QuoteAsset> {
id: pool_uid,
bids: critbit::new(ctx),
asks: critbit::new(ctx),
next_bid_order_id: MIN_BID_ORDER_ID,
next_ask_order_id: MIN_ASK_ORDER_ID,
usr_open_orders: table::new(ctx),
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
base_custodian: custodian::new<BaseAsset>(ctx),
quote_custodian: custodian::new<QuoteAsset>(ctx),
creation_fee,
base_asset_trading_fees: balance::zero(),
quote_asset_trading_fees: balance::zero(),
}, pool_owner_cap)
}
/// Function for creating an external pool. This API can be used to wrap deepbook pools into other objects.
public fun create_pool_with_return<BaseAsset, QuoteAsset>(
tick_size: u64,
lot_size: u64,
creation_fee: Coin<SUI>,
ctx: &mut TxContext,
): Pool<BaseAsset, QuoteAsset> {
create_customized_pool_with_return<BaseAsset, QuoteAsset>(
tick_size,
lot_size,
REFERENCE_TAKER_FEE_RATE,
REFERENCE_MAKER_REBATE_RATE,
creation_fee,
ctx,
)
}
#[allow(lint(self_transfer))]
/// Function for creating pool with customized taker fee rate and maker rebate rate.
/// The taker_fee_rate should be greater than or equal to the maker_rebate_rate, and both should have a scaling of 10^9.
/// Taker_fee_rate of 0.25% should be 2_500_000 for example
public fun create_customized_pool_with_return<BaseAsset, QuoteAsset>(
tick_size: u64,
lot_size: u64,
taker_fee_rate: u64,
maker_rebate_rate: u64,
creation_fee: Coin<SUI>,
ctx: &mut TxContext,
) : Pool<BaseAsset, QuoteAsset> {
let (pool, pool_owner_cap) = create_pool_with_return_<BaseAsset, QuoteAsset>(
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
coin::into_balance(creation_fee),
ctx
);
transfer::public_transfer(pool_owner_cap, tx_context::sender(ctx));
pool
}
/// A V2 function for creating customized pools for better PTB friendliness/compostability.
/// If a user wants to create a pool and then destroy/lock the pool_owner_cap one can do
/// so with this function.
public fun create_customized_pool_v2<BaseAsset, QuoteAsset>(
tick_size: u64,
lot_size: u64,
taker_fee_rate: u64,
maker_rebate_rate: u64,
creation_fee: Coin<SUI>,
ctx: &mut TxContext,
) : (Pool<BaseAsset, QuoteAsset>, PoolOwnerCap) {
create_pool_with_return_<BaseAsset, QuoteAsset>(
taker_fee_rate,
maker_rebate_rate,
tick_size,
lot_size,
coin::into_balance(creation_fee),
ctx
)
}
public fun deposit_base<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
coin: Coin<BaseAsset>,
account_cap: &AccountCap
) {
let quantity = coin::value(&coin);
assert!(quantity != 0, EInsufficientBaseCoin);
custodian::increase_user_available_balance(
&mut pool.base_custodian,
account_owner(account_cap),
coin::into_balance(coin)
);
event::emit(DepositAsset<BaseAsset>{
pool_id: *object::uid_as_inner(&pool.id),
quantity,
owner: account_owner(account_cap)
})
}
public fun deposit_quote<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
coin: Coin<QuoteAsset>,
account_cap: &AccountCap
) {
let quantity = coin::value(&coin);
assert!(quantity != 0, EInsufficientQuoteCoin);
custodian::increase_user_available_balance(
&mut pool.quote_custodian,
account_owner(account_cap),
coin::into_balance(coin)
);
event::emit(DepositAsset<QuoteAsset>{
pool_id: *object::uid_as_inner(&pool.id),
quantity,
owner: account_owner(account_cap)
})
}
public fun withdraw_base<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
quantity: u64,
account_cap: &AccountCap,
ctx: &mut TxContext
): Coin<BaseAsset> {
assert!(quantity > 0, EInvalidQuantity);
event::emit(WithdrawAsset<BaseAsset>{
pool_id: *object::uid_as_inner(&pool.id),
quantity,
owner: account_owner(account_cap)
});
custodian::withdraw_asset(&mut pool.base_custodian, quantity, account_cap, ctx)
}
public fun withdraw_quote<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
quantity: u64,
account_cap: &AccountCap,
ctx: &mut TxContext
): Coin<QuoteAsset> {
assert!(quantity > 0, EInvalidQuantity);
event::emit(WithdrawAsset<QuoteAsset>{
pool_id: *object::uid_as_inner(&pool.id),
quantity,
owner: account_owner(account_cap)
});
custodian::withdraw_asset(&mut pool.quote_custodian, quantity, account_cap, ctx)
}
// for smart routing
public fun swap_exact_base_for_quote<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
client_order_id: u64,
account_cap: &AccountCap,
quantity: u64,
base_coin: Coin<BaseAsset>,
quote_coin: Coin<QuoteAsset>,
clock: &Clock,
ctx: &mut TxContext,
): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) {
assert!(quantity > 0, EInvalidQuantity);
assert!(coin::value(&base_coin) >= quantity, EInsufficientBaseCoin);
let original_val = coin::value("e_coin);
let (ret_base_coin, ret_quote_coin) = place_market_order(
pool,
account_cap,
client_order_id,
quantity,
false,
base_coin,
quote_coin,
clock,
ctx
);
let ret_val = coin::value(&ret_quote_coin);
(ret_base_coin, ret_quote_coin, ret_val - original_val)
}
// for smart routing
public fun swap_exact_base_for_quote_with_metadata<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
client_order_id: u64,
account_cap: &AccountCap,
quantity: u64,
base_coin: Coin<BaseAsset>,
quote_coin: Coin<QuoteAsset>,
clock: &Clock,
ctx: &mut TxContext,
): (Coin<BaseAsset>, Coin<QuoteAsset>, u64, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) {
let original_val = coin::value("e_coin);
let (ret_base_coin, ret_quote_coin, mut matched_order_metadata) = place_market_order_int(
pool,
account_cap,
client_order_id,
quantity,
false,
base_coin,
quote_coin,
clock,
true, // return metadata
ctx
);
let ret_val = coin::value(&ret_quote_coin);
(ret_base_coin, ret_quote_coin, ret_val - original_val, option::extract(&mut matched_order_metadata))
}
// for smart routing
public fun swap_exact_quote_for_base<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
client_order_id: u64,
account_cap: &AccountCap,
quantity: u64,
clock: &Clock,
quote_coin: Coin<QuoteAsset>,
ctx: &mut TxContext,
): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) {
assert!(quantity > 0, EInvalidQuantity);
assert!(coin::value("e_coin) >= quantity, EInsufficientQuoteCoin);
let (base_asset_balance, quote_asset_balance, _matched_order_metadata) = match_bid_with_quote_quantity(
pool,
account_cap,
client_order_id,
quantity,
MAX_PRICE,
clock::timestamp_ms(clock),
coin::into_balance(quote_coin),
false // don't return metadata
);
let val = balance::value(&base_asset_balance);
(coin::from_balance(base_asset_balance, ctx), coin::from_balance(quote_asset_balance, ctx), val)
}
public fun swap_exact_quote_for_base_with_metadata<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
client_order_id: u64,
account_cap: &AccountCap,
quantity: u64,
clock: &Clock,
quote_coin: Coin<QuoteAsset>,
ctx: &mut TxContext,
): (Coin<BaseAsset>, Coin<QuoteAsset>, u64, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) {
assert!(quantity > 0, EInvalidQuantity);
assert!(coin::value("e_coin) >= quantity, EInsufficientQuoteCoin);
let (base_asset_balance, quote_asset_balance, mut matched_order_metadata) = match_bid_with_quote_quantity(
pool,
account_cap,
client_order_id,
quantity,
MAX_PRICE,
clock::timestamp_ms(clock),
coin::into_balance(quote_coin),
true // return metadata
);
let val = balance::value(&base_asset_balance);
(coin::from_balance(base_asset_balance, ctx), coin::from_balance(quote_asset_balance, ctx), val, option::extract(&mut matched_order_metadata))
}
fun match_bid_with_quote_quantity<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
account_cap: &AccountCap,
client_order_id: u64,
quantity: u64,
price_limit: u64,
current_timestamp: u64,
quote_balance: Balance<QuoteAsset>,
compute_metadata: bool,
): (Balance<BaseAsset>, Balance<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) {
// Base balance received by taker, taking into account of taker commission.
// Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
let pool_id = *object::uid_as_inner(&pool.id);
let mut taker_quote_quantity_remaining = quantity;
let mut base_balance_filled = balance::zero<BaseAsset>();
let mut quote_balance_left = quote_balance;
let all_open_orders = &mut pool.asks;
let mut matched_order_metadata = vector::empty<MatchedOrderMetadata<BaseAsset, QuoteAsset>>();
if (critbit::is_empty(all_open_orders)) {
return (base_balance_filled, quote_balance_left, option::none())
};
let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
let mut terminate_loop = false;
let mut canceled_order_events = vector[];
while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) {
let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
while (!linked_table::is_empty(&tick_level.open_orders)) {
let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
let mut maker_base_quantity = maker_order.quantity;
let mut skip_order = false;
if (maker_order.expire_timestamp <= current_timestamp || account_owner(account_cap) == maker_order.owner) {
skip_order = true;
custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> {
client_order_id: maker_order.client_order_id,
order_id: maker_order.order_id,
is_bid: maker_order.is_bid,
owner: maker_order.owner,
original_quantity: maker_order.original_quantity,
base_asset_quantity_canceled: maker_order.quantity,
price: maker_order.price
};
vector::push_back(&mut canceled_order_events, canceled_order_event);
} else {
// Calculate how much quote asset (maker_quote_quantity) is required, including the commission, to fill the maker order.
let maker_quote_quantity_without_commission = clob_math::mul(
maker_base_quantity,
maker_order.price
);
let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
maker_quote_quantity_without_commission,
pool.taker_fee_rate
);
if (is_round_down) taker_commission = taker_commission + 1;
let maker_quote_quantity = maker_quote_quantity_without_commission + taker_commission;
// Total base quantity filled.
let mut filled_base_quantity: u64;
// Total quote quantity filled, excluding commission and rebate.
let mut filled_quote_quantity: u64;
// Total quote quantity paid by taker.
// filled_quote_quantity_without_commission * (FLOAT_SCALING + taker_fee_rate) = filled_quote_quantity
let mut filled_quote_quantity_without_commission: u64;
if (taker_quote_quantity_remaining > maker_quote_quantity) {
filled_quote_quantity = maker_quote_quantity;
filled_quote_quantity_without_commission = maker_quote_quantity_without_commission;
filled_base_quantity = maker_base_quantity;
} else {
terminate_loop = true;
// if not enough quote quantity to pay for taker commission, then no quantity will be filled
filled_quote_quantity_without_commission = clob_math::unsafe_div(
taker_quote_quantity_remaining,
FLOAT_SCALING + pool.taker_fee_rate
);
// filled_base_quantity = 0 is permitted since filled_quote_quantity_without_commission can be 0
filled_base_quantity = clob_math::unsafe_div(
filled_quote_quantity_without_commission,
maker_order.price
);
let filled_base_lot = filled_base_quantity / pool.lot_size;
filled_base_quantity = filled_base_lot * pool.lot_size;
// filled_quote_quantity_without_commission = 0 is permitted here since filled_base_quantity could be 0
filled_quote_quantity_without_commission = clob_math::unsafe_mul(
filled_base_quantity,
maker_order.price
);
// if taker_commission = 0 due to underflow, round it up to 1
let (round_down, mut taker_commission) = clob_math::unsafe_mul_round(
filled_quote_quantity_without_commission,
pool.taker_fee_rate
);
if (round_down) {
taker_commission = taker_commission + 1;
};
filled_quote_quantity = filled_quote_quantity_without_commission + taker_commission;
};
// if maker_rebate = 0 due to underflow, maker will not receive a rebate
let maker_rebate = clob_math::unsafe_mul(
filled_quote_quantity_without_commission,
pool.maker_rebate_rate
);
maker_base_quantity = maker_base_quantity - filled_base_quantity;
// maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
taker_quote_quantity_remaining = taker_quote_quantity_remaining - filled_quote_quantity;
let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
&mut pool.base_custodian,
maker_order.owner,
filled_base_quantity
);
let mut quote_balance_filled = balance::split(
&mut quote_balance_left,
filled_quote_quantity,
);
// Send quote asset including rebate to maker.
custodian::increase_user_available_balance<QuoteAsset>(
&mut pool.quote_custodian,
maker_order.owner,
balance::split(
&mut quote_balance_filled,
maker_rebate + filled_quote_quantity_without_commission,
),
);
// Send remaining of commission - rebate to the protocol.
// commission - rebate = filled_quote_quantity_without_commission - filled_quote_quantity - maker_rebate
balance::join(&mut pool.quote_asset_trading_fees, quote_balance_filled);
balance::join(&mut base_balance_filled, locked_base_balance);
emit_order_filled<BaseAsset, QuoteAsset>(
*object::uid_as_inner(&pool.id),
client_order_id,
account_owner(account_cap),
maker_order,
filled_base_quantity,
// taker_commission = filled_quote_quantity - filled_quote_quantity_without_commission
// This guarantees that the subtraction will not underflow
filled_quote_quantity - filled_quote_quantity_without_commission,
maker_rebate
);
if(compute_metadata) {
vector::push_back(
&mut matched_order_metadata,
matched_order_metadata(
*object::uid_as_inner(&pool.id),
account_owner(account_cap),
maker_order,
filled_base_quantity,
// taker_commission = filled_quote_quantity - filled_quote_quantity_without_commission
// This guarantees that the subtraction will not underflow
filled_quote_quantity - filled_quote_quantity_without_commission,
maker_rebate
)
);
};
};
if (skip_order || maker_base_quantity == 0) {
// Remove the maker order.
let old_order_id = order_id;
let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
if (!option::is_none(maybe_order_id)) {
order_id = *option::borrow(maybe_order_id);
};
let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
linked_table::remove(usr_open_order_ids, old_order_id);
linked_table::remove(&mut tick_level.open_orders, old_order_id);
} else {
// Update the maker order.
let maker_order_mut = linked_table::borrow_mut(
&mut tick_level.open_orders,
order_id);
maker_order_mut.quantity = maker_base_quantity;
};
if (terminate_loop) {
break
};
};
if (linked_table::is_empty(&tick_level.open_orders)) {
(tick_price, _) = next_leaf(all_open_orders, tick_price);
destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
(_, tick_index) = find_leaf(all_open_orders, tick_price);
};
if (terminate_loop) {
break
};
};
if (!vector::is_empty(&canceled_order_events)) {
event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> {
pool_id,
orders_canceled: canceled_order_events,
});
};
return (base_balance_filled, quote_balance_left, if(compute_metadata) option::some(matched_order_metadata) else option::none())
}
fun match_bid<BaseAsset, QuoteAsset>(
pool: &mut Pool<BaseAsset, QuoteAsset>,
account_cap: &AccountCap,
client_order_id: u64,
quantity: u64,
price_limit: u64,
current_timestamp: u64,
quote_balance: Balance<QuoteAsset>,
compute_metadata: bool,
): (Balance<BaseAsset>, Balance<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) {
let pool_id = *object::uid_as_inner(&pool.id);
// Base balance received by taker.
// Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
let mut taker_base_quantity_remaining = quantity;
let mut base_balance_filled = balance::zero<BaseAsset>();
let mut quote_balance_left = quote_balance;
let all_open_orders = &mut pool.asks;
let mut matched_order_metadata = vector::empty<MatchedOrderMetadata<BaseAsset, QuoteAsset>>();
if (critbit::is_empty(all_open_orders)) {
return (base_balance_filled, quote_balance_left, option::none())
};
let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
let mut canceled_order_events = vector[];
while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) {
let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
while (!linked_table::is_empty(&tick_level.open_orders)) {
let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
let mut maker_base_quantity = maker_order.quantity;
let mut skip_order = false;
if (maker_order.expire_timestamp <= current_timestamp || account_owner(account_cap) == maker_order.owner) {
skip_order = true;
custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> {
client_order_id: maker_order.client_order_id,
order_id: maker_order.order_id,
is_bid: maker_order.is_bid,
owner: maker_order.owner,
original_quantity: maker_order.original_quantity,
base_asset_quantity_canceled: maker_order.quantity,
price: maker_order.price
};
vector::push_back(&mut canceled_order_events, canceled_order_event);
} else {
let filled_base_quantity =
if (taker_base_quantity_remaining > maker_base_quantity) { maker_base_quantity }
else { taker_base_quantity_remaining };
// Note that if a user creates a pool that allows orders that are too small, this will fail since we cannot have a filled
// quote quantity of 0.
let filled_quote_quantity = clob_math::mul(filled_base_quantity, maker_order.price);
// if maker_rebate = 0 due to underflow, maker will not receive a rebate
let maker_rebate = clob_math::unsafe_mul(filled_quote_quantity, pool.maker_rebate_rate);
// if taker_commission = 0 due to underflow, round it up to 1
let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
filled_quote_quantity,
pool.taker_fee_rate
);
if (is_round_down) taker_commission = taker_commission + 1;
maker_base_quantity = maker_base_quantity - filled_base_quantity;
// maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
taker_base_quantity_remaining = taker_base_quantity_remaining - filled_base_quantity;
let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
&mut pool.base_custodian,
maker_order.owner,
filled_base_quantity
);
let mut taker_commission_balance = balance::split(
&mut quote_balance_left,
taker_commission,
);
custodian::increase_user_available_balance<QuoteAsset>(
&mut pool.quote_custodian,
maker_order.owner,
balance::split(
&mut taker_commission_balance,
maker_rebate,
),
);
balance::join(&mut pool.quote_asset_trading_fees, taker_commission_balance);
balance::join(&mut base_balance_filled, locked_base_balance);
custodian::increase_user_available_balance<QuoteAsset>(
&mut pool.quote_custodian,
maker_order.owner,
balance::split(
&mut quote_balance_left,
filled_quote_quantity,
),
);
emit_order_filled<BaseAsset, QuoteAsset>(
*object::uid_as_inner(&pool.id),
client_order_id,
account_owner(account_cap),
maker_order,
filled_base_quantity,
taker_commission,
maker_rebate