From af8a526e1e7f99edf9ff4abf9ba1f958b717e9cc Mon Sep 17 00:00:00 2001 From: kent-3 <100624004+kent-3@users.noreply.github.com> Date: Sun, 26 May 2024 00:06:44 -0400 Subject: [PATCH] move lb-libraries out of shade-protocol --- Cargo.toml | 1 + .../liquidity_book/lb_factory/Cargo.toml | 15 +- .../src/bin/secretcli/example_data.rs | 13 +- .../lb_factory/src/bin/secretcli/main.rs | 15 +- .../liquidity_book/lb_factory/src/contract.rs | 69 ++-- .../liquidity_book/lb_factory/src/error.rs | 21 +- .../liquidity_book/lb_factory/src/state.rs | 11 +- .../liquidity_book/lb_factory/src/types.rs | 2 +- contracts/liquidity_book/lb_pair/Cargo.toml | 23 +- .../lb_pair/src/bin/secretcli/example_data.rs | 15 +- .../lb_pair/src/bin/secretcli/main.rs | 19 +- .../liquidity_book/lb_pair/src/contract.rs | 67 ++-- contracts/liquidity_book/lb_pair/src/error.rs | 21 +- .../liquidity_book/lb_pair/src/execute.rs | 93 +++-- .../liquidity_book/lb_pair/src/helper.rs | 34 +- contracts/liquidity_book/lb_pair/src/lib.rs | 1 + contracts/liquidity_book/lb_pair/src/query.rs | 199 +++++----- contracts/liquidity_book/lb_pair/src/state.rs | 20 +- .../liquidity_book/lb_staking/Cargo.toml | 28 +- .../src/bin/secretcli/example_data.rs | 16 +- .../liquidity_book/lb_staking/src/contract.rs | 59 ++- .../liquidity_book/lb_staking/src/execute.rs | 114 ++---- .../liquidity_book/lb_staking/src/state.rs | 15 +- contracts/liquidity_book/lb_token/Cargo.toml | 29 +- .../liquidity_book/lb_token/src/contract.rs | 46 +-- .../liquidity_book/lb_token/src/execute.rs | 64 +-- .../liquidity_book/lb_token/src/query.rs | 40 +- .../liquidity_book/lb_token/src/state/mod.rs | 53 +-- .../lb_token/src/state/permissions.rs | 6 +- .../lb_token/src/state/txhistory.rs | 6 +- .../lb_token/src/unittest/handletests.rs | 72 ++-- .../lb_token/src/unittest/querytests.rs | 142 +++---- .../lb_token/src/unittest/testhelpers.rs | 32 +- contracts/liquidity_book/router/Cargo.toml | 28 +- .../router/src/bin/secretcli/example_data.rs | 15 +- .../router/src/bin/secretcli/main.rs | 2 +- contracts/liquidity_book/tests/Cargo.toml | 32 +- .../tests/src/multitests/lb_factory.rs | 11 +- .../tests/src/multitests/lb_pair_fees.rs | 30 +- .../src/multitests/lb_pair_initial_state.rs | 7 +- .../tests/src/multitests/lb_pair_liquidity.rs | 10 +- .../tests/src/multitests/lb_pair_oracle.rs | 19 +- .../tests/src/multitests/lb_pair_queries.rs | 3 +- .../tests/src/multitests/lb_pair_rewards.rs | 31 +- .../tests/src/multitests/lb_pair_swap.rs | 16 +- .../tests/src/multitests/lb_pair_trivial.rs | 6 +- .../src/multitests/lb_router_integration.rs | 65 ++-- .../multitests/lb_router_register_tokens.rs | 7 +- .../tests/src/multitests/lb_staking.rs | 25 +- .../tests/src/multitests/lb_token.rs | 23 +- .../tests/src/multitests/test_helper.rs | 25 +- packages/lb_libraries/Cargo.toml | 18 + .../src}/bin_helper.rs | 59 +-- .../src}/constants.rs | 0 .../src}/error.rs | 0 .../src}/fee_helper.rs | 0 .../src}/lb_token/expiration.rs | 0 .../src}/lb_token/metadata.rs | 0 .../src}/lb_token/mod.rs | 0 .../src}/lb_token/permissions.rs | 0 .../src}/lb_token/state_structs.rs | 0 .../src}/lb_token/txhistory.rs | 0 .../mod.rs => lb_libraries/src/lib.rs} | 2 - .../src}/math/bit_math.rs | 0 .../src}/math/encoded_sample.rs | 2 +- .../src}/math/liquidity_configurations.rs | 2 +- .../src}/math/mod.rs | 0 .../src}/math/packed_u128_math.rs | 3 +- .../src}/math/safe_math.rs | 2 +- .../src}/math/sample_math.rs | 6 +- .../src}/math/tree_math.rs | 7 +- .../src}/math/u128x128_math.rs | 3 +- .../src}/math/u24.rs | 0 .../src}/math/u256x256_math.rs | 2 +- .../src}/math/uint256_to_u256.rs | 0 .../src}/oracle_helper.rs | 0 .../src}/pair_parameter_helper.rs | 24 +- .../src}/price_helper.rs | 0 packages/lb_libraries/src/types.rs | 30 ++ packages/multi_test/Cargo.toml | 2 +- .../multi_test/src/interfaces/lb_factory.rs | 19 +- packages/multi_test/src/interfaces/lb_pair.rs | 20 +- .../multi_test/src/interfaces/lb_token.rs | 2 +- packages/shade_protocol/Cargo.toml | 4 +- .../liquidity_book/lb_factory.rs | 31 +- .../liquidity_book/lb_libraries/transfer.rs | 108 ------ .../liquidity_book/lb_libraries/types.rs | 57 --- .../lb_libraries/viewing_keys.rs | 112 ------ .../liquidity_book/lb_pair.rs | 29 +- .../liquidity_book/lb_staking.rs | 32 +- .../liquidity_book/lb_token.rs | 19 +- .../contract_interfaces/liquidity_book/mod.rs | 2 - .../liquidity_book/router.rs | 113 ++++++ .../liquidity_book/token_type.rs | 365 ++++++++++++++++++ packages/shade_protocol/src/lib.rs | 3 - .../src/utils/liquidity_book/constants.rs | 20 - 96 files changed, 1376 insertions(+), 1438 deletions(-) create mode 100644 packages/lb_libraries/Cargo.toml rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/bin_helper.rs (96%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/constants.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/error.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/fee_helper.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/expiration.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/metadata.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/mod.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/permissions.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/state_structs.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/lb_token/txhistory.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/mod.rs => lb_libraries/src/lib.rs} (94%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/bit_math.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/encoded_sample.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/liquidity_configurations.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/mod.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/packed_u128_math.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/safe_math.rs (96%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/sample_math.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/tree_math.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/u128x128_math.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/u24.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/u256x256_math.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/math/uint256_to_u256.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/oracle_helper.rs (100%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/pair_parameter_helper.rs (99%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/price_helper.rs (100%) create mode 100644 packages/lb_libraries/src/types.rs delete mode 100644 packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/transfer.rs delete mode 100644 packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs delete mode 100644 packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/viewing_keys.rs create mode 100644 packages/shade_protocol/src/contract_interfaces/liquidity_book/router.rs create mode 100644 packages/shade_protocol/src/contract_interfaces/liquidity_book/token_type.rs delete mode 100644 packages/shade_protocol/src/utils/liquidity_book/constants.rs diff --git a/Cargo.toml b/Cargo.toml index dc7e7613..f16d86b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "packages/multi_test", "packages/multi_derive", "packages/contract_derive", + "packages/lb_libraries", # Network setups #"contracts/airdrop", diff --git a/contracts/liquidity_book/lb_factory/Cargo.toml b/contracts/liquidity_book/lb_factory/Cargo.toml index 658092bb..23ad330f 100644 --- a/contracts/liquidity_book/lb_factory/Cargo.toml +++ b/contracts/liquidity_book/lb_factory/Cargo.toml @@ -2,11 +2,7 @@ name = "lb_factory" version = "0.1.0" edition = "2021" -exclude = [ - # Those files are contract-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] @@ -14,7 +10,7 @@ crate-type = ["cdylib", "rlib"] [[example]] name = "schema" -path = "schema/schema.rs" # Adjust the path according to your project structure +path = "schema/schema.rs" [features] @@ -25,13 +21,12 @@ schema = [] backtraces = ["cosmwasm-std/backtraces"] - - [dependencies] -shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] } +shade-protocol = { path = "../../../packages/shade_protocol" } +lb-libraries = { path = "../../../packages/lb_libraries" } schemars = "0.8.16" serde = { version = "1.0" } -cosmwasm-schema = "1.5" +cosmwasm-schema = "2.0.3" thiserror = { version = "1.0" } ethnum = { version = "1.5" } serde_json = "1" diff --git a/contracts/liquidity_book/lb_factory/src/bin/secretcli/example_data.rs b/contracts/liquidity_book/lb_factory/src/bin/secretcli/example_data.rs index 80b6628e..d61f0164 100644 --- a/contracts/liquidity_book/lb_factory/src/bin/secretcli/example_data.rs +++ b/contracts/liquidity_book/lb_factory/src/bin/secretcli/example_data.rs @@ -1,12 +1,7 @@ +use lb_libraries::types::{ContractImplementation, StaticFeeParameters}; use shade_protocol::{ c_std::{to_binary, Addr, ContractInfo, Uint128, Uint256}, - lb_libraries::types::{ - ContractInstantiationInfo, - LBPair, - LBPairInformation, - StaticFeeParameters, - }, - liquidity_book::lb_pair::{LiquidityParameters, RemoveLiquidity}, + liquidity_book::lb_pair::{LBPair, LBPairInformation, LiquidityParameters, RemoveLiquidity}, snip20::Snip20ReceiveMsg, swap::core::{TokenAmount, TokenType}, utils::asset::RawContract, @@ -54,9 +49,9 @@ pub trait ExampleData { fn example() -> Self; } -impl ExampleData for ContractInstantiationInfo { +impl ExampleData for ContractImplementation { fn example() -> Self { - ContractInstantiationInfo { + ContractImplementation { id: 1u64, code_hash: "0123456789ABCDEF".to_string(), } diff --git a/contracts/liquidity_book/lb_factory/src/bin/secretcli/main.rs b/contracts/liquidity_book/lb_factory/src/bin/secretcli/main.rs index 1195a790..8b29d935 100644 --- a/contracts/liquidity_book/lb_factory/src/bin/secretcli/main.rs +++ b/contracts/liquidity_book/lb_factory/src/bin/secretcli/main.rs @@ -1,11 +1,14 @@ mod example_data; use example_data::{ExampleData, VariousAddr, ACTIVE_ID, BIN_STEP}; +use lb_libraries::types::ContractImplementation; use shade_protocol::{ c_std::{Addr, ContractInfo}, contract_interfaces::liquidity_book::lb_factory::{ExecuteMsg, InstantiateMsg, QueryMsg}, - lb_libraries::types::{ContractInstantiationInfo, LBPair, LBPairInformation}, - liquidity_book::{lb_factory::*, lb_pair::RewardsDistributionAlgorithm}, + liquidity_book::{ + lb_factory::*, + lb_pair::{LBPair, LBPairInformation, RewardsDistributionAlgorithm}, + }, swap::core::TokenType, utils::asset::RawContract, }; @@ -83,11 +86,11 @@ fn main() -> io::Result<()> { // -- Execute Messages let set_lb_pair_implementation = ExecuteMsg::SetLBPairImplementation { - implementation: ContractInstantiationInfo::example(), + implementation: ContractImplementation::example(), }; let set_lb_token_implementation = ExecuteMsg::SetLBTokenImplementation { - implementation: ContractInstantiationInfo::example(), + implementation: ContractImplementation::example(), }; let create_lb_pair = ExecuteMsg::CreateLBPair { @@ -208,10 +211,10 @@ fn main() -> io::Result<()> { fee_recipient: Addr::recipient(), }; let get_lb_pair_implementation_response = LBPairImplementationResponse { - lb_pair_implementation: ContractInstantiationInfo::example(), + lb_pair_implementation: ContractImplementation::example(), }; let get_lb_token_implementation_response = LBTokenImplementationResponse { - lb_token_implementation: ContractInstantiationInfo::example(), + lb_token_implementation: ContractImplementation::example(), }; let get_number_of_lb_pairs_response = NumberOfLBPairsResponse { lb_pair_number: 1 }; diff --git a/contracts/liquidity_book/lb_factory/src/contract.rs b/contracts/liquidity_book/lb_factory/src/contract.rs index 5cf10133..ee39828f 100644 --- a/contracts/liquidity_book/lb_factory/src/contract.rs +++ b/contracts/liquidity_book/lb_factory/src/contract.rs @@ -1,37 +1,19 @@ -use std::collections::HashSet; - use crate::{ prelude::*, state::*, types::{LBPair, LBPairInformation, NextPairKey}, }; - +use lb_libraries::{ + math::encoded_sample::EncodedSample, + pair_parameter_helper::PairParameters, + price_helper::PriceHelper, + types::{Bytes32, ContractImplementation, StaticFeeParameters}, +}; use shade_protocol::{ admin::helpers::{validate_admin, AdminPermissions}, c_std::{ - shd_entry_point, - to_binary, - Addr, - Binary, - ContractInfo, - CosmosMsg, - Deps, - DepsMut, - Env, - MessageInfo, - Reply, - Response, - StdError, - StdResult, - SubMsg, - SubMsgResult, - WasmMsg, - }, - lb_libraries::{ - math::encoded_sample::EncodedSample, - pair_parameter_helper::PairParameters, - price_helper::PriceHelper, - types::{Bytes32, ContractInstantiationInfo, StaticFeeParameters}, + shd_entry_point, to_binary, Addr, Binary, ContractInfo, CosmosMsg, Deps, DepsMut, Env, + MessageInfo, Reply, Response, StdError, StdResult, SubMsg, SubMsgResult, WasmMsg, }, liquidity_book::{ lb_factory::*, @@ -43,6 +25,7 @@ use shade_protocol::{ swap::core::TokenType, utils::callback::ExecuteCallback, }; +use std::collections::HashSet; pub static _OFFSET_IS_PRESET_OPEN: u8 = 255; pub static _MIN_BIN_STEP: u8 = 1; // 0.001% @@ -66,10 +49,10 @@ pub fn instantiate( }, owner: msg.owner.unwrap_or_else(|| info.sender.clone()), fee_recipient: msg.fee_recipient, - lb_pair_implementation: ContractInstantiationInfo::default(), - lb_token_implementation: ContractInstantiationInfo::default(), + lb_pair_implementation: ContractImplementation::default(), + lb_token_implementation: ContractImplementation::default(), admin_auth: msg.admin_auth.into_valid(deps.api)?, - staking_contract_implementation: ContractInstantiationInfo::default(), + staking_contract_implementation: ContractImplementation::default(), recover_staking_funds_receiver: msg.recover_staking_funds_receiver, query_auth: msg.query_auth.into_valid(deps.api)?, max_bins_per_swap: msg.max_bins_per_swap, @@ -214,7 +197,7 @@ fn try_set_lb_pair_implementation( deps: DepsMut, _env: Env, info: MessageInfo, - new_lb_pair_implementation: ContractInstantiationInfo, + new_lb_pair_implementation: ContractImplementation, ) -> Result { let config = STATE.load(deps.storage)?; validate_admin( @@ -248,7 +231,7 @@ fn try_set_lb_token_implementation( deps: DepsMut, _env: Env, info: MessageInfo, - new_lb_token_implementation: ContractInstantiationInfo, + new_lb_token_implementation: ContractImplementation, ) -> Result { let config = STATE.load(deps.storage)?; validate_admin( @@ -282,7 +265,7 @@ fn try_set_staking_contract_implementation( deps: DepsMut, _env: Env, info: MessageInfo, - new_implementation: ContractInstantiationInfo, + new_implementation: ContractImplementation, ) -> Result { let config = STATE.load(deps.storage)?; validate_admin( @@ -341,7 +324,7 @@ fn try_create_lb_pair( .map_err(|_| Error::BinStepHasNoPreset { bin_step })?; let is_owner = info.sender == config.owner; - if !_is_preset_open(preset.0.0) && !is_owner { + if !_is_preset_open(preset.0 .0) && !is_owner { return Err(Error::PresetIsLockedForUsers { user: info.sender, bin_step, @@ -523,13 +506,17 @@ fn try_set_pair_preset( PRESETS.save(deps.storage, bin_step, &preset)?; - STAKING_PRESETS.save(deps.storage, bin_step, &StakingPreset { - total_reward_bins, - rewards_distribution_algorithm, - epoch_staking_index, - epoch_staking_duration, - expiry_staking_duration, - })?; + 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)?; @@ -1136,7 +1123,7 @@ fn query_open_bin_steps(deps: Deps) -> Result { for bin_step in hashset { let preset = PRESETS.load(deps.storage, bin_step)?; - if _is_preset_open(preset.0.0) { + if _is_preset_open(preset.0 .0) { open_bin_steps.push(bin_step) } } diff --git a/contracts/liquidity_book/lb_factory/src/error.rs b/contracts/liquidity_book/lb_factory/src/error.rs index 6c6d2949..e304a151 100644 --- a/contracts/liquidity_book/lb_factory/src/error.rs +++ b/contracts/liquidity_book/lb_factory/src/error.rs @@ -1,19 +1,16 @@ //! ### Custom Errors for LB_Factory contract. -use shade_protocol::{ - c_std::{Addr, StdError}, - lb_libraries::{ - bin_helper::BinError, - fee_helper::FeeError, - math::{ - liquidity_configurations::LiquidityConfigurationsError, - u128x128_math::U128x128MathError, - u256x256_math::U256x256MathError, - }, - oracle_helper::OracleError, - pair_parameter_helper::PairParametersError, +use lb_libraries::{ + bin_helper::BinError, + fee_helper::FeeError, + math::{ + liquidity_configurations::LiquidityConfigurationsError, u128x128_math::U128x128MathError, + u256x256_math::U256x256MathError, }, + oracle_helper::OracleError, + pair_parameter_helper::PairParametersError, }; +use shade_protocol::c_std::{Addr, StdError}; #[derive(thiserror::Error, Debug)] pub enum LBFactoryError { diff --git a/contracts/liquidity_book/lb_factory/src/state.rs b/contracts/liquidity_book/lb_factory/src/state.rs index 7f60f078..bfa8eb4a 100644 --- a/contracts/liquidity_book/lb_factory/src/state.rs +++ b/contracts/liquidity_book/lb_factory/src/state.rs @@ -1,16 +1,15 @@ use crate::types::{LBPair, LBPairInformation, NextPairKey}; -use std::collections::HashSet; - +use lb_libraries::{pair_parameter_helper::PairParameters, types::ContractImplementation}; use shade_protocol::{ c_std::{Addr, ContractInfo, Storage}, cosmwasm_schema::cw_serde, - lb_libraries::{pair_parameter_helper::PairParameters, types::ContractInstantiationInfo}, liquidity_book::lb_pair::RewardsDistributionAlgorithm, secret_storage_plus::{AppendStore, Item, Map}, storage::{singleton, singleton_read, ReadonlySingleton, Singleton}, swap::core::TokenType, Contract, }; +use std::collections::HashSet; pub const CONTRACT_STATUS: Item = Item::new("contract_status"); pub const STATE: Item = Item::new("state"); @@ -56,9 +55,9 @@ pub struct State { pub contract_info: ContractInfo, pub owner: Addr, pub fee_recipient: Addr, - pub lb_pair_implementation: ContractInstantiationInfo, - pub lb_token_implementation: ContractInstantiationInfo, - pub staking_contract_implementation: ContractInstantiationInfo, + pub lb_pair_implementation: ContractImplementation, + pub lb_token_implementation: ContractImplementation, + pub staking_contract_implementation: ContractImplementation, pub admin_auth: Contract, pub query_auth: Contract, pub recover_staking_funds_receiver: Addr, diff --git a/contracts/liquidity_book/lb_factory/src/types.rs b/contracts/liquidity_book/lb_factory/src/types.rs index b066d68d..54239848 100644 --- a/contracts/liquidity_book/lb_factory/src/types.rs +++ b/contracts/liquidity_book/lb_factory/src/types.rs @@ -1,6 +1,6 @@ use shade_protocol::{cosmwasm_schema::cw_serde, swap::core::TokenType}; -pub use shade_protocol::lb_libraries::types::{LBPair, LBPairInformation}; +pub use shade_protocol::liquidity_book::lb_pair::{LBPair, LBPairInformation}; #[cw_serde] pub struct NextPairKey { diff --git a/contracts/liquidity_book/lb_pair/Cargo.toml b/contracts/liquidity_book/lb_pair/Cargo.toml index 8bb9f7e2..f7eb95bf 100644 --- a/contracts/liquidity_book/lb_pair/Cargo.toml +++ b/contracts/liquidity_book/lb_pair/Cargo.toml @@ -2,18 +2,14 @@ name = "lb_pair" version = "0.1.0" edition = "2021" -exclude = [ - # Those files are contract-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] [[example]] name = "schema" -path = "schema/schema.rs" # Adjust the path according to your project structure +path = "schema/schema.rs" [features] @@ -24,11 +20,12 @@ schema = [] backtraces = ["cosmwasm-std/backtraces"] [dependencies] -shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] } +shade-protocol = { path = "../../../packages/shade_protocol" } +lb-libraries = { path = "../../../packages/lb_libraries" } schemars = "0.8.16" serde = { version = "1.0" } -serde-json-wasm = { version = "1.0"} -cosmwasm-schema = "1.5" +serde-json-wasm = { version = "1.0" } +cosmwasm-schema = "2.0.3" thiserror = { version = "1.0" } ethnum = { version = "1.5" } serde_json = "1" @@ -36,10 +33,4 @@ serde_json = "1" [dev-dependencies] anyhow = "1" cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.1.11" } -shade-multi-test = { path = "../../../packages/multi_test", features = [ - "admin", - "lb_pair", - "lb_token", - "snip20", -] } - +shade-multi-test = { path = "../../../packages/multi_test", features = ["admin", "lb_pair", "lb_token", "snip20"] } diff --git a/contracts/liquidity_book/lb_pair/src/bin/secretcli/example_data.rs b/contracts/liquidity_book/lb_pair/src/bin/secretcli/example_data.rs index bb7dfe40..03a3c769 100644 --- a/contracts/liquidity_book/lb_pair/src/bin/secretcli/example_data.rs +++ b/contracts/liquidity_book/lb_pair/src/bin/secretcli/example_data.rs @@ -1,15 +1,8 @@ +use lb_libraries::types::{ContractImplementation, StaticFeeParameters}; use shade_protocol::{ c_std::{to_binary, Addr, ContractInfo, Uint128, Uint256}, - lb_libraries::types::{ - ContractInstantiationInfo, - LBPair, - LBPairInformation, - StaticFeeParameters, - }, liquidity_book::lb_pair::{ - LiquidityParameters, - RemoveLiquidity, - RewardsDistribution, + LBPair, LBPairInformation, LiquidityParameters, RemoveLiquidity, RewardsDistribution, TokenPair, }, snip20::Snip20ReceiveMsg, @@ -65,9 +58,9 @@ pub trait ExampleData { fn example() -> Self; } -impl ExampleData for ContractInstantiationInfo { +impl ExampleData for ContractImplementation { fn example() -> Self { - ContractInstantiationInfo { + ContractImplementation { id: 1u64, code_hash: "0123456789ABCDEF".to_string(), } diff --git a/contracts/liquidity_book/lb_pair/src/bin/secretcli/main.rs b/contracts/liquidity_book/lb_pair/src/bin/secretcli/main.rs index 41c1e915..d190f351 100644 --- a/contracts/liquidity_book/lb_pair/src/bin/secretcli/main.rs +++ b/contracts/liquidity_book/lb_pair/src/bin/secretcli/main.rs @@ -2,19 +2,16 @@ mod example_data; use ethnum::U256; use example_data::*; +use lb_libraries::{ + math::uint256_to_u256::ConvertU256, + pair_parameter_helper::PairParameters, + types::{ContractImplementation, StaticFeeParameters}, +}; use shade_protocol::{ c_std::{Addr, ContractInfo, Decimal256, Uint128, Uint256}, contract_interfaces::liquidity_book::lb_pair::*, - lb_libraries::{ - math::uint256_to_u256::ConvertU256, - pair_parameter_helper::PairParameters, - types::{ContractInstantiationInfo, StaticFeeParameters}, - }, liquidity_book::lb_pair::{ - ContractStatus, - InvokeMsg, - LiquidityParameters, - RemoveLiquidity, + ContractStatus, InvokeMsg, LiquidityParameters, RemoveLiquidity, RewardsDistributionAlgorithm, }, swap::core::{TokenAmount, TokenType}, @@ -115,8 +112,8 @@ fn main() -> io::Result<()> { max_volatility_accumulator: preset.get_max_volatility_accumulator(), }, active_id: ACTIVE_ID, - lb_token_implementation: ContractInstantiationInfo::default(), - staking_contract_implementation: ContractInstantiationInfo::default(), + lb_token_implementation: ContractImplementation::default(), + staking_contract_implementation: ContractImplementation::default(), viewing_key: String::from("viewing_key"), entropy: String::from("entropy"), protocol_fee_recipient: Addr::funds_recipient(), diff --git a/contracts/liquidity_book/lb_pair/src/contract.rs b/contracts/liquidity_book/lb_pair/src/contract.rs index 972254db..99fc0c72 100644 --- a/contracts/liquidity_book/lb_pair/src/contract.rs +++ b/contracts/liquidity_book/lb_pair/src/contract.rs @@ -1,39 +1,19 @@ use crate::{execute::*, helper::*, prelude::*, query::*, state::*}; +use lb_libraries::{ + lb_token::state_structs::LbPair, + math::{sample_math::OracleSample, tree_math::TreeUint24, u24::U24}, + oracle_helper::Oracle, + pair_parameter_helper::PairParameters, +}; use shade_protocol::{ admin::helpers::{validate_admin, AdminPermissions}, c_std::{ - from_binary, - shd_entry_point, - to_binary, - Addr, - Binary, - ContractInfo, - CosmosMsg, - Deps, - DepsMut, - Env, - MessageInfo, - Reply, - Response, - StdError, - StdResult, - SubMsg, - SubMsgResult, - Uint128, - Uint256, - WasmMsg, - }, - contract_interfaces::{ - liquidity_book::{lb_pair::*, lb_staking, lb_token}, - swap::core::TokenType, - }, - lb_libraries::{ - lb_token::state_structs::LbPair, - math::{sample_math::OracleSample, tree_math::TreeUint24, u24::U24}, - oracle_helper::Oracle, - pair_parameter_helper::PairParameters, - viewing_keys::ViewingKey, + from_binary, shd_entry_point, to_binary, Addr, Binary, ContractInfo, CosmosMsg, Deps, + DepsMut, Env, MessageInfo, Reply, Response, StdError, StdResult, SubMsg, SubMsgResult, + Uint128, Uint256, WasmMsg, }, + contract_interfaces::liquidity_book::{lb_pair::*, lb_staking, lb_token}, + swap::core::{TokenAmount, TokenType, ViewingKey}, }; use std::vec; @@ -185,17 +165,20 @@ pub fn instantiate( rewards_distribution_algorithm: msg.rewards_distribution_algorithm, }, )?; - EPHEMERAL_STORAGE.save(deps.storage, &EphemeralStruct { - lb_token_code_hash: msg.lb_token_implementation.code_hash, - staking_contract: msg.staking_contract_implementation, - token_x_symbol, - token_y_symbol, - epoch_index: state.rewards_epoch_index, - epoch_duration: msg.epoch_staking_duration, - expiry_duration: msg.expiry_staking_duration, - recover_funds_receiver: msg.recover_staking_funds_receiver, - query_auth: msg.query_auth, - })?; + EPHEMERAL_STORAGE.save( + deps.storage, + &EphemeralStruct { + lb_token_code_hash: msg.lb_token_implementation.code_hash, + staking_contract: msg.staking_contract_implementation, + token_x_symbol, + token_y_symbol, + epoch_index: state.rewards_epoch_index, + epoch_duration: msg.epoch_staking_duration, + expiry_duration: msg.expiry_staking_duration, + recover_funds_receiver: msg.recover_staking_funds_receiver, + query_auth: msg.query_auth, + }, + )?; response = response.add_messages(messages); diff --git a/contracts/liquidity_book/lb_pair/src/error.rs b/contracts/liquidity_book/lb_pair/src/error.rs index a3e297b4..a0e85111 100644 --- a/contracts/liquidity_book/lb_pair/src/error.rs +++ b/contracts/liquidity_book/lb_pair/src/error.rs @@ -1,19 +1,16 @@ //! ### Custom Errors for LB_Pair contract. -use shade_protocol::{ - c_std::{StdError, Uint128, Uint256}, - lb_libraries::{ - bin_helper::BinError, - fee_helper::FeeError, - math::{ - liquidity_configurations::LiquidityConfigurationsError, - u128x128_math::U128x128MathError, - u256x256_math::U256x256MathError, - }, - oracle_helper::OracleError, - pair_parameter_helper::PairParametersError, +use lb_libraries::{ + bin_helper::BinError, + fee_helper::FeeError, + math::{ + liquidity_configurations::LiquidityConfigurationsError, u128x128_math::U128x128MathError, + u256x256_math::U256x256MathError, }, + oracle_helper::OracleError, + pair_parameter_helper::PairParametersError, }; +use shade_protocol::c_std::{StdError, Uint128, Uint256}; #[derive(thiserror::Error, Debug)] pub enum LBPairError { diff --git a/contracts/liquidity_book/lb_pair/src/execute.rs b/contracts/liquidity_book/lb_pair/src/execute.rs index 864a3805..ec4eefa9 100644 --- a/contracts/liquidity_book/lb_pair/src/execute.rs +++ b/contracts/liquidity_book/lb_pair/src/execute.rs @@ -1,49 +1,43 @@ +use crate::helper::*; use crate::{prelude::*, state::*}; use ethnum::U256; +use lb_libraries::{ + approx_div, + bin_helper::BinHelper, + constants::{BASIS_POINT_MAX, MAX_FEE, PRECISION, SCALE_OFFSET}, + lb_token::state_structs::{TokenAmount, TokenIdBalance}, + math::{ + liquidity_configurations::LiquidityConfigurations, + packed_u128_math::PackedUint128Math, + tree_math::TreeUint24, + u24::U24, + u256x256_math::U256x256Math, + uint256_to_u256::{ConvertU256, ConvertUint256}, + }, + oracle_helper::Oracle, + pair_parameter_helper::PairParameters, + price_helper::PriceHelper, + types::Bytes32, +}; use shade_protocol::{ admin::helpers::{validate_admin, AdminPermissions}, c_std::{ - to_binary, - Addr, - Attribute, - CosmosMsg, - Deps, - DepsMut, - Env, - MessageInfo, - Response, - StdError, - StdResult, - Storage, - Timestamp, - Uint128, - Uint256, + to_binary, Addr, Attribute, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Response, StdError, + StdResult, Storage, Timestamp, Uint128, Uint256, }, contract_interfaces::{ liquidity_book::{lb_pair::*, lb_staking, lb_token}, - swap::{core::TokenType, router::ExecuteMsgResponse}, - }, - lb_libraries::{ - approx_div, - bin_helper::BinHelper, - constants::{BASIS_POINT_MAX, MAX_FEE, PRECISION, SCALE_OFFSET}, - lb_token::state_structs::{TokenAmount, TokenIdBalance}, - math::{ - liquidity_configurations::LiquidityConfigurations, - packed_u128_math::PackedUint128Math, - tree_math::TreeUint24, - u24::U24, - u256x256_math::U256x256Math, - uint256_to_u256::{ConvertU256, ConvertUint256}, - }, - oracle_helper::Oracle, - pair_parameter_helper::PairParameters, - price_helper::PriceHelper, - types::{Bytes32, MintArrays}, + swap::router::ExecuteMsgResponse, }, + swap::core::TokenType, }; -use crate::helper::*; +#[derive(Clone, Debug)] +pub struct MintArrays { + pub ids: Vec, + pub amounts: Vec, + pub liquidity_minted: Vec, +} /// Swap tokens iterating over the bins until the entire amount is swapped. /// @@ -172,8 +166,8 @@ pub fn try_swap( deps.storage, active_id, &bin_reserves - .add(amounts_in_with_fees) // actually amount in wihtout fees - .sub(amounts_out_of_bin), + .add(amounts_in_with_fees) // actually amount in wihtout fees + .sub(amounts_out_of_bin), )?; ids.push(active_id); } @@ -228,9 +222,11 @@ pub fn try_swap( amounts_out.decode_x() }; let msg = if swap_for_y { - BinHelper::transfer_y(amounts_out, token_y.clone(), to) + // BinHelper::transfer_y(amounts_out, token_y.clone(), to) + todo!() } else { - BinHelper::transfer_x(amounts_out, token_x.clone(), to) + // BinHelper::transfer_x(amounts_out, token_x.clone(), to) + todo!() }; // Add the message to messages if it exists if let Some(message) = msg { @@ -997,7 +993,8 @@ fn burn( config.reserves = config.reserves.sub(amounts_out); - let raw_msgs = BinHelper::transfer(amounts_out, token_x, token_y, info.sender); + let raw_msgs: Option> = todo!(); + // let raw_msgs = BinHelper::transfer(amounts_out, token_x, token_y, info.sender); STATE.update(deps.storage, |mut state| -> StdResult { state.reserves = state.reserves.sub(amounts_out); @@ -1051,14 +1048,14 @@ pub fn try_collect_protocol_fees(deps: DepsMut, _env: Env, info: MessageInfo) -> })?; if collected_protocol_fees.iter().any(|&x| x != 0) { - if let Some(msgs) = BinHelper::transfer( - collected_protocol_fees, - token_x.clone(), - token_y.clone(), - state.protocol_fees_recipient, - ) { - messages.extend(msgs); - }; + // if let Some(msgs) = BinHelper::transfer( + // collected_protocol_fees, + // token_x.clone(), + // token_y.clone(), + // state.protocol_fees_recipient, + // ) { + // messages.extend(msgs); + // }; } Ok(Response::default() diff --git a/contracts/liquidity_book/lb_pair/src/helper.rs b/contracts/liquidity_book/lb_pair/src/helper.rs index e16d6be1..88e0adcb 100644 --- a/contracts/liquidity_book/lb_pair/src/helper.rs +++ b/contracts/liquidity_book/lb_pair/src/helper.rs @@ -1,17 +1,15 @@ use crate::prelude::*; use ethnum::U256; +use lb_libraries::math::{tree_math::TreeUint24, u24::U24, uint256_to_u256::ConvertUint256}; use shade_protocol::{ - c_std::{Addr, ContractInfo, CosmosMsg, Deps, Env, StdResult}, - contract_interfaces::{ - liquidity_book::{lb_pair::*, lb_token}, - swap::core::TokenType, - }, - lb_libraries::{ - math::{tree_math::TreeUint24, u24::U24, uint256_to_u256::ConvertUint256}, - viewing_keys::{register_receive, set_viewing_key_msg, ViewingKey}, - }, + c_std::{Addr, CosmosMsg, Deps, Env, StdResult}, + contract_interfaces::liquidity_book::{lb_pair::*, lb_token}, + // TODO: sort out viewing key strategy + s_toolkit::snip20::{register_receive_msg, set_viewing_key_msg}, snip20, + swap::core::{TokenType, ViewingKey}, }; + pub const INSTANTIATE_LP_TOKEN_REPLY_ID: u64 = 1u64; pub const INSTANTIATE_STAKING_CONTRACT_REPLY_ID: u64 = 2u64; pub const MINT_REPLY_ID: u64 = 1u64; @@ -32,20 +30,18 @@ pub fn register_pair_token( } = token { messages.push(set_viewing_key_msg( - viewing_key.0.clone(), + viewing_key.to_string(), None, - &ContractInfo { - address: contract_addr.clone(), - code_hash: token_code_hash.to_string(), - }, + 256, + contract_addr.clone().to_string(), + token_code_hash.to_string(), )?); - messages.push(register_receive( + messages.push(register_receive_msg( env.contract.code_hash.clone(), None, - &ContractInfo { - address: contract_addr.clone(), - code_hash: token_code_hash.to_string(), - }, + 256, + contract_addr.to_string(), + token_code_hash.to_string(), )?); } diff --git a/contracts/liquidity_book/lb_pair/src/lib.rs b/contracts/liquidity_book/lb_pair/src/lib.rs index 3fc1f682..c4c75833 100644 --- a/contracts/liquidity_book/lb_pair/src/lib.rs +++ b/contracts/liquidity_book/lb_pair/src/lib.rs @@ -1,4 +1,5 @@ #![allow(clippy::too_many_arguments)] +#![allow(unused)] mod error; mod prelude; diff --git a/contracts/liquidity_book/lb_pair/src/query.rs b/contracts/liquidity_book/lb_pair/src/query.rs index e91b4604..504b9dd1 100644 --- a/contracts/liquidity_book/lb_pair/src/query.rs +++ b/contracts/liquidity_book/lb_pair/src/query.rs @@ -1,17 +1,22 @@ use crate::{helper::*, prelude::*, state::*}; use ethnum::U256; +use lb_libraries::{ + bin_helper::BinHelper, + constants::SCALE_OFFSET, + fee_helper::FeeHelper, + math::{ + packed_u128_math::PackedUint128Math, + u24::U24, + u256x256_math::U256x256Math, + uint256_to_u256::{ConvertU256, ConvertUint256}, + }, + oracle_helper::MAX_SAMPLE_LIFETIME, + price_helper::PriceHelper, + types::Bytes32, +}; use shade_protocol::{ c_std::{ - from_binary, - to_binary, - Addr, - Binary, - Decimal, - Deps, - Env, - StdResult, - Uint128, - Uint256, + from_binary, to_binary, Addr, Binary, Decimal, Deps, Env, StdResult, Uint128, Uint256, }, contract_interfaces::{ liquidity_book::lb_pair::*, @@ -20,22 +25,8 @@ use shade_protocol::{ FeeInfo, QueryMsgResponse::{GetPairInfo, SwapSimulation}, }, - core::{Fee, TokenPair}, - }, - }, - lb_libraries::{ - bin_helper::BinHelper, - constants::SCALE_OFFSET, - fee_helper::FeeHelper, - math::{ - packed_u128_math::PackedUint128Math, - u24::U24, - u256x256_math::U256x256Math, - uint256_to_u256::{ConvertU256, ConvertUint256}, + core::{Fee, TokenAmount, TokenPair, TokenType}, }, - oracle_helper::MAX_SAMPLE_LIFETIME, - price_helper::PriceHelper, - types::Bytes32, }, Contract, }; @@ -44,48 +35,50 @@ use std::collections::HashSet; // TODO - Revisit if this function is necessary. It seems like something that might belong in the // lb-factory contract. It should at least have it's own interface and not use amm_pair's. pub fn query_pair_info(deps: Deps) -> Result { - let state = STATE.load(deps.storage)?; - - let (reserve_x, reserve_y) = state.reserves.decode(); - - let response = GetPairInfo { - liquidity_token: Contract { - address: state.lb_token.address, - code_hash: state.lb_token.code_hash, - }, - factory: Some(Contract { - address: state.factory.address, - code_hash: state.factory.code_hash, - }), - pair: TokenPair(state.token_x, state.token_y, false), - amount_0: Uint128::from(reserve_x), - amount_1: Uint128::from(reserve_y), - total_liquidity: Uint128::default(), // no global liquidity, liquidity is calculated on per bin basis - contract_version: 1, // TODO set this like const AMM_PAIR_CONTRACT_VERSION: u32 = 1; - fee_info: FeeInfo { - shade_dao_address: Addr::unchecked(""), // TODO set shade dao address - lp_fee: Fee { - // TODO set this - nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, - denom: 1_000_000_000_000_000_000, - }, - shade_dao_fee: Fee { - nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, - denom: 1_000_000_000_000_000_000, - }, - stable_lp_fee: Fee { - nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, - denom: 1_000_000_000_000_000_000, - }, - stable_shade_dao_fee: Fee { - nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, - denom: 1_000_000_000_000_000_000, - }, - }, - stable_info: None, - }; - - to_binary(&response).map_err(Error::CwErr) + unimplemented!() + + // let state = STATE.load(deps.storage)?; + // + // let (reserve_x, reserve_y) = state.reserves.decode(); + // + // let response = GetPairInfo { + // liquidity_token: Contract { + // address: state.lb_token.address, + // code_hash: state.lb_token.code_hash, + // }, + // factory: Some(Contract { + // address: state.factory.address, + // code_hash: state.factory.code_hash, + // }), + // pair: TokenPair(state.token_x, state.token_y, false), + // amount_0: Uint128::from(reserve_x), + // amount_1: Uint128::from(reserve_y), + // total_liquidity: Uint128::default(), // no global liquidity, liquidity is calculated on per bin basis + // contract_version: 1, // TODO set this like const AMM_PAIR_CONTRACT_VERSION: u32 = 1; + // fee_info: FeeInfo { + // shade_dao_address: Addr::unchecked(""), // TODO set shade dao address + // lp_fee: Fee { + // // TODO set this + // nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, + // denom: 1_000_000_000_000_000_000, + // }, + // shade_dao_fee: Fee { + // nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, + // denom: 1_000_000_000_000_000_000, + // }, + // stable_lp_fee: Fee { + // nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, + // denom: 1_000_000_000_000_000_000, + // }, + // stable_shade_dao_fee: Fee { + // nom: state.pair_parameters.get_base_fee(state.bin_step) as u64, + // denom: 1_000_000_000_000_000_000, + // }, + // }, + // stable_info: None, + // }; + // + // to_binary(&response).map_err(Error::CwErr) } // TODO - Revisit if this function is necessary. It seems like something that might belong in the @@ -93,43 +86,45 @@ pub fn query_pair_info(deps: Deps) -> Result { pub fn query_swap_simulation( deps: Deps, env: Env, - offer: shade_protocol::swap::core::TokenAmount, + offer: TokenAmount, _exclude_fee: Option, ) -> Result { - let state = STATE.load(deps.storage)?; - - let mut swap_for_y = false; - match offer.token { - token if token == state.token_x => swap_for_y = true, - token if token == state.token_y => {} - _ => panic!("No such token"), - }; - - let res = query_swap_out(deps, env, offer.amount.into(), swap_for_y)?; - - let res = from_binary::(&res)?; - - if res.amount_in_left.u128() > 0u128 { - return Err(Error::AmountInLeft { - amount_left_in: res.amount_in_left, - total_amount: offer.amount, - swapped_amount: res.amount_out, - }); - } - - let price = Decimal::from_ratio(res.amount_out, offer.amount).to_string(); - - let response = SwapSimulation { - total_fee_amount: res.total_fees, - lp_fee_amount: res.lp_fees, //TODO lpfee - shade_dao_fee_amount: res.shade_dao_fees, // dao fee - result: SwapResult { - return_amount: res.amount_out, - }, - price, - }; - - to_binary(&response).map_err(Error::CwErr) + unimplemented!() + + // let state = STATE.load(deps.storage)?; + // + // let mut swap_for_y = false; + // match offer.token { + // token if token == state.token_x => swap_for_y = true, + // token if token == state.token_y => {} + // _ => panic!("No such token"), + // }; + // + // let res = query_swap_out(deps, env, offer.amount.into(), swap_for_y)?; + // + // let res = from_binary::(&res)?; + // + // if res.amount_in_left.u128() > 0u128 { + // return Err(Error::AmountInLeft { + // amount_left_in: res.amount_in_left, + // total_amount: offer.amount, + // swapped_amount: res.amount_out, + // }); + // } + // + // let price = Decimal::from_ratio(res.amount_out, offer.amount).to_string(); + // + // let response = SwapSimulation { + // total_fee_amount: res.total_fees, + // lp_fee_amount: res.lp_fees, //TODO lpfee + // shade_dao_fee_amount: res.shade_dao_fees, // dao fee + // result: SwapResult { + // return_amount: res.amount_out, + // }, + // price, + // }; + // + // to_binary(&response).map_err(Error::CwErr) } /// Returns the Liquidity Book Factory. diff --git a/contracts/liquidity_book/lb_pair/src/state.rs b/contracts/liquidity_book/lb_pair/src/state.rs index 1f30688f..e50d3b0b 100644 --- a/contracts/liquidity_book/lb_pair/src/state.rs +++ b/contracts/liquidity_book/lb_pair/src/state.rs @@ -1,13 +1,14 @@ +use lb_libraries::{ + math::tree_math::TreeUint24, + oracle_helper::Oracle, + pair_parameter_helper::PairParameters, + types::{Bytes32, ContractImplementation}, +}; +// TODO: sort out viewing key strategy +use shade_protocol::swap::core::ViewingKey; use shade_protocol::{ c_std::{Addr, ContractInfo, Timestamp, Uint128, Uint256}, cosmwasm_schema::cw_serde, - lb_libraries::{ - math::tree_math::TreeUint24, - oracle_helper::Oracle, - pair_parameter_helper::PairParameters, - types::{Bytes32, ContractInstantiationInfo}, - viewing_keys::ViewingKey, - }, liquidity_book::lb_pair::{ContractStatus, RewardsDistribution, RewardsDistributionAlgorithm}, secret_storage_plus::{AppendStore, Bincode2, Item, Map}, swap::core::TokenType, @@ -27,8 +28,7 @@ pub const REWARDS_STATS_STORE: Map = Map::new("re pub const REWARDS_DISTRIBUTION: Map = Map::new("rewards_distribution"); pub const FEE_MAP_TREE: Map = Map::new("fee_tree"); pub const FEE_MAP: Map = Map::new("fee_map"); -pub const STAKING_CONTRACT_IMPL: Item = - Item::new("staking_contract_impl"); +pub const STAKING_CONTRACT_IMPL: Item = Item::new("staking_contract_impl"); pub const BIN_RESERVES_UPDATED: Map> = Map::new("bins_reserves_updated"); pub const BIN_RESERVES_UPDATED_LOG: AppendStore = AppendStore::new("bins_reserves_updated_log"); @@ -85,7 +85,7 @@ pub struct State { pub struct EphemeralStruct { // Contract information pub lb_token_code_hash: String, - pub staking_contract: ContractInstantiationInfo, + pub staking_contract: ContractImplementation, pub query_auth: RawContract, // Token symbols diff --git a/contracts/liquidity_book/lb_staking/Cargo.toml b/contracts/liquidity_book/lb_staking/Cargo.toml index 2867ea78..2d44aa7b 100644 --- a/contracts/liquidity_book/lb_staking/Cargo.toml +++ b/contracts/liquidity_book/lb_staking/Cargo.toml @@ -3,37 +3,29 @@ name = "lb_staking" version = "0.1.0" authors = ["Haseeb Saeed "] edition = "2021" - -exclude = [ - # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] [[example]] name = "schema" -path = "schema/schema.rs" # Adjust the path according to your project structure +path = "schema/schema.rs" [features] default = ["schema"] schema = [] + [dependencies] -shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] } -snafu = { version = "0.7.1" } -schemars = "0.8.16" -serde = { version = "1.0.114", default-features = false, features = [ - "derive", - "alloc" -] } -cosmwasm-schema = "1.5" -serde_json = "1" +shade-protocol = { path = "../../../packages/shade_protocol" } +lb-libraries = { path = "../../../packages/lb_libraries" } +snafu = { version = "0.8.3" } +schemars = "0.8.21" +serde = { version = "1.0.203", default-features = false, features = ["derive", "alloc"] } +cosmwasm-schema = "2.0.3" +serde_json = "1.0.117" [dev-dependencies] diff --git a/contracts/liquidity_book/lb_staking/src/bin/secretcli/example_data.rs b/contracts/liquidity_book/lb_staking/src/bin/secretcli/example_data.rs index d4e8b63c..aafa68e4 100644 --- a/contracts/liquidity_book/lb_staking/src/bin/secretcli/example_data.rs +++ b/contracts/liquidity_book/lb_staking/src/bin/secretcli/example_data.rs @@ -1,14 +1,12 @@ +use lb_libraries::types::{ContractImplementation, StaticFeeParameters}; use serde_json::from_str; use shade_protocol::{ c_std::{to_binary, Addr, ContractInfo, Uint128, Uint256}, - lb_libraries::types::{ - ContractInstantiationInfo, - LBPair, - LBPairInformation, - StaticFeeParameters, - }, liquidity_book::{ - lb_pair::{LiquidityParameters, RemoveLiquidity, RewardsDistribution, TokenPair}, + lb_pair::{ + LBPair, LBPairInformation, LiquidityParameters, RemoveLiquidity, RewardsDistribution, + TokenPair, + }, lb_staking::Auth, lb_token::Snip1155ReceiveMsg, }, @@ -73,9 +71,9 @@ pub trait ExampleData { fn example() -> Self; } -impl ExampleData for ContractInstantiationInfo { +impl ExampleData for ContractImplementation { fn example() -> Self { - ContractInstantiationInfo { + ContractImplementation { id: 1u64, code_hash: "0123456789ABCDEF".to_string(), } diff --git a/contracts/liquidity_book/lb_staking/src/contract.rs b/contracts/liquidity_book/lb_staking/src/contract.rs index 8a818aed..e1aef555 100644 --- a/contracts/liquidity_book/lb_staking/src/contract.rs +++ b/contracts/liquidity_book/lb_staking/src/contract.rs @@ -1,40 +1,21 @@ +use crate::{ + execute::*, + helper::store_empty_reward_set, + query::*, + state::{EPOCH_STORE, EXPIRED_AT_LOGGER, LAST_CLAIMED_EXPIRED_REWARDS_EPOCH_ID, STATE}, +}; use shade_protocol::{ c_std::{ - shd_entry_point, - Addr, - Binary, - Deps, - DepsMut, - Env, - MessageInfo, - Response, - StdError, + shd_entry_point, Addr, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, }, - contract_interfaces::liquidity_book::lb_libraries::viewing_keys::{ - register_receive, - set_viewing_key_msg, - }, liquidity_book::lb_staking::{ - Auth, - AuthPermit, - EpochInfo, - ExecuteMsg, - InstantiateMsg, - QueryMsg, - State, + Auth, AuthPermit, EpochInfo, ExecuteMsg, InstantiateMsg, QueryMsg, State, }, query_auth::helpers::{authenticate_permit, authenticate_vk, PermitAuthentication}, + snip20::helpers::{register_receive, set_viewing_key_msg}, utils::pad_handle_result, - Contract, - BLOCK_SIZE, -}; - -use crate::{ - execute::*, - helper::store_empty_reward_set, - query::*, - state::{EPOCH_STORE, EXPIRED_AT_LOGGER, LAST_CLAIMED_EXPIRED_REWARDS_EPOCH_ID, STATE}, + Contract, BLOCK_SIZE, }; pub const SHADE_STAKING_VIEWING_KEY: &str = "SHADE_STAKING_VIEWING_KEY"; @@ -60,14 +41,18 @@ pub fn instantiate( }; let now = env.block.time.seconds(); - EPOCH_STORE.save(deps.storage, state.epoch_index, &EpochInfo { - rewards_distribution: None, - start_time: now, - end_time: now + state.epoch_durations, - duration: state.epoch_durations, - reward_tokens: None, - expired_at: None, - })?; + EPOCH_STORE.save( + deps.storage, + state.epoch_index, + &EpochInfo { + rewards_distribution: None, + start_time: now, + end_time: now + state.epoch_durations, + duration: state.epoch_durations, + reward_tokens: None, + expired_at: None, + }, + )?; let messages = vec![ register_receive( diff --git a/contracts/liquidity_book/lb_staking/src/execute.rs b/contracts/liquidity_book/lb_staking/src/execute.rs index 2ee41916..be309876 100644 --- a/contracts/liquidity_book/lb_staking/src/execute.rs +++ b/contracts/liquidity_book/lb_staking/src/execute.rs @@ -1,42 +1,27 @@ -use std::{ - collections::HashMap, - ops::{Add, AddAssign, Sub}, - str::FromStr, +use crate::{ + helper::{ + assert_lb_pair, check_if_claimable, finding_total_liquidity, finding_user_liquidity, + register_reward_tokens, require_lb_token, staker_init_checker, TokenKey, + }, + state::{ + store_claim_rewards, store_stake, store_unstake, EPOCH_STORE, EXPIRED_AT_LOGGER, + EXPIRED_AT_LOGGER_MAP, REWARD_TOKENS, REWARD_TOKEN_INFO, STAKERS, STAKERS_BIN_TREE, + STAKERS_LIQUIDITY, STAKERS_LIQUIDITY_SNAPSHOT, STATE, TOTAL_LIQUIDITY, + TOTAL_LIQUIDITY_SNAPSHOT, + }, }; - +use lb_libraries::types::TreeUint24; use shade_protocol::{ - self, admin::helpers::{validate_admin, AdminPermissions}, c_std::{ - from_binary, - Addr, - BankMsg, - Binary, - Coin, - ContractInfo, - CosmosMsg, - DepsMut, - Env, - MessageInfo, - Response, - StdError, - StdResult, - Storage, - Uint128, - Uint256, + from_binary, Addr, BankMsg, Binary, Coin, ContractInfo, CosmosMsg, DepsMut, Env, + MessageInfo, Response, StdError, StdResult, Storage, Uint128, Uint256, }, - lb_libraries::types::TreeUint24, liquidity_book::{ lb_pair::RewardsDistribution, lb_staking::{ - EpochInfo, - InvokeMsg, - Reward, - RewardToken, - RewardTokenInfo, - StakerLiquidity, - StakerLiquiditySnapshot, - State, + EpochInfo, InvokeMsg, Reward, RewardToken, RewardTokenInfo, StakerLiquidity, + StakerLiquiditySnapshot, State, }, lb_token::TransferAction, }, @@ -46,38 +31,12 @@ use shade_protocol::{ }, swap::core::TokenType, utils::{asset::RawContract, pad_handle_result, ExecuteCallback}, - Contract, - BLOCK_SIZE, + Contract, BLOCK_SIZE, }; - -use crate::{ - helper::{ - assert_lb_pair, - check_if_claimable, - finding_total_liquidity, - finding_user_liquidity, - register_reward_tokens, - require_lb_token, - staker_init_checker, - TokenKey, - }, - state::{ - store_claim_rewards, - store_stake, - store_unstake, - EPOCH_STORE, - EXPIRED_AT_LOGGER, - EXPIRED_AT_LOGGER_MAP, - REWARD_TOKENS, - REWARD_TOKEN_INFO, - STAKERS, - STAKERS_BIN_TREE, - STAKERS_LIQUIDITY, - STAKERS_LIQUIDITY_SNAPSHOT, - STATE, - TOTAL_LIQUIDITY, - TOTAL_LIQUIDITY_SNAPSHOT, - }, +use std::{ + collections::HashMap, + ops::{Add, AddAssign, Sub}, + str::FromStr, }; pub const SHADE_STAKING_VIEWING_KEY: &str = "SHADE_STAKING_VIEWING_KEY"; @@ -549,14 +508,18 @@ pub fn try_end_epoch( if env.block.time.seconds() >= prev_epoch_obj.end_time { if !EPOCH_STORE.has(deps.storage, epoch_index.add(1)) { - EPOCH_STORE.save(deps.storage, epoch_index.add(1), &EpochInfo { - rewards_distribution: None, - start_time: prev_epoch_obj.end_time, - end_time: prev_epoch_obj.end_time + state.epoch_durations, - duration: state.epoch_durations, - reward_tokens: None, - expired_at: None, - })?; + EPOCH_STORE.save( + deps.storage, + epoch_index.add(1), + &EpochInfo { + rewards_distribution: None, + start_time: prev_epoch_obj.end_time, + end_time: prev_epoch_obj.end_time + state.epoch_durations, + duration: state.epoch_durations, + reward_tokens: None, + expired_at: None, + }, + )?; state.epoch_index.add_assign(1); @@ -881,10 +844,13 @@ pub fn try_add_rewards( return Err(StdError::generic_err("Cannot start emitting in the past")); } - let decimals = token_info(&deps.querier, &Contract { - address: token.address.clone(), - code_hash: token.code_hash.clone(), - })? + let decimals = token_info( + &deps.querier, + &Contract { + address: token.address.clone(), + code_hash: token.code_hash.clone(), + }, + )? .decimals; let total_epoches = end.sub(start) + 1; diff --git a/contracts/liquidity_book/lb_staking/src/state.rs b/contracts/liquidity_book/lb_staking/src/state.rs index da790f22..8ee5596e 100644 --- a/contracts/liquidity_book/lb_staking/src/state.rs +++ b/contracts/liquidity_book/lb_staking/src/state.rs @@ -1,18 +1,9 @@ +use lb_libraries::types::TreeUint24; use shade_protocol::{ c_std::{Addr, ContractInfo, StdResult, Storage, Uint256}, - lb_libraries::types::TreeUint24, liquidity_book::lb_staking::{ - EpochInfo, - Reward, - RewardTokenInfo, - StakerInfo, - StakerLiquidity, - StakerLiquiditySnapshot, - State, - TotalLiquidity, - TotalLiquiditySnapshot, - Tx, - TxAction, + EpochInfo, Reward, RewardTokenInfo, StakerInfo, StakerLiquidity, StakerLiquiditySnapshot, + State, TotalLiquidity, TotalLiquiditySnapshot, Tx, TxAction, }, s_toolkit::storage::AppendStore, secret_storage_plus::{Bincode2, Item, Map}, diff --git a/contracts/liquidity_book/lb_token/Cargo.toml b/contracts/liquidity_book/lb_token/Cargo.toml index 54f48ec8..a2fd18b9 100644 --- a/contracts/liquidity_book/lb_token/Cargo.toml +++ b/contracts/liquidity_book/lb_token/Cargo.toml @@ -1,22 +1,16 @@ [package] name = "lb_token" version = "0.1.0" -authors = ["DDT5","itsHaseebSaeed"] +authors = ["DDT5", "itsHaseebSaeed"] edition = "2021" - -exclude = [ - # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] + [[example]] name = "schema" -path = "schema/schema.rs" # Adjust the path according to your project structure +path = "schema/schema.rs" [features] @@ -26,19 +20,22 @@ schema = [] # for more explicit tests, cargo test --features=backtraces backtraces = ["cosmwasm-std/backtraces"] + [dependencies] -#snafu = { version = "0.6.3" } +shade-protocol = { path = "../../../packages/shade_protocol" } +lb-libraries = { path = "../../../packages/lb_libraries" } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "=1.1.11" } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "=1.1.11" } serde = { version = "1.0.158", default-features = false, features = ["derive"] } schemars = "0.8.12" -cosmwasm-std = { package = "secret-cosmwasm-std", version = "=1.1.11" } -cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "=1.1.11"} -shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] } +#snafu = { version = "0.6.3" } #base64 = "0.21.2" #rand = { version = "0.8.5", default-features = false } #getrandom = { version = "0.2.10", features = ["js"] } # nope + [dev-dependencies] -cosmwasm-schema = "1.1.8" -serde_json = "1.0.8" +cosmwasm-schema = "2.0.3" +serde_json = "1.0.117" secret-toolkit = { version = "0.10.0", default-features = false, features = ["crypto"] } diff --git a/contracts/liquidity_book/lb_token/src/contract.rs b/contracts/liquidity_book/lb_token/src/contract.rs index 82a7e455..0fa27956 100644 --- a/contracts/liquidity_book/lb_token/src/contract.rs +++ b/contracts/liquidity_book/lb_token/src/contract.rs @@ -1,24 +1,10 @@ -// use base64::{engine::general_purpose, Engine as _}; +use crate::state::{blockinfo_w, contr_conf_r, contr_conf_w, PREFIX_REVOKED_PERMITS}; +use crate::{execute::*, query::*}; use cosmwasm_std::{ - entry_point, - // debug_print, - to_binary, - Binary, - Deps, - DepsMut, - Env, - MessageInfo, - Response, - StdError, - StdResult, + entry_point, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, }; - -use crate::{execute::*, query::*}; - -use crate::state::{blockinfo_w, contr_conf_r, contr_conf_w, PREFIX_REVOKED_PERMITS}; - +use lb_libraries::lb_token::state_structs::ContractConfig; use shade_protocol::{ - lb_libraries::lb_token::state_structs::ContractConfig, liquidity_book::lb_token::{ExecuteMsg, InstantiateMsg, SendAction}, s_toolkit::{ crypto::sha_256, @@ -26,6 +12,7 @@ use shade_protocol::{ viewing_key::{ViewingKey, ViewingKeyStore}, }, }; + ///////////////////////////////////////////////////////////////////////////////// // Init ///////////////////////////////////////////////////////////////////////////////// @@ -147,15 +134,20 @@ pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> S msg, memo, padding: _, - } => try_send(deps, env, info, SendAction { - token_id, - from, - recipient, - recipient_code_hash, - amount, - msg, - memo, - }), + } => try_send( + deps, + env, + info, + SendAction { + token_id, + from, + recipient, + recipient_code_hash, + amount, + msg, + memo, + }, + ), ExecuteMsg::BatchSend { actions, padding: _, diff --git a/contracts/liquidity_book/lb_token/src/execute.rs b/contracts/liquidity_book/lb_token/src/execute.rs index 23c41edb..ac6a865d 100755 --- a/contracts/liquidity_book/lb_token/src/execute.rs +++ b/contracts/liquidity_book/lb_token/src/execute.rs @@ -1,56 +1,25 @@ -// use base64::{engine::general_purpose, Engine as _}; -use cosmwasm_std::{ - to_binary, - Addr, - Binary, - CosmosMsg, - DepsMut, - Env, - MessageInfo, - Response, - StdError, - StdResult, - Storage, - Uint256, -}; - use crate::state::{ - balances_r, - balances_w, - contr_conf_r, - contr_conf_w, - get_receiver_hash, + balances_r, balances_w, contr_conf_r, contr_conf_w, get_receiver_hash, permissions::{may_load_any_permission, new_permission, update_permission}, - set_receiver_hash, - tkn_info_r, - tkn_info_w, - tkn_tot_supply_r, - tkn_tot_supply_w, + set_receiver_hash, tkn_info_r, tkn_info_w, tkn_tot_supply_r, tkn_tot_supply_w, txhistory::{append_new_owner, may_get_current_owner, store_burn, store_mint, store_transfer}, - PREFIX_REVOKED_PERMITS, - RESPONSE_BLOCK_SIZE, + PREFIX_REVOKED_PERMITS, RESPONSE_BLOCK_SIZE, }; - -use shade_protocol::{ - lb_libraries::lb_token::{ - expiration::Expiration, - metadata::Metadata, - permissions::Permission, - state_structs::{ - ContractConfig, - CurateTokenId, - StoredTokenInfo, - TknConfig, - TokenAmount, - TokenInfoMsg, - }, +use cosmwasm_std::{ + to_binary, Addr, Binary, CosmosMsg, DepsMut, Env, MessageInfo, Response, StdError, StdResult, + Storage, Uint256, +}; +use lb_libraries::lb_token::{ + expiration::Expiration, + metadata::Metadata, + permissions::Permission, + state_structs::{ + ContractConfig, CurateTokenId, StoredTokenInfo, TknConfig, TokenAmount, TokenInfoMsg, }, +}; +use shade_protocol::{ liquidity_book::lb_token::{ - ExecuteAnswer, - ResponseStatus::Success, - SendAction, - Snip1155ReceiveMsg, - TransferAction, + ExecuteAnswer, ResponseStatus::Success, SendAction, Snip1155ReceiveMsg, TransferAction, }, s_toolkit::{ permit::RevokedPermits, @@ -58,6 +27,7 @@ use shade_protocol::{ viewing_key::{ViewingKey, ViewingKeyStore}, }, }; + ///////////////////////////////////////////////////////////////////////////////// // Init ///////////////////////////////////////////////////////////////////////////////// diff --git a/contracts/liquidity_book/lb_token/src/query.rs b/contracts/liquidity_book/lb_token/src/query.rs index fb3fbb07..1cd92a82 100755 --- a/contracts/liquidity_book/lb_token/src/query.rs +++ b/contracts/liquidity_book/lb_token/src/query.rs @@ -1,39 +1,23 @@ -use std::collections::BTreeSet; - -use cosmwasm_std::{ - to_binary, - Addr, - Binary, - BlockInfo, - Deps, - // debug_print, - StdError, - StdResult, - Timestamp, - Uint256, -}; - use crate::state::{ - balances_r, - blockinfo_r, - contr_conf_r, - get_receiver_hash, + balances_r, blockinfo_r, contr_conf_r, get_receiver_hash, permissions::{list_owner_permission_keys, may_load_any_permission}, - tkn_info_r, - tkn_tot_supply_r, + tkn_info_r, tkn_tot_supply_r, txhistory::{get_txs, may_get_current_owner}, }; - -use shade_protocol::{ - lb_libraries::lb_token::{ - permissions::{Permission, PermissionKey}, - state_structs::OwnerBalance, - }, - liquidity_book::lb_token::QueryAnswer, +use cosmwasm_std::{ + to_binary, Addr, Binary, BlockInfo, Deps, StdError, StdResult, Timestamp, Uint256, +}; +use lb_libraries::lb_token::{ + permissions::{Permission, PermissionKey}, + state_structs::OwnerBalance, }; +use shade_protocol::liquidity_book::lb_token::QueryAnswer; +use std::collections::BTreeSet; + ///////////////////////////////////////////////////////////////////////////////// // Queries ///////////////////////////////////////////////////////////////////////////////// + pub fn query_contract_info(deps: Deps) -> StdResult { let contr_conf = contr_conf_r(deps.storage).load()?; let response = QueryAnswer::TokenContractInfo { diff --git a/contracts/liquidity_book/lb_token/src/state/mod.rs b/contracts/liquidity_book/lb_token/src/state/mod.rs index 27bf5626..82d0aec2 100755 --- a/contracts/liquidity_book/lb_token/src/state/mod.rs +++ b/contracts/liquidity_book/lb_token/src/state/mod.rs @@ -5,19 +5,11 @@ pub mod txhistory; use cosmwasm_std::{to_binary, Addr, BlockInfo, StdError, StdResult, Storage, Uint256}; use cosmwasm_storage::{ - bucket, - bucket_read, - singleton, - singleton_read, - Bucket, - PrefixedStorage, - ReadonlyBucket, - ReadonlyPrefixedStorage, - ReadonlySingleton, - Singleton, + bucket, bucket_read, singleton, singleton_read, Bucket, PrefixedStorage, ReadonlyBucket, + ReadonlyPrefixedStorage, ReadonlySingleton, Singleton, }; -use shade_protocol::lb_libraries::lb_token::{ +use lb_libraries::lb_token::{ permissions::Permission, state_structs::{ContractConfig, StoredTokenInfo}, }; @@ -114,11 +106,14 @@ fn permission_w<'a>( token_id: &'a str, ) -> Bucket<'a, Permission> { let owner_bin = to_binary(owner).unwrap(); - Bucket::multilevel(storage, &[ - PREFIX_PERMISSIONS, - owner_bin.as_slice(), - token_id.as_bytes(), - ]) + Bucket::multilevel( + storage, + &[ + PREFIX_PERMISSIONS, + owner_bin.as_slice(), + token_id.as_bytes(), + ], + ) } /// private functions. /// To read permission. key is to be [`owner`, `token_id`, `allowed_addr`] @@ -129,11 +124,14 @@ fn permission_r<'a>( token_id: &'a str, ) -> ReadonlyBucket<'a, Permission> { let owner_bin = to_binary(owner).unwrap(); - ReadonlyBucket::multilevel(storage, &[ - PREFIX_PERMISSIONS, - owner_bin.as_slice(), - token_id.as_bytes(), - ]) + ReadonlyBucket::multilevel( + storage, + &[ + PREFIX_PERMISSIONS, + owner_bin.as_slice(), + token_id.as_bytes(), + ], + ) } #[cfg(test)] pub fn perm_r<'a>( @@ -142,11 +140,14 @@ pub fn perm_r<'a>( token_id: &'a str, ) -> ReadonlyBucket<'a, Permission> { let owner_bin = to_binary(owner).unwrap(); - ReadonlyBucket::multilevel(storage, &[ - PREFIX_PERMISSIONS, - owner_bin.as_slice(), - token_id.as_bytes(), - ]) + ReadonlyBucket::multilevel( + storage, + &[ + PREFIX_PERMISSIONS, + owner_bin.as_slice(), + token_id.as_bytes(), + ], + ) } ///////////////////////////////////////////////////////////////////////////////// diff --git a/contracts/liquidity_book/lb_token/src/state/permissions.rs b/contracts/liquidity_book/lb_token/src/state/permissions.rs index 4ff31faa..80f08386 100755 --- a/contracts/liquidity_book/lb_token/src/state/permissions.rs +++ b/contracts/liquidity_book/lb_token/src/state/permissions.rs @@ -2,10 +2,8 @@ use super::*; use cosmwasm_std::{to_binary, Addr, StdError, StdResult, Storage}; -use shade_protocol::{ - lb_libraries::lb_token::permissions::PermissionKey, - s_toolkit::storage::AppendStore, -}; +use lb_libraries::lb_token::permissions::PermissionKey; +use shade_protocol::s_toolkit::storage::AppendStore; pub static PERMISSION_ID_STORE: AppendStore = AppendStore::new(PREFIX_PERMISSION_ID); diff --git a/contracts/liquidity_book/lb_token/src/state/txhistory.rs b/contracts/liquidity_book/lb_token/src/state/txhistory.rs index e87aa584..3f1026a4 100755 --- a/contracts/liquidity_book/lb_token/src/state/txhistory.rs +++ b/contracts/liquidity_book/lb_token/src/state/txhistory.rs @@ -4,10 +4,8 @@ use cosmwasm_std::{Addr, Api, BlockInfo, CanonicalAddr, StdResult, Storage, Uint use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; -use shade_protocol::{ - lb_libraries::lb_token::txhistory::{StoredTx, StoredTxAction, Tx}, - s_toolkit::storage::AppendStore, -}; +use lb_libraries::lb_token::txhistory::{StoredTx, StoredTxAction, Tx}; +use shade_protocol::s_toolkit::storage::AppendStore; use crate::state::save_load_functions::{json_load, json_save}; diff --git a/contracts/liquidity_book/lb_token/src/unittest/handletests.rs b/contracts/liquidity_book/lb_token/src/unittest/handletests.rs index ec02360f..64342a79 100755 --- a/contracts/liquidity_book/lb_token/src/unittest/handletests.rs +++ b/contracts/liquidity_book/lb_token/src/unittest/handletests.rs @@ -1,16 +1,10 @@ -use crate::contract::{execute, instantiate, query}; - -use super::testhelpers::*; - use super::super::state::*; - -use shade_protocol::{ - lb_libraries::lb_token::{expiration::*, permissions::*, state_structs::*}, - liquidity_book::lb_token::{ReceiverHandleMsg, Snip1155ReceiveMsg, *}, -}; - +use super::testhelpers::*; +use crate::contract::{execute, instantiate, query}; use cosmwasm_std::{from_binary, testing::*, to_binary, Addr, Response, StdResult, Uint256}; +use lb_libraries::lb_token::{expiration::*, permissions::*, state_structs::*}; use secret_toolkit::{crypto::sha_256, permit::RevokedPermits}; +use shade_protocol::liquidity_book::lb_token::{ReceiverHandleMsg, Snip1155ReceiveMsg, *}; ///////////////////////////////////////////////////////////////////////////////// // Tests @@ -868,10 +862,8 @@ fn test_transfer() -> StdResult<()> { // cannot transfer if not owner info.sender = addr2.clone(); let result = execute(deps.as_mut(), mock_env(), info.clone(), msg); - assert!( - extract_error_msg(&result) - .contains("These tokens do not exist or you have no permission to transfer") - ); + assert!(extract_error_msg(&result) + .contains("These tokens do not exist or you have no permission to transfer")); // transfer NFT "tkn2"; amount != 1 info.sender = addr2.clone(); @@ -1124,10 +1116,8 @@ fn test_batch_transfer_and_send_errors() -> StdResult<()> { }; let info = mock_info("addr0", &[]); let result = execute(deps.as_mut(), mock_env(), info, msg_batch_trans); - assert!( - extract_error_msg(&result) - .contains("These tokens do not exist or you have no permission to transfer") - ); + assert!(extract_error_msg(&result) + .contains("These tokens do not exist or you have no permission to transfer")); Ok(()) } @@ -1165,10 +1155,8 @@ fn test_transfer_permissions_fungible() -> StdResult<()> { padding: None, }; let mut result = execute(deps.as_mut(), mock_env(), info.clone(), msg_trnsf_0.clone()); - assert!( - extract_error_msg(&result) - .contains("These tokens do not exist or you have no permission to transfer") - ); + assert!(extract_error_msg(&result) + .contains("These tokens do not exist or you have no permission to transfer")); // cannot transfer with insufficient allowance info.sender = addr0.clone(); @@ -1328,10 +1316,8 @@ fn test_transfer_permissions_nft() -> StdResult<()> { info.clone(), msg1_trnsf_0.clone(), ); - assert!( - extract_error_msg(&result) - .contains("These tokens do not exist or you have no permission to transfer") - ); + assert!(extract_error_msg(&result) + .contains("These tokens do not exist or you have no permission to transfer")); assert_eq!( chk_bal(&deps.storage, "2", &addr2).unwrap(), Uint256::from(1u128) @@ -1442,10 +1428,8 @@ fn test_transfer_permissions_nft() -> StdResult<()> { padding: None, }; result = execute(deps.as_mut(), mock_env(), info, msg); - assert!( - extract_error_msg(&result) - .contains("These tokens do not exist or you have no permission to transfer") - ); + assert!(extract_error_msg(&result) + .contains("These tokens do not exist or you have no permission to transfer")); assert_eq!(chk_bal(&deps.storage, "2a", &addr1), None); assert_eq!( chk_bal(&deps.storage, "2a", &addr0).unwrap(), @@ -1478,18 +1462,23 @@ fn test_revoke_permission_sanity() -> StdResult<()> { let mut info = mock_info("addr0", &[]); execute(deps.as_mut(), mock_env(), info.clone(), msg0_perm_b)?; - let vks = generate_viewing_keys(&mut deps, mock_env(), info.clone(), vec![ - addr.a(), - addr.b(), - ])?; + let vks = generate_viewing_keys( + &mut deps, + mock_env(), + info.clone(), + vec![addr.a(), addr.b()], + )?; - let q_answer = - from_binary::(&query(deps.as_ref(), mock_env(), QueryMsg::Permission { + let q_answer = from_binary::(&query( + deps.as_ref(), + mock_env(), + QueryMsg::Permission { owner: addr.a(), allowed_address: addr.b(), key: vks.a(), token_id: "0".to_string(), - })?)?; + }, + )?)?; match q_answer { QueryAnswer::Permission(perm) => { assert_eq!(perm.unwrap().trfer_allowance_perm, Uint256::from(10u128)) @@ -1506,13 +1495,16 @@ fn test_revoke_permission_sanity() -> StdResult<()> { }; info.sender = addr.b(); execute(deps.as_mut(), mock_env(), info, msg_revoke)?; - let q_answer = - from_binary::(&query(deps.as_ref(), mock_env(), QueryMsg::Permission { + let q_answer = from_binary::(&query( + deps.as_ref(), + mock_env(), + QueryMsg::Permission { owner: addr.a(), allowed_address: addr.b(), key: vks.a(), token_id: "0".to_string(), - })?)?; + }, + )?)?; match q_answer { QueryAnswer::Permission(perm) => { assert_eq!(perm.unwrap().trfer_allowance_perm, Uint256::from(0u128)) diff --git a/contracts/liquidity_book/lb_token/src/unittest/querytests.rs b/contracts/liquidity_book/lb_token/src/unittest/querytests.rs index acee0631..9aa027fd 100755 --- a/contracts/liquidity_book/lb_token/src/unittest/querytests.rs +++ b/contracts/liquidity_book/lb_token/src/unittest/querytests.rs @@ -1,16 +1,10 @@ -use core::panic; -use std::ops::Add; - use super::testhelpers::*; - use crate::contract::{execute, query}; - -use shade_protocol::{ - lb_libraries::lb_token::{expiration::*, permissions::*, state_structs::*, txhistory::*}, - liquidity_book::lb_token::*, -}; - +use core::panic; use cosmwasm_std::{from_binary, testing::*, Addr, Response, StdResult, Uint256}; +use lb_libraries::lb_token::{expiration::*, permissions::*, state_structs::*, txhistory::*}; +use shade_protocol::liquidity_book::lb_token::*; +use std::ops::Add; ///////////////////////////////////////////////////////////////////////////////// // Tests @@ -87,11 +81,9 @@ fn test_query_tokenid_public_info_sanity() -> StdResult<()> { total_supply, owner, } => { - assert!( - serde_json::to_string(&token_id_info) - .unwrap() - .contains("\"public_metadata\":{\"token_uri\":\"public uri\"") - ); + assert!(serde_json::to_string(&token_id_info) + .unwrap() + .contains("\"public_metadata\":{\"token_uri\":\"public uri\"")); assert_eq!(token_id_info.private_metadata, None); assert_eq!(token_id_info.curator, addr.a()); assert_eq!(total_supply, Some(Uint256::from(1000u128))); @@ -289,10 +281,12 @@ fn test_query_all_balance() -> StdResult<()> { let mut info = mock_info("addr0", &[]); mint_addtl_default(&mut deps, mock_env(), info.clone())?; - let vks = generate_viewing_keys(&mut deps, mock_env(), info.clone(), vec![ - addr.a(), - addr.b(), - ])?; + let vks = generate_viewing_keys( + &mut deps, + mock_env(), + info.clone(), + vec![addr.a(), addr.b()], + )?; // addr.b cannot query addr.a's AllBalance let msg = QueryMsg::AllBalances { @@ -319,16 +313,19 @@ fn test_query_all_balance() -> StdResult<()> { let q_answer = from_binary::(&query(deps.as_ref(), mock_env(), msg_q_allbal.clone())?)?; match q_answer { - QueryAnswer::AllBalances(i) => assert_eq!(i, vec![ - OwnerBalance { - token_id: "0".to_string(), - amount: Uint256::from(1000u128) - }, - OwnerBalance { - token_id: "0a".to_string(), - amount: Uint256::from(800u128) - }, - ]), + QueryAnswer::AllBalances(i) => assert_eq!( + i, + vec![ + OwnerBalance { + token_id: "0".to_string(), + amount: Uint256::from(1000u128) + }, + OwnerBalance { + token_id: "0a".to_string(), + amount: Uint256::from(800u128) + }, + ] + ), _ => panic!("query error"), } @@ -349,16 +346,19 @@ fn test_query_all_balance() -> StdResult<()> { let q_answer = from_binary::(&query(deps.as_ref(), mock_env(), msg_q_allbal.clone())?)?; match q_answer { - QueryAnswer::AllBalances(i) => assert_eq!(i, vec![ - OwnerBalance { - token_id: "0".to_string(), - amount: Uint256::from(1100u128) - }, - OwnerBalance { - token_id: "0a".to_string(), - amount: Uint256::from(800u128) - }, - ]), + QueryAnswer::AllBalances(i) => assert_eq!( + i, + vec![ + OwnerBalance { + token_id: "0".to_string(), + amount: Uint256::from(1100u128) + }, + OwnerBalance { + token_id: "0a".to_string(), + amount: Uint256::from(800u128) + }, + ] + ), _ => panic!("query error"), } @@ -427,10 +427,12 @@ fn test_query_transaction_history() -> StdResult<()> { // generate vks let mut info = mock_info(addr.a().as_str(), &[]); - let vks = generate_viewing_keys(&mut deps, mock_env(), info.clone(), vec![ - addr.a(), - addr.b(), - ])?; + let vks = generate_viewing_keys( + &mut deps, + mock_env(), + info.clone(), + vec![addr.a(), addr.b()], + )?; // query tx history let msg_tx_hist_a_a = QueryMsg::TransactionHistory { @@ -647,14 +649,17 @@ fn test_query_permission() -> StdResult<()> { let q_result = query(deps.as_ref(), mock_env(), msg_q); let q_answer = from_binary::(&q_result?)?; match q_answer { - QueryAnswer::Permission(perm) => assert_eq!(perm.unwrap_or_default(), Permission { - view_balance_perm: true, - view_balance_exp: Expiration::default(), - view_pr_metadata_perm: false, - view_pr_metadata_exp: Expiration::default(), - trfer_allowance_perm: Uint256::from(10u128), - trfer_allowance_exp: Expiration::default(), - }), + QueryAnswer::Permission(perm) => assert_eq!( + perm.unwrap_or_default(), + Permission { + view_balance_perm: true, + view_balance_exp: Expiration::default(), + view_pr_metadata_perm: false, + view_pr_metadata_exp: Expiration::default(), + trfer_allowance_perm: Uint256::from(10u128), + trfer_allowance_exp: Expiration::default(), + } + ), _ => panic!("query error"), } @@ -676,14 +681,17 @@ fn test_query_permission() -> StdResult<()> { let q_result = query(deps.as_ref(), mock_env(), msg_q2); let q_answer = from_binary::(&q_result?)?; match q_answer { - QueryAnswer::Permission(perm) => assert_eq!(perm.unwrap_or_default(), Permission { - view_balance_perm: true, - view_balance_exp: Expiration::default(), - view_pr_metadata_perm: false, - view_pr_metadata_exp: Expiration::default(), - trfer_allowance_perm: Uint256::from(10u128), - trfer_allowance_exp: Expiration::default(), - }), + QueryAnswer::Permission(perm) => assert_eq!( + perm.unwrap_or_default(), + Permission { + view_balance_perm: true, + view_balance_exp: Expiration::default(), + view_pr_metadata_perm: false, + view_pr_metadata_exp: Expiration::default(), + trfer_allowance_perm: Uint256::from(10u128), + trfer_allowance_exp: Expiration::default(), + } + ), _ => panic!("query error"), } @@ -876,16 +884,12 @@ fn test_query_tokenid_private_info_sanity() -> StdResult<()> { total_supply, owner, } => { - assert!( - serde_json::to_string(&token_id_info) - .unwrap() - .contains("\"public_metadata\":{\"token_uri\":\"public uri\"") - ); - assert!( - serde_json::to_string(&token_id_info) - .unwrap() - .contains("\"private_metadata\":{\"token_uri\":\"private uri\"") - ); + assert!(serde_json::to_string(&token_id_info) + .unwrap() + .contains("\"public_metadata\":{\"token_uri\":\"public uri\"")); + assert!(serde_json::to_string(&token_id_info) + .unwrap() + .contains("\"private_metadata\":{\"token_uri\":\"private uri\"")); assert_eq!(token_id_info.curator, addr.a()); assert_eq!(total_supply, Some(Uint256::from(1000u128))); assert!(owner.is_none()); diff --git a/contracts/liquidity_book/lb_token/src/unittest/testhelpers.rs b/contracts/liquidity_book/lb_token/src/unittest/testhelpers.rs index 33d50ea6..282e36d3 100755 --- a/contracts/liquidity_book/lb_token/src/unittest/testhelpers.rs +++ b/contracts/liquidity_book/lb_token/src/unittest/testhelpers.rs @@ -1,30 +1,20 @@ -use cosmwasm_storage::ReadonlyPrefixedStorage; -use secret_toolkit::viewing_key::{ViewingKey, ViewingKeyStore}; -use serde::de::DeserializeOwned; -use shade_protocol::lb_libraries::lb_token::metadata::{Extension, Metadata}; -use std::any::Any; - use crate::{ contract::{execute, instantiate}, state::balances_r, }; use cosmwasm_std::{ - from_binary, - testing::*, - to_binary, - Addr, - CosmosMsg, - Env, - MessageInfo, - OwnedDeps, - Response, - StdError, - StdResult, - Storage, - Uint256, - WasmMsg, + from_binary, testing::*, to_binary, Addr, CosmosMsg, Env, MessageInfo, OwnedDeps, Response, + StdError, StdResult, Storage, Uint256, WasmMsg, }; -use shade_protocol::{lb_libraries::lb_token::state_structs::*, liquidity_book::lb_token::*}; +use cosmwasm_storage::ReadonlyPrefixedStorage; +use lb_libraries::lb_token::{ + metadata::{Extension, Metadata}, + state_structs::*, +}; +use secret_toolkit::viewing_key::{ViewingKey, ViewingKeyStore}; +use serde::de::DeserializeOwned; +use shade_protocol::liquidity_book::lb_token::*; +use std::any::Any; pub fn default_curate_value() -> CurateTokenId { CurateTokenId { diff --git a/contracts/liquidity_book/router/Cargo.toml b/contracts/liquidity_book/router/Cargo.toml index 3b3e5a6c..f007c471 100644 --- a/contracts/liquidity_book/router/Cargo.toml +++ b/contracts/liquidity_book/router/Cargo.toml @@ -3,37 +3,31 @@ name = "router" version = "0.1.0" authors = ["Tony "] edition = "2021" - -exclude = [ - # Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] [[example]] name = "schema" -path = "schema/schema.rs" # Adjust the path according to your project structure +path = "schema/schema.rs" [features] default = ["schema"] schema = [] + + [dependencies] -shade-protocol = { version = "0.1.0", path = "../../../packages/shade_protocol", features = ["liquidity_book_impl"] } -snafu = { version = "0.7.1" } -schemars = "0.8.16" -serde = { version = "1.0.114", default-features = false, features = [ - "derive", - "alloc" -] } -cosmwasm-schema = "1.5" +shade-protocol = { path = "../../../packages/shade_protocol" } +lb-libraries = { path = "../../../packages/lb_libraries" } +snafu = { version = "0.8.3" } +schemars = "0.8.21" +serde = { version = "1.0.203", default-features = false, features = ["derive", "alloc"] } +cosmwasm-schema = "2.0.3" serde_json = "1" + [dev-dependencies] secret-multi-test = { git = "https://github.com/securesecrets/secret-plus-utils", version = "0.13.4" } serial_test = "2.0.0" diff --git a/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs b/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs index e495b216..a20e2f91 100644 --- a/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs +++ b/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs @@ -1,15 +1,8 @@ +use lb_libraries::types::{ContractImplementation, StaticFeeParameters}; use shade_protocol::{ c_std::{to_binary, Addr, ContractInfo, Uint128, Uint256}, - lb_libraries::types::{ - ContractInstantiationInfo, - LBPair, - LBPairInformation, - StaticFeeParameters, - }, liquidity_book::lb_pair::{ - LiquidityParameters, - RemoveLiquidity, - RewardsDistribution, + LBPair, LBPairInformation, LiquidityParameters, RemoveLiquidity, RewardsDistribution, TokenPair, }, snip20::Snip20ReceiveMsg, @@ -66,9 +59,9 @@ pub trait ExampleData { fn example() -> Self; } -impl ExampleData for ContractInstantiationInfo { +impl ExampleData for ContractImplementation { fn example() -> Self { - ContractInstantiationInfo { + ContractImplementation { id: 1u64, code_hash: "0123456789ABCDEF".to_string(), } diff --git a/contracts/liquidity_book/router/src/bin/secretcli/main.rs b/contracts/liquidity_book/router/src/bin/secretcli/main.rs index da4cc4ba..835d9b87 100644 --- a/contracts/liquidity_book/router/src/bin/secretcli/main.rs +++ b/contracts/liquidity_book/router/src/bin/secretcli/main.rs @@ -1,9 +1,9 @@ mod example_data; use example_data::*; +use lb_libraries::pair_parameter_helper::PairParameters; use shade_protocol::{ c_std::{Addr, Binary, ContractInfo, Uint128}, - lb_libraries::pair_parameter_helper::PairParameters, liquidity_book::lb_pair::{InvokeMsg, SwapResult}, swap::{ core::{TokenAmount, TokenType}, diff --git a/contracts/liquidity_book/tests/Cargo.toml b/contracts/liquidity_book/tests/Cargo.toml index e6688c6f..42dcac38 100644 --- a/contracts/liquidity_book/tests/Cargo.toml +++ b/contracts/liquidity_book/tests/Cargo.toml @@ -2,11 +2,7 @@ name = "lb_tests" version = "0.1.0" edition = "2021" -exclude = [ - # Those files are contract-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication. - "contract.wasm", - "hash.txt", -] +exclude = ["contract.wasm", "hash.txt"] [lib] crate-type = ["cdylib", "rlib"] @@ -17,19 +13,22 @@ default = [] # 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","liquidity_book"] } -schemars = "0.8.16" -serde = { version = "1.0" } -serde-json-wasm = { version = "1.0"} -ethnum = { version = "1.5" } -thiserror = { version = "1.0" } +shade-protocol = { path = "../../../packages/shade_protocol", features = ["liquidity_book"] } +lb-libraries = { path = "../../../packages/lb_libraries" } +schemars = "0.8.21" +serde = { version = "1.0.203" } +serde-json-wasm = { version = "1.0.1" } +ethnum = { version = "1.5.0" } +thiserror = { version = "1.0.61" } + [dev-dependencies] -anyhow = "1" +anyhow = "1.0.86" cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.1.11" } -rand = "0.8" -shade-multi-test = { path = "../../../packages/multi_test", features = [ +rand = "0.8.5" +shade-multi-test = { path = "../../../packages/multi_test", features = [ "admin", "lb_pair", "lb_token", @@ -37,8 +36,7 @@ shade-multi-test = { path = "../../../packages/multi_test", features = [ "snip20", "router", "lb_factory", - "query_auth", - + "query_auth", ] } -lb_pair ={ path = "../lb_pair"} +lb_pair = { path = "../lb_pair" } serial_test = "2.0.0" diff --git a/contracts/liquidity_book/tests/src/multitests/lb_factory.rs b/contracts/liquidity_book/tests/src/multitests/lb_factory.rs index 30927c29..fef12e91 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_factory.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_factory.rs @@ -1,4 +1,9 @@ +use crate::multitests::test_helper::*; use anyhow::Ok; +use lb_libraries::math::{ + encoded_sample::{MASK_UINT12, MASK_UINT20}, + u24::U24, +}; use serial_test::serial; use shade_multi_test::{ interfaces::{lb_factory, lb_pair, snip20}, @@ -9,17 +14,11 @@ use shade_protocol::{ ContractInfo, StdError::{self, GenericErr}, }, - lb_libraries::math::{ - encoded_sample::{MASK_UINT12, MASK_UINT20}, - u24::U24, - }, liquidity_book::{lb_factory::PresetResponse, lb_pair::RewardsDistributionAlgorithm}, swap::core::TokenType, utils::MultiTestable, }; -use crate::multitests::test_helper::*; - #[test] #[serial] pub fn test_setup() -> Result<(), anyhow::Error> { diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_fees.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_fees.rs index 39a6fc6f..f1b4bb3c 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_fees.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_fees.rs @@ -1,29 +1,17 @@ -use crate::multitests::{lb_pair_liquidity::PRECISION, test_helper::*}; - use super::test_helper::{ - increase_allowance_helper, - init_addrs, - liquidity_parameters_generator, - mint_token_helper, - setup, - ID_ONE, + increase_allowance_helper, init_addrs, liquidity_parameters_generator, mint_token_helper, + setup, ID_ONE, }; +use crate::multitests::{lb_pair_liquidity::PRECISION, test_helper::*}; use anyhow::Ok; +use lb_libraries::math::{encoded_sample::MASK_UINT20, u24::U24}; use serial_test::serial; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, - lb_token, - snip20, - utils::DeployedContracts, + lb_factory, lb_pair, lb_token, snip20, utils::DeployedContracts, }; use shade_protocol::{ c_std::{ContractInfo, StdError, Uint128, Uint256}, - lb_libraries::{ - math::{encoded_sample::MASK_UINT20, u24::U24}, - types::LBPairInformation, - }, - liquidity_book::lb_pair::RemoveLiquidity, + liquidity_book::lb_pair::{LBPairInformation, RemoveLiquidity}, multi_test::App, }; @@ -2355,7 +2343,7 @@ pub fn test_fuzz_swap_in_x_and_y_btc_silk() -> Result<(), anyhow::Error> { //generate random number // let amount_y_out = Uint128::from(generate_random(1u128, DEPOSIT_AMOUNT - 1)); let amount_y_out = Uint128::from(1 * 1000_000u128); //1000 silk - // get swap_in for y + // get swap_in for y let (amount_x_in, amount_y_out_left, _fee) = lb_pair::query_swap_in(&app, &lb_pair.info.contract, amount_y_out, true)?; assert_eq!(amount_y_out_left, Uint128::zero()); @@ -2407,7 +2395,7 @@ pub fn test_fuzz_swap_in_x_and_y_btc_silk() -> Result<(), anyhow::Error> { //generate random number // let amount_y_out = Uint128::from(generate_random(1u128, DEPOSIT_AMOUNT - 1)); let amount_x_out = Uint128::from(2 * 1000_000u128); //5_000_000 satoshi - // get swap_in for y + // get swap_in for y let (amount_y_in, amount_x_out_left, _fee) = lb_pair::query_swap_in(&app, &lb_pair.info.contract, amount_x_out, false)?; assert_eq!(amount_x_out_left, Uint128::zero()); @@ -2648,7 +2636,7 @@ pub fn test_base_and_variable_fee_only() -> Result<(), anyhow::Error> { //generate random number // let amount_y_out = Uint128::from(generate_random(1u128, amount_x.u128() - 1)); let amount_y_out = Uint128::from(100 * 1000_000u128); //1000 silk - // get swap_in for y + // get swap_in for y let (amount_x_in, amount_y_out_left, _fee) = lb_pair::query_swap_in(&app, &lb_pair.info.contract, amount_y_out, true)?; assert_eq!(amount_y_out_left, Uint128::zero()); diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_initial_state.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_initial_state.rs index 7d7506cd..172d72b2 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_initial_state.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_initial_state.rs @@ -1,16 +1,17 @@ use crate::multitests::test_helper::*; use anyhow::Ok; +use lb_libraries::{math::u24::U24, oracle_helper::MAX_SAMPLE_LIFETIME}; use serial_test::serial; use shade_multi_test::interfaces::{lb_factory, lb_pair, utils::DeployedContracts}; use shade_protocol::{ c_std::{ContractInfo, Uint128, Uint256}, - lb_libraries::{math::u24::U24, oracle_helper::MAX_SAMPLE_LIFETIME, types::LBPairInformation}, + liquidity_book::lb_pair::LBPairInformation, multi_test::App, }; use std::str::FromStr; -pub fn lb_pair_setup() --> Result<(App, ContractInfo, DeployedContracts, LBPairInformation), anyhow::Error> { +pub fn lb_pair_setup( +) -> Result<(App, ContractInfo, DeployedContracts, LBPairInformation), anyhow::Error> { let addrs = init_addrs(); let (mut app, lb_factory, deployed_contracts, _, _) = setup(None, None)?; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_liquidity.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_liquidity.rs index 3cea731c..e57be6fa 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_liquidity.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_liquidity.rs @@ -1,16 +1,12 @@ use anyhow::Ok; +use lb_libraries::math::u24::U24; use serial_test::serial; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, - lb_token, - snip20, - utils::DeployedContracts, + lb_factory, lb_pair, lb_token, snip20, utils::DeployedContracts, }; use shade_protocol::{ c_std::{ContractInfo, StdError, Uint128, Uint256}, - lb_libraries::{math::u24::U24, types::LBPairInformation}, - liquidity_book::lb_pair::RemoveLiquidity, + liquidity_book::lb_pair::{LBPairInformation, RemoveLiquidity}, multi_test::App, }; use std::{ diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_oracle.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_oracle.rs index e2b747a0..52f0cadb 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_oracle.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_oracle.rs @@ -1,26 +1,21 @@ -use std::ops::Sub; - use crate::multitests::test_helper::*; use anyhow::Ok; use cosmwasm_std::{Timestamp, Uint128}; +use lb_libraries::oracle_helper::MAX_SAMPLE_LIFETIME; use serial_test::serial; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, - lb_token, - snip20, - utils::DeployedContracts, + lb_factory, lb_pair, lb_token, snip20, utils::DeployedContracts, }; use shade_protocol::{ - c_std::ContractInfo, - lb_libraries::{oracle_helper::MAX_SAMPLE_LIFETIME, types::LBPairInformation}, - multi_test::App, + c_std::ContractInfo, liquidity_book::lb_pair::LBPairInformation, multi_test::App, }; +use std::ops::Sub; + pub const DEPOSIT_AMOUNT: u128 = 100_000_000u128; pub const ACTIVE_ID: u32 = ID_ONE; -pub fn lb_pair_setup() --> Result<(App, ContractInfo, DeployedContracts, LBPairInformation), anyhow::Error> { +pub fn lb_pair_setup( +) -> Result<(App, ContractInfo, DeployedContracts, LBPairInformation), anyhow::Error> { let addrs = init_addrs(); let (mut app, lb_factory, deployed_contracts, _, _) = setup(None, None)?; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_queries.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_queries.rs index 9a9cb7bc..4dd2cff1 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_queries.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_queries.rs @@ -4,8 +4,7 @@ use serial_test::serial; use shade_multi_test::interfaces::{lb_factory, lb_pair, lb_token, utils::DeployedContracts}; use shade_protocol::{ c_std::{ContractInfo, Uint128, Uint256}, - lb_libraries::types::LBPairInformation, - liquidity_book::lb_pair::RemoveLiquidity, + liquidity_book::lb_pair::{LBPairInformation, RemoveLiquidity}, multi_test::App, utils::cycle::parse_utc_datetime, }; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_rewards.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_rewards.rs index 5034bed1..7cad41ae 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_rewards.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_rewards.rs @@ -1,13 +1,8 @@ -use crate::multitests::test_helper::*; - use super::test_helper::{ - increase_allowance_helper, - init_addrs, - liquidity_parameters_generator, - mint_token_helper, - setup, - ID_ONE, + increase_allowance_helper, init_addrs, liquidity_parameters_generator, mint_token_helper, + setup, ID_ONE, }; +use crate::multitests::test_helper::*; use anyhow::Ok; use shade_multi_test::interfaces::{lb_factory, lb_pair, lb_token}; use shade_protocol::{ @@ -771,12 +766,10 @@ pub fn test_reset_rewards_config() -> Result<(), anyhow::Error> { let _distribution = lb_pair::query_rewards_distribution(&app, &lb_pair.info.contract, None)?; //Eventhough the distribution was changes mid epoch the effects of change will occur after the epoch. - assert!( - _distribution - .weightages - .iter() - .all(|&x| x == _distribution.weightages[0]) - ); + assert!(_distribution + .weightages + .iter() + .all(|&x| x == _distribution.weightages[0])); //making a swap for token y hence the bin id moves to the right let timestamp = Timestamp::from_seconds(app.block_info().time.seconds() + 7); @@ -821,12 +814,10 @@ pub fn test_reset_rewards_config() -> Result<(), anyhow::Error> { let _distribution = lb_pair::query_rewards_distribution(&app, &lb_pair.info.contract, None)?; //Eventhough the distribution was changes mid epoch the effects of change will occur after the epoch. - assert!( - _distribution - .weightages - .iter() - .any(|&x| x != _distribution.weightages[0]) - ); + assert!(_distribution + .weightages + .iter() + .any(|&x| x != _distribution.weightages[0])); // println!("_distribution {:?}", _distribution); diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_swap.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_swap.rs index e24b8fa0..c914821b 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_swap.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_swap.rs @@ -1,25 +1,17 @@ use crate::multitests::test_helper::*; use super::test_helper::{ - increase_allowance_helper, - init_addrs, - liquidity_parameters_generator, - mint_token_helper, - setup, - ID_ONE, + increase_allowance_helper, init_addrs, liquidity_parameters_generator, mint_token_helper, + setup, ID_ONE, }; use anyhow::Ok; use serial_test::serial; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, - lb_token, - snip20, - utils::DeployedContracts, + lb_factory, lb_pair, lb_token, snip20, utils::DeployedContracts, }; use shade_protocol::{ c_std::{ContractInfo, StdError, Uint128}, - lb_libraries::types::LBPairInformation, + liquidity_book::lb_pair::LBPairInformation, multi_test::App, }; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_pair_trivial.rs b/contracts/liquidity_book/tests/src/multitests/lb_pair_trivial.rs index dfd27091..f740131f 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_pair_trivial.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_pair_trivial.rs @@ -1,17 +1,15 @@ +use crate::multitests::test_helper::*; use anyhow::Ok; use cosmwasm_std::Coin; use serial_test::serial; use shade_multi_test::interfaces::{lb_factory, lb_pair, lb_token, utils::DeployedContracts}; use shade_protocol::{ c_std::{ContractInfo, StdError::GenericErr, Uint128}, - lb_libraries::types::LBPairInformation, - liquidity_book::lb_pair::RemoveLiquidity, + liquidity_book::lb_pair::{LBPairInformation, RemoveLiquidity}, multi_test::{App, BankSudo, SudoMsg}, swap::core::{TokenAmount, TokenType}, }; -use crate::multitests::test_helper::*; - pub const ACTIVE_ID: u32 = ID_ONE - 24647; pub const DEPOSIT_AMOUNT: u128 = 1_000_000_000_000; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_router_integration.rs b/contracts/liquidity_book/tests/src/multitests/lb_router_integration.rs index cabe86d2..06993be3 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_router_integration.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_router_integration.rs @@ -1,8 +1,9 @@ +use super::lb_pair_fees::DEPOSIT_AMOUNT; +use crate::multitests::test_helper::*; use anyhow::Ok; use serial_test::serial; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, + lb_factory, lb_pair, router::{self}, snip20, utils::SupportedContracts, @@ -15,9 +16,6 @@ use shade_protocol::{ }, }; -use super::lb_pair_fees::DEPOSIT_AMOUNT; -use crate::multitests::test_helper::*; - const SWAP_AMOUNT: u128 = 1000; #[test] @@ -362,10 +360,14 @@ pub fn router_integration() -> Result<(), anyhow::Error> { app.init_modules(|router, _, storage| { router .bank - .init_balance(storage, &addrs.joker(), vec![Coin { - denom: "uscrt".into(), - amount: amount_x + Uint128::from(SWAP_AMOUNT), - }]) + .init_balance( + storage, + &addrs.joker(), + vec![Coin { + denom: "uscrt".into(), + amount: amount_x + Uint128::from(SWAP_AMOUNT), + }], + ) .unwrap(); }); @@ -388,12 +390,15 @@ pub fn router_integration() -> Result<(), anyhow::Error> { })) .unwrap(); - assert_eq!(res, BalanceResponse { - amount: Coin { - amount: Uint128::new(SWAP_AMOUNT), - denom: "uscrt".to_string(), - }, - }); + assert_eq!( + res, + BalanceResponse { + amount: Coin { + amount: Uint128::new(SWAP_AMOUNT), + denom: "uscrt".to_string(), + }, + } + ); // 25. SWAP a native token for a SNIP20 token and ASSERT the resulting balance of the SNIP20 token. let offer = TokenAmount { @@ -469,12 +474,15 @@ pub fn router_integration() -> Result<(), anyhow::Error> { })) .unwrap(); - assert_eq!(res, BalanceResponse { - amount: Coin { - amount: Uint128::new(SWAP_AMOUNT + 999), - denom: "uscrt".to_string(), - }, - }); + assert_eq!( + res, + BalanceResponse { + amount: Coin { + amount: Uint128::new(SWAP_AMOUNT + 999), + denom: "uscrt".to_string(), + }, + } + ); //Swapping USCRT -> SILK let offer = TokenAmount { @@ -523,12 +531,15 @@ pub fn router_integration() -> Result<(), anyhow::Error> { })) .unwrap(); - assert_eq!(res, BalanceResponse { - amount: Coin { - amount: Uint128::from(999u128), - denom: "uscrt".to_string(), - }, - }); + assert_eq!( + res, + BalanceResponse { + amount: Coin { + amount: Uint128::from(999u128), + denom: "uscrt".to_string(), + }, + } + ); // 20. CREATE another AMM pair between a native token(SSCRT) and a SNIP20 token(SILK) let shade = extract_contract_info(&deployed_contracts, SHADE)?; diff --git a/contracts/liquidity_book/tests/src/multitests/lb_router_register_tokens.rs b/contracts/liquidity_book/tests/src/multitests/lb_router_register_tokens.rs index 79891562..7c125125 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_router_register_tokens.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_router_register_tokens.rs @@ -1,14 +1,11 @@ +use super::test_helper::{init_addrs, setup, SHADE, SILK}; use anyhow::Ok; use serial_test::serial; -use shade_protocol::c_std::Addr; - -use crate::multitests::test_helper::{SHADE, SILK}; - -use super::test_helper::{init_addrs, setup}; use shade_multi_test::interfaces::{ router::{self, query_router_registered_tokens}, utils::SupportedContracts, }; +use shade_protocol::c_std::Addr; #[test] #[serial] diff --git a/contracts/liquidity_book/tests/src/multitests/lb_staking.rs b/contracts/liquidity_book/tests/src/multitests/lb_staking.rs index 72d7995c..b671fe76 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_staking.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_staking.rs @@ -1,27 +1,20 @@ -use std::vec; - +use super::{lb_pair_fees::ACTIVE_ID, test_helper::*}; use anyhow::Ok; -use cosmwasm_std::{StdError, Timestamp, Uint256}; use ethnum::U256; +use lb_libraries::math::uint256_to_u256::ConvertU256; use shade_multi_test::interfaces::{ - lb_factory, - lb_pair, - lb_staking, - lb_token, - snip20, - utils::DeployedContracts, + lb_factory, lb_pair, lb_staking, lb_token, snip20, utils::DeployedContracts, }; use shade_protocol::{ - c_std::{to_binary, ContractInfo, Uint128}, - lb_libraries::{math::uint256_to_u256::ConvertU256, types::LBPairInformation}, + c_std::{to_binary, ContractInfo, StdError, Timestamp, Uint128, Uint256}, liquidity_book::{ + lb_pair::LBPairInformation, lb_staking::{InvokeMsg, QueryTxnType}, lb_token::SendAction, }, multi_test::App, }; - -use super::{lb_pair_fees::ACTIVE_ID, test_helper::*}; +use std::vec; pub const DEPOSIT_AMOUNT: u128 = 1_000_000_000_000_000_000_u128; pub const NB_BINS_X: u32 = 5; @@ -1951,7 +1944,7 @@ pub fn recover_expired_rewards() -> Result<(), anyhow::Error> { lb_staking::claim_rewards(&mut app, addrs.batman().as_str(), &lb_staking)?; roll_time(&mut app, Some(200)); - lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //11 expires at 16 + lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //11 expires at 16 lb_staking::claim_rewards(&mut app, addrs.batman().as_str(), &lb_staking)?; roll_time(&mut app, Some(200)); @@ -1959,11 +1952,11 @@ pub fn recover_expired_rewards() -> Result<(), anyhow::Error> { lb_staking::claim_rewards(&mut app, addrs.batman().as_str(), &lb_staking)?; roll_time(&mut app, Some(200)); - lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //13 expires at 18 + lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //13 expires at 18 lb_staking::claim_rewards(&mut app, addrs.batman().as_str(), &lb_staking)?; roll_time(&mut app, Some(200)); - lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //14 expires at 19 + lb_pair::calculate_rewards(&mut app, addrs.admin().as_str(), &lb_pair.info.contract)?; //14 expires at 19 lb_staking::claim_rewards(&mut app, addrs.batman().as_str(), &lb_staking)?; //current round index -> 20 diff --git a/contracts/liquidity_book/tests/src/multitests/lb_token.rs b/contracts/liquidity_book/tests/src/multitests/lb_token.rs index dfc2e9c3..ccb4822a 100644 --- a/contracts/liquidity_book/tests/src/multitests/lb_token.rs +++ b/contracts/liquidity_book/tests/src/multitests/lb_token.rs @@ -1,32 +1,17 @@ -use serial_test::serial; -use std::ops::{Add, Mul}; - use crate::multitests::test_helper::*; - -use super::test_helper::{ - increase_allowance_helper, - init_addrs, - liquidity_parameters_generator, - mint_token_helper, - setup, - ID_ONE, -}; use anyhow::Ok; use ethnum::U256; +use lb_libraries::{constants::SCALE_OFFSET, math::uint256_to_u256::ConvertU256}; +use serial_test::serial; use shade_multi_test::interfaces::{lb_factory, lb_pair, lb_token, utils::DeployedContracts}; use shade_protocol::{ c_std::{ContractInfo, StdError, Uint128, Uint256}, - lb_libraries::{ - constants::SCALE_OFFSET, - math::uint256_to_u256::ConvertU256, - types::LBPairInformation, - }, - liquidity_book::lb_pair::RemoveLiquidity, + liquidity_book::lb_pair::{LBPairInformation, RemoveLiquidity}, multi_test::App, }; +use std::ops::{Add, Mul}; pub const PRECISION: u128 = 1_000_000_000_000_000_000_u128; - pub const ACTIVE_ID: u32 = ID_ONE - 24647; pub fn init_setup() -> Result< diff --git a/contracts/liquidity_book/tests/src/multitests/test_helper.rs b/contracts/liquidity_book/tests/src/multitests/test_helper.rs index 0dcddd30..cd24d42c 100644 --- a/contracts/liquidity_book/tests/src/multitests/test_helper.rs +++ b/contracts/liquidity_book/tests/src/multitests/test_helper.rs @@ -1,22 +1,18 @@ use cosmwasm_std::to_binary; +use lb_libraries::{constants::PRECISION, math::u24::U24}; use rand::Rng; use shade_multi_test::{ interfaces::{ - lb_factory, - snip20, + lb_factory, snip20, utils::{DeployedContracts, SupportedContracts}, }, multi::{ - admin::init_admin_auth, - lb_pair::LbPair, - lb_staking::LbStaking, - lb_token::LbToken, + admin::init_admin_auth, lb_pair::LbPair, lb_staking::LbStaking, lb_token::LbToken, query_auth::QueryAuth, }, }; use shade_protocol::{ c_std::{Addr, BlockInfo, ContractInfo, StdResult, Timestamp, Uint128, Uint256}, - lb_libraries::{constants::PRECISION, math::u24::U24}, liquidity_book::{ lb_pair::{LiquidityParameters, RewardsDistributionAlgorithm}, lb_staking::Auth, @@ -25,10 +21,7 @@ use shade_protocol::{ query_auth, swap::core::TokenType, utils::{ - asset::Contract, - cycle::parse_utc_datetime, - ExecuteCallback, - InstantiateCallback, + asset::Contract, cycle::parse_utc_datetime, ExecuteCallback, InstantiateCallback, MultiTestable, }, }; @@ -831,9 +824,13 @@ pub fn mint_token_helper( // Adding minters and minting for SSCRT and SHADE for (token, amount) in tokens_to_mint { - snip20::add_minters_exec(app, admin, deployed_contracts, token, vec![ - admin.to_string(), - ])?; + snip20::add_minters_exec( + app, + admin, + deployed_contracts, + token, + vec![admin.to_string()], + )?; snip20::mint_exec( app, admin, diff --git a/packages/lb_libraries/Cargo.toml b/packages/lb_libraries/Cargo.toml new file mode 100644 index 00000000..1b8e2681 --- /dev/null +++ b/packages/lb_libraries/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "lb-libraries" +version = "0.1.0" +authors = ["Kent", "Haseeb Saeed "] +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.1.11" } +cosmwasm-schema = { version = "2.0.3" } +secret-toolkit = { version = "0.10.0", features = ["snip20"] } +schemars = { version = "0.8.21" } +serde = { version = "1.0.203" } +thiserror = { version = "1.0.61" } +ethnum = { version = "1.5.0" } +primitive-types = { version = "0.12.2", default-features = false } diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/bin_helper.rs b/packages/lb_libraries/src/bin_helper.rs similarity index 96% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/bin_helper.rs rename to packages/lb_libraries/src/bin_helper.rs index b203088e..f0c892aa 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/bin_helper.rs +++ b/packages/lb_libraries/src/bin_helper.rs @@ -4,12 +4,6 @@ //! This library contains functions to help interaction with bins. use crate::{ - c_std::{Addr, BankMsg, Coin, CosmosMsg, Uint128}, - swap::core::TokenType, -}; -use ethnum::U256; - -use super::{ constants::{SCALE, SCALE_OFFSET}, fee_helper::{FeeError, FeeHelper}, math::{ @@ -18,9 +12,12 @@ use super::{ u256x256_math::{U256x256Math, U256x256MathError}, }, pair_parameter_helper::{PairParameters, PairParametersError}, - transfer::HandleMsg, types::Bytes32, }; +use cosmwasm_std::Uint128; +use ethnum::U256; +// use secret_toolkit::snip20::transfer_msg; +// use cosmwasm_std::{Addr, BankMsg, Coin, CosmosMsg, Uint128}; #[derive(thiserror::Error, Debug)] pub enum BinError { @@ -356,7 +353,8 @@ impl BinHelper { Ok((amounts_in_with_fees, amounts_out_of_bin, total_fees)) } - // NOTE: Instead of querying the total balance of the contract and substracting the amount with the reserves, we will just calculate the amount received from the send message + // NOTE: Instead of querying the total balance of the contract and substracting the amount with the reserves, + // we will just calculate the amount received from the send message /// Returns the encoded amounts that were transferred to the contract for both tokens. /// @@ -410,6 +408,11 @@ impl BinHelper { Bytes32::encode_second(amount_received.u128()) } + // TODO: (maybe) move the transfer helper methods into an impl module inside of + // shade_protocol/contract_interfaces/liquidity_book + + /* + /// Transfers the encoded amounts to the recipient for both tokens. /// /// # Arguments @@ -464,15 +467,16 @@ impl BinHelper { contract_addr, token_code_hash, } => { - let msg = HandleMsg::Transfer { - recipient: recipient.to_string(), + let cosmos_msg = transfer_msg( + recipient.to_string(), amount, - padding: None, - memo: None, - }; - let cosmos_msg = msg - .to_cosmos_msg(token_code_hash, contract_addr.to_string(), None) - .unwrap(); + None, + None, + 256, + token_code_hash, + contract_addr.to_string(), + ) + .unwrap(); Some(cosmos_msg) } @@ -505,15 +509,16 @@ impl BinHelper { contract_addr, token_code_hash, } => { - let msg = HandleMsg::Transfer { - recipient: recipient.to_string(), + let cosmos_msg = transfer_msg( + recipient.to_string(), amount, - padding: None, - memo: None, - }; - let cosmos_msg = msg - .to_cosmos_msg(token_code_hash, contract_addr.to_string(), None) - .unwrap(); + None, + None, + 256, + token_code_hash, + contract_addr.to_string(), + ) + .unwrap(); Some(cosmos_msg) } @@ -527,14 +532,16 @@ impl BinHelper { None } } + + */ } #[cfg(test)] mod tests { use super::*; - use super::super::{math::encoded_sample::EncodedSample, types::StaticFeeParameters}; - use crate::c_std::StdResult; + use crate::{math::encoded_sample::EncodedSample, types::StaticFeeParameters}; + use cosmwasm_std::StdResult; use ethnum::U256; use std::str::FromStr; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/constants.rs b/packages/lb_libraries/src/constants.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/constants.rs rename to packages/lb_libraries/src/constants.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/error.rs b/packages/lb_libraries/src/error.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/error.rs rename to packages/lb_libraries/src/error.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/fee_helper.rs b/packages/lb_libraries/src/fee_helper.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/fee_helper.rs rename to packages/lb_libraries/src/fee_helper.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/expiration.rs b/packages/lb_libraries/src/lb_token/expiration.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/expiration.rs rename to packages/lb_libraries/src/lb_token/expiration.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/metadata.rs b/packages/lb_libraries/src/lb_token/metadata.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/metadata.rs rename to packages/lb_libraries/src/lb_token/metadata.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/mod.rs b/packages/lb_libraries/src/lb_token/mod.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/mod.rs rename to packages/lb_libraries/src/lb_token/mod.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/permissions.rs b/packages/lb_libraries/src/lb_token/permissions.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/permissions.rs rename to packages/lb_libraries/src/lb_token/permissions.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/state_structs.rs b/packages/lb_libraries/src/lb_token/state_structs.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/state_structs.rs rename to packages/lb_libraries/src/lb_token/state_structs.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/txhistory.rs b/packages/lb_libraries/src/lb_token/txhistory.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/lb_token/txhistory.rs rename to packages/lb_libraries/src/lb_token/txhistory.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/mod.rs b/packages/lb_libraries/src/lib.rs similarity index 94% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/mod.rs rename to packages/lb_libraries/src/lib.rs index 74aaf928..149f708a 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/mod.rs +++ b/packages/lb_libraries/src/lib.rs @@ -11,9 +11,7 @@ pub mod math; pub mod oracle_helper; pub mod pair_parameter_helper; pub mod price_helper; -pub mod transfer; pub mod types; -pub mod viewing_keys; pub fn approx_div(a: Uint256, b: Uint256) -> Uint256 { if b == Uint256::zero() { diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/bit_math.rs b/packages/lb_libraries/src/math/bit_math.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/bit_math.rs rename to packages/lb_libraries/src/math/bit_math.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/encoded_sample.rs b/packages/lb_libraries/src/math/encoded_sample.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/encoded_sample.rs rename to packages/lb_libraries/src/math/encoded_sample.rs index 830df7d9..576e4c78 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/encoded_sample.rs +++ b/packages/lb_libraries/src/math/encoded_sample.rs @@ -3,7 +3,7 @@ //! //! Helper library used for setting and decoding parts of encoded Bytes32. -use crate::liquidity_book::lb_libraries::types::Bytes32; +use crate::types::Bytes32; use cosmwasm_schema::cw_serde; use ethnum::U256; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/liquidity_configurations.rs b/packages/lb_libraries/src/math/liquidity_configurations.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/liquidity_configurations.rs rename to packages/lb_libraries/src/math/liquidity_configurations.rs index 94ad5eac..d2df509e 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/liquidity_configurations.rs +++ b/packages/lb_libraries/src/math/liquidity_configurations.rs @@ -6,7 +6,7 @@ use cosmwasm_schema::cw_serde; use ethnum::U256; -use crate::liquidity_book::lb_libraries::types::Bytes32; +use crate::types::Bytes32; use super::packed_u128_math::PackedUint128Math; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/mod.rs b/packages/lb_libraries/src/math/mod.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/mod.rs rename to packages/lb_libraries/src/math/mod.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/packed_u128_math.rs b/packages/lb_libraries/src/math/packed_u128_math.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/packed_u128_math.rs rename to packages/lb_libraries/src/math/packed_u128_math.rs index 71607108..8b5d4a22 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/packed_u128_math.rs +++ b/packages/lb_libraries/src/math/packed_u128_math.rs @@ -9,7 +9,8 @@ use ethnum::U256; -use crate::{c_std::StdError, liquidity_book::lb_libraries::types::Bytes32}; +use crate::types::Bytes32; +use cosmwasm_std::StdError; pub const BASIS_POINT_MAX: u128 = 10_000; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/safe_math.rs b/packages/lb_libraries/src/math/safe_math.rs similarity index 96% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/safe_math.rs rename to packages/lb_libraries/src/math/safe_math.rs index c7f21ec4..633ed8c5 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/safe_math.rs +++ b/packages/lb_libraries/src/math/safe_math.rs @@ -1,6 +1,6 @@ use ethnum::U256; -use crate::liquidity_book::lb_libraries::pair_parameter_helper::PairParametersError; +use crate::pair_parameter_helper::PairParametersError; use super::{u128x128_math::U128x128MathError, u24::U24, u256x256_math::U256x256MathError}; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/sample_math.rs b/packages/lb_libraries/src/math/sample_math.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/sample_math.rs rename to packages/lb_libraries/src/math/sample_math.rs index 0e423a8a..c54c2e6a 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/sample_math.rs +++ b/packages/lb_libraries/src/math/sample_math.rs @@ -12,11 +12,9 @@ //! * 208 - 216: sample lifetime (8 bits) //! * 216 - 256: sample creation timestamp (40 bits) -use cosmwasm_schema::cw_serde; - -use crate::liquidity_book::lb_libraries::types::Bytes32; - use super::{encoded_sample::*, packed_u128_math::PackedUint128Math}; +use crate::types::Bytes32; +use cosmwasm_schema::cw_serde; pub const OFFSET_CUMULATIVE_TXNS: u8 = 0; pub const OFFSET_CUMULATIVE_ID: u8 = 16; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/tree_math.rs b/packages/lb_libraries/src/math/tree_math.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/tree_math.rs rename to packages/lb_libraries/src/math/tree_math.rs index 735d7fbb..7967b820 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/tree_math.rs +++ b/packages/lb_libraries/src/math/tree_math.rs @@ -3,13 +3,12 @@ //! //! This module contains functions to interact with a tree of TreeUint24. +use super::{bit_math::BitMath, u24::U24}; +use crate::types::Bytes32; use cosmwasm_schema::cw_serde; use ethnum::U256; use std::collections::HashMap; -use super::{bit_math::BitMath, u24::U24}; -use crate::liquidity_book::lb_libraries::types::Bytes32; - // TODO - This module is likely inefficient because we don't have bit ops for Bytes32. // - Other libraries could benefit from Bytes32 bit ops also... @@ -28,6 +27,8 @@ impl Default for TreeUint24 { } impl TreeUint24 { + // I think I was wrong about this!! + // // Note about HashMap capacity: HashMap will increase its capacity when it's about 2/3 full, which // requires memory reallocation. It would be better to start with the max size needed, to avoid // that reallocation (which may potentially require a lot of gas). diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u128x128_math.rs b/packages/lb_libraries/src/math/u128x128_math.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u128x128_math.rs rename to packages/lb_libraries/src/math/u128x128_math.rs index 44d89c63..c9a653c8 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u128x128_math.rs +++ b/packages/lb_libraries/src/math/u128x128_math.rs @@ -6,7 +6,7 @@ use ethnum::{I256, U256}; -use crate::liquidity_book::lb_libraries::constants::*; +use crate::constants::*; use super::bit_math::BitMath; @@ -167,7 +167,6 @@ impl U128x128Math { #[cfg(test)] mod tests { - use core::panic; use std::str::FromStr; use super::*; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u24.rs b/packages/lb_libraries/src/math/u24.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u24.rs rename to packages/lb_libraries/src/math/u24.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u256x256_math.rs b/packages/lb_libraries/src/math/u256x256_math.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u256x256_math.rs rename to packages/lb_libraries/src/math/u256x256_math.rs index b6c54e86..6e9c1a16 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/u256x256_math.rs +++ b/packages/lb_libraries/src/math/u256x256_math.rs @@ -426,7 +426,7 @@ mod tests { use ethnum::U256; use super::U256x256Math; - use crate::liquidity_book::lb_libraries::constants::{PRECISION, SCALE_OFFSET}; + use crate::constants::{PRECISION, SCALE_OFFSET}; #[test] fn test_get_mul_prods() { diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/uint256_to_u256.rs b/packages/lb_libraries/src/math/uint256_to_u256.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/math/uint256_to_u256.rs rename to packages/lb_libraries/src/math/uint256_to_u256.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/oracle_helper.rs b/packages/lb_libraries/src/oracle_helper.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/oracle_helper.rs rename to packages/lb_libraries/src/oracle_helper.rs diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/pair_parameter_helper.rs b/packages/lb_libraries/src/pair_parameter_helper.rs similarity index 99% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/pair_parameter_helper.rs rename to packages/lb_libraries/src/pair_parameter_helper.rs index c0c10772..5e1f88e1 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/pair_parameter_helper.rs +++ b/packages/lb_libraries/src/pair_parameter_helper.rs @@ -507,7 +507,7 @@ impl PairParameters { #[cfg(test)] mod tests { use super::*; - use crate::liquidity_book::lb_libraries::types::StaticFeeParameters; + use crate::types::StaticFeeParameters; use cosmwasm_std::testing::mock_env; static MAX_STATIC_FEE_PARAMETER: StaticFeeParameters = StaticFeeParameters { @@ -604,7 +604,7 @@ mod tests { // For the second assertion, we'll mimic the bitwise operations let shifted_mask = MASK_UINT16 << OFFSET_ORACLE_ID; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -634,7 +634,7 @@ mod tests { assert_eq!(pair_params.get_volatility_reference(), volatility_reference); let shifted_mask = MASK_UINT20 << OFFSET_VOL_REF; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -673,7 +673,7 @@ mod tests { let mask_not_uint20 = !mask_uint20; let shifted_mask = mask_not_uint20 << OFFSET_VOL_ACC; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -721,7 +721,7 @@ mod tests { // For the final assertion, we'll mimic the bitwise operations let mask_not_uint24 = !MASK_UINT24; let shifted_mask = mask_not_uint24 << OFFSET_ACTIVE_ID; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -786,7 +786,7 @@ mod tests { let mask_not_uint24 = !MASK_UINT24; let shifted_mask = mask_not_uint24 << OFFSET_ACTIVE_ID; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -812,7 +812,7 @@ mod tests { let mask_not_uint40 = !MASK_UINT40; let shifted_mask = mask_not_uint40 << OFFSET_TIME_LAST_UPDATE; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -847,7 +847,7 @@ mod tests { let mask_not_uint20 = !MASK_UINT20; let shifted_mask = mask_not_uint20 << OFFSET_VOL_REF; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -887,7 +887,7 @@ mod tests { let mask_not_uint20 = !MASK_UINT20; let shifted_mask = mask_not_uint20 << OFFSET_VOL_ACC; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!( @@ -957,7 +957,7 @@ mod tests { ); let mask = !(U256::from(1u128 << 84u128) - 1u128) << OFFSET_VOL_REF; - let new_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(pair_params.0 .0); let original_params_bits = U256::from_le_bytes(EncodedSample([0u8; 32]).0); assert_eq!(new_params_bits & mask, original_params_bits & mask); @@ -1024,8 +1024,8 @@ mod tests { ); let mask = !(U256::from(1u128 << 104u128) - 1u128) << OFFSET_VOL_ACC; - let new_params_bits = U256::from_le_bytes(new_params.0.0); - let original_params_bits = U256::from_le_bytes(pair_params.0.0); + let new_params_bits = U256::from_le_bytes(new_params.0 .0); + let original_params_bits = U256::from_le_bytes(pair_params.0 .0); assert_eq!(new_params_bits & mask, original_params_bits & mask); } else { diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/price_helper.rs b/packages/lb_libraries/src/price_helper.rs similarity index 100% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/price_helper.rs rename to packages/lb_libraries/src/price_helper.rs diff --git a/packages/lb_libraries/src/types.rs b/packages/lb_libraries/src/types.rs new file mode 100644 index 00000000..68a95e03 --- /dev/null +++ b/packages/lb_libraries/src/types.rs @@ -0,0 +1,30 @@ +//! ### Liquidity Book Type Library +//! Author: Kent and Haseeb +//! +//! This library contains common types used throughout the project. + +use cosmwasm_schema::cw_serde; + +pub use crate::math::{liquidity_configurations::LiquidityConfigurations, tree_math::TreeUint24}; + +pub type Bytes32 = [u8; 32]; + +// TODO: move this type somewhere else? + +#[cw_serde] +#[derive(Default)] +pub struct ContractImplementation { + pub id: u64, + pub code_hash: String, +} + +#[cw_serde] +pub struct StaticFeeParameters { + pub base_factor: u16, + pub filter_period: u16, + pub decay_period: u16, + pub reduction_factor: u16, + pub variable_fee_control: u32, + pub protocol_share: u16, + pub max_volatility_accumulator: u32, +} diff --git a/packages/multi_test/Cargo.toml b/packages/multi_test/Cargo.toml index 6d07cae8..fc07b322 100644 --- a/packages/multi_test/Cargo.toml +++ b/packages/multi_test/Cargo.toml @@ -47,7 +47,6 @@ snip20 = { version = "0.1.0", path = "../../contracts/snip20", optional = true } lb_factory = { version = "0.1.0", path = "../../contracts/liquidity_book/lb_factory", optional = true} lb_pair = { version = "0.1.0", path = "../../contracts/liquidity_book/lb_pair", optional = true } lb_token = { version = "0.1.0", path = "../../contracts/liquidity_book/lb_token", optional = true } - lb_staking = { version = "0.1.0", path = "../../contracts/liquidity_book/lb_staking", optional = true } router = { version = "0.1.0", path = "../../contracts/liquidity_book/router", optional = true } #liability_mint = { version = "0.1.0", path = "../../contracts/liability_mint", optional = true } @@ -70,6 +69,7 @@ mock_stkd = { version = "0.1.0", package = "mock_stkd_derivative", path = "../.. mock_sienna = { version = "0.1.0", package = "mock_sienna_pair", path = "../../contracts/mock/mock_sienna_pair", optional = true } snip20_migration = { version = "0.1.0", path = "../../contracts/snip20_migration", optional = true } shade-protocol = { path = "../shade_protocol", features = ["multi-test", "swap", "liquidity_book" ] } +lb-libraries = { path = "../lb_libraries" } anyhow = "1" [target.'cfg(not(target_arch="wasm32"))'.dependencies] diff --git a/packages/multi_test/src/interfaces/lb_factory.rs b/packages/multi_test/src/interfaces/lb_factory.rs index 589df3b0..e6ee2be7 100644 --- a/packages/multi_test/src/interfaces/lb_factory.rs +++ b/packages/multi_test/src/interfaces/lb_factory.rs @@ -1,17 +1,14 @@ use crate::multi::lb_factory::LbFactory; +use lb_libraries::types::ContractImplementation; use shade_protocol::{ c_std::{Addr, ContractInfo, StdError, StdResult}, contract_interfaces::liquidity_book::lb_factory, - lb_libraries::types::{ContractInstantiationInfo, LBPair, LBPairInformation}, - liquidity_book::lb_pair::RewardsDistributionAlgorithm, + liquidity_book::lb_pair::{LBPair, LBPairInformation, RewardsDistributionAlgorithm}, multi_test::App, swap::core::TokenType, utils::{ asset::{Contract, RawContract}, - ExecuteCallback, - InstantiateCallback, - MultiTestable, - Query, + ExecuteCallback, InstantiateCallback, MultiTestable, Query, }, }; @@ -56,7 +53,7 @@ pub fn set_lb_pair_implementation( code_hash: String, ) -> StdResult<()> { match (lb_factory::ExecuteMsg::SetLBPairImplementation { - implementation: ContractInstantiationInfo { id, code_hash }, + implementation: ContractImplementation { id, code_hash }, } .test_exec(lb_factory, app, Addr::unchecked(sender), &[])) { @@ -73,7 +70,7 @@ pub fn set_lb_token_implementation( code_hash: String, ) -> StdResult<()> { match (lb_factory::ExecuteMsg::SetLBTokenImplementation { - implementation: ContractInstantiationInfo { id, code_hash }, + implementation: ContractImplementation { id, code_hash }, } .test_exec(lb_factory, app, Addr::unchecked(sender), &[])) { @@ -90,7 +87,7 @@ pub fn set_staking_contract_implementation( code_hash: String, ) -> StdResult<()> { match (lb_factory::ExecuteMsg::SetStakingContractImplementation { - implementation: ContractInstantiationInfo { id, code_hash }, + implementation: ContractImplementation { id, code_hash }, } .test_exec(lb_factory, app, Addr::unchecked(sender), &[])) { @@ -320,7 +317,7 @@ pub fn force_decay( pub fn query_lb_pair_implementation( app: &mut App, lb_factory: &ContractInfo, -) -> StdResult { +) -> StdResult { match (lb_factory::QueryMsg::GetLBPairImplementation {}.test_query(lb_factory, app)) { Ok(lb_factory::LBPairImplementationResponse { lb_pair_implementation, @@ -332,7 +329,7 @@ pub fn query_lb_pair_implementation( pub fn query_lb_token_implementation( app: &mut App, lb_factory: &ContractInfo, -) -> StdResult { +) -> StdResult { match (lb_factory::QueryMsg::GetLBTokenImplementation {}.test_query(lb_factory, app)) { Ok(lb_factory::LBTokenImplementationResponse { lb_token_implementation, diff --git a/packages/multi_test/src/interfaces/lb_pair.rs b/packages/multi_test/src/interfaces/lb_pair.rs index cdc0f614..87f9733a 100644 --- a/packages/multi_test/src/interfaces/lb_pair.rs +++ b/packages/multi_test/src/interfaces/lb_pair.rs @@ -1,27 +1,19 @@ use std::str::FromStr; use crate::multi::lb_pair::LbPair; +use lb_libraries::types::{ContractImplementation, StaticFeeParameters}; use shade_protocol::{ c_std::{to_binary, Addr, Coin, ContractInfo, StdError, StdResult, Uint128, Uint256}, contract_interfaces::{liquidity_book::lb_pair, snip20}, - lb_libraries::types::{ContractInstantiationInfo, StaticFeeParameters}, liquidity_book::lb_pair::{ - BinResponse, - ContractStatus, - LiquidityParameters, - OracleSampleAtResponse, - RemoveLiquidity, - RewardsDistribution, - RewardsDistributionAlgorithm, + BinResponse, ContractStatus, LiquidityParameters, OracleSampleAtResponse, RemoveLiquidity, + RewardsDistribution, RewardsDistributionAlgorithm, }, multi_test::App, swap::core::{TokenAmount, TokenType}, utils::{ asset::{Contract, RawContract}, - ExecuteCallback, - InstantiateCallback, - MultiTestable, - Query, + ExecuteCallback, InstantiateCallback, MultiTestable, Query, }, }; @@ -34,8 +26,8 @@ pub fn init( bin_step: u16, pair_parameters: StaticFeeParameters, active_id: u32, - lb_token_implementation: ContractInstantiationInfo, - staking_contract_implementation: ContractInstantiationInfo, + lb_token_implementation: ContractImplementation, + staking_contract_implementation: ContractImplementation, viewing_key: String, _pair_name: String, entropy: String, diff --git a/packages/multi_test/src/interfaces/lb_token.rs b/packages/multi_test/src/interfaces/lb_token.rs index 3a68be04..5f886316 100644 --- a/packages/multi_test/src/interfaces/lb_token.rs +++ b/packages/multi_test/src/interfaces/lb_token.rs @@ -1,7 +1,7 @@ +use lb_libraries::lb_token::state_structs::OwnerBalance; use shade_protocol::{ c_std::{Addr, ContractInfo, StdError, StdResult, Uint256}, contract_interfaces::liquidity_book::{lb_token, lb_token::*}, - lb_libraries::lb_token::state_structs::OwnerBalance, multi_test::App, utils::{ExecuteCallback, Query}, }; diff --git a/packages/shade_protocol/Cargo.toml b/packages/shade_protocol/Cargo.toml index d1a29e11..c86dd434 100644 --- a/packages/shade_protocol/Cargo.toml +++ b/packages/shade_protocol/Cargo.toml @@ -26,7 +26,7 @@ crate-type = ["cdylib", "rlib"] [features] -default = ["utils", "liquidity_book"] +default = ["utils"] # Utils @@ -132,6 +132,8 @@ thiserror = "1.0.50" secret-storage-plus = { git = "https://github.com/securesecrets/secret-plus-utils", tag = "v0.1.1", optional = true, features = [] } +lb-libraries = { path = "../lb_libraries"} + # Testing anyhow = { version = "1", optional = true } diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_factory.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_factory.rs index a045ee37..0ae18a82 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_factory.rs +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_factory.rs @@ -1,15 +1,26 @@ use super::lb_pair::{self, RewardsDistributionAlgorithm}; use crate::{ - contract_interfaces::swap::core::TokenType, - lb_libraries::types::{ContractInstantiationInfo, LBPair, LBPairInformation}, - utils::asset::RawContract, + contract_interfaces::liquidity_book::lb_pair::{LBPair, LBPairInformation}, + swap::core::TokenType, + utils::{asset::RawContract, ExecuteCallback, InstantiateCallback, Query}, }; - -use crate::utils::{ExecuteCallback, InstantiateCallback, Query}; use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::Addr; +use lb_libraries::types::ContractImplementation; + pub use lb_pair::InstantiateMsg as LBPairInstantiateMsg; +#[cw_serde] +pub struct StaticFeeParameters { + pub base_factor: u16, + pub filter_period: u16, + pub decay_period: u16, + pub reduction_factor: u16, + pub variable_fee_control: u32, + pub protocol_share: u16, + pub max_volatility_accumulator: u32, +} + #[cw_serde] pub struct InstantiateMsg { pub admin_auth: RawContract, @@ -27,15 +38,15 @@ impl InstantiateCallback for InstantiateMsg { pub enum ExecuteMsg { #[serde(rename = "set_lb_pair_implementation")] SetLBPairImplementation { - implementation: ContractInstantiationInfo, + implementation: ContractImplementation, }, #[serde(rename = "set_lb_token_implementation")] SetLBTokenImplementation { - implementation: ContractInstantiationInfo, + implementation: ContractImplementation, }, #[serde(rename = "set_staking_contract_implementation")] SetStakingContractImplementation { - implementation: ContractInstantiationInfo, + implementation: ContractImplementation, }, #[serde(rename = "create_lb_pair")] CreateLBPair { @@ -175,12 +186,12 @@ pub struct FeeRecipientResponse { #[cw_serde] pub struct LBPairImplementationResponse { - pub lb_pair_implementation: ContractInstantiationInfo, + pub lb_pair_implementation: ContractImplementation, } #[cw_serde] pub struct LBTokenImplementationResponse { - pub lb_token_implementation: ContractInstantiationInfo, + pub lb_token_implementation: ContractImplementation, } #[cw_serde] diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/transfer.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/transfer.rs deleted file mode 100644 index 393a95a2..00000000 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/transfer.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! ### Liquidity Book msgs Helper Library -//! Author: Haseeb -//! - -use crate::{ - c_std::{to_binary, Binary, Coin, CosmosMsg, StdResult, Uint128, WasmMsg}, - cosmwasm_schema::cw_serde, -}; -// use cosmwasm_schema::cw_serde; -// use cosmwasm_std::{to_binary, Binary, Coin, CosmosMsg, StdResult, Uint128, WasmMsg}; - -const BLOCK_SIZE: usize = 256; -/// SNIP20 token handle messages -#[cw_serde] -pub enum HandleMsg { - // Basic SNIP20 functions - Transfer { - recipient: String, - amount: Uint128, - memo: Option, - padding: Option, - }, - TransferFrom { - owner: String, - recipient: String, - amount: Uint128, - memo: Option, - padding: Option, - }, - Send { - recipient: String, - recipient_code_hash: Option, - amount: Uint128, - msg: Option, - memo: Option, - padding: Option, - }, - RegisterReceive { - code_hash: String, - padding: Option, - }, - CreateViewingKey { - entropy: String, - padding: Option, - }, - SetViewingKey { - key: String, - padding: Option, - }, -} - -impl HandleMsg { - /// Returns a StdResult used to execute a SNIP20 contract function - /// - /// # Arguments - /// - /// * `block_size` - pad the message to blocks of this size - /// * `callback_code_hash` - String holding the code hash of the contract being called - /// * `contract_addr` - address of the contract being called - /// * `send_amount` - Optional Uint128 amount of native coin to send with the callback message - /// NOTE: Only a Deposit message should have an amount sent with it - pub fn to_cosmos_msg( - &self, - code_hash: String, - contract_addr: String, - send_amount: Option, - ) -> StdResult { - let mut msg = to_binary(self)?; - space_pad(&mut msg.0, BLOCK_SIZE); - let mut funds = Vec::new(); - if let Some(amount) = send_amount { - funds.push(Coin { - amount, - denom: String::from("uscrt"), - }); - } - let execute = WasmMsg::Execute { - contract_addr, - code_hash, - msg, - funds, - }; - Ok(execute.into()) - } -} - -pub fn space_pad(message: &mut Vec, block_size: usize) -> &mut Vec { - let len = message.len(); - let surplus = len % block_size; - if surplus == 0 { - return message; - } - - let missing = block_size - surplus; - message.reserve(missing); - message.extend(std::iter::repeat(b' ').take(missing)); - message -} - -#[cw_serde] -pub enum QueryMsg { - Balance { address: String, key: String }, -} - -#[cw_serde] -pub enum QueryAnswer { - Balance { amount: Uint128 }, -} diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs deleted file mode 100644 index a702af59..00000000 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! ### Liquidity Book Type Library -//! Author: Kent and Haseeb -//! -//! This library contains common types used throughout the project. - -pub use super::math::{liquidity_configurations::LiquidityConfigurations, tree_math::TreeUint24}; -use crate::{c_std::ContractInfo, cosmwasm_schema::cw_serde}; -use ethnum::U256; -// TODO - Try to not use this type in the liquidity_book module, because it's gated by the "swap" -// feature. -use crate::contract_interfaces::swap::core::TokenType; - -pub type Bytes32 = [u8; 32]; - -pub type Bytes8 = [u8; 8]; - -// TODO - This type belongs somewhere else. It's not specific to liquidity_book. -#[cw_serde] -#[derive(Default)] -pub struct ContractInstantiationInfo { - pub id: u64, - pub code_hash: String, -} - -#[cw_serde] -pub struct StaticFeeParameters { - pub base_factor: u16, - pub filter_period: u16, - pub decay_period: u16, - pub reduction_factor: u16, - pub variable_fee_control: u32, - pub protocol_share: u16, - pub max_volatility_accumulator: u32, -} - -#[derive(Clone, Debug)] -pub struct MintArrays { - pub ids: Vec, - pub amounts: Vec, - pub liquidity_minted: Vec, -} - -#[cw_serde] -pub struct LBPair { - pub token_x: TokenType, - pub token_y: TokenType, - pub bin_step: u16, - pub contract: ContractInfo, -} - -#[cw_serde] -pub struct LBPairInformation { - pub bin_step: u16, - pub info: LBPair, - pub created_by_owner: bool, - pub ignored_for_routing: bool, -} diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/viewing_keys.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/viewing_keys.rs deleted file mode 100644 index d68944cb..00000000 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/viewing_keys.rs +++ /dev/null @@ -1,112 +0,0 @@ -// TODO - do we need this file at all? - -use crate::{ - c_std::{ContractInfo, CosmosMsg, StdResult}, - cosmwasm_schema::cw_serde, -}; -// use cosmwasm_schema::cw_serde; -// use cosmwasm_std::{ContractInfo, CosmosMsg, StdResult}; - -use super::transfer::HandleMsg; -// use cosmwasm_std::{Binary, Env, MessageInfo}; -// use std::fmt; -// use subtle::ConstantTimeEq; - -// use crate::utils::crypto::{sha_256, Prng}; - -pub const VIEWING_KEY_SIZE: usize = 32; -// const VIEWING_KEY_PREFIX: &str = "api_key_"; - -#[cw_serde] -pub struct ViewingKey(pub String); - -// pub fn create_hashed_password(s1: &str) -> [u8; VIEWING_KEY_SIZE] { -// sha_256(s1.as_bytes()) -// } - -// impl ViewingKey { -// pub fn new(env: &Env, info: &MessageInfo, seed: &[u8], entropy: &[u8]) -> Self { -// // 16 here represents the lengths in bytes of the block height and time. -// let entropy_len = 16 + info.sender.to_string().len() + entropy.len(); -// let mut rng_entropy = Vec::with_capacity(entropy_len); -// rng_entropy.extend_from_slice(&env.block.height.to_be_bytes()); -// rng_entropy.extend_from_slice(&env.block.time.nanos().to_be_bytes()); -// rng_entropy.extend_from_slice(&info.sender.as_bytes()); -// rng_entropy.extend_from_slice(entropy); - -// let mut rng = Prng::new(seed, &rng_entropy); - -// let rand_slice = rng.rand_bytes(); - -// let key = sha_256(&rand_slice); - -// Self(VIEWING_KEY_PREFIX.to_string() + &Binary::from(&key).to_base64()) -// } - -// pub fn to_hashed(&self) -> [u8; VIEWING_KEY_SIZE] { -// create_hashed_password(&self.0) -// } - -// pub fn as_bytes(&self) -> &[u8] { -// self.0.as_bytes() -// } - -// pub fn check_viewing_key(&self, hashed_pw: &[u8]) -> bool { -// let mine_hashed = create_hashed_password(&self.0); - -// bool::from(mine_hashed.ct_eq(hashed_pw)) -// } -// } - -// impl fmt::Display for ViewingKey { -// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -// write!(f, "{}", self.0) -// } -// } - -impl From<&str> for ViewingKey { - fn from(vk: &str) -> Self { - ViewingKey(vk.into()) - } -} - -// pub fn create_viewing_key( -// env: &Env, -// info: &MessageInfo, -// seed: Binary, -// entroy: Binary, -// ) -> ViewingKey { -// ViewingKey::new(&env, info, seed.as_slice(), entroy.as_slice()) -// } - -pub fn set_viewing_key_msg( - viewing_key: String, - padding: Option, - contract: &ContractInfo, -) -> StdResult { - HandleMsg::SetViewingKey { - key: viewing_key, - padding, - } - .to_cosmos_msg( - contract.code_hash.clone(), - contract.address.to_string(), - None, - ) -} - -pub fn register_receive( - register_hash: String, - padding: Option, - contract: &ContractInfo, -) -> StdResult { - HandleMsg::RegisterReceive { - code_hash: register_hash, - padding, - } - .to_cosmos_msg( - contract.code_hash.clone(), - contract.address.to_string(), - None, - ) -} diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_pair.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_pair.rs index bd09eb41..5763c842 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_pair.rs +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_pair.rs @@ -1,18 +1,29 @@ -use std::fmt::{Debug, Display}; - use crate::{ c_std::{Addr, ContractInfo, Decimal256, Uint128, Uint256}, cosmwasm_schema::{cw_serde, QueryResponses}, - liquidity_book::lb_libraries::types::{ - Bytes32, - ContractInstantiationInfo, - StaticFeeParameters, - }, snip20::Snip20ReceiveMsg, swap::core::{TokenAmount, TokenType}, utils::{asset::RawContract, ExecuteCallback, InstantiateCallback, Query}, Contract, }; +use lb_libraries::types::{Bytes32, ContractImplementation, StaticFeeParameters}; +use std::fmt::{Debug, Display}; + +#[cw_serde] +pub struct LBPair { + pub token_x: TokenType, + pub token_y: TokenType, + pub bin_step: u16, + pub contract: ContractInfo, +} + +#[cw_serde] +pub struct LBPairInformation { + pub bin_step: u16, + pub info: LBPair, + pub created_by_owner: bool, + pub ignored_for_routing: bool, +} #[cw_serde] pub struct InstantiateMsg { @@ -22,8 +33,8 @@ pub struct InstantiateMsg { pub bin_step: u16, pub pair_parameters: StaticFeeParameters, pub active_id: u32, - pub lb_token_implementation: ContractInstantiationInfo, - pub staking_contract_implementation: ContractInstantiationInfo, + pub lb_token_implementation: ContractImplementation, + pub staking_contract_implementation: ContractImplementation, pub viewing_key: String, pub entropy: String, pub protocol_fee_recipient: Addr, diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_staking.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_staking.rs index 0df515d2..6b86ccc1 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_staking.rs +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_staking.rs @@ -1,35 +1,21 @@ -use std::collections::HashMap; - -use crate::{ - liquidity_book::lb_libraries::types::ContractInstantiationInfo, - query_auth::QueryPermit, - Contract, +use super::{ + lb_pair::RewardsDistribution, + lb_token::{space_pad, Snip1155ReceiveMsg}, }; - use crate::{ c_std::{ - to_binary, - Addr, - Binary, - Coin, - ContractInfo, - CosmosMsg, - StdResult, - Uint128, - Uint256, + to_binary, Addr, Binary, Coin, ContractInfo, CosmosMsg, StdResult, Uint128, Uint256, WasmMsg, }, cosmwasm_schema::cw_serde, + query_auth::QueryPermit, snip20::Snip20ReceiveMsg, swap::core::TokenType, utils::{asset::RawContract, ExecuteCallback, InstantiateCallback, Query}, - BLOCK_SIZE, -}; - -use super::{ - lb_pair::RewardsDistribution, - lb_token::{space_pad, Snip1155ReceiveMsg}, + Contract, BLOCK_SIZE, }; +use lb_libraries::types::ContractImplementation; +use std::collections::HashMap; impl InstantiateCallback for InstantiateMsg { const BLOCK_SIZE: usize = BLOCK_SIZE; @@ -45,7 +31,7 @@ impl Query for QueryMsg { #[cw_serde] pub struct StakingContractInstantiateInfo { - pub staking_contract_info: ContractInstantiationInfo, + pub staking_contract_info: ContractImplementation, pub custom_label: Option, pub first_reward_token: Option, pub query_auth: Option, diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_token.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_token.rs index c6f50de3..e1dc9774 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_token.rs +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_token.rs @@ -1,18 +1,17 @@ -use secret_toolkit::permit::Permit; -use serde::{Deserialize, Serialize}; - use crate::{ c_std::{to_binary, Addr, Binary, Coin, CosmosMsg, StdResult, Uint128, Uint256, WasmMsg}, - liquidity_book::lb_libraries::lb_token::{ - expiration::Expiration, - metadata::Metadata, - permissions::{Permission, PermissionKey}, - state_structs::{CurateTokenId, LbPair, OwnerBalance, StoredTokenInfo, TokenAmount}, - txhistory::Tx, - }, schemars::JsonSchema, utils::{ExecuteCallback, InstantiateCallback, Query}, }; +use lb_libraries::lb_token::{ + expiration::Expiration, + metadata::Metadata, + permissions::{Permission, PermissionKey}, + state_structs::{CurateTokenId, LbPair, OwnerBalance, StoredTokenInfo, TokenAmount}, + txhistory::Tx, +}; +use secret_toolkit::permit::Permit; +use serde::{Deserialize, Serialize}; ///////////////////////////////////////////////////////////////////////////////// // Init messages diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/mod.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/mod.rs index 1442936b..97bf1421 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/mod.rs +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/mod.rs @@ -1,6 +1,4 @@ -#[cfg(all(feature = "liquidity_book_impl", feature = "swap"))] pub mod lb_factory; -pub mod lb_libraries; pub mod lb_pair; pub mod lb_staking; pub mod lb_token; diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/router.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/router.rs new file mode 100644 index 00000000..35741f59 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/router.rs @@ -0,0 +1,113 @@ +use crate::{ + c_std::{Addr, Binary, Uint128}, + cosmwasm_schema::cw_serde, + liquidity_book::lb_pair::SwapResult, + snip20::Snip20ReceiveMsg, + swap::core::{TokenAmount, TokenType}, + utils::{ExecuteCallback, InstantiateCallback, Query}, + Contract, + BLOCK_SIZE, +}; + +#[cw_serde] +pub enum ExecuteMsgResponse { + SwapResult { + amount_in: Uint128, + amount_out: Uint128, + }, +} + +#[cw_serde] +pub enum InvokeMsg { + SwapTokensForExact { + path: Vec, + expected_return: Option, + recipient: Option, + }, +} + +#[cw_serde] +pub struct InitMsg { + pub prng_seed: Binary, + pub entropy: Binary, + pub admin_auth: Contract, + pub airdrop_address: Option, +} + +#[cw_serde] +pub struct Hop { + pub addr: String, + pub code_hash: String, +} + +#[cw_serde] +pub enum ExecuteMsg { + // SNIP20 receiver interface + Receive(Snip20ReceiveMsg), + SwapTokensForExact { + /// The token type to swap from. + offer: TokenAmount, + expected_return: Option, + path: Vec, + recipient: Option, + padding: Option, + }, + RegisterSNIP20Token { + token_addr: String, + token_code_hash: String, + oracle_key: Option, + padding: Option, + }, + RecoverFunds { + token: TokenType, + amount: Uint128, + to: String, + msg: Option, + padding: Option, + }, + SetConfig { + admin_auth: Option, + padding: Option, + }, +} + +#[cw_serde] +pub enum QueryMsg { + SwapSimulation { + offer: TokenAmount, + path: Vec, + exclude_fee: Option, + }, + GetConfig {}, + RegisteredTokens {}, +} + +#[cw_serde] +pub enum QueryMsgResponse { + SwapSimulation { + total_fee_amount: Uint128, + lp_fee_amount: Uint128, + shade_dao_fee_amount: Uint128, + result: SwapResult, + price: String, + }, + GetConfig { + admin_auth: Contract, + airdrop_address: Option, + }, + RegisteredTokens { + tokens: Vec, + }, +} + +impl InstantiateCallback for InitMsg { + const BLOCK_SIZE: usize = BLOCK_SIZE; +} + +impl ExecuteCallback for ExecuteMsg { + const BLOCK_SIZE: usize = BLOCK_SIZE; +} + +impl Query for QueryMsg { + const BLOCK_SIZE: usize = BLOCK_SIZE; +} diff --git a/packages/shade_protocol/src/contract_interfaces/liquidity_book/token_type.rs b/packages/shade_protocol/src/contract_interfaces/liquidity_book/token_type.rs new file mode 100644 index 00000000..b9e82f96 --- /dev/null +++ b/packages/shade_protocol/src/contract_interfaces/liquidity_book/token_type.rs @@ -0,0 +1,365 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{ + to_binary, + Addr, + BankMsg, + Coin, + ContractInfo, + CosmosMsg, + Deps, + MessageInfo, + StdError, + StdResult, + Uint128, + WasmMsg, +}; + +// use shade_oracles::querier::{query_price, query_prices}; +use crate::{ + snip20::{ + helpers::{balance_query, token_info}, + ExecuteMsg::{Send, TransferFrom}, + }, + utils::ExecuteCallback, + Contract, +}; + +use super::TokenAmount; + +#[cw_serde] +pub enum TokenType { + CustomToken { + contract_addr: Addr, + token_code_hash: String, + }, + NativeToken { + denom: String, + }, +} + +#[cw_serde] +pub struct StableTokenData { + pub oracle_key: String, + pub decimals: u8, +} + +#[cw_serde] +pub struct StableTokenType { + pub token: TokenType, + pub stable_token_data: StableTokenData, +} + +// impl StableTokenType { +// pub fn query_price(&self, deps: Deps, oracle: Contract) -> StdResult { +// self.stable_token_data.query_price(deps, oracle) +// } +// } + +// pub fn query_two_prices( +// deps: Deps, +// oracle: Contract, +// oracle_key0: String, +// oracle_key1: String, +// ) -> StdResult<[Uint256; 2]> { +// let shade_oracle_contract: shade_protocol::Contract = shade_protocol::Contract { +// address: oracle.address, +// code_hash: oracle.code_hash, +// }; +// let res = query_prices( +// &shade_oracle_contract, +// &deps.querier, +// &[oracle_key0, oracle_key1], +// )?; +// Ok([res[0].data.rate, res[1].data.rate]) +// } +// +// impl StableTokenData { +// pub fn query_price(&self, deps: Deps, oracle: Contract) -> StdResult { +// let shade_oracle_contract: shade_protocol::Contract = shade_protocol::Contract { +// address: oracle.address, +// code_hash: oracle.code_hash, +// }; +// let res = query_price(&shade_oracle_contract, &deps.querier, &self.oracle_key)?; +// Ok(res.data.rate) +// } +// } + +impl TokenType { + pub fn query_decimals(&self, deps: &Deps) -> StdResult { + match self { + TokenType::CustomToken { + contract_addr, + token_code_hash, + .. + } => Ok(token_info(&deps.querier, &Contract { + address: contract_addr.clone(), + code_hash: token_code_hash.clone(), + })? + .decimals), + TokenType::NativeToken { denom } => match denom.as_str() { + "uscrt" => Ok(6), + _ => Err(StdError::generic_err( + "Cannot retrieve decimals for native token", + )), + }, + } + } + + // pub fn load_stable_data(&self, stable_token_data: StableTokenData) -> StableTokenType { + // StableTokenType { + // token: self.clone(), + // stable_token_data, + // } + // } + + pub fn is_native_token(&self) -> bool { + match self { + TokenType::NativeToken { .. } => true, + TokenType::CustomToken { .. } => false, + } + } + + pub fn unique_key(&self) -> String { + match self { + TokenType::NativeToken { denom, .. } => denom.to_string(), + TokenType::CustomToken { contract_addr, .. } => contract_addr.to_string(), + } + } + + pub fn is_custom_token(&self) -> bool { + match self { + TokenType::NativeToken { .. } => false, + TokenType::CustomToken { .. } => true, + } + } + + pub fn assert_sent_native_token_balance( + &self, + info: &MessageInfo, + amount: Uint128, + ) -> StdResult<()> { + if let TokenType::NativeToken { denom, .. } = &self { + return match info.funds.iter().find(|x| x.denom == *denom) { + Some(coin) => { + if amount == coin.amount { + Ok(()) + } else { + Err(StdError::generic_err( + "Native token balance mismatch between the argument and the transferred", + )) + } + } + None => { + if amount.is_zero() { + Ok(()) + } else { + Err(StdError::generic_err( + "Native token balance mismatch between the argument and the transferred", + )) + } + } + }; + } + + Ok(()) + } + + pub fn new_amount(&self, amount: impl Into + Copy) -> TokenAmount { + TokenAmount { + token: self.clone(), + amount: amount.into(), + } + } +} + +impl From for TokenType { + fn from(value: Contract) -> Self { + Self::CustomToken { + contract_addr: value.address, + token_code_hash: value.code_hash, + } + } +} + +impl From for TokenType { + fn from(value: ContractInfo) -> Self { + Self::CustomToken { + contract_addr: value.address, + token_code_hash: value.code_hash, + } + } +} + +impl TokenType { + pub fn query_balance( + &self, + deps: Deps, + exchange_addr: String, + viewing_key: String, + ) -> StdResult { + match self { + TokenType::NativeToken { denom, .. } => { + let result = deps.querier.query_balance(exchange_addr, denom)?; + Ok(result.amount) + } + TokenType::CustomToken { + contract_addr, + token_code_hash, + .. + } => balance_query( + &deps.querier, + deps.api.addr_validate(&exchange_addr)?, + viewing_key, + &Contract { + address: contract_addr.clone(), + code_hash: token_code_hash.clone(), + }, + ), + } + } + + pub fn create_send_msg(&self, recipient: String, amount: Uint128) -> StdResult { + let msg = match self { + TokenType::CustomToken { + contract_addr, + token_code_hash, + .. + } => CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: contract_addr.clone().into_string(), + code_hash: token_code_hash.to_string(), + msg: to_binary(&Send { + recipient, + amount, + padding: None, + msg: None, + recipient_code_hash: None, + memo: None, + })?, + funds: vec![], + }), + TokenType::NativeToken { denom, .. } => CosmosMsg::Bank(BankMsg::Send { + to_address: recipient, + amount: vec![Coin { + denom: denom.clone(), + amount, + }], + }), + }; + Ok(msg) + } + + pub fn into_contract_info(&self) -> Option { + match self { + TokenType::CustomToken { + contract_addr, + token_code_hash, + .. + } => Some(ContractInfo { + address: contract_addr.clone(), + code_hash: token_code_hash.clone(), + }), + TokenType::NativeToken { .. } => None, + } + } +} + +// New Methods from LB +impl TokenType { + pub fn address(&self) -> Addr { + match self { + TokenType::NativeToken { .. } => panic!("Doesn't work for native tokens"), + TokenType::CustomToken { + contract_addr, + token_code_hash: _, + } => contract_addr.clone(), + } + } + + pub fn code_hash(&self) -> String { + match self { + TokenType::NativeToken { .. } => panic!("Doesn't work for native tokens"), + TokenType::CustomToken { + contract_addr: _, + token_code_hash, + } => token_code_hash.to_string(), + } + } + + pub fn transfer(&self, amount: Uint128, recipient: Addr) -> Option { + if amount.gt(&Uint128::zero()) { + match &self { + TokenType::CustomToken { + contract_addr: _, + token_code_hash: _, + } => { + let msg = Send { + recipient: recipient.to_string(), + amount, + padding: None, + msg: None, + recipient_code_hash: None, + memo: None, + }; + let contract: ContractInfo = ContractInfo { + address: self.address(), + code_hash: self.code_hash(), + }; + let cosmos_msg = msg.to_cosmos_msg(&contract, vec![]).unwrap(); + + Some(cosmos_msg) + } + + TokenType::NativeToken { denom } => Some(CosmosMsg::Bank(BankMsg::Send { + to_address: recipient.to_string(), + amount: vec![Coin { + denom: denom.clone(), + amount, + }], + })), + } + } else { + None + } + } + + pub fn transfer_from( + &self, + amount: Uint128, + owner: Addr, + recipient: Addr, + ) -> Option { + if amount.gt(&Uint128::zero()) { + match &self { + TokenType::CustomToken { + contract_addr: _, + token_code_hash: _, + } => { + let msg = TransferFrom { + owner: owner.to_string(), + recipient: recipient.to_string(), + amount, + padding: None, + memo: None, + }; + let contract: ContractInfo = ContractInfo { + address: self.address(), + code_hash: self.code_hash(), + }; + let cosmos_msg = msg.to_cosmos_msg(&contract, vec![]).unwrap(); + + Some(cosmos_msg) + } + + TokenType::NativeToken { denom } => Some(CosmosMsg::Bank(BankMsg::Send { + to_address: recipient.to_string(), + amount: vec![Coin { + denom: denom.clone(), + amount, + }], + })), + } + } else { + None + } + } +} diff --git a/packages/shade_protocol/src/lib.rs b/packages/shade_protocol/src/lib.rs index 2f91daea..97526952 100644 --- a/packages/shade_protocol/src/lib.rs +++ b/packages/shade_protocol/src/lib.rs @@ -45,8 +45,5 @@ pub use anyhow::Result as AnyResult; #[cfg(feature = "utils")] pub use utils::asset::Contract; -#[cfg(all(feature = "liquidity_book_impl", feature = "swap"))] -pub use liquidity_book::lb_libraries; - #[cfg(feature = "chrono")] pub use chrono; diff --git a/packages/shade_protocol/src/utils/liquidity_book/constants.rs b/packages/shade_protocol/src/utils/liquidity_book/constants.rs deleted file mode 100644 index c479ec96..00000000 --- a/packages/shade_protocol/src/utils/liquidity_book/constants.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! ### Liquidity Book Constants Library -//! Author: Kent -//! -//! Set of constants for Liquidity Book contracts. - -use ethnum::U256; -// use cosmwasm_std::Uint256; - -pub static SCALE_OFFSET: u8 = 128; - -// use this one for ethnum U256: -pub static SCALE: U256 = U256::from_words(1, 0); - -pub static PRECISION: u128 = 1_000_000_000_000_000_000; -pub static SQUARED_PRECISION: u128 = PRECISION * PRECISION; - -pub static MAX_FEE: u128 = 1_00_000_000_000_000_000; // 10% -pub static MAX_PROTOCOL_SHARE: u32 = 2_500; // 25% of the fee - -pub static BASIS_POINT_MAX: u32 = 10_000;