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: add AnyNetwork #383

Merged
merged 9 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
109 changes: 109 additions & 0 deletions crates/network/src/any/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use std::ops::{Deref, DerefMut};

use alloy_primitives::U256;
use alloy_rpc_types::{other::WithOtherFields, TransactionRequest};

use crate::{ethereum::build_unsigned, BuilderResult, Network, TransactionBuilder};

use super::AnyNetwork;
leruaa marked this conversation as resolved.
Show resolved Hide resolved

impl TransactionBuilder<AnyNetwork> for WithOtherFields<TransactionRequest> {
fn chain_id(&self) -> Option<alloy_primitives::ChainId> {
self.deref().chain_id()
}

fn set_chain_id(&mut self, chain_id: alloy_primitives::ChainId) {
self.deref_mut().set_chain_id(chain_id)
}

fn nonce(&self) -> Option<u64> {
self.deref().nonce()
}

fn set_nonce(&mut self, nonce: u64) {
self.deref_mut().set_nonce(nonce)
}

fn input(&self) -> Option<&alloy_primitives::Bytes> {
self.deref().input()
}

fn set_input(&mut self, input: alloy_primitives::Bytes) {
self.deref_mut().set_input(input);
}

fn from(&self) -> Option<alloy_primitives::Address> {
self.deref().from()
}

fn set_from(&mut self, from: alloy_primitives::Address) {
self.deref_mut().set_from(from);
}

fn to(&self) -> Option<alloy_primitives::TxKind> {
self.deref().to()
}

fn set_to(&mut self, to: alloy_primitives::TxKind) {
self.deref_mut().set_to(to)
}

fn value(&self) -> Option<alloy_primitives::U256> {
self.deref().value()
}

fn set_value(&mut self, value: alloy_primitives::U256) {
self.deref_mut().set_value(value)
}

fn gas_price(&self) -> Option<U256> {
self.deref().gas_price()
}

fn set_gas_price(&mut self, gas_price: U256) {
self.deref_mut().set_gas_price(gas_price);
}

fn max_fee_per_gas(&self) -> Option<U256> {
self.deref().max_fee_per_gas()
}

fn set_max_fee_per_gas(&mut self, max_fee_per_gas: U256) {
self.deref_mut().set_max_fee_per_gas(max_fee_per_gas);
}

fn max_priority_fee_per_gas(&self) -> Option<U256> {
self.deref().max_priority_fee_per_gas()
}

fn set_max_priority_fee_per_gas(&mut self, max_priority_fee_per_gas: U256) {
self.deref_mut().set_max_priority_fee_per_gas(max_priority_fee_per_gas);
}

fn max_fee_per_blob_gas(&self) -> Option<U256> {
self.deref().max_fee_per_blob_gas()
}

fn set_max_fee_per_blob_gas(&mut self, max_fee_per_blob_gas: U256) {
self.deref_mut().set_max_fee_per_blob_gas(max_fee_per_blob_gas)
}

fn gas_limit(&self) -> Option<U256> {
self.deref().gas_limit()
}

fn set_gas_limit(&mut self, gas_limit: U256) {
self.deref_mut().set_gas_limit(gas_limit);
}

fn build_unsigned(self) -> BuilderResult<<AnyNetwork as Network>::UnsignedTx> {
build_unsigned::<AnyNetwork>(self.unwrap())
}

async fn build<S: crate::NetworkSigner<AnyNetwork>>(
self,
signer: &S,
) -> BuilderResult<alloy_consensus::TxEnvelope> {
Ok(signer.sign_transaction(self.build_unsigned()?).await?)
}
}
41 changes: 41 additions & 0 deletions crates/network/src/any/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use alloy_rpc_types::{
other::WithOtherFields, Header, Transaction, TransactionReceipt, TransactionRequest,
};

leruaa marked this conversation as resolved.
Show resolved Hide resolved
use crate::{Network, ReceiptResponse};

mod builder;

/// Types for a catch-all network.
leruaa marked this conversation as resolved.
Show resolved Hide resolved
///
/// Essentially just returns the regular Ethereum types + a catch all field.
/// This [`Network`] should be used only when the network is not known at
/// compile time.
#[derive(Debug, Clone, Copy)]
pub struct AnyNetwork {
_private: (),
}

impl Network for AnyNetwork {
type TxEnvelope = alloy_consensus::TxEnvelope;

type UnsignedTx = alloy_consensus::TypedTransaction;

type ReceiptEnvelope = alloy_consensus::ReceiptEnvelope;

type Header = alloy_consensus::Header;

type TransactionRequest = WithOtherFields<TransactionRequest>;

type TransactionResponse = WithOtherFields<Transaction>;

type ReceiptResponse = WithOtherFields<TransactionReceipt>;

type HeaderResponse = WithOtherFields<Header>;
}

impl ReceiptResponse for WithOtherFields<TransactionReceipt> {
fn contract_address(&self) -> Option<alloy_primitives::Address> {
self.contract_address
}
}
63 changes: 36 additions & 27 deletions crates/network/src/ethereum/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@ impl TransactionBuilder<Ethereum> for alloy_rpc_types::TransactionRequest {
self.input.input = Some(input);
}

fn to(&self) -> Option<alloy_primitives::TxKind> {
self.to.map(TxKind::Call).or(Some(TxKind::Create))
}

fn from(&self) -> Option<Address> {
self.from
}
Expand All @@ -42,6 +38,10 @@ impl TransactionBuilder<Ethereum> for alloy_rpc_types::TransactionRequest {
self.from = Some(from);
}

fn to(&self) -> Option<alloy_primitives::TxKind> {
self.to.map(TxKind::Call).or(Some(TxKind::Create))
}

fn set_to(&mut self, to: alloy_primitives::TxKind) {
match to {
TxKind::Create => self.to = None,
Expand Down Expand Up @@ -98,29 +98,7 @@ impl TransactionBuilder<Ethereum> for alloy_rpc_types::TransactionRequest {
}

fn build_unsigned(self) -> BuilderResult<<Ethereum as Network>::UnsignedTx> {
match (
self.gas_price.as_ref(),
self.max_fee_per_gas.as_ref(),
self.access_list.as_ref(),
self.max_fee_per_blob_gas.as_ref(),
self.blob_versioned_hashes.as_ref(),
self.sidecar.as_ref(),
) {
// Legacy transaction
(Some(_), None, None, None, None, None) => build_legacy(self).map(Into::into),
// EIP-2930
// If only accesslist is set, and there are no EIP-1559 fees
(_, None, Some(_), None, None, None) => build_2930(self).map(Into::into),
// EIP-1559
// If EIP-4844 fields are missing
(None, _, _, None, None, None) => build_1559(self).map(Into::into),
// EIP-4844
// All blob fields required
(None, _, _, Some(_), Some(_), Some(_)) => {
build_4844(self).map(TxEip4844Variant::from).map(Into::into)
}
_ => build_legacy(self).map(Into::into),
}
build_unsigned::<Ethereum>(self)
}

async fn build<S: NetworkSigner<Ethereum>>(
Expand All @@ -131,6 +109,37 @@ impl TransactionBuilder<Ethereum> for alloy_rpc_types::TransactionRequest {
}
}

/// Build an unsigned transaction
pub(crate) fn build_unsigned<N>(request: TransactionRequest) -> BuilderResult<N::UnsignedTx>
where
N: Network,
N::UnsignedTx: From<TxLegacy> + From<TxEip1559> + From<TxEip2930> + From<TxEip4844Variant>,
{
match (
request.gas_price.as_ref(),
request.max_fee_per_gas.as_ref(),
request.access_list.as_ref(),
request.max_fee_per_blob_gas.as_ref(),
request.blob_versioned_hashes.as_ref(),
request.sidecar.as_ref(),
) {
// Legacy transaction
(Some(_), None, None, None, None, None) => build_legacy(request).map(Into::into),
leruaa marked this conversation as resolved.
Show resolved Hide resolved
// EIP-2930
// If only accesslist is set, and there are no EIP-1559 fees
(_, None, Some(_), None, None, None) => build_2930(request).map(Into::into),
// EIP-1559
// If EIP-4844 fields are missing
(None, _, _, None, None, None) => build_1559(request).map(Into::into),
// EIP-4844
// All blob fields required
(None, _, _, Some(_), Some(_), Some(_)) => {
build_4844(request).map(TxEip4844Variant::from).map(Into::into)
}
_ => build_legacy(request).map(Into::into),
}
}

/// Build a legacy transaction.
fn build_legacy(request: TransactionRequest) -> Result<TxLegacy, TransactionBuilderError> {
Ok(TxLegacy {
Expand Down
1 change: 1 addition & 0 deletions crates/network/src/ethereum/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{Network, ReceiptResponse};

mod builder;
pub(crate) use builder::build_unsigned;

mod signer;
pub use signer::EthereumSigner;
Expand Down
3 changes: 3 additions & 0 deletions crates/network/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ pub use transaction::{
mod ethereum;
pub use ethereum::{Ethereum, EthereumSigner};

mod any;
pub use any::AnyNetwork;

pub use alloy_eips::eip2718;

/// A list of transactions, either hydrated or hashes.
Expand Down
43 changes: 43 additions & 0 deletions crates/rpc-types/src/eth/other.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,46 @@ impl<'a> IntoIterator for &'a OtherFields {
self.as_ref().iter()
}
}

leruaa marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Wrapper allowing to catch all fields missing on the inner struct while
/// deserialize.
leruaa marked this conversation as resolved.
Show resolved Hide resolved
pub struct WithOtherFields<T> {
#[serde(flatten)]
inner: T,
/// All fields not present in the inner struct.
#[serde(flatten)]
pub other: OtherFields,
}

impl<T> WithOtherFields<T> {
/// Create a new `Extra`.
pub fn new(inner: T) -> Self {
Self { inner, other: OtherFields::default() }
}

/// Unwrap the inner struct.
pub fn unwrap(self) -> T {
self.inner
}
}

impl<T> Deref for WithOtherFields<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.inner
}
}

impl<T> DerefMut for WithOtherFields<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}

impl<T: Default> Default for WithOtherFields<T> {
fn default() -> Self {
WithOtherFields::new(T::default())
}
}
1 change: 0 additions & 1 deletion crates/rpc-types/src/eth/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ impl Transaction {
max_fee_per_blob_gas: self.max_fee_per_blob_gas,
blob_versioned_hashes: Some(self.blob_versioned_hashes),
sidecar: None,
other: OtherFields::default(),
}
}
}
Expand Down
5 changes: 1 addition & 4 deletions crates/rpc-types/src/eth/transaction/receipt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{other::OtherFields, Log};
use crate::Log;
use alloy_primitives::{Address, Bloom, B256, U128, U256, U64, U8};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -53,9 +53,6 @@ pub struct TransactionReceipt {
/// For legacy transactions this returns `0`. For EIP-2718 transactions this returns the type.
#[serde(rename = "type")]
pub transaction_type: U8,
/// Arbitrary extra fields.
#[serde(flatten)]
pub other: OtherFields,
}

impl TransactionReceipt {
Expand Down
15 changes: 4 additions & 11 deletions crates/rpc-types/src/eth/transaction/request.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//! Alloy basic Transaction Request type.

use crate::{
eth::transaction::AccessList, other::OtherFields, BlobTransactionSidecar, Transaction,
};
use crate::{eth::transaction::AccessList, BlobTransactionSidecar, Transaction};
use alloy_primitives::{Address, Bytes, ChainId, B256, U256, U8};
use serde::{Deserialize, Serialize};
use std::hash::Hash;
Expand Down Expand Up @@ -52,9 +50,6 @@ pub struct TransactionRequest {
/// Blob sidecar for EIP-4844 transactions.
#[serde(skip_serializing_if = "Option::is_none")]
pub sidecar: Option<BlobTransactionSidecar>,
/// Support for arbitrary additional fields.
#[serde(flatten)]
pub other: OtherFields,
}

impl Hash for TransactionRequest {
Expand All @@ -74,10 +69,6 @@ impl Hash for TransactionRequest {
self.transaction_type.hash(state);
self.blob_versioned_hashes.hash(state);
self.sidecar.hash(state);
for (k, v) in self.other.iter() {
k.hash(state);
v.to_string().hash(state);
}
}
}

Expand Down Expand Up @@ -255,6 +246,8 @@ pub struct TransactionInputError;

#[cfg(test)]
mod tests {
use crate::other::WithOtherFields;

leruaa marked this conversation as resolved.
Show resolved Hide resolved
use super::*;
use alloy_primitives::b256;

Expand Down Expand Up @@ -294,7 +287,7 @@ mod tests {
#[test]
fn serde_tx_request_additional_fields() {
let s = r#"{"accessList":[],"data":"0x0902f1ac","to":"0xa478c2975ab1ea89e8196811f51a7b7ade33eb11","type":"0x02","sourceHash":"0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a"}"#;
let req = serde_json::from_str::<TransactionRequest>(s).unwrap();
let req = serde_json::from_str::<WithOtherFields<TransactionRequest>>(s).unwrap();
assert_eq!(
req.other.get_deserialized::<B256>("sourceHash").unwrap().unwrap(),
b256!("bf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a")
Expand Down
Loading