Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define protocol fee params and forward to driver #2098

Merged
merged 25 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from 9 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
37 changes: 37 additions & 0 deletions crates/autopilot/src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ pub struct Arguments {
)]
pub solve_deadline: Duration,

#[clap(flatten)]
pub quote_deviation_policy: QuoteDeviationPolicy,
sunce86 marked this conversation as resolved.
Show resolved Hide resolved

/// Time interval in days between each cleanup operation of the
/// `order_events` database table.
#[clap(long, env, default_value = "1", value_parser = duration_from_days)]
Expand Down Expand Up @@ -284,6 +287,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)?;
write!(f, "{}", self.quote_deviation_policy)?;
writeln!(
f,
"order_events_cleanup_interval: {:?}",
Expand All @@ -298,6 +302,39 @@ impl std::fmt::Display for Arguments {
}
}

#[derive(clap::Parser, Clone)]
pub struct QuoteDeviationPolicy {
/// How much of the order's surplus should be taken as a protocol fee.
#[clap(
long,
env,
default_value = "0",
value_parser = shared::arguments::parse_percentage_factor
)]
pub protocol_fee_factor: f64,
sunce86 marked this conversation as resolved.
Show resolved Hide resolved

/// Cap protocol fee with a percentage of the order's volume.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the --help text refers to a percentage when it's actually a factor that is to be understood as a percentage. Slight difference that bit us in the past.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we are covered with the parsing function that makes sure it's a factor. We also have a factor in the variable name. I wanted to keep the comments focused on the meaning.

Copy link
Contributor

@MartinquaXD MartinquaXD Dec 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sure that the value entered is in [0,1] but it doesn't make sure that what you provided is actually what you intended. Take slippage for example where it makes sense to configure 0.5%. We had a CLI argument in the past that claimed it was a percentage so we passed in 0.5 which then ended up allowing 50% relative slippage. Despite using shared::arguments::parse_percentage_factor it took us a while to notice the error. 😬

We also have a factor in the variable name.

This is true but I think with MFW's recent push to make the repo more contributor friendly it still makes sense to be precise in the --help text.
It could be as short as:
Cap protocol fee with a percentage of the order's volume. (1.0 meaning 100%)

#[clap(
long,
env,
default_value = "0",
value_parser = shared::arguments::parse_percentage_factor
)]
pub protocol_fee_volume_cap_factor: f64,
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
}

impl std::fmt::Display for QuoteDeviationPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "protocol_fee_factor: {}", self.protocol_fee_factor)?;
writeln!(
f,
"protocol_fee_volume_cap_factor: {}",
self.protocol_fee_volume_cap_factor
)?;
Ok(())
}
}

fn duration_from_days(s: &str) -> Result<Duration, ParseFloatError> {
let days = s.parse::<f64>()?;
Ok(Duration::from_secs_f64(days * 86_400.0))
Expand Down
28 changes: 28 additions & 0 deletions crates/autopilot/src/driver_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ pub mod solve {
pub app_data: AppDataHash,
#[serde(flatten)]
pub signature: Signature,
/// The types of fees that should be collected by the protocol.
/// The driver is expected to apply the fees in the order they are
/// listed.
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
pub fee_policies: Vec<FeePolicy>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -150,6 +154,30 @@ pub mod solve {
pub submission_address: H160,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
#[serde(rename_all = "camelCase")]
pub enum FeePolicy {
/// Applies to limit orders only.
/// This fee should be taken if the solver provided good enough solution
/// 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].
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
QuoteDeviation {
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
/// Percentage of the order's `available surplus` should be taken as
/// a protocol fee.
///
/// `Available surplus` is the difference between the executed_price
/// (adjusted by surplus_fee) and the closer of the two: order
/// limit_price or best_quote. For out-of-market limit orders,
/// order limit price is closer to the executed price. For
/// in-market limit orders, best quote is closer to the executed
/// price.
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
factor: f64,
/// Cap protocol fee with a percentage of the order's volume.
volume_cap_factor: f64,
},
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Response {
Expand Down
2 changes: 2 additions & 0 deletions crates/autopilot/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +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,
quote_deviation_policy: args.quote_deviation_policy,
};
run.run_forever().await;
unreachable!("run loop exited");
Expand Down Expand Up @@ -691,6 +692,7 @@ async fn shadow_mode(args: Arguments) -> ! {
trusted_tokens,
args.score_cap,
args.solve_deadline,
args.quote_deviation_policy,
);
shadow.run_forever().await;

Expand Down
17 changes: 16 additions & 1 deletion crates/autopilot/src/run_loop.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use {
crate::{
arguments::QuoteDeviationPolicy,
database::{
competition::{Competition, ExecutedFee, OrderExecution},
Postgres,
Expand All @@ -8,7 +9,7 @@ use {
driver_model::{
reveal::{self, Request},
settle,
solve::{self, Class},
solve::{self, Class, FeePolicy},
},
solvable_orders::SolvableOrdersCache,
},
Expand Down Expand Up @@ -54,6 +55,7 @@ pub struct RunLoop {
pub score_cap: U256,
pub max_settlement_transaction_wait: Duration,
pub solve_deadline: Duration,
pub quote_deviation_policy: QuoteDeviationPolicy,
}

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

Expand Down Expand Up @@ -449,6 +452,7 @@ pub fn solve_request(
trusted_tokens: &HashSet<H160>,
score_cap: U256,
time_limit: Duration,
quote_deviation_policy: QuoteDeviationPolicy,
) -> solve::Request {
solve::Request {
id,
Expand All @@ -474,6 +478,16 @@ pub fn solve_request(
.collect()
};
let order_is_untouched = remaining_order.executed_amount.is_zero();
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,
}],
};
solve::Order {
uid: order.metadata.uid,
sell_token: order.data.sell_token,
Expand All @@ -499,6 +513,7 @@ pub fn solve_request(
class,
app_data: order.data.app_data,
signature: order.signature.clone(),
fee_policies,
}
})
.collect(),
Expand Down
10 changes: 9 additions & 1 deletion crates/autopilot/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@

use {
crate::{
arguments::QuoteDeviationPolicy,
driver_api::Driver,
driver_model::{reveal, solve},
driver_model::{
reveal,
solve::{self},
},
protocol,
run_loop,
},
Expand Down Expand Up @@ -43,6 +47,7 @@ pub struct RunLoop {
block: u64,
score_cap: U256,
solve_deadline: Duration,
quote_deviation_policy: QuoteDeviationPolicy,
}

impl RunLoop {
Expand All @@ -52,6 +57,7 @@ impl RunLoop {
trusted_tokens: AutoUpdatingTokenList,
score_cap: U256,
solve_deadline: Duration,
quote_deviation_policy: QuoteDeviationPolicy,
) -> Self {
Self {
orderbook,
Expand All @@ -61,6 +67,7 @@ impl RunLoop {
block: 0,
score_cap,
solve_deadline,
quote_deviation_policy,
}
}

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

Expand Down
22 changes: 22 additions & 0 deletions crates/driver/src/domain/competition/order/fees.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#[derive(Clone, Debug)]
pub enum FeePolicy {
/// Applies to limit orders only.
/// This fee should be taken if the solver provided good enough solution
/// 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].
QuoteDeviation {
/// Percentage of the order's `available surplus` should be taken as a
/// protocol fee.
///
/// `Available surplus` is the difference between the executed_price
/// (adjusted by surplus_fee) and the closer of the two: order
/// limit_price or best_quote. For out-of-market limit orders,
/// order limit price is closer to the executed price. For
/// in-market limit orders, best quote is closer to the executed
/// price.
factor: f64,
/// Cap protocol fee with a percentage of the order's volume.
volume_cap_factor: f64,
},
}
7 changes: 6 additions & 1 deletion crates/driver/src/domain/competition/order/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub use signature::Signature;
use {
super::auction,
crate::{
Expand All @@ -9,7 +8,9 @@ use {
bigdecimal::Zero,
num::CheckedDiv,
};
pub use {fees::FeePolicy, signature::Signature};

pub mod fees;
pub mod signature;

/// An order in the auction.
Expand Down Expand Up @@ -39,6 +40,9 @@ pub struct Order {
pub sell_token_balance: SellTokenBalance,
pub buy_token_balance: BuyTokenBalance,
pub signature: Signature,
/// The types of fees that should be collected by the protocol.
/// The driver is expected to apply the fees in the order they are listed.
pub fee_policies: Vec<FeePolicy>,
sunce86 marked this conversation as resolved.
Show resolved Hide resolved
}

/// An amount denominated in the sell token of an [`Order`].
Expand Down Expand Up @@ -453,6 +457,7 @@ mod tests {
data: Default::default(),
signer: Default::default(),
},
fee_policies: Default::default(),
};

assert_eq!(
Expand Down
1 change: 1 addition & 0 deletions crates/driver/src/domain/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ impl Order {
data: Default::default(),
signer: Default::default(),
},
fee_policies: Default::default(),
}],
[
auction::Token {
Expand Down
20 changes: 20 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 @@ -115,6 +115,19 @@ impl Auction {
data: order.signature.into(),
signer: order.owner.into(),
},
fee_policies: order
.fee_policies
.into_iter()
.map(|policy| match policy {
FeePolicy::QuoteDeviation {
factor,
volume_cap_factor,
} => competition::order::FeePolicy::QuoteDeviation {
factor,
volume_cap_factor,
},
})
.collect(),
})
.collect(),
self.tokens.into_iter().map(|token| {
Expand Down Expand Up @@ -234,6 +247,7 @@ struct Order {
signing_scheme: SigningScheme,
#[serde_as(as = "serialize::Hex")]
signature: Vec<u8>,
fee_policies: Vec<FeePolicy>,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -287,3 +301,9 @@ enum Class {
Limit,
Liquidity,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
enum FeePolicy {
QuoteDeviation { factor: f64, volume_cap_factor: f64 },
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the dto also have documentation (so that it can be generated for the swagger docs)?

8 changes: 7 additions & 1 deletion crates/driver/src/tests/setup/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,13 @@ pub fn solve_req(test: &Test) -> serde_json::Value {
},
"appData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"signingScheme": "eip712",
"signature": format!("0x{}", hex::encode(quote.order_signature(&test.blockchain)))
"signature": format!("0x{}", hex::encode(quote.order_signature(&test.blockchain))),
"feePolicies": [{
"quoteDeviation": {
"factor": 0.5,
"volume_cap_factor": 0.06,
}
}],
}));
}
for fulfillment in test.fulfillments.iter() {
Expand Down
Loading