From 70e3a43ee7a58c760857a0a02402a688c1a6f50e Mon Sep 17 00:00:00 2001 From: FelixKim Date: Fri, 20 May 2022 12:48:49 +0900 Subject: [PATCH 1/7] remove stable token dependency, treasury module --- contracts/campaign/src/executions.rs | 13 +-- .../src/tests/claim_participation_reward.rs | 3 +- contracts/campaign/src/tests/deposit.rs | 14 +-- .../campaign/src/tests/remove_reward_pool.rs | 30 +++--- contracts/campaign/src/tests/states.rs | 1 - contracts/campaign/src/tests/withdraw.rs | 2 +- .../campaign_manager/src/tests/swap_fee.rs | 69 +++----------- contracts/vp/src/entrypoints.rs | 3 - contracts/vp/src/executions.rs | 95 +------------------ contracts/vp/src/msg.rs | 2 - packages/valkyrie/src/message_factories.rs | 12 +-- packages/valkyrie/src/mock_querier.rs | 95 +------------------ packages/valkyrie/src/terra.rs | 50 +--------- packages/valkyrie/src/test_constants.rs | 6 +- 14 files changed, 41 insertions(+), 354 deletions(-) diff --git a/contracts/campaign/src/executions.rs b/contracts/campaign/src/executions.rs index b9e78d9..d39c661 100644 --- a/contracts/campaign/src/executions.rs +++ b/contracts/campaign/src/executions.rs @@ -606,7 +606,6 @@ pub fn remove_reward_pool( campaign_state.withdraw(&denom_cw20, &remove_pool_fee_amount)?; response = response.add_message(make_send_msg( - &deps.querier, denom_cw20.clone(), remove_pool_fee_amount, &campaign_config.campaign_manager, @@ -615,7 +614,6 @@ pub fn remove_reward_pool( campaign_state.withdraw(&denom_cw20, &receive_amount)?; response = response.add_message(make_send_msg( - &deps.querier, denom_cw20, receive_amount, &info.sender, @@ -656,7 +654,6 @@ pub fn claim_participation_reward(deps: DepsMut, env: Env, info: MessageInfo) -> let mut response = make_response("claim_participation_reward"); response = response.add_message(make_send_msg( - &deps.querier, reward_config.participation_reward_denom.clone(), reward_amount, &actor.address, @@ -705,7 +702,6 @@ pub fn claim_referral_reward(deps: DepsMut, env: Env, info: MessageInfo) -> Cont let mut response = make_response("claim_referral_reward"); response = response.add_message(make_send_msg( - &deps.querier, cw20::Denom::Cw20(reward_config.referral_reward_token), reward_amount, &actor.address, @@ -1219,7 +1215,6 @@ pub fn withdraw( campaign_state.save(deps.storage)?; response = response.add_message(make_send_msg( - &deps.querier, denom, amount, &info.sender, @@ -1308,22 +1303,20 @@ pub fn validate_participation_reward_distribution_schedule(schedule: &Vec<(u64, } fn make_send_msg( - querier: &QuerierWrapper, denom: Cw20Denom, - amount_with_tax: Uint128, + amount: Uint128, recipient: &Addr, ) -> StdResult { match denom { Cw20Denom::Native(denom) => Ok(message_factories::native_send( - querier, denom, recipient, - amount_with_tax, + amount, )?), Cw20Denom::Cw20(contract_address) => Ok(message_factories::cw20_transfer( &contract_address, recipient, - amount_with_tax, + amount, )), } } diff --git a/contracts/campaign/src/tests/claim_participation_reward.rs b/contracts/campaign/src/tests/claim_participation_reward.rs index 3c1b3f1..3c5306c 100644 --- a/contracts/campaign/src/tests/claim_participation_reward.rs +++ b/contracts/campaign/src/tests/claim_participation_reward.rs @@ -25,7 +25,6 @@ pub fn will_success(deps: &mut CustomDeps, height: u64, sender: &str) -> (Env, M #[test] fn succeed() { let mut deps = custom_deps(); - deps.querier.with_tax(Decimal::percent(10), &[("uusd", &Uint128::new(100))]); super::instantiate::default(&mut deps); super::update_activation::will_success(&mut deps, true); @@ -48,7 +47,7 @@ fn succeed() { SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: participator.to_string(), amount: vec![coin( - 2900, //subtracted tax + 3000, //subtracted tax PARTICIPATION_REWARD_DENOM_NATIVE.to_string(), )], })), diff --git a/contracts/campaign/src/tests/deposit.rs b/contracts/campaign/src/tests/deposit.rs index b49951a..1586376 100644 --- a/contracts/campaign/src/tests/deposit.rs +++ b/contracts/campaign/src/tests/deposit.rs @@ -31,7 +31,7 @@ pub fn will_success( amount: Uint128, ) -> (Env, MessageInfo, Response) { let env = campaign_env(); - let info = mock_info(sender, &[coin(amount.u128(), "uusd")]); + let info = mock_info(sender, &[coin(amount.u128(), "uluna")]); let response = exec( deps, @@ -93,18 +93,6 @@ fn failed_invalid_funds() { ); assert_eq!(result.unwrap_err(), ContractError::Std(StdError::generic_err("Missing deposit denom"))); - let result = exec( - &mut deps, - campaign_env(), - mock_info("Actor", &[]), - "Actor", - vec![ - (Denom::Native("uluna".to_string()), Uint128::new(100)), - (Denom::Native("ukrw".to_string()), Uint128::new(100)), - ], - ); - assert_eq!(result.unwrap_err(), ContractError::Std(StdError::generic_err("Too many sent denom"))); - let result = exec( &mut deps, campaign_env(), diff --git a/contracts/campaign/src/tests/remove_reward_pool.rs b/contracts/campaign/src/tests/remove_reward_pool.rs index 7343887..4a35a57 100644 --- a/contracts/campaign/src/tests/remove_reward_pool.rs +++ b/contracts/campaign/src/tests/remove_reward_pool.rs @@ -5,7 +5,6 @@ use valkyrie::campaign::enumerations::Referrer; use valkyrie::common::{ContractResult, Denom}; use valkyrie::message_matchers; use valkyrie::mock_querier::{custom_deps, CustomDeps}; -use valkyrie::terra::extract_tax; use valkyrie::test_constants::{default_sender, VALKYRIE_TOKEN}; use valkyrie::test_constants::campaign::{CAMPAIGN, CAMPAIGN_ADMIN, campaign_admin_sender, campaign_env, PARTICIPATION_REWARD_AMOUNT, PARTICIPATION_REWARD_DENOM_NATIVE, REFERRAL_REWARD_AMOUNTS}; use valkyrie::test_constants::campaign_manager::CAMPAIGN_MANAGER; @@ -24,7 +23,7 @@ pub fn exec( let response = remove_reward_pool(deps.as_mut(), env, info, denom, amount)?; for msg in message_matchers::native_send(&response.messages) { - deps.querier.minus_native_balance_with_tax(CAMPAIGN, msg.amount.clone()); + deps.querier.minus_native_balance(CAMPAIGN, msg.amount.clone()); deps.querier.plus_native_balance(msg.to_address.as_str(), msg.amount); } @@ -64,30 +63,27 @@ pub fn will_success( #[test] fn succeed_at_pending() { let mut deps = custom_deps(); - deps.querier.with_tax(Decimal::percent(10), &[("uusd", &Uint128::new(100))]); super::instantiate::default(&mut deps); super::add_reward_pool::will_success(&mut deps, 10000, 10000); let mut denom = Denom::Native(PARTICIPATION_REWARD_DENOM_NATIVE.to_string()); let amount = Uint128::new(4000); - let tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), amount).unwrap(); let (_, _, response) = will_success(&mut deps, denom.clone(), Some(amount)); assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_ADMIN.to_string(), - amount: vec![coin(amount.checked_sub(tax).unwrap().u128(), "uusd")], + amount: vec![coin(amount.u128(), "uluna")], })), ]); let remain_amount = Uint128::new(6000); - let tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), remain_amount).unwrap(); let (_, _, response) = will_success(&mut deps, denom.clone(), None); assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_ADMIN.to_string(), - amount: vec![coin(remain_amount.checked_sub(tax).unwrap().u128(), "uusd")], + amount: vec![coin(remain_amount.u128(), "uluna")], })), ]); @@ -121,7 +117,6 @@ fn succeed_at_pending() { #[test] fn succeed_at_active() { let mut deps = custom_deps(); - deps.querier.with_tax(Decimal::percent(10), &[("uusd", &Uint128::new(100))]); let burn_rate = Decimal::percent(10); @@ -129,37 +124,34 @@ fn succeed_at_active() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, 10000, 10000); - let mut denom = Denom::Native("uusd".to_string()); + let mut denom = Denom::Native("uluna".to_string()); let amount = Uint128::new(4000); let (burn_amount, expect_amount) = calc_ratio_amount(amount, burn_rate); - let burn_tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), burn_amount).unwrap(); - let expect_tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), expect_amount).unwrap(); let (_, _, response) = will_success(&mut deps, denom.clone(), Some(amount)); assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_MANAGER.to_string(), - amount: vec![coin(burn_amount.checked_sub(burn_tax).unwrap().u128(), "uusd")], + amount: vec![coin(burn_amount.u128(), "uluna")], })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_ADMIN.to_string(), - amount: vec![coin(expect_amount.checked_sub(expect_tax).unwrap().u128(), "uusd")], + amount: vec![coin(expect_amount.u128(), "uluna")], })), ]); let remain_amount = Uint128::new(6000); let (burn_amount, expect_amount) = calc_ratio_amount(remain_amount, burn_rate); - let burn_tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), burn_amount).unwrap(); - let expect_tax = extract_tax(&deps.as_ref().querier, "uusd".to_string(), expect_amount).unwrap(); + let (_, _, response) = will_success(&mut deps, denom.clone(), None); assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_MANAGER.to_string(), - amount: vec![coin(burn_amount.checked_sub(burn_tax).unwrap().u128(), "uusd")], + amount: vec![coin(burn_amount.u128(), "uluna")], })), SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: CAMPAIGN_ADMIN.to_string(), - amount: vec![coin(expect_amount.checked_sub(expect_tax).unwrap().u128(), "uusd")], + amount: vec![coin(expect_amount.u128(), "uluna")], })), ]); @@ -248,7 +240,7 @@ fn failed_invalid_permission() { &mut deps, campaign_env(), default_sender(), - Denom::Native("uusd".to_string()), + Denom::Native("uluna".to_string()), None, ); @@ -266,7 +258,7 @@ fn failed_overflow() { &mut deps, campaign_env(), campaign_admin_sender(), - Denom::Native("uusd".to_string()), + Denom::Native("uluna".to_string()), Some(Uint128::new(6001)), ); expect_generic_err(&result, "Insufficient balance"); diff --git a/contracts/campaign/src/tests/states.rs b/contracts/campaign/src/tests/states.rs index bb14b42..ca80606 100644 --- a/contracts/campaign/src/tests/states.rs +++ b/contracts/campaign/src/tests/states.rs @@ -8,7 +8,6 @@ use crate::queries::{get_actor}; #[test] fn calc_unlocked_reward() { let mut deps = custom_deps(); - deps.querier.with_tax(Decimal::percent(10), &[("uusd", &Uint128::new(100))]); super::instantiate::default(&mut deps); super::update_activation::will_success(&mut deps, true); diff --git a/contracts/campaign/src/tests/withdraw.rs b/contracts/campaign/src/tests/withdraw.rs index ccb2b0c..296a7b6 100644 --- a/contracts/campaign/src/tests/withdraw.rs +++ b/contracts/campaign/src/tests/withdraw.rs @@ -45,7 +45,7 @@ fn succeed() { let (_, _, response) = will_success(&mut deps, "Actor", withdraw_amount); assert_eq!(response.messages, vec![SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: "Actor".to_string(), - amount: vec![coin(withdraw_amount.u128(), "uusd")], + amount: vec![coin(withdraw_amount.u128(), "uluna")], }))]); } diff --git a/contracts/campaign_manager/src/tests/swap_fee.rs b/contracts/campaign_manager/src/tests/swap_fee.rs index 772aeb7..6f67ab1 100644 --- a/contracts/campaign_manager/src/tests/swap_fee.rs +++ b/contracts/campaign_manager/src/tests/swap_fee.rs @@ -55,12 +55,12 @@ fn succeed_native() { super::instantiate::default(&mut deps); deps.querier.plus_native_balance(CAMPAIGN_MANAGER, vec![ - coin(10000u128, "uusd"), + coin(10000u128, "uluna"), ]); let (_, _, response) = will_success( &mut deps, - Denom::Native("uusd".to_string()), + Denom::Native("uluna".to_string()), None, None, ); @@ -68,12 +68,12 @@ fn succeed_native() { assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: TERRASWAP_ROUTER.to_string(), - funds: vec![coin(10000, "uusd")], + funds: vec![coin(10000, "uluna")], msg: to_binary(&ExecuteMsg::ExecuteSwapOperations { operations: vec![ SwapOperation::TerraSwap { offer_asset_info: AssetInfo::NativeToken { - denom: "uusd".to_string(), + denom: "uluna".to_string(), }, ask_asset_info: AssetInfo::Token { contract_addr: Addr::unchecked(VALKYRIE_TOKEN).to_string(), @@ -137,16 +137,15 @@ fn succeed_route() { super::instantiate::default(&mut deps); deps.querier.plus_native_balance(CAMPAIGN_MANAGER, vec![ - coin(10000u128, "ukrw"), + coin(10000u128, "uluna"), ]); let (_, _, response) = will_success( &mut deps, - Denom::Native("ukrw".to_string()), + Denom::Native("uluna".to_string()), None, Some(vec![ - Denom::Native("ukrw".to_string()), - Denom::Native("uusd".to_string()), + Denom::Native("uluna".to_string()), Denom::Token(VALKYRIE_TOKEN.to_string()), ]), ); @@ -154,16 +153,12 @@ fn succeed_route() { assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: TERRASWAP_ROUTER.to_string(), - funds: vec![coin(10000, "ukrw")], + funds: vec![coin(10000, "uluna")], msg: to_binary(&ExecuteMsg::ExecuteSwapOperations { operations: vec![ - SwapOperation::NativeSwap { - offer_denom: "ukrw".to_string(), - ask_denom: "uusd".to_string(), - }, SwapOperation::TerraSwap { offer_asset_info: AssetInfo::NativeToken { - denom: "uusd".to_string(), + denom: "uluna".to_string(), }, ask_asset_info: AssetInfo::Token { contract_addr: Addr::unchecked(VALKYRIE_TOKEN).to_string(), @@ -184,62 +179,24 @@ fn failed_invalid_route() { super::instantiate::default(&mut deps); deps.querier.plus_native_balance(CAMPAIGN_MANAGER, vec![ - coin(10000u128, "ukrw"), + coin(10000u128, "uluna"), ]); let result = exec( &mut deps, campaign_manager_env(), default_sender(), - Denom::Native("ukrw".to_string()), - None, - Some(vec![ - Denom::Native("ukrw".to_string()), - ]), - ); - expect_generic_err( - &result, - format!( - "route must start with '{}' and end with '{}'", - "ukrw".to_string(), VALKYRIE_TOKEN.to_string(), - ).as_str(), - ); - - let result = exec( - &mut deps, - campaign_manager_env(), - default_sender(), - Denom::Native("ukrw".to_string()), - None, - Some(vec![ - Denom::Native("uusd".to_string()), - Denom::Token(VALKYRIE_TOKEN.to_string()), - ]), - ); - expect_generic_err( - &result, - format!( - "route must start with '{}' and end with '{}'", - "ukrw".to_string(), VALKYRIE_TOKEN.to_string(), - ).as_str(), - ); - - let result = exec( - &mut deps, - campaign_manager_env(), - default_sender(), - Denom::Native("ukrw".to_string()), + Denom::Native("uluna".to_string()), None, Some(vec![ - Denom::Native("ukrw".to_string()), - Denom::Native("uusd".to_string()), + Denom::Native("uluna".to_string()), ]), ); expect_generic_err( &result, format!( "route must start with '{}' and end with '{}'", - "ukrw".to_string(), VALKYRIE_TOKEN.to_string(), + "uluna".to_string(), VALKYRIE_TOKEN.to_string(), ).as_str(), ); } diff --git a/contracts/vp/src/entrypoints.rs b/contracts/vp/src/entrypoints.rs index 8bad258..5f57034 100644 --- a/contracts/vp/src/entrypoints.rs +++ b/contracts/vp/src/entrypoints.rs @@ -8,7 +8,6 @@ use crate::queries::{query_config, query_state, query_swap_state}; use crate::state::{Config}; use cw20_base::ContractError; use cw2::set_contract_version; -use crate::executions::{mint_from_uusd, mint_from_uusd_hook}; use crate::migrations; const CONTRACT_NAME: &str = "valkyrian-pass-cw20-token"; @@ -123,8 +122,6 @@ pub fn execute( cw20_base::contract::execute_mint(deps, env, info, recipient, amount) }, - ExecuteMsg::MintFromUusd {} => mint_from_uusd(deps, env, info), - ExecuteMsg::MintFromUusdHook { burner, exist_balance } => mint_from_uusd_hook(deps, env, info, burner, exist_balance), ExecuteMsg::UpdateMarketing { project, description, diff --git a/contracts/vp/src/executions.rs b/contracts/vp/src/executions.rs index dea22b5..0126945 100644 --- a/contracts/vp/src/executions.rs +++ b/contracts/vp/src/executions.rs @@ -1,14 +1,8 @@ -use astroport::asset::{Asset, AssetInfo}; -use astroport::querier::query_token_balance; -use astroport::router::{ExecuteMsg as AstroExecuteMsg, SwapOperation}; -use cosmwasm_std::{Addr, Coin, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response, StdError, StdResult, SubMsg, to_binary, Uint128, WasmMsg}; -use crate::msg::{ExecuteMsg}; +use cosmwasm_std::{Addr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response, StdError, StdResult, to_binary, Uint128, WasmMsg}; use crate::state::{Config, State, SwapRatio, SwapState}; use cw20::Cw20ExecuteMsg; use cw20_base::ContractError; -static UST:&str = "uusd"; - pub fn update_config( deps: DepsMut, _env: Env, @@ -133,91 +127,4 @@ pub fn approve_admin_nominee( config.save(deps.storage)?; Ok(response) -} - -pub fn mint_from_uusd( - deps: DepsMut, - env: Env, - info: MessageInfo, -) -> Result { - let mut uusd_asset = Asset { - info: AssetInfo::NativeToken { - denom: UST.to_string() - }, - amount: Uint128::zero() - }; - - for fund in info.funds.iter() { - if fund.denom == UST.to_string() { - uusd_asset.amount += fund.amount; - } else { - return Err(ContractError::Std(StdError::generic_err("allowed uusd only.".to_string()))); - } - } - - if uusd_asset.amount.is_zero() { - return Err(ContractError::Std(StdError::generic_err("uusd amount is zero".to_string()))); - } - - let config = Config::load(deps.storage)?; - let mut response = Response::new().add_attribute("action", "mint_from_uusd"); - - // UST => VKR - response.messages.push(SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: config.router.to_string(), - funds: vec![ - Coin { - denom: UST.to_string(), - amount: uusd_asset.amount - uusd_asset.compute_tax(&deps.querier)? - } - ], - msg: to_binary(&AstroExecuteMsg::ExecuteSwapOperations { - // AstroExecuteMsg::ExecuteSwapOperations => OK - // AstroExecuteMsg::ExecuteSwapOperation => Unauthorized - operations: vec![ - SwapOperation::AstroSwap { - offer_asset_info: uusd_asset.info, - ask_asset_info: AssetInfo::Token { - contract_addr: config.offer_token.clone() - } - } - ], - minimum_receive: None, - to: Some(env.contract.address.clone()) - })?, - }))); - - let exist_balance = query_token_balance(&deps.querier, config.offer_token, env.contract.address.clone())?; - - response.messages.push(SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: env.contract.address.to_string(), - funds: vec![], - msg: to_binary(&ExecuteMsg::MintFromUusdHook { - burner: info.sender.to_string(), - exist_balance, - })?, - }))); - - Ok(response) -} - -pub fn mint_from_uusd_hook( - deps: DepsMut, - env: Env, - info: MessageInfo, - burner: String, - exist_balance: Uint128, -) -> Result { - let contract_address = env.clone().contract.address; - - if info.sender.to_string() != contract_address.to_string() { - return Err(ContractError::Unauthorized {}); - } - - let config = Config::load(deps.storage)?; - let now_balance = query_token_balance(&deps.querier, config.offer_token, contract_address.clone())?; - let burn_amount = now_balance - exist_balance; - - //send VKR to this(VP token contract). to burn VKR and mint VP - mint(deps, env, info, burner, burn_amount) } \ No newline at end of file diff --git a/contracts/vp/src/msg.rs b/contracts/vp/src/msg.rs index 0e98fc3..0ba1ee1 100644 --- a/contracts/vp/src/msg.rs +++ b/contracts/vp/src/msg.rs @@ -67,8 +67,6 @@ pub enum ExecuteMsg { /// Only with the "mintable" extension. If authorized, creates amount new tokens /// and adds to the recipient balance. Mint { recipient: String, amount: Uint128 }, - MintFromUusd {}, - MintFromUusdHook { burner: String, exist_balance: Uint128 }, UpdateMarketing { /// A URL pointing to the project behind this token. project: Option, diff --git a/packages/valkyrie/src/message_factories.rs b/packages/valkyrie/src/message_factories.rs index 6a64729..de467a5 100644 --- a/packages/valkyrie/src/message_factories.rs +++ b/packages/valkyrie/src/message_factories.rs @@ -1,23 +1,19 @@ use cosmwasm_std::{ - Addr, BankMsg, Binary, Coin, CosmosMsg, QuerierWrapper, StdResult, to_binary, Uint128, WasmMsg, + Addr, BankMsg, Binary, Coin, CosmosMsg, StdResult, to_binary, Uint128, WasmMsg, }; use cw20::Cw20ExecuteMsg; use serde::Serialize; -use crate::terra::extract_tax; - pub fn native_send( - querier: &QuerierWrapper, denom: String, recipient: &Addr, - amount_with_tax: Uint128, + amount: Uint128, ) -> StdResult { - let tax = extract_tax(querier, denom.to_string(), amount_with_tax)?; - + //only luna Ok(CosmosMsg::Bank(BankMsg::Send { to_address: recipient.to_string(), amount: vec![Coin { - amount: amount_with_tax.checked_sub(tax)?, + amount, denom, }], })) diff --git a/packages/valkyrie/src/mock_querier.rs b/packages/valkyrie/src/mock_querier.rs index c45edaa..1163b0b 100644 --- a/packages/valkyrie/src/mock_querier.rs +++ b/packages/valkyrie/src/mock_querier.rs @@ -1,11 +1,10 @@ use std::collections::HashMap; -use cosmwasm_std::{Api, Binary, CanonicalAddr, Coin, ContractResult, Decimal, from_slice, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, to_binary, Uint128, WasmQuery, from_binary, BankQuery, AllBalanceResponse, Addr, QuerierWrapper}; +use cosmwasm_std::{Api, Binary, CanonicalAddr, Coin, ContractResult, Decimal, from_slice, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, to_binary, Uint128, WasmQuery, from_binary, BankQuery, AllBalanceResponse, Addr}; use cosmwasm_std::testing::{MOCK_CONTRACT_ADDR, MockApi, MockQuerier, MockStorage}; use cw20::{TokenInfoResponse, Cw20QueryMsg}; -use terra_cosmwasm::{TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper, TerraRoute}; +use terra_cosmwasm::{TerraQueryWrapper}; use crate::governance::query_msgs::{QueryMsg as GovQueryMsg, VotingPowerResponse, ContractConfigResponse as GovContractConfigResponse, StakerStateResponse}; -use crate::terra::calc_tax_one_plus; use crate::campaign::query_msgs::{CampaignStateResponse, QueryMsg}; use crate::campaign_manager::query_msgs::{QueryMsg as CampaignManagerQueryMsg, ConfigResponse, ReferralRewardLimitOptionResponse}; @@ -33,7 +32,6 @@ pub fn custom_deps() -> CustomDeps { pub struct WasmMockQuerier { base: MockQuerier, token_querier: TokenQuerier, - tax_querier: TaxQuerier, voting_powers_querier: VotingPowerQuerier, campaign_manager_config_querier: CampaignManagerConfigQuerier, governance_querier: GovConfigQuerier, @@ -153,30 +151,6 @@ pub(crate) fn balances_to_map( balances_map } -#[derive(Clone, Default)] -pub struct TaxQuerier { - rate: Decimal, - // this lets us iterate over all pairs that match the first string - caps: HashMap, -} - -impl TaxQuerier { - pub fn new(rate: Decimal, caps: &[(&str, &Uint128)]) -> Self { - TaxQuerier { - rate, - caps: caps_to_map(caps), - } - } -} - -pub(crate) fn caps_to_map(caps: &[(&str, &Uint128)]) -> HashMap { - let mut owner_map: HashMap = HashMap::new(); - for (denom, cap) in caps.iter() { - owner_map.insert(denom.to_string(), **cap); - } - owner_map -} - impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here @@ -196,9 +170,6 @@ impl Querier for WasmMockQuerier { impl WasmMockQuerier { pub fn handle_query(&self, request: &QueryRequest) -> QuerierResult { match &request { - QueryRequest::Custom( - TerraQueryWrapper { route, query_data } - ) => self.handle_custom(route, query_data), QueryRequest::Wasm( WasmQuery::Raw { contract_addr, key } ) => self.handle_wasm_raw(contract_addr, key), @@ -208,24 +179,6 @@ impl WasmMockQuerier { _ => self.base.handle_query(request), } } - fn handle_custom(&self, route: &TerraRoute, query_data: &TerraQuery) -> QuerierResult { - match route { - TerraRoute::Treasury => self.handle_custom_treasury(query_data), - _ => return QuerierResult::Err(SystemError::UnsupportedRequest { - kind: "handle_custom".to_string(), - }), - } - } - - fn handle_custom_treasury(&self, query_data: &TerraQuery) -> QuerierResult { - match query_data { - TerraQuery::TaxRate {} => self.query_tax_rate(), - TerraQuery::TaxCap { denom } => self.query_tax_cap(denom), - _ => return QuerierResult::Err(SystemError::UnsupportedRequest { - kind: "handle_custom_treasury".to_string(), - }), - } - } fn handle_wasm_raw(&self, contract_addr: &String, key: &Binary) -> QuerierResult { let key: &[u8] = key.as_slice(); @@ -404,27 +357,6 @@ impl WasmMockQuerier { } } - fn query_tax_rate(&self) -> QuerierResult { - let response = TaxRateResponse { - rate: self.tax_querier.rate, - }; - - SystemResult::Ok(ContractResult::Ok(to_binary(&response).unwrap())) - } - - fn query_tax_cap(&self, denom: &String) -> QuerierResult { - let response = TaxCapResponse { - cap: self - .tax_querier - .caps - .get(denom) - .copied() - .unwrap_or_default(), - }; - - SystemResult::Ok(ContractResult::Ok(to_binary(&response).unwrap())) - } - fn query_token_info(&self, contract_addr: &String, key: &[u8]) -> Option { if key.to_vec() != to_length_prefixed(b"token_info").to_vec() { return None; @@ -511,7 +443,6 @@ impl WasmMockQuerier { WasmMockQuerier { base, token_querier: TokenQuerier::default(), - tax_querier: TaxQuerier::default(), campaign_manager_config_querier: CampaignManagerConfigQuerier::default(), voting_powers_querier: VotingPowerQuerier::default(), governance_querier: GovConfigQuerier::default(), @@ -602,11 +533,6 @@ impl WasmMockQuerier { } } - // configure the token owner mock querier - pub fn with_tax(&mut self, rate: Decimal, caps: &[(&str, &Uint128)]) { - self.tax_querier = TaxQuerier::new(rate, caps); - } - pub fn plus_native_balance(&mut self, address: &str, balances: Vec) { let mut current_balances = from_binary::( &self.base.handle_query( @@ -650,23 +576,6 @@ impl WasmMockQuerier { self.base.update_balance(Addr::unchecked(address.to_string()), current_balances); } - pub fn minus_native_balance_with_tax(&mut self, address: &str, mut balances: Vec) { - for balance in balances.iter_mut() { - if balance.denom == "uluna" { - return; - } - - let tax = calc_tax_one_plus( - &QuerierWrapper::new(self), - balance.denom.clone(), - balance.amount, - ).unwrap(); - balance.amount = balance.amount + tax; - } - - self.minus_native_balance(address, balances) - } - pub fn with_balance(&mut self, balances: &[(&str, &[Coin])]) { for (addr, balance) in balances { self.base.update_balance(Addr::unchecked(addr.to_string()), balance.to_vec()); diff --git a/packages/valkyrie/src/terra.rs b/packages/valkyrie/src/terra.rs index e2ee509..280a0e8 100644 --- a/packages/valkyrie/src/terra.rs +++ b/packages/valkyrie/src/terra.rs @@ -1,54 +1,6 @@ -use cosmwasm_std::{Addr, QuerierWrapper, StdResult, Uint128}; +use cosmwasm_std::{Addr, QuerierWrapper, StdResult}; use terra_cosmwasm::TerraQuerier; -use crate::utils::calc_ratio_amount; - -// amount = tax + send_amount -pub fn extract_tax(querier: &QuerierWrapper, denom: String, amount: Uint128) -> StdResult { - if denom == "uluna" { - return Ok(Uint128::zero()); - } - - let querier = TerraQuerier::new(querier); - let rate = querier.query_tax_rate()?.rate; - let tax = calc_ratio_amount(amount, rate).0; - let cap = querier.query_tax_cap(denom)?.cap; - - Ok(std::cmp::min(tax, cap)) -} - -// amount = send_amount -pub fn calc_tax(querier: &QuerierWrapper, denom: String, amount: Uint128) -> StdResult { - if denom == "uluna" { - return Ok(Uint128::zero()); - } - - let querier = TerraQuerier::new(querier); - let rate = querier.query_tax_rate()?.rate; - let tax = Uint128::from(amount) * rate; - - let cap = querier.query_tax_cap(denom)?.cap; - - Ok(std::cmp::min(tax, cap)) -} - -// amount = send_amount -//extract_tax 와 비교했을 때 소수점으로 인해 1만큼의 오차가 높은 확률로 발생함. -//테스트 케이스 작성 편의를 위해 계산된 tax 에 1만큼 더한 값을 사용함. -pub fn calc_tax_one_plus(querier: &QuerierWrapper, denom: String, amount: Uint128) -> StdResult { - if denom == "uluna" { - return Ok(Uint128::zero()); - } - - let querier = TerraQuerier::new(querier); - let rate = querier.query_tax_rate()?.rate; - let tax = Uint128::from(amount) * rate + Uint128::from(1u128); - - let cap = querier.query_tax_cap(denom)?.cap; - - Ok(std::cmp::min(tax, cap)) -} - pub fn is_contract(querier: &QuerierWrapper, address: &Addr) -> StdResult { let querier = TerraQuerier::new(querier); diff --git a/packages/valkyrie/src/test_constants.rs b/packages/valkyrie/src/test_constants.rs index aebac4e..c22e68a 100644 --- a/packages/valkyrie/src/test_constants.rs +++ b/packages/valkyrie/src/test_constants.rs @@ -119,7 +119,7 @@ pub mod campaign_manager { pub const FEE_BURN_RATIO_PERCENT: u64 = 50; pub const FEE_RECIPIENT: &str = GOVERNANCE; pub const CAMPAIGN_DEACTIVATE_PERIOD: u64 = 403290; - pub const KEY_DENOM_NATIVE: &str = "uusd"; + pub const KEY_DENOM_NATIVE: &str = "uluna"; pub const REFERRAL_REWARD_LIMIT_BASE_COUNT: u8 = 5; pub const REFERRAL_REWARD_LIMIT_STAKING_PERCENT: u16 = 50; @@ -144,7 +144,7 @@ pub mod campaign { pub const CAMPAIGN_URL: &str = "https://campaign.url"; pub const CAMPAIGN_PARAMETER_KEY: &str = "vkr"; pub const CAMPAIGN_ADMIN: &str = "CampaignAdmin"; - pub const PARTICIPATION_REWARD_DENOM_NATIVE: &str = "uusd"; + pub const PARTICIPATION_REWARD_DENOM_NATIVE: &str = "uluna"; pub const PARTICIPATION_REWARD_AMOUNT: Uint128 = Uint128::new(3000); pub const PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE1: (u64, u64, Uint128) = (10, 10, Uint128::new(300)); //start, end, amount @@ -154,7 +154,7 @@ pub mod campaign { pub const REFERRAL_REWARD_AMOUNTS: [Uint128; 3] = [Uint128::new(400), Uint128::new(300), Uint128::new(200)]; pub const REFERRAL_REWARD_LOCK_PERIOD: u64 = 100; pub const QUALIFIER: &str = "Qualifier"; - pub const DEPOSIT_DENOM_NATIVE: &str = "uusd"; + pub const DEPOSIT_DENOM_NATIVE: &str = "uluna"; pub const DEPOSIT_AMOUNT: Uint128 = Uint128::new(100); pub const DEPOSIT_LOCK_PERIOD: u64 = 10000; pub const VP_BURN_AMOUNT: Uint128 = Uint128::new(0); From e38d752e26650acab18df42f609b4f14d9be97e6 Mon Sep 17 00:00:00 2001 From: FelixKim Date: Wed, 15 Jun 2022 14:16:22 +0900 Subject: [PATCH 2/7] added valkyrie proxy --- Cargo.lock | 401 +++++++++++++----- README.md | 3 - contracts/campaign/Cargo.toml | 12 +- contracts/campaign/schema/actor_response.json | 41 +- .../campaign/schema/actors_response.json | 41 +- .../campaign/schema/campaign_config_msg.json | 34 +- .../schema/campaign_config_response.json | 12 +- .../schema/campaign_instantiate_msg.json | 12 +- .../schema/campaign_state_response.json | 2 +- contracts/campaign/schema/cw20_hook_msg.json | 2 +- .../campaign/schema/distribute_result.json | 2 +- contracts/campaign/schema/execute_msg.json | 52 ++- contracts/campaign/schema/query_msg.json | 4 +- contracts/campaign/schema/referrer.json | 2 +- .../schema/reward_config_response.json | 34 +- contracts/campaign/src/entrypoints.rs | 2 +- contracts/campaign/src/executions.rs | 52 ++- .../campaign/src/tests/add_reward_pool.rs | 2 +- .../src/tests/claim_participation_reward.rs | 8 +- .../src/tests/claim_referral_reward.rs | 10 +- contracts/campaign/src/tests/deposit.rs | 16 +- contracts/campaign/src/tests/participate.rs | 66 ++- .../campaign/src/tests/remove_reward_pool.rs | 14 +- .../src/tests/set_no_qualification.rs | 4 +- contracts/campaign/src/tests/states.rs | 8 +- .../src/tests/update_campaign_config.rs | 10 +- contracts/campaign_manager/Cargo.toml | 14 +- .../schema/campaign_instantiate_msg.json | 12 +- .../schema/config_response.json | 12 +- .../campaign_manager/schema/execute_msg.json | 22 +- .../schema/instantiate_msg.json | 12 +- .../campaign_manager/schema/migrate_msg.json | 6 +- .../campaign_manager/schema/query_msg.json | 2 +- contracts/campaign_manager/src/entrypoints.rs | 26 +- contracts/campaign_manager/src/executions.rs | 40 +- .../campaign_manager/src/migrations/mod.rs | 4 +- .../campaign_manager/src/migrations/v106.rs | 118 +++--- .../src/migrations/v108_beta0.rs | 120 +++--- contracts/campaign_manager/src/queries.rs | 2 +- contracts/campaign_manager/src/states.rs | 2 +- .../src/tests/created_campaign.rs | 8 +- .../campaign_manager/src/tests/instantiate.rs | 10 +- .../campaign_manager/src/tests/swap_fee.rs | 33 +- .../src/tests/update_config.rs | 24 +- .../update_referral_reward_limit_option.rs | 2 +- contracts/community/Cargo.toml | 11 +- contracts/community/schema/execute_msg.json | 2 +- contracts/community/schema/query_msg.json | 2 +- .../community/src/tests/decrease_allowance.rs | 6 +- .../community/src/tests/increase_allowance.rs | 10 +- .../community/src/tests/update_config.rs | 4 +- contracts/distributor/Cargo.toml | 11 +- contracts/distributor/schema/execute_msg.json | 2 +- contracts/distributor/schema/query_msg.json | 2 +- contracts/distributor/src/tests/distribute.rs | 16 +- .../src/tests/register_distribution.rs | 10 +- .../src/tests/remove_distribution_message.rs | 6 +- .../distributor/src/tests/update_config.rs | 4 +- .../src/tests/update_distribution.rs | 12 +- contracts/governance/Cargo.toml | 11 +- .../governance/schema/cw20_hook_msg.json | 2 +- contracts/governance/schema/execute_msg.json | 2 +- contracts/governance/schema/migrate_msg.json | 51 +-- contracts/governance/schema/query_msg.json | 2 +- .../governance/src/poll/tests/cast_vote.rs | 6 +- .../governance/src/poll/tests/create_poll.rs | 13 +- .../src/poll/tests/reply_execution.rs | 12 +- .../governance/src/staking/executions.rs | 5 +- .../tests/stake_governance_token_hook.rs | 6 +- .../staking/tests/update_staking_config.rs | 2 +- .../src/vp/tests/update_ticket_config.rs | 4 +- contracts/lp_staking/Cargo.toml | 12 +- contracts/lp_staking/README.md | 4 +- .../lp_staking/schema/cw20_hook_msg.json | 2 +- contracts/lp_staking/schema/execute_msg.json | 2 +- contracts/lp_staking/schema/query_msg.json | 2 +- contracts/lp_staking/src/entrypoints.rs | 1 + contracts/lp_staking/src/executions.rs | 2 +- contracts/lp_staking/src/states.rs | 9 +- contracts/lp_staking/src/tests/bond.rs | 4 +- .../lp_staking/src/tests/update_config.rs | 20 +- contracts/proxy/.cargo/config | 6 + contracts/proxy/Cargo.toml | 47 ++ contracts/proxy/README.md | 1 + contracts/proxy/examples/schema.rs | 30 ++ contracts/proxy/schema/asset.json | 68 +++ contracts/proxy/schema/asset_info.json | 47 ++ contracts/proxy/schema/cw20_hook_msg.json | 138 ++++++ contracts/proxy/schema/dex_info.json | 29 ++ contracts/proxy/schema/dex_type.json | 8 + contracts/proxy/schema/execute_msg.json | 284 +++++++++++++ contracts/proxy/schema/instantiate_msg.json | 13 + contracts/proxy/schema/migrate_msg.json | 6 + contracts/proxy/schema/pair_info.json | 84 ++++ contracts/proxy/schema/query_msg.json | 124 ++++++ .../simulate_swap_operations_response.json | 19 + contracts/proxy/schema/swap_operation.json | 77 ++++ contracts/proxy/src/astroport/executions.rs | 93 ++++ contracts/proxy/src/astroport/mod.rs | 4 + contracts/proxy/src/astroport/msgs.rs | 51 +++ contracts/proxy/src/astroport/queries.rs | 69 +++ contracts/proxy/src/entrypoints.rs | 113 +++++ contracts/proxy/src/executions.rs | 210 +++++++++ contracts/proxy/src/lib.rs | 10 + contracts/proxy/src/queries.rs | 140 ++++++ contracts/proxy/src/states.rs | 28 ++ contracts/proxy/src/tests/clear_fixed_dex.rs | 67 +++ contracts/proxy/src/tests/get_largest_pool.rs | 71 ++++ contracts/proxy/src/tests/instantiate.rs | 61 +++ contracts/proxy/src/tests/mod.rs | 4 + contracts/proxy/src/tests/update_config.rs | 89 ++++ contracts/vp/Cargo.toml | 16 +- .../vp/schema/all_allowances_response.json | 2 +- contracts/vp/schema/allowance_response.json | 2 +- contracts/vp/schema/cw20_execute_msg.json | 8 +- contracts/vp/schema/instantiate_msg.json | 4 +- contracts/vp/schema/query_msg.json | 2 +- contracts/vp/src/msg.rs | 3 +- packages/valkyrie/Cargo.toml | 14 +- .../src/campaign_manager/execute_msgs.rs | 4 +- .../src/campaign_manager/query_msgs.rs | 4 +- packages/valkyrie/src/cw20.rs | 16 +- packages/valkyrie/src/lib.rs | 2 +- packages/valkyrie/src/mock_querier.rs | 63 +-- packages/valkyrie/src/proxy/asset.rs | 81 ++++ packages/valkyrie/src/proxy/execute_msgs.rs | 101 +++++ packages/valkyrie/src/proxy/mod.rs | 3 + packages/valkyrie/src/proxy/query_msgs.rs | 20 + packages/valkyrie/src/terra.rs | 9 - packages/valkyrie/src/test_constants.rs | 77 +++- packages/valkyrie/src/tests.rs | 20 +- packages/valkyrie/src/utils.rs | 94 +++- packages/valkyrie_qualifier/Cargo.toml | 6 +- 133 files changed, 3362 insertions(+), 767 deletions(-) create mode 100644 contracts/proxy/.cargo/config create mode 100644 contracts/proxy/Cargo.toml create mode 100644 contracts/proxy/README.md create mode 100644 contracts/proxy/examples/schema.rs create mode 100644 contracts/proxy/schema/asset.json create mode 100644 contracts/proxy/schema/asset_info.json create mode 100644 contracts/proxy/schema/cw20_hook_msg.json create mode 100644 contracts/proxy/schema/dex_info.json create mode 100644 contracts/proxy/schema/dex_type.json create mode 100644 contracts/proxy/schema/execute_msg.json create mode 100644 contracts/proxy/schema/instantiate_msg.json create mode 100644 contracts/proxy/schema/migrate_msg.json create mode 100644 contracts/proxy/schema/pair_info.json create mode 100644 contracts/proxy/schema/query_msg.json create mode 100644 contracts/proxy/schema/simulate_swap_operations_response.json create mode 100644 contracts/proxy/schema/swap_operation.json create mode 100644 contracts/proxy/src/astroport/executions.rs create mode 100644 contracts/proxy/src/astroport/mod.rs create mode 100644 contracts/proxy/src/astroport/msgs.rs create mode 100644 contracts/proxy/src/astroport/queries.rs create mode 100644 contracts/proxy/src/entrypoints.rs create mode 100644 contracts/proxy/src/executions.rs create mode 100644 contracts/proxy/src/lib.rs create mode 100644 contracts/proxy/src/queries.rs create mode 100644 contracts/proxy/src/states.rs create mode 100644 contracts/proxy/src/tests/clear_fixed_dex.rs create mode 100644 contracts/proxy/src/tests/get_largest_pool.rs create mode 100644 contracts/proxy/src/tests/instantiate.rs create mode 100644 contracts/proxy/src/tests/mod.rs create mode 100644 contracts/proxy/src/tests/update_config.rs create mode 100644 packages/valkyrie/src/proxy/asset.rs create mode 100644 packages/valkyrie/src/proxy/execute_msgs.rs create mode 100644 packages/valkyrie/src/proxy/mod.rs create mode 100644 packages/valkyrie/src/proxy/query_msgs.rs delete mode 100644 packages/valkyrie/src/terra.rs diff --git a/Cargo.lock b/Cargo.lock index e07452e..e2cc9e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,19 +3,10 @@ version = 3 [[package]] -name = "astroport" -version = "1.0.1" +name = "base16ct" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b56c6d8a5a14a5f569a3473a962ed1d12bfec2a19ef43584c86aae5667bdeaa8" -dependencies = [ - "cosmwasm-std", - "cw-storage-plus", - "cw20", - "schemars", - "serde", - "terra-cosmwasm", - "uint", -] +checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" [[package]] name = "base64" @@ -23,6 +14,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" +[[package]] +name = "base64ct" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea908e7347a8c64e378c17e30ef880ad73e3b4498346b055c2c00ea342f3179" + [[package]] name = "bigint" version = "4.4.3" @@ -66,6 +63,12 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c32f031ea41b4291d695026c023b95d59db2d8a2c7640800ed56bc8f510f22" +[[package]] +name = "const-oid" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3" + [[package]] name = "cosmwasm-crypto" version = "0.16.3" @@ -73,12 +76,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3703ca1b98c8d890b82c3978f3c5bd47116f8767340dfaa4fd9bdcaa15ebcc64" dependencies = [ "digest", - "ed25519-zebra", - "k256", + "ed25519-zebra 2.2.0", + "k256 0.9.6", "rand_core 0.5.1", "thiserror", ] +[[package]] +name = "cosmwasm-crypto" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb0afef2325df81aadbf9be1233f522ed8f6e91df870c764bc44cca2b1415bd" +dependencies = [ + "digest", + "ed25519-zebra 3.0.0", + "k256 0.10.4", + "rand_core 0.6.3", + "thiserror", +] + [[package]] name = "cosmwasm-derive" version = "0.16.3" @@ -88,11 +104,20 @@ dependencies = [ "syn", ] +[[package]] +name = "cosmwasm-derive" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b36e527620a2a3e00e46b6e731ab6c9b68d11069c986f7d7be8eba79ef081a4" +dependencies = [ + "syn", +] + [[package]] name = "cosmwasm-schema" -version = "0.16.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac9ba1eea088e7f1ec4a7679c43adcb51e80cbc2af6a6d83d1bb652b7adaf6dc" +checksum = "772e80bbad231a47a2068812b723a1ff81dd4a0d56c9391ac748177bea3a61da" dependencies = [ "schemars", "serde_json", @@ -105,11 +130,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c80dbbb380c23a4f10ae6178dd411ed90c9f9931ddf4932156cc5e5ab78d1c19" dependencies = [ "base64", - "cosmwasm-crypto", - "cosmwasm-derive", + "cosmwasm-crypto 0.16.3", + "cosmwasm-derive 0.16.3", "schemars", "serde", - "serde-json-wasm", + "serde-json-wasm 0.3.1", + "thiserror", + "uint", +] + +[[package]] +name = "cosmwasm-std" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875994993c2082a6fcd406937bf0fca21c349e4a624f3810253a14fa83a3a195" +dependencies = [ + "base64", + "cosmwasm-crypto 1.0.0", + "cosmwasm-derive 1.0.0", + "forward_ref", + "schemars", + "serde", + "serde-json-wasm 0.4.1", "thiserror", "uint", ] @@ -120,7 +162,17 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e26053f14f971b05abca3be34f80c631d70c5b5b9df175e7a1d8b4aad83e40cc" dependencies = [ - "cosmwasm-std", + "cosmwasm-std 0.16.3", + "serde", +] + +[[package]] +name = "cosmwasm-storage" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d18403b07304d15d304dad11040d45bbcaf78d603b4be3fb5e2685c16f9229b5" +dependencies = [ + "cosmwasm-std 1.0.0", "serde", ] @@ -157,6 +209,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c6a1d5fa1de37e071642dfa44ec552ca5b299adb128fab16138e24b548fd21" +dependencies = [ + "generic-array", + "rand_core 0.6.3", + "subtle", + "zeroize", +] + [[package]] name = "crypto-mac" version = "0.11.1" @@ -182,22 +246,22 @@ dependencies = [ [[package]] name = "cw-storage-plus" -version = "0.8.1" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1e867b9972b83b32e00e878dfbff48299ba26618dabeb19b9c56fae176dc225" +checksum = "7d7ee1963302b0ac2a9d42fe0faec826209c17452bfd36fbfd9d002a88929261" dependencies = [ - "cosmwasm-std", + "cosmwasm-std 1.0.0", "schemars", "serde", ] [[package]] -name = "cw0" -version = "0.8.1" +name = "cw-utils" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c497f885a40918a02df7d938c81809965fa05cfc21b3dc591e9950237b5de0a9" +checksum = "ef842a1792e4285beff7b3b518705f760fa4111dc1e296e53f3e92d1ef7f6220" dependencies = [ - "cosmwasm-std", + "cosmwasm-std 1.0.0", "schemars", "serde", "thiserror", @@ -205,11 +269,11 @@ dependencies = [ [[package]] name = "cw2" -version = "0.8.1" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d48454f96494aa1018556cd457977375cc8c57ef3e5c767cfa2ea5ec24b0258" +checksum = "c1d81d7c359d6c1fba3aa83dad7ec6f999e512571380ae62f81257c3db569743" dependencies = [ - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "schemars", "serde", @@ -217,25 +281,25 @@ dependencies = [ [[package]] name = "cw20" -version = "0.8.1" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a11a2adbd52258f5b4ed5323f62bc6e559f2cefbe52ef0e58290016fde5bb083" +checksum = "9671d7edef5608acaf5b2f1e473ee3f501eced2cd4f7392e2106c8cf02ba0720" dependencies = [ - "cosmwasm-std", - "cw0", + "cosmwasm-std 1.0.0", + "cw-utils", "schemars", "serde", ] [[package]] name = "cw20-base" -version = "0.8.1" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe3791e0f6b4a0a82b86541d48dcc67c2d607da8e5691a91b40b2c06ddf09c52" +checksum = "62f6fc8c4cd451b418fa4f1ac2ea70595811fa9d8b4033617fe47953d7a93ceb" dependencies = [ - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", - "cw0", + "cw-utils", "cw2", "cw20", "schemars", @@ -249,7 +313,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31e21d2d0f22cde6e88694108429775c0219760a07779bf96503b434a03d7412" dependencies = [ - "const-oid", + "const-oid 0.6.0", +] + +[[package]] +name = "der" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6919815d73839e7ad218de758883aae3a257ba6759ce7a9992501efbb53d705c" +dependencies = [ + "const-oid 0.7.1", ] [[package]] @@ -273,12 +346,24 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43ee23aa5b4f68c7a092b5c3beb25f50c406adc75e2363634f242f28ab255372" dependencies = [ - "der", - "elliptic-curve", + "der 0.4.1", + "elliptic-curve 0.10.5", "hmac", "signature", ] +[[package]] +name = "ecdsa" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d69ae62e0ce582d56380743515fefaf1a8c70cec685d9677636d7e30ae9dc9" +dependencies = [ + "der 0.5.1", + "elliptic-curve 0.11.12", + "rfc6979", + "signature", +] + [[package]] name = "ed25519-zebra" version = "2.2.0" @@ -293,22 +378,55 @@ dependencies = [ "thiserror", ] +[[package]] +name = "ed25519-zebra" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "403ef3e961ab98f0ba902771d29f842058578bb1ce7e3c59dad5a6a93e784c69" +dependencies = [ + "curve25519-dalek", + "hex", + "rand_core 0.6.3", + "serde", + "sha2", + "thiserror", + "zeroize", +] + [[package]] name = "elliptic-curve" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "069397e10739989e400628cbc0556a817a8a64119d7a2315767f4456e1332c23" dependencies = [ - "crypto-bigint", - "ff", + "crypto-bigint 0.2.2", + "ff 0.10.1", "generic-array", - "group", - "pkcs8", + "group 0.10.0", + "pkcs8 0.7.5", "rand_core 0.6.3", "subtle", "zeroize", ] +[[package]] +name = "elliptic-curve" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25b477563c2bfed38a3b7a60964c49e058b2510ad3f12ba3483fd8f62c2306d6" +dependencies = [ + "base16ct", + "crypto-bigint 0.3.2", + "der 0.5.1", + "ff 0.11.1", + "generic-array", + "group 0.11.0", + "rand_core 0.6.3", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "ff" version = "0.10.1" @@ -319,6 +437,22 @@ dependencies = [ "subtle", ] +[[package]] +name = "ff" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "131655483be284720a17d74ff97592b8e76576dc25563148601df2d7c9080924" +dependencies = [ + "rand_core 0.6.3", + "subtle", +] + +[[package]] +name = "forward_ref" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8cbd1169bd7b4a0a20d92b9af7a7e0422888bd38a6f5ec29c1fd8c1558a272e" + [[package]] name = "generic-array" version = "0.14.4" @@ -357,7 +491,18 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c363a5301b8f153d80747126a04b3c82073b9fe3130571a9d170cacdeaf7912" dependencies = [ - "ff", + "ff 0.10.1", + "rand_core 0.6.3", + "subtle", +] + +[[package]] +name = "group" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5ac374b108929de78460075f3dc439fa66df9d8fc77e8f12caa5165fcf0c89" +dependencies = [ + "ff 0.11.1", "rand_core 0.6.3", "subtle", ] @@ -391,8 +536,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "903ae2481bcdfdb7b68e0a9baa4b7c9aff600b9ae2e8e5bb5833b8c91ab851ea" dependencies = [ "cfg-if", - "ecdsa", - "elliptic-curve", + "ecdsa 0.12.4", + "elliptic-curve 0.10.5", + "sha2", +] + +[[package]] +name = "k256" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c3a5e0a0b8450278feda242592512e09f61c72e018b8cd5c859482802daf2d" +dependencies = [ + "cfg-if", + "ecdsa 0.13.4", + "elliptic-curve 0.11.12", + "sec1", "sha2", ] @@ -414,8 +572,19 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbee84ed13e44dd82689fa18348a49934fa79cc774a344c42fc9b301c71b140a" dependencies = [ - "der", - "spki", + "der 0.4.1", + "spki 0.4.0", +] + +[[package]] +name = "pkcs8" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cabda3fb821068a9a4fab19a683eac3af12edf0f34b94a8be53c4972b8149d0" +dependencies = [ + "der 0.5.1", + "spki 0.5.4", + "zeroize", ] [[package]] @@ -463,6 +632,17 @@ dependencies = [ "getrandom 0.2.3", ] +[[package]] +name = "rfc6979" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96ef608575f6392792f9ecf7890c00086591d29a83910939d430753f7c050525" +dependencies = [ + "crypto-bigint 0.3.2", + "hmac", + "zeroize", +] + [[package]] name = "ryu" version = "1.0.5" @@ -471,9 +651,9 @@ checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "schemars" -version = "0.8.3" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6ab463ae35acccb5cba66c0084c985257b797d288b6050cc2f6ac1b266cb78" +checksum = "1847b767a3d62d95cbf3d8a9f0e421cf57a0d8aa4f411d4b16525afb0284d4ed" dependencies = [ "dyn-clone", "schemars_derive", @@ -483,9 +663,9 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.8.3" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "902fdfbcf871ae8f653bddf4b2c05905ddaabc08f69d32a915787e3be0d31356" +checksum = "af4d7e1b012cb3d9129567661a63755ea4b8a7386d339dc945ae187e403c6743" dependencies = [ "proc-macro2", "quote", @@ -493,6 +673,19 @@ dependencies = [ "syn", ] +[[package]] +name = "sec1" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08da66b8b0965a5555b6bd6639e68ccba85e1e2506f5fbb089e93f8a04e1a2d1" +dependencies = [ + "der 0.5.1", + "generic-array", + "pkcs8 0.8.0", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.126" @@ -511,6 +704,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde-json-wasm" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479b4dbc401ca13ee8ce902851b834893251404c4f3c65370a49e047a6be09a5" +dependencies = [ + "serde", +] + [[package]] name = "serde_derive" version = "1.0.126" @@ -524,9 +726,9 @@ dependencies = [ [[package]] name = "serde_derive_internals" -version = "0.25.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dbab34ca63057a1f15280bdf3c39f2b1eb1b54c17e98360e511637aef7418c6" +checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" dependencies = [ "proc-macro2", "quote", @@ -573,7 +775,17 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "987637c5ae6b3121aba9d513f869bd2bff11c4cc086c22473befd6649c0bd521" dependencies = [ - "der", + "der 0.4.1", +] + +[[package]] +name = "spki" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d01ac02a6ccf3e07db148d2be087da624fea0221a16152ed01f0496a6b0a27" +dependencies = [ + "base64ct", + "der 0.5.1", ] [[package]] @@ -599,31 +811,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "terra-cosmwasm" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552f18cba2b535d1f8c0e3b3f37696820b954bc7535d2e33909f2a6342302718" -dependencies = [ - "cosmwasm-std", - "schemars", - "serde", -] - -[[package]] -name = "terraswap" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96f2c2a6371e9ddf2c942368e64645cc3e8fc2855da70c8c6bed238dcdd5522f" -dependencies = [ - "cosmwasm-std", - "cosmwasm-storage", - "cw20", - "schemars", - "serde", - "terra-cosmwasm", -] - [[package]] name = "thiserror" version = "1.0.26" @@ -674,14 +861,12 @@ version = "1.0.8-beta.1" dependencies = [ "bigint", "cosmwasm-schema", - "cosmwasm-std", - "cosmwasm-storage", + "cosmwasm-std 1.0.0", + "cosmwasm-storage 1.0.0", "cw-storage-plus", "cw20", "schemars", "serde", - "terra-cosmwasm", - "terraswap", "thiserror", ] @@ -690,14 +875,12 @@ name = "valkyrie-campaign" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "cw20", "protobuf", "schemars", "serde", - "terra-cosmwasm", - "terraswap", "valkyrie", "valkyrie-qualifier", ] @@ -707,14 +890,12 @@ name = "valkyrie-campaign-manager" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "cw2", "cw20", "schemars", "serde", - "terra-cosmwasm", - "terraswap", "valkyrie", ] @@ -723,12 +904,11 @@ name = "valkyrie-community" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "cw20", "schemars", "serde", - "terra-cosmwasm", "valkyrie", ] @@ -737,12 +917,11 @@ name = "valkyrie-distributor" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "cw20", "schemars", "serde", - "terra-cosmwasm", "valkyrie", ] @@ -751,12 +930,11 @@ name = "valkyrie-governance" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", "cw20", "schemars", "serde", - "terra-cosmwasm", "valkyrie", ] @@ -765,23 +943,36 @@ name = "valkyrie-lp-staking" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", - "cosmwasm-storage", + "cosmwasm-std 1.0.0", + "cosmwasm-storage 0.16.0", "cw-storage-plus", "cw20", "schemars", "serde", - "terra-cosmwasm", - "terraswap", "valkyrie", ] +[[package]] +name = "valkyrie-proxy" +version = "1.0.8-beta.1" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std 1.0.0", + "cw-storage-plus", + "cw20", + "protobuf", + "schemars", + "serde", + "valkyrie", + "valkyrie-qualifier", +] + [[package]] name = "valkyrie-qualifier" version = "1.0.8-beta.1" dependencies = [ "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "schemars", "serde", ] @@ -790,11 +981,9 @@ dependencies = [ name = "valkyrie-vp" version = "1.0.8-beta.1" dependencies = [ - "astroport", "cosmwasm-schema", - "cosmwasm-std", + "cosmwasm-std 1.0.0", "cw-storage-plus", - "cw0", "cw2", "cw20", "cw20-base", diff --git a/README.md b/README.md index 7de90dd..1bd1c76 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,6 @@ This mono repository contains the source code for the smart contracts implementi You can find information about the architecture, usage, and function of the smart contracts on the official Valkyrie Protocol documentation [site](https://docs.valkyrieprotocol.com). -### Dependencies -Valkyrie Protocol depends on Terraswap and uses its implementation of the CW20 token specification. - ## Contracts | Contract | Reference | Description | | --------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | diff --git a/contracts/campaign/Cargo.toml b/contracts/campaign/Cargo.toml index 87226fa..e99710c 100644 --- a/contracts/campaign/Cargo.toml +++ b/contracts/campaign/Cargo.toml @@ -35,15 +35,13 @@ overflow-checks = true [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } valkyrie = { path = "../../packages/valkyrie", default-features = false, version = "1.0.8-beta.1" } valkyrie-qualifier = { path = "../../packages/valkyrie_qualifier", default-features = false, version = "1.0.8-beta.1" } protobuf = { version = "2", features = ["with-bytes"] } -terraswap = "2.4.0" [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } -terra-cosmwasm = { version = "2.2.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/campaign/schema/actor_response.json b/contracts/campaign/schema/actor_response.json index 6cea834..8b4a7b4 100644 --- a/contracts/campaign/schema/actor_response.json +++ b/contracts/campaign/schema/actor_response.json @@ -4,20 +4,32 @@ "type": "object", "required": [ "address", + "claimed_participation_reward_amount", + "claimed_referral_reward_amount", "cumulative_participation_reward_amount", "cumulative_referral_reward_amount", "last_participated_at", "participation_count", "participation_reward_amount", "participation_reward_amounts", + "participation_reward_last_distributed", "referral_count", "referral_reward_amount", - "referral_reward_amounts" + "referral_reward_amounts", + "referral_reward_last_distributed", + "unlocked_participation_reward_amount", + "unlocked_referral_reward_amount" ], "properties": { "address": { "type": "string" }, + "claimed_participation_reward_amount": { + "$ref": "#/definitions/Uint128" + }, + "claimed_referral_reward_amount": { + "$ref": "#/definitions/Uint128" + }, "cumulative_participation_reward_amount": { "$ref": "#/definitions/Uint128" }, @@ -41,18 +53,28 @@ "type": "array", "items": [ { - "$ref": "#/definitions/Uint128" + "type": "integer", + "format": "uint64", + "minimum": 0.0 }, { "type": "integer", "format": "uint64", "minimum": 0.0 + }, + { + "$ref": "#/definitions/Uint128" } ], - "maxItems": 2, - "minItems": 2 + "maxItems": 3, + "minItems": 3 } }, + "participation_reward_last_distributed": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "referral_count": { "type": "integer", "format": "uint64", @@ -79,11 +101,22 @@ "minItems": 2 } }, + "referral_reward_last_distributed": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "referrer_address": { "type": [ "string", "null" ] + }, + "unlocked_participation_reward_amount": { + "$ref": "#/definitions/Uint128" + }, + "unlocked_referral_reward_amount": { + "$ref": "#/definitions/Uint128" } }, "definitions": { diff --git a/contracts/campaign/schema/actors_response.json b/contracts/campaign/schema/actors_response.json index 0714ccb..ee4e3f6 100644 --- a/contracts/campaign/schema/actors_response.json +++ b/contracts/campaign/schema/actors_response.json @@ -18,20 +18,32 @@ "type": "object", "required": [ "address", + "claimed_participation_reward_amount", + "claimed_referral_reward_amount", "cumulative_participation_reward_amount", "cumulative_referral_reward_amount", "last_participated_at", "participation_count", "participation_reward_amount", "participation_reward_amounts", + "participation_reward_last_distributed", "referral_count", "referral_reward_amount", - "referral_reward_amounts" + "referral_reward_amounts", + "referral_reward_last_distributed", + "unlocked_participation_reward_amount", + "unlocked_referral_reward_amount" ], "properties": { "address": { "type": "string" }, + "claimed_participation_reward_amount": { + "$ref": "#/definitions/Uint128" + }, + "claimed_referral_reward_amount": { + "$ref": "#/definitions/Uint128" + }, "cumulative_participation_reward_amount": { "$ref": "#/definitions/Uint128" }, @@ -55,18 +67,28 @@ "type": "array", "items": [ { - "$ref": "#/definitions/Uint128" + "type": "integer", + "format": "uint64", + "minimum": 0.0 }, { "type": "integer", "format": "uint64", "minimum": 0.0 + }, + { + "$ref": "#/definitions/Uint128" } ], - "maxItems": 2, - "minItems": 2 + "maxItems": 3, + "minItems": 3 } }, + "participation_reward_last_distributed": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "referral_count": { "type": "integer", "format": "uint64", @@ -93,11 +115,22 @@ "minItems": 2 } }, + "referral_reward_last_distributed": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, "referrer_address": { "type": [ "string", "null" ] + }, + "unlocked_participation_reward_amount": { + "$ref": "#/definitions/Uint128" + }, + "unlocked_referral_reward_amount": { + "$ref": "#/definitions/Uint128" } } }, diff --git a/contracts/campaign/schema/campaign_config_msg.json b/contracts/campaign/schema/campaign_config_msg.json index f575ac6..a6eb556 100644 --- a/contracts/campaign/schema/campaign_config_msg.json +++ b/contracts/campaign/schema/campaign_config_msg.json @@ -5,9 +5,8 @@ "required": [ "description", "parameter_key", - "participation_reward_amount", "participation_reward_denom", - "participation_reward_lock_period", + "participation_reward_distribution_schedule", "referral_reward_amounts", "referral_reward_lock_period", "title", @@ -20,16 +19,31 @@ "parameter_key": { "type": "string" }, - "participation_reward_amount": { - "$ref": "#/definitions/Uint128" - }, "participation_reward_denom": { "$ref": "#/definitions/Denom" }, - "participation_reward_lock_period": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 + "participation_reward_distribution_schedule": { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "$ref": "#/definitions/Uint128" + } + ], + "maxItems": 3, + "minItems": 3 + } }, "referral_reward_amounts": { "type": "array", @@ -51,7 +65,7 @@ }, "definitions": { "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/campaign_config_response.json b/contracts/campaign/schema/campaign_config_response.json index eafc0ac..e43b428 100644 --- a/contracts/campaign/schema/campaign_config_response.json +++ b/contracts/campaign/schema/campaign_config_response.json @@ -13,7 +13,9 @@ "governance", "parameter_key", "title", - "url" + "url", + "vp_burn_amount", + "vp_token" ], "properties": { "admin": { @@ -72,11 +74,17 @@ }, "url": { "type": "string" + }, + "vp_burn_amount": { + "$ref": "#/definitions/Uint128" + }, + "vp_token": { + "type": "string" } }, "definitions": { "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/campaign_instantiate_msg.json b/contracts/campaign/schema/campaign_instantiate_msg.json index 189ebde..f996443 100644 --- a/contracts/campaign/schema/campaign_instantiate_msg.json +++ b/contracts/campaign/schema/campaign_instantiate_msg.json @@ -10,7 +10,9 @@ "deposit_amount", "deposit_lock_period", "governance", - "referral_reward_token" + "referral_reward_token", + "vp_burn_amount", + "vp_token" ], "properties": { "admin": { @@ -60,6 +62,12 @@ }, "referral_reward_token": { "type": "string" + }, + "vp_burn_amount": { + "$ref": "#/definitions/Uint128" + }, + "vp_token": { + "type": "string" } }, "definitions": { @@ -68,7 +76,7 @@ "type": "string" }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/campaign_state_response.json b/contracts/campaign/schema/campaign_state_response.json index 7f3bce6..3fd651c 100644 --- a/contracts/campaign/schema/campaign_state_response.json +++ b/contracts/campaign/schema/campaign_state_response.json @@ -74,7 +74,7 @@ }, "definitions": { "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/cw20_hook_msg.json b/contracts/campaign/schema/cw20_hook_msg.json index 3e49d7d..8c71a4f 100644 --- a/contracts/campaign/schema/cw20_hook_msg.json +++ b/contracts/campaign/schema/cw20_hook_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Cw20HookMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/distribute_result.json b/contracts/campaign/schema/distribute_result.json index 3b527a9..79f2f3c 100644 --- a/contracts/campaign/schema/distribute_result.json +++ b/contracts/campaign/schema/distribute_result.json @@ -23,7 +23,7 @@ }, "definitions": { "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/execute_msg.json b/contracts/campaign/schema/execute_msg.json index b31929c..fbcc7f0 100644 --- a/contracts/campaign/schema/execute_msg.json +++ b/contracts/campaign/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ @@ -82,6 +82,16 @@ "string", "null" ] + }, + "vp_burn_amount": { + "anyOf": [ + { + "$ref": "#/definitions/Uint128" + }, + { + "type": "null" + } + ] } } } @@ -109,23 +119,31 @@ "update_reward_config": { "type": "object", "properties": { - "participation_reward_amount": { - "anyOf": [ - { - "$ref": "#/definitions/Uint128" - }, - { - "type": "null" - } - ] - }, - "participation_reward_lock_period": { + "participation_reward_distribution_schedule": { "type": [ - "integer", + "array", "null" ], - "format": "uint64", - "minimum": 0.0 + "items": { + "type": "array", + "items": [ + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "$ref": "#/definitions/Uint128" + } + ], + "maxItems": 3, + "minItems": 3 + } }, "referral_reward_amounts": { "type": [ @@ -348,7 +366,7 @@ } }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ @@ -376,7 +394,7 @@ ] }, "Referrer": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/query_msg.json b/contracts/campaign/schema/query_msg.json index e6812f9..0e1ab2b 100644 --- a/contracts/campaign/schema/query_msg.json +++ b/contracts/campaign/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ @@ -186,7 +186,7 @@ ] }, "Referrer": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/referrer.json b/contracts/campaign/schema/referrer.json index 06f3966..d7586c7 100644 --- a/contracts/campaign/schema/referrer.json +++ b/contracts/campaign/schema/referrer.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Referrer", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/schema/reward_config_response.json b/contracts/campaign/schema/reward_config_response.json index 8661c7b..37a7f8d 100644 --- a/contracts/campaign/schema/reward_config_response.json +++ b/contracts/campaign/schema/reward_config_response.json @@ -3,24 +3,38 @@ "title": "RewardConfigResponse", "type": "object", "required": [ - "participation_reward_amount", "participation_reward_denom", - "participation_reward_lock_period", + "participation_reward_distribution_schedule", "referral_reward_amounts", "referral_reward_lock_period", "referral_reward_token" ], "properties": { - "participation_reward_amount": { - "$ref": "#/definitions/Uint128" - }, "participation_reward_denom": { "$ref": "#/definitions/Denom" }, - "participation_reward_lock_period": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 + "participation_reward_distribution_schedule": { + "type": "array", + "items": { + "type": "array", + "items": [ + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + { + "$ref": "#/definitions/Uint128" + } + ], + "maxItems": 3, + "minItems": 3 + } }, "referral_reward_amounts": { "type": "array", @@ -39,7 +53,7 @@ }, "definitions": { "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign/src/entrypoints.rs b/contracts/campaign/src/entrypoints.rs index dd99f65..a495c7e 100644 --- a/contracts/campaign/src/entrypoints.rs +++ b/contracts/campaign/src/entrypoints.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdError, to_binary, from_binary, Addr}; +use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, to_binary, from_binary, Addr, StdError}; use cosmwasm_std::entry_point; use valkyrie::campaign::execute_msgs::{ExecuteMsg, MigrateMsg, Cw20HookMsg}; diff --git a/contracts/campaign/src/executions.rs b/contracts/campaign/src/executions.rs index d39c661..a3b2043 100644 --- a/contracts/campaign/src/executions.rs +++ b/contracts/campaign/src/executions.rs @@ -2,8 +2,6 @@ use std::ops::Mul; use cosmwasm_std::{Addr, Api, attr, Binary, CosmosMsg, Decimal, DepsMut, Env, from_binary, MessageInfo, QuerierWrapper, Reply, ReplyOn, Response, StdError, StdResult, Storage, SubMsg, to_binary, Uint128, WasmMsg}; use cw20::{Cw20ExecuteMsg, Denom as Cw20Denom}; use protobuf::Message; -use terraswap::asset::AssetInfo; -use terraswap::router::{QueryMsg, SimulateSwapOperationsResponse, SwapOperation}; use valkyrie::campaign::enumerations::Referrer; use valkyrie::campaign::execute_msgs::{CampaignConfigMsg, DistributeResult, ReferralReward}; @@ -12,6 +10,9 @@ use valkyrie::campaign_manager::query_msgs::ReferralRewardLimitOptionResponse; use valkyrie::common::{ContractResult, Denom}; use valkyrie::errors::ContractError; use valkyrie::message_factories; +use valkyrie::proxy::asset::AssetInfo; +use valkyrie::proxy::execute_msgs::SwapOperation; +use valkyrie::proxy::query_msgs::{QueryMsg, SimulateSwapOperationsResponse}; use valkyrie::utils::{calc_ratio_amount, make_response}; use valkyrie_qualifier::{QualificationMsg, QualificationResult}; use valkyrie_qualifier::execute_msgs::ExecuteMsg as QualifierExecuteMsg; @@ -475,7 +476,7 @@ fn validate_reward_pool_weight( let participation_reward_value = swap_simulate( &querier, - &global_campaign_config.terraswap_router, + &global_campaign_config.valkyrie_proxy, reward_config.participation_reward_denom.clone(), key_denom.clone(), participation_reward_amount, @@ -483,7 +484,7 @@ fn validate_reward_pool_weight( let referral_reward_value = swap_simulate( &querier, - &global_campaign_config.terraswap_router, + &global_campaign_config.valkyrie_proxy, cw20::Denom::Cw20(reward_config.referral_reward_token.clone()), key_denom.clone(), referral_reward_amount, @@ -506,7 +507,7 @@ fn validate_reward_pool_weight( fn swap_simulate( querier: &QuerierWrapper, - terraswap_router: &String, + valkyrie_proxy: &String, offer: cw20::Denom, ask: cw20::Denom, amount: Uint128, @@ -516,39 +517,44 @@ fn swap_simulate( } let response: SimulateSwapOperationsResponse = querier.query_wasm_smart( - terraswap_router, + valkyrie_proxy, &QueryMsg::SimulateSwapOperations { offer_amount: amount, - operations: vec![swap_operation(offer, ask)], + operations: vec![swap_operation(offer, ask)?], }, )?; Ok(response.amount) } -fn swap_operation(offer: cw20::Denom, ask: cw20::Denom) -> SwapOperation { +fn swap_operation(offer: cw20::Denom, ask: cw20::Denom) -> StdResult { match offer { cw20::Denom::Native(offer_denom) => { match ask { - cw20::Denom::Native(ask_denom) => SwapOperation::NativeSwap { - offer_denom, - ask_denom, - }, - cw20::Denom::Cw20(ask_token) => SwapOperation::TerraSwap { - offer_asset_info: AssetInfo::NativeToken { denom: offer_denom }, - ask_asset_info: AssetInfo::Token { contract_addr: ask_token.to_string() }, + cw20::Denom::Cw20(ask_token) => { + Ok(SwapOperation::Swap { + offer_asset_info: AssetInfo::NativeToken { denom: offer_denom }, + ask_asset_info: AssetInfo::Token { contract_addr: ask_token.to_string() }, + }) }, + _ => { + Err(StdError::generic_err("unavailable native swap")) + } } } cw20::Denom::Cw20(offer_token) => { match ask { - cw20::Denom::Native(ask_denom) => SwapOperation::TerraSwap { - offer_asset_info: AssetInfo::Token { contract_addr: offer_token.to_string() }, - ask_asset_info: AssetInfo::NativeToken { denom: ask_denom }, + cw20::Denom::Native(ask_denom) => { + Ok(SwapOperation::Swap { + offer_asset_info: AssetInfo::Token { contract_addr: offer_token.to_string() }, + ask_asset_info: AssetInfo::NativeToken { denom: ask_denom }, + }) }, - cw20::Denom::Cw20(ask_token) => SwapOperation::TerraSwap { - offer_asset_info: AssetInfo::Token { contract_addr: offer_token.to_string() }, - ask_asset_info: AssetInfo::Token { contract_addr: ask_token.to_string() }, + cw20::Denom::Cw20(ask_token) => { + Ok(SwapOperation::Swap { + offer_asset_info: AssetInfo::Token { contract_addr: offer_token.to_string() }, + ask_asset_info: AssetInfo::Token { contract_addr: ask_token.to_string() }, + }) }, } } @@ -1017,7 +1023,7 @@ fn distribute_participation_reward( let mut total_actor_reward = Uint128::zero(); for (start, end, amount) in reward_config.participation_reward_distribution_schedule.iter() { - let reward_amount = reward_rate.mul(amount.clone()); + let reward_amount = reward_rate.clone().mul(amount.clone()); total_actor_reward += reward_amount; actor.add_participation_reward( (start + height, end + height, reward_amount) @@ -1025,7 +1031,7 @@ fn distribute_participation_reward( } let total_schedule_amount = reward_config.sum_of_participation_reward(); - let gap = total_actor_reward - reward_rate.mul(total_schedule_amount); + let gap = total_actor_reward - reward_rate.clone().mul(total_schedule_amount); if !gap.is_zero() { //add gap to last reward let last_index = actor.participation_reward_amounts.len() - 1; diff --git a/contracts/campaign/src/tests/add_reward_pool.rs b/contracts/campaign/src/tests/add_reward_pool.rs index 8b1341b..18f3dbf 100644 --- a/contracts/campaign/src/tests/add_reward_pool.rs +++ b/contracts/campaign/src/tests/add_reward_pool.rs @@ -20,7 +20,7 @@ pub fn exec( participation_reward_amount: Uint128, referral_reward_amount: Uint128, ) -> ContractResult { - deps.querier.with_terraswap_price( + deps.querier.with_astroport_price( VALKYRIE_TOKEN.to_string(), KEY_DENOM_NATIVE.to_string(), 1f64, diff --git a/contracts/campaign/src/tests/claim_participation_reward.rs b/contracts/campaign/src/tests/claim_participation_reward.rs index 3c5306c..d1f3fab 100644 --- a/contracts/campaign/src/tests/claim_participation_reward.rs +++ b/contracts/campaign/src/tests/claim_participation_reward.rs @@ -1,9 +1,9 @@ -use cosmwasm_std::{Addr, BankMsg, coin, CosmosMsg, Decimal, Env, MessageInfo, Response, SubMsg, Uint128}; +use cosmwasm_std::{Addr, BankMsg, coin, CosmosMsg, Env, MessageInfo, Response, SubMsg, Uint128}; use cosmwasm_std::testing::mock_info; use valkyrie::common::ContractResult; use valkyrie::mock_querier::{custom_deps, CustomDeps}; -use valkyrie::test_constants::campaign::{campaign_env_height, PARTICIPATION_REWARD_AMOUNT, PARTICIPATION_REWARD_DENOM_NATIVE, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE1, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE3}; +use valkyrie::test_constants::campaign::{campaign_env_height, PARTICIPATION_REWARD_AMOUNT, PARTICIPATION_REWARD_DENOM_NATIVE, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE1, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE3, PARTICIPATOR1}; use valkyrie::test_utils::expect_generic_err; use crate::executions::claim_participation_reward; @@ -30,7 +30,7 @@ fn succeed() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, 3995, 3000); - let participator = Addr::unchecked("Participator"); + let participator = Addr::unchecked(PARTICIPATOR1); let (env, _, _) = super::participate::will_success( &mut deps, participator.as_str(), @@ -76,7 +76,7 @@ fn failed_no_reward() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, PARTICIPATION_REWARD_AMOUNT.u128(), 2000); - let participator = Addr::unchecked("Participator"); + let participator = Addr::unchecked(PARTICIPATOR1); let (env, _, _) = super::participate::will_success( &mut deps, &participator.as_str(), diff --git a/contracts/campaign/src/tests/claim_referral_reward.rs b/contracts/campaign/src/tests/claim_referral_reward.rs index 6b018d6..b3113dc 100644 --- a/contracts/campaign/src/tests/claim_referral_reward.rs +++ b/contracts/campaign/src/tests/claim_referral_reward.rs @@ -3,7 +3,7 @@ use cosmwasm_std::testing::mock_info; use valkyrie::common::ContractResult; use valkyrie::mock_querier::{custom_deps, CustomDeps}; -use valkyrie::test_constants::campaign::{campaign_env, campaign_env_height, PARTICIPATION_REWARD_AMOUNT, REFERRAL_REWARD_AMOUNTS, REFERRAL_REWARD_LOCK_PERIOD}; +use valkyrie::test_constants::campaign::{campaign_env, campaign_env_height, PARTICIPATION_REWARD_AMOUNT, PARTICIPATOR1, REFERRAL_REWARD_AMOUNTS, REFERRAL_REWARD_LOCK_PERIOD, REFERRER}; use valkyrie::test_utils::expect_generic_err; use crate::executions::claim_referral_reward; @@ -33,11 +33,11 @@ fn succeed() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, PARTICIPATION_REWARD_AMOUNT.u128() * 2, 4000); - let referrer = Addr::unchecked("Referrer"); + let referrer = Addr::unchecked(REFERRER); super::participate::will_success(&mut deps, referrer.as_str(), None); let (env, _, _) = super::participate::will_success( &mut deps, - "Participator", + PARTICIPATOR1, Some(Referrer::Address(referrer.to_string())), ); @@ -80,11 +80,11 @@ fn failed_no_reward() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, PARTICIPATION_REWARD_AMOUNT.u128() * 2, 4000); - let referrer = Addr::unchecked("Referrer"); + let referrer = Addr::unchecked(REFERRER); super::participate::will_success(&mut deps, referrer.as_str(), None); let (env, _, _) = super::participate::will_success( &mut deps, - "Participator", + PARTICIPATOR1, Some(Referrer::Address(referrer.to_string())), ); diff --git a/contracts/campaign/src/tests/deposit.rs b/contracts/campaign/src/tests/deposit.rs index 1586376..b5f72f7 100644 --- a/contracts/campaign/src/tests/deposit.rs +++ b/contracts/campaign/src/tests/deposit.rs @@ -4,7 +4,7 @@ use crate::states::Deposit; use valkyrie::mock_querier::{CustomDeps, custom_deps}; use crate::executions::deposit; use valkyrie::common::ContractResult; -use valkyrie::test_constants::campaign::{campaign_env, DEPOSIT_DENOM_NATIVE}; +use valkyrie::test_constants::campaign::{campaign_env, DEPOSIT_DENOM_NATIVE, PARTICIPATOR1}; use cosmwasm_std::testing::mock_info; use valkyrie::errors::ContractError; use cw20::Denom; @@ -50,7 +50,7 @@ fn succeed() { super::instantiate::default(&mut deps); - let actor = Addr::unchecked("Actor"); + let actor = Addr::unchecked(PARTICIPATOR1); let deposit = Deposit::load_or_new(&deps.storage, &actor).unwrap(); assert_eq!(deposit, Deposit { @@ -87,8 +87,8 @@ fn failed_invalid_funds() { let result = exec( &mut deps, campaign_env(), - mock_info("Actor", &[]), - "Actor", + mock_info(PARTICIPATOR1, &[]), + PARTICIPATOR1, vec![], ); assert_eq!(result.unwrap_err(), ContractError::Std(StdError::generic_err("Missing deposit denom"))); @@ -96,8 +96,8 @@ fn failed_invalid_funds() { let result = exec( &mut deps, campaign_env(), - mock_info("Actor", &[]), - "Actor", + mock_info(PARTICIPATOR1, &[]), + PARTICIPATOR1, vec![ (Denom::Native("ukrw".to_string()), Uint128::new(100)), ], @@ -107,8 +107,8 @@ fn failed_invalid_funds() { let result = exec( &mut deps, campaign_env(), - mock_info("Actor", &[]), - "Actor", + mock_info(PARTICIPATOR1, &[]), + PARTICIPATOR1, vec![ (Denom::Native(DEPOSIT_DENOM_NATIVE.to_string()), Uint128::zero()), ], diff --git a/contracts/campaign/src/tests/participate.rs b/contracts/campaign/src/tests/participate.rs index 9d0f91e..7ee7c23 100644 --- a/contracts/campaign/src/tests/participate.rs +++ b/contracts/campaign/src/tests/participate.rs @@ -1,6 +1,5 @@ -use cosmwasm_std::{Addr, Env, MessageInfo, Response, Uint128, SubMsg, CosmosMsg, WasmMsg, to_binary, Reply, SubMsgExecutionResponse, Binary, from_binary}; +use cosmwasm_std::{Addr, Env, MessageInfo, Response, Uint128, SubMsg, CosmosMsg, WasmMsg, to_binary, Reply, Binary, from_binary, SubMsgResult, SubMsgResponse}; use cosmwasm_std::testing::mock_info; -use cosmwasm_std::ContractResult as ReplyResult; use valkyrie::campaign::enumerations::Referrer; use valkyrie::common::ContractResult; @@ -10,7 +9,7 @@ use valkyrie::test_utils::{expect_generic_err}; use crate::executions::{participate, participate_qualify_result, REPLY_QUALIFY_PARTICIPATION}; use crate::states::{CampaignState, Actor, CampaignConfig}; -use valkyrie::test_constants::campaign::{campaign_env, PARTICIPATION_REWARD_AMOUNT, REFERRAL_REWARD_AMOUNTS, PARTICIPATION_REWARD_DENOM_NATIVE, DEPOSIT_AMOUNT, REFERRAL_REWARD_LOCK_PERIOD, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE1, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE2, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE3}; +use valkyrie::test_constants::campaign::{campaign_env, PARTICIPATION_REWARD_AMOUNT, REFERRAL_REWARD_AMOUNTS, PARTICIPATION_REWARD_DENOM_NATIVE, DEPOSIT_AMOUNT, REFERRAL_REWARD_LOCK_PERIOD, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE1, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE2, PARTICIPATION_REWARD_DISTRIBUTION_SCHEDULE3, PARTICIPATOR2, REFERRER, PARTICIPATOR1, RECIPIENT, INVALID_REFERRER}; use valkyrie::test_constants::{default_sender, DEFAULT_SENDER, VALKYRIE_TICKET_TOKEN, VALKYRIE_TOKEN}; use valkyrie::campaign_manager::query_msgs::ReferralRewardLimitOptionResponse; use cw20::{Denom, Cw20ExecuteMsg}; @@ -46,7 +45,7 @@ pub fn exec( let qualify_response = participate_qualify_result(deps.as_mut(), env, Reply { id: REPLY_QUALIFY_PARTICIPATION, - result: ReplyResult::Ok(SubMsgExecutionResponse { + result: SubMsgResult::Ok(SubMsgResponse { events: vec![], data: Some(Binary::from(msg.write_to_bytes().unwrap())), }) @@ -121,7 +120,7 @@ fn succeed_without_referrer() { 1000, ); - let participator = Addr::unchecked("Participator"); + let participator = Addr::unchecked(PARTICIPATOR1); let (env, _, _) = will_success(&mut deps, participator.as_str(), None); @@ -182,13 +181,13 @@ fn succeed_with_referrer() { 2000, ); - let participator = Addr::unchecked("Participator"); - let referrer = Addr::unchecked("Referrer"); + let participator = Addr::unchecked(PARTICIPATOR1); + let referrer = Addr::unchecked(REFERRER); - let (referrer_env, _, _) = will_success( + let (_, _, _) = will_success( &mut deps, referrer.as_str(), - Some(Referrer::Address("InvalidReferrer".to_string())), + Some(Referrer::Address(INVALID_REFERRER.to_string())), ); let (env, _, _) = will_success( @@ -289,15 +288,14 @@ fn succeed_twice() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, 6000, 10000000000000); - let participator = Addr::unchecked("participator"); - will_success(&mut deps, participator.as_str(), None); - let (env, _, _) = will_success(&mut deps, participator.as_str(), None); + will_success(&mut deps, PARTICIPATOR1, None); + let (env, _, _) = will_success(&mut deps, PARTICIPATOR1, None); - let participation = get_actor(deps.as_ref(), env.clone(), participator.to_string()).unwrap(); + let participation = get_actor(deps.as_ref(), env.clone(), PARTICIPATOR1.to_string()).unwrap(); assert_eq!(participation, ActorResponse { - address: participator.to_string(), + address: PARTICIPATOR1.to_string(), referrer_address: None, unlocked_participation_reward_amount: Uint128::zero(), @@ -369,7 +367,7 @@ fn succeed_with_burn_vp() { let config = CampaignConfig::load(deps.as_ref().storage).unwrap(); - let participator = Addr::unchecked("participator"); + let participator = Addr::unchecked(PARTICIPATOR1); deps.querier.plus_token_balances(&[(config.vp_token.as_str(), &[(&participator.as_str(), &vp_amount)])]); @@ -441,15 +439,15 @@ fn failed_insufficient_balance() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, PARTICIPATION_REWARD_AMOUNT.u128(), 10000000000000); - will_success(&mut deps, "Participator1", None); + will_success(&mut deps, "terra12u7hcmpltazmmnq0fvyl225usn3fy6qqlp05w0", None); - super::deposit::will_success(&mut deps, "Participator2", DEPOSIT_AMOUNT); + super::deposit::will_success(&mut deps, "terra1zgrx9jjqrfye8swykfgmd6hpde60j0nszzupp9", DEPOSIT_AMOUNT); let result = exec( &mut deps, campaign_env(), - mock_info("Participator2", &[]), - "Participator2".to_string(), + mock_info("terra1zgrx9jjqrfye8swykfgmd6hpde60j0nszzupp9", &[]), + "terra1zgrx9jjqrfye8swykfgmd6hpde60j0nszzupp9".to_string(), None, ); expect_generic_err(&result, "Insufficient balance"); @@ -470,7 +468,7 @@ fn overflow_referral_reward() { }); deps.querier.with_gov_staker_state( - "Referrer", + REFERRER, StakerStateResponse { balance: Uint128::new(20), share: Uint128::new(20), @@ -478,14 +476,14 @@ fn overflow_referral_reward() { } ); - will_success(&mut deps, "Referrer", None); + will_success(&mut deps, REFERRER, None); - let (referrer_env, _, _) = will_success(&mut deps, "Participator", Some(Referrer::Address("Referrer".to_string()))); - will_success(&mut deps, "Participator2", Some(Referrer::Address("Participator".to_string()))); - will_success(&mut deps, "Participator", Some(Referrer::Address("Referrer".to_string()))); + let (referrer_env, _, _) = will_success(&mut deps, PARTICIPATOR1, Some(Referrer::Address(REFERRER.to_string()))); + will_success(&mut deps, PARTICIPATOR2, Some(Referrer::Address(PARTICIPATOR1.to_string()))); + will_success(&mut deps, PARTICIPATOR1, Some(Referrer::Address(REFERRER.to_string()))); //reward limit : 902 - let referrer = Actor::load(&deps.storage, &Addr::unchecked("Referrer")).unwrap(); + let referrer = Actor::load(&deps.storage, &Addr::unchecked(REFERRER)).unwrap(); assert_eq!(referrer.referral_reward_amounts, vec![ (Uint128::new(400), referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD), (Uint128::new(300), referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD), @@ -498,7 +496,7 @@ fn overflow_referral_reward() { deps.querier.with_gov_staker_state( - "Referrer", + REFERRER, StakerStateResponse { balance: Uint128::new(40), share: Uint128::new(40), @@ -506,10 +504,10 @@ fn overflow_referral_reward() { } ); - let (referrer_env, _, _) = will_success(&mut deps, "Participator", Some(Referrer::Address("Referrer".to_string()))); + let (referrer_env, _, _) = will_success(&mut deps, PARTICIPATOR1, Some(Referrer::Address(REFERRER.to_string()))); //reward limit : 904 - let referrer = Actor::load(&deps.storage, &Addr::unchecked("Referrer")).unwrap(); + let referrer = Actor::load(&deps.storage, &Addr::unchecked(REFERRER)).unwrap(); assert_eq!(referrer.referral_reward_amounts, vec![ (Uint128::new(400), referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD), (Uint128::new(300), referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD), @@ -522,7 +520,7 @@ fn overflow_referral_reward() { deps.querier.with_gov_staker_state( - "Referrer", + REFERRER, StakerStateResponse { balance: Uint128::new(60), share: Uint128::new(60), @@ -531,7 +529,7 @@ fn overflow_referral_reward() { ); //reward limit : 906 deps.querier.with_referral_reward_limit_option(ReferralRewardLimitOptionResponse { - overflow_amount_recipient: Some("Recipient".to_string()), + overflow_amount_recipient: Some(RECIPIENT.to_string()), base_count: 1, percent_for_governance_staking: 10, }); @@ -539,23 +537,23 @@ fn overflow_referral_reward() { crate::tests::claim_referral_reward::will_success( &mut deps, referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD, - "Referrer", + REFERRER, ); - let (referrer_env, _, response) = will_success(&mut deps, "Participator", Some(Referrer::Address("Referrer".to_string()))); + let (referrer_env, _, response) = will_success(&mut deps, PARTICIPATOR1, Some(Referrer::Address(REFERRER.to_string()))); assert_eq!(response.messages[0], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: VALKYRIE_TOKEN.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { - recipient: "Recipient".to_string(), + recipient: RECIPIENT.to_string(), amount: Uint128::new(398), }).unwrap(), })), ); - let referrer = Actor::load(&deps.storage, &Addr::unchecked("Referrer")).unwrap(); + let referrer = Actor::load(&deps.storage, &Addr::unchecked(REFERRER)).unwrap(); assert_eq!(referrer.referral_reward_amounts, vec![(Uint128::new(2), referrer_env.block.height + REFERRAL_REWARD_LOCK_PERIOD)]); //reach limit. overflow amount = 3 let state = CampaignState::load(&deps.storage).unwrap(); diff --git a/contracts/campaign/src/tests/remove_reward_pool.rs b/contracts/campaign/src/tests/remove_reward_pool.rs index 4a35a57..f9a307d 100644 --- a/contracts/campaign/src/tests/remove_reward_pool.rs +++ b/contracts/campaign/src/tests/remove_reward_pool.rs @@ -6,7 +6,7 @@ use valkyrie::common::{ContractResult, Denom}; use valkyrie::message_matchers; use valkyrie::mock_querier::{custom_deps, CustomDeps}; use valkyrie::test_constants::{default_sender, VALKYRIE_TOKEN}; -use valkyrie::test_constants::campaign::{CAMPAIGN, CAMPAIGN_ADMIN, campaign_admin_sender, campaign_env, PARTICIPATION_REWARD_AMOUNT, PARTICIPATION_REWARD_DENOM_NATIVE, REFERRAL_REWARD_AMOUNTS}; +use valkyrie::test_constants::campaign::{CAMPAIGN, CAMPAIGN_ADMIN, campaign_admin_sender, campaign_env, PARTICIPATION_REWARD_AMOUNT, PARTICIPATION_REWARD_DENOM_NATIVE, PARTICIPATOR1, PARTICIPATOR2, REFERRAL_REWARD_AMOUNTS}; use valkyrie::test_constants::campaign_manager::CAMPAIGN_MANAGER; use valkyrie::test_utils::{expect_generic_err, expect_unauthorized_err}; use valkyrie::utils::calc_ratio_amount; @@ -207,11 +207,11 @@ fn succeed_free_balance() { super::instantiate::default(&mut deps); super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, 7000, 10000); - super::participate::will_success(&mut deps, "Participator1", None); + super::participate::will_success(&mut deps, PARTICIPATOR1, None); super::participate::will_success( &mut deps, - "Participator2", - Some(Referrer::Address("Participator1".to_string())), + PARTICIPATOR2, + Some(Referrer::Address(PARTICIPATOR1.to_string())), ); will_success( @@ -274,11 +274,11 @@ fn failed_overflow() { super::update_activation::will_success(&mut deps, true); - super::participate::will_success(&mut deps, "Participator1", None); + super::participate::will_success(&mut deps, PARTICIPATOR1, None); super::participate::will_success( &mut deps, - "Participator2", - Some(Referrer::Address("Participator1".to_string())), + PARTICIPATOR2, + Some(Referrer::Address(PARTICIPATOR1.to_string())), ); let result = exec( diff --git a/contracts/campaign/src/tests/set_no_qualification.rs b/contracts/campaign/src/tests/set_no_qualification.rs index a31b4ac..102c6cd 100644 --- a/contracts/campaign/src/tests/set_no_qualification.rs +++ b/contracts/campaign/src/tests/set_no_qualification.rs @@ -36,7 +36,7 @@ fn succeed() { CAMPAIGN_DESCRIPTION.to_string(), CAMPAIGN_URL.to_string(), CAMPAIGN_PARAMETER_KEY.to_string(), - Some("Qualifier".to_string()), + Some(QUALIFIER.to_string()), None, Denom::Native(PARTICIPATION_REWARD_DENOM_NATIVE.to_string()), vec![ @@ -50,7 +50,7 @@ fn succeed() { ); let config = CampaignConfig::load(&deps.storage).unwrap(); - assert_eq!(config.qualifier, Some(Addr::unchecked("Qualifier"))); + assert_eq!(config.qualifier, Some(Addr::unchecked(QUALIFIER))); will_success(&mut deps); diff --git a/contracts/campaign/src/tests/states.rs b/contracts/campaign/src/tests/states.rs index ca80606..399bd1d 100644 --- a/contracts/campaign/src/tests/states.rs +++ b/contracts/campaign/src/tests/states.rs @@ -1,7 +1,7 @@ -use cosmwasm_std::{Addr, Decimal, Uint128}; +use cosmwasm_std::{Addr, Uint128}; use valkyrie::mock_querier::{custom_deps}; -use valkyrie::test_constants::campaign::{DEPOSIT_AMOUNT}; +use valkyrie::test_constants::campaign::{DEPOSIT_AMOUNT, PARTICIPATOR1}; use crate::queries::{get_actor}; @@ -13,7 +13,7 @@ fn calc_unlocked_reward() { super::update_activation::will_success(&mut deps, true); super::add_reward_pool::will_success(&mut deps, 100000, 100000); - let participator = Addr::unchecked("Participator"); + let participator = Addr::unchecked(PARTICIPATOR1); let (mut env, info, _) = super::participate::will_success( &mut deps, participator.as_str(), @@ -50,7 +50,7 @@ fn calc_unlocked_reward() { // 15 blocks passed, participated at 12360 // progressing participate #1 linear vesting distribution. env.block.height = 12345 + 15; - let participator = Addr::unchecked("Participator"); + let participator = Addr::unchecked(PARTICIPATOR1); super::deposit::will_success(&mut deps, participator.as_str(), DEPOSIT_AMOUNT); super::participate::exec( diff --git a/contracts/campaign/src/tests/update_campaign_config.rs b/contracts/campaign/src/tests/update_campaign_config.rs index f6ae8ff..8aa3916 100644 --- a/contracts/campaign/src/tests/update_campaign_config.rs +++ b/contracts/campaign/src/tests/update_campaign_config.rs @@ -6,7 +6,7 @@ use valkyrie::test_utils::{expect_generic_err, expect_unauthorized_err}; use crate::executions::{update_campaign_config, MIN_TITLE_LENGTH, MAX_TITLE_LENGTH, MIN_DESC_LENGTH, MAX_DESC_LENGTH, MIN_URL_LENGTH, MAX_URL_LENGTH, MIN_PARAM_KEY_LENGTH, MAX_PARAM_KEY_LENGTH}; use crate::states::CampaignConfig; -use valkyrie::test_constants::campaign::{CAMPAIGN_ADMIN, campaign_admin_sender, campaign_env}; +use valkyrie::test_constants::campaign::{ADMIN2, CAMPAIGN_ADMIN, campaign_admin_sender, campaign_env, QUALIFIER2}; use valkyrie::test_constants::default_sender; pub fn exec( @@ -89,9 +89,9 @@ fn succeed() { let deposit_amount = Uint128::new(99); let deposit_lock_period = 199u64; let vp_burn_amount = Uint128::new(99999999); - let qualifier = "Qualifier2".to_string(); + let qualifier = QUALIFIER2.to_string(); let qualification_description = "QualificationDescription2".to_string(); - let admin = "Admin2".to_string(); + let admin = ADMIN2.to_string(); will_success( &mut deps, @@ -132,9 +132,9 @@ fn succeed_update_info_after_activation() { let title = "Title2".to_string(); let description = "Desc2".to_string(); - let qualifier = "Qualifier2".to_string(); + let qualifier = QUALIFIER2.to_string(); let qualification_description = "QualificationDescription2".to_string(); - let admin = "Admin2".to_string(); + let admin = ADMIN2.to_string(); will_success( &mut deps, diff --git a/contracts/campaign_manager/Cargo.toml b/contracts/campaign_manager/Cargo.toml index 07123c9..8a66c05 100644 --- a/contracts/campaign_manager/Cargo.toml +++ b/contracts/campaign_manager/Cargo.toml @@ -38,14 +38,12 @@ backtraces = ["cosmwasm-std/backtraces"] [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cw2 = { version = "0.8.1" } -cw20 = { version = "0.8.1" } -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } +schemars = { version = "0.8.10" } +cw2 = { version = "0.11.0" } +cw20 = { version = "0.11.0" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } valkyrie = { path = "../../packages/valkyrie", default-features = false, version = "1.0.8-beta.1" } -terraswap = "2.4.0" [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } -terra-cosmwasm = { version = "2.2.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/campaign_manager/schema/campaign_instantiate_msg.json b/contracts/campaign_manager/schema/campaign_instantiate_msg.json index 189ebde..f996443 100644 --- a/contracts/campaign_manager/schema/campaign_instantiate_msg.json +++ b/contracts/campaign_manager/schema/campaign_instantiate_msg.json @@ -10,7 +10,9 @@ "deposit_amount", "deposit_lock_period", "governance", - "referral_reward_token" + "referral_reward_token", + "vp_burn_amount", + "vp_token" ], "properties": { "admin": { @@ -60,6 +62,12 @@ }, "referral_reward_token": { "type": "string" + }, + "vp_burn_amount": { + "$ref": "#/definitions/Uint128" + }, + "vp_token": { + "type": "string" } }, "definitions": { @@ -68,7 +76,7 @@ "type": "string" }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign_manager/schema/config_response.json b/contracts/campaign_manager/schema/config_response.json index 0dd562e..77d968a 100644 --- a/contracts/campaign_manager/schema/config_response.json +++ b/contracts/campaign_manager/schema/config_response.json @@ -13,8 +13,9 @@ "governance", "key_denom", "remove_pool_fee_rate", - "terraswap_router", - "valkyrie_token" + "valkyrie_proxy", + "valkyrie_token", + "vp_token" ], "properties": { "add_pool_fee_rate": { @@ -51,11 +52,14 @@ "remove_pool_fee_rate": { "$ref": "#/definitions/Decimal" }, - "terraswap_router": { + "valkyrie_proxy": { "type": "string" }, "valkyrie_token": { "type": "string" + }, + "vp_token": { + "type": "string" } }, "definitions": { @@ -64,7 +68,7 @@ "type": "string" }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign_manager/schema/execute_msg.json b/contracts/campaign_manager/schema/execute_msg.json index 532fbf7..cc7f319 100644 --- a/contracts/campaign_manager/schema/execute_msg.json +++ b/contracts/campaign_manager/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ @@ -95,7 +95,7 @@ } ] }, - "terraswap_router": { + "valkyrie_proxy": { "type": [ "string", "null" @@ -106,6 +106,12 @@ "string", "null" ] + }, + "vp_token": { + "type": [ + "string", + "null" + ] } } } @@ -226,6 +232,16 @@ "string", "null" ] + }, + "vp_burn_amount": { + "anyOf": [ + { + "$ref": "#/definitions/Uint128" + }, + { + "type": "null" + } + ] } } } @@ -306,7 +322,7 @@ "type": "string" }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign_manager/schema/instantiate_msg.json b/contracts/campaign_manager/schema/instantiate_msg.json index 3725cb8..2a99bbc 100644 --- a/contracts/campaign_manager/schema/instantiate_msg.json +++ b/contracts/campaign_manager/schema/instantiate_msg.json @@ -14,8 +14,9 @@ "key_denom", "referral_reward_limit_option", "remove_pool_fee_rate", - "terraswap_router", - "valkyrie_token" + "valkyrie_proxy", + "valkyrie_token", + "vp_token" ], "properties": { "add_pool_fee_rate": { @@ -55,11 +56,14 @@ "remove_pool_fee_rate": { "$ref": "#/definitions/Decimal" }, - "terraswap_router": { + "valkyrie_proxy": { "type": "string" }, "valkyrie_token": { "type": "string" + }, + "vp_token": { + "type": "string" } }, "definitions": { @@ -68,7 +72,7 @@ "type": "string" }, "Denom": { - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign_manager/schema/migrate_msg.json b/contracts/campaign_manager/schema/migrate_msg.json index 61a4be9..274021d 100644 --- a/contracts/campaign_manager/schema/migrate_msg.json +++ b/contracts/campaign_manager/schema/migrate_msg.json @@ -3,11 +3,15 @@ "title": "MigrateMsg", "type": "object", "required": [ - "contract_admin" + "contract_admin", + "vp_token" ], "properties": { "contract_admin": { "type": "string" + }, + "vp_token": { + "type": "string" } } } diff --git a/contracts/campaign_manager/schema/query_msg.json b/contracts/campaign_manager/schema/query_msg.json index 6082b30..73d3a97 100644 --- a/contracts/campaign_manager/schema/query_msg.json +++ b/contracts/campaign_manager/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/campaign_manager/src/entrypoints.rs b/contracts/campaign_manager/src/entrypoints.rs index 0fa7c0f..2595587 100644 --- a/contracts/campaign_manager/src/entrypoints.rs +++ b/contracts/campaign_manager/src/entrypoints.rs @@ -7,7 +7,7 @@ use valkyrie::campaign_manager::query_msgs::QueryMsg; use valkyrie::common::ContractResult; use valkyrie::errors::ContractError; -use crate::{executions, queries, migrations}; +use crate::{executions, queries}; const CONTRACT_NAME: &str = "valkyrie-campaign-manager"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -38,7 +38,7 @@ pub fn execute( governance, valkyrie_token, vp_token, - terraswap_router, + valkyrie_proxy, code_id, add_pool_fee_rate, add_pool_min_referral_reward_rate, @@ -55,7 +55,7 @@ pub fn execute( governance, valkyrie_token, vp_token, - terraswap_router, + valkyrie_proxy, code_id, add_pool_fee_rate, add_pool_min_referral_reward_rate, @@ -120,30 +120,12 @@ pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> ContractResult { } #[cfg_attr(not(feature = "library"), entry_point)] -pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> ContractResult { +pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> ContractResult { if cw2::get_contract_version(deps.storage).is_err() { cw2::set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.0".to_string())?; } - //mig to v1.0.6 to v1.0.8-beta.0 - let info = cw2::get_contract_version(deps.storage)?; - if info.version == "v1.0.6".to_string() { - let contract_admin = &deps.api.addr_validate(msg.contract_admin.as_str())?; - migrations::v106::migrate(deps.storage, &env, contract_admin)?; - - set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.0")?; - } - - //mig to v1.0.8-beta.0 to v1.0.8-beta.1 - let info = cw2::get_contract_version(deps.storage)?; - if info.version == "1.0.8-beta.0".to_string() { - let vp_token = &deps.api.addr_validate(msg.vp_token.as_str())?; - migrations::v108_beta0::migrate(deps.storage, &env, vp_token)?; - - set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.1")?; - } - //mig to v1.0.8-beta.1 to ?????? // let info = cw2::get_contract_version(deps.storage)?; // if info.version == "1.0.8-beta.1" { diff --git a/contracts/campaign_manager/src/executions.rs b/contracts/campaign_manager/src/executions.rs index 9e45dbd..4728786 100644 --- a/contracts/campaign_manager/src/executions.rs +++ b/contracts/campaign_manager/src/executions.rs @@ -9,8 +9,8 @@ use valkyrie::utils::{find, make_response, validate_zero_to_one}; use crate::states::*; use valkyrie::cw20::{query_cw20_balance, query_balance}; use cw20::Cw20ExecuteMsg; -use terraswap::asset::AssetInfo; -use terraswap::router::{ExecuteMsg as TerraswapExecuteMsg, SwapOperation}; +use valkyrie::proxy::asset::AssetInfo; +use valkyrie::proxy::execute_msgs::{ExecuteMsg as ProxyExecuteMsg, SwapOperation}; pub fn instantiate( deps: DepsMut, @@ -30,7 +30,7 @@ pub fn instantiate( governance: deps.api.addr_validate(msg.governance.as_str())?, vp_token: deps.api.addr_validate(msg.vp_token.as_str())?, valkyrie_token: deps.api.addr_validate(msg.valkyrie_token.as_str())?, - terraswap_router: deps.api.addr_validate(msg.terraswap_router.as_str())?, + valkyrie_proxy: deps.api.addr_validate(msg.valkyrie_proxy.as_str())?, code_id: msg.code_id, add_pool_fee_rate: msg.add_pool_fee_rate, add_pool_min_referral_reward_rate: msg.add_pool_min_referral_reward_rate, @@ -59,7 +59,7 @@ pub fn update_config( governance: Option, valkyrie_token: Option, vp_token: Option, - terraswap_router: Option, + valkyrie_proxy: Option, code_id: Option, add_pool_fee_rate: Option, add_pool_min_referral_reward_rate: Option, @@ -98,13 +98,13 @@ pub fn update_config( response = response.add_attribute("is_updated_vp_token", "true"); } - if let Some(terraswap_router) = terraswap_router.as_ref() { + if let Some(valkyrie_proxy) = valkyrie_proxy.as_ref() { if !config.is_governance(&info.sender) { return Err(ContractError::Unauthorized {}); } - config.terraswap_router = deps.api.addr_validate(terraswap_router)?; - response = response.add_attribute("is_updated_terraswap_router", "true"); + config.valkyrie_proxy = deps.api.addr_validate(valkyrie_proxy)?; + response = response.add_attribute("is_updated_valkyrie_proxy", "true"); } if let Some(code_id) = code_id.as_ref() { @@ -456,13 +456,14 @@ pub fn swap_fee( let mut response = make_response("swap_fee"); let operations: Vec = route.windows(2).map(|pair| { - pair_to_terraswap_operation(pair) + pair_to_swap_operation(pair) }).collect(); - let terraswap_msg = TerraswapExecuteMsg::ExecuteSwapOperations { + let swap_msg = ProxyExecuteMsg::ExecuteSwapOperations { operations, minimum_receive: None, to: None, + max_spread: None, }; let balance = query_balance( @@ -487,17 +488,17 @@ pub fn swap_fee( let swap_msg = match denom { Denom::Native(denom) => { message_factories::wasm_execute_with_funds( - &config.terraswap_router, + &config.valkyrie_proxy, vec![coin(amount.u128(), denom)], - &terraswap_msg, + &swap_msg, ) } Denom::Token(address) => { message_factories::wasm_execute( &deps.api.addr_validate(&address)?, &Cw20ExecuteMsg::Send { - contract: config.terraswap_router.to_string(), - msg: to_binary(&terraswap_msg)?, + contract: config.valkyrie_proxy.to_string(), + msg: to_binary(&swap_msg)?, amount, }, ) @@ -509,20 +510,11 @@ pub fn swap_fee( Ok(response) } -fn pair_to_terraswap_operation(pair: &[Denom]) -> SwapOperation { +fn pair_to_swap_operation(pair: &[Denom]) -> SwapOperation { let left = pair[0].clone(); let right = pair[1].clone(); - if let Denom::Native(left_denom) = left.clone() { - if let Denom::Native(right_denom) = right.clone() { - return SwapOperation::NativeSwap { - offer_denom: left_denom, - ask_denom: right_denom, - }; - } - } - - SwapOperation::TerraSwap { + SwapOperation::Swap { offer_asset_info: denom_to_asset_info(left), ask_asset_info: denom_to_asset_info(right), } diff --git a/contracts/campaign_manager/src/migrations/mod.rs b/contracts/campaign_manager/src/migrations/mod.rs index 69bcae2..4c0f186 100644 --- a/contracts/campaign_manager/src/migrations/mod.rs +++ b/contracts/campaign_manager/src/migrations/mod.rs @@ -1,2 +1,2 @@ -pub mod v106; -pub mod v108_beta0; +// pub mod v106; +// pub mod v108_beta0; diff --git a/contracts/campaign_manager/src/migrations/v106.rs b/contracts/campaign_manager/src/migrations/v106.rs index 15b3c95..8cc0e34 100644 --- a/contracts/campaign_manager/src/migrations/v106.rs +++ b/contracts/campaign_manager/src/migrations/v106.rs @@ -1,59 +1,59 @@ -use cosmwasm_std::{Addr, Decimal, Env, StdResult, Storage}; -use cw20::Denom; -use cw_storage_plus::Item; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use crate::migrations::v108_beta0::ConfigV108Beta0; - -pub fn migrate( - storage: &mut dyn Storage, - _env: &Env, - contract_admin: &Addr, -) -> StdResult<()> { - let legacy_config = ConfigV106::load(storage)?; - - ConfigV108Beta0 { - governance: legacy_config.governance, - valkyrie_token: legacy_config.valkyrie_token, - terraswap_router: legacy_config.terraswap_router, - code_id: legacy_config.code_id, - add_pool_fee_rate: legacy_config.add_pool_fee_rate, - add_pool_min_referral_reward_rate: legacy_config.add_pool_min_referral_reward_rate, - remove_pool_fee_rate: legacy_config.remove_pool_fee_rate, - fee_burn_ratio: legacy_config.fee_burn_ratio, - fee_recipient: legacy_config.fee_recipient, - deactivate_period: legacy_config.deactivate_period, - key_denom: legacy_config.key_denom, - contract_admin: contract_admin.clone(), - }.save(storage)?; - - Ok(()) -} - -const CONFIG_V106: Item = Item::new("config"); - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct ConfigV106 { - pub governance: Addr, - pub valkyrie_token: Addr, - pub terraswap_router: Addr, - pub code_id: u64, - pub add_pool_fee_rate: Decimal, - pub add_pool_min_referral_reward_rate: Decimal, - pub remove_pool_fee_rate: Decimal, - pub fee_burn_ratio: Decimal, - pub fee_recipient: Addr, - pub deactivate_period: u64, - pub key_denom: Denom, -} - -impl ConfigV106 { - pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { - CONFIG_V106.save(storage, self) - } - - pub fn load(storage: &dyn Storage) -> StdResult { - CONFIG_V106.load(storage) - } -} \ No newline at end of file +// use cosmwasm_std::{Addr, Decimal, Env, StdResult, Storage}; +// use cw20::Denom; +// use cw_storage_plus::Item; +// use schemars::JsonSchema; +// use serde::{Deserialize, Serialize}; +// +// use crate::migrations::v108_beta0::ConfigV108Beta0; +// +// pub fn migrate( +// storage: &mut dyn Storage, +// _env: &Env, +// contract_admin: &Addr, +// ) -> StdResult<()> { +// let legacy_config = ConfigV106::load(storage)?; +// +// ConfigV108Beta0 { +// governance: legacy_config.governance, +// valkyrie_token: legacy_config.valkyrie_token, +// valkyrie_proxy: legacy_config.valkyrie_proxy, +// code_id: legacy_config.code_id, +// add_pool_fee_rate: legacy_config.add_pool_fee_rate, +// add_pool_min_referral_reward_rate: legacy_config.add_pool_min_referral_reward_rate, +// remove_pool_fee_rate: legacy_config.remove_pool_fee_rate, +// fee_burn_ratio: legacy_config.fee_burn_ratio, +// fee_recipient: legacy_config.fee_recipient, +// deactivate_period: legacy_config.deactivate_period, +// key_denom: legacy_config.key_denom, +// contract_admin: contract_admin.clone(), +// }.save(storage)?; +// +// Ok(()) +// } +// +// const CONFIG_V106: Item = Item::new("config"); +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +// pub struct ConfigV106 { +// pub governance: Addr, +// pub valkyrie_token: Addr, +// pub terraswap_router: Addr, +// pub code_id: u64, +// pub add_pool_fee_rate: Decimal, +// pub add_pool_min_referral_reward_rate: Decimal, +// pub remove_pool_fee_rate: Decimal, +// pub fee_burn_ratio: Decimal, +// pub fee_recipient: Addr, +// pub deactivate_period: u64, +// pub key_denom: Denom, +// } +// +// impl ConfigV106 { +// pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { +// CONFIG_V106.save(storage, self) +// } +// +// pub fn load(storage: &dyn Storage) -> StdResult { +// CONFIG_V106.load(storage) +// } +// } \ No newline at end of file diff --git a/contracts/campaign_manager/src/migrations/v108_beta0.rs b/contracts/campaign_manager/src/migrations/v108_beta0.rs index 05f7915..bdd3e93 100644 --- a/contracts/campaign_manager/src/migrations/v108_beta0.rs +++ b/contracts/campaign_manager/src/migrations/v108_beta0.rs @@ -1,60 +1,60 @@ -use cosmwasm_std::{Addr, Decimal, Env, StdResult, Storage}; -use cw20::Denom; -use cw_storage_plus::Item; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use crate::states::Config; - -pub fn migrate( - storage: &mut dyn Storage, - _env: &Env, - vp_token: &Addr, -) -> StdResult<()> { - let legacy_config = ConfigV108Beta0::load(storage)?; - - Config { - governance: legacy_config.governance, - valkyrie_token: legacy_config.valkyrie_token, - vp_token: vp_token.clone(), - terraswap_router: legacy_config.terraswap_router, - code_id: legacy_config.code_id, - add_pool_fee_rate: legacy_config.add_pool_fee_rate, - add_pool_min_referral_reward_rate: legacy_config.add_pool_min_referral_reward_rate, - remove_pool_fee_rate: legacy_config.remove_pool_fee_rate, - fee_burn_ratio: legacy_config.fee_burn_ratio, - fee_recipient: legacy_config.fee_recipient, - deactivate_period: legacy_config.deactivate_period, - key_denom: legacy_config.key_denom, - contract_admin: legacy_config.contract_admin, - }.save(storage)?; - - Ok(()) -} - -const CONFIG_V108_BETA0: Item = Item::new("config"); - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct ConfigV108Beta0 { - pub governance: Addr, - pub valkyrie_token: Addr, - pub terraswap_router: Addr, - pub code_id: u64, - pub add_pool_fee_rate: Decimal, - pub add_pool_min_referral_reward_rate: Decimal, - pub remove_pool_fee_rate: Decimal, - pub fee_burn_ratio: Decimal, - pub fee_recipient: Addr, - pub deactivate_period: u64, - pub key_denom: Denom, - pub contract_admin: Addr, -} - -impl ConfigV108Beta0 { - pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { - CONFIG_V108_BETA0.save(storage, self) - } - - pub fn load(storage: &dyn Storage) -> StdResult { - CONFIG_V108_BETA0.load(storage) - } -} \ No newline at end of file +// use cosmwasm_std::{Addr, Decimal, Env, StdResult, Storage}; +// use cw20::Denom; +// use cw_storage_plus::Item; +// use schemars::JsonSchema; +// use serde::{Deserialize, Serialize}; +// use crate::states::Config; +// +// pub fn migrate( +// storage: &mut dyn Storage, +// _env: &Env, +// vp_token: &Addr, +// ) -> StdResult<()> { +// let legacy_config = ConfigV108Beta0::load(storage)?; +// +// Config { +// governance: legacy_config.governance, +// valkyrie_token: legacy_config.valkyrie_token, +// vp_token: vp_token.clone(), +// valkyrie_proxy: legacy_config.valkyrie_proxy, +// code_id: legacy_config.code_id, +// add_pool_fee_rate: legacy_config.add_pool_fee_rate, +// add_pool_min_referral_reward_rate: legacy_config.add_pool_min_referral_reward_rate, +// remove_pool_fee_rate: legacy_config.remove_pool_fee_rate, +// fee_burn_ratio: legacy_config.fee_burn_ratio, +// fee_recipient: legacy_config.fee_recipient, +// deactivate_period: legacy_config.deactivate_period, +// key_denom: legacy_config.key_denom, +// contract_admin: legacy_config.contract_admin, +// }.save(storage)?; +// +// Ok(()) +// } +// +// const CONFIG_V108_BETA0: Item = Item::new("config"); +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +// pub struct ConfigV108Beta0 { +// pub governance: Addr, +// pub valkyrie_token: Addr, +// pub valkyrie_proxy: Addr, +// pub code_id: u64, +// pub add_pool_fee_rate: Decimal, +// pub add_pool_min_referral_reward_rate: Decimal, +// pub remove_pool_fee_rate: Decimal, +// pub fee_burn_ratio: Decimal, +// pub fee_recipient: Addr, +// pub deactivate_period: u64, +// pub key_denom: Denom, +// pub contract_admin: Addr, +// } +// +// impl ConfigV108Beta0 { +// pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { +// CONFIG_V108_BETA0.save(storage, self) +// } +// +// pub fn load(storage: &dyn Storage) -> StdResult { +// CONFIG_V108_BETA0.load(storage) +// } +// } \ No newline at end of file diff --git a/contracts/campaign_manager/src/queries.rs b/contracts/campaign_manager/src/queries.rs index 5858544..960c2ce 100644 --- a/contracts/campaign_manager/src/queries.rs +++ b/contracts/campaign_manager/src/queries.rs @@ -11,7 +11,7 @@ pub fn get_config(deps: Deps, _env: Env) -> ContractResult { Ok(ConfigResponse { governance: config.governance.to_string(), valkyrie_token: config.valkyrie_token.to_string(), - terraswap_router: config.terraswap_router.to_string(), + valkyrie_proxy: config.valkyrie_proxy.to_string(), code_id: config.code_id, add_pool_fee_rate: config.add_pool_fee_rate, add_pool_min_referral_reward_rate: config.add_pool_min_referral_reward_rate, diff --git a/contracts/campaign_manager/src/states.rs b/contracts/campaign_manager/src/states.rs index 36fa8b2..405fee5 100644 --- a/contracts/campaign_manager/src/states.rs +++ b/contracts/campaign_manager/src/states.rs @@ -16,7 +16,7 @@ pub struct Config { pub governance: Addr, pub valkyrie_token: Addr, pub vp_token: Addr, - pub terraswap_router: Addr, + pub valkyrie_proxy: Addr, pub code_id: u64, pub add_pool_fee_rate: Decimal, pub add_pool_min_referral_reward_rate: Decimal, diff --git a/contracts/campaign_manager/src/tests/created_campaign.rs b/contracts/campaign_manager/src/tests/created_campaign.rs index 653079b..8bb2ae1 100644 --- a/contracts/campaign_manager/src/tests/created_campaign.rs +++ b/contracts/campaign_manager/src/tests/created_campaign.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{Addr, ContractResult as CwContractResult, Env, Event, Reply, Response, SubMsgExecutionResponse}; +use cosmwasm_std::{Addr, Env, Event, Reply, Response, SubMsgResponse, SubMsgResult}; use valkyrie::common::ContractResult; use valkyrie::mock_querier::{custom_deps, CustomDeps}; @@ -10,7 +10,7 @@ use crate::states::{Campaign, CreateCampaignContext}; pub fn exec( deps: &mut CustomDeps, env: Env, - result: CwContractResult, + result: SubMsgResult, ) -> ContractResult { created_campaign(deps.as_mut(), env, Reply { id: REPLY_CREATE_CAMPAIGN, @@ -27,13 +27,13 @@ fn succeed_success_reply() { let context = CreateCampaignContext::load(&deps.storage).unwrap(); - let campaign_address = Addr::unchecked("CampaignContractAddress"); + let campaign_address = Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"); let env = campaign_manager_env(); let result = exec( &mut deps, env.clone(), - CwContractResult::Ok(SubMsgExecutionResponse { + SubMsgResult::Ok(SubMsgResponse { events: vec![ Event::new("instantiate_contract") .add_attribute("contract_address", campaign_address.to_string()), diff --git a/contracts/campaign_manager/src/tests/instantiate.rs b/contracts/campaign_manager/src/tests/instantiate.rs index 2f24e3b..8b1ddd3 100644 --- a/contracts/campaign_manager/src/tests/instantiate.rs +++ b/contracts/campaign_manager/src/tests/instantiate.rs @@ -4,7 +4,7 @@ use valkyrie::campaign_manager::execute_msgs::{InstantiateMsg, ReferralRewardLim use valkyrie::common::{ContractResult, Denom}; use valkyrie::mock_querier::{custom_deps, CustomDeps}; use valkyrie::test_constants::campaign_manager::*; -use valkyrie::test_constants::{default_sender, TERRASWAP_ROUTER, VALKYRIE_TICKET_TOKEN, VALKYRIE_TOKEN}; +use valkyrie::test_constants::{default_sender, VALKYRIE_PROXY, VALKYRIE_TICKET_TOKEN, VALKYRIE_TOKEN}; use valkyrie::test_constants::governance::GOVERNANCE; use crate::executions::instantiate; @@ -16,7 +16,7 @@ pub fn exec( info: MessageInfo, governance: String, valkyrie_token: String, - terraswap_router: String, + valkyrie_proxy: String, code_id: u64, add_pool_fee_rate: Decimal, add_pool_min_referral_reward_rate: Decimal, @@ -34,7 +34,7 @@ pub fn exec( let msg = InstantiateMsg { governance, valkyrie_token, - terraswap_router, + valkyrie_proxy, code_id, add_pool_fee_rate, add_pool_min_referral_reward_rate, @@ -70,7 +70,7 @@ pub fn default(deps: &mut CustomDeps) -> (Env, MessageInfo, Response) { info.clone(), GOVERNANCE.to_string(), VALKYRIE_TOKEN.to_string(), - TERRASWAP_ROUTER.to_string(), + VALKYRIE_PROXY.to_string(), CAMPAIGN_CODE_ID, Decimal::percent(ADD_POOL_FEE_RATE_PERCENT), Decimal::percent(ADD_POOL_MIN_REFERRAL_REWARD_RATE_PERCENT), @@ -99,7 +99,7 @@ fn succeed() { assert_eq!(config, Config { governance: Addr::unchecked(GOVERNANCE), valkyrie_token: Addr::unchecked(VALKYRIE_TOKEN), - terraswap_router: Addr::unchecked(TERRASWAP_ROUTER), + valkyrie_proxy: Addr::unchecked(VALKYRIE_PROXY), code_id: CAMPAIGN_CODE_ID, add_pool_fee_rate: Decimal::percent(ADD_POOL_FEE_RATE_PERCENT), add_pool_min_referral_reward_rate: Decimal::percent(ADD_POOL_MIN_REFERRAL_REWARD_RATE_PERCENT), diff --git a/contracts/campaign_manager/src/tests/swap_fee.rs b/contracts/campaign_manager/src/tests/swap_fee.rs index 6f67ab1..7a9ed95 100644 --- a/contracts/campaign_manager/src/tests/swap_fee.rs +++ b/contracts/campaign_manager/src/tests/swap_fee.rs @@ -3,10 +3,10 @@ use cosmwasm_std::{Env, MessageInfo, Uint128, Response, coin, CosmosMsg, WasmMsg use valkyrie::common::{ContractResult, Denom}; use crate::executions::swap_fee; use valkyrie::test_utils::expect_generic_err; -use terraswap::router::{ExecuteMsg, SwapOperation}; -use terraswap::asset::AssetInfo; use cw20::Cw20ExecuteMsg; -use valkyrie::test_constants::{default_sender, TERRASWAP_ROUTER, VALKYRIE_TOKEN}; +use valkyrie::proxy::asset::AssetInfo; +use valkyrie::proxy::execute_msgs::{ExecuteMsg, SwapOperation}; +use valkyrie::test_constants::{default_sender, VALKYRIE_PROXY, VALKYRIE_TOKEN}; use valkyrie::test_constants::campaign_manager::{CAMPAIGN_MANAGER, campaign_manager_env}; pub fn exec( @@ -67,11 +67,11 @@ fn succeed_native() { assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: TERRASWAP_ROUTER.to_string(), + contract_addr: VALKYRIE_PROXY.to_string(), funds: vec![coin(10000, "uluna")], msg: to_binary(&ExecuteMsg::ExecuteSwapOperations { operations: vec![ - SwapOperation::TerraSwap { + SwapOperation::Swap { offer_asset_info: AssetInfo::NativeToken { denom: "uluna".to_string(), }, @@ -82,6 +82,7 @@ fn succeed_native() { ], minimum_receive: None, to: None, + max_spread: None, }).unwrap(), })), ]); @@ -91,7 +92,7 @@ fn succeed_native() { fn succeed_token() { let mut deps = custom_deps(); deps.querier.with_token_balances(&[( - "Token1", + "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n", &[(CAMPAIGN_MANAGER, &Uint128::new(10000))], )]); @@ -99,23 +100,23 @@ fn succeed_token() { let (_, _, response) = will_success( &mut deps, - Denom::Token("Token1".to_string()), + Denom::Token("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string()), None, None, ); assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: "Token1".to_string(), + contract_addr: "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { - contract: TERRASWAP_ROUTER.to_string(), + contract: VALKYRIE_PROXY.to_string(), amount: Uint128::new(10000), msg: to_binary(&ExecuteMsg::ExecuteSwapOperations { operations: vec![ - SwapOperation::TerraSwap { + SwapOperation::Swap { offer_asset_info: AssetInfo::Token { - contract_addr: Addr::unchecked("Token1").to_string(), + contract_addr: Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n").to_string(), }, ask_asset_info: AssetInfo::Token { contract_addr: Addr::unchecked(VALKYRIE_TOKEN).to_string(), @@ -124,6 +125,7 @@ fn succeed_token() { ], minimum_receive: None, to: None, + max_spread: None, }).unwrap(), }).unwrap(), })), @@ -152,11 +154,11 @@ fn succeed_route() { assert_eq!(response.messages, vec![ SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: TERRASWAP_ROUTER.to_string(), + contract_addr: VALKYRIE_PROXY.to_string(), funds: vec![coin(10000, "uluna")], msg: to_binary(&ExecuteMsg::ExecuteSwapOperations { operations: vec![ - SwapOperation::TerraSwap { + SwapOperation::Swap { offer_asset_info: AssetInfo::NativeToken { denom: "uluna".to_string(), }, @@ -167,6 +169,7 @@ fn succeed_route() { ], minimum_receive: None, to: None, + max_spread: None, }).unwrap(), })), ]); @@ -209,7 +212,7 @@ fn failed_overflow() { coin(10000u128, "ukrw"), ]); deps.querier.with_token_balances(&[( - "Token1", + "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n", &[(CAMPAIGN_MANAGER, &Uint128::new(10000))], )]); @@ -229,7 +232,7 @@ fn failed_overflow() { &mut deps, campaign_manager_env(), default_sender(), - Denom::Token("Token1".to_string()), + Denom::Token("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string()), Some(Uint128::new(10001)), None, ); diff --git a/contracts/campaign_manager/src/tests/update_config.rs b/contracts/campaign_manager/src/tests/update_config.rs index 7480219..6035e83 100644 --- a/contracts/campaign_manager/src/tests/update_config.rs +++ b/contracts/campaign_manager/src/tests/update_config.rs @@ -17,7 +17,7 @@ pub fn exec( governance: Option, valkyrie_token: Option, vp_token: Option, - terraswap_router: Option, + valkyrie_proxy: Option, code_id: Option, add_pool_fee_rate: Option, add_pool_min_referral_reward_rate: Option, @@ -35,7 +35,7 @@ pub fn exec( governance, valkyrie_token, vp_token, - terraswap_router, + valkyrie_proxy, code_id, add_pool_fee_rate, add_pool_min_referral_reward_rate, @@ -53,7 +53,7 @@ pub fn will_success( governance: Option, valkyrie_token: Option, vp_token: Option, - terraswap_router: Option, + valkyrie_proxy: Option, code_id: Option, add_pool_fee_rate: Option, add_pool_min_referral_reward_rate: Option, @@ -74,7 +74,7 @@ pub fn will_success( governance, valkyrie_token, vp_token, - terraswap_router, + valkyrie_proxy, code_id, add_pool_fee_rate, add_pool_min_referral_reward_rate, @@ -95,26 +95,26 @@ fn succeed() { super::instantiate::default(&mut deps); - let governance = "ChangedGovernance"; - let valkyrie_token = "ChangedVkrToken"; - let vp_token = "ChangedVP"; - let terraswap_router = "ChangedTerraswapRouter"; + let governance = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; + let valkyrie_token = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; + let vp_token = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; + let valkyrie_proxy = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; let code_id = 100u64; let add_pool_fee_rate = Decimal::percent(9); let add_pool_min_referral_reward_rate = Decimal::percent(20); let remove_pool_fee_rate = Decimal::percent(99); let fee_burn_ratio = Decimal::percent(90); - let fee_recipient = "ChangedFeeRecipient"; + let fee_recipient = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; let deactivate_period = 99u64; let key_denom = Denom::Native("ukrw".to_string()); - let contract_admin = "ChangedContAdm"; + let contract_admin = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; will_success( &mut deps, Some(governance.to_string()), Some(valkyrie_token.to_string()), Some(vp_token.to_string()), - Some(terraswap_router.to_string()), + Some(valkyrie_proxy.to_string()), Some(code_id), Some(add_pool_fee_rate), Some(add_pool_min_referral_reward_rate), @@ -131,7 +131,7 @@ fn succeed() { governance: Addr::unchecked(governance), vp_token: Addr::unchecked(vp_token), valkyrie_token: Addr::unchecked(valkyrie_token), - terraswap_router: Addr::unchecked(terraswap_router), + valkyrie_proxy: Addr::unchecked(valkyrie_proxy), code_id: code_id.clone(), add_pool_fee_rate: add_pool_fee_rate.clone(), add_pool_min_referral_reward_rate: add_pool_min_referral_reward_rate.clone(), diff --git a/contracts/campaign_manager/src/tests/update_referral_reward_limit_option.rs b/contracts/campaign_manager/src/tests/update_referral_reward_limit_option.rs index fc820cd..a6655b7 100644 --- a/contracts/campaign_manager/src/tests/update_referral_reward_limit_option.rs +++ b/contracts/campaign_manager/src/tests/update_referral_reward_limit_option.rs @@ -55,7 +55,7 @@ fn succeed() { super::instantiate::default(&mut deps); - let overflow_amount_recipient = "ChangedRecipient"; + let overflow_amount_recipient = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; let base_count = 1u8; let percent_for_governance_staking = 10u16; diff --git a/contracts/community/Cargo.toml b/contracts/community/Cargo.toml index d6e6c11..a1c140a 100644 --- a/contracts/community/Cargo.toml +++ b/contracts/community/Cargo.toml @@ -38,12 +38,11 @@ backtraces = ["cosmwasm-std/backtraces"] [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } valkyrie = { path = "../../packages/valkyrie", default-features = false, version = "1.0.8-beta.1" } [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } -terra-cosmwasm = { version = "2.2.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/community/schema/execute_msg.json b/contracts/community/schema/execute_msg.json index 53a4c20..2e55e16 100644 --- a/contracts/community/schema/execute_msg.json +++ b/contracts/community/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/community/schema/query_msg.json b/contracts/community/schema/query_msg.json index 8f44bcf..5e74f1f 100644 --- a/contracts/community/schema/query_msg.json +++ b/contracts/community/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/community/src/tests/decrease_allowance.rs b/contracts/community/src/tests/decrease_allowance.rs index 809d8aa..a673bef 100644 --- a/contracts/community/src/tests/decrease_allowance.rs +++ b/contracts/community/src/tests/decrease_allowance.rs @@ -53,7 +53,7 @@ fn succeed() { &[(COMMUNITY, &Uint128::new(10000))], )]); - let address = Addr::unchecked("Address"); + let address = Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"); super::instantiate::default(&mut deps); super::increase_allowance::will_success(&mut deps, address.to_string(), Uint128::new(1000)); @@ -89,7 +89,7 @@ fn failed_invalid_permission() { &mut deps, community_env(), default_sender(), - "Address".to_string(), + "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string(), None, ); expect_unauthorized_err(&result); @@ -103,7 +103,7 @@ fn failed_insufficient_remain_amount() { &[(COMMUNITY, &Uint128::new(10000))], )]); - let address = Addr::unchecked("Address"); + let address = Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"); super::instantiate::default(&mut deps); super::increase_allowance::will_success(&mut deps, address.to_string(), Uint128::new(1000)); diff --git a/contracts/community/src/tests/increase_allowance.rs b/contracts/community/src/tests/increase_allowance.rs index 812f88b..4136268 100644 --- a/contracts/community/src/tests/increase_allowance.rs +++ b/contracts/community/src/tests/increase_allowance.rs @@ -56,7 +56,7 @@ fn succeed() { super::instantiate::default(&mut deps); - let address = Addr::unchecked("Addr1"); + let address = Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"); let amount = Uint128::new(100); will_success(&mut deps, address.to_string(), amount.clone()); @@ -93,7 +93,7 @@ fn failed_invalid_permission() { &mut deps, community_env(), default_sender(), - "Address".to_string(), + "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string(), Uint128::new(100), ); expect_unauthorized_err(&result); @@ -109,13 +109,13 @@ fn failed_overflow_free_balance() { super::instantiate::default(&mut deps); - will_success(&mut deps, "Address1".to_string(), Uint128::new(1000)); + will_success(&mut deps, "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string(), Uint128::new(1000)); let result = exec( &mut deps, community_env(), governance_sender(), - "Address2".to_string(), + "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f".to_string(), Uint128::new(1), ); expect_generic_err(&result, "Insufficient balance"); @@ -131,7 +131,7 @@ fn failed_zero_amount() { &mut deps, community_env(), campaign_manager_sender(), - "Address".to_string(), + "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f".to_string(), Uint128::zero(), ); diff --git a/contracts/community/src/tests/update_config.rs b/contracts/community/src/tests/update_config.rs index ef981c1..9b6b962 100644 --- a/contracts/community/src/tests/update_config.rs +++ b/contracts/community/src/tests/update_config.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::update_config; use valkyrie::test_utils::expect_unauthorized_err; use crate::states::ContractConfig; -use valkyrie::test_constants::community::community_env; +use valkyrie::test_constants::community::{ADMIN1, community_env}; use valkyrie::test_constants::governance::governance_sender; use valkyrie::test_constants::default_sender; @@ -45,7 +45,7 @@ fn succeed() { super::instantiate::default(&mut deps); - let admin = "Admin1".to_string(); + let admin = ADMIN1.to_string(); will_success( &mut deps, diff --git a/contracts/distributor/Cargo.toml b/contracts/distributor/Cargo.toml index d725658..f67a82d 100644 --- a/contracts/distributor/Cargo.toml +++ b/contracts/distributor/Cargo.toml @@ -38,12 +38,11 @@ backtraces = ["cosmwasm-std/backtraces"] [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } valkyrie = { path = "../../packages/valkyrie", default-features = false, version = "1.0.8-beta.1" } [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } -terra-cosmwasm = { version = "2.2.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/distributor/schema/execute_msg.json b/contracts/distributor/schema/execute_msg.json index a184213..25ff965 100644 --- a/contracts/distributor/schema/execute_msg.json +++ b/contracts/distributor/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/distributor/schema/query_msg.json b/contracts/distributor/schema/query_msg.json index db4e6d6..ce26e53 100644 --- a/contracts/distributor/schema/query_msg.json +++ b/contracts/distributor/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/distributor/src/tests/distribute.rs b/contracts/distributor/src/tests/distribute.rs index 8e00cd3..b1669d8 100644 --- a/contracts/distributor/src/tests/distribute.rs +++ b/contracts/distributor/src/tests/distribute.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::distribute; use valkyrie::test_utils::set_height; use crate::states::{Distribution, ContractState}; -use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR}; +use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR, RECIPIENT, RECIPIENT2}; use valkyrie::test_constants::governance::governance_sender; use cw20::Cw20ExecuteMsg; use valkyrie::lp_staking::execute_msgs::Cw20HookMsg; @@ -56,7 +56,7 @@ fn succeed() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); @@ -64,7 +64,7 @@ fn succeed() { &mut deps, 20000, 30000, - "Recipient2".to_string(), + RECIPIENT2.to_string(), Uint128::new(5000), Some(to_binary(&Cw20HookMsg::Bond {}).unwrap()), ); @@ -75,7 +75,7 @@ fn succeed() { contract_addr: MANAGING_TOKEN.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { - recipient: "Recipient".to_string(), + recipient: RECIPIENT.to_string(), amount: Uint128::new(1), }).unwrap(), })), @@ -87,7 +87,7 @@ fn succeed() { contract_addr: MANAGING_TOKEN.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Transfer { - recipient: "Recipient".to_string(), + recipient: RECIPIENT.to_string(), amount: Uint128::new(1), }).unwrap(), })), @@ -95,7 +95,7 @@ fn succeed() { contract_addr: MANAGING_TOKEN.to_string(), funds: vec![], msg: to_binary(&Cw20ExecuteMsg::Send { - contract: "Recipient2".to_string(), + contract: RECIPIENT2.to_string(), amount: Uint128::new(1), msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(), }).unwrap(), @@ -127,7 +127,7 @@ fn validate_released_amount() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); @@ -135,7 +135,7 @@ fn validate_released_amount() { &mut deps, 20000, 30000, - "Recipient2".to_string(), + RECIPIENT2.to_string(), Uint128::new(5000), None, ); diff --git a/contracts/distributor/src/tests/register_distribution.rs b/contracts/distributor/src/tests/register_distribution.rs index b3da46d..6959430 100644 --- a/contracts/distributor/src/tests/register_distribution.rs +++ b/contracts/distributor/src/tests/register_distribution.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::register_distribution; use valkyrie::test_utils::{expect_unauthorized_err, expect_overflow_err}; use crate::states::{Distribution, ContractState}; -use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR}; +use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR, RECIPIENT}; use valkyrie::test_constants::governance::governance_sender; use valkyrie::test_constants::default_sender; use valkyrie::governance::execute_msgs::Cw20HookMsg; @@ -70,7 +70,7 @@ fn succeed() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), Some(to_binary(&Cw20HookMsg::StakeGovernanceToken {}).unwrap()), ); @@ -84,7 +84,7 @@ fn succeed() { id: 1, start_height: 20000, end_height: 30000, - recipient: Addr::unchecked("Recipient"), + recipient: Addr::unchecked(RECIPIENT), amount: Uint128::new(10000), distributed_amount: Uint128::zero(), message: Some(to_binary(&Cw20HookMsg::StakeGovernanceToken {}).unwrap()), @@ -103,7 +103,7 @@ fn failed_invalid_permission() { default_sender(), 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); @@ -126,7 +126,7 @@ fn failed_overflow() { governance_sender(), 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); diff --git a/contracts/distributor/src/tests/remove_distribution_message.rs b/contracts/distributor/src/tests/remove_distribution_message.rs index ab7f6be..54fb911 100644 --- a/contracts/distributor/src/tests/remove_distribution_message.rs +++ b/contracts/distributor/src/tests/remove_distribution_message.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::remove_distribution_message; use valkyrie::test_utils::expect_unauthorized_err; use crate::states::Distribution; -use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR}; +use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR, RECIPIENT}; use valkyrie::test_constants::governance::governance_sender; use valkyrie::test_constants::default_sender; use valkyrie::lp_staking::execute_msgs::Cw20HookMsg; @@ -53,7 +53,7 @@ fn succeed() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), Some(to_binary(&Cw20HookMsg::Bond {}).unwrap()), ); @@ -77,7 +77,7 @@ fn failed_invalid_permission() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); diff --git a/contracts/distributor/src/tests/update_config.rs b/contracts/distributor/src/tests/update_config.rs index a07667d..034a2df 100644 --- a/contracts/distributor/src/tests/update_config.rs +++ b/contracts/distributor/src/tests/update_config.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::update_config; use valkyrie::test_utils::expect_unauthorized_err; use crate::states::ContractConfig; -use valkyrie::test_constants::distributor::distributor_env; +use valkyrie::test_constants::distributor::{ADMIN1, distributor_env}; use valkyrie::test_constants::governance::governance_sender; use valkyrie::test_constants::default_sender; @@ -45,7 +45,7 @@ fn succeed() { super::instantiate::default(&mut deps); - let admin = "Admin1".to_string(); + let admin = ADMIN1.to_string(); will_success( &mut deps, diff --git a/contracts/distributor/src/tests/update_distribution.rs b/contracts/distributor/src/tests/update_distribution.rs index 1f5d129..90a6eeb 100644 --- a/contracts/distributor/src/tests/update_distribution.rs +++ b/contracts/distributor/src/tests/update_distribution.rs @@ -4,7 +4,7 @@ use valkyrie::common::ContractResult; use crate::executions::update_distribution; use valkyrie::test_utils::{expect_unauthorized_err, expect_overflow_err, set_height, expect_generic_err}; use crate::states::{Distribution, ContractState}; -use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR}; +use valkyrie::test_constants::distributor::{distributor_env, MANAGING_TOKEN, DISTRIBUTOR, RECIPIENT}; use valkyrie::test_constants::governance::governance_sender; use valkyrie::test_constants::default_sender; use valkyrie::lp_staking::execute_msgs::Cw20HookMsg; @@ -69,7 +69,7 @@ fn succeed() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), Some(to_binary(&valkyrie::governance::execute_msgs::Cw20HookMsg::StakeGovernanceToken {}).unwrap()), ); @@ -92,7 +92,7 @@ fn succeed() { id: 1, start_height: 20001, end_height: 31000, - recipient: Addr::unchecked("Recipient"), + recipient: Addr::unchecked(RECIPIENT), amount: Uint128::new(20000), distributed_amount: Uint128::zero(), message: Some(to_binary(&Cw20HookMsg::Bond {}).unwrap()) @@ -112,7 +112,7 @@ fn failed_invalid_permission() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); @@ -143,7 +143,7 @@ fn failed_overflow() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); @@ -174,7 +174,7 @@ fn failed_less_than_released_amount() { &mut deps, 20000, 30000, - "Recipient".to_string(), + RECIPIENT.to_string(), Uint128::new(10000), None, ); diff --git a/contracts/governance/Cargo.toml b/contracts/governance/Cargo.toml index efbbb3a..6a40312 100644 --- a/contracts/governance/Cargo.toml +++ b/contracts/governance/Cargo.toml @@ -35,12 +35,11 @@ overflow-checks = true [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } valkyrie = { path = "../../packages/valkyrie", version = "1.0.8-beta.1" } [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } -terra-cosmwasm = { version = "2.2.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/governance/schema/cw20_hook_msg.json b/contracts/governance/schema/cw20_hook_msg.json index 0a4c4f0..0477ea4 100644 --- a/contracts/governance/schema/cw20_hook_msg.json +++ b/contracts/governance/schema/cw20_hook_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Cw20HookMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/governance/schema/execute_msg.json b/contracts/governance/schema/execute_msg.json index 1e37720..496ce36 100644 --- a/contracts/governance/schema/execute_msg.json +++ b/contracts/governance/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/governance/schema/migrate_msg.json b/contracts/governance/schema/migrate_msg.json index 81a4f43..87b18ea 100644 --- a/contracts/governance/schema/migrate_msg.json +++ b/contracts/governance/schema/migrate_msg.json @@ -1,54 +1,5 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "MigrateMsg", - "type": "object", - "required": [ - "ticket_config" - ], - "properties": { - "ticket_config": { - "$ref": "#/definitions/TicketConfigInitMsg" - } - }, - "definitions": { - "TicketConfigInitMsg": { - "type": "object", - "required": [ - "distribution_schedule", - "ticket_token" - ], - "properties": { - "distribution_schedule": { - "type": "array", - "items": { - "type": "array", - "items": [ - { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - { - "$ref": "#/definitions/Uint128" - } - ], - "maxItems": 3, - "minItems": 3 - } - }, - "ticket_token": { - "type": "string" - } - } - }, - "Uint128": { - "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", - "type": "string" - } - } + "type": "object" } diff --git a/contracts/governance/schema/query_msg.json b/contracts/governance/schema/query_msg.json index 61944f4..9ae7116 100644 --- a/contracts/governance/schema/query_msg.json +++ b/contracts/governance/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/governance/src/poll/tests/cast_vote.rs b/contracts/governance/src/poll/tests/cast_vote.rs index 235bc3a..909924b 100644 --- a/contracts/governance/src/poll/tests/cast_vote.rs +++ b/contracts/governance/src/poll/tests/cast_vote.rs @@ -12,9 +12,9 @@ use crate::poll::states::{Poll, VoteInfo}; use crate::staking::states::StakerState; use crate::tests::init_default; -pub const VOTER1: &str = "Voter1"; -pub const VOTER2: &str = "Voter2"; -pub const VOTER3: &str = "Voter3"; +pub const VOTER1: &str = "terra17q4lzg70un58uefr2fwu7uxtgvftspr7d0a6p3"; +pub const VOTER2: &str = "terra1vwy8s2jqc25x9u0e94459wn22lx0j3x466k4jj"; +pub const VOTER3: &str = "terra1q74qzdrycn0p884ex4pyvwhvp4apjawntu054a"; pub fn exec( deps: &mut CustomDeps, diff --git a/contracts/governance/src/poll/tests/create_poll.rs b/contracts/governance/src/poll/tests/create_poll.rs index 2b35c11..1726120 100644 --- a/contracts/governance/src/poll/tests/create_poll.rs +++ b/contracts/governance/src/poll/tests/create_poll.rs @@ -13,7 +13,7 @@ use crate::poll::executions::create_poll; use crate::poll::states::Poll; use crate::tests::init_default; -pub const PROPOSER1: &str = "Proposer1"; +pub const PROPOSER1: &str = "terra14mtctaszgzm4gcedlfslds802fmklnp4up72da"; pub const POLL_TITLE: &str = "PollTitle"; pub const POLL_DESCRIPTION: &str = "PollDescription"; @@ -375,9 +375,18 @@ fn failed_create_poll_transfer() { } pub fn mock_exec_msg(order: u64) -> ExecutionMsg { + + let contracts = vec![ + "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n", + "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f", + "terra17q4lzg70un58uefr2fwu7uxtgvftspr7d0a6p3", + "terra1vwy8s2jqc25x9u0e94459wn22lx0j3x466k4jj", + "terra14mtctaszgzm4gcedlfslds802fmklnp4up72da", + ]; + ExecutionMsg { order, - contract: format!("Contract{}", order), + contract: contracts[order as usize].to_string(), msg: to_binary(&Cw20ExecuteMsg::Burn { amount: Uint128::new(1), }).unwrap(), diff --git a/contracts/governance/src/poll/tests/reply_execution.rs b/contracts/governance/src/poll/tests/reply_execution.rs index 261c446..aed66ab 100644 --- a/contracts/governance/src/poll/tests/reply_execution.rs +++ b/contracts/governance/src/poll/tests/reply_execution.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{ContractResult as CwContractResult, Env, Reply, Response, SubMsgExecutionResponse, Uint128}; +use cosmwasm_std::{Env, Reply, Response, SubMsgResponse, SubMsgResult, Uint128}; use valkyrie::common::ContractResult; use valkyrie::governance::enumerations::{PollStatus, VoteOption}; @@ -14,7 +14,7 @@ use crate::tests::init_default; pub fn exec( deps: &mut CustomDeps, env: Env, - result: CwContractResult, + result: SubMsgResult, ) -> ContractResult { reply_execution(deps.as_mut(), env, Reply { id: REPLY_EXECUTION, @@ -53,7 +53,7 @@ fn succeed_success_reply() { let (env, _, _) = super::execute_poll::will_success(&mut deps, poll_id); let context = PollExecutionContext::load(&deps.storage).unwrap(); - exec(&mut deps, env.clone(), CwContractResult::Ok(mock_subcall_response())).unwrap(); + exec(&mut deps, env.clone(), SubMsgResult::Ok(mock_subcall_response())).unwrap(); assert!(PollExecutionContext::may_load(&deps.storage).unwrap().is_none()); @@ -92,7 +92,7 @@ fn succeed_failed_reply() { let (env, _, _) = super::execute_poll::will_success(&mut deps, poll_id); let context = PollExecutionContext::load(&deps.storage).unwrap(); - exec(&mut deps, env.clone(), CwContractResult::Err("Mock err".to_string())).unwrap(); + exec(&mut deps, env.clone(), SubMsgResult::Err("Mock err".to_string())).unwrap(); assert!(PollExecutionContext::may_load(&deps.storage).unwrap().is_none()); @@ -100,8 +100,8 @@ fn succeed_failed_reply() { assert_eq!(poll.status, PollStatus::Failed); } -pub fn mock_subcall_response() -> SubMsgExecutionResponse { - SubMsgExecutionResponse { +pub fn mock_subcall_response() -> SubMsgResponse { + SubMsgResponse { events: vec![], data: None, } diff --git a/contracts/governance/src/staking/executions.rs b/contracts/governance/src/staking/executions.rs index 6298f16..2f8a751 100644 --- a/contracts/governance/src/staking/executions.rs +++ b/contracts/governance/src/staking/executions.rs @@ -8,10 +8,9 @@ use valkyrie::errors::ContractError; use crate::common::states::{ContractConfig, load_available_balance}; use super::states::{StakerState, StakingState}; -use valkyrie::utils::make_response; +use valkyrie::utils::{is_contract, make_response}; use valkyrie::message_factories; use valkyrie::governance::execute_msgs::{StakingConfigInitMsg, ExecuteMsg}; -use valkyrie::terra::is_contract; use crate::staking::states::StakingConfig; use crate::vp::states::compute_ticket; @@ -77,7 +76,7 @@ pub fn stake_governance_token( return Err(ContractError::Std(StdError::generic_err("Insufficient funds sent"))); } - if is_contract(&deps.querier, &sender)? { + if is_contract(&sender) { return Err(ContractError::Std(StdError::generic_err("Can only called by wallet"))); } diff --git a/contracts/governance/src/staking/tests/stake_governance_token_hook.rs b/contracts/governance/src/staking/tests/stake_governance_token_hook.rs index 014d42e..3f68e5b 100644 --- a/contracts/governance/src/staking/tests/stake_governance_token_hook.rs +++ b/contracts/governance/src/staking/tests/stake_governance_token_hook.rs @@ -10,10 +10,10 @@ use crate::staking::executions::stake_governance_token_hook; use crate::staking::states::{StakerState, StakingState}; use crate::tests::init_default; -pub const STAKER1: &str = "Staker1"; +pub const STAKER1: &str = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; pub const STAKER1_STAKE_AMOUNT: Uint128 = Uint128::new(10u128); -pub const STAKER2: &str = "Staker2"; +pub const STAKER2: &str = "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f"; pub const STAKER2_STAKE_AMOUNT: Uint128 = Uint128::new(10u128); pub fn exec(deps: &mut CustomDeps, env: Env, info: MessageInfo, sender: Addr, amount: Uint128) -> ContractResult { @@ -81,7 +81,7 @@ fn failed_wrong_token() { let result = exec( &mut deps, governance_env(), - mock_info("Another Token", &[]), + mock_info("terra17q4lzg70un58uefr2fwu7uxtgvftspr7d0a6p3", &[]), Addr::unchecked(STAKER1), STAKER1_STAKE_AMOUNT, ); diff --git a/contracts/governance/src/staking/tests/update_staking_config.rs b/contracts/governance/src/staking/tests/update_staking_config.rs index a01ac35..5eb09f2 100644 --- a/contracts/governance/src/staking/tests/update_staking_config.rs +++ b/contracts/governance/src/staking/tests/update_staking_config.rs @@ -48,7 +48,7 @@ fn succeed() { init_default(deps.as_mut()); - let distributor = "NewDistributor"; + let distributor = "terra17q4lzg70un58uefr2fwu7uxtgvftspr7d0a6p3"; will_success(&mut deps, Some(distributor.to_string())); diff --git a/contracts/governance/src/vp/tests/update_ticket_config.rs b/contracts/governance/src/vp/tests/update_ticket_config.rs index 3becbc2..ad0c7a0 100644 --- a/contracts/governance/src/vp/tests/update_ticket_config.rs +++ b/contracts/governance/src/vp/tests/update_ticket_config.rs @@ -30,12 +30,12 @@ fn update_ticket_config_test() { deps.as_mut(), env.clone(), info.clone(), - Some(Addr::unchecked("DDDD").to_string()), + Some(Addr::unchecked("terra1f68wt2ch3cx2g62dxtc8v68mkdh5wchdgdjwz7").to_string()), Some(vec![TICKET_DIST_SCHEDULE, (100, 200, Uint128::new(1234u128))]) ); let config = TicketConfig::load(&deps.storage).unwrap(); - assert_eq!(config.ticket_token, "DDDD".to_string()); + assert_eq!(config.ticket_token, "terra1f68wt2ch3cx2g62dxtc8v68mkdh5wchdgdjwz7".to_string()); assert_eq!(config.distribution_schedule, vec![TICKET_DIST_SCHEDULE, (100, 200, Uint128::new(1234u128))]); } \ No newline at end of file diff --git a/contracts/lp_staking/Cargo.toml b/contracts/lp_staking/Cargo.toml index 6f13ab6..5457e7d 100644 --- a/contracts/lp_staking/Cargo.toml +++ b/contracts/lp_staking/Cargo.toml @@ -37,15 +37,13 @@ overflow-checks = true backtraces = ["cosmwasm-std/backtraces"] [dependencies] -cosmwasm-std = { version = "0.16.0" } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } valkyrie = { version = "1.0.8-beta.1", path = "../../packages/valkyrie" } -schemars = "0.8.3" -terraswap = "2.4.0" -terra-cosmwasm = { version = "2.2.0" } +schemars = { version = "0.8.10" } serde = { version = "1.0.126", default-features = false, features = ["derive"] } [dev-dependencies] -cosmwasm-schema = "0.16.0" +cosmwasm-schema = { version = "1.0.0" } cosmwasm-storage = { version = "0.16.0", features = ["iterator"] } diff --git a/contracts/lp_staking/README.md b/contracts/lp_staking/README.md index baf51f2..c31163f 100644 --- a/contracts/lp_staking/README.md +++ b/contracts/lp_staking/README.md @@ -1,5 +1,5 @@ # Staking The Staking Contract contains the logic for LP Token staking and reward distribution. VKR tokens -allocated for as liquidity incentives are distributed pro-rata to stakers of the VKR-UST -Terraswap pair LP token. +allocated for as liquidity incentives are distributed pro-rata to stakers of the VKR-USDC +Astroport pair LP token. diff --git a/contracts/lp_staking/schema/cw20_hook_msg.json b/contracts/lp_staking/schema/cw20_hook_msg.json index 37881af..6394dce 100644 --- a/contracts/lp_staking/schema/cw20_hook_msg.json +++ b/contracts/lp_staking/schema/cw20_hook_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Cw20HookMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/lp_staking/schema/execute_msg.json b/contracts/lp_staking/schema/execute_msg.json index 88a9196..a52a177 100644 --- a/contracts/lp_staking/schema/execute_msg.json +++ b/contracts/lp_staking/schema/execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExecuteMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/lp_staking/schema/query_msg.json b/contracts/lp_staking/schema/query_msg.json index 9034de9..6bc84b5 100644 --- a/contracts/lp_staking/schema/query_msg.json +++ b/contracts/lp_staking/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "type": "object", "required": [ diff --git a/contracts/lp_staking/src/entrypoints.rs b/contracts/lp_staking/src/entrypoints.rs index 8f6668b..00bfe26 100644 --- a/contracts/lp_staking/src/entrypoints.rs +++ b/contracts/lp_staking/src/entrypoints.rs @@ -31,6 +31,7 @@ pub fn instantiate( Config { admin: info.sender, token: deps.api.addr_validate(&msg.token.as_str())?, + usdc_token: deps.api.addr_validate(&msg.token.as_str())?, pair: deps.api.addr_validate(&msg.pair.as_str())?, lp_token: deps.api.addr_validate(&msg.lp_token.as_str())?, whitelisted_contracts: msg.whitelisted_contracts.iter() diff --git a/contracts/lp_staking/src/executions.rs b/contracts/lp_staking/src/executions.rs index 11dc0ee..5f227fb 100644 --- a/contracts/lp_staking/src/executions.rs +++ b/contracts/lp_staking/src/executions.rs @@ -20,7 +20,7 @@ pub fn bond( let config: Config = Config::load(deps.storage)?; - if !config.is_authorized(&deps.as_ref(), &sender_addr_raw)? { + if !config.is_authorized(&sender_addr_raw)? { return Err(ContractError::Std(StdError::generic_err( "Can only called by wallet", ))); diff --git a/contracts/lp_staking/src/states.rs b/contracts/lp_staking/src/states.rs index af98c39..5d0fda2 100644 --- a/contracts/lp_staking/src/states.rs +++ b/contracts/lp_staking/src/states.rs @@ -1,9 +1,9 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use cosmwasm_std::{Addr, Decimal, Deps, StdResult, Storage, Uint128}; +use cosmwasm_std::{Addr, Decimal, StdResult, Storage, Uint128}; use cw_storage_plus::{Item, Map}; -use valkyrie::terra::is_contract; +use valkyrie::utils::is_contract; const CONFIG: Item = Item::new("config_v3"); const ADMIN_NOMINEE: Item = Item::new("admin_nominee"); @@ -12,6 +12,7 @@ const ADMIN_NOMINEE: Item = Item::new("admin_nominee"); pub struct Config { pub admin: Addr, pub token: Addr, + pub usdc_token: Addr, pub lp_token: Addr, pub pair: Addr, pub whitelisted_contracts: Vec, @@ -32,8 +33,8 @@ impl Config { self.whitelisted_contracts.contains(&address) } - pub fn is_authorized(&self, deps: &Deps, address: &Addr) -> StdResult { - if is_contract(&deps.querier, &address)? && !self.is_whitelisted_contract(&address) { + pub fn is_authorized(&self, address: &Addr) -> StdResult { + if is_contract(&address) && !self.is_whitelisted_contract(&address) { return Ok(false); } diff --git a/contracts/lp_staking/src/tests/bond.rs b/contracts/lp_staking/src/tests/bond.rs index 69662c6..852a7b1 100644 --- a/contracts/lp_staking/src/tests/bond.rs +++ b/contracts/lp_staking/src/tests/bond.rs @@ -28,8 +28,8 @@ fn will_success(deps: &mut CustomDeps, env:Env, sender:&Addr) { #[test] fn succeed() { - let sender1 = Addr::unchecked("sender1"); - let sender2 = Addr::unchecked("sender2"); + let sender1 = Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"); + let sender2 = Addr::unchecked("terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f"); let mut deps = custom_deps(); let (env, _info, _response) = default(&mut deps, None); diff --git a/contracts/lp_staking/src/tests/update_config.rs b/contracts/lp_staking/src/tests/update_config.rs index b844038..ffb10e3 100644 --- a/contracts/lp_staking/src/tests/update_config.rs +++ b/contracts/lp_staking/src/tests/update_config.rs @@ -68,29 +68,29 @@ fn succeed() { let (_env, info, _response) = default(&mut deps, None); - let whitelisted_contracts = vec!["WHITELISTED1".to_string(), "WHITELISTED2".to_string()]; + let whitelisted_contracts = vec!["terra1r4qtnusnk63wkg2y6sytwr37aymz0sfy3p2yc9".to_string(), "terra14mtctaszgzm4gcedlfslds802fmklnp4up72da".to_string()]; let distribution_schedule = vec![(0, 50, Uint128::new(50u128)), (50, 100, Uint128::new(50u128))]; will_success( &mut deps, - Some("NEW_TOKEN".to_string()), - Some("NEW_PAIR".to_string()), - Some("NEW_LP".to_string()), - Some("NEW_ADMIN".to_string()), + Some("terra1r0rm0evrlkfvpt0csrcpmnpmrega54czajfd86".to_string()), + Some("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string()), + Some("terra199vw7724lzkwz6lf2hsx04lrxfkz09tg8dlp6r".to_string()), + Some("terra1e8ryd9ezefuucd4mje33zdms9m2s90m57878v9".to_string()), Some(whitelisted_contracts.clone()), Some(distribution_schedule.clone()), ); let config = Config::load(&deps.storage).unwrap(); - assert_eq!(config.token, Addr::unchecked("NEW_TOKEN".to_string())); - assert_eq!(config.pair, Addr::unchecked("NEW_PAIR".to_string())); - assert_eq!(config.lp_token, Addr::unchecked("NEW_LP".to_string())); + assert_eq!(config.token, Addr::unchecked("terra1r0rm0evrlkfvpt0csrcpmnpmrega54czajfd86".to_string())); + assert_eq!(config.pair, Addr::unchecked("terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n".to_string())); + assert_eq!(config.lp_token, Addr::unchecked("terra199vw7724lzkwz6lf2hsx04lrxfkz09tg8dlp6r".to_string())); assert_eq!(config.admin, info.sender); assert_eq!(config.whitelisted_contracts, whitelisted_contracts); assert_eq!(config.distribution_schedule, distribution_schedule); let admin_nominee = Config::may_load_admin_nominee(&deps.storage).unwrap(); - assert_eq!(admin_nominee, Some(Addr::unchecked("NEW_ADMIN".to_string()))); + assert_eq!(admin_nominee, Some(Addr::unchecked("terra1e8ryd9ezefuucd4mje33zdms9m2s90m57878v9".to_string()))); } #[test] @@ -99,7 +99,7 @@ fn failed_invalid_permission() { let (env, mut info, _response) = default(&mut deps, None); - info.sender = Addr::unchecked("NEW_ADMIN"); + info.sender = Addr::unchecked("terra1e8ryd9ezefuucd4mje33zdms9m2s90m57878v9"); let result = exec( &mut deps, diff --git a/contracts/proxy/.cargo/config b/contracts/proxy/.cargo/config new file mode 100644 index 0000000..8d4bc73 --- /dev/null +++ b/contracts/proxy/.cargo/config @@ -0,0 +1,6 @@ +[alias] +wasm = "build --release --target wasm32-unknown-unknown" +wasm-debug = "build --target wasm32-unknown-unknown" +unit-test = "test --lib" +integration-test = "test --test integration" +schema = "run --example schema" diff --git a/contracts/proxy/Cargo.toml b/contracts/proxy/Cargo.toml new file mode 100644 index 0000000..b7a0c44 --- /dev/null +++ b/contracts/proxy/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "valkyrie-proxy" +version = "1.0.8-beta.1" +authors = ["Valkyrie Protocol"] +edition = "2018" +description = "" +license = "Apache-2.0" +repository = "https://github.com/valkyrieprotocol/contracts.git" +homepage = "https://valkyrieprotocol.com" +documentation = "https://docs.valkyrieprotocol.com" + +exclude = [ + "contract.wasm", + "hash.txt", +] + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +# for quicker tests, cargo test --lib +# for more explicit tests, cargo test --features=backtraces +backtraces = ["cosmwasm-std/backtraces"] + +[profile.release] +opt-level = 3 +debug = false +rpath = false +lto = true +debug-assertions = false +codegen-units = 1 +panic = 'abort' +incremental = false +overflow-checks = true + +[dependencies] +serde = { version = "1.0.126", default-features = false, features = ["derive"] } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } +valkyrie = { path = "../../packages/valkyrie", default-features = false, version = "1.0.8-beta.1" } +valkyrie-qualifier = { path = "../../packages/valkyrie_qualifier", default-features = false, version = "1.0.8-beta.1" } +protobuf = { version = "2", features = ["with-bytes"] } + +[dev-dependencies] +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/proxy/README.md b/contracts/proxy/README.md new file mode 100644 index 0000000..1c25ae2 --- /dev/null +++ b/contracts/proxy/README.md @@ -0,0 +1 @@ +# Valkyrie Proxy diff --git a/contracts/proxy/examples/schema.rs b/contracts/proxy/examples/schema.rs new file mode 100644 index 0000000..5a62e9e --- /dev/null +++ b/contracts/proxy/examples/schema.rs @@ -0,0 +1,30 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use valkyrie::proxy::asset::*; +use valkyrie::proxy::execute_msgs::*; +use valkyrie::proxy::query_msgs::*; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(Asset), &out_dir); + export_schema(&schema_for!(AssetInfo), &out_dir); + export_schema(&schema_for!(PairInfo), &out_dir); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(SwapOperation), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(DexType), &out_dir); + export_schema(&schema_for!(DexInfo), &out_dir); + export_schema(&schema_for!(Cw20HookMsg), &out_dir); + export_schema(&schema_for!(MigrateMsg), &out_dir); + + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(SimulateSwapOperationsResponse), &out_dir); +} \ No newline at end of file diff --git a/contracts/proxy/schema/asset.json b/contracts/proxy/schema/asset.json new file mode 100644 index 0000000..cd5a11f --- /dev/null +++ b/contracts/proxy/schema/asset.json @@ -0,0 +1,68 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Asset", + "type": "object", + "required": [ + "amount", + "info" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "info": { + "$ref": "#/definitions/AssetInfo" + } + }, + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/asset_info.json b/contracts/proxy/schema/asset_info.json new file mode 100644 index 0000000..44efab7 --- /dev/null +++ b/contracts/proxy/schema/asset_info.json @@ -0,0 +1,47 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "AssetInfo", + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] +} diff --git a/contracts/proxy/schema/cw20_hook_msg.json b/contracts/proxy/schema/cw20_hook_msg.json new file mode 100644 index 0000000..1c0ccb8 --- /dev/null +++ b/contracts/proxy/schema/cw20_hook_msg.json @@ -0,0 +1,138 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Cw20HookMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "execute_swap_operations" + ], + "properties": { + "execute_swap_operations": { + "type": "object", + "required": [ + "operations" + ], + "properties": { + "max_spread": { + "anyOf": [ + { + "$ref": "#/definitions/Decimal" + }, + { + "type": "null" + } + ] + }, + "minimum_receive": { + "anyOf": [ + { + "$ref": "#/definitions/Uint128" + }, + { + "type": "null" + } + ] + }, + "operations": { + "type": "array", + "items": { + "$ref": "#/definitions/SwapOperation" + } + }, + "to": { + "type": [ + "string", + "null" + ] + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Decimal": { + "description": "A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18)", + "type": "string" + }, + "SwapOperation": { + "oneOf": [ + { + "type": "object", + "required": [ + "swap" + ], + "properties": { + "swap": { + "type": "object", + "required": [ + "ask_asset_info", + "offer_asset_info" + ], + "properties": { + "ask_asset_info": { + "$ref": "#/definitions/AssetInfo" + }, + "offer_asset_info": { + "$ref": "#/definitions/AssetInfo" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/dex_info.json b/contracts/proxy/schema/dex_info.json new file mode 100644 index 0000000..8c86553 --- /dev/null +++ b/contracts/proxy/schema/dex_info.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "DexInfo", + "type": "object", + "required": [ + "dex_type", + "factory" + ], + "properties": { + "dex_type": { + "$ref": "#/definitions/DexType" + }, + "factory": { + "$ref": "#/definitions/Addr" + } + }, + "definitions": { + "Addr": { + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" + }, + "DexType": { + "type": "string", + "enum": [ + "astroport" + ] + } + } +} diff --git a/contracts/proxy/schema/dex_type.json b/contracts/proxy/schema/dex_type.json new file mode 100644 index 0000000..26c5cbb --- /dev/null +++ b/contracts/proxy/schema/dex_type.json @@ -0,0 +1,8 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "DexType", + "type": "string", + "enum": [ + "astroport" + ] +} diff --git a/contracts/proxy/schema/execute_msg.json b/contracts/proxy/schema/execute_msg.json new file mode 100644 index 0000000..b95840b --- /dev/null +++ b/contracts/proxy/schema/execute_msg.json @@ -0,0 +1,284 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ExecuteMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "receive" + ], + "properties": { + "receive": { + "$ref": "#/definitions/Cw20ReceiveMsg" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "update_config" + ], + "properties": { + "update_config": { + "type": "object", + "properties": { + "fixed_dex": { + "anyOf": [ + { + "$ref": "#/definitions/DexType" + }, + { + "type": "null" + } + ] + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "clear_fixed_dex" + ], + "properties": { + "clear_fixed_dex": { + "type": "object" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "execute_swap_operations" + ], + "properties": { + "execute_swap_operations": { + "type": "object", + "required": [ + "operations" + ], + "properties": { + "max_spread": { + "anyOf": [ + { + "$ref": "#/definitions/Decimal" + }, + { + "type": "null" + } + ] + }, + "minimum_receive": { + "anyOf": [ + { + "$ref": "#/definitions/Uint128" + }, + { + "type": "null" + } + ] + }, + "operations": { + "type": "array", + "items": { + "$ref": "#/definitions/SwapOperation" + } + }, + "to": { + "type": [ + "string", + "null" + ] + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "execute_swap_operation" + ], + "properties": { + "execute_swap_operation": { + "type": "object", + "required": [ + "operation" + ], + "properties": { + "max_spread": { + "anyOf": [ + { + "$ref": "#/definitions/Decimal" + }, + { + "type": "null" + } + ] + }, + "operation": { + "$ref": "#/definitions/SwapOperation" + }, + "to": { + "type": [ + "string", + "null" + ] + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "assert_minimum_receive" + ], + "properties": { + "assert_minimum_receive": { + "type": "object", + "required": [ + "asset_info", + "minimum_receive", + "prev_balance", + "receiver" + ], + "properties": { + "asset_info": { + "$ref": "#/definitions/AssetInfo" + }, + "minimum_receive": { + "$ref": "#/definitions/Uint128" + }, + "prev_balance": { + "$ref": "#/definitions/Uint128" + }, + "receiver": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Binary": { + "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec", + "type": "string" + }, + "Cw20ReceiveMsg": { + "description": "Cw20ReceiveMsg should be de/serialized under `Receive()` variant in a ExecuteMsg", + "type": "object", + "required": [ + "amount", + "msg", + "sender" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + }, + "msg": { + "$ref": "#/definitions/Binary" + }, + "sender": { + "type": "string" + } + } + }, + "Decimal": { + "description": "A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18)", + "type": "string" + }, + "DexType": { + "type": "string", + "enum": [ + "astroport" + ] + }, + "SwapOperation": { + "oneOf": [ + { + "type": "object", + "required": [ + "swap" + ], + "properties": { + "swap": { + "type": "object", + "required": [ + "ask_asset_info", + "offer_asset_info" + ], + "properties": { + "ask_asset_info": { + "$ref": "#/definitions/AssetInfo" + }, + "offer_asset_info": { + "$ref": "#/definitions/AssetInfo" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/instantiate_msg.json b/contracts/proxy/schema/instantiate_msg.json new file mode 100644 index 0000000..1c2ed5d --- /dev/null +++ b/contracts/proxy/schema/instantiate_msg.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "InstantiateMsg", + "type": "object", + "required": [ + "astroport_factory" + ], + "properties": { + "astroport_factory": { + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/migrate_msg.json b/contracts/proxy/schema/migrate_msg.json new file mode 100644 index 0000000..666fb7e --- /dev/null +++ b/contracts/proxy/schema/migrate_msg.json @@ -0,0 +1,6 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "MigrateMsg", + "description": "We currently take no arguments for migrations", + "type": "object" +} diff --git a/contracts/proxy/schema/pair_info.json b/contracts/proxy/schema/pair_info.json new file mode 100644 index 0000000..527a238 --- /dev/null +++ b/contracts/proxy/schema/pair_info.json @@ -0,0 +1,84 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "PairInfo", + "type": "object", + "required": [ + "asset_decimals", + "asset_infos", + "contract_addr", + "liquidity_token" + ], + "properties": { + "asset_decimals": { + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + }, + "maxItems": 2, + "minItems": 2 + }, + "asset_infos": { + "type": "array", + "items": { + "$ref": "#/definitions/AssetInfo" + }, + "maxItems": 2, + "minItems": 2 + }, + "contract_addr": { + "type": "string" + }, + "liquidity_token": { + "type": "string" + } + }, + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + } + } +} diff --git a/contracts/proxy/schema/query_msg.json b/contracts/proxy/schema/query_msg.json new file mode 100644 index 0000000..79ff5a1 --- /dev/null +++ b/contracts/proxy/schema/query_msg.json @@ -0,0 +1,124 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "QueryMsg", + "oneOf": [ + { + "type": "object", + "required": [ + "config" + ], + "properties": { + "config": { + "type": "object" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "simulate_swap_operations" + ], + "properties": { + "simulate_swap_operations": { + "type": "object", + "required": [ + "offer_amount", + "operations" + ], + "properties": { + "offer_amount": { + "$ref": "#/definitions/Uint128" + }, + "operations": { + "type": "array", + "items": { + "$ref": "#/definitions/SwapOperation" + } + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "SwapOperation": { + "oneOf": [ + { + "type": "object", + "required": [ + "swap" + ], + "properties": { + "swap": { + "type": "object", + "required": [ + "ask_asset_info", + "offer_asset_info" + ], + "properties": { + "ask_asset_info": { + "$ref": "#/definitions/AssetInfo" + }, + "offer_asset_info": { + "$ref": "#/definitions/AssetInfo" + } + } + } + }, + "additionalProperties": false + } + ] + }, + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/simulate_swap_operations_response.json b/contracts/proxy/schema/simulate_swap_operations_response.json new file mode 100644 index 0000000..27c48ee --- /dev/null +++ b/contracts/proxy/schema/simulate_swap_operations_response.json @@ -0,0 +1,19 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SimulateSwapOperationsResponse", + "type": "object", + "required": [ + "amount" + ], + "properties": { + "amount": { + "$ref": "#/definitions/Uint128" + } + }, + "definitions": { + "Uint128": { + "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", + "type": "string" + } + } +} diff --git a/contracts/proxy/schema/swap_operation.json b/contracts/proxy/schema/swap_operation.json new file mode 100644 index 0000000..41868c1 --- /dev/null +++ b/contracts/proxy/schema/swap_operation.json @@ -0,0 +1,77 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SwapOperation", + "oneOf": [ + { + "type": "object", + "required": [ + "swap" + ], + "properties": { + "swap": { + "type": "object", + "required": [ + "ask_asset_info", + "offer_asset_info" + ], + "properties": { + "ask_asset_info": { + "$ref": "#/definitions/AssetInfo" + }, + "offer_asset_info": { + "$ref": "#/definitions/AssetInfo" + } + } + } + }, + "additionalProperties": false + } + ], + "definitions": { + "AssetInfo": { + "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", + "oneOf": [ + { + "type": "object", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "object", + "required": [ + "contract_addr" + ], + "properties": { + "contract_addr": { + "type": "string" + } + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "native_token" + ], + "properties": { + "native_token": { + "type": "object", + "required": [ + "denom" + ], + "properties": { + "denom": { + "type": "string" + } + } + } + }, + "additionalProperties": false + } + ] + } + } +} diff --git a/contracts/proxy/src/astroport/executions.rs b/contracts/proxy/src/astroport/executions.rs new file mode 100644 index 0000000..9b14abd --- /dev/null +++ b/contracts/proxy/src/astroport/executions.rs @@ -0,0 +1,93 @@ +use cosmwasm_std::{Addr, Coin, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response, StdResult, to_binary, WasmMsg}; +use cw20::{Cw20ExecuteMsg, Denom}; +use valkyrie::proxy::execute_msgs::{SwapOperation}; + +use valkyrie::cw20::query_balance; +use valkyrie::errors::ContractError; +use valkyrie::proxy::asset::{Asset, AssetInfo}; +use crate::astroport::msgs::PairExecuteMsg; + +use crate::astroport::queries::{query_pair_info}; + +pub fn execute_swap_operation( + deps: DepsMut, + env: Env, + _info: MessageInfo, + factory: Addr, + operation: SwapOperation, + to: Option, + max_spread: Option, +) -> Result { + + let message = match operation { + SwapOperation::Swap { + offer_asset_info, + ask_asset_info, + } => { + let pair_info = query_pair_info( + deps.as_ref(), + &factory, + &[offer_asset_info.clone(), ask_asset_info], + )?; + + let amount = match &offer_asset_info { + AssetInfo::NativeToken { denom } => { + query_balance(&deps.querier, Denom::Native(denom.to_string()), env.contract.address)? + } + AssetInfo::Token { contract_addr } => { + query_balance(&deps.querier, Denom::Cw20(deps.api.addr_validate(contract_addr.as_str())?), env.contract.address)? + } + }; + let offer_asset = Asset { + info: offer_asset_info, + amount, + }; + + asset_into_swap_msg( + pair_info.contract_addr, + offer_asset, + max_spread, + to, + )? + } + }; + + Ok(Response::new().add_message(message)) +} + +fn asset_into_swap_msg( + pair_contract: String, + offer_asset: Asset, + max_spread: Option, + to: Option, +) -> StdResult { + match offer_asset.info.clone() { + AssetInfo::NativeToken { denom } => Ok(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: pair_contract, + funds: vec![Coin { + denom, + amount: offer_asset.amount, + }], + msg: to_binary(&PairExecuteMsg::Swap { + offer_asset, + belief_price: None, + max_spread, + to, + })?, + })), + AssetInfo::Token { contract_addr } => Ok(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr, + funds: vec![], + msg: to_binary(&Cw20ExecuteMsg::Send { + contract: pair_contract, + amount: offer_asset.amount, + msg: to_binary(&PairExecuteMsg::Swap { + offer_asset, + belief_price: None, + max_spread, + to, + })?, + })?, + })), + } +} \ No newline at end of file diff --git a/contracts/proxy/src/astroport/mod.rs b/contracts/proxy/src/astroport/mod.rs new file mode 100644 index 0000000..711a6b1 --- /dev/null +++ b/contracts/proxy/src/astroport/mod.rs @@ -0,0 +1,4 @@ +pub mod queries; +pub mod msgs; +pub mod executions; + diff --git a/contracts/proxy/src/astroport/msgs.rs b/contracts/proxy/src/astroport/msgs.rs new file mode 100644 index 0000000..b5e79c3 --- /dev/null +++ b/contracts/proxy/src/astroport/msgs.rs @@ -0,0 +1,51 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use cosmwasm_std::{Decimal, Uint128}; +use valkyrie::proxy::asset::{Asset, AssetInfo}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum FactoryQueryMsg { + Config {}, + Pair { + asset_infos: [AssetInfo; 2], + }, + Pairs { + start_after: Option<[AssetInfo; 2]>, + limit: Option, + }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PairExecuteMsg { + Swap { + offer_asset: Asset, + belief_price: Option, + max_spread: Option, + to: Option, + }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PairQueryMsg { + Pair {}, + Pool {}, + Simulation { offer_asset: Asset }, + ReverseSimulation { ask_asset: Asset }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct SimulationResponse { + pub return_amount: Uint128, + pub spread_amount: Uint128, + pub commission_amount: Uint128, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct ReverseSimulationResponse { + pub offer_amount: Uint128, + pub spread_amount: Uint128, + pub commission_amount: Uint128, +} \ No newline at end of file diff --git a/contracts/proxy/src/astroport/queries.rs b/contracts/proxy/src/astroport/queries.rs new file mode 100644 index 0000000..56d94e5 --- /dev/null +++ b/contracts/proxy/src/astroport/queries.rs @@ -0,0 +1,69 @@ +use cosmwasm_std::{Addr, Deps, StdError, StdResult, Uint128}; +use cw20::{Denom}; + +use valkyrie::cw20::query_balance; +use valkyrie::proxy::asset::{Asset, AssetInfo, PairInfo}; +use crate::astroport::msgs::{FactoryQueryMsg, PairQueryMsg, SimulationResponse}; + +pub fn simulate_swap_operation( + deps: Deps, + factory: &Addr, + offer_asset_info: AssetInfo, + ask_asset_info: AssetInfo, + offer_amount: Uint128, +) -> Result { + let pair_info = query_pair_info( + deps, + factory, + &[offer_asset_info.clone(), ask_asset_info.clone()], + )?; + + let res: SimulationResponse = deps.querier.query_wasm_smart( + pair_info.contract_addr, + &PairQueryMsg::Simulation { + offer_asset: Asset { + info: offer_asset_info.clone(), + amount: offer_amount, + }, + }, + )?; + + Ok(res.return_amount) +} + + + +pub fn query_pair_info( + deps: Deps, + factory_contract: &Addr, + asset_infos: &[AssetInfo; 2], +) -> StdResult { + deps.querier.query_wasm_smart( + factory_contract.to_string(), + &FactoryQueryMsg::Pair { + asset_infos: asset_infos.clone(), + }, + ) +} + +pub fn query_pool_size( + deps: Deps, + factory: Addr, + asset_infos: [AssetInfo; 2], +) -> StdResult { + let pair_info = query_pair_info(deps, &factory, &asset_infos)?; + let pool_addr = deps.api.addr_validate(pair_info.contract_addr.as_str())?; + + let mut pool = vec![Uint128::zero(), Uint128::zero()]; + + for index in 0..asset_infos.to_vec().len() { + let asset_info = &asset_infos.to_vec()[index]; + pool[index] = match asset_info { + AssetInfo::Token { contract_addr } => query_balance(&deps.querier, Denom::Cw20(deps.api.addr_validate(contract_addr.as_str())?), pool_addr.clone()), + AssetInfo::NativeToken { denom } => query_balance(&deps.querier, Denom::Native(denom.to_string()), pool_addr.clone()) + }?.clone(); + } + + let size = pool[0] * pool[1]; + Ok(size) +} \ No newline at end of file diff --git a/contracts/proxy/src/entrypoints.rs b/contracts/proxy/src/entrypoints.rs new file mode 100644 index 0000000..f29fcb5 --- /dev/null +++ b/contracts/proxy/src/entrypoints.rs @@ -0,0 +1,113 @@ +use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, to_binary, from_binary}; +use cosmwasm_std::entry_point; + +use valkyrie::proxy::execute_msgs::{ExecuteMsg, MigrateMsg, Cw20HookMsg}; +use valkyrie::proxy::query_msgs::QueryMsg; +use valkyrie::common::ContractResult; + +use cw20::Cw20ReceiveMsg; +use valkyrie::proxy::execute_msgs::InstantiateMsg; +use crate::executions::{assert_minimum_receive, clear_fixed_dex, execute_swap_operation, execute_swap_operations, update_config}; +use crate::queries::{get_config, simulate_swap_operations}; + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: InstantiateMsg, +) -> ContractResult { + let mut deps_mut = deps; + + crate::executions::instantiate(deps_mut.branch(), env, info, msg)?; + + Ok(Response::default()) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> ContractResult { + match msg { + ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg), + ExecuteMsg::UpdateConfig { fixed_dex } => update_config(deps, env, info, fixed_dex), + ExecuteMsg::ClearFixedDex {} => clear_fixed_dex(deps, env, info), + ExecuteMsg::ExecuteSwapOperations { + operations, + minimum_receive, + to, + max_spread, + } => execute_swap_operations( + deps, + env, + info.sender, + operations, + minimum_receive, + to, + max_spread, + ), + ExecuteMsg::ExecuteSwapOperation { + operation, + to, + max_spread, + } => execute_swap_operation(deps, env, info, operation, to, max_spread), + ExecuteMsg::AssertMinimumReceive { + asset_info, + prev_balance, + minimum_receive, + receiver, + } => assert_minimum_receive( + deps.as_ref(), + asset_info, + prev_balance, + minimum_receive, + deps.api.addr_validate(receiver.as_str())?, + ), + } +} + +pub fn receive_cw20( + deps: DepsMut, + env: Env, + _info: MessageInfo, + cw20_msg: Cw20ReceiveMsg, +) -> ContractResult { + let sender = deps.api.addr_validate(&cw20_msg.sender)?; + match from_binary(&cw20_msg.msg)? { + Cw20HookMsg::ExecuteSwapOperations { + operations, + minimum_receive, + to, + max_spread, + } => execute_swap_operations( + deps, + env, + sender, + operations, + minimum_receive, + to, + max_spread, + ), + } +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> ContractResult { + Ok(Response::default()) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> ContractResult { + let result = match msg { + QueryMsg::Config {} => to_binary(&get_config(deps, env)?), + QueryMsg::SimulateSwapOperations { + offer_amount, + operations, + } => to_binary(&simulate_swap_operations(deps, offer_amount, operations)?), + }?; + + Ok(result) +} diff --git a/contracts/proxy/src/executions.rs b/contracts/proxy/src/executions.rs new file mode 100644 index 0000000..cf86f00 --- /dev/null +++ b/contracts/proxy/src/executions.rs @@ -0,0 +1,210 @@ +use std::collections::{HashSet}; +use cosmwasm_std::{Addr, Api, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, to_binary, Uint128, WasmMsg}; +use valkyrie::proxy::execute_msgs::{DexInfo, DexType, ExecuteMsg, SwapOperation}; + +use valkyrie::common::{ContractResult}; +use valkyrie::errors::ContractError; +use valkyrie::proxy::asset::{addr_opt_validate, AssetInfo}; +use valkyrie::proxy::execute_msgs::InstantiateMsg; +use valkyrie::utils::{make_response}; + +use crate::queries::{get_largest_pool, query_pool}; +use crate::states::*; + +pub const MAX_SWAP_OPERATIONS: usize = 50; + +pub fn instantiate( + deps: DepsMut, + _env: Env, + info: MessageInfo, + msg: InstantiateMsg, +) -> ContractResult { + Config { + admin: info.sender, + fixed_dex: None, + dex_list: vec![ + DexInfo { + dex_type: DexType::Astroport, + factory: deps.api.addr_validate(msg.astroport_factory.as_str())?, + } + ], + }.save(deps.storage)?; + + Ok(Response::default()) +} + +pub fn update_config( + deps: DepsMut, + _env: Env, + info: MessageInfo, + fixed_dex: Option, +) -> ContractResult { + // Validate + let mut config = Config::load(deps.storage)?; + if !config.is_admin(&info.sender) { + return Err(ContractError::Unauthorized {}); + } + + // Execute + let mut response = make_response("update_config"); + + if let Some(fixed_dex) = fixed_dex { + config.fixed_dex = Some(fixed_dex); + response = response.add_attribute("is_updated_fixed_dex", "true"); + } + + config.save(deps.storage)?; + + Ok(response) +} + +pub fn clear_fixed_dex( + deps: DepsMut, + _env: Env, + info: MessageInfo, +) -> ContractResult { + // Execute + let mut config = Config::load(deps.storage)?; + if !config.is_admin(&info.sender) { + return Err(ContractError::Unauthorized {}); + } + + config.fixed_dex = None; + config.save(deps.storage)?; + + let response = make_response("clear_fixed_dex"); + Ok(response) +} + +#[allow(clippy::too_many_arguments)] +pub fn execute_swap_operations( + deps: DepsMut, + env: Env, + sender: Addr, + operations: Vec, + minimum_receive: Option, + to: Option, + max_spread: Option, +) -> ContractResult { + let operations_len = operations.len(); + if operations_len == 0 { + return Err(ContractError::Std(StdError::generic_err("must provide operations"))); + } + + if operations_len > MAX_SWAP_OPERATIONS { + return Err(ContractError::Std(StdError::generic_err("swap limit exceed"))); + } + + // Assert the operations are properly set + assert_operations(deps.api, &operations)?; + + let to = addr_opt_validate(deps.api, &to)?.unwrap_or(sender); + let target_asset_info = operations.last().unwrap().get_target_asset_info(); + + let mut messages = operations + .into_iter() + .enumerate() + .map(|(operation_index, op)| { + Ok(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: env.contract.address.to_string(), + funds: vec![], + msg: to_binary(&ExecuteMsg::ExecuteSwapOperation { + operation: op, + to: if operation_index == operations_len - 1 { + Some(to.to_string()) + } else { + None + }, + max_spread, + })?, + })) + }) + .collect::>>()?; + + // Execute minimum amount assertion + if let Some(minimum_receive) = minimum_receive { + let receiver_balance = query_pool(deps.as_ref(), target_asset_info.clone(), to.clone())?; + messages.push(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: env.contract.address.to_string(), + funds: vec![], + msg: to_binary(&ExecuteMsg::AssertMinimumReceive { + asset_info: target_asset_info.clone(), + prev_balance: receiver_balance, + minimum_receive, + receiver: to.to_string(), + })?, + })); + } + + Ok(Response::new().add_messages(messages)) +} + +fn assert_operations(api: &dyn Api, operations: &[SwapOperation]) -> StdResult<()> { + let mut ask_asset_map: HashSet = HashSet::new(); + for operation in operations { + let (offer_asset, ask_asset) = match operation { + SwapOperation::Swap { + offer_asset_info, + ask_asset_info, + } => (offer_asset_info.clone(), ask_asset_info.clone()), + }; + offer_asset.check(api)?; + ask_asset.check(api)?; + + ask_asset_map.remove(&offer_asset.to_string()); + ask_asset_map.insert(ask_asset.to_string()); + } + + if ask_asset_map.len() != 1 { + return Err(StdError::generic_err("invalid operations; multiple output token").into()); + } + + Ok(()) +} + +pub fn execute_swap_operation( + deps: DepsMut, + env: Env, + info: MessageInfo, + operation: SwapOperation, + to: Option, + max_spread: Option, +) -> ContractResult { + let offer_asset_info = operation.get_offer_asset_info(); + let ask_asset_info = operation.get_target_asset_info(); + let lagest_pool = get_largest_pool(deps.as_ref(), [offer_asset_info, ask_asset_info])?; + + let response = match lagest_pool.dex_type { + DexType::Astroport => { + crate::astroport::executions::execute_swap_operation( + deps, + env, + info, + lagest_pool.factory.clone(), + operation.clone(), + to, + max_spread + ) + } + }?; + + Ok(response) +} + +pub fn assert_minimum_receive( + deps: Deps, + asset_info: AssetInfo, + prev_balance: Uint128, + minimum_receive: Uint128, + receiver: Addr, +) -> ContractResult { + asset_info.check(deps.api)?; + let receiver_balance = query_pool(deps, asset_info, receiver)?; + let swap_amount = receiver_balance.checked_sub(prev_balance)?; + + if swap_amount < minimum_receive { + Err(ContractError::Std(StdError::generic_err(format!("assertion minimum receive. receive: {0}, amount: {1}", minimum_receive, swap_amount)))) + } else { + Ok(Response::default()) + } +} \ No newline at end of file diff --git a/contracts/proxy/src/lib.rs b/contracts/proxy/src/lib.rs new file mode 100644 index 0000000..1f3da48 --- /dev/null +++ b/contracts/proxy/src/lib.rs @@ -0,0 +1,10 @@ +pub mod entrypoints; + +mod executions; +mod queries; +mod states; + +mod astroport; + +#[cfg(test)] +mod tests; diff --git a/contracts/proxy/src/queries.rs b/contracts/proxy/src/queries.rs new file mode 100644 index 0000000..1d97996 --- /dev/null +++ b/contracts/proxy/src/queries.rs @@ -0,0 +1,140 @@ +use std::collections::{HashSet}; +use cosmwasm_std::{Addr, Deps, Env, StdError, StdResult, Uint128, }; +use cw20::{Denom}; +use valkyrie::common::{ContractResult}; + +use crate::states::*; + +use valkyrie::cw20::query_balance; +use valkyrie::errors::ContractError; +use valkyrie::proxy::asset::{AssetInfo}; +use valkyrie::proxy::execute_msgs::{DexInfo, DexType, find_dex_factory, SwapOperation}; +use valkyrie::proxy::query_msgs::SimulateSwapOperationsResponse; +use crate::executions::{MAX_SWAP_OPERATIONS}; + +pub fn get_config(deps: Deps, _env: Env) -> ContractResult { + let config = Config::load(deps.storage)?; + Ok(config) +} + +pub fn simulate_swap_operations( + deps: Deps, + offer_amount: Uint128, + operations: Vec, +) -> ContractResult { + let operations_len = operations.len(); + if operations_len == 0 { + return Err(ContractError::Std(StdError::generic_err("must provide options"))); + } + + if operations_len > MAX_SWAP_OPERATIONS { + return Err(ContractError::Std(StdError::generic_err("swap limit exceed"))); + } + + assert_operations(deps, &operations)?; + + let mut offer_amount = offer_amount; + for operation in operations.into_iter() { + let offer_asset_info = operation.get_offer_asset_info(); + let ask_asset_info = operation.get_target_asset_info(); + + let dex_info = get_largest_pool(deps, [offer_asset_info.clone(), ask_asset_info.clone()])?; + + match dex_info.dex_type { + DexType::Astroport => { + offer_amount = crate::astroport::queries::simulate_swap_operation( + deps, + &dex_info.factory, + offer_asset_info.clone(), + ask_asset_info.clone(), + offer_amount + )?; + } + }; + } + + Ok(SimulateSwapOperationsResponse { + amount: offer_amount + }) +} + +pub fn get_largest_pool( + deps: Deps, + pairs: [AssetInfo; 2], +) -> StdResult { + + let config = Config::load(deps.storage)?; + + if let Some(fixed_dex) = config.fixed_dex { + if let Some(dex_info) = find_dex_factory(config.dex_list, fixed_dex) { + Ok(dex_info) + } else { + return Err(StdError::generic_err("unavailable factory.")) + } + } else { + let mut pool_size = Uint128::zero(); + let mut selected = config.dex_list[0].clone(); + + for dex_info in config.dex_list { + match dex_info.dex_type { + DexType::Astroport => { + let size = crate::astroport::queries::query_pool_size(deps, dex_info.factory.clone(), pairs.clone())?; + if size > pool_size { + pool_size = size; + selected = dex_info.clone(); + } + } + } + } + + Ok(selected) + } +} + +pub fn query_pool( + deps: Deps, + asset_info: AssetInfo, + pool_addr: Addr, +) -> StdResult { + match asset_info { + AssetInfo::Token { contract_addr, .. } => query_balance( + &deps.querier, + Denom::Cw20(deps.api.addr_validate(contract_addr.as_str())?), + pool_addr, + ), + AssetInfo::NativeToken { denom, .. } => query_balance( + &deps.querier, + Denom::Native(denom), + pool_addr, + ) + } +} + +fn assert_operations( + deps:Deps, + operations: &[SwapOperation] +) -> Result<(), StdError> { + let mut ask_asset_map: HashSet = HashSet::new(); + for operation in operations { + let (offer_asset, ask_asset) = match operation { + SwapOperation::Swap { + offer_asset_info, + ask_asset_info, + } => ( + offer_asset_info, + ask_asset_info, + ), + }; + offer_asset.check(deps.api)?; + ask_asset.check(deps.api)?; + + ask_asset_map.remove(&offer_asset.to_string()); + ask_asset_map.insert(ask_asset.to_string()); + } + + if ask_asset_map.len() != 1 { + return Err(StdError::generic_err("invalid operations; multiple output token").into()); + } + + Ok(()) +} \ No newline at end of file diff --git a/contracts/proxy/src/states.rs b/contracts/proxy/src/states.rs new file mode 100644 index 0000000..8b2abdd --- /dev/null +++ b/contracts/proxy/src/states.rs @@ -0,0 +1,28 @@ +use cosmwasm_std::{Addr, StdResult, Storage}; +use cw_storage_plus::{Item}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use valkyrie::proxy::execute_msgs::{DexInfo, DexType}; + +pub const CONFIG: Item = Item::new("config"); + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct Config { + pub admin: Addr, + pub fixed_dex: Option, + pub dex_list: Vec, +} + +impl Config { + pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { + CONFIG.save(storage, self) + } + + pub fn load(storage: &dyn Storage) -> StdResult { + CONFIG.load(storage) + } + + pub fn is_admin(&self, address: &Addr) -> bool { + self.admin == *address + } +} \ No newline at end of file diff --git a/contracts/proxy/src/tests/clear_fixed_dex.rs b/contracts/proxy/src/tests/clear_fixed_dex.rs new file mode 100644 index 0000000..0d01d6d --- /dev/null +++ b/contracts/proxy/src/tests/clear_fixed_dex.rs @@ -0,0 +1,67 @@ +use cosmwasm_std::{Env, MessageInfo, Response}; + +use valkyrie::common::ContractResult; +use valkyrie::mock_querier::{custom_deps, CustomDeps}; +use valkyrie::proxy::execute_msgs::DexType; +use valkyrie::test_constants::proxy::{ADMIN, ADMIN2, proxy_env, proxy_sender}; +use valkyrie::test_utils::{expect_unauthorized_err}; + +use crate::executions::{clear_fixed_dex}; +use crate::states::{Config}; + +pub fn exec( + deps: &mut CustomDeps, + env: Env, + info: MessageInfo, +) -> ContractResult { + clear_fixed_dex( + deps.as_mut(), + env, + info, + ) +} + +pub fn will_success( + deps: &mut CustomDeps, +) -> (Env, MessageInfo, Response) { + let env = proxy_env(); + let info = proxy_sender(ADMIN); + + let response = exec( + deps, + env.clone(), + info.clone(), + ).unwrap(); + + (env, info, response) +} + +#[test] +fn succeed() { + let mut deps = custom_deps(); + + super::instantiate::default(&mut deps); + super::update_config::will_success(&mut deps, Some(DexType::Astroport)); + + will_success( + &mut deps, + ); + + let config = Config::load(&deps.storage).unwrap(); + assert_eq!(config.fixed_dex, None); +} + +#[test] +fn failed_invalid_permission() { + let mut deps = custom_deps(); + + super::instantiate::default(&mut deps); + + let result = exec( + &mut deps, + proxy_env(), + proxy_sender(ADMIN2), + ); + + expect_unauthorized_err(&result); +} \ No newline at end of file diff --git a/contracts/proxy/src/tests/get_largest_pool.rs b/contracts/proxy/src/tests/get_largest_pool.rs new file mode 100644 index 0000000..164fae4 --- /dev/null +++ b/contracts/proxy/src/tests/get_largest_pool.rs @@ -0,0 +1,71 @@ +// use cosmwasm_std::{Addr, BankMsg, coin, CosmosMsg, Env, MessageInfo, Response, StdError, SubMsg, Uint128}; +// +// use crate::states::Deposit; +// use valkyrie::mock_querier::{CustomDeps, custom_deps}; +// use crate::executions::withdraw; +// use valkyrie::test_constants::campaign::{campaign_env, DEPOSIT_AMOUNT, DEPOSIT_LOCK_PERIOD}; +// use cosmwasm_std::testing::mock_info; +// use valkyrie::errors::ContractError; +// use valkyrie::common::ContractResult; +// +// pub fn exec( +// deps: &mut CustomDeps, +// env: Env, +// info: MessageInfo, +// amount: Uint128, +// ) -> ContractResult { +// withdraw(deps.as_mut(), env, info, amount) +// } +// +// pub fn will_success( +// deps: &mut CustomDeps, +// sender: &str, +// amount: Uint128, +// ) -> (Env, MessageInfo, Response) { +// let env = campaign_env(); +// let info = mock_info(sender, &[]); +// +// let response = exec(deps, env.clone(), info.clone(), amount).unwrap(); +// +// (env, info, response) +// } +// +// #[test] +// fn succeed() { +// let mut deps = custom_deps(); +// +// super::instantiate::default(&mut deps); +// let (env,_ , _) = super::deposit::will_success(&mut deps, "Actor", Uint128::new(1000)); +// +// let mut deposit = Deposit::load(&deps.storage, &Addr::unchecked("Actor")).unwrap(); +// deposit.locked_amounts = vec![(DEPOSIT_AMOUNT, env.block.height + DEPOSIT_LOCK_PERIOD)]; +// deposit.save(&mut deps.storage).unwrap(); +// +// let withdraw_amount = Uint128::new(1000).checked_sub(DEPOSIT_AMOUNT).unwrap(); +// let (_, _, response) = will_success(&mut deps, "Actor", withdraw_amount); +// assert_eq!(response.messages, vec![SubMsg::new(CosmosMsg::Bank(BankMsg::Send { +// to_address: "Actor".to_string(), +// amount: vec![coin(withdraw_amount.u128(), "uluna")], +// }))]); +// } +// +// #[test] +// fn failed_overdrawn() { +// let mut deps = custom_deps(); +// +// super::instantiate::default(&mut deps); +// let (env, _, _) = super::deposit::will_success(&mut deps, "Actor", Uint128::new(1000)); +// +// let mut deposit = Deposit::load(&deps.storage, &Addr::unchecked("Actor")).unwrap(); +// deposit.locked_amounts = vec![(DEPOSIT_AMOUNT, env.block.height + DEPOSIT_LOCK_PERIOD)]; +// deposit.save(&mut deps.storage).unwrap(); +// +// let withdraw_amount = Uint128::new(1000).checked_sub(DEPOSIT_AMOUNT).unwrap() + Uint128::new(1); +// let result = exec( +// &mut deps, +// campaign_env(), +// mock_info("Actor", &[]), +// withdraw_amount, +// ); +// assert_eq!(result.unwrap_err(), ContractError::Std(StdError::generic_err("Overdraw deposit"))); +// } diff --git a/contracts/proxy/src/tests/instantiate.rs b/contracts/proxy/src/tests/instantiate.rs new file mode 100644 index 0000000..1815ea9 --- /dev/null +++ b/contracts/proxy/src/tests/instantiate.rs @@ -0,0 +1,61 @@ +use cosmwasm_std::{Addr, Env, MessageInfo, Response}; + +use valkyrie::common::{ContractResult}; +use valkyrie::mock_querier::{custom_deps, CustomDeps}; +use valkyrie::proxy::execute_msgs::{DexInfo, DexType, InstantiateMsg}; + +use crate::executions::*; +use crate::states::{Config}; +use valkyrie::test_constants::proxy::{ADMIN, ASTRO_FACTORY, proxy_env, proxy_sender}; + +pub fn exec( + deps: &mut CustomDeps, + env: Env, + info: MessageInfo, +) -> ContractResult { + let msg = InstantiateMsg { + astroport_factory: ASTRO_FACTORY.to_string(), + }; + + instantiate(deps.as_mut(), env, info, msg) +} + +pub fn will_success( + deps: &mut CustomDeps, +) -> (Env, MessageInfo, Response) { + let env = proxy_env(); + let info = proxy_sender(ADMIN); + + let response = exec( + deps, + env.clone(), + info.clone(), + ).unwrap(); + + (env, info, response) +} + +pub fn default(deps: &mut CustomDeps) -> (Env, MessageInfo, Response) { + will_success( + deps + ) +} + +#[test] +fn succeed() { + let mut deps = custom_deps(); + + let (env, _, _) = default(&mut deps); + + let config = Config::load(&deps.storage).unwrap(); + assert_eq!(config, Config { + admin: Addr::unchecked(ADMIN), + fixed_dex: None, + dex_list: vec![ + DexInfo { + dex_type: DexType::Astroport, + factory: Addr::unchecked(ASTRO_FACTORY), + } + ], + }); +} \ No newline at end of file diff --git a/contracts/proxy/src/tests/mod.rs b/contracts/proxy/src/tests/mod.rs new file mode 100644 index 0000000..0207337 --- /dev/null +++ b/contracts/proxy/src/tests/mod.rs @@ -0,0 +1,4 @@ +pub mod instantiate; +pub mod update_config; +pub mod clear_fixed_dex; +// pub mod get_largest_pool; diff --git a/contracts/proxy/src/tests/update_config.rs b/contracts/proxy/src/tests/update_config.rs new file mode 100644 index 0000000..d19a26b --- /dev/null +++ b/contracts/proxy/src/tests/update_config.rs @@ -0,0 +1,89 @@ +use cosmwasm_std::{Env, MessageInfo, Response}; + +use valkyrie::common::ContractResult; +use valkyrie::mock_querier::{custom_deps, CustomDeps}; +use valkyrie::proxy::execute_msgs::DexType; +use valkyrie::test_utils::{expect_unauthorized_err}; + +use crate::executions::{update_config}; +use crate::states::{Config}; +use valkyrie::test_constants::campaign::{ADMIN2}; +use valkyrie::test_constants::proxy::{ADMIN, proxy_env, proxy_sender}; + +pub fn exec( + deps: &mut CustomDeps, + env: Env, + info: MessageInfo, + dex_type: Option, +) -> ContractResult { + update_config( + deps.as_mut(), + env, + info, + dex_type, + ) +} + +pub fn will_success( + deps: &mut CustomDeps, + dex_type: Option, +) -> (Env, MessageInfo, Response) { + let env = proxy_env(); + let info = proxy_sender(ADMIN); + + let response = exec( + deps, + env.clone(), + info.clone(), + dex_type, + ).unwrap(); + + (env, info, response) +} + +#[test] +fn succeed() { + let mut deps = custom_deps(); + + super::instantiate::default(&mut deps); + + will_success( + &mut deps, + None + ); + + let config = Config::load(&deps.storage).unwrap(); + assert_eq!(config.fixed_dex, None); + + will_success( + &mut deps, + Some(DexType::Astroport) + ); + + let config = Config::load(&deps.storage).unwrap(); + assert_eq!(config.fixed_dex, Some(DexType::Astroport)); + + will_success( + &mut deps, + None + ); + + let config = Config::load(&deps.storage).unwrap(); + assert_eq!(config.fixed_dex, Some(DexType::Astroport)); +} + +#[test] +fn failed_invalid_permission() { + let mut deps = custom_deps(); + + super::instantiate::default(&mut deps); + + let result = exec( + &mut deps, + proxy_env(), + proxy_sender(ADMIN2), + None, + ); + + expect_unauthorized_err(&result); +} \ No newline at end of file diff --git a/contracts/vp/Cargo.toml b/contracts/vp/Cargo.toml index 4dac508..f916df4 100644 --- a/contracts/vp/Cargo.toml +++ b/contracts/vp/Cargo.toml @@ -34,16 +34,14 @@ incremental = false overflow-checks = true [dependencies] -cw0 = { version = "0.8.1" } -cw2 = { version = "0.8.1" } -cw20 = { version = "0.8.1" } -cw20-base = { version = "0.8.1", features = ["library"]} -cw-storage-plus = { version = "0.8.1" } -cosmwasm-std = { version = "0.16.0" } -schemars = "0.8.1" +cw2 = { version = "0.11.0" } +cw20 = { version = "0.11.0" } +cw20-base = { version = "0.11.0", features = ["library"]} +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cosmwasm-std = { version = "1.0.0" } +schemars = { version = "0.8.10" } serde = { version = "1.0.103", default-features = false, features = ["derive"] } thiserror = { version = "1.0.23" } -astroport = "1.0.1" [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } +cosmwasm-schema = { version = "1.0.0" } diff --git a/contracts/vp/schema/all_allowances_response.json b/contracts/vp/schema/all_allowances_response.json index a8a11a5..6bb2291 100644 --- a/contracts/vp/schema/all_allowances_response.json +++ b/contracts/vp/schema/all_allowances_response.json @@ -35,7 +35,7 @@ }, "Expiration": { "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ + "oneOf": [ { "description": "AtHeight will expire when `env.block.height` >= height", "type": "object", diff --git a/contracts/vp/schema/allowance_response.json b/contracts/vp/schema/allowance_response.json index 71b49ad..c4f98d6 100644 --- a/contracts/vp/schema/allowance_response.json +++ b/contracts/vp/schema/allowance_response.json @@ -17,7 +17,7 @@ "definitions": { "Expiration": { "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ + "oneOf": [ { "description": "AtHeight will expire when `env.block.height` >= height", "type": "object", diff --git a/contracts/vp/schema/cw20_execute_msg.json b/contracts/vp/schema/cw20_execute_msg.json index 4dd7b8a..e4bc559 100644 --- a/contracts/vp/schema/cw20_execute_msg.json +++ b/contracts/vp/schema/cw20_execute_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Cw20ExecuteMsg", - "anyOf": [ + "oneOf": [ { "description": "Transfer is a base message to move tokens to another account without triggering actions", "type": "object", @@ -316,7 +316,7 @@ }, "EmbeddedLogo": { "description": "This is used to store the logo on the blockchain in an accepted format. Enforce maximum size of 5KB on all variants.", - "anyOf": [ + "oneOf": [ { "description": "Store the Logo as an SVG file. The content must conform to the spec at https://en.wikipedia.org/wiki/Scalable_Vector_Graphics (The contract should do some light-weight sanity-check validation)", "type": "object", @@ -347,7 +347,7 @@ }, "Expiration": { "description": "Expiration represents a point in time when some event happens. It can compare with a BlockInfo and will return is_expired() == true once the condition is hit (and for every block in the future)", - "anyOf": [ + "oneOf": [ { "description": "AtHeight will expire when `env.block.height` >= height", "type": "object", @@ -393,7 +393,7 @@ }, "Logo": { "description": "This is used for uploading logo data, or setting it in InstantiateData", - "anyOf": [ + "oneOf": [ { "description": "A reference to an externally hosted logo. Must be a valid HTTP or HTTPS URL.", "type": "object", diff --git a/contracts/vp/schema/instantiate_msg.json b/contracts/vp/schema/instantiate_msg.json index c8a3fca..7b9aa1e 100644 --- a/contracts/vp/schema/instantiate_msg.json +++ b/contracts/vp/schema/instantiate_msg.json @@ -69,7 +69,7 @@ }, "EmbeddedLogo": { "description": "This is used to store the logo on the blockchain in an accepted format. Enforce maximum size of 5KB on all variants.", - "anyOf": [ + "oneOf": [ { "description": "Store the Logo as an SVG file. The content must conform to the spec at https://en.wikipedia.org/wiki/Scalable_Vector_Graphics (The contract should do some light-weight sanity-check validation)", "type": "object", @@ -133,7 +133,7 @@ }, "Logo": { "description": "This is used for uploading logo data, or setting it in InstantiateData", - "anyOf": [ + "oneOf": [ { "description": "A reference to an externally hosted logo. Must be a valid HTTP or HTTPS URL.", "type": "object", diff --git a/contracts/vp/schema/query_msg.json b/contracts/vp/schema/query_msg.json index 60aac9e..369e21f 100644 --- a/contracts/vp/schema/query_msg.json +++ b/contracts/vp/schema/query_msg.json @@ -1,7 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "title": "QueryMsg", - "anyOf": [ + "oneOf": [ { "description": "Returns the current balance of the given address, 0 if unset. Return type: BalanceResponse.", "type": "object", diff --git a/contracts/vp/src/msg.rs b/contracts/vp/src/msg.rs index 0ba1ee1..e1e743e 100644 --- a/contracts/vp/src/msg.rs +++ b/contracts/vp/src/msg.rs @@ -1,6 +1,5 @@ use cosmwasm_std::{Decimal, Uint128, Binary}; -use cw0::Expiration; -use cw20::{Cw20ReceiveMsg, Logo}; +use cw20::{Cw20ReceiveMsg, Logo, Expiration}; use cw20_base::msg::InstantiateMarketingInfo; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/packages/valkyrie/Cargo.toml b/packages/valkyrie/Cargo.toml index 4c714e3..a1df8c5 100644 --- a/packages/valkyrie/Cargo.toml +++ b/packages/valkyrie/Cargo.toml @@ -27,16 +27,14 @@ overflow-checks = true [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -terraswap = "2.4.0" -cosmwasm-std = { version = "0.16.0" } -cosmwasm-storage = { version = "0.16.0", features = ["iterator"] } -cw-storage-plus = { version = "0.8.1", features = ["iterator"] } -cw20 = { version = "0.8.1" } -terra-cosmwasm = { version = "2.2.0" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } +cosmwasm-storage = { version = "1.0.0", features = ["iterator"] } +cw-storage-plus = { version = "0.11.0", features = ["iterator"] } +cw20 = { version = "0.11.0" } thiserror = { version = "1.0.26" } bigint = { version = "4.4.3"} [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } +cosmwasm-schema = { version = "1.0.0" } #cosmwasm-storage = { version = "0.15.2" } \ No newline at end of file diff --git a/packages/valkyrie/src/campaign_manager/execute_msgs.rs b/packages/valkyrie/src/campaign_manager/execute_msgs.rs index b5c36f7..4550eec 100644 --- a/packages/valkyrie/src/campaign_manager/execute_msgs.rs +++ b/packages/valkyrie/src/campaign_manager/execute_msgs.rs @@ -7,7 +7,7 @@ use crate::common::Denom; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct InstantiateMsg { pub governance: String, - pub terraswap_router: String, + pub valkyrie_proxy: String, pub code_id: u64, pub add_pool_fee_rate: Decimal, pub add_pool_min_referral_reward_rate: Decimal, @@ -36,7 +36,7 @@ pub enum ExecuteMsg { governance: Option, valkyrie_token: Option, vp_token: Option, - terraswap_router: Option, + valkyrie_proxy: Option, code_id: Option, add_pool_fee_rate: Option, add_pool_min_referral_reward_rate: Option, diff --git a/packages/valkyrie/src/campaign_manager/query_msgs.rs b/packages/valkyrie/src/campaign_manager/query_msgs.rs index 0944c21..cb2507d 100644 --- a/packages/valkyrie/src/campaign_manager/query_msgs.rs +++ b/packages/valkyrie/src/campaign_manager/query_msgs.rs @@ -28,7 +28,7 @@ pub enum QueryMsg { pub struct ConfigResponse { pub governance: String, pub valkyrie_token: String, - pub terraswap_router: String, + pub valkyrie_proxy: String, pub code_id: u64, pub add_pool_fee_rate: Decimal, pub add_pool_min_referral_reward_rate: Decimal, @@ -47,7 +47,7 @@ impl Default for ConfigResponse { ConfigResponse { governance: governance::GOVERNANCE.to_string(), valkyrie_token: VALKYRIE_TOKEN.to_string(), - terraswap_router: TERRASWAP_ROUTER.to_string(), + valkyrie_proxy: VALKYRIE_PROXY.to_string(), code_id: CAMPAIGN_CODE_ID, add_pool_fee_rate: Decimal::percent(ADD_POOL_FEE_RATE_PERCENT), add_pool_min_referral_reward_rate: Decimal::percent(ADD_POOL_MIN_REFERRAL_REWARD_RATE_PERCENT), diff --git a/packages/valkyrie/src/cw20.rs b/packages/valkyrie/src/cw20.rs index a9e04e4..3e3985f 100644 --- a/packages/valkyrie/src/cw20.rs +++ b/packages/valkyrie/src/cw20.rs @@ -1,5 +1,5 @@ -use cosmwasm_std::{Addr, attr, Attribute, QuerierWrapper, StdResult, Uint128}; -use cw20::{Denom, Cw20QueryMsg}; +use cosmwasm_std::{Addr, attr, Attribute, QuerierWrapper, QueryRequest, StdResult, to_binary, Uint128, WasmQuery}; +use cw20::{Denom, Cw20QueryMsg, TokenInfoResponse}; pub fn query_balance( querier: &QuerierWrapper, @@ -38,3 +38,15 @@ pub fn create_send_attr(recipient: &Addr, amount: Uint128, action: &str) -> Vec< attr("amount", amount.to_string()), ] } + +pub fn query_token_info( + querier: &QuerierWrapper, + contract_addr: String, +) -> StdResult { + let token_info: TokenInfoResponse = querier.query(&QueryRequest::Wasm(WasmQuery::Smart { + contract_addr, + msg: to_binary(&Cw20QueryMsg::TokenInfo {})?, + }))?; + + Ok(token_info) +} \ No newline at end of file diff --git a/packages/valkyrie/src/lib.rs b/packages/valkyrie/src/lib.rs index 7e8204a..021e315 100644 --- a/packages/valkyrie/src/lib.rs +++ b/packages/valkyrie/src/lib.rs @@ -6,9 +6,9 @@ pub mod community; pub mod campaign_manager; pub mod lp_staking; pub mod distributor; +pub mod proxy; pub mod cw20; -pub mod terra; pub mod utils; pub mod pagination; pub mod message_factories; diff --git a/packages/valkyrie/src/mock_querier.rs b/packages/valkyrie/src/mock_querier.rs index 1163b0b..b8f1465 100644 --- a/packages/valkyrie/src/mock_querier.rs +++ b/packages/valkyrie/src/mock_querier.rs @@ -1,17 +1,21 @@ use std::collections::HashMap; +use std::marker::PhantomData; +use serde::{Deserialize, Serialize}; +use schemars::JsonSchema; -use cosmwasm_std::{Api, Binary, CanonicalAddr, Coin, ContractResult, Decimal, from_slice, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, to_binary, Uint128, WasmQuery, from_binary, BankQuery, AllBalanceResponse, Addr}; +use cosmwasm_std::{Api, Binary, CanonicalAddr, Coin, ContractResult, Decimal, from_slice, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError, SystemResult, to_binary, Uint128, WasmQuery, from_binary, BankQuery, AllBalanceResponse, Addr, CustomQuery}; use cosmwasm_std::testing::{MOCK_CONTRACT_ADDR, MockApi, MockQuerier, MockStorage}; use cw20::{TokenInfoResponse, Cw20QueryMsg}; -use terra_cosmwasm::{TerraQueryWrapper}; use crate::governance::query_msgs::{QueryMsg as GovQueryMsg, VotingPowerResponse, ContractConfigResponse as GovContractConfigResponse, StakerStateResponse}; use crate::campaign::query_msgs::{CampaignStateResponse, QueryMsg}; use crate::campaign_manager::query_msgs::{QueryMsg as CampaignManagerQueryMsg, ConfigResponse, ReferralRewardLimitOptionResponse}; +use crate::proxy::execute_msgs::SwapOperation; -use terraswap::router::{QueryMsg as TerraswapRouterQueryMsg, SwapOperation, SimulateSwapOperationsResponse}; +use crate::proxy::query_msgs::SimulateSwapOperationsResponse; +use crate::proxy::query_msgs::QueryMsg::SimulateSwapOperations; use crate::test_constants::campaign_manager::CAMPAIGN_MANAGER; use crate::test_constants::governance::GOVERNANCE; -use crate::test_constants::TERRASWAP_ROUTER; +use crate::test_constants::VALKYRIE_PROXY; pub type CustomDeps = OwnedDeps; @@ -26,19 +30,27 @@ pub fn custom_deps() -> CustomDeps { storage: MockStorage::default(), api: MockApi::default(), querier: custom_querier, + custom_query_type: PhantomData } } pub struct WasmMockQuerier { - base: MockQuerier, + base: MockQuerier, token_querier: TokenQuerier, voting_powers_querier: VotingPowerQuerier, campaign_manager_config_querier: CampaignManagerConfigQuerier, governance_querier: GovConfigQuerier, campaign_state_querier: CampaignStateQuerier, - terraswap_router_querier: TerraswapRouterQuerier, + astroport_router_querier: AstroportRouterQuerier, } +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct QueryWrapper {} + +// implement custom query +impl CustomQuery for QueryWrapper {} + #[derive(Clone, Default)] pub struct VotingPowerQuerier { powers: HashMap, @@ -110,13 +122,13 @@ impl CampaignStateQuerier { } #[derive(Clone, Default)] -pub struct TerraswapRouterQuerier { +pub struct AstroportRouterQuerier { prices: HashMap<(String, String), f64>, } -impl TerraswapRouterQuerier { +impl AstroportRouterQuerier { pub fn new() -> Self { - TerraswapRouterQuerier { + AstroportRouterQuerier { prices: HashMap::new(), } } @@ -154,7 +166,7 @@ pub(crate) fn balances_to_map( impl Querier for WasmMockQuerier { fn raw_query(&self, bin_request: &[u8]) -> QuerierResult { // MockQuerier doesn't support Custom, so we ignore it completely here - let request: QueryRequest = match from_slice(bin_request) { + let request: QueryRequest = match from_slice(bin_request) { Ok(v) => v, Err(_) => { return SystemResult::Err(SystemError::InvalidRequest { @@ -168,7 +180,7 @@ impl Querier for WasmMockQuerier { } impl WasmMockQuerier { - pub fn handle_query(&self, request: &QueryRequest) -> QuerierResult { + pub fn handle_query(&self, request: &QueryRequest) -> QuerierResult { match &request { QueryRequest::Wasm( WasmQuery::Raw { contract_addr, key } @@ -210,7 +222,7 @@ impl WasmMockQuerier { } if result.is_none() { - result = self.handle_wasm_smart_terraswap_router(contract_addr, msg); + result = self.handle_wasm_smart_astroport_router(contract_addr, msg); } if result.is_none() { @@ -310,17 +322,17 @@ impl WasmMockQuerier { } } - fn handle_wasm_smart_terraswap_router(&self, contract_addr: &String, msg: &Binary) -> Option { - if contract_addr != TERRASWAP_ROUTER { + fn handle_wasm_smart_astroport_router(&self, contract_addr: &String, msg: &Binary) -> Option { + if contract_addr != VALKYRIE_PROXY { return None; } match from_binary(msg) { - Ok(TerraswapRouterQueryMsg::SimulateSwapOperations { offer_amount, operations }) => { + Ok(SimulateSwapOperations { offer_amount, operations }) => { let mut amount = offer_amount.u128(); for operation in operations.iter() { - let price = self.terraswap_router_querier.prices - .get(&terraswap_operation_to_string(operation)) + let price = self.astroport_router_querier.prices + .get(&swap_operation_to_string(operation)) .unwrap(); amount = (amount as f64 * *price) as u128; @@ -333,7 +345,7 @@ impl WasmMockQuerier { )))) } Ok(_) => Some(QuerierResult::Err(SystemError::UnsupportedRequest { - kind: "handle_wasm_smart:terraswap_router".to_string(), + kind: "handle_wasm_smart:valkyrie_proxy".to_string(), })), Err(_) => None, } @@ -439,7 +451,7 @@ impl WasmMockQuerier { const ZERO: Uint128 = Uint128::zero(); impl WasmMockQuerier { - pub fn new(base: MockQuerier) -> Self { + pub fn new(base: MockQuerier) -> Self { WasmMockQuerier { base, token_querier: TokenQuerier::default(), @@ -447,7 +459,7 @@ impl WasmMockQuerier { voting_powers_querier: VotingPowerQuerier::default(), governance_querier: GovConfigQuerier::default(), campaign_state_querier: CampaignStateQuerier::default(), - terraswap_router_querier: TerraswapRouterQuerier::default(), + astroport_router_querier: AstroportRouterQuerier::default(), } } @@ -582,8 +594,8 @@ impl WasmMockQuerier { } } - pub fn with_terraswap_price(&mut self, offer: String, ask: String, price: f64) { - self.terraswap_router_querier.prices.insert((offer, ask), price); + pub fn with_astroport_price(&mut self, offer: String, ask: String, price: f64) { + self.astroport_router_querier.prices.insert((offer, ask), price); } } @@ -604,12 +616,9 @@ fn encode_length(namespace: &[u8]) -> [u8; 2] { [length_bytes[2], length_bytes[3]] } -fn terraswap_operation_to_string(operation: &SwapOperation) -> (String, String) { +fn swap_operation_to_string(operation: &SwapOperation) -> (String, String) { match operation { - SwapOperation::NativeSwap { offer_denom, ask_denom } => { - (offer_denom.to_string(), ask_denom.to_string()) - } - SwapOperation::TerraSwap { offer_asset_info, ask_asset_info } => { + SwapOperation::Swap { offer_asset_info, ask_asset_info } => { (offer_asset_info.to_string(), ask_asset_info.to_string()) } } diff --git a/packages/valkyrie/src/proxy/asset.rs b/packages/valkyrie/src/proxy/asset.rs new file mode 100644 index 0000000..fceb854 --- /dev/null +++ b/packages/valkyrie/src/proxy/asset.rs @@ -0,0 +1,81 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::fmt; + +use cosmwasm_std::{to_binary, Addr, Api, BankMsg, CanonicalAddr, Coin, CosmosMsg, MessageInfo, StdError, StdResult, SubMsg, Uint128, WasmMsg, }; +use cw20::Cw20ExecuteMsg; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct Asset { + pub info: AssetInfo, + pub amount: Uint128, +} + +impl fmt::Display for Asset { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}{}", self.amount, self.info) + } +} + +/// AssetInfo contract_addr is usually passed from the cw20 hook +/// so we can trust the contract_addr is properly validated. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum AssetInfo { + Token { contract_addr: String }, + NativeToken { denom: String }, +} + +impl fmt::Display for AssetInfo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AssetInfo::NativeToken { denom } => write!(f, "{}", denom), + AssetInfo::Token { contract_addr } => write!(f, "{}", contract_addr), + } + } +} + +impl AssetInfo { + pub fn check(&self, api: &dyn Api) -> StdResult<()> { + match self { + AssetInfo::Token { contract_addr } => { + addr_validate_to_lower(api, contract_addr.as_str())?; + } + AssetInfo::NativeToken { denom } => { + if !denom.starts_with("ibc/") && denom != &denom.to_lowercase() { + return Err(StdError::generic_err(format!( + "Non-IBC token denom {} should be lowercase", + denom + ))); + } + } + } + Ok(()) + } +} + +// We define a custom struct for each query response +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct PairInfo { + pub asset_infos: [AssetInfo; 2], + pub contract_addr: String, + pub liquidity_token: String, + pub asset_decimals: [u8; 2], +} + +pub fn addr_opt_validate(api: &dyn Api, addr: &Option) -> StdResult> { + addr.as_ref() + .map(|addr| addr_validate_to_lower(api, addr)) + .transpose() +} + +pub fn addr_validate_to_lower(api: &dyn Api, addr: impl Into) -> StdResult { + let addr = addr.into(); + if addr.to_lowercase() != addr { + return Err(StdError::generic_err(format!( + "Address {} should be lowercase", + addr + ))); + } + api.addr_validate(&addr) +} \ No newline at end of file diff --git a/packages/valkyrie/src/proxy/execute_msgs.rs b/packages/valkyrie/src/proxy/execute_msgs.rs new file mode 100644 index 0000000..6a94205 --- /dev/null +++ b/packages/valkyrie/src/proxy/execute_msgs.rs @@ -0,0 +1,101 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use cosmwasm_std::{Decimal, Uint128, Addr}; +use cw20::Cw20ReceiveMsg; + +use crate::proxy::asset::AssetInfo; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct InstantiateMsg { + pub astroport_factory: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum SwapOperation { + Swap { + offer_asset_info: AssetInfo, + ask_asset_info: AssetInfo, + }, +} + +impl SwapOperation { + pub fn get_offer_asset_info(&self) -> AssetInfo { + match self { + SwapOperation::Swap { offer_asset_info, .. } => offer_asset_info.clone(), + } + } + + pub fn get_target_asset_info(&self) -> AssetInfo { + match self { + SwapOperation::Swap { ask_asset_info, .. } => ask_asset_info.clone(), + } + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExecuteMsg { + Receive(Cw20ReceiveMsg), + UpdateConfig { + fixed_dex: Option, + }, + ClearFixedDex {}, + ExecuteSwapOperations { + operations: Vec, + minimum_receive: Option, + to: Option, + max_spread: Option, + }, + ExecuteSwapOperation { + operation: SwapOperation, + to: Option, + max_spread: Option, + }, + AssertMinimumReceive { + asset_info: AssetInfo, + prev_balance: Uint128, + minimum_receive: Uint128, + receiver: String, + }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum DexType { + Astroport, + // Terraswap +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct DexInfo { + pub dex_type: DexType, + pub factory: Addr, +} + +pub fn find_dex_factory(list: Vec, dex_type: DexType) -> Option { + for item in list.iter() { + if item.dex_type == dex_type { + return Some(item.clone()); + } + } + + None +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Cw20HookMsg { + ExecuteSwapOperations { + operations: Vec, + minimum_receive: Option, + to: Option, + max_spread: Option, + }, +} + +/// We currently take no arguments for migrations +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct MigrateMsg {} \ No newline at end of file diff --git a/packages/valkyrie/src/proxy/mod.rs b/packages/valkyrie/src/proxy/mod.rs new file mode 100644 index 0000000..c4b03d5 --- /dev/null +++ b/packages/valkyrie/src/proxy/mod.rs @@ -0,0 +1,3 @@ +pub mod execute_msgs; +pub mod query_msgs; +pub mod asset; \ No newline at end of file diff --git a/packages/valkyrie/src/proxy/query_msgs.rs b/packages/valkyrie/src/proxy/query_msgs.rs new file mode 100644 index 0000000..420a0ce --- /dev/null +++ b/packages/valkyrie/src/proxy/query_msgs.rs @@ -0,0 +1,20 @@ +use cosmwasm_std::{Uint128}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use crate::proxy::execute_msgs::SwapOperation; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum QueryMsg { + Config {}, + SimulateSwapOperations { + offer_amount: Uint128, + operations: Vec, + }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct SimulateSwapOperationsResponse { + pub amount: Uint128, +} \ No newline at end of file diff --git a/packages/valkyrie/src/terra.rs b/packages/valkyrie/src/terra.rs deleted file mode 100644 index 280a0e8..0000000 --- a/packages/valkyrie/src/terra.rs +++ /dev/null @@ -1,9 +0,0 @@ -use cosmwasm_std::{Addr, QuerierWrapper, StdResult}; -use terra_cosmwasm::TerraQuerier; - -pub fn is_contract(querier: &QuerierWrapper, address: &Addr) -> StdResult { - let querier = TerraQuerier::new(querier); - - Ok(querier.query_contract_info(address.to_string()) - .map_or(false, |_| true)) -} diff --git a/packages/valkyrie/src/test_constants.rs b/packages/valkyrie/src/test_constants.rs index c22e68a..c7162ea 100644 --- a/packages/valkyrie/src/test_constants.rs +++ b/packages/valkyrie/src/test_constants.rs @@ -1,11 +1,11 @@ use cosmwasm_std::MessageInfo; use cosmwasm_std::testing::mock_info; -pub const DEFAULT_SENDER: &str = "DefaultSender"; -pub const CONTRACT_CREATOR: &str = "ContractCreator"; -pub const VALKYRIE_TOKEN: &str = "ValkyrieToken"; -pub const VALKYRIE_TICKET_TOKEN: &str = "TicketToken"; -pub const TERRASWAP_ROUTER: &str = "TerraswapRouter"; +pub const DEFAULT_SENDER: &str = "terra1sq9ppsvt4k378wwhvm2vyfg7kqrhtve8p0n3a6"; +pub const CONTRACT_CREATOR: &str = "terra16m3runusa9csfev7ymj62e8lnswu8um29k5zky"; +pub const VALKYRIE_TOKEN: &str = "terra1xj49zyqrwpv5k928jwfpfy2ha668nwdgkwlrg3"; +pub const VALKYRIE_TICKET_TOKEN: &str = "terra1fh27l8h4s0tfx9ykqxq5efq4xx88f06x6clwmr"; +pub const VALKYRIE_PROXY: &str = "terra1fnywlw4edny3vw44x04xd67uzkdqluymgreu7g"; pub fn default_sender() -> MessageInfo { mock_info(DEFAULT_SENDER, &[]) @@ -27,7 +27,7 @@ pub mod governance { use crate::test_constants::VALKYRIE_TICKET_TOKEN; use crate::test_utils::{mock_env_contract, mock_env_contract_height}; - pub const GOVERNANCE: &str = "Governance"; + pub const GOVERNANCE: &str = "terra16t7dpwwgx9n3lq6l6te3753lsjqwhxwpday9zx"; // common config pub const GOVERNANCE_TOKEN: &str = VALKYRIE_TOKEN; @@ -65,11 +65,13 @@ pub mod community { use crate::test_constants::VALKYRIE_TOKEN; use crate::test_utils::mock_env_contract; - pub const COMMUNITY: &str = "Community"; + pub const COMMUNITY: &str = "terra1f68wt2ch3cx2g62dxtc8v68mkdh5wchdgdjwz7"; pub const MANAGING_TOKEN: &str = VALKYRIE_TOKEN; pub const ADMIN: &str = GOVERNANCE; - pub const ALLOWED_ADDRESS: &str = "AllowedAddress"; + + pub const ADMIN1: &str = "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f"; + pub const ALLOWED_ADDRESS: &str = "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f"; // pub const ALLOWED_AMOUNT: Uint128 = Uint128::new(1000); pub fn community_env() -> Env { @@ -89,7 +91,11 @@ pub mod distributor { use crate::test_constants::VALKYRIE_TOKEN; use crate::test_utils::mock_env_contract; - pub const DISTRIBUTOR: &str = "Distributor"; + pub const DISTRIBUTOR: &str = "terra14lpnyzc9z4g3ugr4lhm8s4nle0tq8vcltkhzh7"; + + pub const RECIPIENT: &str = "terra1333veey879eeqcff8j3gfcgwt8cfrg9mq20v6f"; + pub const RECIPIENT2: &str = "terra17q4lzg70un58uefr2fwu7uxtgvftspr7d0a6p3"; + pub const ADMIN1: &str = "terra1fmcjjt6yc9wqup2r06urnrd928jhrde6gcld6n"; pub const MANAGING_TOKEN: &str = VALKYRIE_TOKEN; pub const ADMIN: &str = GOVERNANCE; @@ -110,7 +116,7 @@ pub mod campaign_manager { use crate::test_utils::mock_env_contract; use crate::test_constants::governance::GOVERNANCE; - pub const CAMPAIGN_MANAGER: &str = "CampaignManager"; + pub const CAMPAIGN_MANAGER: &str = "terra12u7hcmpltazmmnq0fvyl225usn3fy6qqlp05w0"; pub const CAMPAIGN_CODE_ID: u64 = 1; pub const ADD_POOL_FEE_RATE_PERCENT: u64 = 0; @@ -138,12 +144,12 @@ pub mod campaign { use crate::test_utils::{mock_env_contract, mock_env_contract_height}; - pub const CAMPAIGN: &str = "Campaign"; + pub const CAMPAIGN: &str = "terra1zgrx9jjqrfye8swykfgmd6hpde60j0nszzupp9"; pub const CAMPAIGN_TITLE: &str = "CampaignTitle"; pub const CAMPAIGN_DESCRIPTION: &str = "CamapignDescription"; pub const CAMPAIGN_URL: &str = "https://campaign.url"; pub const CAMPAIGN_PARAMETER_KEY: &str = "vkr"; - pub const CAMPAIGN_ADMIN: &str = "CampaignAdmin"; + pub const CAMPAIGN_ADMIN: &str = "terra1h8ljdmae7lx05kjj79c9ekscwsyjd3yr8wyvdn"; pub const PARTICIPATION_REWARD_DENOM_NATIVE: &str = "uluna"; pub const PARTICIPATION_REWARD_AMOUNT: Uint128 = Uint128::new(3000); @@ -153,12 +159,20 @@ pub mod campaign { pub const REFERRAL_REWARD_AMOUNTS: [Uint128; 3] = [Uint128::new(400), Uint128::new(300), Uint128::new(200)]; pub const REFERRAL_REWARD_LOCK_PERIOD: u64 = 100; - pub const QUALIFIER: &str = "Qualifier"; + pub const QUALIFIER: &str = "terra1rlusvz7h678g35dr5a3nzmzd2kzwh2evjpfuq8"; + pub const QUALIFIER2: &str = "terra190fxpjfkp6cygr2k9unzjurq42dyehqd579h5j"; + pub const ADMIN2: &str = "terra190fxpjfkp6cygr2k9unzjurq42dyehqd579h5j"; pub const DEPOSIT_DENOM_NATIVE: &str = "uluna"; pub const DEPOSIT_AMOUNT: Uint128 = Uint128::new(100); pub const DEPOSIT_LOCK_PERIOD: u64 = 10000; pub const VP_BURN_AMOUNT: Uint128 = Uint128::new(0); + pub const REFERRER: &str = "terra1dpe2aqykm2vnakcz4vgpha0agxnlkjvgfahhk7"; + pub const INVALID_REFERRER: &str = "terra174gu7kg8ekk5gsxdma5jlfcedm653tyg6ayppw"; + pub const PARTICIPATOR1: &str = "terra1hk7fturdl9fnvrn566dxer6ds7v4jklp2wqmp7"; + pub const PARTICIPATOR2: &str = "terra1tvld5k6pus2yh7pcu7xuwyjedn7mjxfkkkjjap"; + pub const RECIPIENT: &str = "terra1f68wt2ch3cx2g62dxtc8v68mkdh5wchdgdjwz7"; + pub fn campaign_env() -> Env { mock_env_contract(CAMPAIGN) } @@ -181,13 +195,13 @@ pub mod liquidity { use crate::test_constants::VALKYRIE_TOKEN; use crate::test_utils::{mock_env_contract, mock_env_contract_height}; - pub const LIQUIDITY: &str = "Liquidity"; + pub const LIQUIDITY: &str = "terra1l7xu2rl3c7qmtx3r5sd2tz25glf6jh8ul7aag7"; pub const LP_REWARD_TOKEN: &str = VALKYRIE_TOKEN; - pub const LP_PAIR_TOKEN: &str = "ValkyrieLpPair"; - pub const LP_LIQUIDITY_TOKEN: &str = "ValkyrieLpToken"; - pub const LP_WHITELISTED1: &str = "ValkyrieLpWhitelist1"; - pub const LP_WHITELISTED2: &str = "ValkyrieLpWhitelist2"; + pub const LP_PAIR_TOKEN: &str = "terra17n5sunn88hpy965mzvt3079fqx3rttnplg779g"; + pub const LP_LIQUIDITY_TOKEN: &str = "terra1627ldjvxatt54ydd3ns6xaxtd68a2vtyu7kakj"; + pub const LP_WHITELISTED1: &str = "terra190fxpjfkp6cygr2k9unzjurq42dyehqd579h5j"; + pub const LP_WHITELISTED2: &str = "terra1c7m6j8ya58a2fkkptn8fgudx8sqjqvc8azq0ex"; pub const LP_DISTRIBUTION_SCHEDULE1: (u64, u64, Uint128) = (0, 100, Uint128::new(1000000u128)); pub const LP_DISTRIBUTION_SCHEDULE2: (u64, u64, Uint128) = (100, 200, Uint128::new(10000000u128)); @@ -200,4 +214,31 @@ pub mod liquidity { pub fn governance_env_height(height: u64) -> Env { mock_env_contract_height(LIQUIDITY, height) } +} + +pub mod proxy { + use cosmwasm_std::{Env, MessageInfo, Uint128}; + use cosmwasm_std::testing::mock_info; + + use crate::test_constants::VALKYRIE_TOKEN; + use crate::test_constants::VALKYRIE_TICKET_TOKEN; + use crate::test_utils::{mock_env_contract, mock_env_contract_height}; + pub const PROXY: &str = "terra190fxpjfkp6cygr2k9unzjurq42dyehqd579h5j"; + pub const ASTRO_FACTORY: &str = "terra16t7dpwwgx9n3lq6l6te3753lsjqwhxwpday9zx"; + pub const ADMIN: &str = "terra1hk7fturdl9fnvrn566dxer6ds7v4jklp2wqmp7"; + pub const ADMIN2: &str = "terra1c7m6j8ya58a2fkkptn8fgudx8sqjqvc8azq0ex"; + + pub fn proxy_env() -> Env { + mock_env_contract(PROXY) + } + + pub fn proxy_env_height(height: u64) -> Env { + mock_env_contract_height(PROXY, height) + } + + pub fn proxy_sender(sender:&str) -> MessageInfo { + mock_info(sender, &[]) + } + + } \ No newline at end of file diff --git a/packages/valkyrie/src/tests.rs b/packages/valkyrie/src/tests.rs index 9eab2fc..10d28e9 100644 --- a/packages/valkyrie/src/tests.rs +++ b/packages/valkyrie/src/tests.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{Addr, Uint128}; +use cosmwasm_std::{Addr, StdError, Uint128}; use cosmwasm_std::testing::MOCK_CONTRACT_ADDR; use crate::mock_querier::custom_deps; @@ -30,4 +30,22 @@ fn compress_address() { assert_eq!(compressed_address.len(), 32); assert_eq!(address, decompressed_address); +} + +#[test] +fn compress_contract_address() { + let address = "terra1466nf3zuxpya8q9emxukd7vftaf6h4psr0a07srl5zw74zh84yjqxl5qul"; + let compressed_address = super::utils::compress_addr(&address.to_string()).unwrap(); + let decompressed_address = super::utils::decompress_addr(&compressed_address).unwrap(); + + assert_eq!(compressed_address.len(), 76); + assert_eq!(address, decompressed_address); +} + +#[test] +fn invalid_compressed_address() { + let compressed_address = "awgeilwuhfelwiefj"; + let decompressed_address = super::utils::decompress_addr(&compressed_address).unwrap_err(); + + assert_eq!(decompressed_address, StdError::generic_err("Invalid compressed addr.")); } \ No newline at end of file diff --git a/packages/valkyrie/src/utils.rs b/packages/valkyrie/src/utils.rs index 9c3e20f..906e1d8 100644 --- a/packages/valkyrie/src/utils.rs +++ b/packages/valkyrie/src/utils.rs @@ -1,5 +1,5 @@ -use cosmwasm_std::{Uint128, Decimal, Binary, Response, StdResult, StdError}; -use bigint::U256; +use cosmwasm_std::{Uint128, Decimal, Binary, Response, StdResult, StdError, Addr}; +use bigint::{U256, U512}; use std::num::ParseIntError; pub fn make_response(action: &str) -> Response { @@ -39,7 +39,12 @@ pub fn to_ratio_uint128(values: &Vec) -> Vec { } pub fn parse_uint128(value: &str) -> Result { - value.parse::().map(|v| Uint128::from(v)) + let r = value.parse::().map(|v| Uint128::from(v)); + return if r.is_ok() { + Ok(r.unwrap()) + } else { + Err(r.unwrap_err() as ParseIntError) + } } pub fn find_mut_or_push bool, N: Fn() -> T, F: Fn(&mut T)>( @@ -144,35 +149,80 @@ pub fn put_query_parameter(url: &str, key: &str, value: &str) -> String { const TERRA_ADDRESS_HRP: &str = "terra1"; const TERRA_ADDRESS_HRP_LENGTH: usize = 6; const TERRA_ADDRESS_LENGTH: usize = 44; +const TERRA_CONTRACT_ADDRESS_LENGTH: usize = 64; +const COMPRESSED_TERRA_ADDRESS_LENGTH: usize = 32; +const COMPRESSED_TERRA_CONTRACT_ADDRESS_LENGTH: usize = 76; const BECH32_CHARSET: &str = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + +pub fn is_contract(address: &Addr) -> bool { + address.to_string().len() > TERRA_ADDRESS_LENGTH +} + pub fn compress_addr(address: &str) -> StdResult { - let mut result = U256::zero(); - for c in address[TERRA_ADDRESS_HRP_LENGTH..].chars() { - let index = BECH32_CHARSET.find(c) - .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))?; - result = (result << 5) | U256::from(index); - } + if address.len() == TERRA_ADDRESS_LENGTH { + let mut result = U256::zero(); + for c in address[TERRA_ADDRESS_HRP_LENGTH..].chars() { + let index = BECH32_CHARSET.find(c) + .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))?; + result = (result << 5) | U256::from(index); + } - let mut bytes = [0u8; 32]; - result.to_big_endian(&mut bytes); + let mut bytes = [0u8; 32]; + result.to_big_endian(&mut bytes); + Ok(Binary::from(&bytes[8..]).to_base64()) + } else { + let mut result = U512::zero(); + for c in address[TERRA_ADDRESS_HRP_LENGTH..].chars() { + let index = BECH32_CHARSET.find(c) + .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))?; + result = (result << 5) | U512::from(index); + } + + let mut bytes = [0u8; 64]; + result.to_big_endian(&mut bytes); + Ok(Binary::from(&bytes[8..]).to_base64()) + } - Ok(Binary::from(&bytes[8..]).to_base64()) } pub fn decompress_addr(text: &str) -> StdResult { - let decoded = Binary::from_base64(text).unwrap(); - let mut bytes = [0u8; 32]; - bytes[8..].clone_from_slice(decoded.as_slice()); + let is_contract = if text.len() == COMPRESSED_TERRA_ADDRESS_LENGTH { + false + } else if text.len() == COMPRESSED_TERRA_CONTRACT_ADDRESS_LENGTH { + true + } else { + return Err(StdError::generic_err("Invalid compressed addr.")); + }; - let mut data = U256::from_big_endian(&bytes); + + let decoded = Binary::from_base64(text).unwrap(); let mut result = String::new(); + if !is_contract { + let mut bytes = [0u8; 32]; + bytes[8..].clone_from_slice(decoded.as_slice()); + + let mut data = U256::from_big_endian(&bytes); + + for _ in TERRA_ADDRESS_HRP_LENGTH..TERRA_ADDRESS_LENGTH { + let index = (data & U256::from(0x1F)).as_u32() as usize; + result = BECH32_CHARSET.chars().nth(index) + .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))? + .to_string() + &result; + data = data >> 5; + } + } else { + let mut bytes = [0u8; 64]; + bytes[8..].clone_from_slice(decoded.as_slice()); - for _ in TERRA_ADDRESS_HRP_LENGTH..TERRA_ADDRESS_LENGTH { - let index = (data & U256::from(0x1F)).as_u32() as usize; - result = BECH32_CHARSET.chars().nth(index) - .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))? - .to_string() + &result; - data = data >> 5; + let mut data = U512::from_big_endian(&bytes); + + for _ in TERRA_ADDRESS_HRP_LENGTH..TERRA_CONTRACT_ADDRESS_LENGTH { + let index = (data & U512::from(0x1F)).as_u32() as usize; + result = BECH32_CHARSET.chars().nth(index) + .ok_or(StdError::generic_err("Does not contain BECH32_CHARSET"))? + .to_string() + &result; + data = data >> 5; + } } Ok(TERRA_ADDRESS_HRP.to_string() + &result) diff --git a/packages/valkyrie_qualifier/Cargo.toml b/packages/valkyrie_qualifier/Cargo.toml index d13473b..2683b40 100644 --- a/packages/valkyrie_qualifier/Cargo.toml +++ b/packages/valkyrie_qualifier/Cargo.toml @@ -27,8 +27,8 @@ overflow-checks = true [dependencies] serde = { version = "1.0.126", default-features = false, features = ["derive"] } -schemars = { version = "0.8.3" } -cosmwasm-std = { version = "0.16.0" } +schemars = { version = "0.8.10" } +cosmwasm-std = { version = "1.0.0" } [dev-dependencies] -cosmwasm-schema = { version = "0.16.0" } \ No newline at end of file +cosmwasm-schema = { version = "1.0.0" } \ No newline at end of file From 47f833c91b5f90aecd796d65502a8dad2bb22272 Mon Sep 17 00:00:00 2001 From: FelixKim Date: Wed, 15 Jun 2022 16:13:38 +0900 Subject: [PATCH 3/7] fixed messages --- contracts/proxy/examples/schema.rs | 1 - contracts/proxy/src/astroport/executions.rs | 8 ++-- contracts/proxy/src/astroport/msgs.rs | 25 +++++------ contracts/proxy/src/astroport/queries.rs | 12 ++--- contracts/proxy/src/executions.rs | 16 +++---- contracts/proxy/src/queries.rs | 5 +-- packages/valkyrie/src/proxy/asset.rs | 49 +-------------------- packages/valkyrie/src/test_constants.rs | 4 +- 8 files changed, 30 insertions(+), 90 deletions(-) diff --git a/contracts/proxy/examples/schema.rs b/contracts/proxy/examples/schema.rs index 5a62e9e..a4fcb3c 100644 --- a/contracts/proxy/examples/schema.rs +++ b/contracts/proxy/examples/schema.rs @@ -15,7 +15,6 @@ fn main() { export_schema(&schema_for!(Asset), &out_dir); export_schema(&schema_for!(AssetInfo), &out_dir); - export_schema(&schema_for!(PairInfo), &out_dir); export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(SwapOperation), &out_dir); diff --git a/contracts/proxy/src/astroport/executions.rs b/contracts/proxy/src/astroport/executions.rs index 9b14abd..2c89e91 100644 --- a/contracts/proxy/src/astroport/executions.rs +++ b/contracts/proxy/src/astroport/executions.rs @@ -5,7 +5,7 @@ use valkyrie::proxy::execute_msgs::{SwapOperation}; use valkyrie::cw20::query_balance; use valkyrie::errors::ContractError; use valkyrie::proxy::asset::{Asset, AssetInfo}; -use crate::astroport::msgs::PairExecuteMsg; +use crate::astroport::msgs::AstroportPairExecuteMsg; use crate::astroport::queries::{query_pair_info}; @@ -18,7 +18,6 @@ pub fn execute_swap_operation( to: Option, max_spread: Option, ) -> Result { - let message = match operation { SwapOperation::Swap { offer_asset_info, @@ -38,6 +37,7 @@ pub fn execute_swap_operation( query_balance(&deps.querier, Denom::Cw20(deps.api.addr_validate(contract_addr.as_str())?), env.contract.address)? } }; + let offer_asset = Asset { info: offer_asset_info, amount, @@ -68,7 +68,7 @@ fn asset_into_swap_msg( denom, amount: offer_asset.amount, }], - msg: to_binary(&PairExecuteMsg::Swap { + msg: to_binary(&AstroportPairExecuteMsg::Swap { offer_asset, belief_price: None, max_spread, @@ -81,7 +81,7 @@ fn asset_into_swap_msg( msg: to_binary(&Cw20ExecuteMsg::Send { contract: pair_contract, amount: offer_asset.amount, - msg: to_binary(&PairExecuteMsg::Swap { + msg: to_binary(&AstroportPairExecuteMsg::Swap { offer_asset, belief_price: None, max_spread, diff --git a/contracts/proxy/src/astroport/msgs.rs b/contracts/proxy/src/astroport/msgs.rs index b5e79c3..d47e44e 100644 --- a/contracts/proxy/src/astroport/msgs.rs +++ b/contracts/proxy/src/astroport/msgs.rs @@ -5,20 +5,15 @@ use valkyrie::proxy::asset::{Asset, AssetInfo}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] -pub enum FactoryQueryMsg { - Config {}, +pub enum AstroportFactoryQueryMsg { Pair { asset_infos: [AssetInfo; 2], }, - Pairs { - start_after: Option<[AssetInfo; 2]>, - limit: Option, - }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] -pub enum PairExecuteMsg { +pub enum AstroportPairExecuteMsg { Swap { offer_asset: Asset, belief_price: Option, @@ -29,23 +24,23 @@ pub enum PairExecuteMsg { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] -pub enum PairQueryMsg { +pub enum AstroportPairQueryMsg { Pair {}, - Pool {}, Simulation { offer_asset: Asset }, - ReverseSimulation { ask_asset: Asset }, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct SimulationResponse { +#[serde(rename_all = "snake_case")] +pub struct AstroportSimulationResponse { pub return_amount: Uint128, pub spread_amount: Uint128, pub commission_amount: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct ReverseSimulationResponse { - pub offer_amount: Uint128, - pub spread_amount: Uint128, - pub commission_amount: Uint128, +#[serde(rename_all = "snake_case")] +pub struct AstroportPairInfo { + pub asset_infos: [AssetInfo; 2], + pub contract_addr: String, + pub liquidity_token: String, } \ No newline at end of file diff --git a/contracts/proxy/src/astroport/queries.rs b/contracts/proxy/src/astroport/queries.rs index 56d94e5..e087179 100644 --- a/contracts/proxy/src/astroport/queries.rs +++ b/contracts/proxy/src/astroport/queries.rs @@ -2,8 +2,8 @@ use cosmwasm_std::{Addr, Deps, StdError, StdResult, Uint128}; use cw20::{Denom}; use valkyrie::cw20::query_balance; -use valkyrie::proxy::asset::{Asset, AssetInfo, PairInfo}; -use crate::astroport::msgs::{FactoryQueryMsg, PairQueryMsg, SimulationResponse}; +use valkyrie::proxy::asset::{Asset, AssetInfo}; +use crate::astroport::msgs::{AstroportPairInfo, AstroportSimulationResponse, AstroportFactoryQueryMsg, AstroportPairQueryMsg}; pub fn simulate_swap_operation( deps: Deps, @@ -18,9 +18,9 @@ pub fn simulate_swap_operation( &[offer_asset_info.clone(), ask_asset_info.clone()], )?; - let res: SimulationResponse = deps.querier.query_wasm_smart( + let res: AstroportSimulationResponse = deps.querier.query_wasm_smart( pair_info.contract_addr, - &PairQueryMsg::Simulation { + &AstroportPairQueryMsg::Simulation { offer_asset: Asset { info: offer_asset_info.clone(), amount: offer_amount, @@ -37,10 +37,10 @@ pub fn query_pair_info( deps: Deps, factory_contract: &Addr, asset_infos: &[AssetInfo; 2], -) -> StdResult { +) -> StdResult { deps.querier.query_wasm_smart( factory_contract.to_string(), - &FactoryQueryMsg::Pair { + &AstroportFactoryQueryMsg::Pair { asset_infos: asset_infos.clone(), }, ) diff --git a/contracts/proxy/src/executions.rs b/contracts/proxy/src/executions.rs index cf86f00..1ce90d9 100644 --- a/contracts/proxy/src/executions.rs +++ b/contracts/proxy/src/executions.rs @@ -1,10 +1,10 @@ use std::collections::{HashSet}; -use cosmwasm_std::{Addr, Api, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, to_binary, Uint128, WasmMsg}; +use cosmwasm_std::{Addr, CosmosMsg, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, to_binary, Uint128, WasmMsg}; use valkyrie::proxy::execute_msgs::{DexInfo, DexType, ExecuteMsg, SwapOperation}; use valkyrie::common::{ContractResult}; use valkyrie::errors::ContractError; -use valkyrie::proxy::asset::{addr_opt_validate, AssetInfo}; +use valkyrie::proxy::asset::{AssetInfo}; use valkyrie::proxy::execute_msgs::InstantiateMsg; use valkyrie::utils::{make_response}; @@ -96,9 +96,10 @@ pub fn execute_swap_operations( } // Assert the operations are properly set - assert_operations(deps.api, &operations)?; + assert_operations(&operations)?; - let to = addr_opt_validate(deps.api, &to)?.unwrap_or(sender); + + let to = to.unwrap_or(sender.to_string()); let target_asset_info = operations.last().unwrap().get_target_asset_info(); let mut messages = operations @@ -123,7 +124,7 @@ pub fn execute_swap_operations( // Execute minimum amount assertion if let Some(minimum_receive) = minimum_receive { - let receiver_balance = query_pool(deps.as_ref(), target_asset_info.clone(), to.clone())?; + let receiver_balance = query_pool(deps.as_ref(), target_asset_info.clone(), deps.api.addr_validate(to.as_str())?)?; messages.push(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), funds: vec![], @@ -139,7 +140,7 @@ pub fn execute_swap_operations( Ok(Response::new().add_messages(messages)) } -fn assert_operations(api: &dyn Api, operations: &[SwapOperation]) -> StdResult<()> { +fn assert_operations(operations: &[SwapOperation]) -> StdResult<()> { let mut ask_asset_map: HashSet = HashSet::new(); for operation in operations { let (offer_asset, ask_asset) = match operation { @@ -148,8 +149,6 @@ fn assert_operations(api: &dyn Api, operations: &[SwapOperation]) -> StdResult<( ask_asset_info, } => (offer_asset_info.clone(), ask_asset_info.clone()), }; - offer_asset.check(api)?; - ask_asset.check(api)?; ask_asset_map.remove(&offer_asset.to_string()); ask_asset_map.insert(ask_asset.to_string()); @@ -198,7 +197,6 @@ pub fn assert_minimum_receive( minimum_receive: Uint128, receiver: Addr, ) -> ContractResult { - asset_info.check(deps.api)?; let receiver_balance = query_pool(deps, asset_info, receiver)?; let swap_amount = receiver_balance.checked_sub(prev_balance)?; diff --git a/contracts/proxy/src/queries.rs b/contracts/proxy/src/queries.rs index 1d97996..f1254d4 100644 --- a/contracts/proxy/src/queries.rs +++ b/contracts/proxy/src/queries.rs @@ -31,7 +31,7 @@ pub fn simulate_swap_operations( return Err(ContractError::Std(StdError::generic_err("swap limit exceed"))); } - assert_operations(deps, &operations)?; + assert_operations(&operations)?; let mut offer_amount = offer_amount; for operation in operations.into_iter() { @@ -111,7 +111,6 @@ pub fn query_pool( } fn assert_operations( - deps:Deps, operations: &[SwapOperation] ) -> Result<(), StdError> { let mut ask_asset_map: HashSet = HashSet::new(); @@ -125,8 +124,6 @@ fn assert_operations( ask_asset_info, ), }; - offer_asset.check(deps.api)?; - ask_asset.check(deps.api)?; ask_asset_map.remove(&offer_asset.to_string()); ask_asset_map.insert(ask_asset.to_string()); diff --git a/packages/valkyrie/src/proxy/asset.rs b/packages/valkyrie/src/proxy/asset.rs index fceb854..8d2185d 100644 --- a/packages/valkyrie/src/proxy/asset.rs +++ b/packages/valkyrie/src/proxy/asset.rs @@ -1,9 +1,7 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; - -use cosmwasm_std::{to_binary, Addr, Api, BankMsg, CanonicalAddr, Coin, CosmosMsg, MessageInfo, StdError, StdResult, SubMsg, Uint128, WasmMsg, }; -use cw20::Cw20ExecuteMsg; +use cosmwasm_std::{Uint128}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Asset { @@ -33,49 +31,4 @@ impl fmt::Display for AssetInfo { AssetInfo::Token { contract_addr } => write!(f, "{}", contract_addr), } } -} - -impl AssetInfo { - pub fn check(&self, api: &dyn Api) -> StdResult<()> { - match self { - AssetInfo::Token { contract_addr } => { - addr_validate_to_lower(api, contract_addr.as_str())?; - } - AssetInfo::NativeToken { denom } => { - if !denom.starts_with("ibc/") && denom != &denom.to_lowercase() { - return Err(StdError::generic_err(format!( - "Non-IBC token denom {} should be lowercase", - denom - ))); - } - } - } - Ok(()) - } -} - -// We define a custom struct for each query response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct PairInfo { - pub asset_infos: [AssetInfo; 2], - pub contract_addr: String, - pub liquidity_token: String, - pub asset_decimals: [u8; 2], -} - -pub fn addr_opt_validate(api: &dyn Api, addr: &Option) -> StdResult> { - addr.as_ref() - .map(|addr| addr_validate_to_lower(api, addr)) - .transpose() -} - -pub fn addr_validate_to_lower(api: &dyn Api, addr: impl Into) -> StdResult { - let addr = addr.into(); - if addr.to_lowercase() != addr { - return Err(StdError::generic_err(format!( - "Address {} should be lowercase", - addr - ))); - } - api.addr_validate(&addr) } \ No newline at end of file diff --git a/packages/valkyrie/src/test_constants.rs b/packages/valkyrie/src/test_constants.rs index c7162ea..7b50457 100644 --- a/packages/valkyrie/src/test_constants.rs +++ b/packages/valkyrie/src/test_constants.rs @@ -217,11 +217,9 @@ pub mod liquidity { } pub mod proxy { - use cosmwasm_std::{Env, MessageInfo, Uint128}; + use cosmwasm_std::{Env, MessageInfo}; use cosmwasm_std::testing::mock_info; - use crate::test_constants::VALKYRIE_TOKEN; - use crate::test_constants::VALKYRIE_TICKET_TOKEN; use crate::test_utils::{mock_env_contract, mock_env_contract_height}; pub const PROXY: &str = "terra190fxpjfkp6cygr2k9unzjurq42dyehqd579h5j"; pub const ASTRO_FACTORY: &str = "terra16t7dpwwgx9n3lq6l6te3753lsjqwhxwpday9zx"; From e9a427849e705ccda48f55eb9a432c807aff90fc Mon Sep 17 00:00:00 2001 From: FelixKim Date: Wed, 15 Jun 2022 16:15:19 +0900 Subject: [PATCH 4/7] fixed json schema --- contracts/proxy/schema/pair_info.json | 84 --------------------------- 1 file changed, 84 deletions(-) delete mode 100644 contracts/proxy/schema/pair_info.json diff --git a/contracts/proxy/schema/pair_info.json b/contracts/proxy/schema/pair_info.json deleted file mode 100644 index 527a238..0000000 --- a/contracts/proxy/schema/pair_info.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "title": "PairInfo", - "type": "object", - "required": [ - "asset_decimals", - "asset_infos", - "contract_addr", - "liquidity_token" - ], - "properties": { - "asset_decimals": { - "type": "array", - "items": { - "type": "integer", - "format": "uint8", - "minimum": 0.0 - }, - "maxItems": 2, - "minItems": 2 - }, - "asset_infos": { - "type": "array", - "items": { - "$ref": "#/definitions/AssetInfo" - }, - "maxItems": 2, - "minItems": 2 - }, - "contract_addr": { - "type": "string" - }, - "liquidity_token": { - "type": "string" - } - }, - "definitions": { - "AssetInfo": { - "description": "AssetInfo contract_addr is usually passed from the cw20 hook so we can trust the contract_addr is properly validated.", - "oneOf": [ - { - "type": "object", - "required": [ - "token" - ], - "properties": { - "token": { - "type": "object", - "required": [ - "contract_addr" - ], - "properties": { - "contract_addr": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "native_token" - ], - "properties": { - "native_token": { - "type": "object", - "required": [ - "denom" - ], - "properties": { - "denom": { - "type": "string" - } - } - } - }, - "additionalProperties": false - } - ] - } - } -} From b11e4ec4da51d62b6ee61de03c2e329bdea8adb5 Mon Sep 17 00:00:00 2001 From: FelixKim Date: Fri, 17 Jun 2022 19:48:03 +0900 Subject: [PATCH 5/7] reply message fix. --- contracts/campaign/proto/core_response.proto | 2 +- contracts/campaign/src/proto/core_response.rs | 46 +++++++++---------- contracts/campaign_manager/src/executions.rs | 4 +- packages/valkyrie/src/message_factories.rs | 2 +- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/contracts/campaign/proto/core_response.proto b/contracts/campaign/proto/core_response.proto index 4486031..e88a4b1 100644 --- a/contracts/campaign/proto/core_response.proto +++ b/contracts/campaign/proto/core_response.proto @@ -3,7 +3,7 @@ syntax = "proto3"; // MsgInstantiateContractResponse defines the Msg/InstantiateContract response type. message MsgInstantiateContractResponse { // ContractAddress is the bech32 address of the new contract instance. - string contract_address = 1; + string address = 1; // Data contains base64-encoded bytes to returned from the contract bytes data = 2; } diff --git a/contracts/campaign/src/proto/core_response.rs b/contracts/campaign/src/proto/core_response.rs index fc26a2c..373b81d 100644 --- a/contracts/campaign/src/proto/core_response.rs +++ b/contracts/campaign/src/proto/core_response.rs @@ -26,7 +26,7 @@ #[derive(PartialEq,Clone,Default)] pub struct MsgInstantiateContractResponse { // message fields - pub contract_address: ::std::string::String, + pub address: ::std::string::String, pub data: ::std::vec::Vec, // special fields pub unknown_fields: ::protobuf::UnknownFields, @@ -44,30 +44,30 @@ impl MsgInstantiateContractResponse { ::std::default::Default::default() } - // string contract_address = 1; + // string address = 1; - pub fn get_contract_address(&self) -> &str { - &self.contract_address + pub fn get_address(&self) -> &str { + &self.address } - pub fn clear_contract_address(&mut self) { - self.contract_address.clear(); + pub fn clear_address(&mut self) { + self.address.clear(); } // Param is passed by value, moved - pub fn set_contract_address(&mut self, v: ::std::string::String) { - self.contract_address = v; + pub fn set_address(&mut self, v: ::std::string::String) { + self.address = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. - pub fn mut_contract_address(&mut self) -> &mut ::std::string::String { - &mut self.contract_address + pub fn mut_address(&mut self) -> &mut ::std::string::String { + &mut self.address } // Take field - pub fn take_contract_address(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.contract_address, ::std::string::String::new()) + pub fn take_address(&mut self) -> ::std::string::String { + ::std::mem::replace(&mut self.address, ::std::string::String::new()) } // bytes data = 2; @@ -107,7 +107,7 @@ impl ::protobuf::Message for MsgInstantiateContractResponse { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { - ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.contract_address)?; + ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.address)?; }, 2 => { ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.data)?; @@ -124,8 +124,8 @@ impl ::protobuf::Message for MsgInstantiateContractResponse { #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; - if !self.contract_address.is_empty() { - my_size += ::protobuf::rt::string_size(1, &self.contract_address); + if !self.address.is_empty() { + my_size += ::protobuf::rt::string_size(1, &self.address); } if !self.data.is_empty() { my_size += ::protobuf::rt::bytes_size(2, &self.data); @@ -136,8 +136,8 @@ impl ::protobuf::Message for MsgInstantiateContractResponse { } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { - if !self.contract_address.is_empty() { - os.write_string(1, &self.contract_address)?; + if !self.address.is_empty() { + os.write_string(1, &self.address)?; } if !self.data.is_empty() { os.write_bytes(2, &self.data)?; @@ -181,9 +181,9 @@ impl ::protobuf::Message for MsgInstantiateContractResponse { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( - "contract_address", - |m: &MsgInstantiateContractResponse| { &m.contract_address }, - |m: &mut MsgInstantiateContractResponse| { &mut m.contract_address }, + "address", + |m: &MsgInstantiateContractResponse| { &m.address }, + |m: &mut MsgInstantiateContractResponse| { &mut m.address }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "data", @@ -206,7 +206,7 @@ impl ::protobuf::Message for MsgInstantiateContractResponse { impl ::protobuf::Clear for MsgInstantiateContractResponse { fn clear(&mut self) { - self.contract_address.clear(); + self.address.clear(); self.data.clear(); self.unknown_fields.clear(); } @@ -385,13 +385,13 @@ impl ::protobuf::reflect::ProtobufValue for MsgExecuteContractResponse { static file_descriptor_proto_data: &'static [u8] = b"\ \n\x13core_response.proto\"_\n\x1eMsgInstantiateContractResponse\x12)\n\ - \x10contract_address\x18\x01\x20\x01(\tR\x0fcontractAddress\x12\x12\n\ + \x7address\x18\x01\x20\x01(\tR\x07address\x12\x12\n\ \x04data\x18\x02\x20\x01(\x0cR\x04data\"0\n\x1aMsgExecuteContractRespons\ e\x12\x12\n\x04data\x18\x01\x20\x01(\x0cR\x04dataJ\xd8\x04\n\x06\x12\x04\ \0\0\x0e\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n_\n\x02\x04\0\x12\x04\x03\ \0\x08\x01\x1aS\x20MsgInstantiateContractResponse\x20defines\x20the\x20M\ sg/InstantiateContract\x20response\x20type.\n\n\n\n\x03\x04\0\x01\x12\ - \x03\x03\x08&\nR\n\x04\x04\0\x02\0\x12\x03\x05\x02\x1e\x1aE\x20ContractA\ + \x03\x03\x08&\nR\n\x04\x04\0\x02\0\x12\x03\x05\x02\x1e\x1aE\x20A\ ddress\x20is\x20the\x20bech32\x20address\x20of\x20the\x20new\x20contract\ \x20instance.\n\n\x0c\n\x05\x04\0\x02\0\x05\x12\x03\x05\x02\x08\n\x0c\n\ \x05\x04\0\x02\0\x01\x12\x03\x05\t\x19\n\x0c\n\x05\x04\0\x02\0\x03\x12\ diff --git a/contracts/campaign_manager/src/executions.rs b/contracts/campaign_manager/src/executions.rs index 4728786..b950404 100644 --- a/contracts/campaign_manager/src/executions.rs +++ b/contracts/campaign_manager/src/executions.rs @@ -360,12 +360,12 @@ pub fn created_campaign( } let events = msg.result.unwrap().events; - let event = find(&events, |e| e.ty == "instantiate_contract"); + let event = find(&events, |e| e.ty == "instantiate"); if event.is_none() { return Err(ContractError::Std(StdError::generic_err("Failed to parse data"))); } - let contract_address = find(&event.unwrap().attributes, |a| a.key == "contract_address"); + let contract_address = find(&event.unwrap().attributes, |a| a.key == "_contract_address"); if contract_address.is_none() { return Err(ContractError::Std(StdError::generic_err("Failed to parse data"))); } diff --git a/packages/valkyrie/src/message_factories.rs b/packages/valkyrie/src/message_factories.rs index de467a5..e810822 100644 --- a/packages/valkyrie/src/message_factories.rs +++ b/packages/valkyrie/src/message_factories.rs @@ -37,7 +37,7 @@ pub fn wasm_instantiate(code_id: u64, admin: Option, msg: Binary) -> Cosmo code_id, msg, funds: vec![], - label: String::new(), + label: "campaign".to_string(), }) } From 4ac0d3d96dee68b08ca390d29eb8b0c3d2e47164 Mon Sep 17 00:00:00 2001 From: FelixKim Date: Mon, 27 Jun 2022 15:15:45 +0900 Subject: [PATCH 6/7] modified vp init msg --- contracts/vp/src/entrypoints.rs | 2 +- contracts/vp/src/msg.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/contracts/vp/src/entrypoints.rs b/contracts/vp/src/entrypoints.rs index 5f57034..6430d9a 100644 --- a/contracts/vp/src/entrypoints.rs +++ b/contracts/vp/src/entrypoints.rs @@ -44,7 +44,7 @@ pub fn instantiate( name: msg.name, symbol: msg.symbol, decimals: msg.decimals, - initial_balances: vec![], + initial_balances: msg.initial_balances, marketing: msg.marketing, mint: Some(MinterResponse { minter: env.contract.address.to_string(), diff --git a/contracts/vp/src/msg.rs b/contracts/vp/src/msg.rs index e1e743e..35ff65b 100644 --- a/contracts/vp/src/msg.rs +++ b/contracts/vp/src/msg.rs @@ -1,5 +1,5 @@ use cosmwasm_std::{Decimal, Uint128, Binary}; -use cw20::{Cw20ReceiveMsg, Logo, Expiration}; +use cw20::{Cw20ReceiveMsg, Logo, Expiration, Cw20Coin}; use cw20_base::msg::InstantiateMarketingInfo; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -17,6 +17,7 @@ pub struct InstantiateMsg { pub base_swap_ratio: Decimal, pub custom_swap_ratio: Vec, pub router: String, + pub initial_balances: Vec, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] From b5fcb666f17d7e291f40365756e50fc0d7b9bf54 Mon Sep 17 00:00:00 2001 From: FelixKim Date: Mon, 27 Jun 2022 17:03:21 +0900 Subject: [PATCH 7/7] fixed vp init msg --- contracts/vp/src/entrypoints.rs | 21 +++++------- contracts/vp/src/executions.rs | 6 ---- contracts/vp/src/migrations/v108_beta0.rs | 42 ++--------------------- contracts/vp/src/msg.rs | 6 +--- contracts/vp/src/state.rs | 1 - 5 files changed, 13 insertions(+), 63 deletions(-) diff --git a/contracts/vp/src/entrypoints.rs b/contracts/vp/src/entrypoints.rs index 6430d9a..d101f42 100644 --- a/contracts/vp/src/entrypoints.rs +++ b/contracts/vp/src/entrypoints.rs @@ -8,7 +8,6 @@ use crate::queries::{query_config, query_state, query_swap_state}; use crate::state::{Config}; use cw20_base::ContractError; use cw2::set_contract_version; -use crate::migrations; const CONTRACT_NAME: &str = "valkyrian-pass-cw20-token"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -33,7 +32,6 @@ pub fn instantiate( offer_token: deps.api.addr_validate(msg.offer_token.as_str())?, base_swap_ratio: msg.base_swap_ratio, custom_swap_ratio: msg.custom_swap_ratio, - router: deps.api.addr_validate(msg.router.as_str())?, }.save(deps.storage)?; cw20_base::contract::instantiate( @@ -138,14 +136,13 @@ pub fn execute( offer_token, base_swap_ratio, custom_swap_ratio, - router, } => { let config = Config::load(deps.storage)?; if !config.is_admin(&info.sender) { return Err(ContractError::Unauthorized {}); } - crate::executions::update_config(deps, env, info, admin, whitelist, offer_token, base_swap_ratio, custom_swap_ratio, router) + crate::executions::update_config(deps, env, info, admin, whitelist, offer_token, base_swap_ratio, custom_swap_ratio) }, ExecuteMsg::ApproveAdminNominee {} => crate::executions::approve_admin_nominee(deps, env, info), } @@ -198,19 +195,19 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { } #[cfg_attr(not(feature = "library"), entry_point)] -pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> Result { +pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result { if cw2::get_contract_version(deps.storage).is_err() { cw2::set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.0".to_string())?; } //mig to v1.0.8-beta.0 to v1.0.8-beta.1 - let info = cw2::get_contract_version(deps.storage)?; - if info.version == "v1.0.8-beta.0".to_string() { - let router = &deps.api.addr_validate(msg.router.as_str())?; - migrations::v108_beta0::migrate(deps.storage, &env, router)?; - - set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.1")?; - } + // let info = cw2::get_contract_version(deps.storage)?; + // if info.version == "v1.0.8-beta.0".to_string() { + // let router = &deps.api.addr_validate(msg.router.as_str())?; + // migrations::v108_beta0::migrate(deps.storage, &env, router)?; + // + // set_contract_version(deps.storage, CONTRACT_NAME, "1.0.8-beta.1")?; + // } Ok(Response::default()) } \ No newline at end of file diff --git a/contracts/vp/src/executions.rs b/contracts/vp/src/executions.rs index 0126945..52855c6 100644 --- a/contracts/vp/src/executions.rs +++ b/contracts/vp/src/executions.rs @@ -12,7 +12,6 @@ pub fn update_config( offer_token: Option, base_swap_ratio: Option, custom_swap_ratio: Option>, - router: Option, ) -> Result { let mut response = Response::new(); response = response.add_attribute("action", "update_config"); @@ -46,11 +45,6 @@ pub fn update_config( response = response.add_attribute("is_updated_custom_swap_ratio", "true"); } - if let Some(router) = router { - config.router = deps.api.addr_validate(router.as_str())?; - response = response.add_attribute("is_updated_router", "true"); - } - config.save(deps.storage)?; Ok(response) } diff --git a/contracts/vp/src/migrations/v108_beta0.rs b/contracts/vp/src/migrations/v108_beta0.rs index 36f909f..920a1f7 100644 --- a/contracts/vp/src/migrations/v108_beta0.rs +++ b/contracts/vp/src/migrations/v108_beta0.rs @@ -1,45 +1,9 @@ -use cosmwasm_std::{Addr, Decimal, Env, StdResult, Storage}; -use cw_storage_plus::Item; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use crate::state::{Config, SwapRatio}; +use cosmwasm_std::{Addr, Env, StdResult, Storage}; pub fn migrate( - storage: &mut dyn Storage, + _storage: &mut dyn Storage, _env: &Env, - router: &Addr, + _router: &Addr, ) -> StdResult<()> { - let legacy_config = ConfigV108Beta0::load(storage)?; - - Config { - admin: legacy_config.admin, - whitelist: legacy_config.whitelist, - offer_token: legacy_config.offer_token, - base_swap_ratio: legacy_config.base_swap_ratio, - custom_swap_ratio: legacy_config.custom_swap_ratio, - router: router.clone(), - }.save(storage)?; - Ok(()) -} - -const CONFIG_V108_BETA0: Item = Item::new("config"); - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct ConfigV108Beta0 { - pub admin: Addr, - pub whitelist: Vec, - pub offer_token: Addr, - pub base_swap_ratio: Decimal, - pub custom_swap_ratio: Vec, -} - -impl ConfigV108Beta0 { - pub fn save(&self, storage: &mut dyn Storage) -> StdResult<()> { - CONFIG_V108_BETA0.save(storage, self) - } - - pub fn load(storage: &dyn Storage) -> StdResult { - CONFIG_V108_BETA0.load(storage) - } } \ No newline at end of file diff --git a/contracts/vp/src/msg.rs b/contracts/vp/src/msg.rs index 35ff65b..53a4fa1 100644 --- a/contracts/vp/src/msg.rs +++ b/contracts/vp/src/msg.rs @@ -16,7 +16,6 @@ pub struct InstantiateMsg { pub offer_token: String, pub base_swap_ratio: Decimal, pub custom_swap_ratio: Vec, - pub router: String, pub initial_balances: Vec, } @@ -83,7 +82,6 @@ pub enum ExecuteMsg { offer_token: Option, base_swap_ratio: Option, custom_swap_ratio: Option>, - router: Option, }, ApproveAdminNominee {}, } @@ -145,6 +143,4 @@ pub enum QueryMsg { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] -pub struct MigrateMsg { - pub router: String, -} \ No newline at end of file +pub struct MigrateMsg {} \ No newline at end of file diff --git a/contracts/vp/src/state.rs b/contracts/vp/src/state.rs index 81798f5..44daaa0 100644 --- a/contracts/vp/src/state.rs +++ b/contracts/vp/src/state.rs @@ -14,7 +14,6 @@ pub struct Config { pub offer_token: Addr, pub base_swap_ratio: Decimal, pub custom_swap_ratio: Vec, - pub router: Addr, } #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]