Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into auction-transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
fleupold committed Jan 24, 2024
2 parents f6a0152 + afcc32f commit 1e684c0
Show file tree
Hide file tree
Showing 24 changed files with 449 additions and 534 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/pull-request.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ jobs:
CARGO_PROFILE_DEV_DEBUG: 0
CARGO_PROFILE_TEST_DEBUG: 0
CARGO_TERM_COLOR: always
FORK_URL: ${{ secrets.FORK_URL }}
FORK_URL_MAINNET: ${{ secrets.FORK_URL_MAINNET }}
FORK_URL_GNOSIS: ${{ secrets.FORK_URL_GNOSIS }}
TOML_TRACE_ERROR: 1
steps:
- uses: actions/checkout@v3
Expand Down
42 changes: 42 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Contributing Guidelines

There are many ways to contribute to CoW Protocol. We welcome contributions of all kinds from anyone, whether you've been a long-time user or you are just getting started with development.

## Troubleshooting

You can help other users in the community to solve their issues in the [CoW Protocol Discord].

[CoW Protocol Discord]: https://discord.gg/cowprotocol
[CoW Protocol Forums]: https://forum.cow.fi

## Opening an issue

You can [open an issue] to suggest a feature or report a minor bug. For serious bugs please do not open an issue, instead refer to our [security policy] for appropriate steps.

If you believe your issue may be due to user error and not a problem in the library, consider instead posting a question on the [CoW Protocol Discord].

Before opening an issue, be sure to search through the existing open and closed issues, and consider posting a comment in one of those instead.

When requesting a new feature, include as many details as you can, especially around the use cases that motivate it.
Features are prioritised according to the impact they may have on the ecosystem, so we appreciate information showing that the impact could be high.

[security policy]: https://github.com/cowprotocol/services/security
[open an issue]: https://github.com/cowprotocol/services/issues/new/choose

## Submitting a pull request

If you would like to contribute code or documentation you may do so by forking the repository and submitting a pull request.

Any non-trivial documentation must be first discussed with the maintainers in an issue (see [Opening an issue](#opening-an-issue)). Only very minor changes are accepted without prior discussion.

When opening the pull request you will be presented with a template and a series of instructions. Read through it carefully and follow all the steps.
Expect a review and feedback from the maintainers afterwards.

If you're looking for a good place to start, look for issues labelled ["help wanted"](https://github.com/cowprotocol/services/labels/help%20wanted)!

## Reward for Contributions
We are excited to support our community's contributions in a tangible way.
For merged pull requests that contribute to issues labeled "help wanted", we are offering a reward of 100 DAI.
To be eligible for this reward, make sure your pull request meets all the required criteria and is successfully merged.

Please leave a Gnosis Chain address at which you'd like to receive the DAI either in the PR description or via Discord DM to *mastercow.eth*.
2 changes: 1 addition & 1 deletion crates/autopilot/src/boundary/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub use {
signature::{EcdsaSignature, Signature},
DomainSeparator,
},
shared::order_validation::is_order_outside_market_price,
shared::order_validation::{is_order_outside_market_price, Amounts},
};
use {ethrpc::Web3, url::Url};

Expand Down
20 changes: 12 additions & 8 deletions crates/autopilot/src/domain/fee/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,18 @@ impl ProtocolFee {
return vec![];
};

tracing::debug!(?order.metadata.uid, ?self.policy, ?order.data.sell_amount, ?order.data.buy_amount, ?quote, "checking if order is outside market price");
if boundary::is_order_outside_market_price(
&order.data.sell_amount,
&order.data.buy_amount,
&quote.buy_amount,
&quote.sell_amount,
&quote.fee,
) {
let order_ = boundary::Amounts {
sell: order.data.sell_amount,
buy: order.data.buy_amount,
fee: order.data.fee_amount,
};
let quote = boundary::Amounts {
sell: quote.sell_amount,
buy: quote.buy_amount,
fee: quote.fee,
};
tracing::debug!(?order.metadata.uid, ?self.policy, ?order_, ?quote, "checking if order is outside market price");
if boundary::is_order_outside_market_price(&order_, &quote) {
vec![self.policy]
} else {
vec![]
Expand Down
6 changes: 3 additions & 3 deletions crates/autopilot/src/run_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,12 +294,12 @@ impl RunLoop {
tracing::warn!(?err, driver = %driver.name, "settlement failed");
}
}
let unsettled_orders: Vec<_> = solutions
let unsettled_orders: HashSet<_> = solutions
.iter()
.flat_map(|p| p.solution.orders.keys())
.filter(|uid| !solution.orders.contains_key(uid))
.collect();
Metrics::matched_unsettled(driver, unsettled_orders.as_slice());
Metrics::matched_unsettled(driver, unsettled_orders);
}
}

Expand Down Expand Up @@ -689,7 +689,7 @@ impl Metrics {
.inc_by(time.as_millis().try_into().unwrap_or(u64::MAX));
}

fn matched_unsettled(winning: &infra::Driver, unsettled: &[&domain::OrderUid]) {
fn matched_unsettled(winning: &infra::Driver, unsettled: HashSet<&domain::OrderUid>) {
if !unsettled.is_empty() {
tracing::debug!(?unsettled, "some orders were matched but not settled");
}
Expand Down
6 changes: 4 additions & 2 deletions crates/contracts/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,14 +586,16 @@ fn main() {
builder
.add_network_str(MAINNET, "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f")
.add_network_str(GOERLI, "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f")
// Not available on Sepolia or Gnosis Chain
.add_network_str(GNOSIS, "0xA818b4F111Ccac7AA31D0BCc0806d64F2E0737D7")
// Not available on Sepolia
});
generate_contract_with_config("UniswapV2Router02", |builder| {
// <https://docs.uniswap.org/contracts/v2/reference/smart-contracts/router-02>
builder
.add_network_str(MAINNET, "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
.add_network_str(GOERLI, "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
// Not available on Sepolia or Gnosis Chain
.add_network_str(GNOSIS, "0x1C232F01118CB8B424793ae03F870aa7D0ac7f77")
// Not available on Sepolia
});
generate_contract_with_config("UniswapV3SwapRouter", |builder| {
// <https://github.com/Uniswap/v3-periphery/blob/697c2474757ea89fec12a4e6db16a574fe259610/deploys.md>
Expand Down
10 changes: 10 additions & 0 deletions crates/driver/src/boundary/mempool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub struct Config {
pub max_confirm_time: std::time::Duration,
pub retry_interval: std::time::Duration,
pub kind: Kind,
pub submission: SubmissionLogic,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -71,6 +72,15 @@ pub enum RevertProtection {
Disabled,
}

/// The submission logic to use for publishing settlements to the blockchain.
/// Can either use the battle tested legacy code, or the new domain native
/// driver logic.
#[derive(Debug, Clone)]
pub enum SubmissionLogic {
Boundary,
Native,
}

/// The mempool to use for publishing settlements to the blockchain.
#[derive(Clone)]
pub struct Mempool {
Expand Down
17 changes: 12 additions & 5 deletions crates/driver/src/domain/mempools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use {
super::eth,
crate::{
domain::competition::solution::Settlement,
infra::{self, observe, solver::Solver},
infra::{self, observe, solver::Solver, Ethereum},
},
futures::{future::select_ok, FutureExt},
thiserror::Error,
Expand All @@ -11,14 +11,14 @@ use {

/// The mempools used to execute settlements.
#[derive(Debug, Clone)]
pub struct Mempools(Vec<infra::Mempool>);
pub struct Mempools(Vec<infra::Mempool>, Ethereum);

impl Mempools {
pub fn new(mempools: Vec<infra::Mempool>) -> Result<Self, NoMempools> {
pub fn new(mempools: Vec<infra::Mempool>, ethereum: Ethereum) -> Result<Self, NoMempools> {
if mempools.is_empty() {
Err(NoMempools)
} else {
Ok(Self(mempools))
Ok(Self(mempools, ethereum))
}
}

Expand All @@ -33,7 +33,14 @@ impl Mempools {

let (tx_hash, _remaining_futures) = select_ok(self.0.iter().cloned().map(|mempool| {
async move {
let result = mempool.execute(solver, settlement.clone()).await;
let result = match &mempool {
infra::Mempool::Boundary(mempool) => {
mempool.execute(solver, settlement.clone()).await
}
infra::Mempool::Native(_) => {
todo!("implement")
}
};
observe::mempool_executed(&mempool, settlement, &result);
result
}
Expand Down
10 changes: 9 additions & 1 deletion crates/driver/src/infra/blockchain/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub struct GasPriceEstimator {
//TODO: remove visibility once boundary is removed
pub(super) gas: Arc<NativeGasEstimator>,
additional_tip: Option<AdditionalTip>,
max_fee_per_gas: eth::U256,
}

impl GasPriceEstimator {
Expand All @@ -42,9 +43,16 @@ impl GasPriceEstimator {
mempool.additional_tip_percentage,
)
});
// Use the lowest max_fee_per_gas of all mempools as the max_fee_per_gas
let max_fee_per_gas = mempools
.iter()
.map(|mempool| eth::U256::from_f64_lossy(mempool.gas_price_cap))
.min()
.expect("at least one mempool");
Ok(Self {
gas,
additional_tip,
max_fee_per_gas,
})
}

Expand All @@ -69,7 +77,7 @@ impl GasPriceEstimator {
None => estimate,
};
eth::GasPrice {
max: eth::U256::from_f64_lossy(estimate.max_fee_per_gas).into(),
max: self.max_fee_per_gas.into(),
tip: eth::U256::from_f64_lossy(estimate.max_priority_fee_per_gas).into(),
base: eth::U256::from_f64_lossy(estimate.base_fee_per_gas).into(),
}
Expand Down
4 changes: 4 additions & 0 deletions crates/driver/src/infra/config/file/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,10 @@ pub async fn load(network: &blockchain::Network, path: &Path) -> infra::Config {
use_soft_cancellations: *use_soft_cancellations,
},
},
submission: match config.submission.logic {
file::Logic::Boundary => mempool::SubmissionLogic::Boundary,
file::Logic::Native => mempool::SubmissionLogic::Native,
},
})
.collect(),
simulator: match (config.tenderly, config.enso) {
Expand Down
13 changes: 13 additions & 0 deletions crates/driver/src/infra/config/file/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ struct SubmissionConfig {
/// mempool of a node or the private MEVBlocker mempool.
#[serde(rename = "mempool", default)]
mempools: Vec<Mempool>,

#[serde(default)]
logic: Logic,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -446,6 +449,16 @@ enum BalancerV2Preset {
BalancerV2,
}

#[derive(Debug, Deserialize, Default)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
enum Logic {
/// Use legacy submissions logic (default)
#[default]
Boundary,
/// Use Driver domain native submission logic
Native,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct ZeroExConfig {
Expand Down
45 changes: 44 additions & 1 deletion crates/driver/src/infra/mempool/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,44 @@
pub use crate::boundary::mempool::{Config, GlobalTxPool, Kind, Mempool, RevertProtection};
pub use crate::boundary::mempool::{Config, GlobalTxPool, Kind, RevertProtection, SubmissionLogic};

#[derive(Debug, Clone)]
pub enum Mempool {
/// Legacy implementation of the mempool, using the shared and solvers crate
Boundary(crate::boundary::mempool::Mempool),
/// Driver native mempool implementation
Native(Inner),
}

impl std::fmt::Display for Mempool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Boundary(mempool) => write!(f, "Boundary({mempool})"),
Self::Native(mempool) => write!(f, "Native({mempool})"),
}
}
}

impl Mempool {
pub fn config(&self) -> &Config {
match self {
Self::Boundary(mempool) => mempool.config(),
Self::Native(mempool) => &mempool.config,
}
}
}

#[derive(Debug, Clone)]
pub struct Inner {
config: Config,
}

impl std::fmt::Display for Inner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Mempool({})", self.config.kind.format_variant())
}
}

impl Inner {
pub fn config(&self) -> &Config {
&self.config
}
}
13 changes: 11 additions & 2 deletions crates/driver/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,19 @@ async fn run_with(args: cli::Args, addr_sender: Option<oneshot::Sender<SocketAdd
config
.mempools
.iter()
.map(|mempool| {
Mempool::new(mempool.to_owned(), eth.clone(), tx_pool.clone()).unwrap()
.map(|mempool| match mempool.submission {
infra::mempool::SubmissionLogic::Boundary => Mempool::Boundary(
crate::boundary::Mempool::new(
mempool.to_owned(),
eth.clone(),
tx_pool.clone(),
)
.unwrap(),
),
infra::mempool::SubmissionLogic::Native => todo!("implement"),
})
.collect(),
eth.clone(),
)
.unwrap(),
eth,
Expand Down
17 changes: 14 additions & 3 deletions crates/driver/src/tests/setup/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,20 @@ impl Solver {
let url = config.blockchain.web3_url.parse().unwrap();
let rpc = infra::blockchain::Rpc::new(&url).await.unwrap();
let gas = Arc::new(
infra::blockchain::GasPriceEstimator::new(rpc.web3(), &[])
.await
.unwrap(),
infra::blockchain::GasPriceEstimator::new(
rpc.web3(),
&[infra::mempool::Config {
additional_tip_percentage: Default::default(),
gas_price_cap: f64::MAX,
target_confirm_time: Default::default(),
max_confirm_time: Default::default(),
retry_interval: Default::default(),
kind: infra::mempool::Kind::Public(infra::mempool::RevertProtection::Disabled),
submission: infra::mempool::SubmissionLogic::Native,
}],
)
.await
.unwrap(),
);
let eth = Ethereum::new(
rpc,
Expand Down
5 changes: 0 additions & 5 deletions crates/orderbook/openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1202,12 +1202,9 @@ components:
UnsupportedOrderType,
InsufficientValidTo,
ExcessiveValidTo,
TransferEthToContract,
InvalidNativeSellToken,
SameBuyAndSellToken,
UnsupportedSignature,
UnsupportedToken,
UnsupportedCustomInteraction
InvalidAppData,
AppDataHashMismatch,
AppdataFromMismatch,
Expand Down Expand Up @@ -1255,7 +1252,6 @@ components:
InsufficientValidTo,
ExcessiveValidTo,
InvalidSignature,
TransferEthToContract,
TransferSimulationFailed,
UnsupportedToken,
WrongOwner,
Expand All @@ -1264,7 +1260,6 @@ components:
UnsupportedBuyTokenDestination,
UnsupportedSellTokenSource,
UnsupportedOrderType,
UnsupportedSignature,
]
description:
type: string
Expand Down
Loading

0 comments on commit 1e684c0

Please sign in to comment.