Skip to content

Commit

Permalink
Lp + Dao fees
Browse files Browse the repository at this point in the history
  • Loading branch information
itsHaseebSaeed committed Oct 26, 2023
1 parent 2696b91 commit 1406d6c
Show file tree
Hide file tree
Showing 28 changed files with 513 additions and 276 deletions.
124 changes: 27 additions & 97 deletions contracts/liquidity_book/lb_factory/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ use shade_protocol::{
lb_libraries::{math, pair_parameter_helper, price_helper, tokens, types, viewing_keys},
liquidity_book::{
lb_factory::*,
lb_pair::ExecuteMsg::{ForceDecay as LbPairForceDecay, SetStaticFeeParameters},
lb_pair::{
self,
ExecuteMsg::{ForceDecay as LbPairForceDecay, SetStaticFeeParameters},
},
},
};

Expand All @@ -39,6 +42,7 @@ use tokens::TokenType;
use types::{Bytes32, ContractInstantiationInfo, StaticFeeParameters};

use crate::{
error,
prelude::*,
state::*,
types::{LBPair, LBPairInformation, NextPairKey},
Expand Down Expand Up @@ -80,15 +84,26 @@ pub fn instantiate(
};

CONFIG.save(deps.storage, &state)?;
CONTRACT_STATUS.save(deps.storage, &ContractStatus::Active);

// TODO: decide on response output and format
Ok(Response::default())
}

/////////////// EXECUTE ///////////////

#[entry_point]
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> Result<Response> {
let contract_status = CONTRACT_STATUS.load(deps.storage)?;
match contract_status {
ContractStatus::FreezeAll => match msg {
ExecuteMsg::SetLBPairImplementation { .. }
| ExecuteMsg::SetLBTokenImplementation { .. } => {
return Err(error::LBFactoryError::TransactionBlock());
}
_ => {}
},
ContractStatus::Active => {}
}
match msg {
ExecuteMsg::SetLBPairImplementation {
lb_pair_implementation,
Expand All @@ -102,6 +117,7 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> R
active_id,
bin_step,
viewing_key,
entropy,
} => try_create_lb_pair(
deps,
env,
Expand All @@ -111,6 +127,7 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> R
active_id,
bin_step,
viewing_key,
entropy,
),
// ExecuteMsg::SetLBPairIgnored {
// token_x,
Expand Down Expand Up @@ -197,11 +214,6 @@ fn try_set_lb_pair_implementation(
) -> Result<Response> {
let state = CONFIG.load(deps.storage)?;

// TODO: query the LBPair contract to check that the factory address is correct
// if ILBPair(new_lb_pair_implementation).getFactory() != env.contract.address {
// return Err(Error::LBPairSafetyCheckFailed(new_lb_pair_implementation.address))
// }

validate_admin(
&deps.querier,
AdminPermissions::LiquidityBookAdmin,
Expand Down Expand Up @@ -242,10 +254,6 @@ fn try_set_lb_token_implementation(
info.sender.to_string(),
&state.admin_auth,
)?;
// TODO: query the LBToken contract to check that the factory address is correct
// if ILBToken(new_lb_token_implementation).getFactory() != env.contract.address {
// return Err(Error::LBTokenSafetyCheckFailed(new_lb_token_implementation.address))
// }

let old_lb_token_implementation = state.lb_token_implementation;
if (old_lb_token_implementation == new_lb_token_implementation) {
Expand Down Expand Up @@ -283,6 +291,7 @@ fn try_create_lb_pair(
active_id: u32,
bin_step: u16,
viewing_key: String,
entropy: String,
) -> Result<Response> {
let state = CONFIG.load(deps.storage)?;

Expand Down Expand Up @@ -325,9 +334,6 @@ fn try_create_lb_pair(

let (token_a, token_b) = _sort_tokens(token_x.clone(), token_y.clone());

// TODO: error if address doesn't exist on chain
// if (address(tokenA) == address(0)) revert LBFactory__AddressZero();

if LB_PAIRS_INFO
.load(
deps.storage,
Expand Down Expand Up @@ -379,11 +385,8 @@ fn try_create_lb_pair(
},
active_id,
lb_token_implementation: state.lb_token_implementation,
//TODO add viewing key
viewing_key,
//TODO add pair_name
pair_name: String::new(),
entropy: String::new(),
entropy,
protocol_fee_recipient: state.fee_recipient,
admin_auth: state.admin_auth.into(),
})?,
Expand All @@ -403,80 +406,8 @@ fn try_create_lb_pair(
})?;

Ok(Response::new().add_submessages(messages))

// emit LBPairCreated(tokenX, tokenY, binStep, pair, _allLBPairs.length - 1);
}

// /// Sets whether the pair is ignored or not for routing, it will make the pair unusable by the router.
// ///
// /// # Arguments
// ///
// /// * `token_x` - The address of the first token of the pair.
// /// * `token_y` - The address of the second token of the pair.
// /// * `bin_step` - The bin step in basis point of the pair.
// /// * `ignored` - Whether to ignore (true) or not (false) the pair for routing.
// fn try_set_lb_pair_ignored(
// deps: DepsMut,
// env: Env,
// info: MessageInfo,
// token_a: TokenType,
// token_b: TokenType,
// bin_step: u16,
// ignored: bool,
// ) -> Result<Response> {
// let state = CONFIG.load(deps.storage)?;
// only_owner(&info.sender, &state.owner)?;

// let (token_a, token_b) = _sort_tokens(token_a, token_b);

// let mut pair_information = LB_PAIRS_INFO
// .load(
// deps.storage,
// (
// token_a.unique_key().clone(),
// token_b.unique_key().clone(),
// bin_step,
// ),
// )
// .unwrap();

// if pair_information
// .lb_pair
// .contract
// .address
// .as_str()
// .is_empty()
// {
// return Err(Error::LBPairDoesNotExist {
// token_x: token_a.unique_key().clone(),
// token_y: token_b.unique_key().clone(),
// bin_step,
// });
// }

// if pair_information.ignored_for_routing == ignored {
// return Err(Error::LBPairIgnoredIsAlreadyInTheSameState);
// }

// pair_information.ignored_for_routing = ignored;

// LB_PAIRS_INFO.save(
// deps.storage,
// (
// token_a.unique_key().clone(),
// token_b.unique_key().clone(),
// bin_step,
// ),
// &pair_information,
// )?;

// // emit LBPairIgnoredStateChanged(pairInformation.LBPair, ignored);

// // TODO: be more specific about which pair changed
// Ok(Response::default()
// .add_attribute_plaintext("LBPair ignored state changed", format!("{}", ignored)))
// }

/// Sets the preset parameters of a bin step
///
/// # Arguments
Expand Down Expand Up @@ -695,7 +626,6 @@ fn try_set_fee_recipient(
info.sender.to_string(),
&state.admin_auth,
)?;
// TODO: Is there way to check that the address exists / is not zero?

let old_fee_recipient = state.fee_recipient;
if old_fee_recipient == fee_recipient {
Expand Down Expand Up @@ -844,8 +774,7 @@ fn try_force_decay(deps: DepsMut, env: Env, info: MessageInfo, pair: LBPair) ->
info.sender.to_string(),
&state.admin_auth,
)?;
// TODO: I think this needs to send a message to the LBPair contract to execute the force decay.
// pair.forceDecay();

let (token_a, token_b) = _sort_tokens(pair.token_x, pair.token_y);
let mut lb_pair = LB_PAIRS_INFO
.load(
Expand Down Expand Up @@ -1005,7 +934,7 @@ fn query_number_of_lb_pairs(deps: Deps) -> Result<Binary> {
/// # Returns
///
/// * lb_pair - The address of the LBPair at index `index`.
// TODO: Unsure if this function is necessary. Not sure how to index the Keyset.
// TODO: Unsure if this function is necessary. Not sure how to index the Keyset. WAITING: For Front-end to make some decisions about this
fn query_lb_pair_at_index(deps: Deps, index: u32) -> Result<Binary> {
let lb_pair = todo!();

Expand Down Expand Up @@ -1036,7 +965,7 @@ fn query_number_of_quote_assets(deps: Deps) -> Result<Binary> {
/// # Returns
///
/// * `asset` - The address of the quote asset at index `index`.
// TODO: Unsure if this function is necessary. Not sure how to index the Keyset.
// TODO: Unsure if this function is necessary. Not sure how to index the Keyset. WAITING: For Front-end to make some decisions about this
fn query_quote_asset_at_index(deps: Deps, index: u32) -> Result<Binary> {
let asset = QUOTE_ASSET_WHITELIST.get_at(deps.storage, index)?;

Expand Down Expand Up @@ -1333,7 +1262,6 @@ pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
&LBPairInformation {
bin_step: lb_pair_key.bin_step,
lb_pair: lb_pair.clone(),
// TODO: get 'is_owner' from the create_lb_pair function
created_by_owner: lb_pair_key.is_open,
ignored_for_routing: false,
},
Expand All @@ -1356,7 +1284,9 @@ pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
)?;

ephemeral_storage_w(deps.storage).remove();
Ok(Response::default())
Ok(Response::default()
.add_attribute("lb_pair_address", lb_pair.contract.address.to_string())
.add_attribute("lb_pair_hash", lb_pair.contract.code_hash.to_string()))
}
None => Err(StdError::generic_err(format!("Expecting contract id"))),
},
Expand Down
26 changes: 21 additions & 5 deletions contracts/liquidity_book/lb_factory/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
use bin_helper::BinError;
use cosmwasm_std::Addr;
use fee_helper::FeeError;
use math::liquidity_configurations::LiquidityConfigurationsError;
use math::u128x128_math::U128x128MathError;
use math::u256x256_math::U256x256MathError;
use math::{
liquidity_configurations::LiquidityConfigurationsError,
u128x128_math::U128x128MathError,
u256x256_math::U256x256MathError,
};
use oracle_helper::OracleError;
use pair_parameter_helper::PairParametersError;
use shade_protocol::lb_libraries::{
bin_helper, fee_helper, math, oracle_helper, pair_parameter_helper,
bin_helper,
fee_helper,
math,
oracle_helper,
pair_parameter_helper,
};

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -76,15 +82,25 @@ pub enum LBFactoryError {
#[error("Flash loan fee is already {fee}!")]
SameFlashLoanFee { fee: u8 },

#[error("LBPair safety check failed. {lb_pair_implementation} factory address does not match this one!")]
#[error(
"LBPair safety check failed. {lb_pair_implementation} factory address does not match this one!"
)]
LBPairSafetyCheckFailed { lb_pair_implementation: Addr },

#[error(
"LBFactory safety check failed. {lb_factory_implementation} factory address does not match this one!"
)]
LBFactorySafetyCheckFailed { lb_factory_implementation: Addr },

#[error("LB implementation is already set to code ID {lb_implementation}!")]
SameImplementation { lb_implementation: u64 },

#[error("The LBPair implementation has not been set yet!")]
ImplementationNotSet,

#[error("Transaction is blocked by contract status")]
TransactionBlock(),

#[error(transparent)]
CwErr(#[from] cosmwasm_std::StdError),

Expand Down
13 changes: 8 additions & 5 deletions contracts/liquidity_book/lb_factory/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ use crate::{
prelude::*,
types::{LBPair, LBPairInformation, NextPairKey},
};

pub const CONTRACT_STATUS: Item<ContractStatus> = Item::new("contract_status");
pub const CONFIG: Item<State> = Item::new("config");
pub static EPHEMERAL_STORAGE_KEY: &[u8] = b"ephemeral_storage";

// TODO: not sure if this should be a Keyset or a Vec.
// pub static ALL_LB_PAIRS: Item<Vec<LBPair>> = Item::new(b"all_lb_pairs");
pub const ALL_LB_PAIRS: AppendStore<LBPair> = AppendStore::new("all_lb_pairs");

Expand All @@ -32,7 +31,6 @@ pub const LB_PAIRS_INFO: Map<(String, String, u16), LBPairInformation> = Map::ne
/// Map of bin_step to preset, which is an encoded Bytes32 set of pair parameters
pub const PRESETS: Map<u16, PairParameters> = Map::new("presets");

// TODO: not sure if this should be a Keyset or a Vec.
// Does it need to store ContractInfo or would Addr be enough?
// pub static QUOTE_ASSET_WHITELIST: Item<Vec<ContractInfo>> = Item::new(b"quote_asset_whitelist");
pub const QUOTE_ASSET_WHITELIST: AppendStore<TokenType> = AppendStore::new("quote_asset_whitelist");
Expand All @@ -43,11 +41,16 @@ pub const QUOTE_ASSET_WHITELIST: AppendStore<TokenType> = AppendStore::new("quot
///
// The Vec<u16> will represent the "EnumerableSet.UintSet" from the solidity code.
// The primary purpose of EnumerableSet.UintSet is to provide a convenient way to store, iterate, and retrieve elements in a set, while ensuring that they remain unique.
// TODO: There doesn't appear to be a way to have a mapping to a Keyset, so a Vec will have to do for now...
pub const AVAILABLE_LB_PAIR_BIN_STEPS: Map<(String, String), Vec<u16>> =
Map::new("available_lb_pair_bin_steps");

// TODO: Rename State to Config?
//TODO: add multiple other status according to your need
#[cw_serde]
pub enum ContractStatus {
Active, // allows all operations
FreezeAll, // blocks everything except admin-protected config changes
}

#[cw_serde]
pub struct State {
pub contract_info: ContractInfo,
Expand Down
2 changes: 0 additions & 2 deletions contracts/liquidity_book/lb_factory/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use shade_protocol::lb_libraries::{tokens, types};
use tokens::TokenType;
pub use types::{LBPair, LBPairInformation};

// TODO: maybe we don't need this file at all?

#[cw_serde]
pub struct NextPairKey {
pub token_a: TokenType,
Expand Down
Loading

0 comments on commit 1406d6c

Please sign in to comment.