Skip to content

Commit

Permalink
chore: restructure pallet part 1, unit tests and internal mockup
Browse files Browse the repository at this point in the history
  • Loading branch information
neutrinoks committed Feb 29, 2024
1 parent 4e36311 commit db9dc58
Show file tree
Hide file tree
Showing 66 changed files with 717 additions and 663 deletions.
17 changes: 12 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,15 @@ hex = "0.4"
rand = "0.8"
lazy_static = "1.4"
move-stdlib = { git = "https://github.com/eigerco/substrate-move.git", features = ["stdlib-bytecode"] }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.4.0" }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.4.0" }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.4.0" }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.4.0" }

[features]
default = ["std"]
std = [
"anyhow/std",
"codec/std",
"frame-benchmarking?/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"scale-info/std",
Expand All @@ -56,8 +54,17 @@ std = [
"move-core-types/std",
"move-vm-backend/std",
]
runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"]
try-runtime = ["frame-support/try-runtime"]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
]

# Builds move projects for test purposes.
#
Expand Down
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn build_move_projects() -> Result<(), Box<dyn Error>> {
println!("cargo:warning=Building move projects in tests/assets folder");

let smove_run = Command::new("bash")
.args(["tests/assets/move-projects/smove-build-all.sh"])
.args(["src/tests/assets/move-projects/smove-build-all.sh"])
.output()
.expect("failed to execute script which builds necessary move modules");

Expand Down
88 changes: 31 additions & 57 deletions src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -1,73 +1,47 @@
//! Benchmarking setup for pallet-move
use frame_benchmarking::v2::*;
use frame_system::{Config as SysConfig, RawOrigin};
use sp_runtime::traits::Zero;
#![cfg(feature = "runtime-benchmarks")]

use crate::balance::BalanceOf;
use crate::{script_transaction, no_type_args, Pallet, Config};
use frame_benchmarking::*;
use frame_system::{Call, Config as SysConfig, RawOrigin};
use move_vm_backend_common::types::ScriptTransaction;
use sp_core::{crypto::Ss58Codec, sr25519::Public};
use sp_runtime::{AccountId32, traits::Zero};
use sp_std::vec;

use crate::{balance::BalanceOf, Config, *};
const BOB_ADDR: &str = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty";

fn addr32_from_ss58(ss58addr: &str) -> AccountId32 {
let (pk, _) = Public::from_ss58check_with_version(ss58addr).unwrap();
pk.into()
}

#[benchmarks(
where
benchmarks! {
where_clause { where
T: Config + SysConfig,
T::AccountId: From<AccountId32>,
BalanceOf<T>: From<u128> + Into<u128>,
)]
mod benchmarks {
use sp_core::{crypto::Ss58Codec, sr25519::Public};
use sp_runtime::AccountId32;

use super::*;

const BOB_ADDR: &str = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty";

fn addr32_from_ss58(ss58addr: &str) -> AccountId32 {
let (pk, _) = Public::from_ss58check_with_version(ss58addr).unwrap();
pk.into()
}

#[benchmark]
fn execute() {
execute {
let caller: T::AccountId = addr32_from_ss58(BOB_ADDR).into();
let module =
include_bytes!("../tests/assets/move-projects/move-basics/build/move-basics/bytecode_scripts/empty_scr.mv")
.to_vec();
let transaction = ScriptTransaction {
bytecode: module,
type_args: vec![],
args: vec![],
};
let transaction_bc = bcs::to_bytes(&transaction).unwrap();
#[extrinsic_call]
execute(
RawOrigin::Signed(caller),
transaction_bc,
100_000,
BalanceOf::<T>::zero(),
);
}
let script = crate::mock::assets::read_script_from_project("move-basics", "empty_scr");
let transaction_bc = script_transaction!(script, no_type_args!());
}: _(RawOrigin::Signed(caller), transaction_bc, 100_000, BalanceOf::<T>::zero())
verify {}

#[benchmark]
fn publish_module() {
publish_module {
let caller: T::AccountId = addr32_from_ss58(BOB_ADDR).into();
let module = include_bytes!(
"../tests/assets/move-projects/using_stdlib_natives/build/using_stdlib_natives/bytecode_modules/Vector.mv"
)
.to_vec();
#[extrinsic_call]
publish_module(RawOrigin::Signed(caller), module, 500_000);
}
let module = crate::mock::assets::read_module_from_project("using_stdlib_natives", "Vector");
}: _(RawOrigin::Signed(caller), module, 500_000)
verify {}

#[benchmark]
fn publish_module_bundle() {
publish_module_bundle {
let caller: T::AccountId = addr32_from_ss58(BOB_ADDR).into();
let module = include_bytes!(
"../tests/assets/move-projects/using_stdlib_natives/build/using_stdlib_natives/bundles/using_stdlib_natives.mvb"
)
.to_vec();
#[extrinsic_call]
publish_module_bundle(RawOrigin::Signed(caller), module, 1_500_000);
}
let bundle = crate::mock::assets::read_bundle_from_project("using_stdlib_natives", "using_stdlib_natives");
}: _(RawOrigin::Signed(caller), bundle, 1_500_000)
verify {}

impl_benchmark_test_suite!(MovePallet, crate::mock::new_test_ext(), crate::mock::Test);
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test);
}
18 changes: 10 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
#![cfg_attr(not(feature = "std"), no_std)]

pub use pallet::*;
pub use weights::*;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub mod balance;
#[cfg(any(test, feature = "runtime-benchmarks"))]
mod benchmarking;
#[cfg(test)]
mod mock;
mod result;
mod signer;
mod storage;

mod result;
#[cfg(test)]
mod tests;
pub mod weights;

pub use pallet::*;
pub use weights::*;

// The pallet is defined below.
#[frame_support::pallet]
pub mod pallet {
Expand Down
79 changes: 64 additions & 15 deletions tests/mock.rs → src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
//! Crate internal mockup for unit tests.
use crate as pallet_move;

use frame_support::traits::{ConstU128, ConstU16, ConstU32, ConstU64};
use move_core_types::account_address::AccountAddress;
use sp_core::{crypto::Ss58Codec, sr25519::Public, H256};
Expand All @@ -8,6 +12,16 @@ use sp_runtime::{

type Block = frame_system::mocking::MockBlock<Test>;

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system,
Balances: pallet_balances,
MoveModule: pallet_move,
}
);

impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
Expand Down Expand Up @@ -63,7 +77,6 @@ impl pallet_move::Config for Test {
}

/// Test Externalities Builder for an easier test setup.
#[allow(dead_code)]
#[derive(Default)]
pub(crate) struct ExtBuilder {
/// Overwrite default accounts with balances.
Expand All @@ -74,7 +87,6 @@ pub(crate) struct ExtBuilder {
substrate_stdlib: Option<Vec<u8>>,
}

#[allow(dead_code)]
impl ExtBuilder {
/// Overwrites default balances on dev-test setup.
pub(crate) fn with_balances(mut self, balances: Vec<(AccountId32, Balance)>) -> Self {
Expand Down Expand Up @@ -118,7 +130,6 @@ impl ExtBuilder {
}

// Build genesis storage according to the mock runtime.
#[allow(dead_code)]
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut storage = frame_system::GenesisConfig::<Test>::default()
.build_storage()
Expand All @@ -136,7 +147,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
}

// Common constants accross the tests.
#[allow(dead_code)]
pub const EMPTY_CHEQUE: u128 = 0; // Not all scripts need the `cheque_amount` parameter.
pub const CAFE_ADDR: &str = "0xCAFE";
pub const BOB_ADDR: &str = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty";
Expand Down Expand Up @@ -172,18 +182,15 @@ lazy_static::lazy_static! {
};
}

#[allow(dead_code)]
pub fn addr32_from_ss58(ss58addr: &str) -> AccountId32 {
let (pk, _) = Public::from_ss58check_with_version(ss58addr).unwrap();
pk.into()
}

#[allow(dead_code)]
pub fn addr32_to_move(addr32: &AccountId32) -> Result<AccountAddress, pallet_move::Error<Test>> {
MoveModule::to_move_address(addr32)
}

#[allow(dead_code)]
pub fn addrs_from_ss58(
ss58: &str,
) -> Result<(AccountId32, AccountAddress), pallet_move::Error<Test>> {
Expand All @@ -192,12 +199,54 @@ pub fn addrs_from_ss58(
Ok((addr_32, addr_mv))
}

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system,
Balances: pallet_balances,
MoveModule: pallet_move,
pub mod assets {
const MOVE_PROJECTS: &str = "src/tests/assets/move-projects";

/// Reads bytes from a file for the given path.
/// Can panic if the file doesn't exist.
fn read_bytes(file_path: &str) -> Vec<u8> {
std::fs::read(file_path)
.unwrap_or_else(|e| panic!("Can't read {file_path}: {e} - make sure you run pallet-move/tests/assets/move-projects/smove-build-all.sh"))
}
);

/// Reads a precompiled Move module from our assets directory.
pub fn read_module_from_project(project: &str, module_name: &str) -> Vec<u8> {
let path =
format!("{MOVE_PROJECTS}/{project}/build/{project}/bytecode_modules/{module_name}.mv");
read_bytes(&path)
}

/// Reads a precompiled Move bundle from our assets directory.
pub fn read_bundle_from_project(project: &str, bundle_name: &str) -> Vec<u8> {
let path = format!("{MOVE_PROJECTS}/{project}/build/{project}/bundles/{bundle_name}.mvb");
read_bytes(&path)
}

/// Reads a precompiled Move scripts from our assets directory.
pub fn read_script_from_project(project: &str, script_name: &str) -> Vec<u8> {
let path =
format!("{MOVE_PROJECTS}/{project}/build/{project}/bytecode_scripts/{script_name}.mv");
read_bytes(&path)
}
}

#[macro_export]
macro_rules! script_transaction {
($bytecode:expr, $type_args:expr $(, $args:expr)*) => {
{
let transaction = ScriptTransaction {
bytecode: $bytecode,
type_args: $type_args,
args: vec![$(bcs::to_bytes($args).unwrap()),*],
};
bcs::to_bytes(&transaction).unwrap()
}
}
}

#[macro_export]
macro_rules! no_type_args {
() => {
vec![]
};
}
10 changes: 10 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! Container module for all test modules.
pub mod address;
pub mod balance;
pub mod example;
pub mod execute;
pub mod modules;
pub mod publish;
pub mod signer;
pub mod update_stdlib;
Loading

0 comments on commit db9dc58

Please sign in to comment.