Skip to content

Commit

Permalink
One Simulation To Rule Them All (#1842)
Browse files Browse the repository at this point in the history
> One simulation to find them
> One simulation to bring them all
> And in the Kubernetes cluster bind them

Now that we can simulation account balances and ERC-1271 signature for
orders with pre-hooks without any additional node requirements, the
existing parameterization of the "strategies" for these simulations
(naive web3 RPC requests vs simulation) is no longer needed. We can just
use the new `StorageAccessible` simulation trick everywhere.

This allows us to remove/simplify code an rely on a single method for
simulating these order related properties.

### Test Plan

E2E tests continue to pass after removing flags.
  • Loading branch information
Nicholas Rodrigues Lordello authored Sep 6, 2023
1 parent aabdf24 commit 9452c0f
Show file tree
Hide file tree
Showing 11 changed files with 71 additions and 771 deletions.
4 changes: 2 additions & 2 deletions crates/autopilot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ pub async fn main(args: arguments::Arguments) {
.or_else(|| shared::network::block_interval(&network, chain_id))
.expect("unknown network block interval");

let signature_validator = args.shared.signatures.validator(
let signature_validator = signature_validator::validator(
signature_validator::Contracts {
chain_id,
settlement: settlement_contract.address(),
Expand All @@ -174,7 +174,7 @@ pub async fn main(args: arguments::Arguments) {
web3.clone(),
);

let balance_fetcher = args.shared.balances.cached(
let balance_fetcher = account_balances::cached(
account_balances::Contracts {
chain_id,
settlement: settlement_contract.address(),
Expand Down
14 changes: 2 additions & 12 deletions crates/e2e/tests/e2e/colocation_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,11 @@ async fn allowance(web3: Web3) {

let services = Services::new(onchain.contracts()).await;
services.start_autopilot(vec![
"--account-balances=simulation".to_string(),
"--enable-colocation=true".to_string(),
"--drivers=http://localhost:11088/test_solver".to_string(),
]);
services
.start_api(vec![
"--account-balances=simulation".to_string(),
"--enable-custom-interactions=true".to_string(),
])
.start_api(vec!["--enable-custom-interactions=true".to_string()])
.await;

let order = OrderCreation {
Expand Down Expand Up @@ -248,17 +244,11 @@ async fn signature(web3: Web3) {

let services = Services::new(onchain.contracts()).await;
services.start_autopilot(vec![
"--account-balances=simulation".to_string(),
"--eip1271-signature-validator=simulation".to_string(),
"--enable-colocation=true".to_string(),
"--drivers=http://localhost:11088/test_solver".to_string(),
]);
services
.start_api(vec![
"--account-balances=simulation".to_string(),
"--eip1271-signature-validator=simulation".to_string(),
"--enable-custom-interactions=true".to_string(),
])
.start_api(vec!["--enable-custom-interactions=true".to_string()])
.await;

// Place Orders
Expand Down
12 changes: 3 additions & 9 deletions crates/e2e/tests/e2e/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,9 @@ async fn test(web3: Web3) {
.await;

let services = Services::new(onchain.contracts()).await;
services.start_autopilot(vec!["--account-balances=simulation".to_string()]);
services.start_autopilot(vec![]);
services
.start_api(vec![
"--account-balances=simulation".to_string(),
"--enable-custom-interactions=true".to_string(),
])
.start_api(vec!["--enable-custom-interactions=true".to_string()])
.await;

let order = OrderCreation {
Expand Down Expand Up @@ -86,10 +83,7 @@ async fn test(web3: Web3) {
assert_eq!(balance, to_wei(5));

tracing::info!("Waiting for trade.");
services.start_old_driver(
solver.private_key(),
vec!["--account-balances=simulation".to_string()],
);
services.start_old_driver(solver.private_key(), vec![]);
let trade_happened = || async {
cow.balance_of(trader.address())
.call()
Expand Down
4 changes: 2 additions & 2 deletions crates/orderbook/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ pub async fn run(args: Arguments) {
.expect("Failed to retrieve network version ID");
let network_name = network_name(&network, chain_id);

let signature_validator = args.shared.signatures.validator(
let signature_validator = signature_validator::validator(
signature_validator::Contracts {
chain_id,
settlement: settlement_contract.address(),
Expand Down Expand Up @@ -145,7 +145,7 @@ pub async fn run(args: Arguments) {
let domain_separator = DomainSeparator::new(chain_id, settlement_contract.address());
let postgres = Postgres::new(args.db_url.as_str()).expect("failed to create database");

let balance_fetcher = args.shared.balances.fetcher(
let balance_fetcher = account_balances::fetcher(
account_balances::Contracts {
chain_id,
settlement: settlement_contract.address(),
Expand Down
44 changes: 33 additions & 11 deletions crates/shared/src/account_balances.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
mod arguments;
mod cached;
mod simulation;
mod web3;

use {
anyhow::Result,
ethrpc::{current_block::CurrentBlockStream, Web3},
model::{
interaction::InteractionData,
order::{Order, SellTokenSource},
},
primitive_types::{H160, U256},
std::sync::Arc,
};

pub use self::{
arguments::{Arguments, Contracts, Strategy},
cached::CachingBalanceFetcher,
simulation::Balances as SimulationBalanceFetcher,
web3::Web3BalanceFetcher,
};
mod cached;
mod simulation;

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Query {
Expand Down Expand Up @@ -71,3 +64,32 @@ pub trait BalanceFetching: Send + Sync {
amount: U256,
) -> Result<(), TransferSimulationError>;
}

/// Contracts required for balance simulation.
pub struct Contracts {
pub chain_id: u64,
pub settlement: H160,
pub vault_relayer: H160,
pub vault: Option<H160>,
}

/// Create the default [`BalanceFetching`] instance.
pub fn fetcher(contracts: Contracts, web3: Web3) -> Arc<dyn BalanceFetching> {
Arc::new(simulation::Balances::new(
web3,
contracts.settlement,
contracts.vault_relayer,
contracts.vault,
))
}

/// Create a cached [`BalanceFetching`] instance.
pub fn cached(
contracts: Contracts,
web3: Web3,
blocks: CurrentBlockStream,
) -> Arc<dyn BalanceFetching> {
let cached = Arc::new(cached::Balances::new(fetcher(contracts, web3)));
cached.spawn_background_task(blocks);
cached
}
89 changes: 0 additions & 89 deletions crates/shared/src/account_balances/arguments.rs

This file was deleted.

18 changes: 9 additions & 9 deletions crates/shared/src/account_balances/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ struct BalanceEntry {
balance: U256,
}

pub struct CachingBalanceFetcher {
pub struct Balances {
inner: Arc<dyn BalanceFetching>,
balance_cache: Arc<Mutex<BalanceCache>>,
}

impl CachingBalanceFetcher {
impl Balances {
pub fn new(inner: Arc<dyn BalanceFetching>) -> Self {
Self {
inner,
Expand All @@ -93,7 +93,7 @@ struct CacheResponse {
requested_at: BlockNumber,
}

impl CachingBalanceFetcher {
impl Balances {
fn get_cached_balances(&self, queries: &[Query]) -> CacheResponse {
let mut cache = self.balance_cache.lock().unwrap();
let (cached, missing) = queries
Expand Down Expand Up @@ -156,7 +156,7 @@ impl CachingBalanceFetcher {
}

#[async_trait::async_trait]
impl BalanceFetching for CachingBalanceFetcher {
impl BalanceFetching for Balances {
async fn get_balances(&self, queries: &[Query]) -> Vec<Result<U256>> {
let CacheResponse {
mut cached,
Expand Down Expand Up @@ -224,7 +224,7 @@ mod tests {
.withf(|arg| arg == [query(1)])
.returning(|_| vec![Ok(1.into())]);

let fetcher = CachingBalanceFetcher::new(Arc::new(inner));
let fetcher = Balances::new(Arc::new(inner));
// 1st call to `inner`.
let result = fetcher.get_balances(&[query(1)]).await;
assert_eq!(result[0].as_ref().unwrap(), &1.into());
Expand All @@ -242,7 +242,7 @@ mod tests {
.withf(|arg| arg == [query(1)])
.returning(|_| vec![Err(anyhow::anyhow!("some error"))]);

let fetcher = CachingBalanceFetcher::new(Arc::new(inner));
let fetcher = Balances::new(Arc::new(inner));
// 1st call to `inner`.
assert!(fetcher.get_balances(&[query(1)]).await[0].is_err());
// 2nd call to `inner`.
Expand All @@ -261,7 +261,7 @@ mod tests {
.withf(|arg| arg == [query(1)])
.returning(|_| vec![Ok(U256::one())]);

let fetcher = CachingBalanceFetcher::new(Arc::new(inner));
let fetcher = Balances::new(Arc::new(inner));
fetcher.spawn_background_task(receiver);

// 1st call to `inner`. Balance gets cached.
Expand Down Expand Up @@ -298,7 +298,7 @@ mod tests {
.withf(|arg| arg == [query(2)])
.returning(|_| vec![Ok(2.into())]);

let fetcher = CachingBalanceFetcher::new(Arc::new(inner));
let fetcher = Balances::new(Arc::new(inner));
// 1st call to `inner` putting balance 1 into the cache.
let result = fetcher.get_balances(&[query(1)]).await;
assert_eq!(result[0].as_ref().unwrap(), &1.into());
Expand All @@ -324,7 +324,7 @@ mod tests {
.times(7)
.returning(|_| vec![Ok(U256::one())]);

let fetcher = CachingBalanceFetcher::new(Arc::new(inner));
let fetcher = Balances::new(Arc::new(inner));
fetcher.spawn_background_task(receiver);

let cached_entry = || {
Expand Down
Loading

0 comments on commit 9452c0f

Please sign in to comment.