This repository has been archived by the owner on Apr 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
market.move
6607 lines (6444 loc) · 278 KB
/
market.move
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
/// Market-level book keeping functionality, with matching engine.
/// Allows for self-matched trades since preventing them is practically
/// impossible in a permissionless market: all a user has to do is
/// open two wallets and trade them against each other.
///
/// End-to-end matching engine testing begins with a call to
/// `register_end_to_end_users_test()`, which places a limit order order
/// on the book for `USER_1` (`@user_1`) `USER_2`, and `USER_3`, with
/// `USER_1`'s order nearest the spread and `USER_3`'s order furthest
/// away. Then a call to the matching engine is invoked, and post-match
/// state is verified via `verify_end_to_end_state_test()`. See tests
/// of form `test_end_to_end....()`.
///
/// Dependency charts for both matching engine functions and end-to-end
/// testing functions are at [`doc/doc-site/overview/matching.md`](
/// ../../../../../../doc/doc-site/overview/matching.md).
///
/// ---
module econia::market {
// Uses >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use aptos_framework::coin;
use aptos_std::type_info;
use econia::critbit::{Self, CritBitTree};
use econia::open_table;
use econia::order_id;
use econia::registry::{Self, CustodianCapability};
use econia::user;
use std::signer::address_of;
use std::option;
use std::vector;
// Uses <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Test-only uses >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[test_only]
use aptos_framework::account;
#[test_only]
use econia::assets::{Self, BC, BG, QC, QG};
// Test-only uses <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Structs >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/// An order on the order book
struct Order has store {
/// Number of lots to be filled
size: u64,
/// Address of corresponding user
user: address,
/// For given user, the ID of the custodian required to approve
/// orders and coin withdrawals
general_custodian_id: u64
}
#[method(
orders_vector,
orders_vectors,
price_levels_vectors
)]
/// An order book for a given market
struct OrderBook has store {
/// Base asset type info. When trading an
/// `aptos_framework::coin::Coin`, corresponds to the phantom
/// `CoinType`, for instance `MyCoin` rather than
/// `Coin<MyCoin>`. Otherwise corresponds to
/// `registry::GenericAsset`, or a non-coin asset indicated by
/// the market host.
base_type_info: type_info::TypeInfo,
/// Quote asset type info. When trading an
/// `aptos_framework::coin::Coin`, corresponds to the phantom
/// `CoinType`, for instance `MyCoin` rather than
/// `Coin<MyCoin>`. Otherwise corresponds to
/// `registry::GenericAsset`, or a non-coin asset indicated by
/// the market host.
quote_type_info: type_info::TypeInfo,
/// Number of base units exchanged per lot
lot_size: u64,
/// Number of quote units exchanged per tick
tick_size: u64,
/// ID of custodian capability required to verify deposits,
/// swaps, and withdrawals of assets that are not coins. A
/// "market-wide asset transfer custodian ID" that only applies
/// to markets having at least one non-coin asset. For a market
/// having one coin asset and one generic asset, only applies to
/// the generic asset. Marked `PURE_COIN_PAIR` when base and
/// quote types are both coins.
generic_asset_transfer_custodian_id: u64,
/// Asks tree
asks: CritBitTree<Order>,
/// Bids tree
bids: CritBitTree<Order>,
/// Order ID of minimum ask, per price-time priority. The ask
/// side "spread maker".
min_ask: u128,
/// Order ID of maximum bid, per price-time priority. The bid
/// side "spread maker".
max_bid: u128,
/// Number of maker orders placed on book
counter: u64
}
/// Order book map for all of a user's `OrderBook`s
struct OrderBooks has key {
/// Map from market ID to `OrderBook`. Separated into different
/// table entries to reduce transaction collisions across
/// markets
map: open_table::OpenTable<u64, OrderBook>
}
// Structs <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Error codes >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/// When an order book already exists at given address
const E_ORDER_BOOK_EXISTS: u64 = 0;
/// When a host does not have an `OrderBooks`
const E_NO_ORDER_BOOKS: u64 = 1;
/// When indicated `OrderBook` does not exist
const E_NO_ORDER_BOOK: u64 = 2;
/// When minimum number of lots are not filled by matching engine
const E_MIN_LOTS_NOT_FILLED: u64 = 3;
/// When minimum number of ticks are not filled by matching engine
const E_MIN_TICKS_NOT_FILLED: u64 = 4;
/// When order not found in book
const E_NO_ORDER: u64 = 5;
/// When invalid user attempts to manage an order
const E_INVALID_USER: u64 = 6;
/// When invalid custodian attempts to manage an order
const E_INVALID_CUSTODIAN: u64 = 7;
/// When a post-or-abort limit order crosses the spread
const E_POST_OR_ABORT_CROSSED_SPREAD: u64 = 8;
/// When matching overflows the asset received from trading
const E_INBOUND_ASSET_OVERFLOW: u64 = 9;
/// When not enough asset to trade away for indicated match values
const E_NOT_ENOUGH_OUTBOUND_ASSET: u64 = 10;
/// When minimum indicated base units to match exceeds maximum
const E_MIN_BASE_EXCEEDS_MAX: u64 = 11;
/// When minimum indicated quote units to match exceeds maximum
const E_MIN_QUOTE_EXCEEDS_MAX: u64 = 12;
/// When indicated limit price is 0
const E_LIMIT_PRICE_0: u64 = 13;
/// When invalid base type indicated
const E_INVALID_BASE: u64 = 14;
/// When invalid quote type indicated
const E_INVALID_QUOTE: u64 = 15;
/// When a base asset is improperly option-wrapped for generic swap
const E_INVALID_OPTION_BASE: u64 = 16;
/// When a quote asset is improperly option-wrapped for generic swap
const E_INVALID_OPTION_QUOTE: u64 = 17;
/// When both assets are coins but at least one should be generic
const E_BOTH_COINS: u64 = 18;
/// When a limit order has too many flags
const E_TOO_MANY_ORDER_FLAGS: u64 = 19;
/// When limit order size max base fill overflows a `u64`
const E_SIZE_BASE_OVERFLOW: u64 = 20;
/// When limit order size max ticks fill overflows a `u64`
const E_SIZE_TICKS_OVERFLOW: u64 = 21;
/// When limit order size max quote fill overflows a `u64`
const E_SIZE_QUOTE_OVERFLOW: u64 = 22;
// Error codes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Constants >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/// Ask flag
const ASK: bool = true;
/// Bid flag
const BID: bool = false;
/// Buy direction flag
const BUY: bool = true;
/// `u64` bitmask with all bits set
const HI_64: u64 = 0xffffffffffffffff;
/// Left traversal direction, denoting predecessor traversal
const LEFT: bool = true;
/// Default value for maximum bid order ID
const MAX_BID_DEFAULT: u128 = 0;
/// Default value for minimum ask order ID
const MIN_ASK_DEFAULT: u128 = 0xffffffffffffffffffffffffffffffff;
/// Custodian ID flag for no delegated custodian
const NO_CUSTODIAN: u64 = 0;
/// When both base and quote assets are coins
const PURE_COIN_PAIR: u64 = 0;
/// Right traversal direction, denoting successor traversal
const RIGHT: bool = false;
/// Sell direction flag
const SELL: bool = false;
// Constants <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Public functions >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/// Cancel all limit order on behalf of user, via
/// `general_custodian_capability_ref`.
///
/// See wrapped function `cancel_all_limit_orders()`.
public fun cancel_all_limit_orders_custodian(
user: address,
host: address,
market_id: u64,
side: bool,
general_custodian_capability_ref: &CustodianCapability
) acquires OrderBooks {
cancel_all_limit_orders(
user,
host,
market_id,
registry::custodian_id(general_custodian_capability_ref),
side
);
}
/// Cancel a limit order on behalf of user, via
/// `general_custodian_capability_ref`.
///
/// See wrapped function `cancel_limit_order()`.
public fun cancel_limit_order_custodian(
user: address,
host: address,
market_id: u64,
side: bool,
order_id: u128,
general_custodian_capability_ref: &CustodianCapability
) acquires OrderBooks {
cancel_limit_order(
user,
host,
market_id,
registry::custodian_id(general_custodian_capability_ref),
side,
order_id
);
}
/// Place a limit order on behalf of user, via
/// `general_custodian_capability_ref`.
///
/// See wrapped function `place_limit_order()`.
public fun place_limit_order_custodian<
BaseType,
QuoteType
>(
user: address,
host: address,
market_id: u64,
side: bool,
size: u64,
price: u64,
post_or_abort: bool,
fill_or_abort: bool,
immediate_or_cancel: bool,
general_custodian_capability_ref: &CustodianCapability
) acquires OrderBooks {
place_limit_order<
BaseType,
QuoteType
>(
&user,
&host,
&market_id,
®istry::custodian_id(general_custodian_capability_ref),
&side,
&size,
&price,
&post_or_abort,
&fill_or_abort,
&immediate_or_cancel
);
}
/// Place a market order from a market account, on behalf of a user,
/// via `general_custodian_capability_ref`.
///
/// See wrapped function `place_market_order_order()`.
public fun place_market_order_custodian<
BaseType,
QuoteType
>(
user: address,
host: address,
market_id: u64,
direction: bool,
min_base: u64,
max_base: u64,
min_quote: u64,
max_quote: u64,
limit_price: u64,
general_custodian_capability_ref: &CustodianCapability
) acquires OrderBooks {
place_market_order<
BaseType,
QuoteType
>(
&user,
&host,
&market_id,
®istry::custodian_id(general_custodian_capability_ref),
&direction,
&min_base,
&max_base,
&min_quote,
&max_quote,
&limit_price
);
}
/// Swap between coins of `BaseCoinType` and `QuoteCoinType`.
///
/// # Type parameters
/// * `BaseCoinType`: Base type for market
/// * `QuoteCoinType`: Quote type for market
///
/// # Parameters
/// * `host`: Market host
/// * `market_id`: Market ID
/// * `direction`: `BUY` or `SELL`
/// * `min_base`: Minimum number of base coins to fill
/// * `max_base`: Maximum number of base coins to fill
/// * `min_quote`: Minimum number of quote coins to fill
/// * `max_quote`: Maximum number of quote coins to fill
/// * `limit_price`: Maximum price to match against if `direction`
/// is `BUY`, and minimum price to match against if `direction` is
/// `SELL`. If passed as `HI_64` in the case of a `BUY` or `0` in
/// the case of a `SELL`, will match at any price. Price for a
/// given market is the number of ticks per lot.
/// * `base_coins_ref_mut`: Mutable reference to base coins on hand
/// before swap. Incremented if a `BUY`, and decremented if a
/// `SELL`.
/// * `quote_coins_ref_mut`: Mutable reference to quote coins on
/// hand before swap. Incremented if a `SELL`, and decremented if
/// a `BUY`.
///
/// # Returns
/// * `u64`: Base coins filled
/// * `u64`: Quote coins filled
///
/// # Abort conditions
///
/// ## If a `BUY`
/// * If quote coins on hand is less than `max_quote`
/// * If filling `max_base` would overflow base coins on hand
///
/// ## If a `SELL`
/// * If base coins on hand is less than `max_base`
/// * If filling `max_quote` would overflow quote coins on hand
public fun swap_coins<
BaseCoinType,
QuoteCoinType
>(
host: address,
market_id: u64,
direction: bool,
min_base: u64,
max_base: u64,
min_quote: u64,
max_quote: u64,
limit_price: u64,
base_coins_ref_mut: &mut coin::Coin<BaseCoinType>,
quote_coins_ref_mut: &mut coin::Coin<QuoteCoinType>
): (
u64,
u64
) acquires OrderBooks {
// Get value of base coins on hand
let base_value = coin::value(base_coins_ref_mut);
// Get value of quote coins on hand
let quote_value = coin::value(quote_coins_ref_mut);
// Range check fill amounts
match_range_check_fills(&direction, &min_base, &max_base, &min_quote,
&max_quote, &base_value, &base_value, "e_value, "e_value);
// Get option-wrapped base and quote coins for matching engine
let (optional_base_coins, optional_quote_coins) =
if (direction == BUY) ( // If buying base with quote
// Start with 0 base coins
option::some(coin::zero<BaseCoinType>()),
// Start with max quote coins needed for trade
option::some(coin::extract(quote_coins_ref_mut, max_quote))
) else ( // If selling base for quote
// Start with max base coins needed for trade
option::some(coin::extract(base_coins_ref_mut, max_base)),
// Start with 0 quote coins
option::some(coin::zero<QuoteCoinType>())
);
// Declare tracker variables for amount of base and quote filled
let (base_filled, quote_filled) = (0, 0);
// Swap against order book
swap<BaseCoinType, QuoteCoinType>(&host, &market_id, &direction,
&min_base, &max_base, &min_quote, &max_quote, &limit_price,
&mut optional_base_coins, &mut optional_quote_coins,
&mut base_filled, &mut quote_filled, &PURE_COIN_PAIR);
coin::merge( // Merge post-match base coins into coins on hand
base_coins_ref_mut, option::destroy_some(optional_base_coins));
coin::merge( // Merge post-match quote coins into coins on hand
quote_coins_ref_mut, option::destroy_some(optional_quote_coins));
// Return count for base coins and quote coins filled
(base_filled, quote_filled)
}
/// Swap between assets where at least one is not a coin type.
///
/// # Type parameters
/// * `BaseType`: Base type for market
/// * `QuoteType`: Quote type for market
///
/// # Parameters
/// * `host`: Market host
/// * `market_id`: Market ID
/// * `direction`: `BUY` or `SELL`
/// * `min_base`: Minimum number of base coins to fill
/// * `max_base`: Maximum number of base coins to fill
/// * `min_quote`: Minimum number of quote coins to fill
/// * `max_quote`: Maximum number of quote coins to fill
/// * `limit_price`: Maximum price to match against if `direction`
/// is `BUY`, and minimum price to match against if `direction` is
/// `SELL`. If passed as `HI_64` in the case of a `BUY` or `0` in
/// the case of a `SELL`, will match at any price. Price for a
/// given market is the number of ticks per lot.
/// * `optional_base_coins_ref_mut`: If base is a coin type, coins
/// wrapped in an option, else an empty option
/// * `optional_quote_coins_ref_mut`: If quote is a coin type, coins
/// wrapped in an option, else an empty option
/// * `generic_asset_transfer_custodian_capability_ref`: Immutable
/// reference to generic asset transfer `CustodianCapability` for
/// given market
///
/// # Returns
/// * `u64`: Base assets filled
/// * `u64`: Quote assets filled
///
/// # Abort conditions
/// * If base and quote assets are both coin types
/// * If base is a coin type but base coin option is none, or if
/// base is not a coin type but base coin option is some (the
/// second condition should be impossible, since a coin resource
/// cannot be generated from a non-coin coin type)
/// * If quote is a coin type but quote coin option is none, or if
/// quote is not a coin type but quote coin option is some (the
/// second condition should be impossible, since a coin resource
/// cannot be generated from a non-coin coin type)
/// * If `generic_asset_transfer_custodian_capability_ref` does not
/// indicate generic asset transfer custodian for given market,
/// per inner function `swap()`
public fun swap_generic<
BaseType,
QuoteType
>(
host: address,
market_id: u64,
direction: bool,
min_base: u64,
max_base: u64,
min_quote: u64,
max_quote: u64,
limit_price: u64,
optional_base_coins_ref_mut:
&mut option::Option<coin::Coin<BaseType>>,
optional_quote_coins_ref_mut:
&mut option::Option<coin::Coin<QuoteType>>,
generic_asset_transfer_custodian_capability_ref: &CustodianCapability
): (
u64,
u64
) acquires OrderBooks {
// Determine if base is coin type
let base_is_coin = coin::is_coin_initialized<BaseType>();
// Determine if quote is coin type
let quote_is_coin = coin::is_coin_initialized<QuoteType>();
// Assert that base and quote assets are not both coins
assert!(!(base_is_coin && quote_is_coin), E_BOTH_COINS);
// Assert that if base is coin then option is some, and that if
// base is not coin then option is none
assert!(base_is_coin == option::is_some(optional_base_coins_ref_mut),
E_INVALID_OPTION_BASE);
// Assert that if quote is coin then option is some, and that if
// quote is not coin then option is none
assert!(quote_is_coin == option::is_some(optional_quote_coins_ref_mut),
E_INVALID_OPTION_QUOTE);
let base_value = if (base_is_coin) // If base is a coin
// Base value is the value of option-wrapped coins
coin::value(option::borrow(optional_base_coins_ref_mut)) else
// Else base value is 0 for a buy and max amount for sell
if (direction == BUY) 0 else max_base;
let quote_value = if (quote_is_coin) // If quote is a coin
// Quote value is the value of option-wrapped coins
coin::value(option::borrow(optional_quote_coins_ref_mut)) else
// Else quote value is max for a buy and 0 for sell
if (direction == BUY) max_quote else 0;
// Range check fill amounts
match_range_check_fills(&direction, &min_base, &max_base, &min_quote,
&max_quote, &base_value, &base_value, "e_value, "e_value);
// Declare tracker variables for amount of base and quote filled
let (base_filled, quote_filled) = (0, 0);
// Get generic asset transfer custodian ID
let generic_asset_transfer_custodian_id = registry::custodian_id(
generic_asset_transfer_custodian_capability_ref);
// Swap against order book
swap<BaseType, QuoteType>(&host, &market_id, &direction, &min_base,
&max_base, &min_quote, &max_quote, &limit_price,
optional_base_coins_ref_mut, optional_quote_coins_ref_mut,
&mut base_filled, &mut quote_filled,
&generic_asset_transfer_custodian_id);
// Return count for base coins and quote coins filled
(base_filled, quote_filled)
}
// Public functions <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Public entry functions >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#[cmd]
/// Cancel all limit orders as a signing user.
///
/// See wrapped function `cancel_all_limit_orders()`.
public entry fun cancel_all_limit_orders_user(
user: &signer,
host: address,
market_id: u64,
side: bool,
) acquires OrderBooks {
cancel_all_limit_orders(
address_of(user),
host,
market_id,
NO_CUSTODIAN,
side,
);
}
#[cmd]
/// Cancel a limit order as a signing user.
///
/// See wrapped function `cancel_limit_order()`.
public entry fun cancel_limit_order_user(
user: &signer,
host: address,
market_id: u64,
side: bool,
order_id: u128
) acquires OrderBooks {
cancel_limit_order(
address_of(user),
host,
market_id,
NO_CUSTODIAN,
side,
order_id
);
}
#[cmd]
/// Place a limit order as a signing user.
///
/// See wrapped function `place_limit_order()`.
public entry fun place_limit_order_user<
BaseType,
QuoteType
>(
user: &signer,
host: address,
market_id: u64,
side: bool,
size: u64,
price: u64,
post_or_abort: bool,
fill_or_abort: bool,
immediate_or_cancel: bool
) acquires OrderBooks {
place_limit_order<
BaseType,
QuoteType
>(
&address_of(user),
&host,
&market_id,
&NO_CUSTODIAN,
&side,
&size,
&price,
&post_or_abort,
&fill_or_abort,
&immediate_or_cancel
);
}
#[cmd]
/// Place a market order from a market account, as a signing user.
///
/// See wrapped function `place_market_order_order()`.
public entry fun place_market_order_user<
BaseType,
QuoteType
>(
user: &signer,
host: address,
market_id: u64,
direction: bool,
min_base: u64,
max_base: u64,
min_quote: u64,
max_quote: u64,
limit_price: u64,
) acquires OrderBooks {
place_market_order<
BaseType,
QuoteType
>(
&address_of(user),
&host,
&market_id,
&NO_CUSTODIAN,
&direction,
&min_base,
&max_base,
&min_quote,
&max_quote,
&limit_price
);
}
#[cmd]
/// Register a market having at least one asset that is not a coin
/// type, which requires the authority of custodian indicated by
/// `generic_asset_transfer_custodian_id_ref` to verify deposits
/// and withdrawals of non-coin assets.
///
/// See wrapped function `register_market()`.
public entry fun register_market_generic<
BaseType,
QuoteType
>(
host: &signer,
lot_size: u64,
tick_size: u64,
generic_asset_transfer_custodian_id_ref: &CustodianCapability
) acquires OrderBooks {
register_market<BaseType, QuoteType>(
host,
lot_size,
tick_size,
registry::custodian_id(generic_asset_transfer_custodian_id_ref)
);
}
#[cmd]
/// Register a market for both base and quote assets as coin types.
///
/// See wrapped function `register_market()`.
public entry fun register_market_pure_coin<
BaseCoinType,
QuoteCoinType
>(
host: &signer,
lot_size: u64,
tick_size: u64,
) acquires OrderBooks {
register_market<BaseCoinType, QuoteCoinType>(
host,
lot_size,
tick_size,
PURE_COIN_PAIR
);
}
#[cmd]
/// Swap between a `user`'s `aptos_framework::coin::CoinStore`s.
///
/// Initialize a `CoinStore` is a user does not already have one.
public entry fun swap_between_coinstores<
BaseCoinType,
QuoteCoinType
>(
user: &signer,
host: address,
market_id: u64,
direction: bool,
min_base: u64,
max_base: u64,
min_quote: u64,
max_quote: u64,
limit_price: u64
) acquires OrderBooks {
let user_address = address_of(user); // Get user address
// Register base coin store if user does not have one
if (!coin::is_account_registered<BaseCoinType>(user_address))
coin::register<BaseCoinType>(user);
// Register quote coin store if user does not have one
if (!coin::is_account_registered<QuoteCoinType>(user_address))
coin::register<QuoteCoinType>(user);
// Get value of base coins on hand
let base_value = coin::balance<BaseCoinType>(user_address);
// Get value of quote coins on hand
let quote_value = coin::balance<QuoteCoinType>(user_address);
// Range check fill amounts
match_range_check_fills(&direction, &min_base, &max_base, &min_quote,
&max_quote, &base_value, &base_value, "e_value, "e_value);
// Get option-wrapped base and quote coins for matching engine
let (optional_base_coins, optional_quote_coins) =
if (direction == BUY) ( // If buying base with quote
// Start with 0 base coins
option::some(coin::zero<BaseCoinType>()),
// Start with max quote coins needed for trade
option::some(coin::withdraw<QuoteCoinType>(user, max_quote))
) else ( // If selling base for quote
// Start with max base coins needed for trade
option::some(coin::withdraw<BaseCoinType>(user, max_base)),
// Start with 0 quote coins
option::some(coin::zero<QuoteCoinType>())
);
// Declare tracker variables for amount of base and quote
// filled, needed for function call but dropped later
let (base_filled_drop, quote_filled_drop) = (0, 0);
// Swap against order book
swap<BaseCoinType, QuoteCoinType>(&host, &market_id, &direction,
&min_base, &max_base, &min_quote, &max_quote, &limit_price,
&mut optional_base_coins, &mut optional_quote_coins,
&mut base_filled_drop, &mut quote_filled_drop, &PURE_COIN_PAIR);
coin::deposit( // Deposit base coins back to user's coin store
user_address, option::destroy_some(optional_base_coins));
coin::deposit( // Deposit quote coins back to user's coin store
user_address, option::destroy_some(optional_quote_coins));
}
// Public entry functions <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Private functions >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/// Cancel all of a user's limit orders on the book, and remove from
/// their market account, silently returning if they have no open
/// orders.
///
/// See wrapped function `cancel_limit_order()`.
///
/// # Parameters
/// * `user`: Address of user cancelling order
/// * `host`: Where corresponding `OrderBook` is hosted
/// * `market_id`: Market ID
/// * `general_custodian_id`: General custodian ID for `user`'s
/// market account
/// * `side`: `ASK` or `BID`
///
/// # Assumes
/// * That `get_n_orders_internal()` aborts if no corresponding user
/// orders tree available to cancel from
fun cancel_all_limit_orders(
user: address,
host: address,
market_id: u64,
general_custodian_id: u64,
side: bool,
) acquires OrderBooks {
let market_account_id = user::get_market_account_id(market_id,
general_custodian_id); // Get user's market account ID
let n_orders = // Get number of orders on given side
user::get_n_orders_internal(user, market_account_id, side);
while (n_orders > 0) { // While user has open orders
// Get order ID of order nearest the spread
let order_id_nearest_spread =
user::get_order_id_nearest_spread_internal(
user, market_account_id, side);
// Cancel the order
cancel_limit_order(user, host, market_id, general_custodian_id,
side, order_id_nearest_spread);
n_orders = n_orders - 1; // Decrement order count
}
}
/// Cancel limit order on book, remove from user's market account.
///
/// # Parameters
/// * `user`: Address of user cancelling order
/// * `host`: Where corresponding `OrderBook` is hosted
/// * `market_id`: Market ID
/// * `general_custodian_id`: General custodian ID for `user`'s
/// market account
/// * `side`: `ASK` or `BID`
///
/// # Abort conditions
/// * If the specified `order_id` is not on given `side` for
/// corresponding `OrderBook`
/// * If `user` is not the user who placed the order with the
/// corresponding `order_id`
/// * If `custodian_id` is not the same as that indicated on order
/// with the corresponding `order_id`
fun cancel_limit_order(
user: address,
host: address,
market_id: u64,
general_custodian_id: u64,
side: bool,
order_id: u128
) acquires OrderBooks {
// Verify order book exists
verify_order_book_exists(host, market_id);
// Borrow mutable reference to order books map
let order_books_map_ref_mut =
&mut borrow_global_mut<OrderBooks>(host).map;
// Borrow mutable reference to order book
let order_book_ref_mut =
open_table::borrow_mut(order_books_map_ref_mut, market_id);
// Get mutable reference to orders tree for corresponding side
let tree_ref_mut = if (side == ASK) &mut order_book_ref_mut.asks else
&mut order_book_ref_mut.bids;
// Assert order is on book
assert!(critbit::has_key(tree_ref_mut, order_id), E_NO_ORDER);
let Order{ // Pop and unpack order from book,
size: _, // Drop size count
user: order_user, // Save indicated user for checking later
// Save indicated general custodian ID for checking later
general_custodian_id: order_general_custodian_id
} = critbit::pop(tree_ref_mut, order_id);
// Assert user attempting to cancel is user on order
assert!(user == order_user, E_INVALID_USER);
// Assert custodian attempting to cancel is custodian on order
assert!(general_custodian_id == order_general_custodian_id,
E_INVALID_CUSTODIAN);
// If cancelling an ask that was previously the spread maker
if (side == ASK && order_id == order_book_ref_mut.min_ask) {
// Update minimum ask to default value if tree is empty
order_book_ref_mut.min_ask = if (critbit::is_empty(tree_ref_mut))
// Else to the minimum ask on the book
MIN_ASK_DEFAULT else critbit::min_key(tree_ref_mut);
// Else if cancelling a bid that was previously the spread maker
} else if (side == BID && order_id == order_book_ref_mut.max_bid) {
// Update maximum bid to default value if tree is empty
order_book_ref_mut.max_bid = if (critbit::is_empty(tree_ref_mut))
// Else to the maximum bid on the book
MAX_BID_DEFAULT else critbit::max_key(tree_ref_mut);
};
// Get market account ID, lot size, and tick size for order
let (market_account_id, lot_size, tick_size) = (
user::get_market_account_id(market_id, general_custodian_id),
order_book_ref_mut.lot_size,
order_book_ref_mut.tick_size);
// Remove order from corresponding user's market account
user::remove_order_internal(user, market_account_id, lot_size,
tick_size, side, order_id);
}
/// Increment counter for number of orders placed on `OrderBook`,
/// returning the original value.
fun get_counter(
order_book_ref_mut: &mut OrderBook
): u64 {
// Borrow mutable reference to order book serial counter
let counter_ref_mut = &mut order_book_ref_mut.counter;
let count = *counter_ref_mut; // Get count
*counter_ref_mut = count + 1; // Set new count
count // Return original count
}
/// Match an incoming order against the order book.
///
/// Range check arguments, initialize local variables, verify that
/// loopwise matching can proceed, then match against the orders
/// tree in a loopwise traversal. Verify fill amounts afterwards.
///
/// Silently returns if no fills possible.
///
/// Institutes pass-by-reference for enhanced efficiency.
///
/// # Type parameters
/// * `BaseType`: Base type for market
/// * `QuoteType`: Quote type for market
///
/// # Parameters
/// * `market_id_ref`: Immutable reference to market ID
/// * `order_book_ref_mut`: Mutable reference to corresponding
/// `OrderBook`
/// * `lot_size_ref`: Immutable reference to lot size for market
/// * `tick_size_ref`: Immutable reference to tick size for market
/// * `direction_ref`: `&BUY` or `&SELL`
/// * `min_lots_ref`: Immutable reference to minimum number of lots
/// to fill
/// * `max_lots_ref`: Immutable reference to maximum number of lots
/// to fill
/// * `min_ticks_ref`: Immutable reference to minimum number of
/// ticks to fill
/// * `max_ticks_ref`: Immutable reference to maximum number of
/// ticks to fill
/// * `limit_price_ref`: Immutable reference to maximum price to
/// match against if `direction_ref` is `&BUY`, and minimum price
/// to match against if `direction_ref` is `&SELL`
/// * `optional_base_coins_ref_mut`: Mutable reference to optional
/// base coins passing through the matching engine, gradually
/// incremented in the case of `BUY`, and gradually decremented
/// in the case of `SELL`
/// * `optional_quote_coins_ref_mut`: Mutable reference to optional
/// quote coins passing through the matching engine, gradually
/// decremented in the case of `BUY`, and gradually incremented
/// in the case of `SELL`
/// * `lots_filled_ref_mut`: Mutable reference to counter for number
/// of lots filled by matching engine
/// * `ticks_filled_ref_mut`: Mutable reference to counter for
/// number of ticks filled by matching engine
///
/// # Assumes
/// * That if optional coins are passed, they contain sufficient
/// amounts for matching in accordance with other specified values
/// * That `lot_size_ref` and `tick_size_ref` indicate the same
/// lot and tick size as `order_book_ref_mut`
/// * That min/max fill amounts have been checked via
/// `match_range_check_fills()`
///
/// # Checks not performed
/// * Does not enforce that limit price is nonzero, as a limit price
/// of zero is effectively a flag to sell at any price.
/// * Does not enforce that max fill amounts are nonzero, as the
/// matching engine simply returns silently before overfilling
fun match<
BaseType,
QuoteType
>(
market_id_ref: &u64,
order_book_ref_mut: &mut OrderBook,
lot_size_ref: &u64,
tick_size_ref: &u64,
direction_ref: &bool,
min_lots_ref: &u64,
max_lots_ref: &u64,
min_ticks_ref: &u64,
max_ticks_ref: &u64,
limit_price_ref: &u64,
optional_base_coins_ref_mut:
&mut option::Option<coin::Coin<BaseType>>,
optional_quote_coins_ref_mut:
&mut option::Option<coin::Coin<QuoteType>>,
lots_filled_ref_mut: &mut u64,
ticks_filled_ref_mut: &mut u64
) {
// Initialize variables, check types
let (lots_until_max, ticks_until_max, side, tree_ref_mut,
spread_maker_ref_mut, n_orders, traversal_direction) =
match_init<BaseType, QuoteType>(order_book_ref_mut,
direction_ref, max_lots_ref, max_ticks_ref);
if (n_orders != 0) { // If orders tree has orders to match
// Match them via loopwise iterated traversal
match_loop<BaseType, QuoteType>(market_id_ref, tree_ref_mut,
&side, lot_size_ref, tick_size_ref, &mut lots_until_max,
&mut ticks_until_max, limit_price_ref, &mut n_orders,
spread_maker_ref_mut, &traversal_direction,
optional_base_coins_ref_mut, optional_quote_coins_ref_mut);
};
// Verify fill amounts, compute final threshold allowance counts
match_verify_fills(min_lots_ref, max_lots_ref, min_ticks_ref,
max_ticks_ref, &lots_until_max, &ticks_until_max,
lots_filled_ref_mut, ticks_filled_ref_mut);
}
/// Match against the book from a user's market account.
///
/// Verify user has sufficient assets in their market account,
/// withdraw enough to meet range-checked min/max fill requirements,
/// match against the book, then deposit back to user's market
/// account.
///
/// Institutes pass-by-reference for enhanced efficiency.
///
/// # Type parameters
/// * `BaseType`: Base type for market
/// * `QuoteType`: Quote type for market
///
/// # Parameters
/// * `user_ref`: Immutable reference to user's address
/// * `market_account_id_ref`: Immutable reference to user's
/// corresponding market account ID
/// * `market_id_ref`: Immutable reference to market ID
/// * `order_book_ref_mut`: Mutable reference to corresponding
/// `OrderBook`
/// * `direction_ref`: `&BUY` or `&SELL`
/// * `min_base_ref`: Immutable reference to minimum number of base
/// units to fill
/// * `max_base_ref`: Immutable reference to maximum number of base
/// units to fill
/// * `min_quote_ref`: Immutable reference to minimum number of
/// quote units to fill
/// * `max_quote_ref`: Immutable reference to maximum number of
/// quote units to fill
/// * `limit_price_ref`: Immutable reference to maximum price to
/// match against if `direction_ref` is `&BUY`, and minimum price
/// to match against if `direction_ref` is `&SELL`. If passed as
/// `HI_64` in the case of a `BUY` or `0` in the case of a `SELL`,
/// will match at any price. Price for a given market is the
/// number of ticks per lot.
/// * `lots_filled_ref_mut`: Mutable reference to number of lots
/// matched against book
fun match_from_market_account<
BaseType,
QuoteType
>(
user_ref: &address,
market_account_id_ref: &u128,
market_id_ref: &u64,
order_book_ref_mut: &mut OrderBook,
direction_ref: &bool,
min_base_ref: &u64,
max_base_ref: &u64,
min_quote_ref: &u64,
max_quote_ref: &u64,
limit_price_ref: &u64,