Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 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
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
68 changes: 68 additions & 0 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,31 @@ pub struct OrderSimulationConfig {
/// URL.
#[serde(default)]
pub tenderly: Option<crate::simulator::TenderlyConfig>,

/// Mode for the EIP-1271 order simulation.
#[serde(default)]
pub eip1271_simulation_mode: Eip1271SimulationMode,

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

/// Mode for the EIP-1271 order simulation at order creation.
#[derive(Copy, Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum Eip1271SimulationMode {
Shadow,
Enforce,
#[default]
Disabled,
}

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

/// Top-level orderbook service configuration.
Expand Down Expand Up @@ -228,6 +254,8 @@ pub mod test_util {
order_simulation: Some(OrderSimulationConfig {
gas_limit: U256::try_from(16777215).expect("u64 can be converted to U256"),
tenderly: None,
eip1271_simulation_mode: Default::default(),
eip1271_simulation_timeout: std::time::Duration::from_secs(2),
}),
hide_competition_before_deadline: false,
}
Expand Down Expand Up @@ -438,4 +466,44 @@ mod tests {
);
assert_eq!(config.http_client.timeout, deserialized.http_client.timeout)
}

#[test]
fn parses_simulation_mode_default() {
let toml = r#"gas-limit = "0x1000000""#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.eip1271_simulation_mode, Eip1271SimulationMode::Disabled);
assert_eq!(cfg.eip1271_simulation_timeout, Duration::from_secs(2));
}

#[test]
fn parses_simulation_mode_enforce() {
let toml = r#"
gas-limit = "0x1000000"
eip1271-simulation-mode = "enforce"
eip1271-simulation-timeout = "5s"
"#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.eip1271_simulation_mode, Eip1271SimulationMode::Enforce);
assert_eq!(cfg.eip1271_simulation_timeout, Duration::from_secs(5));
}

#[test]
fn parses_simulation_mode_shadow() {
let toml = r#"
gas-limit = "0x1000000"
eip1271-simulation-mode = "shadow"
"#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.eip1271_simulation_mode, Eip1271SimulationMode::Shadow);
}

#[test]
fn parses_simulation_mode_disabled() {
let toml = r#"
gas-limit = "0x1000000"
eip1271-simulation-mode = "disabled"
"#;
let cfg: OrderSimulationConfig = toml::from_str(toml).unwrap();
assert_eq!(cfg.eip1271_simulation_mode, Eip1271SimulationMode::Disabled);
}
}
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
194 changes: 194 additions & 0 deletions crates/e2e/tests/e2e/eip1271_creation_simulation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
//! Local-node tests for the EIP-1271 creation-time simulation.
//!
//! - Negative: a Safe-signed order whose `app_data.protocol.wrappers` points at
//! a custom always-revert wrapper. With the orderbook in
//! `Eip1271SimulationMode::Enforce`, the simulation drives `settle()` through
//! the wrapper, the wrapper reverts, and the API rejects with HTTP 400
//! `Eip1271SimulationFailed`. A wrapper is used rather than a buggy pre-hook
//! because `HooksTrampoline.execute` deliberately swallows hook reverts, so a
//! buggy hook would not surface as a simulation failure.
//! - Positive: a Safe-signed order with empty app_data is accepted, proving the
//! adapter wiring lets healthy orders through.

use {
alloy::{
primitives::{Address, Bytes, TxKind, hex},
providers::Provider,
rpc::types::TransactionRequest,
},
configs::{orderbook::Eip1271SimulationMode, test_util::TestDefault},
e2e::setup::{MintableToken, OnchainComponents, Services, run_test, safe::Safe},
model::order::{OrderCreation, OrderCreationAppData, OrderKind},
number::units::EthUnit,
reqwest::StatusCode,
serde_json::json,
shared::web3::Web3,
};

/// Constructor + runtime that always reverts with empty data on any call.
///
/// Constructor copies the 5-byte runtime (`PUSH1 0; PUSH1 0; REVERT`) into
/// memory and returns it. The deployed contract reverts unconditionally
/// regardless of selector or calldata.
const ALWAYS_REVERT_INIT_CODE: [u8; 17] = hex!("6005600c60003960056000f360006000fd");

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

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

async fn rejects_when_wrapper_reverts(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.clone(), 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_in_enforce_mode(&onchain, solver).await;

let wrapper_addr = deploy_always_revert(&web3, trader.address()).await;

let order = sign_order(
&safe,
&onchain,
&token,
Some(WrapperRef {
address: wrapper_addr,
data: vec![],
}),
);

let (status, body) = services.create_order(&order).await.unwrap_err();
assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}");
assert!(
body.contains("Eip1271SimulationFailed"),
"expected Eip1271SimulationFailed in body, got: {body}",
);
}

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_in_enforce_mode(&onchain, solver).await;

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

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);
}

/// Deploys a contract whose runtime is `PUSH1 0; PUSH1 0; REVERT`.
async fn deploy_always_revert(web3: &Web3, from: Address) -> Address {
let mut tx = TransactionRequest::default()
.from(from)
.input(Bytes::from(ALWAYS_REVERT_INIT_CODE.to_vec()).into());
tx.to = Some(TxKind::Create);
let receipt = web3
.provider
.send_transaction(tx)
.await
.unwrap()
.get_receipt()
.await
.unwrap();
receipt
.contract_address
.expect("deployment receipt should carry the contract address")
}

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_in_enforce_mode<'a>(
onchain: &'a OnchainComponents,
solver: e2e::setup::onchain_components::TestAccount,
) -> Services<'a> {
let mut orderbook_config = configs::orderbook::Configuration::test_default();
orderbook_config
.order_simulation
.as_mut()
.expect("test_default enables order_simulation")
.eip1271_simulation_mode = Eip1271SimulationMode::Enforce;

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

struct WrapperRef {
address: Address,
data: Vec<u8>,
}

fn sign_order(
safe: &Safe,
onchain: &OnchainComponents,
sell_token: &MintableToken,
wrapper: Option<WrapperRef>,
) -> OrderCreation {
let app_data = match wrapper {
Some(w) => json!({
"metadata": {
"wrappers": [{
"address": format!("{:?}", w.address),
"data": format!("0x{}", hex::encode(&w.data)),
"isOmittable": false,
}],
},
}),
None => json!({}),
}
.to_string();

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: app_data },
..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
18 changes: 12 additions & 6 deletions crates/e2e/tests/e2e/malformed_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,11 @@ async fn http_validation(web3: Web3) {
"kind": "sell",
"owner": VALID_ADDRESS,
"appData": bad_app_data,
"signingScheme": "presign",
"signature": "0x",
"feeAmount": "0",
"validTo": u32::MAX,
"partiallyFillable": false,
}))
.send()
.await
Expand All @@ -503,15 +508,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 Expand Up @@ -563,6 +563,12 @@ async fn simulation_not_enabled(web3: Web3) {
"buyAmount": "1000000000000000000",
"kind": "sell",
"owner": VALID_ADDRESS,
"appData": "{}",
"signingScheme": "presign",
"signature": "0x",
"feeAmount": "0",
"validTo": u32::MAX,
"partiallyFillable": false,
}))
.send()
.await
Expand Down
5 changes: 5 additions & 0 deletions crates/orderbook/src/api/post_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,11 @@ impl IntoResponse for ValidationErrorWrapper {
),
)
.into_response(),
ValidationError::SimulationFailed(reason) => (
StatusCode::BAD_REQUEST,
error("Eip1271SimulationFailed", reason),
)
.into_response(),
ValidationError::InsufficientBalance => (
StatusCode::BAD_REQUEST,
error(
Expand Down
Loading
Loading