Skip to content

Commit

Permalink
fix: tests (#358)
Browse files Browse the repository at this point in the history
  • Loading branch information
evilrobot-01 authored Oct 25, 2024
1 parent a2b653d commit a8c024c
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 139 deletions.
8 changes: 4 additions & 4 deletions extension/src/environment.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use core::fmt::Debug;

use codec::{Decode, Encode};
use codec::Decode;
use frame_support::pallet_prelude::Weight;
use pallet_revive::{
chain_extension::{ChargedAmount, Result},
wasm::Memory,
AccountId32Mapper, AddressMapper,
};
use sp_core::{crypto::AccountId32, H160};
use sp_core::crypto::AccountId32;
use sp_std::vec::Vec;

use crate::{AccountIdOf, Config};
use crate::AccountIdOf;

/// Provides access to the parameters passed to a chain extension and its execution environment.
///
Expand Down Expand Up @@ -219,5 +219,5 @@ where

#[test]
fn default_ext_works() {
assert_eq!(().address(), &())
assert_eq!(().address(), ())
}
46 changes: 24 additions & 22 deletions extension/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,29 +369,31 @@ mod tests {
}

#[test]
#[ignore]
fn dispatch_call_adjusts_weight() {
let migrate_weight = <Test as pallet_revive::Config>::WeightInfo::migrate();
let migration_noop_weight =
<Test as pallet_revive::Config>::WeightInfo::migration_noop();
new_test_ext().execute_with(|| {
// Attempt to perform non-existent migration with additional weight limit specified.
let extra_weight = Weight::from_parts(123456789, 12345);
let weight_limit = migration_noop_weight.saturating_add(extra_weight);
let call = RuntimeCall::Contracts(pallet_revive::Call::migrate { weight_limit });
let encoded_call = call.encode();
let mut env = MockEnvironment::new(FuncId::get(), encoded_call.clone());
let expected: DispatchError =
pallet_revive::Error::<Test>::NoMigrationPerformed.into();
assert_eq!(DispatchCall::execute(&mut env).err().unwrap(), expected);
// Ensure pre-dispatch weight is weight function + weight limit
assert_eq!(call.get_dispatch_info().weight, migrate_weight + weight_limit);
assert_eq!(
env.charged(),
read_from_buffer_weight(encoded_call.len() as u32) +
call.get_dispatch_info().weight -
extra_weight
);
})
todo!("restore the below on revive")
// let migrate_weight = <Test as pallet_revive::Config>::WeightInfo::migrate();
// let migration_noop_weight =
// <Test as pallet_revive::Config>::WeightInfo::migration_noop();
// new_test_ext().execute_with(|| {
// // Attempt to perform non-existent migration with additional weight limit specified.
// let extra_weight = Weight::from_parts(123456789, 12345);
// let weight_limit = migration_noop_weight.saturating_add(extra_weight);
// let call = RuntimeCall::Contracts(pallet_revive::Call::migrate { weight_limit });
// let encoded_call = call.encode();
// let mut env = MockEnvironment::new(FuncId::get(), encoded_call.clone());
// let expected: DispatchError =
// pallet_revive::Error::<Test>::NoMigrationPerformed.into();
// assert_eq!(DispatchCall::execute(&mut env).err().unwrap(), expected);
// // Ensure pre-dispatch weight is weight function + weight limit
// assert_eq!(call.get_dispatch_info().weight, migrate_weight + weight_limit);
// assert_eq!(
// env.charged(),
// read_from_buffer_weight(encoded_call.len() as u32) +
// call.get_dispatch_info().weight -
// extra_weight
// );
// })
}

#[test]
Expand Down
91 changes: 51 additions & 40 deletions extension/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@ use std::marker::PhantomData;
use codec::{Decode, Encode};
use frame_support::{
derive_impl,
pallet_prelude::Weight,
pallet_prelude::{ConstU32, Weight},
parameter_types,
traits::{fungible::Inspect, ConstU32, Everything, Nothing},
traits::{fungible::Inspect, EnsureOrigin, Everything, Nothing},
};
use frame_system::{pallet_prelude::BlockNumberFor, EnsureSigned};
use pallet_revive::{chain_extension::RetVal, DefaultAddressGenerator, Frame, Schedule};
use sp_runtime::{BuildStorage, DispatchError, Perbill};
use frame_system::pallet_prelude::BlockNumberFor;
use pallet_revive::{chain_extension::RetVal, AccountId32Mapper};
use sp_core::crypto::AccountId32;
use sp_runtime::{traits::IdentityLookup, BuildStorage, DispatchError, Perbill};

use crate::{
decoding::Identity, environment, matching::WithFuncId, AccountIdOf, ContractWeightsOf,
Converter, Decodes, DecodingFailed, DefaultConverter, DispatchCall, Extension, Function,
Matches, Processor, ReadState, Readable,
};

pub(crate) const ALICE: u64 = 1;
pub(crate) const ALICE: AccountId32 = AccountId32::new([1u8; 32]);
pub(crate) const DEBUG_OUTPUT: pallet_revive::DebugInfo = pallet_revive::DebugInfo::UnsafeDebug;
pub(crate) const GAS_LIMIT: Weight = Weight::from_parts(500_000_000_000, 3 * 1024 * 1024);
pub(crate) const INIT_AMOUNT: <Test as pallet_balances::Config>::Balance = 100_000_000;
Expand Down Expand Up @@ -67,8 +68,9 @@ frame_support::construct_runtime!(
#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Test {
type AccountData = pallet_balances::AccountData<u64>;
type AccountId = u64;
type AccountId = AccountId32;
type Block = frame_system::mocking::MockBlock<Test>;
type Lookup = IdentityLookup<Self::AccountId>;
}

#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)]
Expand All @@ -80,54 +82,36 @@ impl pallet_balances::Config for Test {
#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig as pallet_timestamp::DefaultConfig)]
impl pallet_timestamp::Config for Test {}

#[derive_impl(pallet_revive::config_preludes::TestDefaultConfig as pallet_revive::DefaultConfig)]
impl pallet_revive::Config for Test {
type AddressGenerator = DefaultAddressGenerator;
type ApiVersion = ();
type AddressMapper = AccountId32Mapper<Self>;
type CallFilter = ();
// TestFilter;
type CallStack = [Frame<Self>; 5];
type ChainExtension = Extension<Config>;
type ChainId = ChainId;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type Currency = Balances;
type Debug = ();
// TestDebug;
type DefaultDepositLimit = DefaultDepositLimit;
type DepositPerByte = DepositPerByte;
type DepositPerItem = DepositPerItem;
type Environment = ();
type InstantiateOrigin = EnsureSigned<Self::AccountId>;
type MaxCodeLen = ConstU32<{ 100 * 1024 }>;
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
type MaxDelegateDependencies = MaxDelegateDependencies;
type MaxStorageKeyLen = ConstU32<128>;
type Migrations = ();
// crate::migration::codegen::BenchMigrations;
type Randomness = Test;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type Schedule = MySchedule;
type InstantiateOrigin = EnsureAccount<Self, InstantiateAccount>;
type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
type Time = Timestamp;
type UnsafeUnstableInterface = ();
// UnstableInterface;
type UploadOrigin = EnsureSigned<Self::AccountId>;
type WeightInfo = ();
type WeightPrice = ();
// Self;
type Xcm = ();
type UnsafeUnstableInterface = UnstableInterface;
type UploadOrigin = EnsureAccount<Self, UploadAccount>;
}

parameter_types! {
pub MySchedule: Schedule<Test> = {
let schedule = <Schedule<Test>>::default();
schedule
};
pub static DepositPerByte: <Test as pallet_balances::Config>::Balance = 1;
pub const DepositPerItem: <Test as pallet_balances::Config>::Balance = 2;
pub static MaxDelegateDependencies: u32 = 32;
pub static MaxTransientStorageSize: u32 = 4 * 1024;
pub static CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
pub static DefaultDepositLimit: <Test as pallet_balances::Config>::Balance = 10_000_000;
pub static ChainId: u64 = 909;
pub static UploadAccount: Option<<Test as frame_system::Config>::AccountId> = None;
pub static InstantiateAccount: Option<<Test as frame_system::Config>::AccountId> = None;
pub static UnstableInterface: bool = true;
}

impl frame_support::traits::Randomness<HashOf<Test>, BlockNumberFor<Test>> for Test {
Expand Down Expand Up @@ -344,13 +328,13 @@ impl<E> environment::BufOut for Environment<E> {
/// A mocked smart contract environment.
#[derive(Clone, Default)]
pub(crate) struct MockExt {
pub(crate) address: AccountIdOf<Test>,
pub(crate) address: Option<AccountIdOf<Test>>,
}
impl environment::Ext for MockExt {
type AccountId = AccountIdOf<Test>;

fn address(&self) -> &Self::AccountId {
&self.address
fn address(&self) -> Self::AccountId {
self.address.clone().unwrap_or(ALICE)
}
}

Expand All @@ -366,6 +350,10 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities {

let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
// register account mappings
ext.execute_with(|| {
Contracts::map_account(RuntimeOrigin::signed(ALICE)).unwrap();
});
ext
}

Expand All @@ -387,3 +375,26 @@ impl Converter for UppercaseConverter {
}
}
}

pub struct EnsureAccount<T, A>(PhantomData<(T, A)>);
impl<T: pallet_revive::Config, A: sp_core::Get<Option<crate::AccountIdOf<T>>>>
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) {
return Err(o);
}

Ok(who)
}

#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<T::RuntimeOrigin, ()> {
Err(())
}
}
29 changes: 15 additions & 14 deletions extension/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use std::{path::Path, sync::LazyLock};
use codec::{Decode, Encode};
use frame_support::weights::Weight;
use frame_system::Call;
use pallet_contracts::{Code, CollectEvents, ContractExecResult, Determinism, StorageDeposit};
use pallet_revive::{
AccountId32Mapper, AddressMapper, Code, CollectEvents, ContractExecResult, StorageDeposit,
};
use sp_runtime::{
DispatchError::{self, BadOrigin, Module},
ModuleError,
Expand All @@ -16,7 +18,7 @@ use crate::{
};

static CONTRACT: LazyLock<Vec<u8>> =
LazyLock::new(|| initialize_contract("contract/target/ink/proxy.wasm"));
LazyLock::new(|| initialize_contract("contract/target/ink/proxy.riscv"));

mod dispatch_call {
use super::*;
Expand All @@ -27,7 +29,7 @@ mod dispatch_call {
// Instantiate a new contract.
let contract = instantiate();
let dispatch_result = call(
contract,
contract.clone(),
DispatchContractFuncId::get(),
RuntimeCall::System(Call::remark_with_event { remark: "pop".as_bytes().to_vec() }),
GAS_LIMIT,
Expand All @@ -37,9 +39,9 @@ mod dispatch_call {
let decoded = <Result<Vec<u8>, u32>>::decode(&mut &return_value.data[..]).unwrap();
assert!(decoded.unwrap().is_empty());
// Successfully emit event.
assert!(dispatch_result.events.unwrap().iter().any(|e| matches!(e.event,
assert!(dispatch_result.events.unwrap().iter().any(|e| matches!(&e.event,
RuntimeEvent::System(frame_system::Event::<Test>::Remarked { sender, .. })
if sender == contract)));
if *sender == contract)));
assert_eq!(dispatch_result.storage_deposit, StorageDeposit::Charge(0));
});
}
Expand Down Expand Up @@ -126,7 +128,7 @@ mod read_state {
// Instantiate a new contract.
let contract = instantiate();
let read_result = call(contract, ReadExtFuncId::get(), 99u8, GAS_LIMIT);
let expected: DispatchError = pallet_contracts::Error::<Test>::DecodingFailed.into();
let expected: DispatchError = pallet_revive::Error::<Test>::DecodingFailed.into();
// Make sure the error is passed through the error converter.
let error =
<() as ErrorConverter>::convert(expected, &mock::MockEnvironment::default()).err();
Expand Down Expand Up @@ -155,7 +157,7 @@ fn invalid_func_id_fails() {
// Instantiate a new contract.
let contract = instantiate();
let result = call(contract, INVALID_FUNC_ID, (), GAS_LIMIT);
let expected: DispatchError = pallet_contracts::Error::<Test>::DecodingFailed.into();
let expected: DispatchError = pallet_revive::Error::<Test>::DecodingFailed.into();
// Make sure the error is passed through the error converter.
let error =
<() as ErrorConverter>::convert(expected, &mock::MockEnvironment::default()).err();
Expand Down Expand Up @@ -185,10 +187,10 @@ fn initialize_contract(contract_path: &str) -> Vec<u8> {
/// Instantiating the contract.
fn instantiate() -> AccountId {
let result = Contracts::bare_instantiate(
ALICE,
RuntimeOrigin::signed(ALICE),
0,
GAS_LIMIT,
None,
1_000_000_000_000,
Code::Upload(CONTRACT.clone()),
function_selector("new"),
Default::default(),
Expand All @@ -198,7 +200,7 @@ fn instantiate() -> AccountId {
log::debug!("instantiate result: {result:?}");
let result = result.result.unwrap();
assert!(!result.result.did_revert());
result.account_id
AccountId32Mapper::<Test>::to_fallback_account_id(&result.addr)
}

/// Perform a call to a specified contract.
Expand All @@ -210,15 +212,14 @@ fn call(
) -> ContractExecResult<Balance, EventRecord> {
log::debug!("call: func_id={func_id}, input={input:?}");
let result = Contracts::bare_call(
ALICE,
contract,
RuntimeOrigin::signed(ALICE),
AccountId32Mapper::<Test>::to_address(&contract),
0,
gas_limit,
None,
0,
[function_selector("call"), (func_id, input.encode()).encode()].concat(),
DEBUG_OUTPUT,
CollectEvents::UnsafeCollect,
Determinism::Enforced,
);
log::debug!("gas consumed: {:?}", result.gas_consumed);
log::debug!("call result: {result:?}");
Expand Down
4 changes: 2 additions & 2 deletions pallets/api/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use pop_chain_extension::{
use sp_runtime::DispatchError;
use sp_std::vec::Vec;

/// Encoded version of `pallet_contracts::Error::DecodingFailed`, as found within
/// Encoded version of `pallet_revive::Error::DecodingFailed`, as found within
/// `DispatchError::ModuleError`.
pub const DECODING_FAILED_ERROR: [u8; 4] = [11, 0, 0, 0];
pub const DECODING_FAILED_ERROR: [u8; 4] = [9, 0, 0, 0];
/// The logging target for the chain extension.
pub const LOG_TARGET: &str = "pop-api::extension";

Expand Down
13 changes: 6 additions & 7 deletions pallets/api/src/messaging/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,13 @@ pub enum Read<T: Config> {

#[derive(Debug)]
#[cfg_attr(feature = "std", derive(PartialEq, Clone))]
pub enum ReadResult<T: Config> {
pub enum ReadResult {
Poll(Option<Status>),
Get(Option<BoundedVec<u8, T::MaxResponseLen>>),
Get(Option<Vec<u8>>),
QueryId(Option<QueryId>),
}

impl<T: Config> ReadResult<T> {
impl ReadResult {
pub fn encode(&self) -> Vec<u8> {
use ReadResult::*;
match self {
Expand All @@ -342,7 +342,7 @@ impl<T: Config> ReadResult<T> {

impl<T: Config> crate::Read for Pallet<T> {
type Read = Read<T>;
type Result = ReadResult<T>;
type Result = ReadResult;

fn weight(_read: &Self::Read) -> Weight {
// TODO: implement benchmarks
Expand All @@ -359,9 +359,8 @@ impl<T: Config> crate::Read for Pallet<T> {
})),
Read::Get(request) =>
ReadResult::Get(Messages::<T>::get(request.0, request.1).and_then(|m| match m {
Message::IsmpResponse { response, .. } => Some(response),
Message::XcmResponse { response, .. } =>
Some(response.encode().try_into().unwrap()), // todo: handle error
Message::IsmpResponse { response, .. } => Some(response.into_inner()),
Message::XcmResponse { response, .. } => Some(response.encode()),
_ => None,
})),
Read::QueryId(request) => ReadResult::QueryId(
Expand Down
Loading

0 comments on commit a8c024c

Please sign in to comment.