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

0xripleys outflow limits #125

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions token-lending/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use lending_state::SolendState;
use solana_client::rpc_config::RpcSendTransactionConfig;
use solana_sdk::{commitment_config::CommitmentLevel, compute_budget::ComputeBudgetInstruction};
use solend_program::state::SLOTS_PER_YEAR;
use solend_sdk::{
instruction::{
liquidate_obligation_and_redeem_reserve_collateral, redeem_reserve_collateral,
Expand Down Expand Up @@ -871,6 +872,9 @@ fn main() {
fee_receiver: liquidity_fee_receiver_keypair.pubkey(),
protocol_liquidation_fee,
protocol_take_rate,
// FIXME: add support for rate limiter params
window_duration: SLOTS_PER_YEAR / 365,
max_outflow: u64::MAX,
},
source_liquidity_pubkey,
source_liquidity_owner_keypair,
Expand Down
86 changes: 78 additions & 8 deletions token-lending/program/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use crate::{
state::{
CalculateBorrowResult, CalculateLiquidationResult, CalculateRepayResult,
InitLendingMarketParams, InitObligationParams, InitReserveParams, LendingMarket,
NewReserveCollateralParams, NewReserveLiquidityParams, Obligation, Reserve,
ReserveCollateral, ReserveConfig, ReserveLiquidity,
LendingMarketConfig, NewReserveCollateralParams, NewReserveLiquidityParams, Obligation,
Reserve, ReserveCollateral, ReserveConfig, ReserveLiquidity,
},
};
use pyth_sdk_solana::{self, state::ProductAccount};
Expand All @@ -30,6 +30,7 @@ use solana_program::{
Sysvar,
},
};
use solend_sdk::state::RateLimiter;
use solend_sdk::{switchboard_v2_devnet, switchboard_v2_mainnet};
use spl_token::state::Mint;
use std::{cmp::min, result::Result};
Expand All @@ -53,9 +54,9 @@ pub fn process_instruction(
msg!("Instruction: Init Lending Market");
process_init_lending_market(program_id, owner, quote_currency, accounts)
}
LendingInstruction::SetLendingMarketOwner { new_owner } => {
LendingInstruction::SetLendingMarketOwnerAndConfig { new_owner, config } => {
msg!("Instruction: Set Lending Market Owner");
process_set_lending_market_owner(program_id, new_owner, accounts)
process_set_lending_market_owner_and_config(program_id, new_owner, config, accounts)
}
LendingInstruction::InitReserve {
liquidity_amount,
Expand Down Expand Up @@ -190,16 +191,18 @@ fn process_init_lending_market(
token_program_id: *token_program_id.key,
oracle_program_id: *oracle_program_id.key,
switchboard_oracle_program_id: *switchboard_oracle_program_id.key,
current_slot: Clock::get()?.slot,
});
LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;

Ok(())
}

#[inline(never)] // avoid stack frame limit
fn process_set_lending_market_owner(
fn process_set_lending_market_owner_and_config(
program_id: &Pubkey,
new_owner: Pubkey,
config: LendingMarketConfig,
accounts: &[AccountInfo],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
Expand All @@ -221,6 +224,19 @@ fn process_set_lending_market_owner(
}

lending_market.owner = new_owner;
if (Decimal::from(config.max_outflow), config.window_duration)
!= (
lending_market.rate_limiter.max_outflow,
lending_market.rate_limiter.window_duration,
)
{
lending_market.rate_limiter = RateLimiter::new(
Decimal::from(config.max_outflow),
config.window_duration,
Clock::get()?.slot,
);
}

LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;

Ok(())
Expand Down Expand Up @@ -659,7 +675,6 @@ fn process_redeem_reserve_collateral(
}
let token_program_id = next_account_info(account_info_iter)?;

_refresh_reserve_interest(program_id, reserve_info, clock)?;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since the lending market rate limiter is denominated in usd, we need an up-to-date price so i removed this function call

_redeem_reserve_collateral(
program_id,
collateral_amount,
Expand All @@ -673,6 +688,7 @@ fn process_redeem_reserve_collateral(
user_transfer_authority_info,
clock,
token_program_id,
true,
)?;
let mut reserve = Reserve::unpack(&reserve_info.data.borrow())?;
reserve.last_update.mark_stale();
Expand All @@ -695,8 +711,9 @@ fn _redeem_reserve_collateral<'a>(
user_transfer_authority_info: &AccountInfo<'a>,
clock: &Clock,
token_program_id: &AccountInfo<'a>,
check_rate_limits: bool,
) -> Result<u64, ProgramError> {
let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
let mut lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
Expand Down Expand Up @@ -750,8 +767,33 @@ fn _redeem_reserve_collateral<'a>(
}

let liquidity_amount = reserve.redeem_collateral(collateral_amount)?;

if check_rate_limits {
let market_value = reserve
.liquidity
.market_price
.try_mul(Decimal::from(liquidity_amount))?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try_div(10**reserve.liquidity.mint_decimals)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe call it redemption_value


lending_market
.rate_limiter
.update(clock.slot, market_value)
.map_err(|err| {
msg!("Market outflow limit exceeded! Please try again later.");
err
})?;

reserve
.rate_limiter
.update(clock.slot, Decimal::from(liquidity_amount))
.map_err(|err| {
msg!("Reserve outflow limit exceeded! Please try again later.");
err
})?;
}

reserve.last_update.mark_stale();
Reserve::pack(reserve, &mut reserve_info.data.borrow_mut())?;
LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;

spl_token_burn(TokenBurnParams {
mint: reserve_collateral_mint_info.clone(),
Expand Down Expand Up @@ -1359,7 +1401,7 @@ fn process_borrow_obligation_liquidity(
}
let token_program_id = next_account_info(account_info_iter)?;

let lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
let mut lending_market = LendingMarket::unpack(&lending_market_info.data.borrow())?;
if lending_market_info.owner != program_id {
msg!("Lending market provided is not owned by the lending program");
return Err(LendingError::InvalidAccountOwner.into());
Expand Down Expand Up @@ -1477,6 +1519,32 @@ fn process_borrow_obligation_liquidity(

let cumulative_borrow_rate_wads = borrow_reserve.liquidity.cumulative_borrow_rate_wads;

// check outflow rate limits
{
let market_value = borrow_reserve
.liquidity
.market_price
.try_mul(borrow_amount)?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same divide needed


lending_market
.rate_limiter
.update(clock.slot, market_value)
.map_err(|err| {
msg!("Market outflow limit exceeded! Please try again later.");
err
})?;

borrow_reserve
.rate_limiter
.update(clock.slot, borrow_amount)
.map_err(|err| {
msg!("Reserve outflow limit exceeded! Please try again later");
err
})?;
}

LendingMarket::pack(lending_market, &mut lending_market_info.data.borrow_mut())?;

borrow_reserve.liquidity.borrow(borrow_amount)?;
borrow_reserve.last_update.mark_stale();
Reserve::pack(borrow_reserve, &mut borrow_reserve_info.data.borrow_mut())?;
Expand Down Expand Up @@ -1885,6 +1953,7 @@ fn process_liquidate_obligation_and_redeem_reserve_collateral(
user_transfer_authority_info,
clock,
token_program_id,
false,
)?;
let withdraw_reserve = Reserve::unpack(&withdraw_reserve_info.data.borrow())?;
if &withdraw_reserve.config.fee_receiver != withdraw_reserve_liquidity_fee_receiver_info.key
Expand Down Expand Up @@ -1959,6 +2028,7 @@ fn process_withdraw_obligation_collateral_and_redeem_reserve_liquidity(
user_transfer_authority_info,
clock,
token_program_id,
true,
)?;
Ok(())
}
Expand Down
145 changes: 128 additions & 17 deletions token-lending/program/tests/borrow_obligation_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,26 +166,49 @@ async fn test_success() {
assert_eq!(mint_supply_changes, HashSet::new());

// check program state
let lending_market_post = test.load_account(lending_market.pubkey).await;
assert_eq!(lending_market, lending_market_post);

let wsol_reserve_post = test.load_account::<Reserve>(wsol_reserve.pubkey).await;
let lending_market_post = test
.load_account::<LendingMarket>(lending_market.pubkey)
.await;
assert_eq!(
wsol_reserve_post.account,
Reserve {
last_update: LastUpdate {
slot: 1000,
stale: true
},
liquidity: ReserveLiquidity {
available_amount: 6 * LAMPORTS_PER_SOL - (4 * LAMPORTS_PER_SOL + 400),
borrowed_amount_wads: Decimal::from(4 * LAMPORTS_PER_SOL + 400),
..wsol_reserve.account.liquidity
lending_market_post.account,
LendingMarket {
rate_limiter: {
let mut rate_limiter = lending_market.account.rate_limiter;
rate_limiter
.update(1000, Decimal::from(10 * (4 * LAMPORTS_PER_SOL + 400)))
.unwrap();
rate_limiter
},
..wsol_reserve.account
..lending_market.account
}
);

let wsol_reserve_post = test.load_account::<Reserve>(wsol_reserve.pubkey).await;
let expected_wsol_reserve_post = Reserve {
last_update: LastUpdate {
slot: 1000,
stale: true,
},
"{:#?}",
wsol_reserve_post
liquidity: ReserveLiquidity {
available_amount: 6 * LAMPORTS_PER_SOL - (4 * LAMPORTS_PER_SOL + 400),
borrowed_amount_wads: Decimal::from(4 * LAMPORTS_PER_SOL + 400),
..wsol_reserve.account.liquidity
},
rate_limiter: {
let mut rate_limiter = wsol_reserve.account.rate_limiter;
rate_limiter
.update(1000, Decimal::from(4 * LAMPORTS_PER_SOL + 400))
.unwrap();

rate_limiter
},
..wsol_reserve.account
};

assert_eq!(
wsol_reserve_post.account, expected_wsol_reserve_post,
"{:#?} {:#?}",
wsol_reserve_post, expected_wsol_reserve_post
);

let obligation_post = test.load_account::<Obligation>(obligation.pubkey).await;
Expand Down Expand Up @@ -315,3 +338,91 @@ async fn test_fail_borrow_over_reserve_borrow_limit() {
)
);
}

#[tokio::test]
async fn test_fail_reserve_borrow_rate_limit_exceeded() {
let (mut test, lending_market, _, wsol_reserve, user, obligation, host_fee_receiver) =
setup(&ReserveConfig {
// ie, within 10 slots, the maximum outflow is 1 SOL
window_duration: 10,
max_outflow: LAMPORTS_PER_SOL,
..test_reserve_config()
})
.await;

// borrow maximum amount
lending_market
.borrow_obligation_liquidity(
&mut test,
&wsol_reserve,
&obligation,
&user,
&host_fee_receiver.get_account(&wsol_mint::id()).unwrap(),
LAMPORTS_PER_SOL,
)
.await
.unwrap();

// for the next 10 slots, we shouldn't be able to borrow anything.
let cur_slot = test.get_clock().await.slot;
for _ in cur_slot..(cur_slot + 10) {
let res = lending_market
.borrow_obligation_liquidity(
&mut test,
&wsol_reserve,
&obligation,
&user,
&host_fee_receiver.get_account(&wsol_mint::id()).unwrap(),
1,
)
.await
.err()
.unwrap()
.unwrap();

assert_eq!(
res,
TransactionError::InstructionError(
3,
InstructionError::Custom(LendingError::OutflowRateLimitExceeded as u32)
)
);

test.advance_clock_by_slots(1).await;
}

// after 10 slots, we should be able to at borrow most 0.1 SOL
let res = lending_market
.borrow_obligation_liquidity(
&mut test,
&wsol_reserve,
&obligation,
&user,
&host_fee_receiver.get_account(&wsol_mint::id()).unwrap(),
LAMPORTS_PER_SOL / 10 + 1,
)
.await
.err()
.unwrap()
.unwrap();

assert_eq!(
res,
TransactionError::InstructionError(
3,
InstructionError::Custom(LendingError::OutflowRateLimitExceeded as u32)
)
);

lending_market
.borrow_obligation_liquidity(
&mut test,
&wsol_reserve,
&obligation,
&user,
&host_fee_receiver.get_account(&wsol_mint::id()).unwrap(),
LAMPORTS_PER_SOL / 10,
)
.await
.unwrap();
}
Loading