Skip to content

Commit fa51801

Browse files
committed
wip: updating to trevm @ 0.20
1 parent 946e7d2 commit fa51801

File tree

4 files changed

+67
-79
lines changed

4 files changed

+67
-79
lines changed

Cargo.toml

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ signet-bundle = { git = "https://github.com/init4tech/signet-sdk", branch = "mai
2828
signet-types = { git = "https://github.com/init4tech/signet-sdk", branch = "main" }
2929
signet-zenith = { git = "https://github.com/init4tech/signet-sdk", branch = "main" }
3030

31+
trevm = { version = "0.20.4", features = [ "concurrent-db" ]}
32+
3133
alloy = { version = "0.12.6", features = [
3234
"full",
3335
"json-rpc",
@@ -38,13 +40,6 @@ alloy = { version = "0.12.6", features = [
3840
"serde",
3941
] }
4042

41-
trevm = { version = "0.19.12", features = [ "concurrent-db" ]}
42-
revm = { version = "19.5.0", features = [ "alloydb" ]}
43-
44-
# HACK: Update these to use main alloy package
45-
alloy-provider = { version = "0.7.3" }
46-
alloy-eips = { version = "0.7.3" }
47-
4843
aws-config = "1.1.7"
4944
aws-sdk-kms = "1.15.0"
5045

src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,5 @@ pub mod tasks;
2727
/// Utilities.
2828
pub mod utils;
2929

30-
use alloy_eips as _;
31-
use alloy_provider as _;
3230
/// Anonymous crate dependency imports.
3331
use openssl as _;

src/tasks/simulator.rs

Lines changed: 63 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,14 @@ use crate::tasks::block::InProgressBlock;
22
use alloy::consensus::TxEnvelope;
33
use alloy::primitives::U256;
44
use eyre::Result;
5-
use revm::{db::CacheDB, primitives::{address, Account, CfgEnv, ExecutionResult}, DatabaseRef};
6-
use std::{convert::Infallible, sync::Arc};
5+
use std::sync::Arc;
76
use tokio::{select, sync::mpsc::UnboundedReceiver, task::JoinSet};
87
use trevm::{
9-
db::sync::{ConcurrentState, ConcurrentStateInfo},
10-
revm::{
11-
primitives::{EVMError, ResultAndState},
12-
Database, DatabaseCommit, EvmBuilder,
13-
},
14-
BlockDriver, Cfg, DbConnect, EvmFactory, NoopBlock, TrevmBuilder, Tx,
8+
db::sync::{ConcurrentState, ConcurrentStateInfo}, helpers::Ctx, revm::{
9+
context::{
10+
result::{EVMError, ExecutionResult, ResultAndState}, CfgEnv
11+
}, inspector::inspectors::GasInspector, primitives::address, state::Account, Database, DatabaseCommit, DatabaseRef, Inspector
12+
}, BlockDriver, Cfg, DbConnect, EvmFactory, NoopBlock, Trevm, TrevmBuilder, TrevmBuilderError, Tx
1513
};
1614

1715
/// Tracks the EVM state, score, and result of an EVM execution.
@@ -29,47 +27,43 @@ pub struct Best<T, S: PartialOrd + Ord = U256> {
2927

3028
/// Binds a database and an extension together.
3129
#[derive(Debug, Clone)]
32-
pub struct SimulatorFactory<Db, Ext> {
30+
pub struct SimulatorFactory<Db, Insp> {
3331
/// The database state the execution is carried out on.
3432
pub db: Db,
35-
/// The extension, if any, provided to the trevm instance.
36-
pub ext: Ext,
33+
/// The inspector
34+
pub inspector: Insp,
3735
}
3836

3937
/// SimResult is an [`Option`] type that holds a tuple of a transaction and its associated
4038
/// state as a [`Db`] type updates if it was successfully executed.
41-
type SimResult<Db> = Option<(Best<TxEnvelope>, ConcurrentState<Arc<ConcurrentState<Db>>>)>;
39+
type SimResult<Db> = Result<Option<(Best<TxEnvelope>, ConcurrentState<Arc<ConcurrentState<Db>>>)>>;
4240

43-
impl<Db, Ext> SimulatorFactory<Db, Ext>
41+
impl<Db, Insp> SimulatorFactory<Db, Insp>
4442
where
45-
Ext: Send + Sync + Clone + 'static,
43+
Insp: Inspector<Ctx<ConcurrentState<Db>>> + Send + Sync + Clone + 'static,
4644
Db: Database + DatabaseRef + DatabaseCommit + Send + Sync + Clone + 'static,
4745
{
4846
/// Creates a new Simulator factory out of the database and extension.
49-
pub const fn new(db: Db, ext: Ext) -> Self {
50-
Self { db, ext }
47+
pub const fn new(db: Db, inspector: Insp) -> Self {
48+
Self { db, inspector }
5149
}
5250

5351
/// Spawns a trevm simulator that runs until `deadline` is hit.
5452
/// * Spawn does not guarantee that a thread is finished before the deadline.
5553
/// * This is intentional, so that it can maximize simulation time before the deadline.
5654
/// * This function always returns whatever the latest finished in progress block is.
57-
pub fn spawn<T, F>(
55+
pub fn spawn<F>(
5856
self,
5957
mut inbound_tx: UnboundedReceiver<TxEnvelope>,
6058
evaluator: Arc<F>,
6159
deadline: tokio::time::Instant,
6260
) -> tokio::task::JoinHandle<InProgressBlock>
6361
where
64-
T: Tx,
6562
F: Fn(&ResultAndState) -> U256 + Send + Sync + 'static,
6663
{
6764
tokio::spawn(async move {
68-
// Spawn a join set to track all simulation threads
6965
let mut join_set = JoinSet::new();
70-
7166
let mut best: Option<Best<TxEnvelope>> = None;
72-
7367
let mut block = InProgressBlock::new();
7468

7569
let sleep = tokio::time::sleep_until(deadline);
@@ -84,13 +78,13 @@ where
8478
// Setup the simulation environment
8579
let sim = self.clone();
8680
let eval = evaluator.clone();
87-
let mut parent_db = Arc::new(sim.connect().unwrap());
81+
let db = self.connect().expect("must connect db");
82+
let mut parent_db = Arc::new(db);
8883

89-
// Kick off the work in a new thread
9084
join_set.spawn(async move {
9185
let result = sim.simulate_tx(inbound_tx, eval, parent_db.child());
9286

93-
if let Some((best, db)) = result {
87+
if let Ok(Some((best, db))) = result {
9488
if let Ok(()) = parent_db.merge_child(db) {
9589
tracing::debug!("merging updated simulation state");
9690
return Some(best)
@@ -141,34 +135,22 @@ where
141135
F: Fn(&ResultAndState) -> U256 + Send + Sync + 'static,
142136
Db: Database + DatabaseRef + DatabaseCommit + Send + Sync + Clone + 'static,
143137
{
144-
let trevm_instance = EvmBuilder::default().with_db(db).build_trevm();
138+
let t = TrevmBuilder::new().with_db(db).with_insp(self.inspector.clone()).build_trevm()?;
145139

146-
let result = trevm_instance
147-
.fill_cfg(&PecorinoCfg)
148-
.fill_block(&NoopBlock)
149-
.fill_tx(&tx) // Use as_ref() to get &SimTxEnvelope from Arc
150-
.run();
140+
let result = t.fill_cfg(&PecorinoCfg).fill_block(&NoopBlock).fill_tx(&tx).run();
151141

152142
match result {
153143
Ok(t) => {
154-
// log and evaluate simulation results
155-
tracing::info!(tx_hash = ?tx.clone().tx_hash(), "transaction simulated");
156144
let result = t.result_and_state().clone();
157-
tracing::debug!(gas_used = &result.result.gas_used(), "gas consumed");
145+
let db = t.into_db();
158146
let score = evaluator(&result);
159-
tracing::debug!(score = ?score, "transaction evaluated");
147+
let best = Best { tx: Arc::new(tx), result, score };
160148

161-
// accept results
162-
let t = t.accept();
163-
let db = t.1.into_db();
164-
165-
// return the updated db with the candidate applied to its state
166-
Some((Best { tx: Arc::new(tx), result, score }, db))
149+
Ok(Some((best, db)))
167150
}
168-
Err(e) => {
169-
// if this transaction fails to run, log the error and return None
170-
tracing::error!(err = ?e.as_transaction_error(), "failed to simulate tx");
171-
None
151+
Err(terr) => {
152+
tracing::error!(err = ?terr.error(), "transaction simulation error");
153+
Ok(None)
172154
}
173155
}
174156
}
@@ -178,7 +160,7 @@ where
178160
&self,
179161
_bundle: Arc<Vec<T>>,
180162
_evaluator: Arc<F>,
181-
_trevm_instance: trevm::EvmNeedsCfg<'_, (), ConcurrentState<CacheDB<Arc<Db>>>>,
163+
_db: ConcurrentState<Arc<ConcurrentState<Db>>>,
182164
) -> Option<Best<Vec<T>>>
183165
where
184166
T: Tx + Send + Sync + 'static,
@@ -188,52 +170,59 @@ where
188170
}
189171
}
190172

191-
/// Wraps a Db into an EvmFactory compatible [`Database`]
192-
impl<'a, Db, Ext> DbConnect<'a> for SimulatorFactory<Db, Ext>
173+
impl<Db, Insp> DbConnect for SimulatorFactory<Db, Insp>
193174
where
194175
Db: Database + DatabaseRef + DatabaseCommit + Sync + Send + Clone + 'static,
195-
Ext: Sync + Clone,
176+
Insp: Inspector<Ctx<ConcurrentState<Db>>> + Sync + Send + Clone,
196177
{
197178
type Database = ConcurrentState<Db>;
198-
type Error = Infallible;
179+
type Error = TrevmBuilderError;
199180

200-
fn connect(&'a self) -> Result<Self::Database, Self::Error> {
181+
fn connect(&self) -> Result<Self::Database, Self::Error> {
201182
let inner = ConcurrentState::new(self.db.clone(), ConcurrentStateInfo::default());
202183
Ok(inner)
203184
}
204185
}
205186

206187
/// Makes a SimulatorFactory capable of creating and configuring trevm instances
207-
impl<'a, Db, Ext> EvmFactory<'a> for SimulatorFactory<Db, Ext>
188+
impl<Db, Insp> EvmFactory for SimulatorFactory<Db, Insp>
208189
where
209190
Db: Database + DatabaseRef + DatabaseCommit + Sync + Send + Clone + 'static,
210-
Ext: Sync + Clone,
191+
Insp: Inspector<Ctx<ConcurrentState<Db>>> + Sync + Send + Clone,
211192
{
212-
type Ext = ();
193+
type Insp = Insp;
213194

214-
/// Create makes a [`ConcurrentState`] database by calling connect
215-
fn create(&'a self) -> Result<trevm::EvmNeedsCfg<'a, Self::Ext, Self::Database>, Self::Error> {
195+
fn create(
196+
&self,
197+
) -> std::result::Result<trevm::EvmNeedsCfg<Self::Database, Self::Insp>, Self::Error> {
216198
let db = self.connect()?;
217-
let trevm = trevm::revm::EvmBuilder::default().with_db(db).build_trevm();
218-
Ok(trevm)
199+
let result =
200+
TrevmBuilder::new().with_db(db).with_insp(self.inspector.clone()).build_trevm();
201+
match result {
202+
Ok(t) => Ok(t),
203+
Err(e) => Err(e.into()),
204+
}
219205
}
220206
}
221207

222-
/// A trait for extracting transactions from
223-
pub trait BlockExtractor<Ext, Db: Database + DatabaseCommit>: Send + Sync + 'static {
208+
pub trait BlockExtractor<Insp, Db>
209+
where
210+
Db: Database + DatabaseCommit,
211+
Insp: Inspector<Ctx<Db>>,
212+
{
224213
/// BlockDriver runs the transactions over the provided trevm instance.
225-
type Driver: BlockDriver<Ext, Error<Db>: core::error::Error>;
214+
type Driver: BlockDriver<Insp, Error<Db>: core::error::Error>;
226215

227216
/// Instantiate an configure a new [`trevm`] instance.
228-
fn trevm(&self, db: Db) -> trevm::EvmNeedsBlock<'static, Ext, Db>;
217+
fn trevm(&self, db: Db) -> trevm::EvmNeedsBlock<Db, Insp>;
229218

230219
/// Extracts transactions from the source.
231220
///
232221
/// Extraction is infallible. Worst case it should return a no-op driver.
233222
fn extract(&mut self, bytes: &[u8]) -> Self::Driver;
234223
}
235224

236-
impl<Ext> BlockDriver<Ext> for InProgressBlock {
225+
impl<Insp> BlockDriver<Insp> for InProgressBlock {
237226
type Block = NoopBlock;
238227

239228
type Error<Db: Database + DatabaseCommit> = Error<Db>;
@@ -244,10 +233,13 @@ impl<Ext> BlockDriver<Ext> for InProgressBlock {
244233

245234
/// Loops through the transactions in the block and runs them, accepting the state at the end
246235
/// if it was successful and returning and erroring out otherwise.
247-
fn run_txns<'a, Db: Database + DatabaseCommit>(
236+
fn run_txns<Db: Database + DatabaseCommit>(
248237
&mut self,
249-
mut trevm: trevm::EvmNeedsTx<'a, Ext, Db>,
250-
) -> trevm::RunTxResult<'a, Ext, Db, Self> {
238+
mut trevm: trevm::EvmNeedsTx<Db, Insp>,
239+
) -> trevm::RunTxResult<Db, Insp, Self>
240+
where
241+
Insp: Inspector<Ctx<Db>>,
242+
{
251243
for tx in self.transactions().iter() {
252244
if tx.recover_signer().is_ok() {
253245
let sender = tx.recover_signer().unwrap();
@@ -272,8 +264,11 @@ impl<Ext> BlockDriver<Ext> for InProgressBlock {
272264

273265
fn post_block<Db: Database + DatabaseCommit>(
274266
&mut self,
275-
_trevm: &trevm::EvmNeedsBlock<'_, Ext, Db>,
276-
) -> Result<(), Self::Error<Db>> {
267+
_trevm: &trevm::EvmNeedsBlock<Db, Insp>,
268+
) -> Result<(), Self::Error<Db>>
269+
where
270+
Insp: Inspector<Ctx<Db>>,
271+
{
277272
Ok(())
278273
}
279274
}
@@ -330,4 +325,4 @@ pub fn eval_fn(state: &ResultAndState) -> U256 {
330325
tracing::info!(balance = ?target_account.info.balance, "target account balance");
331326

332327
target_account.info.balance
333-
}
328+
}

tests/simulator_test.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use alloy::signers::SignerSync as _;
66
use alloy::transports::http::{Client, Http};
77
use builder::config::WalletlessProvider;
88
use builder::tasks::simulator::SimulatorFactory;
9-
use revm::db::{AlloyDB, CacheDB};
10-
use revm::primitives::{address, TxKind};
9+
use trevm::revm::database::{AlloyDB, CacheDB};
10+
use trevm::revm::primitives::{address, TxKind};
1111
use std::sync::Arc;
1212
use tokio::sync::mpsc;
1313
use tokio::time::{Duration, Instant};

0 commit comments

Comments
 (0)