difftreelog
Merge remote-tracking branch 'remotes/origin/feature/NFTPAR-418' into develop Scheduler and parachain
in: master
27 files changed
Cargo.lockdiffbeforeafterboth3433 "pallet-proxy",3433 "pallet-proxy",3434 "pallet-randomness-collective-flip",3434 "pallet-randomness-collective-flip",3435 "pallet-recovery",3435 "pallet-recovery",3436 "pallet-scheduler",3436 "pallet-scheduler 3.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3)",3437 "pallet-session",3437 "pallet-session",3438 "pallet-society",3438 "pallet-society",3439 "pallet-staking",3439 "pallet-staking",4517 "futures 0.3.14",4517 "futures 0.3.14",4518 "jsonrpc-core",4518 "jsonrpc-core",4519 "log",4519 "log",4520 "nft-data-structs",4520 "nft-runtime",4521 "nft-runtime",4521 "pallet-contracts",4522 "pallet-contracts",4522 "pallet-contracts-rpc",4523 "pallet-contracts-rpc",4567 "substrate-prometheus-endpoint",4568 "substrate-prometheus-endpoint",4568]4569]45704571[[package]]4572name = "nft-data-structs"4573version = "0.9.0"4574dependencies = [4575 "frame-support",4576 "frame-system",4577 "pallet-contracts",4578 "parity-scale-codec",4579 "serde",4580 "sp-core",4581 "sp-runtime",4582]456945834570[[package]]4584[[package]]4571name = "nft-runtime"4585name = "nft-runtime"4585 "frame-system-benchmarking",4599 "frame-system-benchmarking",4586 "frame-system-rpc-runtime-api",4600 "frame-system-rpc-runtime-api",4587 "hex-literal",4601 "hex-literal",4602 "nft-data-structs",4588 "pallet-aura",4603 "pallet-aura",4589 "pallet-balances",4604 "pallet-balances",4590 "pallet-contracts",4605 "pallet-contracts",4591 "pallet-contracts-primitives",4606 "pallet-contracts-primitives",4592 "pallet-contracts-rpc-runtime-api",4607 "pallet-contracts-rpc-runtime-api",4593 "pallet-inflation",4608 "pallet-inflation",4594 "pallet-nft",4609 "pallet-nft",4610 "pallet-nft-charge-transaction",4611 "pallet-nft-transaction-payment",4595 "pallet-randomness-collective-flip",4612 "pallet-randomness-collective-flip",4613 "pallet-scheduler 3.0.0",4596 "pallet-sudo",4614 "pallet-sudo",4597 "pallet-timestamp",4615 "pallet-timestamp",4598 "pallet-transaction-payment",4616 "pallet-transaction-payment",5245 "frame-benchmarking",5263 "frame-benchmarking",5246 "frame-support",5264 "frame-support",5247 "frame-system",5265 "frame-system",5266 "nft-data-structs",5248 "pallet-balances",5267 "pallet-balances",5249 "pallet-contracts",5268 "pallet-contracts",5250 "pallet-randomness-collective-flip",5269 "pallet-randomness-collective-flip",5258 "sp-std",5277 "sp-std",5259]5278]52795280[[package]]5281name = "pallet-nft-charge-transaction"5282version = "3.0.0"5283dependencies = [5284 "frame-benchmarking",5285 "frame-support",5286 "frame-system",5287 "nft-data-structs",5288 "pallet-balances",5289 "pallet-contracts",5290 "pallet-nft",5291 "pallet-nft-transaction-payment",5292 "pallet-randomness-collective-flip",5293 "pallet-timestamp",5294 "pallet-transaction-payment",5295 "parity-scale-codec",5296 "serde",5297 "sp-core",5298 "sp-io",5299 "sp-runtime",5300 "sp-std",5301]53025303[[package]]5304name = "pallet-nft-transaction-payment"5305version = "3.0.0"5306dependencies = [5307 "frame-benchmarking",5308 "frame-support",5309 "frame-system",5310 "nft-data-structs",5311 "pallet-balances",5312 "pallet-contracts",5313 "pallet-nft",5314 "pallet-randomness-collective-flip",5315 "pallet-timestamp",5316 "pallet-transaction-payment",5317 "parity-scale-codec",5318 "serde",5319 "sp-core",5320 "sp-io",5321 "sp-runtime",5322 "sp-std",5323]526053245261[[package]]5325[[package]]5262name = "pallet-nicks"5326name = "pallet-nicks"5343 "sp-std",5407 "sp-std",5344]5408]54095410[[package]]5411name = "pallet-scheduler"5412version = "3.0.0"5413dependencies = [5414 "frame-benchmarking",5415 "frame-support",5416 "frame-system",5417 "log",5418 "nft-data-structs",5419 "pallet-contracts",5420 "pallet-nft",5421 "pallet-nft-transaction-payment",5422 "parity-scale-codec",5423 "serde",5424 "sp-core",5425 "sp-io",5426 "sp-runtime",5427 "sp-std",5428 "substrate-test-utils",5429]534554305346[[package]]5431[[package]]5347name = "pallet-session"5432name = "pallet-session"6639 "pallet-offences",6724 "pallet-offences",6640 "pallet-proxy",6725 "pallet-proxy",6641 "pallet-randomness-collective-flip",6726 "pallet-randomness-collective-flip",6642 "pallet-scheduler",6727 "pallet-scheduler 3.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3)",6643 "pallet-session",6728 "pallet-session",6644 "pallet-staking",6729 "pallet-staking",6645 "pallet-staking-reward-curve",6730 "pallet-staking-reward-curve",10140 "sp-state-machine",10225 "sp-state-machine",10141]10226]1022710228[[package]]10229name = "substrate-test-utils"10230version = "3.0.0"10231source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"10232dependencies = [10233 "futures 0.3.14",10234 "substrate-test-utils-derive",10235 "tokio 0.2.25",10236]1023710238[[package]]10239name = "substrate-test-utils-derive"10240version = "0.9.0"10241source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"10242dependencies = [10243 "proc-macro-crate 1.0.0",10244 "quote",10245 "syn",10246]101421024710143[[package]]10248[[package]]10144name = "substrate-wasm-builder"10249name = "substrate-wasm-builder"10404 "pin-project-lite 0.1.12",10509 "pin-project-lite 0.1.12",10405 "signal-hook-registry",10510 "signal-hook-registry",10406 "slab",10511 "slab",10512 "tokio-macros",10407 "winapi 0.3.9",10513 "winapi 0.3.9",10408]10514]104091051510471 "log",10577 "log",10472]10578]1057910580[[package]]10581name = "tokio-macros"10582version = "0.2.6"10583source = "registry+https://github.com/rust-lang/crates.io-index"10584checksum = "e44da00bfc73a25f814cd8d7e57a68a5c31b74b3152a0a1d1f590c97ed06265a"10585dependencies = [10586 "proc-macro2",10587 "quote",10588 "syn",10589]104731059010474[[package]]10591[[package]]10475name = "tokio-named-pipes"10592name = "tokio-named-pipes"11476 "pallet-proxy",11593 "pallet-proxy",11477 "pallet-randomness-collective-flip",11594 "pallet-randomness-collective-flip",11478 "pallet-recovery",11595 "pallet-recovery",11479 "pallet-scheduler",11596 "pallet-scheduler 3.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3)",11480 "pallet-session",11597 "pallet-session",11481 "pallet-society",11598 "pallet-society",11482 "pallet-staking",11599 "pallet-staking",Cargo.tomldiffbeforeafterboth2members = [2members = [3 'node',3 'node',4 'pallets/*',4 'pallets/*',5 'primitives',5 'runtime',6 'runtime',6]7]7resolver = "2"8resolver = "2"node/Cargo.tomldiffbeforeafterboth283path = '../runtime'283path = '../runtime'284version = '3.0.0'284version = '3.0.0'285286[dependencies.nft-data-structs]287path="../primitives"288default-features = false285289286################################################################################290################################################################################287# Package 291# Package node/src/chain_spec.rsdiffbeforeafterboth556use cumulus_primitives_core::ParaId;6use cumulus_primitives_core::ParaId;7use nft_runtime::*;7use nft_runtime::*;8use nft_data_structs::*;8use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};9use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};9use sc_service::ChainType;10use sc_service::ChainType;10use sp_core::{sr25519, Pair, Public};11use sp_core::{sr25519, Pair, Public};161 balances: endowed_accounts162 balances: endowed_accounts162 .iter()163 .iter()163 .cloned()164 .cloned()164 .map(|k| (k, 1 << 100))165 .map(|k| (k, 1 << 70))165 .collect(),166 .collect(),166 },167 },167 pallet_treasury: Default::default(),168 pallet_treasury: Default::default(),pallets/nft-charge-transaction/Cargo.tomldiffbeforeafterbothno changes
pallets/nft-charge-transaction/src/lib.rsdiffbeforeafterbothno changes
pallets/nft-transaction-payment/Cargo.tomldiffbeforeafterbothno changes
pallets/nft-transaction-payment/README.mddiffbeforeafterbothno changes
pallets/nft-transaction-payment/src/benchmarking.rsdiffbeforeafterbothno changes
pallets/nft-transaction-payment/src/lib.rsdiffbeforeafterbothno changes
pallets/nft-transaction-payment/src/tests.rsdiffbeforeafterbothno changes
pallets/nft/Cargo.tomldiffbeforeafterboth27 'pallet-contracts/std',27 'pallet-contracts/std',28 'pallet-randomness-collective-flip/std',28 'pallet-randomness-collective-flip/std',29 'pallet-transaction-payment/std',29 'pallet-transaction-payment/std',30 'nft-data-structs/std',30 'sp-std/std',31 'sp-std/std',31 'sp-runtime/std',32 'sp-runtime/std',32 'frame-benchmarking/std',33 'frame-benchmarking/std',118branch = 'polkadot-v0.9.3'119branch = 'polkadot-v0.9.3'119version = '3.0.0'120version = '3.0.0'120121121122################################################################################123# Local Dependencies124125[dependencies.nft-data-structs]126default-features = false127path = '../../primitives'128version = '0.9.0'pallets/nft/src/lib.rsdiffbeforeafterboth13#[cfg(feature = "std")]13#[cfg(feature = "std")]14pub use serde::*;14pub use serde::*;151516use core::ops::{Deref, DerefMut};17use codec::{Decode, Encode};16use codec::{Decode, Encode};18pub use frame_support::{17pub use frame_support::{19 construct_runtime, decl_event, decl_module, decl_storage, decl_error,18 construct_runtime, decl_event, decl_module, decl_storage, decl_error,343335use frame_system::{self as system, ensure_signed, ensure_root};34use frame_system::{self as system, ensure_signed, ensure_root};36use sp_runtime::sp_std::prelude::Vec;35use sp_runtime::sp_std::prelude::Vec;36use core::ops::{Deref, DerefMut};37use sp_runtime::{37use nft_data_structs::{38 traits::{39 Hash, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,38 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,40 },39 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits,41 transaction_validity::{42 TransactionPriority, InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,40 CollectionId, CollectionMode, TokenId, 43 },41 SchemaVersion, SponsorshipState, Ownership,44 FixedPointOperand, FixedU128,42 NftItemType, FungibleItemType, ReFungibleItemType45};43};46use sp_runtime::traits::StaticLookup;47use pallet_contracts::chain_extension::UncheckedFrom;48use pallet_transaction_payment::OnChargeTransaction;494450#[cfg(test)]45#[cfg(test)]51mod mock;46mod mock;555056mod default_weights;51mod default_weights;5758pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;59pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;60pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;61pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;6263// Structs64// #region6566pub type CollectionId = u32;67pub type TokenId = u32;68pub type DecimalPoints = u8;6970#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]71#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]72pub enum CollectionMode {73 Invalid,74 NFT,75 // decimal points76 Fungible(DecimalPoints),77 ReFungible,78}7980impl Default for CollectionMode {81 fn default() -> Self {82 Self::Invalid83 }84}8586impl Into<u8> for CollectionMode {87 fn into(self) -> u8 {88 match self {89 CollectionMode::Invalid => 0,90 CollectionMode::NFT => 1,91 CollectionMode::Fungible(_) => 2,92 CollectionMode::ReFungible => 3,93 }94 }95}9697#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]98#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]99pub enum AccessMode {100 Normal,101 WhiteList,102}103impl Default for AccessMode {104 fn default() -> Self {105 Self::Normal106 }107}108109#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]110#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]111pub enum SchemaVersion {112 ImageURL,113 Unique,114}115impl Default for SchemaVersion {116 fn default() -> Self {117 Self::ImageURL118 }119}120121#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]122#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]123pub struct Ownership<AccountId> {124 pub owner: AccountId,125 pub fraction: u128,126}127128#[derive(Encode, Decode, Debug, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]130pub enum SponsorshipState<AccountId> {131 /// The fees are applied to the transaction sender132 Disabled,133 Unconfirmed(AccountId),134 /// Transactions are sponsored by specified account135 Confirmed(AccountId),136}137138impl<AccountId> SponsorshipState<AccountId> {139 fn sponsor(&self) -> Option<&AccountId> {140 match self {141 Self::Confirmed(sponsor) => Some(sponsor),142 _ => None,143 }144 }145146 fn pending_sponsor(&self) -> Option<&AccountId> {147 match self {148 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),149 _ => None,150 }151 }152153 fn confirmed(&self) -> bool {154 matches!(self, Self::Confirmed(_))155 }156}157158impl<T> Default for SponsorshipState<T> {159 fn default() -> Self {160 Self::Disabled161 }162}16352164#[derive(Encode, Decode, Clone, PartialEq)]53#[cfg(feature = "runtime-benchmarks")]165#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]54mod benchmarking;166pub struct Collection<T: Config> {167 pub owner: T::AccountId,168 pub mode: CollectionMode,169 pub access: AccessMode,170 pub decimal_points: DecimalPoints,171 pub name: Vec<u16>, // 64 include null escape char172 pub description: Vec<u16>, // 256 include null escape char173 pub token_prefix: Vec<u8>, // 16 include null escape char174 pub mint_mode: bool,175 pub offchain_schema: Vec<u8>,176 pub schema_version: SchemaVersion,177 pub sponsorship: SponsorshipState<T::AccountId>,178 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 179 pub variable_on_chain_schema: Vec<u8>, //180 pub const_on_chain_schema: Vec<u8>, //181}182183pub struct CollectionHandle<T: Config> {184 pub id: CollectionId,185 collection: Collection<T>,186}187188impl<T: Config> Deref for CollectionHandle<T> {189 type Target = Collection<T>;190191 fn deref(&self) -> &Self::Target {192 &self.collection193 }194}195196impl<T: Config> DerefMut for CollectionHandle<T> {197 fn deref_mut(&mut self) -> &mut Self::Target {198 &mut self.collection199 }200}201202#[derive(Encode, Decode, Debug, Clone, PartialEq)]203#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]204pub struct NftItemType<AccountId> {205 pub owner: AccountId,206 pub const_data: Vec<u8>,207 pub variable_data: Vec<u8>,208}209210#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]211#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]212pub struct FungibleItemType {213 pub value: u128,214}215216#[derive(Encode, Decode, Debug, Clone, PartialEq)]217#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]218pub struct ReFungibleItemType<AccountId> {219 pub owner: Vec<Ownership<AccountId>>,220 pub const_data: Vec<u8>,221 pub variable_data: Vec<u8>,222}223224// #[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]225// #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]226// pub struct VestingItem<AccountId, Moment> {227// pub sender: AccountId,228// pub recipient: AccountId,229// pub collection_id: CollectionId,230// pub item_id: TokenId,231// pub amount: u64,232// pub vesting_date: Moment,233// }234235#[derive(Encode, Decode, Debug, Clone, PartialEq)]236#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]237pub struct CollectionLimits<BlockNumber: Encode + Decode> {238 pub account_token_ownership_limit: u32,239 pub sponsored_data_size: u32,240 /// None - setVariableMetadata is not sponsored241 /// Some(v) - setVariableMetadata is sponsored 242 /// if there is v block between txs243 pub sponsored_data_rate_limit: Option<BlockNumber>,244 pub token_limit: u32,245246 // Timeouts for item types in passed blocks247 pub sponsor_transfer_timeout: u32,248 pub owner_can_transfer: bool,249 pub owner_can_destroy: bool,250}251252impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {253 fn default() -> Self {254 Self { 255 account_token_ownership_limit: 10_000_000, 256 token_limit: u32::max_value(),257 sponsored_data_size: u32::MAX, 258 sponsored_data_rate_limit: None,259 sponsor_transfer_timeout: 14400,260 owner_can_transfer: true,261 owner_can_destroy: true262 }263 }264}265266#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]267#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]268pub struct ChainLimits {269 pub collection_numbers_limit: u32,270 pub account_token_ownership_limit: u32,271 pub collections_admins_limit: u64,272 pub custom_data_limit: u32,273274 // Timeouts for item types in passed blocks275 pub nft_sponsor_transfer_timeout: u32,276 pub fungible_sponsor_transfer_timeout: u32,277 pub refungible_sponsor_transfer_timeout: u32,278279 // Schema limits280 pub offchain_schema_limit: u32,281 pub variable_on_chain_schema_limit: u32,282 pub const_on_chain_schema_limit: u32,283}28455285pub trait WeightInfo {56pub trait WeightInfo {286 fn create_collection() -> Weight;57 fn create_collection() -> Weight;315 fn set_collection_limits() -> Weight;86 fn set_collection_limits() -> Weight;316}87}317318#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]319#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]320pub struct CreateNftData {321 pub const_data: Vec<u8>,322 pub variable_data: Vec<u8>,323}324325#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]326#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]327pub struct CreateFungibleData {328 pub value: u128,329}330331#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]332#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]333pub struct CreateReFungibleData {334 pub const_data: Vec<u8>,335 pub variable_data: Vec<u8>,336 pub pieces: u128,337}338339#[derive(Encode, Decode, Debug, Clone, PartialEq)]340#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]341pub enum CreateItemData {342 NFT(CreateNftData),343 Fungible(CreateFungibleData),344 ReFungible(CreateReFungibleData),345}346347impl CreateItemData {348 pub fn len(&self) -> usize {349 let len = match self {350 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),351 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),352 _ => 0353 };354 355 return len;356 }357}358359impl From<CreateNftData> for CreateItemData {360 fn from(item: CreateNftData) -> Self {361 CreateItemData::NFT(item)362 }363}364365impl From<CreateReFungibleData> for CreateItemData {366 fn from(item: CreateReFungibleData) -> Self {367 CreateItemData::ReFungible(item)368 }369}370371impl From<CreateFungibleData> for CreateItemData {372 fn from(item: CreateFungibleData) -> Self {373 CreateItemData::Fungible(item)374 }375}37637788378decl_error! {89decl_error! {455 }166 }456}167}168169pub struct CollectionHandle<T: system::Config> {170 pub id: CollectionId,171 pub collection: Collection<T>,172}173174impl<T: frame_system::Config> Deref for CollectionHandle<T> {175 type Target = Collection<T>;176177 fn deref(&self) -> &Self::Target {178 &self.collection179 }180}181182impl<T: frame_system::Config> DerefMut for CollectionHandle<T> {183 fn deref_mut(&mut self) -> &mut Self::Target {184 &mut self.collection185 }186}457187458pub trait Config: system::Config + Sized + pallet_transaction_payment::Config + pallet_contracts::Config {188pub trait Config: system::Config + Sized {459 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;189 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;460190461 /// Weight information for extrinsics in this pallet.191 /// Weight information for extrinsics in this pallet.466 type TreasuryAccountId: Get<Self::AccountId>;196 type TreasuryAccountId: Get<Self::AccountId>;467}197}468469#[cfg(feature = "runtime-benchmarks")]470mod benchmarking;471472// #endregion473198474// # Used definitions199// # Used definitions475//200//2492 }2217 }2493}2218}249422192495////////////////////////////////////////////////////////////////////////////////////////////////////2496// Economic models2497// #region24982499/// Fee multiplier.2500pub type Multiplier = FixedU128;25012502type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;25032504/// Require the transactor pay for themselves and maybe include a tip to gain additional priority2505/// in the queue.2506#[derive(Encode, Decode, Clone, Eq, PartialEq)]2507pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);25082509impl<T: Config + Send + Sync> sp_std::fmt::Debug 2510 for ChargeTransactionPayment<T>2511{2512 #[cfg(feature = "std")]2513 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2514 write!(f, "ChargeTransactionPayment<{:?}>", self.0)2515 }2516 #[cfg(not(feature = "std"))]2517 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2518 Ok(())2519 }2520}25212522impl<T: Config> ChargeTransactionPayment<T>2523where2524 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2525 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2526 T::AccountId: AsRef<[u8]>,2527 T::AccountId: UncheckedFrom<T::Hash>,2528{2529 fn traditional_fee(2530 len: usize,2531 info: &DispatchInfoOf<T::Call>,2532 tip: BalanceOf<T>,2533 ) -> BalanceOf<T>2534 where2535 T::Call: Dispatchable<Info = DispatchInfo>,2536 {2537 <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)2538 }25392540 fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {2541 let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);2542 let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);2543 let len_saturation = max_block_length as u64 / (len as u64).max(1);2544 let coefficient: BalanceOf<T> = weight_saturation2545 .min(len_saturation)2546 .saturated_into::<BalanceOf<T>>();2547 final_fee2548 .saturating_mul(coefficient)2549 .saturated_into::<TransactionPriority>()2550 }25512552 fn withdraw_fee(2553 &self,2554 who: &T::AccountId,2555 call: &T::Call,2556 info: &DispatchInfoOf<T::Call>,2557 len: usize,2558 ) -> Result<2559 (2560 BalanceOf<T>,2561 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2562 ),2563 TransactionValidityError,2564 > {2565 let tip = self.0;25662567 let fee = Self::traditional_fee(len, info, tip);25682569 // Only mess with balances if fee is not zero.2570 if fee.is_zero() {2571 return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)2572 .map(|i| (fee, i));2573 }25742575 // Determine who is paying transaction fee based on ecnomic model2576 // Parse call to extract collection ID and access collection sponsor2577 let mut sponsor: Option<T::AccountId> = (|| match IsSubType::<Call<T>>::is_sub_type(call) {2578 Some(Call::create_item(collection_id, _owner, _properties)) => {2579 let collection = <CollectionById<T>>::get(collection_id)?;25802581 // sponsor timeout2582 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;25832584 let limit = collection.limits.sponsor_transfer_timeout;2585 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2586 let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2587 let limit_time = last_tx_block + limit.into();2588 if block_number <= limit_time {2589 return None;2590 }2591 }2592 <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);25932594 // check free create limit2595 if collection.limits.sponsored_data_size >= (_properties.len() as u32) {2596 collection.sponsorship.sponsor()2597 .cloned()2598 } else {2599 None2600 }2601 }2602 Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2603 let collection = <CollectionById<T>>::get(collection_id)?;2604 2605 let mut sponsor_transfer = false;2606 if collection.sponsorship.confirmed() {26072608 let collection_limits = collection.limits;2609 let collection_mode = collection.mode;2610 2611 // sponsor timeout2612 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;2613 sponsor_transfer = match collection_mode {2614 CollectionMode::NFT => {2615 2616 // get correct limit2617 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2618 collection_limits.sponsor_transfer_timeout2619 } else {2620 ChainLimit::get().nft_sponsor_transfer_timeout2621 };2622 2623 let mut sponsored = true;2624 if <NftTransferBasket<T>>::contains_key(collection_id, item_id) {2625 let last_tx_block = <NftTransferBasket<T>>::get(collection_id, item_id);2626 let limit_time = last_tx_block + limit.into();2627 if block_number <= limit_time {2628 sponsored = false;2629 }2630 }2631 if sponsored {2632 <NftTransferBasket<T>>::insert(collection_id, item_id, block_number);2633 }26342635 sponsored2636 }2637 CollectionMode::Fungible(_) => {2638 2639 // get correct limit2640 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2641 collection_limits.sponsor_transfer_timeout2642 } else {2643 ChainLimit::get().fungible_sponsor_transfer_timeout2644 };2645 2646 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;2647 let mut sponsored = true;2648 if <FungibleTransferBasket<T>>::contains_key(collection_id, who) {2649 let last_tx_block = <FungibleTransferBasket<T>>::get(collection_id, who);2650 let limit_time = last_tx_block + limit.into();2651 if block_number <= limit_time {2652 sponsored = false;2653 }2654 }2655 if sponsored {2656 <FungibleTransferBasket<T>>::insert(collection_id, who, block_number);2657 }26582659 sponsored2660 }2661 CollectionMode::ReFungible => {2662 2663 // get correct limit2664 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2665 collection_limits.sponsor_transfer_timeout2666 } else {2667 ChainLimit::get().refungible_sponsor_transfer_timeout2668 };2669 2670 let mut sponsored = true;2671 if <ReFungibleTransferBasket<T>>::contains_key(collection_id, item_id) {2672 let last_tx_block = <ReFungibleTransferBasket<T>>::get(collection_id, item_id);2673 let limit_time = last_tx_block + limit.into();2674 if block_number <= limit_time {2675 sponsored = false;2676 }2677 }2678 if sponsored {2679 <ReFungibleTransferBasket<T>>::insert(collection_id, item_id, block_number);2680 }26812682 sponsored2683 }2684 _ => {2685 false2686 },2687 };2688 }26892690 if !sponsor_transfer {2691 None2692 } else {2693 collection.sponsorship.sponsor()2694 .cloned()2695 }2696 }26972698 Some(Call::set_variable_meta_data(collection_id, item_id, data)) => {2699 let mut sponsor_metadata_changes = false;27002701 let collection = <CollectionById<T>>::get(collection_id)?;27022703 if2704 collection.sponsorship.confirmed() &&2705 // Can't sponsor fungible collection, this tx will be rejected2706 // as invalid2707 !matches!(collection.mode, CollectionMode::Fungible(_)) &&2708 data.len() <= collection.limits.sponsored_data_size as usize2709 {2710 if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {2711 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;27122713 if <VariableMetaDataBasket<T>>::get(collection_id, item_id)2714 .map(|last_block| block_number - last_block > rate_limit)2715 .unwrap_or(true) 2716 {2717 sponsor_metadata_changes = true;2718 <VariableMetaDataBasket<T>>::insert(collection_id, item_id, block_number);2719 }2720 }2721 }27222723 if !sponsor_metadata_changes {2724 None2725 } else {2726 collection.sponsorship.sponsor().cloned()2727 }2728 }27292730 _ => None,2731 })();27322733 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {2734 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {27352736 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());27372738 let owned_contract = <ContractOwner<T>>::get(called_contract.clone()).as_ref() == Some(who);2739 let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone());2740 2741 if !owned_contract && white_list_enabled {2742 if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {2743 return Err(InvalidTransaction::Call.into());2744 }2745 }2746 },2747 _ => {},2748 }27492750 // Sponsor smart contracts2751 sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {27522753 // On instantiation: set the contract owner2754 Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {27552756 let new_contract_address = <pallet_contracts::Pallet<T>>::contract_address(2757 &who,2758 code_hash,2759 salt,2760 );2761 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());27622763 None2764 },27652766 // On instantiation with code: set the contract owner2767 Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt)) => {27682769 let new_contract_address = <pallet_contracts::Pallet<T>>::contract_address(2770 &who,2771 &T::Hashing::hash(&_code),2772 _salt,2773 );27742775 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());27762777 None2778 }27792780 // When the contract is called, check if the sponsoring is enabled and pay fees from contract endowment if it is2781 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {27822783 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());27842785 let mut sponsor_transfer = false;2786 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2787 let last_tx_block = <ContractSponsorBasket<T>>::get((&called_contract, &who));2788 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;2789 let rate_limit = <ContractSponsoringRateLimit<T>>::get(&called_contract);2790 let limit_time = last_tx_block + rate_limit;27912792 if block_number >= limit_time {2793 <ContractSponsorBasket<T>>::insert((called_contract.clone(), who.clone()), block_number);2794 sponsor_transfer = true;2795 }2796 } else {2797 sponsor_transfer = false;2798 }2799 2800 if sponsor_transfer {2801 if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {2802 if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {2803 return Some(called_contract);2804 }2805 }2806 }28072808 None2809 },28102811 _ => None,2812 });28132814 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());28152816 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)2817 .map(|i| (fee, i))2818 }2819}282028212822impl<T: Config + Send + Sync> SignedExtension2823 for ChargeTransactionPayment<T>2824where2825 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2826 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2827 T::AccountId: AsRef<[u8]>,2828 T::AccountId: UncheckedFrom<T::Hash>,2829{2830 const IDENTIFIER: &'static str = "ChargeTransactionPayment";2831 type AccountId = T::AccountId;2832 type Call = T::Call;2833 type AdditionalSigned = ();2834 type Pre = (2835 // tip2836 BalanceOf<T>,2837 // who pays fee2838 Self::AccountId,2839 // imbalance resulting from withdrawing the fee2840 <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2841 );2842 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {2843 Ok(())2844 }28452846 fn validate(2847 &self,2848 who: &Self::AccountId,2849 call: &Self::Call,2850 info: &DispatchInfoOf<Self::Call>,2851 len: usize,2852 ) -> TransactionValidity {2853 let (fee, _) = self.withdraw_fee(who, call, info, len)?;2854 Ok(ValidTransaction {2855 priority: Self::get_priority(len, info, fee),2856 ..Default::default()2857 })2858 }28592860 fn pre_dispatch(2861 self,2862 who: &Self::AccountId,2863 call: &Self::Call,2864 info: &DispatchInfoOf<Self::Call>,2865 len: usize,2866 ) -> Result<Self::Pre, TransactionValidityError> {2867 let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;2868 Ok((self.0, who.clone(), imbalance))2869 }28702871 fn post_dispatch(2872 pre: Self::Pre,2873 info: &DispatchInfoOf<Self::Call>,2874 post_info: &PostDispatchInfoOf<Self::Call>,2875 len: usize,2876 _result: &DispatchResult,2877 ) -> Result<(), TransactionValidityError> {2878 let (tip, who, imbalance) = pre;2879 let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(2880 len as u32,2881 info,2882 post_info,2883 tip,2884 );2885 <T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;2886 Ok(())2887 }2888}28892890// #endregionpallets/nft/src/types.rsdiffbeforeafterbothno changes
pallets/scheduler/Cargo.tomldiffbeforeafterbothno changes
pallets/scheduler/README.mddiffbeforeafterbothno changes
pallets/scheduler/src/benchmarking.rsdiffbeforeafterbothno changes
pallets/scheduler/src/lib.rsdiffbeforeafterbothno changes
pallets/scheduler/src/weights.rsdiffbeforeafterbothno changes
primitives/Cargo.tomldiffbeforeafterbothno changes
primitives/src/lib.rsdiffbeforeafterbothno changes
runtime/Cargo.tomldiffbeforeafterboth55 'pallet-vesting/std',55 'pallet-vesting/std',56 'parachain-info/std',56 'parachain-info/std',57 'serde',57 'serde',58 'pallet-inflation/std',59 'pallet-nft/std',60 'pallet-scheduler/std',61 'pallet-nft-charge-transaction/std',62 'pallet-nft-transaction-payment/std', 63 'nft-data-structs/std',58 'sp-api/std',64 'sp-api/std',59 'sp-block-builder/std',65 'sp-block-builder/std',60 "sp-consensus-aura/std",66 "sp-consensus-aura/std",71 'xcm-builder/std',77 'xcm-builder/std',72 'xcm-executor/std',78 'xcm-executor/std',7374 'pallet-inflation/std',75 'pallet-nft/std',76]79]778078################################################################################81################################################################################365[dependencies]368[dependencies]366pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }369pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }367pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }370pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }371nft-data-structs = { path = '../primitives', default-features = false, version = '0.9.0' }372pallet-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }373pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }374pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }368375369################################################################################376################################################################################370# Build Dependencies377# Build Dependenciesruntime/src/chain_extension.rsdiffbeforeafterboth171718extern crate pallet_nft;18extern crate pallet_nft;19pub use pallet_nft::*;19pub use pallet_nft::*;20use nft_data_structs::*;21// use crate::Runtime;2223use sp_runtime::AccountId32;24use crate::Vec;202521/// Create item parameters26/// Create item parameters22#[derive(Debug, PartialEq, Encode, Decode)]27#[derive(Debug, PartialEq, Encode, Decode)]38/// The chain Extension of NFT pallet43/// The chain Extension of NFT pallet39pub struct NFTExtension;44pub struct NFTExtension;404541impl<C: Config> ChainExtension<C> for NFTExtension {46impl<C: Config + pallet_contracts::Config> ChainExtension<C> for NFTExtension {42 fn call<E: Ext>(func_id: u32, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>47 fn call<E: Ext>(func_id: u32, env: Environment<E, InitState>) -> Result<RetVal, DispatchError>43 where48 where44 E: Ext<T = C>,49 E: Ext<T = C>,runtime/src/lib.rsdiffbeforeafterboth778#![cfg_attr(not(feature = "std"), no_std)]8#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "256"]10#![recursion_limit = "1024"]111112// Make the WASM binary available.12// Make the WASM binary available.13#[cfg(feature = "std")]13#[cfg(feature = "std")]17use sp_core::{ crypto::KeyTypeId, OpaqueMetadata };17use sp_core::{ crypto::KeyTypeId, OpaqueMetadata };18// #[cfg(any(feature = "std", test))]18// #[cfg(any(feature = "std", test))]19// pub use sp_runtime::BuildStorage;19// pub use sp_runtime::BuildStorage;20use sp_runtime::traits::{2021 AccountIdLookup, AccountIdConversion, BlakeTwo256, Block as BlockT, ConvertInto, IdentifyAccount, Verify,22};23use sp_runtime::{21use sp_runtime::{24 Permill, Perbill, Percent,22 Permill, Perbill, Percent,25 create_runtime_str, generic, impl_opaque_keys,23 create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 26 IdentityLookup, NumberFor, Verify, AccountIdConversion,27 },26 transaction_validity::{TransactionSource, TransactionValidity},28 transaction_validity::{TransactionSource, TransactionValidity},27 ApplyExtrinsicResult, MultiSignature,29 ApplyExtrinsicResult, MultiSignature,28};30};51 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients53 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients52 },54 },53};55};56use pallet_nft_transaction_payment::*;57use pallet_nft_charge_transaction::*;58use nft_data_structs::*;54use pallet_contracts::weights::WeightInfo;59use pallet_contracts::weights::WeightInfo;55// #[cfg(any(feature = "std", test))]60// #[cfg(any(feature = "std", test))]56use frame_system::{61use frame_system::{57 self as system,62 self as system,58 EnsureRoot, 63 EnsureRoot, EnsureSigned,59 limits::{BlockWeights, BlockLength},64 limits::{BlockWeights, BlockLength},60};65};61use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};66use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};62use smallvec::smallvec;67use smallvec::smallvec;6869use sp_runtime::{70 traits::{ 71 Dispatchable,72 },73};74use pallet_contracts::chain_extension::UncheckedFrom;75637664pub use pallet_timestamp::Call as TimestampCall;77pub use pallet_timestamp::Call as TimestampCall;193 }206 }194}207}195196// impl OnUnbalanced<NegativeImbalance> for DealWithFees {197// fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {198// if let Some(fees) = fees_then_tips.next() {199// // for fees, 100% to treasury200// let mut split = fees.ration(100, 0);201// if let Some(tips) = fees_then_tips.next() {202// // for tips, if any, 100% to treasury203// tips.ration_merge_into(100, 0, &mut split);204// }205// Treasury::on_unbalanced(split.0);206// // Author::on_unbalanced(split.1);207// }208// }209// }210208211/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.209/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.212/// This is used to limit the maximal weight of a single extrinsic.210/// This is used to limit the maximal weight of a single extrinsic.657 type InflationBlockInterval = InflationBlockInterval;655 type InflationBlockInterval = InflationBlockInterval;658}656}657658parameter_types! {659 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *660 RuntimeBlockWeights::get().max_block;661 pub const MaxScheduledPerBlock: u32 = 50;662}663664pub struct Sponsoring;665impl SponsoringResolve<AccountId, Call> for Sponsoring {666667 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId> 668 where 669 Call: Dispatchable<Info=DispatchInfo>,670 Call: IsSubType<pallet_nft::Call<Runtime>>, 671 Call: IsSubType<pallet_contracts::Call<Runtime>>,672 AccountId: AsRef<[u8]>,673 AccountId: UncheckedFrom<Hash>674 {675 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)676 }677}678679impl pallet_scheduler::Config for Runtime {680 type Event = Event;681 type Origin = Origin;682 type PalletsOrigin = OriginCaller;683 type Call = Call;684 type MaximumWeight = MaximumSchedulerWeight;685 type ScheduleOrigin = EnsureSigned<AccountId>;686 type MaxScheduledPerBlock = MaxScheduledPerBlock;687 type Sponsoring = Sponsoring;688 type WeightInfo = ();689}690691impl pallet_nft_transaction_payment::Config for Runtime {692}693694impl pallet_nft_charge_transaction::Config for Runtime {695}659696660construct_runtime!(697construct_runtime!(661 pub enum Runtime where698 pub enum Runtime where689 // Unique Pallets726 // Unique Pallets690 Inflation: pallet_inflation::{Pallet, Call, Storage},727 Inflation: pallet_inflation::{Pallet, Call, Storage},691 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},728 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>},729 Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},730 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage},731 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage },692 }732 }693);733);694734710 system::CheckEra<Runtime>,750 system::CheckEra<Runtime>,711 system::CheckNonce<Runtime>,751 system::CheckNonce<Runtime>,712 system::CheckWeight<Runtime>,752 system::CheckWeight<Runtime>,713 pallet_nft::ChargeTransactionPayment<Runtime>,753 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,714);754);715/// Unchecked extrinsic type as expected by this runtime.755/// Unchecked extrinsic type as expected by this runtime.716pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;756pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;tests/src/pallet-presence.test.tsdiffbeforeafterboth131314// Pallets that must always be present14// Pallets that must always be present15const requiredPallets = [15const requiredPallets = [16 'nft', 'inflation', 'balances', 'contracts', 'randomnesscollectiveflip', 'system', 'timestamp', 'transactionpayment', 'treasury', 'vesting'16 'nft', 'inflation', 'balances', 'contracts', 'randomnesscollectiveflip', 'system', 'timestamp', 'transactionpayment', 'treasury', 'vesting',17 'scheduler', 'nftpayment', 'charging'17];18];181919// Pallets that depend on consensus and governance configuration20// Pallets that depend on consensus and governance configurationtests/src/scheduler.test.tsdiffbeforeafterbothno changes
tests/src/util/helpers.tsdiffbeforeafterboth556import { ApiPromise, Keyring } from '@polkadot/api';6import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import type { AccountId, BlockNumber, Call, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';11import { BigNumber } from 'bignumber.js';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';19import { hexToStr, strToUTF16, utf16ToStr } from './util';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';21// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';202221chai.use(chaiAsPromised);23chai.use(chaiAsPromised);22const expect = chai.expect;24const expect = chai.expect;702 });704 });703}705}706707async function getBlockNumber(api: ApiPromise): Promise<number> {708 return new Promise<number>(async (resolve, reject) => {709 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {710 unsubscribe();711 resolve(head.number.toNumber());712 });713 });714}715716export async function717scheduleTransferExpectSuccess(collectionId: number,718 tokenId: number,719 sender: IKeyringPair,720 recipient: IKeyringPair,721 value: number | bigint = 1,722 type: string = 'NFT') {723 await usingApi(async (api: ApiPromise) => {724 let balanceBefore = new BN(0);725726727 let blockNumber: number | undefined = await getBlockNumber(api);728 let expectedBlockNumber = blockNumber + 2;729730 expect(blockNumber).to.be.greaterThan(0);731 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 732 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);733734 const events = await submitTransactionAsync(sender, scheduleTx);735736 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());737 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());738739 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;740 expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);741742 // sleep for 2 blocks743 await new Promise(resolve => setTimeout(resolve, 6000 * 2));744745 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());746 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());747748 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;749 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);750 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());751 });752}753704754705export async function755export async function