Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
78 commits
Select commit Hold shift + click to select a range
6897fec
Add EIP-1271 shadow simulator scaffolding
squadgazzz Apr 21, 2026
4d63688
Fix clippy and align SimulationFailed with tuple convention
squadgazzz Apr 21, 2026
7eb008b
Thread optional EIP-1271 shadow simulator into OrderValidator
squadgazzz Apr 21, 2026
3d074e4
Extract shadow sim timeout constant and rename HTTP error code
squadgazzz Apr 21, 2026
d68cb90
Integrate EIP-1271 shadow simulation in OrderValidator
squadgazzz Apr 21, 2026
f0af347
Add shadow sim mode and timeout to orderbook config
squadgazzz Apr 21, 2026
bd51ed8
Wire EIP-1271 shadow simulator through orderbook runtime
squadgazzz Apr 21, 2026
5c6e8d2
Rename shadow-sim types to drop the shadow prefix
squadgazzz Apr 21, 2026
557ae35
Clean up remaining 'shadow' references in docs and locals
squadgazzz Apr 21, 2026
6e7ee7a
Nits
squadgazzz Apr 21, 2026
1733fb2
Group EIP-1271 sim deps into Eip1271SimConfig on OrderValidator
squadgazzz Apr 21, 2026
af31a39
Rename Eip1271Simulator trait to Eip1271Simulating; promote SimConfig…
squadgazzz Apr 21, 2026
65a0290
Collapse build_1271_validator args to take Option<Eip1271Simulator>
squadgazzz Apr 21, 2026
a37c7a0
Move DEFAULT_EIP1271_SIM_TIMEOUT into test module
squadgazzz Apr 21, 2026
9c93de6
Simplify Eip1271Simulator doc comment
squadgazzz Apr 21, 2026
f5ddba5
Rename cheap→signature in sim metrics; merge sim_only_total into total
squadgazzz Apr 21, 2026
cebd99b
Rename duration_seconds histogram to simulation_time
squadgazzz Apr 21, 2026
67a4d32
Drop owner from sim logs; OrderUid already encodes it
squadgazzz Apr 21, 2026
2fbf9f0
Split sim disagreement log into explicit arms instead of an empty-str…
squadgazzz Apr 21, 2026
a781c44
Use Debug formatting (?) in sim logs to match project convention
squadgazzz Apr 21, 2026
d11442e
Expand sim abbreviation to simulation across types, fields, metrics, …
squadgazzz Apr 21, 2026
eca5c61
Simplify Eip1271Simulating doc and scope its mock to cfg(test) only
squadgazzz Apr 21, 2026
5407c8b
Add Disabled mode for order-creation EIP-1271 simulation
squadgazzz Apr 21, 2026
eed5990
Disabled by default
squadgazzz Apr 21, 2026
2785108
Align default test with Disabled as the default simulation mode
squadgazzz Apr 21, 2026
7281ded
Redundant comment
squadgazzz Apr 21, 2026
3525684
Assert simulator is never invoked for non-EIP-1271 orders
squadgazzz Apr 21, 2026
191d7ff
Consolidate EIP-1271 signature/simulation quadrant tests into a matrix
squadgazzz Apr 21, 2026
e62217c
Use .label() on outcomes instead of hardcoded strings in sim logs
squadgazzz Apr 21, 2026
4c25c46
Address Claude-review feedback on PR 4355
squadgazzz Apr 21, 2026
250f5da
Convert order_simulator::Error via From impl for ? ergonomics
squadgazzz Apr 22, 2026
c51a522
Review comments
squadgazzz Apr 22, 2026
7bd2592
Nit
squadgazzz Apr 22, 2026
ea11e37
Add SignatureCheck::new constructor
squadgazzz Apr 22, 2026
ebfd4a9
Pull timeout handling out of simulation_fut in run_eip1271_with_signa…
squadgazzz Apr 22, 2026
06c478a
Merge branch 'main' into feat/orderbook-eip1271-shadow-sim
squadgazzz Apr 22, 2026
490bcdc
Address jose review nits
squadgazzz Apr 27, 2026
fbe765c
Comment
squadgazzz Apr 28, 2026
b162fb4
Merge feat branch and port adapter to Martin's updated API
squadgazzz Apr 29, 2026
66eae59
Map flashloan.protocol_adapter to FlashloanRequest.borrower
squadgazzz Apr 29, 2026
7ea1551
Add local-node e2e for Eip1271SimulationMode::Enforce
squadgazzz Apr 29, 2026
8e50706
Wrap simulation via parameters_from_app_data and switch e2e to revert…
squadgazzz Apr 29, 2026
d4e3050
Use TxKind::Create explicitly when deploying always-revert wrapper
squadgazzz Apr 29, 2026
befab13
fmt
squadgazzz Apr 29, 2026
dc9cfb5
Merge branch 'new-api-simulator-crate' into prototype-eip1271-on-new-api
squadgazzz Apr 29, 2026
9ae38fe
nit
squadgazzz Apr 29, 2026
8f72eca
Patch malformed-request tests to populate fields Martin made required
squadgazzz Apr 29, 2026
2fb0d7f
Better comment
squadgazzz Apr 30, 2026
58278bc
Wire FlashLoanRouter address and add forked Aave replay test
squadgazzz Apr 30, 2026
2cb914d
Replace forked replay test with orderbook unit test pinned by RPC block
squadgazzz Apr 30, 2026
56d9bbc
Tidy aave replay test: doc on test, locals over consts, simpler assert
squadgazzz Apr 30, 2026
f490a72
Add negative replay test for over-subscribed Aave flashloan
squadgazzz Apr 30, 2026
7238293
Move Aave replay test from orderbook to simulator crate
squadgazzz Apr 30, 2026
f92ed6b
Inline aave-replay fixtures as constants, drop fixture files
squadgazzz Apr 30, 2026
f605197
Split APP_DATA via concat! and drop redundant info log
squadgazzz Apr 30, 2026
1e8ddaa
Use single r-string for APP_DATA instead of concat! ladder
squadgazzz Apr 30, 2026
1794027
Format APP_DATA multi-line and canonicalise via serde_json before use
squadgazzz Apr 30, 2026
42da4d2
Fmt
squadgazzz Apr 30, 2026
7c4aab8
Tighten APP_DATA / canonicalise_app_data doc comments
squadgazzz Apr 30, 2026
2ea5775
Assert negative test errors with EVM revert, not just any Err
squadgazzz Apr 30, 2026
59a1312
Merge remote-tracking branch 'origin/new-api-simulator-crate' into pr…
squadgazzz Apr 30, 2026
474aaa3
Migrate to AccountOverrideRequest::BuyTokensForBuffers
squadgazzz Apr 30, 2026
40e091d
fmt-toml: sort simulator Cargo.toml deps alphabetically
squadgazzz Apr 30, 2026
eaa186a
Merge branch 'new-api-simulator-crate' into prototype-eip1271-on-new-api
squadgazzz May 5, 2026
9338743
Migrate orderbook + aave_replay to new simulator API
squadgazzz May 5, 2026
ce7e042
Merge branch 'new-api-simulator-crate' into prototype-eip1271-on-new-api
squadgazzz May 5, 2026
c6f42f8
Fix merge resolution after base branch API rename
squadgazzz May 5, 2026
9988c39
Merge branch 'new-api-simulator-crate' into prototype-eip1271-on-new-api
squadgazzz May 6, 2026
5679bc0
Address PR review feedback
squadgazzz May 6, 2026
888e0b1
Move OrderSimulating + adapter into the simulator crate
squadgazzz May 6, 2026
c84adf7
Drop redundant order_simulation_ prefix from config fields
squadgazzz May 6, 2026
953ae86
Minor refactor
squadgazzz May 7, 2026
2e4d4b7
Add Aave v3 collateral-swap replay negative test
squadgazzz May 7, 2026
76eab54
Trim verbose comments in aave_replay tests
squadgazzz May 7, 2026
b113f00
Trim the comment
squadgazzz May 7, 2026
d45a99b
Merge branch 'new-api-simulator-crate' into prototype-eip1271-on-new-api
squadgazzz May 7, 2026
18be75f
Simplify EIP-1271 order simulation to shadow mode
squadgazzz May 7, 2026
2a1e8b0
Inline SimulationOutcome into Result<(), OrderSimulationError>
squadgazzz May 7, 2026
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 38 additions & 4 deletions crates/configs/src/orderbook/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use {
std::{
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
path::Path,
time::Duration,
},
};

Expand Down Expand Up @@ -59,6 +60,14 @@ pub struct OrderSimulationConfig {
/// URL.
#[serde(default)]
pub tenderly: Option<crate::simulator::TenderlyConfig>,

/// Per-call timeout for the order creation simulation.
#[serde(default = "default_simulation_timeout", with = "humantime_serde")]
pub timeout: Duration,
}

fn default_simulation_timeout() -> Duration {
Duration::from_secs(2)
}

/// Top-level orderbook service configuration.
Expand Down Expand Up @@ -171,6 +180,16 @@ pub mod test_util {
std::path::Path,
};

impl TestDefault for OrderSimulationConfig {
fn test_default() -> Self {
Self {
gas_limit: U256::try_from(16777215).expect("u64 can be converted to U256"),
tenderly: None,
timeout: std::time::Duration::from_secs(2),
}
}
}

impl Configuration {
pub async fn to_path<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
Ok(tokio::fs::write(path, toml::to_string_pretty(self)?).await?)
Expand Down Expand Up @@ -225,10 +244,7 @@ pub mod test_util {
..TestDefault::test_default()
},
// Enable order simulation for testing
order_simulation: Some(OrderSimulationConfig {
gas_limit: U256::try_from(16777215).expect("u64 can be converted to U256"),
tenderly: None,
}),
order_simulation: Some(TestDefault::test_default()),
hide_competition_before_deadline: false,
}
}
Expand Down Expand Up @@ -438,4 +454,22 @@ mod tests {
);
assert_eq!(config.http_client.timeout, deserialized.http_client.timeout)
}

#[test]
fn parses_order_simulation_defaults() {
let toml = r#"gas-limit = "16777216""#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.timeout, Duration::from_secs(2));
assert!(cfg.tenderly.is_none());
}

#[test]
fn parses_order_simulation_full() {
let toml = r#"
gas-limit = "16777216"
timeout = "5s"
"#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.timeout, Duration::from_secs(5));
}
}
14 changes: 7 additions & 7 deletions crates/cow-amm/src/amm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@ impl Amm {
// To avoid issues caused by that we check the validity of the signature.
let hash = hashed_eip712_message(domain_separator, &template.order.hash_struct());
validator
.validate_signature_and_get_additional_gas(SignatureCheck {
signer: self.address,
hash: hash.0,
signature: template.signature.to_bytes(),
interactions: template.pre_interactions.clone(),
balance_override: None,
})
.validate_signature_and_get_additional_gas(SignatureCheck::new(
self.address,
hash.0,
template.signature.to_bytes(),
template.pre_interactions.clone(),
None,
))
.await
.context("invalid signature")?;

Expand Down
100 changes: 100 additions & 0 deletions crates/e2e/tests/e2e/eip1271_creation_simulation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Local-node smoke test for the EIP-1271 creation-time simulation wiring.
//!
//! A Safe-signed order with empty `app_data` is accepted, proving that
//! `OrderSimulator` runs alongside the cheap signature check without
//! disrupting the happy path. The simulation runs in shadow mode (logs
//! disagreements, never rejects). An enforce-mode rejection test will be
//! added together with the enforce-mode follow-up PR.

use {
configs::{
orderbook::{Configuration, OrderSimulationConfig},
test_util::TestDefault,
},
e2e::setup::{MintableToken, OnchainComponents, Services, run_test, safe::Safe},
model::order::{OrderCreation, OrderCreationAppData, OrderKind},
number::units::EthUnit,
shared::web3::Web3,
};

#[tokio::test]
#[ignore]
async fn local_node_eip1271_creation_simulation_accepts_valid_order() {
run_test(accepts_valid_order).await;
}

async fn accepts_valid_order(web3: Web3) {
let mut onchain = OnchainComponents::deploy(web3.clone()).await;
let [solver] = onchain.make_solvers(1u64.eth()).await;
let [trader] = onchain.make_accounts(1u64.eth()).await;

let safe = Safe::deploy(trader, web3.provider.clone()).await;

let [token] = onchain
.deploy_tokens_with_weth_uni_v2_pools(100_000u64.eth(), 100_000u64.eth())
.await;
fund_safe(&safe, &token, &onchain).await;

let services = start_services_with_simulation(&onchain, solver).await;

let order = sign_order(&safe, &onchain, &token);

let uid = services
.create_order(&order)
.await
.expect("expected order to be accepted");
let stored = services.get_order(&uid).await.unwrap();
assert_eq!(stored.metadata.uid, uid);
}

async fn fund_safe(safe: &Safe, token: &MintableToken, onchain: &OnchainComponents) {
token.mint(safe.address(), 10u64.eth()).await;
safe.exec_alloy_call(
token
.approve(onchain.contracts().allowance, 10u64.eth())
.into_transaction_request(),
)
.await;
}

async fn start_services_with_simulation<'a>(
onchain: &'a OnchainComponents,
solver: e2e::setup::onchain_components::TestAccount,
) -> Services<'a> {
let orderbook_config = Configuration {
order_simulation: Some(OrderSimulationConfig::test_default()),
..Configuration::test_default()
};

let services = Services::new(onchain).await;
services
.start_protocol_with_args(
configs::autopilot::Configuration::test("test_solver", solver.address()),
orderbook_config,
solver,
)
.await;
services
}

fn sign_order(
safe: &Safe,
onchain: &OnchainComponents,
sell_token: &MintableToken,
) -> OrderCreation {
let mut order = OrderCreation {
kind: OrderKind::Sell,
sell_token: *sell_token.address(),
sell_amount: 5u64.eth(),
buy_token: *onchain.contracts().weth.address(),
buy_amount: 1u64.eth(),
valid_to: model::time::now_in_epoch_seconds() + 300,
from: Some(safe.address()),
app_data: OrderCreationAppData::Full {
full: "{}".to_string(),
},
..Default::default()
};
safe.sign_order(&mut order, onchain);
order
}
1 change: 1 addition & 0 deletions crates/e2e/tests/e2e/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod cow_amm;
mod database;
mod debug_order;
mod deprecated_endpoints;
mod eip1271_creation_simulation;
mod eip4626;
mod eth_integration;
mod eth_safe;
Expand Down
9 changes: 2 additions & 7 deletions crates/e2e/tests/e2e/malformed_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ async fn http_validation(web3: Web3) {
"zero sellAmount should return 422"
);

// some fields missing → 422
// Invalid kind enum value → 422
let response = client
.post(format!("{API_HOST}/restricted/api/v1/debug/simulation"))
.json(&json!({
Expand Down Expand Up @@ -510,15 +510,10 @@ async fn http_validation(web3: Web3) {
);
let body: Error = response.json().await.unwrap();
assert!(
body.description.contains("app_data"),
body.description.contains("app data"),
"error description should name the failing field. Got: {}",
body.description
);
assert!(
body.description.contains(bad_app_data),
"error description should include the bad value. Got: {}",
body.description
);
}

#[tokio::test]
Expand Down
73 changes: 45 additions & 28 deletions crates/orderbook/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use {
},
shared::{
order_quoting::{self, OrderQuoter},
order_validation::{OrderValidPeriodConfiguration, OrderValidator},
order_validation::{OrderSimulator, OrderValidPeriodConfiguration, OrderValidator},
},
std::{future::Future, net::SocketAddr, sync::Arc, time::Duration},
token_info::{CachedTokenInfoFetcher, TokenInfoFetcher},
Expand Down Expand Up @@ -385,6 +385,49 @@ pub async fn run(config: Configuration) {
let chainalysis_oracle = ChainalysisOracle::Instance::deployed(&web3.provider)
.await
.ok();

let order_simulator = match &config.order_simulation {
Some(sim_config) => {
let tenderly: Option<Arc<dyn simulator::tenderly::Api>> =
sim_config.tenderly.as_ref().map(|tenderly_config| {
Arc::new(simulator::tenderly::TenderlyApi::new(
tenderly_config,
&http_factory,
chain.id().to_string(),
)) as _
});
Some(
simulator::simulation_builder::SettlementSimulator::new(
settlement_contract.clone(),
flashloan_router_address,
hooks_trampoline_address,
*native_token.address(),
sim_config.gas_limit.saturating_to(),
balance_overrider.clone(),
current_block_stream.clone(),
tenderly,
)
.await
.expect("failed to create SettlementSimulator"),
)
}
None => None,
};

let validator_simulator = config
.order_simulation
.as_ref()
.zip(order_simulator.clone())
.map(|(sim_config, settlement_simulator)| {
let simulator: Arc<dyn simulator::order_simulation::OrderSimulating> = Arc::new(
simulator::order_simulation::OrderSimulatorAdapter::new(settlement_simulator),
);
OrderSimulator {
simulator,
timeout: sim_config.timeout,
}
});

let order_validator = Arc::new(OrderValidator::new(
native_token.clone(),
Arc::new(order_validation::banned::Users::new(
Expand All @@ -399,6 +442,7 @@ pub async fn run(config: Configuration) {
optimal_quoter.clone(),
balance_fetcher,
signature_validator,
validator_simulator,
Arc::new(postgres_write.clone()),
config.order_validation.max_limit_orders_per_user,
code_fetcher,
Expand All @@ -421,33 +465,6 @@ pub async fn run(config: Configuration) {
ipfs,
));

let order_simulator = if let Some(config) = config.order_simulation {
let tenderly: Option<Arc<dyn simulator::tenderly::Api>> =
config.tenderly.as_ref().map(|tenderly_config| {
Arc::new(simulator::tenderly::TenderlyApi::new(
tenderly_config,
&http_factory,
chain.id().to_string(),
)) as _
});
Some(
simulator::simulation_builder::SettlementSimulator::new(
settlement_contract.clone(),
flashloan_router_address,
hooks_trampoline_address,
*native_token.address(),
config.gas_limit.saturating_to(),
balance_overrider.clone(),
current_block_stream.clone(),
tenderly,
)
.await
.expect("failed to initialize SettlementSimulator"),
)
} else {
None
};

let orderbook = Arc::new(Orderbook::new(
domain_separator,
*settlement_contract.address(),
Expand Down
2 changes: 2 additions & 0 deletions crates/shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
serde_with = { workspace = true }
signature-validator = { workspace = true }
simulator = { workspace = true }
strum = { workspace = true }
thiserror = { workspace = true }
token-info = { workspace = true }
Expand All @@ -75,6 +76,7 @@ mockall = { workspace = true }
price-estimation = { workspace = true, features = ["test-util"] }
regex = { workspace = true }
signature-validator = { workspace = true, features = ["test-util"] }
simulator = { workspace = true, features = ["test-util"] }
testlib = { workspace = true }
tokio = { workspace = true, features = ["rt-multi-thread"] }
toml = { workspace = true }
Expand Down
Loading
Loading