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

added liquidate and redeem (with protocol fee) #75

Merged
merged 7 commits into from
Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
added liquidated and redeem (with protocol fee)
  • Loading branch information
nope-finance committed Feb 27, 2022
commit 1ec27477cf8f75fb182601bc7ad6897f18b11ab0
88 changes: 88 additions & 0 deletions token-lending/program/src/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,36 @@ pub enum LendingInstruction {
/// Reserve config to update to
config: ReserveConfig,
},

// 17
/// Repay borrowed liquidity to a reserve to receive collateral at a discount from an unhealthy
/// obligation. Requires a refreshed obligation and reserves.
///
/// Accounts expected by this instruction:
///
/// 0. `[writable]` Source liquidity token account.
/// Minted by repay reserve liquidity mint.
/// $authority can transfer $liquidity_amount.
/// 1. `[writable]` Destination collateral token account.
/// Minted by withdraw reserve collateral mint.
/// 2. `[writable]` Destination liquidity token account.
/// 3. `[writable]` Repay reserve account - refreshed.
/// 4. `[writable]` Repay reserve liquidity supply SPL Token account.
/// 5. `[writable]` Withdraw reserve account - refreshed.
/// 6. `[writable]` Withdraw reserve collateral SPL Token mint.
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
/// 7. `[writable]` Withdraw reserve collateral supply SPL Token account.
/// 8. `[writable]` Withdraw reserve liquidity supply SPL Token account.
/// 9. `[writable]` Withdraw reserve liquidity fee receiver account.
/// 10 `[writable]` Obligation account - refreshed.
/// 11 `[]` Lending market account.
/// 12 `[]` Derived lending market authority.
/// 13 `[signer]` User transfer authority ($authority).
/// 14 `[]` Clock sysvar.
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
/// 15 `[]` Token program id.
LiquidateObligationAndRedeemReserveCollateral {
/// Amount of liquidity to repay - u64::MAX for up to 100% of borrowed amount
liquidity_amount: u64,
},
}

impl LendingInstruction {
Expand Down Expand Up @@ -514,6 +544,10 @@ impl LendingInstruction {
},
}
}
17 => {
let (liquidity_amount, _rest) = Self::unpack_u64(rest)?;
Self::LiquidateObligationAndRedeemReserveCollateral { liquidity_amount }
}
_ => {
msg!("Instruction cannot be unpacked");
return Err(LendingError::InstructionUnpackError.into());
Expand Down Expand Up @@ -692,6 +726,10 @@ impl LendingInstruction {
buf.extend_from_slice(&config.borrow_limit.to_le_bytes());
buf.extend_from_slice(&config.fee_receiver.to_bytes());
}
Self::LiquidateObligationAndRedeemReserveCollateral { liquidity_amount } => {
buf.push(17);
buf.extend_from_slice(&liquidity_amount.to_le_bytes());
}
}
buf
}
Expand Down Expand Up @@ -1216,3 +1254,53 @@ pub fn update_reserve_config(
data: LendingInstruction::UpdateReserveConfig { config }.pack(),
}
}

/// Creates a `LiquidateObligationAndRedeemReserveCollateral` instruction
#[allow(clippy::too_many_arguments)]
pub fn liquidate_obligation_and_redeem_reserve_collateral(
program_id: Pubkey,
liquidity_amount: u64,
source_liquidity_pubkey: Pubkey,
destination_collateral_pubkey: Pubkey,
destination_liquidity_pubkey: Pubkey,
repay_reserve_pubkey: Pubkey,
repay_reserve_liquidity_supply_pubkey: Pubkey,
withdraw_reserve_pubkey: Pubkey,
withdraw_reserve_collateral_mint_pubkey: Pubkey,
withdraw_reserve_collateral_supply_pubkey: Pubkey,
withdraw_reserve_liquidity_supply_pubkey: Pubkey,
withdraw_reserve_liquidity_fee_receiver_pubkey: Pubkey,
obligation_pubkey: Pubkey,
lending_market_pubkey: Pubkey,
user_transfer_authority_pubkey: Pubkey,
) -> Instruction {
let (lending_market_authority_pubkey, _bump_seed) = Pubkey::find_program_address(
&[&lending_market_pubkey.to_bytes()[..PUBKEY_BYTES]],
&program_id,
);
Instruction {
program_id,
accounts: vec![
AccountMeta::new(source_liquidity_pubkey, false),
AccountMeta::new(destination_collateral_pubkey, false),
AccountMeta::new(destination_liquidity_pubkey, false),
AccountMeta::new(repay_reserve_pubkey, false),
AccountMeta::new(repay_reserve_liquidity_supply_pubkey, false),
AccountMeta::new(withdraw_reserve_pubkey, false),
AccountMeta::new(withdraw_reserve_collateral_mint_pubkey, false),
AccountMeta::new(withdraw_reserve_collateral_supply_pubkey, false),
AccountMeta::new(withdraw_reserve_liquidity_supply_pubkey, false),
AccountMeta::new(withdraw_reserve_liquidity_fee_receiver_pubkey, false),
AccountMeta::new(obligation_pubkey, false),
AccountMeta::new_readonly(lending_market_pubkey, false),
AccountMeta::new_readonly(lending_market_authority_pubkey, false),
AccountMeta::new_readonly(user_transfer_authority_pubkey, true),
AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(spl_token::id(), false),
],
data: LendingInstruction::LiquidateObligationAndRedeemReserveCollateral {
liquidity_amount,
}
.pack(),
}
}
138 changes: 135 additions & 3 deletions token-lending/program/src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ pub fn process_instruction(
msg!("Instruction: UpdateReserveConfig");
process_update_reserve_config(program_id, config, accounts)
}
LendingInstruction::LiquidateObligationAndRedeemReserveCollateral { liquidity_amount } => {
msg!("Instruction: Liquidate Obligation and Redeem Reserve Collateral");
process_liquidate_obligation_and_redeem_reserve_collateral(
program_id,
liquidity_amount,
accounts,
)
}
}
}

Expand Down Expand Up @@ -637,7 +645,7 @@ fn _redeem_reserve_collateral<'a>(
user_transfer_authority_info: &AccountInfo<'a>,
clock: &Clock,
token_program_id: &AccountInfo<'a>,
) -> ProgramResult {
) -> Result<u64, ProgramError> {
let 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");
Expand Down Expand Up @@ -713,7 +721,7 @@ fn _redeem_reserve_collateral<'a>(
token_program: token_program_id.clone(),
})?;

Ok(())
Ok(liquidity_amount)
}

#[inline(never)] // avoid stack frame limit
Expand Down Expand Up @@ -1577,6 +1585,42 @@ fn process_liquidate_obligation(
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;

let _withdraw_collateral_amount = _liquidate_obligation(
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
program_id,
liquidity_amount,
source_liquidity_info,
destination_collateral_info,
repay_reserve_info,
repay_reserve_liquidity_supply_info,
withdraw_reserve_info,
withdraw_reserve_collateral_supply_info,
obligation_info,
lending_market_info,
lending_market_authority_info,
user_transfer_authority_info,
clock,
token_program_id,
)?;
Ok(())
}

#[allow(clippy::too_many_arguments)]
fn _liquidate_obligation<'a>(
program_id: &Pubkey,
liquidity_amount: u64,
source_liquidity_info: &AccountInfo<'a>,
destination_collateral_info: &AccountInfo<'a>,
repay_reserve_info: &AccountInfo<'a>,
repay_reserve_liquidity_supply_info: &AccountInfo<'a>,
withdraw_reserve_info: &AccountInfo<'a>,
withdraw_reserve_collateral_supply_info: &AccountInfo<'a>,
obligation_info: &AccountInfo<'a>,
lending_market_info: &AccountInfo<'a>,
lending_market_authority_info: &AccountInfo<'a>,
user_transfer_authority_info: &AccountInfo<'a>,
clock: &Clock,
token_program_id: &AccountInfo<'a>,
) -> Result<u64, ProgramError> {
let 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");
Expand Down Expand Up @@ -1741,6 +1785,93 @@ fn process_liquidate_obligation(
token_program: token_program_id.clone(),
})?;

Ok(withdraw_amount)
}

#[inline(never)] // avoid stack frame limit
fn process_liquidate_obligation_and_redeem_reserve_collateral(
program_id: &Pubkey,
liquidity_amount: u64,
accounts: &[AccountInfo],
) -> ProgramResult {
if liquidity_amount == 0 {
msg!("Liquidity amount provided cannot be zero");
return Err(LendingError::InvalidAmount.into());
}

let account_info_iter = &mut accounts.iter();
let source_liquidity_info = next_account_info(account_info_iter)?;
let destination_collateral_info = next_account_info(account_info_iter)?;
let destination_liquidity_info = next_account_info(account_info_iter)?;
let repay_reserve_info = next_account_info(account_info_iter)?;
let repay_reserve_liquidity_supply_info = next_account_info(account_info_iter)?;
let withdraw_reserve_info = next_account_info(account_info_iter)?;
let withdraw_reserve_collateral_mint_info = next_account_info(account_info_iter)?;
let withdraw_reserve_collateral_supply_info = next_account_info(account_info_iter)?;
let withdraw_reserve_liquidity_supply_info = next_account_info(account_info_iter)?;
let withdraw_reserve_liquidity_fee_receiver_info = next_account_info(account_info_iter)?;
let obligation_info = next_account_info(account_info_iter)?;
let lending_market_info = next_account_info(account_info_iter)?;
let lending_market_authority_info = next_account_info(account_info_iter)?;
let user_transfer_authority_info = next_account_info(account_info_iter)?;
let clock = &Clock::from_account_info(next_account_info(account_info_iter)?)?;
let token_program_id = next_account_info(account_info_iter)?;

let withdraw_collateral_amount = _liquidate_obligation(
program_id,
liquidity_amount,
source_liquidity_info,
destination_collateral_info,
repay_reserve_info,
repay_reserve_liquidity_supply_info,
withdraw_reserve_info,
withdraw_reserve_collateral_supply_info,
obligation_info,
lending_market_info,
lending_market_authority_info,
user_transfer_authority_info,
clock,
token_program_id,
)?;

_refresh_reserve_interest(program_id, withdraw_reserve_info, clock)?;
let withdraw_liquidity_amount = _redeem_reserve_collateral(
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
program_id,
withdraw_collateral_amount,
destination_collateral_info,
Copy link

Choose a reason for hiding this comment

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

Rather than withdrawing collateral during _liquidate_obligation and then burning the collateral in _redeem_reserve_collateral, you could save a CPI by just directly burning from the reserve's collateral supply. And on this subject, there is some other redundant work done in both _liquidate_obligation and _redeem_reserve_collateral (notably the PDA creation) that could be saved with some more work as well.

Copy link
Member Author

Choose a reason for hiding this comment

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

yeh I think the reasoning i had for doing this way was to be more modular and write as little new math/logic code as possible not optimize compute (beyond sticking to < 200k ish). but perhaps there is some level of optimization that could be added.

Copy link

Choose a reason for hiding this comment

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

Makes sense, optimizations can easily introduce critical bugs as well, so there's a trade-off

destination_liquidity_info,
withdraw_reserve_info,
withdraw_reserve_collateral_mint_info,
withdraw_reserve_liquidity_supply_info,
lending_market_info,
lending_market_authority_info,
user_transfer_authority_info,
clock,
token_program_id,
)?;
let mut withdraw_reserve = Reserve::unpack(&withdraw_reserve_info.data.borrow())?;
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
if &withdraw_reserve.config.fee_receiver != withdraw_reserve_liquidity_fee_receiver_info.key {
msg!("Withdraw reserve liquidity fee receiver does not match the reserve liquidity fee receiver provided");
return Err(LendingError::InvalidAccountInput.into());
}
let protocol_fee =
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
withdraw_reserve.calculate_protocol_liquidation_fee(withdraw_liquidity_amount)?;

spl_token_transfer(TokenTransferParams {
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
source: destination_liquidity_info.clone(),
destination: withdraw_reserve_liquidity_fee_receiver_info.clone(),
amount: protocol_fee,
authority: user_transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program_id.clone(),
})?;

withdraw_reserve.last_update.mark_stale();
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
Reserve::pack(
nope-finance marked this conversation as resolved.
Show resolved Hide resolved
withdraw_reserve,
&mut withdraw_reserve_info.data.borrow_mut(),
)?;

Ok(())
}

Expand Down Expand Up @@ -1971,7 +2102,8 @@ fn process_withdraw_obligation_collateral_and_redeem_reserve_liquidity(
user_transfer_authority_info,
clock,
token_program_id,
)
)?;
Ok(())
}

#[inline(never)] // avoid stack frame limit
Expand Down
14 changes: 14 additions & 0 deletions token-lending/program/src/state/reserve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,20 @@ impl Reserve {
withdraw_amount,
})
}

/// Calculate protocol cut of liquidation bonus
pub fn calculate_protocol_liquidation_fee(
&self,
amount_liquidated: u64,
) -> Result<u64, ProgramError> {
let bonus_rate = Rate::from_percent(self.config.liquidation_bonus).try_add(Rate::one())?;
let amount_liquidated_wads = Decimal::from(amount_liquidated);

let bonus = amount_liquidated_wads.try_sub(amount_liquidated_wads.try_div(bonus_rate)?)?;

let protocol_fee = bonus.try_mul(Rate::from_percent(30))?.try_ceil_u64()?;
Ok(protocol_fee)
}
}

/// Initialize a reserve
Expand Down