From 34fd9b856a2abd2a4378a0a163a6a405f12c89f1 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 +- .../liquidity_book/lb_factory/src/contract.rs | 69 ++++----- .../liquidity_book/lb_factory/src/error.rs | 21 ++- .../liquidity_book/lb_factory/src/state.rs | 8 +- .../liquidity_book/lb_factory/src/types.rs | 2 +- contracts/liquidity_book/lb_pair/Cargo.toml | 23 +-- .../liquidity_book/lb_pair/src/contract.rs | 62 +++----- contracts/liquidity_book/lb_pair/src/error.rs | 21 ++- .../liquidity_book/lb_pair/src/execute.rs | 56 +++---- .../liquidity_book/lb_pair/src/helper.rs | 29 ++-- contracts/liquidity_book/lb_pair/src/query.rs | 39 ++--- contracts/liquidity_book/lb_pair/src/state.rs | 20 +-- .../liquidity_book/lb_staking/Cargo.toml | 28 ++-- .../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 | 16 +- .../router/src/bin/secretcli/main.rs | 2 +- contracts/liquidity_book/tests/Cargo.toml | 32 ++-- packages/lb_libraries/Cargo.toml | 18 +++ .../src}/bin_helper.rs | 53 ++++--- .../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 .../src}/types.rs | 24 ++- packages/shade_protocol/Cargo.toml | 2 + .../liquidity_book/lb_factory.rs | 19 +-- .../liquidity_book/lb_libraries/transfer.rs | 108 ------------- .../lb_libraries/viewing_keys.rs | 112 -------------- .../liquidity_book/lb_pair.rs | 13 +- .../liquidity_book/lb_staking.rs | 32 ++-- .../liquidity_book/lb_token.rs | 19 ++- .../contract_interfaces/liquidity_book/mod.rs | 2 - packages/shade_protocol/src/lib.rs | 3 - .../src/utils/liquidity_book/constants.rs | 20 --- 69 files changed, 579 insertions(+), 1049 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%) rename packages/{shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries => lb_libraries/src}/types.rs (71%) 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/viewing_keys.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/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..f27544bb 100644 --- a/contracts/liquidity_book/lb_factory/src/state.rs +++ b/contracts/liquidity_book/lb_factory/src/state.rs @@ -1,10 +1,10 @@ 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}, @@ -56,9 +56,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..f325f780 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 lb_libraries::types::{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/contract.rs b/contracts/liquidity_book/lb_pair/src/contract.rs index 972254db..4313ce71 100644 --- a/contracts/liquidity_book/lb_pair/src/contract.rs +++ b/contracts/liquidity_book/lb_pair/src/contract.rs @@ -1,39 +1,22 @@ 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, + 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, - }, + swap::core::ViewingKey, }; use std::vec; @@ -185,17 +168,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..83535857 100644 --- a/contracts/liquidity_book/lb_pair/src/execute.rs +++ b/contracts/liquidity_book/lb_pair/src/execute.rs @@ -1,50 +1,36 @@ +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, MintArrays}, +}; 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}, - }, }; -use crate::helper::*; - /// Swap tokens iterating over the bins until the entire amount is swapped. /// /// Token X will be swapped for token Y if `swap_for_y` is true, and token Y for token X if `swap_for_y` is false. diff --git a/contracts/liquidity_book/lb_pair/src/helper.rs b/contracts/liquidity_book/lb_pair/src/helper.rs index e16d6be1..7fe15f00 100644 --- a/contracts/liquidity_book/lb_pair/src/helper.rs +++ b/contracts/liquidity_book/lb_pair/src/helper.rs @@ -1,17 +1,18 @@ 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}, + c_std::{Addr, 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}, - }, + // TODO: sort out viewing key strategy + s_toolkit::snip20::{register_receive_msg, set_viewing_key_msg}, snip20, + swap::core::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 +33,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/query.rs b/contracts/liquidity_book/lb_pair/src/query.rs index e91b4604..ab91737d 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::*, @@ -23,20 +28,6 @@ use shade_protocol::{ 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}, - }, - oracle_helper::MAX_SAMPLE_LIFETIME, - price_helper::PriceHelper, - types::Bytes32, - }, Contract, }; use std::collections::HashSet; 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/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..71d23b42 100644 --- a/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs +++ b/contracts/liquidity_book/router/src/bin/secretcli/example_data.rs @@ -1,16 +1,8 @@ +use lb_libraries::types::{ContractImplementation, LBPair, LBPairInformation, 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, - TokenPair, + LiquidityParameters, RemoveLiquidity, RewardsDistribution, TokenPair, }, snip20::Snip20ReceiveMsg, swap::core::{TokenAmount, TokenType}, @@ -66,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/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..0e1b8ce4 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/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..7dcf1101 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,11 @@ use super::{ u256x256_math::{U256x256Math, U256x256MathError}, }, pair_parameter_helper::{PairParameters, PairParametersError}, - transfer::HandleMsg, - types::Bytes32, + types::{Bytes32, TokenType}, }; +use cosmwasm_std::{Addr, BankMsg, Coin, CosmosMsg, Uint128}; +use ethnum::U256; +use secret_toolkit::snip20::transfer_msg; #[derive(thiserror::Error, Debug)] pub enum BinError { @@ -356,7 +352,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. /// @@ -464,15 +461,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 +503,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) } @@ -533,8 +532,8 @@ impl BinHelper { 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/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs b/packages/lb_libraries/src/types.rs similarity index 71% rename from packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs rename to packages/lb_libraries/src/types.rs index a702af59..efad2ead 100644 --- a/packages/shade_protocol/src/contract_interfaces/liquidity_book/lb_libraries/types.rs +++ b/packages/lb_libraries/src/types.rs @@ -3,25 +3,33 @@ //! //! 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 cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, ContractInfo}; 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 use crate::math::{liquidity_configurations::LiquidityConfigurations, tree_math::TreeUint24}; +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 struct ContractImplementation { pub id: u64, pub code_hash: String, } +#[cw_serde] +pub enum TokenType { + CustomToken { + contract_addr: Addr, + token_code_hash: String, + }, + NativeToken { + denom: String, + }, +} + #[cw_serde] pub struct StaticFeeParameters { pub base_factor: u16, diff --git a/packages/shade_protocol/Cargo.toml b/packages/shade_protocol/Cargo.toml index d1a29e11..780620ad 100644 --- a/packages/shade_protocol/Cargo.toml +++ b/packages/shade_protocol/Cargo.toml @@ -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..1a8dc989 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,13 +1,10 @@ use super::lb_pair::{self, RewardsDistributionAlgorithm}; -use crate::{ - contract_interfaces::swap::core::TokenType, - lb_libraries::types::{ContractInstantiationInfo, LBPair, LBPairInformation}, - utils::asset::RawContract, -}; - use crate::utils::{ExecuteCallback, InstantiateCallback, Query}; +use crate::{contract_interfaces::swap::core::TokenType, utils::asset::RawContract}; use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::Addr; +use lb_libraries::types::{ContractImplementation, LBPair, LBPairInformation}; + pub use lb_pair::InstantiateMsg as LBPairInstantiateMsg; #[cw_serde] @@ -27,15 +24,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 +172,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/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..6f8bf151 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,13 @@ -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 InstantiateMsg { @@ -22,8 +17,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/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;