Skip to content

fix: bump alloy to 0.15 #199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
May 12, 2025
Merged
Show file tree
Hide file tree
Changes from all 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(())
}
65 changes: 35 additions & 30 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 All @@ -69,9 +73,9 @@ async fn main() -> Result<()> {

println!("-------get_full_block--------");
// The backend handle falls back to the RPC provider if the block is not in the cache.
println!("1st request (via rpc): {:?}", time_rpc);
println!("1st request (via rpc): {time_rpc:?}");
// The block is cached due to the previous request and can be fetched from db.
println!("2nd request (via fork db): {:?}\n", time_cache);
println!("2nd request (via fork db): {time_cache:?}\n");

let alice = anvil.addresses()[0];
let bob = anvil.addresses()[1];
Expand All @@ -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 @@ -108,27 +112,25 @@ async fn main() -> Result<()> {
let time_cache = start_t.elapsed();

println!("-------get_account--------");
println!("1st request (via rpc): {:?}", time_rpc);
println!("2nd request (via fork db): {:?}\n", time_cache);
println!("1st request (via rpc): {time_rpc:?}");
println!("2nd request (via fork db): {time_cache:?}\n");

assert_eq!(alice_bal_after, alice_bal - total_spent);
assert_eq!(bob_bal_after, bob_bal + U256::from(100));

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
9 changes: 5 additions & 4 deletions examples/advanced/examples/reth_db_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,13 @@ async fn main() -> Result<()> {
// Initialize the provider with the reth-db layer. The reth-db layer intercepts the rpc
// requests and returns the results from the reth-db database.
// Any RPC method that is not implemented in the RethDbProvider gracefully falls back to the
// RPC provider specified in the `on_http` method.
let provider =
ProviderBuilder::new().layer(RethDbLayer::new(db_path)).on_http(reth.endpoint_url());
// RPC provider specified in the `connect_http` method.
let provider = ProviderBuilder::new()
.layer(RethDbLayer::new(db_path))
.connect_http(reth.endpoint_url());

// Initialize the RPC provider to compare the time taken to fetch the results.
let rpc_provider = ProviderBuilder::new().on_http(reth.endpoint_url());
let rpc_provider = ProviderBuilder::new().connect_http(reth.endpoint_url());

println!("--------get_block_number---------");

Expand Down
6 changes: 3 additions & 3 deletions examples/comparison/examples/compare_new_heads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ async fn main() -> Result<()> {
let provider = match ProviderBuilder::new().network::<AnyNetwork>().connect(&url).await {
Ok(provider) => provider,
Err(e) => {
eprintln!("skipping {} at {} because of error: {}", name, url, e);
eprintln!("skipping {name} at {url} because of error: {e}");
continue;
}
};

let mut stream = match provider.subscribe_blocks().await {
Ok(stream) => stream.into_stream().take(10),
Err(e) => {
eprintln!("skipping {} at {} because of error: {}", name, url, e);
eprintln!("skipping {name} at {url} because of error: {e}");
continue;
}
};
Expand All @@ -53,7 +53,7 @@ async fn main() -> Result<()> {
let _p = provider; // keep provider alive
while let Some(header) = stream.next().await {
if let Err(e) = sx.send((name.clone(), header, Utc::now())) {
eprintln!("sending to channel failed: {}", e);
eprintln!("sending to channel failed: {e}");
}
}
}));
Expand Down
8 changes: 4 additions & 4 deletions examples/comparison/examples/compare_pending_txs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async fn main() -> Result<()> {
let mut rpcs = vec![];
for (name, url) in tmp {
if url.starts_with("http") {
eprintln!("skipping {} at {} because it is not a websocket/ipc endpoint", name, url);
eprintln!("skipping {name} at {url} because it is not a websocket/ipc endpoint");
continue;
}
rpcs.push((name, url));
Expand All @@ -41,15 +41,15 @@ async fn main() -> Result<()> {
let provider = match ProviderBuilder::new().network::<AnyNetwork>().connect(&url).await {
Ok(provider) => provider,
Err(e) => {
eprintln!("skipping {} at {} because of error: {}", name, url, e);
eprintln!("skipping {name} at {url} because of error: {e}");
continue;
}
};

let mut stream = match provider.subscribe_pending_transactions().await {
Ok(stream) => stream.into_stream().take(50),
Err(e) => {
eprintln!("skipping {} at {} because of error: {}", name, url, e);
eprintln!("skipping {name} at {url} because of error: {e}");
continue;
}
};
Expand All @@ -60,7 +60,7 @@ async fn main() -> Result<()> {
let _p = provider; // keep provider alive
while let Some(tx_hash) = stream.next().await {
if let Err(e) = sx.send((name.clone(), tx_hash, Utc::now())) {
eprintln!("sending to channel failed: {}", e);
eprintln!("sending to channel failed: {e}");
}
}
}));
Expand Down
3 changes: 2 additions & 1 deletion examples/contracts/examples/arb_profit_calc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Simple arbitrage profit calculator for WETH/DAI pools
//! Reads the balaces of the Uniswap V2 and SushiSwap pools and calculates a basic arb opportunity.
//! Reads the balaces of the Uniswap V2 and `SushiSwap` pools and calculates a basic arb
//! opportunity.

mod helpers;
use crate::helpers::{get_amount_in, get_amount_out, get_sushi_pair, get_uniswap_pair};
Expand Down
Loading