-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathssnlist.scilla
2698 lines (2451 loc) · 98.8 KB
/
ssnlist.scilla
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
scilla_version 0
import ListUtils IntUtils PairUtils
library SSNList
(* A non-custodial staking contract with admin privileges *)
(* SSN Data Type *)
(* Each SSN has the following fields: *)
(* ActiveStatus : Bool *)
(* Represents whether the SSN has the minnimum stake amount and therefore ready to participate in staking and receive rewards. *)
(* StakeAmount : Uint128 *)
(* Total stake that can be used for reward calculation. *)
(* StakeRewards : Uint128 *)
(* (Unwithdrawn) Reward accumulated so far across all cycles. It only includes the reward that the SSN can distribute to its delegators. *)
(* It does not include SSN's own commission. *)
(* Name : String *)
(* A human-readable name for this SSN. *)
(* URLRaw : String *)
(* Represents "ip:port" of the SSN serving raw API requests. *)
(* URLApi : String *)
(* Representing URL exposed by SSN serving public API requests. *)
(* BufferedDeposit : Uint128 *)
(* Stake deposit that cannot be counted as a part of reward calculation for the ongoing reward cycle. But, to be considered *)
(* for the next one. *)
(* Commission : Uint128 *)
(* Percentage of incoming rewards that the SSN takes as commission. If the commission is 10.5%, then it is multiplied by 10^7 and then the resulting integer is set as commission. The assumption is that the percentage is up to 7 decimal places. *)
(* CommissionRewards : Uint128 *)
(* Number of ZILs earned as commission by the SSN. *)
(* ReceivingAddress : ByStr20 *)
(* Address that will be used to receive commission. *)
(* Invariant : ActiveStatus = (Minstake < StakeAmount) *)
type Ssn =
| Ssn of Bool Uint128 Uint128 String String String Uint128 Uint128 Uint128 ByStr20
(* SSNAddress : ByStr20 *)
(* Address of the SSN. *)
(* CycleReward : Uint128 *)
(* Integer representation of reward assigned by the verifier to this SSN for this cycle. *)
(* TotalStakeAmount : Uint128 *)
(* Total stake amount at a specific cycle. *)
type SsnStakeRewardShare =
| SsnStakeRewardShare of ByStr20 Uint128 Uint128
(* SSNCycleInfo Data Type *)
(* Each SSNCycleInfo has the following fields: *)
(* TotalStakeDuringTheCycle : Uint128 *)
(* Represents the amount staked during this cycle for the given SSN. *)
(* TotalRewardEarnedDuringTheCycle : Uint128 *)
(* Represents the total reward earned during this cycle for the given SSN. . *)
type SSNCycleInfo =
| SSNCycleInfo of Uint128 Uint128
(* Used in order to be able to iterate over the procedure CalcStakeRewards *)
(* deleg, ssn_operator, reward_cycle *)
type TmpArg =
| TmpArg of ByStr20 ByStr20 Uint32
let one_msg =
fun (m : Message) =>
let e = Nil {Message} in
Cons {Message} m e
let uint128_one = Uint128 1
let uint128_zero = Uint128 0
let uint128_10_power_7 = Uint128 10000000
let uint128_10_power_9 = Uint128 1000000000
let uint128_100 = Uint128 100
let uint32_one = Uint32 1
let uint32_zero = Uint32 0
let option_value =
tfun 'A =>
fun (default: 'A) =>
fun (opt_val: Option 'A) =>
match opt_val with
| Some v => v
| None => default
end
let option_map_uint128_uint128_value =
let f = @option_value (Map Uint128 Uint128) in
let emt = Emp Uint128 Uint128 in
f emt
let option_uint128_value =
let f = @option_value Uint128 in
f uint128_zero
let option_uint32_value =
let f = @option_value Uint32 in
f uint32_zero
let sub_one_to_zero =
fun (x: Uint32) =>
let less_than_one = builtin lt x uint32_one in
match less_than_one with
| True =>
uint32_zero
| False =>
let res = builtin sub x uint32_one in
res
end
let option_add =
fun (x_opt: Option Uint128) =>
fun (y_opt: Option Uint128) =>
match x_opt with
| Some x =>
let y = option_uint128_value y_opt in
let res = builtin add x y in
Some {Uint128} res
| None => y_opt
end
let change_rate =
fun (old: Uint128) =>
fun (new: Uint128) =>
let a = builtin lt old new in
match a with
| True =>
builtin sub new old
| False =>
builtin sub old new
end
let iota : Uint32 -> Uint32 -> List Uint32 =
fun (m : Uint32) => fun (n : Uint32) =>
let m_lt_n = builtin lt m n in
match m_lt_n with
| True =>
let delta = builtin sub n m in
let delta_nat = builtin to_nat delta in
let nil = Nil {Uint32} in
let acc_init = Pair {(List Uint32) Uint32} nil n in
let one = Uint32 1 in
let step = fun (xs_n : Pair (List Uint32) Uint32) => fun (ignore : Nat) =>
match xs_n with
| Pair xs n =>
let new_n = builtin sub n one in
let new_xs = Cons {Uint32} new_n xs in
Pair {(List Uint32) Uint32} new_xs new_n
end in
let fold = @nat_fold (Pair (List Uint32) Uint32) in
let xs_m = fold step acc_init delta_nat in
match xs_m with
| Pair xs m => xs
end
| False => Nil {Uint32}
end
let uint128_to_uint256 : Uint128 -> Uint256 =
fun (x : Uint128) =>
let ox256 = builtin to_uint256 x in
match ox256 with
| None =>
(* this never happens, hence we throw a division by zero exception just in case *)
let zero = Uint256 0 in
builtin div zero zero
| Some x256 => x256
end
(* Compute "(x * y) / z" with protection against integer overflows *)
let muldiv : Uint128 -> Uint128 -> Uint128 -> Uint128 =
fun (x : Uint128) =>
fun (y : Uint128) =>
fun (z : Uint128) =>
let x256 = uint128_to_uint256 x in
let y256 = uint128_to_uint256 y in
let z256 = uint128_to_uint256 z in
let x_mul_y256 = builtin mul x256 y256 in
let res256 = builtin div x_mul_y256 z256 in
let ores128 = builtin to_uint128 res256 in
match ores128 with
| None =>
(* this must never happen, hence we throw an integer overflow exception *)
let max_uint128 = Uint128 340282366920938463463374607431768211455 in
let fourtytwo128 = Uint128 42 in
builtin mul max_uint128 fourtytwo128
| Some res128 =>
res128
end
let map_to_stake_rewards =
fun (total_stake: Uint128) =>
fun (element: Pair ByStr20 Uint128) =>
match element with
| Pair ssnaddr cycle_reward => SsnStakeRewardShare ssnaddr cycle_reward total_stake
end
(* check if last_withdraw_cycle_deleg[deleg] is empty *)
let is_ssn_cycle_map_empty =
fun(m : Map ByStr20 Uint32) =>
let map_size = builtin size m in
builtin eq map_size uint32_zero
(* check if deposit_amt_deleg[deleg] is empty *)
let is_ssn_deposit_map_empty =
fun(m : Map ByStr20 Uint128) =>
let map_size = builtin size m in
builtin eq map_size uint32_zero
(* check if withdrawal_pending[deleg] is empty *)
let is_block_deposit_map_empty =
fun(m : Map BNum Uint128) =>
let map_size = builtin size m in
builtin eq map_size uint32_zero
(* check if nested maps are empty *)
(* buff_deposit_deleg[deleg] *)
(* direct_deposit_deleg[deleg] *)
(* deleg_stake_per_cycle[deleg] *)
let is_ssn_cycle_deposit_map_empty =
fun(m : Map ByStr20 (Map Uint32 Uint128)) =>
let map_size = builtin size m in
builtin eq map_size uint32_zero
(* check if final inner map is empty *)
(* buff_deposit_deleg[deleg][ssn] *)
(* direct_deposit_deleg[deleg][ssn] *)
(* deleg_stake_per_cycle[deleg][ssn] *)
let is_cycle_deposit_map_empty =
fun(m : Map Uint32 Uint128) =>
let map_size = builtin size m in
builtin eq map_size uint32_zero
let bool_active = True
let bool_inactive = False
let addfunds_tag = "AddFunds"
(* for SwapDelegator *)
let reset_addr = 0x0000000000000000000000000000000000000000
type Error =
| ContractFrozenFailure
| VerifierValidationFailed
| AdminValidationFailed
| StagingAdminNotExist
| StagingAdminValidationFailed
| ProxyValidationFailed
| DelegDoesNotExistAtSSN
| DelegHasBufferedDeposit
| ChangeCommError
| SSNNotExist
| SSNAlreadyExist
| DelegHasUnwithdrawRewards
| DelegHasNoSufficientAmt
| SSNNoComm
| DelegStakeNotEnough
| ExceedMaxChangeRate
| ExceedMaxCommRate
| InvalidTotalAmt
| VerifierNotSet
| VerifierRecvAddrNotSet
| ReDelegInvalidSSNAddr
| AvailableRewardsError
| InvalidSwapAddr
| SwapAddrValidationFailed
| SwapAddrAlreadyExistsAsRequest
let make_error =
fun (result: Error) =>
let result_code =
match result with
| ContractFrozenFailure => Int32 -1
| VerifierValidationFailed => Int32 -2
| AdminValidationFailed => Int32 -3
| StagingAdminNotExist => Int32 -4
| StagingAdminValidationFailed => Int32 -5
| ProxyValidationFailed => Int32 -6
| DelegDoesNotExistAtSSN => Int32 -7
| DelegHasBufferedDeposit => Int32 -8
| ChangeCommError => Int32 -9
| SSNNotExist => Int32 -10
| SSNAlreadyExist => Int32 -11
| DelegHasUnwithdrawRewards => Int32 -12
| DelegHasNoSufficientAmt => Int32 -13
| SSNNoComm => Int32 -14
| DelegStakeNotEnough => Int32 -15
| ExceedMaxChangeRate => Int32 -16
| ExceedMaxCommRate => Int32 -17
| InvalidTotalAmt => Int32 -18
| VerifierNotSet => Int32 -19
| VerifierRecvAddrNotSet => Int32 -20
| ReDelegInvalidSSNAddr => Int32 -21
| AvailableRewardsError => Int32 -22
| InvalidSwapAddr => Int32 -23
| SwapAddrValidationFailed => Int32 -24
| SwapAddrAlreadyExistsAsRequest => Int32 -25
end
in
{ _exception: "Error"; code: result_code }
(* Utility used for migration *)
let list_map_to_pair_with_constant : forall 'A. forall 'B. List 'A -> 'B -> List (Pair 'A 'B) =
tfun 'A =>
tfun 'B =>
fun (list : List 'A) =>
fun (const : 'B) =>
let f = fun (key : 'A) => Pair {'A 'B} key const in
let mapper = @list_map 'A (Pair 'A 'B) in
mapper f list
(***************************************************)
(* The contract definition *)
(***************************************************)
contract SSNList(
init_admin: ByStr20,
init_proxy_address: ByStr20,
init_gzil_address: ByStr20
)
(* Keeps track of SSNS *)
(* AddressOfSSN -> SSNInfo *)
field ssnlist: Map ByStr20 Ssn = Emp ByStr20 Ssn
(* Record commission for SSN for each reward cycle *)
(* AddressofSSN -> (RewardCycle -> commission ) *)
field comm_for_ssn: Map ByStr20 (Map Uint32 Uint128) = Emp ByStr20 (Map Uint32 Uint128)
(* Following data structure helps to calculate rewards for delegators *)
(* Keeps track of stakes deposited at SSNs *)
(* Record deposit amount for every deleg for every ssn *)
(* AddressofDeleg -> (AddressofSSN -> StakeAmount) *)
field deposit_amt_deleg: Map ByStr20 (Map ByStr20 Uint128) = Emp ByStr20 (Map ByStr20 Uint128)
(* AddressofSSN -> (AddressofDeleg -> StakeAmount) *)
(* Used by offchain services like wallets *)
field ssn_deleg_amt: Map ByStr20 (Map ByStr20 Uint128) = Emp ByStr20 (Map ByStr20 Uint128)
(* Keeps track of buffered deposit for a delegator *)
(* AddressOfDeleg -> (AddressofSSN -> (RewardCycleNumber -> BufferedStakeAmountDuringTheCycle)) *)
(* The BufferedStakeAmount will only be truely delegated at next cycle *)
field buff_deposit_deleg: Map ByStr20 (Map ByStr20 (Map Uint32 Uint128)) = Emp ByStr20 (Map ByStr20 (Map Uint32 Uint128))
(* Keeps track of stake deposits for a delegator that can be considered for reward calcuation *)
(* AddressofDeleg -> (AddressofSSN -> (RewardCycleNumber -> StakeAmount)) *)
field direct_deposit_deleg: Map ByStr20 (Map ByStr20 (Map Uint32 Uint128)) = Emp ByStr20 (Map ByStr20 (Map Uint32 Uint128))
(* Keeps track of the cycle number when a deleg last withdrew its rewards *)
(* AddressOfDeleg -> ( AddressOfSSN -> CycleNumberWhenLastWithdrawn) *)
(* notice here, the last withdraw cycle also indicated the earlist deposit cycle this round *)
(* this will help reduce some calculation for DistributeStakeRewards, also can avoid some corner cases *)
field last_withdraw_cycle_deleg: Map ByStr20 (Map ByStr20 Uint32) = Emp ByStr20 (Map ByStr20 Uint32)
(* Keeps track of the cycle number when a deleg last buffered deposit its delegate *)
(* AddressOfDeleg -> ( AddressOfSSN -> CycleNumberWhenLastDeposit) *)
field last_buf_deposit_cycle_deleg: Map ByStr20 (Map ByStr20 Uint32) = Emp ByStr20 (Map ByStr20 Uint32)
(* AddressOfSSN -> (RewardCycleNumber -> Pair (TotalStakeDuringTheCycleForSSN, TotalRewardEarnedDuringTheCycle) *)
field stake_ssn_per_cycle: Map ByStr20 (Map Uint32 SSNCycleInfo) = Emp ByStr20 (Map Uint32 SSNCycleInfo)
(* AddressOfDeleg -> AddressOfSSN -> EffectCycleNum -> Deposit *)
field deleg_stake_per_cycle: Map ByStr20 (Map ByStr20 (Map Uint32 Uint128)) = Emp ByStr20 (Map ByStr20 (Map Uint32 Uint128))
(* AddressOfDeleg -> BlockNumber -> Deposit *)
field withdrawal_pending: Map ByStr20 (Map BNum Uint128) = Emp ByStr20 (Map BNum Uint128)
(* AddressOfInitialDeleg -> AddressOfNewDeleg *)
(* used to transfer all stakes and pending withdrawal of deleg_A -> deleg_B *)
(* see RequestDelegatorSwap *)
field deleg_swap_request: Map ByStr20 ByStr20 = Emp ByStr20 ByStr20
field bnum_req: Uint128 = Uint128 35000
(* Temporary storage maps *)
field cycle_rewards_deleg: Uint128 = uint128_zero
(* Used during AssignStakeReward *)
(* Record the latest rewards earned by verifier *)
field verifier_reward: Uint128 = uint128_zero
field available_withdrawal: Uint128 = uint128_zero
field current_deleg: Option ByStr20 = None {ByStr20}
(* Used during SwapDelegator *)
(* Keeps tracks of the ssn address to pass to other procedures in forall calls *)
field current_ssn: Option ByStr20 = None {ByStr20}
(* Used during SwapDelegator *)
(* Keeps tracks of the new deleg address to pass to other procedures*)
field new_deleg: Option ByStr20 = None {ByStr20}
field verifier: Option ByStr20 = None {ByStr20}
field verifier_receiving_addr: Option ByStr20 = None {ByStr20}
(* 10 mil ZIL expressed in Qa where 1 ZIL = 10^12 Qa *)
field minstake: Uint128 = Uint128 10000000000000000000
(* 10 ZIL expresssed in Qa where 1 ZIL = 10^12 Qa *)
field mindelegstake: Uint128 = Uint128 10000000000000
field contractadmin: ByStr20 = init_admin
field stagingcontractadmin: Option ByStr20 = None {ByStr20}
field gziladdr: ByStr20 = init_gzil_address
field lastrewardcycle: Uint32 = uint32_one
field paused: Bool = True
(* 1% *)
field maxcommchangerate: Uint128 = uint128_one
(* 100% expressed as an integer multipled by 10^7 *)
field maxcommrate: Uint128 = Uint128 1000000000
field totalstakeamount: Uint128 = uint128_zero
(* Procedures *)
(* Internal functions, used like Solidity modifiers *)
(* to erase buff_deposit_deleg outer keys *)
(* see CleanBuffDeposit *)
procedure CleanBuffDepositDelegAddr(deleg: ByStr20)
buff_deposit_deleg_map <- buff_deposit_deleg[deleg];
match buff_deposit_deleg_map with
| Some buff_deposit_deleg_entry =>
is_map_empty = is_ssn_cycle_deposit_map_empty buff_deposit_deleg_entry;
match is_map_empty with
| True => (* empty map *)
delete buff_deposit_deleg[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase buff_deposit_deleg inner keys *)
(* see CleanBuffDeposit *)
procedure CleanBuffDepositSSNAddr(deleg_ssn_pair: Pair ByStr20 ByStr20)
match deleg_ssn_pair with
| Pair deleg ssn =>
inner_map <- buff_deposit_deleg[deleg][ssn];
match inner_map with
| Some inner_entry =>
is_map_empty = is_cycle_deposit_map_empty inner_entry;
match is_map_empty with
| True => (* empty map *)
delete buff_deposit_deleg[deleg][ssn]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
end
(* to erase direct_deposit_deleg inner keys *)
procedure CleanDirectDepositSSNAddr(deleg_ssn_pair: Pair ByStr20 ByStr20)
match deleg_ssn_pair with
| Pair deleg ssn =>
inner_map <- direct_deposit_deleg[deleg][ssn];
match inner_map with
| Some inner_entry =>
is_map_empty = is_cycle_deposit_map_empty inner_entry;
match is_map_empty with
| True => (* empty map *)
delete direct_deposit_deleg[deleg][ssn]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
end
(* to erase direct_deposit_deleg outer keys *)
procedure CleanDirectDepositDelegAddr(deleg: ByStr20)
direct_deposit_deleg_map <- direct_deposit_deleg[deleg];
match direct_deposit_deleg_map with
| Some direct_deposit_deleg_entry =>
is_map_empty = is_ssn_cycle_deposit_map_empty direct_deposit_deleg_entry;
match is_map_empty with
| True => (* empty map *)
delete direct_deposit_deleg[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase deleg_stake_per_cycle inner keys *)
procedure CleanDelegStakePerCycleSSNAddr(deleg_ssn_pair: Pair ByStr20 ByStr20)
match deleg_ssn_pair with
| Pair deleg ssn =>
inner_map <- deleg_stake_per_cycle[deleg][ssn];
match inner_map with
| Some inner_entry =>
is_map_empty = is_cycle_deposit_map_empty inner_entry;
match is_map_empty with
| True => (* empty map *)
delete deleg_stake_per_cycle[deleg][ssn]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
end
(* to erase deleg_stake_per_cycle outer keys *)
procedure CleanDelegStakePerCycleDelegAddr(deleg: ByStr20)
deleg_stake_per_cycle_map <- deleg_stake_per_cycle[deleg];
match deleg_stake_per_cycle_map with
| Some deleg_stake_per_cycle_entry =>
is_map_empty = is_ssn_cycle_deposit_map_empty deleg_stake_per_cycle_entry;
match is_map_empty with
| True => (* empty map *)
delete deleg_stake_per_cycle[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase deposit_amt_deleg outer keys *)
procedure CleanDepositAmtDelegAddr(deleg: ByStr20)
ssn_deposit_map <- deposit_amt_deleg[deleg];
match ssn_deposit_map with
| Some ssn_deposit_entry =>
is_map_empty = is_ssn_deposit_map_empty ssn_deposit_entry;
match is_map_empty with
| True => (* empty map *)
delete deposit_amt_deleg[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase last_withdraw_cycle_deleg outer keys *)
procedure CleanLastWithdrawCycleDelegAddr(deleg: ByStr20)
ssn_cycle_map <- last_withdraw_cycle_deleg[deleg];
match ssn_cycle_map with
| Some ssn_cycle_entry =>
is_map_empty = is_ssn_cycle_map_empty ssn_cycle_entry;
match is_map_empty with
| True => (* empty map *)
delete last_withdraw_cycle_deleg[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase last_buf_deposit_cycle_deleg outer keys *)
procedure CleanLastBuffDepositCycleDelegAddr(deleg: ByStr20)
ssn_cycle_map <- last_buf_deposit_cycle_deleg[deleg];
match ssn_cycle_map with
| Some ssn_cycle_entry =>
is_map_empty = is_ssn_cycle_map_empty ssn_cycle_entry;
match is_map_empty with
| True => (* empty map *)
delete last_buf_deposit_cycle_deleg[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* to erase withdrawal_pending outer keys *)
procedure CleanPendingWithdrawalDelegAddr(deleg: ByStr20)
block_deposit_map <- withdrawal_pending[deleg];
match block_deposit_map with
| Some block_deposit_entry =>
is_map_empty = is_block_deposit_map_empty block_deposit_entry;
match is_map_empty with
| True => (* empty map *)
delete withdrawal_pending[deleg]
| False => (* contains other records *)
end
| None => (* nothing to delete *)
end
end
(* delete the cycle key and any other external keys if the inner map is empty *)
(* for use in replace of normal delete operation to erase empty nested maps *)
procedure DeleteBuffDeposit(deleg: ByStr20, ssnaddr: ByStr20, cycle: Uint32)
delete buff_deposit_deleg[deleg][ssnaddr][cycle];
deleg_ssn_pair = Pair {ByStr20 ByStr20} deleg ssnaddr;
CleanBuffDepositSSNAddr deleg_ssn_pair;
CleanBuffDepositDelegAddr deleg
end
(* delete the cycle key and any other external keys if the inner map is empty *)
(* for use in replace of normal delete operation to erase empty nested maps *)
procedure DeleteDirectDeposit(deleg: ByStr20, ssnaddr: ByStr20, cycle: Uint32)
delete direct_deposit_deleg[deleg][ssnaddr][cycle];
deleg_ssn_pair = Pair {ByStr20 ByStr20} deleg ssnaddr;
CleanDirectDepositSSNAddr deleg_ssn_pair;
CleanDirectDepositDelegAddr deleg
end
(* delete the blk num and any other external keys if the inner map is empty *)
(* for use in replace of normal delete operation to erase empty nested maps *)
procedure DeletePendingWithdrawal(deleg: ByStr20, withdraw_number: BNum)
delete withdrawal_pending[deleg][withdraw_number];
CleanPendingWithdrawalDelegAddr deleg
end
procedure TruncateDeleg(deleg: ByStr20, ssnaddr: ByStr20)
delete deposit_amt_deleg[deleg][ssnaddr];
delete ssn_deleg_amt[ssnaddr][deleg];
delete buff_deposit_deleg[deleg][ssnaddr];
delete direct_deposit_deleg[deleg][ssnaddr];
delete last_withdraw_cycle_deleg[deleg][ssnaddr];
delete deleg_stake_per_cycle[deleg][ssnaddr];
delete last_buf_deposit_cycle_deleg[deleg][ssnaddr];
(* ssn_deleg_amt won't have empty maps *)
CleanDepositAmtDelegAddr deleg;
CleanBuffDepositDelegAddr deleg;
CleanDirectDepositDelegAddr deleg;
CleanDelegStakePerCycleDelegAddr deleg;
CleanLastWithdrawCycleDelegAddr deleg;
CleanLastBuffDepositCycleDelegAddr deleg
end
procedure ThrowError(err: Error)
e = make_error err;
throw e
end
procedure ValidateRate(rate: Uint128)
max_rate <- maxcommrate;
validate = uint128_le rate max_rate;
match validate with
| True =>
| False =>
e = ExceedMaxCommRate;
ThrowError e
end
end
procedure ValidateChangeRate(old: Uint128, new: Uint128)
maxcommchangerate_l <- maxcommchangerate;
absolute_change = change_rate old new;
absolute_change = builtin div absolute_change uint128_10_power_7;
valid = uint128_le absolute_change maxcommchangerate_l;
match valid with
| True =>
| False =>
e = ExceedMaxChangeRate;
ThrowError e
end
end
procedure IncreaseTotalStakeAmt(amt: Uint128)
current_amt <- totalstakeamount;
new_amt = builtin add current_amt amt;
totalstakeamount := new_amt
end
procedure DecreaseTotalStakeAmt(amt: Uint128)
current_amt <- totalstakeamount;
valid = uint128_le amt current_amt;
match valid with
| True =>
new_amt = builtin sub current_amt amt;
totalstakeamount := new_amt
| False =>
e = InvalidTotalAmt;
ThrowError e
end
end
procedure IncreaseTotalStakeAmtOnStatus(amt: Uint128, status: Bool)
match status with
| True =>
e = { _eventname: "SSNActive"; increase_amt: amt };
event e;
IncreaseTotalStakeAmt amt
| False =>
end
end
procedure DecreaseTotalStakeAmtOnStatus(amt: Uint128, status: Bool)
match status with
| True =>
| False =>
e = { _eventname: "SSNInactive"; decreased_amt: amt };
event e;
DecreaseTotalStakeAmt amt
end
end
(* Check if the initiator is verifier *)
procedure CallerIsVerifier(initiator: ByStr20)
verifier_tmp <- verifier;
match verifier_tmp with
| Some v =>
is_verifier = builtin eq initiator v;
match is_verifier with
| True =>
| False =>
e = VerifierValidationFailed;
ThrowError e
end
| None =>
e = VerifierNotSet;
ThrowError e
end
end
(* Check if the initiator is admin *)
procedure IsAdmin(initiator: ByStr20)
contractadmin_tmp <- contractadmin;
is_admin = builtin eq initiator contractadmin_tmp;
match is_admin with
| True =>
| False =>
e = AdminValidationFailed;
ThrowError e
end
end
(* Check if the caller is the proxy *)
procedure IsProxy()
is_proxy = builtin eq _sender init_proxy_address;
match is_proxy with
| True =>
| False =>
e = ProxyValidationFailed;
ThrowError e
end
end
(* Check if the contract is not paused *)
procedure IsNotPaused()
paused_tmp <- paused;
match paused_tmp with
| False =>
| True =>
e = ContractFrozenFailure;
ThrowError e
end
end
(* Check if the contract is paused *)
procedure IsPaused()
paused_tmp <- paused;
match paused_tmp with
| False =>
e = ContractFrozenFailure;
ThrowError e
| True =>
end
end
procedure TransferFunds(tag: String, amt: Uint128, recipient: ByStr20)
msg = {_tag: tag; _recipient: recipient; _amount: amt};
msgs = one_msg msg;
send msgs
end
(* current_block > withdraw_number + bnum_req *)
procedure CalculateTotalWithdrawal(withdraw: Pair BNum Uint128)
current_deleg_o <- current_deleg;
match current_deleg_o with
| Some deleg =>
match withdraw with
| Pair withdraw_number amt =>
current_bnum <- & BLOCKNUMBER;
current_bnum_req <- bnum_req;
bnum = builtin badd withdraw_number current_bnum_req;
can_withdraw = builtin blt bnum current_bnum;
match can_withdraw with
| True =>
DeletePendingWithdrawal deleg withdraw_number;
current_amt <- available_withdrawal;
current_amt = builtin add current_amt amt;
available_withdrawal := current_amt
| False =>
end
end
| None => (* Won't reach *)
end
end
procedure AssertCorrectRewards(remaining_rewards: Uint128, ssn_rewards: Uint128)
validate = uint128_le ssn_rewards remaining_rewards;
match validate with
| True =>
| False =>
e = AvailableRewardsError;
ThrowError e
end
end
procedure UpdateStakeReward(entry: SsnStakeRewardShare)
lastreward_blk <- lastrewardcycle;
match entry with
| SsnStakeRewardShare ssnaddr cycle_reward total_stake =>
curval <- ssnlist[ssnaddr];
match curval with
| None =>
e = SSNNotExist;
ThrowError e
| Some (Ssn active_status stake_amt rewards name urlraw urlapi buffdeposit comm comm_rewards rec_addr) =>
match active_status with
| False =>
e = { _eventname: "SSN inactive"; ssn_addr: ssnaddr};
event e
| True =>
(* To calculate rewards belong to this ssn operator *)
new_rewards = muldiv stake_amt cycle_reward total_stake;
current_verifier_reward <- verifier_reward;
AssertCorrectRewards current_verifier_reward new_rewards;
new_current_verifier_reward = builtin sub current_verifier_reward new_rewards;
verifier_reward := new_current_verifier_reward;
(* To calculate commission *)
reward_comm_tmp = muldiv new_rewards comm uint128_10_power_9;
total_reward_comm = builtin add reward_comm_tmp comm_rewards;
(* To calculate rewards can be distributed to delegators *)
delegate_reward = builtin sub new_rewards reward_comm_tmp;
p = SSNCycleInfo stake_amt delegate_reward;
stake_ssn_per_cycle[ssnaddr][lastreward_blk] := p;
(* Update ssn info *)
new_stake_amt = builtin add stake_amt buffdeposit;
deleg_reward = builtin add delegate_reward rewards;
ssn = Ssn active_status new_stake_amt deleg_reward name urlraw urlapi uint128_zero comm total_reward_comm rec_addr;
ssnlist[ssnaddr] := ssn;
IncreaseTotalStakeAmt buffdeposit;
e = { _eventname: "SSN assign reward"; ssnaddr: ssnaddr; cycle_number: lastreward_blk; delegate_rewards: delegate_reward; comm_rewards: reward_comm_tmp};
event e
end
end
end
end
(* this procedure is to send rewards to deleg *)
procedure SendDelegRewards(addr: ByStr20, amt: Uint128)
to_send = builtin eq amt uint128_zero;
match to_send with
| True =>
| False =>
TransferFunds addfunds_tag amt addr;
e = { _eventname: "Send deleg rewards"; addr: addr; amt: amt};
event e
end
end
(* Check if a delegs exists for a given SSN *)
procedure DelegExists(ssnaddr: ByStr20, deleg: ByStr20)
if_exists <- exists deposit_amt_deleg[deleg][ssnaddr];
match if_exists with
| True =>
| False =>
e = DelegDoesNotExistAtSSN;
ThrowError e
end
end
procedure FillLastWithdrawCycle(ssnaddr: ByStr20, deleg : ByStr20)
lwcd_o <- last_withdraw_cycle_deleg[deleg][ssnaddr];
match lwcd_o with
| Some lwcd =>
| None =>
lrc <- lastrewardcycle;
last_withdraw_cycle_deleg[deleg][ssnaddr] := lrc
end
end
procedure FillInDepositDelegAmt(ssnaddr: ByStr20, deleg: ByStr20, amount: Uint128)
deposit_amt <- deposit_amt_deleg[deleg][ssnaddr];
match deposit_amt with
| Some amt =>
new_amt = builtin add amt amount;
deposit_amt_deleg[deleg][ssnaddr] := new_amt;
ssn_deleg_amt[ssnaddr][deleg] := new_amt
| None =>
deposit_amt_deleg[deleg][ssnaddr] := amount;
ssn_deleg_amt[ssnaddr][deleg] := amount
end
end
procedure AssertNoRewards(ssnaddr: ByStr20, deleg: ByStr20, total_rewards: Uint128)
no_total_rewards = builtin eq total_rewards uint128_zero;
match no_total_rewards with
| True =>
| False =>
lrcd_tmp <- last_withdraw_cycle_deleg[deleg][ssnaddr];
lrcd = option_uint32_value lrcd_tmp;
lrc <- lastrewardcycle;
has_reward = builtin lt lrcd lrc;
match has_reward with
| True =>
offset = builtin sub lrc lrcd;
offset_only_one = builtin eq offset uint32_one;
match offset_only_one with
| True =>
(* if there is only one cycle ahead, and if it only has buffered deposit, then the rewards *)
(* could be zero, we should let him go. to identify this case, we need calculate the exact rewards *)
last_reward_cycle = builtin sub lrc uint32_one;
last2_reward_cycle = sub_one_to_zero last_reward_cycle;
cur_opt <- direct_deposit_deleg[deleg][ssnaddr][last_reward_cycle];
buf_opt <- buff_deposit_deleg[deleg][ssnaddr][last2_reward_cycle];
comb_opt = option_add cur_opt buf_opt;
last_amt_o <- deleg_stake_per_cycle[deleg][ssnaddr][last_reward_cycle];
last_amt = option_uint128_value last_amt_o;
staking_of_deleg = match comb_opt with
| Some stake => builtin add last_amt stake
| None => last_amt
end;
no_rewards = builtin eq staking_of_deleg uint128_zero;
match no_rewards with
| True =>
| False =>
e = DelegHasUnwithdrawRewards;
ThrowError e
end
| False =>
e = DelegHasUnwithdrawRewards;
ThrowError e
end
| False =>
end
end
end
procedure AsseertNoBufferedDeposit(ssnaddr: ByStr20, deleg: ByStr20)
ldcd_o <- last_buf_deposit_cycle_deleg[deleg][ssnaddr];
ldcd = option_uint32_value ldcd_o;
lrc <- lastrewardcycle;
(* in fact, lrc will only more than or equal to ldcd, equal means he has delegated this round and withdrawn this round as well *)
has_buffered = uint32_le lrc ldcd;
match has_buffered with
| True =>
e = DelegHasBufferedDeposit;
ThrowError e
| False =>
end
end
(* corner case check for swap request process in which there is buff_deposit but zero reward after assign rewards *)
procedure AssertNoBufferedDepositLessOneCycle(ssnaddr: ByStr20, deleg: ByStr20)
lrc <- lastrewardcycle;
last_reward_cycle = builtin sub lrc uint32_one;
has_buffered <- buff_deposit_deleg[deleg][ssnaddr][last_reward_cycle];
match has_buffered with
| Some buff_deposit =>
e = DelegHasBufferedDeposit;
ThrowError e
| None =>
end
end
procedure IsDelegstakeSufficient(amount: Uint128)
mindelegstake_l <- mindelegstake;
suffi = uint128_le mindelegstake_l amount;
match suffi with
| True =>
| False =>
e = DelegStakeNotEnough;
ThrowError e
end
end
procedure AdjustDeleg(ssnaddr: ByStr20, deleg: ByStr20, total_amount: Uint128, withdraw_amount: Uint128)
sufficient = uint128_le withdraw_amount total_amount;
match sufficient with
| True =>
need_truncate = builtin eq withdraw_amount total_amount;
match need_truncate with
| True =>
(* Remove all info map recorded for this deleg *)
TruncateDeleg deleg ssnaddr
| False =>
(* Readjust all rest deleg to this cycle *)
lrc <- lastrewardcycle;
rest_deleg = builtin sub total_amount withdraw_amount;
(* rest delegate should also meet mindelegstake *)
IsDelegstakeSufficient rest_deleg;
TruncateDeleg deleg ssnaddr;
(* Refer to transition TruncateDeleg, here we don't use Fillin transition because we *)
(* know they are all empty, and this can reduce some gasfee *)
deposit_amt_deleg[deleg][ssnaddr] := rest_deleg;
ssn_deleg_amt[ssnaddr][deleg] := rest_deleg;
direct_deposit_deleg[deleg][ssnaddr][lrc] := rest_deleg;
last_withdraw_cycle_deleg[deleg][ssnaddr] := lrc
end
| False =>
e = DelegHasNoSufficientAmt;
ThrowError e
end
end
procedure UnDelegateStakeAmt(initiator: ByStr20, ssn: ByStr20, undeleg_amt: Uint128)
ssn_o <- ssnlist[ssn];
deleg <- deposit_amt_deleg[initiator][ssn];
match ssn_o with
| Some (Ssn active_status stake_amt rewards name urlraw urlapi buffdeposit comm comm_rewards rec_addr) =>