Skip to content

Commit

Permalink
fixed typescript scripts for blend strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
joaquinsoza committed Dec 3, 2024
1 parent 7a65c7f commit 2d117b1
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 84 deletions.
4 changes: 3 additions & 1 deletion apps/contracts/src/strategies/deploy_blend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export async function deployBlendStrategy(addressBook: AddressBook) {

const initArgs = xdr.ScVal.scvVec([
new Address("CCEVW3EEW4GRUZTZRTAMJAXD6XIF5IG7YQJMEEMKMVVGFPESTRXY2ZAV").toScVal(), //Blend pool on testnet!
nativeToScVal(0, {type: "u32"}) // ReserveId 0 is XLM
nativeToScVal(0, { type: "u32" }), // ReserveId 0 is XLM
new Address("CB22KRA3YZVCNCQI64JQ5WE7UY2VAV7WFLK6A2JN3HEX56T2EDAFO7QF").toScVal(), // BLND Token
new Address("CAG5LRYQ5JVEUI5TEID72EYOVX44TTUJT5BQR2J6J77FH65PCCFAJDDH").toScVal(), // Soroswap router
]);

const args: xdr.ScVal[] = [
Expand Down
2 changes: 1 addition & 1 deletion apps/contracts/src/tests/blend/test_vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export async function testBlendVault(user?: Keypair) {
console.log(purple, '----------------------- Depositing XLM to the vault -----------------------')
console.log(purple, '---------------------------------------------------------------------------')
const { user, balanceBefore: depositBalanceBefore, result: depositResult, balanceAfter: depositBalanceAfter }
= await depositToVault(blendVaultAddress, [initialAmount], newUser);
= await depositToVault(blendVaultAddress, [initialAmount], newUser, false);

console.log(green, '------------ XLM deposited to the vault ------------')
console.log(green, 'Deposit balance before: ', depositBalanceBefore)
Expand Down
2 changes: 1 addition & 1 deletion apps/contracts/src/tests/vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export async function depositToVault(deployedVault: string, amount: number[], us
const depositParams: xdr.ScVal[] = [
xdr.ScVal.scvVec(amountsDesired.map((amount) => nativeToScVal(amount, { type: "i128" }))),
xdr.ScVal.scvVec(amountsMin.map((min) => nativeToScVal(min, { type: "i128" }))),
(new Address(newUser.publicKey())).toScVal(),
new Address(newUser.publicKey()).toScVal(),
xdr.ScVal.scvBool(investDeposit)
];

Expand Down
2 changes: 1 addition & 1 deletion apps/contracts/strategies/blend/src/constants.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// 1 with 7 decimal places
pub const SCALAR_7: i128 = 1_0000000;
// pub const SCALAR_7: i128 = 1_0000000;
/// 1 with 9 decimal places
pub const SCALAR_9: i128 = 1_000_000_000;
/// The minimum amount of tokens than can be deposited or withdrawn from the vault
Expand Down
5 changes: 2 additions & 3 deletions apps/contracts/strategies/blend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
use blend_pool::perform_reinvest;
use constants::{MIN_DUST, SCALAR_9};
use soroban_sdk::{
contract, contractimpl, token::TokenClient, vec, Address, Env, IntoVal, String, Val, Vec};
contract, contractimpl, token::TokenClient, Address, Env, IntoVal, String, Val, Vec};

mod blend_pool;
mod constants;
mod reserves;
mod soroswap;
mod storage;

use soroswap::internal_swap_exact_tokens_for_tokens;
use storage::{extend_instance_ttl, is_initialized, set_initialized, Config};

pub use defindex_strategy_core::{
Expand Down Expand Up @@ -96,6 +95,7 @@ impl DeFindexStrategyTrait for BlendStrategy {
}

let config = storage::get_config(&e);
blend_pool::claim(&e, &e.current_contract_address(), &config);
perform_reinvest(&e, &config)?;

let reserves = storage::get_strategy_reserves(&e);
Expand Down Expand Up @@ -184,5 +184,4 @@ impl DeFindexStrategyTrait for BlendStrategy {
}
}

#[cfg(any(test, feature = "testutils"))]
mod test;
77 changes: 38 additions & 39 deletions apps/contracts/strategies/blend/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
extern crate std;

use crate::{
blend_pool::{self, BlendPoolClient, Request, ReserveConfig, ReserveEmissionMetadata}, constants::SCALAR_7, storage::DAY_IN_LEDGERS, BlendStrategy, BlendStrategyClient
blend_pool::{self, BlendPoolClient, Request, ReserveConfig, ReserveEmissionMetadata}, storage::DAY_IN_LEDGERS, BlendStrategy, BlendStrategyClient
};
use sep_41_token::testutils::MockTokenClient;
use soroban_fixed_point_math::FixedPoint;
use soroban_sdk::{
testutils::{Address as _, BytesN as _, Ledger as _, LedgerInfo}, token::StellarAssetClient, vec, Address, BytesN, Env, IntoVal, String, Symbol, Val, Vec
};
Expand Down Expand Up @@ -33,7 +32,7 @@ pub(crate) fn register_blend_strategy(e: &Env) -> Address {
pub struct BlendFixture<'a> {
pub backstop: blend_backstop::Client<'a>,
pub emitter: blend_emitter::Client<'a>,
pub backstop_token: blend_comet::Client<'a>,
pub _backstop_token: blend_comet::Client<'a>,
pub pool_factory: blend_factory_pool::Client<'a>,
}

Expand Down Expand Up @@ -177,7 +176,7 @@ pub trait EnvTestUtils {
fn jump(&self, ledgers: u32);

/// Jump the env by the given amount of seconds. Incremends the sequence by 1.
fn jump_time(&self, seconds: u64);
// fn jump_time(&self, seconds: u64);

/// Set the ledger to the default LedgerInfo
///
Expand All @@ -200,18 +199,18 @@ impl EnvTestUtils for Env {
});
}

fn jump_time(&self, seconds: u64) {
self.ledger().set(LedgerInfo {
timestamp: self.ledger().timestamp().saturating_add(seconds),
protocol_version: 21,
sequence_number: self.ledger().sequence().saturating_add(1),
network_id: Default::default(),
base_reserve: 10,
min_temp_entry_ttl: 30 * DAY_IN_LEDGERS,
min_persistent_entry_ttl: 30 * DAY_IN_LEDGERS,
max_entry_ttl: 365 * DAY_IN_LEDGERS,
});
}
// fn jump_time(&self, seconds: u64) {
// self.ledger().set(LedgerInfo {
// timestamp: self.ledger().timestamp().saturating_add(seconds),
// protocol_version: 21,
// sequence_number: self.ledger().sequence().saturating_add(1),
// network_id: Default::default(),
// base_reserve: 10,
// min_temp_entry_ttl: 30 * DAY_IN_LEDGERS,
// min_persistent_entry_ttl: 30 * DAY_IN_LEDGERS,
// max_entry_ttl: 365 * DAY_IN_LEDGERS,
// });
// }

fn set_default_info(&self) {
self.ledger().set(LedgerInfo {
Expand All @@ -227,32 +226,32 @@ impl EnvTestUtils for Env {
}
}

pub fn assert_approx_eq_abs(a: i128, b: i128, delta: i128) {
assert!(
a > b - delta && a < b + delta,
"assertion failed: `(left != right)` \
(left: `{:?}`, right: `{:?}`, epsilon: `{:?}`)",
a,
b,
delta
);
}
// pub fn assert_approx_eq_abs(a: i128, b: i128, delta: i128) {
// assert!(
// a > b - delta && a < b + delta,
// "assertion failed: `(left != right)` \
// (left: `{:?}`, right: `{:?}`, epsilon: `{:?}`)",
// a,
// b,
// delta
// );
// }

/// Asset that `b` is within `percentage` of `a` where `percentage`
/// is a percentage in decimal form as a fixed-point number with 7 decimal
/// places
pub fn assert_approx_eq_rel(a: i128, b: i128, percentage: i128) {
let rel_delta = b.fixed_mul_floor(percentage, SCALAR_7).unwrap();

assert!(
a > b - rel_delta && a < b + rel_delta,
"assertion failed: `(left != right)` \
(left: `{:?}`, right: `{:?}`, epsilon: `{:?}`)",
a,
b,
rel_delta
);
}
// pub fn assert_approx_eq_rel(a: i128, b: i128, percentage: i128) {
// let rel_delta = b.fixed_mul_floor(percentage, SCALAR_7).unwrap();

// assert!(
// a > b - rel_delta && a < b + rel_delta,
// "assertion failed: `(left != right)` \
// (left: `{:?}`, right: `{:?}`, epsilon: `{:?}`)",
// a,
// b,
// rel_delta
// );
// }

/// Oracle
use sep_40_oracle::testutils::{Asset, MockPriceOracleClient, MockPriceOracleWASM};
Expand Down Expand Up @@ -344,7 +343,7 @@ impl<'a> BlendFixture<'a> {
BlendFixture {
backstop: backstop_client,
emitter: emitter_client,
backstop_token: comet_client,
_backstop_token: comet_client,
pool_factory: pool_factory_client,
}
}
Expand Down
74 changes: 36 additions & 38 deletions apps/contracts/strategies/blend/src/test/success.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
#![cfg(test)]
use crate::blend_pool::{BlendPoolClient, Request};
use crate::constants::{MIN_DUST, SCALAR_7};
use crate::constants::MIN_DUST;
use crate::storage::DAY_IN_LEDGERS;
use crate::test::{create_blend_pool, create_blend_strategy, BlendFixture, EnvTestUtils};
use crate::BlendStrategyClient;
use defindex_strategy_core::StrategyError;
use sep_41_token::testutils::MockTokenClient;
use soroban_fixed_point_math::FixedPoint;
use soroban_sdk::testutils::{Address as _, AuthorizedFunction, AuthorizedInvocation};
use soroban_sdk::{vec, Address, Env, Error, IntoVal, Symbol};
use soroban_sdk::{vec, Address, Env, IntoVal, Symbol};
use crate::test::std;

#[test]
Expand All @@ -22,12 +21,11 @@ fn success() {
let user_2 = Address::generate(&e);
let user_3 = Address::generate(&e);
let user_4 = Address::generate(&e);
let user_5 = Address::generate(&e);

let blnd = e.register_stellar_asset_contract_v2(admin.clone());
let usdc = e.register_stellar_asset_contract_v2(admin.clone());
let xlm = e.register_stellar_asset_contract_v2(admin.clone());
let blnd_client = MockTokenClient::new(&e, &blnd.address());
let _blnd_client = MockTokenClient::new(&e, &blnd.address());
let usdc_client = MockTokenClient::new(&e, &usdc.address());
let xlm_client = MockTokenClient::new(&e, &xlm.address());

Expand All @@ -43,35 +41,35 @@ fn success() {

/*
* Deposit into pool
* -> deposit 100 into blend strategy for each user_3 and user_4
* -> deposit 200 into pool for user_5
* -> deposit 100 into blend strategy for each user_2 and user_3
* -> deposit 200 into pool for user_4
* -> admin borrow from pool to return to 50% util rate
* -> verify a deposit into an uninitialized vault fails
*/
let pool_usdc_balace_start = usdc_client.balance(&pool);
let starting_balance = 100_0000000;
usdc_client.mint(&user_2, &starting_balance);
usdc_client.mint(&user_3, &starting_balance);
usdc_client.mint(&user_4, &starting_balance);

let user_3_balance = usdc_client.balance(&user_3);
let user_3_balance = usdc_client.balance(&user_2);
assert_eq!(user_3_balance, starting_balance);


strategy_client.deposit(&starting_balance, &user_3);
strategy_client.deposit(&starting_balance, &user_2);
// -> verify deposit auth

assert_eq!(
e.auths()[0],
(
user_3.clone(),
user_2.clone(),
AuthorizedInvocation {
function: AuthorizedFunction::Contract((
strategy.clone(),
Symbol::new(&e, "deposit"),
vec![
&e,
starting_balance.into_val(&e),
user_3.to_val(),
user_2.to_val(),
]
)),
sub_invocations: std::vec![AuthorizedInvocation {
Expand All @@ -80,7 +78,7 @@ fn success() {
Symbol::new(&e, "transfer"),
vec![
&e,
user_3.to_val(),
user_2.to_val(),
strategy.to_val(),
starting_balance.into_val(&e)
]
Expand All @@ -91,27 +89,27 @@ fn success() {
)
);

strategy_client.deposit(&starting_balance, &user_4);
strategy_client.deposit(&starting_balance, &user_3);

// verify deposit (pool b_rate still 1 as no time has passed)
assert_eq!(usdc_client.balance(&user_2), 0);
assert_eq!(usdc_client.balance(&user_3), 0);
assert_eq!(usdc_client.balance(&user_4), 0);
assert_eq!(strategy_client.balance(&user_2), starting_balance);
assert_eq!(strategy_client.balance(&user_3), starting_balance);
assert_eq!(strategy_client.balance(&user_4), starting_balance);
assert_eq!(
usdc_client.balance(&pool),
pool_usdc_balace_start + starting_balance * 2
);
let vault_positions = pool_client.get_positions(&strategy);
assert_eq!(vault_positions.supply.get(0).unwrap(), starting_balance * 2);

// user_5 deposit directly into pool
// user_4 deposit directly into pool
let merry_starting_balance = 200_0000000;
usdc_client.mint(&user_5, &merry_starting_balance);
usdc_client.mint(&user_4, &merry_starting_balance);
pool_client.submit(
&user_5,
&user_5,
&user_5,
&user_4,
&user_4,
&user_4,
&vec![
&e,
Request {
Expand Down Expand Up @@ -145,18 +143,18 @@ fn success() {

/*
* Withdraw from pool
* -> withdraw all funds from pool for user_5
* -> withdraw (excluding dust) from blend strategy for user_3 and user_4
* -> withdraw all funds from pool for user_4
* -> withdraw (excluding dust) from blend strategy for user_2 and user_3
* -> verify a withdraw from an uninitialized vault fails
* -> verify a withdraw from an empty vault fails
* -> verify an over withdraw fails
*/

// withdraw all funds from pool for user_5
// withdraw all funds from pool for user_4
pool_client.submit(
&user_5,
&user_5,
&user_5,
&user_4,
&user_4,
&user_4,
&vec![
&e,
Request {
Expand All @@ -166,50 +164,50 @@ fn success() {
},
],
);
let user_5_final_balance = usdc_client.balance(&user_5);
let user_5_final_balance = usdc_client.balance(&user_4);
let user_5_profit = user_5_final_balance - merry_starting_balance;

// withdraw from blend strategy for user_3 and user_4
// they are expected to receive half of the profit of user_5
// withdraw from blend strategy for user_2 and user_3
// they are expected to receive half of the profit of user_4
let expected_user_4_profit = user_5_profit / 2;
let withdraw_amount = starting_balance + expected_user_4_profit;
// withdraw_amount = 100_0958904

// -> verify over withdraw fails
let result = strategy_client.try_withdraw(&(withdraw_amount + 100_000_000_0000000), &user_4);
let result = strategy_client.try_withdraw(&(withdraw_amount + 100_000_000_0000000), &user_3);
assert_eq!(result, Err(Ok(StrategyError::InvalidArgument))); // TODO: Check which is the one failing

strategy_client.withdraw(&withdraw_amount, &user_3);
strategy_client.withdraw(&withdraw_amount, &user_2);
// -> verify withdraw auth
assert_eq!(
e.auths()[0],
(
user_3.clone(),
user_2.clone(),
AuthorizedInvocation {
function: AuthorizedFunction::Contract((
strategy.clone(),
Symbol::new(&e, "withdraw"),
vec![
&e,
withdraw_amount.into_val(&e),
user_3.to_val(),
user_2.to_val(),
]
)),
sub_invocations: std::vec![]
}
)
);

strategy_client.withdraw(&withdraw_amount, &user_4);
strategy_client.withdraw(&withdraw_amount, &user_3);

// -> verify withdraw
assert_eq!(usdc_client.balance(&user_2), withdraw_amount);
assert_eq!(usdc_client.balance(&user_3), withdraw_amount);
assert_eq!(usdc_client.balance(&user_4), withdraw_amount);
assert_eq!(strategy_client.balance(&user_2), 0);
assert_eq!(strategy_client.balance(&user_3), 0);
assert_eq!(strategy_client.balance(&user_4), 0);

// -> verify withdraw from empty vault fails
let result = strategy_client.try_withdraw(&MIN_DUST, &user_4);
let result = strategy_client.try_withdraw(&MIN_DUST, &user_3);
assert_eq!(result, Err(Ok(StrategyError::InsufficientBalance)));

// TODO: Finish harvest testings, pending soroswap router setup with a blend token pair with the underlying asset
Expand Down

0 comments on commit 2d117b1

Please sign in to comment.