nym-pool-contract-common 1.20.4

Common library for the Nym Pool contract
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Coin};

pub type GranterAddress = Addr;
pub type GranteeAddress = Addr;

pub use grants::*;
pub use query_responses::*;

#[cw_serde]
pub struct TransferRecipient {
    pub recipient: String,
    pub amount: Coin,
}

pub mod grants {
    use crate::utils::ensure_unix_timestamp_not_in_the_past;
    use crate::{GranteeAddress, GranterAddress, NymPoolContractError};
    use cosmwasm_schema::cw_serde;
    use cosmwasm_std::{Addr, Coin, Env, Timestamp, Uint128};
    use std::cmp::min;

    #[cw_serde]
    pub struct GranterInformation {
        // realistically this is always going to be the contract admin,
        // but let's keep this metadata regardless just in case it ever changes,
        // such as we create a granter controlled by validator multisig or governance
        pub created_by: Addr,
        pub created_at_height: u64,
    }

    #[cw_serde]
    pub struct Grant {
        pub granter: GranterAddress,
        pub grantee: GranteeAddress,
        pub granted_at_height: u64,
        pub allowance: Allowance,
    }

    #[cw_serde]
    pub enum Allowance {
        Basic(BasicAllowance),
        ClassicPeriodic(ClassicPeriodicAllowance),
        CumulativePeriodic(CumulativePeriodicAllowance),
        Delayed(DelayedAllowance),
    }

    impl From<BasicAllowance> for Allowance {
        fn from(value: BasicAllowance) -> Self {
            Allowance::Basic(value)
        }
    }

    impl From<ClassicPeriodicAllowance> for Allowance {
        fn from(value: ClassicPeriodicAllowance) -> Self {
            Allowance::ClassicPeriodic(value)
        }
    }

    impl From<CumulativePeriodicAllowance> for Allowance {
        fn from(value: CumulativePeriodicAllowance) -> Self {
            Allowance::CumulativePeriodic(value)
        }
    }

    impl From<DelayedAllowance> for Allowance {
        fn from(value: DelayedAllowance) -> Self {
            Allowance::Delayed(value)
        }
    }

    impl Allowance {
        pub fn expired(&self, env: &Env) -> bool {
            self.basic().expired(env)
        }

        pub fn basic(&self) -> &BasicAllowance {
            match self {
                Allowance::Basic(allowance) => allowance,
                Allowance::ClassicPeriodic(allowance) => &allowance.basic,
                Allowance::CumulativePeriodic(allowance) => &allowance.basic,
                Allowance::Delayed(allowance) => &allowance.basic,
            }
        }

        pub fn basic_mut(&mut self) -> &mut BasicAllowance {
            match self {
                Allowance::Basic(allowance) => allowance,
                Allowance::ClassicPeriodic(allowance) => &mut allowance.basic,
                Allowance::CumulativePeriodic(allowance) => &mut allowance.basic,
                Allowance::Delayed(allowance) => &mut allowance.basic,
            }
        }

        pub fn expiration(&self) -> Option<Timestamp> {
            let expiration_unix = match self {
                Allowance::Basic(allowance) => allowance.expiration_unix_timestamp,
                Allowance::ClassicPeriodic(allowance) => allowance.basic.expiration_unix_timestamp,
                Allowance::CumulativePeriodic(allowance) => {
                    allowance.basic.expiration_unix_timestamp
                }
                Allowance::Delayed(allowance) => allowance.basic.expiration_unix_timestamp,
            };

            expiration_unix.map(Timestamp::from_seconds)
        }

        /// Perform validation of a new grant that's to be created
        pub fn validate_new(&self, env: &Env, denom: &str) -> Result<(), NymPoolContractError> {
            // 1. perform validation on the inner, basic, allowance
            self.basic().validate(env, denom)?;

            // 2. perform additional validation specific to each variant
            match self {
                // we already validated basic allowance
                Allowance::Basic(_) => Ok(()),
                Allowance::ClassicPeriodic(allowance) => allowance.validate_new_inner(denom),
                Allowance::CumulativePeriodic(allowance) => allowance.validate_new_inner(denom),
                Allowance::Delayed(allowance) => allowance.validate_new_inner(env),
            }
        }

        /// Updates initial state of this allowance settings things such as period reset timestamps.
        pub fn set_initial_state(&mut self, env: &Env) {
            match self {
                // nothing to do for the basic allowance
                Allowance::Basic(_) => {}
                Allowance::ClassicPeriodic(allowance) => allowance.set_initial_state(env),
                Allowance::CumulativePeriodic(allowance) => allowance.set_initial_state(env),
                // nothing to do for the delayed allowance
                Allowance::Delayed(_) => {}
            }
        }

        pub fn try_update_state(&mut self, env: &Env) {
            match self {
                // nothing to do for the basic allowance
                Allowance::Basic(_) => {}
                Allowance::ClassicPeriodic(allowance) => allowance.try_update_state(env),
                Allowance::CumulativePeriodic(allowance) => allowance.try_update_state(env),
                // nothing to do for the delayed allowance
                Allowance::Delayed(_) => {}
            }
        }

        pub fn within_spendable_limits(&self, amount: &Coin) -> bool {
            match self {
                Allowance::Basic(allowance) => allowance.within_spendable_limits(amount),
                Allowance::ClassicPeriodic(allowance) => allowance.within_spendable_limits(amount),
                Allowance::CumulativePeriodic(allowance) => {
                    allowance.within_spendable_limits(amount)
                }
                Allowance::Delayed(allowance) => allowance.within_spendable_limits(amount),
            }
        }

        // check whether given the current allowance state, the provided amount could be spent
        // note: it's responsibility of the caller to call `try_update_state` before the call.
        pub fn ensure_can_spend(
            &self,
            env: &Env,
            amount: &Coin,
        ) -> Result<(), NymPoolContractError> {
            match self {
                Allowance::Basic(allowance) => allowance.ensure_can_spend(env, amount),
                Allowance::ClassicPeriodic(allowance) => allowance.ensure_can_spend(env, amount),
                Allowance::CumulativePeriodic(allowance) => allowance.ensure_can_spend(env, amount),
                Allowance::Delayed(allowance) => allowance.ensure_can_spend(env, amount),
            }
        }

        pub fn try_spend(&mut self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            self.try_update_state(env);

            match self {
                Allowance::Basic(allowance) => allowance.try_spend(env, amount),
                Allowance::ClassicPeriodic(allowance) => allowance.try_spend(env, amount),
                Allowance::CumulativePeriodic(allowance) => allowance.try_spend(env, amount),
                Allowance::Delayed(allowance) => allowance.try_spend(env, amount),
            }
        }

        pub fn increase_spend_limit(&mut self, amount: Uint128) {
            if let Some(ref mut limit) = self.basic_mut().spend_limit {
                limit.amount += amount
            }
        }

        pub fn is_used_up(&self) -> bool {
            let Some(ref limit) = self.basic().spend_limit else {
                return false;
            };
            limit.amount.is_zero()
        }
    }

    /// BasicAllowance is an allowance with a one-time grant of coins
    /// that optionally expires. The grantee can use up to SpendLimit to cover fees.
    #[cw_serde]
    pub struct BasicAllowance {
        /// spend_limit specifies the maximum amount of coins that can be spent
        /// by this allowance and will be updated as coins are spent. If it is
        /// empty, there is no spend limit and any amount of coins can be spent.
        pub spend_limit: Option<Coin>,

        /// expiration specifies an optional time when this allowance expires
        pub expiration_unix_timestamp: Option<u64>,
    }

    impl BasicAllowance {
        pub fn unlimited() -> BasicAllowance {
            BasicAllowance {
                spend_limit: None,
                expiration_unix_timestamp: None,
            }
        }

        pub fn validate(&self, env: &Env, denom: &str) -> Result<(), NymPoolContractError> {
            // expiration shouldn't be in the past.
            if let Some(expiration) = self.expiration_unix_timestamp {
                ensure_unix_timestamp_not_in_the_past(expiration, env)?;
            }

            // if spend limit is set, it must use the same denomination as the underlying pool
            if let Some(ref spend_limit) = self.spend_limit {
                if spend_limit.denom != denom {
                    return Err(NymPoolContractError::InvalidDenom {
                        expected: denom.to_string(),
                        got: spend_limit.denom.to_string(),
                    });
                }

                if spend_limit.amount.is_zero() {
                    return Err(NymPoolContractError::ZeroAmount);
                }
            }

            Ok(())
        }

        pub fn expired(&self, env: &Env) -> bool {
            let Some(expiration) = self.expiration_unix_timestamp else {
                return false;
            };
            let current_unix_timestamp = env.block.time.seconds();

            expiration < current_unix_timestamp
        }

        fn within_spendable_limits(&self, amount: &Coin) -> bool {
            let Some(ref spend_limit) = self.spend_limit else {
                // if there's no spend limit then whatever the amount is, it's spendable
                return true;
            };

            spend_limit.amount >= amount.amount
        }

        fn ensure_can_spend(&self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            if self.expired(env) {
                return Err(NymPoolContractError::GrantExpired);
            }
            if !self.within_spendable_limits(amount) {
                return Err(NymPoolContractError::SpendingAboveAllowance);
            }
            Ok(())
        }

        fn try_spend(&mut self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            self.ensure_can_spend(env, amount)?;

            if let Some(ref mut spend_limit) = self.spend_limit {
                spend_limit.amount -= amount.amount;
            }
            Ok(())
        }
    }

    /// ClassicPeriodicAllowance extends BasicAllowance to allow for both a maximum cap,
    /// as well as a limit per time period.
    #[cw_serde]
    pub struct ClassicPeriodicAllowance {
        /// basic specifies a struct of `BasicAllowance`
        pub basic: BasicAllowance,

        /// period_duration_secs specifies the time duration in which period_spend_limit coins can
        /// be spent before that allowance is reset
        pub period_duration_secs: u64,

        /// period_spend_limit specifies the maximum number of coins that can be spent
        /// in the period
        pub period_spend_limit: Coin,

        /// period_can_spend is the number of coins left to be spent before the period_reset time
        // set by the contract during initialisation of the grant
        #[serde(default)]
        pub period_can_spend: Option<Coin>,

        /// period_reset is the time at which this period resets and a new one begins,
        /// it is calculated from the start time of the first transaction after the
        /// last period ended
        // set by the contract during initialisation of the grant
        #[serde(default)]
        pub period_reset_unix_timestamp: u64,
    }

    impl ClassicPeriodicAllowance {
        pub(super) fn validate_new_inner(&self, denom: &str) -> Result<(), NymPoolContractError> {
            // period duration shouldn't be zero
            if self.period_duration_secs == 0 {
                return Err(NymPoolContractError::ZeroAllowancePeriod);
            }

            // the denom for period spend limit must match the expected value
            if self.period_spend_limit.denom != denom {
                return Err(NymPoolContractError::InvalidDenom {
                    expected: denom.to_string(),
                    got: self.period_spend_limit.denom.to_string(),
                });
            }

            if self.period_spend_limit.amount.is_zero() {
                return Err(NymPoolContractError::ZeroAmount);
            }

            // if the basic spend limit is set, the period spend limit cannot be larger than it
            if let Some(ref basic_limit) = self.basic.spend_limit {
                if basic_limit.amount < self.period_spend_limit.amount {
                    return Err(NymPoolContractError::PeriodicGrantOverSpendLimit {
                        periodic: self.period_spend_limit.clone(),
                        total_limit: basic_limit.clone(),
                    });
                }
            }

            Ok(())
        }

        /// The value that can be spent in the period is the lesser of the basic spend limit
        /// and the period spend limit
        ///
        /// ```go
        ///    if _, isNeg := a.Basic.SpendLimit.SafeSub(a.PeriodSpendLimit...); isNeg && !a.Basic.SpendLimit.Empty() {
        ///        a.PeriodCanSpend = a.Basic.SpendLimit
        ///    } else {
        ///        a.PeriodCanSpend = a.PeriodSpendLimit
        ///    }
        /// ```
        fn determine_period_can_spend(&self) -> Coin {
            let Some(ref basic_limit) = self.basic.spend_limit else {
                // if there's no spend limit, there's nothing to compare against
                return self.period_spend_limit.clone();
            };

            if basic_limit.amount < self.period_spend_limit.amount {
                basic_limit.clone()
            } else {
                self.period_spend_limit.clone()
            }
        }

        pub(super) fn set_initial_state(&mut self, env: &Env) {
            self.try_update_state(env);
        }

        /// try_update_state will check if the period_reset_unix_timestamp has been hit. If not, it is a no-op.
        /// If we hit the reset period, it will top up the period_can_spend amount to
        /// min(period_spend_limit, basic.spend_limit) so it is never more than the maximum allowed.
        /// It will also update the period_reset_unix_timestamp.
        ///
        /// If we are within one period, it will update from the
        /// last period_reset (eg. if you always do one tx per day, it will always reset the same time)
        /// If we are more than one period out (eg. no activity in a week), reset is one period from the execution of this method
        pub fn try_update_state(&mut self, env: &Env) {
            if env.block.time.seconds() < self.period_reset_unix_timestamp {
                // we haven't yet reached the reset time
                return;
            }
            self.period_can_spend = Some(self.determine_period_can_spend());

            // If we are within the period, step from expiration (eg. if you always do one tx per day,
            // it will always reset the same time)
            // If we are more then one period out (eg. no activity in a week),
            // reset is one period from this time
            self.period_reset_unix_timestamp += self.period_duration_secs;
            if env.block.time.seconds() > self.period_duration_secs {
                self.period_reset_unix_timestamp =
                    env.block.time.seconds() + self.period_duration_secs;
            }
        }

        fn within_spendable_limits(&self, amount: &Coin) -> bool {
            let Some(ref available) = self.period_can_spend else {
                return false;
            };
            available.amount >= amount.amount
        }

        fn ensure_can_spend(&self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            if self.basic.expired(env) {
                return Err(NymPoolContractError::GrantExpired);
            }
            if !self.within_spendable_limits(amount) {
                return Err(NymPoolContractError::SpendingAboveAllowance);
            }
            Ok(())
        }

        fn try_spend(&mut self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            self.ensure_can_spend(env, amount)?;

            // deduct from both the current period and the max amount
            if let Some(ref mut spend_limit) = self.basic.spend_limit {
                spend_limit.amount -= amount.amount;
            }

            // SAFETY: initial `period_can_spend` value is always unconditionally set by the contract during
            // grant creation
            #[allow(clippy::unwrap_used)]
            let period_can_spend = self.period_can_spend.as_mut().unwrap();
            period_can_spend.amount -= amount.amount;

            Ok(())
        }
    }

    #[cw_serde]
    pub struct CumulativePeriodicAllowance {
        /// basic specifies a struct of `BasicAllowance`
        pub basic: BasicAllowance,

        /// period_duration_secs specifies the time duration in which spendable coins can
        /// be spent before that allowance is incremented
        pub period_duration_secs: u64,

        /// period_grant specifies the maximum number of coins that is granted per period
        pub period_grant: Coin,

        /// accumulation_limit is the maximum value the grants and accumulate to
        pub accumulation_limit: Option<Coin>,

        /// spendable is the number of coins left to be spent before additional grant is applied
        // set by the contract during initialisation of the grant
        #[serde(default)]
        pub spendable: Option<Coin>,

        /// last_grant_applied is the time at which last transaction associated with this allowance
        /// has been sent and `spendable` value has been adjusted
        // set by the contract during initialisation of the grant
        #[serde(default)]
        pub last_grant_applied_unix_timestamp: u64,
    }

    impl CumulativePeriodicAllowance {
        pub(super) fn validate_new_inner(&self, denom: &str) -> Result<(), NymPoolContractError> {
            // period duration shouldn't be zero
            if self.period_duration_secs == 0 {
                return Err(NymPoolContractError::ZeroAllowancePeriod);
            }

            // the denom for period grant must match the expected value
            if self.period_grant.denom != denom {
                return Err(NymPoolContractError::InvalidDenom {
                    expected: denom.to_string(),
                    got: self.period_grant.denom.to_string(),
                });
            }

            if self.period_grant.amount.is_zero() {
                return Err(NymPoolContractError::ZeroAmount);
            }

            // the period grant must not be larger than the total spend limit, if set
            if let Some(ref basic_limit) = self.basic.spend_limit {
                if basic_limit.amount < self.period_grant.amount {
                    return Err(NymPoolContractError::PeriodicGrantOverSpendLimit {
                        periodic: self.period_grant.clone(),
                        total_limit: basic_limit.clone(),
                    });
                }
            }

            if let Some(ref accumulation_limit) = self.accumulation_limit {
                // if set, the accumulation limit must not be smaller than the period grant
                if accumulation_limit.amount < self.period_grant.amount {
                    return Err(NymPoolContractError::AccumulationBelowGrantAmount {
                        accumulation: accumulation_limit.clone(),
                        periodic_grant: self.period_grant.clone(),
                    });
                }

                // if set, the denom for accumulation limit must match the expected value
                if accumulation_limit.denom != denom {
                    return Err(NymPoolContractError::InvalidDenom {
                        expected: denom.to_string(),
                        got: accumulation_limit.denom.to_string(),
                    });
                }

                // if set, the accumulation limit must not be larger than the total spend limit
                if let Some(ref basic_limit) = self.basic.spend_limit {
                    if basic_limit.amount < accumulation_limit.amount {
                        return Err(NymPoolContractError::AccumulationOverSpendLimit {
                            accumulation: accumulation_limit.clone(),
                            total_limit: basic_limit.clone(),
                        });
                    }
                }
            }

            Ok(())
        }

        pub(super) fn set_initial_state(&mut self, env: &Env) {
            self.last_grant_applied_unix_timestamp = env.block.time.seconds();

            // initially we can spend equivalent of a single grant
            self.spendable = Some(self.period_grant.clone())
        }

        #[inline]
        fn missed_periods(&self, env: &Env) -> u64 {
            (env.block.time.seconds() - self.last_grant_applied_unix_timestamp)
                % self.period_duration_secs
        }

        /// The value that can be spent is the last of the basic spend limit, the accumulation limit
        /// and number of missed periods multiplied by the period grant
        fn determine_spendable(&self, env: &Env) -> Coin {
            // SAFETY: initial `spendable` value is always unconditionally set by the contract during
            // grant creation
            #[allow(clippy::unwrap_used)]
            let spendable = self.spendable.as_ref().unwrap();

            let missed_periods = self.missed_periods(env);
            let mut max_spendable = spendable.clone();
            max_spendable.amount += Uint128::new(missed_periods as u128) * self.period_grant.amount;

            match (&self.basic.spend_limit, &self.accumulation_limit) {
                (Some(spend_limit), Some(accumulation_limit)) => {
                    let limit = min(spend_limit.amount, accumulation_limit.amount);
                    let amount = min(limit, max_spendable.amount);
                    Coin::new(amount, max_spendable.denom)
                }
                (None, Some(accumulation_limit)) => {
                    let amount = min(accumulation_limit.amount, max_spendable.amount);
                    Coin::new(amount, max_spendable.denom)
                }
                (Some(spend_limit), None) => {
                    let amount = min(spend_limit.amount, max_spendable.amount);
                    Coin::new(amount, max_spendable.denom)
                }
                (None, None) => max_spendable,
            }
        }

        /// try_update_state will check if we've rolled over into the next grant period. If not, it is a no-op.
        /// If we hit the next period, it will top up the spendable amount to
        /// min(accumulation_limit, basic.spend_limit, spendable + period_grant * num_missed_periods) so it is never more than the maximum allowed.
        /// It will also update the last_grant_applied_unix_timestamp.
        pub fn try_update_state(&mut self, env: &Env) {
            let missed_periods = self.missed_periods(env);

            if missed_periods == 0 {
                // we haven't yet reached the next grant time
                return;
            }

            self.spendable = Some(self.determine_spendable(env))
        }

        fn within_spendable_limits(&self, amount: &Coin) -> bool {
            let Some(ref available) = self.spendable else {
                return false;
            };
            available.amount >= amount.amount
        }

        fn ensure_can_spend(&self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            if self.basic.expired(env) {
                return Err(NymPoolContractError::GrantExpired);
            }
            if !self.within_spendable_limits(amount) {
                return Err(NymPoolContractError::SpendingAboveAllowance);
            }
            Ok(())
        }

        fn try_spend(&mut self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            self.ensure_can_spend(env, amount)?;

            // deduct from both the current period and the max amount
            if let Some(ref mut spend_limit) = self.basic.spend_limit {
                spend_limit.amount -= amount.amount;
            }

            // SAFETY: initial `spendable` value is always unconditionally set by the contract during
            // grant creation
            #[allow(clippy::unwrap_used)]
            let spendable = self.spendable.as_mut().unwrap();
            spendable.amount -= amount.amount;

            Ok(())
        }
    }

    /// Create a grant to allow somebody to withdraw from the pool only after the specified time.
    /// For example, we could create a grant for mixnet rewarding/testing/etc
    /// However, if the required work has not been completed, the grant could be revoked before it's withdrawn
    #[cw_serde]
    pub struct DelayedAllowance {
        /// basic specifies a struct of `BasicAllowance`
        pub basic: BasicAllowance,

        /// available_at specifies when this allowance is going to become usable
        pub available_at_unix_timestamp: u64,
    }

    impl DelayedAllowance {
        pub(super) fn validate_new_inner(&self, env: &Env) -> Result<(), NymPoolContractError> {
            // available at must be set in the future
            ensure_unix_timestamp_not_in_the_past(self.available_at_unix_timestamp, env)?;

            // and it must become available before the underlying allowance expires
            if let Some(expiration) = self.basic.expiration_unix_timestamp {
                if expiration < self.available_at_unix_timestamp {
                    return Err(NymPoolContractError::UnattainableDelayedAllowance {
                        expiration_timestamp: expiration,
                        available_timestamp: self.available_at_unix_timestamp,
                    });
                }
            }

            Ok(())
        }

        fn within_spendable_limits(&self, amount: &Coin) -> bool {
            self.basic.within_spendable_limits(amount)
        }

        fn ensure_can_spend(&self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            if self.basic.expired(env) {
                return Err(NymPoolContractError::GrantExpired);
            }
            if !self.within_spendable_limits(amount) {
                return Err(NymPoolContractError::SpendingAboveAllowance);
            }
            if self.available_at_unix_timestamp < env.block.time.seconds() {
                return Err(NymPoolContractError::GrantNotYetAvailable {
                    available_at_timestamp: self.available_at_unix_timestamp,
                });
            }

            Ok(())
        }

        fn try_spend(&mut self, env: &Env, amount: &Coin) -> Result<(), NymPoolContractError> {
            self.ensure_can_spend(env, amount)?;

            if let Some(ref mut spend_limit) = self.basic.spend_limit {
                spend_limit.amount -= amount.amount;
            }

            Ok(())
        }
    }
}

pub mod query_responses {
    use crate::{Grant, GranteeAddress, GranterAddress, GranterInformation};
    use cosmwasm_schema::cw_serde;
    use cosmwasm_std::Coin;

    #[cw_serde]
    pub struct AvailableTokensResponse {
        pub available: Coin,
    }

    #[cw_serde]
    pub struct TotalLockedTokensResponse {
        pub locked: Coin,
    }

    #[cw_serde]
    pub struct LockedTokensResponse {
        pub grantee: GranteeAddress,

        pub locked: Option<Coin>,
    }

    #[cw_serde]
    pub struct GrantInformation {
        pub grant: Grant,
        pub expired: bool,
    }

    #[cw_serde]
    pub struct GrantResponse {
        pub grantee: GranteeAddress,
        pub grant: Option<GrantInformation>,
    }

    #[cw_serde]
    pub struct GranterResponse {
        pub granter: GranterAddress,
        pub information: Option<GranterInformation>,
    }

    #[cw_serde]
    pub struct GrantsPagedResponse {
        pub grants: Vec<GrantInformation>,
        pub start_next_after: Option<String>,
    }

    #[cw_serde]
    pub struct GranterDetails {
        pub granter: GranterAddress,
        pub information: GranterInformation,
    }

    impl From<(GranterAddress, GranterInformation)> for GranterDetails {
        fn from((granter, information): (GranterAddress, GranterInformation)) -> Self {
            GranterDetails {
                granter,
                information,
            }
        }
    }

    #[cw_serde]
    pub struct GrantersPagedResponse {
        pub granters: Vec<GranterDetails>,
        pub start_next_after: Option<String>,
    }

    #[cw_serde]
    pub struct LockedTokens {
        pub grantee: GranteeAddress,
        pub locked: Coin,
    }

    #[cw_serde]
    pub struct LockedTokensPagedResponse {
        pub locked: Vec<LockedTokens>,
        pub start_next_after: Option<String>,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cosmwasm_std::{Uint128, coin};

    const TEST_DENOM: &str = "unym";

    fn mock_basic_allowance() -> BasicAllowance {
        BasicAllowance {
            spend_limit: Some(coin(100000, TEST_DENOM)),
            expiration_unix_timestamp: Some(1643652000),
        }
    }

    fn mock_classic_periodic_allowance() -> ClassicPeriodicAllowance {
        ClassicPeriodicAllowance {
            basic: mock_basic_allowance(),
            period_duration_secs: 10,
            period_spend_limit: coin(1000, TEST_DENOM),
            period_can_spend: None,
            period_reset_unix_timestamp: 0,
        }
    }

    fn mock_cumulative_periodic_allowance() -> CumulativePeriodicAllowance {
        CumulativePeriodicAllowance {
            basic: mock_basic_allowance(),
            period_duration_secs: 10,
            period_grant: coin(1000, TEST_DENOM),
            accumulation_limit: Some(coin(10000, TEST_DENOM)),
            spendable: None,
            last_grant_applied_unix_timestamp: 0,
        }
    }

    fn mock_delayed_allowance() -> DelayedAllowance {
        DelayedAllowance {
            basic: mock_basic_allowance(),
            available_at_unix_timestamp: 1643650000,
        }
    }

    #[test]
    fn increasing_spend_limit() {
        // no-op if there's no limit
        let mut basic = mock_basic_allowance();
        basic.spend_limit = None;
        let mut basic = Allowance::Basic(basic);

        let mut classic = mock_classic_periodic_allowance();
        classic.basic.spend_limit = None;
        let mut classic = Allowance::ClassicPeriodic(classic);

        let mut cumulative = mock_cumulative_periodic_allowance();
        cumulative.basic.spend_limit = None;
        let mut cumulative = Allowance::CumulativePeriodic(cumulative);

        let mut delayed = mock_delayed_allowance();
        delayed.basic.spend_limit = None;
        let mut delayed = Allowance::Delayed(delayed);

        let basic_og = basic.clone();
        let classic_og = classic.clone();
        let cumulative_og = cumulative.clone();
        let delayed_og = delayed.clone();

        basic.increase_spend_limit(Uint128::new(100));
        classic.increase_spend_limit(Uint128::new(100));
        cumulative.increase_spend_limit(Uint128::new(100));
        delayed.increase_spend_limit(Uint128::new(100));

        assert_eq!(basic, basic_og);
        assert_eq!(classic, classic_og);
        assert_eq!(cumulative, cumulative_og);
        assert_eq!(delayed, delayed_og);

        // adds to spend limit otherwise
        let limit = coin(1000, TEST_DENOM);
        let mut basic = mock_basic_allowance();
        basic.spend_limit = Some(limit.clone());
        let mut basic = Allowance::Basic(basic);

        let mut classic = mock_classic_periodic_allowance();
        classic.basic.spend_limit = Some(limit.clone());
        let mut classic = Allowance::ClassicPeriodic(classic);

        let mut cumulative = mock_cumulative_periodic_allowance();
        cumulative.basic.spend_limit = Some(limit.clone());
        let mut cumulative = Allowance::CumulativePeriodic(cumulative);

        let mut delayed = mock_delayed_allowance();
        delayed.basic.spend_limit = Some(limit.clone());
        let mut delayed = Allowance::Delayed(delayed);

        basic.increase_spend_limit(Uint128::new(100));
        classic.increase_spend_limit(Uint128::new(100));
        cumulative.increase_spend_limit(Uint128::new(100));
        delayed.increase_spend_limit(Uint128::new(100));

        assert_eq!(
            basic.basic().spend_limit.as_ref().unwrap().amount,
            limit.amount + Uint128::new(100)
        );
        assert_eq!(
            classic.basic().spend_limit.as_ref().unwrap().amount,
            limit.amount + Uint128::new(100)
        );
        assert_eq!(
            cumulative.basic().spend_limit.as_ref().unwrap().amount,
            limit.amount + Uint128::new(100)
        );
        assert_eq!(
            delayed.basic().spend_limit.as_ref().unwrap().amount,
            limit.amount + Uint128::new(100)
        );
    }

    #[cfg(test)]
    mod validating_new_allowances {
        use super::*;

        #[cfg(test)]
        mod basic_allowance {
            use super::*;
            use cosmwasm_std::Timestamp;
            use cosmwasm_std::testing::mock_env;

            #[test]
            fn doesnt_allow_expirations_in_the_past() {
                let mut allowance = mock_basic_allowance();

                let mut env = mock_env();

                // allowance expiration is in the past
                env.block.time =
                    Timestamp::from_seconds(allowance.expiration_unix_timestamp.unwrap() + 1);
                assert!(allowance.validate(&env, TEST_DENOM).is_err());

                // allowance expiration is equal to the current block time
                env.block.time =
                    Timestamp::from_seconds(allowance.expiration_unix_timestamp.unwrap());
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());

                // allowance expiration is in the future
                env.block.time =
                    Timestamp::from_seconds(allowance.expiration_unix_timestamp.unwrap() - 1);
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());

                // no explicit expiration
                allowance.expiration_unix_timestamp = None;
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());
            }

            #[test]
            fn spend_limit_must_match_expected_denom() {
                let mut allowance = mock_basic_allowance();

                let env = mock_env();

                // mismatched denom
                assert!(allowance.validate(&env, "baddenom").is_err());

                // matched denom
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());

                // no spend limit
                allowance.spend_limit = None;
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());
            }

            #[test]
            fn spend_limit_must_be_non_zero() {
                let mut allowance = mock_basic_allowance();

                let env = mock_env();

                // zero amount
                allowance.spend_limit = Some(coin(0, TEST_DENOM));
                assert!(allowance.validate(&env, TEST_DENOM).is_err());

                // non-zero amount
                allowance.spend_limit = Some(coin(69, TEST_DENOM));
                assert!(allowance.validate(&env, TEST_DENOM).is_ok());
            }
        }

        #[cfg(test)]
        mod classic_periodic_allowance {
            use super::*;
            use crate::NymPoolContractError;

            #[test]
            fn period_duration_must_be_nonzero() {
                let mut allowance = mock_classic_periodic_allowance();

                allowance.period_duration_secs = 0;
                assert_eq!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::ZeroAllowancePeriod
                );

                allowance.period_duration_secs = 1;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn spend_limit_must_match_expected_denom() {
                let allowance = mock_classic_periodic_allowance();

                // mismatched denom
                assert!(allowance.validate_new_inner("baddenom").is_err());

                // matched denom
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn spend_limit_must_be_non_zero() {
                let mut allowance = mock_classic_periodic_allowance();

                // zero amount
                allowance.period_spend_limit = coin(0, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_err());

                // non-zero amount
                allowance.period_spend_limit = coin(69, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn period_spend_limit_must_be_smaller_than_total_limit() {
                let mut allowance = mock_classic_periodic_allowance();

                let total_limit = coin(1000, TEST_DENOM);
                allowance.basic.spend_limit = Some(total_limit);

                // above total spend limit
                allowance.period_spend_limit = coin(1001, TEST_DENOM);
                assert!(matches!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::PeriodicGrantOverSpendLimit { .. }
                ));

                // below total spend limit
                allowance.period_spend_limit = coin(999, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // equal to total spend limit
                allowance.period_spend_limit = coin(1000, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no total spend limit
                allowance.basic.spend_limit = None;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }
        }

        #[cfg(test)]
        mod cumulative_periodic_allowance {
            use super::*;
            use crate::NymPoolContractError;

            #[test]
            fn period_duration_must_be_nonzero() {
                let mut allowance = mock_cumulative_periodic_allowance();

                allowance.period_duration_secs = 0;
                assert_eq!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::ZeroAllowancePeriod
                );

                allowance.period_duration_secs = 1;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn grant_must_match_expected_denom() {
                let allowance = mock_cumulative_periodic_allowance();

                // mismatched denom
                assert!(allowance.validate_new_inner("baddenom").is_err());

                // matched denom
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn grant_must_be_non_zero() {
                let mut allowance = mock_cumulative_periodic_allowance();

                // zero amount
                allowance.period_grant = coin(0, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_err());

                // non-zero amount
                allowance.period_grant = coin(69, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn grant_amount_must_be_smaller_than_total_limit() {
                let mut allowance = mock_cumulative_periodic_allowance();

                let total_limit = coin(1000, TEST_DENOM);
                allowance.basic.spend_limit = Some(total_limit);
                allowance.accumulation_limit = None;

                // above total spend limit
                allowance.period_grant = coin(1001, TEST_DENOM);
                assert!(matches!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::PeriodicGrantOverSpendLimit { .. }
                ));

                // below total spend limit
                allowance.period_grant = coin(999, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // equal to total spend limit
                allowance.period_grant = coin(1000, TEST_DENOM);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no total spend limit
                allowance.basic.spend_limit = None;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn accumulation_limit_must_be_smaller_than_total_limit() {
                let mut allowance = mock_cumulative_periodic_allowance();

                let total_limit = coin(1000, TEST_DENOM);
                allowance.basic.spend_limit = Some(total_limit.clone());
                allowance.period_grant = coin(500, TEST_DENOM);

                // above total spend limit
                allowance.accumulation_limit = Some(coin(1001, TEST_DENOM));
                assert!(matches!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::AccumulationOverSpendLimit { .. }
                ));

                // below total spend limit
                allowance.accumulation_limit = Some(coin(999, TEST_DENOM));
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // equal to total spend limit
                allowance.accumulation_limit = Some(coin(1000, TEST_DENOM));
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no total spend limit
                allowance.basic.spend_limit = None;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no accumulation limit
                allowance.accumulation_limit = None;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no accumulation limit but with spend limit
                allowance.basic.spend_limit = Some(total_limit);
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn accumulation_limit_must_not_be_smaller_than_grant_amount() {
                let mut allowance = mock_cumulative_periodic_allowance();

                let total_limit = coin(1000, TEST_DENOM);
                allowance.basic.spend_limit = Some(total_limit);
                allowance.period_grant = coin(500, TEST_DENOM);

                // below grant amount
                allowance.accumulation_limit = Some(coin(499, TEST_DENOM));
                assert!(matches!(
                    allowance.validate_new_inner(TEST_DENOM).unwrap_err(),
                    NymPoolContractError::AccumulationBelowGrantAmount { .. }
                ));

                // above grant amount
                allowance.accumulation_limit = Some(coin(501, TEST_DENOM));
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // equal to grant amount
                allowance.accumulation_limit = Some(coin(500, TEST_DENOM));
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());

                // no accumulation limit
                allowance.accumulation_limit = None;
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }

            #[test]
            fn accumulation_limit_must_match_expected_denom() {
                let mut allowance = mock_cumulative_periodic_allowance();
                allowance.accumulation_limit = Some(coin(1000, "baddenom"));

                // mismatched denom
                assert!(allowance.validate_new_inner(TEST_DENOM).is_err());

                // matched denom
                allowance.accumulation_limit = Some(coin(1000, TEST_DENOM));
                assert!(allowance.validate_new_inner(TEST_DENOM).is_ok());
            }
        }

        #[cfg(test)]
        mod delayed_allowance {
            use super::*;
            use cosmwasm_std::Timestamp;
            use cosmwasm_std::testing::mock_env;

            #[test]
            fn doesnt_allow_availability_in_the_past() {
                let allowance = mock_delayed_allowance();
                let mut env = mock_env();

                // availability is in the past
                env.block.time = Timestamp::from_seconds(allowance.available_at_unix_timestamp + 1);
                assert!(allowance.validate_new_inner(&env).is_err());

                // availability is equal to the current block time
                env.block.time = Timestamp::from_seconds(allowance.available_at_unix_timestamp);
                assert!(allowance.validate_new_inner(&env).is_ok());

                // availability is in the future
                env.block.time = Timestamp::from_seconds(allowance.available_at_unix_timestamp - 1);
                assert!(allowance.validate_new_inner(&env).is_ok());
            }

            #[test]
            fn must_have_available_before_allowance_expiration() {
                let mut allowance = mock_delayed_allowance();
                let mut env = mock_env();
                env.block.time = Timestamp::from_seconds(100);
                allowance.basic.expiration_unix_timestamp = Some(1000);

                // after expiration
                allowance.available_at_unix_timestamp = 1001;
                assert!(allowance.validate_new_inner(&env).is_err());

                // equal to expiration
                allowance.available_at_unix_timestamp = 1000;
                assert!(allowance.validate_new_inner(&env).is_ok());

                // before expiration
                allowance.available_at_unix_timestamp = 999;
                assert!(allowance.validate_new_inner(&env).is_ok());

                // with no explicit expiration
                allowance.basic.expiration_unix_timestamp = None;
                assert!(allowance.validate_new_inner(&env).is_ok());
            }
        }
    }

    #[cfg(test)]
    mod setting_initial_state {
        use super::*;
        use cosmwasm_std::testing::mock_env;

        #[test]
        fn basic_allowance() {
            let mut basic = Allowance::Basic(mock_basic_allowance());

            let og = basic.clone();

            // this is a no-op
            let env = mock_env();
            basic.set_initial_state(&env);
            assert_eq!(basic, og);
        }

        #[test]
        fn classic_periodic_allowance() {
            let mut inner = mock_classic_periodic_allowance();
            let mut cumulative = Allowance::ClassicPeriodic(inner.clone());

            let env = mock_env();

            let mut expected = inner.clone();

            // sets the spendable amount to min(basic_limit, period_limit)
            expected.period_can_spend = Some(expected.period_spend_limit.clone());

            // set period reset to current block time + period duration
            expected.period_reset_unix_timestamp =
                env.block.time.seconds() + expected.period_duration_secs;

            inner.set_initial_state(&env);
            assert_eq!(inner, expected);

            cumulative.set_initial_state(&env);
            assert_eq!(cumulative, Allowance::ClassicPeriodic(inner));
        }

        #[test]
        fn cumulative_periodic_allowance() {
            let mut inner = mock_cumulative_periodic_allowance();
            let mut cumulative = Allowance::CumulativePeriodic(inner.clone());

            let env = mock_env();

            // sets the last applied grant to current time and spendable to a single grant value
            let mut expected = inner.clone();
            expected.last_grant_applied_unix_timestamp = env.block.time.seconds();
            expected.spendable = Some(expected.period_grant.clone());

            inner.set_initial_state(&env);
            assert_eq!(inner, expected);

            cumulative.set_initial_state(&env);
            assert_eq!(cumulative, Allowance::CumulativePeriodic(inner));
        }

        #[test]
        fn delayed_allowance() {
            let mut delayed = Allowance::Delayed(mock_delayed_allowance());

            let og = delayed.clone();

            // this is a no-op
            let env = mock_env();
            delayed.set_initial_state(&env);
            assert_eq!(delayed, og);
        }
    }
}