Skip to content

Commit

Permalink
add cw_ownable, API docs
Browse files Browse the repository at this point in the history
  • Loading branch information
hard-nett committed Aug 14, 2024
1 parent 3ef2bc7 commit 242c833
Show file tree
Hide file tree
Showing 17 changed files with 101 additions and 49 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions contracts/gauges/gauge-adapter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ cosmwasm-schema = { workspace = true }
cosmwasm-std = { workspace = true }
cw-storage-plus = { workspace = true }
cw2 = { workspace = true }
cw-ownable = { workspace = true }
cw20 = { workspace = true }
cw-denom = { workspace = true }
cw-orch = { workspace = true }
Expand Down
37 changes: 28 additions & 9 deletions contracts/gauges/gauge-adapter/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cw2::set_contract_version;
use cw20::Cw20ReceiveMsg;
use cw_denom::UncheckedDenom;
use cw_utils::{one_coin, PaymentError};
use execute::execute_update_owner;

use crate::{
error::ContractError,
Expand Down Expand Up @@ -39,8 +40,15 @@ pub fn instantiate(
},
)?;

// set owner
cw_ownable::initialize_owner(
deps.storage,
deps.api,
Some(deps.api.addr_validate(&msg.owner)?.as_str()),
)?;

let config = Config {
admin: deps.api.addr_validate(&msg.admin)?,
owner: deps.api.addr_validate(&msg.owner)?,
required_deposit: msg
.required_deposit
.map(|x| x.into_checked(deps.as_ref()))
Expand All @@ -56,7 +64,7 @@ pub fn instantiate(
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
Expand All @@ -76,6 +84,7 @@ pub fn execute(
execute::create_submission(deps, info.sender, name, url, address, received)
}
ExecuteMsg::ReturnDeposits {} => execute::return_deposits(deps, info.sender),
ExecuteMsg::UpdateOwnership(action) => execute_update_owner(deps, info, env, action),
}
}

Expand Down Expand Up @@ -118,7 +127,7 @@ pub mod execute {
required_deposit,
community_pool: _,
reward: _,
admin: _,
owner: _,
} = CONFIG.load(deps.storage)?;
if let Some(required_deposit) = required_deposit {
if let Some(received) = received {
Expand Down Expand Up @@ -157,7 +166,7 @@ pub mod execute {

pub fn return_deposits(deps: DepsMut, sender: Addr) -> Result<Response, ContractError> {
let Config {
admin,
owner,
required_deposit,
community_pool: _,
reward: _,
Expand All @@ -166,7 +175,7 @@ pub mod execute {
// No refund if no deposit was required.
let required_deposit = required_deposit.ok_or(ContractError::NoDepositToRefund {})?;

ensure_eq!(sender, admin, ContractError::Unauthorized {});
ensure_eq!(sender, owner, ContractError::Unauthorized {});

let msgs = SUBMISSIONS
.range(deps.storage, None, None, Order::Ascending)
Expand All @@ -181,6 +190,16 @@ pub mod execute {

Ok(Response::new().add_messages(msgs))
}

pub fn execute_update_owner(
deps: DepsMut,
info: MessageInfo,
env: Env,
action: cw_ownable::Action,
) -> Result<Response, ContractError> {
let ownership = cw_ownable::update_ownership(deps, &env.block, &info.sender, action)?;
Ok(Response::default().add_attributes(ownership.into_attributes()))
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
Expand Down Expand Up @@ -303,7 +322,7 @@ mod tests {
fn proper_initialization() {
let mut deps = mock_dependencies();
let msg = InstantiateMsg {
admin: "admin".to_owned(),
owner: "owner".to_owned(),
required_deposit: Some(AssetUnchecked::new_native("wynd", 10_000_000)),
community_pool: "community".to_owned(),
reward: AssetUnchecked::new_native("ujuno", 150_000_000_000),
Expand All @@ -318,7 +337,7 @@ mod tests {

// Check if the config is stored.
let config = CONFIG.load(deps.as_ref().storage).unwrap();
assert_eq!(config.admin, Addr::unchecked("admin"));
assert_eq!(config.owner, Addr::unchecked("owner"));
assert_eq!(
config.required_deposit,
Some(Asset {
Expand Down Expand Up @@ -370,7 +389,7 @@ mod tests {

let reward = Uint128::new(150_000_000_000);
let msg = InstantiateMsg {
admin: "admin".to_owned(),
owner: "owner".to_owned(),
required_deposit: Some(AssetUnchecked::new_native("wynd", 10_000_000)),
community_pool: "community".to_owned(),
reward: AssetUnchecked::new_native("ujuno", reward.into()),
Expand Down Expand Up @@ -416,7 +435,7 @@ mod tests {
fn return_deposits_authorization() {
let mut deps = mock_dependencies();
let msg = InstantiateMsg {
admin: "admin".to_owned(),
owner: "owner".to_owned(),
required_deposit: None,
community_pool: "community".to_owned(),
reward: AssetUnchecked::new_native("ujuno", 150_000_000_000),
Expand Down
3 changes: 3 additions & 0 deletions contracts/gauges/gauge-adapter/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ pub enum ContractError {

#[error("{0}")]
PaymentError(#[from] PaymentError),

#[error("{0}")]
Ownership(#[from] cw_ownable::OwnershipError),

#[error("{0}")]
DenomError(#[from] DenomError),
Expand Down
12 changes: 9 additions & 3 deletions contracts/gauges/gauge-adapter/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::{Addr, CosmosMsg, Decimal, Uint128};
use cw20::Cw20ReceiveMsg;
use cw_denom::UncheckedDenom;
use cw_ownable::cw_ownable_execute;

#[cw_serde]
pub struct InstantiateMsg {
/// Address that is allowed to return deposits.
pub admin: String,
pub owner: String,
/// Deposit required for valid submission. This option allows to reduce spam.
pub required_deposit: Option<AssetUnchecked>,
/// Address of contract where each deposit is transferred.
Expand All @@ -15,8 +16,10 @@ pub struct InstantiateMsg {
pub reward: AssetUnchecked,
}

#[cw_serde]

#[cw_ownable_execute]
#[derive(cw_orch::ExecuteFns)]
#[cw_serde]
pub enum ExecuteMsg {
/// Implements the Cw20 receiver interface.
Receive(Cw20ReceiveMsg),
Expand Down Expand Up @@ -50,19 +53,22 @@ pub enum MigrateMsg {}
#[cw_serde]
#[derive(QueryResponses, cw_orch::QueryFns)]
pub enum AdapterQueryMsg {
/// Returns adapters internal Config state.
#[returns(crate::state::Config)]
Config {},
/// Returns all available options to vote for.
#[returns(AllOptionsResponse)]
AllOptions {},
/// Checks if a provided option is included in the available options. Returns a boolean.
#[returns(CheckOptionResponse)]
CheckOption { option: String },
/// Returns the messages determined by the current voting results for options.Used by the gauge orchestrator to pass messages for DAO to execute.
#[returns(SampleGaugeMsgsResponse)]
SampleGaugeMsgs {
/// Option along with weight.
/// Sum of all weights should be 1.0 (within rounding error).
selected: Vec<(String, Decimal)>,
},

// Marketing-gauge specific queries to help on frontend
#[returns(SubmissionResponse)]
Submission { address: String },
Expand Down
2 changes: 1 addition & 1 deletion contracts/gauges/gauge-adapter/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use cw_storage_plus::{Item, Map};
#[cw_serde]
pub struct Config {
/// Address that is allowed to return deposits.
pub admin: Addr,
pub owner: Addr,
/// Deposit required for valid submission.
pub required_deposit: Option<Asset>,
/// Address of contract where each deposit is transferred.
Expand Down
1 change: 1 addition & 0 deletions contracts/gauges/gauge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ cosmwasm-schema = { workspace = true }
cosmwasm-std = { workspace = true }
dao-interface = { workspace = true }
cw-orch = { workspace = true }
cw-ownable = { workspace = true }
cw-storage-plus = { workspace = true }
cw-utils = { workspace = true }
cw2 = { workspace = true }
Expand Down
24 changes: 5 additions & 19 deletions contracts/gauges/gauge/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,13 @@ pub fn instantiate(
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
cw_ownable::initialize_owner(deps.storage, deps.api, Some(&msg.owner))?;

let voting_powers = deps.api.addr_validate(&msg.voting_powers)?;
let hook_caller = deps.api.addr_validate(&msg.hook_caller)?;
let owner = deps.api.addr_validate(&msg.owner)?;
let config = Config {
voting_powers,
hook_caller,
owner,
dao_core: info.sender,
};
CONFIG.save(deps.storage, &config)?;
Expand Down Expand Up @@ -372,10 +371,7 @@ mod execute {
sender: Addr,
options: GaugeConfig,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
if sender != config.owner {
return Err(ContractError::Unauthorized {});
}
cw_ownable::assert_owner(deps.storage, &sender)?;

let adapter = attach_gauge(deps, env, options)?;

Expand Down Expand Up @@ -460,10 +456,7 @@ mod execute {
max_options_selected: Option<u32>,
max_available_percentage: Option<Decimal>,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
if sender != config.owner {
return Err(ContractError::Unauthorized {});
}
cw_ownable::assert_owner(deps.storage, &sender)?;

let mut gauge = GAUGES.load(deps.storage, gauge_id)?;
if let Some(epoch_size) = epoch_size {
Expand Down Expand Up @@ -513,10 +506,7 @@ mod execute {
sender: Addr,
gauge_id: GaugeId,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
if sender != config.owner {
return Err(ContractError::Unauthorized {});
}
cw_ownable::assert_owner(deps.storage, &sender)?;

let gauge = GAUGES.load(deps.storage, gauge_id)?;
let gauge = Gauge {
Expand All @@ -542,10 +532,7 @@ mod execute {
};

// only owner can remove option for now
if sender != CONFIG.load(deps.storage)?.owner {
return Err(ContractError::Unauthorized {});
}

cw_ownable::assert_owner(deps.storage, &sender)?;
remove_tally(deps.storage, gauge_id, &option)?;

Ok(Response::new()
Expand Down Expand Up @@ -817,7 +804,6 @@ mod execute {

msgs.extend(execute_messages.execute);


// increments epoch count
gauge.count = gauge.increment_gauge_count()?;

Expand Down
2 changes: 2 additions & 0 deletions contracts/gauges/gauge/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ pub enum ContractError {

#[error("Unauthorized")]
Unauthorized {},
#[error("{0}")]
Ownership(#[from] cw_ownable::OwnershipError),

#[error("Gauge with ID {0} does not exists")]
GaugeMissing(u64),
Expand Down
12 changes: 10 additions & 2 deletions contracts/gauges/gauge/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ type GaugeId = u64;
pub struct InstantiateMsg {
/// Address of contract to that contains all voting powers (where we query)
pub voting_powers: String,
/// Addres that will call voting power change hooks (often same as voting power contract)
/// Address that will call voting power change hooks (often same as voting power contract)
pub hook_caller: String,
/// Address that can add new gauges or stop them
/// Optional Address that can add new gauges or stop them
pub owner: String,
/// Allow attaching multiple adaptors during instantiation.
/// Important, as instantiation and CreateGauge both come from DAO proposals
Expand Down Expand Up @@ -105,31 +105,39 @@ pub struct CreateGaugeReply {
#[cw_serde]
#[derive(QueryResponses, cw_orch::QueryFns)]
pub enum QueryMsg {
/// General contract info
#[returns(dao_interface::voting::InfoResponse)]
Info {},
/// Returns details for a specific gauge.
#[returns(GaugeResponse)]
Gauge { id: u64 },
/// List all gauges
#[returns(ListGaugesResponse)]
ListGauges {
start_after: Option<u64>,
limit: Option<u32>,
},
/// Returns the vote for a given voter
#[returns(VoteResponse)]
Vote { gauge: u64, voter: String },
/// Returns a list of all unexpired votes for a specific gauge-id
#[returns(ListVotesResponse)]
ListVotes {
gauge: u64,
start_after: Option<String>,
limit: Option<u32>,
},
/// Returns a list of all options available to vote for a specific gauge-id
#[returns(ListOptionsResponse)]
ListOptions {
gauge: u64,
start_after: Option<String>,
limit: Option<u32>,
},
/// Returns the selected messages that were determined by voting
#[returns(SelectedSetResponse)]
SelectedSet { gauge: u64 },
/// Returns the last selected messages that were executed by the DAO
#[returns(LastExecutedSetResponse)]
LastExecutedSet { gauge: u64 },
}
Expand Down
10 changes: 8 additions & 2 deletions contracts/gauges/gauge/src/multitest/gauge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,10 @@ fn execute_stopped_gauge() {
let err = suite
.stop_gauge(&gauge_contract, voter1, gauge_id)
.unwrap_err();
assert_eq!(ContractError::Unauthorized {}, err.downcast().unwrap());
assert_eq!(
ContractError::Ownership(cw_ownable::OwnershipError::NotOwner),
err.downcast().unwrap()
);

// stop the gauge by owner
suite
Expand Down Expand Up @@ -759,7 +762,10 @@ fn update_gauge() {
None,
)
.unwrap_err();
assert_eq!(ContractError::Unauthorized {}, err.downcast().unwrap());
assert_eq!(
ContractError::Ownership(cw_ownable::OwnershipError::NotOwner),
err.downcast().unwrap()
);

let err = suite
.update_gauge(
Expand Down
Loading

0 comments on commit 242c833

Please sign in to comment.