Skip to content

Commit

Permalink
Fix arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
sunce86 committed Dec 5, 2023
1 parent f783d68 commit 1e79009
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 88 deletions.
61 changes: 16 additions & 45 deletions crates/autopilot/src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use {
std::{
net::SocketAddr,
num::{NonZeroUsize, ParseFloatError},
str::FromStr,
time::Duration,
},
url::Url,
Expand Down Expand Up @@ -209,10 +208,9 @@ pub struct Arguments {
)]
pub solve_deadline: Duration,

/// A list of fee policies in the following format: `[LimitOrderOutOfMarket:0.1:0.2,LimitOrderInMarket::2.5]`
///
#[clap(long, env, use_value_delimiter = true)]
pub fee_policies: Vec<FeePolicy>,
/// Describes how the protocol fee should be calculated.
#[clap(flatten)]
pub fee_policy: FeePolicy,

/// Time interval in days between each cleanup operation of the
/// `order_events` database table.
Expand Down Expand Up @@ -290,7 +288,7 @@ impl std::fmt::Display for Arguments {
writeln!(f, "score_cap: {}", self.score_cap)?;
display_option(f, "shadow", &self.shadow)?;
writeln!(f, "solve_deadline: {:?}", self.solve_deadline)?;
display_list(f, "fee_policies", self.fee_policies.iter())?;
writeln!(f, "fee_policy: {}", self.fee_policy)?;
writeln!(
f,
"order_events_cleanup_interval: {:?}",
Expand All @@ -306,44 +304,7 @@ impl std::fmt::Display for Arguments {
}

#[derive(clap::Parser, Clone)]
pub enum FeePolicy {
LimitOrderOutOfMarket(FeePolicyParams),
LimitOrderInMarket(FeePolicyParams),
}

impl FromStr for FeePolicy {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split(':');
let policy = parts.next().unwrap();
let params = FeePolicyParams {
price_improvement_factor: parts.next().unwrap().parse().ok(),
volume_factor: parts.next().unwrap().parse().ok(),
};
match policy {
"LimitOrderOutOfMarket" => Ok(FeePolicy::LimitOrderOutOfMarket(params)),
"LimitOrderInMarket" => Ok(FeePolicy::LimitOrderInMarket(params)),
_ => Err(anyhow::anyhow!("Unknown fee policy: {}", policy)),
}
}
}

impl std::fmt::Display for FeePolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FeePolicy::LimitOrderOutOfMarket(params) => {
write!(f, "LimitOrderOutOfMarket {{ {} }}", params)
}
FeePolicy::LimitOrderInMarket(params) => {
write!(f, "LimitOrderInMarket {{ {} }}", params)
}
}
}
}

#[derive(clap::Parser, Clone)]
pub struct FeePolicyParams {
pub struct FeePolicy {
/// How much of the order's price improvement over max(limit price,
/// best_bid) should be taken as a protocol fee.
#[clap(
Expand All @@ -353,6 +314,7 @@ pub struct FeePolicyParams {
value_parser = shared::arguments::parse_percentage_factor
)]
pub price_improvement_factor: Option<f64>,

/// How much of the order's volume should be taken as a protocol fee.
#[clap(
long,
Expand All @@ -361,9 +323,18 @@ pub struct FeePolicyParams {
value_parser = shared::arguments::parse_percentage_factor
)]
pub volume_factor: Option<f64>,

/// Should protocol fees be collected or skipped for limit orders with
/// in-market price at the time of order creation.
#[clap(long, env, default_value = "true")]
pub skip_in_market_orders: bool,

/// Should protocol fees be collected or skipped for TWAP limit orders.
#[clap(long, env, default_value = "true")]
pub skip_twap_orders: bool,
}

impl std::fmt::Display for FeePolicyParams {
impl std::fmt::Display for FeePolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
Expand Down
12 changes: 11 additions & 1 deletion crates/autopilot/src/driver_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ pub mod solve {
/// that even after the surplus fee is taken, there is still more
/// surplus left above whatever the user expects [order limit price
/// or best quote, whichever is better for the user].
/// The fee is taken in `sell` token for `buy` orders and in `buy`
/// token for `sell` orders.
QuoteDeviation {
/// Percentage of the order's `available surplus` should be taken as
/// a protocol fee.
Expand All @@ -174,7 +176,15 @@ pub mod solve {
/// price.
factor: f64,
/// Cap protocol fee with a percentage of the order's volume.
volume_cap_factor: f64,
volume_cap_factor: Option<f64>,
},
/// How much of the order's volume should be taken as a protocol fee.
/// The fee is taken in `sell` token for `sell` orders and in `buy`
/// token for `buy` orders.
Volume {
/// Percentage of the order's volume should be taken as a protocol
/// fee.
factor: f64,
},
}

Expand Down
4 changes: 2 additions & 2 deletions crates/autopilot/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ pub async fn run(args: Arguments) {
score_cap: args.score_cap,
max_settlement_transaction_wait: args.max_settlement_transaction_wait,
solve_deadline: args.solve_deadline,
fee_policies: args.fee_policies,
fee_policy: args.fee_policy,
};
run.run_forever().await;
unreachable!("run loop exited");
Expand Down Expand Up @@ -692,7 +692,7 @@ async fn shadow_mode(args: Arguments) -> ! {
trusted_tokens,
args.score_cap,
args.solve_deadline,
args.fee_policies,
args.fee_policy,
);
shadow.run_forever().await;

Expand Down
61 changes: 25 additions & 36 deletions crates/autopilot/src/run_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub struct RunLoop {
pub score_cap: U256,
pub max_settlement_transaction_wait: Duration,
pub solve_deadline: Duration,
pub fee_policies: Vec<arguments::FeePolicy>,
pub fee_policy: arguments::FeePolicy,
}

impl RunLoop {
Expand Down Expand Up @@ -304,7 +304,7 @@ impl RunLoop {
&self.market_makable_token_list.all(),
self.score_cap,
self.solve_deadline,
self.fee_policies.clone(),
self.fee_policy.clone(),
);
let request = &request;

Expand Down Expand Up @@ -452,7 +452,7 @@ pub fn solve_request(
trusted_tokens: &HashSet<H160>,
score_cap: U256,
time_limit: Duration,
fee_policies: Vec<arguments::FeePolicy>,
fee_policy: arguments::FeePolicy,
) -> solve::Request {
solve::Request {
id,
Expand All @@ -478,39 +478,28 @@ pub fn solve_request(
.collect()
};
let order_is_untouched = remaining_order.executed_amount.is_zero();
let fee_policies = fee_policies
.iter()
.filter_map(|policy| match policy {
arguments::FeePolicy::LimitOrderInMarket(params) => {
tracing::warn!("LimitOrderInMarket fee policy not yet supported");
None
}
arguments::FeePolicy::LimitOrderOutOfMarket(params) => {
match params.price_improvement_factor {
Some(price_improvement_factor) => {
// todo
None
}
None => {
tracing::warn!("not supported yet");
None
}
}
}
})
.collect();

// let fee_policies = match order.metadata.class {
// OrderClass::Market => vec![],
// OrderClass::Liquidity => vec![],
// // todo https://github.com/cowprotocol/services/issues/2092
// // skip protocol fee for limit orders with in-market price
// // OrderClass::Limit(_) => vec![FeePolicy::QuoteDeviation {
// // factor: quote_deviation_policy.protocol_fee_factor,
// // volume_cap_factor:
// quote_deviation_policy.protocol_fee_volume_cap_factor, //
// }], OrderClass::Limit(_) => vec![],
// };
let fee_policy = match (
fee_policy.price_improvement_factor,
fee_policy.volume_factor,
) {
(Some(factor), volume_cap_factor) => Some(FeePolicy::QuoteDeviation {
factor,
volume_cap_factor,
}),
(None, Some(factor)) => Some(FeePolicy::Volume { factor }),
(_, _) => None,
};

let fee_policies = match order.metadata.class {
OrderClass::Market => vec![],
OrderClass::Liquidity => vec![],
// todo https://github.com/cowprotocol/services/issues/2092
// skip protocol fee for limit orders with in-market price

// todo https://github.com/cowprotocol/services/issues/2115
// skip protocol fee for TWAP limit orders
OrderClass::Limit(_) => fee_policy.map(|policy| vec![policy]).unwrap_or(vec![]),
};
solve::Order {
uid: order.metadata.uid,
sell_token: order.data.sell_token,
Expand Down
8 changes: 4 additions & 4 deletions crates/autopilot/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub struct RunLoop {
block: u64,
score_cap: U256,
solve_deadline: Duration,
fee_policies: Vec<FeePolicy>,
fee_policy: FeePolicy,
}

impl RunLoop {
Expand All @@ -57,7 +57,7 @@ impl RunLoop {
trusted_tokens: AutoUpdatingTokenList,
score_cap: U256,
solve_deadline: Duration,
fee_policies: Vec<FeePolicy>,
fee_policy: FeePolicy,
) -> Self {
Self {
orderbook,
Expand All @@ -67,7 +67,7 @@ impl RunLoop {
block: 0,
score_cap,
solve_deadline,
fee_policies,
fee_policy,
}
}

Expand Down Expand Up @@ -200,7 +200,7 @@ impl RunLoop {
&self.trusted_tokens.all(),
self.score_cap,
self.solve_deadline,
self.fee_policies.clone(),
self.fee_policy.clone(),
);
let request = &request;

Expand Down
10 changes: 10 additions & 0 deletions crates/driver/src/domain/competition/order/fees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ pub enum FeePolicy {
/// that even after the surplus fee is taken, there is still more
/// surplus left above whatever the user expects [order limit price
/// vs best quote].
/// The fee is taken in `sell` token for `buy` orders and in `buy`
/// token for `sell` orders.
QuoteDeviation {
/// Percentage of the order's `available surplus` should be taken as a
/// protocol fee.
Expand All @@ -19,4 +21,12 @@ pub enum FeePolicy {
/// Cap protocol fee with a percentage of the order's volume.
volume_cap_factor: f64,
},
/// How much of the order's volume should be taken as a protocol fee.
/// The fee is taken in `sell` token for `sell` orders and in `buy`
/// token for `buy` orders.
Volume {
/// Percentage of the order's volume should be taken as a protocol
/// fee.
factor: f64,
},
}
4 changes: 4 additions & 0 deletions crates/driver/src/infra/api/routes/solve/dto/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ impl Auction {
factor,
volume_cap_factor,
},
FeePolicy::Volume { factor } => {
competition::order::FeePolicy::Volume { factor }
}
})
.collect(),
})
Expand Down Expand Up @@ -306,4 +309,5 @@ enum Class {
#[serde(rename_all = "camelCase", deny_unknown_fields)]
enum FeePolicy {
QuoteDeviation { factor: f64, volume_cap_factor: f64 },
Volume { factor: f64 },
}
5 changes: 5 additions & 0 deletions crates/driver/src/tests/setup/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ pub fn solve_req(test: &Test) -> serde_json::Value {
"factor": 0.5,
"volume_cap_factor": 0.06,
}
},
{
"volume": {
"factor": 0.1,
}
}],
}));
}
Expand Down

0 comments on commit 1e79009

Please sign in to comment.