Skip to content

Commit

Permalink
Update sandbox
Browse files Browse the repository at this point in the history
  • Loading branch information
pgherveou committed Feb 5, 2024
1 parent 4255618 commit 1187c42
Show file tree
Hide file tree
Showing 28 changed files with 736 additions and 375 deletions.
170 changes: 58 additions & 112 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ homepage = "https://github.com/Cardinal-Cryptography/drink"
license = "Apache-2.0"
readme = "README.md"
repository = "https://github.com/Cardinal-Cryptography/drink"
version = "0.8.6"
version = "0.8.10"

[workspace.dependencies]
anyhow = { version = "1.0.71" }
Expand Down Expand Up @@ -57,5 +57,5 @@ sp-runtime-interface = { version = "24.0.0" }

# Local dependencies

drink = { version = "0.8.6", path = "drink" }
drink-test-macro = { version = "0.8.6", path = "drink/test-macro" }
drink = { version = "0.8.10", path = "drink" }
drink-test-macro = { package = "drink-test-macro-next", version = "0.8.10", path = "drink/test-macro" }
6 changes: 1 addition & 5 deletions drink-cli/src/app_state/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use std::{env, path::PathBuf};

pub use contracts::{Contract, ContractIndex, ContractRegistry};
use drink::{
runtime::{MinimalRuntime, Runtime},
session::Session,
Weight, DEFAULT_GAS_LIMIT,
};
use drink::{runtime::MinimalRuntime, session::Session, SandboxConfig, Weight, DEFAULT_GAS_LIMIT};
use sp_core::crypto::AccountId32;
pub use user_input::UserInput;

Expand Down
2 changes: 1 addition & 1 deletion drink/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "drink"
name = "drink-next"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
Expand Down
6 changes: 3 additions & 3 deletions drink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ use parity_scale_codec::{Decode, Encode};
/// Export pallets that are used in the minimal runtime.
pub use {frame_support, frame_system, pallet_balances, pallet_contracts, pallet_timestamp};

pub use crate::runtime::minimal::{self, MinimalRuntime};
use crate::{
errors::MessageResult,
mock::MockRegistry,
runtime::{pallet_contracts_debugging::InterceptingExtT, *},
errors::MessageResult, mock::MockRegistry,
runtime::pallet_contracts_debugging::InterceptingExtT,
};

/// Alias for `frame-system`'s `RuntimeCall` type.
Expand Down
43 changes: 1 addition & 42 deletions drink/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,12 @@
//! `drink` with any runtime that implements the `Runtime` trait.
pub mod minimal;
pub mod pallet_contracts_debugging;

pub use frame_metadata::RuntimeMetadataPrefixed;
use frame_support::sp_runtime::{traits::Dispatchable, Storage};
use frame_system::pallet_prelude::BlockNumberFor;
pub use minimal::MinimalRuntime;
pub mod pallet_contracts_debugging;

/// The type of an account identifier.
pub type AccountIdFor<R> = <R as frame_system::Config>::AccountId;

/// The type of a hash.
pub type HashFor<R> = <R as frame_system::Config>::Hash;

/// A runtime to use.
pub trait Runtime: frame_system::Config {
/// Initialize the storage at the genesis block.
fn initialize_storage(_storage: &mut Storage) -> Result<(), String> {
Ok(())
}

/// Initialize a new block at particular height.
fn initialize_block(
_height: BlockNumberFor<Self>,
_parent_hash: <Self as frame_system::Config>::Hash,
) -> Result<(), String> {
Ok(())
}

/// Finalize a block at particular height.
fn finalize_block(
_height: BlockNumberFor<Self>,
) -> Result<<Self as frame_system::Config>::Hash, String> {
Ok(Default::default())
}

/// Default actor for the runtime.
fn default_actor() -> AccountIdFor<Self>;

/// Metadata of the runtime.
fn get_metadata() -> RuntimeMetadataPrefixed;

/// Convert an account to an call origin.
fn convert_account_to_origin(
account: AccountIdFor<Self>,
) -> <<Self as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin;
}

/// Convenient umbrella trait for `Runtime + pallet_contracts::Config`
pub trait RuntimeWithContracts: Runtime + pallet_contracts::Config {}
impl<T: Runtime + pallet_contracts::Config> RuntimeWithContracts for T {}
151 changes: 83 additions & 68 deletions drink/src/runtime/minimal.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,89 @@
#![allow(missing_docs)] // `construct_macro` doesn't allow doc comments for the runtime type.

#[macro_export]
macro_rules! impl_sandbox_config {
(
struct $name:ident {
runtime: $runtime:tt;
default_balance: $default_balance:expr;
default_actor: $default_actor:expr;
}
) => {
struct $name;
impl_sandbox_config!($name, $runtime, $default_balance, $default_actor);
};
(
$name:ident, $runtime:tt, $default_balance:expr, $default_actor:expr
) => {
impl $crate::SandboxConfig for $name {
type Runtime = $runtime;

fn initialize_storage(storage: &mut $crate::frame_support::sp_runtime::Storage) -> Result<(), String> {
use $crate::frame_support::sp_runtime::BuildStorage;
$crate::pallet_balances::GenesisConfig::<$runtime> {
balances: vec![(Self::default_actor(), $default_balance)],
}
.assimilate_storage(storage)
}

fn initialize_block(
height: $crate::frame_system::pallet_prelude::BlockNumberFor<$runtime>,
parent_hash: <$runtime as $crate::frame_system::Config>::Hash,
) -> Result<(), String> {
use std::time::SystemTime;
use $crate::frame_support::traits::Hooks;

$crate::frame_system::Pallet::<$runtime>::reset_events();
$crate::frame_system::Pallet::<$runtime>::initialize(&height, &parent_hash, &Default::default());
$crate::pallet_balances::Pallet::<$runtime>::on_initialize(height);
$crate::pallet_timestamp::Pallet::<$runtime>::set_timestamp(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time went backwards")
.as_secs(),
);
$crate::pallet_timestamp::Pallet::<$runtime>::on_initialize(height);
$crate::pallet_contracts::Pallet::<$runtime>::on_initialize(height);
$crate::frame_system::Pallet::<$runtime>::note_finished_initialize();
Ok(())
}

fn finalize_block(
height: $crate::frame_system::pallet_prelude::BlockNumberFor<$runtime>,
) -> Result<<$runtime as $crate::frame_system::Config>::Hash, String> {
use $crate::frame_support::traits::Hooks;

$crate::pallet_contracts::Pallet::<$runtime>::on_finalize(height);
$crate::pallet_timestamp::Pallet::<$runtime>::on_finalize(height);
$crate::pallet_balances::Pallet::<$runtime>::on_finalize(height);
Ok($crate::frame_system::Pallet::<$runtime>::finalize().hash())
}

fn default_actor() -> $crate::runtime::AccountIdFor<$runtime> {
$default_actor
}

fn get_metadata() -> $crate::runtime::RuntimeMetadataPrefixed {
$runtime::metadata()
}

fn convert_account_to_origin(
account: $crate::runtime::AccountIdFor<$runtime>,
) -> <<$runtime as $crate::frame_system::Config>::RuntimeCall as $crate::frame_support::sp_runtime::traits::Dispatchable>::RuntimeOrigin {
Some(account).into()
}
}
};
}

/// Macro creating a minimal runtime with the given name. Optionally can take a chain extension
/// type as a second argument.
///
/// The new macro will automatically implement `drink::Runtime`.
#[macro_export]
macro_rules! create_minimal_runtime {
macro_rules! create_minimal_sandbox {
($name:ident) => {
create_minimal_runtime!($name, ());
create_minimal_sandbox!($name, ());
};
($name:ident, $chain_extension: ty) => {

Expand Down Expand Up @@ -128,83 +204,22 @@ mod construct_runtime {
type Xcm = ();
}

// ------------ Implement `drink::Runtime` trait ---------------------------------------------------

use std::time::SystemTime;

use $crate::frame_support::{
sp_runtime::{traits::Dispatchable, BuildStorage, Storage},
traits::Hooks,
};

use $crate::runtime::{AccountIdFor, Runtime, RuntimeMetadataPrefixed};

// ------------ Implement `drink::Runtime` trait ---------------------------------------------------

/// Default initial balance for the default account.
pub const INITIAL_BALANCE: u128 = 1_000_000_000_000_000;
$crate::impl_sandbox_config!($name, $name, INITIAL_BALANCE, AccountId32::new([1u8; 32]));
}

impl Runtime for $name {
fn initialize_storage(storage: &mut Storage) -> Result<(), String> {
$crate::pallet_balances::GenesisConfig::<Self> {
balances: vec![(Self::default_actor(), INITIAL_BALANCE)],
}
.assimilate_storage(storage)
}

fn initialize_block(
height: $crate::frame_system::pallet_prelude::BlockNumberFor<Self>,
parent_hash: H256,
) -> Result<(), String> {
System::reset_events();
System::initialize(&height, &parent_hash, &Default::default());

Balances::on_initialize(height);
Timestamp::set_timestamp(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time went backwards")
.as_secs(),
);
Timestamp::on_initialize(height);
Contracts::on_initialize(height);

System::note_finished_initialize();

Ok(())
}

fn finalize_block(
height: $crate::frame_system::pallet_prelude::BlockNumberFor<Self>,
) -> Result<H256, String> {
Contracts::on_finalize(height);
Timestamp::on_finalize(height);
Balances::on_finalize(height);

Ok(System::finalize().hash())
}

fn default_actor() -> AccountIdFor<Self> {
AccountId32::new([1u8; 32])
}

fn get_metadata() -> RuntimeMetadataPrefixed {
Self::metadata()
}

fn convert_account_to_origin(
account: AccountIdFor<Self>,
) -> <<Self as $crate::frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin {
Some(account).into()
}
}
}

// ------------ Export runtime type itself, pallets and useful types from the auxiliary module -----
pub use construct_runtime::{
$name, Balances, Contracts, PalletInfo, RuntimeCall, RuntimeEvent, RuntimeHoldReason,
RuntimeOrigin, System, Timestamp, INITIAL_BALANCE,
RuntimeOrigin, System, Timestamp,
};
};
}

create_minimal_runtime!(MinimalRuntime);
create_minimal_sandbox!(MinimalRuntime);
8 changes: 5 additions & 3 deletions drink/src/sandbox.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! A sandboxed runtime.
mod sandbox_core;
pub use sandbox_core::SandboxConfig;
pub mod balance_api;
pub mod contract_api;
pub mod runtime_api;
Expand All @@ -12,12 +14,12 @@ use sp_externalities::Extension;
use sp_io::TestExternalities;

/// A sandboxed runtime.
pub struct Sandbox<R: frame_system::Config> {
pub struct Sandbox<Config: SandboxConfig> {
externalities: TestExternalities,
_phantom: std::marker::PhantomData<R>,
_phantom: std::marker::PhantomData<Config>,
}

impl<R: frame_system::Config> Sandbox<R> {
impl<Config: SandboxConfig> Sandbox<Config> {
/// Execute the given closure with the inner externallities.
///
/// Returns the result of the given closure.
Expand Down
22 changes: 15 additions & 7 deletions drink/src/sandbox/balance_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use frame_support::{sp_runtime::DispatchError, traits::fungible::Mutate};
use super::Sandbox;
use crate::{runtime::AccountIdFor, BalanceOf};

impl<R: pallet_balances::Config> Sandbox<R> {
impl<Config: crate::SandboxConfig> Sandbox<Config>
where
Config::Runtime: crate::pallet_balances::Config,
{
/// Mint tokens to an account.
///
/// # Arguments
Expand All @@ -13,18 +16,23 @@ impl<R: pallet_balances::Config> Sandbox<R> {
/// * `amount` - The number of tokens to add.
pub fn mint_into(
&mut self,
address: AccountIdFor<R>,
amount: BalanceOf<R>,
) -> Result<BalanceOf<R>, DispatchError> {
self.execute_with(|| pallet_balances::Pallet::<R>::mint_into(&address, amount))
address: AccountIdFor<Config::Runtime>,
amount: BalanceOf<Config::Runtime>,
) -> Result<BalanceOf<Config::Runtime>, DispatchError> {
self.execute_with(|| {
pallet_balances::Pallet::<Config::Runtime>::mint_into(&address, amount)
})
}

/// Return the free balance of an account.
///
/// # Arguments
///
/// * `address` - The address of the account to query.
pub fn free_balance(&mut self, address: &AccountIdFor<R>) -> BalanceOf<R> {
self.execute_with(|| pallet_balances::Pallet::<R>::free_balance(address))
pub fn free_balance(
&mut self,
address: &AccountIdFor<Config::Runtime>,
) -> BalanceOf<Config::Runtime> {
self.execute_with(|| pallet_balances::Pallet::<Config::Runtime>::free_balance(address))
}
}
Loading

0 comments on commit 1187c42

Please sign in to comment.