difftreelog
feat(Scheduler) most critical improvements done, polishing needed
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6108,7 +6108,7 @@
[[package]]
name = "pallet-template-transaction-payment"
version = "3.0.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -6272,7 +6272,6 @@
"parity-scale-codec",
"scale-info",
"serde",
- "sp-api",
"sp-core",
"sp-io",
"sp-runtime",
@@ -11313,7 +11312,7 @@
"chrono",
"lazy_static",
"matchers",
- "parking_lot 0.11.2",
+ "parking_lot 0.10.2",
"regex",
"serde",
"serde_json",
@@ -11443,7 +11442,7 @@
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"
dependencies = [
- "cfg-if 1.0.0",
+ "cfg-if 0.1.10",
"rand 0.8.4",
"static_assertions",
]
@@ -11812,7 +11811,7 @@
[[package]]
name = "up-sponsorship"
version = "0.1.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"impl-trait-for-tuples",
]
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -20,11 +20,11 @@
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }
log = { version = "0.4.14", default-features = false }
[dev-dependencies]
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
[features]
@@ -38,6 +38,7 @@
"up-sponsorship/std",
"sp-io/std",
"sp-std/std",
+ "sp-core/std",
"log/std",
]
runtime-benchmarks = [
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -60,6 +60,8 @@
use sp_runtime::{
RuntimeDebug,
traits::{Zero, One, BadOrigin, Saturating},
+ transaction_validity::TransactionValidityError,
+ DispatchErrorWithPostInfo,
};
use frame_support::{
decl_module, decl_storage, decl_event, decl_error,
@@ -69,23 +71,13 @@
schedule::{self, DispatchTime},
OriginTrait, EnsureOrigin, IsType,
},
- weights::{GetDispatchInfo, Weight},
+ weights::{GetDispatchInfo, Weight, PostDispatchInfo},
};
use frame_system::{self as system, ensure_signed};
pub use weights::WeightInfo;
+use up_sponsorship::SponsorshipHandler;
use scale_info::TypeInfo;
-use sp_runtime::ApplyExtrinsicResult;
-use sp_runtime::traits::{IdentifyAccount, Verify};
-use sp_runtime::{MultiSignature};
-
-pub trait ApplyExtrinsic<C: Dispatchable> {
- fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;
-}
-
-/// The address format for describing accounts.
-pub type Signature = MultiSignature;
-pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
-pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
+use sp_core::H160;
/// Our pallet's configuration trait. All our types and constants go in here. If the
/// pallet is dependent on specific other pallets, then their configuration traits
@@ -122,10 +114,38 @@
/// Not strictly enforced, but used for weight estimation.
type MaxScheduledPerBlock: Get<u32>;
+ /// Sponsoring function.
+ type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
+
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
- type Executor: ApplyExtrinsic<<Self as Config>::Call>;
+ /// The helper type used for custom transaction fee logic.
+ type CallExecutor: DispatchCall<Self, H160>;
+}
+
+/// A Scheduler-Runtime interface for finer payment handling.
+pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
+ /// The type that encodes information that can be passed from pre_dispatch to post-dispatch.
+ type Pre: Default + Codec + Clone + TypeInfo;
+
+ /// Resolve the call dispatch, including any post-dispatch operations.
+ fn dispatch_call(
+ pre_dispatch: Self::Pre,
+ function: <T as Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ >;
+
+ /// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).
+ fn pre_dispatch(
+ signer: T::AccountId,
+ function: <T as Config>::Call,
+ ) -> Result<Self::Pre, TransactionValidityError>;
+
+ /// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).
+ fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;
}
pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;
@@ -139,19 +159,19 @@
/// The location of a scheduled task that can be used to remove it.
pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
+/*#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))] todo remove completely?
#[derive(Clone, RuntimeDebug, Encode, Decode)]
struct ScheduledV1<Call, BlockNumber> {
maybe_id: Option<Vec<u8>>,
priority: schedule::Priority,
call: Call,
maybe_periodic: Option<schedule::Period<BlockNumber>>,
-}
+}*/
/// Information regarding an item to be executed in the future.
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]
-pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {
+pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {
/// The unique identity for this task, if there is one.
maybe_id: Option<Vec<u8>>,
/// This task's priority.
@@ -162,17 +182,19 @@
maybe_periodic: Option<schedule::Period<BlockNumber>>,
/// The origin to dispatch the call.
origin: PalletsOrigin,
+ /// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.
+ pre_dispatch: PreDispatch,
_phantom: PhantomData<AccountId>,
}
/// The current version of Scheduled struct.
-pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =
- ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;
+/*pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> =
+ ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch>;*/
// A value placed in storage that represents the current version of the Scheduler storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic.
-#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
+/*#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] todo remove completely?
enum Releases {
V1,
V2,
@@ -182,7 +204,7 @@
fn default() -> Self {
Releases::V1
}
-}
+}*/
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct CallSpec {
@@ -194,18 +216,24 @@
trait Store for Module<T: Config> as Scheduler {
/// Items to be executed, indexed by the block number that they should be executed on.
pub Agenda: map hasher(twox_64_concat) T::BlockNumber
- => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;
+ => Vec<Option<Scheduled<
+ <T as Config>::Call,
+ T::BlockNumber,
+ T::PalletsOrigin,
+ T::AccountId,
+ <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre
+ >>>;
- pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber
- => Vec<Option<CallSpec>>;
+ /*pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber todo remove completely?
+ => Vec<Option<CallSpec>>;*/
/// Lookup from identity to the block number and index of the task.
Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;
- /// Storage version of the pallet.
- ///
- /// New networks start with last version.
- StorageVersion build(|_| Releases::V2): Releases;
+ // / Storage version of the pallet.
+ // /
+ // / New networks start with last version.
+ //StorageVersion build(|_| Releases::V2): Releases; todo remove completely?
}
}
@@ -418,19 +446,25 @@
Some((order, index, *cumulative_weight, s))
})
.filter_map(|(order, index, cumulative_weight, mut s)| {
- // We allow a scheduled call if any is true:
+ // We allow a scheduled call if:
// - It's priority is `HARD_DEADLINE`
- // - It does not push the weight past the limit.
+ // - It does not push the weight past the limit
+ // or, alternatively,
// - It is the first item in the schedule
- if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
+ if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {
+ let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());
+
+ if let Err(_) = r {
+ log::warn!(
+ target: "runtime::scheduler",
+ "Warning: Scheduler has failed to execute a post-dispatch transaction. \
+ This block might have become invalid.",
+ );
+ // todo possibly force a skip/return here, do something with the error
+ }
+
+ let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?
- // let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
- // s.origin.clone()
- // ).into();
- // let sender = ensure_signed(origin).unwrap_or_default();
- // let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);
- // let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
- // let r = s.call.clone().dispatch(sponsor.into());
let maybe_id = s.maybe_id.clone();
if let Some((period, count)) = s.maybe_periodic {
if count > 1 {
@@ -451,7 +485,7 @@
Self::deposit_event(RawEvent::Dispatched(
(now, index),
maybe_id,
- Ok(())// r.map(|_| ()).map_err(|e| e.error)
+ r.map(|_| ()).map_err(|e| e.error)
));
total_weight = cumulative_weight;
None
@@ -500,13 +534,19 @@
let sender = ensure_signed(
<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),
)
- .unwrap_or_default();
- let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);
- let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
- let r = call.clone().dispatch(sponsor.into());
+ .unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment
+ //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);
+ //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));
+ //let r = call.clone().dispatch(sponsor.into());
+
+ let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {
+ Ok(pre_dispatch) => pre_dispatch,
+ Err(_) => return Err(Error::<T>::FailedToSchedule.into()),
+ };
- //T::PaymentHandler::apply();
- //T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch extrinsic here
+ // todo continually pre-dispatch according to maybe_periodic -- but it's called only once?
+ // no, reschedule and cancel rely on scheduled being only the next instance
+ // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee
// sanitize maybe_periodic
let maybe_periodic = maybe_periodic
@@ -514,12 +554,21 @@
// Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.
.map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));
+ if let Some(periodic) = maybe_periodic {
+ for _i in 0..=periodic.1 {
+ // displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment
+ // send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?
+ // roadblock - they will return on post_dispatch -- oh! tips?
+ }
+ }
+
let s = Some(Scheduled {
maybe_id,
priority,
call,
maybe_periodic,
origin,
+ pre_dispatch,
_phantom: PhantomData::<T::AccountId>::default(),
});
Agenda::<T>::append(when, s);
@@ -557,7 +606,7 @@
let scheduled = Agenda::<T>::try_mutate(when, |agenda| {
agenda.get_mut(index as usize).map_or(
Ok(None),
- |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
+ |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
if *o != s.origin {
return Err(BadOrigin.into());
@@ -570,8 +619,14 @@
if let Some(s) = scheduled {
if let Some(id) = s.maybe_id {
Lookup::<T>::remove(id);
- // todo add back money / displace to another function for consistency
}
+ if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {
+ log::warn!(
+ target: "runtime::scheduler",
+ "Warning: Scheduler has failed to execute a post-dispatch transaction. \
+ This block might have become invalid.",
+ );
+ } // maybe do something with the error?
Self::deposit_event(RawEvent::Canceled(when, index));
Ok(())
} else {
@@ -643,12 +698,19 @@
if *o != s.origin {
return Err(BadOrigin.into());
}
+ if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())
+ {
+ log::warn!(
+ target: "runtime::scheduler",
+ "Warning: Scheduler has failed to execute a post-dispatch transaction. \
+ This block might have become invalid.",
+ );
+ } // maybe do something with the error?
}
*s = None;
}
Ok(())
})?;
- // todo add money back / displace to another function
Self::deposit_event(RawEvent::Canceled(when, index));
Ok(())
} else {
@@ -842,11 +904,32 @@
}
}
- pub struct DummyExecutor; // todo do something with naming and function body
- impl<C: Dispatchable> ApplyExtrinsic<C> for DummyExecutor {
- fn apply_extrinsic(_signer: Address, _function: C) -> ApplyExtrinsicResult {
+ pub struct DummyExecutor;
+ impl<T: frame_system::Config + Config, SelfContainedSignedInfo>
+ DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor
+ {
+ type Pre = ();
+
+ fn dispatch_call(
+ _pre: Self::Pre,
+ _call: <T as Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
todo!()
}
+
+ fn pre_dispatch(
+ _signer: <T as frame_system::Config>::AccountId,
+ _call: <T as Config>::Call,
+ ) -> Result<Self::Pre, TransactionValidityError> {
+ todo!()
+ }
+
+ fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {
+ todo!()
+ }
}
parameter_types! {
@@ -898,7 +981,8 @@
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type SponsorshipHandler = ();
type WeightInfo = ();
- type Executor = DummyExecutor;
+ type CallExecutor = DummyExecutor;
}
}
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19use sp_runtime::DispatchError;20// #[cfg(any(feature = "std", test))]21// pub use sp_runtime::BuildStorage;2223use sp_runtime::{24 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,25 traits::{26 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use pallet_unq_scheduler::ApplyExtrinsic;58use up_data_structs::*;59// use pallet_contracts::weights::WeightInfo;60// #[cfg(any(feature = "std", test))]61use frame_system::{62 self as frame_system, EnsureRoot, EnsureSigned,63 limits::{BlockWeights, BlockLength},64};65use sp_arithmetic::{66 traits::{BaseArithmetic, Unsigned},67};68use smallvec::smallvec;69use codec::{Encode, Decode};70use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};71use fp_rpc::TransactionStatus;72use sp_core::crypto::Public;73use sp_runtime::{74 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},75 transaction_validity::TransactionValidityError,76};7778// pub use pallet_timestamp::Call as TimestampCall;79pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8081// Polkadot imports82use pallet_xcm::XcmPassthrough;83use polkadot_parachain::primitives::Sibling;84use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};85use xcm_builder::{86 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,87 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,88 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,89 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,90 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,91};92use xcm_executor::{Config, XcmExecutor};9394// mod chain_extension;95// use crate::chain_extension::{NFTExtension, Imbalance};9697/// An index to a block.98pub type BlockNumber = u32;99100/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.101pub type Signature = MultiSignature;102103/// Some way of identifying an account on the chain. We intentionally make it equivalent104/// to the public key of our transaction signing scheme.105pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;106107pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;108109/// The type for looking up accounts. We don't expect more than 4 billion of them, but you110/// never know...111pub type AccountIndex = u32;112113/// Balance of an account.114pub type Balance = u128;115116/// Index of a transaction in the chain.117pub type Index = u32;118119/// A hash of some data used by the chain.120pub type Hash = sp_core::H256;121122/// Digest item type.123pub type DigestItem = generic::DigestItem;124125/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know126/// the specifics of the runtime. They can then be made to be agnostic over specific formats127/// of data like extrinsics, allowing for them to continue syncing the network through upgrades128/// to even the core data structures.129pub mod opaque {130 use super::*;131132 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;133134 /// Opaque block type.135 pub type Block = generic::Block<Header, UncheckedExtrinsic>;136137 pub type SessionHandlers = ();138139 impl_opaque_keys! {140 pub struct SessionKeys {141 pub aura: Aura,142 }143 }144}145146/// This runtime version.147pub const VERSION: RuntimeVersion = RuntimeVersion {148 spec_name: create_runtime_str!("opal"),149 impl_name: create_runtime_str!("opal"),150 authoring_version: 1,151 spec_version: 914000,152 impl_version: 1,153 apis: RUNTIME_API_VERSIONS,154 transaction_version: 1,155};156157pub const MILLISECS_PER_BLOCK: u64 = 12000;158159pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;160161// These time units are defined in number of blocks.162pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);163pub const HOURS: BlockNumber = MINUTES * 60;164pub const DAYS: BlockNumber = HOURS * 24;165166parameter_types! {167 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;168}169170#[derive(codec::Encode, codec::Decode)]171pub enum XCMPMessage<XAccountId, XBalance> {172 /// Transfer tokens to the given account from the Parachain account.173 TransferToken(XAccountId, XBalance),174}175176/// The version information used to identify this runtime when compiled natively.177#[cfg(feature = "std")]178pub fn native_version() -> NativeVersion {179 NativeVersion {180 runtime_version: VERSION,181 can_author_with: Default::default(),182 }183}184185type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;186187pub struct DealWithFees;188impl OnUnbalanced<NegativeImbalance> for DealWithFees {189 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {190 if let Some(fees) = fees_then_tips.next() {191 // for fees, 100% to treasury192 let mut split = fees.ration(100, 0);193 if let Some(tips) = fees_then_tips.next() {194 // for tips, if any, 100% to treasury195 tips.ration_merge_into(100, 0, &mut split);196 }197 Treasury::on_unbalanced(split.0);198 // Author::on_unbalanced(split.1);199 }200 }201}202203/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.204/// This is used to limit the maximal weight of a single extrinsic.205const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);206/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used207/// by Operational extrinsics.208const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);209/// We allow for 2 seconds of compute with a 6 second average block time.210const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;211212parameter_types! {213 pub const BlockHashCount: BlockNumber = 2400;214 pub RuntimeBlockLength: BlockLength =215 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);216 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);217 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;218 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()219 .base_block(BlockExecutionWeight::get())220 .for_class(DispatchClass::all(), |weights| {221 weights.base_extrinsic = ExtrinsicBaseWeight::get();222 })223 .for_class(DispatchClass::Normal, |weights| {224 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);225 })226 .for_class(DispatchClass::Operational, |weights| {227 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);228 // Operational transactions have some extra reserved space, so that they229 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.230 weights.reserved = Some(231 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT232 );233 })234 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)235 .build_or_panic();236 pub const Version: RuntimeVersion = VERSION;237 pub const SS58Prefix: u8 = 42;238}239240parameter_types! {241 pub const ChainId: u64 = 8888;242}243244pub struct FixedFee;245impl FeeCalculator for FixedFee {246 fn min_gas_price() -> U256 {247 // Targeting 0.15 UNQ per transfer248 1_024_947_215_000u64.into()249 }250}251252// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case253// (contract, which only writes a lot of data),254// approximating on top of our real store write weight255parameter_types! {256 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;257 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;258 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();259}260261/// Limiting EVM execution to 50% of block for substrate users and management tasks262/// EVM transaction consumes more weight than substrate's, so we can't rely on them being263/// scheduled fairly264const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);265parameter_types! {266 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());267}268269pub enum FixedGasWeightMapping {}270impl GasWeightMapping for FixedGasWeightMapping {271 fn gas_to_weight(gas: u64) -> Weight {272 gas.saturating_mul(WeightPerGas::get())273 }274 fn weight_to_gas(weight: Weight) -> u64 {275 weight / WeightPerGas::get()276 }277}278279impl pallet_evm::Config for Runtime {280 type BlockGasLimit = BlockGasLimit;281 type FeeCalculator = FixedFee;282 type GasWeightMapping = FixedGasWeightMapping;283 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;284 type CallOrigin = EnsureAddressTruncated;285 type WithdrawOrigin = EnsureAddressTruncated;286 type AddressMapping = HashedAddressMapping<Self::Hashing>;287 type Precompiles = ();288 type Currency = Balances;289 type Event = Event;290 type OnMethodCall = (291 pallet_evm_migration::OnMethodCall<Self>,292 pallet_unique::UniqueErcSupport<Self>,293 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,294 );295 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;296 type ChainId = ChainId;297 type Runner = pallet_evm::runner::stack::Runner<Self>;298 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;299 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;300 type FindAuthor = EthereumFindAuthor<Aura>;301}302303impl pallet_evm_migration::Config for Runtime {304 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;305}306307pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);308impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {309 fn find_author<'a, I>(digests: I) -> Option<H160>310 where311 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,312 {313 if let Some(author_index) = F::find_author(digests) {314 let authority_id = Aura::authorities()[author_index as usize].clone();315 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));316 }317 None318 }319}320321impl pallet_ethereum::Config for Runtime {322 type Event = Event;323 type StateRoot = pallet_ethereum::IntermediateStateRoot;324}325326impl pallet_randomness_collective_flip::Config for Runtime {}327328impl frame_system::Config for Runtime {329 /// The data to be stored in an account.330 type AccountData = pallet_balances::AccountData<Balance>;331 /// The identifier used to distinguish between accounts.332 type AccountId = AccountId;333 /// The basic call filter to use in dispatchable.334 type BaseCallFilter = Everything;335 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).336 type BlockHashCount = BlockHashCount;337 /// The maximum length of a block (in bytes).338 type BlockLength = RuntimeBlockLength;339 /// The index type for blocks.340 type BlockNumber = BlockNumber;341 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.342 type BlockWeights = RuntimeBlockWeights;343 /// The aggregated dispatch type that is available for extrinsics.344 type Call = Call;345 /// The weight of database operations that the runtime can invoke.346 type DbWeight = RocksDbWeight;347 /// The ubiquitous event type.348 type Event = Event;349 /// The type for hashing blocks and tries.350 type Hash = Hash;351 /// The hashing algorithm used.352 type Hashing = BlakeTwo256;353 /// The header type.354 type Header = generic::Header<BlockNumber, BlakeTwo256>;355 /// The index type for storing how many extrinsics an account has signed.356 type Index = Index;357 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.358 type Lookup = AccountIdLookup<AccountId, ()>;359 /// What to do if an account is fully reaped from the system.360 type OnKilledAccount = ();361 /// What to do if a new account is created.362 type OnNewAccount = ();363 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;364 /// The ubiquitous origin type.365 type Origin = Origin;366 /// This type is being generated by `construct_runtime!`.367 type PalletInfo = PalletInfo;368 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.369 type SS58Prefix = SS58Prefix;370 /// Weight information for the extrinsics of this pallet.371 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;372 /// Version of the runtime.373 type Version = Version;374}375376parameter_types! {377 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;378}379380impl pallet_timestamp::Config for Runtime {381 /// A timestamp: milliseconds since the unix epoch.382 type Moment = u64;383 type OnTimestampSet = ();384 type MinimumPeriod = MinimumPeriod;385 type WeightInfo = ();386}387388parameter_types! {389 // pub const ExistentialDeposit: u128 = 500;390 pub const ExistentialDeposit: u128 = 0;391 pub const MaxLocks: u32 = 50;392}393394impl pallet_balances::Config for Runtime {395 type MaxLocks = MaxLocks;396 type MaxReserves = ();397 type ReserveIdentifier = [u8; 8];398 /// The type for recording an account's balance.399 type Balance = Balance;400 /// The ubiquitous event type.401 type Event = Event;402 type DustRemoval = Treasury;403 type ExistentialDeposit = ExistentialDeposit;404 type AccountStore = System;405 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;406}407408pub const MICROUNIQUE: Balance = 1_000_000_000_000;409pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;410pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;411pub const UNIQUE: Balance = 100 * CENTIUNIQUE;412413pub const fn deposit(items: u32, bytes: u32) -> Balance {414 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE415}416417/*418parameter_types! {419 pub TombstoneDeposit: Balance = deposit(420 1,421 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,422 );423 pub DepositPerContract: Balance = TombstoneDeposit::get();424 pub const DepositPerStorageByte: Balance = deposit(0, 1);425 pub const DepositPerStorageItem: Balance = deposit(1, 0);426 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);427 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;428 pub const SignedClaimHandicap: u32 = 2;429 pub const MaxDepth: u32 = 32;430 pub const MaxValueSize: u32 = 16 * 1024;431 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb432 // The lazy deletion runs inside on_initialize.433 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *434 RuntimeBlockWeights::get().max_block;435 // The weight needed for decoding the queue should be less or equal than a fifth436 // of the overall weight dedicated to the lazy deletion.437 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (438 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -439 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)440 )) / 5) as u32;441 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();442}443444impl pallet_contracts::Config for Runtime {445 type Time = Timestamp;446 type Randomness = RandomnessCollectiveFlip;447 type Currency = Balances;448 type Event = Event;449 type RentPayment = ();450 type SignedClaimHandicap = SignedClaimHandicap;451 type TombstoneDeposit = TombstoneDeposit;452 type DepositPerContract = DepositPerContract;453 type DepositPerStorageByte = DepositPerStorageByte;454 type DepositPerStorageItem = DepositPerStorageItem;455 type RentFraction = RentFraction;456 type SurchargeReward = SurchargeReward;457 type WeightPrice = pallet_transaction_payment::Pallet<Self>;458 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;459 type ChainExtension = NFTExtension;460 type DeletionQueueDepth = DeletionQueueDepth;461 type DeletionWeightLimit = DeletionWeightLimit;462 type Schedule = Schedule;463 type CallStack = [pallet_contracts::Frame<Self>; 31];464}465*/466467parameter_types! {468 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer469 /// This value increases the priority of `Operational` transactions by adding470 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.471 pub const OperationalFeeMultiplier: u8 = 5;472}473474/// Linear implementor of `WeightToFeePolynomial`475pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);476477impl<T> WeightToFeePolynomial for LinearFee<T>478where479 T: BaseArithmetic + From<u32> + Copy + Unsigned,480{481 type Balance = T;482483 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {484 smallvec!(WeightToFeeCoefficient {485 // Targeting 0.1 Unique per NFT transfer486 coeff_integer: 142_688_000u32.into(),487 coeff_frac: Perbill::zero(),488 negative: false,489 degree: 1,490 })491 }492}493494impl pallet_transaction_payment::Config for Runtime {495 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;496 type TransactionByteFee = TransactionByteFee;497 type OperationalFeeMultiplier = OperationalFeeMultiplier;498 type WeightToFee = LinearFee<Balance>;499 type FeeMultiplierUpdate = ();500}501502parameter_types! {503 pub const ProposalBond: Permill = Permill::from_percent(5);504 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;505 pub const SpendPeriod: BlockNumber = 5 * MINUTES;506 pub const Burn: Permill = Permill::from_percent(0);507 pub const TipCountdown: BlockNumber = 1 * DAYS;508 pub const TipFindersFee: Percent = Percent::from_percent(20);509 pub const TipReportDepositBase: Balance = 1 * UNIQUE;510 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;511 pub const BountyDepositBase: Balance = 1 * UNIQUE;512 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;513 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");514 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;515 pub const MaximumReasonLength: u32 = 16384;516 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);517 pub const BountyValueMinimum: Balance = 5 * UNIQUE;518 pub const MaxApprovals: u32 = 100;519}520521impl pallet_treasury::Config for Runtime {522 type PalletId = TreasuryModuleId;523 type Currency = Balances;524 type ApproveOrigin = EnsureRoot<AccountId>;525 type RejectOrigin = EnsureRoot<AccountId>;526 type Event = Event;527 type OnSlash = ();528 type ProposalBond = ProposalBond;529 type ProposalBondMinimum = ProposalBondMinimum;530 type SpendPeriod = SpendPeriod;531 type Burn = Burn;532 type BurnDestination = ();533 type SpendFunds = ();534 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;535 type MaxApprovals = MaxApprovals;536}537538impl pallet_sudo::Config for Runtime {539 type Event = Event;540 type Call = Call;541}542543pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);544545impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider546 for RelayChainBlockNumberProvider<T>547{548 type BlockNumber = BlockNumber;549550 fn current_block_number() -> Self::BlockNumber {551 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()552 .map(|d| d.relay_parent_number)553 .unwrap_or_default()554 }555}556557parameter_types! {558 pub const MinVestedTransfer: Balance = 10 * UNIQUE;559 pub const MaxVestingSchedules: u32 = 28;560}561562impl orml_vesting::Config for Runtime {563 type Event = Event;564 type Currency = pallet_balances::Pallet<Runtime>;565 type MinVestedTransfer = MinVestedTransfer;566 type VestedTransferOrigin = EnsureSigned<AccountId>;567 type WeightInfo = ();568 type MaxVestingSchedules = MaxVestingSchedules;569 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;570}571572parameter_types! {573 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;574 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;575}576577impl cumulus_pallet_parachain_system::Config for Runtime {578 type Event = Event;579 type OnValidationData = ();580 type SelfParaId = parachain_info::Pallet<Self>;581 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<582 // MaxDownwardMessageWeight,583 // XcmExecutor<XcmConfig>,584 // Call,585 // >;586 type OutboundXcmpMessageSource = XcmpQueue;587 type DmpMessageHandler = DmpQueue;588 type ReservedDmpWeight = ReservedDmpWeight;589 type ReservedXcmpWeight = ReservedXcmpWeight;590 type XcmpMessageHandler = XcmpQueue;591}592593impl parachain_info::Config for Runtime {}594595impl cumulus_pallet_aura_ext::Config for Runtime {}596597parameter_types! {598 pub const RelayLocation: MultiLocation = MultiLocation::parent();599 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;600 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();601 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();602}603604/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used605/// when determining ownership of accounts for asset transacting and when attempting to use XCM606/// `Transact` in order to determine the dispatch Origin.607pub type LocationToAccountId = (608 // The parent (Relay-chain) origin converts to the default `AccountId`.609 ParentIsDefault<AccountId>,610 // Sibling parachain origins convert to AccountId via the `ParaId::into`.611 SiblingParachainConvertsVia<Sibling, AccountId>,612 // Straight up local `AccountId32` origins just alias directly to `AccountId`.613 AccountId32Aliases<RelayNetwork, AccountId>,614);615616/// Means for transacting assets on this chain.617pub type LocalAssetTransactor = CurrencyAdapter<618 // Use this currency:619 Balances,620 // Use this currency when it is a fungible asset matching the given location or name:621 IsConcrete<RelayLocation>,622 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:623 LocationToAccountId,624 // Our chain's account ID type (we can't get away without mentioning it explicitly):625 AccountId,626 // We don't track any teleports.627 (),628>;629630/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,631/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can632/// biases the kind of local `Origin` it will become.633pub type XcmOriginToTransactDispatchOrigin = (634 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location635 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for636 // foreign chains who want to have a local sovereign account on this chain which they control.637 SovereignSignedViaLocation<LocationToAccountId, Origin>,638 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when639 // recognised.640 RelayChainAsNative<RelayOrigin, Origin>,641 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when642 // recognised.643 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,644 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a645 // transaction from the Root origin.646 ParentAsSuperuser<Origin>,647 // Native signed account converter; this just converts an `AccountId32` origin into a normal648 // `Origin::Signed` origin of the same 32-byte value.649 SignedAccountId32AsNative<RelayNetwork, Origin>,650 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.651 XcmPassthrough<Origin>,652);653654parameter_types! {655 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.656 pub UnitWeightCost: Weight = 1_000_000;657 // 1200 UNIQUEs buy 1 second of weight.658 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);659 pub const MaxInstructions: u32 = 100;660 pub const MaxAuthorities: u32 = 100_000;661}662663match_type! {664 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {665 MultiLocation { parents: 1, interior: Here } |666 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }667 };668}669670pub type Barrier = (671 TakeWeightCredit,672 AllowTopLevelPaidExecutionFrom<Everything>,673 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,674 // ^^^ Parent & its unit plurality gets free execution675);676677pub struct XcmConfig;678impl Config for XcmConfig {679 type Call = Call;680 type XcmSender = XcmRouter;681 // How to withdraw and deposit an asset.682 type AssetTransactor = LocalAssetTransactor;683 type OriginConverter = XcmOriginToTransactDispatchOrigin;684 type IsReserve = NativeAsset;685 type IsTeleporter = (); // Teleportation is disabled686 type LocationInverter = LocationInverter<Ancestry>;687 type Barrier = Barrier;688 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;689 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;690 type ResponseHandler = (); // Don't handle responses for now.691 type SubscriptionService = PolkadotXcm;692693 type AssetTrap = PolkadotXcm;694 type AssetClaims = PolkadotXcm;695}696697// parameter_types! {698// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;699// }700701/// No local origins on this chain are allowed to dispatch XCM sends/executions.702pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);703704/// The means for routing XCM messages which are not for local execution into the right message705/// queues.706pub type XcmRouter = (707 // Two routers - use UMP to communicate with the relay chain:708 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,709 // ..and XCMP to communicate with the sibling chains.710 XcmpQueue,711);712713impl pallet_evm_coder_substrate::Config for Runtime {714 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;715 type GasWeightMapping = FixedGasWeightMapping;716}717718impl pallet_xcm::Config for Runtime {719 type Event = Event;720 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;721 type XcmRouter = XcmRouter;722 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;723 type XcmExecuteFilter = Everything;724 type XcmExecutor = XcmExecutor<XcmConfig>;725 type XcmTeleportFilter = Everything;726 type XcmReserveTransferFilter = Everything;727 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;728 type LocationInverter = LocationInverter<Ancestry>;729 type Origin = Origin;730 type Call = Call;731 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;732 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;733}734735impl cumulus_pallet_xcm::Config for Runtime {736 type Event = Event;737 type XcmExecutor = XcmExecutor<XcmConfig>;738}739740impl cumulus_pallet_xcmp_queue::Config for Runtime {741 type Event = Event;742 type XcmExecutor = XcmExecutor<XcmConfig>;743 type ChannelInfo = ParachainSystem;744 type VersionWrapper = ();745}746747impl cumulus_pallet_dmp_queue::Config for Runtime {748 type Event = Event;749 type XcmExecutor = XcmExecutor<XcmConfig>;750 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;751}752753impl pallet_aura::Config for Runtime {754 type AuthorityId = AuraId;755 type DisabledValidators = ();756 type MaxAuthorities = MaxAuthorities;757}758759parameter_types! {760 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();761 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;762}763764impl pallet_common::Config for Runtime {765 type Event = Event;766 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;767 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;768 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;769770 type Currency = Balances;771 type CollectionCreationPrice = CollectionCreationPrice;772 type TreasuryAccountId = TreasuryAccountId;773}774775impl pallet_fungible::Config for Runtime {776 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;777}778impl pallet_refungible::Config for Runtime {779 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;780}781impl pallet_nonfungible::Config for Runtime {782 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;783}784785impl pallet_unique::Config for Runtime {786 type Event = Event;787 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;788}789790parameter_types! {791 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied792}793794/// Used for the pallet inflation795impl pallet_inflation::Config for Runtime {796 type Currency = Balances;797 type TreasuryAccountId = TreasuryAccountId;798 type InflationBlockInterval = InflationBlockInterval;799 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;800}801802parameter_types! {803 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *804 RuntimeBlockWeights::get().max_block;805 pub const MaxScheduledPerBlock: u32 = 50;806}807808type EvmSponsorshipHandler = (809 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,810 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,811);812type SponsorshipHandler = (813 pallet_unique::UniqueSponsorshipHandler<Runtime>,814 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,815 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,816);817818// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {819// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)820// }821822pub struct SchedulerPaymentExecutor;823impl<C: Dispatchable> ApplyExtrinsic<C> for SchedulerPaymentExecutor {824 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {825 /*let extrinsic = sign(fp_self_contained::CheckedExtrinsic {826 signed: fp_self_contained::CheckedSignature::SelfContained(None),827 function,828 });829830 Executive::apply_extrinsic(extrinsic)*/831 todo!()832 }833}834835impl pallet_unq_scheduler::Config for Runtime {836 type Event = Event;837 type Origin = Origin;838 type PalletsOrigin = OriginCaller;839 type Call = Call;840 type MaximumWeight = MaximumSchedulerWeight;841 type ScheduleOrigin = EnsureSigned<AccountId>;842 type MaxScheduledPerBlock = MaxScheduledPerBlock;843 type WeightInfo = ();844 type Executor = SchedulerPaymentExecutor;845}846847impl pallet_evm_transaction_payment::Config for Runtime {848 type EvmSponsorshipHandler = EvmSponsorshipHandler;849 type Currency = Balances;850 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;851 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;852}853854impl pallet_charge_transaction::Config for Runtime {855 type SponsorshipHandler = SponsorshipHandler;856}857858// impl pallet_contract_helpers::Config for Runtime {859// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;860// }861862parameter_types! {863 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049864 pub const HelpersContractAddress: H160 = H160([865 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,866 ]);867}868869impl pallet_evm_contract_helpers::Config for Runtime {870 type ContractAddress = HelpersContractAddress;871 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;872}873874construct_runtime!(875 pub enum Runtime where876 Block = Block,877 NodeBlock = opaque::Block,878 UncheckedExtrinsic = UncheckedExtrinsic879 {880 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,881 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,882883 Aura: pallet_aura::{Pallet, Config<T>} = 22,884 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,885886 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,887 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,888 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,889 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,890 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,891 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,892 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,893 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,894 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,895 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,896897 // XCM helpers.898 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,899 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,900 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,901 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,902903 // Unique Pallets904 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,905 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,906 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,907 // free = 63908 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,909 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,910 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,911 Fungible: pallet_fungible::{Pallet, Storage} = 67,912 Refungible: pallet_refungible::{Pallet, Storage} = 68,913 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,914915 // Frontier916 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,917 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,918919 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,920 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,921 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,922 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,923 }924);925926pub struct TransactionConverter;927928impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {929 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {930 UncheckedExtrinsic::new_unsigned(931 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),932 )933 }934}935936impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {937 fn convert_transaction(938 &self,939 transaction: pallet_ethereum::Transaction,940 ) -> opaque::UncheckedExtrinsic {941 let extrinsic = UncheckedExtrinsic::new_unsigned(942 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),943 );944 let encoded = extrinsic.encode();945 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])946 .expect("Encoded extrinsic is always valid")947 }948}949950/// The address format for describing accounts.951pub type Address = sp_runtime::MultiAddress<AccountId, ()>;952/// Block header type as expected by this runtime.953pub type Header = generic::Header<BlockNumber, BlakeTwo256>;954/// Block type as expected by this runtime.955pub type Block = generic::Block<Header, UncheckedExtrinsic>;956/// A Block signed with a Justification957pub type SignedBlock = generic::SignedBlock<Block>;958/// BlockId type as expected by this runtime.959pub type BlockId = generic::BlockId<Block>;960/// The SignedExtension to the basic transaction logic.961pub type SignedExtra = (962 frame_system::CheckSpecVersion<Runtime>,963 // system::CheckTxVersion<Runtime>,964 frame_system::CheckGenesis<Runtime>,965 frame_system::CheckEra<Runtime>,966 frame_system::CheckNonce<Runtime>,967 frame_system::CheckWeight<Runtime>,968 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,969 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,970);971/// Unchecked extrinsic type as expected by this runtime.972pub type UncheckedExtrinsic =973 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;974/// Extrinsic type that has already been checked.975pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;976/// Executive: handles dispatch to the various modules.977pub type Executive = frame_executive::Executive<978 Runtime,979 Block,980 frame_system::ChainContext<Runtime>,981 Runtime,982 AllPallets,983>;984985impl_opaque_keys! {986 pub struct SessionKeys {987 pub aura: Aura,988 }989}990991impl fp_self_contained::SelfContainedCall for Call {992 type SignedInfo = H160;993994 fn is_self_contained(&self) -> bool {995 match self {996 Call::Ethereum(call) => call.is_self_contained(),997 _ => false,998 }999 }10001001 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1002 match self {1003 Call::Ethereum(call) => call.check_self_contained(),1004 _ => None,1005 }1006 }10071008 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1009 match self {1010 Call::Ethereum(call) => call.validate_self_contained(info),1011 _ => None,1012 }1013 }10141015 fn pre_dispatch_self_contained(1016 &self,1017 info: &Self::SignedInfo,1018 ) -> Option<Result<(), TransactionValidityError>> {1019 match self {1020 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1021 _ => None,1022 }1023 }10241025 fn apply_self_contained(1026 self,1027 info: Self::SignedInfo,1028 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1029 match self {1030 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1031 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1032 )),1033 _ => None,1034 }1035 }1036}10371038macro_rules! dispatch_unique_runtime {1039 ($collection:ident.$method:ident($($name:ident),*)) => {{1040 use pallet_unique::dispatch::Dispatched;10411042 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1043 let dispatch = collection.as_dyn();10441045 Ok(dispatch.$method($($name),*))1046 }};1047}1048impl_runtime_apis! {1049 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1050 for Runtime1051 {1052 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1053 dispatch_unique_runtime!(collection.account_tokens(account))1054 }1055 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1056 dispatch_unique_runtime!(collection.token_exists(token))1057 }10581059 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId, DispatchError> {1060 dispatch_unique_runtime!(collection.token_owner(token))1061 }1062 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1063 dispatch_unique_runtime!(collection.const_metadata(token))1064 }1065 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1066 dispatch_unique_runtime!(collection.variable_metadata(token))1067 }10681069 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1070 dispatch_unique_runtime!(collection.collection_tokens())1071 }1072 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1073 dispatch_unique_runtime!(collection.account_balance(account))1074 }1075 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1076 dispatch_unique_runtime!(collection.balance(account, token))1077 }1078 fn allowance(1079 collection: CollectionId,1080 sender: CrossAccountId,1081 spender: CrossAccountId,1082 token: TokenId,1083 ) -> Result<u128, DispatchError> {1084 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1085 }10861087 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1088 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1089 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1090 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1091 }1092 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1093 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1094 }1095 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1096 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1097 }1098 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1099 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1100 }1101 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1102 dispatch_unique_runtime!(collection.last_token_id())1103 }1104 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1105 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1106 }1107 fn collection_stats() -> Result<CollectionStats, DispatchError> {1108 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1109 }1110 }11111112 impl sp_api::Core<Block> for Runtime {1113 fn version() -> RuntimeVersion {1114 VERSION1115 }11161117 fn execute_block(block: Block) {1118 Executive::execute_block(block)1119 }11201121 fn initialize_block(header: &<Block as BlockT>::Header) {1122 Executive::initialize_block(header)1123 }1124 }11251126 impl sp_api::Metadata<Block> for Runtime {1127 fn metadata() -> OpaqueMetadata {1128 OpaqueMetadata::new(Runtime::metadata().into())1129 }1130 }11311132 impl sp_block_builder::BlockBuilder<Block> for Runtime {1133 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1134 Executive::apply_extrinsic(extrinsic)1135 }11361137 fn finalize_block() -> <Block as BlockT>::Header {1138 Executive::finalize_block()1139 }11401141 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1142 data.create_extrinsics()1143 }11441145 fn check_inherents(1146 block: Block,1147 data: sp_inherents::InherentData,1148 ) -> sp_inherents::CheckInherentsResult {1149 data.check_extrinsics(&block)1150 }11511152 // fn random_seed() -> <Block as BlockT>::Hash {1153 // RandomnessCollectiveFlip::random_seed().01154 // }1155 }11561157 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1158 fn validate_transaction(1159 source: TransactionSource,1160 tx: <Block as BlockT>::Extrinsic,1161 hash: <Block as BlockT>::Hash,1162 ) -> TransactionValidity {1163 Executive::validate_transaction(source, tx, hash)1164 }1165 }11661167 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1168 fn offchain_worker(header: &<Block as BlockT>::Header) {1169 Executive::offchain_worker(header)1170 }1171 }11721173 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1174 fn chain_id() -> u64 {1175 <Runtime as pallet_evm::Config>::ChainId::get()1176 }11771178 fn account_basic(address: H160) -> EVMAccount {1179 EVM::account_basic(&address)1180 }11811182 fn gas_price() -> U256 {1183 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1184 }11851186 fn account_code_at(address: H160) -> Vec<u8> {1187 EVM::account_codes(address)1188 }11891190 fn author() -> H160 {1191 <pallet_evm::Pallet<Runtime>>::find_author()1192 }11931194 fn storage_at(address: H160, index: U256) -> H256 {1195 let mut tmp = [0u8; 32];1196 index.to_big_endian(&mut tmp);1197 EVM::account_storages(address, H256::from_slice(&tmp[..]))1198 }11991200 #[allow(clippy::redundant_closure)]1201 fn call(1202 from: H160,1203 to: H160,1204 data: Vec<u8>,1205 value: U256,1206 gas_limit: U256,1207 gas_price: Option<U256>,1208 nonce: Option<U256>,1209 estimate: bool,1210 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1211 let config = if estimate {1212 let mut config = <Runtime as pallet_evm::Config>::config().clone();1213 config.estimate = true;1214 Some(config)1215 } else {1216 None1217 };12181219 <Runtime as pallet_evm::Config>::Runner::call(1220 from,1221 to,1222 data,1223 value,1224 gas_limit.low_u64(),1225 gas_price,1226 nonce,1227 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1228 ).map_err(|err| err.into())1229 }12301231 #[allow(clippy::redundant_closure)]1232 fn create(1233 from: H160,1234 data: Vec<u8>,1235 value: U256,1236 gas_limit: U256,1237 gas_price: Option<U256>,1238 nonce: Option<U256>,1239 estimate: bool,1240 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1241 let config = if estimate {1242 let mut config = <Runtime as pallet_evm::Config>::config().clone();1243 config.estimate = true;1244 Some(config)1245 } else {1246 None1247 };12481249 <Runtime as pallet_evm::Config>::Runner::create(1250 from,1251 data,1252 value,1253 gas_limit.low_u64(),1254 gas_price,1255 nonce,1256 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1257 ).map_err(|err| err.into())1258 }12591260 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1261 Ethereum::current_transaction_statuses()1262 }12631264 fn current_block() -> Option<pallet_ethereum::Block> {1265 Ethereum::current_block()1266 }12671268 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1269 Ethereum::current_receipts()1270 }12711272 fn current_all() -> (1273 Option<pallet_ethereum::Block>,1274 Option<Vec<pallet_ethereum::Receipt>>,1275 Option<Vec<TransactionStatus>>1276 ) {1277 (1278 Ethereum::current_block(),1279 Ethereum::current_receipts(),1280 Ethereum::current_transaction_statuses()1281 )1282 }12831284 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1285 xts.into_iter().filter_map(|xt| match xt.0.function {1286 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1287 _ => None1288 }).collect()1289 }1290 }12911292 impl sp_session::SessionKeys<Block> for Runtime {1293 fn decode_session_keys(1294 encoded: Vec<u8>,1295 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1296 SessionKeys::decode_into_raw_public_keys(&encoded)1297 }12981299 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1300 SessionKeys::generate(seed)1301 }1302 }13031304 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1305 fn slot_duration() -> sp_consensus_aura::SlotDuration {1306 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1307 }13081309 fn authorities() -> Vec<AuraId> {1310 Aura::authorities().to_vec()1311 }1312 }13131314 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1315 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1316 ParachainSystem::collect_collation_info()1317 }1318 }13191320 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1321 fn account_nonce(account: AccountId) -> Index {1322 System::account_nonce(account)1323 }1324 }13251326 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1327 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1328 TransactionPayment::query_info(uxt, len)1329 }1330 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1331 TransactionPayment::query_fee_details(uxt, len)1332 }1333 }13341335 /*1336 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1337 for Runtime1338 {1339 fn call(1340 origin: AccountId,1341 dest: AccountId,1342 value: Balance,1343 gas_limit: u64,1344 input_data: Vec<u8>,1345 ) -> pallet_contracts_primitives::ContractExecResult {1346 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1347 }13481349 fn instantiate(1350 origin: AccountId,1351 endowment: Balance,1352 gas_limit: u64,1353 code: pallet_contracts_primitives::Code<Hash>,1354 data: Vec<u8>,1355 salt: Vec<u8>,1356 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1357 {1358 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1359 }13601361 fn get_storage(1362 address: AccountId,1363 key: [u8; 32],1364 ) -> pallet_contracts_primitives::GetStorageResult {1365 Contracts::get_storage(address, key)1366 }13671368 fn rent_projection(1369 address: AccountId,1370 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1371 Contracts::rent_projection(address)1372 }1373 }1374 */13751376 #[cfg(feature = "runtime-benchmarks")]1377 impl frame_benchmarking::Benchmark<Block> for Runtime {1378 fn benchmark_metadata(extra: bool) -> (1379 Vec<frame_benchmarking::BenchmarkList>,1380 Vec<frame_support::traits::StorageInfo>,1381 ) {1382 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1383 use frame_support::traits::StorageInfoTrait;13841385 let mut list = Vec::<BenchmarkList>::new();13861387 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1388 list_benchmark!(list, extra, pallet_unique, Unique);1389 list_benchmark!(list, extra, pallet_inflation, Inflation);1390 list_benchmark!(list, extra, pallet_fungible, Fungible);1391 list_benchmark!(list, extra, pallet_refungible, Refungible);1392 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1393 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);13941395 let storage_info = AllPalletsWithSystem::storage_info();13961397 return (list, storage_info)1398 }13991400 fn dispatch_benchmark(1401 config: frame_benchmarking::BenchmarkConfig1402 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1403 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};14041405 let allowlist: Vec<TrackedStorageKey> = vec![1406 // Block Number1407 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1408 // Total Issuance1409 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1410 // Execution Phase1411 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1412 // Event Count1413 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1414 // System Events1415 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1416 ];14171418 let mut batches = Vec::<BenchmarkBatch>::new();1419 let params = (&config, &allowlist);14201421 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1422 add_benchmark!(params, batches, pallet_unique, Unique);1423 add_benchmark!(params, batches, pallet_inflation, Inflation);1424 add_benchmark!(params, batches, pallet_fungible, Fungible);1425 add_benchmark!(params, batches, pallet_refungible, Refungible);1426 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1427 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);14281429 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1430 Ok(batches)1431 }1432 }1433}14341435struct CheckInherents;14361437impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1438 fn check_inherents(1439 block: &Block,1440 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1441 ) -> sp_inherents::CheckInherentsResult {1442 let relay_chain_slot = relay_state_proof1443 .read_slot()1444 .expect("Could not read the relay chain slot from the proof");14451446 let inherent_data =1447 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1448 relay_chain_slot,1449 sp_std::time::Duration::from_secs(6),1450 )1451 .create_inherent_data()1452 .expect("Could not create the timestamp inherent data");14531454 inherent_data.check_extrinsics(block)1455 }1456}14571458cumulus_pallet_parachain_system::register_validate_block!(1459 Runtime = Runtime,1460 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1461 CheckInherents = CheckInherents,1462);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19use sp_runtime::DispatchError;20use fp_self_contained::*;21use sp_runtime::traits::{SignedExtension, Member};22// #[cfg(any(feature = "std", test))]23// pub use sp_runtime::BuildStorage;2425use sp_runtime::{26 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,27 traits::{28 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,29 },30 transaction_validity::{TransactionSource, TransactionValidity},31 ApplyExtrinsicResult, MultiSignature,32};3334use sp_std::prelude::*;3536#[cfg(feature = "std")]37use sp_version::NativeVersion;38use sp_version::RuntimeVersion;39pub use pallet_transaction_payment::{40 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,41};42// A few exports that help ease life for downstream crates.43pub use pallet_balances::Call as BalancesCall;44pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};45pub use frame_support::{46 construct_runtime, match_type,47 dispatch::DispatchResult,48 PalletId, parameter_types, StorageValue, ConsensusEngineId,49 traits::{50 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,51 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,52 },53 weights::{54 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},55 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,56 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,57 },58};59use pallet_unq_scheduler::DispatchCall;60use up_data_structs::*;61// use pallet_contracts::weights::WeightInfo;62// #[cfg(any(feature = "std", test))]63use frame_system::{64 self as frame_system, EnsureRoot, EnsureSigned,65 limits::{BlockWeights, BlockLength},66};67use sp_arithmetic::{68 traits::{BaseArithmetic, Unsigned},69};70use smallvec::smallvec;71use scale_info::TypeInfo;72use codec::{Encode, Decode};73use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};74use fp_rpc::TransactionStatus;75use sp_core::crypto::Public;76use sp_runtime::{77 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},78 transaction_validity::TransactionValidityError,79 DispatchErrorWithPostInfo,80};8182// pub use pallet_timestamp::Call as TimestampCall;83pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8485// Polkadot imports86use pallet_xcm::XcmPassthrough;87use polkadot_parachain::primitives::Sibling;88use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};89use xcm_builder::{90 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,91 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,92 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,93 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,94 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,95};96use xcm_executor::{Config, XcmExecutor};9798// mod chain_extension;99// use crate::chain_extension::{NFTExtension, Imbalance};100101/// An index to a block.102pub type BlockNumber = u32;103104/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.105pub type Signature = MultiSignature;106107/// Some way of identifying an account on the chain. We intentionally make it equivalent108/// to the public key of our transaction signing scheme.109pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;110111pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;112113/// The type for looking up accounts. We don't expect more than 4 billion of them, but you114/// never know...115pub type AccountIndex = u32;116117/// Balance of an account.118pub type Balance = u128;119120/// Index of a transaction in the chain.121pub type Index = u32;122123/// A hash of some data used by the chain.124pub type Hash = sp_core::H256;125126/// Digest item type.127pub type DigestItem = generic::DigestItem;128129/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know130/// the specifics of the runtime. They can then be made to be agnostic over specific formats131/// of data like extrinsics, allowing for them to continue syncing the network through upgrades132/// to even the core data structures.133pub mod opaque {134 use super::*;135136 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;137138 /// Opaque block type.139 pub type Block = generic::Block<Header, UncheckedExtrinsic>;140141 pub type SessionHandlers = ();142143 impl_opaque_keys! {144 pub struct SessionKeys {145 pub aura: Aura,146 }147 }148}149150/// This runtime version.151pub const VERSION: RuntimeVersion = RuntimeVersion {152 spec_name: create_runtime_str!("opal"),153 impl_name: create_runtime_str!("opal"),154 authoring_version: 1,155 spec_version: 914000,156 impl_version: 1,157 apis: RUNTIME_API_VERSIONS,158 transaction_version: 1,159};160161pub const MILLISECS_PER_BLOCK: u64 = 12000;162163pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;164165// These time units are defined in number of blocks.166pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);167pub const HOURS: BlockNumber = MINUTES * 60;168pub const DAYS: BlockNumber = HOURS * 24;169170parameter_types! {171 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;172}173174#[derive(codec::Encode, codec::Decode)]175pub enum XCMPMessage<XAccountId, XBalance> {176 /// Transfer tokens to the given account from the Parachain account.177 TransferToken(XAccountId, XBalance),178}179180/// The version information used to identify this runtime when compiled natively.181#[cfg(feature = "std")]182pub fn native_version() -> NativeVersion {183 NativeVersion {184 runtime_version: VERSION,185 can_author_with: Default::default(),186 }187}188189type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;190191pub struct DealWithFees;192impl OnUnbalanced<NegativeImbalance> for DealWithFees {193 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {194 if let Some(fees) = fees_then_tips.next() {195 // for fees, 100% to treasury196 let mut split = fees.ration(100, 0);197 if let Some(tips) = fees_then_tips.next() {198 // for tips, if any, 100% to treasury199 tips.ration_merge_into(100, 0, &mut split);200 }201 Treasury::on_unbalanced(split.0);202 // Author::on_unbalanced(split.1);203 }204 }205}206207/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.208/// This is used to limit the maximal weight of a single extrinsic.209const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);210/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used211/// by Operational extrinsics.212const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);213/// We allow for 2 seconds of compute with a 6 second average block time.214const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;215216parameter_types! {217 pub const BlockHashCount: BlockNumber = 2400;218 pub RuntimeBlockLength: BlockLength =219 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);220 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);221 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;222 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()223 .base_block(BlockExecutionWeight::get())224 .for_class(DispatchClass::all(), |weights| {225 weights.base_extrinsic = ExtrinsicBaseWeight::get();226 })227 .for_class(DispatchClass::Normal, |weights| {228 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);229 })230 .for_class(DispatchClass::Operational, |weights| {231 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);232 // Operational transactions have some extra reserved space, so that they233 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.234 weights.reserved = Some(235 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT236 );237 })238 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)239 .build_or_panic();240 pub const Version: RuntimeVersion = VERSION;241 pub const SS58Prefix: u8 = 42;242}243244parameter_types! {245 pub const ChainId: u64 = 8888;246}247248pub struct FixedFee;249impl FeeCalculator for FixedFee {250 fn min_gas_price() -> U256 {251 // Targeting 0.15 UNQ per transfer252 1_024_947_215_000u64.into()253 }254}255256// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case257// (contract, which only writes a lot of data),258// approximating on top of our real store write weight259parameter_types! {260 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;261 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;262 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();263}264265/// Limiting EVM execution to 50% of block for substrate users and management tasks266/// EVM transaction consumes more weight than substrate's, so we can't rely on them being267/// scheduled fairly268const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);269parameter_types! {270 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());271}272273pub enum FixedGasWeightMapping {}274impl GasWeightMapping for FixedGasWeightMapping {275 fn gas_to_weight(gas: u64) -> Weight {276 gas.saturating_mul(WeightPerGas::get())277 }278 fn weight_to_gas(weight: Weight) -> u64 {279 weight / WeightPerGas::get()280 }281}282283impl pallet_evm::Config for Runtime {284 type BlockGasLimit = BlockGasLimit;285 type FeeCalculator = FixedFee;286 type GasWeightMapping = FixedGasWeightMapping;287 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;288 type CallOrigin = EnsureAddressTruncated;289 type WithdrawOrigin = EnsureAddressTruncated;290 type AddressMapping = HashedAddressMapping<Self::Hashing>;291 type Precompiles = ();292 type Currency = Balances;293 type Event = Event;294 type OnMethodCall = (295 pallet_evm_migration::OnMethodCall<Self>,296 pallet_unique::UniqueErcSupport<Self>,297 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,298 );299 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;300 type ChainId = ChainId;301 type Runner = pallet_evm::runner::stack::Runner<Self>;302 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;303 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;304 type FindAuthor = EthereumFindAuthor<Aura>;305}306307impl pallet_evm_migration::Config for Runtime {308 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;309}310311pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);312impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {313 fn find_author<'a, I>(digests: I) -> Option<H160>314 where315 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,316 {317 if let Some(author_index) = F::find_author(digests) {318 let authority_id = Aura::authorities()[author_index as usize].clone();319 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));320 }321 None322 }323}324325impl pallet_ethereum::Config for Runtime {326 type Event = Event;327 type StateRoot = pallet_ethereum::IntermediateStateRoot;328}329330impl pallet_randomness_collective_flip::Config for Runtime {}331332impl frame_system::Config for Runtime {333 /// The data to be stored in an account.334 type AccountData = pallet_balances::AccountData<Balance>;335 /// The identifier used to distinguish between accounts.336 type AccountId = AccountId;337 /// The basic call filter to use in dispatchable.338 type BaseCallFilter = Everything;339 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).340 type BlockHashCount = BlockHashCount;341 /// The maximum length of a block (in bytes).342 type BlockLength = RuntimeBlockLength;343 /// The index type for blocks.344 type BlockNumber = BlockNumber;345 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.346 type BlockWeights = RuntimeBlockWeights;347 /// The aggregated dispatch type that is available for extrinsics.348 type Call = Call;349 /// The weight of database operations that the runtime can invoke.350 type DbWeight = RocksDbWeight;351 /// The ubiquitous event type.352 type Event = Event;353 /// The type for hashing blocks and tries.354 type Hash = Hash;355 /// The hashing algorithm used.356 type Hashing = BlakeTwo256;357 /// The header type.358 type Header = generic::Header<BlockNumber, BlakeTwo256>;359 /// The index type for storing how many extrinsics an account has signed.360 type Index = Index;361 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.362 type Lookup = AccountIdLookup<AccountId, ()>;363 /// What to do if an account is fully reaped from the system.364 type OnKilledAccount = ();365 /// What to do if a new account is created.366 type OnNewAccount = ();367 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;368 /// The ubiquitous origin type.369 type Origin = Origin;370 /// This type is being generated by `construct_runtime!`.371 type PalletInfo = PalletInfo;372 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.373 type SS58Prefix = SS58Prefix;374 /// Weight information for the extrinsics of this pallet.375 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;376 /// Version of the runtime.377 type Version = Version;378}379380parameter_types! {381 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;382}383384impl pallet_timestamp::Config for Runtime {385 /// A timestamp: milliseconds since the unix epoch.386 type Moment = u64;387 type OnTimestampSet = ();388 type MinimumPeriod = MinimumPeriod;389 type WeightInfo = ();390}391392parameter_types! {393 // pub const ExistentialDeposit: u128 = 500;394 pub const ExistentialDeposit: u128 = 0;395 pub const MaxLocks: u32 = 50;396}397398impl pallet_balances::Config for Runtime {399 type MaxLocks = MaxLocks;400 type MaxReserves = ();401 type ReserveIdentifier = [u8; 8];402 /// The type for recording an account's balance.403 type Balance = Balance;404 /// The ubiquitous event type.405 type Event = Event;406 type DustRemoval = Treasury;407 type ExistentialDeposit = ExistentialDeposit;408 type AccountStore = System;409 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;410}411412pub const MICROUNIQUE: Balance = 1_000_000_000_000;413pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;414pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;415pub const UNIQUE: Balance = 100 * CENTIUNIQUE;416417pub const fn deposit(items: u32, bytes: u32) -> Balance {418 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE419}420421/*422parameter_types! {423 pub TombstoneDeposit: Balance = deposit(424 1,425 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,426 );427 pub DepositPerContract: Balance = TombstoneDeposit::get();428 pub const DepositPerStorageByte: Balance = deposit(0, 1);429 pub const DepositPerStorageItem: Balance = deposit(1, 0);430 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);431 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;432 pub const SignedClaimHandicap: u32 = 2;433 pub const MaxDepth: u32 = 32;434 pub const MaxValueSize: u32 = 16 * 1024;435 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb436 // The lazy deletion runs inside on_initialize.437 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *438 RuntimeBlockWeights::get().max_block;439 // The weight needed for decoding the queue should be less or equal than a fifth440 // of the overall weight dedicated to the lazy deletion.441 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (442 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -443 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)444 )) / 5) as u32;445 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();446}447448impl pallet_contracts::Config for Runtime {449 type Time = Timestamp;450 type Randomness = RandomnessCollectiveFlip;451 type Currency = Balances;452 type Event = Event;453 type RentPayment = ();454 type SignedClaimHandicap = SignedClaimHandicap;455 type TombstoneDeposit = TombstoneDeposit;456 type DepositPerContract = DepositPerContract;457 type DepositPerStorageByte = DepositPerStorageByte;458 type DepositPerStorageItem = DepositPerStorageItem;459 type RentFraction = RentFraction;460 type SurchargeReward = SurchargeReward;461 type WeightPrice = pallet_transaction_payment::Pallet<Self>;462 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;463 type ChainExtension = NFTExtension;464 type DeletionQueueDepth = DeletionQueueDepth;465 type DeletionWeightLimit = DeletionWeightLimit;466 type Schedule = Schedule;467 type CallStack = [pallet_contracts::Frame<Self>; 31];468}469*/470471parameter_types! {472 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer473 /// This value increases the priority of `Operational` transactions by adding474 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.475 pub const OperationalFeeMultiplier: u8 = 5;476}477478/// Linear implementor of `WeightToFeePolynomial`479pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);480481impl<T> WeightToFeePolynomial for LinearFee<T>482where483 T: BaseArithmetic + From<u32> + Copy + Unsigned,484{485 type Balance = T;486487 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {488 smallvec!(WeightToFeeCoefficient {489 // Targeting 0.1 Unique per NFT transfer490 coeff_integer: 142_688_000u32.into(),491 coeff_frac: Perbill::zero(),492 negative: false,493 degree: 1,494 })495 }496}497498impl pallet_transaction_payment::Config for Runtime {499 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;500 type TransactionByteFee = TransactionByteFee;501 type OperationalFeeMultiplier = OperationalFeeMultiplier;502 type WeightToFee = LinearFee<Balance>;503 type FeeMultiplierUpdate = ();504}505506parameter_types! {507 pub const ProposalBond: Permill = Permill::from_percent(5);508 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;509 pub const SpendPeriod: BlockNumber = 5 * MINUTES;510 pub const Burn: Permill = Permill::from_percent(0);511 pub const TipCountdown: BlockNumber = 1 * DAYS;512 pub const TipFindersFee: Percent = Percent::from_percent(20);513 pub const TipReportDepositBase: Balance = 1 * UNIQUE;514 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;515 pub const BountyDepositBase: Balance = 1 * UNIQUE;516 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;517 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");518 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;519 pub const MaximumReasonLength: u32 = 16384;520 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);521 pub const BountyValueMinimum: Balance = 5 * UNIQUE;522 pub const MaxApprovals: u32 = 100;523}524525impl pallet_treasury::Config for Runtime {526 type PalletId = TreasuryModuleId;527 type Currency = Balances;528 type ApproveOrigin = EnsureRoot<AccountId>;529 type RejectOrigin = EnsureRoot<AccountId>;530 type Event = Event;531 type OnSlash = ();532 type ProposalBond = ProposalBond;533 type ProposalBondMinimum = ProposalBondMinimum;534 type SpendPeriod = SpendPeriod;535 type Burn = Burn;536 type BurnDestination = ();537 type SpendFunds = ();538 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;539 type MaxApprovals = MaxApprovals;540}541542impl pallet_sudo::Config for Runtime {543 type Event = Event;544 type Call = Call;545}546547pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);548549impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider550 for RelayChainBlockNumberProvider<T>551{552 type BlockNumber = BlockNumber;553554 fn current_block_number() -> Self::BlockNumber {555 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()556 .map(|d| d.relay_parent_number)557 .unwrap_or_default()558 }559}560561parameter_types! {562 pub const MinVestedTransfer: Balance = 10 * UNIQUE;563 pub const MaxVestingSchedules: u32 = 28;564}565566impl orml_vesting::Config for Runtime {567 type Event = Event;568 type Currency = pallet_balances::Pallet<Runtime>;569 type MinVestedTransfer = MinVestedTransfer;570 type VestedTransferOrigin = EnsureSigned<AccountId>;571 type WeightInfo = ();572 type MaxVestingSchedules = MaxVestingSchedules;573 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;574}575576parameter_types! {577 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;578 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;579}580581impl cumulus_pallet_parachain_system::Config for Runtime {582 type Event = Event;583 type OnValidationData = ();584 type SelfParaId = parachain_info::Pallet<Self>;585 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<586 // MaxDownwardMessageWeight,587 // XcmExecutor<XcmConfig>,588 // Call,589 // >;590 type OutboundXcmpMessageSource = XcmpQueue;591 type DmpMessageHandler = DmpQueue;592 type ReservedDmpWeight = ReservedDmpWeight;593 type ReservedXcmpWeight = ReservedXcmpWeight;594 type XcmpMessageHandler = XcmpQueue;595}596597impl parachain_info::Config for Runtime {}598599impl cumulus_pallet_aura_ext::Config for Runtime {}600601parameter_types! {602 pub const RelayLocation: MultiLocation = MultiLocation::parent();603 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;604 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();605 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();606}607608/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used609/// when determining ownership of accounts for asset transacting and when attempting to use XCM610/// `Transact` in order to determine the dispatch Origin.611pub type LocationToAccountId = (612 // The parent (Relay-chain) origin converts to the default `AccountId`.613 ParentIsDefault<AccountId>,614 // Sibling parachain origins convert to AccountId via the `ParaId::into`.615 SiblingParachainConvertsVia<Sibling, AccountId>,616 // Straight up local `AccountId32` origins just alias directly to `AccountId`.617 AccountId32Aliases<RelayNetwork, AccountId>,618);619620/// Means for transacting assets on this chain.621pub type LocalAssetTransactor = CurrencyAdapter<622 // Use this currency:623 Balances,624 // Use this currency when it is a fungible asset matching the given location or name:625 IsConcrete<RelayLocation>,626 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:627 LocationToAccountId,628 // Our chain's account ID type (we can't get away without mentioning it explicitly):629 AccountId,630 // We don't track any teleports.631 (),632>;633634/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,635/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can636/// biases the kind of local `Origin` it will become.637pub type XcmOriginToTransactDispatchOrigin = (638 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location639 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for640 // foreign chains who want to have a local sovereign account on this chain which they control.641 SovereignSignedViaLocation<LocationToAccountId, Origin>,642 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when643 // recognised.644 RelayChainAsNative<RelayOrigin, Origin>,645 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when646 // recognised.647 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,648 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a649 // transaction from the Root origin.650 ParentAsSuperuser<Origin>,651 // Native signed account converter; this just converts an `AccountId32` origin into a normal652 // `Origin::Signed` origin of the same 32-byte value.653 SignedAccountId32AsNative<RelayNetwork, Origin>,654 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.655 XcmPassthrough<Origin>,656);657658parameter_types! {659 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.660 pub UnitWeightCost: Weight = 1_000_000;661 // 1200 UNIQUEs buy 1 second of weight.662 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);663 pub const MaxInstructions: u32 = 100;664 pub const MaxAuthorities: u32 = 100_000;665}666667match_type! {668 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {669 MultiLocation { parents: 1, interior: Here } |670 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }671 };672}673674pub type Barrier = (675 TakeWeightCredit,676 AllowTopLevelPaidExecutionFrom<Everything>,677 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,678 // ^^^ Parent & its unit plurality gets free execution679);680681pub struct XcmConfig;682impl Config for XcmConfig {683 type Call = Call;684 type XcmSender = XcmRouter;685 // How to withdraw and deposit an asset.686 type AssetTransactor = LocalAssetTransactor;687 type OriginConverter = XcmOriginToTransactDispatchOrigin;688 type IsReserve = NativeAsset;689 type IsTeleporter = (); // Teleportation is disabled690 type LocationInverter = LocationInverter<Ancestry>;691 type Barrier = Barrier;692 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;693 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;694 type ResponseHandler = (); // Don't handle responses for now.695 type SubscriptionService = PolkadotXcm;696697 type AssetTrap = PolkadotXcm;698 type AssetClaims = PolkadotXcm;699}700701// parameter_types! {702// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;703// }704705/// No local origins on this chain are allowed to dispatch XCM sends/executions.706pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);707708/// The means for routing XCM messages which are not for local execution into the right message709/// queues.710pub type XcmRouter = (711 // Two routers - use UMP to communicate with the relay chain:712 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,713 // ..and XCMP to communicate with the sibling chains.714 XcmpQueue,715);716717impl pallet_evm_coder_substrate::Config for Runtime {718 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;719 type GasWeightMapping = FixedGasWeightMapping;720}721722impl pallet_xcm::Config for Runtime {723 type Event = Event;724 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;725 type XcmRouter = XcmRouter;726 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;727 type XcmExecuteFilter = Everything;728 type XcmExecutor = XcmExecutor<XcmConfig>;729 type XcmTeleportFilter = Everything;730 type XcmReserveTransferFilter = Everything;731 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;732 type LocationInverter = LocationInverter<Ancestry>;733 type Origin = Origin;734 type Call = Call;735 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;736 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;737}738739impl cumulus_pallet_xcm::Config for Runtime {740 type Event = Event;741 type XcmExecutor = XcmExecutor<XcmConfig>;742}743744impl cumulus_pallet_xcmp_queue::Config for Runtime {745 type Event = Event;746 type XcmExecutor = XcmExecutor<XcmConfig>;747 type ChannelInfo = ParachainSystem;748 type VersionWrapper = ();749}750751impl cumulus_pallet_dmp_queue::Config for Runtime {752 type Event = Event;753 type XcmExecutor = XcmExecutor<XcmConfig>;754 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;755}756757impl pallet_aura::Config for Runtime {758 type AuthorityId = AuraId;759 type DisabledValidators = ();760 type MaxAuthorities = MaxAuthorities;761}762763parameter_types! {764 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();765 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;766}767768impl pallet_common::Config for Runtime {769 type Event = Event;770 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;771 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;772 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;773774 type Currency = Balances;775 type CollectionCreationPrice = CollectionCreationPrice;776 type TreasuryAccountId = TreasuryAccountId;777}778779impl pallet_fungible::Config for Runtime {780 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;781}782impl pallet_refungible::Config for Runtime {783 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;784}785impl pallet_nonfungible::Config for Runtime {786 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;787}788789impl pallet_unique::Config for Runtime {790 type Event = Event;791 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;792}793794parameter_types! {795 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied796}797798/// Used for the pallet inflation799impl pallet_inflation::Config for Runtime {800 type Currency = Balances;801 type TreasuryAccountId = TreasuryAccountId;802 type InflationBlockInterval = InflationBlockInterval;803 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;804}805806parameter_types! {807 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *808 RuntimeBlockWeights::get().max_block;809 pub const MaxScheduledPerBlock: u32 = 50;810}811812type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;813814/*fn get_signed_extra(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {815 (816 frame_system::CheckSpecVersion::<Runtime>::new(),817 frame_system::CheckGenesis::<Runtime>::new(),818 frame_system::CheckEra::<Runtime>::from(Era::Immortal),819 frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(820 from,821 )),822 frame_system::CheckWeight::<Runtime>::new(),823 ChargeTransactionPayment::new(0),824 )825}*/826827#[derive(Default, Encode, Decode, Clone, TypeInfo)]828pub struct SchedulerPreDispatch {829 tip: Balance,830 signer: AccountId,831 fee: Option<Balance>,832}833834pub struct SchedulerPaymentExecutor;835impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>836 DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor837where838 <T as frame_system::Config>::Call: Member839 + Dispatchable<Origin = Origin, Info = DispatchInfo>840 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>841 + GetDispatchInfo842 + From<frame_system::Call<Runtime>>,843 SelfContainedSignedInfo: Send + Sync + 'static,844 Call: From<<T as frame_system::Config>::Call>845 + From<<T as pallet_unq_scheduler::Config>::Call>846 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,847 sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,848{849 type Pre = SchedulerPreDispatch;850851 fn dispatch_call(852 //signer: <T as frame_system::Config>::AccountId,853 pre_dispatch: Self::Pre,854 call: <T as pallet_unq_scheduler::Config>::Call,855 ) -> Result<856 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,857 TransactionValidityError,858 > {859 /*let dispatch_info = call.get_dispatch_info();860861 let extrinsic = fp_self_contained::CheckedExtrinsic::<862 AccountId,863 Call,864 SignedExtra,865 SelfContainedSignedInfo,866 > {867 signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(868 signer.clone().into(),869 get_signed_extra(signer.clone().into()),870 ),871 function: call.clone().into(),872 };873874 extrinsic.apply::<Runtime>(&dispatch_info, 0)*/875 let dispatch_info = call.get_dispatch_info();876 let pre = (877 pre_dispatch.tip,878 pre_dispatch.signer.clone().into(),879 pre_dispatch.fee.map(|fee| NegativeImbalance::new(fee)),880 );881882 let maybe_who = Some(pre_dispatch.signer.clone().into());883 let res = Call::from(call.clone()).dispatch(Origin::from(maybe_who));884 let post_info = match res {885 Ok(dispatch_info) => dispatch_info,886 Err(err) => err.post_info,887 };888 SignedExtra::post_dispatch(889 ((), (), (), (), (), pre),890 &dispatch_info,891 &post_info,892 0,893 &res.map(|_| ()).map_err(|e| e.error),894 )?;895 Ok(res)896 }897898 fn pre_dispatch(899 signer: <T as frame_system::Config>::AccountId,900 call: <T as pallet_unq_scheduler::Config>::Call,901 ) -> Result<Self::Pre, TransactionValidityError> {902 let dispatch_info = call.get_dispatch_info();903 //<T as Config>::OnChargeTransaction::withdraw_fee();904 let fee_charger = ChargeTransactionPayment::new(905 // Linear scaling of the fee tip if the priority is high enough906 0, //if priority > HARD_DEADLINE { 0 } else { (HARD_DEADLINE - priority + 1) / HARD_DEADLINE * PRIORITY_TIP_MULTIPLIER * total_fee }907 );908 let pre = fee_charger.pre_dispatch(&signer.into(), &call.into(), &dispatch_info, 0)?;909910 Ok(SchedulerPreDispatch {911 tip: pre.0,912 signer: pre.1,913 fee: pre.2.map(|imbalance| imbalance.peek()),914 })915 }916917 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError> {918 todo!()919 // simply call post_dispatch with 0 actual fee and the whole remaining, already withdrawn, fee920 }921}922923impl pallet_unq_scheduler::Config for Runtime {924 type Event = Event;925 type Origin = Origin;926 type PalletsOrigin = OriginCaller;927 type Call = Call;928 type MaximumWeight = MaximumSchedulerWeight;929 type ScheduleOrigin = EnsureSigned<AccountId>;930 type MaxScheduledPerBlock = MaxScheduledPerBlock;931 type SponsorshipHandler = SponsorshipHandler;932 type WeightInfo = ();933 type CallExecutor = SchedulerPaymentExecutor;934}935936type EvmSponsorshipHandler = (937 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,938 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,939);940941type SponsorshipHandler = (942 pallet_unique::UniqueSponsorshipHandler<Runtime>,943 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,944 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,945);946947impl pallet_evm_transaction_payment::Config for Runtime {948 type EvmSponsorshipHandler = EvmSponsorshipHandler;949 type Currency = Balances;950 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;951 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;952}953954impl pallet_charge_transaction::Config for Runtime {955 type SponsorshipHandler = SponsorshipHandler;956}957958// impl pallet_contract_helpers::Config for Runtime {959// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;960// }961962parameter_types! {963 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049964 pub const HelpersContractAddress: H160 = H160([965 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,966 ]);967}968969impl pallet_evm_contract_helpers::Config for Runtime {970 type ContractAddress = HelpersContractAddress;971 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;972}973974construct_runtime!(975 pub enum Runtime where976 Block = Block,977 NodeBlock = opaque::Block,978 UncheckedExtrinsic = UncheckedExtrinsic979 {980 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,981 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,982983 Aura: pallet_aura::{Pallet, Config<T>} = 22,984 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,985986 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,987 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,988 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,989 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,990 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,991 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,992 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,993 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,994 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,995 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,996997 // XCM helpers.998 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,999 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1000 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1001 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10021003 // Unique Pallets1004 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1005 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1006 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1007 // free = 631008 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1009 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1010 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1011 Fungible: pallet_fungible::{Pallet, Storage} = 67,1012 Refungible: pallet_refungible::{Pallet, Storage} = 68,1013 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,10141015 // Frontier1016 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1017 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10181019 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1020 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1021 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1022 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1023 }1024);10251026pub struct TransactionConverter;10271028impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1029 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1030 UncheckedExtrinsic::new_unsigned(1031 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1032 )1033 }1034}10351036impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1037 fn convert_transaction(1038 &self,1039 transaction: pallet_ethereum::Transaction,1040 ) -> opaque::UncheckedExtrinsic {1041 let extrinsic = UncheckedExtrinsic::new_unsigned(1042 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1043 );1044 let encoded = extrinsic.encode();1045 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1046 .expect("Encoded extrinsic is always valid")1047 }1048}10491050/// The address format for describing accounts.1051pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1052/// Block header type as expected by this runtime.1053pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1054/// Block type as expected by this runtime.1055pub type Block = generic::Block<Header, UncheckedExtrinsic>;1056/// A Block signed with a Justification1057pub type SignedBlock = generic::SignedBlock<Block>;1058/// BlockId type as expected by this runtime.1059pub type BlockId = generic::BlockId<Block>;1060/// The SignedExtension to the basic transaction logic.1061pub type SignedExtra = (1062 frame_system::CheckSpecVersion<Runtime>,1063 // system::CheckTxVersion<Runtime>,1064 frame_system::CheckGenesis<Runtime>,1065 frame_system::CheckEra<Runtime>,1066 frame_system::CheckNonce<Runtime>,1067 frame_system::CheckWeight<Runtime>,1068 ChargeTransactionPayment,1069 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1070);1071/// Unchecked extrinsic type as expected by this runtime.1072pub type UncheckedExtrinsic =1073 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1074/// Extrinsic type that has already been checked.1075pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1076/// Executive: handles dispatch to the various modules.1077pub type Executive = frame_executive::Executive<1078 Runtime,1079 Block,1080 frame_system::ChainContext<Runtime>,1081 Runtime,1082 AllPallets,1083>;10841085impl_opaque_keys! {1086 pub struct SessionKeys {1087 pub aura: Aura,1088 }1089}10901091impl fp_self_contained::SelfContainedCall for Call {1092 type SignedInfo = H160;10931094 fn is_self_contained(&self) -> bool {1095 match self {1096 Call::Ethereum(call) => call.is_self_contained(),1097 _ => false,1098 }1099 }11001101 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1102 match self {1103 Call::Ethereum(call) => call.check_self_contained(),1104 _ => None,1105 }1106 }11071108 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1109 match self {1110 Call::Ethereum(call) => call.validate_self_contained(info),1111 _ => None,1112 }1113 }11141115 fn pre_dispatch_self_contained(1116 &self,1117 info: &Self::SignedInfo,1118 ) -> Option<Result<(), TransactionValidityError>> {1119 match self {1120 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1121 _ => None,1122 }1123 }11241125 fn apply_self_contained(1126 self,1127 info: Self::SignedInfo,1128 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1129 match self {1130 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1131 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1132 )),1133 _ => None,1134 }1135 }1136}11371138macro_rules! dispatch_unique_runtime {1139 ($collection:ident.$method:ident($($name:ident),*)) => {{1140 use pallet_unique::dispatch::Dispatched;11411142 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1143 let dispatch = collection.as_dyn();11441145 Ok(dispatch.$method($($name),*))1146 }};1147}1148impl_runtime_apis! {1149 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1150 for Runtime1151 {1152 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1153 dispatch_unique_runtime!(collection.account_tokens(account))1154 }1155 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1156 dispatch_unique_runtime!(collection.token_exists(token))1157 }11581159 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId, DispatchError> {1160 dispatch_unique_runtime!(collection.token_owner(token))1161 }1162 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1163 dispatch_unique_runtime!(collection.const_metadata(token))1164 }1165 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1166 dispatch_unique_runtime!(collection.variable_metadata(token))1167 }11681169 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1170 dispatch_unique_runtime!(collection.collection_tokens())1171 }1172 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1173 dispatch_unique_runtime!(collection.account_balance(account))1174 }1175 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1176 dispatch_unique_runtime!(collection.balance(account, token))1177 }1178 fn allowance(1179 collection: CollectionId,1180 sender: CrossAccountId,1181 spender: CrossAccountId,1182 token: TokenId,1183 ) -> Result<u128, DispatchError> {1184 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1185 }11861187 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1188 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1189 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1190 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1191 }1192 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1193 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1194 }1195 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1196 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1197 }1198 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1199 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1200 }1201 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1202 dispatch_unique_runtime!(collection.last_token_id())1203 }1204 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1205 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1206 }1207 fn collection_stats() -> Result<CollectionStats, DispatchError> {1208 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1209 }1210 }12111212 impl sp_api::Core<Block> for Runtime {1213 fn version() -> RuntimeVersion {1214 VERSION1215 }12161217 fn execute_block(block: Block) {1218 Executive::execute_block(block)1219 }12201221 fn initialize_block(header: &<Block as BlockT>::Header) {1222 Executive::initialize_block(header)1223 }1224 }12251226 impl sp_api::Metadata<Block> for Runtime {1227 fn metadata() -> OpaqueMetadata {1228 OpaqueMetadata::new(Runtime::metadata().into())1229 }1230 }12311232 impl sp_block_builder::BlockBuilder<Block> for Runtime {1233 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1234 Executive::apply_extrinsic(extrinsic)1235 }12361237 fn finalize_block() -> <Block as BlockT>::Header {1238 Executive::finalize_block()1239 }12401241 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1242 data.create_extrinsics()1243 }12441245 fn check_inherents(1246 block: Block,1247 data: sp_inherents::InherentData,1248 ) -> sp_inherents::CheckInherentsResult {1249 data.check_extrinsics(&block)1250 }12511252 // fn random_seed() -> <Block as BlockT>::Hash {1253 // RandomnessCollectiveFlip::random_seed().01254 // }1255 }12561257 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1258 fn validate_transaction(1259 source: TransactionSource,1260 tx: <Block as BlockT>::Extrinsic,1261 hash: <Block as BlockT>::Hash,1262 ) -> TransactionValidity {1263 Executive::validate_transaction(source, tx, hash)1264 }1265 }12661267 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1268 fn offchain_worker(header: &<Block as BlockT>::Header) {1269 Executive::offchain_worker(header)1270 }1271 }12721273 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1274 fn chain_id() -> u64 {1275 <Runtime as pallet_evm::Config>::ChainId::get()1276 }12771278 fn account_basic(address: H160) -> EVMAccount {1279 EVM::account_basic(&address)1280 }12811282 fn gas_price() -> U256 {1283 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1284 }12851286 fn account_code_at(address: H160) -> Vec<u8> {1287 EVM::account_codes(address)1288 }12891290 fn author() -> H160 {1291 <pallet_evm::Pallet<Runtime>>::find_author()1292 }12931294 fn storage_at(address: H160, index: U256) -> H256 {1295 let mut tmp = [0u8; 32];1296 index.to_big_endian(&mut tmp);1297 EVM::account_storages(address, H256::from_slice(&tmp[..]))1298 }12991300 #[allow(clippy::redundant_closure)]1301 fn call(1302 from: H160,1303 to: H160,1304 data: Vec<u8>,1305 value: U256,1306 gas_limit: U256,1307 gas_price: Option<U256>,1308 nonce: Option<U256>,1309 estimate: bool,1310 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1311 let config = if estimate {1312 let mut config = <Runtime as pallet_evm::Config>::config().clone();1313 config.estimate = true;1314 Some(config)1315 } else {1316 None1317 };13181319 <Runtime as pallet_evm::Config>::Runner::call(1320 from,1321 to,1322 data,1323 value,1324 gas_limit.low_u64(),1325 gas_price,1326 nonce,1327 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1328 ).map_err(|err| err.into())1329 }13301331 #[allow(clippy::redundant_closure)]1332 fn create(1333 from: H160,1334 data: Vec<u8>,1335 value: U256,1336 gas_limit: U256,1337 gas_price: Option<U256>,1338 nonce: Option<U256>,1339 estimate: bool,1340 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1341 let config = if estimate {1342 let mut config = <Runtime as pallet_evm::Config>::config().clone();1343 config.estimate = true;1344 Some(config)1345 } else {1346 None1347 };13481349 <Runtime as pallet_evm::Config>::Runner::create(1350 from,1351 data,1352 value,1353 gas_limit.low_u64(),1354 gas_price,1355 nonce,1356 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1357 ).map_err(|err| err.into())1358 }13591360 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1361 Ethereum::current_transaction_statuses()1362 }13631364 fn current_block() -> Option<pallet_ethereum::Block> {1365 Ethereum::current_block()1366 }13671368 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1369 Ethereum::current_receipts()1370 }13711372 fn current_all() -> (1373 Option<pallet_ethereum::Block>,1374 Option<Vec<pallet_ethereum::Receipt>>,1375 Option<Vec<TransactionStatus>>1376 ) {1377 (1378 Ethereum::current_block(),1379 Ethereum::current_receipts(),1380 Ethereum::current_transaction_statuses()1381 )1382 }13831384 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1385 xts.into_iter().filter_map(|xt| match xt.0.function {1386 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1387 _ => None1388 }).collect()1389 }1390 }13911392 impl sp_session::SessionKeys<Block> for Runtime {1393 fn decode_session_keys(1394 encoded: Vec<u8>,1395 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1396 SessionKeys::decode_into_raw_public_keys(&encoded)1397 }13981399 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1400 SessionKeys::generate(seed)1401 }1402 }14031404 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1405 fn slot_duration() -> sp_consensus_aura::SlotDuration {1406 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1407 }14081409 fn authorities() -> Vec<AuraId> {1410 Aura::authorities().to_vec()1411 }1412 }14131414 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1415 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1416 ParachainSystem::collect_collation_info()1417 }1418 }14191420 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1421 fn account_nonce(account: AccountId) -> Index {1422 System::account_nonce(account)1423 }1424 }14251426 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1427 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1428 TransactionPayment::query_info(uxt, len)1429 }1430 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1431 TransactionPayment::query_fee_details(uxt, len)1432 }1433 }14341435 /*1436 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1437 for Runtime1438 {1439 fn call(1440 origin: AccountId,1441 dest: AccountId,1442 value: Balance,1443 gas_limit: u64,1444 input_data: Vec<u8>,1445 ) -> pallet_contracts_primitives::ContractExecResult {1446 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1447 }14481449 fn instantiate(1450 origin: AccountId,1451 endowment: Balance,1452 gas_limit: u64,1453 code: pallet_contracts_primitives::Code<Hash>,1454 data: Vec<u8>,1455 salt: Vec<u8>,1456 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1457 {1458 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1459 }14601461 fn get_storage(1462 address: AccountId,1463 key: [u8; 32],1464 ) -> pallet_contracts_primitives::GetStorageResult {1465 Contracts::get_storage(address, key)1466 }14671468 fn rent_projection(1469 address: AccountId,1470 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1471 Contracts::rent_projection(address)1472 }1473 }1474 */14751476 #[cfg(feature = "runtime-benchmarks")]1477 impl frame_benchmarking::Benchmark<Block> for Runtime {1478 fn benchmark_metadata(extra: bool) -> (1479 Vec<frame_benchmarking::BenchmarkList>,1480 Vec<frame_support::traits::StorageInfo>,1481 ) {1482 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1483 use frame_support::traits::StorageInfoTrait;14841485 let mut list = Vec::<BenchmarkList>::new();14861487 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1488 list_benchmark!(list, extra, pallet_unique, Unique);1489 list_benchmark!(list, extra, pallet_inflation, Inflation);1490 list_benchmark!(list, extra, pallet_fungible, Fungible);1491 list_benchmark!(list, extra, pallet_refungible, Refungible);1492 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1493 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);14941495 let storage_info = AllPalletsWithSystem::storage_info();14961497 return (list, storage_info)1498 }14991500 fn dispatch_benchmark(1501 config: frame_benchmarking::BenchmarkConfig1502 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1503 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};15041505 let allowlist: Vec<TrackedStorageKey> = vec![1506 // Block Number1507 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1508 // Total Issuance1509 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1510 // Execution Phase1511 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1512 // Event Count1513 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1514 // System Events1515 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1516 ];15171518 let mut batches = Vec::<BenchmarkBatch>::new();1519 let params = (&config, &allowlist);15201521 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1522 add_benchmark!(params, batches, pallet_unique, Unique);1523 add_benchmark!(params, batches, pallet_inflation, Inflation);1524 add_benchmark!(params, batches, pallet_fungible, Fungible);1525 add_benchmark!(params, batches, pallet_refungible, Refungible);1526 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1527 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);15281529 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1530 Ok(batches)1531 }1532 }1533}15341535struct CheckInherents;15361537impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1538 fn check_inherents(1539 block: &Block,1540 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1541 ) -> sp_inherents::CheckInherentsResult {1542 let relay_chain_slot = relay_state_proof1543 .read_slot()1544 .expect("Could not read the relay chain slot from the proof");15451546 let inherent_data =1547 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1548 relay_chain_slot,1549 sp_std::time::Duration::from_secs(6),1550 )1551 .create_inherent_data()1552 .expect("Could not create the timestamp inherent data");15531554 inherent_data.check_extrinsics(block)1555 }1556}15571558cumulus_pallet_parachain_system::register_validate_block!(1559 Runtime = Runtime,1560 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1561 CheckInherents = CheckInherents,1562);tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -3,22 +3,41 @@
// file 'LICENSE', which is part of this source code package.
//
-import chai from 'chai';
+import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
import {
+ default as usingApi,
+ submitTransactionAsync,
+ submitTransactionExpectFailAsync,
+} from './substrate/substrate-api';
+import {
createItemExpectSuccess,
createCollectionExpectSuccess,
scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ setCollectionLimitsExpectSuccess,
+ getDetailedCollectionInfo,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {getBalanceSingle} from './substrate/get-balance';
chai.use(chaiAsPromised);
-describe('Integration Test scheduler base transaction', () => {
+describe('Scheduling token and balance transfers', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -29,7 +48,7 @@
});
});
- it('User can transfer owned token with delay (scheduler)', async () => {
+ it('Can schedule a transfer of an owned token with delay', async () => {
await usingApi(async () => {
// nft
const nftCollectionId = await createCollectionExpectSuccess();
@@ -37,7 +56,219 @@
await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async (api) => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
+ const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+ expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+ });
+ });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async () => {
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const aliceBalanceBefore = await getFreeBalance(alice);
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
+ const aliceBalanceAfter = await getFreeBalance(alice);
+ expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ });
+ });
+
+ /*it('Can\'t schedule a transaction with no funds', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+
+ await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
+
+ await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ });
+ });*/
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Grace zeroBalance with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });
+
+ /*it.skip('Going bankrupt after sponsoring a scheduled transaction does not nullify the transaction', async () => {
+ await usingApi(async (api) => {
+ // Find two empty, unused accounts
+ const zeroBalance = await findUnusedAddress(api);
+ const zeroBalanceSponsor = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Grace these with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Grace these with money, enough to cover future transactions
+ const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceSponsorTx);
+
+ // Set a collection sponsor
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ // const waitForBlocks = 4;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalanceSponsor.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(4);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });*/
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+
+ /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
+ sponsoredDataRateLimit: 2,
+ });*/
+ //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(2);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+});
+
+describe.skip('Scheduling EVM smart contracts', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async() => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ // todo contract testing
+ it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api) => {
+ // Find unused address
+ const zeroBalance = await findUnusedAddress(api);
+
+ // Mint token for alice
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // Transfer this token from Alice to unused address and back
+ // Alice to Zero gets sponsored
+ const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
+ const events1 = await submitTransactionAsync(alice, aliceToZero);
+ const result1 = getGenericResult(events1);
+
+ // Second transfer should fail
+ const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
+ const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
+ const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+ const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+
+ // Try again after Zero gets some balance - now it should succeed
+ const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balancetx);
+ const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
+ const result2 = getGenericResult(events2);
+
+ expect(result1.success).to.be.true;
+ expect(result2.success).to.be.true;
+ expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -481,10 +481,16 @@
}
export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async () => {
+ const sender = privateKey(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
await usingApi(async (api) => {
// Run the transaction
- const sender = privateKey(senderSeed);
const tx = api.tx.unique.confirmSponsorship(collectionId);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -792,7 +798,7 @@
}
/* eslint no-async-promise-executor: "off" */
-async function getBlockNumber(api: ApiPromise): Promise<number> {
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
return new Promise<number>(async (resolve) => {
const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
unsubscribe();
@@ -822,6 +828,31 @@
}
export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);
+
+ const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ console.log(await getFreeBalance(sender));
+
+ // sleep for n + 1 blocks
+ await waitNewBlocks(blockSchedule + 1);
+
+ const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
+ expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ });
+}
+
+export async function
scheduleTransferExpectSuccess(
collectionId: number,
tokenId: number,
@@ -838,19 +869,36 @@
const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
- await submitTransactionAsync(sender, scheduleTx);
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
- // sleep for 4 blocks
- await waitNewBlocks(blockSchedule + 1);
+ const balanceBefore = await getFreeBalance(recipient);
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+ const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);
- const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
- expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
});
}