forked from iclighthouse/ICDex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathICDexPair.mo
More file actions
5554 lines (5505 loc) · 268 KB
/
Copy pathICDexPair.mo
File metadata and controls
5554 lines (5505 loc) · 268 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
/**
* Module : ICDex
* Author : ICLighthouse Team
* Stability : Experimental
* Github : https://github.com/iclighthouse/
*/
import Array "mo:base/Array";
import Binary "mo:icl/Binary";
import Blob "mo:base/Blob";
import Cycles "mo:base/ExperimentalCycles";
// import DIP20 "mo:icl/DIP20";
import DRC20 "mo:icl/DRC20";
import DRC205 "mo:icl/DRC205";
import DRC207 "mo:icl/DRC207";
import Deque "mo:base/Deque";
import Error "mo:base/Error";
import Float "mo:base/Float";
import Hash "mo:base/Hash";
import Hex "mo:icl/Hex";
import ICRC1 "mo:icl/ICRC1";
import ICRC2 "mo:icl/ICRC1";
import Int "mo:base/Int";
import Int64 "mo:base/Int64";
// import Ledger "mo:icl/Ledger";
import List "mo:base/List";
import Nat "mo:base/Nat";
import Nat32 "mo:base/Nat32";
import Nat64 "mo:base/Nat64";
import Option "mo:base/Option";
import OrderBook "mo:icl/OrderBook";
import Principal "mo:base/Principal";
import Result "mo:base/Result";
import SagaTM "./ICTC/SagaTM";
import Text "mo:base/Text";
import Time "mo:base/Time";
import Tools "mo:icl/Tools";
import Trie "mo:base/Trie";
// import Trie "./lib/Elastic-Trie";
import Types "mo:icl/ICDexTypes";
// import ICRouter "lib/ICRouter";
import Iter "mo:base/Iter";
import Backup "./lib/ICDexBackupTypes";
import Timer "mo:base/Timer";
import STO "./lib/StrategyOrder";
//record { token0=principal "kzxhi-syaaa-aaaak-aan4a-cai"; token1=principal "ryjl3-tyaaa-aaaaa-aaaba-cai"; owner=opt principal ""; name="TTT/ICP"; unitSize=10000000:nat64;}
shared(installMsg) actor class ICDexPair(initArgs: Types.InitArgs) = this {
// Types
type AccountId = Types.AccountId;
type Address = Types.Address;
type Txid = Types.Txid;
type TxAccount = Text;
type Sa = Types.Sa;
type Nonce = Types.Nonce;
type Data = Types.Data;
type Toid = Nat;
type Ttid = Nat;
type Amount = Types.Amount;
type Timestamp = Types.Timestamp;
type PeriodNs = Types.PeriodNs;
type IcpE8s = Types.IcpE8s;
type AccountSetting = Types.AccountSetting;
type KeepingBalance = Types.KeepingBalance;
type BalanceChange = Types.BalanceChange;
type TokenInfo = Types.TokenInfo;
type DebitToken = Types.DebitToken;
type OrderSide = Types.OrderSide;
type OrderType = Types.OrderType;
type OrderPrice = Types.OrderPrice;
type PriceResponse = OrderBook.PriceResponse;
type KBar = OrderBook.KBar;
type KLines = OrderBook.KLines;
type TradingStatus = Types.TradingStatus;
type OrderFilled = Types.OrderFilled;
type TradingOrder = Types.TradingOrder;
//type TradingOrderResponse = Types.TradingOrderResponse;
type PriceWeighted = Types.PriceWeighted;
type Vol = Types.Vol;
type OrderStatusResponse = Types.OrderStatusResponse;
type TradingResult = Types.TradingResult;
type DexSetting = Types.DexSetting;
type DexConfig = Types.DexConfig;
type TrieList<K, V> = Types.TrieList<K, V>;
type ListPage = Types.ListPage;
type ListSize = Types.ListSize;
type SysMode = {#GeneralTrading; #ClosingOnly; #DisabledTrading; #ReadOnly};
type ETHAddress = Text;
// Variables
private var icdex_debug : Bool = true; /*config*/
private let version_: Text = "0.11.1";
private let ns_: Nat = 1000000000;
private stable var ExpirationDuration : Int = 3 * 30 * 24 * 3600 * ns_;
private stable var name_: Text = initArgs.name;
// if (name_ == "icdexSNS1/ICP"){ name_ := "icdex:SNS1/ICP" }; // to fix
private stable var pause: Bool = false;
private stable var mode: SysMode = #GeneralTrading;
private stable var pairOpeningTime: Time.Time = 0;
private stable var owner: Principal = Option.get(initArgs.owner, installMsg.caller);
private stable var icdex_: Principal = installMsg.caller; // icdex_router (to be upgraded)
// private stable var icrouter_: Principal = Principal.fromText("j4d4d-pqaaa-aaaak-aanxq-cai"); // dex_rooter (to be upgraded)
if (icdex_debug){
icdex_ := Principal.fromText("pymhy-xyaaa-aaaak-act7a-cai");
// icrouter_ := Principal.fromText("pwokq-miaaa-aaaak-act6a-cai");
};
private stable var token0_: Principal = initArgs.token0;
private stable var token0Symbol: Text = "";
private stable var token0Std: Types.TokenStd = #drc20;
private stable var token0Gas: ?Nat = null;
private stable var token1_: Principal = initArgs.token1;
private stable var token1Symbol: Text = "";
private stable var token1Std: Types.TokenStd = #icrc1;
private stable var token1Gas: ?Nat = null;
private stable var setting: DexSetting = {
UNIT_SIZE = Nat64.toNat(initArgs.unitSize); // e.g. 1000000 token smallest units
ICP_FEE = 10000; // 10000 E8s
TRADING_FEE = 5000; // value 5000 means 0.5%
MAKER_BONUS_RATE = 0; // value 25 means 25% BONUS = MAKER_BONUS_RATE * fee
MAX_TPS = 10;
MAX_PENDINGS = 20;
STORAGE_INTERVAL = 10; // seconds
ICTC_RUN_INTERVAL = 10; // seconds
};
private stable var icdex_index: Nat = 0;
private stable var icdex_totalFee: Types.FeeBalance = { value0=0; value1=0;};
private stable var icdex_totalVol: Vol = { value0 = 0; value1 = 0;};
private stable var icdex_orders : Trie.Trie<Txid, TradingOrder> = Trie.empty();
private stable var icdex_failedOrders: Trie.Trie<Txid, TradingOrder> = Trie.empty();
private stable var icdex_orderBook: OrderBook.OrderBook = OrderBook.create();
//private stable var icdex_stopBook: StopBook = {sell = List.nil<StopOrder>(); buy = List.nil<StopOrder>();};
//private stable var icdex_klines: OrderBookOld.KLines = OrderBookOld.createK();
private stable var icdex_klines2: OrderBook.KLines = OrderBook.createK();
private stable var icdex_lastPrice: OrderBook.OrderPrice = { quantity = #Sell(0); price = 0 };
private stable var icdex_latestfilled = Deque.empty<(Timestamp, Txid, OrderFilled, OrderSide)>();
private stable var icdex_priceWeighted: PriceWeighted = { token0TimeWeighted = 0; token1TimeWeighted = 0; updateTime = 0; };
private stable var icdex_vols: Trie.Trie<AccountId, Vol> = Trie.empty();
private stable var icdex_nonces: Trie.Trie<AccountId, Nonce> = Trie.empty();
//private stable var icdex_countPendingOrders: Trie.Trie<AccountId, Nat> = Trie.empty();
private stable var icdex_pendingOrders: Trie.Trie<AccountId, [Txid]> = Trie.empty();
private stable var icdex_makers: Trie.Trie<AccountId, (rate: Nat, managedBy: Principal)> = Trie.empty(); // Nat / 100
private stable var icdex_dip20Balances: Trie.Trie<AccountId, (Principal, Nat)> = Trie.empty(); // will be discarded
private stable var icdex_lastSessions = Deque.empty<(Principal, Nat)>(); // will be discarded
private stable var icdex_lastVisits = Deque.empty<(AccountId, Nat)>();
private stable var icdex_RPCAccounts: Trie.Trie<ETHAddress, [ICRC1.Account]> = Trie.empty(); // ethaddress -> [account] // *pre-occupancy
private stable var icdex_accountSettings: Trie.Trie<AccountId, AccountSetting> = Trie.empty(); // ***
private stable var icdex_keepingBalances: Trie.Trie<AccountId, KeepingBalance> = Trie.empty(); // ***
private stable var icdex_poolBalance: {token0: Amount; token1: Amount } = {token0 = 0; token1 = 0 }; // ***
private stable var icdex_soid: STO.Soid = 1; // ***
private stable var icdex_stOrderRecords: STO.STOrderRecords = Trie.empty(); // Trie.Trie<Soid, STOrder> // ***
private stable var icdex_userProOrderList: STO.UserProOrderList = Trie.empty(); // Trie.Trie<AccountId, List.List<Soid>> // ***
private stable var icdex_activeProOrderList: STO.ActiveProOrderList = List.nil<STO.Soid>(); // ***
private stable var icdex_userStopLossOrderList: STO.UserStopLossOrderList = Trie.empty(); // Stop Loss Orders: Trie.Trie<AccountId, List.List<Soid>>; // ***
private stable var icdex_activeStopLossOrderList: STO.ActiveStopLossOrderList = { // Stop Loss Orders: (Txid, Soid, trigger: Price) // ***
buy = List.nil<(STO.Soid, STO.Price)>();
sell = List.nil<(STO.Soid, STO.Price)>();
};
private stable var icdex_stOrderTxids: STO.STOrderTxids = Trie.empty(); // Trie.Trie<Txid, Soid> // ***
private stable var clearingTxids = List.nil<(Txid)>();
private stable var lastExpiredTime : Time.Time = 0;
private stable var timeSortedTxids = Deque.empty<(Txid, Time.Time)>(); // Front (latest) --- Back (expired)
private stable var countRejections: Nat = 0;
private stable var lastExecutionDuration: Int = 0;
private stable var maxExecutionDuration: Int = 0;
private stable var lastSagaRunningTime : Time.Time = 0;
private stable var lastStorageTime : Time.Time = 0;
private var countAsyncMessage : Nat = 0;
private let maxTotalPendingNumber : Nat = 50000;
private var drc205 = DRC205.DRC205({EN_DEBUG = icdex_debug; MAX_CACHE_TIME = 6 * 30 * 24 * 3600 * ns_; MAX_CACHE_NUMBER_PER = 1000; MAX_STORAGE_TRIES = 2; });
private stable var stats_brokers: Trie.Trie<AccountId, {vol: Vol; commission: Vol; count: Nat; rate: Float}> = Trie.empty();
private stable var stats_makers: Trie.Trie<AccountId, {vol: Vol; commission: Vol; orders: Nat; filledCount: Nat;}> = Trie.empty();
private let sa_zero : [Nat8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; // pool
private let sa_one : [Nat8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]; // temp
/* ===========================
Local function section
============================== */
/**
* System pressure control functions
*/
private func _checkICTCError() : (){
let count = _getSaga().getBlockingOrders().size();
if (count >= (if (icdex_debug){ 10 }else{ 5 })){
pause := true;
mode := #DisabledTrading;
pairOpeningTime := 0;
};
};
private func _ictcAllDone(): Bool{
let tos = _getSaga().getAliveOrders();
var res: Bool = true;
for ((toid, order) in tos.vals()){
switch(order){
case(?(order_)){
if (order_.status != #Done and order_.status != #Recovered){
res := false;
};
};
case(_){};
};
};
return res;
};
private func _ictcDone(_toids: [SagaTM.Toid]) : Bool{
var completed: Bool = true;
for (toid in _toids.vals()){
let status = _getSaga().status(toid);
if (status != ?#Done and status != ?#Recovered){
completed := false;
};
};
return completed;
};
private func _accountIctcDone(_a: AccountId): Bool{
for ((t, o) in Trie.iter(_accountPendingOrders(?_a))){
if (not(_ictcDone(o.toids))){
return false;
};
};
return true;
};
private func _visitLog(_a: AccountId): (){
icdex_lastVisits := Deque.pushFront(icdex_lastVisits, (_a, _now()));
var enLoop: Bool = true;
while(enLoop){
switch(Deque.popBack(icdex_lastVisits)){
case(?(deque, (_account, _ts))){
if (_now() > _ts + 3600 or List.size(icdex_lastVisits.0) + List.size(icdex_lastVisits.1) > 5999){
icdex_lastVisits := deque;
}else{
enLoop := false;
};
};
case(_){ enLoop := false; };
};
};
};
private func _tps(_duration: Nat, _a: ?AccountId) : (total: Nat, tpsX10: Nat){
if (icdex_debug) { return (0, 0); }; /*config*/
var count: Nat = 0;
var ts = _now();
var temp_deque = icdex_lastVisits;
while(ts > 0 and _now() < ts + _duration){
switch(Deque.popFront(temp_deque)){
case(?((_account, _ts), deque)){
temp_deque := deque;
ts := _ts;
switch(_a){
case(?(account)){
if(_now() < _ts + _duration and account == _account){ count += 1; };
};
case(_){
if(_now() < _ts + _duration){ count += 1; };
};
};
};
case(_){ ts := 0; return (0,0); };
};
};
return (count, count * 10 / _duration);
};
private func _checkTPSLimit() : Bool{
return _tps(5, null).1 < setting.MAX_TPS*10 and _tps(15, null).1 < setting.MAX_TPS*8;
};
private func _asyncMessageSize() : Nat{
return countAsyncMessage + _getSaga().asyncMessageSize();
};
private func _checkAsyncMessageLimit() : Bool{
return _asyncMessageSize() < 390; /*config*/
};
private func _checkOverload(_caller: ?AccountId) : async* (){
if (not(_checkAsyncMessageLimit()) or not(_checkTPSLimit())){
countRejections += 1;
throw Error.reject("405: IC network is busy, please try again later.");
};
_visitLog(Option.get(_caller, Tools.principalToAccountBlob(Principal.fromActor(this), null)));
};
private func _maxPendings(_trader: AccountId) : Nat{
var proOrderCount : Nat = 0;
switch(Trie.get(icdex_userProOrderList, keyb(_trader), Blob.equal)){
case(?(userOrderList)){ proOrderCount := List.size(userOrderList); };
case(_){};
};
switch(Trie.get(icdex_makers, keyb(_trader), Blob.equal)){
case(?(v, p)){ return setting.MAX_PENDINGS * 10 + proOrderCount * 10; };
case(_){ return setting.MAX_PENDINGS + proOrderCount * 5; };
};
};
/**
* Common Local Functions
*/
private func _now() : Timestamp{
return Int.abs(Time.now() / ns_);
};
private func _token0Canister() : Principal{ token0_ };
private func _token1Canister() : Principal{ token1_ };
// private let ledger: Ledger.Self = actor("ryjl3-tyaaa-aaaaa-aaaba-cai");
private func keyb(t: Blob) : Trie.Key<Blob> { return { key = t; hash = Blob.hash(t) }; };
private func keyn(t: Nat) : Trie.Key<Nat> { return { key = t; hash = Tools.natHash(t) }; };
private func keyt(t: Text) : Trie.Key<Text> { return { key = t; hash = Text.hash(t) }; };
private func trieItems<K, V>(_trie: Trie.Trie<K,V>, _page: ListPage, _size: ListSize) : TrieList<K, V> {
let length = Trie.size(_trie);
if (_page < 1 or _size < 1){
return {data = []; totalPage = 0; total = length; };
};
let offset = Nat.sub(_page, 1) * _size;
var totalPage: Nat = length / _size;
if (totalPage * _size < length) { totalPage += 1; };
if (offset >= length){
return {data = []; totalPage = totalPage; total = length; };
};
let end: Nat = offset + Nat.sub(_size, 1);
var i: Nat = 0;
var res: [(K, V)] = [];
for ((k,v) in Trie.iter<K, V>(_trie)){
if (i >= offset and i <= end){
res := Tools.arrayAppend(res, [(k,v)]);
};
i += 1;
};
return {data = res; totalPage = totalPage; total = length; };
};
private func _getAccountId(_address: Address): AccountId{
switch (Tools.accountHexToAccountBlob(_address)){
case(?(a)){
return a;
};
case(_){
var p = Principal.fromText(_address);
var a = Tools.principalToAccountBlob(p, null);
return a;
// switch(Tools.accountDecode(Principal.toBlob(p))){
// case(#ICRC1Account(account)){
// switch(account.subaccount){
// case(?(sa)){ return Tools.principalToAccountBlob(account.owner, ?Blob.toArray(sa)); };
// case(_){ return Tools.principalToAccountBlob(account.owner, null); };
// };
// };
// case(#AccountId(account)){ return account; };
// case(#Other(account)){ return account; };
// };
};
};
};
private func _toSaBlob(_sa: ?[Nat8]) : ?Blob{
switch(_sa){
case(?(sa)){
if (sa.size() == 0 or sa == sa_zero){
return null;
}else{
return ?Blob.fromArray(sa);
};
};
case(_){ return null; };
}
};
private func _toSaNat8(_sa: ?Blob) : ?[Nat8]{
switch(_sa){
case(?(sa)){
if (sa.size() == 0 or sa == Blob.fromArray(sa_zero)){
return null;
}else{
return ?Blob.toArray(sa);
};
};
case(_){ return null; };
}
};
private func _toOptSub(_sub: Blob) : ?Blob{
if (_sub.size() == 0 or _sub == Blob.fromArray(sa_zero)){
return null;
}else{
return ?_sub;
};
};
private func _getGas(_update: Bool) : async* (){
if (_update or Option.isNull(token0Gas)){
if (token0Std == #drc20){
let token: DRC20.Self = actor(Principal.toText(_token0Canister()));
token0Gas := ?(await token.drc20_fee());
} /*else if (token0Std == #dip20){
let token: DIP20.Self = actor(Principal.toText(_token0Canister()));
token0Gas := ?(await token.getTokenFee());
}*/ else { // if (token0Std == #icrc1 or token0Std == #icp)
let token: ICRC1.Self = actor(Principal.toText(_token0Canister()));
token0Gas := ?(await token.icrc1_fee());
} /*else if (token0Std == #ledger){
let token: Ledger.Self = actor(Principal.toText(_token0Canister()));
token0Gas := ?Nat64.toNat((await token.transfer_fee({})).transfer_fee.e8s);
}*/;
};
if (_update or Option.isNull(token1Gas)){
if (token1Std == #drc20){
let token: DRC20.Self = actor(Principal.toText(_token1Canister()));
token1Gas := ?(await token.drc20_fee());
} /*else if (token1Std == #dip20){
let token: DIP20.Self = actor(Principal.toText(_token1Canister()));
token1Gas := ?(await token.getTokenFee());
}*/ else { // if (token1Std == #icrc1 or token1Std == #icp)
let token: ICRC1.Self = actor(Principal.toText(_token1Canister()));
token1Gas := ?(await token.icrc1_fee());
} /*else if (token1Std == #ledger){
let token: Ledger.Self = actor(Principal.toText(_token1Canister()));
token1Gas := ?Nat64.toNat((await token.transfer_fee({})).transfer_fee.e8s);
}*/;
};
};
private func _getFee0() : Nat{
switch(token0Gas){
case(?(gas)){ return gas; };
case(_){ assert(false); return 0; };
};
};
private func _getFee1() : Nat{
switch(token1Gas){
case(?(gas)){ return gas; };
case(_){ assert(false); return 0; };
};
};
private func _natToFloat(_n: Nat) : Float{
let n: Int = _n;
return Float.fromInt(n);
};
private func _floatToNat(_f: Float) : Nat{
let i = Float.toInt(_f);
assert(i >= 0);
return Int.abs(i);
};
private func _onlyOwner(_caller: Principal) : Bool { //ict
return _caller == owner or Principal.isController(_caller);
};
// private func _onlyToken(_caller: Principal) : Bool { //ict
// return _caller == token0_ or _caller == token1_;
// };
private func _notPaused(_caller: ?Principal) : Bool {
let caller = Option.get(_caller, Principal.fromActor(this));
if (pairOpeningTime > 0 and Time.now() >= pairOpeningTime){
pause := false;
mode := #GeneralTrading;
pairOpeningTime := 0;
};
return not(pause) and (Time.now() >= pairOpeningTime or (_inIDO() and _onlyIDOFunder(caller)));
};
private func _onlyOrderOwner(_account: AccountId, _txid: Txid) : Bool{
// switch(Trie.get(icdex_orders, keyb(_txid), Blob.equal)){
// case(?(order)){ return order.account == _account; };
// case(_){ return false; };
// };
let nonceBytes = Tools.slice(Blob.toArray(_txid), 0, ?3);
let nonce = Nat32.toNat(Binary.BigEndian.toNat32(nonceBytes));
let max: Nat = 2 ** 32;
var i: Nat = 0;
while (i < 64){
if (_txid == drc205.generateTxid(Principal.fromActor(this), _account, i * max + nonce)){
return true;
};
i += 1;
};
return false
};
private func _onlyVipMaker(_trader: AccountId) : Bool{
switch(Trie.get(icdex_makers, keyb(_trader), Blob.equal)){
case(?(v, p)){ return v > 0; };
case(_){ return false; };
};
};
private func _getNonce(_a: AccountId): Nat{
switch(Trie.get(icdex_nonces, keyb(_a), Blob.equal)){
case(?(v)){ return v; };
case(_){ return 0; };
};
};
private func _addNonce(_a: AccountId): (){
var n = _getNonce(_a);
icdex_nonces := Trie.put(icdex_nonces, keyb(_a), Blob.equal, n+1).0;
icdex_index += 1;
};
private func _accountIdToHex(_a: AccountId) : Text{
return Hex.encode(Blob.toArray(_a));
};
// private func _getSA(_sa: Blob) : Blob{
// var sa = Blob.toArray(_sa);
// while (sa.size() < 32){
// sa := Tools.arrayAppend([0:Nat8], sa);
// };
// return Blob.fromArray(sa);
// };
// private func _getMainAccount() : AccountId{
// let main = Principal.fromActor(this);
// return Blob.fromArray(Tools.principalToAccount(main, null));
// };
private func _getPairAccount(_sub: Blob) : AccountId{
let main = Principal.fromActor(this);
let sa = Blob.toArray(_sub);
return Blob.fromArray(Tools.principalToAccount(main, ?sa));
};
/*private func _getDip20Principal(_a: AccountId) : Principal{
switch(Trie.get(icdex_dip20Balances, keyb(_a), Blob.equal)){
case(?(p, v)){ return p; };
case(_){ assert(false); return Principal.fromText("aaaaa-aa"); };
};
};*/
/*private func _getDip20Balance(_a: AccountId) : Nat{ // token0 / token1
switch(Trie.get(icdex_dip20Balances, keyb(_a), Blob.equal)){
case(?(p, v)){ return v; };
case(_){ return 0; };
};
};*/
private func _getBaseBalance(_sub: Blob) : async* Nat{ // token0
let _a = _getPairAccount(_sub);
var balance : Nat = 0;
try{
countAsyncMessage += 1;
if (token0Std == #drc20){
let token: DRC20.Self = actor(Principal.toText(_token0Canister()));
let res = await token.drc20_balanceOf(_accountIdToHex(_a));
balance := res;
} /*else if (token0Std == #dip20) { // #dip20
balance := _getDip20Balance(_a);
}*/ else { // if (token0Std == #icrc1 or token0Std == #icp)
let token : ICRC1.Self = actor(Principal.toText(_token0Canister()));
let res = await token.icrc1_balance_of({owner = Principal.fromActor(this); subaccount = _toOptSub(_sub)});
balance := res;
}/* else if (token0Std == #icp){ // or token0Std == #ledger
let token: Ledger.Self = actor(Principal.toText(_token0Canister()));
let res = await token.account_balance({ account = _a; });
balance := Nat64.toNat(res.e8s);
}*/;
countAsyncMessage -= Nat.min(1, countAsyncMessage);
return balance;
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("query token0 balance error: "# Error.message(e));
};
};
private func _getQuoteBalance(_sub: Blob) : async* Nat{ // token1
let _a = _getPairAccount(_sub);
var balance : Nat = 0;
try{
countAsyncMessage += 1;
if (token1Std == #drc20){ // drc20
let token: DRC20.Self = actor(Principal.toText(_token1Canister()));
let res = await token.drc20_balanceOf(_accountIdToHex(_a));
balance := res;
} /*else if (token1Std == #dip20) { // #dip20
balance := _getDip20Balance(_a);
} else if (token1Std == #icp){ // or token1Std == #ledger
let token: Ledger.Self = actor(Principal.toText(_token1Canister()));
let res = await token.account_balance({ account = _a; });
balance := Nat64.toNat(res.e8s);
}*/ else { // #icrc1 or #icp
let token : ICRC1.Self = actor(Principal.toText(_token1Canister()));
let res = await token.icrc1_balance_of({owner = Principal.fromActor(this); subaccount = _toOptSub(_sub)});
balance := res;
};
countAsyncMessage -= Nat.min(1, countAsyncMessage);
return balance;
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("query token1 balance error: "# Error.message(e));
};
};
private func _tokenTransfer(_token: Principal, _fromSa: Blob, _toIcrc1Account: ICRC1.Account, _value: Nat, _data: ?Blob) : async* (){
var _fee : Nat = 0;
var _std : Types.TokenStd = #icrc1;
if (_token == _token0Canister()){
_fee := _getFee0();
_std := token0Std;
}else if (_token == _token1Canister()){
_fee := _getFee1();
_std := token1Std;
};
let _toAccount = Tools.principalToAccountBlob(_toIcrc1Account.owner, _toSaNat8(_toIcrc1Account.subaccount));
if (_std == #drc20){
let token: DRC20.Self = actor(Principal.toText(_token));
try{
countAsyncMessage += 1;
let res = await token.drc20_transfer(_accountIdToHex(_toAccount), _value, null, ?Blob.toArray(_fromSa), _data);
switch(res){
case(#ok(txid)){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
};
case(#err(e)){
throw Error.reject("DRC20 token.drc20_transfer() error: "# e.message);
};
};
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("Error transferring token: "# Error.message(e));
};
}else{ // #icrc1
let token: ICRC1.Self = actor(Principal.toText(_token));
try{
countAsyncMessage += 1;
let res = await token.icrc1_transfer({
from_subaccount = ?_fromSa;
to = _toIcrc1Account;
amount = _value;
fee = null;
memo = _data;
created_at_time = null; // nanos
});
switch(res){
case(#Ok(blockNumber)){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
};
case(#Err(e)){
throw Error.reject("ICRC1 token.icrc1_transfer() error.");
};
};
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("Error transferring token: "# Error.message(e));
};
};
};
private func _drc20TransferFrom(_token: Principal, _from: AccountId, _to: AccountId, _value: Nat, _data: ?Blob) : async* Txid{
let token: DRC20.Self = actor(Principal.toText(_token));
try{
countAsyncMessage += 1;
let res = await token.drc20_transferFrom(_accountIdToHex(_from), _accountIdToHex(_to), _value, null, null, _data);
switch(res){
case(#ok(txid)){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
return txid;
};
case(#err(e)){
throw Error.reject("DRC20 token.drc20_transferFrom() error: "# e.message);
};
};
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("Error transferring token: "# Error.message(e));
};
};
/* private func _icrc1TransferFrom() */
/*private func _dip20TransferFrom(_token: Principal, _a: AccountId, _from: Principal, _to: Principal, _value: Nat) : async Nat{
let token: DIP20.Self = actor(Principal.toText(_token));
try{
countAsyncMessage += 1;
let res = await token.transferFrom(_from, _to, _value);
switch(res){
case(#Ok(txid)){
_dip20Increase(_a, _to, _value);
countAsyncMessage -= Nat.min(1, countAsyncMessage);
return txid;
};
case(#Err(e)){
throw Error.reject("DIP20 token.transferFrom() error!");
};
};
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("query dip20 balance error: "# Error.message(e));
};
};*/
/*private func _dip20Increase(_a: AccountId, _p: Principal, _value: Nat) : (){
switch(Trie.get(icdex_dip20Balances, keyb(_a), Blob.equal)){
case(?(p, v)){
icdex_dip20Balances := Trie.put(icdex_dip20Balances, keyb(_a), Blob.equal, (p, v + _value)).0;
};
case(_){
icdex_dip20Balances := Trie.put(icdex_dip20Balances, keyb(_a), Blob.equal, (_p, _value)).0;
};
};
};
private func _dip20Decrease(_a: AccountId, _value: Nat) : (){
switch(Trie.get(icdex_dip20Balances, keyb(_a), Blob.equal)){
case(?(p, v)){
if (Nat.sub(v, _value) == 0){
icdex_dip20Balances := Trie.remove(icdex_dip20Balances, keyb(_a), Blob.equal).0;
} else{
icdex_dip20Balances := Trie.put(icdex_dip20Balances, keyb(_a), Blob.equal, (p, Nat.sub(v, _value))).0;
};
};
case(_){ assert(false); };
};
};*/
/**
* ICTC local functions and local tasks
*/
private var saga: ?SagaTM.SagaTM = null;
/*private func _dip20Send(_from: AccountId, _value: Nat) : (){
_dip20Decrease(_from, _value);
};
private func _dip20SendComp(_a: AccountId, _p: Principal, _value: Nat) : (){
_dip20Increase(_a, _p, _value);
};*/
private func _localBatchTransfer(_args: [(_act: {#add; #sub}, _account: Blob, _token: {#token0; #token1}, _amount: {#locked: Nat; #available: Nat})]) :
([KeepingBalance]){
var res : [KeepingBalance] = [];
for (arg in _args.vals()){
switch(arg.0){
case(#add){
res := Tools.arrayAppend(res, [_addAccountBalance(arg.1, arg.2, arg.3)]);
};
case(#sub){
res := Tools.arrayAppend(res, [_subAccountBalance(arg.1, arg.2, arg.3)]);
};
};
};
return res;
};
// Local task entrance
private func _local(_args: SagaTM.CallType, _receipt: ?SagaTM.Receipt) : async (SagaTM.TaskResult){
switch(_args){
case(#This(method)){
switch(method){
// case(#dip20Send(_a, _value)){
// /*var result = (); // Receipt
// // do
// result := _dip20Send(_a, _value);*/
// // check & return
// return (#Done, ?#This(#dip20Send), null);
// };
// case(#dip20SendComp(_a, _p, _value)){
// /*var result = (); // Receipt
// // do
// result := _dip20SendComp(_a, _p, _value);*/
// // check & return
// return (#Done, ?#This(#dip20SendComp), null);
// };
case(#batchTransfer(_args: [(_act: {#add; #sub}, _account: Blob, _token: {#token0; #token1}, _amount: {#locked: Nat; #available: Nat})])){
let result = _localBatchTransfer(_args);
return (#Done, ?#This(#batchTransfer(result)), null);
};
case(_){return (#Error, null, ?{code=#future(9901); message="Non-local function."; });};
};
};
case(_){ return (#Error, null, ?{code=#future(9901); message="Non-local function."; });};
};
};
// // Task callback
// private func _taskCallback(_toName: Text, _ttid: SagaTM.Ttid, _task: SagaTM.Task, _result: SagaTM.TaskResult) : async (){
// //taskLogs := Tools.arrayAppend(taskLogs, [(_ttid, _task, _result)]);
// };
// // Order callback
// private func _orderCallback(_toName: Text, _toid: SagaTM.Toid, _status: SagaTM.OrderStatus, _data: ?Blob) : async (){
// //orderLogs := Tools.arrayAppend(orderLogs, [(_toid, _status)]);
// };
// Create saga object
private func _getSaga() : SagaTM.SagaTM {
switch(saga){
case(?(_saga)){ return _saga };
case(_){
let _saga = SagaTM.SagaTM(Principal.fromActor(this), ?_local, null, null); //?_taskCallback, ?_orderCallback
saga := ?_saga;
return _saga;
};
};
};
private func _buildTask(_txid: ?Txid, _callee: Principal, _callType: SagaTM.CallType, _preTtid: [SagaTM.Ttid]) : SagaTM.PushTaskRequest{
var cycles = 0;
// if (_callee == _token0Canister()) {
// cycles := token0GasCycles;
// };
return {
callee = _callee;
callType = _callType;
preTtid = _preTtid;
attemptsMax = ?3;
recallInterval = ?200000000; // nanoseconds
cycles = cycles;
data = _txid;
};
};
private func _ictcSagaRun(_toid: Nat, _forced: Bool): async* (){
if (_forced or (_tps(15, null).1 < setting.MAX_TPS*7 and _checkAsyncMessageLimit()) ){
lastSagaRunningTime := Time.now();
let saga = _getSaga();
if (_toid == 0){
try{
countAsyncMessage += 1;
let sagaRes = await* saga.getActuator().run();
countAsyncMessage -= Nat.min(1, countAsyncMessage);
}catch(e){
countAsyncMessage -= Nat.min(1, countAsyncMessage);
throw Error.reject("430: ICTC error: "# Error.message(e));
};
}else{
try{
countAsyncMessage += 2;
let sagaRes = await saga.run(_toid);
countAsyncMessage -= Nat.min(2, countAsyncMessage);
}catch(e){
countAsyncMessage -= Nat.min(2, countAsyncMessage);
throw Error.reject("430: ICTC error: "# Error.message(e));
};
};
};
};
/**
* Core Local Functions for Trading
*/
private stable var initialized: Bool = false;
private stable var fallbacking_txids = List.nil<(Txid, Time.Time)>();
private func _createTx(_a: AccountId) : (ICRC1.Account, Text, Nat, Txid){ // (address, id)
let account = _a;
let nonce = _getNonce(account);
let txid = drc205.generateTxid(Principal.fromActor(this), account, nonce);
let address = Hex.encode(Blob.toArray(_getPairAccount(txid)));
//_addNonce(account);
return ({owner = Principal.fromActor(this); subaccount = _toOptSub(txid) }, address, nonce, txid);
};
private func _orderIcrc1Account(_txid: Txid) : ICRC1.Account{
switch(Trie.get(icdex_orders, keyb(_txid), Blob.equal)){
case(?(order)){
switch(order.icrc1Account){
case(?(account)) {
switch(account.subaccount){
case(?(sub)){
if (Blob.toArray(sub).size() == 0 or Blob.toArray(sub) == sa_zero){
return { owner = account.owner; subaccount = null; };
};
};
case(_){};
};
return account;
};
case(_){
if (icdex_debug) { assert(false);};
return { owner = Principal.fromActor(this); subaccount = ?Blob.fromArray(sa_one); }; // temp account
};
};
};
case(_){ /*config*/
if (icdex_debug) { assert(false);};
return { owner = Principal.fromActor(this); subaccount = null; };
};
};
};
private func _putLatestFilled(_txid: Txid, _filled: [OrderFilled], _side: OrderSide) : (){
let maxNumber : Nat = 50;
for (t in _filled.vals()){
icdex_latestfilled := Deque.pushFront(icdex_latestfilled, (_now(), _txid, t, _side));
};
var length = List.size(icdex_latestfilled.0) + List.size(icdex_latestfilled.1);
while(length > maxNumber){
switch(Deque.popBack(icdex_latestfilled)){
case(?(dq, t)){ icdex_latestfilled := dq; };
case(_){};
};
length -= 1;
};
};
private func _getLatestFilled() : [(Timestamp, Txid, OrderFilled, OrderSide)]{
return List.toArray(List.append(icdex_latestfilled.0, List.reverse(icdex_latestfilled.1)));
};
private func _makerFilled(_txid: Txid, _filled: OrderFilled, _toid: SagaTM.Toid) : (account: AccountId, nonce: Nonce){
var account: Blob = Blob.fromArray([]);
var nonce: Nonce = 0;
//var cpFilled : [OrderFilled] = [];
var token0Value : BalanceChange = #CreditRecord(0); // maker filled
var token1Value : BalanceChange = #CreditRecord(0); // maker filled
switch(Trie.get(icdex_orders, keyb(_filled.counterparty), Blob.equal)){
case(?(order)){
if (order.status == #Pending){
account := order.account;
nonce := order.nonce;
var remainingQuantity = OrderBook.quantity(order.remaining);
var remainingAmount = OrderBook.amount(order.remaining);
var tokenAmount: Nat = 0; // maker vol
var currencyAmount: Nat = 0; // maker vol
//var gas0: Nat = 0;
//var gas1: Nat = 0;
switch(_filled.token0Value){
case(#CreditRecord(value)){ // Maker Sell (_txid Taker Buy)
tokenAmount += value;
remainingQuantity := Nat.max(remainingQuantity, value) - value;
token0Value := #DebitRecord(value);
};
case(#DebitRecord(value)){ // Maker Buy
tokenAmount += value;
remainingQuantity := Nat.max(remainingQuantity, value) - value;
token0Value := #CreditRecord(value);
//gas0 += _getFee0();
};
case(_){};
};
switch(_filled.token1Value){
case(#DebitRecord(value)){ // Maker Sell
currencyAmount += value;
token1Value := #CreditRecord(value);
//gas1 += _getFee1();
};
case(#CreditRecord(value)){ // Maker Buy
currencyAmount += value;
remainingAmount := Nat.max(remainingAmount, value) - value;
token1Value := #DebitRecord(value);
};
case(_){};
};
_updateTotalVol(tokenAmount, currencyAmount);
_updateVol(account, tokenAmount, currencyAmount);
//if (quantity < setting.UNIT_SIZE){ quantity := 0; };
let remaining: OrderPrice = OrderBook.setQuantity(order.remaining, remainingQuantity, ?remainingAmount);
var status: TradingStatus = order.status;
// if (Option.isNull(OrderBook.get(icdex_orderBook, order.txid, ?OrderBook.side(order.orderPrice)))){
// status := #Closed;
// };
if (remainingQuantity < setting.UNIT_SIZE){
status := #Closed;
};
let filled : [OrderFilled] = [{counterparty = _txid; token0Value = token0Value; token1Value = token1Value; time = Time.now() }];
_update(order.txid, ?remaining, ?_toid, ?filled, null, null, ?status, null);
//ignore _refund(_toid, order.txid, []);
if (status == #Closed){
_hook_close(order.txid);
};
};
};
case(_){ /*assert(false);*/ };
};
return (account, nonce);
};
// send token
private func _sendToken(_isAutoMode: Bool, _tokenSide: {#token0;#token1}, _toid: SagaTM.Toid, _subaccount: Blob, _preTtids: [SagaTM.Ttid], _toIcrc1Account: [ICRC1.Account], _value: [Nat], _transferData: ?Blob, _callback: ?SagaTM.Callback) : [SagaTM.Ttid]{
assert(_toIcrc1Account.size() == _value.size());
var ttids : [SagaTM.Ttid] = [];
let saga = _getSaga();
var std = token0Std;
var tokenPrincipal = _token0Canister();
var fee = _getFee0();
if (_tokenSide == #token1){
std := token1Std;
tokenPrincipal := _token1Canister();
fee := _getFee1();
};
var subaccount = _subaccount;
var totalAmount : Nat = 0;
for (v in _value.vals()){
totalAmount += v;
};
var localTransferArgs_pre: [(_act: {#add; #sub}, _account: Blob, _token: {#token0; #token1}, _amount: {#locked: Nat; #available: Nat})] = [];
if (_isAutoMode){
switch(Trie.get(icdex_orders, keyb(_subaccount), Blob.equal)){ // _subaccount = txid
case(?(order)){
let mode = _exchangeMode(order.account, ?order.nonce);
if (mode == #PoolMode){
subaccount := Blob.fromArray(sa_zero);
localTransferArgs_pre := Tools.arrayAppend(localTransferArgs_pre, [(#sub, order.account, _tokenSide, #locked(totalAmount))]);
};
};
case(_){};
};
};
var sub = ?subaccount;
var sa = _toSaNat8(sub);
if (subaccount.size() == 0){
sub := null;
sa := null;
};
let length = _toIcrc1Account.size();
var toIcrc1Accounts: [ICRC1.Account] = _toIcrc1Account;
var values: [Nat] = _value;
var valueToPool: Nat = 0;
var localTransferArgs_post: [(_act: {#add; #sub}, _account: Blob, _token: {#token0; #token1}, _amount: {#locked: Nat; #available: Nat})] = [];
if (_isAutoMode and length > 0){
toIcrc1Accounts := [];
values := [];
for (i in Iter.range(0, Nat.sub(length, 1))){
let account = Tools.principalToAccountBlob(_toIcrc1Account[i].owner, _toSaNat8(_toIcrc1Account[i].subaccount));
let isKeptFunds = _isKeepingBalanceInPair(account);
if (isKeptFunds){
valueToPool += _value[i];
localTransferArgs_post := Tools.arrayAppend(localTransferArgs_post, [(#add, account, _tokenSide, #available(_value[i]))]);
}else{
toIcrc1Accounts := Tools.arrayAppend(toIcrc1Accounts, [_toIcrc1Account[i]]);
values := Tools.arrayAppend(values, [_value[i]]);
};
};
if (valueToPool > 0 and localTransferArgs_pre.size() == 0){ // to: Pool
toIcrc1Accounts := Tools.arrayAppend(toIcrc1Accounts, [{owner = Principal.fromActor(this); subaccount = ?Blob.fromArray(sa_zero)}]);
values := Tools.arrayAppend(values, [valueToPool]);
};
};
if (localTransferArgs_pre.size() > 0){
let task_pre = _buildTask(sub, Principal.fromActor(this), #This(#batchTransfer(localTransferArgs_pre)), _preTtids);
let ttid_pre = saga.push(_toid, task_pre, null, null);
ttids := Tools.arrayAppend(ttids, [ttid_pre]);
};
if (std == #drc20 and toIcrc1Accounts.size() > 1){
let accountArr = Array.map<ICRC1.Account, Address>(toIcrc1Accounts, func (t:ICRC1.Account): Address{
_accountIdToHex(Tools.principalToAccountBlob(t.owner, _toSaNat8(t.subaccount)))
});
let valueArr = Array.map<Nat, Nat>(values, func (t:Nat): Nat{
Nat.sub(t, fee);
});
let task = _buildTask(sub, tokenPrincipal, #DRC20(#transferBatch(accountArr, valueArr, null, sa, _transferData)), _preTtids);
let ttid = saga.push(_toid, task, null, _callback);
if (Option.isSome(_callback)){ _putTTCallback(ttid) };
ttids := Tools.arrayAppend(ttids, [ttid]);
}else{