Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
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
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
rust-version = "1.81"
rust-version = "1.83"
authors = ["Alloy Contributors"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/alloy-rs/examples"
Expand Down Expand Up @@ -95,7 +95,7 @@ significant_drop_tightening = "allow"
needless_return = "allow"

[workspace.dependencies]
alloy = { version = "0.14", features = [
alloy = { version = "0.15", features = [
"eips",
"full",
"json-rpc",
Expand All @@ -114,7 +114,7 @@ alloy = { version = "0.14", features = [

# async
futures-util = "0.3"
tokio = "1.44"
tokio = "1.45"

# misc
eyre = "0.6"
Expand Down
4 changes: 2 additions & 2 deletions benches/benches/rlp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ fn rlp(c: &mut Criterion) {
g.bench_with_input("Alloy-Rlp/Encoding", &my_struct, |b, my_struct| {
b.iter(|| {
let mut out = Vec::new();
let _ = my_struct.encode(&mut out);
my_struct.encode(&mut out);
black_box(out);
})
});

let mut encoded = Vec::new();
let _ = my_struct.encode(&mut encoded);
my_struct.encode(&mut encoded);

// Parity RLP decoding
g.bench_with_input("Parity-Rlp/Decoding", &encoded, |b, encoded| {
Expand Down
2 changes: 1 addition & 1 deletion clippy.toml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
msrv = "1.81"
msrv = "1.83"
19 changes: 10 additions & 9 deletions examples/advanced/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@ repository.workspace = true
workspace = true

[dev-dependencies]
foundry-fork-db = "0.13"
alloy.workspace = true
# foundry-fork-db = "0.12"
alloy-evm = "0.7.2"

# # reth
# revm-primitives = { version = "17.0.0", default-features = false }
# revm = { version = "21.0.0", default-features = false }
# reth-db = { git = "https://github.com/paradigmxyz/reth", package = "reth-db", rev = "v1.3.8" }
# reth-provider = { git = "https://github.com/paradigmxyz/reth", package = "reth-provider", rev = "v1.3.8" }
# reth-node-types = { git = "https://github.com/paradigmxyz/reth", package = "reth-node-types", rev = "v1.3.8" }
# reth-chainspec = { git = "https://github.com/paradigmxyz/reth", package = "reth-chainspec", rev = "v1.3.8" }
# reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", package = "reth-node-ethereum", rev = "v1.3.8" }
# reth
revm = { version = "23.1.0", default-features = false }
revm-primitives = { version = "19.0.0", default-features = false }
reth-db = { git = "https://github.com/paradigmxyz/reth", package = "reth-db", rev = "55f4b0b" }
reth-provider = { git = "https://github.com/paradigmxyz/reth", package = "reth-provider", rev = "55f4b0b" }
reth-node-types = { git = "https://github.com/paradigmxyz/reth", package = "reth-node-types", rev = "55f4b0b" }
reth-chainspec = { git = "https://github.com/paradigmxyz/reth", package = "reth-chainspec", rev = "55f4b0b" }
reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", package = "reth-node-ethereum", rev = "55f4b0b" }
Comment on lines +23 to +27
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also move this entirely to reth and just reference it here


eyre.workspace = true
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
Expand Down
7 changes: 4 additions & 3 deletions examples/advanced/examples/any_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ async fn main() -> Result<()> {

// Create a provider with the Arbitrum Sepolia network and the wallet.
let rpc_url = "https://sepolia-rollup.arbitrum.io/rpc".parse()?;
let provider = ProviderBuilder::new().network::<AnyNetwork>().wallet(signer).on_http(rpc_url);
let provider =
ProviderBuilder::new().network::<AnyNetwork>().wallet(signer).connect_http(rpc_url);

// Create a contract instance.
let contract = Counter::new(COUNTER_CONTRACT_ADDRESS, &provider);
Expand All @@ -62,8 +63,8 @@ async fn main() -> Result<()> {
let l1_gas = arb_fields.gas_used_for_l1.to::<u128>();
let l1_block_number = arb_fields.l1_block_number.to::<u64>();

println!("Gas used for L1: {}", l1_gas);
println!("L1 block number: {}", l1_block_number);
println!("Gas used for L1: {l1_gas}");
println!("L1 block number: {l1_block_number}");

Ok(())
}
6 changes: 3 additions & 3 deletions examples/advanced/examples/decoding_json_abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Functions
println!("Functions:");
for (name, functions) in &abi.functions {
println!("\n>> {}:", name);
println!("\n>> {name}:");
for function in functions {
println!(" Inputs: {:?}", function.inputs);
println!(" Outputs: {:?}", function.outputs);
Expand All @@ -36,7 +36,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Events
println!("Events:");
for (name, events) in &abi.events {
println!("\n>> {}:", name);
println!("\n>> {name}:");
for event in events {
println!(" Inputs: {:?}", event.inputs);
println!(" Anonymous: {}", event.anonymous);
Expand All @@ -48,7 +48,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Errors
println!("Errors:");
for (name, errors) in &abi.errors {
println!(">> {}:", name);
println!(">> {name}:");
for error in errors {
println!(" Inputs: {:?}", error.inputs);
}
Expand Down
4 changes: 2 additions & 2 deletions examples/advanced/examples/encoding_dyn_abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

// Verify the signature
let recovered_address = signature.recover_address_from_prehash(&eip712_hash)?;
println!("Recovered address: {}", recovered_address);
println!("Recovered address: {recovered_address}");

assert_eq!(recovered_address, wallet.address(), "Signature verification failed");
println!("Signature verified successfully!");
Expand All @@ -87,7 +87,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
fn print_tuple(value: &DynSolValue, field_names: &[&str]) {
if let DynSolValue::Tuple(values) = value {
for (value, name) in values.iter().zip(field_names.iter()) {
println!(" {}: {:?}", name, value);
println!(" {name}: {value:?}");
}
}
}
2 changes: 1 addition & 1 deletion examples/advanced/examples/encoding_sol_static.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

let encoded = hex::encode(swapExactTokensForTokensCall::abi_encode(&swap_data));

println!("Encoded: 0x{}", encoded);
println!("Encoded: 0x{encoded}");

Ok(())
}
57 changes: 31 additions & 26 deletions examples/advanced/examples/foundry_fork_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,29 @@ use alloy::{
providers::{Provider, ProviderBuilder},
rpc::types::TransactionRequest,
};
use alloy_evm::{eth::EthEvmContext, EthEvm, Evm};
Copy link
Member Author

@zerosnacks zerosnacks May 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯!

use eyre::Result;
use foundry_fork_db::{cache::BlockchainDbMeta, BlockchainDb, SharedBackend};
use revm::{db::CacheDB, DatabaseRef, Evm};
use revm_primitives::{BlobExcessGasAndPrice, BlockEnv, TxEnv};
use revm::{
context::{BlockEnv, Evm as RevmEvm, TxEnv},
context_interface::block::BlobExcessGasAndPrice,
database::WrapDatabaseRef,
handler::{instructions::EthInstructions, EthPrecompiles},
inspector::NoOpInspector,
DatabaseRef,
};

#[tokio::main]
async fn main() -> Result<()> {
let anvil = Anvil::new().spawn();
let provider = ProviderBuilder::new().network::<AnyNetwork>().on_http(anvil.endpoint_url());
let provider =
ProviderBuilder::new().network::<AnyNetwork>().connect_http(anvil.endpoint_url());

let block = provider.get_block(BlockId::latest()).await?.unwrap();

// The `BlockchainDbMeta` is used a identifier when the db is flushed to the disk.
// This aids in cases where the disk contains data from multiple forks.
let meta = BlockchainDbMeta::default()
.with_chain_id(31337)
.with_block(&block.inner)
.with_url(&anvil.endpoint());
let meta = BlockchainDbMeta::default().with_block(&block.inner).with_url(&anvil.endpoint());

let db = BlockchainDb::new(meta, None);

Expand All @@ -45,9 +50,8 @@ async fn main() -> Result<()> {
//
// For example, if we send two requests to get_full_block(0) simultaneously, the
// `BackendHandler` is smart enough to only send one request to the RPC provider, and queue the
// other request until the response is received.
// Once the response from RPC provider is received it relays the response to both the requests
// over their respective channels.
// other request until the response is received. Once the response from RPC provider is
// received it relays the response to both the requests // over their respective channels.
//
// The `SharedBackend` and `BackendHandler` communicate over an unbounded channel.
let shared = SharedBackend::spawn_backend(Arc::new(provider.clone()), db, None).await;
Expand Down Expand Up @@ -87,15 +91,15 @@ async fn main() -> Result<()> {
.with_gas_limit(21000)
.with_nonce(0);

let mut evm = configure_evm_env(block, shared.clone(), configure_tx_env(tx_req));
let mut evm = configure_evm(block, shared.clone());

// Fetches accounts from the RPC
let start_t = std::time::Instant::now();
let alice_bal = shared.basic_ref(alice)?.unwrap().balance;
let bob_bal = shared.basic_ref(bob)?.unwrap().balance;
let time_rpc = start_t.elapsed();

let res = evm.transact().unwrap();
let res = evm.transact(configure_tx_env(tx_req)).unwrap();

let total_spent = U256::from(res.result.gas_used()) * U256::from(basefee) + U256::from(100);

Expand All @@ -117,18 +121,16 @@ async fn main() -> Result<()> {
Ok(())
}

fn configure_evm_env(
fn configure_evm(
block: AnyRpcBlock,
shared: SharedBackend,
tx_env: TxEnv,
) -> Evm<'static, (), CacheDB<SharedBackend>> {
let basefee = block.header.base_fee_per_gas().map(U256::from).unwrap_or_default();
) -> EthEvm<WrapDatabaseRef<SharedBackend>, NoOpInspector> {
let block_env = BlockEnv {
number: U256::from(block.header.number()),
coinbase: block.header.beneficiary(),
timestamp: U256::from(block.header.timestamp()),
gas_limit: U256::from(block.header.gas_limit()),
basefee,
number: block.header.number(),
beneficiary: block.header.beneficiary(),
timestamp: block.header.timestamp(),
gas_limit: block.header.gas_limit(),
basefee: block.header.base_fee_per_gas().unwrap_or(0),
prevrandao: block.header.mix_hash(),
difficulty: block.header.difficulty(),
blob_excess_gas_and_price: Some(BlobExcessGasAndPrice::new(
Expand All @@ -137,19 +139,22 @@ fn configure_evm_env(
)),
};

let db = CacheDB::new(shared);
let context =
EthEvmContext::new(WrapDatabaseRef(shared), revm_primitives::hardfork::SpecId::PRAGUE)
.with_block(block_env);

let evm = Evm::builder().with_block_env(block_env).with_db(db).with_tx_env(tx_env).build();
let evm = RevmEvm::new(context, EthInstructions::default(), EthPrecompiles::default())
.with_inspector(NoOpInspector);

evm
EthEvm::new(evm, false)
}

fn configure_tx_env(tx_req: TransactionRequest) -> TxEnv {
TxEnv {
caller: tx_req.from.unwrap(),
transact_to: tx_req.to.unwrap(),
kind: tx_req.to.unwrap(),
value: tx_req.value.unwrap(),
gas_price: U256::from(tx_req.max_fee_per_gas.unwrap()),
gas_price: tx_req.max_fee_per_gas.unwrap(),
gas_limit: tx_req.gas.unwrap_or_default(),
..Default::default()
}
Expand Down
32 changes: 16 additions & 16 deletions examples/advanced/examples/reth_db_layer.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
//! `RethDbLayer` implementation to be used with `RethDbProvider` to wrap the Provider trait over
//! reth-db.

#![allow(dead_code)]
use std::path::PathBuf;
// #![allow(dead_code)]
// use std::path::PathBuf;

/// We use the tower-like layering functionality that has been baked into the alloy-provider to
/// intercept the requests and redirect to the `RethDbProvider`.
pub(crate) struct RethDbLayer {
db_path: PathBuf,
}
// /// We use the tower-like layering functionality that has been baked into the alloy-provider to
// /// intercept the requests and redirect to the `RethDbProvider`.
// pub(crate) struct RethDbLayer {
// db_path: PathBuf,
// }

/// Initialize the `RethDBLayer` with the path to the reth datadir.
impl RethDbLayer {
pub(crate) const fn new(db_path: PathBuf) -> Self {
Self { db_path }
}
// /// Initialize the `RethDBLayer` with the path to the reth datadir.
// impl RethDbLayer {
// pub(crate) const fn new(db_path: PathBuf) -> Self {
// Self { db_path }
// }

pub(crate) const fn db_path(&self) -> &PathBuf {
&self.db_path
}
}
// pub(crate) const fn db_path(&self) -> &PathBuf {
// &self.db_path
// }
// }

const fn main() {}
Loading
Loading