difftreelog
CORE-36 Enable/Disable Transfers + Unit tests fix
in: master
8 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5850,34 +5850,34 @@
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
+source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.7#9c572625f6557dfdb19f47474369a0327d51dfbc"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
"parity-scale-codec 2.1.3",
- "serde",
- "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
- "substrate-test-utils",
- "up-sponsorship",
]
[[package]]
name = "pallet-scheduler"
version = "3.0.0"
-source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.7#9c572625f6557dfdb19f47474369a0327d51dfbc"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"log",
"parity-scale-codec 2.1.3",
+ "serde",
+ "sp-core",
"sp-io",
"sp-runtime",
"sp-std",
+ "substrate-test-utils",
+ "up-sponsorship",
]
[[package]]
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -196,6 +196,7 @@
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
limits: CollectionLimits::default(),
+ transfers_enabled: true,
},
)],
nft_item_id: vec![],
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -31,6 +31,8 @@
type ExistentialDeposit = ExistentialDeposit;
type WeightInfo = ();
type MaxLocks = MaxLocks;
+ type MaxReserves = ();
+ type ReserveIdentifier = ();
}
frame_support::construct_runtime!(
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -175,6 +175,8 @@
BadCreateRefungibleCall,
/// Gas limit exceeded
OutOfGas,
+ /// Collection settings not allowing items transferring
+ TransferNotAllowed,
}
}
@@ -533,6 +535,7 @@
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
limits,
+ transfers_enabled: true,
};
// Add new collection to map
@@ -922,6 +925,34 @@
Ok(())
}
+ // TODO! transaction weight
+
+ /// Set transfers_enabled value for particular collection
+ ///
+ /// # Permissions
+ ///
+ /// * Collection Owner.
+ ///
+ /// # Arguments
+ ///
+ /// * collection_id: ID of the collection.
+ ///
+ /// * value: New flag value.
+ #[weight = <T as Config>::WeightInfo::burn_item()]
+ #[transactional]
+ pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {
+
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let mut target_collection = Self::get_collection(collection_id)?;
+
+ Self::check_owner_permissions(&target_collection, sender.as_sub())?;
+
+ target_collection.transfers_enabled = value;
+ Self::save_collection(target_collection);
+
+ Ok(())
+ }
+
/// Destroys a concrete instance of NFT.
///
/// # Permissions
@@ -1575,6 +1606,12 @@
Error::<T>::AccountTokenLimitExceeded
);
+ // preliminary transfer check
+ ensure!(
+ collection.transfers_enabled,
+ Error::<T>::TransferNotAllowed
+ );
+
Ok(())
}
pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -74,6 +74,8 @@
type ExistentialDeposit = ExistentialDeposit;
type WeightInfo = ();
type MaxLocks = MaxLocks;
+ type MaxReserves = ();
+ type ReserveIdentifier = [u8; 8];
}
parameter_types! {
@@ -100,40 +102,40 @@
type Timestamp = pallet_timestamp::Pallet<Test>;
type Randomness = pallet_randomness_collective_flip::Pallet<Test>;
-parameter_types! {
- pub const TombstoneDeposit: u64 = 1;
- pub const DepositPerContract: u64 = 1;
- pub const DepositPerStorageByte: u64 = 1;
- pub const DepositPerStorageItem: u64 = 1;
- pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * 24 * 60 * 10);
- pub const SurchargeReward: u64 = 1;
- pub const SignedClaimHandicap: u32 = 2;
- pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);
- pub DeletionQueueDepth: u32 = 10;
- pub Schedule: pallet_contracts::Schedule<Test> = Default::default();
-}
+// parameter_types! {
+// pub const TombstoneDeposit: u64 = 1;
+// pub const DepositPerContract: u64 = 1;
+// pub const DepositPerStorageByte: u64 = 1;
+// pub const DepositPerStorageItem: u64 = 1;
+// pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * 24 * 60 * 10);
+// pub const SurchargeReward: u64 = 1;
+// pub const SignedClaimHandicap: u32 = 2;
+// pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);
+// pub DeletionQueueDepth: u32 = 10;
+// pub Schedule: pallet_contracts::Schedule<Test> = Default::default();
+// }
-impl pallet_contracts::Config for Test {
- type Time = Timestamp;
- type Randomness = Randomness;
- type Currency = pallet_balances::Pallet<Test>;
- type Event = ();
- type RentPayment = ();
- type SignedClaimHandicap = SignedClaimHandicap;
- type TombstoneDeposit = TombstoneDeposit;
- type DepositPerContract = DepositPerContract;
- type DepositPerStorageByte = DepositPerStorageByte;
- type DepositPerStorageItem = DepositPerStorageItem;
- type RentFraction = RentFraction;
- type SurchargeReward = SurchargeReward;
- type DeletionWeightLimit = DeletionWeightLimit;
- type DeletionQueueDepth = DeletionQueueDepth;
- type ChainExtension = ();
- type WeightPrice = ();
- type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
- type Schedule = Schedule;
- type CallStack = [pallet_contracts::Frame<Self>; 31];
-}
+// impl pallet_contracts::Config for Test {
+// type Time = Timestamp;
+// type Randomness = Randomness;
+// type Currency = pallet_balances::Pallet<Test>;
+// type Event = ();
+// type RentPayment = ();
+// type SignedClaimHandicap = SignedClaimHandicap;
+// type TombstoneDeposit = TombstoneDeposit;
+// type DepositPerContract = DepositPerContract;
+// type DepositPerStorageByte = DepositPerStorageByte;
+// type DepositPerStorageItem = DepositPerStorageItem;
+// type RentFraction = RentFraction;
+// type SurchargeReward = SurchargeReward;
+// type DeletionWeightLimit = DeletionWeightLimit;
+// type DeletionQueueDepth = DeletionQueueDepth;
+// type ChainExtension = ();
+// type WeightPrice = ();
+// type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
+// type Schedule = Schedule;
+// type CallStack = [pallet_contracts::Frame<Self>; 31];
+// }
parameter_types! {
pub const CollectionCreationPrice: u32 = 0;
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -2351,3 +2351,60 @@
);
});
}
+
+#[test]
+fn collection_transfer_flag_works() {
+ new_test_ext().execute_with(|| {
+ default_limits();
+
+ let origin1 = Origin::signed(1);
+
+ let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ assert_ok!(TemplateModule::set_transfers_enabled_flag(origin1, 1, true));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
+ let origin1 = Origin::signed(1);
+
+ // default scenario
+ assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1000));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(2));
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 2), 1);
+
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ });
+}
+
+#[test]
+fn collection_transfer_flag_works_neg() {
+ new_test_ext().execute_with(|| {
+ default_limits();
+
+ let origin1 = Origin::signed(1);
+
+ let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ assert_ok!(TemplateModule::set_transfers_enabled_flag(origin1, 1, false));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
+ let origin1 = Origin::signed(1);
+
+ // default scenario
+ assert_noop!(
+ TemplateModule::transfer(origin1, account(2), 1, 1, 1000),
+ Error::<Test>::TransferNotAllowed
+ );
+ assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(1));
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::balance_count(1, 2), 0);
+
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ });
+}
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -947,900 +947,4 @@
fn root() -> OriginCaller {
system::RawOrigin::Root.into()
}
-
- #[test]
- fn basic_scheduling_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call
- ));
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn schedule_after_works() {
- new_test_ext().execute_with(|| {
- run_to_block(2);
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::After(3),
- None,
- 127,
- root(),
- call
- ));
- run_to_block(5);
- assert!(logger::log().is_empty());
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn schedule_after_zero_works() {
- new_test_ext().execute_with(|| {
- run_to_block(2);
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::After(0),
- None,
- 127,
- root(),
- call
- ));
- // Will trigger on the next block.
- run_to_block(3);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn periodic_scheduling_works() {
- new_test_ext().execute_with(|| {
- // at #4, every 3 blocks, 3 times.
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000))
- ));
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(7);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
- run_to_block(9);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
- run_to_block(10);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- run_to_block(100);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn reschedule_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call).unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule((4, 0), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- assert_noop!(
- Scheduler::do_reschedule((6, 0), DispatchTime::At(6)),
- Error::<Test>::RescheduleNoChange
- );
-
- run_to_block(4);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn reschedule_named_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call
- )
- .unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- assert_noop!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)),
- Error::<Test>::RescheduleNoChange
- );
-
- run_to_block(4);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn reschedule_named_perodic_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- call
- )
- .unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(5)).unwrap(),
- (5, 0)
- );
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- run_to_block(5);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(10)).unwrap(),
- (10, 0)
- );
-
- run_to_block(9);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(10);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
-
- run_to_block(13);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
-
- run_to_block(100);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn cancel_named_scheduling_works_with_normal_cancel() {
- new_test_ext().execute_with(|| {
- // at #4.
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000)),
- )
- .unwrap();
- let i = Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000)),
- )
- .unwrap();
- run_to_block(3);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
- assert_ok!(Scheduler::do_cancel(None, i));
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn cancel_named_periodic_scheduling_works() {
- new_test_ext().execute_with(|| {
- // at #4, every 3 blocks, 3 times.
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000)),
- )
- .unwrap();
- // same id results in error.
- assert!(Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000))
- )
- .is_err());
- // different id is ok.
- Scheduler::do_schedule_named(
- 2u32.encode(),
- DispatchTime::At(8),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000)),
- )
- .unwrap();
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(6);
- assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_weight_limits() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // 69 and 42 do not fit together
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(5);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_hard_deadlines_more() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // With base weights, 69 and 42 should not fit together, but do because of hard deadlines
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_priority_ordering() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 1,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_priority_ordering_with_soft_deadlines() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 255,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 126,
- root(),
- Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
- ));
-
- // 2600 does not fit with 69 or 42, but has higher priority, so will go through
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 2600u32)]);
- // 69 and 42 fit together
- run_to_block(5);
- assert_eq!(
- logger::log(),
- vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn on_initialize_weight_is_correct() {
- new_test_ext().execute_with(|| {
- let base_weight: Weight =
- <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 2);
- let base_multiplier = 0;
- let named_multiplier = <Test as frame_system::Config>::DbWeight::get().writes(1);
- let periodic_multiplier =
- <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 1);
-
- // Named
- assert_ok!(Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(1),
- None,
- 255,
- root(),
- Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))
- ));
- // Anon Periodic
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(1),
- Some((1000, 3)),
- 128,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
- ));
- // Anon
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(1),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // Named Periodic
- assert_ok!(Scheduler::do_schedule_named(
- 2u32.encode(),
- DispatchTime::At(1),
- Some((1000, 3)),
- 126,
- root(),
- Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
- ));
-
- // Will include the named periodic only
- let actual_weight = Scheduler::on_initialize(1);
- let call_weight = MaximumSchedulerWeight::get() / 2;
- assert_eq!(
- actual_weight,
- call_weight
- + base_weight + base_multiplier
- + named_multiplier + periodic_multiplier
- );
- assert_eq!(logger::log(), vec![(root(), 2600u32)]);
-
- // Will include anon and anon periodic
- let actual_weight = Scheduler::on_initialize(2);
- let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;
- assert_eq!(
- actual_weight,
- call_weight + base_weight + base_multiplier * 2 + periodic_multiplier
- );
- assert_eq!(
- logger::log(),
- vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
- );
-
- // Will include named only
- let actual_weight = Scheduler::on_initialize(3);
- let call_weight = MaximumSchedulerWeight::get() / 3;
- assert_eq!(
- actual_weight,
- call_weight + base_weight + base_multiplier + named_multiplier
- );
- assert_eq!(
- logger::log(),
- vec![
- (root(), 2600u32),
- (root(), 69u32),
- (root(), 42u32),
- (root(), 3u32)
- ]
- );
-
- // Will contain none
- let actual_weight = Scheduler::on_initialize(4);
- assert_eq!(actual_weight, 0);
- });
- }
-
- #[test]
- fn root_calls_works() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- Origin::root(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode()));
- assert_ok!(Scheduler::cancel(Origin::root(), 4, 1));
- // Scheduled calls are made NONE, so should not effect state
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn fails_to_schedule_task_in_the_past() {
- new_test_ext().execute_with(|| {
- run_to_block(3);
-
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
-
- assert_err!(
- Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call),
- Error::<Test>::TargetBlockNumberInPast,
- );
-
- assert_err!(
- Scheduler::schedule(Origin::root(), 2, None, 127, call2.clone()),
- Error::<Test>::TargetBlockNumberInPast,
- );
-
- assert_err!(
- Scheduler::schedule(Origin::root(), 3, None, 127, call2),
- Error::<Test>::TargetBlockNumberInPast,
- );
- });
- }
-
- #[test]
- fn should_use_orign() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(
- system::RawOrigin::Signed(1).into(),
- 4,
- None,
- 127,
- call2
- ));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::cancel_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode()
- ));
- assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
- // Scheduled calls are made NONE, so should not effect state
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn should_check_orign() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_noop!(
- Scheduler::schedule_named(
- system::RawOrigin::Signed(2).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ),
- BadOrigin
- );
- assert_noop!(
- Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2),
- BadOrigin
- );
- });
- }
-
- #[test]
- fn should_check_orign_for_cancel() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(
- system::RawOrigin::Signed(1).into(),
- 4,
- None,
- 127,
- call2
- ));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_noop!(
- Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
- BadOrigin
- );
- run_to_block(5);
- assert_eq!(
- logger::log(),
- vec![
- (system::RawOrigin::Signed(1).into(), 69u32),
- (system::RawOrigin::Signed(1).into(), 42u32)
- ]
- );
- });
- }
-
- #[test]
- fn migration_to_v2_works() {
- new_test_ext().execute_with(|| {
- for i in 0..3u64 {
- let k = i.twox_64_concat();
- let old = vec![
- Some(ScheduledV1 {
- maybe_id: None,
- priority: i as u8 + 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- }),
- None,
- Some(ScheduledV1 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- }),
- ];
- frame_support::migration::put_storage_value(b"Scheduler", b"Agenda", &k, old);
- }
-
- assert_eq!(StorageVersion::get(), Releases::V1);
-
- assert!(Scheduler::migrate_v1_to_t2());
-
- assert_eq_uvec!(
- Agenda::<Test>::iter().collect::<Vec<_>>(),
- vec![
- (
- 0,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 1,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 11,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 2,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 12,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- )
- ]
- );
-
- assert_eq!(StorageVersion::get(), Releases::V2);
- });
- }
-
- #[test]
- fn test_migrate_origin() {
- new_test_ext().execute_with(|| {
- for i in 0..3u64 {
- let k = i.twox_64_concat();
- let old: Vec<Option<Scheduled<_, _, u32, u64>>> = vec![
- Some(Scheduled {
- maybe_id: None,
- priority: i as u8 + 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- origin: 3u32,
- maybe_periodic: None,
- _phantom: Default::default(),
- }),
- None,
- Some(Scheduled {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- origin: 2u32,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- _phantom: Default::default(),
- }),
- ];
- frame_support::migration::put_storage_value(b"Scheduler", b"Agenda", &k, old);
- }
-
- impl From<u32> for OriginCaller {
- fn from(value: u32) -> Self {
- match value {
- 3 => system::RawOrigin::Root.into(),
- 2 => system::RawOrigin::None.into(),
- _ => unimplemented!(),
- }
- }
- }
-
- Scheduler::migrate_origin::<u32>();
-
- assert_eq_uvec!(
- Agenda::<Test>::iter().collect::<Vec<_>>(),
- vec![
- (
- 0,
- vec![
- Some(ScheduledV2::<_, _, OriginCaller, u64> {
- maybe_id: None,
- priority: 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 1,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 11,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 2,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 12,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- )
- ]
- );
- });
- }
}
primitives/nft/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23pub use serde::{Serialize, Deserialize};45use sp_runtime::sp_std::prelude::Vec;6use codec::{Decode, Encode};7pub use frame_support::{8 construct_runtime, decl_event, decl_module, decl_storage, decl_error,9 dispatch::DispatchResult,10 ensure, fail, parameter_types,11 traits::{12 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,13 Randomness, IsSubType, WithdrawReasons,14 },15 weights::{16 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},17 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,18 WeightToFeePolynomial, DispatchClass,19 },20 StorageValue, transactional,21};2223pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;24pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;25pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;26pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;2728pub type CollectionId = u32;29pub type TokenId = u32;30pub type DecimalPoints = u8;3132#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]33#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]34pub enum CollectionMode {35 Invalid,36 NFT,37 // decimal points38 Fungible(DecimalPoints),39 ReFungible,40}4142impl Default for CollectionMode {43 fn default() -> Self {44 Self::Invalid45 }46}4748impl CollectionMode {49 pub fn id(&self) -> u8 {50 match self {51 CollectionMode::Invalid => 0,52 CollectionMode::NFT => 1,53 CollectionMode::Fungible(_) => 2,54 CollectionMode::ReFungible => 3,55 }56 }57}5859pub trait SponsoringResolve<AccountId, Call> {60 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;61}6263#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]64#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]65pub enum AccessMode {66 Normal,67 WhiteList,68}69impl Default for AccessMode {70 fn default() -> Self {71 Self::Normal72 }73}7475#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]76#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]77pub enum SchemaVersion {78 ImageURL,79 Unique,80}81impl Default for SchemaVersion {82 fn default() -> Self {83 Self::ImageURL84 }85}8687#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]88#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]89pub struct Ownership<AccountId> {90 pub owner: AccountId,91 pub fraction: u128,92}9394#[derive(Encode, Decode, Debug, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]96pub enum SponsorshipState<AccountId> {97 /// The fees are applied to the transaction sender98 Disabled,99 Unconfirmed(AccountId),100 /// Transactions are sponsored by specified account101 Confirmed(AccountId),102}103104impl<AccountId> SponsorshipState<AccountId> {105 pub fn sponsor(&self) -> Option<&AccountId> {106 match self {107 Self::Confirmed(sponsor) => Some(sponsor),108 _ => None,109 }110 }111112 pub fn pending_sponsor(&self) -> Option<&AccountId> {113 match self {114 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),115 _ => None,116 }117 }118119 pub fn confirmed(&self) -> bool {120 matches!(self, Self::Confirmed(_))121 }122}123124impl<T> Default for SponsorshipState<T> {125 fn default() -> Self {126 Self::Disabled127 }128}129130#[derive(Encode, Decode, Clone, PartialEq)]131#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]132pub struct Collection<T: frame_system::Config> {133 pub owner: T::AccountId,134 pub mode: CollectionMode,135 pub access: AccessMode,136 pub decimal_points: DecimalPoints,137 pub name: Vec<u16>, // 64 include null escape char138 pub description: Vec<u16>, // 256 include null escape char139 pub token_prefix: Vec<u8>, // 16 include null escape char140 pub mint_mode: bool,141 pub offchain_schema: Vec<u8>,142 pub schema_version: SchemaVersion,143 pub sponsorship: SponsorshipState<T::AccountId>,144 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions145 pub variable_on_chain_schema: Vec<u8>, //146 pub const_on_chain_schema: Vec<u8>, //147}148149#[derive(Encode, Decode, Debug, Clone, PartialEq)]150#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]151pub struct NftItemType<AccountId> {152 pub owner: AccountId,153 pub const_data: Vec<u8>,154 pub variable_data: Vec<u8>,155}156157#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]158#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]159pub struct FungibleItemType {160 pub value: u128,161}162163#[derive(Encode, Decode, Debug, Clone, PartialEq)]164#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]165pub struct ReFungibleItemType<AccountId> {166 pub owner: Vec<Ownership<AccountId>>,167 pub const_data: Vec<u8>,168 pub variable_data: Vec<u8>,169}170171#[derive(Encode, Decode, Debug, Clone, PartialEq)]172#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]173pub struct CollectionLimits<BlockNumber: Encode + Decode> {174 pub account_token_ownership_limit: u32,175 pub sponsored_data_size: u32,176 /// None - setVariableMetadata is not sponsored177 /// Some(v) - setVariableMetadata is sponsored178 /// if there is v block between txs179 pub sponsored_data_rate_limit: Option<BlockNumber>,180 pub token_limit: u32,181182 // Timeouts for item types in passed blocks183 pub sponsor_transfer_timeout: u32,184 pub owner_can_transfer: bool,185 pub owner_can_destroy: bool,186}187188impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {189 fn default() -> Self {190 Self {191 account_token_ownership_limit: 10_000_000,192 token_limit: u32::max_value(),193 sponsored_data_size: u32::MAX,194 sponsored_data_rate_limit: None,195 sponsor_transfer_timeout: 14400,196 owner_can_transfer: true,197 owner_can_destroy: true,198 }199 }200}201202#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]203#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]204pub struct ChainLimits {205 pub collection_numbers_limit: u32,206 pub account_token_ownership_limit: u32,207 pub collections_admins_limit: u64,208 pub custom_data_limit: u32,209210 // Timeouts for item types in passed blocks211 pub nft_sponsor_transfer_timeout: u32,212 pub fungible_sponsor_transfer_timeout: u32,213 pub refungible_sponsor_transfer_timeout: u32,214215 // Schema limits216 pub offchain_schema_limit: u32,217 pub variable_on_chain_schema_limit: u32,218 pub const_on_chain_schema_limit: u32,219}220221#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]222#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]223pub struct CreateNftData {224 pub const_data: Vec<u8>,225 pub variable_data: Vec<u8>,226}227228#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]229#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]230pub struct CreateFungibleData {231 pub value: u128,232}233234#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]235#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]236pub struct CreateReFungibleData {237 pub const_data: Vec<u8>,238 pub variable_data: Vec<u8>,239 pub pieces: u128,240}241242#[derive(Encode, Decode, Debug, Clone, PartialEq)]243#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]244pub enum CreateItemData {245 NFT(CreateNftData),246 Fungible(CreateFungibleData),247 ReFungible(CreateReFungibleData),248}249250impl CreateItemData {251 pub fn data_size(&self) -> usize {252 match self {253 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),254 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),255 _ => 0,256 }257 }258}259260impl From<CreateNftData> for CreateItemData {261 fn from(item: CreateNftData) -> Self {262 CreateItemData::NFT(item)263 }264}265266impl From<CreateReFungibleData> for CreateItemData {267 fn from(item: CreateReFungibleData) -> Self {268 CreateItemData::ReFungible(item)269 }270}271272impl From<CreateFungibleData> for CreateItemData {273 fn from(item: CreateFungibleData) -> Self {274 CreateItemData::Fungible(item)275 }276}1#![cfg_attr(not(feature = "std"), no_std)]23pub use serde::{Serialize, Deserialize};45use sp_runtime::sp_std::prelude::Vec;6use codec::{Decode, Encode};7pub use frame_support::{8 construct_runtime, decl_event, decl_module, decl_storage, decl_error,9 dispatch::DispatchResult,10 ensure, fail, parameter_types,11 traits::{12 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,13 Randomness, IsSubType, WithdrawReasons,14 },15 weights::{16 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},17 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,18 WeightToFeePolynomial, DispatchClass,19 },20 StorageValue, transactional,21};2223pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;24pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;25pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;26pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;2728pub type CollectionId = u32;29pub type TokenId = u32;30pub type DecimalPoints = u8;3132#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]33#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]34pub enum CollectionMode {35 Invalid,36 NFT,37 // decimal points38 Fungible(DecimalPoints),39 ReFungible,40}4142impl Default for CollectionMode {43 fn default() -> Self {44 Self::Invalid45 }46}4748impl CollectionMode {49 pub fn id(&self) -> u8 {50 match self {51 CollectionMode::Invalid => 0,52 CollectionMode::NFT => 1,53 CollectionMode::Fungible(_) => 2,54 CollectionMode::ReFungible => 3,55 }56 }57}5859pub trait SponsoringResolve<AccountId, Call> {60 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;61}6263#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]64#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]65pub enum AccessMode {66 Normal,67 WhiteList,68}69impl Default for AccessMode {70 fn default() -> Self {71 Self::Normal72 }73}7475#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]76#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]77pub enum SchemaVersion {78 ImageURL,79 Unique,80}81impl Default for SchemaVersion {82 fn default() -> Self {83 Self::ImageURL84 }85}8687#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]88#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]89pub struct Ownership<AccountId> {90 pub owner: AccountId,91 pub fraction: u128,92}9394#[derive(Encode, Decode, Debug, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]96pub enum SponsorshipState<AccountId> {97 /// The fees are applied to the transaction sender98 Disabled,99 Unconfirmed(AccountId),100 /// Transactions are sponsored by specified account101 Confirmed(AccountId),102}103104impl<AccountId> SponsorshipState<AccountId> {105 pub fn sponsor(&self) -> Option<&AccountId> {106 match self {107 Self::Confirmed(sponsor) => Some(sponsor),108 _ => None,109 }110 }111112 pub fn pending_sponsor(&self) -> Option<&AccountId> {113 match self {114 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),115 _ => None,116 }117 }118119 pub fn confirmed(&self) -> bool {120 matches!(self, Self::Confirmed(_))121 }122}123124impl<T> Default for SponsorshipState<T> {125 fn default() -> Self {126 Self::Disabled127 }128}129130#[derive(Encode, Decode, Clone, PartialEq)]131#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]132pub struct Collection<T: frame_system::Config> {133 pub owner: T::AccountId,134 pub mode: CollectionMode,135 pub access: AccessMode,136 pub decimal_points: DecimalPoints,137 pub name: Vec<u16>, // 64 include null escape char138 pub description: Vec<u16>, // 256 include null escape char139 pub token_prefix: Vec<u8>, // 16 include null escape char140 pub mint_mode: bool,141 pub offchain_schema: Vec<u8>,142 pub schema_version: SchemaVersion,143 pub sponsorship: SponsorshipState<T::AccountId>,144 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions145 pub variable_on_chain_schema: Vec<u8>, //146 pub const_on_chain_schema: Vec<u8>, //147 pub transfers_enabled: bool,148}149150#[derive(Encode, Decode, Debug, Clone, PartialEq)]151#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]152pub struct NftItemType<AccountId> {153 pub owner: AccountId,154 pub const_data: Vec<u8>,155 pub variable_data: Vec<u8>,156}157158#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]159#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]160pub struct FungibleItemType {161 pub value: u128,162}163164#[derive(Encode, Decode, Debug, Clone, PartialEq)]165#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]166pub struct ReFungibleItemType<AccountId> {167 pub owner: Vec<Ownership<AccountId>>,168 pub const_data: Vec<u8>,169 pub variable_data: Vec<u8>,170}171172#[derive(Encode, Decode, Debug, Clone, PartialEq)]173#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]174pub struct CollectionLimits<BlockNumber: Encode + Decode> {175 pub account_token_ownership_limit: u32,176 pub sponsored_data_size: u32,177 /// None - setVariableMetadata is not sponsored178 /// Some(v) - setVariableMetadata is sponsored179 /// if there is v block between txs180 pub sponsored_data_rate_limit: Option<BlockNumber>,181 pub token_limit: u32,182183 // Timeouts for item types in passed blocks184 pub sponsor_transfer_timeout: u32,185 pub owner_can_transfer: bool,186 pub owner_can_destroy: bool,187}188189impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {190 fn default() -> Self {191 Self {192 account_token_ownership_limit: 10_000_000,193 token_limit: u32::max_value(),194 sponsored_data_size: u32::MAX,195 sponsored_data_rate_limit: None,196 sponsor_transfer_timeout: 14400,197 owner_can_transfer: true,198 owner_can_destroy: true,199 }200 }201}202203#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]204#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]205pub struct ChainLimits {206 pub collection_numbers_limit: u32,207 pub account_token_ownership_limit: u32,208 pub collections_admins_limit: u64,209 pub custom_data_limit: u32,210211 // Timeouts for item types in passed blocks212 pub nft_sponsor_transfer_timeout: u32,213 pub fungible_sponsor_transfer_timeout: u32,214 pub refungible_sponsor_transfer_timeout: u32,215216 // Schema limits217 pub offchain_schema_limit: u32,218 pub variable_on_chain_schema_limit: u32,219 pub const_on_chain_schema_limit: u32,220}221222#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]223#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]224pub struct CreateNftData {225 pub const_data: Vec<u8>,226 pub variable_data: Vec<u8>,227}228229#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]230#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]231pub struct CreateFungibleData {232 pub value: u128,233}234235#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]236#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]237pub struct CreateReFungibleData {238 pub const_data: Vec<u8>,239 pub variable_data: Vec<u8>,240 pub pieces: u128,241}242243#[derive(Encode, Decode, Debug, Clone, PartialEq)]244#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]245pub enum CreateItemData {246 NFT(CreateNftData),247 Fungible(CreateFungibleData),248 ReFungible(CreateReFungibleData),249}250251impl CreateItemData {252 pub fn data_size(&self) -> usize {253 match self {254 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),255 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),256 _ => 0,257 }258 }259}260261impl From<CreateNftData> for CreateItemData {262 fn from(item: CreateNftData) -> Self {263 CreateItemData::NFT(item)264 }265}266267impl From<CreateReFungibleData> for CreateItemData {268 fn from(item: CreateReFungibleData) -> Self {269 CreateItemData::ReFungible(item)270 }271}272273impl From<CreateFungibleData> for CreateItemData {274 fn from(item: CreateFungibleData) -> Self {275 CreateItemData::Fungible(item)276 }277}