Skip to content
This repository has been archived by the owner on Sep 28, 2023. It is now read-only.

Pallet-scheduler Chain extension #148

Draft
wants to merge 2 commits into
base: polkadot-v0.9.39
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ members = [
"chain-extensions/dapps-staking",
"chain-extensions/pallet-assets",
"chain-extensions/xvm",
"chain-extensions/pallet-scheduler",
"chain-extensions/types/*",
"frame/block-reward",
"frame/collator-selection",
Expand Down Expand Up @@ -97,6 +98,7 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }

# (native)
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39" }
Expand All @@ -120,6 +122,8 @@ pallet-authorship = { git = "https://github.com/paritytech/substrate", branch =
pallet-session = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
pallet-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
pallet-assets = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
pallet-scheduler = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }
pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.39", default-features = false }

# Polkadot
# (wasm)
Expand Down Expand Up @@ -154,6 +158,7 @@ pallet-xc-asset-config = { path = "./frame/xc-asset-config", default-features =
dapps-staking-chain-extension-types = { path = "./chain-extensions/types/dapps-staking", default-features = false }
xvm-chain-extension-types = { path = "./chain-extensions/types/xvm", default-features = false }
assets-chain-extension-types = { path = "./chain-extensions/types/assets", default-features = false }
scheduler-chain-extension-types = { path = "./chain-extensions/types/scheduler", default-features = false }

pallet-evm-precompile-assets-erc20 = { path = "./precompiles/assets-erc20", default-features = false }
precompile-utils = { path = "./precompiles/utils", default-features = false }
Expand Down
50 changes: 50 additions & 0 deletions chain-extensions/pallet-scheduler/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
[package]
name = "pallet-chain-extension-scheduler"
version = "0.1.0"
license = "Apache-2.0"
description = "Scheduler chain extension for WASM contracts"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true

[dependencies]
frame-support = { workspace = true }
frame-system = { workspace = true }
log = { workspace = true }
num-traits = { workspace = true }
pallet-contracts = { workspace = true }
pallet-contracts-primitives = { workspace = true }
pallet-scheduler = { workspace = true }
parity-scale-codec = { workspace = true }
scale-info = { workspace = true }
scheduler-chain-extension-types = { workspace = true }
sp-core = { workspace = true }
sp-runtime = { workspace = true }
sp-std = { workspace = true }

[dev-dependencies]
env_logger = "0.9"
pallet-balances = { workspace = true }
pallet-preimage = { workspace = true }
pallet-timestamp = { workspace = true }
sp-io = { workspace = true }
sp-keystore = { workspace = true }

[features]
default = ["std"]
std = [
"parity-scale-codec/std",
"frame-support/std",
"frame-system/std",
"num-traits/std",
"pallet-contracts/std",
"pallet-contracts-primitives/std",
"scale-info/std",
"sp-std/std",
"sp-core/std",
"sp-runtime/std",
"pallet-scheduler/std",
"scheduler-chain-extension-types/std",
"pallet-balances/std",
]
167 changes: 167 additions & 0 deletions chain-extensions/pallet-scheduler/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// This file is part of Astar.

// Copyright (C) 2019-2023 Stake Technologies Pte.Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later

// Astar is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Astar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Astar. If not, see <http://www.gnu.org/licenses/>.

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

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

use frame_support::dispatch::Weight;
use frame_support::traits::{schedule, Currency};
use frame_system::RawOrigin;
use pallet_contracts::{
chain_extension::{ChainExtension, Environment, Ext, InitState, RetVal, SysConfig},
Call as PalletContractCall,
};
use pallet_scheduler::WeightInfo;
use parity_scale_codec::{Encode, HasCompact};
use scale_info::TypeInfo;
use scheduler_chain_extension_types::*;
use sp_core::Get;
use sp_runtime::traits::StaticLookup;
use sp_runtime::DispatchError;
use sp_std::boxed::Box;
use sp_std::fmt::Debug;
use sp_std::marker::PhantomData;

enum SchedulerFunc {
Schedule,
Cancel,
}

impl TryFrom<u16> for SchedulerFunc {
type Error = DispatchError;

fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
1 => Ok(SchedulerFunc::Schedule),
2 => Ok(SchedulerFunc::Cancel),
_ => Err(DispatchError::Other(
"PalletSchedulerExtension: Unimplemented func_id",
)),
}
}
}
Comment on lines +45 to +62
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
enum SchedulerFunc {
Schedule,
Cancel,
}
impl TryFrom<u16> for SchedulerFunc {
type Error = DispatchError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
1 => Ok(SchedulerFunc::Schedule),
2 => Ok(SchedulerFunc::Cancel),
_ => Err(DispatchError::Other(
"PalletSchedulerExtension: Unimplemented func_id",
)),
}
}
}
#[repr(u16)]
#[derive(TryFromPrimitive)]
enum SchedulerFunc {
Schedule = 1,
Cancel = 2,
}

Using num_enum will make this less error prone, right now enum values are not mapping 1 to 1 with TryFrom implementation which is not ideal.


type BalanceOf<T> = <<T as pallet_contracts::Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::Balance;

/// Pallet Scheduler chain extension.
pub struct SchedulerExtension<T, W>(PhantomData<(T, W)>);

impl<T, W> Default for SchedulerExtension<T, W> {
fn default() -> Self {
SchedulerExtension(PhantomData)
}
}
Comment on lines +69 to +75
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub struct SchedulerExtension<T, W>(PhantomData<(T, W)>);
impl<T, W> Default for SchedulerExtension<T, W> {
fn default() -> Self {
SchedulerExtension(PhantomData)
}
}
#[derive(DefaultNoBound)]
pub struct SchedulerExtension<T, W>(PhantomData<(T, W)>);

No need to manually impl Default, use use frame_support::DefaultNoBound;


impl<T, W> ChainExtension<T> for SchedulerExtension<T, W>
where
T: pallet_scheduler::Config + pallet_contracts::Config,
<<T as SysConfig>::Lookup as StaticLookup>::Source: From<<T as SysConfig>::AccountId>,
<T as SysConfig>::AccountId: From<[u8; 32]>,
<<<T as pallet_contracts::Config>::Currency as Currency<<T as SysConfig>::AccountId>>::Balance as HasCompact>::Type: Clone + Encode + TypeInfo + Debug + Eq,
<T as pallet_contracts::Config>::RuntimeCall: From<pallet_contracts::Call<T>> + Encode,
<T as pallet_scheduler::Config>::RuntimeCall: From<pallet_contracts::Call<T>>,
W: weights::WeightInfo,
{
fn call<E: Ext>(&mut self, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>
where
E: Ext<T = T>,
{
let func_id = env.func_id().try_into()?;
let mut env = env.buf_in_buf_out();

match func_id {
SchedulerFunc::Schedule => {
let (origin, when, maybe_periodic, priority, call_input): (
Origin,
T::BlockNumber,
Option<schedule::Period<T::BlockNumber>>,
schedule::Priority,
ContractCallInput<T::AccountId, BalanceOf<T>>,
) = env.read_as_unbounded(env.in_len())?;

let read_weight = <W as weights::WeightInfo>::read_as_unbounded(env.in_len());
env.charge_weight(read_weight)?;

let base_weight = <T as pallet_scheduler::Config>::WeightInfo::schedule(
T::MaxScheduledPerBlock::get(),
);
env.charge_weight(base_weight)?;

let raw_origin = select_origin!(&origin, env.ext().address().clone());

let call: <T as pallet_scheduler::Config>::RuntimeCall =
PalletContractCall::<T>::call {
dest: call_input.dest.into(),
value: call_input.value,
gas_limit: Weight::from_parts(call_input.gas_limit.0, call_input.gas_limit.1),
data: call_input.data.into(),
storage_deposit_limit: None,
}.into();

let call_result = pallet_scheduler::Pallet::<T>::schedule(
raw_origin.into(),
when,
maybe_periodic,
priority,
Box::new(call),
);
return match call_result {
Err(e) => {
let mapped_error = Outcome::from(e);
Ok(RetVal::Converging(mapped_error as u32))
}
Ok(_) => Ok(RetVal::Converging(Outcome::Success as u32)),
};
},
SchedulerFunc::Cancel => {
let (origin, when, index): (
Origin,
T::BlockNumber,
u32,
) = env.read_as()?;

let base_weight = <T as pallet_scheduler::Config>::WeightInfo::cancel(
T::MaxScheduledPerBlock::get(),
);
env.charge_weight(base_weight)?;

let raw_origin = select_origin!(&origin, env.ext().address().clone());

let call_result = pallet_scheduler::Pallet::<T>::cancel(
raw_origin.into(),
when,
index,
);
return match call_result {
Err(e) => {
let mapped_error = Outcome::from(e);
Ok(RetVal::Converging(mapped_error as u32))
}
Ok(_) => Ok(RetVal::Converging(Outcome::Success as u32)),
};
}
}
}
}