Skip to content

Commit

Permalink
feat(test): add new process for different AccountId
Browse files Browse the repository at this point in the history
  • Loading branch information
wd30130 committed Jul 25, 2024
1 parent a0b40eb commit 56324f6
Show file tree
Hide file tree
Showing 9 changed files with 246 additions and 23 deletions.
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,9 @@ pallet-evm-precompile-simple = { git = "https://github.com/paritytech/frontier",
# ink
ink_env = { git = "https://github.com/paritytech/ink" }

# hybrid vm
hp-system = { path = "primitives/system", default-features = false }
pallet-hybrid-vm = { path = "frame/hybrid-vm", default-features = false }
pallet-hybrid-vm-port = { path = "frame/hybrid-vm-port", default-features = false }
pallet-evm-precompile-call-hybrid-vm = { path = "frame/evm-precompile/call-hybrid-vm" }

6 changes: 3 additions & 3 deletions frame/evm-precompile/call-hybrid-vm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pallet-evm-precompile-call-hybrid-vm"
version = "0.1.0"
version = "0.3.0"
description = "Call Hybrid vm precompiles for EVM pallet."
repository.workspace = true
edition.workspace = true
Expand All @@ -24,8 +24,8 @@ frame-system = { workspace = true, default-features = false}
pallet-evm = { workspace = true, default-features = false}
fp-evm = { workspace = true, default-features = false}

hp-system = { version = "0.1.0", path = "../../../primitives/system", default-features = false }
pallet-hybrid-vm = { version = "0.2.0", path = "../../hybrid-vm", default-features = false }
hp-system = { workspace = true, default-features = false }
pallet-hybrid-vm = { workspace = true, default-features = false }

[dev-dependencies]
frame-system = { workspace = true, default-features = false}
Expand Down
11 changes: 7 additions & 4 deletions frame/hybrid-vm-port/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pallet-hybrid-vm-port"
version = "0.2.0-dev"
version = "0.3.0"
license = "Apache-2.0"
description = "HybridVM port pallet for HybridVM."
edition = { workspace = true }
Expand All @@ -20,7 +20,7 @@ frame-support = { workspace = true }
frame-system = { workspace = true }
sp-io = { workspace = true }
sp-runtime = { workspace = true }
pallet-contracts = { workspace = true, default-features = false}
pallet-contracts = { workspace = true, default-features = false }
# Frontier
fp-consensus = { workspace = true }
fp-ethereum = { workspace = true }
Expand All @@ -31,17 +31,20 @@ pallet-evm = { workspace = true }
# ink!
ink_env = { workspace = true }
#local
pallet-hybrid-vm = { path = "../hybrid-vm" }
hp-system = { path = "../../primitives/system" }
pallet-hybrid-vm = { workspace = true, default-features = false }
hp-system = { workspace = true, default-features = false }

[dev-dependencies]
byte-slice-cast= { workspace = true }
hex = { workspace = true }
libsecp256k1 = { workspace = true, features = ["static-context", "hmac"] }
rlp = { workspace = true }
# Substrate
pallet-balances = { workspace = true, features = ["default", "insecure_zero_ed"] }
pallet-insecure-randomness-collective-flip = { workspace = true, default-features = false}
pallet-timestamp = { workspace = true, features = ["default"] }
sp-core = { workspace = true, features = ["default"] }
sp-std = { workspace = true, features = ["default"] }
# Frontier
fp-self-contained = { workspace = true, features = ["default"] }

Expand Down
4 changes: 2 additions & 2 deletions frame/hybrid-vm-port/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,8 +684,8 @@ impl<T: Config> Pallet<T> {
let balance_result =
<T as pallet_hybrid_vm::Config>::U256BalanceMapping::u256_to_balance(value);
let balance = match balance_result {
Some(t) => t,
None => {
Ok(t) => t,
Err(_) => {
return Err(DispatchErrorWithPostInfo {
post_info: PostDispatchInfo {
actual_weight: None,
Expand Down
192 changes: 188 additions & 4 deletions frame/hybrid-vm-port/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,45 @@ use frame_support::{
weights::Weight,
ConsensusEngineId, PalletId,
};
use sp_core::{hashing::keccak_256, H160, H256, U256};
use sp_core::crypto::UncheckedFrom;
use sp_core::{hashing::keccak_256, ConstBool, H160, H256, U256};

use sp_runtime::{
traits::{BlakeTwo256, Dispatchable, IdentityLookup},
AccountId32, BuildStorage,
traits::{BlakeTwo256, Convert, Dispatchable, IdentityLookup},
AccountId32, BuildStorage, Perbill,
};
// Frontier
use pallet_evm::{AddressMapping, EnsureAddressTruncated, FeeCalculator};
use pallet_evm::{AddressMapping, BalanceOf, EnsureAddressTruncated, FeeCalculator};

// Contracts
use pallet_contracts::chain_extension::{Environment, Ext, InitState, RetVal};

// HybridVM
use byte_slice_cast::AsByteSlice;
use hp_system::{AccountId32Mapping, AccountIdMapping, U256BalanceMapping};

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

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

type Balance = u64;

frame_support::construct_runtime! {
pub enum Test {
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Timestamp: pallet_timestamp::{Pallet, Call, Storage},
EVM: pallet_evm::{Pallet, Call, Storage, Config<T>, Event<T>},
Ethereum: crate::{Pallet, Call, Storage, Event, Origin},
Randomness: pallet_insecure_randomness_collective_flip::{Pallet, Storage},
Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>, HoldReason},
HybridVM: pallet_hybrid_vm::{Pallet, Call, Storage, Event<T>},
}
}

impl pallet_insecure_randomness_collective_flip::Config for Test {}

parameter_types! {
pub const BlockHashCount: u64 = 250;
}
Expand Down Expand Up @@ -182,6 +198,174 @@ impl pallet_evm::Config for Test {
type WeightInfo = ();
}

impl Convert<Weight, BalanceOf<Self>> for Test {
fn convert(w: Weight) -> BalanceOf<Self> {
w.ref_time().into()
}
}

#[derive(Default)]
pub struct HybridVMChainExtension;

impl pallet_contracts::chain_extension::ChainExtension<Test> for HybridVMChainExtension {
fn call<E>(&mut self, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>
where
E: Ext<T = Test>,
<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
let func_id = env.func_id();
match func_id {
5 => HybridVM::call_evm::<E>(env),
_ => Err(DispatchError::from("Passed unknown func_id to chain extension")),
}
}
}

pub enum AllowBalancesCall {}

impl frame_support::traits::Contains<RuntimeCall> for AllowBalancesCall {
fn contains(call: &RuntimeCall) -> bool {
matches!(call, RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }))
}
}

// Unit = the base number of indivisible units for balances
const UNIT: Balance = 1_000_000_000_000;
const MILLIUNIT: Balance = 1_000_000_000;

const fn deposit(items: u32, bytes: u32) -> Balance {
(items as Balance * UNIT + (bytes as Balance) * (5 * MILLIUNIT / 100)) / 10
}

fn schedule<T: pallet_contracts::Config>() -> pallet_contracts::Schedule<T> {
pallet_contracts::Schedule {
limits: pallet_contracts::Limits {
runtime_memory: 1024 * 1024 * 1024,
..Default::default()
},
..Default::default()
}
}

parameter_types! {
pub static UploadAccount: Option<<Test as frame_system::Config>::AccountId> = None;
pub static InstantiateAccount: Option<<Test as frame_system::Config>::AccountId> = None;
}

pub struct EnsureAccount<T, A>(sp_std::marker::PhantomData<(T, A)>);
impl<T: Config, A: sp_core::Get<Option<AccountId32>>>
EnsureOrigin<<T as frame_system::Config>::RuntimeOrigin> for EnsureAccount<T, A>
where
<T as frame_system::Config>::AccountId: From<AccountId32>,
{
type Success = T::AccountId;

fn try_origin(o: T::RuntimeOrigin) -> Result<Self::Success, T::RuntimeOrigin> {
let who = <frame_system::EnsureSigned<_> as EnsureOrigin<_>>::try_origin(o.clone())?;
if matches!(A::get(), Some(a) if who != a.clone().into()) {
return Err(o);
}

Ok(who)
}

#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<T::RuntimeOrigin, ()> {
Err(())
}
}

parameter_types! {
pub const DepositPerItem: u64 = deposit(1, 0) as u64;
pub const DepositPerByte: u64 = deposit(0, 1) as u64;
pub Schedule: pallet_contracts::Schedule<Test> = schedule::<Test>();
pub const DefaultDepositLimit: u64 = deposit(1024, 1024 * 1024) as u64;
pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
pub const MaxDelegateDependencies: u32 = 32;
}

#[derive_impl(pallet_contracts::config_preludes::TestDefaultConfig)]
impl pallet_contracts::Config for Test {
type Time = Timestamp;
type Randomness = Randomness;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type CallFilter = AllowBalancesCall;
type DepositPerItem = DepositPerItem;
type DepositPerByte = DepositPerByte;
type CallStack = [pallet_contracts::Frame<Self>; 23];
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = HybridVMChainExtension;
type Schedule = Schedule;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type MaxCodeLen = ConstU32<{ 128 * 1024 }>;
type DefaultDepositLimit = DefaultDepositLimit;
type MaxStorageKeyLen = ConstU32<128>;
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
type UnsafeUnstableInterface = ConstBool<false>;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type MaxDelegateDependencies = MaxDelegateDependencies;
type RuntimeHoldReason = RuntimeHoldReason;
type UploadOrigin = EnsureAccount<Self, UploadAccount>;
type InstantiateOrigin = EnsureAccount<Self, InstantiateAccount>;
type Environment = ();
type Debug = ();
type Migrations = ();
type Xcm = ();
}

pub struct GasPrice;
impl Get<Option<U256>> for GasPrice {
fn get() -> Option<U256> {
Some(U256::from(100_000_000_000u64))
}
}

parameter_types! {
pub const EnableCallEVM: bool = true;
pub const EnableCallWasmVM: bool = true;
pub const GasLimit: u64 = 10_000_000u64;
}

impl U256BalanceMapping for Test {
type Balance = u64;
fn u256_to_balance(value: U256) -> Result<Self::Balance, &'static str> {
Balance::try_from(value)
}
}

impl AccountIdMapping<Test> for Test {
fn into_address(account_id: <Test as frame_system::Config>::AccountId) -> H160 {
let mut address_arr = [0u8; 32];
address_arr[0..32].copy_from_slice(account_id.as_byte_slice());

H160::from_slice(&address_arr[0..20])
}
}

impl AccountId32Mapping<Test> for Test {
fn id32_to_id(id32: AccountId32) -> <Test as frame_system::Config>::AccountId {
id32.into()
}

fn id_to_id32(account_id: <Test as frame_system::Config>::AccountId) -> AccountId32 {
account_id.into()
}
}

impl pallet_hybrid_vm::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type U256BalanceMapping = Self;
type AccountIdMapping = Self;
type AccountId32Mapping = Self;
type EnableCallEVM = EnableCallEVM;
type EnableCallWasmVM = EnableCallWasmVM;
type GasLimit = GasLimit;
type GasPrice = GasPrice;
}

parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}
Expand Down
8 changes: 4 additions & 4 deletions frame/hybrid-vm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pallet-hybrid-vm"
version = "0.2.0"
version = "0.3.0"
description = "Engine for Hybrid vm"
repository.workspace = true
edition.workspace = true
Expand Down Expand Up @@ -36,8 +36,8 @@ pallet-contracts = { workspace = true, default-features = false}
pallet-evm = { workspace = true, default-features = false}
fp-evm = { workspace = true, default-features = false}

# local
hp-system = { version = "0.1.0", path = "../../primitives/system" }
# hybrid vm
hp-system = { workspace = true, default-features = false }

[dev-dependencies]
assert_matches = { workspace = true }
Expand All @@ -55,7 +55,7 @@ pallet-evm-precompile-simple = { workspace = true, default-features = false}

ink_env = { workspace = true }

pallet-evm-precompile-call-hybrid-vm = { version = "0.1.0", path = "../evm-precompile/call-hybrid-vm" }
pallet-evm-precompile-call-hybrid-vm = { workspace = true }

[features]
default = ["std"]
Expand Down
Loading

0 comments on commit 56324f6

Please sign in to comment.