Skip to content

Commit

Permalink
Add TestDefaultConfig to pallet-evm & pallet-ethereum (#1524)
Browse files Browse the repository at this point in the history
* feat: Implement TestDefaultConfig for pallet-evm

* feat: Implement TestDefaultConfig for pallet-ethereum

* style: Reformat

* Extend to the ethereum pallet

* chore: Align ChainId in TestDefaultConfig with template runtime

* chore: Clean up imports

* test: Fix broken pallet-ethereum tests

* chore: Fix clippy error

* chore: Fix clippy error (2)

---------

Co-authored-by: bear <[email protected]>
  • Loading branch information
conr2d and boundless-forest authored Oct 22, 2024
1 parent 5a24856 commit 18aa99b
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 219 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions frame/ethereum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ frame-support = { workspace = true }
frame-system = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }
sp-version = { workspace = true }
# Frontier
fp-consensus = { workspace = true }
fp-ethereum = { workspace = true }
Expand Down Expand Up @@ -54,6 +55,7 @@ std = [
"frame-system/std",
"sp-io/std",
"sp-runtime/std",
"sp-version/std",
# Frontier
"fp-consensus/std",
"fp-ethereum/std",
Expand Down
34 changes: 31 additions & 3 deletions frame/ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ use sp_runtime::{
},
RuntimeDebug, SaturatedConversion,
};
use sp_version::RuntimeVersion;
// Frontier
use fp_consensus::{PostLog, PreLog, FRONTIER_ENGINE_ID};
pub use fp_ethereum::TransactionData;
Expand Down Expand Up @@ -192,9 +193,10 @@ pub mod pallet {
#[pallet::origin]
pub type Origin = RawOrigin;

#[pallet::config]
#[pallet::config(with_default)]
pub trait Config: frame_system::Config + pallet_evm::Config {
/// The overarching event type.
#[pallet::no_default_bounds]
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// How Ethereum state root is calculated.
type StateRoot: Get<H256>;
Expand All @@ -204,6 +206,32 @@ pub mod pallet {
type ExtraDataLength: Get<u32>;
}

pub mod config_preludes {
use super::*;
use frame_support::{derive_impl, parameter_types};

pub struct TestDefaultConfig;

#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
impl frame_system::DefaultConfig for TestDefaultConfig {}

#[derive_impl(pallet_evm::config_preludes::TestDefaultConfig, no_aggregated_types)]
impl pallet_evm::DefaultConfig for TestDefaultConfig {}

parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}

#[register_default_impl(TestDefaultConfig)]
impl DefaultConfig for TestDefaultConfig {
#[inject_runtime_type]
type RuntimeEvent = ();
type StateRoot = IntermediateStateRoot<Self::Version>;
type PostLogContent = PostBlockAndTxnHashes;
type ExtraDataLength = ConstU32<30>;
}
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_finalize(n: BlockNumberFor<T>) {
Expand Down Expand Up @@ -968,9 +996,9 @@ pub enum ReturnValue {
}

pub struct IntermediateStateRoot<T>(PhantomData<T>);
impl<T: Config> Get<H256> for IntermediateStateRoot<T> {
impl<T: Get<RuntimeVersion>> Get<H256> for IntermediateStateRoot<T> {
fn get() -> H256 {
let version = T::Version::get().state_version();
let version = T::get().state_version();
H256::decode(&mut &sp_io::storage::root(version)[..])
.expect("Node is configured to use the same hash; qed")
}
Expand Down
116 changes: 10 additions & 106 deletions frame/ethereum/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,16 @@
use ethereum::{TransactionAction, TransactionSignature};
use rlp::RlpStream;
// Substrate
use frame_support::{
derive_impl, parameter_types,
traits::{ConstU32, FindAuthor},
weights::Weight,
ConsensusEngineId, PalletId,
};
use frame_support::{derive_impl, parameter_types, traits::FindAuthor, ConsensusEngineId};
use sp_core::{hashing::keccak_256, H160, H256, U256};
use sp_runtime::{
traits::{BlakeTwo256, Dispatchable, IdentityLookup},
traits::{Dispatchable, IdentityLookup},
AccountId32, BuildStorage,
};
// Frontier
use pallet_evm::{AddressMapping, EnsureAddressTruncated, FeeCalculator};
use pallet_evm::{config_preludes::ChainId, AddressMapping};

use super::*;
use crate::IntermediateStateRoot;

pub type SignedExtra = (frame_system::CheckSpecVersion<Test>,);

Expand All @@ -55,30 +49,11 @@ parameter_types! {

#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Test {
type RuntimeEvent = RuntimeEvent;
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type RuntimeTask = RuntimeTask;
type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId32;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = frame_system::mocking::MockBlock<Self>;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
}

parameter_types! {
Expand All @@ -89,39 +64,14 @@ parameter_types! {
pub const MaxReserves: u32 = 50;
}

#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
type WeightInfo = ();
type Balance = u64;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type ReserveIdentifier = [u8; 8];
type FreezeIdentifier = RuntimeFreezeReason;
type MaxLocks = MaxLocks;
type MaxReserves = MaxReserves;
type MaxFreezes = ConstU32<1>;
}

parameter_types! {
pub const MinimumPeriod: u64 = 6000 / 2;
}

impl pallet_timestamp::Config for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
type WeightInfo = ();
}

pub struct FixedGasPrice;
impl FeeCalculator for FixedGasPrice {
fn min_gas_price() -> (U256, Weight) {
(1.into(), Weight::zero())
}
}
#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
impl pallet_timestamp::Config for Test {}

pub struct FindAuthorTruncated;
impl FindAuthor<H160> for FindAuthorTruncated {
Expand All @@ -133,66 +83,24 @@ impl FindAuthor<H160> for FindAuthorTruncated {
}
}

const BLOCK_GAS_LIMIT: u64 = 150_000_000;
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;

parameter_types! {
pub const TransactionByteFee: u64 = 1;
pub const ChainId: u64 = 42;
pub const EVMModuleId: PalletId = PalletId(*b"py/evmpa");
pub BlockGasLimit: U256 = U256::from(BLOCK_GAS_LIMIT);
pub const GasLimitPovSizeRatio: u64 = BLOCK_GAS_LIMIT.saturating_div(MAX_POV_SIZE);
pub const WeightPerGas: Weight = Weight::from_parts(20_000, 0);
}

pub struct HashedAddressMapping;
impl AddressMapping<AccountId32> for HashedAddressMapping {
fn into_account_id(address: H160) -> AccountId32 {
let mut data = [0u8; 32];
data[0..20].copy_from_slice(&address[..]);
AccountId32::from(Into::<[u8; 32]>::into(data))
}
}

parameter_types! {
pub SuicideQuickClearLimit: u32 = 0;
}

#[derive_impl(pallet_evm::config_preludes::TestDefaultConfig)]
impl pallet_evm::Config for Test {
type AccountProvider = pallet_evm::FrameSystemAccountProvider<Self>;
type FeeCalculator = FixedGasPrice;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = crate::EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAddressTruncated;
type WithdrawOrigin = EnsureAddressTruncated;
type AddressMapping = HashedAddressMapping;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type PrecompilesType = ();
type PrecompilesValue = ();
type ChainId = ChainId;
type BlockGasLimit = BlockGasLimit;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type OnChargeTransaction = ();
type OnCreate = ();
type FindAuthor = FindAuthorTruncated;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type SuicideQuickClearLimit = SuicideQuickClearLimit;
type Timestamp = Timestamp;
type WeightInfo = ();
}

parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}

impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type StateRoot = IntermediateStateRoot<Self>;
type PostLogContent = PostBlockAndTxnHashes;
type ExtraDataLength = ConstU32<30>;
}
#[derive_impl(crate::config_preludes::TestDefaultConfig)]
impl Config for Test {}

impl fp_self_contained::SelfContainedCall for RuntimeCall {
type SignedInfo = H160;
Expand Down Expand Up @@ -262,12 +170,9 @@ fn address_build(seed: u8) -> AccountInfo {
let public_key = &libsecp256k1::PublicKey::from_secret_key(&secret_key).serialize()[1..65];
let address = H160::from(H256::from(keccak_256(public_key)));

let mut data = [0u8; 32];
data[0..20].copy_from_slice(&address[..]);

AccountInfo {
private_key,
account_id: AccountId32::from(Into::<[u8; 32]>::into(data)),
account_id: <Test as pallet_evm::Config>::AddressMapping::into_account_id(address),
address,
}
}
Expand Down Expand Up @@ -301,7 +206,6 @@ pub fn new_test_ext_with_initial_balance(
accounts_len: usize,
initial_balance: u64,
) -> (Vec<AccountInfo>, sp_io::TestExternalities) {
// sc_cli::init_logger("");
let mut ext = frame_system::GenesisConfig::<Test>::default()
.build_storage()
.unwrap();
Expand Down
Loading

0 comments on commit 18aa99b

Please sign in to comment.