This commit is contained in:
Hardhat Chad
2025-09-17 10:14:05 -07:00
parent 4cee87860f
commit 959fd70c44
37 changed files with 1089 additions and 2947 deletions

View File

@@ -20,6 +20,9 @@ pub const MAX_SUPPLY: u64 = ONE_ORE * 5_000_000;
/// The seed of the block account PDA.
pub const BLOCK: &[u8] = b"block";
/// The seed of the board account PDA.
pub const BOARD: &[u8] = b"board";
/// The seed of the config account PDA.
pub const CONFIG: &[u8] = b"config";
@@ -29,6 +32,9 @@ pub const MARKET: &[u8] = b"market";
/// The seed of the miner account PDA.
pub const MINER: &[u8] = b"miner";
/// The seed of the square account PDA.
pub const SQUARE: &[u8] = b"square";
/// The seed of the treasury account PDA.
pub const TREASURY: &[u8] = b"treasury";

View File

@@ -1,10 +1,7 @@
use steel::*;
use crate::state::SwapDirection;
pub enum OreEvent {
Reset = 0,
Swap = 1,
Mine = 2,
}
@@ -30,58 +27,6 @@ pub struct ResetEvent {
pub ts: i64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct SwapEvent {
/// The event discriminator.
pub disc: u64,
/// The authority of the swap.
pub authority: Pubkey,
/// The block id.
pub block_id: u64,
/// Swap direction.
pub direction: u64,
/// Amount of base tokens to transfer.
pub base_to_transfer: u64,
/// Amount of quote tokens to transfer.
pub quote_to_transfer: u64,
/// Amount of base tokens swapped via virtual limit order.
pub base_via_order: u64,
/// Amount of quote tokens swapped via virtual limit order.
pub quote_via_order: u64,
/// Amount of base tokens swapped via curve.
pub base_via_curve: u64,
/// Amount of quote tokens swapped via curve.
pub quote_via_curve: u64,
/// Amount of quote tokens taken in fees.
pub quote_fee: u64,
/// Amount of base tokens in the market.
pub base_liquidity: u64,
/// Amount of quote tokens in the market.
pub quote_liquidity: u64,
/// Amount of hashpower the miner now has.
pub miner_hashpower: u64,
/// Amount of hashpower the block now has.
pub block_hashpower: u64,
/// The timestamp of the event.
pub ts: i64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct MineEvent {
@@ -107,12 +52,5 @@ pub struct MineEvent {
pub ts: i64,
}
impl SwapEvent {
pub fn direction(&self) -> SwapDirection {
SwapDirection::try_from(self.direction as u8).unwrap()
}
}
event!(ResetEvent);
event!(SwapEvent);
event!(MineEvent);

View File

@@ -5,20 +5,14 @@ use steel::*;
pub enum OreInstruction {
// User
Claim = 0,
Log = 1,
Mine = 2,
Swap = 3,
Initialize = 4,
Open = 5,
Close = 6,
Reset = 7,
Initialize = 1,
InitializeSquare = 2,
Prospect = 3,
Reset = 4,
// Admin
SetAdmin = 8,
SetBlockDuration = 9,
SetFeeCollector = 10,
SetFeeRate = 11,
SetSniperFeeDuration = 12,
// Seeker
ClaimSeeker = 13,
@@ -32,13 +26,11 @@ pub struct Claim {
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Open {
pub id: [u8; 8],
}
pub struct Initialize {}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Close {}
pub struct InitializeSquare {}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
@@ -46,12 +38,10 @@ pub struct Reset {}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Initialize {}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Log {}
pub struct Prospect {
pub amount: [u8; 8],
pub square_id: [u8; 8],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Mine {
@@ -108,16 +98,10 @@ pub struct SetSniperFeeDuration {
pub struct ClaimSeeker {}
instruction!(OreInstruction, Claim);
instruction!(OreInstruction, Open);
instruction!(OreInstruction, Close);
instruction!(OreInstruction, Reset);
instruction!(OreInstruction, Prospect);
instruction!(OreInstruction, Initialize);
instruction!(OreInstruction, Log);
instruction!(OreInstruction, Mine);
instruction!(OreInstruction, Swap);
instruction!(OreInstruction, InitializeSquare);
instruction!(OreInstruction, SetAdmin);
instruction!(OreInstruction, SetBlockDuration);
instruction!(OreInstruction, SetFeeCollector);
instruction!(OreInstruction, SetFeeRate);
instruction!(OreInstruction, SetSniperFeeDuration);
instruction!(OreInstruction, ClaimSeeker);

View File

@@ -7,36 +7,22 @@ use crate::{
state::*,
};
pub fn log(signer: Pubkey, msg: &[u8]) -> Instruction {
let mut data = Log {}.to_bytes();
data.extend_from_slice(msg);
Instruction {
program_id: crate::ID,
accounts: vec![AccountMeta::new(signer, true)],
data: data,
}
}
pub fn program_log(accounts: &[AccountInfo], msg: &[u8]) -> Result<(), ProgramError> {
invoke_signed(&log(*accounts[0].key, msg), accounts, &crate::ID, &[MARKET])
}
// let [signer_info, board_info, config_info, mint_info, treasury_info, vault_info, system_program, token_program, associated_token_program] =
pub fn initialize(signer: Pubkey) -> Instruction {
let config_address = config_pda().0;
let market_address = market_pda().0;
let board_address = board_pda().0;
let mint_address = MINT_ADDRESS;
let treasury_address = TREASURY_ADDRESS;
let treasury_tokens_address = treasury_tokens_address();
let vault_address = vault_address();
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(board_address, false),
AccountMeta::new(config_address, false),
AccountMeta::new(market_address, false),
AccountMeta::new(mint_address, false),
AccountMeta::new(treasury_address, false),
AccountMeta::new(treasury_tokens_address, false),
AccountMeta::new(vault_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(spl_token::ID, false),
@@ -46,41 +32,41 @@ pub fn initialize(signer: Pubkey) -> Instruction {
}
}
pub fn mine(signer: Pubkey, id: u64, nonce: u64) -> Instruction {
let block_adddress = block_pda(id).0;
let miner_address = miner_pda(signer).0;
let market_address = market_pda().0;
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(block_adddress, false),
AccountMeta::new(market_address, false),
AccountMeta::new(miner_address, false),
AccountMeta::new_readonly(crate::ID, false),
],
data: Mine {
nonce: nonce.to_le_bytes(),
}
.to_bytes(),
}
}
// let [signer_info, square_info, system_program] = accounts else {
pub fn open(signer: Pubkey, id: u64) -> Instruction {
let block_adddress = block_pda(id).0;
let market_address = market_pda().0;
pub fn initialize_squares(signer: Pubkey) -> Instruction {
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(block_adddress, false),
AccountMeta::new(market_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new(square_pda(0).0, false),
AccountMeta::new(square_pda(1).0, false),
AccountMeta::new(square_pda(2).0, false),
AccountMeta::new(square_pda(3).0, false),
AccountMeta::new(square_pda(4).0, false),
AccountMeta::new(square_pda(5).0, false),
AccountMeta::new(square_pda(6).0, false),
AccountMeta::new(square_pda(7).0, false),
AccountMeta::new(square_pda(8).0, false),
AccountMeta::new(square_pda(9).0, false),
AccountMeta::new(square_pda(10).0, false),
AccountMeta::new(square_pda(11).0, false),
AccountMeta::new(square_pda(12).0, false),
AccountMeta::new(square_pda(13).0, false),
AccountMeta::new(square_pda(14).0, false),
AccountMeta::new(square_pda(15).0, false),
AccountMeta::new(square_pda(16).0, false),
AccountMeta::new(square_pda(17).0, false),
AccountMeta::new(square_pda(18).0, false),
AccountMeta::new(square_pda(19).0, false),
AccountMeta::new(square_pda(20).0, false),
AccountMeta::new(square_pda(21).0, false),
AccountMeta::new(square_pda(22).0, false),
AccountMeta::new(square_pda(23).0, false),
AccountMeta::new(square_pda(24).0, false),
],
data: Open {
id: id.to_le_bytes(),
}
.to_bytes(),
data: InitializeSquare {}.to_bytes(),
}
}
@@ -107,106 +93,63 @@ pub fn claim(signer: Pubkey, amount: u64) -> Instruction {
}
}
pub fn close(signer: Pubkey, opener: Pubkey, winner: Pubkey, id: u64) -> Instruction {
let block_adddress = block_pda(id).0;
let market_address = market_pda().0;
let miner_address = miner_pda(winner).0;
let miner_tokens_address = get_associated_token_address(&miner_address, &MINT_ADDRESS);
// let [signer_info, board_info, mint_info, treasury_info, reserve_tokens_info, vault_info, system_program, token_program, slot_hashes_sysvar] =
pub fn reset(signer: Pubkey, miners: Vec<Pubkey>) -> Instruction {
let board_address = board_pda().0;
let mint_address = MINT_ADDRESS;
let treasury_address = TREASURY_ADDRESS;
let treasury_tokens_address = treasury_tokens_address();
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(block_adddress, false),
AccountMeta::new(miner_address, false),
AccountMeta::new_readonly(market_address, false),
AccountMeta::new(miner_tokens_address, false),
AccountMeta::new(mint_address, false),
AccountMeta::new(opener, false),
AccountMeta::new(treasury_address, false),
AccountMeta::new(treasury_tokens_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new_readonly(spl_associated_token_account::ID, false),
],
data: Close {}.to_bytes(),
}
}
// let [signer_info, block_prev_info, block_next_info, config_info, market_info, mint_info, reserve_tokens_info, treasury_info, treasury_tokens_info, vault_info, system_program, token_program, ore_program, slot_hashes_sysvar] =
pub fn reset(signer: Pubkey, id: u64) -> Instruction {
let block_prev_adddress = block_pda(id).0;
let block_next_adddress = block_pda(id + 1).0;
let config_address = config_pda().0;
let market_address = market_pda().0;
let mint_address = MINT_ADDRESS;
let treasury_address = TREASURY_ADDRESS;
let treasury_tokens_address = treasury_tokens_address();
let reserve_tokens_address = BOOST_RESERVE_TOKEN;
let vault_address = vault_address();
let mut accounts = vec![
AccountMeta::new(signer, true),
AccountMeta::new(board_address, false),
AccountMeta::new(mint_address, false),
AccountMeta::new(treasury_address, false),
AccountMeta::new(reserve_tokens_address, false),
AccountMeta::new(vault_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new_readonly(sysvar::slot_hashes::ID, false),
];
for miner in miners {
if miner != Pubkey::default() {
accounts.push(AccountMeta::new(miner_pda(miner).0, false));
}
}
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(block_prev_adddress, false),
AccountMeta::new(block_next_adddress, false),
AccountMeta::new_readonly(config_address, false),
AccountMeta::new(market_address, false),
AccountMeta::new(mint_address, false),
AccountMeta::new(BOOST_RESERVE_TOKEN, false),
AccountMeta::new(treasury_address, false),
AccountMeta::new(treasury_tokens_address, false),
AccountMeta::new(vault_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new_readonly(crate::ID, false),
AccountMeta::new_readonly(sysvar::slot_hashes::ID, false),
],
accounts,
data: Reset {}.to_bytes(),
}
}
// let [signer_info, block_info, config_info, fee_collector_info, market_info, miner_info, mint_info, tokens_info, vault_info, system_program, token_program, associated_token_program, ore_program] =
pub fn swap(
signer: Pubkey,
id: u64,
fee_collector: Pubkey,
amount: u64,
direction: SwapDirection,
precision: SwapPrecision,
seed: [u8; 32],
) -> Instruction {
let block_adddress = block_pda(id).0;
// let [signer_info, board_info, config_info, fee_collector_info, miner_info, mint_info, sender_info, square_info, vault_info, system_program, token_program, associated_token_program] =
pub fn prospect(signer: Pubkey, fee_collector: Pubkey, amount: u64, square_id: u64) -> Instruction {
let board_address = board_pda().0;
let config_address = config_pda().0;
let market_address = market_pda().0;
let miner_address = miner_pda(signer).0;
let tokens_address = get_associated_token_address(&signer, &MINT_ADDRESS);
let sender_address = get_associated_token_address(&signer, &MINT_ADDRESS);
let square_address = square_pda(square_id).0;
let vault_address = vault_address();
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(block_adddress, false),
AccountMeta::new(board_address, false),
AccountMeta::new(config_address, false),
AccountMeta::new(fee_collector, false),
AccountMeta::new(market_address, false),
AccountMeta::new(miner_address, false),
AccountMeta::new(MINT_ADDRESS, false),
AccountMeta::new(tokens_address, false),
AccountMeta::new(sender_address, false),
AccountMeta::new(square_address, false),
AccountMeta::new(vault_address, false),
AccountMeta::new_readonly(system_program::ID, false),
AccountMeta::new_readonly(spl_token::ID, false),
AccountMeta::new_readonly(spl_associated_token_account::ID, false),
AccountMeta::new_readonly(crate::ID, false),
AccountMeta::new_readonly(sysvar::slot_hashes::ID, false),
],
data: Swap {
data: Prospect {
amount: amount.to_le_bytes(),
direction: direction as u8,
precision: precision as u8,
seed: seed,
square_id: square_id.to_le_bytes(),
}
.to_bytes(),
}
@@ -228,22 +171,6 @@ pub fn set_admin(signer: Pubkey, admin: Pubkey) -> Instruction {
}
}
pub fn set_block_duration(signer: Pubkey, block_duration: u64) -> Instruction {
let config_address = config_pda().0;
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(config_address, false),
AccountMeta::new_readonly(system_program::ID, false),
],
data: SetBlockDuration {
block_duration: block_duration.to_le_bytes(),
}
.to_bytes(),
}
}
pub fn set_fee_collector(signer: Pubkey, fee_collector: Pubkey) -> Instruction {
let config_address = config_pda().0;
Instruction {
@@ -260,38 +187,6 @@ pub fn set_fee_collector(signer: Pubkey, fee_collector: Pubkey) -> Instruction {
}
}
pub fn set_fee_rate(signer: Pubkey, fee_rate: u64) -> Instruction {
let config_address = config_pda().0;
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(config_address, false),
AccountMeta::new_readonly(system_program::ID, false),
],
data: SetFeeRate {
fee_rate: fee_rate.to_le_bytes(),
}
.to_bytes(),
}
}
pub fn set_sniper_fee_duration(signer: Pubkey, sniper_fee_duration: u64) -> Instruction {
let config_address = config_pda().0;
Instruction {
program_id: crate::ID,
accounts: vec![
AccountMeta::new(signer, true),
AccountMeta::new(config_address, false),
AccountMeta::new_readonly(system_program::ID, false),
],
data: SetSniperFeeDuration {
sniper_fee_duration: sniper_fee_duration.to_le_bytes(),
}
.to_bytes(),
}
}
pub fn claim_seeker(signer: Pubkey, mint: Pubkey) -> Instruction {
Instruction {
program_id: crate::ID,

View File

@@ -1,27 +1,18 @@
use steel::*;
use crate::state::block_pda;
use crate::state::board_pda;
use super::OreAccount;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Block {
/// The block number.
pub struct Board {
/// The commits for the round.
pub commits: [u64; 25],
/// The round number.
pub id: u64,
/// The party that opened the block.
pub opener: Pubkey,
/// The reward configuration.
pub reward: u64,
/// The best hash submitted to the block.
pub best_hash: [u8; 32],
/// The authority of the miner who submitted the best hash.
pub best_hash_miner: Pubkey,
/// The timestamp at which the block starts mining.
pub start_at: i64,
@@ -34,14 +25,20 @@ pub struct Block {
/// The hash of the end slot, provided by solana, used for random number generation.
pub slot_hash: [u8; 32],
/// The total amount of hashpower bought in the block.
pub total_hashpower: u64,
/// The total amount of ORE burned for the round.
pub total_burned: u64,
/// The total amount of ORE committed for the round.
pub total_commits: u64,
/// The total amount of ORE won by miners for the round.
pub total_winnings: u64,
}
impl Block {
impl Board {
pub fn pda(&self) -> (Pubkey, u8) {
block_pda(self.id)
board_pda()
}
}
account!(OreAccount, Block);
account!(OreAccount, Board);

View File

@@ -1,87 +0,0 @@
use steel::Pubkey;
use crate::{error::OreError, event::OreEvent};
use super::{Market, SwapDirection, TokenType, VirtualLimitOrder};
use crate::event::SwapEvent;
impl Market {
pub fn buy_exact_in(&mut self, quote_in: u64) -> Result<SwapEvent, OreError> {
// Get fee from quote side.
let quote_fee = self.fee(quote_in);
let quote_in_post_fee = quote_in - quote_fee;
// Upcast data.
let quote_in_post_fee = quote_in_post_fee as u128;
// Get virtual limit order.
let VirtualLimitOrder {
size_in_base: ask_size_in_base,
size_in_quote: ask_size_in_quote,
} = self.get_virtual_limit_order(SwapDirection::Buy);
// Execute swap.
let (base_via_ask, quote_via_ask, base_via_curve, quote_via_curve) =
if !self.sandwich_resistance_enabled() {
// Fill entire swap via curve.
let quote_via_curve = quote_in_post_fee;
let base_via_curve = self.get_base_out(quote_via_curve);
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Buy)?;
(0, 0, base_via_curve, quote_via_curve)
} else if ask_size_in_quote >= quote_in_post_fee {
// Fill entire swap via virtual limit order.
let quote_via_ask = quote_in_post_fee;
let base_via_ask = self.get_complementary_limit_order_size(
quote_in_post_fee,
SwapDirection::Buy,
TokenType::Quote,
);
self.update_reserves(base_via_ask, quote_via_ask, SwapDirection::Buy)?;
(base_via_ask, quote_via_ask, 0, 0)
} else {
// Partially fill swap via virtual limit order.
let base_via_ask = ask_size_in_base;
let quote_via_ask = ask_size_in_quote;
self.update_reserves(base_via_ask, quote_via_ask, SwapDirection::Buy)?;
// Fill remaining swap amount via curve.
let quote_via_curve = quote_in_post_fee - ask_size_in_quote;
let base_via_curve = self.get_base_out(quote_via_curve);
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Buy)?;
(base_via_ask, quote_via_ask, base_via_curve, quote_via_curve)
};
// Produce swap result.
let base_out = base_via_ask + base_via_curve;
let swap_event = SwapEvent {
disc: OreEvent::Swap as u64,
authority: Pubkey::default(),
block_id: 0,
direction: SwapDirection::Buy as u64,
base_to_transfer: base_out as u64,
quote_to_transfer: quote_in,
base_via_order: base_via_ask as u64,
quote_via_order: quote_via_ask as u64,
base_via_curve: base_via_curve as u64,
quote_via_curve: quote_via_curve as u64,
quote_fee: quote_fee as u64,
base_liquidity: self.base.liquidity() as u64,
quote_liquidity: self.quote.liquidity() as u64,
miner_hashpower: 0,
block_hashpower: 0,
ts: 0,
};
// Sanity check swap event.
assert!(
swap_event.base_to_transfer == swap_event.base_via_order + swap_event.base_via_curve
);
assert!(
swap_event.quote_to_transfer
== swap_event.quote_via_order + swap_event.quote_via_curve + swap_event.quote_fee
);
// Return
Ok(swap_event)
}
}

View File

@@ -1,92 +0,0 @@
use steel::Pubkey;
use crate::{error::OreError, event::OreEvent};
use super::{Market, SwapDirection, TokenType, VirtualLimitOrder};
use crate::event::SwapEvent;
impl Market {
pub fn buy_exact_out(&mut self, base_out: u64) -> Result<SwapEvent, OreError> {
// Check if there is enough liquidity.
if self.base.balance < base_out {
return Err(OreError::InsufficientLiquidity);
}
// Upcast data.
let base_out = base_out as u128;
// Get virtual limit order.
let VirtualLimitOrder {
size_in_base: ask_size_in_base,
size_in_quote: ask_size_in_quote,
} = self.get_virtual_limit_order(SwapDirection::Buy);
// Execute swap.
let (base_via_ask, quote_via_ask, base_via_curve, quote_via_curve) =
if !self.sandwich_resistance_enabled() {
// Fill entire swap via curve.
let base_via_curve = base_out;
let quote_via_curve = self.get_quote_in(base_via_curve)?;
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Buy)?;
(0, 0, base_via_curve, quote_via_curve)
} else if ask_size_in_base >= base_out {
// Fill entire swap through virtual limit order.
let base_via_ask = base_out;
let quote_via_ask = self.get_complementary_limit_order_size(
base_via_ask,
SwapDirection::Buy,
TokenType::Base,
);
self.update_reserves(base_via_ask, quote_via_ask, SwapDirection::Buy)?;
(base_via_ask, quote_via_ask, 0, 0)
} else {
// Partially fill swap through virtual limit order.
let base_via_ask = ask_size_in_base;
let quote_via_ask = ask_size_in_quote;
self.update_reserves(base_via_ask, quote_via_ask, SwapDirection::Buy)?;
// Fill remaining swap amount through pool.
let base_via_curve = base_out - base_via_ask;
let quote_via_curve = self.get_quote_in(base_via_curve)?;
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Buy)?;
(base_via_ask, quote_via_ask, base_via_curve, quote_via_curve)
};
// Calculate fee.
let quote_post_fee = quote_via_ask + quote_via_curve;
let quote_in = self.pre_fee(quote_post_fee as u64) as u128;
let quote_fee = quote_in - quote_post_fee;
// Produce swap result.
let swap_event = SwapEvent {
disc: OreEvent::Swap as u64,
authority: Pubkey::default(),
block_id: 0,
direction: SwapDirection::Buy as u64,
base_to_transfer: base_out as u64,
quote_to_transfer: quote_in as u64,
base_via_order: base_via_ask as u64,
quote_via_order: quote_via_ask as u64,
base_via_curve: base_via_curve as u64,
quote_via_curve: quote_via_curve as u64,
quote_fee: quote_fee as u64,
base_liquidity: self.base.liquidity() as u64,
quote_liquidity: self.quote.liquidity() as u64,
miner_hashpower: 0,
block_hashpower: 0,
ts: 0,
};
// Sanity check swap result.
assert!(
swap_event.base_to_transfer == swap_event.base_via_order + swap_event.base_via_curve
);
assert!(
swap_event.quote_to_transfer
== swap_event.quote_via_order + swap_event.quote_via_curve + swap_event.quote_fee
);
// Return.
Ok(swap_event)
}
}

View File

@@ -1,46 +0,0 @@
use crate::error::OreError;
use super::Market;
// TODO Add weights.
impl Market {
/// Returns the constant product invariant.
pub(crate) fn k(&self) -> u128 {
(self.base.liquidity() * self.quote.liquidity()).saturating_sub(1)
}
/// Returns the amount of base tokens that can be bought from a given amount of quote tokens.
pub fn get_base_out(&self, quote_in: u128) -> u128 {
let base_out = self.base.liquidity()
- (self.k() / (self.quote.liquidity() + quote_in)).saturating_add(1);
base_out
}
/// Returns the amount of quote tokens received from selling a given amount of base tokens.
pub fn get_quote_out(&self, base_in: u128) -> u128 {
let quote_out = self.quote.liquidity()
- (self.k() / (self.base.liquidity() + base_in)).saturating_add(1);
quote_out
}
/// Returns the amount of quote tokens needed to buy a given amount of base tokens.
pub fn get_quote_in(&self, base_out: u128) -> Result<u128, OreError> {
if base_out >= self.base.liquidity() {
return Err(OreError::InsufficientVaultReserves.into());
}
let quote_in = (self.k() / (self.base.liquidity() - base_out)).saturating_add(1)
- self.quote.liquidity();
Ok(quote_in)
}
/// Returns the amount of base tokens which must be sold to receive a given amount of quote tokens.
pub fn get_base_in(&self, quote_out: u128) -> Result<u128, OreError> {
if quote_out >= self.quote.liquidity() {
return Err(OreError::InsufficientVaultReserves.into());
}
let base_in = (self.k() / (self.quote.liquidity() - quote_out)).saturating_add(1)
- self.base.liquidity();
Ok(base_in)
}
}

View File

@@ -1,24 +0,0 @@
use crate::consts::*;
use super::Market;
impl Market {
pub(crate) fn apply_fees(&mut self, quote_fee: u64) {
// Process protocol fees.
self.fee.cumulative += quote_fee;
self.fee.uncollected += quote_fee;
}
/// Calculates the fee from a quote amount.
pub(crate) fn fee(&self, quote_size: u64) -> u64 {
quote_size * self.fee.rate / DENOMINATOR_BPS
}
/// Calculates the pre-fee quote from a post-fee quote amount.
pub(crate) fn pre_fee(&self, quote_post_fee: u64) -> u64 {
// x * 10000 / (10000 - fee) is approximately equivalent to x * (1 - fee / 10000)
let numerator = quote_post_fee * DENOMINATOR_BPS;
let denominator = DENOMINATOR_BPS - self.fee.rate;
return numerator / denominator;
}
}

View File

@@ -1,454 +0,0 @@
use spl_associated_token_account::get_associated_token_address;
use steel::*;
use crate::state::{market_pda, OreAccount};
// TODO Bonding curve stuff
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Market {
/// Base token parameters.
pub base: TokenParams,
/// Quote token parameters.
pub quote: TokenParams,
/// Fee parameters.
pub fee: FeeParams,
/// Snapshot of the market state at the time of the last swap.
pub snapshot: Snapshot,
/// The id of the current block.
pub block_id: u64,
}
impl Market {
pub fn pda(&self) -> (Pubkey, u8) {
market_pda()
}
pub fn base_vault(&self) -> Pubkey {
get_associated_token_address(&self.pda().0, &self.base.mint)
}
pub fn quote_vault(&self) -> Pubkey {
get_associated_token_address(&self.pda().0, &self.quote.mint)
}
pub fn sandwich_resistance_enabled(&self) -> bool {
self.snapshot.enabled == 1
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct TokenParams {
/// Mint of the token.
pub mint: Pubkey,
/// Amount of tokens held in liquidity.
pub balance: u64,
/// Amount of virtual tokens held in liquidity.
pub balance_virtual: u64,
}
impl TokenParams {
pub fn liquidity(&self) -> u128 {
(self.balance + self.balance_virtual) as u128
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct FeeParams {
/// Cumulative protocol fees.
pub cumulative: u64,
/// Fee rate in basis points.
pub rate: u64,
/// Current uncollected protocol fees.
pub uncollected: u64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Snapshot {
/// Whether sandwich resistance is enabled.
pub enabled: u64,
/// Base token balance at the time of the snapshot.
pub base_balance: u64,
/// Quote token balance at the time of the snapshot.
pub quote_balance: u64,
/// Slot at which the snapshot was taken.
pub slot: u64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct VirtualLimitOrder {
/// Size of the virtual limit order in base tokens.
pub size_in_base: u128,
/// Size of the virtual limit order in quote tokens.
pub size_in_quote: u128,
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, TryFromPrimitive)]
pub enum SwapDirection {
/// Swap quote tokens for base tokens.
Buy = 0,
/// Swap base tokens for quote tokens.
Sell = 1,
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, TryFromPrimitive)]
pub enum SwapPrecision {
/// Swap with precision exact in amount.
ExactIn = 0,
/// Swap with precision exact out amount.
ExactOut = 1,
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, TryFromPrimitive)]
pub enum TokenType {
/// Base token.
Base = 0,
/// Quote token.
Quote = 1,
}
account!(OreAccount, Market);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fees_buy_exact_in() {
let mut market = new_market();
let swap = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
Clock::default(),
)
.unwrap();
assert_eq!(swap.quote_via_curve, 99_000);
assert_eq!(market.fee.uncollected, 1000); // Protocol fee is 1%
}
#[test]
fn test_fees_sell_exact_in() {
let mut market = new_market();
let swap = market
.swap(
100_000,
SwapDirection::Sell,
SwapPrecision::ExactIn,
Clock::default(),
)
.unwrap();
assert_eq!(swap.quote_via_curve, 98_991);
assert_eq!(market.fee.uncollected, 999);
}
#[test]
fn test_fees_buy_exact_out() {
let mut market = new_market();
let swap = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactOut,
Clock::default(),
)
.unwrap();
assert_eq!(swap.quote_via_curve, 100_011);
assert_eq!(market.fee.uncollected, 1010);
}
#[test]
fn test_fees_sell_exact_out() {
let mut market = new_market();
let swap = market
.swap(
100_000,
SwapDirection::Sell,
SwapPrecision::ExactOut,
Clock::default(),
)
.unwrap();
assert_eq!(swap.quote_via_curve, 101_010);
assert_eq!(market.fee.uncollected, 1010);
}
#[test]
fn test_fills() {
let mut market = new_market();
let mut clock = Clock::default();
clock.slot = 10;
// Small buy
// Assert swap is filled via curve.
// Post swap, price is above snapshot.
let swap_1 = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_1.base_via_curve > 0 && swap_1.quote_via_curve > 0);
assert!(swap_1.base_via_order == 0 && swap_1.quote_via_order == 0);
// Large sell
// Assert swap is partially filled via order and partially filled via curve.
// Post swap, price is below snapshot.
let swap_2 = market
.swap(
1_000_000,
SwapDirection::Sell,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_2.base_via_curve > 0 && swap_2.quote_via_curve > 0);
assert!(swap_2.base_via_order > 0 && swap_2.quote_via_order > 0);
// Small buy
// Assert swap is filled via order
// Post swap, price is still below snapshot.
let swap_3 = market
.swap(
1_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_3.base_via_curve == 0 && swap_3.quote_via_curve == 0);
assert!(swap_3.base_via_order > 0 && swap_3.quote_via_order > 0);
// Large buy
// Assert swap is partially filled via order and partially filled via curve.
// Post swap, price is above snapshot.
let swap_4 = market
.swap(
1_000_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_4.base_via_curve > 0 && swap_4.quote_via_curve > 0);
assert!(swap_4.base_via_order > 0 && swap_4.quote_via_order > 0);
}
#[test]
fn test_sandwich() {
let mut market = new_market();
market.fee.rate = 0;
market.snapshot = Snapshot {
enabled: 0,
base_balance: 0,
quote_balance: 0,
slot: 0,
};
let mut clock = Clock::default();
clock.slot = 10;
// Open sandwich
let swap_1 = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
let amount_base_1 = swap_1.base_to_transfer;
assert!(swap_1.base_via_curve > 0 && swap_1.quote_via_curve > 0);
assert!(swap_1.base_via_order == 0 && swap_1.quote_via_order == 0);
// Victim buys
let swap_2 = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_2.base_via_curve > 0 && swap_2.quote_via_curve > 0);
assert!(swap_2.base_via_order == 0 && swap_2.quote_via_order == 0);
// Close sandwich
let swap_3 = market
.swap(
amount_base_1,
SwapDirection::Sell,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_3.base_via_curve > 0 && swap_3.quote_via_curve > 0);
assert!(swap_3.base_via_order == 0 && swap_3.quote_via_order == 0);
// Assert sandwich attack succeeded
assert!(swap_3.quote_to_transfer > swap_1.quote_to_transfer);
}
#[test]
fn test_sandwich_resistance() {
let mut market = new_market();
market.fee.rate = 0;
let mut clock = Clock::default();
clock.slot = 10;
// Open sandwich
let swap_1 = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
let amount_base_1 = swap_1.base_to_transfer;
assert!(swap_1.base_via_curve > 0 && swap_1.quote_via_curve > 0);
assert!(swap_1.base_via_order == 0 && swap_1.quote_via_order == 0);
// Victim buys
let swap_2 = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_2.base_via_curve > 0 && swap_2.quote_via_curve > 0);
assert!(swap_2.base_via_order == 0 && swap_2.quote_via_order == 0);
// Close sandwich
let swap_3 = market
.swap(
amount_base_1,
SwapDirection::Sell,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap_3.base_via_curve == 0 && swap_3.quote_via_curve == 0);
assert!(swap_3.base_via_order > 0 && swap_3.quote_via_order > 0);
// Assert sandwich attack failed
assert!(swap_3.quote_to_transfer <= swap_1.quote_to_transfer);
}
#[test]
fn test_virtual_liquidity() {
let mut market = new_market();
market.fee.rate = 0;
market.quote.balance_virtual = 1_000_000_000;
market.quote.balance = 0;
let mut clock = Clock::default();
clock.slot = 10;
// Sell
// Assert swap fails without real liquidity to satisfy order.
let swap = market.swap(
100_000,
SwapDirection::Sell,
SwapPrecision::ExactIn,
clock.clone(),
);
assert!(swap.is_err());
// Buy
// Assert buy succeeds adding liquidity.
let swap = market
.swap(
100_000,
SwapDirection::Buy,
SwapPrecision::ExactIn,
clock.clone(),
)
.unwrap();
assert!(swap.base_via_curve > 0 && swap.quote_via_curve > 0);
assert!(swap.base_via_order == 0 && swap.quote_via_order == 0);
assert_eq!(market.quote.balance, 100_000);
assert_eq!(market.quote.balance_virtual, 1_000_000_000);
// Sell
// Assert sell fails if there is insufficient liquidity.
let swap = market.swap(
100_001,
SwapDirection::Sell,
SwapPrecision::ExactOut,
clock.clone(),
);
assert!(swap.is_err());
// Sell
// Assert sell succeeds removing liquidity.
let swap = market
.swap(
100_000,
SwapDirection::Sell,
SwapPrecision::ExactOut,
clock.clone(),
)
.unwrap();
assert!(swap.base_via_curve > 0 && swap.quote_via_curve > 0);
assert!(swap.base_via_order > 0 && swap.quote_via_order > 0);
assert_eq!(market.quote.balance, 0);
assert_eq!(market.quote.balance_virtual, 1_000_000_000);
}
fn new_market() -> Market {
Market {
base: TokenParams {
mint: Pubkey::new_unique(),
balance: 1_000_000_000,
balance_virtual: 0,
},
quote: TokenParams {
mint: Pubkey::new_unique(),
balance: 1_000_000_000,
balance_virtual: 0,
},
fee: FeeParams {
cumulative: 0,
uncollected: 0,
rate: 100, // 100 bps
},
snapshot: Snapshot {
enabled: 1,
base_balance: 0,
quote_balance: 0,
slot: 0,
},
block_id: 0,
}
}
}

View File

@@ -1,12 +0,0 @@
mod buy_exact_in;
mod buy_exact_out;
mod curve;
mod fees;
mod market;
mod sell_exact_in;
mod sell_exact_out;
mod swap;
mod vaults;
mod virtual_limit_order;
pub use market::*;

View File

@@ -1,95 +0,0 @@
use steel::Pubkey;
use crate::{error::OreError, event::OreEvent};
use super::{Market, SwapDirection, TokenType, VirtualLimitOrder};
use crate::event::SwapEvent;
impl Market {
pub fn sell_exact_in(&mut self, base_in: u64) -> Result<SwapEvent, OreError> {
// Get fee from quote side.
let mut quote_fee = 0;
// Upcast data.
let base_in = base_in as u128;
// Get virtual limit order.
let VirtualLimitOrder {
size_in_base: bid_size_in_base,
size_in_quote: bid_size_in_quote,
} = self.get_virtual_limit_order(SwapDirection::Sell);
// Execute swap.
let (base_via_bid, quote_via_bid, base_via_curve, quote_via_curve) =
if !self.sandwich_resistance_enabled() {
// Fill entire swap via curve.
let base_via_curve = base_in;
let mut quote_via_curve = self.get_quote_out(base_via_curve);
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Sell)?;
let swap_fee = self.fee(quote_via_curve as u64);
quote_fee += swap_fee;
quote_via_curve -= swap_fee as u128;
(0, 0, base_via_curve, quote_via_curve)
} else if bid_size_in_base >= base_in {
// Fill entire swap through virtual limit order.
let base_via_bid = base_in;
let mut quote_via_bid = self.get_complementary_limit_order_size(
base_in,
SwapDirection::Sell,
TokenType::Base,
);
quote_fee += self.fee(quote_via_bid as u64);
self.update_reserves(base_via_bid, quote_via_bid, SwapDirection::Sell)?;
quote_via_bid -= quote_fee as u128;
(base_via_bid, quote_via_bid, 0, 0)
} else {
// Partially fill swap through virtual limit order.
let base_via_bid = bid_size_in_base;
let mut quote_via_bid = bid_size_in_quote;
quote_fee += self.fee(quote_via_bid as u64);
self.update_reserves(base_via_bid, quote_via_bid, SwapDirection::Sell)?;
quote_via_bid -= quote_fee as u128;
// Fill remaining swap through pool.
let base_via_curve = base_in - base_via_bid;
let mut quote_via_curve = self.get_quote_out(base_via_curve);
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Sell)?;
let swap_fee = self.fee(quote_via_curve as u64);
quote_fee += swap_fee;
quote_via_curve -= swap_fee as u128;
(base_via_bid, quote_via_bid, base_via_curve, quote_via_curve)
};
// Produce swap result.
let quote_out = quote_via_bid + quote_via_curve;
let swap_event = SwapEvent {
disc: OreEvent::Swap as u64,
authority: Pubkey::default(),
block_id: 0,
direction: SwapDirection::Sell as u64,
base_to_transfer: base_in as u64,
quote_to_transfer: quote_out as u64,
base_via_order: base_via_bid as u64,
quote_via_order: quote_via_bid as u64,
base_via_curve: base_via_curve as u64,
quote_via_curve: quote_via_curve as u64,
quote_fee: quote_fee as u64,
base_liquidity: self.base.liquidity() as u64,
quote_liquidity: self.quote.liquidity() as u64,
miner_hashpower: 0,
block_hashpower: 0,
ts: 0,
};
// Sanity check swap result.
assert!(
swap_event.base_to_transfer == swap_event.base_via_order + swap_event.base_via_curve
);
assert!(
swap_event.quote_to_transfer == swap_event.quote_via_order + swap_event.quote_via_curve
);
// Return.
Ok(swap_event)
}
}

View File

@@ -1,94 +0,0 @@
use steel::Pubkey;
use crate::{error::OreError, event::OreEvent};
use super::{Market, SwapDirection, TokenType, VirtualLimitOrder};
use crate::event::SwapEvent;
impl Market {
pub fn sell_exact_out(&mut self, quote_out: u64) -> Result<SwapEvent, OreError> {
// Check if there is enough liquidity.
if self.quote.balance < quote_out {
return Err(OreError::InsufficientLiquidity);
}
// Calculate fee.
let quote_out_pre_fee = self.pre_fee(quote_out) as u128;
let quote_fee = quote_out_pre_fee - quote_out as u128;
// Upcast data.
let quote_out = quote_out as u128;
// Get virtual limit order.
let VirtualLimitOrder {
size_in_base: bid_size_in_base,
size_in_quote: bid_size_in_quote,
} = self.get_virtual_limit_order(SwapDirection::Sell);
// Execute swap.
let (base_via_bid, quote_via_bid, base_via_curve, quote_via_curve) =
if !self.sandwich_resistance_enabled() {
// Fill entire swap via curve.
let quote_via_curve = quote_out_pre_fee;
let base_via_curve = self.get_base_in(quote_via_curve)?;
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Sell)?;
(0, 0, base_via_curve, quote_via_curve)
} else if bid_size_in_quote >= quote_out {
// Fill entire swap through virtual limit order.
let quote_via_bid = quote_out_pre_fee;
let base_via_bid = self.get_complementary_limit_order_size(
quote_via_bid,
SwapDirection::Sell,
TokenType::Quote,
);
self.update_reserves(base_via_bid, quote_via_bid, SwapDirection::Sell)?;
(base_via_bid, quote_via_bid, 0, 0)
} else {
// Partially fill swap through virtual limit order.
let base_via_bid = bid_size_in_base;
let quote_via_bid = bid_size_in_quote;
self.update_reserves(base_via_bid, quote_via_bid, SwapDirection::Sell)?;
// Fill remaining swap amount through pool.
let quote_via_curve = quote_out_pre_fee - quote_via_bid;
let base_via_curve = self.get_base_in(quote_via_curve)?;
self.update_reserves(base_via_curve, quote_via_curve, SwapDirection::Sell)?;
(base_via_bid, quote_via_bid, base_via_curve, quote_via_curve)
};
// Calculate fee.
let base_in = base_via_bid + base_via_curve;
// Produce swap result.
let swap_event = SwapEvent {
disc: OreEvent::Swap as u64,
authority: Pubkey::default(),
block_id: 0,
direction: SwapDirection::Sell as u64,
base_to_transfer: base_in as u64,
quote_to_transfer: quote_out as u64,
base_via_order: base_via_bid as u64,
quote_via_order: quote_via_bid as u64,
base_via_curve: base_via_curve as u64,
quote_via_curve: quote_via_curve as u64,
quote_fee: quote_fee as u64,
base_liquidity: self.base.liquidity() as u64,
quote_liquidity: self.quote.liquidity() as u64,
miner_hashpower: 0,
block_hashpower: 0,
ts: 0,
};
// Sanity check swap result.
assert!(
swap_event.base_to_transfer == swap_event.base_via_order + swap_event.base_via_curve
);
assert!(
swap_event.quote_to_transfer
== swap_event.quote_via_order + swap_event.quote_via_curve - swap_event.quote_fee
);
// Return.
Ok(swap_event)
}
}

View File

@@ -1,45 +0,0 @@
use steel::Clock;
use crate::error::OreError;
use super::{Market, SwapDirection, SwapPrecision};
use crate::event::SwapEvent;
impl Market {
pub fn swap(
&mut self,
amount: u64,
direction: SwapDirection,
precision: SwapPrecision,
clock: Clock,
) -> Result<SwapEvent, OreError> {
// Update snapshot.
self.update_snapshot(&clock);
// Get invariant.
let k_pre = self.k();
// Execute swap.
let mut swap_event = match (direction, precision) {
(SwapDirection::Buy, SwapPrecision::ExactIn) => self.buy_exact_in(amount)?,
(SwapDirection::Buy, SwapPrecision::ExactOut) => self.buy_exact_out(amount)?,
(SwapDirection::Sell, SwapPrecision::ExactIn) => self.sell_exact_in(amount)?,
(SwapDirection::Sell, SwapPrecision::ExactOut) => self.sell_exact_out(amount)?,
};
// Update timestamp.
swap_event.ts = clock.unix_timestamp;
// Check invariant.
let k_post = self.k();
if k_pre > k_post {
return Err(OreError::InvariantViolation.into());
}
// Apply fees.
self.apply_fees(swap_event.quote_fee);
// Return.
Ok(swap_event)
}
}

View File

@@ -1,43 +0,0 @@
use solana_program::log::sol_log;
use steel::*;
use crate::error::OreError;
use super::Market;
/// Vault reserve checks.
impl Market {
/// Sanity check that vaults have reserves for all market debts.
/// Assumes the token accounts have already been validated as the market's base and quote vaults.
// pub fn check_vaults(
// &self,
// base_vault: &TokenAccount,
// quote_vault: &TokenAccount,
// ) -> Result<(), OreError> {
// self.check_base_vault(base_vault)?;
// self.check_quote_vault(quote_vault)?;
// Ok(())
// }
/// Sanity check that base vault has reserves for all market debts.
/// Assumes the token account has already been validated as the market's base vault.
// pub fn check_base_vault(&self, base_vault: &TokenAccount) -> Result<(), OreError> {
// if base_vault.amount() < self.base.balance {
// sol_log(&format!("A base_vault.amount: {}", base_vault.amount()));
// sol_log(&format!("A self.base.balance: {}", self.base.balance));
// sol_log("Insufficient base vault reserves");
// return Err(OreError::InsufficientVaultReserves.into());
// }
// Ok(())
// }
/// Sanity check that quote vault has reserves for all market debts.
/// Assumes the token account has already been validated as the market's quote vault.
pub fn check_quote_vault(&self, quote_vault: &TokenAccount) -> Result<(), OreError> {
if quote_vault.amount() < self.quote.balance + self.fee.uncollected {
sol_log("Insufficient quote vault reserves");
return Err(OreError::InsufficientVaultReserves.into());
}
Ok(())
}
}

View File

@@ -1,158 +0,0 @@
use steel::Clock;
use crate::{consts::SLOT_WINDOW, error::OreError};
use super::{Market, SwapDirection, TokenType, VirtualLimitOrder};
impl Market {
/// This function solves the closed-form solution for the size of the virtual limit order
/// in the pool. The virutal limit order is always priced at the snapshot price.
///
/// The size of the limit order is determined by the following constraint:
///
/// ```no_run
/// (quote_snapshot / base_snapshot) = (quote_reserves + ∆_quote) / (base_reserves + ∆_base)
/// ```
///
/// Note that the signs of ∆_quote and ∆_base are always flipped.
///
/// This means that the size of the limit order is set such that the new pool price
/// after the swap is equal to the price at the snapshot.
///
/// Because we know the limit order is priced at the snapshot price, we can derive
/// the following equations:
/// - ∆_base = -∆_quote * base_snapshot / quote_snapshot
/// - ∆_quote = -∆_base * quote_snapshot / base_snapshot
///
///
/// We can then solve for ∆_base and ∆_quote after substituting the above equations. There are separate cases
/// for buy and sell
///
/// - Limit order on the buy side (bid)
/// ```no_run
/// ∆_base = (base_snapshot * quote_reserves - quote_snapshot * base_reserves) / (2 * quote_snapshot)
/// ∆_quote = (base_snapshot * quote_reserves - quote_snapshot * base_reserves) / (2 * base_snapshot)
/// ```
///
/// - Limit order on the sell side (ask)
/// ```no_run
/// ∆_base = (quote_snapshot * base_reserves - base_snapshot * quote_reserves) / (2 * quote_snapshot)
/// ∆_quote = (quote_snapshot * base_reserves - base_snapshot * quote_reserves) / (2 * base_snapshot)
/// ```
pub fn get_virtual_limit_order(&self, direction: SwapDirection) -> VirtualLimitOrder {
// Upcast data.
let base_balance = self.base.liquidity();
let quote_balance = self.quote.liquidity();
let base_snapshot = self.snapshot.base_balance as u128;
let quote_snapshot = self.snapshot.quote_balance as u128;
// Get virtual limit order.
match direction {
SwapDirection::Buy => {
let ask = if quote_snapshot * base_balance > base_snapshot * quote_balance {
let size_in_quote = (quote_snapshot * base_balance
- base_snapshot * quote_balance)
/ (2 * base_snapshot);
let size_in_base = size_in_quote * base_snapshot / quote_snapshot;
VirtualLimitOrder {
size_in_base,
size_in_quote,
}
} else {
VirtualLimitOrder::default()
};
ask
}
SwapDirection::Sell => {
let bid = if base_snapshot * quote_balance > quote_snapshot * base_balance {
let size_in_base = (base_snapshot * quote_balance
- quote_snapshot * base_balance)
/ (2 * quote_snapshot);
let size_in_quote = size_in_base * quote_snapshot / base_snapshot;
VirtualLimitOrder {
size_in_base,
size_in_quote,
}
} else {
VirtualLimitOrder::default()
};
bid
}
}
}
/// This function returns the size of the virtual limit order in the complementary token type
/// given an `amount` and the `input_token_type`.
/// - If the `input_token_type` is Base, then the size of the limit order in Quote is computed.
/// - If the `input_token_type` is Quote, then the size of the limit order in Base is computed.
pub(crate) fn get_complementary_limit_order_size(
&self,
amount: u128,
direction: SwapDirection,
token_type: TokenType,
) -> u128 {
if amount == 0 {
return 0;
}
let quote_snapshot = self.snapshot.quote_balance as u128;
let base_snapshot = self.snapshot.base_balance as u128;
match direction {
SwapDirection::Buy => {
match token_type {
// If `amount` is in base, then the size of the limit order in quote is computed and rounded up
TokenType::Base => ((amount * quote_snapshot).saturating_sub(1)
/ base_snapshot)
.saturating_add(1),
// If `amount` is in quote, then the size of the limit order in base is computed
TokenType::Quote => amount * base_snapshot / quote_snapshot,
}
}
SwapDirection::Sell => {
match token_type {
// If `amount` is in base, then the size of the limit order in quote is computed
TokenType::Base => amount * quote_snapshot / base_snapshot,
// If `amount` is in quote, then the size of the limit order in base is computed and rounded up
TokenType::Quote => ((amount * base_snapshot).saturating_sub(1)
/ quote_snapshot)
.saturating_add(1),
}
}
}
}
pub(crate) fn update_snapshot(&mut self, clock: &Clock) {
let slot = clock.slot;
let snapshot_slot = (slot / SLOT_WINDOW) * SLOT_WINDOW;
if snapshot_slot != self.snapshot.slot {
self.snapshot.slot = snapshot_slot;
self.snapshot.base_balance = self.base.liquidity() as u64;
self.snapshot.quote_balance = self.quote.liquidity() as u64;
}
}
pub(crate) fn update_reserves(
&mut self,
base: u128,
quote: u128,
direction: SwapDirection,
) -> Result<(), OreError> {
match direction {
SwapDirection::Buy => {
if base > self.base.balance as u128 {
return Err(OreError::InsufficientVaultReserves.into());
}
self.base.balance -= base as u64;
self.quote.balance += quote as u64;
}
SwapDirection::Sell => {
if quote > self.quote.balance as u128 {
return Err(OreError::InsufficientVaultReserves.into());
}
self.base.balance += base as u64;
self.quote.balance -= quote as u64;
}
}
Ok(())
}
}

View File

@@ -10,20 +10,14 @@ pub struct Miner {
/// The authority of this miner account.
pub authority: Pubkey,
/// The ID of the last block this miner mined in.
pub block_id: u64,
/// The miner's committed square in the current round round.
pub commits: [u64; 25],
/// An account authorized to execute actions on behalf of this miner.
pub executor: Pubkey,
/// The amount of ORE this miner can claim.
pub rewards: u64,
/// The amount of hashpower this miner has committed to the current block.
pub hashpower: u64,
/// A user-supplied seed for random number generation.
pub seed: [u8; 32],
/// The total amount of hashpower this miner has committed across all blocks.
pub total_hashpower: u64,
/// The ID of the round this miner last played in.
pub round_id: u64,
/// The total amount of ORE this miner has mined across all blocks.
pub total_rewards: u64,

View File

@@ -1,13 +1,13 @@
mod block;
mod board;
mod config;
mod market;
mod miner;
mod square;
mod treasury;
pub use block::*;
pub use board::*;
pub use config::*;
pub use market::*;
pub use miner::*;
pub use square::*;
pub use treasury::*;
use crate::consts::*;
@@ -17,38 +17,40 @@ use steel::*;
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum OreAccount {
Block = 100,
Config = 101,
Market = 102,
Miner = 103,
Treasury = 104,
//
Board = 105,
Square = 106,
}
pub fn block_pda(id: u64) -> (Pubkey, u8) {
Pubkey::find_program_address(&[BLOCK, &id.to_le_bytes()], &crate::ID)
pub fn board_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[BOARD], &crate::ID)
}
pub fn config_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[CONFIG], &crate::ID)
}
pub fn market_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[MARKET], &crate::ID)
}
pub fn miner_pda(authority: Pubkey) -> (Pubkey, u8) {
Pubkey::find_program_address(&[MINER, &authority.to_bytes()], &crate::ID)
}
pub fn square_pda(id: u64) -> (Pubkey, u8) {
Pubkey::find_program_address(&[SQUARE, &id.to_le_bytes()], &crate::ID)
}
pub fn vault_address() -> Pubkey {
let market_address = market_pda().0;
spl_associated_token_account::get_associated_token_address(&market_address, &MINT_ADDRESS)
let board_address = board_pda().0;
spl_associated_token_account::get_associated_token_address(&board_address, &MINT_ADDRESS)
}
pub fn treasury_pda() -> (Pubkey, u8) {
Pubkey::find_program_address(&[TREASURY], &crate::ID)
}
pub fn treasury_tokens_address() -> Pubkey {
spl_associated_token_account::get_associated_token_address(&TREASURY_ADDRESS, &MINT_ADDRESS)
}
// pub fn treasury_tokens_address() -> Pubkey {
// spl_associated_token_account::get_associated_token_address(&TREASURY_ADDRESS, &MINT_ADDRESS)
// }

29
api/src/state/square.rs Normal file
View File

@@ -0,0 +1,29 @@
use steel::*;
use crate::state::square_pda;
use super::OreAccount;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Square {
/// The count of miners on this square.
pub count: u64,
/// The commits for the round.
pub id: u64,
/// The round number.
pub round_id: u64,
/// The miners on this square.
pub miners: [Pubkey; 16],
}
impl Square {
pub fn pda(&self) -> (Pubkey, u8) {
square_pda(self.id)
}
}
account!(OreAccount, Square);