From cccc53761aabeee6d5ca52b1d6f7dad0bad99e10 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Wed, 10 Jul 2024 20:32:12 +0530 Subject: [PATCH 1/7] add: cleanup function for unused storage in AH contract --- bindings/src/account_history/msg/execute.rs | 5 +- .../src/action/execute/clean_up_storage.rs | 20 ++++++ .../src/action/mod.rs | 6 +- .../src/action/sudo/update_account_chain.rs | 61 +------------------ .../src/entry_point/execute.rs | 15 ++--- .../src/entry_point/mod.rs | 2 - .../src/entry_point/sudo.rs | 28 --------- .../src/tests/get_all_pools.rs | 4 +- .../get_eden_boost_earn_program_details.rs | 4 +- .../tests/get_eden_earn_program_details.rs | 4 +- .../src/tests/get_elys_earn_program_detail.rs | 4 +- .../src/tests/get_liquid_assets.rs | 4 +- .../src/tests/get_rewards.rs | 4 +- .../src/tests/get_staked_assets.rs | 4 +- .../tests/get_usdc_earn_program_details.rs | 4 +- .../src/tests/update_accounts.rs | 4 +- .../src/tests/week_snapshots.rs | 4 +- 17 files changed, 49 insertions(+), 128 deletions(-) create mode 100644 contracts/account-history-contract/src/action/execute/clean_up_storage.rs delete mode 100644 contracts/account-history-contract/src/entry_point/sudo.rs diff --git a/bindings/src/account_history/msg/execute.rs b/bindings/src/account_history/msg/execute.rs index 0588fadf..317e85d7 100644 --- a/bindings/src/account_history/msg/execute.rs +++ b/bindings/src/account_history/msg/execute.rs @@ -12,10 +12,7 @@ pub enum ExecuteMsg { delete_epoch: Option, }, UpdateAccount {}, - CleanHistory { - limit: u64, - }, - CleanOldHistory { + CleanStorage { limit: u64, }, } diff --git a/contracts/account-history-contract/src/action/execute/clean_up_storage.rs b/contracts/account-history-contract/src/action/execute/clean_up_storage.rs new file mode 100644 index 00000000..84017b23 --- /dev/null +++ b/contracts/account-history-contract/src/action/execute/clean_up_storage.rs @@ -0,0 +1,20 @@ +use cosmwasm_std::{DepsMut, Response, StdResult}; + +use crate::states::{HISTORY, OLD_HISTORY_2, USER_ADDRESS_QUEUE}; +use elys_bindings::{ElysMsg, ElysQuery}; + +pub fn clean_up_storage(deps: &mut DepsMut, limit: u64) -> StdResult> { + // Delete history values + for _ in 0..limit { + if let Some(val) = HISTORY.first(deps.storage)? { + HISTORY.remove(deps.storage, &val.0); + } + if let Some(val) = OLD_HISTORY_2.first(deps.storage)? { + OLD_HISTORY_2.remove(deps.storage, &val.0); + } + if USER_ADDRESS_QUEUE.front(deps.storage).is_ok() { + USER_ADDRESS_QUEUE.pop_front(deps.storage)?; + } + } + Ok(Response::default()) +} diff --git a/contracts/account-history-contract/src/action/mod.rs b/contracts/account-history-contract/src/action/mod.rs index 241f5943..1509b16c 100644 --- a/contracts/account-history-contract/src/action/mod.rs +++ b/contracts/account-history-contract/src/action/mod.rs @@ -1,8 +1,6 @@ pub mod sudo { mod update_account_chain; - pub use update_account_chain::{ - clean_old_history, clean_up_history, update_account, update_account_chain, - }; + pub use update_account_chain::update_account_chain; } pub mod query { @@ -70,5 +68,7 @@ pub mod query { pub mod execute { mod add_user_address_to_queue; + mod clean_up_storage; pub use add_user_address_to_queue::add_user_address_to_queue; + pub use clean_up_storage::clean_up_storage; } diff --git a/contracts/account-history-contract/src/action/sudo/update_account_chain.rs b/contracts/account-history-contract/src/action/sudo/update_account_chain.rs index 289aedf3..cc4f4cca 100644 --- a/contracts/account-history-contract/src/action/sudo/update_account_chain.rs +++ b/contracts/account-history-contract/src/action/sudo/update_account_chain.rs @@ -1,6 +1,4 @@ -use chrono::NaiveDateTime; -use cosmwasm_std::{DepsMut, Env, Response, StdResult, Timestamp}; -use cw_utils::Expiration; +use cosmwasm_std::{DepsMut, Env, Response, StdResult}; use crate::{ states::{HISTORY, METADATA, OLD_HISTORY_2, PROCESSED_ACCOUNT_PER_BLOCK, USER_ADDRESS_QUEUE}, @@ -79,60 +77,3 @@ pub fn update_account_chain(deps: DepsMut, env: Env) -> StdResult, - env: Env, - limit: u64, -) -> StdResult> { - let generator = AccountSnapshotGenerator::new(&deps.as_ref())?; - let block_info = env.block; - let expiration = match generator.expiration { - Expiration::AtHeight(h) => Timestamp::from_seconds(h * 3), // since a block is created every 3 seconds - Expiration::AtTime(t) => t.clone(), - _ => panic!("never expire"), - }; - - if expiration > block_info.time { - return Ok(Response::default()); - } - - let expired_date = NaiveDateTime::from_timestamp_opt( - block_info - .time - .minus_seconds(expiration.seconds()) - .seconds() as i64, - 0, - ) - .expect("Failed to convert block time to date") - .format("%Y-%m-%d") - .to_string(); - - // Delete limit values - for _ in 0..limit { - if let Some(val) = HISTORY.first(deps.storage)? { - let date_part = &val.0[0..10]; - if date_part < expired_date.as_str() { - HISTORY.remove(deps.storage, &val.0); - } - } else { - break; - } - } - Ok(Response::default()) -} - -pub fn clean_old_history( - deps: &mut DepsMut, - limit: u64, -) -> StdResult> { - // Delete limit values - for _ in 0..limit { - if let Some(val) = OLD_HISTORY_2.first(deps.storage)? { - OLD_HISTORY_2.remove(deps.storage, &val.0); - } else { - break; - } - } - Ok(Response::default()) -} diff --git a/contracts/account-history-contract/src/entry_point/execute.rs b/contracts/account-history-contract/src/entry_point/execute.rs index 9398f8b9..09842ec7 100644 --- a/contracts/account-history-contract/src/entry_point/execute.rs +++ b/contracts/account-history-contract/src/entry_point/execute.rs @@ -3,8 +3,8 @@ use elys_bindings::{account_history::msg::ExecuteMsg, ElysMsg, ElysQuery}; use crate::{ action::{ - execute::add_user_address_to_queue, - sudo::{clean_old_history, clean_up_history, update_account_chain}, + execute::{add_user_address_to_queue, clean_up_storage}, + sudo::update_account_chain, }, states::{ DELETE_EPOCH, DELETE_OLD_DATA_ENABLED, PARAMS_ADMIN, PROCESSED_ACCOUNT_PER_BLOCK, @@ -67,18 +67,11 @@ pub fn execute( let resp = update_account_chain(deps, env)?; Ok(resp) } - ExecuteMsg::CleanHistory { limit } => { + ExecuteMsg::CleanStorage { limit } => { if info.sender != PARAMS_ADMIN.load(deps.storage)? { return Err(StdError::generic_err("Unauthorized")); } - let resp = clean_up_history(&mut deps, env, limit)?; - Ok(resp) - } - ExecuteMsg::CleanOldHistory { limit } => { - if info.sender != PARAMS_ADMIN.load(deps.storage)? { - return Err(StdError::generic_err("Unauthorized")); - } - let resp = clean_old_history(&mut deps, limit)?; + let resp = clean_up_storage(&mut deps, limit)?; Ok(resp) } } diff --git a/contracts/account-history-contract/src/entry_point/mod.rs b/contracts/account-history-contract/src/entry_point/mod.rs index db29648a..41977caa 100644 --- a/contracts/account-history-contract/src/entry_point/mod.rs +++ b/contracts/account-history-contract/src/entry_point/mod.rs @@ -2,10 +2,8 @@ mod execute; mod instantiate; mod migrate; mod query; -mod sudo; pub use execute::execute; pub use instantiate::instantiate; pub use migrate::migrate; pub use query::query; -pub use sudo::sudo; diff --git a/contracts/account-history-contract/src/entry_point/sudo.rs b/contracts/account-history-contract/src/entry_point/sudo.rs deleted file mode 100644 index 4a41fc18..00000000 --- a/contracts/account-history-contract/src/entry_point/sudo.rs +++ /dev/null @@ -1,28 +0,0 @@ -use crate::msg::SudoMsg; -use crate::states::{DELETE_EPOCH, DELETE_OLD_DATA_ENABLED}; -use crate::{ - action::sudo::{clean_old_history, clean_up_history, update_account}, - states::UPDATE_ACCOUNT_ENABLED, -}; -use cosmwasm_std::{entry_point, DepsMut, Env, Response, StdError, StdResult}; -use elys_bindings::{ElysMsg, ElysQuery}; - -#[cfg_attr(not(feature = "library"), entry_point)] -pub fn sudo(mut deps: DepsMut, env: Env, msg: SudoMsg) -> StdResult> { - match msg { - SudoMsg::ClockEndBlock {} => { - if UPDATE_ACCOUNT_ENABLED.load(deps.storage)? == false { - return Err(StdError::generic_err("Update account is disabled")); - } - - let epoch = DELETE_EPOCH.load(deps.storage)?; - if DELETE_OLD_DATA_ENABLED.load(deps.storage)? == true && env.block.height % epoch == 0 - { - clean_old_history(&mut deps, epoch)?; - clean_up_history(&mut deps, env.clone(), epoch)?; - } - - update_account(deps, env) - } - } -} diff --git a/contracts/account-history-contract/src/tests/get_all_pools.rs b/contracts/account-history-contract/src/tests/get_all_pools.rs index c1957470..49c018f4 100644 --- a/contracts/account-history-contract/src/tests/get_all_pools.rs +++ b/contracts/account-history-contract/src/tests/get_all_pools.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -258,7 +258,7 @@ fn get_all_pools() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs index b188c0f9..c5221a20 100644 --- a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -236,7 +236,7 @@ fn get_eden_boost_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs index f521428f..db3c4a48 100644 --- a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -236,7 +236,7 @@ fn get_eden_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs b/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs index 9fce1ac3..f04a9275 100644 --- a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs +++ b/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -235,7 +235,7 @@ fn get_elys_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_liquid_assets.rs b/contracts/account-history-contract/src/tests/get_liquid_assets.rs index 8ec7fb13..e5b5013d 100644 --- a/contracts/account-history-contract/src/tests/get_liquid_assets.rs +++ b/contracts/account-history-contract/src/tests/get_liquid_assets.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::tests::get_liquid_assets::query_resp::{GetLiquidAssetsResp, LiquidAsset}; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -408,7 +408,7 @@ fn get_liquid_assets() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_rewards.rs b/contracts/account-history-contract/src/tests/get_rewards.rs index b5cba5f1..6107e951 100644 --- a/contracts/account-history-contract/src/tests/get_rewards.rs +++ b/contracts/account-history-contract/src/tests/get_rewards.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -218,7 +218,7 @@ fn get_rewards() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_staked_assets.rs b/contracts/account-history-contract/src/tests/get_staked_assets.rs index 7dad9124..63b5d870 100644 --- a/contracts/account-history-contract/src/tests/get_staked_assets.rs +++ b/contracts/account-history-contract/src/tests/get_staked_assets.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::tests::get_staked_assets::query_resp::StakedAssetsResponse; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -524,7 +524,7 @@ fn get_staked_assets() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs index a3b5a726..f1d7c179 100644 --- a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -235,7 +235,7 @@ fn get_usdc_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/update_accounts.rs b/contracts/account-history-contract/src/tests/update_accounts.rs index 52acf446..91d3fadb 100644 --- a/contracts/account-history-contract/src/tests/update_accounts.rs +++ b/contracts/account-history-contract/src/tests/update_accounts.rs @@ -17,7 +17,7 @@ use trade_shield_contract::msg as trade_shield_msg; use trade_shield_contract::types::{OrderPrice, SpotOrderType}; use crate::entry_point::instantiate; -use crate::entry_point::{execute, query, sudo}; +use crate::entry_point::{execute, query}; use anyhow::{bail, Error, Result as AnyResult}; use cosmwasm_std::{to_json_binary, Empty, Int128, SignedDecimal, StdError, Uint128}; use cw_multi_test::{AppResponse, Module}; @@ -365,7 +365,7 @@ fn history() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/week_snapshots.rs b/contracts/account-history-contract/src/tests/week_snapshots.rs index 49ac5fde..23984d12 100644 --- a/contracts/account-history-contract/src/tests/week_snapshots.rs +++ b/contracts/account-history-contract/src/tests/week_snapshots.rs @@ -3,7 +3,7 @@ use std::vec; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query, sudo}, + entry_point::{execute, query}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -361,7 +361,7 @@ fn get_portfolio() { .unwrap(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); + let code = ContractWrapper::new(execute, instantiate, query); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. From 7952e88635fb20d7a1251a2736ca75ba2506b86b Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Thu, 11 Jul 2024 11:20:51 +0530 Subject: [PATCH 2/7] feat: remove testcase --- contracts/account-history-contract/src/lib.rs | 3 - .../src/tests/get_all_pools.rs | 358 -------- .../get_eden_boost_earn_program_details.rs | 295 ------ .../tests/get_eden_earn_program_details.rs | 308 ------- .../src/tests/get_elys_earn_program_detail.rs | 304 ------- .../src/tests/get_liquid_assets.rs | 541 ----------- .../src/tests/get_rewards.rs | 287 ------ .../src/tests/get_staked_assets.rs | 850 ------------------ .../tests/get_usdc_earn_program_details.rs | 305 ------- .../account-history-contract/src/tests/mod.rs | 10 - .../src/tests/update_accounts.rs | 465 ---------- .../src/tests/week_snapshots.rs | 846 ----------------- 12 files changed, 4572 deletions(-) delete mode 100644 contracts/account-history-contract/src/tests/get_all_pools.rs delete mode 100644 contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs delete mode 100644 contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs delete mode 100644 contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs delete mode 100644 contracts/account-history-contract/src/tests/get_liquid_assets.rs delete mode 100644 contracts/account-history-contract/src/tests/get_rewards.rs delete mode 100644 contracts/account-history-contract/src/tests/get_staked_assets.rs delete mode 100644 contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs delete mode 100644 contracts/account-history-contract/src/tests/mod.rs delete mode 100644 contracts/account-history-contract/src/tests/update_accounts.rs delete mode 100644 contracts/account-history-contract/src/tests/week_snapshots.rs diff --git a/contracts/account-history-contract/src/lib.rs b/contracts/account-history-contract/src/lib.rs index c2d0a800..1705184a 100644 --- a/contracts/account-history-contract/src/lib.rs +++ b/contracts/account-history-contract/src/lib.rs @@ -10,6 +10,3 @@ mod action; mod error; mod states; mod types; - -#[cfg(test)] -mod tests; diff --git a/contracts/account-history-contract/src/tests/get_all_pools.rs b/contracts/account-history-contract/src/tests/get_all_pools.rs deleted file mode 100644 index 49c018f4..00000000 --- a/contracts/account-history-contract/src/tests/get_all_pools.rs +++ /dev/null @@ -1,358 +0,0 @@ -use std::collections::HashMap; -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coin, coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::types::CoinValue; -use elys_bindings::query_resp::{ - DelegationDelegatorReward, EstakingRewardsResponse, MasterchefUserPendingRewardData, - MasterchefUserPendingRewardResponse, PoolApr, PoolFilterType, PoolResp, QueryEarnPoolResponse, - QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::{BalanceAvailable, PoolAsset}; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ("user", "uedenb") => BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("21798000").unwrap(), - }, - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229342748").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmEarnMiningPoolAll { .. } => { - let resp = QueryEarnPoolResponse { - pools: Some(vec![PoolResp { - pool_id: 1, - apr: Some(PoolApr { pool_id: 1, ..Default::default() }), - assets: vec![PoolAsset { - token: Coin { - denom: "uelys".to_string(), - amount: Uint128::new(100), - }, - weight: Uint128::new(1), - usd_value: Some(Decimal::from_str("353.08010067676894").unwrap()), - }], - pool_ratio: "".to_string(), - current_pool_ratio: None, - current_pool_ratio_string: None, - rewards_apr: Decimal::one(), - rewards_usd: Decimal::from_str("10").unwrap(), - reward_coins: vec![Coin { - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - amount: Uint128::new(10), - }], - fiat_rewards: None, - borrow_apr: Decimal::from_str("2").unwrap(), - leverage_lp: Decimal::zero(), - perpetual: Decimal::zero(), - lp_token_price: None, - tvl: Decimal::zero(), - total_shares: Coin { denom: "uelys".to_string(), amount: Uint128::new(1000) }, - share_usd_price: Some(Decimal::from_str("3530.8010067676894").unwrap()), - swap_fee: Decimal::from_str("0.1").unwrap(), - fee_denom: "uelys".to_string(), - use_oracle: Some(true), - is_leveragelp: Some(true), - }]), - }; - Ok(to_json_binary(&resp)?) - } - - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_all_pools() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: QueryEarnPoolResponse = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetLiquidityPools { - pool_ids: Some(vec![1u64]), - filter_type: PoolFilterType::FilterAll, - pagination: None, - }, - ) - .unwrap(); - - let mut current_pool_ratio = HashMap::new(); - current_pool_ratio.insert("uelys".to_string(), Decimal::one()); - - let mut current = HashMap::new(); - current.insert("uelys".to_string(), Decimal::one()); - - let expected = QueryEarnPoolResponse { - pools: Some( - [PoolResp { - pool_id: 1, - apr: Some(PoolApr { - pool_id: 1, - ..Default::default() - }), - assets: [PoolAsset { - token: coin(100, "uelys"), - weight: Uint128::one(), - usd_value: Some(Decimal::from_str("0.000353080100676768").unwrap()), - }] - .to_vec(), - pool_ratio: "".to_string(), - current_pool_ratio: Some(current), - current_pool_ratio_string: None, - rewards_apr: Decimal::one(), - rewards_usd: Decimal::from_str("10").unwrap(), - reward_coins: coins( - 10, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) - .to_vec(), - fiat_rewards: Some( - [CoinValue { - denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - amount_token: Decimal::from_str("0.00001").unwrap(), - price: Decimal::one(), - amount_usd: Decimal::from_str("0.00001").unwrap(), - }] - .to_vec(), - ), - borrow_apr: Decimal::from_str("2").unwrap(), - leverage_lp: Decimal::zero(), - perpetual: Decimal::zero(), - lp_token_price: None, - tvl: Decimal::zero(), - total_shares: coin(1000, "uelys"), - share_usd_price: Some(Decimal::zero()), - swap_fee: Decimal::from_str("0.1").unwrap(), - fee_denom: "uelys".to_string(), - use_oracle: Some(true), - is_leveragelp: Some(true), - }] - .to_vec(), - ), - }; - - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs deleted file mode 100644 index c5221a20..00000000 --- a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs +++ /dev/null @@ -1,295 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::earn::GetEdenBoostEarnProgramResp; -use elys_bindings::account_history::types::earn_detail::earn_detail::AprEdenBoost; -use elys_bindings::account_history::types::earn_program::EdenBoostEarnProgram; -use elys_bindings::account_history::types::CoinValue; -use elys_bindings::query_resp::{ - BalanceBorrowed, DelegationDelegatorReward, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, - QueryStableStakeAprResponse, StakedAvailable, Validator, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ("user", "uedenb") => BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("21798000").unwrap(), - }, - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229342748").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedBalanceOfDenom { .. } => { - let resp = StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::StableStakeBalanceOfBorrow {} => { - let resp = BalanceBorrowed { - usd_amount: Decimal::from_atomics(Uint128::new(3265035180871), 10).unwrap(), - percentage: Decimal::from_atomics(Uint128::new(0000238391578776388), 18) - .unwrap(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_eden_boost_earn_program_details() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: GetEdenBoostEarnProgramResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetEdenBoostEarnProgramDetails { - address: "user".to_string(), - }, - ) - .unwrap(); - - let expected = GetEdenBoostEarnProgramResp { - data: EdenBoostEarnProgram { - bonding_period: 0, - apr: AprEdenBoost { - uusdc: Uint128::zero(), - ueden: Uint128::zero(), - }, - available: Some(Uint128::new(21798000)), - staked: Some(Uint128::new(100120000000)), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_str("0.000121").unwrap(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - amount_usd: Decimal::from_str("0.00042722692181889").unwrap(), - }]), - }, - }; - - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs deleted file mode 100644 index db3c4a48..00000000 --- a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs +++ /dev/null @@ -1,308 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::earn::GetEdenEarnProgramResp; -use elys_bindings::account_history::types::earn_program::EdenEarnProgram; -use elys_bindings::account_history::types::{AprElys, CoinValue}; -use elys_bindings::query_resp::{ - BalanceBorrowed, DelegationDelegatorReward, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, - QueryStableStakeAprResponse, StakedAvailable, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ("user", "ueden") => BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("21798000").unwrap(), - }, - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229342748").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedBalanceOfDenom { .. } => { - let resp = StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::StableStakeBalanceOfBorrow {} => { - let resp = BalanceBorrowed { - usd_amount: Decimal::from_atomics(Uint128::new(3265035180871), 10).unwrap(), - percentage: Decimal::from_atomics(Uint128::new(0000238391578776388), 18) - .unwrap(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: "elysvaloper1gnmpr8vvslp3shcq6e922xr0uq4aa2w5gdzht0" - .to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_eden_earn_program_details() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: GetEdenEarnProgramResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetEdenEarnProgramDetails { - address: "user".to_string(), - }, - ) - .unwrap(); - - let expected = GetEdenEarnProgramResp { - data: EdenEarnProgram { - bonding_period: 0, - apr: AprElys { - uusdc: Uint128::zero(), - ueden: Uint128::zero(), - uedenb: Uint128::zero(), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("76.964400345522093541").unwrap(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::from_str("100130.012").unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_str("0.000121").unwrap(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - amount_usd: Decimal::from_str("0.00042722692181889").unwrap(), - }]), - vesting: BalanceAvailable { - amount: Uint128::from_str("100").unwrap(), - usd_amount: Decimal::from_str("100").unwrap(), - }, - vesting_details: Some(vec![]), - }, - }; - - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs b/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs deleted file mode 100644 index f04a9275..00000000 --- a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs +++ /dev/null @@ -1,304 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::earn::GetElysEarnProgramResp; -use elys_bindings::account_history::types::earn_program::ElysEarnProgram; -use elys_bindings::account_history::types::{AprElys, CoinValue}; -use elys_bindings::query_resp::{ - BalanceBorrowed, DelegationDelegatorReward, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, - QueryStableStakeAprResponse, StakedAvailable, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(1234), - usd_amount: Decimal::from_str("1234").unwrap(), - }, - ("user", "uelys") => BalanceAvailable { - amount: Uint128::new(45666543), - usd_amount: Decimal::from_str("45666543").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedBalanceOfDenom { .. } => { - let resp = StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::StableStakeBalanceOfBorrow {} => { - let resp = BalanceBorrowed { - usd_amount: Decimal::from_atomics(Uint128::new(3265035180871), 10).unwrap(), - percentage: Decimal::from_atomics(Uint128::new(0000238391578776388), 18) - .unwrap(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: "validator".to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_elys_earn_program_details() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: GetElysEarnProgramResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetElysEarnProgramDetails { - address: "user".to_string(), - }, - ) - .unwrap(); - - let expected = GetElysEarnProgramResp { - data: ElysEarnProgram { - bonding_period: 14, - apr: AprElys { - uusdc: Uint128::zero(), - ueden: Uint128::zero(), - uedenb: Uint128::zero(), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(45666543), - usd_amount: Decimal::from_str("161.239475999999978995").unwrap(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_str("0.000121").unwrap(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - amount_usd: Decimal::from_str("0.00042722692181889").unwrap(), - }]), - staked_positions: None, - unstaked_positions: None, - }, - }; - - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/get_liquid_assets.rs b/contracts/account-history-contract/src/tests/get_liquid_assets.rs deleted file mode 100644 index e5b5013d..00000000 --- a/contracts/account-history-contract/src/tests/get_liquid_assets.rs +++ /dev/null @@ -1,541 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::tests::get_liquid_assets::query_resp::{GetLiquidAssetsResp, LiquidAsset}; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coin, to_json_binary, Addr, Coin, DecCoin, Decimal, Decimal256, Empty, Int128, SignedDecimal, - StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::query_resp::{ - AmmSwapEstimationByDenomResponse, DelegationDelegatorReward, Entry, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, OracleAssetInfoResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::{BalanceAvailable, OracleAssetInfo, Price}; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { .. } => { - let resp = BalanceAvailable { - amount: Uint128::new(0), - usd_amount: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OracleAssetInfo { denom } => { - let resp = match denom.as_str() { - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "USDC".to_string(), - decimal: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display: "USDC".to_string(), - elys_ticker: "USDC".to_string(), - }, - } - } - "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "OSMO".to_string(), - decimal: 6, - denom: "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23".to_string(), - display: "OSMO".to_string(), - elys_ticker: "OSMO".to_string(), - }, - } - } - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "JUNO".to_string(), - decimal: 6, - denom: "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40".to_string(), - display: "JUNO".to_string(), - elys_ticker: "JUNO".to_string(), - }, - } - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "ATOM".to_string(), - decimal: 6, - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4".to_string(), - display: "ATOM".to_string(), - elys_ticker: "ATOM".to_string(), - }, - } - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmSwapEstimationByDenom { .. } => { - let resp = AmmSwapEstimationByDenomResponse { - in_route: None, - out_route: None, - spot_price: Decimal::from_str("3.5").unwrap(), - amount: Coin { - denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - amount: Uint128::new(100), - }, - swap_fee: SignedDecimal::one(), - discount: SignedDecimal::from_str("20").unwrap(), - available_liquidity: Coin { - denom: "uelys".to_string(), - amount: Uint128::new(100000), - }, - weight_balance_ratio: SignedDecimal::one(), - price_impact: SignedDecimal::zero(), - slippage: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_liquid_assets() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - vec![ - coin( - 21798000, - "ibc/0E1517E2771CA7C03F2ED3F9BAECCAEADF0BFD79B89679E834933BC0F179AD98", - ), - coin( - 5333229342748, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - coin( - 2704998, - "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", - ), - coin( - 594000000000200000, - "ibc/2FBCFC209420E6CECED6EE0BC599E74349759352CE953E27A6871BB3D84BC058", - ), - coin( - 1085352, - "ibc/326A89923D85047E6418A671FBACCAFA2686B01A16ED4A0AD92954FCE1485910", - ), - coin( - 168400000000000000, - "ibc/43881AB3B3D05FD9D3606D7F57CBE6EEEA89D18AC66AF9E2915ED43940E71CFD", - ), - coin( - 49765000, - "ibc/4DAE26570FD24ABA40E2BE4137E39D946C78B00B248D3F78B0919567C4371156", - ), - coin( - 9100000, - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40", - ), - coin( - 141000000000000000, - "ibc/E059CD828E5009D4CF03C4494BEA73749250287FC98DD46E19F9016B918BF49D", - ), - coin( - 37403942, - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4", - ), - coin( - 79979999999749000, - "ibc/FB22E35236996F6B0B1C9D407E8A379A7B1F4083F1960907A1622F022AE450E1", - ), - coin(45666543, "uelys"), - coin(45666543, "ueden"), - ], - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // Query the contract for the existing order. - let resp: GetLiquidAssetsResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetLiquidAssets { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - let mut expected: GetLiquidAssetsResp = GetLiquidAssetsResp { - liquid_assets: vec![ - LiquidAsset { - denom: "uelys".to_string(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - available_amount: Decimal::from_str("45.666543").unwrap(), - available_value: Decimal::from_str("161.239475999999978995").unwrap(), - in_order_amount: Decimal::zero(), - in_order_value: Decimal::zero(), - total_amount: Decimal::from_str("45.666543").unwrap(), - total_value: Decimal::from_str("161.239475999999978995").unwrap(), - }, - LiquidAsset { - denom: "ueden".to_string(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - available_amount: Decimal::from_str("45.666543").unwrap(), - available_value: Decimal::from_str("161.239475999999978995").unwrap(), - in_order_amount: Decimal::zero(), - in_order_value: Decimal::zero(), - total_amount: Decimal::from_str("45.666543").unwrap(), - total_value: Decimal::from_str("161.239475999999978995").unwrap(), - }, - LiquidAsset { - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" - .to_string(), - price: Decimal::from_str("9.02450744362719844").unwrap(), - available_amount: Decimal::from_str("37.403942").unwrap(), - available_value: Decimal::from_str("337.552153000000000072").unwrap(), - in_order_amount: Decimal::zero(), - in_order_value: Decimal::zero(), - total_amount: Decimal::from_str("37.403942").unwrap(), - total_value: Decimal::from_str("337.552153000000000072").unwrap(), - }, - LiquidAsset { - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - price: Decimal::one(), - available_amount: Decimal::from_str("5333229.342748").unwrap(), - available_value: Decimal::from_str("5333229.342748").unwrap(), - in_order_amount: Decimal::zero(), - in_order_value: Decimal::zero(), - total_amount: Decimal::from_str("5333229.342748").unwrap(), - total_value: Decimal::from_str("5333229.342748").unwrap(), - }, - ], - total_liquid_asset_balance: DecCoin::new( - Decimal256::zero(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - }; - - for i in expected.liquid_assets.iter() { - expected.total_liquid_asset_balance.amount += Decimal256::from(i.total_value.clone()); - } - - // test if the response is the same as the expected - assert_eq!(resp.liquid_assets.len(), expected.liquid_assets.len()); - - assert_eq!( - resp.liquid_assets - .iter() - .find(|l| l.denom.as_str() == "uelys") - .cloned(), - Some(expected.liquid_assets[0].clone()) - ); - assert_eq!( - resp.liquid_assets - .iter() - .find(|l| l.denom.as_str() == "ueden") - .cloned(), - Some(expected.liquid_assets[1].clone()) - ); - assert_eq!( - resp.liquid_assets - .iter() - .find(|l| l.denom.as_str() - == "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4") - .cloned(), - Some(expected.liquid_assets[2].clone()) - ); - assert_eq!( - resp.liquid_assets - .iter() - .find(|l| l.denom.as_str() - == "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65") - .cloned(), - Some(expected.liquid_assets[3].clone()) - ); - assert_eq!( - resp.total_liquid_asset_balance, - expected.total_liquid_asset_balance - ); -} diff --git a/contracts/account-history-contract/src/tests/get_rewards.rs b/contracts/account-history-contract/src/tests/get_rewards.rs deleted file mode 100644 index 6107e951..00000000 --- a/contracts/account-history-contract/src/tests/get_rewards.rs +++ /dev/null @@ -1,287 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::GetRewardsResp; -use elys_bindings::account_history::types::{CoinValue, Reward}; -use elys_bindings::query_resp::{ - DelegationDelegatorReward, EstakingRewardsResponse, MasterchefUserPendingRewardData, - MasterchefUserPendingRewardResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ("user", "uedenb") => BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("21798000").unwrap(), - }, - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229342748").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_rewards() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: GetRewardsResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetRewards { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - assert_eq!( - resp.rewards_map, - Reward { - usdc_usd: Decimal::zero(), - eden_usd: Decimal::from_str("0.000070616020135353").unwrap(), - eden_boost: Decimal::from_str("0.000121").unwrap(), - other_usd: Decimal::zero(), - total_usd: Decimal::from_str("0.000070616020135353").unwrap() - } - ); - - assert_eq!( - resp.rewards.contains(&CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_str("0.00002").unwrap(), - price: Decimal::from_str("3.5308010067676894").unwrap(), - amount_usd: Decimal::from_str("0.000070616020135353").unwrap(), - }), - true - ); - assert_eq!( - resp.rewards.contains(&CoinValue { - denom: "uedenb".to_string(), - amount_token: Decimal::from_str("0.000121").unwrap(), - price: Decimal::zero(), - amount_usd: Decimal::zero(), - }), - true - ); -} diff --git a/contracts/account-history-contract/src/tests/get_staked_assets.rs b/contracts/account-history-contract/src/tests/get_staked_assets.rs deleted file mode 100644 index 63b5d870..00000000 --- a/contracts/account-history-contract/src/tests/get_staked_assets.rs +++ /dev/null @@ -1,850 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::tests::get_staked_assets::query_resp::StakedAssetsResponse; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, DecCoin, Decimal, Decimal256, Empty, Int128, StdError, - Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::StakeAssetBalanceBreakdown; -use elys_bindings::account_history::types::earn_detail::earn_detail::AprEdenBoost; -use elys_bindings::account_history::types::earn_program::{ - EdenBoostEarnProgram, EdenEarnProgram, ElysEarnProgram, UsdcEarnProgram, -}; -use elys_bindings::account_history::types::{ - AprElys, AprUsdc, CoinValue, QueryAprResponse, StakedAssets, -}; -use elys_bindings::query_resp::{ - BalanceBorrowed, DelegationDelegatorReward, Entry, EstakingRewardsResponse, Lockup, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, QueryAprsResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, - QueryStakedPositionResponse, QueryUnstakedPositionResponse, QueryVestingInfoResponse, - StakedAvailable, Validator, -}; -use elys_bindings::types::{ - BalanceAvailable, Price, StakedPosition, StakingValidator, UnstakedPosition, -}; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedPositions { delegator_address } => { - let resp = match delegator_address.as_str() { - "user" => QueryStakedPositionResponse { - staked_position: Some(vec![StakedPosition { - id: "2".to_string(), - validator: StakingValidator { - id: Some(String::from("1")), - address: "elysvaloper1ng8sen6z5xzcfjtyrsedpe43hglymq040x3cpw" - .to_string(), - name: "nirvana".to_string(), - voting_power: Decimal::from_str("25.6521469796402094").unwrap(), - commission: Decimal::from_str("0.1").unwrap(), - }, - staked: BalanceAvailable { - amount: Uint128::new(10000000), - usd_amount: Decimal::from_str("35.308010067676894").unwrap(), - }, - }]), - }, - _ => return Err(Error::new(StdError::not_found(delegator_address))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentUnStakedPositions { delegator_address } => { - let resp = match delegator_address.as_str() { - "user" => QueryUnstakedPositionResponse { - unstaked_position: Some(vec![UnstakedPosition { - id: "1".to_string(), - validator: StakingValidator { - id: Some(String::from("1")), - address: "elysvaloper1ng8sen6z5xzcfjtyrsedpe43hglymq040x3cpw" - .to_string(), - name: "nirvana".to_string(), - voting_power: Decimal::from_str("25.6521469796402094").unwrap(), - commission: Decimal::from_str("0.1").unwrap(), - }, - remaining_time: 1707328694, - unstaked: BalanceAvailable { - amount: Uint128::new(100038144098), - usd_amount: Decimal::from_str("353214.779896389585407707").unwrap(), - }, - }]), - }, - _ => return Err(Error::new(StdError::not_found(delegator_address))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ( - "user", - "ibc/0E1517E2771CA7C03F2ED3F9BAECCAEADF0BFD79B89679E834933BC0F179AD98", - ) => BalanceAvailable { - amount: Uint128::new(21798000), - usd_amount: Decimal::from_str("21798000").unwrap(), - }, - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229342748").unwrap(), - }, - ( - "user", - "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", - ) => BalanceAvailable { - amount: Uint128::new(2704998), - usd_amount: Decimal::from_str("2704998").unwrap(), - }, - ( - "user", - "ibc/2FBCFC209420E6CECED6EE0BC599E74349759352CE953E27A6871BB3D84BC058", - ) => BalanceAvailable { - amount: Uint128::new(594000000000200000), - usd_amount: Decimal::from_str("594000000000200000").unwrap(), - }, - ( - "user", - "ibc/326A89923D85047E6418A671FBACCAFA2686B01A16ED4A0AD92954FCE1485910", - ) => BalanceAvailable { - amount: Uint128::new(1085352), - usd_amount: Decimal::from_str("1085352").unwrap(), - }, - ( - "user", - "ibc/43881AB3B3D05FD9D3606D7F57CBE6EEEA89D18AC66AF9E2915ED43940E71CFD", - ) => BalanceAvailable { - amount: Uint128::new(168400000000000000), - usd_amount: Decimal::from_str("168400000000000000").unwrap(), - }, - ( - "user", - "ibc/4DAE26570FD24ABA40E2BE4137E39D946C78B00B248D3F78B0919567C4371156", - ) => BalanceAvailable { - amount: Uint128::new(49765000), - usd_amount: Decimal::from_str("49765000").unwrap(), - }, - ( - "user", - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40", - ) => BalanceAvailable { - amount: Uint128::new(9100000), - usd_amount: Decimal::from_str("9100000").unwrap(), - }, - ( - "user", - "ibc/E059CD828E5009D4CF03C4494BEA73749250287FC98DD46E19F9016B918BF49D", - ) => BalanceAvailable { - amount: Uint128::new(141000000000000000), - usd_amount: Decimal::from_str("141000000000000000").unwrap(), - }, - ( - "user", - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4", - ) => BalanceAvailable { - amount: Uint128::new(37403942), - usd_amount: Decimal::from_str("37403942").unwrap(), - }, - ( - "user", - "ibc/FB22E35236996F6B0B1C9D407E8A379A7B1F4083F1960907A1622F022AE450E1", - ) => BalanceAvailable { - amount: Uint128::new(79979999999749000), - usd_amount: Decimal::from_str("79979999999749000").unwrap(), - }, - ("user", "uelys") => BalanceAvailable { - amount: Uint128::new(45666543), - usd_amount: Decimal::from_str("45666543").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedBalanceOfDenom { denom, .. } => { - let resp: StakedAvailable = match denom.as_str() { - "uusdc" => StakedAvailable { - usd_amount: Decimal::zero(), - amount: Uint128::zero(), - lockups: None, - }, - "uelys" => StakedAvailable { - usd_amount: Decimal::from_str("35.308010067676894").unwrap(), - amount: Uint128::new(10000000), - lockups: Some(vec![]), - }, - "ueden" => StakedAvailable { - usd_amount: Decimal::from_str("9136.339725178804921781").unwrap(), - amount: Uint128::new(2587611057), - lockups: Some(vec![Lockup { - amount: Int128::new(5200770174), - // use now time - unlock_timestamp: block.time.seconds(), - }]), - }, - "uedenb" => StakedAvailable { - usd_amount: Decimal::zero(), - amount: Uint128::zero(), - lockups: None, - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::StableStakeBalanceOfBorrow {} => { - let resp = BalanceBorrowed { - usd_amount: Decimal::from_str("204000000001").unwrap(), - percentage: Decimal::one(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::IncentiveApr { - withdraw_type, - denom, - } => { - let resp: QueryAprResponse = match (withdraw_type, denom.as_str()) { - (1, "uusdc") => QueryAprResponse { - apr: Uint128::new(100), - }, - (1, "ueden") => QueryAprResponse { - apr: Uint128::new(168), - }, - (4, "uusdc") => QueryAprResponse { - apr: Uint128::zero(), - }, - (4, "ueden") => QueryAprResponse { - apr: Uint128::new(29), - }, - (3, "uusdc") => QueryAprResponse { - apr: Uint128::zero(), - }, - (3, "ueden") => QueryAprResponse { - apr: Uint128::new(29), - }, - (3, "uedenb") => QueryAprResponse { - apr: Uint128::new(100), - }, - (2, "uusdc") => QueryAprResponse { - apr: Uint128::zero(), - }, - (2, "ueden") => QueryAprResponse { - apr: Uint128::new(29), - }, - (2, "uedenb") => QueryAprResponse { - apr: Uint128::new(100), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::IncentiveAprs {} => Ok(to_json_binary(&QueryAprsResponse { - usdc_apr_usdc: Uint128::new(100), - usdc_apr_edenb: Uint128::zero(), - usdc_apr_eden: Uint128::zero(), - usdc_apr_elys: Uint128::zero(), - eden_apr_usdc: Uint128::new(168), - eden_apr_edenb: Uint128::new(29), - eden_apr_elys: Uint128::new(29), - eden_apr_eden: Uint128::new(29), - edenb_apr_eden: Uint128::new(100), - edenb_apr_elys: Uint128::new(100), - })?), - ElysQuery::CommitmentVestingInfo { .. } => { - let resp = QueryVestingInfoResponse { - vesting: BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - vesting_details: Some(vec![]), - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_staked_assets() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 200__000_000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // Query the contract for the existing order. - let resp: StakedAssetsResponse = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetStakedAssets { - user_address: Some("user".to_string()), - }, - ) - .unwrap(); - - let balance_break_down = StakeAssetBalanceBreakdown { - vesting: Decimal::zero(), - unstaking: vec![UnstakedPosition { - id: "1".to_string(), - validator: StakingValidator { - id: Some(String::from("1")), - address: "elysvaloper1ng8sen6z5xzcfjtyrsedpe43hglymq040x3cpw".to_string(), - name: "nirvana".to_string(), - voting_power: Decimal::from_str("25.6521469796402094").unwrap(), - commission: Decimal::from_str("0.1").unwrap(), - }, - remaining_time: 1707328694, - unstaked: BalanceAvailable { - amount: Uint128::new(100038144098), - usd_amount: Decimal::from_str("353214.779896389585407707").unwrap(), - }, - }] - .iter() - .fold(Decimal::zero(), |acc, item| { - acc.checked_add(item.unstaked.usd_amount) - .unwrap_or_default() - }), - staked: Decimal::from_str("9171.647735246481815781").unwrap(), - }; - - let expected: StakedAssetsResponse = StakedAssetsResponse { - total_staked_balance: DecCoin::new( - Decimal256::from_str("9171.647735246481815781").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - ), - total_balance: balance_break_down.total(), - balance_break_down, - staked_assets: StakedAssets { - eden_boost_earn_program: EdenBoostEarnProgram { - bonding_period: 0, - apr: AprEdenBoost { - uusdc: Uint128::zero(), - ueden: Uint128::new(29), - }, - available: Some(Uint128::zero()), - staked: Some(Uint128::zero()), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_str("0.000121").unwrap(), - price: Decimal::from_atomics(Uint128::new(35308010067676894), 16).unwrap(), - amount_usd: Decimal::from_str("0.00042722692181889").unwrap(), - }]), - }, - eden_earn_program: EdenEarnProgram { - bonding_period: 0, - apr: AprElys { - uusdc: Uint128::zero(), - ueden: Uint128::new(29), - uedenb: Uint128::new(100), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(0), - usd_amount: Decimal::zero(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::from_str("9136.339725178804921781").unwrap(), - amount: Uint128::new(2587611057), - lockups: Some(vec![Lockup { - amount: Int128::new(5200770174), - unlock_timestamp: 1571797419, - }]), - }), - rewards: Some(vec![]), - vesting: BalanceAvailable { - amount: Uint128::from_str("0").unwrap(), - usd_amount: Decimal::from_str("0").unwrap(), - }, - vesting_details: Some(vec![]), - }, - elys_earn_program: ElysEarnProgram { - bonding_period: 14, - apr: AprElys { - uusdc: Uint128::zero(), - ueden: Uint128::new(29), - uedenb: Uint128::new(100), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(45666543), - usd_amount: Decimal::from_str("161.239475999999978995").unwrap(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::from_str("35.308010067676894").unwrap(), - amount: Uint128::new(10000000), - lockups: Some(vec![]), - }), - rewards: Some(vec![]), - staked_positions: Some(vec![StakedPosition { - id: "2".to_string(), - validator: StakingValidator { - id: Some("1".to_string()), - address: "elysvaloper1ng8sen6z5xzcfjtyrsedpe43hglymq040x3cpw".to_string(), - name: "nirvana".to_string(), - voting_power: Decimal::from_str("25.6521469796402094").unwrap(), - commission: Decimal::from_str("0.1").unwrap(), - }, - staked: BalanceAvailable { - amount: Uint128::from_str("10000000").unwrap(), - usd_amount: Decimal::from_str("35.308010067676894").unwrap(), - }, - }]), - unstaked_positions: Some(vec![UnstakedPosition { - id: "1".to_string(), - validator: StakingValidator { - id: Some("1".to_string()), - address: "elysvaloper1ng8sen6z5xzcfjtyrsedpe43hglymq040x3cpw".to_string(), - name: "nirvana".to_string(), - voting_power: Decimal::from_str("25.6521469796402094").unwrap(), - commission: Decimal::from_str("0.1").unwrap(), - }, - remaining_time: 1707328694, - unstaked: BalanceAvailable { - amount: Uint128::from_str("100038144098").unwrap(), - usd_amount: Decimal::from_str("353214.779896389585407707").unwrap(), - }, - }]), - }, - usdc_earn_program: UsdcEarnProgram { - bonding_period: 0, - apr: AprUsdc { - uusdc: Int128::new(12), - ueden: Int128::new(12), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(5333229342748), - usd_amount: Decimal::from_str("5333229.342748").unwrap(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::zero(), - amount: Uint128::zero(), - lockups: None, - }), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_atomics(Uint128::new(000002), 5).unwrap(), - price: Decimal::from_atomics(Uint128::new(35308010067676894), 16).unwrap(), - amount_usd: Decimal::from_str("0.000070616020135353").unwrap(), - }]), - borrowed: Some(BalanceBorrowed { - usd_amount: Decimal::from_str("204000.000001").unwrap(), - percentage: Decimal::one(), - }), - }, - }, - }; - - // test if the response is the same as the expected - - // staked assets - - // USDC program - assert_eq!( - resp.staked_assets.usdc_earn_program.bonding_period, - expected.staked_assets.usdc_earn_program.bonding_period - ); - assert_eq!( - resp.staked_assets.usdc_earn_program.apr, - expected.staked_assets.usdc_earn_program.apr - ); - assert_eq!( - resp.staked_assets.usdc_earn_program.available, - expected.staked_assets.usdc_earn_program.available - ); - assert_eq!( - resp.staked_assets.usdc_earn_program.staked, - expected.staked_assets.usdc_earn_program.staked - ); - assert_eq!( - resp.staked_assets.usdc_earn_program.rewards, - expected.staked_assets.usdc_earn_program.rewards - ); - assert_eq!( - resp.staked_assets.usdc_earn_program.borrowed, - expected.staked_assets.usdc_earn_program.borrowed - ); - assert_eq!( - resp.staked_assets.usdc_earn_program, - expected.staked_assets.usdc_earn_program - ); - - // ELYS program - assert_eq!( - resp.staked_assets.elys_earn_program.bonding_period, - expected.staked_assets.elys_earn_program.bonding_period - ); - assert_eq!( - resp.staked_assets.elys_earn_program.apr, - expected.staked_assets.elys_earn_program.apr - ); - assert_eq!( - resp.staked_assets.elys_earn_program.available, - expected.staked_assets.elys_earn_program.available - ); - assert_eq!( - resp.staked_assets.elys_earn_program.staked, - expected.staked_assets.elys_earn_program.staked - ); - assert_eq!( - resp.staked_assets.elys_earn_program.rewards, - expected.staked_assets.elys_earn_program.rewards - ); - assert_eq!( - resp.staked_assets.elys_earn_program.staked_positions, - expected.staked_assets.elys_earn_program.staked_positions - ); - assert_eq!( - resp.staked_assets.elys_earn_program.unstaked_positions, - expected.staked_assets.elys_earn_program.unstaked_positions - ); - assert_eq!( - resp.staked_assets.elys_earn_program, - expected.staked_assets.elys_earn_program - ); - - // EDEN program - assert_eq!( - resp.staked_assets.eden_earn_program.bonding_period, - expected.staked_assets.eden_earn_program.bonding_period - ); - assert_eq!( - resp.staked_assets.eden_earn_program.apr, - expected.staked_assets.eden_earn_program.apr - ); - assert_eq!( - resp.staked_assets.eden_earn_program.available, - expected.staked_assets.eden_earn_program.available - ); - assert_eq!( - resp.staked_assets.eden_earn_program.staked, - expected.staked_assets.eden_earn_program.staked - ); - assert_eq!( - resp.staked_assets.eden_earn_program.rewards, - expected.staked_assets.eden_earn_program.rewards - ); - assert_eq!( - resp.staked_assets.eden_earn_program.vesting, - expected.staked_assets.eden_earn_program.vesting - ); - assert_eq!( - resp.staked_assets.eden_earn_program.vesting_details, - expected.staked_assets.eden_earn_program.vesting_details - ); - assert_eq!( - resp.staked_assets.eden_earn_program, - expected.staked_assets.eden_earn_program - ); - - // EDEN BOOST program - assert_eq!( - resp.staked_assets.eden_boost_earn_program.bonding_period, - expected - .staked_assets - .eden_boost_earn_program - .bonding_period - ); - assert_eq!( - resp.staked_assets.eden_boost_earn_program.apr, - expected.staked_assets.eden_boost_earn_program.apr - ); - assert_eq!( - resp.staked_assets.eden_boost_earn_program.available, - expected.staked_assets.eden_boost_earn_program.available - ); - assert_eq!( - resp.staked_assets.eden_boost_earn_program.staked, - expected.staked_assets.eden_boost_earn_program.staked - ); - assert_eq!( - resp.staked_assets.eden_boost_earn_program.rewards, - expected.staked_assets.eden_boost_earn_program.rewards - ); - assert_eq!( - resp.staked_assets.eden_boost_earn_program, - expected.staked_assets.eden_boost_earn_program - ); - - assert_eq!(resp.staked_assets, expected.staked_assets); - - assert_eq!(resp.total_staked_balance, expected.total_staked_balance); - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs deleted file mode 100644 index f1d7c179..00000000 --- a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs +++ /dev/null @@ -1,305 +0,0 @@ -use std::str::FromStr; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coins, to_json_binary, Addr, Coin, Decimal, Empty, Int128, StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BasicAppBuilder, ContractWrapper, Executor, Module}; -use elys_bindings::account_history::msg::query_resp::earn::GetUsdcEarnProgramResp; -use elys_bindings::account_history::types::earn_program::UsdcEarnProgram; -use elys_bindings::account_history::types::{AprUsdc, CoinValue}; -use elys_bindings::query_resp::{ - BalanceBorrowed, DelegationDelegatorReward, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, - QueryStableStakeAprResponse, StakedAvailable, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, query as trade_shield_query, -}; -use trade_shield_contract::msg::InstantiateMsg as TradeShieldInstantiateMsg; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { address, denom } => { - let resp = match (address.as_str(), denom.as_str()) { - ( - "user", - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ) => BalanceAvailable { - amount: Uint128::new(1234), - usd_amount: Decimal::from_str("1234").unwrap(), - }, - ("user", "uelys") => BalanceAvailable { - amount: Uint128::new(45666543), - usd_amount: Decimal::from_str("45666543").unwrap(), - }, - _ => BalanceAvailable { - amount: Uint128::zero(), - usd_amount: Decimal::zero(), - }, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { denom } => { - let resp = match denom.as_str() { - "uusdc" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - "ueden" => QueryStableStakeAprResponse { - apr: Int128::zero(), - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::CommitmentStakedBalanceOfDenom { .. } => { - let resp = StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::StableStakeBalanceOfBorrow {} => { - let resp = BalanceBorrowed { - usd_amount: Decimal::from_atomics(Uint128::new(3265035180871), 10).unwrap(), - percentage: Decimal::from_atomics(Uint128::new(0000238391578776388), 18) - .unwrap(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.5308010067676894").unwrap(), - "ueden" => Decimal::from_str("3.5308010067676894").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.02450744362719844").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: "validator".to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_usdc_earn_program_details() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - )]; - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|roouter, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - roouter - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = TradeShieldInstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - None, - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let resp: GetUsdcEarnProgramResp = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::GetUsdcEarnProgramDetails { - address: "user".to_string(), - }, - ) - .unwrap(); - - let expected = GetUsdcEarnProgramResp { - data: UsdcEarnProgram { - bonding_period: 0, - apr: AprUsdc { - uusdc: Int128::zero(), - ueden: Int128::zero(), - }, - available: Some(BalanceAvailable { - amount: Uint128::new(1234), - usd_amount: Decimal::from_str("0.001234").unwrap(), - }), - staked: Some(StakedAvailable { - usd_amount: Decimal::from_atomics(Uint128::new(100130012), 3).unwrap(), - amount: Uint128::new(100120000000), - lockups: None, - }), - rewards: Some(vec![CoinValue { - denom: "ueden".to_string(), - amount_token: Decimal::from_atomics(Uint128::new(000002), 5).unwrap(), - price: Decimal::from_atomics(Uint128::new(35308010067676894), 16).unwrap(), - amount_usd: Decimal::from_str("0.000070616020135353").unwrap(), - }]), - borrowed: Some(BalanceBorrowed { - usd_amount: Decimal::from_str("0.0003265035180871").unwrap(), - percentage: Decimal::from_atomics(Uint128::new(0000238391578776388), 18).unwrap(), - }), - }, - }; - - assert_eq!(resp, expected); -} diff --git a/contracts/account-history-contract/src/tests/mod.rs b/contracts/account-history-contract/src/tests/mod.rs deleted file mode 100644 index 5617595e..00000000 --- a/contracts/account-history-contract/src/tests/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -mod get_all_pools; -mod get_eden_boost_earn_program_details; -mod get_eden_earn_program_details; -mod get_elys_earn_program_detail; -mod get_liquid_assets; -mod get_rewards; -mod get_staked_assets; -mod get_usdc_earn_program_details; -mod update_accounts; -mod week_snapshots; diff --git a/contracts/account-history-contract/src/tests/update_accounts.rs b/contracts/account-history-contract/src/tests/update_accounts.rs deleted file mode 100644 index 91d3fadb..00000000 --- a/contracts/account-history-contract/src/tests/update_accounts.rs +++ /dev/null @@ -1,465 +0,0 @@ -use std::str::FromStr; - -use crate::msg::query_resp::UserValueResponse; -use crate::msg::SudoMsg; -use crate::msg::{InstantiateMsg, QueryMsg}; -use cosmwasm_std::{coins, Addr, BlockInfo, Coin, Decimal, Decimal256, Timestamp}; -use cw_multi_test::{BankSudo, BasicAppBuilder, ContractWrapper, Executor, SudoMsg as AppSudo}; -use elys_bindings::types::{OracleAssetInfo, Price, SwapAmountInRoute}; -use elys_bindings_test::{ - ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, - migrate as trade_shield_migrate, query as trade_shield_query, -}; -use trade_shield_contract::msg as trade_shield_msg; -use trade_shield_contract::types::{OrderPrice, SpotOrderType}; - -use crate::entry_point::instantiate; -use crate::entry_point::{execute, query}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{to_json_binary, Empty, Int128, SignedDecimal, StdError, Uint128}; -use cw_multi_test::{AppResponse, Module}; - -use elys_bindings::query_resp::{ - AmmSwapEstimationByDenomResponse, DelegationDelegatorReward, Entry, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, OracleAssetInfoResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::ElysModule; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { .. } => { - let resp = BalanceAvailable { - amount: Uint128::new(0), - usd_amount: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.449114").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.165195").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OracleAssetInfo { denom } => { - let resp = match denom.as_str() { - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "USDC".to_string(), - decimal: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display: "USDC".to_string(), - elys_ticker: "USDC".to_string(), - }, - } - } - "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "OSMO".to_string(), - decimal: 6, - denom: "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23".to_string(), - display: "OSMO".to_string(), - elys_ticker: "OSMO".to_string(), - }, - } - } - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "JUNO".to_string(), - decimal: 6, - denom: "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40".to_string(), - display: "JUNO".to_string(), - elys_ticker: "JUNO".to_string(), - }, - } - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "ATOM".to_string(), - decimal: 6, - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4".to_string(), - display: "ATOM".to_string(), - elys_ticker: "ATOM".to_string(), - }, - } - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmSwapEstimationByDenom { denom_out, .. } => { - let resp = AmmSwapEstimationByDenomResponse { - in_route: Some(vec![SwapAmountInRoute { - pool_id: 1, - token_out_denom: denom_out, - }]), - out_route: None, - spot_price: Decimal::from_str("3.5").unwrap(), - amount: Coin { - denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - amount: Uint128::new(100), - }, - swap_fee: SignedDecimal::one(), - discount: SignedDecimal::from_str("20").unwrap(), - available_liquidity: Coin { - denom: "uelys".to_string(), - amount: Uint128::new(100000), - }, - weight_balance_ratio: SignedDecimal::one(), - price_impact: SignedDecimal::zero(), - slippage: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn history() { - let wallet: Vec<(&str, Vec)> = vec![("user-a", coins(300, "uelys"))]; - std::env::set_var("IS_TEST_ENV", "TESTING"); - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|router, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - router - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query) - .with_migrate(trade_shield_migrate); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = trade_shield_msg::InstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - Some("admin".to_string()), - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address.clone()), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.migrate_contract( - Addr::unchecked("admin"), - Addr::unchecked(trade_shield_address.clone()), - &trade_shield_msg::MigrateMsg { - account_history_address: Some(addr.to_string()), - }, - trade_shield_code_id, - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user-a"), - Addr::unchecked(trade_shield_address.clone()), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: "uelys".to_string(), - order_target_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_price: Some(OrderPrice { - base_denom: "uelys".to_string(), - quote_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - rate: Decimal::one(), - }), - }, - &coins(100, "uelys"), - ) - .unwrap(); - - let update_msg = SudoMsg::ClockEndBlock {}; - - // t0 - app.set_block(BlockInfo { - height: 1, - time: Timestamp::from_seconds(0 * 24 * 60 * 60), - chain_id: "elys-app".to_string(), - }); - - app.wasm_sudo(addr.clone(), &update_msg).unwrap(); - - let query_msg = QueryMsg::UserValue { - user_address: "user-a".to_string(), - }; - - let res: UserValueResponse = app.wrap().query_wasm_smart(&addr, &query_msg).unwrap(); - - assert_eq!( - res.value.total_balance_usd, - Decimal256::from_str("400.00110371648").unwrap(), - ); - - app.sudo(AppSudo::Bank(BankSudo::Mint { - to_address: "user-a".to_string(), - amount: coins(200, "uelys"), - })) - .unwrap(); - - // t1 - app.set_block(BlockInfo { - height: 2, - time: Timestamp::from_seconds(1 * 24 * 60 * 60), - chain_id: "elys-app".to_string(), - }); - - app.wasm_sudo(addr.clone(), &update_msg).unwrap(); - - let res: UserValueResponse = app.wrap().query_wasm_smart(&addr, &query_msg).unwrap(); - - assert_eq!( - res.value.total_balance_usd, - Decimal256::from_str("400.00110371648").unwrap(), - ); // The previous value wasn't removed yet but wasn't read either since it's expired. - std::env::set_var("IS_TEST_ENV", "FALSE"); -} diff --git a/contracts/account-history-contract/src/tests/week_snapshots.rs b/contracts/account-history-contract/src/tests/week_snapshots.rs deleted file mode 100644 index 23984d12..00000000 --- a/contracts/account-history-contract/src/tests/week_snapshots.rs +++ /dev/null @@ -1,846 +0,0 @@ -use std::str::FromStr; -use std::vec; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coin, coins, to_json_binary, Addr, BlockInfo, Coin, Decimal, Empty, Int128, SignedDecimal, - StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BankSudo, BasicAppBuilder, ContractWrapper, Executor, Module}; -use cw_utils::Expiration; -use elys_bindings::account_history::types::PortfolioBalanceSnapshot; -use elys_bindings::query_resp::{ - AmmSwapEstimationByDenomResponse, DelegationDelegatorReward, Entry, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, OracleAssetInfoResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::{OracleAssetInfo, Price, SwapAmountInRoute}; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, - migrate as trade_shield_migrate, query as trade_shield_query, -}; -use trade_shield_contract::msg as trade_shield_msg; -use trade_shield_contract::types::{OrderPrice, SpotOrderType}; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.449114").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.165195").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OracleAssetInfo { denom } => { - let resp = match denom.as_str() { - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "USDC".to_string(), - decimal: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display: "USDC".to_string(), - elys_ticker: "USDC".to_string(), - }, - } - } - "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "OSMO".to_string(), - decimal: 6, - denom: "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23".to_string(), - display: "OSMO".to_string(), - elys_ticker: "OSMO".to_string(), - }, - } - } - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "JUNO".to_string(), - decimal: 6, - denom: "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40".to_string(), - display: "JUNO".to_string(), - elys_ticker: "JUNO".to_string(), - }, - } - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "ATOM".to_string(), - decimal: 6, - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4".to_string(), - display: "ATOM".to_string(), - elys_ticker: "ATOM".to_string(), - }, - } - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmSwapEstimationByDenom { - amount, - denom_out, - discount, - .. - } => { - let resp = AmmSwapEstimationByDenomResponse { - in_route: Some(vec![SwapAmountInRoute { - pool_id: 1, - token_out_denom: denom_out.clone(), - }]), - out_route: None, - spot_price: Decimal::one(), - amount, - swap_fee: SignedDecimal::zero(), - discount: SignedDecimal::from_str(discount.to_string().as_str()).unwrap(), - available_liquidity: coin(999999999, denom_out), - weight_balance_ratio: SignedDecimal::zero(), - price_impact: SignedDecimal::zero(), - slippage: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_portfolio() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - vec![coin( - 1445910542, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - )]; - std::env::set_var("IS_TEST_ENV", "TESTING"); - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|router, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - router - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query) - .with_migrate(trade_shield_migrate); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = trade_shield_msg::InstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - Some("admin".to_string()), - ) - .unwrap(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address.to_string()), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.migrate_contract( - Addr::unchecked("admin"), - trade_shield_address.clone(), - &trade_shield_msg::MigrateMsg { - account_history_address: Some(addr.to_string()), - }, - trade_shield_code_id, - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - // t0 - app.set_block(BlockInfo { - height: 1, - time: Timestamp::from_seconds(0), - chain_id: "elys".to_string(), - }); - - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t1 (1d later) - app.set_block(BlockInfo { - height: 2, - time: Timestamp::from_seconds(24 * 60 * 60), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 100000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t2 (2d later) - app.set_block(BlockInfo { - height: 3, - time: Timestamp::from_seconds(24 * 60 * 60 * 2), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 300000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t3 (3d later) - app.set_block(BlockInfo { - height: 4, - time: Timestamp::from_seconds(24 * 60 * 60 * 3), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 50000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // Query the contract for the existing order. - let last_snapshot: PortfolioBalanceSnapshot = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::LastSnapshot { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - // test if the response is the same as the expected - assert_eq!( - last_snapshot.date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - - //update date 5 hours later - app.set_block(BlockInfo { - height: 5, - time: Timestamp::from_seconds(24 * 60 * 60 * 3 + 5 * 60 * 60), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let last_snapshot: PortfolioBalanceSnapshot = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::LastSnapshot { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - // test if the response is the same as the expected - assert_eq!( - last_snapshot.date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - - //update day 4 - app.set_block(BlockInfo { - height: 6, - time: Timestamp::from_seconds(24 * 60 * 60 * 4), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 5 - app.set_block(BlockInfo { - height: 7, - time: Timestamp::from_seconds(24 * 60 * 60 * 5), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 6 - app.set_block(BlockInfo { - height: 8, - time: Timestamp::from_seconds(24 * 60 * 60 * 6), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 7 - app.set_block(BlockInfo { - height: 9, - time: Timestamp::from_seconds(24 * 60 * 60 * 7), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // check the all the snapshots recorded - let snapshots: Vec = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::UserSnapshots { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - assert_eq!(snapshots.len(), 7); - - // update day 8 - app.set_block(BlockInfo { - height: 10, - time: Timestamp::from_seconds(24 * 60 * 60 * 8), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // check the all the snapshots recorded - let snapshots: Vec = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::UserSnapshots { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - assert_eq!(snapshots.len(), 7); - - assert_eq!( - snapshots[0].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 2)) - ); - assert_eq!( - snapshots[1].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - assert_eq!( - snapshots[2].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 4)) - ); - assert_eq!( - snapshots[3].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 5)) - ); - assert_eq!( - snapshots[4].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 6)) - ); - assert_eq!( - snapshots[5].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 7)) - ); - assert_eq!( - snapshots[6].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 8)) - ); - std::env::set_var("IS_TEST_ENV", "FALSE"); -} From 8cb0d071459e2c499d28639aef0472a1e90f4741 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Thu, 11 Jul 2024 18:16:51 +0530 Subject: [PATCH 3/7] fix: tests and add sudo --- bindings/src/account_history/msg/execute.rs | 1 - .../src/action/execute/clean_up_storage.rs | 4 +- .../src/action/mod.rs | 5 - .../src/action/sudo/mod.rs | 3 - .../src/action/sudo/update_account_chain.rs | 79 -- .../src/entry_point/execute.rs | 12 +- .../src/entry_point/mod.rs | 2 + .../src/entry_point/sudo.rs | 19 + .../src/tests/get_all_pools.rs | 9 +- .../get_eden_boost_earn_program_details.rs | 4 +- .../src/tests/get_liquid_assets.rs | 4 +- .../src/tests/get_rewards.rs | 4 +- .../account-history-contract/src/tests/mod.rs | 10 +- .../src/tests/update_accounts.rs | 465 ---------- .../src/tests/week_snapshots.rs | 846 ------------------ 15 files changed, 39 insertions(+), 1428 deletions(-) delete mode 100644 contracts/account-history-contract/src/action/sudo/mod.rs delete mode 100644 contracts/account-history-contract/src/action/sudo/update_account_chain.rs create mode 100644 contracts/account-history-contract/src/entry_point/sudo.rs delete mode 100644 contracts/account-history-contract/src/tests/update_accounts.rs delete mode 100644 contracts/account-history-contract/src/tests/week_snapshots.rs diff --git a/bindings/src/account_history/msg/execute.rs b/bindings/src/account_history/msg/execute.rs index 317e85d7..d44758fe 100644 --- a/bindings/src/account_history/msg/execute.rs +++ b/bindings/src/account_history/msg/execute.rs @@ -11,7 +11,6 @@ pub enum ExecuteMsg { delete_old_data_enabled: Option, delete_epoch: Option, }, - UpdateAccount {}, CleanStorage { limit: u64, }, diff --git a/contracts/account-history-contract/src/action/execute/clean_up_storage.rs b/contracts/account-history-contract/src/action/execute/clean_up_storage.rs index 84017b23..98a93352 100644 --- a/contracts/account-history-contract/src/action/execute/clean_up_storage.rs +++ b/contracts/account-history-contract/src/action/execute/clean_up_storage.rs @@ -12,8 +12,8 @@ pub fn clean_up_storage(deps: &mut DepsMut, limit: u64) -> StdResult< if let Some(val) = OLD_HISTORY_2.first(deps.storage)? { OLD_HISTORY_2.remove(deps.storage, &val.0); } - if USER_ADDRESS_QUEUE.front(deps.storage).is_ok() { - USER_ADDRESS_QUEUE.pop_front(deps.storage)?; + if !USER_ADDRESS_QUEUE.is_empty(deps.storage).unwrap() { + let _ = USER_ADDRESS_QUEUE.pop_front(deps.storage); } } Ok(Response::default()) diff --git a/contracts/account-history-contract/src/action/mod.rs b/contracts/account-history-contract/src/action/mod.rs index 1509b16c..12cc5b4d 100644 --- a/contracts/account-history-contract/src/action/mod.rs +++ b/contracts/account-history-contract/src/action/mod.rs @@ -1,8 +1,3 @@ -pub mod sudo { - mod update_account_chain; - pub use update_account_chain::update_account_chain; -} - pub mod query { mod get_liquid_assets; use crate::error::ContractError; diff --git a/contracts/account-history-contract/src/action/sudo/mod.rs b/contracts/account-history-contract/src/action/sudo/mod.rs deleted file mode 100644 index cda648a7..00000000 --- a/contracts/account-history-contract/src/action/sudo/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -use update_account::update_account; -use update_account_chain::update_account_chain; -use clean_up_history::clean_up_history; diff --git a/contracts/account-history-contract/src/action/sudo/update_account_chain.rs b/contracts/account-history-contract/src/action/sudo/update_account_chain.rs deleted file mode 100644 index cc4f4cca..00000000 --- a/contracts/account-history-contract/src/action/sudo/update_account_chain.rs +++ /dev/null @@ -1,79 +0,0 @@ -use cosmwasm_std::{DepsMut, Env, Response, StdResult}; - -use crate::{ - states::{HISTORY, METADATA, OLD_HISTORY_2, PROCESSED_ACCOUNT_PER_BLOCK, USER_ADDRESS_QUEUE}, - types::AccountSnapshotGenerator, - utils::get_today, -}; -use elys_bindings::{ElysMsg, ElysQuerier, ElysQuery}; - -pub fn update_account(deps: DepsMut, env: Env) -> StdResult> { - let querier = ElysQuerier::new(&deps.querier); - - // update metadata prices - let mut metadata = METADATA.load(deps.storage)?; - metadata = metadata.update_prices(&querier)?; - METADATA.save(deps.storage, &metadata)?; - - let today = get_today(&env.block); - - let processed_account_per_block: usize = - PROCESSED_ACCOUNT_PER_BLOCK.load(deps.storage)? as usize; - - let generator = AccountSnapshotGenerator::new(&deps.as_ref())?; - - for _ in 0..processed_account_per_block { - if USER_ADDRESS_QUEUE.is_empty(deps.storage)? == true { - break; - } - - // remove the first element from the queue - let user_address = if let Some(addr) = USER_ADDRESS_QUEUE.pop_back(deps.storage)? { - addr.to_string() - } else { - break; - }; - - let key = today.clone() + &user_address; - - if let Some(_) = HISTORY.may_load(deps.storage, &key)? { - // skip if the account has been updated today - continue; - } - - let new_part = generator.generate_portfolio_balance_snapshot_for_address( - &querier, - &deps.as_ref(), - &env, - &user_address, - )?; - HISTORY.save(deps.storage, &key, &new_part)?; - } - - Ok(Response::default()) -} - -pub fn update_account_chain(deps: DepsMut, env: Env) -> StdResult> { - let processed_account_per_block: usize = - PROCESSED_ACCOUNT_PER_BLOCK.load(deps.storage)? as usize; - - let mut msgs = vec![]; - for _ in 0..processed_account_per_block { - if USER_ADDRESS_QUEUE.is_empty(deps.storage)? == true { - break; - } - - // remove the first element from the queue - let user_address = if let Some(addr) = USER_ADDRESS_QUEUE.pop_back(deps.storage)? { - addr.to_string() - } else { - break; - }; - - let msg: ElysMsg = - ElysMsg::tier_set_portfolio(env.contract.address.to_string(), user_address); - msgs.push(msg) - } - - Ok(Response::default().add_messages(msgs)) -} diff --git a/contracts/account-history-contract/src/entry_point/execute.rs b/contracts/account-history-contract/src/entry_point/execute.rs index 09842ec7..a22593ad 100644 --- a/contracts/account-history-contract/src/entry_point/execute.rs +++ b/contracts/account-history-contract/src/entry_point/execute.rs @@ -2,10 +2,7 @@ use cosmwasm_std::{entry_point, DepsMut, Env, MessageInfo, Response, StdError, S use elys_bindings::{account_history::msg::ExecuteMsg, ElysMsg, ElysQuery}; use crate::{ - action::{ - execute::{add_user_address_to_queue, clean_up_storage}, - sudo::update_account_chain, - }, + action::execute::{add_user_address_to_queue, clean_up_storage}, states::{ DELETE_EPOCH, DELETE_OLD_DATA_ENABLED, PARAMS_ADMIN, PROCESSED_ACCOUNT_PER_BLOCK, TRADE_SHIELD_ADDRESS, UPDATE_ACCOUNT_ENABLED, @@ -60,13 +57,6 @@ pub fn execute( } Ok(Response::new()) } - ExecuteMsg::UpdateAccount {} => { - if info.sender != PARAMS_ADMIN.load(deps.storage)? { - return Err(StdError::generic_err("Unauthorized")); - } - let resp = update_account_chain(deps, env)?; - Ok(resp) - } ExecuteMsg::CleanStorage { limit } => { if info.sender != PARAMS_ADMIN.load(deps.storage)? { return Err(StdError::generic_err("Unauthorized")); diff --git a/contracts/account-history-contract/src/entry_point/mod.rs b/contracts/account-history-contract/src/entry_point/mod.rs index 41977caa..db29648a 100644 --- a/contracts/account-history-contract/src/entry_point/mod.rs +++ b/contracts/account-history-contract/src/entry_point/mod.rs @@ -2,8 +2,10 @@ mod execute; mod instantiate; mod migrate; mod query; +mod sudo; pub use execute::execute; pub use instantiate::instantiate; pub use migrate::migrate; pub use query::query; +pub use sudo::sudo; diff --git a/contracts/account-history-contract/src/entry_point/sudo.rs b/contracts/account-history-contract/src/entry_point/sudo.rs new file mode 100644 index 00000000..91c56a48 --- /dev/null +++ b/contracts/account-history-contract/src/entry_point/sudo.rs @@ -0,0 +1,19 @@ +use crate::{msg::SudoMsg, states::DELETE_EPOCH}; +use crate::states::DELETE_OLD_DATA_ENABLED; +use crate::action::execute::clean_up_storage; +use cosmwasm_std::{entry_point, DepsMut, Env, Response, StdResult}; +use elys_bindings::{ElysMsg, ElysQuery}; + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn sudo(mut deps: DepsMut, _env: Env, msg: SudoMsg) -> StdResult> { + match msg { + SudoMsg::ClockEndBlock {} => { + let epoch = DELETE_EPOCH.load(deps.storage)?; + if DELETE_OLD_DATA_ENABLED.load(deps.storage)? == true + { + clean_up_storage(&mut deps, epoch)?; + } + return Ok(Response::new()); + } + } +} \ No newline at end of file diff --git a/contracts/account-history-contract/src/tests/get_all_pools.rs b/contracts/account-history-contract/src/tests/get_all_pools.rs index 49c018f4..764d5914 100644 --- a/contracts/account-history-contract/src/tests/get_all_pools.rs +++ b/contracts/account-history-contract/src/tests/get_all_pools.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -258,7 +258,7 @@ fn get_all_pools() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. @@ -282,8 +282,9 @@ fn get_all_pools() { ) .unwrap(); - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); + let msg = app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}); + + println!("{:?}", msg); let resp: QueryEarnPoolResponse = app .wrap() diff --git a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs index c5221a20..b188c0f9 100644 --- a/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_eden_boost_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -236,7 +236,7 @@ fn get_eden_boost_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_liquid_assets.rs b/contracts/account-history-contract/src/tests/get_liquid_assets.rs index e5b5013d..8ec7fb13 100644 --- a/contracts/account-history-contract/src/tests/get_liquid_assets.rs +++ b/contracts/account-history-contract/src/tests/get_liquid_assets.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::tests::get_liquid_assets::query_resp::{GetLiquidAssetsResp, LiquidAsset}; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -408,7 +408,7 @@ fn get_liquid_assets() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_rewards.rs b/contracts/account-history-contract/src/tests/get_rewards.rs index 6107e951..b5cba5f1 100644 --- a/contracts/account-history-contract/src/tests/get_rewards.rs +++ b/contracts/account-history-contract/src/tests/get_rewards.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -218,7 +218,7 @@ fn get_rewards() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/mod.rs b/contracts/account-history-contract/src/tests/mod.rs index 5617595e..8e3a9c37 100644 --- a/contracts/account-history-contract/src/tests/mod.rs +++ b/contracts/account-history-contract/src/tests/mod.rs @@ -1,10 +1,8 @@ mod get_all_pools; mod get_eden_boost_earn_program_details; -mod get_eden_earn_program_details; -mod get_elys_earn_program_detail; +mod get_eden_earn_program_details; //f +mod get_elys_earn_program_detail; //f mod get_liquid_assets; mod get_rewards; -mod get_staked_assets; -mod get_usdc_earn_program_details; -mod update_accounts; -mod week_snapshots; +mod get_staked_assets; //f +mod get_usdc_earn_program_details; //f diff --git a/contracts/account-history-contract/src/tests/update_accounts.rs b/contracts/account-history-contract/src/tests/update_accounts.rs deleted file mode 100644 index 91d3fadb..00000000 --- a/contracts/account-history-contract/src/tests/update_accounts.rs +++ /dev/null @@ -1,465 +0,0 @@ -use std::str::FromStr; - -use crate::msg::query_resp::UserValueResponse; -use crate::msg::SudoMsg; -use crate::msg::{InstantiateMsg, QueryMsg}; -use cosmwasm_std::{coins, Addr, BlockInfo, Coin, Decimal, Decimal256, Timestamp}; -use cw_multi_test::{BankSudo, BasicAppBuilder, ContractWrapper, Executor, SudoMsg as AppSudo}; -use elys_bindings::types::{OracleAssetInfo, Price, SwapAmountInRoute}; -use elys_bindings_test::{ - ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, - migrate as trade_shield_migrate, query as trade_shield_query, -}; -use trade_shield_contract::msg as trade_shield_msg; -use trade_shield_contract::types::{OrderPrice, SpotOrderType}; - -use crate::entry_point::instantiate; -use crate::entry_point::{execute, query}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{to_json_binary, Empty, Int128, SignedDecimal, StdError, Uint128}; -use cw_multi_test::{AppResponse, Module}; - -use elys_bindings::query_resp::{ - AmmSwapEstimationByDenomResponse, DelegationDelegatorReward, Entry, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, OracleAssetInfoResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::BalanceAvailable; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::ElysModule; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AmmBalance { .. } => { - let resp = BalanceAvailable { - amount: Uint128::new(0), - usd_amount: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.449114").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.165195").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OracleAssetInfo { denom } => { - let resp = match denom.as_str() { - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "USDC".to_string(), - decimal: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display: "USDC".to_string(), - elys_ticker: "USDC".to_string(), - }, - } - } - "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "OSMO".to_string(), - decimal: 6, - denom: "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23".to_string(), - display: "OSMO".to_string(), - elys_ticker: "OSMO".to_string(), - }, - } - } - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "JUNO".to_string(), - decimal: 6, - denom: "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40".to_string(), - display: "JUNO".to_string(), - elys_ticker: "JUNO".to_string(), - }, - } - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "ATOM".to_string(), - decimal: 6, - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4".to_string(), - display: "ATOM".to_string(), - elys_ticker: "ATOM".to_string(), - }, - } - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmSwapEstimationByDenom { denom_out, .. } => { - let resp = AmmSwapEstimationByDenomResponse { - in_route: Some(vec![SwapAmountInRoute { - pool_id: 1, - token_out_denom: denom_out, - }]), - out_route: None, - spot_price: Decimal::from_str("3.5").unwrap(), - amount: Coin { - denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - amount: Uint128::new(100), - }, - swap_fee: SignedDecimal::one(), - discount: SignedDecimal::from_str("20").unwrap(), - available_liquidity: Coin { - denom: "uelys".to_string(), - amount: Uint128::new(100000), - }, - weight_balance_ratio: SignedDecimal::one(), - price_impact: SignedDecimal::zero(), - slippage: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn history() { - let wallet: Vec<(&str, Vec)> = vec![("user-a", coins(300, "uelys"))]; - std::env::set_var("IS_TEST_ENV", "TESTING"); - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|router, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - router - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query) - .with_migrate(trade_shield_migrate); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = trade_shield_msg::InstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - Some("admin".to_string()), - ) - .unwrap() - .to_string(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address.clone()), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.migrate_contract( - Addr::unchecked("admin"), - Addr::unchecked(trade_shield_address.clone()), - &trade_shield_msg::MigrateMsg { - account_history_address: Some(addr.to_string()), - }, - trade_shield_code_id, - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user-a"), - Addr::unchecked(trade_shield_address.clone()), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: "uelys".to_string(), - order_target_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_price: Some(OrderPrice { - base_denom: "uelys".to_string(), - quote_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - rate: Decimal::one(), - }), - }, - &coins(100, "uelys"), - ) - .unwrap(); - - let update_msg = SudoMsg::ClockEndBlock {}; - - // t0 - app.set_block(BlockInfo { - height: 1, - time: Timestamp::from_seconds(0 * 24 * 60 * 60), - chain_id: "elys-app".to_string(), - }); - - app.wasm_sudo(addr.clone(), &update_msg).unwrap(); - - let query_msg = QueryMsg::UserValue { - user_address: "user-a".to_string(), - }; - - let res: UserValueResponse = app.wrap().query_wasm_smart(&addr, &query_msg).unwrap(); - - assert_eq!( - res.value.total_balance_usd, - Decimal256::from_str("400.00110371648").unwrap(), - ); - - app.sudo(AppSudo::Bank(BankSudo::Mint { - to_address: "user-a".to_string(), - amount: coins(200, "uelys"), - })) - .unwrap(); - - // t1 - app.set_block(BlockInfo { - height: 2, - time: Timestamp::from_seconds(1 * 24 * 60 * 60), - chain_id: "elys-app".to_string(), - }); - - app.wasm_sudo(addr.clone(), &update_msg).unwrap(); - - let res: UserValueResponse = app.wrap().query_wasm_smart(&addr, &query_msg).unwrap(); - - assert_eq!( - res.value.total_balance_usd, - Decimal256::from_str("400.00110371648").unwrap(), - ); // The previous value wasn't removed yet but wasn't read either since it's expired. - std::env::set_var("IS_TEST_ENV", "FALSE"); -} diff --git a/contracts/account-history-contract/src/tests/week_snapshots.rs b/contracts/account-history-contract/src/tests/week_snapshots.rs deleted file mode 100644 index 23984d12..00000000 --- a/contracts/account-history-contract/src/tests/week_snapshots.rs +++ /dev/null @@ -1,846 +0,0 @@ -use std::str::FromStr; -use std::vec; - -use crate::entry_point::instantiate; -use crate::{ - entry_point::{execute, query}, - msg::*, -}; -use anyhow::{bail, Error, Result as AnyResult}; -use cosmwasm_std::{ - coin, coins, to_json_binary, Addr, BlockInfo, Coin, Decimal, Empty, Int128, SignedDecimal, - StdError, Timestamp, Uint128, -}; -use cw_multi_test::{AppResponse, BankSudo, BasicAppBuilder, ContractWrapper, Executor, Module}; -use cw_utils::Expiration; -use elys_bindings::account_history::types::PortfolioBalanceSnapshot; -use elys_bindings::query_resp::{ - AmmSwapEstimationByDenomResponse, DelegationDelegatorReward, Entry, EstakingRewardsResponse, - MasterchefUserPendingRewardData, MasterchefUserPendingRewardResponse, OracleAssetInfoResponse, - QueryGetEntryResponse, QueryGetPriceResponse, QueryStableStakeAprResponse, Validator, -}; -use elys_bindings::types::{OracleAssetInfo, Price, SwapAmountInRoute}; -use elys_bindings::{ElysMsg, ElysQuery}; -use elys_bindings_test::{ - ElysModule, ACCOUNT, ASSET_INFO, LAST_MODULE_USED, PERPETUAL_OPENED_POSITION, PRICES, -}; -use trade_shield_contract::entry_point::{ - execute as trade_shield_execute, instantiate as trade_shield_init, - migrate as trade_shield_migrate, query as trade_shield_query, -}; -use trade_shield_contract::msg as trade_shield_msg; -use trade_shield_contract::types::{OrderPrice, SpotOrderType}; - -struct ElysModuleWrapper(ElysModule); - -impl Module for ElysModuleWrapper { - type QueryT = ElysQuery; - type ExecT = ElysMsg; - type SudoT = Empty; - - fn query( - &self, - api: &dyn cosmwasm_std::Api, - storage: &dyn cosmwasm_std::Storage, - querier: &dyn cosmwasm_std::Querier, - block: &cosmwasm_std::BlockInfo, - request: Self::QueryT, - ) -> AnyResult { - match request { - ElysQuery::AssetProfileEntry { base_denom } => { - let resp = match base_denom.as_str() { - "uusdc" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uusdc".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display_name: "USDC".to_string(), - display_symbol: "uUSDC".to_string(), - external_symbol: "uUSDC".to_string(), - ibc_channel_id: "channel-12".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "channel-19".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "transfer/channel-12".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "uusdc".to_string(), - withdraw_enabled: true, - }, - }, - "ueden" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "ueden".to_string(), - commit_enabled: true, - decimals: 6, - denom: "ueden".to_string(), - display_name: "EDEN".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - "uelys" => QueryGetEntryResponse { - entry: Entry { - address: "".to_string(), - authority: "elys10d07y265gmmuvt4z0w9aw880jnsr700j6z2zm3".to_string(), - base_denom: "uelys".to_string(), - commit_enabled: true, - decimals: 6, - denom: "uelys".to_string(), - display_name: "ELYS".to_string(), - display_symbol: "".to_string(), - external_symbol: "".to_string(), - ibc_channel_id: "".to_string(), - ibc_counterparty_chain_id: "".to_string(), - ibc_counterparty_channel_id: "".to_string(), - ibc_counterparty_denom: "".to_string(), - network: "".to_string(), - path: "".to_string(), - permissions: vec![], - transfer_limit: "".to_string(), - unit_denom: "".to_string(), - withdraw_enabled: true, - }, - }, - _ => return Err(Error::new(StdError::not_found(base_denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmPriceByDenom { token_in, .. } => { - let spot_price = match token_in.denom.as_str() { - "uelys" => Decimal::from_str("3.449114").unwrap(), - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - Decimal::one() - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - Decimal::from_str("9.165195").unwrap() - } - _ => return Err(Error::new(StdError::not_found(token_in.denom.as_str()))), - }; - Ok(to_json_binary(&spot_price)?) - } - ElysQuery::OraclePrice { asset, .. } => { - let resp = match asset.as_str() { - "USDC" => QueryGetPriceResponse { - price: Price { - asset: "USDC".to_string(), - price: Decimal::one(), - source: "uelys".to_string(), - provider: "elys1wzm8dvpxpxxf26y4xn85w5adakcenprg4cq2uf".to_string(), - // set timestamp to now - timestamp: block.time.seconds(), - block_height: block.height, - }, - }, - _ => return Err(Error::new(StdError::not_found(asset))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::OracleAssetInfo { denom } => { - let resp = match denom.as_str() { - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "USDC".to_string(), - decimal: 6, - denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - display: "USDC".to_string(), - elys_ticker: "USDC".to_string(), - }, - } - } - "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "OSMO".to_string(), - decimal: 6, - denom: "ibc/47BD209179859CDE4A2806763D7189B6E6FE13A17880FE2B42DE1E6C1E329E23".to_string(), - display: "OSMO".to_string(), - elys_ticker: "OSMO".to_string(), - }, - } - } - "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "JUNO".to_string(), - decimal: 6, - denom: "ibc/977D5388D2FBE72D9A33FE2423BF8F4DADF3B591207CC98A295B9ACF81E4DE40".to_string(), - display: "JUNO".to_string(), - elys_ticker: "JUNO".to_string(), - }, - } - } - "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4" => { - OracleAssetInfoResponse { - asset_info: OracleAssetInfo { - band_ticker: "ATOM".to_string(), - decimal: 6, - denom: "ibc/E2D2F6ADCC68AA3384B2F5DFACCA437923D137C14E86FB8A10207CF3BED0C8D4".to_string(), - display: "ATOM".to_string(), - elys_ticker: "ATOM".to_string(), - }, - } - }, - _ => return Err(Error::new(StdError::not_found(denom))), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::AmmSwapEstimationByDenom { - amount, - denom_out, - discount, - .. - } => { - let resp = AmmSwapEstimationByDenomResponse { - in_route: Some(vec![SwapAmountInRoute { - pool_id: 1, - token_out_denom: denom_out.clone(), - }]), - out_route: None, - spot_price: Decimal::one(), - amount, - swap_fee: SignedDecimal::zero(), - discount: SignedDecimal::from_str(discount.to_string().as_str()).unwrap(), - available_liquidity: coin(999999999, denom_out), - weight_balance_ratio: SignedDecimal::zero(), - price_impact: SignedDecimal::zero(), - slippage: Decimal::zero(), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::EstakingRewards { .. } => { - let resp = EstakingRewardsResponse { - rewards: vec![DelegationDelegatorReward { - validator_address: Validator::EdenBoost.to_string(), - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }], - total: vec![Coin { - denom: "uedenb".to_string(), - amount: Uint128::from_str("121").unwrap(), - }], - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefStableStakeApr { .. } => { - let resp = QueryStableStakeAprResponse { - apr: Int128::new(12), - }; - Ok(to_json_binary(&resp)?) - } - ElysQuery::MasterchefUserPendingReward { .. } => { - let resp = MasterchefUserPendingRewardResponse { - rewards: vec![MasterchefUserPendingRewardData { - pool_id: 32767u64, - reward: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }], - total_rewards: vec![Coin { - denom: "ueden".to_string(), - amount: Uint128::new(20), - }], - }; - Ok(to_json_binary(&resp)?) - } - _ => self.0.query(api, storage, querier, block, request), - } - } - - fn execute( - &self, - api: &dyn cosmwasm_std::Api, - storage: &mut dyn cosmwasm_std::Storage, - router: &dyn cw_multi_test::CosmosRouter, - block: &cosmwasm_std::BlockInfo, - sender: Addr, - msg: Self::ExecT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - match msg { - _ => self.0.execute(api, storage, router, block, sender, msg), - } - } - - fn sudo( - &self, - _api: &dyn cosmwasm_std::Api, - _storage: &mut dyn cosmwasm_std::Storage, - _router: &dyn cw_multi_test::CosmosRouter, - _block: &cosmwasm_std::BlockInfo, - _msg: Self::SudoT, - ) -> AnyResult - where - ExecC: std::fmt::Debug - + Clone - + PartialEq - + schemars::JsonSchema - + serde::de::DeserializeOwned - + 'static, - QueryC: cosmwasm_std::CustomQuery + serde::de::DeserializeOwned + 'static, - { - bail!("sudo is not implemented for ElysModule") - } -} - -#[test] -fn get_portfolio() { - // Create a wallet for the "user" with an initial balance of 100 usdc - let wallet = vec![( - "user", - vec![coin( - 1445910542, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - )]; - std::env::set_var("IS_TEST_ENV", "TESTING"); - - let mut addresses: Vec = vec![]; - let mut app = BasicAppBuilder::::new_custom() - .with_custom(ElysModuleWrapper(ElysModule {})) - .build(|router, _, storage| { - for (wallet_owner, wallet_contenent) in wallet { - router - .bank - .init_balance(storage, &Addr::unchecked(wallet_owner), wallet_contenent) - .unwrap(); - addresses.push(wallet_owner.to_owned()) - } - ACCOUNT.save(storage, &addresses).unwrap(); - PERPETUAL_OPENED_POSITION.save(storage, &vec![]).unwrap(); - ASSET_INFO.save(storage, &vec![]).unwrap(); - PRICES.save(storage, &vec![]).unwrap(); - LAST_MODULE_USED.save(storage, &None).unwrap(); - }); - - // trade shield deployment - let trade_shield_code = - ContractWrapper::new(trade_shield_execute, trade_shield_init, trade_shield_query) - .with_migrate(trade_shield_migrate); - let trade_shield_code_id = app.store_code(Box::new(trade_shield_code)); - let trade_shield_init = trade_shield_msg::InstantiateMsg { - account_history_address: None, - }; - let trade_shield_address = app - .instantiate_contract( - trade_shield_code_id, - Addr::unchecked("owner"), - &trade_shield_init, - &[], - "Contract", - Some("admin".to_string()), - ) - .unwrap(); - - // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); - let code_id = app.store_code(Box::new(code)); - - // Create a mock message to instantiate the contract with no initial orders. - let instantiate_msg = InstantiateMsg { - limit: Some(3), - expiration: Some(cw_utils::Expiration::AtTime(Timestamp::from_seconds( - 604800, - ))), - trade_shield_address: Some(trade_shield_address.to_string()), - }; - - // Instantiate the contract with "owner" as the deployer. - let addr = app - .instantiate_contract( - code_id, - Addr::unchecked("owner"), - &instantiate_msg, - &[], - "Contract", - None, - ) - .unwrap(); - - app.migrate_contract( - Addr::unchecked("admin"), - trade_shield_address.clone(), - &trade_shield_msg::MigrateMsg { - account_history_address: Some(addr.to_string()), - }, - trade_shield_code_id, - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - // t0 - app.set_block(BlockInfo { - height: 1, - time: Timestamp::from_seconds(0), - chain_id: "elys".to_string(), - }); - - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t1 (1d later) - app.set_block(BlockInfo { - height: 2, - time: Timestamp::from_seconds(24 * 60 * 60), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 100000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t2 (2d later) - app.set_block(BlockInfo { - height: 3, - time: Timestamp::from_seconds(24 * 60 * 60 * 2), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 300000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // t3 (3d later) - app.set_block(BlockInfo { - height: 4, - time: Timestamp::from_seconds(24 * 60 * 60 * 3), - chain_id: "elys".to_string(), - }); - - // mint some coins - app.sudo( - BankSudo::Mint { - to_address: "user".to_string(), - amount: vec![coin( - 50000000, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - )], - } - .into(), - ) - .unwrap(); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - // update account - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // Query the contract for the existing order. - let last_snapshot: PortfolioBalanceSnapshot = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::LastSnapshot { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - // test if the response is the same as the expected - assert_eq!( - last_snapshot.date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - - //update date 5 hours later - app.set_block(BlockInfo { - height: 5, - time: Timestamp::from_seconds(24 * 60 * 60 * 3 + 5 * 60 * 60), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - let last_snapshot: PortfolioBalanceSnapshot = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::LastSnapshot { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - // test if the response is the same as the expected - assert_eq!( - last_snapshot.date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - - //update day 4 - app.set_block(BlockInfo { - height: 6, - time: Timestamp::from_seconds(24 * 60 * 60 * 4), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 5 - app.set_block(BlockInfo { - height: 7, - time: Timestamp::from_seconds(24 * 60 * 60 * 5), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 6 - app.set_block(BlockInfo { - height: 8, - time: Timestamp::from_seconds(24 * 60 * 60 * 6), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // update day 7 - app.set_block(BlockInfo { - height: 9, - time: Timestamp::from_seconds(24 * 60 * 60 * 7), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // check the all the snapshots recorded - let snapshots: Vec = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::UserSnapshots { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - assert_eq!(snapshots.len(), 7); - - // update day 8 - app.set_block(BlockInfo { - height: 10, - time: Timestamp::from_seconds(24 * 60 * 60 * 8), - chain_id: "elys".to_string(), - }); - - app.execute_contract( - Addr::unchecked("user"), - trade_shield_address.clone(), - &trade_shield_msg::ExecuteMsg::CreateSpotOrder { - order_type: SpotOrderType::StopLoss, - order_source_denom: - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65".to_string(), - order_target_denom: "uelys".to_string(), - order_price: Some(OrderPrice { - base_denom: "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65" - .to_string(), - quote_denom: "uelys".to_string(), - rate: Decimal::one(), - }), - }, - &coins( - 100, - "ibc/2180E84E20F5679FCC760D8C165B60F42065DEF7F46A72B447CFF1B7DC6C0A65", - ), - ) - .unwrap(); - - app.wasm_sudo(addr.clone(), &SudoMsg::ClockEndBlock {}) - .unwrap(); - - // check the all the snapshots recorded - let snapshots: Vec = app - .wrap() - .query_wasm_smart( - &addr, - &QueryMsg::UserSnapshots { - user_address: "user".to_string(), - }, - ) - .unwrap(); - - assert_eq!(snapshots.len(), 7); - - assert_eq!( - snapshots[0].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 2)) - ); - assert_eq!( - snapshots[1].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 3)) - ); - assert_eq!( - snapshots[2].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 4)) - ); - assert_eq!( - snapshots[3].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 5)) - ); - assert_eq!( - snapshots[4].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 6)) - ); - assert_eq!( - snapshots[5].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 7)) - ); - assert_eq!( - snapshots[6].date, - Expiration::AtTime(Timestamp::from_seconds(24 * 60 * 60 * 8)) - ); - std::env::set_var("IS_TEST_ENV", "FALSE"); -} From 3396b94001aa8d1abdaa1168db16bb7e17ecb426 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Thu, 11 Jul 2024 18:32:32 +0530 Subject: [PATCH 4/7] feat(WIP): failed test cases --- .../src/tests/get_eden_earn_program_details.rs | 4 ++-- .../src/tests/get_elys_earn_program_detail.rs | 4 ++-- .../src/tests/get_staked_assets.rs | 4 ++-- .../src/tests/get_usdc_earn_program_details.rs | 4 ++-- contracts/account-history-contract/src/tests/mod.rs | 8 ++++---- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs index db3c4a48..f521428f 100644 --- a/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_eden_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -236,7 +236,7 @@ fn get_eden_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs b/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs index f04a9275..9fce1ac3 100644 --- a/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs +++ b/contracts/account-history-contract/src/tests/get_elys_earn_program_detail.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -235,7 +235,7 @@ fn get_elys_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_staked_assets.rs b/contracts/account-history-contract/src/tests/get_staked_assets.rs index 63b5d870..7dad9124 100644 --- a/contracts/account-history-contract/src/tests/get_staked_assets.rs +++ b/contracts/account-history-contract/src/tests/get_staked_assets.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::tests::get_staked_assets::query_resp::StakedAssetsResponse; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -524,7 +524,7 @@ fn get_staked_assets() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs b/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs index f1d7c179..a3b5a726 100644 --- a/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs +++ b/contracts/account-history-contract/src/tests/get_usdc_earn_program_details.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use crate::entry_point::instantiate; use crate::{ - entry_point::{execute, query}, + entry_point::{execute, query, sudo}, msg::*, }; use anyhow::{bail, Error, Result as AnyResult}; @@ -235,7 +235,7 @@ fn get_usdc_earn_program_details() { .to_string(); // Create a contract wrapper and store its code. - let code = ContractWrapper::new(execute, instantiate, query); + let code = ContractWrapper::new(execute, instantiate, query).with_sudo(sudo); let code_id = app.store_code(Box::new(code)); // Create a mock message to instantiate the contract with no initial orders. diff --git a/contracts/account-history-contract/src/tests/mod.rs b/contracts/account-history-contract/src/tests/mod.rs index 4afb7662..f5708269 100644 --- a/contracts/account-history-contract/src/tests/mod.rs +++ b/contracts/account-history-contract/src/tests/mod.rs @@ -1,8 +1,8 @@ mod get_all_pools; mod get_eden_boost_earn_program_details; -// mod get_eden_earn_program_details; -// mod get_elys_earn_program_detail; +mod get_eden_earn_program_details; +mod get_elys_earn_program_detail; mod get_liquid_assets; mod get_rewards; -// mod get_staked_assets; -// mod get_usdc_earn_program_details; +mod get_staked_assets; +mod get_usdc_earn_program_details; From ce34c51b36957d91ce274e5608313e67d0fbfbc8 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Thu, 11 Jul 2024 19:33:59 +0530 Subject: [PATCH 5/7] add: query to retrive storage len/size --- bindings/src/account_history/msg/mod.rs | 2 ++ bindings/src/account_history/msg/query.rs | 4 ++-- .../msg/query_resp/get_storage_size.rs | 8 ++++++++ .../src/entry_point/execute.rs | 2 +- .../src/entry_point/query.rs | 20 +++++++++++++++---- 5 files changed, 29 insertions(+), 7 deletions(-) create mode 100644 bindings/src/account_history/msg/query_resp/get_storage_size.rs diff --git a/bindings/src/account_history/msg/mod.rs b/bindings/src/account_history/msg/mod.rs index 0f3b94c0..6e6323c0 100644 --- a/bindings/src/account_history/msg/mod.rs +++ b/bindings/src/account_history/msg/mod.rs @@ -13,6 +13,7 @@ pub use sudo::SudoMsg; pub mod query_resp { mod get_all_resp; mod get_rewards_resp; + mod get_storage_size; mod liquid_asset; mod membership_tier_response; mod params_resp; @@ -21,6 +22,7 @@ pub mod query_resp { pub use get_all_resp::GetAllResp; pub use get_rewards_resp::GetRewardsResp; + pub use get_storage_size::StorageSizeResp; pub use liquid_asset::LiquidAsset; pub use membership_tier_response::MembershipTierResponse; pub use params_resp::ParamsResp; diff --git a/bindings/src/account_history/msg/query.rs b/bindings/src/account_history/msg/query.rs index 99b769a4..7c4d7d38 100644 --- a/bindings/src/account_history/msg/query.rs +++ b/bindings/src/account_history/msg/query.rs @@ -160,8 +160,8 @@ pub enum QueryMsg { IncentiveAprs {}, #[cfg(feature = "debug")] - #[returns(Uint128)] - AddressQueueSize {}, + #[returns(StorageSizeResp)] + StorageSize {}, #[cfg(feature = "debug")] #[returns(ContractVersion)] diff --git a/bindings/src/account_history/msg/query_resp/get_storage_size.rs b/bindings/src/account_history/msg/query_resp/get_storage_size.rs new file mode 100644 index 00000000..dff0900c --- /dev/null +++ b/bindings/src/account_history/msg/query_resp/get_storage_size.rs @@ -0,0 +1,8 @@ +use cosmwasm_schema::cw_serde; + +#[cw_serde] +pub struct StorageSizeResp { + pub user_address_queue_data_size: u128, + pub history_data_size: u128, + pub old_history_2_data_size: u128, +} diff --git a/contracts/account-history-contract/src/entry_point/execute.rs b/contracts/account-history-contract/src/entry_point/execute.rs index a22593ad..1f9810cc 100644 --- a/contracts/account-history-contract/src/entry_point/execute.rs +++ b/contracts/account-history-contract/src/entry_point/execute.rs @@ -12,7 +12,7 @@ use crate::{ #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( mut deps: DepsMut, - env: Env, + _env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> StdResult> { diff --git a/contracts/account-history-contract/src/entry_point/query.rs b/contracts/account-history-contract/src/entry_point/query.rs index d6f427e1..a629aaf2 100644 --- a/contracts/account-history-contract/src/entry_point/query.rs +++ b/contracts/account-history-contract/src/entry_point/query.rs @@ -6,7 +6,7 @@ use crate::{ get_membership_tier, get_perpetuals_assets, get_pool_balances, get_rewards, get_staked_assets, get_usdc_earn_program_details, }, - states::USER_ADDRESS_QUEUE, + states::{HISTORY, OLD_HISTORY_2, USER_ADDRESS_QUEUE}, types::AccountSnapshotGenerator, }; @@ -19,7 +19,9 @@ use crate::action::query::{ use cosmwasm_std::{entry_point, to_json_binary, Binary, Deps, Env, StdResult}; use cw2::CONTRACT; use elys_bindings::{ - account_history::types::ElysDenom, query_resp::QueryAprResponse, ElysQuerier, ElysQuery, + account_history::{msg::query_resp::StorageSizeResp, types::ElysDenom}, + query_resp::QueryAprResponse, + ElysQuerier, ElysQuery, }; use crate::msg::QueryMsg; @@ -254,10 +256,20 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult { + StorageSize {} => { let user_address_queue_data_size = USER_ADDRESS_QUEUE.len(deps.storage)? as u128; + let history_data_size = HISTORY + .keys(deps.storage, None, None, cosmwasm_std::Order::Descending) + .count() as u128; + let old_history_2_data_size = OLD_HISTORY_2 + .keys(deps.storage, None, None, cosmwasm_std::Order::Descending) + .count() as u128; - to_json_binary(&user_address_queue_data_size) + to_json_binary(&StorageSizeResp { + user_address_queue_data_size, + history_data_size, + old_history_2_data_size, + }) } Version {} => to_json_binary(&CONTRACT.load(deps.storage)?), } From b2e982b683e4563401dfc7893bc936275b9ad205 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Thu, 11 Jul 2024 19:39:55 +0530 Subject: [PATCH 6/7] add: bulk clean history storage --- bindings/src/account_history/msg/execute.rs | 1 + .../src/entry_point/execute.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/bindings/src/account_history/msg/execute.rs b/bindings/src/account_history/msg/execute.rs index d44758fe..4af4ee62 100644 --- a/bindings/src/account_history/msg/execute.rs +++ b/bindings/src/account_history/msg/execute.rs @@ -14,4 +14,5 @@ pub enum ExecuteMsg { CleanStorage { limit: u64, }, + CleanStorageBulk {}, } diff --git a/contracts/account-history-contract/src/entry_point/execute.rs b/contracts/account-history-contract/src/entry_point/execute.rs index 1f9810cc..de7a742b 100644 --- a/contracts/account-history-contract/src/entry_point/execute.rs +++ b/contracts/account-history-contract/src/entry_point/execute.rs @@ -4,8 +4,8 @@ use elys_bindings::{account_history::msg::ExecuteMsg, ElysMsg, ElysQuery}; use crate::{ action::execute::{add_user_address_to_queue, clean_up_storage}, states::{ - DELETE_EPOCH, DELETE_OLD_DATA_ENABLED, PARAMS_ADMIN, PROCESSED_ACCOUNT_PER_BLOCK, - TRADE_SHIELD_ADDRESS, UPDATE_ACCOUNT_ENABLED, + DELETE_EPOCH, DELETE_OLD_DATA_ENABLED, HISTORY, OLD_HISTORY_2, PARAMS_ADMIN, + PROCESSED_ACCOUNT_PER_BLOCK, TRADE_SHIELD_ADDRESS, UPDATE_ACCOUNT_ENABLED, }, }; @@ -64,5 +64,13 @@ pub fn execute( let resp = clean_up_storage(&mut deps, limit)?; Ok(resp) } + ExecuteMsg::CleanStorageBulk {} => { + if info.sender != PARAMS_ADMIN.load(deps.storage)? { + return Err(StdError::generic_err("Unauthorized")); + } + HISTORY.clear(deps.storage); + OLD_HISTORY_2.clear(deps.storage); + Ok(Response::new()) + } } } From 7a14bbd37395ddd16f2edee17f19d46c6e036478 Mon Sep 17 00:00:00 2001 From: CryptoKage2306 <26vivek06@gmail.com> Date: Fri, 12 Jul 2024 19:14:54 +0530 Subject: [PATCH 7/7] fix: test cases --- .../account-history-contract/src/action/mod.rs | 5 +++++ .../src/action/sudo/update_metadata_prices.rs | 14 ++++++++++++++ .../src/entry_point/sudo.rs | 4 +++- 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 contracts/account-history-contract/src/action/sudo/update_metadata_prices.rs diff --git a/contracts/account-history-contract/src/action/mod.rs b/contracts/account-history-contract/src/action/mod.rs index 12cc5b4d..641ed9de 100644 --- a/contracts/account-history-contract/src/action/mod.rs +++ b/contracts/account-history-contract/src/action/mod.rs @@ -67,3 +67,8 @@ pub mod execute { pub use add_user_address_to_queue::add_user_address_to_queue; pub use clean_up_storage::clean_up_storage; } + +pub mod sudo { + mod update_metadata_prices; + pub use update_metadata_prices::update_metadata_prices; +} diff --git a/contracts/account-history-contract/src/action/sudo/update_metadata_prices.rs b/contracts/account-history-contract/src/action/sudo/update_metadata_prices.rs new file mode 100644 index 00000000..3d5293d5 --- /dev/null +++ b/contracts/account-history-contract/src/action/sudo/update_metadata_prices.rs @@ -0,0 +1,14 @@ +use crate::states::METADATA; +use cosmwasm_std::{DepsMut, Response, StdResult}; +use elys_bindings::{ElysMsg, ElysQuerier, ElysQuery}; + +pub fn update_metadata_prices(deps: DepsMut) -> StdResult> { + let querier = ElysQuerier::new(&deps.querier); + + // update metadata prices + let mut metadata = METADATA.load(deps.storage)?; + metadata = metadata.update_prices(&querier)?; + METADATA.save(deps.storage, &metadata)?; + + Ok(Response::default()) +} diff --git a/contracts/account-history-contract/src/entry_point/sudo.rs b/contracts/account-history-contract/src/entry_point/sudo.rs index 33d06fff..950a6491 100644 --- a/contracts/account-history-contract/src/entry_point/sudo.rs +++ b/contracts/account-history-contract/src/entry_point/sudo.rs @@ -1,4 +1,5 @@ use crate::action::execute::clean_up_storage; +use crate::action::sudo::update_metadata_prices; use crate::states::DELETE_OLD_DATA_ENABLED; use crate::{msg::SudoMsg, states::DELETE_EPOCH}; use cosmwasm_std::{entry_point, DepsMut, Env, Response, StdResult}; @@ -12,7 +13,8 @@ pub fn sudo(mut deps: DepsMut, _env: Env, msg: SudoMsg) -> StdResult< if DELETE_OLD_DATA_ENABLED.load(deps.storage)? == true { clean_up_storage(&mut deps, epoch)?; } - return Ok(Response::new()); + update_metadata_prices(deps)?; + Ok(Response::new()) } } }