Skip to content

Commit

Permalink
rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
teddav committed Jul 2, 2024
1 parent 43ed470 commit 879ca35
Show file tree
Hide file tree
Showing 9 changed files with 9,831 additions and 45 deletions.
9,769 changes: 9,769 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

12 changes: 9 additions & 3 deletions crates/cheatcodes/src/evm.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Implementations of [`Evm`](spec::Group::Evm) cheatcodes.

use crate::{BroadcastableTransaction, 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};
Expand Down Expand Up @@ -570,7 +572,11 @@ impl Cheatcode for stopAndReturnStateDiffCall {
}

impl Cheatcode for sendRawTransactionCall {
fn apply_full<DB: DatabaseExt>(&self, ccx: &mut CheatsCtxt<DB>) -> Result {
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!("sendRawTransaction: error decoding transaction ({err})"))?;
Expand All @@ -586,7 +592,7 @@ impl Cheatcode for sendRawTransactionCall {
tx.into(),
&ccx.ecx.env,
&mut ccx.ecx.journaled_state,
ccx.state,
&mut executor.get_inspector(ccx.state),
)?;

Ok(Default::default())
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

tower.workspace = true

Expand Down
39 changes: 26 additions & 13 deletions crates/common/src/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use alloy_consensus::TxEnvelope;
use alloy_provider::{network::AnyNetwork, Provider};
use alloy_rpc_types::{AnyTransactionReceipt, BlockId, TransactionRequest, WithOtherFields};
use alloy_rpc_types::{AnyTransactionReceipt, BlockId, TransactionRequest};
use alloy_serde::WithOtherFields;
use alloy_transport::Transport;
use eyre::Result;
Expand Down Expand Up @@ -150,23 +150,27 @@ mod tests {
/// Used for broadcasting transactions
/// A transaction can either be a TransactionRequest waiting to be signed
/// or a TxEnvelope, already signed
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TransactionMaybeSigned {
/// if tx is already signed, this is equal to `signed_tx` stripped of its signature
pub tx: TransactionRequest,
/// the signed transaction
pub signed_tx: Option<TxEnvelope>,
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TransactionMaybeSigned {
NotSigned(TransactionRequest),
Signed(TransactionRequest, TxEnvelope),
}

impl Default for TransactionMaybeSigned {
fn default() -> Self {
Self::NotSigned(TransactionRequest::default())
}
}

impl TransactionMaybeSigned {
/// Creates a new (unsigned) transaction for broadcast
pub fn new(tx: TransactionRequest) -> Self {
Self { tx, signed_tx: None }
Self::NotSigned(tx)
}

/// Creates a new signed transaction for broadcast
pub fn new_signed(tx: TxEnvelope) -> Self {
Self { tx: tx.clone().into(), signed_tx: Some(tx) }
Self::Signed(tx.clone().into(), tx)
}
}

Expand All @@ -178,25 +182,34 @@ impl From<TransactionRequest> for TransactionMaybeSigned {

impl From<TxEnvelope> for TransactionMaybeSigned {
fn from(envelope: TxEnvelope) -> Self {
Self { tx: envelope.clone().into(), signed_tx: Some(envelope) }
Self::Signed(envelope.clone().into(), envelope)
}
}

impl From<TransactionMaybeSigned> for TransactionRequest {
fn from(val: TransactionMaybeSigned) -> Self {
val.tx
match val {
TransactionMaybeSigned::NotSigned(tx) => tx,
TransactionMaybeSigned::Signed(tx, _) => tx,
}
}
}

impl Deref for TransactionMaybeSigned {
type Target = TransactionRequest;
fn deref(&self) -> &Self::Target {
&self.tx
match self {
TransactionMaybeSigned::NotSigned(tx) => tx,
TransactionMaybeSigned::Signed(tx, _) => tx,
}
}
}

impl DerefMut for TransactionMaybeSigned {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.tx
match self {
TransactionMaybeSigned::NotSigned(tx) => tx,
TransactionMaybeSigned::Signed(tx, _) => tx,
}
}
}
4 changes: 2 additions & 2 deletions crates/evm/core/src/backend/cow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,12 @@ impl<'a> DatabaseExt for CowBackend<'a> {
self.backend_mut(env).transact(id, transaction, env, journaled_state, inspector)
}

fn transact_from_tx<I: InspectorExt<Backend>>(
fn transact_from_tx(
&mut self,
transaction: TransactionRequest,
env: &Env,
journaled_state: &mut JournaledState,
inspector: &mut I,
inspector: &mut dyn InspectorExt<Backend>,
) -> eyre::Result<()> {
self.backend_mut(env).transact_from_tx(transaction, env, journaled_state, inspector)
}
Expand Down
25 changes: 10 additions & 15 deletions crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use crate::{
InspectorExt,
};
use alloy_genesis::GenesisAccount;
use alloy_primitives::{b256, keccak256, Address, TxKind, B256, U256};
use alloy_primitives::{keccak256, uint, Address, TxKind, B256, U256};
use alloy_rpc_types::{
Block, BlockNumberOrTag, BlockTransactions, Transaction, TransactionRequest, WithOtherFields,
Block, BlockNumberOrTag, BlockTransactions, Transaction, TransactionRequest,
};
use alloy_serde::WithOtherFields;
use eyre::Context;
Expand All @@ -22,7 +22,7 @@ use revm::{
precompile::{PrecompileSpecId, Precompiles},
primitives::{
Account, AccountInfo, Bytecode, Env, EnvWithHandlerCfg, EvmState, EvmStorageSlot,
HashMap as Map, Log, ResultAndState, SpecId, TxKind, KECCAK_EMPTY,
HashMap as Map, Log, ResultAndState, SpecId, KECCAK_EMPTY,
},
Database, DatabaseCommit, JournaledState,
};
Expand Down Expand Up @@ -205,15 +205,13 @@ pub trait DatabaseExt: Database<Error = DatabaseError> + DatabaseCommit {
) -> eyre::Result<()>;

/// Executes a given TransactionRequest, commits the new state to the DB
fn transact_from_tx<I: InspectorExt<Backend>>(
fn transact_from_tx(
&mut self,
transaction: TransactionRequest,
env: &Env,
journaled_state: &mut JournaledState,
inspector: &mut I,
) -> eyre::Result<()>
where
Self: Sized;
inspector: &mut dyn InspectorExt<Backend>,
) -> eyre::Result<()>;

/// Returns the `ForkId` that's currently used in the database, if fork mode is on
fn active_fork_id(&self) -> Option<LocalForkId>;
Expand Down Expand Up @@ -1233,12 +1231,12 @@ impl DatabaseExt for Backend {
)
}

fn transact_from_tx<I: InspectorExt<Self>>(
fn transact_from_tx(
&mut self,
tx: TransactionRequest,
env: &Env,
journaled_state: &mut JournaledState,
inspector: &mut I,
inspector: &mut dyn InspectorExt<Self>,
) -> eyre::Result<()> {
trace!(?tx, "execute signed transaction");

Expand Down Expand Up @@ -1270,11 +1268,8 @@ impl DatabaseExt for Backend {
env.tx.value =
tx.value.ok_or_else(|| eyre::eyre!("transact_from_tx: No `value` field found"))?;
env.tx.data = tx.input.into_input().unwrap_or_default();
env.tx.transact_to = match tx.to {
Some(TxKind::Call(a)) => TransactTo::Call(a),
Some(TxKind::Create) => TransactTo::create(),
None => TransactTo::create(),
};
env.tx.transact_to =
tx.to.ok_or_else(|| eyre::eyre!("transact_from_tx: No `to` field found"))?;
env.tx.chain_id = tx.chain_id;

self.commit(journaled_state.state.clone());
Expand Down
23 changes: 13 additions & 10 deletions crates/script/src/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use alloy_eips::eip2718::Encodable2718;
use alloy_network::{AnyNetwork, EthereumWallet, TransactionBuilder};
use alloy_primitives::{utils::format_units, Address, TxHash};
use alloy_provider::{utils::Eip1559Estimation, Provider};
use alloy_rpc_types::{IntoTransactionRequest, TransactionRequest, WithOtherFields};
use alloy_rpc_types::TransactionRequest;
use alloy_serde::WithOtherFields;
use alloy_transport::Transport;
use eyre::{bail, Context, Result};
Expand Down Expand Up @@ -40,7 +40,7 @@ where
// set in the request and omit the estimate altogether, so we remove it here
tx.gas = None;

let t = tx.clone().into_transaction_request();
let t: WithOtherFields<TransactionRequest> = WithOtherFields::new(tx.inner.clone().into());
tx.set_gas_limit(
provider.estimate_gas(&t).await.wrap_err("Failed to estimate gas for tx")? *
estimate_multiplier as u128 /
Expand Down Expand Up @@ -86,12 +86,16 @@ pub async fn send_transaction(
debug!("sending transaction from unlocked account {:?}: {:?}", addr, tx);

// Submit the transaction
provider.send_transaction(tx.into_transaction_request()).await?
let t: WithOtherFields<TransactionRequest> =
WithOtherFields::new(tx.inner.clone().into());
provider.send_transaction(t).await?
}
SendTransactionKind::Raw(signer) => {
debug!("sending transaction: {:?}", tx);

let signed = tx.into_transaction_request().build(signer).await?;
let t: WithOtherFields<TransactionRequest> =
WithOtherFields::new(tx.inner.clone().into());
let signed = t.build(signer).await?;

// Submit the raw transaction
provider.send_raw_transaction(signed.encoded_2718().as_ref()).await?
Expand All @@ -109,7 +113,7 @@ pub async fn send_transaction(
#[derive(Clone)]
pub enum SendTransactionKind<'a> {
Unlocked(Address),
Raw(&'a EthereumSigner),
Raw(&'a EthereumWallet),
Signed(TxEnvelope),
}

Expand All @@ -118,7 +122,7 @@ pub enum SendTransactionsKind {
/// Send via `eth_sendTransaction` and rely on the `from` address being unlocked.
Unlocked(HashSet<Address>),
/// Send a signed transaction via `eth_sendRawTransaction`
Raw(HashMap<Address, EthereumSigner>, Vec<TxEnvelope>),
Raw(HashMap<Address, EthereumWallet>, Vec<TxEnvelope>),
}

impl SendTransactionsKind {
Expand Down Expand Up @@ -213,12 +217,11 @@ impl BundledState {
.sequences()
.iter()
.flat_map(|sequence| {
sequence.transactions().map(|tx| {
if tx.signed_tx.is_some() {
(None, tx.signed_tx.clone())
} else {
sequence.transactions().map(|tx| match &tx.inner {
TransactionMaybeSigned::NotSigned(tx) => {
(Some(tx.from.expect("No sender for onchain transaction!")), None)
}
TransactionMaybeSigned::Signed(_, signed) => (None, Some(signed.clone())),
})
})
.unzip();
Expand Down
2 changes: 1 addition & 1 deletion crates/script/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
verify::VerifyBundle,
};
use alloy_primitives::{hex, Address, TxHash};
use alloy_rpc_types::{AnyTransactionReceipt, TransactionRequest, WithOtherFields};
use alloy_rpc_types::AnyTransactionReceipt;
use alloy_serde::WithOtherFields;
use eyre::{ContextCompat, Result, WrapErr};
use forge_verify::provider::VerificationProviderType;
Expand Down
1 change: 0 additions & 1 deletion crates/script/src/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::ScriptResult;
use alloy_dyn_abi::JsonAbiExt;
use alloy_primitives::{hex, Address, Bytes, TxKind, B256};
use alloy_rpc_types::request::TransactionRequest;
use alloy_serde::WithOtherFields;
use eyre::{ContextCompat, Result, WrapErr};
use foundry_common::{fmt::format_token_raw, ContractData, TransactionMaybeSigned, SELECTOR_LEN};
Expand Down

0 comments on commit 879ca35

Please sign in to comment.