Skip to content
Open
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
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/solana-solvers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ axum = { workspace = true }
base64 = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
const-hex = { workspace = true }
futures = { workspace = true }
observe = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true, features = ["derive"] }
Expand Down
17 changes: 8 additions & 9 deletions crates/solana-solvers/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
//! HTTP API for the solver engine.
//!
//! Serves the `/solve` contract the driver calls. The handler is a scaffold: it
//! accepts any auction and returns no solutions.
//! Serves the `/solve` contract the driver calls.

use {
crate::config::Config,
crate::{dex::Dex, domain::solver, dto::auction::Auction},
axum::{
Json,
Router,
Expand All @@ -20,7 +19,7 @@ const REQUEST_BODY_LIMIT: usize = 10 * 1024 * 1024;

pub struct Api {
pub addr: SocketAddr,
pub config: Config,
pub dex: Arc<Dex>,
}

impl Api {
Expand All @@ -32,7 +31,7 @@ impl Api {
let app = Router::new()
.route("/healthz", get(healthz))
.route("/solve", post(solve))
.with_state(Arc::new(self.config))
.with_state(self.dex)
.layer(RequestBodyLimitLayer::new(REQUEST_BODY_LIMIT))
.layer(axum::extract::DefaultBodyLimit::disable());

Expand All @@ -48,8 +47,8 @@ async fn healthz() -> &'static str {
"ok"
}

/// Scaffold `/solve`: accepts any auction and returns no solutions, so the
/// driver wiring can be exercised against an empty result.
async fn solve(State(_config): State<Arc<Config>>, Json(_auction): Json<Value>) -> Json<Value> {
Json(json!({ "solutions": [] }))
/// Quote every order in the auction and return the single-order solutions.
async fn solve(State(dex): State<Arc<Dex>>, Json(auction): Json<Auction>) -> Json<Value> {
let solutions = solver::solve(dex.as_ref(), &auction).await;
Json(json!({ "solutions": solutions }))
}
3 changes: 2 additions & 1 deletion crates/solana-solvers/src/dex/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ pub struct Order {
pub side: Side,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Side {
Buy,
Sell,
Expand Down
4 changes: 4 additions & 0 deletions crates/solana-solvers/src/domain/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//! Domain logic: the solve loop that quotes each auction order and assembles
//! the solutions the driver consumes.

pub mod solver;
124 changes: 124 additions & 0 deletions crates/solana-solvers/src/domain/solver/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//! Solve loop: quote each auction order and assemble single-order solutions.

use {
crate::{
dex::{self, Dex},
dto::{auction::Auction, solution::Solution},
},
futures::future::join_all,
solana_sdk::pubkey::Pubkey,
std::future::Future,
};

/// Quotes one order into a swap. A seam over [`Dex`] so the loop is testable
/// without the network.
pub trait Quote {
fn quote(
&self,
order: &dex::Order,
taker: &Pubkey,
) -> impl Future<Output = Result<dex::Swap, dex::jupiter::Error>> + Send;
}

impl Quote for Dex {
fn quote(
&self,
order: &dex::Order,
taker: &Pubkey,
) -> impl Future<Output = Result<dex::Swap, dex::jupiter::Error>> + Send {
self.swap(order, taker)
}
}

/// Quote every order concurrently and return one single-order solution per
/// routable order. Buys (when disabled) and orders the aggregator cannot route
/// yield no candidate, the rest of the auction still proceeds.
///
/// Order counts are small (bounded by the settlement account budget), so every
/// order is quoted at once.
pub async fn solve<Q: Quote>(quoter: &Q, auction: &Auction) -> Vec<Solution> {
let candidates = auction.orders.iter().enumerate().map(|(index, order)| {
let dex_order = order.to_dex_order();
async move {
let swap = quoter.quote(&dex_order, &auction.taker).await.ok()?;
Solution::new(index as u64, order.uid, &dex_order, swap).ok()
}
});
join_all(candidates).await.into_iter().flatten().collect()
}

#[cfg(test)]
mod tests {
use {
super::*,
crate::dto::{auction, order::OrderUid},
};

fn pubkey(byte: u8) -> Pubkey {
Pubkey::new_from_array([byte; 32])
}

fn order(uid: u8, side: dex::Side, sell_mint: Pubkey) -> auction::Order {
auction::Order {
uid: OrderUid([uid; 32]),
sell_mint,
buy_mint: pubkey(2),
buy_destination: pubkey(3),
amount: 1_000,
side,
}
}

/// Routes any sell except the `0xff` sell mint, rejects buys.
struct MockQuote;

impl Quote for MockQuote {
fn quote(
&self,
order: &dex::Order,
_taker: &Pubkey,
) -> impl Future<Output = Result<dex::Swap, dex::jupiter::Error>> + Send {
let result = match order.side {
dex::Side::Buy => Err(dex::jupiter::Error::OrderNotSupported),
dex::Side::Sell if order.sell_mint == pubkey(0xff) => {
Err(dex::jupiter::Error::NotFound)
}
dex::Side::Sell => Ok(dex::Swap {
in_amount: 1_000,
out_amount: 2_000,
instructions: vec![],
address_lookup_tables: vec![],
}),
};
async move { result }
}
}

#[tokio::test]
async fn emits_one_solution_per_routable_order() {
let auction = Auction {
id: 1,
taker: pubkey(1),
orders: vec![
order(0x01, dex::Side::Sell, pubkey(0x10)), // routable
order(0x02, dex::Side::Sell, pubkey(0xff)), // no route
order(0x03, dex::Side::Buy, pubkey(0x11)), // buys disabled
],
};

let solutions = solve(&MockQuote, &auction).await;

assert_eq!(solutions.len(), 1);
assert_eq!(solutions[0].trades[0].order_uid, OrderUid([0x01; 32]));
}

#[tokio::test]
async fn empty_auction_yields_no_solutions() {
let auction = Auction {
id: 1,
taker: pubkey(1),
orders: vec![],
};
assert!(solve(&MockQuote, &auction).await.is_empty());
}
}
59 changes: 59 additions & 0 deletions crates/solana-solvers/src/dto/auction.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! Inbound `/solve` auction: the orders the driver asks the solver to fill.
//!
//! Proposed shape. The driver spec pins the solution response, not the auction
//! request, so these are the fields the solve loop needs and will be reconciled
//! with the driver's request DTO.

use {
super::order::OrderUid,
crate::dex,
serde::Deserialize,
serde_with::serde_as,
solana_sdk::pubkey::Pubkey,
};

/// The auction the driver posts to `/solve`.
#[serde_as]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Auction {
pub id: u64,
/// Settlement signer the swap instructions are built for.
#[serde_as(as = "serde_with::DisplayFromStr")]
pub taker: Pubkey,
pub orders: Vec<Order>,
}

/// One order to quote.
#[serde_as]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
#[serde_as(as = "serde_with::DisplayFromStr")]
pub uid: OrderUid,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub sell_mint: Pubkey,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub buy_mint: Pubkey,
/// The buy-mint buffer the swap output lands in.
#[serde_as(as = "serde_with::DisplayFromStr")]
pub buy_destination: Pubkey,
/// Sell amount for a sell, buy amount for a buy. Decimal string on the
/// wire.
#[serde_as(as = "serde_with::DisplayFromStr")]
pub amount: u64,
pub side: dex::Side,
}

impl Order {
/// The adapter-facing view of this order.
pub fn to_dex_order(&self) -> dex::Order {
dex::Order {
sell_mint: self.sell_mint,
buy_mint: self.buy_mint,
buy_destination: self.buy_destination,
amount: self.amount,
side: self.side,
}
}
}
4 changes: 3 additions & 1 deletion crates/solana-solvers/src/dto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! Wire DTOs the solver engine emits: the solution the driver consumes.
//! Wire DTOs: the inbound `/solve` auction the driver posts and the solution
//! the solver emits back.

pub mod auction;
pub mod order;
pub mod solution;
10 changes: 10 additions & 0 deletions crates/solana-solvers/src/dto/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,13 @@ impl serde::Serialize for OrderUid {
serializer.collect_str(self)
}
}

impl std::str::FromStr for OrderUid {
type Err = const_hex::FromHexError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut bytes = [0u8; 32];
const_hex::decode_to_slice(s.strip_prefix("0x").unwrap_or(s), &mut bytes)?;
Ok(Self(bytes))
}
}
1 change: 1 addition & 0 deletions crates/solana-solvers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod api;
mod cli;
pub mod config;
pub mod dex;
pub mod domain;
pub mod dto;
mod run;

Expand Down
6 changes: 5 additions & 1 deletion crates/solana-solvers/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ use {
api::Api,
cli::{Args, Command},
config,
dex,
},
clap::Parser,
std::sync::Arc,
};

/// Parse args and run the selected solver engine until shutdown.
Expand All @@ -28,9 +30,11 @@ pub async fn start(args: impl IntoIterator<Item = String>) {
match args.command {
Command::Jupiter { config: path } => {
let config = config::load(&path).await;
let jupiter = dex::jupiter::Jupiter::new(&config.dex)
.unwrap_or_else(|err| panic!("build jupiter dex: {err}"));
let api = Api {
addr: args.addr,
config,
dex: Arc::new(dex::Dex::Jupiter(jupiter)),
};
if let Err(err) = api.serve(shutdown_signal()).await {
tracing::error!(?err, "server error");
Expand Down
Loading