Skip to content

Commit b5d24dc

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

File tree

4 files changed

+81
-79
lines changed

4 files changed

+81
-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: 77 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,21 @@ 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::{
8+
BlockDriver, Cfg, DbConnect, EvmFactory, NoopBlock, TrevmBuilder, TrevmBuilderError, Tx,
99
db::sync::{ConcurrentState, ConcurrentStateInfo},
10+
helpers::Ctx,
1011
revm::{
11-
primitives::{EVMError, ResultAndState},
12-
Database, DatabaseCommit, EvmBuilder,
12+
Database, DatabaseCommit, DatabaseRef, Inspector,
13+
context::{
14+
CfgEnv,
15+
result::{EVMError, ExecutionResult, ResultAndState},
16+
},
17+
primitives::address,
18+
state::Account,
1319
},
14-
BlockDriver, Cfg, DbConnect, EvmFactory, NoopBlock, TrevmBuilder, Tx,
1520
};
1621

1722
/// Tracks the EVM state, score, and result of an EVM execution.
@@ -29,47 +34,44 @@ pub struct Best<T, S: PartialOrd + Ord = U256> {
2934

3035
/// Binds a database and an extension together.
3136
#[derive(Debug, Clone)]
32-
pub struct SimulatorFactory<Db, Ext> {
37+
pub struct SimulatorFactory<Db, Insp> {
3338
/// The database state the execution is carried out on.
3439
pub db: Db,
35-
/// The extension, if any, provided to the trevm instance.
36-
pub ext: Ext,
40+
/// The inspector
41+
pub inspector: Insp,
3742
}
3843

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

43-
impl<Db, Ext> SimulatorFactory<Db, Ext>
48+
impl<Db, Insp> SimulatorFactory<Db, Insp>
4449
where
45-
Ext: Send + Sync + Clone + 'static,
50+
SimulatorFactory<Db, Insp>: DbConnect,
51+
Insp: Inspector<Ctx<ConcurrentState<Arc<ConcurrentState<Db>>>>> + Clone,
4652
Db: Database + DatabaseRef + DatabaseCommit + Send + Sync + Clone + 'static,
4753
{
4854
/// 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 }
55+
pub const fn new(db: Db, inspector: Insp) -> Self {
56+
Self { db, inspector }
5157
}
5258

5359
/// Spawns a trevm simulator that runs until `deadline` is hit.
5460
/// * Spawn does not guarantee that a thread is finished before the deadline.
5561
/// * This is intentional, so that it can maximize simulation time before the deadline.
5662
/// * This function always returns whatever the latest finished in progress block is.
57-
pub fn spawn<T, F>(
63+
pub fn spawn<F>(
5864
self,
5965
mut inbound_tx: UnboundedReceiver<TxEnvelope>,
6066
evaluator: Arc<F>,
6167
deadline: tokio::time::Instant,
6268
) -> tokio::task::JoinHandle<InProgressBlock>
6369
where
64-
T: Tx,
6570
F: Fn(&ResultAndState) -> U256 + Send + Sync + 'static,
6671
{
6772
tokio::spawn(async move {
68-
// Spawn a join set to track all simulation threads
6973
let mut join_set = JoinSet::new();
70-
7174
let mut best: Option<Best<TxEnvelope>> = None;
72-
7375
let mut block = InProgressBlock::new();
7476

7577
let sleep = tokio::time::sleep_until(deadline);
@@ -84,9 +86,10 @@ where
8486
// Setup the simulation environment
8587
let sim = self.clone();
8688
let eval = evaluator.clone();
87-
let mut parent_db = Arc::new(sim.connect().unwrap());
89+
let db: Db = self.connect().expect("must connect db");
90+
91+
let parent_db = Arc::new(ConcurrentState::new(db, ConcurrentStateInfo::default()));
8892

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

@@ -141,35 +144,27 @@ where
141144
F: Fn(&ResultAndState) -> U256 + Send + Sync + 'static,
142145
Db: Database + DatabaseRef + DatabaseCommit + Send + Sync + Clone + 'static,
143146
{
144-
let trevm_instance = EvmBuilder::default().with_db(db).build_trevm();
147+
let t = TrevmBuilder::new().with_db(db).with_insp(self.inspector.clone()).build_trevm()?;
145148

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();
149+
let result = t.fill_cfg(&PecorinoCfg).fill_block(&NoopBlock).fill_tx(&tx).run();
151150

152151
match result {
153152
Ok(t) => {
154-
// log and evaluate simulation results
155-
tracing::info!(tx_hash = ?tx.clone().tx_hash(), "transaction simulated");
156153
let result = t.result_and_state().clone();
157-
tracing::debug!(gas_used = &result.result.gas_used(), "gas consumed");
154+
let db = t.into_db();
158155
let score = evaluator(&result);
159-
tracing::debug!(score = ?score, "transaction evaluated");
160-
161-
// accept results
162-
let t = t.accept();
163-
let db = t.1.into_db();
156+
let best = Best {
157+
tx: Arc::new(tx),
158+
result,
159+
score,
160+
};
164161

165-
// return the updated db with the candidate applied to its state
166-
Some((Best { tx: Arc::new(tx), result, score }, db))
167-
}
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
172-
}
162+
Ok(Some((best, db)))
163+
},
164+
Err(terr) => {
165+
tracing::error!(err = ?terr.error(), "transaction simulation error");
166+
Ok(None)
167+
},
173168
}
174169
}
175170

@@ -178,7 +173,7 @@ where
178173
&self,
179174
_bundle: Arc<Vec<T>>,
180175
_evaluator: Arc<F>,
181-
_trevm_instance: trevm::EvmNeedsCfg<'_, (), ConcurrentState<CacheDB<Arc<Db>>>>,
176+
_db: ConcurrentState<Arc<ConcurrentState<Db>>>,
182177
) -> Option<Best<Vec<T>>>
183178
where
184179
T: Tx + Send + Sync + 'static,
@@ -188,52 +183,60 @@ where
188183
}
189184
}
190185

191-
/// Wraps a Db into an EvmFactory compatible [`Database`]
192-
impl<'a, Db, Ext> DbConnect<'a> for SimulatorFactory<Db, Ext>
186+
impl<Db, Insp> DbConnect for SimulatorFactory<Db, Insp>
193187
where
194188
Db: Database + DatabaseRef + DatabaseCommit + Sync + Send + Clone + 'static,
195-
Ext: Sync + Clone,
189+
Insp: Inspector<Ctx<ConcurrentState<Arc<ConcurrentState<Db>>>>> + Sync + Clone,
196190
{
197-
type Database = ConcurrentState<Db>;
198-
type Error = Infallible;
191+
type Database = ConcurrentState<Arc<ConcurrentState<Db>>>;
192+
type Error = TrevmBuilderError;
199193

200-
fn connect(&'a self) -> Result<Self::Database, Self::Error> {
194+
fn connect(&self) -> Result<Self::Database, Self::Error> {
201195
let inner = ConcurrentState::new(self.db.clone(), ConcurrentStateInfo::default());
202-
Ok(inner)
196+
let outer = ConcurrentState::new(Arc::new(inner), ConcurrentStateInfo::default());
197+
Ok(outer)
203198
}
204199
}
205200

206201
/// Makes a SimulatorFactory capable of creating and configuring trevm instances
207-
impl<'a, Db, Ext> EvmFactory<'a> for SimulatorFactory<Db, Ext>
202+
impl<Db, Insp> EvmFactory for SimulatorFactory<Db, Insp>
208203
where
209204
Db: Database + DatabaseRef + DatabaseCommit + Sync + Send + Clone + 'static,
210-
Ext: Sync + Clone,
205+
Insp: Inspector<Ctx<ConcurrentState<Arc<ConcurrentState<Db>>>>> + Sync + Clone,
211206
{
212-
type Ext = ();
207+
type Insp = Insp;
213208

214-
/// Create makes a [`ConcurrentState`] database by calling connect
215-
fn create(&'a self) -> Result<trevm::EvmNeedsCfg<'a, Self::Ext, Self::Database>, Self::Error> {
209+
fn create(
210+
&self,
211+
) -> std::result::Result<trevm::EvmNeedsCfg<Self::Database, Self::Insp>, Self::Error> {
216212
let db = self.connect()?;
217-
let trevm = trevm::revm::EvmBuilder::default().with_db(db).build_trevm();
218-
Ok(trevm)
213+
let result =
214+
TrevmBuilder::new().with_db(db).with_insp(self.inspector.clone()).build_trevm();
215+
match result {
216+
Ok(t) => Ok(t),
217+
Err(e) => Err(e.into()),
218+
}
219219
}
220220
}
221221

222-
/// A trait for extracting transactions from
223-
pub trait BlockExtractor<Ext, Db: Database + DatabaseCommit>: Send + Sync + 'static {
222+
pub trait BlockExtractor<Insp, Db>
223+
where
224+
Db: Database + DatabaseCommit,
225+
Insp: Inspector<Ctx<Db>>,
226+
{
224227
/// BlockDriver runs the transactions over the provided trevm instance.
225-
type Driver: BlockDriver<Ext, Error<Db>: core::error::Error>;
228+
type Driver: BlockDriver<Insp, Error<Db>: core::error::Error>;
226229

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

230233
/// Extracts transactions from the source.
231234
///
232235
/// Extraction is infallible. Worst case it should return a no-op driver.
233236
fn extract(&mut self, bytes: &[u8]) -> Self::Driver;
234237
}
235238

236-
impl<Ext> BlockDriver<Ext> for InProgressBlock {
239+
impl<Insp> BlockDriver<Insp> for InProgressBlock {
237240
type Block = NoopBlock;
238241

239242
type Error<Db: Database + DatabaseCommit> = Error<Db>;
@@ -244,10 +247,13 @@ impl<Ext> BlockDriver<Ext> for InProgressBlock {
244247

245248
/// Loops through the transactions in the block and runs them, accepting the state at the end
246249
/// if it was successful and returning and erroring out otherwise.
247-
fn run_txns<'a, Db: Database + DatabaseCommit>(
250+
fn run_txns<Db: Database + DatabaseCommit>(
248251
&mut self,
249-
mut trevm: trevm::EvmNeedsTx<'a, Ext, Db>,
250-
) -> trevm::RunTxResult<'a, Ext, Db, Self> {
252+
mut trevm: trevm::EvmNeedsTx<Db, Insp>,
253+
) -> trevm::RunTxResult<Db, Insp, Self>
254+
where
255+
Insp: Inspector<Ctx<Db>>,
256+
{
251257
for tx in self.transactions().iter() {
252258
if tx.recover_signer().is_ok() {
253259
let sender = tx.recover_signer().unwrap();
@@ -272,8 +278,11 @@ impl<Ext> BlockDriver<Ext> for InProgressBlock {
272278

273279
fn post_block<Db: Database + DatabaseCommit>(
274280
&mut self,
275-
_trevm: &trevm::EvmNeedsBlock<'_, Ext, Db>,
276-
) -> Result<(), Self::Error<Db>> {
281+
_trevm: &trevm::EvmNeedsBlock<Db, Insp>,
282+
) -> Result<(), Self::Error<Db>>
283+
where
284+
Insp: Inspector<Ctx<Db>>,
285+
{
277286
Ok(())
278287
}
279288
}
@@ -330,4 +339,4 @@ pub fn eval_fn(state: &ResultAndState) -> U256 {
330339
tracing::info!(balance = ?target_account.info.balance, "target account balance");
331340

332341
target_account.info.balance
333-
}
342+
}

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)