Skip to content
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ keywords = [
anyhow = "1.0.71"
bech32 = "0.9.1"
cosmwasm-schema = "1.2.6"
cosmwasm-std = "1.2.6"
cosmwasm-std = "1.3.1"
cw2 = "1.1.0"
cw-storage-plus = "1.0.1"
cw-utils = "1.0.1"
Expand Down
7 changes: 6 additions & 1 deletion contracts/red-bank/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use cosmwasm_std::{CheckedFromRatioError, CheckedMultiplyFractionError, OverflowError, StdError};
use cosmwasm_std::{
CheckedFromRatioError, CheckedMultiplyFractionError, DivideByZeroError, OverflowError, StdError,
};
use cw_utils::PaymentError;
use mars_health::error::HealthError;
use mars_liquidation::error::LiquidationError;
Expand Down Expand Up @@ -33,6 +35,9 @@ pub enum ContractError {
#[error("{0}")]
CheckedMultiplyFraction(#[from] CheckedMultiplyFractionError),

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

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

Expand Down
2 changes: 1 addition & 1 deletion contracts/red-bank/src/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ pub fn get_user_positions_map(
user_addr: &Addr,
oracle_addr: &Addr,
params_addr: &Addr,
) -> StdResult<HashMap<String, Position>> {
) -> Result<HashMap<String, Position>, ContractError> {
let block_time = env.block.time.seconds();

// Find all denoms that the user has a collateral or debt position in
Expand Down
4 changes: 2 additions & 2 deletions contracts/red-bank/src/interest_rates.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::str;

use cosmwasm_std::{Addr, Decimal, Env, Event, Response, StdResult, Storage, Uint128};
use cosmwasm_std::{Addr, Decimal, Env, Event, Response, Storage, Uint128};
use mars_interest_rate::{
calculate_applied_linear_interest_rate, compute_scaled_amount, compute_underlying_amount,
get_underlying_debt_amount, get_underlying_liquidity_amount, ScalingOperation,
Expand All @@ -26,7 +26,7 @@ pub fn apply_accumulated_interests(
rewards_collector_addr: &Addr,
incentives_addr: &Addr,
mut response: Response,
) -> StdResult<Response> {
) -> Result<Response, ContractError> {
let current_timestamp = env.block.time.seconds();
let previous_borrow_index = market.borrow_index;

Expand Down
24 changes: 12 additions & 12 deletions contracts/red-bank/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub fn query_user_debt(
block: &BlockInfo,
user_addr: Addr,
denom: String,
) -> StdResult<UserDebtResponse> {
) -> Result<UserDebtResponse, ContractError> {
let Debt {
amount_scaled,
uncollateralized,
Expand All @@ -117,7 +117,7 @@ pub fn query_user_debts(
user_addr: Addr,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<Vec<UserDebtResponse>> {
) -> Result<Vec<UserDebtResponse>, ContractError> {
let block_time = block.time.seconds();

let start = start_after.map(|denom| Bound::ExclusiveRaw(denom.into_bytes()));
Expand Down Expand Up @@ -151,7 +151,7 @@ pub fn query_user_collateral(
user_addr: Addr,
account_id: Option<String>,
denom: String,
) -> StdResult<UserCollateralResponse> {
) -> Result<UserCollateralResponse, ContractError> {
let acc_id = account_id.unwrap_or("".to_string());

let Collateral {
Expand All @@ -178,7 +178,7 @@ pub fn query_user_collaterals(
account_id: Option<String>,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<Vec<UserCollateralResponse>> {
) -> Result<Vec<UserCollateralResponse>, ContractError> {
let block_time = block.time.seconds();

let start = start_after.map(|denom| Bound::ExclusiveRaw(denom.into_bytes()));
Expand Down Expand Up @@ -213,39 +213,39 @@ pub fn query_scaled_liquidity_amount(
env: Env,
denom: String,
amount: Uint128,
) -> StdResult<Uint128> {
) -> Result<Uint128, ContractError> {
let market = MARKETS.load(deps.storage, &denom)?;
get_scaled_liquidity_amount(amount, &market, env.block.time.seconds())
Ok(get_scaled_liquidity_amount(amount, &market, env.block.time.seconds())?)
}

pub fn query_scaled_debt_amount(
deps: Deps,
env: Env,
denom: String,
amount: Uint128,
) -> StdResult<Uint128> {
) -> Result<Uint128, ContractError> {
let market = MARKETS.load(deps.storage, &denom)?;
get_scaled_debt_amount(amount, &market, env.block.time.seconds())
Ok(get_scaled_debt_amount(amount, &market, env.block.time.seconds())?)
}

pub fn query_underlying_liquidity_amount(
deps: Deps,
env: Env,
denom: String,
amount_scaled: Uint128,
) -> StdResult<Uint128> {
) -> Result<Uint128, ContractError> {
let market = MARKETS.load(deps.storage, &denom)?;
get_underlying_liquidity_amount(amount_scaled, &market, env.block.time.seconds())
Ok(get_underlying_liquidity_amount(amount_scaled, &market, env.block.time.seconds())?)
}

pub fn query_underlying_debt_amount(
deps: Deps,
env: Env,
denom: String,
amount_scaled: Uint128,
) -> StdResult<Uint128> {
) -> Result<Uint128, ContractError> {
let market = MARKETS.load(deps.storage, &denom)?;
get_underlying_debt_amount(amount_scaled, &market, env.block.time.seconds())
Ok(get_underlying_debt_amount(amount_scaled, &market, env.block.time.seconds())?)
}

pub fn query_user_position(
Expand Down
5 changes: 2 additions & 3 deletions contracts/red-bank/tests/test_borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use mars_red_bank::{
};
use mars_red_bank_types::red_bank::{ExecuteMsg, Market};
use mars_testing::{mock_env, mock_env_at_block_time, MockEnvParams};
use mars_utils::math;

use crate::helpers::th_default_asset_params;

Expand Down Expand Up @@ -965,10 +964,10 @@ fn borrow_collateral_check() {
.unwrap()
* exchange_rate_3);
let exceeding_borrow_amount =
math::divide_uint128_by_decimal(max_borrow_allowed_in_base_asset, exchange_rate_2).unwrap()
max_borrow_allowed_in_base_asset.checked_div_floor(exchange_rate_2).unwrap()
+ Uint128::from(100_u64);
let permissible_borrow_amount =
math::divide_uint128_by_decimal(max_borrow_allowed_in_base_asset, exchange_rate_2).unwrap()
max_borrow_allowed_in_base_asset.checked_div_floor(exchange_rate_2).unwrap()
- Uint128::from(100_u64);

// borrow above the allowed amount given current collateral, should fail
Expand Down
9 changes: 3 additions & 6 deletions contracts/red-bank/tests/test_misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use mars_red_bank::{
};
use mars_red_bank_types::red_bank::{Debt, ExecuteMsg, Market};
use mars_testing::{mock_env, mock_env_at_block_time, MockEnvParams};
use mars_utils::math;

use crate::helpers::th_default_asset_params;

Expand Down Expand Up @@ -338,11 +337,9 @@ fn update_asset_collateral() {
* token_2_exchange_rate;
let weighted_liquidation_threshold_in_base_asset =
token_1_weighted_lt_in_base_asset + token_2_weighted_lt_in_base_asset;
let max_debt_for_valid_hf = math::divide_uint128_by_decimal(
weighted_liquidation_threshold_in_base_asset,
token_3_exchange_rate,
)
.unwrap();
let max_debt_for_valid_hf = weighted_liquidation_threshold_in_base_asset
.checked_div_floor(token_3_exchange_rate)
.unwrap();
let token_3_debt_scaled = get_scaled_debt_amount(
max_debt_for_valid_hf,
&market_3_initial,
Expand Down
12 changes: 5 additions & 7 deletions contracts/red-bank/tests/test_withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use mars_red_bank_types::{
red_bank::{Collateral, Debt, ExecuteMsg, Market},
};
use mars_testing::{mock_env_at_block_time, MarsMockQuerier};
use mars_utils::math;

use crate::helpers::th_default_asset_params;

Expand Down Expand Up @@ -637,13 +636,12 @@ fn how_much_to_withdraw(suite: &HealthCheckTestSuite, block_time: u64) -> Uint12
* prices[1];

// How much to withdraw in base asset to have health factor equal to one
let how_much_to_withdraw_in_base_asset = math::divide_uint128_by_decimal(
weighted_liquidation_threshold_in_base_asset - total_collateralized_debt_in_base_asset,
asset_params[2].liquidation_threshold,
)
.unwrap();
let how_much_to_withdraw_in_base_asset = (weighted_liquidation_threshold_in_base_asset
- total_collateralized_debt_in_base_asset)
.checked_div_floor(asset_params[2].liquidation_threshold)
.unwrap();

math::divide_uint128_by_decimal(how_much_to_withdraw_in_base_asset, prices[2]).unwrap()
how_much_to_withdraw_in_base_asset.checked_div_floor(prices[2]).unwrap()
}

#[test]
Expand Down
22 changes: 11 additions & 11 deletions packages/interest-rate/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use cosmwasm_std::{Decimal, StdError, StdResult, Uint128};
use mars_red_bank_types::red_bank::Market;
use mars_utils::math;
use mars_red_bank_types::{error::MarsError, red_bank::Market};

/// Scaling factor used to keep more precision during division / multiplication by index.
pub const SCALING_FACTOR: Uint128 = Uint128::new(1_000_000);
Expand Down Expand Up @@ -31,7 +30,7 @@ pub fn get_scaled_liquidity_amount(
amount: Uint128,
market: &Market,
timestamp: u64,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
compute_scaled_amount(
amount,
get_updated_liquidity_index(market, timestamp)?,
Expand All @@ -48,7 +47,7 @@ pub fn get_underlying_liquidity_amount(
amount_scaled: Uint128,
market: &Market,
timestamp: u64,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
compute_underlying_amount(
amount_scaled,
get_updated_liquidity_index(market, timestamp)?,
Expand All @@ -68,7 +67,7 @@ pub fn get_scaled_debt_amount(
amount: Uint128,
market: &Market,
timestamp: u64,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
compute_scaled_amount(
amount,
get_updated_borrow_index(market, timestamp)?,
Expand All @@ -85,7 +84,7 @@ pub fn get_underlying_debt_amount(
amount_scaled: Uint128,
market: &Market,
timestamp: u64,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
compute_underlying_amount(
amount_scaled,
get_updated_borrow_index(market, timestamp)?,
Expand All @@ -108,12 +107,12 @@ pub fn compute_scaled_amount(
amount: Uint128,
index: Decimal,
scaling_operation: ScalingOperation,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
// Scale by SCALING_FACTOR to have better precision
let scaled_amount = amount.checked_mul(SCALING_FACTOR)?;
match scaling_operation {
ScalingOperation::Truncate => math::divide_uint128_by_decimal(scaled_amount, index),
ScalingOperation::Ceil => math::divide_uint128_by_decimal_and_ceil(scaled_amount, index),
ScalingOperation::Truncate => Ok(scaled_amount.checked_div_floor(index)?),
ScalingOperation::Ceil => Ok(scaled_amount.checked_div_ceil(index)?),
}
}

Expand All @@ -123,15 +122,16 @@ pub fn compute_underlying_amount(
scaled_amount: Uint128,
index: Decimal,
scaling_operation: ScalingOperation,
) -> StdResult<Uint128> {
) -> Result<Uint128, MarsError> {
// Multiply scaled amount by decimal (index)
let before_scaling_factor = scaled_amount * index;

// Descale by SCALING_FACTOR which is introduced when scaling the amount
match scaling_operation {
ScalingOperation::Truncate => Ok(before_scaling_factor.checked_div(SCALING_FACTOR)?),
ScalingOperation::Ceil => {
math::uint128_checked_div_with_ceil(before_scaling_factor, SCALING_FACTOR)
let scaling_factor_dec = Decimal::from_ratio(SCALING_FACTOR, Uint128::one());
Ok(before_scaling_factor.checked_div_ceil(scaling_factor_dec)?)
}
}
}
Expand Down
16 changes: 15 additions & 1 deletion packages/types/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use cosmwasm_std::StdError;
use cosmwasm_std::{
CheckedFromRatioError, CheckedMultiplyFractionError, DivideByZeroError, OverflowError, StdError,
};
use thiserror::Error;

#[derive(Error, Debug, PartialEq)]
Expand All @@ -22,6 +24,18 @@ pub enum MarsError {
Deserialize {
target_type: String,
},

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

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

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

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

impl From<MarsError> for StdError {
Expand Down
Loading