Skip to content

Commit

Permalink
Merge pull request #325 from White-Whale-Defi-Platform/chore/cleanup-…
Browse files Browse the repository at this point in the history
…state-and-fees

Chore/cleanup state and fees
  • Loading branch information
0xFable authored Apr 11, 2024
2 parents fd601e8 + 9911660 commit 7440733
Show file tree
Hide file tree
Showing 11 changed files with 246 additions and 141 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion contracts/liquidity_hub/pool-manager/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::ops::Mul;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Coin, Decimal, Decimal256, StdError, StdResult, Storage, Uint128, Uint256};

use white_whale_std::fee::PoolFee;
use white_whale_std::pool_network::asset::{Asset, AssetInfo, PairType};
use white_whale_std::pool_network::pair::PoolFee;

use crate::error::ContractError;
use crate::math::Decimal256Helper;
Expand Down
29 changes: 1 addition & 28 deletions contracts/liquidity_hub/pool-manager/src/liquidity/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use white_whale_std::pool_network::asset::PairType;

use crate::{
helpers::{self},
state::{get_pair_by_identifier, COLLECTABLE_PROTOCOL_FEES},
state::get_pair_by_identifier,
};
use crate::{
state::{MANAGER_CONFIG, PAIRS},
Expand All @@ -18,21 +18,6 @@ use white_whale_std::pool_network::{
};
pub const MAX_ASSETS_PER_POOL: usize = 4;

/// Gets the protocol fee amount for the given asset_id
pub fn get_protocol_fee_for_asset(collected_protocol_fees: Vec<Coin>, asset_id: String) -> Uint128 {
let protocol_fee_asset = collected_protocol_fees
.iter()
.find(|&protocol_fee_asset| protocol_fee_asset.clone().denom == asset_id.clone())
.cloned();

// get the protocol fee for the given pool_asset
if let Some(protocol_fee_asset) = protocol_fee_asset {
protocol_fee_asset.amount
} else {
Uint128::zero()
}
}

// todo allow providing liquidity with a single asset

//todo allow passing an optional locking period for the LP once the liquidity is provided, so tokens
Expand Down Expand Up @@ -73,18 +58,6 @@ pub fn provide_liquidity(
return Err(ContractError::InvalidZeroAmount {});
}

// TODO: remove
let collected_protocol_fees = COLLECTABLE_PROTOCOL_FEES
.load(deps.storage, &pair.lp_denom)
.unwrap_or_default();

// todo remove this, as collected_protocol_fees is not a thing
for pool in pool_assets.iter_mut() {
let protocol_fee =
get_protocol_fee_for_asset(collected_protocol_fees.clone(), pool.clone().denom);
pool.amount = pool.amount.checked_sub(protocol_fee).unwrap();
}

let liquidity_token = pair.lp_denom.clone();

// Compute share and other logic based on the number of assets
Expand Down
14 changes: 8 additions & 6 deletions contracts/liquidity_hub/pool-manager/src/manager/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use cosmwasm_std::{
attr, Attribute, Coin, CosmosMsg, DepsMut, Env, MessageInfo, Response, Uint128,
};
use white_whale_std::{
pool_network::{asset::PairType, pair::PoolFee, querier::query_native_decimals},
fee::PoolFee,
pool_network::{asset::PairType, querier::query_native_decimals},
whale_lair::fill_rewards_msg,
};

use crate::state::{add_allow_native_token, get_pair_by_identifier, PAIR_COUNTER};
use crate::state::{get_pair_by_identifier, NATIVE_TOKEN_DECIMALS, PAIR_COUNTER};
use crate::{
state::{Config, MANAGER_CONFIG, PAIRS},
ContractError,
Expand All @@ -26,7 +27,8 @@ pub const MAX_ASSETS_PER_POOL: usize = 4;
///
/// ```rust
/// # use cosmwasm_std::{DepsMut, Decimal, Env, MessageInfo, Response, CosmosMsg, WasmMsg, to_json_binary};
/// # use white_whale_std::pool_network::{asset::{PairType}, pair::PoolFee};
/// # use white_whale_std::pool_network::{asset::{PairType}};
/// # use white_whale_std::fee::PoolFee;
/// # use white_whale_std::fee::Fee;
/// # use pool_manager::error::ContractError;
/// # use pool_manager::manager::commands::MAX_ASSETS_PER_POOL;
Expand All @@ -49,6 +51,7 @@ pub const MAX_ASSETS_PER_POOL: usize = 4;
/// burn_fee: Fee {
/// share: Decimal::zero(),
/// },
/// extra_fees: vec![],
/// };
///
/// #[cfg(feature = "osmosis")]
Expand All @@ -65,6 +68,7 @@ pub const MAX_ASSETS_PER_POOL: usize = 4;
/// osmosis_fee: Fee {
/// share: Decimal::zero(),
/// },
/// extra_fees: vec![],
/// };
/// let pair_type = PairType::ConstantProduct;
/// let token_factory_lp = false;
Expand Down Expand Up @@ -229,9 +233,7 @@ pub fn add_native_token_decimals(
if balance.is_zero() {
return Err(ContractError::InvalidVerificationBalance {});
}

add_allow_native_token(deps.storage, denom.to_string(), decimals)?;

NATIVE_TOKEN_DECIMALS.save(deps.storage, denom.as_bytes(), &decimals)?;
Ok(Response::new().add_attributes(vec![
("action", "add_allow_native_token"),
("denom", &denom),
Expand Down
9 changes: 5 additions & 4 deletions contracts/liquidity_hub/pool-manager/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ use white_whale_std::pool_network::{
// router::SimulateSwapOperationsResponse,
};

use crate::state::NATIVE_TOKEN_DECIMALS;
use crate::{
helpers::{self, calculate_stableswap_y, StableSwapDirection},
state::{get_decimals, get_pair_by_identifier, ALLOW_NATIVE_TOKENS},
state::get_pair_by_identifier,
ContractError,
};
use crate::{math::Decimal256Helper, state::SWAP_ROUTES};
Expand All @@ -21,7 +22,7 @@ pub fn query_native_token_decimal(
deps: Deps,
denom: String,
) -> Result<NativeTokenDecimalsResponse, ContractError> {
let decimals = ALLOW_NATIVE_TOKENS.load(deps.storage, denom.as_bytes())?;
let decimals = NATIVE_TOKEN_DECIMALS.load(deps.storage, denom.as_bytes())?;

Ok(NativeTokenDecimalsResponse { decimals })
}
Expand All @@ -41,7 +42,7 @@ pub fn query_simulation(
let ask_pool: Coin;
let offer_decimal: u8;
let ask_decimal: u8;
let decimals = get_decimals(&pair_info);
let decimals = pair_info.asset_decimals.clone();
// We now have the pools and pair info; we can now calculate the swap
// Verify the pool
if offer_asset.denom == pools[0].denom {
Expand Down Expand Up @@ -107,7 +108,7 @@ pub fn query_reverse_simulation(
let pair_info = get_pair_by_identifier(&deps, &pair_identifier)?;
let pools = pair_info.assets.clone();

let decimals = get_decimals(&pair_info);
let decimals = pair_info.asset_decimals.clone();
let offer_pool: Coin = pools[0].clone();
let offer_decimal = decimals[0];
let ask_pool: Coin = pools[1].clone();
Expand Down
87 changes: 4 additions & 83 deletions contracts/liquidity_hub/pool-manager/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Api, Coin, Deps, Order, StdResult, Storage};
use cw_storage_plus::{Bound, Index, IndexList, IndexedMap, Item, Map, UniqueIndex};
use cosmwasm_std::{Addr, Coin, Deps};
use cw_storage_plus::{Index, IndexList, IndexedMap, Item, Map, UniqueIndex};
use white_whale_std::pool_manager::{PairInfo, SwapOperation};
use white_whale_std::pool_network::asset::{Asset, AssetInfoRaw};
use white_whale_std::pool_network::pair::FeatureToggle;

use crate::ContractError;
Expand Down Expand Up @@ -35,93 +34,15 @@ pub fn get_pair_by_identifier(
.may_load(deps.storage, pair_identifier)?
.ok_or(ContractError::UnExistingPair {})
}

//todo not used, remove
// Used for PAIRS
pub fn pair_key(asset_infos: &[AssetInfoRaw]) -> Vec<u8> {
let mut asset_infos = asset_infos.to_vec();
asset_infos.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));

asset_infos
.iter()
.flat_map(|info| info.as_bytes().to_vec())
.collect()
}
pub fn get_decimals(pair_info: &PairInfo) -> Vec<u8> {
pair_info.asset_decimals.clone()
}
// Remove after adding decimals to pair info
pub const NATIVE_TOKEN_DECIMALS: Map<&[u8], u8> = Map::new("allow_native_token");

// Swap routes are used to establish defined routes for a given fee token to a desired fee token and is used for fee collection
pub const SWAP_ROUTES: Map<(&str, &str), Vec<SwapOperation>> = Map::new("swap_routes");

//todo remove
// Dyanmic Maps for Fee and Pair info
pub const COLLECTABLE_PROTOCOL_FEES: Map<&str, Vec<Coin>> = Map::new("collected_protocol_fees");

//todo remove
pub const TOTAL_COLLECTED_PROTOCOL_FEES: Map<&str, Vec<Asset>> =
Map::new("total_collected_protocol_fees");

//todo remove
pub const ALL_TIME_BURNED_FEES: Map<&str, Vec<Asset>> = Map::new("all_time_burned_fees");

pub const MANAGER_CONFIG: Item<Config> = Item::new("manager_config");
pub const PAIR_COUNTER: Item<u64> = Item::new("vault_count");

//todo remove
// key : asset info / value: decimals
pub const ALLOW_NATIVE_TOKENS: Map<&[u8], u8> = Map::new("allow_native_token");
//todo remove
pub fn add_allow_native_token(
storage: &mut dyn Storage,
denom: String,
decimals: u8,
) -> StdResult<()> {
ALLOW_NATIVE_TOKENS.save(storage, denom.as_bytes(), &decimals)
}

// settings for pagination
const MAX_LIMIT: u32 = 1000;
const DEFAULT_LIMIT: u32 = 10;

//todo this is not even used, remove?
// start_after AssetInfoRaw??? There shouldn't be any AssetInfoRaw around
pub fn read_pairs(
storage: &dyn Storage,
_api: &dyn Api,
start_after: Option<[AssetInfoRaw; 2]>,
limit: Option<u32>,
) -> StdResult<Vec<PairInfo>> {
// Note PairInfo may need to be refactored to handle the 2or3 design
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let start = calc_range_start(start_after).map(Bound::ExclusiveRaw);

PAIRS
.range(storage, start, None, Order::Ascending)
.take(limit)
.map(|item| {
let (_, v) = item?;
Ok(v)
})
.collect::<StdResult<Vec<PairInfo>>>()
}

// todo look at the cw_utils, there's calc_range_start, this could maybe be removed
// this will set the first key after the provided key, by appending a 1 byte
fn calc_range_start(start_after: Option<[AssetInfoRaw; 2]>) -> Option<Vec<u8>> {
start_after.map(|asset_infos| {
let mut asset_infos = asset_infos.to_vec();
asset_infos.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));

let mut v = [asset_infos[0].as_bytes(), asset_infos[1].as_bytes()]
.concat()
.as_slice()
.to_vec();
v.push(1);
v
})
}

#[cw_serde]
pub struct Config {
pub whale_lair_addr: Addr,
Expand Down
Loading

0 comments on commit 7440733

Please sign in to comment.