git.delta.rocks / unique-network / refs/commits / 75e888b5af30

difftreelog

Merge remote-tracking branch 'remotes/origin/feature/NFTPAR-418' into develop Scheduler and parachain

str-mv2021-06-17parents: #b93e7f4 #2a44139.patch.diff
in: master

27 files changed

modifiedCargo.lockdiffbeforeafterboth
3433 "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]
4570
4571[[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]
45694583
4570[[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]
5279
5280[[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]
5302
5303[[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]
52605324
5261[[package]]5325[[package]]
5262name = "pallet-nicks"5326name = "pallet-nicks"
5343 "sp-std",5407 "sp-std",
5344]5408]
5409
5410[[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]
53455430
5346[[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]
10227
10228[[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]
10237
10238[[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]
1014210247
10143[[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]
1040910515
10471 "log",10577 "log",
10472]10578]
10579
10580[[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]
1047310590
10474[[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",
modifiedCargo.tomldiffbeforeafterboth
2members = [2members = [
3 'node',3 'node',
4 'pallets/*',4 'pallets/*',
5 'primitives',
5 'runtime',6 'runtime',
6]7]
7resolver = "2"8resolver = "2"
modifiednode/Cargo.tomldiffbeforeafterboth
283path = '../runtime'283path = '../runtime'
284version = '3.0.0'284version = '3.0.0'
285
286[dependencies.nft-data-structs]
287path="../primitives"
288default-features = false
285289
286################################################################################290################################################################################
287# Package 291# Package
modifiednode/src/chain_spec.rsdiffbeforeafterboth
55
6use 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_accounts
162 .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(),
addedpallets/nft-charge-transaction/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/nft-transaction-payment/README.mddiffbeforeafterboth

no changes

addedpallets/nft-transaction-payment/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/nft-transaction-payment/src/tests.rsdiffbeforeafterboth

no changes

modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
27 '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'
120121
121122################################################################################
123# Local Dependencies
124
125[dependencies.nft-data-structs]
126default-features = false
127path = '../../primitives'
128version = '0.9.0'
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
13#[cfg(feature = "std")]13#[cfg(feature = "std")]
14pub use serde::*;14pub use serde::*;
1515
16use 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,
3433
35use 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, ReFungibleItemType
45};43};
46use sp_runtime::traits::StaticLookup;
47use pallet_contracts::chain_extension::UncheckedFrom;
48use pallet_transaction_payment::OnChargeTransaction;
4944
50#[cfg(test)]45#[cfg(test)]
51mod mock;46mod mock;
5550
56mod default_weights;51mod default_weights;
57
58pub 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;
62
63// Structs
64// #region
65
66pub type CollectionId = u32;
67pub type TokenId = u32;
68pub type DecimalPoints = u8;
69
70#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]
71#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
72pub enum CollectionMode {
73 Invalid,
74 NFT,
75 // decimal points
76 Fungible(DecimalPoints),
77 ReFungible,
78}
79
80impl Default for CollectionMode {
81 fn default() -> Self {
82 Self::Invalid
83 }
84}
85
86impl 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}
96
97#[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::Normal
106 }
107}
108
109#[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::ImageURL
118 }
119}
120
121#[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}
127
128#[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 sender
132 Disabled,
133 Unconfirmed(AccountId),
134 /// Transactions are sponsored by specified account
135 Confirmed(AccountId),
136}
137
138impl<AccountId> SponsorshipState<AccountId> {
139 fn sponsor(&self) -> Option<&AccountId> {
140 match self {
141 Self::Confirmed(sponsor) => Some(sponsor),
142 _ => None,
143 }
144 }
145
146 fn pending_sponsor(&self) -> Option<&AccountId> {
147 match self {
148 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
149 _ => None,
150 }
151 }
152
153 fn confirmed(&self) -> bool {
154 matches!(self, Self::Confirmed(_))
155 }
156}
157
158impl<T> Default for SponsorshipState<T> {
159 fn default() -> Self {
160 Self::Disabled
161 }
162}
16352
164#[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 char
172 pub description: Vec<u16>, // 256 include null escape char
173 pub token_prefix: Vec<u8>, // 16 include null escape char
174 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}
182
183pub struct CollectionHandle<T: Config> {
184 pub id: CollectionId,
185 collection: Collection<T>,
186}
187
188impl<T: Config> Deref for CollectionHandle<T> {
189 type Target = Collection<T>;
190
191 fn deref(&self) -> &Self::Target {
192 &self.collection
193 }
194}
195
196impl<T: Config> DerefMut for CollectionHandle<T> {
197 fn deref_mut(&mut self) -> &mut Self::Target {
198 &mut self.collection
199 }
200}
201
202#[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}
209
210#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
211#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
212pub struct FungibleItemType {
213 pub value: u128,
214}
215
216#[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}
223
224// #[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// }
234
235#[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 sponsored
241 /// Some(v) - setVariableMetadata is sponsored
242 /// if there is v block between txs
243 pub sponsored_data_rate_limit: Option<BlockNumber>,
244 pub token_limit: u32,
245
246 // Timeouts for item types in passed blocks
247 pub sponsor_transfer_timeout: u32,
248 pub owner_can_transfer: bool,
249 pub owner_can_destroy: bool,
250}
251
252impl<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: true
262 }
263 }
264}
265
266#[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,
273
274 // Timeouts for item types in passed blocks
275 pub nft_sponsor_transfer_timeout: u32,
276 pub fungible_sponsor_transfer_timeout: u32,
277 pub refungible_sponsor_transfer_timeout: u32,
278
279 // Schema limits
280 pub offchain_schema_limit: u32,
281 pub variable_on_chain_schema_limit: u32,
282 pub const_on_chain_schema_limit: u32,
283}
28455
285pub 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}
317
318#[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}
324
325#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
326#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
327pub struct CreateFungibleData {
328 pub value: u128,
329}
330
331#[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}
338
339#[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}
346
347impl 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 _ => 0
353 };
354
355 return len;
356 }
357}
358
359impl From<CreateNftData> for CreateItemData {
360 fn from(item: CreateNftData) -> Self {
361 CreateItemData::NFT(item)
362 }
363}
364
365impl From<CreateReFungibleData> for CreateItemData {
366 fn from(item: CreateReFungibleData) -> Self {
367 CreateItemData::ReFungible(item)
368 }
369}
370
371impl From<CreateFungibleData> for CreateItemData {
372 fn from(item: CreateFungibleData) -> Self {
373 CreateItemData::Fungible(item)
374 }
375}
376
37788
378decl_error! {89decl_error! {
455 }166 }
456}167}
168
169pub struct CollectionHandle<T: system::Config> {
170 pub id: CollectionId,
171 pub collection: Collection<T>,
172}
173
174impl<T: frame_system::Config> Deref for CollectionHandle<T> {
175 type Target = Collection<T>;
176
177 fn deref(&self) -> &Self::Target {
178 &self.collection
179 }
180}
181
182impl<T: frame_system::Config> DerefMut for CollectionHandle<T> {
183 fn deref_mut(&mut self) -> &mut Self::Target {
184 &mut self.collection
185 }
186}
457187
458pub 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>;
460190
461 /// 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}
468
469#[cfg(feature = "runtime-benchmarks")]
470mod benchmarking;
471
472// #endregion
473198
474// # Used definitions199// # Used definitions
475//200//
2492 }2217 }
2493}2218}
24942219
2495////////////////////////////////////////////////////////////////////////////////////////////////////
2496// Economic models
2497// #region
2498
2499/// Fee multiplier.
2500pub type Multiplier = FixedU128;
2501
2502type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
2503
2504/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
2505/// in the queue.
2506#[derive(Encode, Decode, Clone, Eq, PartialEq)]
2507pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);
2508
2509impl<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}
2521
2522impl<T: Config> ChargeTransactionPayment<T>
2523where
2524 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 where
2535 T::Call: Dispatchable<Info = DispatchInfo>,
2536 {
2537 <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
2538 }
2539
2540 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_saturation
2545 .min(len_saturation)
2546 .saturated_into::<BalanceOf<T>>();
2547 final_fee
2548 .saturating_mul(coefficient)
2549 .saturated_into::<TransactionPriority>()
2550 }
2551
2552 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;
2566
2567 let fee = Self::traditional_fee(len, info, tip);
2568
2569 // 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 }
2574
2575 // Determine who is paying transaction fee based on ecnomic model
2576 // Parse call to extract collection ID and access collection sponsor
2577 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)?;
2580
2581 // sponsor timeout
2582 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;
2583
2584 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);
2593
2594 // check free create limit
2595 if collection.limits.sponsored_data_size >= (_properties.len() as u32) {
2596 collection.sponsorship.sponsor()
2597 .cloned()
2598 } else {
2599 None
2600 }
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() {
2607
2608 let collection_limits = collection.limits;
2609 let collection_mode = collection.mode;
2610
2611 // sponsor timeout
2612 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;
2613 sponsor_transfer = match collection_mode {
2614 CollectionMode::NFT => {
2615
2616 // get correct limit
2617 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
2618 collection_limits.sponsor_transfer_timeout
2619 } else {
2620 ChainLimit::get().nft_sponsor_transfer_timeout
2621 };
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 }
2634
2635 sponsored
2636 }
2637 CollectionMode::Fungible(_) => {
2638
2639 // get correct limit
2640 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
2641 collection_limits.sponsor_transfer_timeout
2642 } else {
2643 ChainLimit::get().fungible_sponsor_transfer_timeout
2644 };
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 }
2658
2659 sponsored
2660 }
2661 CollectionMode::ReFungible => {
2662
2663 // get correct limit
2664 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
2665 collection_limits.sponsor_transfer_timeout
2666 } else {
2667 ChainLimit::get().refungible_sponsor_transfer_timeout
2668 };
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 }
2681
2682 sponsored
2683 }
2684 _ => {
2685 false
2686 },
2687 };
2688 }
2689
2690 if !sponsor_transfer {
2691 None
2692 } else {
2693 collection.sponsorship.sponsor()
2694 .cloned()
2695 }
2696 }
2697
2698 Some(Call::set_variable_meta_data(collection_id, item_id, data)) => {
2699 let mut sponsor_metadata_changes = false;
2700
2701 let collection = <CollectionById<T>>::get(collection_id)?;
2702
2703 if
2704 collection.sponsorship.confirmed() &&
2705 // Can't sponsor fungible collection, this tx will be rejected
2706 // as invalid
2707 !matches!(collection.mode, CollectionMode::Fungible(_)) &&
2708 data.len() <= collection.limits.sponsored_data_size as usize
2709 {
2710 if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {
2711 let block_number = <system::Pallet<T>>::block_number() as T::BlockNumber;
2712
2713 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 }
2722
2723 if !sponsor_metadata_changes {
2724 None
2725 } else {
2726 collection.sponsorship.sponsor().cloned()
2727 }
2728 }
2729
2730 _ => None,
2731 })();
2732
2733 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
2734 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
2735
2736 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
2737
2738 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 }
2749
2750 // Sponsor smart contracts
2751 sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
2752
2753 // On instantiation: set the contract owner
2754 Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {
2755
2756 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());
2762
2763 None
2764 },
2765
2766 // On instantiation with code: set the contract owner
2767 Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt)) => {
2768
2769 let new_contract_address = <pallet_contracts::Pallet<T>>::contract_address(
2770 &who,
2771 &T::Hashing::hash(&_code),
2772 _salt,
2773 );
2774
2775 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());
2776
2777 None
2778 }
2779
2780 // When the contract is called, check if the sponsoring is enabled and pay fees from contract endowment if it is
2781 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
2782
2783 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
2784
2785 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;
2791
2792 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 }
2807
2808 None
2809 },
2810
2811 _ => None,
2812 });
2813
2814 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());
2815
2816 <<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}
2820
2821
2822impl<T: Config + Send + Sync> SignedExtension
2823 for ChargeTransactionPayment<T>
2824where
2825 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 // tip
2836 BalanceOf<T>,
2837 // who pays fee
2838 Self::AccountId,
2839 // imbalance resulting from withdrawing the fee
2840 <<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 }
2845
2846 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 }
2859
2860 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 }
2870
2871 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}
2889
2890// #endregion
deletedpallets/nft/src/types.rsdiffbeforeafterboth

no changes

addedpallets/scheduler/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/scheduler/README.mddiffbeforeafterboth

no changes

addedpallets/scheduler/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/scheduler/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/scheduler/src/weights.rsdiffbeforeafterboth

no changes

addedprimitives/Cargo.tomldiffbeforeafterboth

no changes

addedprimitives/src/lib.rsdiffbeforeafterboth

no changes

modifiedruntime/Cargo.tomldiffbeforeafterboth
55 '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',
73
74 'pallet-inflation/std',
75 'pallet-nft/std',
76]79]
7780
78################################################################################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' }
368375
369################################################################################376################################################################################
370# Build Dependencies377# Build Dependencies
modifiedruntime/src/chain_extension.rsdiffbeforeafterboth
1717
18extern crate pallet_nft;18extern crate pallet_nft;
19pub use pallet_nft::*;19pub use pallet_nft::*;
20use nft_data_structs::*;
21// use crate::Runtime;
22
23use sp_runtime::AccountId32;
24use crate::Vec;
2025
21/// Create item parameters26/// Create item parameters
22#[derive(Debug, PartialEq, Encode, Decode)]27#[derive(Debug, PartialEq, Encode, Decode)]
38/// The chain Extension of NFT pallet43/// The chain Extension of NFT pallet
39pub struct NFTExtension;44pub struct NFTExtension;
4045
41impl<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 where
44 E: Ext<T = C>,49 E: Ext<T = C>,
modifiedruntime/src/lib.rsdiffbeforeafterboth
77
8#![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"]
1111
12// 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::{20
21 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, WeightToFeeCoefficients
52 },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;
68
69use sp_runtime::{
70 traits::{
71 Dispatchable,
72 },
73};
74use pallet_contracts::chain_extension::UncheckedFrom;
75
6376
64pub use pallet_timestamp::Call as TimestampCall;77pub use pallet_timestamp::Call as TimestampCall;
193 }206 }
194}207}
195
196// 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 treasury
200// let mut split = fees.ration(100, 0);
201// if let Some(tips) = fees_then_tips.next() {
202// // for tips, if any, 100% to treasury
203// tips.ration_merge_into(100, 0, &mut split);
204// }
205// Treasury::on_unbalanced(split.0);
206// // Author::on_unbalanced(split.1);
207// }
208// }
209// }
210208
211/// 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}
657
658parameter_types! {
659 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
660 RuntimeBlockWeights::get().max_block;
661 pub const MaxScheduledPerBlock: u32 = 50;
662}
663
664pub struct Sponsoring;
665impl SponsoringResolve<AccountId, Call> for Sponsoring {
666
667 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}
678
679impl 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}
690
691impl pallet_nft_transaction_payment::Config for Runtime {
692}
693
694impl pallet_nft_charge_transaction::Config for Runtime {
695}
659696
660construct_runtime!(697construct_runtime!(
661 pub enum Runtime where698 pub enum Runtime where
689 // Unique Pallets726 // Unique Pallets
690 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);
694734
710 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>;
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
1313
14// Pallets that must always be present14// Pallets that must always be present
15const 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];
1819
19// Pallets that depend on consensus and governance configuration20// Pallets that depend on consensus and governance configuration
addedtests/src/scheduler.test.tsdiffbeforeafterboth

no changes

modifiedtests/src/util/helpers.tsdiffbeforeafterboth
55
6import { 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';
2022
21chai.use(chaiAsPromised);23chai.use(chaiAsPromised);
22const expect = chai.expect;24const expect = chai.expect;
702 });704 });
703}705}
706
707async 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}
715
716export async function
717scheduleTransferExpectSuccess(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);
725
726
727 let blockNumber: number | undefined = await getBlockNumber(api);
728 let expectedBlockNumber = blockNumber + 2;
729
730 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);
733
734 const events = await submitTransactionAsync(sender, scheduleTx);
735
736 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());
738
739 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;
740 expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);
741
742 // sleep for 2 blocks
743 await new Promise(resolve => setTimeout(resolve, 6000 * 2));
744
745 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());
747
748 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}
753
704754
705export async function755export async function