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

Merged
merged 23 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2143b67
feat: sendRawTransaction cheatcode
teddav May 29, 2024
9e75860
added unit tests
teddav Jun 12, 2024
43ed470
clippy + forge fmt
teddav Jun 12, 2024
879ca35
rebase
teddav Jul 2, 2024
b4205ea
rename cheatcode to broadcastrawtransaction
teddav Jul 2, 2024
af447fc
revert anvil to sendrawtransaction + rename enum to Unsigned
teddav Jul 3, 2024
ad9337a
better TransactionMaybeSigned
klkvr Jul 3, 2024
447e541
fix: ci
klkvr Jul 3, 2024
1c32bde
fixes
klkvr Jul 9, 2024
f8c551b
Merge branch 'master' into feat/sendrawtransaction
klkvr Jul 11, 2024
7ae74c4
review fixes
klkvr Jul 11, 2024
9021acf
add newline
klkvr Jul 11, 2024
426bacc
Update crates/common/src/transactions.rs
zerosnacks Jul 25, 2024
4aeb322
Update crates/script/src/broadcast.rs
zerosnacks Jul 25, 2024
18bd137
Merge remote-tracking branch 'upstream/master' into feat/sendrawtrans…
zerosnacks Jul 25, 2024
24ed29e
revm now uses Alloys AccessList: https://github.com/bluealloy/revm/pu…
zerosnacks Jul 25, 2024
57d24da
Merge branch 'master' into feat/sendrawtransaction
mattsse Jul 26, 2024
3399b06
only broadcast if you can transact, reorder cheatcode to be in broadc…
zerosnacks Jul 26, 2024
023e5ad
update spec
zerosnacks Jul 26, 2024
a228ec3
Merge branch 'master' into feat/sendrawtransaction
zerosnacks Jul 26, 2024
42652dc
fix cheatcode classification
zerosnacks Jul 26, 2024
7de715b
Merge branch 'feat/sendrawtransaction' of github.com:teddav/foundry i…
zerosnacks Jul 26, 2024
b396eb7
fix cheatcodes file
zerosnacks Jul 26, 2024
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 @@ -28,13 +28,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;
zerosnacks marked this conversation as resolved.
Show resolved Hide resolved

// ======== 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),
)?;
zerosnacks marked this conversation as resolved.
Show resolved Hide resolved

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_core::{
abi::Vm::stopExpectSafeMemoryCall,
Expand Down Expand Up @@ -188,12 +188,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 @@ -513,7 +513,8 @@ impl Cheatcodes {
None
},
..Default::default()
},
}
.into(),
});

input.log_debug(self, &input.scheme().unwrap_or(CreateScheme::Create));
Expand Down Expand Up @@ -849,7 +850,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 @@ -41,6 +41,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