Skip to content

Commit

Permalink
lb-factory changes + integration testing stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
itsHaseebSaeed committed Dec 26, 2023
1 parent 83f15b3 commit efcda10
Show file tree
Hide file tree
Showing 92 changed files with 7,881 additions and 2,145 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ members = [
"contracts/liquidity_book/lb_pair",
"contracts/liquidity_book/lb_token",
"contracts/liquidity_book/router",
"contracts/liquidity_book/staking_contract",
"contracts/liquidity_book/lb_staking",
"contracts/liquidity_book/tests",

# Staking
Expand Down
8 changes: 8 additions & 0 deletions contracts/liquidity_book/.cargo/config
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[alias]
# Temporarily removed the backtraces feature from the unit-test run due to compilation errors in
# the cosmwasm-std package:
# cosmwasm-std = { git = "https://github.com/scrtlabs/cosmwasm", branch = "secret" }
# unit-test = "test --lib --features backtraces"
unit-test = "test --lib"
integration-test = "test --test integration"
schema = "run --example schema"
9 changes: 0 additions & 9 deletions contracts/liquidity_book/.cargo/config.toml

This file was deleted.

12 changes: 11 additions & 1 deletion contracts/liquidity_book/lb_factory/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,22 @@ exclude = [
[lib]
crate-type = ["cdylib", "rlib"]


[[example]]
name = "schema"
path = "schema/schema.rs" # Adjust the path according to your project structure


[features]
default = []
default = ["schema"]
schema = []
# for quicker tests, cargo test --lib
# for more explicit tests, cargo test --features=backtraces
backtraces = ["cosmwasm-std/backtraces"]




[dependencies]
shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] }
schemars = "0.8.16"
Expand Down
49 changes: 49 additions & 0 deletions contracts/liquidity_book/lb_factory/schema/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use cosmwasm_schema::{export_schema, remove_schemas, schema_for};
use std::{env::current_dir, fs::create_dir_all};

use shade_protocol::liquidity_book::lb_factory::{
AllBinStepsResponse,
AllLBPairsResponse,
ExecuteMsg,
FeeRecipientResponse,
InstantiateMsg,
IsQuoteAssetResponse,
LBPairAtIndexResponse,
LBPairImplementationResponse,
LBPairInformationResponse,
LBTokenImplementationResponse,
MinBinStepResponse,
NumberOfLBPairsResponse,
NumberOfQuoteAssetsResponse,
OpenBinStepsResponse,
PresetResponse,
QueryMsg,
QuoteAssetAtIndexResponse,
};

fn main() {
let mut out_dir = current_dir().unwrap();
out_dir.push("schema");
create_dir_all(&out_dir).unwrap();
remove_schemas(&out_dir).unwrap();

export_schema(&schema_for!(InstantiateMsg), &out_dir);
export_schema(&schema_for!(ExecuteMsg), &out_dir);
export_schema(&schema_for!(QueryMsg), &out_dir);

// Add export_schema for each response struct
export_schema(&schema_for!(MinBinStepResponse), &out_dir);
export_schema(&schema_for!(FeeRecipientResponse), &out_dir);
export_schema(&schema_for!(LBPairImplementationResponse), &out_dir);
export_schema(&schema_for!(LBTokenImplementationResponse), &out_dir);
export_schema(&schema_for!(NumberOfLBPairsResponse), &out_dir);
export_schema(&schema_for!(LBPairAtIndexResponse), &out_dir);
export_schema(&schema_for!(NumberOfQuoteAssetsResponse), &out_dir);
export_schema(&schema_for!(QuoteAssetAtIndexResponse), &out_dir);
export_schema(&schema_for!(IsQuoteAssetResponse), &out_dir);
export_schema(&schema_for!(LBPairInformationResponse), &out_dir);
export_schema(&schema_for!(PresetResponse), &out_dir);
export_schema(&schema_for!(AllBinStepsResponse), &out_dir);
export_schema(&schema_for!(OpenBinStepsResponse), &out_dir);
export_schema(&schema_for!(AllLBPairsResponse), &out_dir);
}
12 changes: 6 additions & 6 deletions contracts/liquidity_book/lb_factory/src/bin/secretcli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,7 @@ fn main() -> io::Result<()> {
admin_auth: RawContract::example(),
owner: Some(Addr::owner()),
fee_recipient: Addr::recipient(),
total_reward_bins: 10,
rewards_distribution_algorithm: RewardsDistributionAlgorithm::TimeBasedRewards,
epoch_staking_index: 1,
epoch_staking_duration: 100,
expiry_staking_duration: None,

recover_staking_funds_receiver: Addr::funds_recipient(),
};

Expand Down Expand Up @@ -113,7 +109,11 @@ fn main() -> io::Result<()> {
protocol_share: 100,
max_volatility_accumulator: 100,
is_open: true,
total_reward_bins: 0,
total_reward_bins: 10,
rewards_distribution_algorithm: RewardsDistributionAlgorithm::TimeBasedRewards,
epoch_staking_index: 1,
epoch_staking_duration: 100,
expiry_staking_duration: None,
};

let set_preset_open_state = ExecuteMsg::SetPresetOpenState {
Expand Down
88 changes: 55 additions & 33 deletions contracts/liquidity_book/lb_factory/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashSet;

use crate::{
prelude::*,
state::*,
Expand All @@ -17,7 +19,6 @@ use shade_protocol::{
DepsMut,
Env,
MessageInfo,
Order::Ascending,
Reply,
Response,
StdError,
Expand All @@ -34,7 +35,10 @@ use shade_protocol::{
},
liquidity_book::{
lb_factory::*,
lb_pair::ExecuteMsg::{ForceDecay as LbPairForceDecay, SetStaticFeeParameters},
lb_pair::{
ExecuteMsg::{ForceDecay as LbPairForceDecay, SetStaticFeeParameters},
RewardsDistributionAlgorithm,
},
},
swap::core::TokenType,
utils::callback::ExecuteCallback,
Expand Down Expand Up @@ -65,16 +69,12 @@ pub fn instantiate(
lb_pair_implementation: ContractInstantiationInfo::default(),
lb_token_implementation: ContractInstantiationInfo::default(),
admin_auth: msg.admin_auth.into_valid(deps.api)?,
total_reward_bins: msg.total_reward_bins,
rewards_distribution_algorithm: msg.rewards_distribution_algorithm,
staking_contract_implementation: ContractInstantiationInfo::default(),
epoch_staking_index: msg.epoch_staking_index,
epoch_staking_duration: msg.epoch_staking_duration,
expiry_staking_duration: msg.expiry_staking_duration,
recover_staking_funds_receiver: msg.recover_staking_funds_receiver,
};

STATE.save(deps.storage, &config)?;
PRESET_HASHSET.save(deps.storage, &HashSet::new())?;
CONTRACT_STATUS.save(deps.storage, &ContractStatus::Active)?;

Ok(Response::default())
Expand Down Expand Up @@ -140,6 +140,10 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> R
max_volatility_accumulator,
is_open,
total_reward_bins,
rewards_distribution_algorithm,
epoch_staking_index,
epoch_staking_duration,
expiry_staking_duration,
} => try_set_pair_preset(
deps,
env,
Expand All @@ -154,6 +158,10 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> R
max_volatility_accumulator,
is_open,
total_reward_bins,
rewards_distribution_algorithm,
epoch_staking_index,
epoch_staking_duration,
expiry_staking_duration,
),
ExecuteMsg::SetPresetOpenState { bin_step, is_open } => {
try_set_preset_open_state(deps, env, info, bin_step, is_open)
Expand Down Expand Up @@ -356,6 +364,10 @@ fn try_create_lb_pair(
});
}

let config = STATE.load(deps.storage)?;

let staking_preset = STAKING_PRESETS.load(deps.storage, bin_step)?;

// safety check, making sure that the price can be calculated
PriceHelper::get_price_from_id(active_id, bin_step)?;

Expand Down Expand Up @@ -412,12 +424,12 @@ fn try_create_lb_pair(
entropy,
protocol_fee_recipient: config.fee_recipient,
admin_auth: config.admin_auth.into(),
total_reward_bins: Some(config.total_reward_bins),
rewards_distribution_algorithm: config.rewards_distribution_algorithm,
total_reward_bins: Some(staking_preset.total_reward_bins),
rewards_distribution_algorithm: staking_preset.rewards_distribution_algorithm,
staking_contract_implementation: config.staking_contract_implementation,
epoch_staking_index: config.epoch_staking_index,
epoch_staking_duration: config.epoch_staking_duration,
expiry_staking_duration: config.expiry_staking_duration,
epoch_staking_index: staking_preset.epoch_staking_index,
epoch_staking_duration: staking_preset.epoch_staking_duration,
expiry_staking_duration: staking_preset.expiry_staking_duration,
recover_staking_funds_receiver: config.recover_staking_funds_receiver,
})?,
code_hash: config.lb_pair_implementation.code_hash.clone(),
Expand Down Expand Up @@ -535,6 +547,10 @@ fn try_set_pair_preset(
max_volatility_accumulator: u32,
is_open: bool,
total_reward_bins: u32,
rewards_distribution_algorithm: RewardsDistributionAlgorithm,
epoch_staking_index: u64,
epoch_staking_duration: u64,
expiry_staking_duration: Option<u64>,
) -> Result<Response> {
let mut state = STATE.load(deps.storage)?;
validate_admin(
Expand Down Expand Up @@ -563,9 +579,23 @@ fn try_set_pair_preset(
preset.0.set_bool(true, _OFFSET_IS_PRESET_OPEN);
}

let mut hashset = PRESET_HASHSET.load(deps.storage)?;

if !hashset.contains(&bin_step) {
hashset.insert(bin_step);

PRESET_HASHSET.save(deps.storage, &hashset)?;
}

PRESETS.save(deps.storage, bin_step, &preset)?;

state.total_reward_bins = total_reward_bins;
STAKING_PRESETS.save(deps.storage, bin_step, &StakingPreset {
total_reward_bins,
rewards_distribution_algorithm,
epoch_staking_index,
epoch_staking_duration,
expiry_staking_duration,
})?;

STATE.save(deps.storage, &state)?;

Expand Down Expand Up @@ -636,6 +666,10 @@ fn try_remove_preset(

PRESETS.remove(deps.storage, bin_step);

let mut hashset = PRESET_HASHSET.load(deps.storage)?;
hashset.remove(&bin_step);
PRESET_HASHSET.save(deps.storage, &hashset)?;

Ok(Response::default().add_attribute_plaintext("preset removed", bin_step.to_string()))
}

Expand Down Expand Up @@ -1137,10 +1171,11 @@ fn query_all_bin_steps(deps: Deps) -> Result<Binary> {

let mut bin_step_with_preset = Vec::<u16>::new();

let iterator = PRESETS.range(deps.storage, None, None, Ascending);
let hashset = PRESET_HASHSET.load(deps.storage)?;

// let iterator = PRESETS.range(deps.storage, None, None, Ascending);

for result in iterator {
let (bin_step, _preset) = result.map_err(Error::CwErr)?;
for bin_step in hashset {
bin_step_with_preset.push(bin_step)
}

Expand All @@ -1158,27 +1193,14 @@ fn query_all_bin_steps(deps: Deps) -> Result<Binary> {
/// * `open_bin_step` - The list of open bin steps.
fn query_open_bin_steps(deps: Deps) -> Result<Binary> {
// this way is harder to ready, but maybe more efficient?
// let open_bin_steps = PRESETS
// .map(|result| {
// result
// .map_err(Error::CwErr)
// .map(|(bin_step, preset)| {
// if _is_preset_open(preset.0 .0) {
// Some(bin_step)
// } else {
// None
// }
// })
// .transpose()
// })
// .collect::<Result<Vec<u16>>>()?;

let hashset = PRESET_HASHSET.load(deps.storage)?;

let mut open_bin_steps = Vec::<u16>::new();

let iterator = PRESETS.range(deps.storage, None, None, Ascending);
for bin_step in hashset {
let preset = PRESETS.load(deps.storage, bin_step)?;

for result in iterator {
let (bin_step, preset) = result.map_err(Error::CwErr)?;
if _is_preset_open(preset.0.0) {
open_bin_steps.push(bin_step)
}
Expand Down
17 changes: 15 additions & 2 deletions contracts/liquidity_book/lb_factory/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use crate::types::{LBPair, LBPairInformation, NextPairKey};
use std::collections::HashSet;

use shade_protocol::{
c_std::{Addr, ContractInfo, Storage},
cosmwasm_schema::cw_serde,
lb_libraries::{pair_parameter_helper::PairParameters, types::ContractInstantiationInfo},
lb_libraries::{
pair_parameter_helper::PairParameters,
types::{ContractInstantiationInfo, TreeUint24},
},
liquidity_book::lb_pair::RewardsDistributionAlgorithm,
secret_storage_plus::{AppendStore, Item, Map},
storage::{singleton, singleton_read, ReadonlySingleton, Singleton},
Expand All @@ -22,9 +26,14 @@ pub static ALL_LB_PAIRS: AppendStore<LBPair> = AppendStore::new("all_lb_pairs");
/// The tokens are ordered to save gas, but they can be in the reverse order in the actual pair.
pub const LB_PAIRS_INFO: Map<(String, String, u16), LBPairInformation> = Map::new("lb_pairs_info");

pub const PRESET_HASHSET: Item<HashSet<u16>> = Item::new("preset_hashset");

/// Map of bin_step to preset, which is an encoded Bytes32 set of pair parameters
pub const PRESETS: Map<u16, PairParameters> = Map::new("presets");

/// Map of bin_step to preset, which is an encoded Bytes32 set of pair parameters
pub const STAKING_PRESETS: Map<u16, StakingPreset> = Map::new("stkaing_presets");

// 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 static QUOTE_ASSET_WHITELIST: AppendStore<TokenType> =
Expand Down Expand Up @@ -54,12 +63,16 @@ pub struct State {
pub lb_token_implementation: ContractInstantiationInfo,
pub staking_contract_implementation: ContractInstantiationInfo,
pub admin_auth: Contract,
pub recover_staking_funds_receiver: Addr,
}

#[cw_serde]
pub struct StakingPreset {
pub total_reward_bins: u32,
pub rewards_distribution_algorithm: RewardsDistributionAlgorithm,
pub epoch_staking_index: u64,
pub epoch_staking_duration: u64,
pub expiry_staking_duration: Option<u64>,
pub recover_staking_funds_receiver: Addr,
}

pub fn ephemeral_storage_w(storage: &mut dyn Storage) -> Singleton<NextPairKey> {
Expand Down
Loading

0 comments on commit efcda10

Please sign in to comment.