Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V2 update/gas optimization #69

Draft
wants to merge 5 commits into
base: v2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contracts/carrot-app/examples/localnet_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ fn one_element(upper_tick: i64, lower_tick: i64, share: Decimal) -> StrategyElem
upper_tick,
position_id: None,
_phantom: std::marker::PhantomData,
position_cache: None,
}),
},
share,
Expand Down
1 change: 1 addition & 0 deletions contracts/carrot-app/examples/localnet_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ fn main() -> anyhow::Result<()> {
)?;

carrot.deposit(coins(10_000, "uosmo"), None)?;
// carrot.deposit(coins(10_000, "uosmo"), None)?;

carrot.update_strategy(coins(10_000, "uosmo"), five_strategy())?;
carrot.withdraw(None)?;
Expand Down
2 changes: 2 additions & 0 deletions contracts/carrot-app/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ mod yield_sources {
upper_tick: self.upper_tick,
position_id: self.position_id,
_phantom: PhantomData,
position_cache: self.position_cache,
})
}
}
Expand All @@ -179,6 +180,7 @@ mod yield_sources {
upper_tick: params.upper_tick,
position_id: params.position_id,
_phantom: std::marker::PhantomData,
position_cache: params.position_cache,
})
}
YieldParamsBase::Mars(params) => YieldParamsBase::Mars(params),
Expand Down
20 changes: 14 additions & 6 deletions contracts/carrot-app/src/distribution/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ use cosmwasm_schema::cw_serde;

use crate::{error::AppError, msg::InternalExecuteMsg};

pub struct DepositStrategy {
pub withdraw_strategy: Vec<(StrategyElement, Decimal)>,
pub deposit_msgs: Vec<InternalExecuteMsg>,
}

/// This functions creates the current deposit strategy
// /// 1. We query the target strategy in storage (target strategy)
// /// 2. We query the current status of the strategy (current strategy) from all deposits (external queries)
Expand All @@ -22,10 +27,10 @@ use crate::{error::AppError, msg::InternalExecuteMsg};
pub fn generate_deposit_strategy(
deps: Deps,
funds: Vec<Coin>,
target_strategy: Strategy,
mut target_strategy: Strategy,
yield_source_params: Option<Vec<Option<Vec<AssetShare>>>>,
app: &App,
) -> AppResult<(Vec<(StrategyElement, Decimal)>, Vec<InternalExecuteMsg>)> {
) -> AppResult<DepositStrategy> {
// This is the current distribution of funds inside the strategies
let current_strategy_status = target_strategy.query_current_status(deps, app)?;

Expand All @@ -44,18 +49,21 @@ pub fn generate_deposit_strategy(
let deposit_msgs =
this_deposit_strategy.fill_all_and_get_messages(deps, usable_funds.into(), app)?;

Ok((withdraw_strategy, deposit_msgs))
Ok(DepositStrategy {
withdraw_strategy,
deposit_msgs,
})
}

impl Strategy {
// We determine the best balance strategy depending on the current deposits and the target strategy.
// This method needs to be called on the stored strategy
// We error if deposit value is non-zero here
pub fn current_deposit_strategy(
&self,
&mut self,
deps: Deps,
funds: &mut Coins,
current_strategy_status: Self,
mut current_strategy_status: Self,
app: &App,
) -> AppResult<(Vec<(StrategyElement, Decimal)>, Self)> {
let total_value = self.current_balance(deps, app)?.total_value;
Expand All @@ -78,7 +86,7 @@ impl Strategy {
// First we generate the messages for withdrawing strategies that have too much funds
let withdraw_strategy: Vec<(StrategyElement, Decimal)> = current_strategy_status
.0
.iter()
.iter_mut()
.zip(self.0.clone())
.map(|(current, target)| {
// We need to take into account the total value added by the current shares
Expand Down
10 changes: 5 additions & 5 deletions contracts/carrot-app/src/distribution/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use crate::{

impl Strategy {
// Returns the total balance
pub fn current_balance(&self, deps: Deps, app: &App) -> AppResult<AssetsBalanceResponse> {
pub fn current_balance(&mut self, deps: Deps, app: &App) -> AppResult<AssetsBalanceResponse> {
let mut funds = Coins::default();
let mut total_value = Uint128::zero();
self.0.iter().try_for_each(|s| {
self.0.iter_mut().try_for_each(|s| {
let deposit_value = s
.yield_source
.params
Expand All @@ -36,10 +36,10 @@ impl Strategy {
}

/// Returns the current status of the full strategy. It returns shares reflecting the underlying positions
pub fn query_current_status(&self, deps: Deps, app: &App) -> AppResult<Strategy> {
pub fn query_current_status(&mut self, deps: Deps, app: &App) -> AppResult<Strategy> {
let all_strategy_values = self
.0
.iter()
.iter_mut()
.map(|s| s.query_current_value(deps, app))
.collect::<Result<Vec<_>, _>>()?;

Expand Down Expand Up @@ -89,7 +89,7 @@ impl StrategyElement {
/// If there is no deposit or the query for the user deposit value fails
/// the function returns 0 value with the registered asset distribution
pub fn query_current_value(
&self,
&mut self,
deps: Deps,
app: &App,
) -> AppResult<(Uint128, Vec<AssetShare>)> {
Expand Down
2 changes: 1 addition & 1 deletion contracts/carrot-app/src/distribution/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Strategy {
let (rewards, msgs): (Vec<Vec<Coin>>, _) = self
.0
.into_iter()
.map(|s| {
.map(|mut s| {
let (rewards, raw_msgs) = s.yield_source.params.withdraw_rewards(deps, app)?;

Ok::<_, AppError>((
Expand Down
8 changes: 4 additions & 4 deletions contracts/carrot-app/src/distribution/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ impl Strategy {
.collect()
}
pub fn withdraw_preview(
self,
&mut self,
deps: Deps,
withdraw_share: Option<Decimal>,
app: &App,
) -> AppResult<Vec<Coin>> {
let mut withdraw_result = Coins::default();
self.0.into_iter().try_for_each(|s| {
self.0.iter_mut().try_for_each(|s| {
let funds = s.withdraw_preview(deps, withdraw_share, app)?;
funds.into_iter().try_for_each(|f| withdraw_result.add(f))?;
Ok::<_, AppError>(())
Expand All @@ -37,7 +37,7 @@ impl Strategy {

impl StrategyElement {
pub fn withdraw(
self,
mut self,
deps: Deps,
withdraw_share: Option<Decimal>,
app: &App,
Expand All @@ -62,7 +62,7 @@ impl StrategyElement {
}

pub fn withdraw_preview(
&self,
&mut self,
deps: Deps,
withdraw_share: Option<Decimal>,
app: &App,
Expand Down
28 changes: 14 additions & 14 deletions contracts/carrot-app/src/handlers/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use crate::{
autocompound::AutocompoundState,
check::Checkable,
contract::{App, AppResult},
distribution::deposit::generate_deposit_strategy,
distribution::deposit::{generate_deposit_strategy, DepositStrategy},
error::AppError,
handlers::query::query_balance,
helpers::assert_contract,
msg::{AppExecuteMsg, ExecuteMsg},
state::{AUTOCOMPOUND_STATE, CONFIG, STRATEGY_CONFIG},
state::{load_strategy, save_strategy, AUTOCOMPOUND_STATE, CONFIG},
yield_sources::{AssetShare, Strategy, StrategyUnchecked},
};
use abstract_app::abstract_sdk::features::AbstractResponse;
Expand Down Expand Up @@ -56,7 +56,7 @@ fn deposit(
.assert_admin(deps.as_ref(), &info.sender)
.or(assert_contract(&info, &env))?;

let target_strategy = STRATEGY_CONFIG.load(deps.storage)?;
let target_strategy = load_strategy(deps.as_ref())?;
let deposit_msgs = _inner_deposit(
deps.as_ref(),
&env,
Expand Down Expand Up @@ -92,18 +92,18 @@ fn withdraw(
}

fn update_strategy(
deps: DepsMut,
mut deps: DepsMut,
env: Env,
_info: MessageInfo,
strategy: StrategyUnchecked,
funds: Vec<Coin>,
app: App,
) -> AppResult {
// We load it raw because we're changing the strategy
let old_strategy = STRATEGY_CONFIG.load(deps.storage)?;
let old_strategy = load_strategy(deps.as_ref())?;

// We check the new strategy
let strategy = strategy.check(deps.as_ref(), &app)?;
let mut strategy = strategy.check(deps.as_ref(), &app)?;

// We execute operations to rebalance the funds between the strategies
let mut available_funds: Coins = funds.try_into()?;
Expand All @@ -117,7 +117,7 @@ fn update_strategy(
let (withdrawn_funds, withdraw_msgs): (Vec<Vec<Coin>>, Vec<Option<ExecutorMsg>>) =
all_stale_sources
.into_iter()
.map(|s| {
.map(|mut s| {
Ok::<_, AppError>((
s.withdraw_preview(deps.as_ref(), None, &app)
.unwrap_or_default(),
Expand All @@ -133,7 +133,7 @@ fn update_strategy(
.try_for_each(|f| f.into_iter().try_for_each(|f| available_funds.add(f)))?;

// 2. We replace the strategy with the new strategy
STRATEGY_CONFIG.save(deps.storage, &strategy)?;
save_strategy(deps.branch(), &mut strategy)?;

// 3. We deposit the funds into the new strategy
let deposit_msgs = _inner_deposit(
Expand All @@ -160,7 +160,7 @@ fn update_strategy(

fn autocompound(deps: DepsMut, env: Env, info: MessageInfo, app: App) -> AppResult {
// Everyone can autocompound
let strategy = STRATEGY_CONFIG.load(deps.storage)?;
let strategy = load_strategy(deps.as_ref())?;

// We withdraw all rewards from protocols
let (all_rewards, collect_rewards_msgs) = strategy.withdraw_rewards(deps.as_ref(), &app)?;
Expand Down Expand Up @@ -207,8 +207,10 @@ pub fn _inner_deposit(
yield_source_params: Option<Vec<Option<Vec<AssetShare>>>>,
app: &App,
) -> AppResult<Vec<CosmosMsg>> {
let (withdraw_strategy, deposit_msgs) =
generate_deposit_strategy(deps, funds, target_strategy, yield_source_params, app)?;
let DepositStrategy {
withdraw_strategy,
deposit_msgs,
} = generate_deposit_strategy(deps, funds, target_strategy, yield_source_params, app)?;

let deposit_withdraw_msgs = withdraw_strategy
.into_iter()
Expand Down Expand Up @@ -242,9 +244,7 @@ fn _inner_withdraw(

// We withdraw the necessary share from all registered investments
let withdraw_msgs =
STRATEGY_CONFIG
.load(deps.storage)?
.withdraw(deps.as_ref(), withdraw_share, app)?;
load_strategy(deps.as_ref())?.withdraw(deps.as_ref(), withdraw_share, app)?;

Ok(withdraw_msgs.into_iter().collect())
}
8 changes: 4 additions & 4 deletions contracts/carrot-app/src/handlers/instantiate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ use crate::{
check::Checkable,
contract::{App, AppResult},
msg::AppInstantiateMsg,
state::{CONFIG, STRATEGY_CONFIG},
state::{save_strategy, CONFIG},
};
use abstract_app::abstract_sdk::AbstractResponse;
use cosmwasm_std::{DepsMut, Env, MessageInfo};

use super::execute::_inner_deposit;

pub fn instantiate_handler(
deps: DepsMut,
mut deps: DepsMut,
env: Env,
_info: MessageInfo,
app: App,
Expand All @@ -20,8 +20,8 @@ pub fn instantiate_handler(
let config = msg.config.check(deps.as_ref(), &app)?;

CONFIG.save(deps.storage, &config)?;
let strategy = msg.strategy.check(deps.as_ref(), &app)?;
STRATEGY_CONFIG.save(deps.storage, &strategy)?;
let mut strategy = msg.strategy.check(deps.as_ref(), &app)?;
save_strategy(deps.branch(), &mut strategy)?;

let mut response = app.response("instantiate_savings_app");

Expand Down
15 changes: 3 additions & 12 deletions contracts/carrot-app/src/handlers/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@ use crate::{
msg::{AppExecuteMsg, ExecuteMsg, InternalExecuteMsg},
replies::REPLY_AFTER_SWAPS_STEP,
state::{
CONFIG, STRATEGY_CONFIG, TEMP_CURRENT_COIN, TEMP_CURRENT_YIELD, TEMP_DEPOSIT_COINS,
TEMP_EXPECTED_SWAP_COIN,
},
yield_sources::{
yield_type::{YieldType, YieldTypeImplementation},
Strategy,
CONFIG, TEMP_CURRENT_COIN, TEMP_CURRENT_YIELD, TEMP_DEPOSIT_COINS, TEMP_EXPECTED_SWAP_COIN,
},
yield_sources::yield_type::{YieldType, YieldTypeImplementation},
};
use abstract_app::{abstract_sdk::features::AbstractResponse, objects::AnsAsset};
use abstract_dex_adapter::DexInterface;
Expand Down Expand Up @@ -149,7 +145,7 @@ pub fn execute_one_deposit_step(

pub fn execute_finalize_deposit(
deps: DepsMut,
yield_type: YieldType,
mut yield_type: YieldType,
yield_index: usize,
app: App,
) -> AppResult {
Expand All @@ -161,8 +157,3 @@ pub fn execute_finalize_deposit(

Ok(app.response("finalize-deposit").add_submessages(msgs))
}

pub fn save_strategy(deps: DepsMut, strategy: Strategy) -> AppResult<()> {
STRATEGY_CONFIG.save(deps.storage, &strategy)?;
Ok(())
}
Loading
Loading