From 1446b56c39f6b5bfb9856d8fcb764a7828493906 Mon Sep 17 00:00:00 2001 From: Samuel Barbosa Date: Fri, 29 Jul 2022 17:37:34 -0500 Subject: [PATCH] chore: consolidated error types. --- contracts/contracts/hub/src/contract.rs | 26 +++++--- contracts/contracts/hub/src/errors.rs | 11 ---- contracts/contracts/hub/src/lib.rs | 1 - contracts/contracts/offer/src/contract.rs | 24 +++---- contracts/contracts/offer/src/errors.rs | 17 ----- contracts/contracts/offer/src/lib.rs | 1 - contracts/contracts/trade/src/contract.rs | 45 +++++++------ contracts/contracts/trade/src/errors.rs | 63 ------------------- contracts/contracts/trade/src/lib.rs | 1 - .../trading_incentives/src/contract.rs | 39 +++++++----- .../trading_incentives/src/errors.rs | 14 ----- .../contracts/trading_incentives/src/lib.rs | 1 - contracts/packages/protocol/src/errors.rs | 42 ++++++++----- contracts/packages/protocol/src/guards.rs | 52 +++++---------- 14 files changed, 116 insertions(+), 221 deletions(-) delete mode 100644 contracts/contracts/hub/src/errors.rs delete mode 100644 contracts/contracts/offer/src/errors.rs delete mode 100644 contracts/contracts/trade/src/errors.rs delete mode 100644 contracts/contracts/trading_incentives/src/errors.rs diff --git a/contracts/contracts/hub/src/contract.rs b/contracts/contracts/hub/src/contract.rs index f8c5adcb..e01df8f8 100644 --- a/contracts/contracts/hub/src/contract.rs +++ b/contracts/contracts/hub/src/contract.rs @@ -1,9 +1,9 @@ use cosmwasm_std::{entry_point, Addr, Binary, Deps, StdResult}; use cosmwasm_std::{to_binary, CosmosMsg, DepsMut, Env, MessageInfo, Response, SubMsg, WasmMsg}; use cw20::Denom; +use localterra_protocol::errors::ContractError; +use localterra_protocol::errors::ContractError::Unauthorized; -use crate::errors::HubError; -use crate::errors::HubError::Unauthorized; use crate::state::{ADMIN, CONFIG}; use localterra_protocol::hub::{Admin, ExecuteMsg, HubConfig, InstantiateMsg, QueryMsg}; use localterra_protocol::offer::ExecuteMsg::RegisterHub as OfferRegisterHub; @@ -16,7 +16,7 @@ pub fn instantiate( _env: Env, _info: MessageInfo, msg: InstantiateMsg, -) -> Result { +) -> Result { let admin = Admin { addr: msg.admin_addr.clone(), }; @@ -32,7 +32,7 @@ pub fn execute( _env: Env, info: MessageInfo, msg: ExecuteMsg, -) -> Result { +) -> Result { match msg { ExecuteMsg::UpdateConfig(config) => update_config(deps, info, config), ExecuteMsg::UpdateAdmin { admin_addr } => update_admin(deps, info, admin_addr), @@ -43,10 +43,13 @@ fn update_config( deps: DepsMut, info: MessageInfo, config: HubConfig, -) -> Result { +) -> Result { let admin = ADMIN.load(deps.storage).unwrap(); if !info.sender.eq(&admin.addr) { - return Err(Unauthorized {}); + return Err(Unauthorized { + owner: admin.addr.clone(), + caller: info.sender.clone(), + }); } CONFIG.save(deps.storage, &config).unwrap(); let local_denom = match config.local_denom { @@ -85,10 +88,17 @@ fn update_config( Ok(res) } -fn update_admin(deps: DepsMut, info: MessageInfo, new_admin: Addr) -> Result { +fn update_admin( + deps: DepsMut, + info: MessageInfo, + new_admin: Addr, +) -> Result { let mut admin = ADMIN.load(deps.storage).unwrap(); if !info.sender.eq(&admin.addr) { - return Err(Unauthorized {}); + return Err(Unauthorized { + owner: admin.addr.clone(), + caller: info.sender.clone(), + }); } let old_admin = admin.addr.clone(); diff --git a/contracts/contracts/hub/src/errors.rs b/contracts/contracts/hub/src/errors.rs deleted file mode 100644 index dd914a04..00000000 --- a/contracts/contracts/hub/src/errors.rs +++ /dev/null @@ -1,11 +0,0 @@ -use cosmwasm_std::StdError; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum HubError { - #[error("{0}")] - Std(#[from] StdError), - - #[error("Unauthorized")] - Unauthorized {}, -} diff --git a/contracts/contracts/hub/src/lib.rs b/contracts/contracts/hub/src/lib.rs index 6b8e3f0d..f83e2003 100644 --- a/contracts/contracts/hub/src/lib.rs +++ b/contracts/contracts/hub/src/lib.rs @@ -1,3 +1,2 @@ pub mod contract; -pub mod errors; mod state; diff --git a/contracts/contracts/offer/src/contract.rs b/contracts/contracts/offer/src/contract.rs index 76950757..9dd4671d 100644 --- a/contracts/contracts/offer/src/contract.rs +++ b/contracts/contracts/offer/src/contract.rs @@ -5,8 +5,8 @@ use cosmwasm_std::{ use cw_storage_plus::Bound; use localterra_protocol::currencies::FiatCurrency; -use localterra_protocol::errors::GuardError; -use localterra_protocol::errors::GuardError::{HubAlreadyRegistered, Unauthorized}; +use localterra_protocol::errors::ContractError; +use localterra_protocol::errors::ContractError::{HubAlreadyRegistered, Unauthorized}; use localterra_protocol::guards::{assert_min_g_max, assert_ownership, assert_range_0_to_99}; use localterra_protocol::hub::HubConfig; use localterra_protocol::hub_utils::{ @@ -25,7 +25,7 @@ pub fn instantiate( _env: Env, _info: MessageInfo, _msg: InstantiateMsg, -) -> Result { +) -> Result { offers_count_storage(deps.storage).save(&OffersCount { count: 0 })?; Ok(Response::default()) } @@ -36,7 +36,7 @@ pub fn execute( env: Env, info: MessageInfo, msg: ExecuteMsg, -) -> Result { +) -> Result { match msg { ExecuteMsg::Create { offer } => create_offer(deps, env, info, offer), ExecuteMsg::UpdateOffer { offer_update } => update_offer(deps, env, info, offer_update), @@ -112,7 +112,7 @@ pub fn create_offer( env: Env, info: MessageInfo, msg: OfferMsg, -) -> Result { +) -> Result { assert_min_g_max(msg.min_amount, msg.max_amount)?; let mut offers_count = offers_count_storage(deps.storage).load().unwrap(); @@ -159,7 +159,7 @@ pub fn execute_update_trade_arbitrator( _env: Env, info: MessageInfo, arbitrator: Addr, -) -> Result { +) -> Result { // TODO assert the calling contract can only update its own arbitrator and only if the arbitrator is not yet set. LOCAL-660 let mut trade = trades().load(deps.storage, &info.sender.as_str())?; @@ -183,7 +183,7 @@ pub fn execute_update_last_traded( env: Env, info: MessageInfo, offer_id: String, -) -> Result { +) -> Result { let hub_addr = query_hub_addr(deps.as_ref()).unwrap(); let hub_config = get_hub_config(&deps.querier, hub_addr.addr.to_string()); @@ -214,7 +214,7 @@ pub fn create_arbitrator( info: MessageInfo, arbitrator: Addr, asset: FiatCurrency, -) -> Result { +) -> Result { let hub_addr = HUB_ADDR.load(deps.storage).unwrap(); let admin = get_hub_admin(&deps.querier, hub_addr.addr.to_string()); assert_ownership(info.sender, admin)?; @@ -248,7 +248,7 @@ pub fn delete_arbitrator( info: MessageInfo, arbitrator: Addr, asset: FiatCurrency, -) -> Result { +) -> Result { let hub_addr = HUB_ADDR.load(deps.storage).unwrap(); let admin = get_hub_admin(&deps.querier, hub_addr.addr.to_string()); assert_ownership(info.sender, admin)?; @@ -270,7 +270,7 @@ pub fn update_offer( _env: Env, info: MessageInfo, msg: OfferUpdateMsg, -) -> Result { +) -> Result { assert_min_g_max(msg.min_amount, msg.max_amount)?; let mut offer_model = OfferModel::may_load(deps.storage, &msg.id); @@ -287,7 +287,7 @@ pub fn update_offer( Ok(res) } -fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { +fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { register_hub_internal(info.sender, deps.storage, HubAlreadyRegistered {}) } @@ -295,7 +295,7 @@ fn increment_trades_count( deps: DepsMut, info: MessageInfo, offer_id: String, -) -> Result { +) -> Result { let hub_addr = query_hub_addr(deps.as_ref()).unwrap(); let hub_cfg: HubConfig = get_hub_config(&deps.querier, hub_addr.addr.to_string()); diff --git a/contracts/contracts/offer/src/errors.rs b/contracts/contracts/offer/src/errors.rs deleted file mode 100644 index 59c6bd70..00000000 --- a/contracts/contracts/offer/src/errors.rs +++ /dev/null @@ -1,17 +0,0 @@ -use cosmwasm_std::{Addr, StdError}; -use localterra_protocol::offer::OfferState; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum OfferError { - #[error("{0}")] - Std(#[from] StdError), - #[error("Invalid state change.")] - InvalidStateChange { from: OfferState, to: OfferState }, - #[error("Unauthorized.")] - Unauthorized { owner: Addr, caller: Addr }, - #[error("Governance not found.")] - GovernanceNotFound { gov_addr: Addr }, - #[error("Invalid reply message id.")] - InvalidReply {}, -} diff --git a/contracts/contracts/offer/src/lib.rs b/contracts/contracts/offer/src/lib.rs index 6b4a226e..3407c199 100644 --- a/contracts/contracts/offer/src/lib.rs +++ b/contracts/contracts/offer/src/lib.rs @@ -1,3 +1,2 @@ pub mod contract; -pub mod errors; pub mod state; diff --git a/contracts/contracts/trade/src/contract.rs b/contracts/contracts/trade/src/contract.rs index c43cdd02..c24b1311 100644 --- a/contracts/contracts/trade/src/contract.rs +++ b/contracts/contracts/trade/src/contract.rs @@ -8,6 +8,11 @@ use std::str::FromStr; use localterra_protocol::constants::{FUNDING_TIMEOUT, LOCAL_FEE, REQUEST_TIMEOUT}; use localterra_protocol::denom_utils::denom_to_string; +use localterra_protocol::errors::ContractError; +use localterra_protocol::errors::ContractError::{ + FundEscrowError, HubAlreadyRegistered, InvalidTradeStateChange, OfferNotFound, + RefundErrorNotExpired, TradeExpired, +}; use localterra_protocol::guards::{ assert_caller_is_buyer_or_seller, assert_ownership, assert_trade_state_and_type, assert_trade_state_change_is_valid, assert_value_in_range, trade_request_is_expired, @@ -24,9 +29,6 @@ use localterra_protocol::trade::{ }; use localterra_protocol::trading_incentives::ExecuteMsg as TradingIncentivesMsg; -use crate::errors::TradeError; -use crate::errors::TradeError::HubAlreadyRegistered; - pub const SWAP_REPLY_ID: u64 = 1u64; #[entry_point] @@ -35,7 +37,7 @@ pub fn instantiate( _env: Env, _info: MessageInfo, _msg: InstantiateMsg, -) -> Result { +) -> Result { Ok(Response::default()) } @@ -45,7 +47,7 @@ pub fn execute( env: Env, info: MessageInfo, msg: ExecuteMsg, -) -> Result { +) -> Result { match msg { ExecuteMsg::Create(new_trade) => create_trade(deps, env, new_trade), ExecuteMsg::AcceptRequest { trade_id } => accept_request(deps, env, info, trade_id), @@ -59,7 +61,7 @@ pub fn execute( } } -fn create_trade(deps: DepsMut, env: Env, new_trade: NewTrade) -> Result { +fn create_trade(deps: DepsMut, env: Env, new_trade: NewTrade) -> Result { //Load Offer let hub_addr = HUB_ADDR.load(deps.storage).unwrap(); let hub_cfg = get_hub_config(&deps.querier, hub_addr.addr.to_string()); @@ -71,7 +73,7 @@ fn create_trade(deps: DepsMut, env: Env, new_trade: NewTrade) -> Result StdResult { } } -fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { +fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { register_hub_internal(info.sender, deps.storage, HubAlreadyRegistered {}) } @@ -211,7 +213,7 @@ fn fund_escrow( env: Env, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); let offer = load_offer( @@ -226,7 +228,7 @@ fn fund_escrow( trade.state = TradeState::RequestExpired; TradeModel::store(deps.storage, &trade).unwrap(); - return Err(TradeError::Expired { + return Err(TradeExpired { timeout: REQUEST_TIMEOUT, expired_at: env.block.time.seconds() + REQUEST_TIMEOUT, created_at: trade.created_at, @@ -250,7 +252,7 @@ fn fund_escrow( if balance.amount >= trade.amount { trade.state = TradeState::EscrowFunded; } else { - return Err(TradeError::FundEscrowError { + return Err(FundEscrowError { required_amount: trade.amount.clone(), sent_amount: balance.amount.clone(), }); @@ -272,7 +274,7 @@ fn dispute_escrow( env: Env, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); // TODO check escrow funding timer* // Only the buyer or seller can start a dispute @@ -328,7 +330,7 @@ fn accept_request( _env: Env, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); // Only the buyer can accept the request assert_ownership(info.sender, trade.buyer.clone()).unwrap(); @@ -357,7 +359,7 @@ fn fiat_deposited( deps: DepsMut, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); // The buyer is always the one depositing fiat // Only the buyer can mark the fiat as deposited @@ -386,7 +388,7 @@ fn cancel_request( deps: DepsMut, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); // Only the buyer or seller can cancel the trade. assert_caller_is_buyer_or_seller(info.sender, trade.buyer.clone(), trade.seller.clone()) @@ -396,7 +398,7 @@ fn cancel_request( if !((trade.state == TradeState::RequestCreated) || (trade.state == TradeState::RequestAccepted)) { - return Err(TradeError::InvalidStateChange { + return Err(InvalidTradeStateChange { from: trade.state, to: TradeState::RequestCanceled, }); @@ -413,11 +415,9 @@ fn release_escrow( deps: DepsMut, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let mut trade = TradeModel::from_store(deps.storage, &trade_id); let trade_denom = denom_to_string(&trade.denom); - - let arbitrator = trade.arbitrator.clone().unwrap_or(Addr::unchecked("")); if trade.seller.eq(&info.sender) { assert_trade_state_change_is_valid( trade.state.clone(), @@ -426,9 +426,8 @@ fn release_escrow( ) .unwrap(); } else { - return Err(TradeError::Unauthorized { + return Err(ContractError::Unauthorized { owner: trade.seller.clone(), - arbitrator: arbitrator.clone(), caller: info.sender.clone(), }); } @@ -581,7 +580,7 @@ fn handle_swap_reply(_deps: DepsMut, msg: Reply) -> StdResult { Ok(res) } -fn refund_escrow(deps: DepsMut, env: Env, trade_id: String) -> Result { +fn refund_escrow(deps: DepsMut, env: Env, trade_id: String) -> Result { // Refund can only happen if trade state is TradeState::EscrowFunded and FundingTimeout is expired let trade = TradeModel::from_store(deps.storage, &trade_id); assert_trade_state_change_is_valid( @@ -595,7 +594,7 @@ fn refund_escrow(deps: DepsMut, env: Env, trade_id: String) -> Result trade.created_at + FUNDING_TIMEOUT; if !expired { - return Err(TradeError::RefundErrorNotExpired { + return Err(RefundErrorNotExpired { message: "Only expired trades that are not disputed can be refunded by non-arbitrators." .to_string(), diff --git a/contracts/contracts/trade/src/errors.rs b/contracts/contracts/trade/src/errors.rs deleted file mode 100644 index e5e5aa5b..00000000 --- a/contracts/contracts/trade/src/errors.rs +++ /dev/null @@ -1,63 +0,0 @@ -use cosmwasm_std::{Addr, StdError, Uint128}; -use localterra_protocol::trade::TradeState; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum TradeError { - #[error("{0}")] - Std(#[from] StdError), - #[error("Amount is outside of offer amount range.")] - AmountError { - amount: Uint128, - min_amount: Uint128, - max_amount: Uint128, - }, - #[error("Invalid trade state change.")] - InvalidStateChange { from: TradeState, to: TradeState }, - #[error("Failed to execute contract.")] - ExecutionError { message: String }, - #[error("This trade has expired.")] - Expired { - timeout: u64, - expired_at: u64, - created_at: u64, - }, - #[error("Failed to instantiate contract.")] - InstantiationError { message: String }, - #[error("Offer not found.")] - OfferNotFound { offer_id: String }, - #[error("Refund error: Not Expired")] - RefundErrorNotExpired { message: String, trade: String }, - #[error("Refund error: Arbitration not allow.")] - RefundErrorNoArbitrationAllowed { message: String, trade: String }, - #[error("Refund error: Contract has no funds.")] - RefundErrorNoFunds { message: String, trade: String }, - #[error("Release error.")] - ReleaseError { message: String }, - #[error("Swap error.")] - SwapError { - required_amount: Uint128, - returned_amount: Uint128, - }, - #[error("Fund escrow error.")] - FundEscrowError { - required_amount: Uint128, - sent_amount: Uint128, - }, - #[error("Escrow already funded.")] - AlreadyFundedError {}, - #[error("Unauthorized.")] - Unauthorized { - owner: Addr, - arbitrator: Addr, - caller: Addr, - }, - #[error("Unauthorized Dispute.")] - UnauthorizedDispute { - seller: Addr, - buyer: Addr, - caller: Addr, - }, - #[error("Hub Already Registered")] - HubAlreadyRegistered {}, -} diff --git a/contracts/contracts/trade/src/lib.rs b/contracts/contracts/trade/src/lib.rs index 43d262bd..2943dbb5 100644 --- a/contracts/contracts/trade/src/lib.rs +++ b/contracts/contracts/trade/src/lib.rs @@ -1,2 +1 @@ pub mod contract; -pub mod errors; diff --git a/contracts/contracts/trading_incentives/src/contract.rs b/contracts/contracts/trading_incentives/src/contract.rs index 1e93b3a2..fcabc12f 100644 --- a/contracts/contracts/trading_incentives/src/contract.rs +++ b/contracts/contracts/trading_incentives/src/contract.rs @@ -1,12 +1,15 @@ -use crate::errors::TradingIncentivesError; -use crate::errors::TradingIncentivesError::HubAlreadyRegistered; use crate::state::{DISTRIBUTION, TOTAL_VOLUME, TRADER_VOLUME}; use cosmwasm_std::{ entry_point, to_binary, BankMsg, Binary, Coin, CosmosMsg, Decimal, Deps, QueryRequest, - StdError, StdResult, Storage, SubMsg, WasmQuery, + StdResult, Storage, SubMsg, WasmQuery, }; use cosmwasm_std::{DepsMut, Env, MessageInfo, Response, Uint128}; use cw20::Denom; +use localterra_protocol::errors::ContractError; +use localterra_protocol::errors::ContractError::{ + DistributionClaimInvalidPeriod, DistributionNotStarted, HubAlreadyRegistered, + InvalidTradeState, Unauthorized, +}; use localterra_protocol::hub_utils::{get_hub_config, register_hub_internal, HUB_ADDR}; use localterra_protocol::offer::load_offer; use localterra_protocol::trade::{QueryMsg as TradeQueryMsg, Trade, TradeState}; @@ -22,7 +25,7 @@ pub fn instantiate( _env: Env, _info: MessageInfo, _msg: InstantiateMsg, -) -> Result { +) -> Result { let period_duration = 604800u64; //1 week in seconds let distribution_periods = 51u8; let total_duration = period_duration * distribution_periods as u64; @@ -57,7 +60,7 @@ pub fn execute( env: Env, info: MessageInfo, msg: ExecuteMsg, -) -> Result { +) -> Result { match msg { ExecuteMsg::RegisterTrade { trade } => register_trade(deps, env, info, trade), ExecuteMsg::ClaimRewards { period } => claim_rewards(deps, env, info, period), @@ -114,13 +117,16 @@ fn register_trade( env: Env, info: MessageInfo, trade_id: String, -) -> Result { +) -> Result { let hub_addr = HUB_ADDR.load(deps.storage).unwrap(); let hub_cfg = get_hub_config(&deps.querier, hub_addr.addr.to_string()); //Only callable by the Trade Contract. if hub_cfg.trade_addr.ne(&info.sender) { - return Err(TradingIncentivesError::Unauthorized {}); + return Err(Unauthorized { + owner: hub_cfg.trade_addr.clone(), + caller: info.sender.clone(), + }); } let trade: Trade = deps @@ -143,7 +149,10 @@ fn register_trade( let maker = offer.owner.to_string(); if trade.state != TradeState::EscrowReleased { - return Err(TradingIncentivesError::Unauthorized {}); + return Err(InvalidTradeState { + current: trade.state.clone(), + expected: TradeState::EscrowReleased, + }); } let amount = trade.amount.clone(); @@ -182,20 +191,16 @@ fn claim_rewards( env: Env, info: MessageInfo, period: u8, -) -> Result { +) -> Result { let distribution = get_distribution_info(env, deps.storage).unwrap(); let rewards_denom = get_rewards_denom(deps.as_ref()); if distribution.start_time.eq(&0u64) { - return Err(TradingIncentivesError::Std(StdError::generic_err( - "Distribution hasn't started yet.", - ))); + return Err(DistributionNotStarted {}); } if period >= distribution.current_period { - return Err(TradingIncentivesError::Std(StdError::generic_err( - "Only past periods can be claimed.", - ))); + return Err(DistributionClaimInvalidPeriod {}); } let amount = @@ -223,7 +228,7 @@ fn start_distribution( deps: DepsMut, env: Env, info: MessageInfo, -) -> Result { +) -> Result { let mut distribution = DISTRIBUTION.load(deps.storage).unwrap(); let rewards_denom = get_rewards_denom(deps.as_ref()); @@ -260,6 +265,6 @@ fn get_rewards_denom(deps: Deps) -> String { } } -fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { +fn register_hub(deps: DepsMut, info: MessageInfo) -> Result { register_hub_internal(info.sender, deps.storage, HubAlreadyRegistered {}) } diff --git a/contracts/contracts/trading_incentives/src/errors.rs b/contracts/contracts/trading_incentives/src/errors.rs deleted file mode 100644 index 1c81a7ce..00000000 --- a/contracts/contracts/trading_incentives/src/errors.rs +++ /dev/null @@ -1,14 +0,0 @@ -use cosmwasm_std::StdError; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum TradingIncentivesError { - #[error("{0}")] - Std(#[from] StdError), - - #[error("Unauthorized")] - Unauthorized {}, - - #[error("Hub Already Registered")] - HubAlreadyRegistered {}, -} diff --git a/contracts/contracts/trading_incentives/src/lib.rs b/contracts/contracts/trading_incentives/src/lib.rs index 4e714c3a..be70cfad 100644 --- a/contracts/contracts/trading_incentives/src/lib.rs +++ b/contracts/contracts/trading_incentives/src/lib.rs @@ -1,4 +1,3 @@ pub mod contract; -mod errors; mod math; mod state; diff --git a/contracts/packages/protocol/src/errors.rs b/contracts/packages/protocol/src/errors.rs index e55eb098..d7647233 100644 --- a/contracts/packages/protocol/src/errors.rs +++ b/contracts/packages/protocol/src/errors.rs @@ -4,17 +4,11 @@ use cosmwasm_std::{Addr, StdError, Uint128}; use thiserror::Error; #[derive(Error, Debug)] -pub enum GuardError { +pub enum ContractError { #[error("{0}")] Std(#[from] StdError), #[error("Invalid state change.")] InvalidStateChange { from: OfferState, to: OfferState }, - #[error("Invalid trade state change.")] - InvalidTradeStateChange { - from: TradeState, - from_allowed: TradeState, - to: TradeState, - }, #[error("Amount is outside of offer amount range.")] AmountError { amount: Uint128, @@ -31,14 +25,30 @@ pub enum GuardError { }, #[error("Hub Already Registered.")] HubAlreadyRegistered {}, - #[error("Unauthorized Release.")] - UnauthorizedRelease { - caller: Addr, - seller: Addr, - arbitrator: Addr, + #[error("This trade has expired.")] + TradeExpired { + timeout: u64, + expired_at: u64, + created_at: u64, + }, + #[error("Fund escrow error.")] + FundEscrowError { + required_amount: Uint128, + sent_amount: Uint128, + }, + #[error("Offer not found.")] + OfferNotFound { offer_id: String }, + #[error("Invalid trade state change.")] + InvalidTradeStateChange { from: TradeState, to: TradeState }, + #[error("Refund error: Not Expired")] + RefundErrorNotExpired { message: String, trade: String }, + #[error("Distribution hasn't started yet.")] + DistributionNotStarted {}, + #[error("Only past periods can be claimed.")] + DistributionClaimInvalidPeriod {}, + #[error("Trade state is invalid.")] + InvalidTradeState { + current: TradeState, + expected: TradeState, }, - #[error("Governance not found.")] - GovernanceNotFound { gov_addr: Addr }, - #[error("Invalid reply message id.")] - InvalidReply {}, } diff --git a/contracts/packages/protocol/src/guards.rs b/contracts/packages/protocol/src/guards.rs index 75f2b426..14ce0ed4 100644 --- a/contracts/packages/protocol/src/guards.rs +++ b/contracts/packages/protocol/src/guards.rs @@ -1,13 +1,13 @@ -use crate::errors::GuardError; +use crate::errors::ContractError; use crate::offer::OfferType; use crate::trade::{Trade, TradeState}; use cosmwasm_std::{Addr, StdError, Uint128}; -pub fn assert_ownership(caller: Addr, owner: Addr) -> Result<(), GuardError> { +pub fn assert_ownership(caller: Addr, owner: Addr) -> Result<(), ContractError> { if caller.eq(&owner) { Ok(()) } else { - Err(GuardError::Unauthorized { owner, caller }) + Err(ContractError::Unauthorized { owner, caller }) } } @@ -15,11 +15,11 @@ pub fn assert_caller_is_buyer_or_seller( caller: Addr, buyer: Addr, seller: Addr, -) -> Result<(), GuardError> { +) -> Result<(), ContractError> { if caller.eq(&buyer) || caller.eq(&seller) { Ok(()) } else { - Err(GuardError::UnauthorizedUser { + Err(ContractError::UnauthorizedUser { caller, buyer, seller, @@ -27,41 +27,21 @@ pub fn assert_caller_is_buyer_or_seller( } } -pub fn assert_caller_is_seller_or_arbitrator( - caller: Addr, - seller: Addr, - arbitrator: Addr, -) -> Result<(), GuardError> { - if caller.eq(&seller) || caller.eq(&arbitrator) { - Ok(()) - } else { - Err(GuardError::UnauthorizedRelease { - caller, - seller, - arbitrator, - }) - } -} - pub fn assert_trade_state_change_is_valid( from: TradeState, from_allowed: TradeState, to: TradeState, -) -> Result<(), GuardError> { - if from == from_allowed { +) -> Result<(), ContractError> { + if from.eq(&from_allowed) { Ok(()) } else { - Err(GuardError::InvalidTradeStateChange { - from, - from_allowed, - to, - }) + Err(ContractError::InvalidTradeStateChange { from, to }) } } -pub fn assert_min_g_max(min: Uint128, max: Uint128) -> Result<(), GuardError> { +pub fn assert_min_g_max(min: Uint128, max: Uint128) -> Result<(), ContractError> { if min >= max { - Err(GuardError::Std(StdError::generic_err( + Err(ContractError::Std(StdError::generic_err( "Min amount must be greater than Max amount.", ))) } else { @@ -73,10 +53,10 @@ pub fn assert_value_in_range( min: Uint128, max: Uint128, amount: Uint128, -) -> Result<(), GuardError> { +) -> Result<(), ContractError> { //Check that amount is inside Offer limits if amount > max || amount < min { - return Err(GuardError::AmountError { + return Err(ContractError::AmountError { amount, min_amount: min, max_amount: max, @@ -86,10 +66,10 @@ pub fn assert_value_in_range( } } -pub fn assert_range_0_to_99(random_value: usize) -> Result<(), GuardError> { +pub fn assert_range_0_to_99(random_value: usize) -> Result<(), ContractError> { // No need to check `random_value < 0` since datatype is an unsigned integer if random_value > 99 { - Err(GuardError::Std(StdError::generic_err( + Err(ContractError::Std(StdError::generic_err( "Value out of range: 0..99.", ))) } else { @@ -104,13 +84,13 @@ pub fn trade_request_is_expired(block_time: u64, created_at: u64, expire_timer: pub fn assert_trade_state_and_type( trade: &Trade, offer_type: &OfferType, -) -> Result<(), GuardError> { +) -> Result<(), ContractError> { if offer_type == &OfferType::Sell && trade.state == TradeState::RequestCreated { Ok(()) } else if offer_type == &OfferType::Buy && trade.state == TradeState::RequestAccepted { Ok(()) } else { - Err(GuardError::Std(StdError::generic_err( + Err(ContractError::Std(StdError::generic_err( "Incorrect sender funding the trade.", // TODO: use custom error. LOCAL-734 ))) }