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 27, 2024
1 parent 4e36311 commit 7083154
Show file tree
Hide file tree
Showing 63 changed files with 669 additions and 596 deletions.
10 changes: 6 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
pub use pallet::*;
pub use weights::*;

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

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

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

// The pallet is defined below.
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 Down Expand Up @@ -62,8 +66,17 @@ impl pallet_move::Config for Test {
type Currency = Balances;
}

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

/// 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;
86 changes: 86 additions & 0 deletions src/tests/address.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//! Address conversion utilities based on the Pontem address solution.
//! To properly handle Move VM addresses and Substrate addresses, we need to convert them to each other.
use crate::mock::*;

use move_core_types::account_address::AccountAddress;
use sp_core::{crypto::Ss58Codec, sr25519::Public};

// This dataset contains only allowed and unprotected memory addressses.
const DATASET: &[(&str, &str); 5] = &[
(
"gkQ5K6EnLRgZkwozG8GiBAEnJyM6FxzbSaSmVhKJ2w8FcK7ih",
"d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d",
),
(
"gkNW9pAcCHxZrnoVkhLkEQtsLsW5NWTC75cdAdxAMs9LNYCYg",
"8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48",
),
(
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d",
),
(
"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty",
"8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48",
),
(
"5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y",
"90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22",
),
];

#[test]
fn to_move_address_check() {
new_test_ext().execute_with(|| {
for pair in DATASET.iter() {
let (pk, _) = Public::from_ss58check_with_version(pair.0).unwrap();
let addr = MoveModule::to_move_address(&pk.into()).unwrap();
assert_eq!(pair.1, addr.to_string());
}
})
}

#[test]
fn to_substrate_account_check() {
new_test_ext().execute_with(|| {
for pair in DATASET.iter() {
let pk_expected = Public::from_ss58check_with_version(pair.0)
.unwrap()
.0
.into();
let addr = MoveModule::to_move_address(&pk_expected).unwrap();
let pk_decoded = MoveModule::to_native_account(&addr).expect("Cannot decode address");
assert_eq!(pk_expected, pk_decoded);
}
})
}

#[test]
fn account_to_bytes_check() {
for pair in DATASET.iter() {
let (pk, _) = Public::from_ss58check_with_version(pair.0).unwrap();
let bytes = MoveModule::to_move_address(&pk.into())
.unwrap()
.into_bytes();
assert_eq!(pair.1, hex::encode(bytes));

let bytes_expected = AccountAddress::from_hex_literal(&format!("0x{}", pair.1))
.unwrap()
.to_vec();
assert_eq!(bytes_expected, bytes);
}
}

#[test]
fn check_protected_address_errors() {
new_test_ext().execute_with(|| {
// Check the one protected and prohibited memory address for an error.
// The ss58-address is equivalent to Move-address "0x1".
let prohibited = "gkKH52LJ2UumhVBim1n3mCsSj3ctj3GkV8JLVLdhJakxmEDcq";
let pk_expected = Public::from_ss58check_with_version(prohibited)
.unwrap()
.0
.into();
assert!(MoveModule::to_move_address(&pk_expected).is_err());
});
}
Loading

0 comments on commit 7083154

Please sign in to comment.