Skip to content

Commit

Permalink
revert risk parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
sunce86 committed Apr 2, 2024
1 parent e2507cb commit bc6d339
Show file tree
Hide file tree
Showing 22 changed files with 178 additions and 16 deletions.
1 change: 1 addition & 0 deletions crates/solvers/config/example.baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ chain-id = "1"
base-tokens = []
max-hops = 0
max-partial-attempts = 5
risk-parameters = [0,0,0,0]
# solution-gas-offset = 106391 # rough estimate of the settlement overhead
1 change: 1 addition & 0 deletions crates/solvers/config/example.naive.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
risk-parameters = [0,0,0,0]
3 changes: 3 additions & 0 deletions crates/solvers/src/domain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ pub mod eth;
pub mod liquidity;
pub mod notification;
pub mod order;
mod risk;
pub mod solution;
pub mod solver;

pub use risk::Risk;
26 changes: 26 additions & 0 deletions crates/solvers/src/domain/risk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use super::{auction::GasPrice, eth::Gas};

/// Parameters that define the possibility of a revert when executing a
/// solution.
#[derive(Debug, Default, Clone)]
pub struct Risk {
pub gas_amount_factor: f64,
pub gas_price_factor: f64,
pub nmb_orders_factor: f64,
pub intercept: f64,
}

impl Risk {
pub fn success_probability(
&self,
gas_amount: Gas,
gas_price: GasPrice,
nmb_orders: usize,
) -> f64 {
let exponent = -self.intercept
- self.gas_amount_factor * gas_amount.0.to_f64_lossy() / 1_000_000.
- self.gas_price_factor * gas_price.0 .0.to_f64_lossy() / 10_000_000_000.
- self.nmb_orders_factor * nmb_orders as f64;
1. / (1. + exponent.exp())
}
}
7 changes: 7 additions & 0 deletions crates/solvers/src/domain/solver/baseline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use {
crate::{
boundary,
domain::{
self,
auction,
eth,
liquidity,
Expand All @@ -31,6 +32,7 @@ pub struct Config {
pub base_tokens: Vec<eth::TokenAddress>,
pub max_hops: usize,
pub max_partial_attempts: usize,
pub risk: domain::Risk,
pub solution_gas_offset: eth::SignedGas,
}

Expand All @@ -55,6 +57,10 @@ struct Inner {
/// Basically we continuously halve the amount to execute until we find a
/// valid solution or exceed this count.
max_partial_attempts: usize,

/// Parameters used to calculate the revert risk of a solution.
risk: domain::Risk,

/// Units of gas that get added to the gas estimate for executing a
/// computed trade route to arrive at a gas estimate for a whole settlement.
solution_gas_offset: eth::SignedGas,
Expand All @@ -68,6 +74,7 @@ impl Baseline {
base_tokens: config.base_tokens.into_iter().collect(),
max_hops: config.max_hops,
max_partial_attempts: config.max_partial_attempts,
risk: config.risk,
solution_gas_offset: config.solution_gas_offset,
}))
}
Expand Down
16 changes: 14 additions & 2 deletions crates/solvers/src/domain/solver/naive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,26 @@
use {
crate::{
boundary,
domain::{auction, eth, liquidity, order, solution},
domain::{self, auction, eth, liquidity, order, solution},
},
std::collections::HashMap,
};

pub struct Naive;
pub struct Config {
pub risk: domain::Risk,
}

pub struct Naive {
/// Parameters used to calculate the revert risk of a solution.
risk: domain::Risk,
}

impl Naive {
/// Creates a new naive solver for the specified configuration.
pub fn new(config: Config) -> Self {
Self { risk: config.risk }
}

/// Solves the specified auction, returning a vector of all possible
/// solutions.
pub async fn solve(&self, auction: auction::Auction) -> Vec<solution::Solution> {
Expand Down
5 changes: 4 additions & 1 deletion crates/solvers/src/infra/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ pub enum Command {
config: PathBuf,
},
/// optimistically batch similar orders and get difference from AMMs
Naive,
Naive {
#[clap(long, env)]
config: PathBuf,
},
/// forward auction to solver implementing the legacy HTTP interface
Legacy {
#[clap(long, env)]
Expand Down
13 changes: 12 additions & 1 deletion crates/solvers/src/infra/config/baseline.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use {
crate::{
domain::{eth, solver::baseline},
domain::{eth, solver::baseline, Risk},
infra::{config::unwrap_or_log, contracts},
util::serialize,
},
Expand Down Expand Up @@ -38,6 +38,11 @@ struct Config {
/// The maximum number of pieces to divide partially fillable limit orders
/// when trying to solve it against baseline liquidity.
max_partial_attempts: usize,

/// Parameters used to calculate the revert risk of a solution.
/// (gas_amount_factor, gas_price_factor, nmb_orders_factor, intercept)
risk_parameters: (f64, f64, f64, f64),

/// Units of gas that get added to the gas estimate for executing a
/// computed trade route to arrive at a gas estimate for a whole settlement.
#[serde(default = "default_gas_offset")]
Expand Down Expand Up @@ -76,6 +81,12 @@ pub async fn load(path: &Path) -> baseline::Config {
.collect(),
max_hops: config.max_hops,
max_partial_attempts: config.max_partial_attempts,
risk: Risk {
gas_amount_factor: config.risk_parameters.0,
gas_price_factor: config.risk_parameters.1,
nmb_orders_factor: config.risk_parameters.2,
intercept: config.risk_parameters.3,
},
solution_gas_offset: config.solution_gas_offset.into(),
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/solvers/src/infra/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt::Debug;

pub mod baseline;
pub mod legacy;
pub mod naive;

/// Unwraps result or logs a `TOML` parsing error.
fn unwrap_or_log<T, E, P>(result: Result<T, E>, path: &P) -> T
Expand Down
40 changes: 40 additions & 0 deletions crates/solvers/src/infra/config/naive.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use {
crate::{
domain::{solver::naive, Risk},
infra::config::unwrap_or_log,
},
serde::Deserialize,
serde_with::serde_as,
std::path::Path,
tokio::fs,
};

#[serde_as]
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct Config {
/// Parameters used to calculate the revert risk of a solution.
/// (gas_amount_factor, gas_price_factor, nmb_orders_factor, intercept)
risk_parameters: (f64, f64, f64, f64),
}

/// Load the driver configuration from a TOML file.
///
/// # Panics
///
/// This method panics if the config is invalid or on I/O errors.
pub async fn load(path: &Path) -> naive::Config {
let data = fs::read_to_string(path)
.await
.unwrap_or_else(|e| panic!("I/O error while reading {path:?}: {e:?}"));
// Not printing detailed error because it could potentially leak secrets.
let config = unwrap_or_log(toml::de::from_str::<Config>(&data), &path);
naive::Config {
risk: Risk {
gas_amount_factor: config.risk_parameters.0,
gas_price_factor: config.risk_parameters.1,
nmb_orders_factor: config.risk_parameters.2,
intercept: config.risk_parameters.3,
},
}
}
5 changes: 4 additions & 1 deletion crates/solvers/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ async fn run_with(args: cli::Args, bind: Option<oneshot::Sender<SocketAddr>>) {
let config = config::baseline::load(&config).await;
Solver::Baseline(solver::Baseline::new(config))
}
cli::Command::Naive => Solver::Naive(solver::Naive),
cli::Command::Naive { config } => {
let config = config::naive::load(&config).await;
Solver::Naive(solver::Naive::new(config))
}
cli::Command::Legacy { config } => {
let config = config::legacy::load(&config).await;
Solver::Legacy(solver::Legacy::new(config))
Expand Down
4 changes: 4 additions & 0 deletions crates/solvers/src/tests/baseline/bal_liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ async fn weighted() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -133,6 +134,7 @@ async fn weighted_v3plus() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -247,6 +249,7 @@ async fn stable() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -414,6 +417,7 @@ async fn composable_stable_v4() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down
5 changes: 5 additions & 0 deletions crates/solvers/src/tests/baseline/buy_order_rounding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ async fn balancer_weighted() {
base-tokens = ["0x9c58bacc331c9aa871afd802db6379a98e80cedb"]
max-hops = 1
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -284,6 +285,7 @@ async fn balancer_weighted_v3plus() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -398,6 +400,7 @@ async fn distant_convergence() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -512,6 +515,7 @@ async fn same_path() {
base-tokens = ["0x9c58bacc331c9aa871afd802db6379a98e80cedb"]
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down Expand Up @@ -662,6 +666,7 @@ async fn balancer_stable() {
base-tokens = []
max-hops = 0
max-partial-attempts = 1
risk-parameters = [0,0,0,0]
"#
.to_owned(),
),
Expand Down
6 changes: 5 additions & 1 deletion crates/solvers/src/tests/naive/extract_deepest_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ use {crate::tests, serde_json::json};

#[tokio::test]
async fn test() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ use {crate::tests, serde_json::json};

#[tokio::test]
async fn sell_orders_on_both_sides() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down
6 changes: 5 additions & 1 deletion crates/solvers/src/tests/naive/limit_order_price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ use {crate::tests, serde_json::json};

#[tokio::test]
async fn test() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down
24 changes: 20 additions & 4 deletions crates/solvers/src/tests/naive/matches_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ use {crate::tests, serde_json::json};

#[tokio::test]
async fn sell_orders_on_both_sides() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down Expand Up @@ -108,7 +112,11 @@ async fn sell_orders_on_both_sides() {

#[tokio::test]
async fn sell_orders_on_one_side() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down Expand Up @@ -211,7 +219,11 @@ async fn sell_orders_on_one_side() {

#[tokio::test]
async fn buy_orders_on_both_sides() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down Expand Up @@ -314,7 +326,11 @@ async fn buy_orders_on_both_sides() {

#[tokio::test]
async fn buy_and_sell_orders() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down
6 changes: 5 additions & 1 deletion crates/solvers/src/tests/naive/reserves_too_small.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ use {crate::tests, serde_json::json};

#[tokio::test]
async fn test() {
let engine = tests::SolverEngine::new("naive", tests::Config::None).await;
let engine = tests::SolverEngine::new(
"naive",
tests::Config::String(r#"risk-parameters = [0,0,0,0]"#.to_owned()),
)
.await;

let solution = engine
.solve(json!({
Expand Down
Loading

0 comments on commit bc6d339

Please sign in to comment.