Skip to content

Commit

Permalink
Trunk/swift (#61)
Browse files Browse the repository at this point in the history
* Generate swift IDL types (add Signature type for [u8;64])
Make get_market_accounts_with_fallback pub
Add to/from_str for MarketType
* add sign_message to wallet
* bump drift-ffi-sys
* use better mainnet endpoint
---------

Co-authored-by: Nour Alharithi <[email protected]>
  • Loading branch information
jordy25519 and NourAlharithi authored Oct 21, 2024
1 parent dea7b62 commit 9e08dbe
Show file tree
Hide file tree
Showing 12 changed files with 430 additions and 25 deletions.
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,6 @@ jobs:
env:
RUST_LOG: info
TEST_DEVNET_RPC_ENDPOINT: ${{ secrets.DEVNET_RPC_ENDPOINT }}
TEST_MAINNET_RPC_ENDPOINT: ${{ secrets.MAINNET_RPC_ENDPOINT }}
TEST_PRIVATE_KEY: ${{ secrets.TEST_PRIVATE_KEY }}
CARGO_DRIFT_FFI_PATH: "/usr/lib"
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,4 @@ hex = "0.4"
hex-literal = "0.4"

[build-dependencies]
drift-idl-gen = { version = "0.1.0", path = "crates/drift-idl-gen"}
drift-idl-gen = { version = "0.1.1", path = "crates/drift-idl-gen"}
2 changes: 1 addition & 1 deletion crates/drift-idl-gen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "drift-idl-gen"
version = "0.1.0"
version = "0.1.1"
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/drift-labs/drift-rs"
Expand Down
25 changes: 24 additions & 1 deletion crates/drift-idl-gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,16 @@ impl ArgType {
}
}
ArgType::Defined { defined } => defined.clone(),
ArgType::Array { array: (t, len) } => format!("[{}; {}]", t.to_rust_type(), len),
ArgType::Array { array: (t, len) } => {
let rust_type = t.to_rust_type();
// this is a common signature representation
if *len == 64_usize && rust_type == "u8" {
// [u8; 64] does not have a Default impl
"Signature".into()
} else {
format!("[{}; {}]", t.to_rust_type(), len)
}
}
ArgType::Option { option } => format!("Option<{}>", option.to_rust_type()),
ArgType::Vec { vec } => format!("Vec<{}>", vec.to_rust_type()),
}
Expand Down Expand Up @@ -588,6 +597,20 @@ fn generate_idl_types(idl: &Idl) -> String {
}
}

#[repr(transparent)]
#[derive(AnchorDeserialize, AnchorSerialize, Copy, Clone, PartialEq, Debug)]
pub struct Signature(pub [u8; 64]);

impl Default for Signature {
fn default() -> Self {
Self([0_u8; 64])
}
}

impl anchor_lang::Space for Signature {
const INIT_SPACE: usize = 8 * 64;
}

/// wrapper around fixed array types used for padding with `Default` implementation
#[repr(transparent)]
#[derive(AnchorDeserialize, AnchorSerialize, Copy, Clone, PartialEq)]
Expand Down
9 changes: 4 additions & 5 deletions crates/src/account_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,14 @@ mod tests {
use solana_sdk::pubkey;

use super::*;
use crate::{accounts::User, constants::DEFAULT_PUBKEY, Wallet};
use crate::{
accounts::User, constants::DEFAULT_PUBKEY, utils::test_envs::mainnet_endpoint, Wallet,
};

#[tokio::test]
async fn test_user_subscribe() {
let _ = env_logger::try_init();
let account_map = AccountMap::new(
"https://api.mainnet-beta.solana.com".into(),
CommitmentConfig::confirmed(),
);
let account_map = AccountMap::new(mainnet_endpoint().into(), CommitmentConfig::confirmed());
let user_1 = Wallet::derive_user_account(
&pubkey!("DxoRJ4f5XRMvXU9SGuM4ZziBFUxbhB3ubur5sVZEvue2"),
0,
Expand Down
178 changes: 171 additions & 7 deletions crates/src/drift_idl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#![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,6 +11,8 @@ use anchor_lang::{
Discriminator,
};
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 version of the trait"]
Expand Down Expand Up @@ -163,7 +164,7 @@ pub mod instructions {
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct PlaceAndTakePerpOrder {
pub params: OrderParams,
pub maker_order_id: Option<u32>,
pub success_condition: Option<u32>,
}
#[automatically_derived]
impl anchor_lang::Discriminator for PlaceAndTakePerpOrder {
Expand All @@ -183,6 +184,18 @@ pub mod instructions {
#[automatically_derived]
impl anchor_lang::InstructionData for PlaceAndMakePerpOrder {}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct PlaceSwiftTakerOrder {
pub swift_message_bytes: Vec<u8>,
pub swift_order_params_message_bytes: Vec<u8>,
pub swift_message_signature: Signature,
}
#[automatically_derived]
impl anchor_lang::Discriminator for PlaceSwiftTakerOrder {
const DISCRIMINATOR: [u8; 8] = [50, 89, 120, 78, 254, 15, 104, 140];
}
#[automatically_derived]
impl anchor_lang::InstructionData for PlaceSwiftTakerOrder {}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct PlaceSpotOrder {
pub params: OrderParams,
}
Expand Down Expand Up @@ -1781,8 +1794,9 @@ pub mod instructions {
impl anchor_lang::InstructionData for InitializePythPullOracle {}
}
pub mod types {
use super::*;
use std::ops::Mul;

use super::*;
#[doc = r" backwards compatible u128 deserializing data from rust <=1.76.0 when u/i128 was 8-byte aligned"]
#[doc = r" https://solana.stackexchange.com/questions/7720/using-u128-without-sacrificing-alignment-8"]
#[derive(
Expand Down Expand Up @@ -1835,6 +1849,17 @@ pub mod types {
Self(value.to_le_bytes())
}
}
#[repr(transparent)]
#[derive(AnchorDeserialize, AnchorSerialize, Copy, Clone, PartialEq, Debug)]
pub struct Signature(pub [u8; 64]);
impl Default for Signature {
fn default() -> Self {
Self([0_u8; 64])
}
}
impl anchor_lang::Space for Signature {
const INIT_SPACE: usize = 8 * 64;
}
#[doc = r" wrapper around fixed array types used for padding with `Default` implementation"]
#[repr(transparent)]
#[derive(AnchorDeserialize, AnchorSerialize, Copy, Clone, PartialEq)]
Expand Down Expand Up @@ -2003,6 +2028,33 @@ pub mod types {
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub struct SwiftServerMessage {
pub swift_order_signature: Signature,
pub slot: u64,
}
#[repr(C)]
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub struct SwiftOrderParamsMessage {
pub swift_order_params: OrderParams,
pub expected_order_id: i32,
pub sub_account_id: u16,
pub take_profit_order_params: Option<SwiftTriggerOrderParams>,
pub stop_loss_order_params: Option<SwiftTriggerOrderParams>,
}
#[repr(C)]
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub struct SwiftTriggerOrderParams {
pub trigger_price: u64,
pub base_asset_amount: u64,
}
#[repr(C)]
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub struct ModifyOrderParams {
pub direction: Option<PositionDirection>,
pub base_asset_amount: Option<u64>,
Expand Down Expand Up @@ -2558,6 +2610,14 @@ pub mod types {
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub enum PlaceAndTakeOrderSuccessCondition {
#[default]
PartialFill,
FullFill,
}
#[derive(
AnchorSerialize, AnchorDeserialize, InitSpace, Copy, Clone, Default, Debug, PartialEq,
)]
pub enum PerpOperation {
#[default]
UpdateFunding,
Expand Down Expand Up @@ -4733,6 +4793,88 @@ pub mod accounts {
}
#[repr(C)]
#[derive(Copy, Clone, Default, AnchorSerialize, AnchorDeserialize)]
pub struct PlaceSwiftTakerOrder {
pub state: Pubkey,
pub user: Pubkey,
pub user_stats: Pubkey,
pub authority: Pubkey,
pub ix_sysvar: Pubkey,
}
#[automatically_derived]
impl anchor_lang::Discriminator for PlaceSwiftTakerOrder {
const DISCRIMINATOR: [u8; 8] = [237, 23, 214, 85, 135, 68, 88, 236];
}
#[automatically_derived]
unsafe impl anchor_lang::__private::bytemuck::Pod for PlaceSwiftTakerOrder {}
#[automatically_derived]
unsafe impl anchor_lang::__private::bytemuck::Zeroable for PlaceSwiftTakerOrder {}
#[automatically_derived]
impl anchor_lang::ZeroCopy for PlaceSwiftTakerOrder {}
#[automatically_derived]
impl anchor_lang::InstructionData for PlaceSwiftTakerOrder {}
#[automatically_derived]
impl ToAccountMetas for PlaceSwiftTakerOrder {
fn to_account_metas(&self) -> Vec<AccountMeta> {
vec![
AccountMeta {
pubkey: self.state,
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: self.user,
is_signer: false,
is_writable: true,
},
AccountMeta {
pubkey: self.user_stats,
is_signer: false,
is_writable: true,
},
AccountMeta {
pubkey: self.authority,
is_signer: true,
is_writable: false,
},
AccountMeta {
pubkey: self.ix_sysvar,
is_signer: false,
is_writable: false,
},
]
}
}
#[automatically_derived]
impl anchor_lang::AccountSerialize for PlaceSwiftTakerOrder {
fn try_serialize<W: std::io::Write>(&self, writer: &mut W) -> anchor_lang::Result<()> {
if writer.write_all(&Self::DISCRIMINATOR).is_err() {
return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
}
if AnchorSerialize::serialize(self, writer).is_err() {
return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
}
Ok(())
}
}
#[automatically_derived]
impl anchor_lang::AccountDeserialize for PlaceSwiftTakerOrder {
fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
let given_disc = &buf[..8];
if Self::DISCRIMINATOR != given_disc {
return Err(anchor_lang::error!(
anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch
));
}
Self::try_deserialize_unchecked(buf)
}
fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
let mut data: &[u8] = &buf[8..];
AnchorDeserialize::deserialize(&mut data)
.map_err(|_| anchor_lang::error::ErrorCode::AccountDidNotDeserialize.into())
}
}
#[repr(C)]
#[derive(Copy, Clone, Default, AnchorSerialize, AnchorDeserialize)]
pub struct PlaceSpotOrder {
pub state: Pubkey,
pub user: Pubkey,
Expand Down Expand Up @@ -6926,8 +7068,9 @@ pub mod accounts {
#[repr(C)]
#[derive(Copy, Clone, Default, AnchorSerialize, AnchorDeserialize)]
pub struct SettleExpiredMarket {
pub admin: Pubkey,
pub state: Pubkey,
pub authority: Pubkey,
pub perp_market: Pubkey,
}
#[automatically_derived]
impl anchor_lang::Discriminator for SettleExpiredMarket {
Expand All @@ -6945,15 +7088,20 @@ pub mod accounts {
impl ToAccountMetas for SettleExpiredMarket {
fn to_account_metas(&self) -> Vec<AccountMeta> {
vec![
AccountMeta {
pubkey: self.admin,
is_signer: true,
is_writable: false,
},
AccountMeta {
pubkey: self.state,
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: self.authority,
is_signer: true,
is_writable: false,
pubkey: self.perp_market,
is_signer: false,
is_writable: true,
},
]
}
Expand Down Expand Up @@ -7432,6 +7580,7 @@ pub mod accounts {
pub struct SetUserStatusToBeingLiquidated {
pub state: Pubkey,
pub user: Pubkey,
pub authority: Pubkey,
}
#[automatically_derived]
impl anchor_lang::Discriminator for SetUserStatusToBeingLiquidated {
Expand Down Expand Up @@ -7459,6 +7608,11 @@ pub mod accounts {
is_signer: false,
is_writable: true,
},
AccountMeta {
pubkey: self.authority,
is_signer: true,
is_writable: false,
},
]
}
}
Expand Down Expand Up @@ -16862,6 +17016,16 @@ pub mod errors {
LiquidationOrderFailedToFill,
#[msg("Invalid prediction market order")]
InvalidPredictionMarketOrder,
#[msg("Ed25519 Ix must be before place and make swift order ix")]
InvalidVerificationIxIndex,
#[msg("Swift message verificaiton failed")]
SigVerificationFailed,
#[msg("Market index mismatched b/w taker and maker swift order params")]
MismatchedSwiftOrderParamsMarketIndex,
#[msg("Swift only available for market/oracle perp orders")]
InvalidSwiftOrderParam,
#[msg("Place and take order success condition failed")]
PlaceAndTakeOrderSuccessConditionFailed,
}
}
pub mod events {
Expand Down
Loading

0 comments on commit 9e08dbe

Please sign in to comment.