Skip to content
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

feat: support no_std #250

Merged
merged 7 commits into from
Jan 18, 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
8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ alloy-sol-types = "0.8"
alloy-primitives = { version = "0.8", features = ["map"] }
revm = { version = "19.0.0", default-features = false, features = ["std"] }

anstyle = "1.0"
anstyle = { version = "1.0", optional = true }
colorchoice = "1.0"
thiserror = "2.0"
thiserror = { version = "2.0", default-features = false }

# serde
serde = { version = "1", optional = true, features = ["derive"] }
serde_json = "1.0"
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

# js-tracer
boa_engine = { version = "0.20", optional = true }
Expand All @@ -52,5 +52,7 @@ boa_gc = { version = "0.20", optional = true }
snapbox = { version = "0.6", features = ["term-svg"] }

[features]
default = ["std"]
std = ["alloy-primitives/std", "anstyle/std", "serde/std", "serde_json/std", "revm/std", "thiserror/std"]
serde = ["dep:serde", "revm/serde"]
js-tracer = ["dep:boa_engine", "dep:boa_gc"]
7 changes: 5 additions & 2 deletions src/access_list.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use alloy_primitives::{Address, B256};
use alloc::collections::BTreeSet;
use alloy_primitives::{
map::{HashMap, HashSet},
Address, B256,
};
use alloy_rpc_types_eth::{AccessList, AccessListItem};
use revm::{
interpreter::{opcode, Interpreter},
Database, EvmContext, Inspector,
};
use std::collections::{BTreeSet, HashMap, HashSet};

/// An [Inspector] that collects touched accounts and storage slots.
///
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![deny(unused_must_use, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

/// An inspector implementation for an EIP2930 Accesslist
pub mod access_list;
Expand Down
3 changes: 2 additions & 1 deletion src/opcode.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::string::ToString;
use alloy_primitives::map::HashMap;
use alloy_rpc_types_trace::opcode::OpcodeGas;
use revm::{
interpreter::{
Expand All @@ -6,7 +8,6 @@ use revm::{
},
Database, EvmContext, Inspector,
};
use std::collections::HashMap;

/// An Inspector that counts opcodes and measures gas usage per opcode.
#[derive(Clone, Debug, Default)]
Expand Down
1 change: 1 addition & 0 deletions src/tracing/arena.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::types::{CallTrace, CallTraceNode, TraceMemberOrder};
use alloc::{vec, vec::Vec};

/// An arena of recorded traces.
///
Expand Down
17 changes: 9 additions & 8 deletions src/tracing/builder/geth.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
//! Geth trace builder

use crate::tracing::{
types::{CallTraceNode, CallTraceStepStackItem},
utils::load_account_code,
};
use alloy_primitives::{Address, Bytes, B256, U256};
use alloc::{
borrow::Cow,
collections::{BTreeMap, VecDeque},
vec::Vec,
};
use alloy_primitives::{map::HashMap, Address, Bytes, B256, U256};
use alloy_rpc_types_trace::geth::{
AccountChangeKind, AccountState, CallConfig, CallFrame, DefaultFrame, DiffMode,
GethDefaultTracingOptions, PreStateConfig, PreStateFrame, PreStateMode, StructLog,
Expand All @@ -13,10 +17,6 @@ use revm::{
db::DatabaseRef,
primitives::{EvmState, ResultAndState},
};
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap, VecDeque},
};

/// A type for creating geth style traces
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -111,7 +111,7 @@ impl<'a> GethTraceBuilder<'a> {
let main_trace = &main_trace_node.trace;

let mut struct_logs = Vec::new();
let mut storage = HashMap::new();
let mut storage = HashMap::default();
self.fill_geth_trace(main_trace_node, &opts, &mut storage, &mut struct_logs);

DefaultFrame {
Expand Down Expand Up @@ -267,7 +267,8 @@ impl<'a> GethTraceBuilder<'a> {
) -> Result<PreStateFrame, DB::Error> {
let account_diffs = state.iter().map(|(addr, acc)| (*addr, acc));
let mut state_diff = DiffMode::default();
let mut account_change_kinds = HashMap::with_capacity(account_diffs.len());
let mut account_change_kinds =
HashMap::with_capacity_and_hasher(account_diffs.len(), Default::default());
for (addr, changed_acc) in account_diffs {
let db_acc = db.basic_ref(addr)?.unwrap_or_default();

Expand Down
3 changes: 2 additions & 1 deletion src/tracing/builder/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ use crate::tracing::{
utils::load_account_code,
TracingInspectorConfig,
};
use alloc::{collections::VecDeque, string::ToString, vec, vec::Vec};
use alloy_primitives::{map::HashSet, Address, U256, U64};
use alloy_rpc_types_eth::TransactionInfo;
use alloy_rpc_types_trace::parity::*;
use core::iter::Peekable;
use revm::{
db::DatabaseRef,
primitives::{Account, ExecutionResult, ResultAndState, SpecId, KECCAK_EMPTY},
};
use std::{collections::VecDeque, iter::Peekable};

/// A type for creating parity style traces
///
Expand Down
2 changes: 1 addition & 1 deletion src/tracing/builder/walker.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::tracing::types::CallTraceNode;
use std::collections::VecDeque;
use alloc::{collections::VecDeque, vec::Vec};

/// Traverses the internal tracing structure breadth-first.
///
Expand Down
5 changes: 2 additions & 3 deletions src/tracing/fourbyte.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@
//! ```
//!
//! See also <https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers>

use alloy_primitives::{hex, Selector};
use alloc::format;
use alloy_primitives::{hex, map::HashMap, Selector};
use alloy_rpc_types_trace::geth::FourByteFrame;
use revm::{
interpreter::{CallInputs, CallOutcome},
Database, EvmContext, Inspector,
};
use std::collections::HashMap;

/// Fourbyte tracing inspector that records all function selectors and their calldata sizes.
#[derive(Clone, Debug, Default)]
Expand Down
18 changes: 12 additions & 6 deletions src/tracing/js/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ use crate::tracing::{
types::CallKind,
TransactionContext,
};
use alloc::{
boxed::Box,
format,
rc::Rc,
string::{String, ToString},
};
use alloy_primitives::{Address, Bytes, B256, U256};
use boa_engine::{
js_string,
Expand All @@ -16,6 +22,7 @@ use boa_engine::{
Context, JsArgs, JsError, JsNativeError, JsObject, JsResult, JsValue,
};
use boa_gc::{empty_trace, Finalize, Trace};
use core::cell::RefCell;
use revm::{
interpreter::{
opcode::{PUSH0, PUSH32},
Expand All @@ -24,7 +31,6 @@ use revm::{
primitives::{AccountInfo, Bytecode, EvmState, KECCAK_EMPTY},
DatabaseRef,
};
use std::{cell::RefCell, rc::Rc};

/// A macro that creates a native function that returns via [JsValue::from]
macro_rules! js_value_getter {
Expand Down Expand Up @@ -99,7 +105,7 @@ impl<Val: 'static> GuardedNullableGc<Val> {

// SAFETY: guard enforces that the value is removed from the refcell before it is dropped.
#[allow(clippy::missing_transmute_annotations)]
let this = Self { inner: unsafe { std::mem::transmute(inner) } };
let this = Self { inner: unsafe { core::mem::transmute(inner) } };

(this, guard)
}
Expand Down Expand Up @@ -752,7 +758,7 @@ impl EvmDbRef {
pub(crate) fn new<'a, 'b, DB>(state: &'a EvmState, db: &'b DB) -> (Self, EvmDbGuard<'a, 'b>)
where
DB: DatabaseRef,
DB::Error: std::fmt::Display,
DB::Error: core::fmt::Display,
{
let (state, state_guard) = StateRef::new(state);

Expand All @@ -764,7 +770,7 @@ impl EvmDbRef {
// the guard.
let db = JsDb(db);
let js_db = unsafe {
std::mem::transmute::<
core::mem::transmute::<
Box<dyn DatabaseRef<Error = String> + '_>,
Box<dyn DatabaseRef<Error = String> + 'static>,
>(Box::new(db))
Expand Down Expand Up @@ -799,7 +805,7 @@ impl EvmDbRef {
let acc = self.read_basic(address, ctx)?;
let code_hash = acc.map(|acc| acc.code_hash).unwrap_or(KECCAK_EMPTY);
if code_hash == KECCAK_EMPTY {
return JsUint8Array::from_iter(std::iter::empty(), ctx);
return JsUint8Array::from_iter(core::iter::empty(), ctx);
}

let Some(Ok(bytecode)) = self.inner.db.0.with_inner(|db| db.code_by_hash_ref(code_hash))
Expand Down Expand Up @@ -948,7 +954,7 @@ pub(crate) struct JsDb<DB: DatabaseRef>(DB);
impl<DB> DatabaseRef for JsDb<DB>
where
DB: DatabaseRef,
DB::Error: std::fmt::Display,
DB::Error: core::fmt::Display,
{
type Error = String;

Expand Down
5 changes: 3 additions & 2 deletions src/tracing/js/builtins.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Builtin functions

use alloy_primitives::{hex, Address, FixedBytes, B256, U256};
use alloc::{format, string::ToString, vec::Vec};
use alloy_primitives::{hex, map::HashSet, Address, FixedBytes, B256, U256};
use boa_engine::{
builtins::{array_buffer::ArrayBuffer, typed_array::TypedArray},
js_string,
Expand All @@ -9,7 +10,7 @@ use boa_engine::{
Context, JsArgs, JsError, JsNativeError, JsResult, JsString, JsValue, NativeFunction, Source,
};
use boa_gc::{empty_trace, Finalize, Trace};
use std::{borrow::Borrow, collections::HashSet};
use core::borrow::Borrow;

/// bigIntegerJS is the minified version of <https://github.com/peterolson/BigInteger.js>.
pub(crate) const BIG_INT_JS: &str = include_str!("bigint.js");
Expand Down
11 changes: 8 additions & 3 deletions src/tracing/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ use crate::tracing::{
types::CallKind,
TransactionContext,
};
use alloc::{
format,
string::{String, ToString},
vec::Vec,
};
use alloy_primitives::{Address, Bytes, Log, U256};
pub use boa_engine::vm::RuntimeLimits;
use boa_engine::{js_string, Context, JsError, JsObject, JsResult, JsValue, Source};
Expand Down Expand Up @@ -213,7 +218,7 @@ impl JsInspector {
) -> Result<serde_json::Value, JsInspectorError>
where
DB: DatabaseRef,
<DB as DatabaseRef>::Error: std::fmt::Display,
<DB as DatabaseRef>::Error: core::fmt::Display,
{
let result = self.result(res, env, db)?;
Ok(to_serde_value(result, &mut self.ctx)?)
Expand All @@ -228,7 +233,7 @@ impl JsInspector {
) -> Result<JsValue, JsInspectorError>
where
DB: DatabaseRef,
<DB as DatabaseRef>::Error: std::fmt::Display,
<DB as DatabaseRef>::Error: core::fmt::Display,
{
let ResultAndState { result, state } = res;
let (db, _db_guard) = EvmDbRef::new(&state, db);
Expand Down Expand Up @@ -388,7 +393,7 @@ impl JsInspector {
impl<DB> Inspector<DB> for JsInspector
where
DB: Database + DatabaseRef,
<DB as DatabaseRef>::Error: std::fmt::Display,
<DB as DatabaseRef>::Error: core::fmt::Display,
{
fn step(&mut self, interp: &mut Interpreter, context: &mut EvmContext<DB>) {
if self.step_fn.is_none() {
Expand Down
3 changes: 3 additions & 0 deletions src/tracing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::{
utils::gas_used,
},
};
use alloc::vec::Vec;
use alloy_primitives::{Address, Bytes, Log, B256, U256};
use revm::{
interpreter::{
Expand Down Expand Up @@ -43,7 +44,9 @@ use types::{CallLog, CallTrace, CallTraceStep};

mod utils;

#[cfg(feature = "std")]
mod writer;
#[cfg(feature = "std")]
pub use writer::{TraceWriter, TraceWriterConfig};

#[cfg(feature = "js-tracer")]
Expand Down
1 change: 1 addition & 0 deletions src/tracing/mux.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::tracing::{FourByteInspector, TracingInspector, TracingInspectorConfig};
use alloc::vec::Vec;
use alloy_primitives::{map::HashMap, Address, Log, U256};
use alloy_rpc_types_eth::TransactionInfo;
use alloy_rpc_types_trace::geth::{
Expand Down
11 changes: 8 additions & 3 deletions src/tracing/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
//! Types for representing call trace items.

use crate::tracing::{config::TraceStyle, utils, utils::convert_memory};
use alloc::{
collections::VecDeque,
format,
string::{String, ToString},
vec::Vec,
};
pub use alloy_primitives::Log;
use alloy_primitives::{Address, Bytes, FixedBytes, LogData, U256};
use alloy_rpc_types_trace::{
Expand All @@ -11,7 +17,6 @@ use alloy_rpc_types_trace::{
},
};
use revm::interpreter::{opcode, CallScheme, CreateScheme, InstructionResult, OpCode};
use std::collections::VecDeque;

/// Decoded call data.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
Expand Down Expand Up @@ -534,8 +539,8 @@ impl From<CallKind> for CreationMethod {
}
}

impl std::fmt::Display for CallKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for CallKind {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.to_str())
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/tracing/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
//! Util functions for revm related ops

use alloc::{
string::{String, ToString},
vec::Vec,
};
use alloy_primitives::{hex, Bytes};
use alloy_sol_types::{ContractError, GenericRevertReason};
use revm::{
Expand Down
8 changes: 3 additions & 5 deletions src/tracing/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ use super::{
},
CallTraceArena,
};
use alloy_primitives::{address, hex, Address, B256, U256};
use alloc::{format, string::String, vec::Vec};
use alloy_primitives::{address, hex, map::HashMap, Address, B256, U256};
use anstyle::{AnsiColor, Color, Style};
use colorchoice::ColorChoice;
use std::{
collections::HashMap,
io::{self, Write},
};
use std::io::{self, Write};

const CHEATCODE_ADDRESS: Address = address!("7109709ECfa91a80626fF3989D68f67F5b1DD12D");

Expand Down
1 change: 1 addition & 0 deletions src/transfer.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use alloc::{vec, vec::Vec};
use alloy_primitives::{address, b256, Address, Log, LogData, B256, U256};
use alloy_sol_types::SolValue;
use revm::{
Expand Down
5 changes: 5 additions & 0 deletions tests/it/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
#![allow(missing_docs)]
#[cfg(feature = "std")]
pub mod utils;

#[cfg(feature = "std")]
mod geth;
#[cfg(feature = "js-tracer")]
mod geth_js;
#[cfg(feature = "std")]
mod parity;
#[cfg(feature = "std")]
mod transfer;
#[cfg(feature = "std")]
mod writer;
Loading