scilla-parser 2.0.0

Scilla smart contract parser written in Rust
Documentation
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
scilla_version 0

import
  BoolUtils
  IntUtils
  ListUtils
  PairUtils

library StakingContract

type Denom =
| Zil
| Token of ByStr20

type Coins =
| Coins of Denom Uint128

type RewardParam =
| RewardParam of Uint128 Uint128 Uint64 Uint64

type Stake =
| Stake of Uint128 Uint64 Uint64 Uint128

type RewardResult =
| RewardResult of Uint128 Uint128

let fee_denom = Uint256 10000

let zil_address = 0x0000000000000000000000000000000000000000

let bool_active = True

let bool_inactive = False

let zil = Zil

let zero = Uint128 0

let zero_i256 = Int256 0

let min_bps = Uint128 1

let max_bps = Uint128 10000

let seconds_per_year = Uint128 31536000

let true = True

let one_msg =
  fun (m : Message) =>
    let e = Nil {(Message)} in
    Cons {(Message)} m e

type Error =
| CodeNotOwner
| ContractFrozenFailure
| Unauthorized
| ContractFrozenFailurePaused
| ContractFrozenFailureNotPaused
| RewardTokenNotFound
| NoStakeFoundBySender
| AmountGreaterThanStakedAmount
| NotAllowedToWithdrawStakeTokens
| InvalidBPSError
| CodeInsufficientFunds

let make_error =
  fun (result : Error) =>
    let result_code =
      match result with
      | CodeNotOwner => Int32 -1
      | ContractFrozenFailure => Int32 -2
      | Unauthorized => Int32 -3
      | ContractFrozenFailurePaused => Int32 -4
      | ContractFrozenFailureNotPaused => Int32 -5
      | RewardTokenNotFound => Int32 -6
      | NoStakeFoundBySender => Int32 -7
      | AmountGreaterThanStakedAmount => Int32 -8
      | NotAllowedToWithdrawStakeTokens => Int32 -9
      | InvalidBPSError => Int32 -10
      | CodeInsufficientFunds => Int32 -11
      end
    in
    { _exception : "Error"; code : result_code }

let get_value =
  fun (var : Option Uint128) =>
    match var with
    | Some v => v
    | None => zero
    end

let uint64_to_uint128 : Uint64 -> Uint128 =
  fun (x : Uint64) =>
    let ox128 = builtin to_uint128 x in
    match ox128 with
    | None => let zero = Uint128 0 in builtin div zero zero
    | Some x128 => x128
    end

let int256_to_uint128 : Int256 -> Uint128 =
  fun (x : Int256) =>
    let ox128 = builtin to_uint128 x in
    match ox128 with
    | None => let zero = Uint128 0 in builtin div zero zero
    | Some x128 => x128
    end

let is_admin_or_owner : (Map ByStr20 Bool) -> ByStr20 -> ByStr20 -> Bool =
  fun (administrators : Map ByStr20 Bool) =>
    fun (owner : ByStr20) =>
      fun (sender : ByStr20) =>
        let is_admin = builtin contains administrators sender in
        let is_owner = builtin eq sender owner in
        let allowed = orb is_admin is_owner in
        match allowed with
        | True => True
        | False => False
        end

let update_reward_param : RewardParam -> Uint64 -> RewardParam =
  fun (reward_param : RewardParam) =>
    fun (current_timestamp : Uint64) =>
      match reward_param with
      | RewardParam apr treasury_fee start_timestamp end_timestamp =>
        let zero_timestamp = Uint64 0 in
        let is_eq_timestamp_zero = builtin eq end_timestamp zero_timestamp in
        match is_eq_timestamp_zero with
        | True => RewardParam apr treasury_fee start_timestamp current_timestamp
        | False => RewardParam apr treasury_fee start_timestamp end_timestamp
        end
      end

let update_all_reward_params :
  forall 'A. (List RewardParam) -> Uint64 -> List RewardParam =
  tfun 'A =>
    fun (l : List RewardParam) =>
      fun (current_timestamp : Uint64) =>
        let foldl = @list_foldl (RewardParam) (List RewardParam) in
        let init = Nil {(RewardParam)} in
        let iter =
          fun (reward_params_list : List RewardParam) =>
            fun (reward_param : RewardParam) =>
              let updated_reward_param =
                update_reward_param reward_param current_timestamp
              in
              Cons {(RewardParam)} updated_reward_param reward_params_list
        in
        foldl iter init l

let is_timestamp_let : Uint64 -> Uint64 -> Bool =
  fun (ts1 : Uint64) =>
    fun (ts2 : Uint64) =>
      let is_ts1_le_ts2 = uint64_lt ts1 ts2 in
      let is_ts1_eq_ts2 = builtin eq ts1 ts2 in
      orb is_ts1_le_ts2 is_ts1_eq_ts2

let get_time_difference : Uint128 -> Uint64 -> RewardParam -> Uint64 -> Uint64 =
  fun (staked_amount : Uint128) =>
    fun (staked_timestamp : Uint64) =>
      fun (reward_param : RewardParam) =>
        fun (current_timestamp : Uint64) =>
          match reward_param with
          | RewardParam apr treasury_fee start_timestamp end_timestamp =>
            let zero_timestamp = Uint64 0 in
            let microseconds = Uint64 1000000 in
            let is_eq_block_zero = builtin eq end_timestamp zero_timestamp in
            match is_eq_block_zero with
            | True =>
              let is_staked_timestamp_leq_start_timestamp =
                is_timestamp_let staked_timestamp start_timestamp
              in
              match is_staked_timestamp_leq_start_timestamp with
              | True =>
                let diff = builtin sub current_timestamp start_timestamp in
                builtin div diff microseconds
              | False =>
                let diff = builtin sub current_timestamp staked_timestamp in
                builtin div diff microseconds
              end
            | False =>
              let is_staked_timestamp_leq_end_timestamp =
                is_timestamp_let staked_timestamp end_timestamp
              in
              match is_staked_timestamp_leq_end_timestamp with
              | True =>
                let is_staked_timestamp_leq_start_timestamp =
                  is_timestamp_let staked_timestamp start_timestamp
                in
                match is_staked_timestamp_leq_start_timestamp with
                | True =>
                  let diff = builtin sub end_timestamp start_timestamp in
                  builtin div diff microseconds
                | False =>
                  let diff = builtin sub end_timestamp staked_timestamp in
                  builtin div diff microseconds
                end
              | False => zero_timestamp
              end
            end
          end

let uint128_to_uint256 : Uint128 -> Uint256 =
  fun (x : Uint128) =>
    let ox256 = builtin to_uint256 x in
    match ox256 with
    | None => let zero = Uint256 0 in builtin div zero zero
    | Some x256 => x256
    end

let muldiv : Uint128 -> Uint128 -> Uint128 -> Uint128 -> Uint256 -> Uint128 =
  fun (w : Uint128) =>
    fun (x : Uint128) =>
      fun (y : Uint128) =>
        fun (z : Uint128) =>
          fun (f : Uint256) =>
            let w256 = uint128_to_uint256 w in
            let x256 = uint128_to_uint256 x in
            let y256 = uint128_to_uint256 y in
            let z256 = uint128_to_uint256 z in
            let w_mul_x256 = builtin mul w256 x256 in
            let w_mul_x_mul_y256 = builtin mul w_mul_x256 y256 in
            let w_mul_x_mul_y256_div_z256 = builtin div w_mul_x_mul_y256 z256 in
            let res256 = builtin div w_mul_x_mul_y256_div_z256 f in
            let ores128 = builtin to_uint128 res256 in
            match ores128 with
            | None =>
              let max_uint128 = Uint128 340282366920938463463374607431768211455
              in
              let fourtytwo128 = Uint128 42 in
              builtin mul max_uint128 fourtytwo128
            | Some res128 => res128
            end

let calculate_treasury_fee_amt : Uint128 -> Uint256 -> Uint128 -> Uint128 =
  fun (treasury_fee : Uint128) =>
    fun (fee_denom : Uint256) =>
      fun (amount : Uint128) =>
        let tf256 = uint128_to_uint256 treasury_fee in
        let amt256 = uint128_to_uint256 amount in
        let tf_mul_amt = builtin mul tf256 amt256 in
        let res256 = builtin div tf_mul_amt fee_denom in
        let ores128 = builtin to_uint128 res256 in
        match ores128 with
        | None =>
          let max_uint128 = Uint128 340282366920938463463374607431768211455 in
          let fourtytwo128 = Uint128 42 in
          builtin mul max_uint128 fourtytwo128
        | Some res128 => res128
        end

let calculate_rewards :
  forall 'A.
    (List RewardParam) ->
    Uint128 ->
    Uint64 ->
    Uint64 ->
    Uint128 ->
    Uint256 ->
    RewardResult =
  tfun 'A =>
    fun (l : List RewardParam) =>
      fun (staked_amount : Uint128) =>
        fun (staked_timestamp : Uint64) =>
          fun (current_timestamp : Uint64) =>
            fun (seconds_per_year : Uint128) =>
              fun (fee_denom : Uint256) =>
                let foldl = @list_foldl (RewardParam) (RewardResult) in
                let init = RewardResult zero zero in
                let iter =
                  fun (rewards : RewardResult) =>
                    fun (reward_param : RewardParam) =>
                      match reward_param with
                      | RewardParam apr treasury_fee start_block end_block =>
                        let time_diff_ui64 =
                          get_time_difference
                            staked_amount staked_timestamp reward_param current_timestamp
                        in
                        let time_diff = uint64_to_uint128 time_diff_ui64 in
                        let res_total =
                          muldiv
                            staked_amount time_diff apr seconds_per_year fee_denom
                        in
                        let treasury_fee_amt =
                          calculate_treasury_fee_amt
                            treasury_fee fee_denom res_total
                        in
                        let res = builtin sub res_total treasury_fee_amt in
                        match rewards with
                        | RewardResult curr_rewards_count curr_treasury_fee_amt =>
                          let new_rewards_count =
                            builtin add curr_rewards_count res
                          in
                          let new_treasury_fee_amt =
                            builtin add curr_treasury_fee_amt treasury_fee_amt
                          in
                          RewardResult new_rewards_count new_treasury_fee_amt
                        end
                      end
                in
                foldl iter init l

let portion =
  fun (amount : Uint128) =>
    fun (bps : Uint128) =>
      let max_bps = Uint128 10000 in
      let x = builtin div max_bps bps in
      let result = builtin div amount x in
      result

let option_value =
  tfun 'A =>
    fun (default : 'A) =>
      fun (maybe_val : Option 'A) =>
        match maybe_val with
        | Some v => v
        | None => default
        end

let option_timestamp = @option_value (Uint64)

let get_prev_bnum =
  fun (cur_blk : BNum) =>
    let one_bnum = BNum 1 in
    let zero_block = BNum 0 in
    let prev_block = builtin bsub cur_blk one_bnum in
    let prev_block_uint128 = int256_to_uint128 prev_block in
    builtin badd zero_block prev_block_uint128


contract StakingContract
  (
    initial_owner : ByStr20,
    initial_staking_token_address :
      ByStr20 with contract
        field allowances : Map ByStr20 (Map ByStr20 Uint128),
        field balances : Map ByStr20 Uint128,
        field total_supply : Uint128
      end
  )


field owner : ByStr20 = initial_owner

field staking_token_address : ByStr20 = initial_staking_token_address

field pending_owner : ByStr20 = zil_address

field paused : Bool = True

field reward_pairs : Map ByStr20 (List RewardParam) =
  Emp (ByStr20) (List RewardParam)

field stakes : Map ByStr20 Stake = Emp (ByStr20) (Stake)

field rewards : Map ByStr20 (Map ByStr20 Uint128) =
  Emp (ByStr20) (Map ByStr20 Uint128)

field administrators : Map ByStr20 Bool = Emp (ByStr20) (Bool)

field treasury_balances : Map ByStr20 Uint128 = Emp (ByStr20) (Uint128)

field treasury_fees_address : ByStr20 = initial_owner

field penalty_fee_balances : Uint128 = zero

field total_staked_amount : Uint128 = zero

procedure Throw (err : Error)
  e = make_error err;
  throw e
end

procedure EnsureContractIsNotPaused ()
  paused_tmp <- paused;
  match paused_tmp with
  | False =>
  | True =>
    err = ContractFrozenFailurePaused;
    Throw err
  end
end

procedure EnsureContractIsPaused ()
  paused_tmp <- paused;
  match paused_tmp with
  | False =>
    err = ContractFrozenFailureNotPaused;
    Throw err
  | True =>
  end
end

procedure EnsureSenderIsOwner (initiator : ByStr20)
  current_owner <- owner;
  is_owner = builtin eq initiator current_owner;
  match is_owner with
  | True =>
  | False =>
    err = CodeNotOwner;
    Throw err
  end
end

procedure EnsureSenderIsAdminOrOwner (address : ByStr20)
  admins <- administrators;
  current_owner <- owner;
  check_allowed = is_admin_or_owner admins current_owner address;
  match check_allowed with
  | True =>
  | False =>
    err = Unauthorized;
    Throw err
  end
end

procedure EnsureNotStakeToken (address : ByStr20)
  stake_token_addr <- staking_token_address;
  is_same = builtin eq address stake_token_addr;
  match is_same with
  | True =>
    err = NotAllowedToWithdrawStakeTokens;
    Throw err
  | False =>
  end
end

procedure RequireValidBPS (val_bps : Uint128)
  is_gte_min = uint128_ge val_bps min_bps;
  is_lte_max = uint128_le val_bps max_bps;
  is_valid = andb is_gte_min is_lte_max;
  match is_valid with
  | True =>
  | False =>
    error = InvalidBPSError;
    Throw error
  end
end

procedure Send (coins : Coins, to_address : ByStr20)
  match coins with
  | Coins denom amount =>
    match denom with
    | Zil =>
      msg = { _tag : "AddFunds"; _recipient : to_address; _amount : amount };
      msgs = one_msg msg;
      send msgs
    | Token token =>
      msg_to_token =
        {
          _tag : "Transfer";
          _recipient : token;
          _amount : zero;
          to : to_address;
          amount : amount
        };
      msgs = one_msg msg_to_token;
      send msgs
    end
  end
end

procedure Receive (coins : Coins, initiator : ByStr20)
  EnsureContractIsNotPaused;
  match coins with
  | Coins denom amount =>
    match denom with
    | Zil =>
      needs_refund = uint128_gt _amount amount;
      accept;
      match needs_refund with
      | True =>
        refund =
          let refund_amount = builtin sub _amount amount in
          Coins zil refund_amount;
        Send refund initiator
      | False =>
      end
    | Token token =>
      msg_to_token =
        {
          _tag : "TransferFrom";
          _recipient : token;
          _amount : zero;
          from : initiator;
          to : _this_address;
          amount : amount
        };
      msgs = one_msg msg_to_token;
      send msgs
    end
  end
end

procedure UpdateTreasuryFeeAmount (reward_token : ByStr20, amount : Uint128)
  is_amount_eq_zero = builtin eq amount zero;
  match is_amount_eq_zero with
  | False =>
    maybe_treasury_fee_amount <- treasury_balances[reward_token];
    match maybe_treasury_fee_amount with
    | Some curr_amount =>
      new_amount = builtin add curr_amount amount;
      treasury_balances[reward_token] := new_amount;
      e =
        {
          _eventname : "UpdateTreasuryFeeAmountWithPreviousValueSuccess";
          sender : _origin;
          reward_token : reward_token;
          old_amount : curr_amount;
          new_amount : new_amount;
          difference : amount
        };
      event e
    | None =>
      treasury_balances[reward_token] := amount;
      e =
        {
          _eventname : "UpdateRewardsAmountFirstClaimSuccess";
          sender : _origin;
          reward_token : reward_token;
          new_amount : amount
        };
      event e
    end
  | True =>
  end
end

procedure UpdateRewardsAmount (reward_token : ByStr20, amount : Uint128)
  is_amount_eq_zero = builtin eq amount zero;
  match is_amount_eq_zero with
  | False =>
    maybe_rewards_amount <- rewards[reward_token][_origin];
    match maybe_rewards_amount with
    | Some curr_amount =>
      new_amount = builtin add curr_amount amount;
      rewards[reward_token][_origin] := new_amount;
      e =
        {
          _eventname : "UpdateRewardsAmountWithPreviousValueSuccess";
          sender : _origin;
          reward_token : reward_token;
          old_amount : curr_amount;
          new_amount : new_amount;
          difference : amount
        };
      event e
    | None =>
      rewards[reward_token][_origin] := amount;
      e =
        {
          _eventname : "UpdateRewardsAmountFirstClaimSuccess";
          sender : _origin;
          reward_token : reward_token;
          new_amount : amount
        };
      event e
    end
  | True =>
  end
end

procedure UpdateRewards (reward_token : ByStr20, reward_res : RewardResult)
  match reward_res with
  | RewardResult total_rewards treasury_fee_amt =>
    UpdateRewardsAmount reward_token total_rewards;
    UpdateTreasuryFeeAmount reward_token treasury_fee_amt
  end
end

procedure DoClaimRewards (reward_pair : Pair ByStr20 (List RewardParam))
  maybe_stake <- stakes[_origin];
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  match maybe_stake with
  | Some stake =>
    match stake with
    | Stake staked_amount staked_timestamp end_block penalty_fee =>
      reward_token_address =
        let fst_reward_token_address = @fst (ByStr20) (List RewardParam) in
        fst_reward_token_address reward_pair;
      reward_param_list =
        let snd_reward_param_list = @snd (ByStr20) (List RewardParam) in
        snd_reward_param_list reward_pair;
      calculate_rewards_fun = @calculate_rewards (List RewardParam);
      maybe_running_interest_amount <- rewards[reward_token_address][_origin];
      match maybe_running_interest_amount with
      | Some running_interest_amount =>
        total_amount = builtin add staked_amount running_interest_amount;
        reward_res =
          calculate_rewards_fun
            reward_param_list total_amount staked_timestamp current_timestamp seconds_per_year fee_denom;
        UpdateRewards reward_token_address reward_res
      | None =>
        reward_res =
          calculate_rewards_fun
            reward_param_list staked_amount staked_timestamp current_timestamp seconds_per_year fee_denom;
        UpdateRewards reward_token_address reward_res
      end
    end
  | None =>
    err = NoStakeFoundBySender;
    Throw err
  end
end

procedure DoRemoveRewardToken (reward_token_address : ByStr20)
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  maybe_reward_params_list <- reward_pairs[reward_token_address];
  match maybe_reward_params_list with
  | Some reward_params_list =>
    update_all_reward_params_fun = @update_all_reward_params (List RewardParam);
    updated_reward_params_list =
      update_all_reward_params_fun reward_params_list current_timestamp;
    reward_pairs[reward_token_address] := updated_reward_params_list
  | None =>
    err = RewardTokenNotFound;
    Throw err
  end
end

procedure DoRemoveAllRewardTokens
  (reward_pair : Pair ByStr20 (List RewardParam))
  reward_token_address =
    let fst_reward_token_address = @fst (ByStr20) (List RewardParam) in
    fst_reward_token_address reward_pair;
  DoRemoveRewardToken reward_token_address
end

procedure DoWithdrawRewards (reward_pair : Pair ByStr20 (List RewardParam))
  reward_token_address =
    let fst_reward_token_address = @fst (ByStr20) (List RewardParam) in
    fst_reward_token_address reward_pair;
  maybe_reward_token_amt <- rewards[reward_token_address][_origin];
  match maybe_reward_token_amt with
  | Some reward_token_amt =>
    is_zil = builtin eq reward_token_address zil_address;
    match is_zil with
    | True =>
      stake_token_addr <- staking_token_address;
      is_staked_token_same_as_withdraw =
        builtin eq reward_token_address stake_token_addr;
      match is_staked_token_same_as_withdraw with
      | True =>
        balances <- _balance;
        total_staked <- total_staked_amount;
        available_bal_to_withdraw = builtin sub balances total_staked;
        is_valid_withdrawal_amount =
          uint128_le reward_token_amt available_bal_to_withdraw;
        match is_valid_withdrawal_amount with
        | True =>
          zils_out = Coins zil reward_token_amt;
          Send zils_out _origin
        | False =>
          err = CodeInsufficientFunds;
          Throw err
        end
      | False =>
        zils_out = Coins zil reward_token_amt;
        Send zils_out _origin
      end
    | False =>
      stake_token_addr <- staking_token_address;
      is_staked_token_same_as_withdraw =
        builtin eq reward_token_address stake_token_addr;
      match is_staked_token_same_as_withdraw with
      | True =>
        balances <-& initial_staking_token_address.balances[_this_address];
        contract_balance = get_value balances;
        total_staked <- total_staked_amount;
        available_bal_to_withdraw = builtin sub contract_balance total_staked;
        is_valid_withdrawal_amount =
          uint128_le reward_token_amt available_bal_to_withdraw;
        match is_valid_withdrawal_amount with
        | True =>
          reward_token = Token reward_token_address;
          tokens_out = Coins reward_token reward_token_amt;
          Send tokens_out _origin
        | False =>
          err = CodeInsufficientFunds;
          Throw err
        end
      | False =>
        reward_token = Token reward_token_address;
        tokens_out = Coins reward_token reward_token_amt;
        Send tokens_out _origin
      end
    end;
    delete rewards[reward_token_address][_origin];
    e =
      {
        _eventname : "WithdrawRewardsSuccess";
        sender : _origin;
        reward_token : reward_token_address;
        amount : reward_token_amt
      };
    event e
  | None =>
    e =
      {
        _eventname : "WithdrawRewardsSuccess";
        sender : _origin;
        reward_token : reward_token_address;
        amount : zero
      };
    event e
  end
end

transition AddStake
  (amount : Uint128, expiration_time : Uint64, penalty_fee_bps : Uint128)
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  maybe_stake <- stakes[_origin];
  RequireValidBPS penalty_fee_bps;
  token_address <- staking_token_address;
  token = Token token_address;
  tokens_in = Coins token amount;
  Receive tokens_in _origin;
  match maybe_stake with
  | Some stake =>
    match stake with
    | Stake staked_amount timestamp end_timestamp penalty_fee =>
      curent_reward_pairs <- reward_pairs;
      rewards_list = builtin to_list curent_reward_pairs;
      forall rewards_list DoClaimRewards;
      total_amount = builtin add staked_amount amount;
      updated_stake =
        Stake total_amount current_timestamp end_timestamp penalty_fee;
      stakes[_origin] := updated_stake;
      total_staked <- total_staked_amount;
      new_total_staked = builtin add total_staked amount;
      total_staked_amount := new_total_staked
    end
  | None =>
    stake = Stake amount current_timestamp expiration_time penalty_fee_bps;
    stakes[_origin] := stake;
    total_staked <- total_staked_amount;
    new_total_staked = builtin add total_staked amount;
    total_staked_amount := new_total_staked
  end
end

transition RemoveStake (amount : Uint128)
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  maybe_stake <- stakes[_origin];
  match maybe_stake with
  | Some (Stake staked_amount staked_timestamp end_timestamp penalty_fee) =>
    is_amount_less_than_staked_amount = builtin lt amount staked_amount;
    is_amount_equal_to_staked_amount = builtin eq amount staked_amount;
    is_amount_less_or_equal_to_staked_amount =
      orb is_amount_less_than_staked_amount is_amount_equal_to_staked_amount;
    match is_amount_less_or_equal_to_staked_amount with
    | True =>
      curent_reward_pairs <- reward_pairs;
      rewards_list = builtin to_list curent_reward_pairs;
      forall rewards_list DoClaimRewards;
      is_lt_curr_timestamp = uint64_lt current_timestamp end_timestamp;
      match is_lt_curr_timestamp with
      | True =>
        fee_bps = portion amount penalty_fee;
        new_amount = builtin sub amount fee_bps;
        penalty_fee_amount <- penalty_fee_balances;
        new_penalty_fee_amount = builtin add penalty_fee_amount fee_bps;
        penalty_fee_balances := new_penalty_fee_amount;
        token_address <- staking_token_address;
        staked_token = Token token_address;
        output = Coins staked_token new_amount;
        Send output _origin
      | False =>
        token_address <- staking_token_address;
        staked_token = Token token_address;
        output = Coins staked_token amount;
        Send output _origin
      end;
      remaining_amount = builtin sub staked_amount amount;
      is_remaining_amount_eq_zero = builtin eq remaining_amount zero;
      match is_remaining_amount_eq_zero with
      | True => delete stakes[_origin]
      | False =>
        updated_stake =
          Stake remaining_amount current_timestamp end_timestamp penalty_fee;
        stakes[_origin] := updated_stake
      end;
      total_staked <- total_staked_amount;
      new_total_staked = builtin sub total_staked amount;
      total_staked_amount := new_total_staked
    | False =>
      err = AmountGreaterThanStakedAmount;
      Throw err
    end
  | None =>
    err = NoStakeFoundBySender;
    Throw err
  end
end

transition ClaimRewards ()
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  maybe_stake <- stakes[_origin];
  match maybe_stake with
  | Some (Stake staked_amount staked_timestamp end_timestamp penalty_fee) =>
    curent_reward_pairs <- reward_pairs;
    rewards_list = builtin to_list curent_reward_pairs;
    forall rewards_list DoClaimRewards;
    forall rewards_list DoWithdrawRewards;
    updated_stake =
      Stake staked_amount current_timestamp end_timestamp penalty_fee;
    stakes[_origin] := updated_stake
  | None =>
    curent_reward_pairs <- reward_pairs;
    rewards_list = builtin to_list curent_reward_pairs;
    forall rewards_list DoWithdrawRewards
  end
end

transition AddRewardToken
  (reward_token_address : ByStr20, apr : Uint128, treasury_fee : Uint128)
  EnsureSenderIsAdminOrOwner _sender;
  current_block <-& BLOCKNUMBER;
  prev_block = get_prev_bnum current_block;
  ts <-& TIMESTAMP(prev_block);
  zero_64 = Uint64 0;
  current_timestamp = option_timestamp zero_64 ts;
  end_timestamp = Uint64 0;
  reward_param = RewardParam apr treasury_fee current_timestamp end_timestamp;
  maybe_reward_params_list <- reward_pairs[reward_token_address];
  match maybe_reward_params_list with
  | Some reward_params_list =>
    update_all_reward_params_fun = @update_all_reward_params (List RewardParam);
    updated_reward_params_list =
      update_all_reward_params_fun reward_params_list current_timestamp;
    reward_params_list_new =
      Cons {(RewardParam)} reward_param updated_reward_params_list;
    reward_pairs[reward_token_address] := reward_params_list_new
  | None =>
    reward_params_list = Nil {(RewardParam)};
    reward_params_list_new =
      Cons {(RewardParam)} reward_param reward_params_list;
    reward_pairs[reward_token_address] := reward_params_list_new
  end
end

transition RemoveRewardToken (reward_token_address : ByStr20)
  EnsureSenderIsAdminOrOwner _sender;
  DoRemoveRewardToken reward_token_address
end

transition RemoveAllRewardTokens ()
  EnsureSenderIsAdminOrOwner _sender;
  curent_reward_pairs <- reward_pairs;
  rewards_list = builtin to_list curent_reward_pairs;
  forall rewards_list DoRemoveAllRewardTokens
end

transition Pause ()
  EnsureSenderIsAdminOrOwner _sender;
  paused := bool_active
end

transition UnPause ()
  EnsureSenderIsAdminOrOwner _sender;
  paused := bool_inactive
end

transition AddAdmin (address : ByStr20)
  EnsureSenderIsOwner _sender;
  administrators[address] := true;
  e = { _eventname : "AddAdminSuccess"; addressAdded : address };
  event e
end

transition RemoveAdmin (address : ByStr20)
  EnsureSenderIsOwner _sender;
  delete administrators[address];
  e = { _eventname : "RemoveAdminSuccess"; address : address };
  event e
end

transition TransferOwnership (new_owner : ByStr20)
  EnsureSenderIsOwner _sender;
  existing_owner <- owner;
  new_owner_is_existing_owner = builtin eq new_owner existing_owner;
  match new_owner_is_existing_owner with
  | True =>
    e = { _exception : "ExistingOwner" };
    throw e
  | False => pending_owner := new_owner
  end
end

transition AcceptPendingOwnership ()
  new_owner <- pending_owner;
  sender_is_pending_owner = builtin eq _sender new_owner;
  match sender_is_pending_owner with
  | False =>
    e = { _exception : "InvalidSender" };
    throw e
  | True =>
    owner := new_owner;
    pending_owner := zil_address;
    e = { _eventname : "OwnershipTransferred"; owner : new_owner };
    event e
  end
end

transition WithdrawTokens (token_address : ByStr20, token_amount : Uint128)
  EnsureSenderIsOwner _sender;
  stake_token_addr <- staking_token_address;
  is_staked_token_same_as_withdraw = builtin eq token_address stake_token_addr;
  match is_staked_token_same_as_withdraw with
  | True =>
    balances <-& initial_staking_token_address.balances[_this_address];
    contract_balance = get_value balances;
    total_staked <- total_staked_amount;
    available_bal_to_withdraw = builtin sub contract_balance total_staked;
    is_valid_withdrawal_amount =
      uint128_le token_amount available_bal_to_withdraw;
    match is_valid_withdrawal_amount with
    | True =>
      reward_token = Token token_address;
      tokens_out = Coins reward_token token_amount;
      Send tokens_out _sender
    | False =>
      err = CodeInsufficientFunds;
      Throw err
    end
  | False =>
    reward_token = Token token_address;
    tokens_out = Coins reward_token token_amount;
    Send tokens_out _sender
  end
end

transition WithdrawZils (zil_amount : Uint128)
  EnsureSenderIsAdminOrOwner _sender;
  zils_out = Coins zil zil_amount;
  Send zils_out _sender
end

transition Deposit (token_address : ByStr20, token_amount : Uint128)
  EnsureSenderIsAdminOrOwner _sender;
  token = Token token_address;
  tokens_in = Coins token token_amount;
  Receive tokens_in _sender
end

transition TransferFromSuccessCallBack
  (initiator : ByStr20, sender : ByStr20, recipient : ByStr20, amount : Uint128)

end

transition TransferSuccessCallBack
  (sender : ByStr20, recipient : ByStr20, amount : Uint128)

end

transition RecipientAcceptTransferFrom
  (initiator : ByStr20, sender : ByStr20, recipient : ByStr20, amount : Uint128)
  is_valid_transfer_to_self =
    let self_triggered = builtin eq initiator _this_address in
    let is_transfer_to_self = builtin eq recipient _this_address in
    andb self_triggered is_transfer_to_self;
  match is_valid_transfer_to_self with
  | False =>
    e = { _exception : "InvalidInvocation" };
    throw e
  | True =>
  end
end

transition AddFunds ()
  accept
end

transition RecipientAcceptTransfer
  (sender : ByStr20, recipient : ByStr20, amount : Uint128)

end