Skip to content

Commit

Permalink
Add lock collateral records
Browse files Browse the repository at this point in the history
  • Loading branch information
EquilateralDelta committed Dec 6, 2023
1 parent 6f1cbfc commit bb11a0e
Show file tree
Hide file tree
Showing 10 changed files with 152 additions and 31 deletions.
1 change: 1 addition & 0 deletions hxro-print-trade-provider/program/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use dex::utils::numeric::Fractional;

pub const CONFIG_SEED: &str = "config";
pub const OPERATOR_SEED: &str = "operator";
pub const LOCKED_COLLATERAL_RECORD_SEED: &str = "locked_collateral_record";

pub const MAX_PRODUCTS_PER_TRADE: usize = 6;
pub const EXPECTED_DECIMALS: u8 = 9;
Expand Down
2 changes: 2 additions & 0 deletions hxro-print-trade-provider/program/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@ pub enum HxroPrintTradeProviderError {
InvalidPrintTradeAddress,
#[msg("Invalid print trade parameters")]
InvalidPrintTradeParams,
#[msg("Only a lock record creator can remove it")]
NotALockCreator,
}
18 changes: 9 additions & 9 deletions hxro-print-trade-provider/program/src/helpers/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use agnostic_orderbook::state::Side;
use dex::utils::numeric::Fractional;
use rfq::state::{AuthoritySide, Response, Rfq};

use crate::state::ParsedLegData;
use crate::state::{FractionalCopy, ParsedLegData, ProductInfo};

use super::common::{get_leg_instrument_type, parse_leg_data};

Expand All @@ -15,24 +15,24 @@ pub fn to_hxro_side(side: AuthoritySide) -> Side {
}
}

pub struct ProductInfo {
pub product_index: u64,
pub size: Fractional,
}

pub fn to_hxro_product(rfq: &Rfq, response: &Response, leg_index: u8) -> Result<ProductInfo> {
pub fn to_hxro_product(
perspective: AuthoritySide,
rfq: &Rfq,
response: &Response,
leg_index: u8,
) -> Result<ProductInfo> {
let leg = &rfq.legs[leg_index as usize];
let instrument_type = get_leg_instrument_type(leg)?;
let (_, ParsedLegData { product_index }) = parse_leg_data(leg, instrument_type)?;

let mut amount = response.get_leg_amount_to_transfer(&rfq, leg_index) as i64;
if response.get_leg_assets_receiver(rfq, leg_index) == AuthoritySide::Maker {
if response.get_leg_assets_receiver(rfq, leg_index) == perspective.inverse() {
amount = -amount;
}

let result = ProductInfo {
product_index: product_index as u64,
size: Fractional {
size: FractionalCopy {
m: amount,
exp: leg.amount_decimals as u64,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ use dex::{cpi::accounts::InitializePrintTrade, state::print_trade::PrintTradePro
use rfq::state::AuthoritySide;

use crate::constants::OPERATOR_SEED;
use crate::state::ProductInfo;
use crate::{
constants::{OPERATOR_COUNTERPARTY_FEE_PROPORTION, OPERATOR_CREATOR_FEE_PROPORTION},
PreparePrintTradeAccounts,
};

use super::conversions::to_hxro_price;
use super::conversions::to_hxro_product;
use super::conversions::to_hxro_side;
use super::conversions::{to_hxro_price, ProductInfo};

pub fn initialize_print_trade<'info>(
ctx: &Context<'_, '_, '_, 'info, PreparePrintTradeAccounts<'info>>,
Expand Down Expand Up @@ -43,10 +44,10 @@ pub fn initialize_print_trade<'info>(
let ProductInfo {
product_index,
size,
} = to_hxro_product(rfq, response, i as u8)?;
} = to_hxro_product(AuthoritySide::Taker, rfq, response, i as u8)?;
products[i] = PrintTradeProductIndex {
product_index: product_index as usize,
size,
size: size.into(),
};
}
let params = InitializePrintTradeParams {
Expand Down
1 change: 1 addition & 0 deletions hxro-print-trade-provider/program/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod initialize_trader_risk_group;
mod validation;

pub use close_print_trade::*;
pub use conversions::*;
pub use create_print_trade::*;
pub use execute_print_trade::*;
pub use initialize_trader_risk_group::*;
Expand Down
48 changes: 45 additions & 3 deletions hxro-print-trade-provider/program/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use anchor_lang::prelude::*;
use constants::{CONFIG_SEED, OPERATOR_SEED};
use constants::{CONFIG_SEED, LOCKED_COLLATERAL_RECORD_SEED, OPERATOR_SEED};
use dex::state::market_product_group::MarketProductGroup;
use dex::state::print_trade::{PrintTrade, PrintTradeExecutionOutput};
use dex::{program::Dex, state::trader_risk_group::TraderRiskGroup};
use rfq::interfaces::print_trade_provider::SettlementResult;
use rfq::state::{ProtocolState, Response, Rfq};
use state::Config;
use state::{Config, LockedCollateralRecord, ProductInfo};

// use dex_cpi::instruction::*;

use errors::HxroPrintTradeProviderError;
use helpers::{
close_print_trade, execute_print_trade, initialize_print_trade, initialize_trader_risk_group,
validate_print_trade_accounts, ValidationInput,
to_hxro_product, validate_print_trade_accounts, ValidationInput,
};
use state::AuthoritySideDuplicate;

Expand All @@ -31,6 +31,8 @@ declare_id!("GyRW7qvzx6UTVW9DkQGMy5f1rp9XK2x53FvWSjUUF7BJ");

#[program]
pub mod hxro_print_trade_provider {
use crate::state::FractionalCopy;

use super::*;

pub fn initialize_config(
Expand All @@ -52,6 +54,12 @@ pub mod hxro_print_trade_provider {
initialize_trader_risk_group(ctx)
}

pub fn remove_locked_collateral_record(
_ctx: Context<RemoveLockedCollateralRecord>,
) -> Result<()> {
Ok(())
}

pub fn validate_print_trade(ctx: Context<ValidatePrintTradeAccounts>) -> Result<()> {
let ValidatePrintTradeAccounts {
rfq,
Expand Down Expand Up @@ -152,6 +160,22 @@ pub mod hxro_print_trade_provider {
} else {
initialize_print_trade(&ctx, authority_side.into())?;
}

let mut locks = [ProductInfo {
product_index: 0,
size: FractionalCopy { m: 0, exp: 0 },
}; 6];
for i in 0..rfq.legs.len() {
locks[i] = to_hxro_product(authority_side.into(), rfq, response, i as u8)?;
}
ctx.accounts
.locked_collateral_record
.set_inner(LockedCollateralRecord {
user: user.key(),
response: response.key(),
locks,
});

Ok(())
}

Expand Down Expand Up @@ -245,6 +269,15 @@ pub struct ModifyConfigAccounts<'info> {
pub config: Account<'info, Config>,
}

#[derive(Accounts)]
pub struct RemoveLockedCollateralRecord<'info> {
#[account(mut)]
pub user: Signer<'info>,

#[account(mut, close=user, constraint = locked_collateral_record.user == user.key() @ HxroPrintTradeProviderError::NotALockCreator)]
pub locked_collateral_record: Account<'info, LockedCollateralRecord>,
}

#[derive(Accounts)]
pub struct InitializeOperatorTraderRiskGroupAccounts<'info> {
#[account(mut, constraint = protocol.authority == authority.key() @ HxroPrintTradeProviderError::NotAProtocolAuthority)]
Expand Down Expand Up @@ -310,13 +343,22 @@ pub struct PreparePrintTradeAccounts<'info> {
pub rfq: Box<Account<'info, Rfq>>,
pub response: Box<Account<'info, Response>>,

#[account(
init,
payer = user,
seeds = [LOCKED_COLLATERAL_RECORD_SEED.as_bytes(), user.key().as_ref(), response.key().as_ref()],
space = 8 + LockedCollateralRecord::INIT_SPACE,
bump
)]
pub locked_collateral_record: Account<'info, LockedCollateralRecord>,
/// CHECK PDA account
#[account(seeds = [OPERATOR_SEED.as_bytes()], bump)]
pub operator: UncheckedAccount<'info>,
pub config: Account<'info, Config>,
pub dex: Program<'info, Dex>,
#[account(constraint = config.valid_mpg == market_product_group.key() @ HxroPrintTradeProviderError::NotAValidatedMpg)]
pub market_product_group: AccountLoader<'info, MarketProductGroup>,
#[account(mut)]
pub user: Signer<'info>,
pub taker_trg: AccountLoader<'info, TraderRiskGroup>,
pub maker_trg: AccountLoader<'info, TraderRiskGroup>,
Expand Down
31 changes: 31 additions & 0 deletions hxro-print-trade-provider/program/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anchor_lang::prelude::*;
use dex::utils::numeric::Fractional;
use rfq::state::AuthoritySide;

#[account]
Expand All @@ -7,6 +8,36 @@ pub struct Config {
pub valid_mpg: Pubkey,
}

#[account]
#[derive(InitSpace)]
pub struct LockedCollateralRecord {
pub user: Pubkey,
pub response: Pubkey,
pub locks: [ProductInfo; 6],
}

#[derive(AnchorSerialize, AnchorDeserialize, Copy, Clone, PartialEq, Eq, Default, InitSpace)]
pub struct ProductInfo {
pub product_index: u64,
pub size: FractionalCopy,
}

#[repr(C)]
#[derive(AnchorSerialize, AnchorDeserialize, Copy, Clone, PartialEq, Eq, Default, InitSpace)]
pub struct FractionalCopy {
pub m: i64,
pub exp: u64,
}

impl From<FractionalCopy> for Fractional {
fn from(value: FractionalCopy) -> Self {
Self {
m: value.m,
exp: value.exp,
}
}
}

// Duplicate required because anchor doesn't generate IDL for imported structs
#[derive(AnchorSerialize, AnchorDeserialize, Copy, Clone, PartialEq, Eq)]
pub enum AuthoritySideDuplicate {
Expand Down
8 changes: 4 additions & 4 deletions tests/integration/hxro.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ describe("RFQ HXRO instrument integration tests", () => {
expect(responseData.defaultingParty).to.be.deep.equal(AuthoritySide.Taker);

await response.settleOnePartyDefault();
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Taker);
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Maker);
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Taker, { skipPreStep: true });
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Maker, { skipPreStep: true });
await response.cleanUp();
});

Expand Down Expand Up @@ -246,8 +246,8 @@ describe("RFQ HXRO instrument integration tests", () => {
expect(responseData.defaultingParty).to.be.deep.equal(AuthoritySide.Maker);

await response.settleOnePartyDefault();
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Taker);
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Maker);
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Taker, { skipPreStep: true });
await response.revertPrintTradeSettlementPreparation(AuthoritySide.Maker, { skipPreStep: true });
await response.cleanUp();
});

Expand Down
Loading

0 comments on commit bb11a0e

Please sign in to comment.