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

feat: add force_void instruction #239

Merged
merged 9 commits into from
Oct 21, 2024
Merged
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
38 changes: 38 additions & 0 deletions programs/monaco_protocol/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,44 @@ pub struct VoidMarket<'info> {
pub authorised_operators: Account<'info, AuthorisedOperators>,
}

#[derive(Accounts)]
pub struct ForceVoidMarket<'info> {
#[account(mut)]
pub market: Account<'info, Market>,
#[account(
mut,
has_one = market @ CoreError::VoidMarketMismatch,
)]
pub market_matching_queue: Option<Account<'info, MarketMatchingQueue>>,
#[account(
has_one = market @ CoreError::VoidMarketMismatch,
)]
pub order_request_queue: Option<Account<'info, MarketOrderRequestQueue>>,

#[account(mut)]
pub market_operator: Signer<'info>,
#[account(seeds = [b"authorised_operators".as_ref(), b"MARKET".as_ref()], bump)]
pub authorised_operators: Account<'info, AuthorisedOperators>,
}

#[derive(Accounts)]
pub struct ForceUnsettledCount<'info> {
#[account(mut)]
pub market: Account<'info, Market>,
#[account(
token::mint = market.mint_account,
token::authority = market_escrow,
seeds = [b"escrow".as_ref(), market.key().as_ref()],
bump,
)]
pub market_escrow: Account<'info, TokenAccount>,

#[account(mut)]
pub market_operator: Signer<'info>,
#[account(seeds = [b"authorised_operators".as_ref(), b"MARKET".as_ref()], bump)]
pub authorised_operators: Account<'info, AuthorisedOperators>,
}

#[derive(Accounts)]
pub struct OpenMarket<'info> {
#[account(mut)]
Expand Down
3 changes: 3 additions & 0 deletions programs/monaco_protocol/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@ pub enum CoreError {
#[msg("Market: cannot recreate market, provided mint does not match existing market")]
MarketMintMismatch,

#[msg("Market: attempted to decrease market unsettled count with non-zero escrow")]
MarketUnsettledCountDecreaseWithNonZeroEscrow,

/*
Close Account
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,63 @@ pub fn void(
Ok(())
}

pub fn force_void(
market: &mut Market,
void_time: UnixTimestamp,
order_request_queue: &Option<MarketOrderRequestQueue>,
) -> Result<()> {
require!(
Initializing.eq(&market.market_status) || Open.eq(&market.market_status),
CoreError::VoidMarketNotInitializingOrOpen
);

if market.market_status != Initializing {
require!(
order_request_queue.is_some(),
CoreError::VoidMarketRequestQueueNotProvided
);
require!(
order_request_queue
.as_ref()
.unwrap()
.order_requests
.is_empty(),
CoreError::OrderRequestQueueIsNotEmpty
);
}

market.market_settle_timestamp = Option::from(void_time);
market.market_status = ReadyToVoid;
Ok(())
}

pub fn force_unsettled_count(
market: &mut Market,
escrow_amount: u64,
new_count: u32,
) -> Result<()> {
require!(
ReadyToVoid.eq(&market.market_status),
CoreError::MarketInvalidStatus
);

let old_count = market.unsettled_accounts_count;
if old_count == new_count {
return Ok(());
}

if new_count < old_count {
require!(
escrow_amount == 0,
CoreError::MarketUnsettledCountDecreaseWithNonZeroEscrow
);
}

market.unsettled_accounts_count = new_count;

Ok(())
}

pub fn complete_void(market: &mut Market) -> Result<()> {
require!(
ReadyToVoid.eq(&market.market_status),
Expand Down Expand Up @@ -1034,3 +1091,100 @@ mod void_market_tests {
assert_eq!(expected_error, result)
}
}

#[cfg(test)]
mod force_void_tests {
use crate::error::CoreError;
use crate::instructions::market::force_void;
use crate::state::market_account::{mock_market, MarketStatus};
use crate::state::market_order_request_queue::{mock_order_request_queue, OrderRequest};
use anchor_lang::error;
use solana_program::pubkey::Pubkey;

#[test]
fn force_void_happy_path() {
let market_pk = Pubkey::new_unique();
let mut market = mock_market(MarketStatus::Open);
let order_request_queue = mock_order_request_queue(market_pk);

let result = force_void(&mut market, 1665483869, &Some(order_request_queue));

assert!(result.is_ok());
assert_eq!(MarketStatus::ReadyToVoid, market.market_status);
}

#[test]
fn force_void_incorrect_market_status() {
let market_pk = Pubkey::new_unique();
let mut market = mock_market(MarketStatus::Settled);
let order_request_queue = mock_order_request_queue(market_pk);

let result = force_void(&mut market, 1665483869, &Some(order_request_queue));

assert!(result.is_err());
let expected_error = Err(error!(CoreError::VoidMarketNotInitializingOrOpen));
assert_eq!(expected_error, result)
}

#[test]
fn force_void_request_queue_not_empty() {
let market_pk = Pubkey::new_unique();
let mut market = mock_market(MarketStatus::Open);

let mut order_request_queue = mock_order_request_queue(market_pk);
order_request_queue
.order_requests
.enqueue(OrderRequest::new_unique());

let result = force_void(&mut market, 1665483869, &Some(order_request_queue));

assert!(result.is_err());
let expected_error = Err(error!(CoreError::OrderRequestQueueIsNotEmpty));
assert_eq!(expected_error, result)
}
}

#[cfg(test)]
mod force_unsettled_count_tests {
use crate::error::CoreError;
use crate::instructions::market::force_unsettled_count;
use crate::state::market_account::{mock_market, MarketStatus};
use anchor_lang::error;

#[test]
fn force_unsettled_count_happy_path() {
let mut market = mock_market(MarketStatus::ReadyToVoid);
market.unsettled_accounts_count = 0;

let result = force_unsettled_count(&mut market, 100, 1);

assert!(result.is_ok());
assert_eq!(1, market.unsettled_accounts_count)
}

#[test]
fn force_unsettled_count_incorrect_market_status() {
let mut market = mock_market(MarketStatus::Open);
market.unsettled_accounts_count = 0;

let result = force_unsettled_count(&mut market, 100, 1);

assert!(result.is_err());
let expected_error = Err(error!(CoreError::MarketInvalidStatus));
assert_eq!(expected_error, result)
}

#[test]
fn force_unsettled_count_decrease_with_non_zero_escrow() {
let mut market = mock_market(MarketStatus::ReadyToVoid);
market.unsettled_accounts_count = 1;

let result = force_unsettled_count(&mut market, 100, 0);

assert!(result.is_err());
let expected_error = Err(error!(
CoreError::MarketUnsettledCountDecreaseWithNonZeroEscrow
));
assert_eq!(expected_error, result)
}
}
52 changes: 51 additions & 1 deletion programs/monaco_protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::instructions::transfer;
use crate::instructions::verify_operator_authority;
use crate::state::market_account::{Market, MarketOrderBehaviour};
use crate::state::market_liquidities::LiquiditySource;
use crate::state::market_matching_queue_account::MarketMatchingQueue;
use crate::state::market_order_request_queue::{MarketOrderRequestQueue, OrderRequestData};
use crate::state::market_position_account::MarketPosition;
use crate::state::operator_account::AuthorisedOperators;
Expand All @@ -32,7 +33,6 @@ pub mod monaco_protocol {
use super::*;
use crate::instructions::current_timestamp;
use crate::state::market_liquidities::LiquiditySource;
use crate::state::market_matching_queue_account::MarketMatchingQueue;

pub const PRICE_SCALE: u8 = 3_u8;
pub const SEED_SEPARATOR_CHAR: char = '␞';
Expand Down Expand Up @@ -680,6 +680,56 @@ pub mod monaco_protocol {
)
}

pub fn force_void_market(ctx: Context<ForceVoidMarket>) -> Result<()> {
verify_operator_authority(
ctx.accounts.market_operator.key,
&ctx.accounts.authorised_operators,
)?;
verify_market_authority(
ctx.accounts.market_operator.key,
&ctx.accounts.market.authority,
)?;

let void_time = current_timestamp();
instructions::market::force_void(
&mut ctx.accounts.market,
void_time,
&ctx.accounts
.order_request_queue
.clone()
.map(|queue: Account<MarketOrderRequestQueue>| queue.into_inner()),
)?;

// clear matching queue
if let Some(ref mut _queue) = ctx.accounts.market_matching_queue {
ctx.accounts
.market_matching_queue
.as_mut()
.unwrap()
.matches
.clear();
}

Ok(())
}

pub fn force_unsettled_count(ctx: Context<ForceUnsettledCount>, new_count: u32) -> Result<()> {
verify_operator_authority(
ctx.accounts.market_operator.key,
&ctx.accounts.authorised_operators,
)?;
verify_market_authority(
ctx.accounts.market_operator.key,
&ctx.accounts.market.authority,
)?;

instructions::market::force_unsettled_count(
&mut ctx.accounts.market,
ctx.accounts.market_escrow.amount,
new_count,
)
}

pub fn complete_market_void(ctx: Context<CompleteMarketVoid>) -> Result<()> {
instructions::market::complete_void(&mut ctx.accounts.market)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ impl MatchingQueue {
}
clone
}

pub fn clear(&mut self) {
self.front = 0;
self.len = 0;
self.empty = true;
}
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, Debug, Default)]
Expand Down Expand Up @@ -322,4 +328,17 @@ mod tests_matching_queue {
queue.peek_mut().unwrap().stake = 10;
assert_eq!(10, queue.peek().unwrap().stake);
}

#[test]
fn test_clear() {
let mut queue = MatchingQueue::new(3);
queue.enqueue(OrderMatch::default());
queue.enqueue(OrderMatch::default());
assert_eq!(2, queue.len());

queue.clear();
assert_eq!(0, queue.len());
assert_eq!(0, queue.front);
assert_eq!(0, queue.back());
}
}
Loading