Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Snapshot cw4 (take 2) #166

Merged
merged 6 commits into from
Dec 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 25 additions & 45 deletions contracts/cw3-flex-multisig/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@ use cw_storage_plus::Bound;

use crate::error::ContractError;
use crate::msg::{HandleMsg, InitMsg, QueryMsg};
use crate::snapshot::{snapshot_diff, snapshoted_weight};
use crate::state::{
max_proposal_height, next_id, parse_id, proposals, Ballot, Config, Proposal, BALLOTS, CONFIG,
};
use crate::state::{next_id, parse_id, Ballot, Config, Proposal, BALLOTS, CONFIG, PROPOSALS};

// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cw3-flex-multisig";
Expand Down Expand Up @@ -129,7 +126,7 @@ pub fn handle_propose(
required_weight: cfg.required_weight,
};
let id = next_id(deps.storage)?;
proposals().save(deps.storage, id.into(), &prop)?;
PROPOSALS.save(deps.storage, id.into(), &prop)?;

// add the first yes vote from voter
let ballot = Ballot {
Expand Down Expand Up @@ -162,7 +159,7 @@ pub fn handle_vote(
let cfg = CONFIG.load(deps.storage)?;

// ensure proposal exists and can be voted on
let mut prop = proposals().load(deps.storage, proposal_id.into())?;
let mut prop = PROPOSALS.load(deps.storage, proposal_id.into())?;
if prop.status != Status::Open {
return Err(ContractError::NotOpen {});
}
Expand All @@ -171,13 +168,10 @@ pub fn handle_vote(
}

// use a snapshot of "start of proposal" if available, otherwise, current group weight
let vote_power = snapshoted_weight(
deps.as_ref(),
&raw_sender,
prop.start_height,
&cfg.group_addr,
)?
.ok_or_else(|| ContractError::Unauthorized {})?;
let vote_power = cfg
.group_addr
.member_at_height(&deps.querier, info.sender.clone(), prop.start_height)?
.ok_or_else(|| ContractError::Unauthorized {})?;

// cast vote if no vote previously cast
BALLOTS.update(
Expand All @@ -199,7 +193,7 @@ pub fn handle_vote(
if prop.yes_weight >= prop.required_weight {
prop.status = Status::Passed;
}
proposals().save(deps.storage, proposal_id.into(), &prop)?;
PROPOSALS.save(deps.storage, proposal_id.into(), &prop)?;
}

Ok(HandleResponse {
Expand All @@ -222,7 +216,7 @@ pub fn handle_execute(
) -> Result<HandleResponse, ContractError> {
// anyone can trigger this if the vote passed

let mut prop = proposals().load(deps.storage, proposal_id.into())?;
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 {
Expand All @@ -231,7 +225,7 @@ pub fn handle_execute(

// set it to executed
prop.status = Status::Executed;
proposals().save(deps.storage, proposal_id.into(), &prop)?;
PROPOSALS.save(deps.storage, proposal_id.into(), &prop)?;

// dispatch all proposed messages
Ok(HandleResponse {
Expand All @@ -253,7 +247,7 @@ pub fn handle_close(
) -> Result<HandleResponse<Empty>, ContractError> {
// anyone can trigger this if the vote passed

let mut prop = proposals().load(deps.storage, proposal_id.into())?;
let mut prop = PROPOSALS.load(deps.storage, proposal_id.into())?;
if [Status::Executed, Status::Rejected, Status::Passed]
.iter()
.any(|x| *x == prop.status)
Expand All @@ -266,7 +260,7 @@ pub fn handle_close(

// set it to failed
prop.status = Status::Rejected;
proposals().save(deps.storage, proposal_id.into(), &prop)?;
PROPOSALS.save(deps.storage, proposal_id.into(), &prop)?;

Ok(HandleResponse {
messages: vec![],
Expand All @@ -280,28 +274,18 @@ pub fn handle_close(
}

pub fn handle_membership_hook(
mut deps: DepsMut,
env: Env,
deps: DepsMut,
_env: Env,
info: MessageInfo,
diffs: Vec<MemberDiff>,
_diffs: Vec<MemberDiff>,
) -> Result<HandleResponse<Empty>, ContractError> {
// this must be called with the same group contract
// This is now a no-op
// But we leave the authorization check as a demo
let cfg = CONFIG.load(deps.storage)?;
if info.sender != cfg.group_addr.0 {
return Err(ContractError::Unauthorized {});
}

// find the latest snapshot height
let max_height = max_proposal_height(deps.storage)?;

// only try snapshot if there is an open proposal
if let Some(last_height) = max_height {
// save the diff if we have no diff on that account since last snapshot
for diff in diffs {
snapshot_diff(deps.branch(), diff, env.block.height, last_height)?;
}
}

Ok(HandleResponse::default())
}

Expand Down Expand Up @@ -339,7 +323,7 @@ fn query_threshold(deps: Deps) -> StdResult<ThresholdResponse> {
}

fn query_proposal(deps: Deps, env: Env, id: u64) -> StdResult<ProposalResponse> {
let prop = proposals().load(deps.storage, id.into())?;
let prop = PROPOSALS.load(deps.storage, id.into())?;
let status = prop.current_status(&env.block);
Ok(ProposalResponse {
id,
Expand All @@ -363,7 +347,7 @@ fn list_proposals(
) -> 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()
let props: StdResult<Vec<_>> = PROPOSALS
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|p| map_proposal(&env.block, p))
Expand All @@ -380,7 +364,7 @@ fn reverse_proposals(
) -> 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()
let props: StdResult<Vec<_>> = PROPOSALS
.range(deps.storage, None, end, Order::Descending)
.take(limit)
.map(|p| map_proposal(&env.block, p))
Expand Down Expand Up @@ -474,7 +458,7 @@ mod tests {
use cw0::Duration;
use cw2::{query_contract_info, ContractVersion};
use cw4::{Cw4HandleMsg, Member};
use cw_multi_test::{App, Contract, ContractWrapper, SimpleBank};
use cw_multi_test::{next_block, App, Contract, ContractWrapper, SimpleBank};

use super::*;

Expand Down Expand Up @@ -567,24 +551,20 @@ mod tests {
member(VOTER5, 5),
];
let group_addr = init_group(app, members);
app.update_block(next_block);

// 2. Set up Multisig backed by this group
let flex_addr = init_flex(app, group_addr.clone(), required_weight, max_voting_period);
app.update_block(next_block);

// 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
// 3. (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();
app.update_block(next_block);
}

// Bonus: set some funds on the multisig contract for future proposals
Expand Down
1 change: 0 additions & 1 deletion contracts/cw3-flex-multisig/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
pub mod contract;
mod error;
pub mod msg;
mod snapshot;
pub mod state;

#[cfg(all(target_arch = "wasm32", not(feature = "library")))]
Expand Down
61 changes: 0 additions & 61 deletions contracts/cw3-flex-multisig/src/snapshot.rs

This file was deleted.

72 changes: 3 additions & 69 deletions contracts/cw3-flex-multisig/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;

use cosmwasm_std::{BlockInfo, CosmosMsg, Empty, Order, StdError, StdResult, Storage};
use cosmwasm_std::{BlockInfo, CosmosMsg, Empty, StdError, StdResult, Storage};

use cw0::{Duration, Expiration};
use cw3::{Status, Vote};
use cw4::Cw4Contract;
use cw_storage_plus::{
range_with_prefix, Index, IndexList, IndexedMap, Item, Map, MultiIndex, Prefix, U64Key,
};
use cw_storage_plus::{Item, Map, U64Key};

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Config {
Expand All @@ -34,7 +32,6 @@ pub struct Proposal {
}

impl Proposal {
/// TODO: we should get the current BlockInfo and then we can determine this a bit better
pub fn current_status(&self, block: &BlockInfo) -> Status {
let mut status = self.status;

Expand All @@ -50,38 +47,6 @@ impl Proposal {
}
}

pub fn max_proposal_height(storage: &dyn Storage) -> StdResult<Option<u64>> {
// we grab the last height under Status::Open s O(1)
// unfortunately there is no good API for it, we have to reverse the format of MultiIndex
// it uses `Map<'a, (&'a [u8], &'a [u8]), u32>` with namespace b"proposals__status"
// keys there are formed from (b"proposals__status", index, pk) with the first 2 length-prefixed
//
// we know that index is always 9 bytes, and if we try to query with just the status byte it has
// the wrong length-prefix.
// We can find the prefix for status_height_index(h=0) (with proper length prefix)
// then trim off the last 8 bytes (height), and do a range_prefix query to scan the first value in that space
// ooff... do not try this at home. One day I will add an API for it in storage-plus
let prefix = Prefix::<u32>::new(
b"proposals__status",
&[&status_height_index(Status::Open, 0)],
);
let cutoff = prefix.len() - 8;
let raw_prefix = &prefix[..cutoff];

let last = range_with_prefix(storage, raw_prefix, None, None, Order::Descending).next();
let res = match last {
Some((k, _)) => {
// k is big-endian encoding of u64 (first 8 bytes)
let fixed: [u8; 8] = k[..8].try_into().map_err(|e| {
StdError::generic_err(format!("wrong length for k: {} - {}", k.len(), e))
})?;
Some(u64::from_be_bytes(fixed))
}
None => None,
};
Ok(res)
}

// we cast a ballot with our chosen vote and a given weight
// stored under the key that voted
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
Expand All @@ -96,6 +61,7 @@ pub const PROPOSAL_COUNT: Item<u64> = Item::new(b"proposal_count");

// multiple-item map
pub const BALLOTS: Map<(U64Key, &[u8]), Ballot> = Map::new(b"votes");
pub const PROPOSALS: Map<U64Key, Proposal> = Map::new(b"proposals");

pub fn next_id(store: &mut dyn Storage) -> StdResult<u64> {
let id: u64 = PROPOSAL_COUNT.may_load(store)?.unwrap_or_default() + 1;
Expand All @@ -111,35 +77,3 @@ pub fn parse_id(data: &[u8]) -> StdResult<u64> {
)),
}
}

// pub const PROPOSALS: Map<U64Key, Proposal> = Map::new(b"proposals");

pub struct ProposalIndexes<'a> {
pub status: MultiIndex<'a, Proposal>,
}

impl<'a> IndexList<Proposal> for ProposalIndexes<'a> {
fn get_indexes(&'_ self) -> Box<dyn Iterator<Item = &'_ dyn Index<Proposal>> + '_> {
let v: Vec<&dyn Index<Proposal>> = vec![&self.status];
Box::new(v.into_iter())
}
}

/// Returns a value that can be used as a secondary index key in the proposals map
pub fn status_height_index(status: Status, height: u64) -> Vec<u8> {
let mut idx = vec![status as u8];
idx.extend_from_slice(&height.to_be_bytes());
idx
}

// secondary indexes on state for PROPOSALS to find all open proposals efficiently
pub fn proposals<'a>() -> IndexedMap<'a, U64Key, Proposal, ProposalIndexes<'a>> {
let indexes = ProposalIndexes {
status: MultiIndex::new(
|p| status_height_index(p.status, p.start_height),
b"proposals",
b"proposals__status",
),
};
IndexedMap::new(b"proposals", indexes)
}
8 changes: 8 additions & 0 deletions contracts/cw4-group/schema/query_msg.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@
"properties": {
"addr": {
"$ref": "#/definitions/HumanAddr"
},
"at_height": {
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0.0
}
}
}
Expand Down
Loading