-
Notifications
You must be signed in to change notification settings - Fork 355
/
contract.rs
2297 lines (2018 loc) · 73.4 KB
/
contract.rs
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
use schemars::JsonSchema;
use std::fmt;
use std::ops::{AddAssign, Sub};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
ensure, ensure_ne, to_json_binary, BankMsg, Binary, Coin, CosmosMsg, Deps, DepsMut,
DistributionMsg, Empty, Env, MessageInfo, Order, Response, StakingMsg, StdResult,
};
use cw1::CanExecuteResponse;
use cw1_whitelist::{
contract::{
execute_freeze, execute_update_admins, instantiate as whitelist_instantiate,
query_admin_list,
},
msg::InstantiateMsg,
state::ADMIN_LIST,
};
use cw2::{get_contract_version, set_contract_version};
use cw_storage_plus::Bound;
use cw_utils::Expiration;
use semver::Version;
use crate::error::ContractError;
use crate::msg::{
AllAllowancesResponse, AllPermissionsResponse, AllowanceInfo, ExecuteMsg, PermissionsInfo,
QueryMsg,
};
use crate::state::{Allowance, Permissions, ALLOWANCES, PERMISSIONS};
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cw1-subkeys";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
mut deps: DepsMut,
env: Env,
info: MessageInfo,
msg: InstantiateMsg,
) -> StdResult<Response> {
let result = whitelist_instantiate(deps.branch(), env, info, msg)?;
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(result)
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
// Note: implement this function with different type to add support for custom messages
// and then import the rest of this contract code.
msg: ExecuteMsg<Empty>,
) -> Result<Response<Empty>, ContractError> {
match msg {
ExecuteMsg::Execute { msgs } => execute_execute(deps, env, info, msgs),
ExecuteMsg::Freeze {} => Ok(execute_freeze(deps, env, info)?),
ExecuteMsg::UpdateAdmins { admins } => Ok(execute_update_admins(deps, env, info, admins)?),
ExecuteMsg::IncreaseAllowance {
spender,
amount,
expires,
} => execute_increase_allowance(deps, env, info, spender, amount, expires),
ExecuteMsg::DecreaseAllowance {
spender,
amount,
expires,
} => execute_decrease_allowance(deps, env, info, spender, amount, expires),
ExecuteMsg::SetPermissions {
spender,
permissions,
} => execute_set_permissions(deps, env, info, spender, permissions),
}
}
pub fn execute_execute<T>(
deps: DepsMut,
env: Env,
info: MessageInfo,
msgs: Vec<CosmosMsg<T>>,
) -> Result<Response<T>, ContractError>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
let cfg = ADMIN_LIST.load(deps.storage)?;
// Not an admin - need to check for permissions
if !cfg.is_admin(info.sender.as_ref()) {
for msg in &msgs {
match msg {
CosmosMsg::Staking(staking_msg) => {
let perm = PERMISSIONS.may_load(deps.storage, &info.sender)?;
let perm = perm.ok_or(ContractError::NotAllowed {})?;
check_staking_permissions(staking_msg, perm)?;
}
CosmosMsg::Distribution(distribution_msg) => {
let perm = PERMISSIONS.may_load(deps.storage, &info.sender)?;
let perm = perm.ok_or(ContractError::NotAllowed {})?;
check_distribution_permissions(distribution_msg, perm)?;
}
CosmosMsg::Bank(BankMsg::Send {
to_address: _,
amount,
}) => {
ALLOWANCES.update::<_, ContractError>(deps.storage, &info.sender, |allow| {
let mut allowance = allow.ok_or(ContractError::NoAllowance {})?;
ensure!(
!allowance.expires.is_expired(&env.block),
ContractError::NoAllowance {}
);
// Decrease allowance
allowance.balance = allowance.balance.sub(amount.clone())?;
Ok(allowance)
})?;
}
_ => {
return Err(ContractError::MessageTypeRejected {});
}
}
}
}
// Relay messages
let res = Response::new()
.add_messages(msgs)
.add_attribute("action", "execute")
.add_attribute("owner", info.sender);
Ok(res)
}
pub fn check_staking_permissions(
staking_msg: &StakingMsg,
permissions: Permissions,
) -> Result<(), ContractError> {
match staking_msg {
StakingMsg::Delegate { .. } => {
ensure!(permissions.delegate, ContractError::DelegatePerm {});
}
StakingMsg::Undelegate { .. } => {
ensure!(permissions.undelegate, ContractError::UnDelegatePerm {});
}
StakingMsg::Redelegate { .. } => {
ensure!(permissions.redelegate, ContractError::ReDelegatePerm {});
}
_ => return Err(ContractError::UnsupportedMessage {}),
}
Ok(())
}
pub fn check_distribution_permissions(
distribution_msg: &DistributionMsg,
permissions: Permissions,
) -> Result<(), ContractError> {
match distribution_msg {
DistributionMsg::SetWithdrawAddress { .. } => {
ensure!(permissions.withdraw, ContractError::WithdrawAddrPerm {});
}
DistributionMsg::WithdrawDelegatorReward { .. } => {
ensure!(permissions.withdraw, ContractError::WithdrawPerm {});
}
_ => return Err(ContractError::UnsupportedMessage {}),
}
Ok(())
}
pub fn execute_increase_allowance<T>(
deps: DepsMut,
env: Env,
info: MessageInfo,
spender: String,
amount: Coin,
expires: Option<Expiration>,
) -> Result<Response<T>, ContractError>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
let cfg = ADMIN_LIST.load(deps.storage)?;
ensure!(cfg.is_admin(&info.sender), ContractError::Unauthorized {});
let spender_addr = deps.api.addr_validate(&spender)?;
ensure_ne!(
info.sender,
spender_addr,
ContractError::CannotSetOwnAccount {}
);
ALLOWANCES.update::<_, ContractError>(deps.storage, &spender_addr, |allow| {
let prev_expires = allow
.as_ref()
.map(|allow| allow.expires)
.unwrap_or_default();
let mut allowance = allow
.filter(|allow| !allow.expires.is_expired(&env.block))
.unwrap_or_default();
if let Some(exp) = expires {
if exp.is_expired(&env.block) {
return Err(ContractError::SettingExpiredAllowance(exp));
}
allowance.expires = exp;
} else if prev_expires.is_expired(&env.block) {
return Err(ContractError::SettingExpiredAllowance(prev_expires));
}
allowance.balance.add_assign(amount.clone());
Ok(allowance)
})?;
let res = Response::new()
.add_attribute("action", "increase_allowance")
.add_attribute("owner", info.sender)
.add_attribute("spender", spender)
.add_attribute("denomination", amount.denom)
.add_attribute("amount", amount.amount);
Ok(res)
}
pub fn execute_decrease_allowance<T>(
deps: DepsMut,
env: Env,
info: MessageInfo,
spender: String,
amount: Coin,
expires: Option<Expiration>,
) -> Result<Response<T>, ContractError>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
let cfg = ADMIN_LIST.load(deps.storage)?;
ensure!(cfg.is_admin(&info.sender), ContractError::Unauthorized {});
let spender_addr = deps.api.addr_validate(&spender)?;
ensure_ne!(
info.sender,
spender_addr,
ContractError::CannotSetOwnAccount {}
);
let allowance =
ALLOWANCES.update::<_, ContractError>(deps.storage, &spender_addr, |allow| {
// Fail fast
let mut allowance = allow
.filter(|allow| !allow.expires.is_expired(&env.block))
.ok_or(ContractError::NoAllowance {})?;
if let Some(exp) = expires {
if exp.is_expired(&env.block) {
return Err(ContractError::SettingExpiredAllowance(exp));
}
allowance.expires = exp;
}
allowance.balance = allowance.balance.sub_saturating(amount.clone())?; // Tolerates underflows (amount bigger than balance), but fails if there are no tokens at all for the denom (report potential errors)
Ok(allowance)
})?;
if allowance.balance.is_empty() {
ALLOWANCES.remove(deps.storage, &spender_addr);
}
let res = Response::new()
.add_attribute("action", "decrease_allowance")
.add_attribute("owner", info.sender)
.add_attribute("spender", spender)
.add_attribute("denomination", amount.denom)
.add_attribute("amount", amount.amount);
Ok(res)
}
pub fn execute_set_permissions<T>(
deps: DepsMut,
_env: Env,
info: MessageInfo,
spender: String,
perm: Permissions,
) -> Result<Response<T>, ContractError>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
let cfg = ADMIN_LIST.load(deps.storage)?;
ensure!(cfg.is_admin(&info.sender), ContractError::Unauthorized {});
let spender_addr = deps.api.addr_validate(&spender)?;
ensure_ne!(
info.sender,
spender_addr,
ContractError::CannotSetOwnAccount {}
);
PERMISSIONS.save(deps.storage, &spender_addr, &perm)?;
let res = Response::new()
.add_attribute("action", "set_permissions")
.add_attribute("owner", info.sender)
.add_attribute("spender", spender)
.add_attribute("permissions", perm.to_string());
Ok(res)
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::AdminList {} => to_json_binary(&query_admin_list(deps)?),
QueryMsg::Allowance { spender } => to_json_binary(&query_allowance(deps, env, spender)?),
QueryMsg::Permissions { spender } => to_json_binary(&query_permissions(deps, spender)?),
QueryMsg::CanExecute { sender, msg } => {
to_json_binary(&query_can_execute(deps, env, sender, msg)?)
}
QueryMsg::AllAllowances { start_after, limit } => {
to_json_binary(&query_all_allowances(deps, env, start_after, limit)?)
}
QueryMsg::AllPermissions { start_after, limit } => {
to_json_binary(&query_all_permissions(deps, start_after, limit)?)
}
}
}
// if the subkey has no allowance, return an empty struct (not an error)
pub fn query_allowance(deps: Deps, env: Env, spender: String) -> StdResult<Allowance> {
// we can use unchecked here as it is a query - bad value means a miss, we never write it
let spender = deps.api.addr_validate(&spender)?;
let allow = ALLOWANCES
.may_load(deps.storage, &spender)?
.filter(|allow| !allow.expires.is_expired(&env.block))
.unwrap_or_default();
Ok(allow)
}
// if the subkey has no permissions, return an empty struct (not an error)
pub fn query_permissions(deps: Deps, spender: String) -> StdResult<Permissions> {
let spender = deps.api.addr_validate(&spender)?;
let permissions = PERMISSIONS
.may_load(deps.storage, &spender)?
.unwrap_or_default();
Ok(permissions)
}
fn query_can_execute(
deps: Deps,
env: Env,
sender: String,
msg: CosmosMsg,
) -> StdResult<CanExecuteResponse> {
Ok(CanExecuteResponse {
can_execute: can_execute(deps, env, sender, msg)?,
})
}
// this can just return booleans and the query_can_execute wrapper creates the struct once, not on every path
fn can_execute(deps: Deps, env: Env, sender: String, msg: CosmosMsg) -> StdResult<bool> {
let cfg = ADMIN_LIST.load(deps.storage)?;
if cfg.is_admin(&sender) {
return Ok(true);
}
let sender = deps.api.addr_validate(&sender)?;
match msg {
CosmosMsg::Bank(BankMsg::Send { amount, .. }) => {
// now we check if there is enough allowance for this message
let allowance = ALLOWANCES.may_load(deps.storage, &sender)?;
match allowance {
// if there is an allowance, we subtract the requested amount to ensure it is covered (error on underflow)
Some(allow) => {
Ok(!allow.expires.is_expired(&env.block) && allow.balance.sub(amount).is_ok())
}
None => Ok(false),
}
}
CosmosMsg::Staking(staking_msg) => {
let perm_opt = PERMISSIONS.may_load(deps.storage, &sender)?;
match perm_opt {
Some(permission) => Ok(check_staking_permissions(&staking_msg, permission).is_ok()),
None => Ok(false),
}
}
CosmosMsg::Distribution(distribution_msg) => {
let perm_opt = PERMISSIONS.may_load(deps.storage, &sender)?;
match perm_opt {
Some(permission) => {
Ok(check_distribution_permissions(&distribution_msg, permission).is_ok())
}
None => Ok(false),
}
}
_ => Ok(false),
}
}
const MAX_LIMIT: u32 = 30;
const DEFAULT_LIMIT: u32 = 10;
fn calc_limit(request: Option<u32>) -> usize {
request.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize
}
// return a list of all allowances here
pub fn query_all_allowances(
deps: Deps,
env: Env,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<AllAllowancesResponse> {
let limit = calc_limit(limit);
// we use raw addresses here....
let start = start_after.map(|s| Bound::ExclusiveRaw(s.into()));
let allowances = ALLOWANCES
.range(deps.storage, start, None, Order::Ascending)
.filter(|item| {
if let Ok((_, allow)) = item {
!allow.expires.is_expired(&env.block)
} else {
true
}
})
.take(limit)
.map(|item| {
item.map(|(addr, allow)| AllowanceInfo {
spender: addr.into(),
balance: allow.balance,
expires: allow.expires,
})
})
.collect::<StdResult<Vec<_>>>()?;
Ok(AllAllowancesResponse { allowances })
}
// return a list of all permissions here
pub fn query_all_permissions(
deps: Deps,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<AllPermissionsResponse> {
let limit = calc_limit(limit);
let start = start_after.map(|s| Bound::ExclusiveRaw(s.into()));
let permissions = PERMISSIONS
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|item| {
item.map(|(addr, perm)| PermissionsInfo {
spender: addr.into(),
permissions: perm,
})
})
.collect::<StdResult<Vec<_>>>()?;
Ok(AllPermissionsResponse { permissions })
}
// Migrate contract if version is lower than current version
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: Empty) -> Result<Response, ContractError> {
let version: Version = CONTRACT_VERSION.parse()?;
let storage_version: Version = get_contract_version(deps.storage)?.version.parse()?;
if storage_version < version {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// If state structure changed in any contract version in the way migration is needed, it
// should occur here
}
Ok(Response::new())
}
#[cfg(test)]
mod tests {
use cosmwasm_std::testing::{
mock_dependencies, mock_env, mock_info, MockApi, MockQuerier, MockStorage,
};
use cosmwasm_std::{coin, coins, OwnedDeps, StakingMsg, SubMsg, Timestamp};
use cw1_whitelist::msg::AdminListResponse;
use cw2::{get_contract_version, ContractVersion};
use cw_utils::NativeBalance;
use easy_addr::addr;
use crate::state::Permissions;
use std::collections::HashMap;
use super::*;
const OWNER: &str = addr!("owner");
const ADMIN1: &str = addr!("admin1");
const ADMIN2: &str = addr!("admin2");
const SPENDER1: &str = addr!("spender1");
const SPENDER2: &str = addr!("spender2");
const SPENDER3: &str = addr!("spender3");
const SPENDER4: &str = addr!("spender4");
const TOKEN: &str = "token";
const TOKEN1: &str = "token1";
const TOKEN2: &str = "token2";
const ALL_PERMS: Permissions = Permissions {
delegate: true,
redelegate: true,
undelegate: true,
withdraw: true,
};
const NO_PERMS: Permissions = Permissions {
delegate: false,
redelegate: false,
undelegate: false,
withdraw: false,
};
// Expiration constant working properly with default `mock_env`
const NON_EXPIRED_HEIGHT: Expiration = Expiration::AtHeight(22_222);
const NON_EXPIRED_TIME: Expiration =
Expiration::AtTime(Timestamp::from_nanos(2_571_797_419_879_305_533));
const EXPIRED_HEIGHT: Expiration = Expiration::AtHeight(10);
const EXPIRED_TIME: Expiration = Expiration::AtTime(Timestamp::from_nanos(100));
/// Helper structure for Suite configuration
#[derive(Default)]
struct SuiteConfig {
spenders: HashMap<&'static str, Spender>,
admins: Vec<&'static str>,
}
impl SuiteConfig {
fn new() -> Self {
Self::default()
}
fn init(self) -> Suite {
Suite::init_with_config(self)
}
fn with_allowance(mut self, spender: &'static str, allowance: Coin) -> Self {
self.spenders
.entry(spender)
.or_default()
.allowances
.push(allowance);
self
}
fn expire_allowances(mut self, spender: &'static str, expires: Expiration) -> Self {
let item = self.spenders.entry(spender).or_default();
assert!(
item.allowances_expire.is_none(),
"Allowances expiration for spender {spender} already configured",
);
item.allowances_expire = Some(expires);
self
}
fn with_permissions(mut self, spender: &'static str, permissions: Permissions) -> Self {
let item = self.spenders.entry(spender).or_default();
assert!(
item.permissions.is_none(),
"Permissions for spender {spender} already configured",
);
item.permissions = Some(permissions);
self
}
fn with_admin(mut self, admin: &'static str) -> Self {
self.admins.push(admin);
self
}
}
#[derive(Default)]
struct Spender {
allowances: Vec<Coin>,
allowances_expire: Option<Expiration>,
permissions: Option<Permissions>,
}
/// Test suite helper unifying test initialization, keeping access to created data
struct Suite {
deps: OwnedDeps<MockStorage, MockApi, MockQuerier>,
owner: MessageInfo,
}
impl Suite {
/// Initializes test case using default config
fn init() -> Self {
Self::init_with_config(SuiteConfig::default())
}
/// Initialized test case using provided config
fn init_with_config(config: SuiteConfig) -> Self {
let mut deps = mock_dependencies();
let admins = std::iter::once(OWNER)
.chain(config.admins)
.map(ToOwned::to_owned)
.collect();
let instantiate_msg = InstantiateMsg {
admins,
mutable: true,
};
let owner = mock_info(OWNER, &[]);
instantiate(
deps.as_mut().branch(),
mock_env(),
owner.clone(),
instantiate_msg,
)
.unwrap();
for (name, spender) in config.spenders {
let Spender {
allowances,
allowances_expire: expires,
permissions,
} = spender;
for amount in allowances {
let msg = ExecuteMsg::IncreaseAllowance {
spender: name.to_owned(),
amount,
expires,
};
// Extend block and time, so all alowances are set, even if expired in normal
// mock_env
let mut env = mock_env();
env.block.time = Timestamp::from_nanos(0);
env.block.height = 0;
execute(deps.as_mut().branch(), env, owner.clone(), msg).unwrap();
}
if let Some(permissions) = permissions {
let msg = ExecuteMsg::SetPermissions {
spender: name.to_owned(),
permissions,
};
execute(deps.as_mut().branch(), mock_env(), owner.clone(), msg).unwrap();
}
}
Self { deps, owner }
}
}
/// Helper function for comparing vectors or another slice-like object as they would represent
/// set with duplications. Compares sets by first sorting elements using provided ordering.
/// This functions reshufless elements inplace, as it should never matter as compared
/// containers should represent same value regardless of ordering, and making this inplace just
/// safes obsolete copying.
///
/// This is implemented as a macro instead of function to throw panic in the place of macro
/// usage instead of from function called inside test.
macro_rules! assert_sorted_eq {
($left:expr, $right:expr, $cmp:expr $(,)?) => {
let mut left = $left;
left.sort_by(&$cmp);
let mut right = $right;
right.sort_by($cmp);
assert_eq!(left, right);
};
}
#[test]
fn get_contract_version_works() {
let Suite { deps, .. } = Suite::init();
assert_eq!(
ContractVersion {
contract: CONTRACT_NAME.to_string(),
version: CONTRACT_VERSION.to_string(),
},
get_contract_version(&deps.storage).unwrap()
)
}
mod allowance {
use super::*;
#[test]
fn query() {
let Suite { deps, .. } = SuiteConfig::new()
.with_allowance(SPENDER1, coin(1, TOKEN))
.with_allowance(SPENDER2, coin(2, TOKEN))
.init();
// Check allowances work for accounts with balances
let allowance =
query_allowance(deps.as_ref(), mock_env(), SPENDER1.to_owned()).unwrap();
assert_eq!(
allowance,
Allowance {
balance: NativeBalance(vec![coin(1, TOKEN)]),
expires: Expiration::Never {},
}
);
let allowance =
query_allowance(deps.as_ref(), mock_env(), SPENDER2.to_owned()).unwrap();
assert_eq!(
allowance,
Allowance {
balance: NativeBalance(vec![coin(2, TOKEN)]),
expires: Expiration::Never {},
}
);
// Check allowances work for accounts with no balance
let allowance =
query_allowance(deps.as_ref(), mock_env(), SPENDER3.to_string()).unwrap();
assert_eq!(allowance, Allowance::default());
}
#[test]
fn query_expired() {
let Suite { deps, .. } = SuiteConfig::new()
.with_allowance(SPENDER1, coin(1, TOKEN))
.expire_allowances(SPENDER1, EXPIRED_HEIGHT)
.init();
// Check allowances work for accounts with balances
let allowance =
query_allowance(deps.as_ref(), mock_env(), SPENDER1.to_owned()).unwrap();
assert_eq!(
allowance,
Allowance {
balance: NativeBalance(vec![]),
expires: Expiration::Never {},
}
);
}
#[test]
fn query_all() {
let s1_allow = coin(1234, TOKEN);
let s2_allow = coin(2345, TOKEN);
let s3_allow = coin(3456, TOKEN);
let s2_expire = Expiration::Never {};
let s3_expire = NON_EXPIRED_HEIGHT;
let Suite { deps, .. } = SuiteConfig::new()
.with_allowance(SPENDER1, s1_allow.clone())
.with_allowance(SPENDER2, s2_allow.clone())
.expire_allowances(SPENDER2, s2_expire)
.with_allowance(SPENDER3, s3_allow.clone())
.expire_allowances(SPENDER3, s3_expire)
// This allowance is already expired - should not occur in result
.with_allowance(SPENDER4, coin(2222, TOKEN))
.expire_allowances(SPENDER4, EXPIRED_HEIGHT)
.init();
// let's try pagination.
//
// Check is tricky, as there is no guarantee about order expiration are received (as it is
// dependent at least on ordering of insertions), so to check if pagination works, all what
// can we do is to ensure parts are of expected size, and that collectively all allowances
// are returned.
let batch1 = query_all_allowances(deps.as_ref(), mock_env(), None, Some(2))
.unwrap()
.allowances;
assert_eq!(2, batch1.len());
// now continue from after the last one
let batch2 = query_all_allowances(
deps.as_ref(),
mock_env(),
Some(batch1[1].spender.clone()),
Some(2),
)
.unwrap()
.allowances;
assert_eq!(1, batch2.len());
let expected = vec![
AllowanceInfo {
spender: SPENDER1.to_owned(),
balance: NativeBalance(vec![s1_allow]),
expires: Expiration::Never {}, // Not set, expected default
},
AllowanceInfo {
spender: SPENDER2.to_owned(),
balance: NativeBalance(vec![s2_allow]),
expires: s2_expire,
},
AllowanceInfo {
spender: SPENDER3.to_owned(),
balance: NativeBalance(vec![s3_allow]),
expires: s3_expire,
},
];
assert_sorted_eq!(
expected,
[batch1, batch2].concat(),
AllowanceInfo::cmp_by_spender
);
}
}
mod permissions {
use super::*;
#[test]
fn query() {
let Suite { deps, .. } = SuiteConfig::new()
.with_permissions(SPENDER1, ALL_PERMS)
.with_permissions(SPENDER2, NO_PERMS)
.init();
let permissions = query_permissions(deps.as_ref(), SPENDER1.to_string()).unwrap();
assert_eq!(permissions, ALL_PERMS);
let permissions = query_permissions(deps.as_ref(), SPENDER2.to_string()).unwrap();
assert_eq!(permissions, NO_PERMS);
// no permission is set. should return false
let permissions = query_permissions(deps.as_ref(), SPENDER3.to_string()).unwrap();
assert_eq!(permissions, NO_PERMS);
}
#[test]
fn query_all() {
let Suite { deps, .. } = SuiteConfig::new()
.with_permissions(SPENDER1, ALL_PERMS)
.with_permissions(SPENDER2, NO_PERMS)
.with_permissions(SPENDER3, NO_PERMS)
.init();
// let's try pagination
let batch1 = query_all_permissions(deps.as_ref(), None, Some(2))
.unwrap()
.permissions;
assert_eq!(batch1.len(), 2);
let batch2 =
query_all_permissions(deps.as_ref(), Some(batch1[1].spender.clone()), Some(2))
.unwrap()
.permissions;
assert_eq!(batch2.len(), 1);
let expected = vec![
PermissionsInfo {
spender: SPENDER1.to_owned(),
permissions: ALL_PERMS,
},
PermissionsInfo {
spender: SPENDER2.to_owned(),
permissions: NO_PERMS,
},
PermissionsInfo {
spender: SPENDER3.to_owned(),
permissions: NO_PERMS,
},
];
assert_sorted_eq!(
[batch1, batch2].concat(),
expected,
PermissionsInfo::cmp_by_spender
);
}
}
mod admins {
use super::*;
#[test]
fn query() {
let Suite { deps, .. } = SuiteConfig::new().with_admin(ADMIN1).init();
// Verify
assert_eq!(
query_admin_list(deps.as_ref()).unwrap().canonical(),
AdminListResponse {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned()],
mutable: true,
}
.canonical()
);
}
#[test]
fn update() {
let Suite {
mut deps, owner, ..
} = SuiteConfig::new().init();
let rsp = execute(
deps.as_mut(),
mock_env(),
owner,
ExecuteMsg::UpdateAdmins {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
},
)
.unwrap();
assert_eq!(rsp.messages, vec![]);
assert!(rsp.events.is_empty());
assert_eq!(rsp.data, None);
assert_eq!(
query_admin_list(deps.as_ref()).unwrap().canonical(),
AdminListResponse {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
mutable: true,
}
.canonical()
);
}
#[test]
fn non_owner_update() {
let Suite { mut deps, .. } = SuiteConfig::new().with_admin(ADMIN1).init();
let info = mock_info(ADMIN1, &[]);
let rsp = execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::UpdateAdmins {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
},
)
.unwrap();
assert_eq!(rsp.messages, vec![]);
assert!(rsp.events.is_empty());
assert_eq!(rsp.data, None);
assert_eq!(
query_admin_list(deps.as_ref()).unwrap().canonical(),
AdminListResponse {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
mutable: true,
}
.canonical()
);
}
#[test]
fn non_admin_fail_to_update() {
let Suite { mut deps, .. } = SuiteConfig::new().init();
let info = mock_info(ADMIN1, &[]);
execute(
deps.as_mut(),
mock_env(),
info,
ExecuteMsg::UpdateAdmins {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
},
)
.unwrap_err();
assert_eq!(
query_admin_list(deps.as_ref()).unwrap().canonical(),
AdminListResponse {
admins: vec![OWNER.to_owned()],
mutable: true,
}
.canonical()
);
}
#[test]
fn removed_owner_fail_to_update() {
let Suite {
mut deps, owner, ..
} = SuiteConfig::new().init();
// Exact result not checked as it is verified in another test
execute(
deps.as_mut(),
mock_env(),
owner.clone(),
ExecuteMsg::UpdateAdmins {
admins: vec![ADMIN1.to_owned()],
},
)
.unwrap();
execute(
deps.as_mut(),
mock_env(),
owner,
ExecuteMsg::UpdateAdmins {
admins: vec![OWNER.to_owned(), ADMIN1.to_owned(), ADMIN2.to_owned()],
},
)
.unwrap_err();