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: sendRawTransaction cheatcode #4931

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion crates/cheatcodes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ alloy-primitives.workspace = true
alloy-genesis.workspace = true
alloy-sol-types.workspace = true
alloy-provider.workspace = true
alloy-rpc-types.workspace = true
alloy-rpc-types = { workspace = true, features = ["k256"] }
alloy-signer.workspace = true
alloy-signer-local = { workspace = true, features = [
"mnemonic-all-languages",
"keystore",
] }
parking_lot.workspace = true
alloy-consensus = { workspace = true, features = ["k256"] }
alloy-rlp.workspace = true

eyre.workspace = true
itertools.workspace = true
Expand Down
20 changes: 20 additions & 0 deletions crates/cheatcodes/assets/cheatcodes.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/cheatcodes/spec/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,10 @@ interface Vm {
#[cheatcode(group = Evm, safety = Safe)]
function lastCallGas() external view returns (Gas memory gas);

/// takes a signed transaction as bytes and executes it
#[cheatcode(group = Evm, safety = Safe)]
function broadcastRawTransaction(bytes calldata data) external;

// ======== Test Assertions and Utilities ========

/// If the condition is false, discard this run's fuzz inputs and generate new ones.
Expand Down
35 changes: 34 additions & 1 deletion crates/cheatcodes/src/evm.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
//! Implementations of [`Evm`](spec::Group::Evm) cheatcodes.

use crate::{Cheatcode, Cheatcodes, CheatsCtxt, Result, Vm::*};
use crate::{
BroadcastableTransaction, Cheatcode, Cheatcodes, CheatcodesExecutor, CheatsCtxt, Result, Vm::*,
};
use alloy_consensus::TxEnvelope;
use alloy_genesis::{Genesis, GenesisAccount};
use alloy_primitives::{Address, Bytes, B256, U256};
use alloy_rlp::Decodable;
use alloy_sol_types::SolValue;
use foundry_common::fs::{read_json_file, write_json_file};
use foundry_evm_core::{
Expand Down Expand Up @@ -567,6 +571,35 @@ impl Cheatcode for stopAndReturnStateDiffCall {
}
}

impl Cheatcode for broadcastRawTransactionCall {
fn apply_full<DB: DatabaseExt, E: CheatcodesExecutor>(
&self,
ccx: &mut CheatsCtxt<DB>,
executor: &mut E,
) -> Result {
let mut data = self.data.as_ref();
let tx = TxEnvelope::decode(&mut data).map_err(|err| {
fmt_err!("broadcastRawTransaction: error decoding transaction ({err})")
})?;

if ccx.state.broadcast.is_some() {
ccx.state.broadcastable_transactions.push_back(BroadcastableTransaction {
rpc: ccx.db.active_fork_url(),
transaction: tx.clone().try_into()?,
});
}

ccx.ecx.db.transact_from_tx(
tx.into(),
&ccx.ecx.env,
&mut ccx.ecx.journaled_state,
&mut executor.get_inspector(ccx.state),
)?;

Ok(Default::default())
}
}

impl Cheatcode for setBlockhashCall {
fn apply_stateful<DB: DatabaseExt>(&self, ccx: &mut CheatsCtxt<DB>) -> Result {
let Self { blockNumber, blockHash } = *self;
Expand Down
12 changes: 7 additions & 5 deletions crates/cheatcodes/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::{
use alloy_primitives::{hex, Address, Bytes, Log, TxKind, B256, U256};
use alloy_rpc_types::request::{TransactionInput, TransactionRequest};
use alloy_sol_types::{SolCall, SolInterface, SolValue};
use foundry_common::{evm::Breakpoints, SELECTOR_LEN};
use foundry_common::{evm::Breakpoints, TransactionMaybeSigned, SELECTOR_LEN};
use foundry_config::Config;
use foundry_evm_abi::Console;
use foundry_evm_core::{
Expand Down Expand Up @@ -198,12 +198,12 @@ impl Context {
}

/// Helps collecting transactions from different forks.
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug)]
pub struct BroadcastableTransaction {
/// The optional RPC URL.
pub rpc: Option<String>,
/// The transaction to broadcast.
pub transaction: TransactionRequest,
pub transaction: TransactionMaybeSigned,
}

/// List of transactions that can be broadcasted.
Expand Down Expand Up @@ -523,7 +523,8 @@ impl Cheatcodes {
None
},
..Default::default()
},
}
.into(),
});

input.log_debug(self, &input.scheme().unwrap_or(CreateScheme::Create));
Expand Down Expand Up @@ -859,7 +860,8 @@ impl Cheatcodes {
None
},
..Default::default()
},
}
.into(),
});
debug!(target: "cheatcodes", tx=?self.broadcastable_transactions.back().unwrap(), "broadcastable call");

Expand Down
1 change: 1 addition & 0 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ alloy-transport-http = { workspace = true, features = [
alloy-transport-ipc.workspace = true
alloy-transport-ws.workspace = true
alloy-transport.workspace = true
alloy-consensus = { workspace = true, features = ["k256"] }

tower.workspace = true

Expand Down
89 changes: 88 additions & 1 deletion crates/common/src/transactions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Wrappers for transactions.

use alloy_consensus::{Transaction, TxEnvelope};
use alloy_primitives::{Address, TxKind, U256};
use alloy_provider::{network::AnyNetwork, Provider};
use alloy_rpc_types::{AnyTransactionReceipt, BlockId};
use alloy_rpc_types::{AnyTransactionReceipt, BlockId, TransactionRequest};
use alloy_serde::WithOtherFields;
use alloy_transport::Transport;
use eyre::Result;
Expand Down Expand Up @@ -144,3 +146,88 @@ mod tests {
assert_eq!(extract_revert_reason(error_string_2), None);
}
}

/// Used for broadcasting transactions
/// A transaction can either be a TransactionRequest waiting to be signed
/// or a TxEnvelope, already signed
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TransactionMaybeSigned {
Signed {
#[serde(flatten)]
tx: TxEnvelope,
from: Address,
},
Unsigned(WithOtherFields<TransactionRequest>),
}

impl TransactionMaybeSigned {
/// Creates a new (unsigned) transaction for broadcast
pub fn new(tx: WithOtherFields<TransactionRequest>) -> Self {
Self::Unsigned(tx)
}

/// Creates a new signed transaction for broadcast.
pub fn new_signed(
tx: TxEnvelope,
) -> core::result::Result<Self, alloy_primitives::SignatureError> {
let from = tx.recover_signer()?;
Ok(Self::Signed { tx, from })
}

pub fn as_unsigned_mut(&mut self) -> Option<&mut WithOtherFields<TransactionRequest>> {
match self {
Self::Unsigned(tx) => Some(tx),
_ => None,
}
}

pub fn from(&self) -> Option<Address> {
match self {
Self::Signed { from, .. } => Some(*from),
Self::Unsigned(tx) => tx.from,
}
}

pub fn input(&self) -> Option<&[u8]> {
match self {
Self::Signed { tx, .. } => Some(tx.input()),
Self::Unsigned(tx) => tx.input.input().map(|i| i.as_ref()),
}
}

pub fn to(&self) -> Option<TxKind> {
match self {
Self::Signed { tx, .. } => Some(tx.to()),
Self::Unsigned(tx) => tx.to,
}
}

pub fn value(&self) -> Option<U256> {
match self {
Self::Signed { tx, .. } => Some(tx.value()),
Self::Unsigned(tx) => tx.value,
}
}

pub fn gas(&self) -> Option<u128> {
match self {
Self::Signed { tx, .. } => Some(tx.gas_limit()),
Self::Unsigned(tx) => tx.gas,
}
}
}

impl From<TransactionRequest> for TransactionMaybeSigned {
fn from(tx: TransactionRequest) -> Self {
Self::new(WithOtherFields::new(tx))
}
}

impl TryFrom<TxEnvelope> for TransactionMaybeSigned {
type Error = alloy_primitives::SignatureError;

fn try_from(tx: TxEnvelope) -> core::result::Result<Self, Self::Error> {
Self::new_signed(tx)
}
}
11 changes: 11 additions & 0 deletions crates/evm/core/src/backend/cow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
};
use alloy_genesis::GenesisAccount;
use alloy_primitives::{Address, B256, U256};
use alloy_rpc_types::TransactionRequest;
use eyre::WrapErr;
use foundry_fork_db::DatabaseError;
use revm::{
Expand Down Expand Up @@ -190,6 +191,16 @@ impl<'a> DatabaseExt for CowBackend<'a> {
self.backend_mut(env).transact(id, transaction, env, journaled_state, inspector)
}

fn transact_from_tx(
&mut self,
transaction: TransactionRequest,
env: &Env,
journaled_state: &mut JournaledState,
inspector: &mut dyn InspectorExt<Backend>,
) -> eyre::Result<()> {
self.backend_mut(env).transact_from_tx(transaction, env, journaled_state, inspector)
}

fn active_fork_id(&self) -> Option<LocalForkId> {
self.backend.active_fork_id()
}
Expand Down
Loading
Loading