-
Notifications
You must be signed in to change notification settings - Fork 348
/
contract.rs
1227 lines (1087 loc) · 38.3 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 std::cmp::Ordering;
use cosmwasm_std::{
attr, to_binary, Binary, BlockInfo, CanonicalAddr, CosmosMsg, Deps, DepsMut, Empty, Env,
HandleResponse, HumanAddr, InitResponse, MessageInfo, Order, StdResult,
};
use cw0::{maybe_canonical, Expiration};
use cw2::set_contract_version;
use cw3::{
ProposalListResponse, ProposalResponse, Status, ThresholdResponse, Vote, VoteInfo,
VoteListResponse, VoteResponse, VoterInfo, VoterListResponse, VoterResponse,
};
use cw4::{Cw4Contract, MemberChangedHookMsg, MemberDiff};
use cw_storage_plus::{Bound, PkOwned};
use crate::error::ContractError;
use crate::msg::{HandleMsg, InitMsg, QueryMsg};
use crate::state::{
next_id, parse_id, proposals, status_index, Ballot, Config, Proposal, BALLOTS, CONFIG,
};
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cw3-flex-multisig";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn init(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InitMsg,
) -> Result<InitResponse, ContractError> {
if msg.required_weight == 0 {
return Err(ContractError::ZeroWeight {});
}
// we just convert to canonical to check if this is a valid format
if deps.api.canonical_address(&msg.group_addr).is_err() {
return Err(ContractError::InvalidGroup {
addr: msg.group_addr,
});
}
let group = Cw4Contract(msg.group_addr);
let total_weight = group.total_weight(&deps.querier)?;
if total_weight < msg.required_weight {
return Err(ContractError::UnreachableWeight {});
}
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let cfg = Config {
required_weight: msg.required_weight,
max_voting_period: msg.max_voting_period,
group_addr: group,
};
CONFIG.save(deps.storage, &cfg)?;
Ok(InitResponse::default())
}
pub fn handle(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: HandleMsg,
) -> Result<HandleResponse<Empty>, ContractError> {
match msg {
HandleMsg::Propose {
title,
description,
msgs,
latest,
} => handle_propose(deps, env, info, title, description, msgs, latest),
HandleMsg::Vote { proposal_id, vote } => handle_vote(deps, env, info, proposal_id, vote),
HandleMsg::Execute { proposal_id } => handle_execute(deps, env, info, proposal_id),
HandleMsg::Close { proposal_id } => handle_close(deps, env, info, proposal_id),
HandleMsg::MemberChangedHook(MemberChangedHookMsg { diffs }) => {
handle_membership_hook(deps, env, info, diffs)
}
}
}
pub fn handle_propose(
deps: DepsMut,
env: Env,
info: MessageInfo,
title: String,
description: String,
msgs: Vec<CosmosMsg>,
// we ignore earliest
latest: Option<Expiration>,
) -> Result<HandleResponse<Empty>, ContractError> {
// only members of the multisig can create a proposal
let raw_sender = deps.api.canonical_address(&info.sender)?;
let cfg = CONFIG.load(deps.storage)?;
let vote_power = cfg
.group_addr
.is_member(&deps.querier, &raw_sender)?
.ok_or_else(|| ContractError::Unauthorized {})?;
// max expires also used as default
let max_expires = cfg.max_voting_period.after(&env.block);
let mut expires = latest.unwrap_or(max_expires);
let comp = expires.partial_cmp(&max_expires);
if let Some(Ordering::Greater) = comp {
expires = max_expires;
} else if comp.is_none() {
return Err(ContractError::WrongExpiration {});
}
let status = if vote_power < cfg.required_weight {
Status::Open
} else {
Status::Passed
};
// create a proposal
let prop = Proposal {
title,
description,
expires,
msgs,
status,
yes_weight: vote_power,
required_weight: cfg.required_weight,
};
let id = next_id(deps.storage)?;
proposals().save(deps.storage, id.into(), &prop)?;
// add the first yes vote from voter
let ballot = Ballot {
weight: vote_power,
vote: Vote::Yes,
};
BALLOTS.save(deps.storage, (id.into(), &raw_sender), &ballot)?;
Ok(HandleResponse {
messages: vec![],
attributes: vec![
attr("action", "propose"),
attr("sender", info.sender),
attr("proposal_id", id),
attr("status", format!("{:?}", prop.status)),
],
data: None,
})
}
pub fn handle_vote(
deps: DepsMut,
env: Env,
info: MessageInfo,
proposal_id: u64,
vote: Vote,
) -> Result<HandleResponse<Empty>, ContractError> {
// only members of the multisig can vote
let raw_sender = deps.api.canonical_address(&info.sender)?;
let cfg = CONFIG.load(deps.storage)?;
let vote_power = cfg
.group_addr
.is_member(&deps.querier, &raw_sender)?
.ok_or_else(|| ContractError::Unauthorized {})?;
// ensure proposal exists and can be voted on
let mut prop = proposals().load(deps.storage, proposal_id.into())?;
if prop.status != Status::Open {
return Err(ContractError::NotOpen {});
}
if prop.expires.is_expired(&env.block) {
return Err(ContractError::Expired {});
}
// cast vote if no vote previously cast
BALLOTS.update(
deps.storage,
(proposal_id.into(), &raw_sender),
|bal| match bal {
Some(_) => Err(ContractError::AlreadyVoted {}),
None => Ok(Ballot {
weight: vote_power,
vote,
}),
},
)?;
// if yes vote, update tally
if vote == Vote::Yes {
prop.yes_weight += vote_power;
// update status when the passing vote comes in
if prop.yes_weight >= prop.required_weight {
prop.status = Status::Passed;
}
proposals().save(deps.storage, proposal_id.into(), &prop)?;
}
Ok(HandleResponse {
messages: vec![],
attributes: vec![
attr("action", "vote"),
attr("sender", info.sender),
attr("proposal_id", proposal_id),
attr("status", format!("{:?}", prop.status)),
],
data: None,
})
}
pub fn handle_execute(
deps: DepsMut,
_env: Env,
info: MessageInfo,
proposal_id: u64,
) -> Result<HandleResponse, ContractError> {
// anyone can trigger this if the vote passed
let mut prop = proposals().load(deps.storage, proposal_id.into())?;
// we allow execution even after the proposal "expiration" as long as all vote come in before
// that point. If it was approved on time, it can be executed any time.
if prop.status != Status::Passed {
return Err(ContractError::WrongExecuteStatus {});
}
// set it to executed
prop.status = Status::Executed;
proposals().save(deps.storage, proposal_id.into(), &prop)?;
// dispatch all proposed messages
Ok(HandleResponse {
messages: prop.msgs,
attributes: vec![
attr("action", "execute"),
attr("sender", info.sender),
attr("proposal_id", proposal_id),
],
data: None,
})
}
pub fn handle_close(
deps: DepsMut,
env: Env,
info: MessageInfo,
proposal_id: u64,
) -> Result<HandleResponse<Empty>, ContractError> {
// anyone can trigger this if the vote passed
let mut prop = proposals().load(deps.storage, proposal_id.into())?;
if [Status::Executed, Status::Rejected, Status::Passed]
.iter()
.any(|x| *x == prop.status)
{
return Err(ContractError::WrongCloseStatus {});
}
if !prop.expires.is_expired(&env.block) {
return Err(ContractError::NotExpired {});
}
// set it to failed
prop.status = Status::Rejected;
proposals().save(deps.storage, proposal_id.into(), &prop)?;
Ok(HandleResponse {
messages: vec![],
attributes: vec![
attr("action", "close"),
attr("sender", info.sender),
attr("proposal_id", proposal_id),
],
data: None,
})
}
pub fn handle_membership_hook(
deps: DepsMut,
_env: Env,
info: MessageInfo,
_diffs: Vec<MemberDiff>,
) -> Result<HandleResponse<Empty>, ContractError> {
// this must be called with the same group contract
let cfg = CONFIG.load(deps.storage)?;
if info.sender != cfg.group_addr.0 {
return Err(ContractError::Unauthorized {});
}
// find all open proposals as (k, v) pairs using secondary index
let open: StdResult<Vec<_>> = proposals()
.idx
.status
.items(
deps.storage,
&status_index(Status::Open),
None,
None,
Order::Ascending,
)
.collect();
// close all open proposals
for (k, mut prop) in open? {
prop.status = Status::Rejected;
// TODO: make this PkOwned cast cleaner
proposals().save(deps.storage, PkOwned(k).into(), &prop)?;
}
Ok(HandleResponse::default())
}
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::Threshold {} => to_binary(&query_threshold(deps)?),
QueryMsg::Proposal { proposal_id } => to_binary(&query_proposal(deps, env, proposal_id)?),
QueryMsg::Vote { proposal_id, voter } => to_binary(&query_vote(deps, proposal_id, voter)?),
QueryMsg::ListProposals { start_after, limit } => {
to_binary(&list_proposals(deps, env, start_after, limit)?)
}
QueryMsg::ReverseProposals {
start_before,
limit,
} => to_binary(&reverse_proposals(deps, env, start_before, limit)?),
QueryMsg::ListVotes {
proposal_id,
start_after,
limit,
} => to_binary(&list_votes(deps, proposal_id, start_after, limit)?),
QueryMsg::Voter { address } => to_binary(&query_voter(deps, address)?),
QueryMsg::ListVoters { start_after, limit } => {
to_binary(&list_voters(deps, start_after, limit)?)
}
}
}
fn query_threshold(deps: Deps) -> StdResult<ThresholdResponse> {
let cfg = CONFIG.load(deps.storage)?;
let total_weight = cfg.group_addr.total_weight(&deps.querier)?;
Ok(ThresholdResponse::AbsoluteCount {
weight_needed: cfg.required_weight,
total_weight,
})
}
fn query_proposal(deps: Deps, env: Env, id: u64) -> StdResult<ProposalResponse> {
let prop = proposals().load(deps.storage, id.into())?;
let status = prop.current_status(&env.block);
Ok(ProposalResponse {
id,
title: prop.title,
description: prop.description,
msgs: prop.msgs,
expires: prop.expires,
status,
})
}
// settings for pagination
const MAX_LIMIT: u32 = 30;
const DEFAULT_LIMIT: u32 = 10;
fn list_proposals(
deps: Deps,
env: Env,
start_after: Option<u64>,
limit: Option<u32>,
) -> StdResult<ProposalListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let start = start_after.map(Bound::exclusive_int);
let props: StdResult<Vec<_>> = proposals()
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|p| map_proposal(&env.block, p))
.collect();
Ok(ProposalListResponse { proposals: props? })
}
fn reverse_proposals(
deps: Deps,
env: Env,
start_before: Option<u64>,
limit: Option<u32>,
) -> StdResult<ProposalListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let end = start_before.map(Bound::exclusive_int);
let props: StdResult<Vec<_>> = proposals()
.range(deps.storage, None, end, Order::Descending)
.take(limit)
.map(|p| map_proposal(&env.block, p))
.collect();
Ok(ProposalListResponse { proposals: props? })
}
fn map_proposal(
block: &BlockInfo,
item: StdResult<(Vec<u8>, Proposal)>,
) -> StdResult<ProposalResponse> {
let (key, prop) = item?;
let status = prop.current_status(block);
Ok(ProposalResponse {
id: parse_id(&key)?,
title: prop.title,
description: prop.description,
msgs: prop.msgs,
expires: prop.expires,
status,
})
}
fn query_vote(deps: Deps, proposal_id: u64, voter: HumanAddr) -> StdResult<VoteResponse> {
let voter_raw = deps.api.canonical_address(&voter)?;
let prop = BALLOTS.may_load(deps.storage, (proposal_id.into(), &voter_raw))?;
let vote = prop.map(|b| b.vote);
Ok(VoteResponse { vote })
}
fn list_votes(
deps: Deps,
proposal_id: u64,
start_after: Option<HumanAddr>,
limit: Option<u32>,
) -> StdResult<VoteListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let canon = maybe_canonical(deps.api, start_after)?;
let start = canon.map(Bound::exclusive);
let api = &deps.api;
let votes: StdResult<Vec<_>> = BALLOTS
.prefix(proposal_id.into())
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|item| {
let (key, ballot) = item?;
Ok(VoteInfo {
voter: api.human_address(&CanonicalAddr::from(key))?,
vote: ballot.vote,
weight: ballot.weight,
})
})
.collect();
Ok(VoteListResponse { votes: votes? })
}
fn query_voter(deps: Deps, voter: HumanAddr) -> StdResult<VoterInfo> {
let cfg = CONFIG.load(deps.storage)?;
let voter_raw = deps.api.canonical_address(&voter)?;
let weight = cfg.group_addr.is_member(&deps.querier, &voter_raw)?;
Ok(VoterInfo { weight })
}
fn list_voters(
deps: Deps,
start_after: Option<HumanAddr>,
limit: Option<u32>,
) -> StdResult<VoterListResponse> {
let cfg = CONFIG.load(deps.storage)?;
let voters = cfg
.group_addr
.list_members(&deps.querier, start_after, limit)?
.into_iter()
.map(|member| VoterResponse {
addr: member.addr,
weight: member.weight,
})
.collect();
Ok(VoterListResponse { voters })
}
#[cfg(test)]
mod tests {
use cosmwasm_std::testing::{mock_env, MockApi, MockStorage};
use cosmwasm_std::{coin, coins, BankMsg, Coin};
use cw0::Duration;
use cw2::{query_contract_info, ContractVersion};
use cw4::{Cw4HandleMsg, Member};
use cw_multi_test::{App, Contract, ContractWrapper, SimpleBank};
use super::*;
const OWNER: &str = "admin0001";
const VOTER1: &str = "voter0001";
const VOTER2: &str = "voter0002";
const VOTER3: &str = "voter0003";
const VOTER4: &str = "voter0004";
const VOTER5: &str = "voter0005";
const SOMEBODY: &str = "somebody";
fn member<T: Into<HumanAddr>>(addr: T, weight: u64) -> Member {
Member {
addr: addr.into(),
weight,
}
}
pub fn contract_flex() -> Box<dyn Contract> {
let contract = ContractWrapper::new(
crate::contract::handle,
crate::contract::init,
crate::contract::query,
);
Box::new(contract)
}
pub fn contract_group() -> Box<dyn Contract> {
let contract = ContractWrapper::new(
cw4_group::contract::handle,
cw4_group::contract::init,
cw4_group::contract::query,
);
Box::new(contract)
}
fn mock_app() -> App {
let env = mock_env();
let api = Box::new(MockApi::default());
let bank = SimpleBank {};
App::new(api, env.block, bank, || Box::new(MockStorage::new()))
}
// uploads code and returns address of group contract
fn init_group(app: &mut App, members: Vec<Member>) -> HumanAddr {
let group_id = app.store_code(contract_group());
let msg = cw4_group::msg::InitMsg {
admin: Some(OWNER.into()),
members,
};
app.instantiate_contract(group_id, OWNER, &msg, &[], "group")
.unwrap()
}
// uploads code and returns address of group contract
fn init_flex(
app: &mut App,
group: HumanAddr,
required_weight: u64,
max_voting_period: Duration,
) -> HumanAddr {
let flex_id = app.store_code(contract_flex());
let msg = crate::msg::InitMsg {
group_addr: group,
required_weight,
max_voting_period,
};
app.instantiate_contract(flex_id, OWNER, &msg, &[], "flex")
.unwrap()
}
// this will set up both contracts, initializing the group with
// all voters defined above, and the multisig pointing to it and given threshold criteria.
// Returns (multisig address, group address).
fn setup_test_case(
app: &mut App,
required_weight: u64,
max_voting_period: Duration,
init_funds: Vec<Coin>,
multisig_as_group_admin: bool,
) -> (HumanAddr, HumanAddr) {
// 1. Initialize group contract with members (and OWNER as admin)
let members = vec![
member(OWNER, 0),
member(VOTER1, 1),
member(VOTER2, 2),
member(VOTER3, 3),
member(VOTER4, 4),
member(VOTER5, 5),
];
let group_addr = init_group(app, members);
// 2. Set up Multisig backed by this group
let flex_addr = init_flex(app, group_addr.clone(), required_weight, max_voting_period);
// 3. Register a hook to the multisig on the group contract
let add_hook = Cw4HandleMsg::AddHook {
addr: flex_addr.clone(),
};
app.execute_contract(OWNER, &group_addr, &add_hook, &[])
.unwrap();
// 4. (Optional) Set the multisig as the group owner
if multisig_as_group_admin {
let update_admin = Cw4HandleMsg::UpdateAdmin {
admin: Some(flex_addr.clone()),
};
app.execute_contract(OWNER, &group_addr, &update_admin, &[])
.unwrap();
}
// Bonus: set some funds on the multisig contract for future proposals
if !init_funds.is_empty() {
app.set_bank_balance(flex_addr.clone(), init_funds).unwrap();
}
(flex_addr, group_addr)
}
fn pay_somebody_proposal(flex_addr: &HumanAddr) -> HandleMsg {
let bank_msg = BankMsg::Send {
from_address: flex_addr.clone(),
to_address: SOMEBODY.into(),
amount: coins(1, "BTC"),
};
let msgs = vec![CosmosMsg::Bank(bank_msg)];
HandleMsg::Propose {
title: "Pay somebody".to_string(),
description: "Do I pay her?".to_string(),
msgs,
latest: None,
}
}
#[test]
fn test_init_works() {
let mut app = mock_app();
// make a simple group
let group_addr = init_group(&mut app, vec![member(OWNER, 1)]);
let flex_id = app.store_code(contract_flex());
let max_voting_period = Duration::Time(1234567);
// Zero required weight fails
let init_msg = InitMsg {
group_addr: group_addr.clone(),
required_weight: 0,
max_voting_period,
};
let res = app.instantiate_contract(flex_id, OWNER, &init_msg, &[], "zero required weight");
// Verify
assert_eq!(res.unwrap_err(), ContractError::ZeroWeight {}.to_string());
// Total weight less than required weight not allowed
let init_msg = InitMsg {
group_addr: group_addr.clone(),
required_weight: 100,
max_voting_period,
};
let res = app.instantiate_contract(flex_id, OWNER, &init_msg, &[], "high required weight");
// Verify
assert_eq!(
res.unwrap_err(),
ContractError::UnreachableWeight {}.to_string()
);
// All valid
let init_msg = InitMsg {
group_addr: group_addr.clone(),
required_weight: 1,
max_voting_period,
};
let flex_addr = app
.instantiate_contract(flex_id, OWNER, &init_msg, &[], "all good")
.unwrap();
// Verify contract version set properly
let version = query_contract_info(&app, &flex_addr).unwrap();
assert_eq!(
ContractVersion {
contract: CONTRACT_NAME.to_string(),
version: CONTRACT_VERSION.to_string(),
},
version,
);
// Get voters query
let voters: VoterListResponse = app
.wrap()
.query_wasm_smart(
&flex_addr,
&QueryMsg::ListVoters {
start_after: None,
limit: None,
},
)
.unwrap();
assert_eq!(
voters.voters,
vec![VoterResponse {
addr: OWNER.into(),
weight: 1
}]
);
}
#[test]
fn test_propose_works() {
let mut app = mock_app();
let required_weight = 4;
let voting_period = Duration::Time(2000000);
let (flex_addr, _) = setup_test_case(
&mut app,
required_weight,
voting_period,
coins(10, "BTC"),
false,
);
let proposal = pay_somebody_proposal(&flex_addr);
// Only voters can propose
let res = app.execute_contract(SOMEBODY, &flex_addr, &proposal, &[]);
assert_eq!(res.unwrap_err(), ContractError::Unauthorized {}.to_string());
// Wrong expiration option fails
let msgs = match proposal.clone() {
HandleMsg::Propose { msgs, .. } => msgs,
_ => panic!("Wrong variant"),
};
let proposal_wrong_exp = HandleMsg::Propose {
title: "Rewarding somebody".to_string(),
description: "Do we reward her?".to_string(),
msgs,
latest: Some(Expiration::AtHeight(123456)),
};
let res = app.execute_contract(OWNER, &flex_addr, &proposal_wrong_exp, &[]);
assert_eq!(
res.unwrap_err(),
ContractError::WrongExpiration {}.to_string()
);
// Proposal from voter works
let res = app
.execute_contract(VOTER3, &flex_addr, &proposal, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "propose"),
attr("sender", VOTER3),
attr("proposal_id", 1),
attr("status", "Open"),
],
);
// Proposal from voter with enough vote power directly passes
let res = app
.execute_contract(VOTER4, &flex_addr, &proposal, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "propose"),
attr("sender", VOTER4),
attr("proposal_id", 2),
attr("status", "Passed"),
],
);
}
fn get_tally(app: &App, flex_addr: &HumanAddr, proposal_id: u64) -> u64 {
// Get all the voters on the proposal
let voters = QueryMsg::ListVotes {
proposal_id,
start_after: None,
limit: None,
};
let votes: VoteListResponse = app.wrap().query_wasm_smart(flex_addr, &voters).unwrap();
// Sum the weights of the Yes votes to get the tally
votes
.votes
.iter()
.filter(|&v| v.vote == Vote::Yes)
.map(|v| v.weight)
.sum()
}
fn expire(voting_period: Duration) -> impl Fn(&mut BlockInfo) {
move |block: &mut BlockInfo| {
match voting_period {
Duration::Time(duration) => block.time += duration + 1,
Duration::Height(duration) => block.height += duration + 1,
};
}
}
fn unexpire(voting_period: Duration) -> impl Fn(&mut BlockInfo) {
move |block: &mut BlockInfo| {
match voting_period {
Duration::Time(duration) => block.time -= duration,
Duration::Height(duration) => block.height -= duration,
};
}
}
#[test]
fn test_vote_works() {
let mut app = mock_app();
let required_weight = 3;
let voting_period = Duration::Time(2000000);
let (flex_addr, _) = setup_test_case(
&mut app,
required_weight,
voting_period,
coins(10, "BTC"),
false,
);
// create proposal with 0 vote power
let proposal = pay_somebody_proposal(&flex_addr);
let res = app
.execute_contract(OWNER, &flex_addr, &proposal, &[])
.unwrap();
// Get the proposal id from the logs
let proposal_id: u64 = res.attributes[2].value.parse().unwrap();
// Owner cannot vote (again)
let yes_vote = HandleMsg::Vote {
proposal_id,
vote: Vote::Yes,
};
let err = app
.execute_contract(OWNER, &flex_addr, &yes_vote, &[])
.unwrap_err();
assert_eq!(err, ContractError::AlreadyVoted {}.to_string());
// Only voters can vote
let err = app
.execute_contract(SOMEBODY, &flex_addr, &yes_vote, &[])
.unwrap_err();
assert_eq!(err, ContractError::Unauthorized {}.to_string());
// But voter1 can
let res = app
.execute_contract(VOTER1, &flex_addr, &yes_vote, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "vote"),
attr("sender", VOTER1),
attr("proposal_id", proposal_id),
attr("status", "Open"),
],
);
// No/Veto votes have no effect on the tally
// Compute the current tally
let tally = get_tally(&app, &flex_addr, proposal_id);
assert_eq!(tally, 1);
// Cast a No vote
let no_vote = HandleMsg::Vote {
proposal_id,
vote: Vote::No,
};
let _ = app
.execute_contract(VOTER2, &flex_addr, &no_vote, &[])
.unwrap();
// Cast a Veto vote
let veto_vote = HandleMsg::Vote {
proposal_id,
vote: Vote::Veto,
};
let _ = app
.execute_contract(VOTER3, &flex_addr, &veto_vote, &[])
.unwrap();
// Tally unchanged
assert_eq!(tally, get_tally(&app, &flex_addr, proposal_id));
let err = app
.execute_contract(VOTER3, &flex_addr, &yes_vote, &[])
.unwrap_err();
assert_eq!(err, ContractError::AlreadyVoted {}.to_string());
// Expired proposals cannot be voted
app.update_block(expire(voting_period));
let err = app
.execute_contract(VOTER4, &flex_addr, &yes_vote, &[])
.unwrap_err();
assert_eq!(err, ContractError::Expired {}.to_string());
app.update_block(unexpire(voting_period));
// Powerful voter supports it, so it passes
let res = app
.execute_contract(VOTER4, &flex_addr, &yes_vote, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "vote"),
attr("sender", VOTER4),
attr("proposal_id", proposal_id),
attr("status", "Passed"),
],
);
// non-Open proposals cannot be voted
let err = app
.execute_contract(VOTER5, &flex_addr, &yes_vote, &[])
.unwrap_err();
assert_eq!(err, ContractError::NotOpen {}.to_string());
}
#[test]
fn test_execute_works() {
let mut app = mock_app();
let required_weight = 3;
let voting_period = Duration::Time(2000000);
let (flex_addr, _) = setup_test_case(
&mut app,
required_weight,
voting_period,
coins(10, "BTC"),
true,
);
// ensure we have cash to cover the proposal
let contract_bal = app.wrap().query_balance(&flex_addr, "BTC").unwrap();
assert_eq!(contract_bal, coin(10, "BTC"));
// create proposal with 0 vote power
let proposal = pay_somebody_proposal(&flex_addr);
let res = app
.execute_contract(OWNER, &flex_addr, &proposal, &[])
.unwrap();
// Get the proposal id from the logs
let proposal_id: u64 = res.attributes[2].value.parse().unwrap();
// Only Passed can be executed
let execution = HandleMsg::Execute { proposal_id };
let err = app
.execute_contract(OWNER, &flex_addr, &execution, &[])
.unwrap_err();
assert_eq!(err, ContractError::WrongExecuteStatus {}.to_string());
// Vote it, so it passes
let vote = HandleMsg::Vote {
proposal_id,
vote: Vote::Yes,
};
let res = app
.execute_contract(VOTER3, &flex_addr, &vote, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "vote"),
attr("sender", VOTER3),
attr("proposal_id", proposal_id),
attr("status", "Passed"),
],
);
// In passing: Try to close Passed fails
let closing = HandleMsg::Close { proposal_id };
let err = app
.execute_contract(OWNER, &flex_addr, &closing, &[])
.unwrap_err();
assert_eq!(err, ContractError::WrongCloseStatus {}.to_string());
// Execute works. Anybody can execute Passed proposals
let res = app
.execute_contract(SOMEBODY, &flex_addr, &execution, &[])
.unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "execute"),
attr("sender", SOMEBODY),
attr("proposal_id", proposal_id),
],
);
// verify money was transfered
let some_bal = app.wrap().query_balance(SOMEBODY, "BTC").unwrap();
assert_eq!(some_bal, coin(1, "BTC"));
let contract_bal = app.wrap().query_balance(&flex_addr, "BTC").unwrap();
assert_eq!(contract_bal, coin(9, "BTC"));
// In passing: Try to close Executed fails
let err = app
.execute_contract(OWNER, &flex_addr, &closing, &[])
.unwrap_err();
assert_eq!(err, ContractError::WrongCloseStatus {}.to_string());
}
#[test]
fn test_close_works() {
let mut app = mock_app();
let required_weight = 3;
let voting_period = Duration::Height(2000000);
let (flex_addr, _) = setup_test_case(
&mut app,
required_weight,
voting_period,
coins(10, "BTC"),
true,
);