Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock builder proposal: usage example #2313

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions substrate/frame/examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pallet-example-frame-crate = { path = "frame-crate", default-features = false }
pallet-example-kitchensink = { path = "kitchensink", default-features = false}
pallet-example-offchain-worker = { path = "offchain-worker", default-features = false}
pallet-example-split = { path = "split", default-features = false}
pallet-example-mock-builder = { path = "mock-builder", default-features = false}

[features]
default = [ "std" ]
Expand All @@ -31,6 +32,7 @@ std = [
"pallet-example-kitchensink/std",
"pallet-example-offchain-worker/std",
"pallet-example-split/std",
"pallet-example-mock-builder/std",
]
try-runtime = [
"pallet-default-config-example/try-runtime",
Expand All @@ -39,4 +41,5 @@ try-runtime = [
"pallet-example-kitchensink/try-runtime",
"pallet-example-offchain-worker/try-runtime",
"pallet-example-split/try-runtime",
"pallet-example-mock-builder/try-runtime",
]
56 changes: 56 additions & 0 deletions substrate/frame/examples/mock-builder/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[package]
name = "pallet-example-mock-builder"
version = "4.0.0-dev"
authors.workspace = true
edition.workspace = true
license = "MIT-0"
homepage = "https://substrate.io"
repository.workspace = true
description = "FRAME pallet tested with mock-builder"
readme = "README.md"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }

frame-support = { path = "../../support", default-features = false}
frame-system = { path = "../../system", default-features = false}

sp-runtime = { path = "../../../primitives/runtime", default-features = false}

polkadot-runtime-common = { path = "../../../../polkadot/runtime/common", default-features = false}

[dev-dependencies]
sp-io = { path = "../../../primitives/io"}
sp-core = { path = "../../../primitives/core"}
sp-std = { path = "../../../primitives/std"}

polkadot-primitives = { path = "../../../../polkadot/primitives", default-features = false}

mock-builder = { git = "https://github.com/foss3/runtime-pallet-library", branch = "polkadot-v1.2.0" }

[features]
default = [ "std" ]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-runtime/std",
"polkadot-runtime-common/std",
]
runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
"polkadot-runtime-common/try-runtime",
]
95 changes: 95 additions & 0 deletions substrate/frame/examples/mock-builder/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! Silly pallet to show how to testing with mock-builder works
//!
//! The pallet allows to create auctions once a certain deposit is reached and some time has been
//! passed from the last deposit.

#![cfg_attr(not(feature = "std"), no_std)]

pub use pallet::*;

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[frame_support::pallet]
pub mod pallet {
use frame_support::{
pallet_prelude::*,
traits::{Currency, ReservableCurrency, Time},
};
use frame_system::pallet_prelude::*;
use polkadot_runtime_common::traits::Auctioneer;
use sp_runtime::traits::Saturating;

type MomentOf<T> = <<T as Config>::Time as Time>::Moment;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

#[pallet::pallet]
pub struct Pallet<T>(_);

#[pallet::config]
pub trait Config: frame_system::Config {
type Time: Time;
type Currency: ReservableCurrency<Self::AccountId>;
type Auction: Auctioneer<BlockNumberFor<Self>, LeasePeriod = BlockNumberFor<Self>>;

#[pallet::constant]
type ExpectedAmount: Get<BalanceOf<Self>>;

#[pallet::constant]
type WaitingTime: Get<MomentOf<Self>>;

#[pallet::constant]
type Period: Get<BlockNumberFor<Self>>;
}

#[pallet::storage]
pub type LastDeposit<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, MomentOf<T>>;

#[pallet::error]
pub enum Error<T> {
NotEnoughDeposit,
NotEnoughWaiting,
}

#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(Weight::default())]
pub fn make_reserve(origin: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {
let who = ensure_signed(origin)?;

T::Currency::reserve(&who, amount)?;
LastDeposit::<T>::insert(who, T::Time::now());

Ok(())
}

/// To create an auction we need to fullfull the following non-sense conditions:
/// - origin has T::ExpectedAmount reserved.
/// - T::WaitingTime has passed from the last make_deposit call.
#[pallet::call_index(1)]
#[pallet::weight(Weight::default())]
pub fn create_auction(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;

// Check reserve
let current = T::Currency::reserved_balance(&who);
ensure!(current >= T::ExpectedAmount::get(), Error::<T>::NotEnoughDeposit);

// Check time
let now = T::Time::now();
let last = LastDeposit::<T>::get(who).unwrap_or(now);
let ready_at = T::WaitingTime::get().saturating_add(last);
ensure!(now >= ready_at, Error::<T>::NotEnoughWaiting);

let block = frame_system::Pallet::<T>::block_number();
T::Auction::new_auction(block, T::Period::get())?;

Ok(())
}
}
}
71 changes: 71 additions & 0 deletions substrate/frame/examples/mock-builder/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
mod mock_pallets;
use mock_pallets::{mock_pallet_auctioneer, mock_pallet_currency, mock_pallet_time};

use super::pallet;
use frame_support::{
derive_impl,
traits::{ConstU128, ConstU64},
};
use frame_system::pallet_prelude::BlockNumberFor;

pub const DAY: u64 = 24 * 3600 * 1000; // ms

pub const INITIAL_TIME: u64 = 10 * DAY;
pub const EXPECTED_AMOUNT: u128 = 100;
pub const WAITING_TIME: u64 = DAY;
pub const PERIOD: u64 = 50;

frame_support::construct_runtime!(
pub struct Runtime {
System: frame_system,
MockTime: mock_pallet_time,
MockCurrency: mock_pallet_currency,
MockAuctioneer: mock_pallet_auctioneer,
MyPallet: pallet,
}
);

#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
type Block = frame_system::mocking::MockBlock<Runtime>;
}

impl mock_pallet_time::Config for Runtime {
type Moment = u64;
}

impl mock_pallet_currency::Config for Runtime {
type Balance = u128;
type PositiveImbalance = ();
type NegativeImbalance = ();
}

impl mock_pallet_auctioneer::Config for Runtime {
type LeasePeriod = BlockNumberFor<Runtime>;
type Currency = mock_pallet_currency::Pallet<Runtime>;
}

impl pallet::Config for Runtime {
type Time = mock_pallet_time::Pallet<Runtime>;
type Currency = mock_pallet_currency::Pallet<Runtime>;
type Auction = mock_pallet_auctioneer::Pallet<Runtime>;
type ExpectedAmount = ConstU128<EXPECTED_AMOUNT>;
type WaitingTime = ConstU64<WAITING_TIME>;
type Period = ConstU64<PERIOD>;
}

pub fn new_test_ext() -> sp_io::TestExternalities {
let mut ext = sp_io::TestExternalities::new(Default::default());

ext.execute_with(|| {
// Initial time for all test cases
MockTime::mock_now(|| INITIAL_TIME);

// Initial reserved balances for all test cases
MockCurrency::mock_reserved_balance(|_account| 0);

// Mock calls can be later overwriten in the test cases
});

ext
}
Loading