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

feat: Implement BadTokenMonitor #3153

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 2 additions & 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/database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ pub const TABLES: &[&str] = &[
"auction_participants",
"app_data",
"jit_orders",
"bad_tokens"
Copy link
Contributor

Choose a reason for hiding this comment

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

I'd like to avoid persisting bad tokens in the DB. At least from the start we should collect the heuristics only based on an in-memory cache.
This trades code complexity for accuracy after restarts. Also so far the driver does not depend on any DB at all which would be an additional piece of infra external teams would have to maintain.

];

/// The names of potentially big volume tables we use in the db.
Expand Down
2 changes: 2 additions & 0 deletions crates/driver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ axum = { workspace = true }
bigdecimal = { workspace = true }
chrono = { workspace = true, features = ["clock"], default-features = false }
cow-amm = { path = "../cow-amm" }
database = { path = "../database" }
derive_more = { workspace = true }
ethabi = "18.0"
ethereum-types = { workspace = true }
Expand All @@ -47,6 +48,7 @@ reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_with = { workspace = true }
sqlx = { workspace = true }
tap = "1.0.1"
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "time"] }
Expand Down
4 changes: 4 additions & 0 deletions crates/driver/src/domain/competition/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,10 @@ impl Tokens {
pub fn iter(&self) -> impl Iterator<Item = &Token> {
self.0.values()
}

pub fn iter_keys(&self) -> impl Iterator<Item = &eth::TokenAddress> {
self.0.keys()
}
}

#[derive(Debug, Clone)]
Expand Down
19 changes: 12 additions & 7 deletions crates/driver/src/domain/competition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ use {
crate::{
domain::{competition::solution::Settlement, eth},
infra::{
self,
blockchain::Ethereum,
notify,
observe,
simulator::{RevertError, SimulatorError},
solver::{self, SolutionMerging, Solver},
self,
bad_token::BadTokenMonitor,
blockchain::Ethereum,
database::Postgres,
notify,
observe,
simulator::{RevertError, SimulatorError},
solver::{self, SolutionMerging, Solver},
Simulator,
},
util::Bytes,
Expand Down Expand Up @@ -49,14 +51,15 @@ pub struct Competition {
pub eth: Ethereum,
pub liquidity: infra::liquidity::Fetcher,
pub simulator: Simulator,
pub bad_token_monitor: BadTokenMonitor,
pub mempools: Mempools,
/// Cached solutions with the most recent solutions at the front.
pub settlements: Mutex<VecDeque<Settlement>>,
}

impl Competition {
/// Solve an auction as part of this competition.
pub async fn solve(&self, auction: &Auction) -> Result<Option<Solved>, Error> {
pub async fn solve(&self, auction: &Auction, db: &Postgres) -> Result<Option<Solved>, Error> {
let liquidity = match self.solver.liquidity() {
solver::Liquidity::Fetch => {
self.liquidity
Expand Down Expand Up @@ -257,6 +260,8 @@ impl Competition {
&infra::simulator::Error::Revert(err),
true,
);

self.bad_token_monitor.consolidate(&db, auction.tokens().iter_keys());
return;
}
}
Expand Down
38 changes: 27 additions & 11 deletions crates/driver/src/infra/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
use {
super::database::Postgres,
crate::{
domain::{self, Mempools},
infra::{
self,
config::file::OrderPriorityStrategy,
liquidity,
solver::{Solver, Timeouts},
tokens,
Ethereum,
self,
bad_token::BadTokenMonitor,
config::file::OrderPriorityStrategy,
liquidity,
solver::{Solver, Timeouts},
tokens,
Ethereum,
Simulator,
},
},
error::Error,
futures::Future,
std::{net::SocketAddr, sync::Arc},
},
error::Error,
futures::Future,
std::{net::SocketAddr, sync::Arc},
tokio::sync::oneshot,
};

Expand All @@ -26,6 +28,7 @@ pub struct Api {
pub solvers: Vec<Solver>,
pub liquidity: liquidity::Fetcher,
pub simulator: Simulator,
pub db: Postgres,
pub eth: Ethereum,
pub mempools: Mempools,
pub addr: SocketAddr,
Expand Down Expand Up @@ -57,6 +60,8 @@ impl Api {
app = routes::metrics(app);
app = routes::healthz(app);

let mut bad_token_monitors = BadTokenMonitor::collect_from_path("./src/infra/bad_token/configs", &solvers);
Copy link
Contributor

Choose a reason for hiding this comment

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

Things like this should be passed via arguments to the program.
Instead of introducing another file this could be part of the existing driver config file (each solver could have their own section with supported tokens).


// Multiplex each solver as part of the API. Multiple solvers are multiplexed
// on the same driver so only one liquidity collector collects the liquidity
// for all of them. This is important because liquidity collection is
Expand All @@ -70,15 +75,21 @@ impl Api {
let router = routes::reveal(router);
let router = routes::settle(router);
let router = router.with_state(State(Arc::new(Inner {
db: self.db.clone(),
eth: self.eth.clone(),
solver: solver.clone(),
competition: domain::Competition {
solver,
eth: self.eth.clone(),
liquidity: self.liquidity.clone(),
bad_token_monitor: {
let mut monitor = bad_token_monitors.remove(&solver.address()).unwrap();
Copy link
Contributor

Choose a reason for hiding this comment

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

This function already returns a Result so having error handling instead of .unwrap() would be very easy.

monitor.initialize(&self.db);
monitor
},
simulator: self.simulator.clone(),
mempools: self.mempools.clone(),
settlements: Default::default(),
solver,
},
liquidity: self.liquidity.clone(),
tokens: tokens.clone(),
Expand Down Expand Up @@ -128,6 +139,10 @@ impl State {
&self.0.tokens
}

fn database(&self) -> &Postgres {
&self.0.db
}

fn pre_processor(&self) -> &domain::competition::AuctionProcessor {
&self.0.pre_processor
}
Expand All @@ -138,6 +153,7 @@ impl State {
}

struct Inner {
db: Postgres,
eth: Ethereum,
solver: Solver,
competition: domain::Competition,
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/infra/api/routes/solve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async fn route(
.pre_processor()
.prioritize(auction, &competition.solver.account().address())
.await;
let result = competition.solve(&auction).await;
let result = competition.solve(&auction, state.database()).await;
observe::solved(state.solver().name(), &result);
Ok(axum::Json(dto::Solved::new(result?, &competition.solver)))
};
Expand Down
20 changes: 20 additions & 0 deletions crates/driver/src/infra/bad_token/configs/sample.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
solver = "0x1234567890abcdef1234567890abcdef12345678"
timespan = 3


[[tokens.supported]]
Copy link
Contributor

Choose a reason for hiding this comment

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

Why are there multiple entries for tokens.supported? A list should be defined in a single array, I think.
Also it might be nicer to have a mapping token => supported_enum to avoid error cases where the same token is part of both lists.

address = "0xabcdefabcdefabcdefabcdefabcdefabcd"

[[tokens.supported]]
address = "0x1234123412341234123412341234123412341234"

[[tokens.unsupported]]
address = "0x5678567856785678567856785678567856785678"

[[tokens.unsupported]]
address = "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"

[heuristic.ThresholdBased]
threshold = 10

mode = "LogOnly"
Loading
Loading