Skip to content

Commit

Permalink
Remove MarketType shadow (derive trait impls manually), it made consu…
Browse files Browse the repository at this point in the history
…mer code clunky

Fix formatting in IDL types
  • Loading branch information
jordy25519 committed Oct 29, 2024
1 parent 98a6464 commit a09391e
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 42 deletions.
2 changes: 1 addition & 1 deletion crates/drift-idl-gen/src/custom_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<'de> serde::Deserialize<'de> for Signature {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
let s = <&[u8]>::deserialize(d)?;
s.try_into()
.map(|s| Signature(s))
.map(Signature)
.map_err(serde::de::Error::custom)
}
}
Expand Down
10 changes: 7 additions & 3 deletions crates/drift-idl-gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,11 +523,11 @@ fn generate_idl_types(idl: &Idl) -> String {
//!
//! Auto-generated IDL types, manual edits do not persist (see `crates/drift-idl-gen`)
//!
use self::traits::ToAccountMetas;
use anchor_lang::{prelude::{account, AnchorSerialize, AnchorDeserialize, InitSpace, event, error_code, msg, borsh::{self}}, Discriminator};
// use solana-sdk Pubkey, the vendored anchor-lang Pubkey maybe behind
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
use serde::{Serialize, Deserialize};
use self::traits::ToAccountMetas;

pub mod traits {
use solana_sdk::instruction::AccountMeta;
Expand All @@ -540,34 +540,38 @@ fn generate_idl_types(idl: &Idl) -> String {
}

pub mod instructions {
//! IDL instruction types
use super::{*, types::*};

#instructions_tokens
}

pub mod types {
use std::ops::Mul;

//! IDL types
use super::*;
use std::ops::Mul;

#custom_types

#types_tokens
}

pub mod accounts {
//! IDL Account types
use super::{*, types::*};

#accounts_tokens
}

pub mod errors {
//! IDL error types
use super::{*, types::*};

#errors_tokens
}

pub mod events {
//! IDL event types
use super::{*, types::*};
#events_tokens
}
Expand Down
13 changes: 8 additions & 5 deletions crates/src/drift_idl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![doc = r""]
#![doc = r" Auto-generated IDL types, manual edits do not persist (see `crates/drift-idl-gen`)"]
#![doc = r""]
use self::traits::ToAccountMetas;
use anchor_lang::{
prelude::{
account,
Expand All @@ -12,8 +13,6 @@ use anchor_lang::{
};
use serde::{Deserialize, Serialize};
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};

use self::traits::ToAccountMetas;
pub mod traits {
use solana_sdk::instruction::AccountMeta;
#[doc = r" This is distinct from the anchor_lang version of the trait"]
Expand All @@ -23,6 +22,7 @@ pub mod traits {
}
}
pub mod instructions {
#![doc = r" IDL instruction types"]
use super::{types::*, *};
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct InitializeUser {
Expand Down Expand Up @@ -1803,9 +1803,9 @@ pub mod instructions {
impl anchor_lang::InstructionData for InitializePythPullOracle {}
}
pub mod types {
use std::ops::Mul;

#![doc = r" IDL types"]
use super::*;
use std::ops::Mul;
#[doc = ""]
#[doc = " backwards compatible u128 deserializing data from rust <=1.76.0 when u/i128 was 8-byte aligned"]
#[doc = " https://solana.stackexchange.com/questions/7720/using-u128-without-sacrificing-alignment-8"]
Expand Down Expand Up @@ -1883,7 +1883,7 @@ pub mod types {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
let s = <&[u8]>::deserialize(d)?;
s.try_into()
.map(|s| Signature(s))
.map(Signature)
.map_err(serde::de::Error::custom)
}
}
Expand Down Expand Up @@ -3506,6 +3506,7 @@ pub mod types {
}
}
pub mod accounts {
#![doc = r" IDL Account types"]
use super::{types::*, *};
#[repr(C)]
#[derive(
Expand Down Expand Up @@ -17343,6 +17344,7 @@ pub mod accounts {
}
}
pub mod errors {
#![doc = r" IDL error types"]
use super::{types::*, *};
#[derive(PartialEq)]
#[error_code]
Expand Down Expand Up @@ -17930,6 +17932,7 @@ pub mod errors {
}
}
pub mod events {
#![doc = r" IDL event types"]
use super::{types::*, *};
#[event]
pub struct NewUserRecord {
Expand Down
2 changes: 1 addition & 1 deletion crates/src/jit_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl JitProxyClient {
let program_data = tx_builder.program_data();
let account_data = tx_builder.account_data();

let writable_markets = match order.market_type.into() {
let writable_markets = match order.market_type {
MarketType::Perp => {
vec![MarketId::perp(order.market_index)]
}
Expand Down
16 changes: 8 additions & 8 deletions crates/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,7 @@ impl DriftClientBackend {
fn try_get_account<T: AccountDeserialize>(&self, account: &Pubkey) -> SdkResult<T> {
self.account_map
.account_data(account)
.ok_or_else(|| SdkError::NoAccountData(account.clone()))
.ok_or_else(|| SdkError::NoAccountData(*account))
}

/// Returns latest blockhash
Expand Down Expand Up @@ -1077,7 +1077,7 @@ impl<'a> TransactionBuilder<'a> {
pub fn place_orders(mut self, orders: Vec<OrderParams>) -> Self {
let mut readable_accounts: Vec<MarketId> = orders
.iter()
.map(|o| (o.market_index, o.market_type.into()).into())
.map(|o| (o.market_index, o.market_type).into())
.collect();
readable_accounts.extend(&self.force_markets.readable);

Expand Down Expand Up @@ -1141,7 +1141,7 @@ impl<'a> TransactionBuilder<'a> {
market: (u16, MarketType),
direction: Option<PositionDirection>,
) -> Self {
let (idx, kind) = market;
let (idx, r#type) = market;
let accounts = build_accounts(
self.program_data,
types::accounts::CancelOrder {
Expand All @@ -1150,7 +1150,7 @@ impl<'a> TransactionBuilder<'a> {
user: self.sub_account,
},
&[self.account_data.as_ref()],
[(idx, kind).into()]
[(idx, r#type).into()]
.iter()
.chain(self.force_markets.readable.iter()),
self.force_markets.writeable.iter(),
Expand All @@ -1161,7 +1161,7 @@ impl<'a> TransactionBuilder<'a> {
accounts,
data: InstructionData::data(&drift_idl::instructions::CancelOrders {
market_index: Some(idx),
market_type: Some(kind.into()),
market_type: Some(r#type),
direction,
}),
};
Expand Down Expand Up @@ -1296,7 +1296,7 @@ impl<'a> TransactionBuilder<'a> {
fulfillment_type: Option<SpotFulfillmentType>,
) -> Self {
let (taker, taker_account) = taker_info;
let is_perp = order.market_type == MarketType::Perp.into();
let is_perp = order.market_type == MarketType::Perp;
let perp_writable = [MarketId::perp(order.market_index)];
let spot_writable = [MarketId::spot(order.market_index), MarketId::QUOTE_SPOT];
let mut accounts = build_accounts(
Expand Down Expand Up @@ -1327,7 +1327,7 @@ impl<'a> TransactionBuilder<'a> {
accounts.push(AccountMeta::new(referrer, false));
}

let ix = if order.market_type == MarketType::Perp.into() {
let ix = if order.market_type == MarketType::Perp {
Instruction {
program_id: constants::PROGRAM_ID,
accounts,
Expand Down Expand Up @@ -1371,7 +1371,7 @@ impl<'a> TransactionBuilder<'a> {
user_accounts.push(maker);
}

let is_perp = order.market_type == MarketType::Perp.into();
let is_perp = order.market_type == MarketType::Perp;
let perp_writable = [MarketId::perp(order.market_index)];
let spot_writable = [MarketId::spot(order.market_index), MarketId::QUOTE_SPOT];

Expand Down
4 changes: 2 additions & 2 deletions crates/src/math/liquidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub async fn calculate_liquidation_price_and_unrealized_pnl(
unrealized_pnl: calculate_unrealized_pnl_inner(&position, oracle_price)?,
liquidation_price: calculate_liquidation_price_inner(
user,
&perp_market,
perp_market,
spot_market,
oracle_price,
&mut accounts_list,
Expand Down Expand Up @@ -143,7 +143,7 @@ pub async fn calculate_liquidation_price(

calculate_liquidation_price_inner(
user,
&perp_market,
perp_market,
spot_market,
oracle.data.price,
&mut account_maps,
Expand Down
38 changes: 16 additions & 22 deletions crates/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub use crate::drift_idl::{
};
use crate::{
constants::{ids, LUT_DEVNET, LUT_MAINNET},
drift_idl::{self, errors::ErrorCode},
drift_idl::errors::ErrorCode,
Wallet,
};

Expand Down Expand Up @@ -99,6 +99,20 @@ pub struct MarketId {
kind: MarketType,
}

// there are derived/auto-generated trait impls for `MarketType` so
// it can be used a key in maps, within `MarketId`
// doing here rather than adding to all structs or special casing in IDL generation
impl core::cmp::Eq for MarketType {}
impl core::hash::Hash for MarketType {
fn hash<H: core::hash::Hasher>(&self, ra_expand_state: &mut H) {
core::mem::discriminant(self).hash(ra_expand_state);
match self {
MarketType::Spot => {}
MarketType::Perp => {}
}
}
}

impl MarketId {
/// `MarketId` for the USDC Spot Market
pub const QUOTE_SPOT: Self = Self {
Expand Down Expand Up @@ -158,26 +172,6 @@ impl From<(u16, MarketType)> for MarketId {
}
}

/// Shadow the IDL market type to add some extra traits e.g. Eq + Hash
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum MarketType {
#[default]
Spot,
Perp,
}

impl From<drift_idl::types::MarketType> for MarketType {
fn from(value: drift_idl::types::MarketType) -> Self {
unsafe { std::mem::transmute(value) }
}
}

impl From<MarketType> for drift_idl::types::MarketType {
fn from(value: MarketType) -> Self {
unsafe { std::mem::transmute(value) }
}
}

/// Provides builder API for Orders
#[derive(Default)]
pub struct NewOrder {
Expand Down Expand Up @@ -252,7 +246,7 @@ impl NewOrder {
OrderParams {
order_type: self.order_type,
market_index: self.market_id.index,
market_type: self.market_id.kind.into(),
market_type: self.market_id.kind,
price: self.price,
base_asset_amount: self.amount,
reduce_only: self.reduce_only,
Expand Down

0 comments on commit a09391e

Please sign in to comment.