Skip to content

Commit

Permalink
Merge branch 'main' into feat/blend-soroswap-setup
Browse files Browse the repository at this point in the history
  • Loading branch information
chopan123 committed Dec 11, 2024
2 parents d38aab6 + a67c1c5 commit 4264ad3
Show file tree
Hide file tree
Showing 27 changed files with 1,708 additions and 703 deletions.
2 changes: 2 additions & 0 deletions apps/contracts/factory/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub(crate) fn create_asset_params(test: &DeFindexFactoryTest) -> Vec<AssetStrate
pub struct DeFindexFactoryTest<'a> {
env: Env,
factory_contract: DeFindexFactoryClient<'a>,
defindex_wasm_hash: BytesN<32>,
admin: Address,
defindex_receiver: Address,
emergency_manager: Address,
Expand Down Expand Up @@ -134,6 +135,7 @@ impl<'a> DeFindexFactoryTest<'a> {
env,
factory_contract,
admin,
defindex_wasm_hash,
defindex_receiver,
emergency_manager,
fee_receiver,
Expand Down
48 changes: 29 additions & 19 deletions apps/contracts/factory/src/test/factory/budget.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
extern crate std;

use crate::test::{create_asset_params, DeFindexFactoryTest};
use crate::test::{create_asset_params, create_defindex_factory, DeFindexFactoryTest};
use soroban_sdk::{vec as sorobanvec, BytesN, String, Vec};

#[test]
fn budget() {

let test = DeFindexFactoryTest::setup();
test.env.mock_all_auths();

test.env.budget().reset_unlimited();

// initialize factory contract

test.factory_contract.initialize(&test.admin, &test.defindex_receiver, &100u32, &test.defindex_wasm_hash);
let factory_contract = create_defindex_factory(
&test.env,
&test.admin,
&test.defindex_receiver,
2000u32,
&test.defindex_wasm_hash,
);

let mem = test.env.budget().memory_bytes_cost();
let cpu = test.env.budget().cpu_instruction_cost();

std::println!("initialize() | cpu: {}, mem: {}", cpu, mem);
std::println!("create_defindex_factory() | cpu: {}, mem: {}", cpu, mem);

test.env.budget().reset_unlimited();

Expand All @@ -27,48 +33,52 @@ fn budget() {

let salt = BytesN::from_array(&test.env, &[0; 32]);

test.factory_contract.create_defindex_vault(
let _ = factory_contract.create_defindex_vault(
&test.emergency_manager,
&test.fee_receiver,
&2000u32,
&test.fee_receiver,
&200u32,
&String::from_str(&test.env, "dfToken"),
&String::from_str(&test.env, "DFT"),
&test.manager,
&asset_params,
&test.admin,
&asset_params,
&salt
);

let mem = test.env.budget().memory_bytes_cost();
let cpu = test.env.budget().cpu_instruction_cost();
std::println!("create_defindex_vault() | cpu: {}, mem: {}", cpu, mem);
std::println!("create_defindex_vault() | cpu: {}, mem: {}", cpu, mem);

test.env.budget().reset_unlimited();
let users = DeFindexFactoryTest::generate_random_users(&test.env, 2);
// create defindex vault deposit
let asset_params = create_asset_params(&test);
let salt = BytesN::from_array(&test.env, &[0; 32]);

let amount_0 = 100i128;
let amount_1 = 200i128;
let amount_0 = 1000i128;
let amount_1 = 2000i128;

let amounts: Vec<i128> = sorobanvec![&test.env, amount_0.clone(), amount_1.clone()];

test.factory_contract.try_create_defindex_vault_deposit(
&users[0],
// Mint tokens to manager
test.token0_admin_client.mint(&test.manager, &amount_0);
test.token1_admin_client.mint(&test.manager, &amount_1);

test.factory_contract.create_defindex_vault_deposit(
&test.manager,
&test.emergency_manager,
&test.fee_receiver,
&10u32,
&String::from_str(&test.env, "DFTa"),
&String::from_str(&test.env, "AAA"),
&2000u32,
&String::from_str(&test.env, "dfToken"),
&String::from_str(&test.env, "DFT"),
&test.manager,
&asset_params,
&amounts,
&salt
);


let mem = test.env.budget().memory_bytes_cost();
let cpu = test.env.budget().cpu_instruction_cost();
std::println!("create_defindex_vault_deposit() | cpu: {}, mem: {}", cpu, mem);
std::println!("create_defindex_vault_deposit() | cpu: {}, mem: {}", cpu, mem);


}
47 changes: 47 additions & 0 deletions apps/contracts/src/utils/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,50 @@ export const getCurrentTimePlusOneHour = () => {

return oneHourLater;
};

export function getTransactionBudget(tx: any): { instructions: number, readBytes: number, writeBytes: number } {
const resources = tx.envelopeXdr.value().tx().ext().value().resources()
const warningTolerance = 0.85
const MAXWRITEBYTES = 132096
const MAXREADBYTES = 200000
const MAXINSTRUCTIONS = 100000000
const budget= {
instructions: resources.instructions(),
readBytes: resources.readBytes(),
writeBytes: resources.writeBytes(),
}
const getPercentage = (value: number, max: number)=>{
return (value * 100)/max
}
if(budget.instructions > MAXINSTRUCTIONS * warningTolerance){
console.warn('Instructions budget exceeded')
console.table({
value:{
instructions: budget.instructions,
maxInstructions: MAXINSTRUCTIONS,
'%': getPercentage(budget.instructions, MAXINSTRUCTIONS)
},
})
}
if(budget.readBytes > MAXREADBYTES * warningTolerance){
console.warn('ReadBytes budget exceeded')
console.table({
value: {
readBytes: budget.readBytes,
maxReadBytes: MAXREADBYTES,
'%': getPercentage(budget.readBytes, MAXREADBYTES)
}
})
}
if(budget.writeBytes > MAXWRITEBYTES * warningTolerance){
console.warn('WriteBytes budget exceeded')
console.table({
value:{
writeBytes: budget.writeBytes,
maxWriteBytes: MAXWRITEBYTES,
'%': getPercentage(budget.writeBytes, MAXWRITEBYTES)
}
})
}
return budget
}
7 changes: 6 additions & 1 deletion apps/contracts/strategies/hodl/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub struct HodlStrategyTest<'a> {
env: Env,
token: TokenClient<'a>,
user: Address,
user1: Address,
}

impl<'a> HodlStrategyTest<'a> {
Expand All @@ -38,14 +39,18 @@ impl<'a> HodlStrategyTest<'a> {
let admin = Address::generate(&env);
let token = create_token_contract(&env, &admin);
let user = Address::generate(&env);
let user1 = Address::generate(&env);

// Mint 1,000,000,000 to user
StellarAssetClient::new(&env, &token.address).mint(&user, &1_000_000_000);
// Mint 1,000,000,000 to user1
StellarAssetClient::new(&env, &token.address).mint(&user1, &1_000_000_000);

HodlStrategyTest {
env,
token,
user
user,
user1,
}
}

Expand Down
33 changes: 31 additions & 2 deletions apps/contracts/strategies/hodl/src/test/hodl/deposit.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::test::create_hodl_strategy;
use crate::test::HodlStrategyTest;
use crate::test::StrategyError;

// test deposit with negative amount
#[test]
fn deposit_with_negative_amount() {
Expand All @@ -27,7 +26,6 @@ fn deposit_mock_auths() {
fn deposit_and_withdrawal_flow() {
let test = HodlStrategyTest::setup();

// initialize
let strategy = create_hodl_strategy(&test.env, &test.token.address);

// Initial user token balance
Expand Down Expand Up @@ -71,4 +69,35 @@ fn deposit_and_withdrawal_flow() {
let result = strategy.try_withdraw(&amount_to_withdraw, &test.user);
assert_eq!(result, Err(Ok(StrategyError::InsufficientBalance)));

}

#[test]
fn deposit_from_a_withdrawal_from_b() {
let test = HodlStrategyTest::setup();
let strategy = create_hodl_strategy(&test.env, &test.token.address);

// Initial user token balance
let balance = test.token.balance(&test.user);

let amount = 123456;

// Deposit amount of token from the user to the strategy
strategy.deposit(&amount, &test.user);

let balance_after_deposit = test.token.balance(&test.user);
assert_eq!(balance_after_deposit, balance - amount);

// Reading strategy balance
let strategy_balance_after_deposit = test.token.balance(&strategy.address);
assert_eq!(strategy_balance_after_deposit, amount);

// Reading user balance on strategy contract
let user_balance_on_strategy = strategy.balance(&test.user);
assert_eq!(user_balance_on_strategy, amount);


let amount_to_withdraw = 100_000;
// Withdrawing token from the strategy to user
let result = strategy.try_withdraw(&amount_to_withdraw, &test.user1);
assert_eq!(result, Err(Ok(StrategyError::InsufficientBalance)));
}
73 changes: 16 additions & 57 deletions apps/contracts/vault/src/deposit.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
use common::models::AssetStrategySet;
use soroban_sdk::{panic_with_error, token::TokenClient, Address, Env, Vec};
use soroban_sdk::{panic_with_error, token::TokenClient, Address, Env, Vec, Map};

use crate::{
funds::{
fetch_invested_funds_for_asset, fetch_invested_funds_for_strategy,
fetch_total_managed_funds,
},
investment::check_and_execute_investments,
models::{AssetInvestmentAllocation, StrategyAllocation},
storage::get_assets,
token::{internal_mint, VaultToken},
utils::{calculate_deposit_amounts_and_shares_to_mint, check_nonnegative_amount},
ContractError, MINIMUM_LIQUIDITY,
models::{CurrentAssetInvestmentAllocation},
};

/// Common logic for processing deposits.
pub fn process_deposit(
e: &Env,
assets: &Vec<AssetStrategySet>,
total_managed_funds: &Map<Address, CurrentAssetInvestmentAllocation>,
amounts_desired: &Vec<i128>,
amounts_min: &Vec<i128>,
from: &Address,
Expand All @@ -35,12 +31,21 @@ pub fn process_deposit(

let total_supply = VaultToken::total_supply(e.clone());
let (amounts, shares_to_mint) = if assets_length == 1 {
calculate_single_asset_shares(e, amounts_desired, total_supply)?
calculate_single_asset_shares(
e,
amounts_desired,
&total_managed_funds,
total_supply)?
} else {
if total_supply == 0 {
(amounts_desired.clone(), amounts_desired.iter().sum())
} else {
calculate_deposit_amounts_and_shares_to_mint(&e, &assets, amounts_desired, amounts_min)?
calculate_deposit_amounts_and_shares_to_mint(
&e,
&assets,
&total_managed_funds,
amounts_desired,
amounts_min)?
}
};

Expand All @@ -66,12 +71,12 @@ pub fn process_deposit(
fn calculate_single_asset_shares(
e: &Env,
amounts_desired: &Vec<i128>,
total_managed_funds: &Map<Address, CurrentAssetInvestmentAllocation>,
total_supply: i128,
) -> Result<(Vec<i128>, i128), ContractError> {
let shares = if total_supply == 0 {
amounts_desired.get(0).unwrap()
} else {
let total_managed_funds = fetch_total_managed_funds(&e);
VaultToken::total_supply(e.clone())
.checked_mul(amounts_desired.get(0).unwrap())
.unwrap_or_else(|| panic_with_error!(&e, ContractError::ArithmeticError))
Expand Down Expand Up @@ -106,50 +111,4 @@ fn mint_shares(
internal_mint(e.clone(), from, shares_to_mint);
}
Ok(())
}

/// Generate investment allocations and execute them.
pub fn generate_and_execute_investments(
e: &Env,
amounts: &Vec<i128>,
assets: &Vec<AssetStrategySet>,
) -> Result<(), ContractError> {
let mut asset_investments = Vec::new(&e);

for (i, amount) in amounts.iter().enumerate() {
let asset = assets.get(i as u32).unwrap();
let (asset_invested_funds, _) = fetch_invested_funds_for_asset(&e, &asset);

let mut strategy_allocations = Vec::new(&e);
let mut remaining_amount = amount;

for (j, strategy) in asset.strategies.iter().enumerate() {
let strategy_invested_funds = fetch_invested_funds_for_strategy(&e, &strategy.address);

let mut invest_amount = if asset_invested_funds > 0 {
(amount * strategy_invested_funds) / asset_invested_funds
} else {
0
};

if j == asset.strategies.len() as usize - 1 {
invest_amount = remaining_amount;
}

remaining_amount -= invest_amount;

strategy_allocations.push_back(Some(StrategyAllocation {
strategy_address: strategy.address.clone(),
amount: invest_amount,
}));
}

asset_investments.push_back(Some(AssetInvestmentAllocation {
asset: asset.address.clone(),
strategy_allocations,
}));
}

check_and_execute_investments(e.clone(), assets.clone(), asset_investments)?;
Ok(())
}
}
Loading

0 comments on commit 4264ad3

Please sign in to comment.