difftreelog
Merge pull request #242 from UniqueNetwork/feature/fix_unit_tests
in: master
Fix unit tests
13 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4939,216 +4939,6 @@
]
[[package]]
-name = "nft"
-version = "0.9.12"
-dependencies = [
- "cumulus-client-cli",
- "cumulus-client-collator",
- "cumulus-client-consensus-aura",
- "cumulus-client-consensus-common",
- "cumulus-client-network",
- "cumulus-client-service",
- "cumulus-primitives-core",
- "cumulus-primitives-parachain-inherent",
- "fc-consensus",
- "fc-db",
- "fc-mapping-sync",
- "fc-rpc",
- "fc-rpc-core",
- "flexi_logger",
- "fp-rpc",
- "frame-benchmarking",
- "frame-benchmarking-cli",
- "futures 0.3.17",
- "jsonrpc-core",
- "jsonrpc-pubsub",
- "log",
- "nft-data-structs",
- "nft-rpc",
- "nft-runtime",
- "pallet-ethereum",
- "pallet-transaction-payment-rpc",
- "parity-scale-codec",
- "parking_lot 0.11.2",
- "polkadot-cli",
- "polkadot-parachain",
- "polkadot-primitives",
- "polkadot-service",
- "polkadot-test-service",
- "sc-basic-authorship",
- "sc-chain-spec",
- "sc-cli",
- "sc-client-api",
- "sc-consensus",
- "sc-consensus-aura",
- "sc-executor",
- "sc-finality-grandpa",
- "sc-keystore",
- "sc-network",
- "sc-rpc",
- "sc-rpc-api",
- "sc-service",
- "sc-telemetry",
- "sc-tracing",
- "sc-transaction-pool",
- "serde",
- "serde_json",
- "sp-api",
- "sp-block-builder",
- "sp-blockchain",
- "sp-consensus",
- "sp-consensus-aura",
- "sp-core",
- "sp-finality-grandpa",
- "sp-inherents",
- "sp-keystore",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-timestamp",
- "sp-transaction-pool",
- "sp-trie",
- "structopt",
- "substrate-build-script-utils",
- "substrate-frame-rpc-system",
- "substrate-prometheus-endpoint",
-]
-
-[[package]]
-name = "nft-data-structs"
-version = "0.9.0"
-dependencies = [
- "derivative",
- "frame-support",
- "frame-system",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-core",
- "sp-runtime",
- "sp-std",
-]
-
-[[package]]
-name = "nft-rpc"
-version = "3.3.1"
-dependencies = [
- "fc-db",
- "fc-mapping-sync",
- "fc-rpc",
- "fc-rpc-core",
- "fp-rpc",
- "futures 0.3.17",
- "jsonrpc-core",
- "jsonrpc-pubsub",
- "nft-runtime",
- "pallet-ethereum",
- "pallet-nft",
- "pallet-transaction-payment-rpc",
- "pallet-transaction-payment-rpc-runtime-api",
- "sc-client-api",
- "sc-consensus-aura",
- "sc-consensus-epochs",
- "sc-finality-grandpa",
- "sc-finality-grandpa-rpc",
- "sc-keystore",
- "sc-network",
- "sc-rpc",
- "sc-rpc-api",
- "sc-service",
- "sc-transaction-pool",
- "sp-api",
- "sp-block-builder",
- "sp-blockchain",
- "sp-consensus",
- "sp-consensus-aura",
- "sp-core",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-storage",
- "sp-transaction-pool",
- "substrate-frame-rpc-system",
- "tokio 0.2.25",
- "uc-rpc",
- "up-rpc",
-]
-
-[[package]]
-name = "nft-runtime"
-version = "0.9.12"
-dependencies = [
- "cumulus-pallet-aura-ext",
- "cumulus-pallet-dmp-queue",
- "cumulus-pallet-parachain-system",
- "cumulus-pallet-xcm",
- "cumulus-pallet-xcmp-queue",
- "cumulus-primitives-core",
- "cumulus-primitives-timestamp",
- "cumulus-primitives-utility",
- "derivative",
- "fp-rpc",
- "fp-self-contained",
- "frame-benchmarking",
- "frame-executive",
- "frame-support",
- "frame-system",
- "frame-system-benchmarking",
- "frame-system-rpc-runtime-api",
- "hex-literal",
- "nft-data-structs",
- "orml-vesting",
- "pallet-aura",
- "pallet-balances",
- "pallet-common",
- "pallet-ethereum",
- "pallet-evm",
- "pallet-evm-coder-substrate",
- "pallet-evm-contract-helpers",
- "pallet-evm-migration",
- "pallet-evm-transaction-payment",
- "pallet-fungible",
- "pallet-inflation",
- "pallet-nft",
- "pallet-nonfungible",
- "pallet-randomness-collective-flip",
- "pallet-refungible",
- "pallet-sudo",
- "pallet-template-transaction-payment",
- "pallet-timestamp",
- "pallet-transaction-payment",
- "pallet-transaction-payment-rpc-runtime-api",
- "pallet-treasury",
- "pallet-unq-scheduler",
- "pallet-xcm",
- "parachain-info",
- "parity-scale-codec",
- "polkadot-parachain",
- "scale-info",
- "serde",
- "smallvec",
- "sp-api",
- "sp-arithmetic",
- "sp-block-builder",
- "sp-consensus-aura",
- "sp-core",
- "sp-inherents",
- "sp-io",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-std",
- "sp-transaction-pool",
- "sp-version",
- "substrate-wasm-builder",
- "up-evm-mapping",
- "up-rpc",
- "xcm",
- "xcm-builder",
- "xcm-executor",
-]
-
-[[package]]
name = "nodrop"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5581,7 +5371,6 @@
"evm-coder",
"frame-support",
"frame-system",
- "nft-data-structs",
"pallet-evm",
"pallet-evm-coder-substrate",
"parity-scale-codec",
@@ -5590,6 +5379,7 @@
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
"up-evm-mapping",
]
@@ -5853,7 +5643,6 @@
"frame-benchmarking",
"frame-support",
"frame-system",
- "nft-data-structs",
"pallet-common",
"pallet-evm-coder-substrate",
"parity-scale-codec",
@@ -5861,6 +5650,7 @@
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
]
[[package]]
@@ -5956,7 +5746,7 @@
[[package]]
name = "pallet-inflation"
-version = "3.0.0"
+version = "0.1.0"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -6057,43 +5847,6 @@
]
[[package]]
-name = "pallet-nft"
-version = "3.0.0"
-dependencies = [
- "ethereum 0.9.0 (git+https://github.com/purestake/ethereum?branch=joshy-scale-info)",
- "evm-coder",
- "fp-evm",
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "hex-literal",
- "nft-data-structs",
- "pallet-balances",
- "pallet-common",
- "pallet-ethereum",
- "pallet-evm",
- "pallet-evm-coder-substrate",
- "pallet-fungible",
- "pallet-nonfungible",
- "pallet-randomness-collective-flip",
- "pallet-refungible",
- "pallet-timestamp",
- "pallet-transaction-payment",
- "parity-scale-codec",
- "primitive-types 0.10.1",
- "rlp",
- "scale-info",
- "serde",
- "sp-api",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
- "up-evm-mapping",
- "up-sponsorship",
-]
-
-[[package]]
name = "pallet-nicks"
version = "4.0.0-dev"
source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.12#d76f39995315ec36980908e4b99709bd14927044"
@@ -6116,7 +5869,6 @@
"frame-benchmarking",
"frame-support",
"frame-system",
- "nft-data-structs",
"pallet-common",
"pallet-evm-coder-substrate",
"parity-scale-codec",
@@ -6124,6 +5876,7 @@
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
]
[[package]]
@@ -6216,13 +5969,13 @@
"frame-benchmarking",
"frame-support",
"frame-system",
- "nft-data-structs",
"pallet-common",
"parity-scale-codec",
"scale-info",
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
]
[[package]]
@@ -6469,8 +6222,45 @@
]
[[package]]
+name = "pallet-unique"
+version = "0.1.0"
+dependencies = [
+ "ethereum 0.9.0 (git+https://github.com/purestake/ethereum?branch=joshy-scale-info)",
+ "evm-coder",
+ "fp-evm",
+ "frame-benchmarking",
+ "frame-support",
+ "frame-system",
+ "hex-literal",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-ethereum",
+ "pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-fungible",
+ "pallet-nonfungible",
+ "pallet-randomness-collective-flip",
+ "pallet-refungible",
+ "pallet-timestamp",
+ "pallet-transaction-payment",
+ "parity-scale-codec",
+ "primitive-types 0.10.1",
+ "rlp",
+ "scale-info",
+ "serde",
+ "sp-api",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+ "up-evm-mapping",
+ "up-sponsorship",
+]
+
+[[package]]
name = "pallet-unq-scheduler"
-version = "3.0.0"
+version = "0.1.0"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -11714,7 +11504,6 @@
"jsonrpc-core",
"jsonrpc-core-client",
"jsonrpc-derive",
- "nft-data-structs",
"pallet-common",
"parity-scale-codec",
"sp-api",
@@ -11722,6 +11511,7 @@
"sp-core",
"sp-rpc",
"sp-runtime",
+ "up-data-structs",
"up-rpc",
]
@@ -11786,6 +11576,201 @@
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
+name = "unique-node"
+version = "0.9.12"
+dependencies = [
+ "cumulus-client-cli",
+ "cumulus-client-collator",
+ "cumulus-client-consensus-aura",
+ "cumulus-client-consensus-common",
+ "cumulus-client-network",
+ "cumulus-client-service",
+ "cumulus-primitives-core",
+ "cumulus-primitives-parachain-inherent",
+ "fc-consensus",
+ "fc-db",
+ "fc-mapping-sync",
+ "fc-rpc",
+ "fc-rpc-core",
+ "flexi_logger",
+ "fp-rpc",
+ "frame-benchmarking",
+ "frame-benchmarking-cli",
+ "futures 0.3.17",
+ "jsonrpc-core",
+ "jsonrpc-pubsub",
+ "log",
+ "pallet-ethereum",
+ "pallet-transaction-payment-rpc",
+ "parity-scale-codec",
+ "parking_lot 0.11.2",
+ "polkadot-cli",
+ "polkadot-parachain",
+ "polkadot-primitives",
+ "polkadot-service",
+ "polkadot-test-service",
+ "sc-basic-authorship",
+ "sc-chain-spec",
+ "sc-cli",
+ "sc-client-api",
+ "sc-consensus",
+ "sc-consensus-aura",
+ "sc-executor",
+ "sc-finality-grandpa",
+ "sc-keystore",
+ "sc-network",
+ "sc-rpc",
+ "sc-rpc-api",
+ "sc-service",
+ "sc-telemetry",
+ "sc-tracing",
+ "sc-transaction-pool",
+ "serde",
+ "serde_json",
+ "sp-api",
+ "sp-block-builder",
+ "sp-blockchain",
+ "sp-consensus",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-finality-grandpa",
+ "sp-inherents",
+ "sp-keystore",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-timestamp",
+ "sp-transaction-pool",
+ "sp-trie",
+ "structopt",
+ "substrate-build-script-utils",
+ "substrate-frame-rpc-system",
+ "substrate-prometheus-endpoint",
+ "unique-rpc",
+ "unique-runtime",
+ "up-data-structs",
+]
+
+[[package]]
+name = "unique-rpc"
+version = "0.1.0"
+dependencies = [
+ "fc-db",
+ "fc-mapping-sync",
+ "fc-rpc",
+ "fc-rpc-core",
+ "fp-rpc",
+ "futures 0.3.17",
+ "jsonrpc-core",
+ "jsonrpc-pubsub",
+ "pallet-ethereum",
+ "pallet-transaction-payment-rpc",
+ "pallet-transaction-payment-rpc-runtime-api",
+ "pallet-unique",
+ "sc-client-api",
+ "sc-consensus-aura",
+ "sc-consensus-epochs",
+ "sc-finality-grandpa",
+ "sc-finality-grandpa-rpc",
+ "sc-keystore",
+ "sc-network",
+ "sc-rpc",
+ "sc-rpc-api",
+ "sc-service",
+ "sc-transaction-pool",
+ "sp-api",
+ "sp-block-builder",
+ "sp-blockchain",
+ "sp-consensus",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-storage",
+ "sp-transaction-pool",
+ "substrate-frame-rpc-system",
+ "tokio 0.2.25",
+ "uc-rpc",
+ "unique-runtime",
+ "up-rpc",
+]
+
+[[package]]
+name = "unique-runtime"
+version = "0.9.12"
+dependencies = [
+ "cumulus-pallet-aura-ext",
+ "cumulus-pallet-dmp-queue",
+ "cumulus-pallet-parachain-system",
+ "cumulus-pallet-xcm",
+ "cumulus-pallet-xcmp-queue",
+ "cumulus-primitives-core",
+ "cumulus-primitives-timestamp",
+ "cumulus-primitives-utility",
+ "derivative",
+ "fp-rpc",
+ "fp-self-contained",
+ "frame-benchmarking",
+ "frame-executive",
+ "frame-support",
+ "frame-system",
+ "frame-system-benchmarking",
+ "frame-system-rpc-runtime-api",
+ "hex-literal",
+ "orml-vesting",
+ "pallet-aura",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-ethereum",
+ "pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-evm-contract-helpers",
+ "pallet-evm-migration",
+ "pallet-evm-transaction-payment",
+ "pallet-fungible",
+ "pallet-inflation",
+ "pallet-nonfungible",
+ "pallet-randomness-collective-flip",
+ "pallet-refungible",
+ "pallet-sudo",
+ "pallet-template-transaction-payment",
+ "pallet-timestamp",
+ "pallet-transaction-payment",
+ "pallet-transaction-payment-rpc-runtime-api",
+ "pallet-treasury",
+ "pallet-unique",
+ "pallet-unq-scheduler",
+ "pallet-xcm",
+ "parachain-info",
+ "parity-scale-codec",
+ "polkadot-parachain",
+ "scale-info",
+ "serde",
+ "smallvec",
+ "sp-api",
+ "sp-arithmetic",
+ "sp-block-builder",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-inherents",
+ "sp-io",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-std",
+ "sp-transaction-pool",
+ "sp-version",
+ "substrate-wasm-builder",
+ "up-data-structs",
+ "up-evm-mapping",
+ "up-rpc",
+ "xcm",
+ "xcm-builder",
+ "xcm-executor",
+]
+
+[[package]]
name = "universal-hash"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -11832,6 +11817,21 @@
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
+name = "up-data-structs"
+version = "0.1.0"
+dependencies = [
+ "derivative",
+ "frame-support",
+ "frame-system",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
name = "up-evm-mapping"
version = "0.1.0"
dependencies = [
@@ -11843,13 +11843,13 @@
name = "up-rpc"
version = "0.1.0"
dependencies = [
- "nft-data-structs",
"pallet-common",
"parity-scale-codec",
"sp-api",
"sp-core",
"sp-runtime",
"sp-std",
+ "up-data-structs",
]
[[package]]
pallets/common/src/account.rsdiffbeforeafterboth--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -7,7 +7,7 @@
use pallet_evm::AddressMapping;
use sp_std::vec::Vec;
use sp_std::clone::Clone;
-use up_evm_mapping::EvmBackwardsAddressMapping;
+pub use up_evm_mapping::EvmBackwardsAddressMapping;
pub trait CrossAccountId<AccountId>:
Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug + Default
pallets/common/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::{Deref, DerefMut};4use sp_std::vec::Vec;5use account::CrossAccountId;6use frame_support::{7 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},8 ensure, fail,9 traits::{Imbalance, Get, Currency},10};11use up_data_structs::{12 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,13 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,14 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,15 WithdrawReasons, CollectionStats,16};17pub use pallet::*;18use sp_core::H160;19use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};20pub mod account;21#[cfg(feature = "runtime-benchmarks")]22pub mod benchmarking;23pub mod erc;24pub mod eth;2526#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]27pub struct CollectionHandle<T: Config> {28 pub id: CollectionId,29 collection: Collection<T::AccountId>,30 pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,31}32impl<T: Config> CollectionHandle<T> {33 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {34 <CollectionById<T>>::get(id).map(|collection| Self {35 id,36 collection,37 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(38 eth::collection_id_to_address(id),39 gas_limit,40 ),41 })42 }43 pub fn new(id: CollectionId) -> Option<Self> {44 Self::new_with_gas_limit(id, u64::MAX)45 }46 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {47 Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)48 }49 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {50 self.recorder.log_sub(log)51 }52 pub fn log_infallible(&self, log: impl evm_coder::ToLog) {53 self.recorder.log_infallible(log)54 }55 #[allow(dead_code)]56 fn consume_gas(&self, gas: u64) -> DispatchResult {57 self.recorder.consume_gas_sub(gas)58 }59 pub fn consume_sload(&self) -> DispatchResult {60 self.recorder.consume_sload_sub()61 }62 pub fn consume_sstores(&self, amount: usize) -> DispatchResult {63 self.recorder.consume_sstores_sub(amount)64 }65 pub fn consume_sstore(&self) -> DispatchResult {66 self.recorder.consume_sstore_sub()67 }68 pub fn consume_log(&self, topics: usize, data: usize) -> DispatchResult {69 self.recorder.consume_log_sub(topics, data)70 }71 pub fn submit_logs(self) -> DispatchResult {72 self.recorder.submit_logs()73 }74 pub fn save(self) -> DispatchResult {75 self.recorder.submit_logs()?;76 <CollectionById<T>>::insert(self.id, self.collection);77 Ok(())78 }79}80impl<T: Config> Deref for CollectionHandle<T> {81 type Target = Collection<T::AccountId>;8283 fn deref(&self) -> &Self::Target {84 &self.collection85 }86}8788impl<T: Config> DerefMut for CollectionHandle<T> {89 fn deref_mut(&mut self) -> &mut Self::Target {90 &mut self.collection91 }92}9394impl<T: Config> CollectionHandle<T> {95 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {96 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);97 Ok(())98 }99 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {100 self.consume_sload()?;101102 Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))103 }104 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {105 ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);106 Ok(())107 }108 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {109 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)110 }111 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {112 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)113 }114 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {115 self.consume_sload()?;116117 ensure!(118 <Allowlist<T>>::get((self.id, user)),119 <Error<T>>::AddressNotInAllowlist120 );121 Ok(())122 }123124 pub fn check_can_update_meta(125 &self,126 subject: &T::CrossAccountId,127 item_owner: &T::CrossAccountId,128 ) -> DispatchResult {129 match self.meta_update_permission {130 MetaUpdatePermission::ItemOwner => {131 ensure!(subject == item_owner, <Error<T>>::NoPermission);132 Ok(())133 }134 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),135 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),136 }137 }138}139140#[frame_support::pallet]141pub mod pallet {142 use super::*;143 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};144 use account::CrossAccountId;145 use frame_support::traits::Currency;146 use up_data_structs::TokenId;147 use scale_info::TypeInfo;148149 #[pallet::config]150 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {151 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;152153 type CrossAccountId: CrossAccountId<Self::AccountId>;154155 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;156 type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;157158 type Currency: Currency<Self::AccountId>;159 type CollectionCreationPrice: Get<160 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,161 >;162 type TreasuryAccountId: Get<Self::AccountId>;163 }164165 #[pallet::pallet]166 #[pallet::generate_store(pub(super) trait Store)]167 pub struct Pallet<T>(_);168169 #[pallet::extra_constants]170 impl<T: Config> Pallet<T> {171 pub fn collection_admins_limit() -> u32 {172 COLLECTION_ADMINS_LIMIT173 }174 }175176 #[pallet::event]177 #[pallet::generate_deposit(pub fn deposit_event)]178 pub enum Event<T: Config> {179 /// New collection was created180 ///181 /// # Arguments182 ///183 /// * collection_id: Globally unique identifier of newly created collection.184 ///185 /// * mode: [CollectionMode] converted into u8.186 ///187 /// * account_id: Collection owner.188 CollectionCreated(CollectionId, u8, T::AccountId),189190 /// New item was created.191 ///192 /// # Arguments193 ///194 /// * collection_id: Id of the collection where item was created.195 ///196 /// * item_id: Id of an item. Unique within the collection.197 ///198 /// * recipient: Owner of newly created item199 ///200 /// * amount: Always 1 for NFT201 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),202203 /// Collection item was burned.204 ///205 /// # Arguments206 ///207 /// * collection_id.208 ///209 /// * item_id: Identifier of burned NFT.210 ///211 /// * owner: which user has destroyed its tokens212 ///213 /// * amount: Always 1 for NFT214 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),215216 /// Item was transferred217 ///218 /// * collection_id: Id of collection to which item is belong219 ///220 /// * item_id: Id of an item221 ///222 /// * sender: Original owner of item223 ///224 /// * recipient: New owner of item225 ///226 /// * amount: Always 1 for NFT227 Transfer(228 CollectionId,229 TokenId,230 T::CrossAccountId,231 T::CrossAccountId,232 u128,233 ),234235 /// * collection_id236 ///237 /// * item_id238 ///239 /// * sender240 ///241 /// * spender242 ///243 /// * amount244 Approved(245 CollectionId,246 TokenId,247 T::CrossAccountId,248 T::CrossAccountId,249 u128,250 ),251 }252253 #[pallet::error]254 pub enum Error<T> {255 /// This collection does not exist.256 CollectionNotFound,257 /// Sender parameter and item owner must be equal.258 MustBeTokenOwner,259 /// No permission to perform action260 NoPermission,261 /// Collection is not in mint mode.262 PublicMintingNotAllowed,263 /// Address is not in allow list.264 AddressNotInAllowlist,265266 /// Collection name can not be longer than 63 char.267 CollectionNameLimitExceeded,268 /// Collection description can not be longer than 255 char.269 CollectionDescriptionLimitExceeded,270 /// Token prefix can not be longer than 15 char.271 CollectionTokenPrefixLimitExceeded,272 /// Total collections bound exceeded.273 TotalCollectionsLimitExceeded,274 /// variable_data exceeded data limit.275 TokenVariableDataLimitExceeded,276 /// Exceeded max admin amount277 CollectionAdminAmountExceeded,278279 /// Collection settings not allowing items transferring280 TransferNotAllowed,281 /// Account token limit exceeded per collection282 AccountTokenLimitExceeded,283 /// Collection token limit exceeded284 CollectionTokenLimitExceeded,285 /// Metadata flag frozen286 MetadataFlagFrozen,287288 /// Item not exists.289 TokenNotFound,290 /// Item balance not enough.291 TokenValueTooLow,292 /// Requested value more than approved.293 TokenValueNotEnough,294 /// Tried to approve more than owned295 CantApproveMoreThanOwned,296297 /// Can't transfer tokens to ethereum zero address298 AddressIsZero,299 /// Target collection doesn't supports this operation300 UnsupportedOperation,301 }302303 #[pallet::storage]304 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;305 #[pallet::storage]306 pub type DestroyedCollectionCount<T> =307 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;308309 /// Collection info310 #[pallet::storage]311 pub type CollectionById<T> = StorageMap<312 Hasher = Blake2_128Concat,313 Key = CollectionId,314 Value = Collection<<T as frame_system::Config>::AccountId>,315 QueryKind = OptionQuery,316 >;317318 #[pallet::storage]319 pub type AdminAmount<T> = StorageMap<320 Hasher = Blake2_128Concat,321 Key = CollectionId,322 Value = u32,323 QueryKind = ValueQuery,324 >;325326 /// List of collection admins327 #[pallet::storage]328 pub type IsAdmin<T: Config> = StorageNMap<329 Key = (330 Key<Blake2_128Concat, CollectionId>,331 Key<Blake2_128Concat, T::CrossAccountId>,332 ),333 Value = bool,334 QueryKind = ValueQuery,335 >;336337 /// Allowlisted collection users338 #[pallet::storage]339 pub type Allowlist<T: Config> = StorageNMap<340 Key = (341 Key<Blake2_128Concat, CollectionId>,342 Key<Blake2_128Concat, T::CrossAccountId>,343 ),344 Value = bool,345 QueryKind = ValueQuery,346 >;347348 /// Not used by code, exists only to provide some types to metadata349 #[pallet::storage]350 pub type DummyStorageValue<T> =351 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;352}353354impl<T: Config> Pallet<T> {355 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens356 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {357 ensure!(358 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,359 <Error<T>>::AddressIsZero360 );361 Ok(())362 }363 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {364 <IsAdmin<T>>::iter_prefix((collection,))365 .map(|(a, _)| a)366 .collect()367 }368 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {369 <Allowlist<T>>::iter_prefix((collection,))370 .map(|(a, _)| a)371 .collect()372 }373 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {374 <Allowlist<T>>::get((collection, user))375 }376 pub fn collection_stats() -> CollectionStats {377 let created = <CreatedCollectionCount<T>>::get();378 let destroyed = <DestroyedCollectionCount<T>>::get();379 CollectionStats {380 created: created.0,381 destroyed: destroyed.0,382 alive: created.0 - destroyed.0,383 }384 }385}386387impl<T: Config> Pallet<T> {388 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {389 {390 ensure!(391 data.name.len() <= MAX_COLLECTION_NAME_LENGTH,392 Error::<T>::CollectionNameLimitExceeded393 );394 ensure!(395 data.description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH,396 Error::<T>::CollectionDescriptionLimitExceeded397 );398 ensure!(399 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH,400 Error::<T>::CollectionTokenPrefixLimitExceeded401 );402 }403404 let created_count = <CreatedCollectionCount<T>>::get()405 .0406 .checked_add(1)407 .ok_or(ArithmeticError::Overflow)?;408 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;409 let id = CollectionId(created_count);410411 // bound Total number of collections412 ensure!(413 created_count - destroyed_count < COLLECTION_NUMBER_LIMIT,414 <Error<T>>::TotalCollectionsLimitExceeded415 );416417 // =========418419 // Take a (non-refundable) deposit of collection creation420 {421 let mut imbalance =422 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();423 imbalance.subsume(424 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(425 &T::TreasuryAccountId::get(),426 T::CollectionCreationPrice::get(),427 ),428 );429 <T as Config>::Currency::settle(430 &data.owner,431 imbalance,432 WithdrawReasons::TRANSFER,433 ExistenceRequirement::KeepAlive,434 )435 .map_err(|_| Error::<T>::NoPermission)?;436 }437438 <CreatedCollectionCount<T>>::put(created_count);439 <Pallet<T>>::deposit_event(Event::CollectionCreated(440 id,441 data.mode.id(),442 data.owner.clone(),443 ));444 <CollectionById<T>>::insert(id, data);445 Ok(id)446 }447448 pub fn destroy_collection(449 collection: CollectionHandle<T>,450 sender: &T::CrossAccountId,451 ) -> DispatchResult {452 ensure!(453 collection.limits.owner_can_destroy(),454 <Error<T>>::NoPermission,455 );456 collection.check_is_owner(&sender)?;457458 let destroyed_collections = <DestroyedCollectionCount<T>>::get()459 .0460 .checked_add(1)461 .ok_or(ArithmeticError::Overflow)?;462463 // =========464465 <DestroyedCollectionCount<T>>::put(destroyed_collections);466 <CollectionById<T>>::remove(collection.id);467 <AdminAmount<T>>::remove(collection.id);468 <IsAdmin<T>>::remove_prefix((collection.id,), None);469 <Allowlist<T>>::remove_prefix((collection.id,), None);470 Ok(())471 }472473 pub fn toggle_allowlist(474 collection: &CollectionHandle<T>,475 sender: &T::CrossAccountId,476 user: &T::CrossAccountId,477 allowed: bool,478 ) -> DispatchResult {479 collection.check_is_owner_or_admin(&sender)?;480481 // =========482483 if allowed {484 <Allowlist<T>>::insert((collection.id, user), true);485 } else {486 <Allowlist<T>>::remove((collection.id, user));487 }488489 Ok(())490 }491492 pub fn toggle_admin(493 collection: &CollectionHandle<T>,494 sender: &T::CrossAccountId,495 user: &T::CrossAccountId,496 admin: bool,497 ) -> DispatchResult {498 collection.check_is_owner_or_admin(&sender)?;499500 let was_admin = <IsAdmin<T>>::get((collection.id, user));501 if was_admin == admin {502 return Ok(());503 }504 let amount = <AdminAmount<T>>::get(collection.id);505506 if admin {507 let amount = amount508 .checked_add(1)509 .ok_or(<Error<T>>::CollectionAdminAmountExceeded)?;510 ensure!(511 amount <= Self::collection_admins_limit(),512 <Error<T>>::CollectionAdminAmountExceeded,513 );514515 // =========516517 <AdminAmount<T>>::insert(collection.id, amount);518 <IsAdmin<T>>::insert((collection.id, user), true);519 } else {520 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));521 <IsAdmin<T>>::remove((collection.id, user));522 }523524 Ok(())525 }526}527528#[macro_export]529macro_rules! unsupported {530 () => {531 Err(<Error<T>>::UnsupportedOperation.into())532 };533}534535/// Worst cases536pub trait CommonWeightInfo {537 fn create_item() -> Weight;538 fn create_multiple_items(amount: u32) -> Weight;539 fn burn_item() -> Weight;540 fn transfer() -> Weight;541 fn approve() -> Weight;542 fn transfer_from() -> Weight;543 fn burn_from() -> Weight;544 fn set_variable_metadata(bytes: u32) -> Weight;545}546547pub trait CommonCollectionOperations<T: Config> {548 fn create_item(549 &self,550 sender: T::CrossAccountId,551 to: T::CrossAccountId,552 data: CreateItemData,553 ) -> DispatchResultWithPostInfo;554 fn create_multiple_items(555 &self,556 sender: T::CrossAccountId,557 to: T::CrossAccountId,558 data: Vec<CreateItemData>,559 ) -> DispatchResultWithPostInfo;560 fn burn_item(561 &self,562 sender: T::CrossAccountId,563 token: TokenId,564 amount: u128,565 ) -> DispatchResultWithPostInfo;566567 fn transfer(568 &self,569 sender: T::CrossAccountId,570 to: T::CrossAccountId,571 token: TokenId,572 amount: u128,573 ) -> DispatchResultWithPostInfo;574 fn approve(575 &self,576 sender: T::CrossAccountId,577 spender: T::CrossAccountId,578 token: TokenId,579 amount: u128,580 ) -> DispatchResultWithPostInfo;581 fn transfer_from(582 &self,583 sender: T::CrossAccountId,584 from: T::CrossAccountId,585 to: T::CrossAccountId,586 token: TokenId,587 amount: u128,588 ) -> DispatchResultWithPostInfo;589 fn burn_from(590 &self,591 sender: T::CrossAccountId,592 from: T::CrossAccountId,593 token: TokenId,594 amount: u128,595 ) -> DispatchResultWithPostInfo;596597 fn set_variable_metadata(598 &self,599 sender: T::CrossAccountId,600 token: TokenId,601 data: Vec<u8>,602 ) -> DispatchResultWithPostInfo;603604 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;605 fn token_exists(&self, token: TokenId) -> bool;606 fn last_token_id(&self) -> TokenId;607608 fn token_owner(&self, token: TokenId) -> T::CrossAccountId;609 fn const_metadata(&self, token: TokenId) -> Vec<u8>;610 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;611612 /// How many tokens collection contains (Applicable to nonfungible/refungible)613 fn collection_tokens(&self) -> u32;614 /// Amount of different tokens account has (Applicable to nonfungible/refungible)615 fn account_balance(&self, account: T::CrossAccountId) -> u32;616 /// Amount of specific token account have (Applicable to fungible/refungible)617 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;618 fn allowance(619 &self,620 sender: T::CrossAccountId,621 spender: T::CrossAccountId,622 token: TokenId,623 ) -> u128;624}625626// Flexible enough for implementing CommonCollectionOperations627pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {628 let post_info = PostDispatchInfo {629 actual_weight: Some(weight),630 pays_fee: Pays::Yes,631 };632 match res {633 Ok(()) => Ok(post_info),634 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),635 }636}1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::{Deref, DerefMut};4use sp_std::vec::Vec;5use account::CrossAccountId;6use frame_support::{7 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},8 ensure, fail,9 traits::{Imbalance, Get, Currency},10};11use up_data_structs::{12 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,13 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,14 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,15 WithdrawReasons, CollectionStats,16};17pub use pallet::*;18use sp_core::H160;19use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};20pub mod account;21#[cfg(feature = "runtime-benchmarks")]22pub mod benchmarking;23pub mod erc;24pub mod eth;2526#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]27pub struct CollectionHandle<T: Config> {28 pub id: CollectionId,29 collection: Collection<T::AccountId>,30 pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,31}32impl<T: Config> CollectionHandle<T> {33 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {34 <CollectionById<T>>::get(id).map(|collection| Self {35 id,36 collection,37 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(38 eth::collection_id_to_address(id),39 gas_limit,40 ),41 })42 }43 pub fn new(id: CollectionId) -> Option<Self> {44 Self::new_with_gas_limit(id, u64::MAX)45 }46 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {47 Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)48 }49 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {50 self.recorder.log_sub(log)51 }52 pub fn log_infallible(&self, log: impl evm_coder::ToLog) {53 self.recorder.log_infallible(log)54 }55 #[allow(dead_code)]56 fn consume_gas(&self, gas: u64) -> DispatchResult {57 self.recorder.consume_gas_sub(gas)58 }59 pub fn consume_sload(&self) -> DispatchResult {60 self.recorder.consume_sload_sub()61 }62 pub fn consume_sstores(&self, amount: usize) -> DispatchResult {63 self.recorder.consume_sstores_sub(amount)64 }65 pub fn consume_sstore(&self) -> DispatchResult {66 self.recorder.consume_sstore_sub()67 }68 pub fn consume_log(&self, topics: usize, data: usize) -> DispatchResult {69 self.recorder.consume_log_sub(topics, data)70 }71 pub fn submit_logs(self) -> DispatchResult {72 self.recorder.submit_logs()73 }74 pub fn save(self) -> DispatchResult {75 self.recorder.submit_logs()?;76 <CollectionById<T>>::insert(self.id, self.collection);77 Ok(())78 }79}80impl<T: Config> Deref for CollectionHandle<T> {81 type Target = Collection<T::AccountId>;8283 fn deref(&self) -> &Self::Target {84 &self.collection85 }86}8788impl<T: Config> DerefMut for CollectionHandle<T> {89 fn deref_mut(&mut self) -> &mut Self::Target {90 &mut self.collection91 }92}9394impl<T: Config> CollectionHandle<T> {95 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {96 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);97 Ok(())98 }99 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {100 self.consume_sload()?;101102 Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))103 }104 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {105 ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);106 Ok(())107 }108 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {109 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)110 }111 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {112 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)113 }114 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {115 self.consume_sload()?;116117 ensure!(118 <Allowlist<T>>::get((self.id, user)),119 <Error<T>>::AddressNotInAllowlist120 );121 Ok(())122 }123124 pub fn check_can_update_meta(125 &self,126 subject: &T::CrossAccountId,127 item_owner: &T::CrossAccountId,128 ) -> DispatchResult {129 match self.meta_update_permission {130 MetaUpdatePermission::ItemOwner => {131 ensure!(subject == item_owner, <Error<T>>::NoPermission);132 Ok(())133 }134 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),135 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),136 }137 }138}139140#[frame_support::pallet]141pub mod pallet {142 use super::*;143 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};144 use account::CrossAccountId;145 use frame_support::traits::Currency;146 use up_data_structs::TokenId;147 use scale_info::TypeInfo;148149 #[pallet::config]150 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {151 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;152153 type CrossAccountId: CrossAccountId<Self::AccountId>;154155 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;156 type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;157158 type Currency: Currency<Self::AccountId>;159 type CollectionCreationPrice: Get<160 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,161 >;162 type TreasuryAccountId: Get<Self::AccountId>;163 }164165 #[pallet::pallet]166 #[pallet::generate_store(pub(super) trait Store)]167 pub struct Pallet<T>(_);168169 #[pallet::extra_constants]170 impl<T: Config> Pallet<T> {171 pub fn collection_admins_limit() -> u32 {172 COLLECTION_ADMINS_LIMIT173 }174 }175176 #[pallet::event]177 #[pallet::generate_deposit(pub fn deposit_event)]178 pub enum Event<T: Config> {179 /// New collection was created180 ///181 /// # Arguments182 ///183 /// * collection_id: Globally unique identifier of newly created collection.184 ///185 /// * mode: [CollectionMode] converted into u8.186 ///187 /// * account_id: Collection owner.188 CollectionCreated(CollectionId, u8, T::AccountId),189190 /// New item was created.191 ///192 /// # Arguments193 ///194 /// * collection_id: Id of the collection where item was created.195 ///196 /// * item_id: Id of an item. Unique within the collection.197 ///198 /// * recipient: Owner of newly created item199 ///200 /// * amount: Always 1 for NFT201 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),202203 /// Collection item was burned.204 ///205 /// # Arguments206 ///207 /// * collection_id.208 ///209 /// * item_id: Identifier of burned NFT.210 ///211 /// * owner: which user has destroyed its tokens212 ///213 /// * amount: Always 1 for NFT214 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),215216 /// Item was transferred217 ///218 /// * collection_id: Id of collection to which item is belong219 ///220 /// * item_id: Id of an item221 ///222 /// * sender: Original owner of item223 ///224 /// * recipient: New owner of item225 ///226 /// * amount: Always 1 for NFT227 Transfer(228 CollectionId,229 TokenId,230 T::CrossAccountId,231 T::CrossAccountId,232 u128,233 ),234235 /// * collection_id236 ///237 /// * item_id238 ///239 /// * sender240 ///241 /// * spender242 ///243 /// * amount244 Approved(245 CollectionId,246 TokenId,247 T::CrossAccountId,248 T::CrossAccountId,249 u128,250 ),251 }252253 #[pallet::error]254 pub enum Error<T> {255 /// This collection does not exist.256 CollectionNotFound,257 /// Sender parameter and item owner must be equal.258 MustBeTokenOwner,259 /// No permission to perform action260 NoPermission,261 /// Collection is not in mint mode.262 PublicMintingNotAllowed,263 /// Address is not in allow list.264 AddressNotInAllowlist,265266 /// Collection name can not be longer than 63 char.267 CollectionNameLimitExceeded,268 /// Collection description can not be longer than 255 char.269 CollectionDescriptionLimitExceeded,270 /// Token prefix can not be longer than 15 char.271 CollectionTokenPrefixLimitExceeded,272 /// Total collections bound exceeded.273 TotalCollectionsLimitExceeded,274 /// variable_data exceeded data limit.275 TokenVariableDataLimitExceeded,276 /// Exceeded max admin count277 CollectionAdminCountExceeded,278279 /// Collection settings not allowing items transferring280 TransferNotAllowed,281 /// Account token limit exceeded per collection282 AccountTokenLimitExceeded,283 /// Collection token limit exceeded284 CollectionTokenLimitExceeded,285 /// Metadata flag frozen286 MetadataFlagFrozen,287288 /// Item not exists.289 TokenNotFound,290 /// Item balance not enough.291 TokenValueTooLow,292 /// Requested value more than approved.293 TokenValueNotEnough,294 /// Tried to approve more than owned295 CantApproveMoreThanOwned,296297 /// Can't transfer tokens to ethereum zero address298 AddressIsZero,299 /// Target collection doesn't supports this operation300 UnsupportedOperation,301 }302303 #[pallet::storage]304 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;305 #[pallet::storage]306 pub type DestroyedCollectionCount<T> =307 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;308309 /// Collection info310 #[pallet::storage]311 pub type CollectionById<T> = StorageMap<312 Hasher = Blake2_128Concat,313 Key = CollectionId,314 Value = Collection<<T as frame_system::Config>::AccountId>,315 QueryKind = OptionQuery,316 >;317318 #[pallet::storage]319 pub type AdminAmount<T> = StorageMap<320 Hasher = Blake2_128Concat,321 Key = CollectionId,322 Value = u32,323 QueryKind = ValueQuery,324 >;325326 /// List of collection admins327 #[pallet::storage]328 pub type IsAdmin<T: Config> = StorageNMap<329 Key = (330 Key<Blake2_128Concat, CollectionId>,331 Key<Blake2_128Concat, T::CrossAccountId>,332 ),333 Value = bool,334 QueryKind = ValueQuery,335 >;336337 /// Allowlisted collection users338 #[pallet::storage]339 pub type Allowlist<T: Config> = StorageNMap<340 Key = (341 Key<Blake2_128Concat, CollectionId>,342 Key<Blake2_128Concat, T::CrossAccountId>,343 ),344 Value = bool,345 QueryKind = ValueQuery,346 >;347348 /// Not used by code, exists only to provide some types to metadata349 #[pallet::storage]350 pub type DummyStorageValue<T> =351 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;352}353354impl<T: Config> Pallet<T> {355 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens356 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {357 ensure!(358 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,359 <Error<T>>::AddressIsZero360 );361 Ok(())362 }363 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {364 <IsAdmin<T>>::iter_prefix((collection,))365 .map(|(a, _)| a)366 .collect()367 }368 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {369 <Allowlist<T>>::iter_prefix((collection,))370 .map(|(a, _)| a)371 .collect()372 }373 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {374 <Allowlist<T>>::get((collection, user))375 }376 pub fn collection_stats() -> CollectionStats {377 let created = <CreatedCollectionCount<T>>::get();378 let destroyed = <DestroyedCollectionCount<T>>::get();379 CollectionStats {380 created: created.0,381 destroyed: destroyed.0,382 alive: created.0 - destroyed.0,383 }384 }385}386387impl<T: Config> Pallet<T> {388 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {389 {390 ensure!(391 data.name.len() <= MAX_COLLECTION_NAME_LENGTH,392 Error::<T>::CollectionNameLimitExceeded393 );394 ensure!(395 data.description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH,396 Error::<T>::CollectionDescriptionLimitExceeded397 );398 ensure!(399 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH,400 Error::<T>::CollectionTokenPrefixLimitExceeded401 );402 }403404 let created_count = <CreatedCollectionCount<T>>::get()405 .0406 .checked_add(1)407 .ok_or(ArithmeticError::Overflow)?;408 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;409 let id = CollectionId(created_count);410411 // bound Total number of collections412 ensure!(413 created_count - destroyed_count < COLLECTION_NUMBER_LIMIT,414 <Error<T>>::TotalCollectionsLimitExceeded415 );416417 // =========418419 // Take a (non-refundable) deposit of collection creation420 {421 let mut imbalance =422 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();423 imbalance.subsume(424 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(425 &T::TreasuryAccountId::get(),426 T::CollectionCreationPrice::get(),427 ),428 );429 <T as Config>::Currency::settle(430 &data.owner,431 imbalance,432 WithdrawReasons::TRANSFER,433 ExistenceRequirement::KeepAlive,434 )435 .map_err(|_| Error::<T>::NoPermission)?;436 }437438 <CreatedCollectionCount<T>>::put(created_count);439 <Pallet<T>>::deposit_event(Event::CollectionCreated(440 id,441 data.mode.id(),442 data.owner.clone(),443 ));444 <CollectionById<T>>::insert(id, data);445 Ok(id)446 }447448 pub fn destroy_collection(449 collection: CollectionHandle<T>,450 sender: &T::CrossAccountId,451 ) -> DispatchResult {452 ensure!(453 collection.limits.owner_can_destroy(),454 <Error<T>>::NoPermission,455 );456 collection.check_is_owner(&sender)?;457458 let destroyed_collections = <DestroyedCollectionCount<T>>::get()459 .0460 .checked_add(1)461 .ok_or(ArithmeticError::Overflow)?;462463 // =========464465 <DestroyedCollectionCount<T>>::put(destroyed_collections);466 <CollectionById<T>>::remove(collection.id);467 <AdminAmount<T>>::remove(collection.id);468 <IsAdmin<T>>::remove_prefix((collection.id,), None);469 <Allowlist<T>>::remove_prefix((collection.id,), None);470 Ok(())471 }472473 pub fn toggle_allowlist(474 collection: &CollectionHandle<T>,475 sender: &T::CrossAccountId,476 user: &T::CrossAccountId,477 allowed: bool,478 ) -> DispatchResult {479 collection.check_is_owner_or_admin(&sender)?;480481 // =========482483 if allowed {484 <Allowlist<T>>::insert((collection.id, user), true);485 } else {486 <Allowlist<T>>::remove((collection.id, user));487 }488489 Ok(())490 }491492 pub fn toggle_admin(493 collection: &CollectionHandle<T>,494 sender: &T::CrossAccountId,495 user: &T::CrossAccountId,496 admin: bool,497 ) -> DispatchResult {498 collection.check_is_owner_or_admin(&sender)?;499500 let was_admin = <IsAdmin<T>>::get((collection.id, user));501 if was_admin == admin {502 return Ok(());503 }504 let amount = <AdminAmount<T>>::get(collection.id);505506 if admin {507 let amount = amount508 .checked_add(1)509 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;510 ensure!(511 amount <= Self::collection_admins_limit(),512 <Error<T>>::CollectionAdminCountExceeded,513 );514515 // =========516517 <AdminAmount<T>>::insert(collection.id, amount);518 <IsAdmin<T>>::insert((collection.id, user), true);519 } else {520 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));521 <IsAdmin<T>>::remove((collection.id, user));522 }523524 Ok(())525 }526}527528#[macro_export]529macro_rules! unsupported {530 () => {531 Err(<Error<T>>::UnsupportedOperation.into())532 };533}534535/// Worst cases536pub trait CommonWeightInfo {537 fn create_item() -> Weight;538 fn create_multiple_items(amount: u32) -> Weight;539 fn burn_item() -> Weight;540 fn transfer() -> Weight;541 fn approve() -> Weight;542 fn transfer_from() -> Weight;543 fn burn_from() -> Weight;544 fn set_variable_metadata(bytes: u32) -> Weight;545}546547pub trait CommonCollectionOperations<T: Config> {548 fn create_item(549 &self,550 sender: T::CrossAccountId,551 to: T::CrossAccountId,552 data: CreateItemData,553 ) -> DispatchResultWithPostInfo;554 fn create_multiple_items(555 &self,556 sender: T::CrossAccountId,557 to: T::CrossAccountId,558 data: Vec<CreateItemData>,559 ) -> DispatchResultWithPostInfo;560 fn burn_item(561 &self,562 sender: T::CrossAccountId,563 token: TokenId,564 amount: u128,565 ) -> DispatchResultWithPostInfo;566567 fn transfer(568 &self,569 sender: T::CrossAccountId,570 to: T::CrossAccountId,571 token: TokenId,572 amount: u128,573 ) -> DispatchResultWithPostInfo;574 fn approve(575 &self,576 sender: T::CrossAccountId,577 spender: T::CrossAccountId,578 token: TokenId,579 amount: u128,580 ) -> DispatchResultWithPostInfo;581 fn transfer_from(582 &self,583 sender: T::CrossAccountId,584 from: T::CrossAccountId,585 to: T::CrossAccountId,586 token: TokenId,587 amount: u128,588 ) -> DispatchResultWithPostInfo;589 fn burn_from(590 &self,591 sender: T::CrossAccountId,592 from: T::CrossAccountId,593 token: TokenId,594 amount: u128,595 ) -> DispatchResultWithPostInfo;596597 fn set_variable_metadata(598 &self,599 sender: T::CrossAccountId,600 token: TokenId,601 data: Vec<u8>,602 ) -> DispatchResultWithPostInfo;603604 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;605 fn token_exists(&self, token: TokenId) -> bool;606 fn last_token_id(&self) -> TokenId;607608 fn token_owner(&self, token: TokenId) -> T::CrossAccountId;609 fn const_metadata(&self, token: TokenId) -> Vec<u8>;610 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;611612 /// How many tokens collection contains (Applicable to nonfungible/refungible)613 fn collection_tokens(&self) -> u32;614 /// Amount of different tokens account has (Applicable to nonfungible/refungible)615 fn account_balance(&self, account: T::CrossAccountId) -> u32;616 /// Amount of specific token account have (Applicable to fungible/refungible)617 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;618 fn allowance(619 &self,620 sender: T::CrossAccountId,621 spender: T::CrossAccountId,622 token: TokenId,623 ) -> u128;624}625626// Flexible enough for implementing CommonCollectionOperations627pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {628 let post_info = PostDispatchInfo {629 actual_weight: Some(weight),630 pays_fee: Pays::Yes,631 };632 match res {633 Ok(()) => Ok(post_info),634 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),635 }636}pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -182,7 +182,7 @@
_token: TokenId,
_data: Vec<u8>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::FungibleItemsHaveData)
+ fail!(<Error<T>>::FungibleItemsDontHaveData)
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -35,7 +35,7 @@
/// Not default id passed as TokenId argument
FungibleItemsHaveNoId,
/// Tried to set data for fungible item
- FungibleItemsHaveData,
+ FungibleItemsDontHaveData,
}
#[pallet::config]
@@ -48,7 +48,7 @@
pub struct Pallet<T>(_);
#[pallet::storage]
- pub(super) type TotalSupply<T: Config> =
+ pub type TotalSupply<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
#[pallet::storage]
@@ -62,7 +62,7 @@
>;
#[pallet::storage]
- pub(super) type Allowance<T: Config> = StorageNMap<
+ pub type Allowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128, T::CrossAccountId>,
pallets/inflation/src/lib.rsdiffbeforeafterboth--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -46,7 +46,8 @@
pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
-pub const YEAR: u32 = 5_259_600;
+// pub const YEAR: u32 = 5_259_600; // 6-second block
+pub const YEAR: u32 = 2_629_800; // 12-second block
pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;
pub const START_INFLATION_PERCENT: u32 = 10;
pub const END_INFLATION_PERCENT: u32 = 4;
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -18,7 +18,7 @@
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
-const YEAR: u64 = 5_259_600;
+const YEAR: u64 = 2_629_800;
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
@@ -112,8 +112,8 @@
// first inflation deposit should be equal to BlockInflation
Inflation::on_initialize(1);
- // SBP M2 review: Verify expected block inflation for year 1
- assert_eq!(Inflation::block_inflation(), 1901);
+ // Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803
+ assert_eq!(Inflation::block_inflation(), 3803);
assert_eq!(
Balances::free_balance(1234) - initial_issuance,
Inflation::block_inflation()
@@ -158,26 +158,21 @@
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
Inflation::on_initialize(1);
- let block_inflation_year_0 = Inflation::block_inflation();
- // SBP M2 review: go through all the block inflations for year 1,
+ // Go through all the block inflations for year 1,
// total issuance will be updated accordingly
for block in (100..YEAR).step_by(100) {
Inflation::on_initialize(block);
}
assert_eq!(
- initial_issuance + (1901 * (YEAR / 100)),
+ initial_issuance + (3803 * (YEAR / 100)),
<Balances as Currency<_>>::total_issuance()
);
Inflation::on_initialize(YEAR);
let block_inflation_year_1 = Inflation::block_inflation();
- // SBP M2 review: Verify expected block inflation for year 2
- assert_eq!(block_inflation_year_1, 1952);
-
- // SBP M2 review: this is actually not true
- // Assert that year 1 inflation is less than year 0
- // assert!(block_inflation_year_0 > block_inflation_year_1);
+ // Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904
+ assert_eq!(block_inflation_year_1, 3904);
});
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -58,7 +58,7 @@
}
#[pallet::pallet]
- #[pallet::generate_store(pub trait Store)]
+ #[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -54,7 +54,7 @@
}
#[pallet::pallet]
- #[pallet::generate_store(pub trait Store)]
+ #[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -738,9 +738,7 @@
use super::*;
use frame_support::{
- Hashable, assert_err, assert_noop, assert_ok, ord_parameter_types, parameter_types,
- traits::{Contains, OnFinalize, OnInitialize},
- weights::constants::RocksDbWeight,
+ ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,
};
use sp_core::H256;
use sp_runtime::{
@@ -749,7 +747,6 @@
traits::{BlakeTwo256, IdentityLookup},
};
use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};
- use substrate_test_utils::assert_eq_uvec;
use crate as scheduler;
mod logger {
@@ -758,9 +755,6 @@
thread_local! {
static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());
- }
- pub fn log() -> Vec<(OriginCaller, u32)> {
- LOG.with(|log| log.borrow().clone())
}
pub trait Config: system::Config {
type Event: From<Event> + Into<<Self as system::Config>::Event>;
@@ -871,24 +865,5 @@
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type WeightInfo = ();
type SponsorshipHandler = ();
- }
-
- pub fn new_test_ext() -> sp_io::TestExternalities {
- let t = system::GenesisConfig::default()
- .build_storage::<Test>()
- .unwrap();
- t.into()
- }
-
- fn run_to_block(n: u64) {
- while System::block_number() < n {
- Scheduler::on_finalize(System::block_number());
- System::set_block_number(System::block_number() + 1);
- Scheduler::on_initialize(System::block_number());
- }
- }
-
- fn root() -> OriginCaller {
- system::RawOrigin::Root.into()
}
}
pallets/unique/src/mock.rsdiffbeforeafterboth--- a/pallets/unique/src/mock.rs
+++ b/pallets/unique/src/mock.rs
@@ -10,7 +10,7 @@
use pallet_transaction_payment::{CurrencyAdapter};
use frame_system as system;
use pallet_evm::AddressMapping;
-use crate::{EvmBackwardsAddressMapping, CrossAccountId};
+use pallet_common::account::{EvmBackwardsAddressMapping, CrossAccountId};
use codec::{Encode, Decode};
use scale_info::TypeInfo;
@@ -27,6 +27,10 @@
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
TemplateModule: pallet_template::{Pallet, Call, Storage},
Balances: pallet_balances::{Pallet, Call, Storage},
+ Common: pallet_common::{Pallet, Storage, Event<T>},
+ Fungible: pallet_fungible::{Pallet, Storage},
+ Refungible: pallet_refungible::{Pallet, Storage},
+ Nonfungible: pallet_nonfungible::{Pallet, Storage},
}
);
@@ -124,13 +128,16 @@
#[derive(Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, TypeInfo)]
pub struct TestCrossAccountId(u64, sp_core::H160);
impl CrossAccountId<u64> for TestCrossAccountId {
+ fn as_sub(&self) -> &u64 {
+ &self.0
+ }
+ fn as_eth(&self) -> &sp_core::H160 {
+ &self.1
+ }
fn from_sub(sub: u64) -> Self {
let mut eth = [0; 20];
eth[12..20].copy_from_slice(&sub.to_be_bytes());
Self(sub, sp_core::H160(eth))
- }
- fn as_sub(&self) -> &u64 {
- &self.0
}
fn from_eth(eth: sp_core::H160) -> Self {
let mut sub_raw = [0; 8];
@@ -138,11 +145,17 @@
let sub = u64::from_be_bytes(sub_raw);
Self(sub, eth)
}
- fn as_eth(&self) -> &sp_core::H160 {
- &self.1
+ fn conv_eq(&self, other: &Self) -> bool {
+ self.as_sub() == other.as_sub()
}
}
+impl Default for TestCrossAccountId {
+ fn default() -> Self {
+ Self::from_sub(0)
+ }
+}
+
pub struct TestEtheremTransactionSender;
impl pallet_ethereum::EthereumTransactionSender for TestEtheremTransactionSender {
fn submit_logs_transaction(
@@ -157,15 +170,29 @@
type EthereumTransactionSender = TestEtheremTransactionSender;
}
-impl pallet_template::Config for Test {
+impl pallet_common::Config for Test {
type Event = ();
- type WeightInfo = ();
- type CollectionCreationPrice = CollectionCreationPrice;
- type Currency = pallet_balances::Pallet<Test>;
- type TreasuryAccountId = TreasuryAccountId;
- type EvmAddressMapping = TestEvmAddressMapping;
type EvmBackwardsAddressMapping = TestEvmBackwardsAddressMapping;
+ type EvmAddressMapping = TestEvmAddressMapping;
type CrossAccountId = TestCrossAccountId;
+
+ type Currency = Balances;
+ type CollectionCreationPrice = CollectionCreationPrice;
+ type TreasuryAccountId = TreasuryAccountId;
+}
+
+impl pallet_fungible::Config for Test {
+ type WeightInfo = ();
+}
+impl pallet_refungible::Config for Test {
+ type WeightInfo = ();
+}
+impl pallet_nonfungible::Config for Test {
+ type WeightInfo = ();
+}
+
+impl pallet_template::Config for Test {
+ type WeightInfo = ();
}
// Build genesis storage according to the mock runtime.
pallets/unique/src/tests.rsdiffbeforeafterboth--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -1,10 +1,11 @@
// Tests to be written here
use super::*;
use crate::mock::*;
-use crate::{AccessMode, CollectionMode, Ownership, CreateItemData};
+use crate::{AccessMode, CollectionMode};
use up_data_structs::{
- CreateNftData, CreateFungibleData, CreateReFungibleData, CollectionId, TokenId,
- MAX_DECIMAL_POINTS,
+ COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
+ CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
+ TokenId,
};
use frame_support::{assert_noop, assert_ok};
use sp_std::convert::TryInto;
@@ -49,18 +50,30 @@
let saved_col_name: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let saved_description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let saved_prefix: Vec<u8> = b"token_prefix1\0".to_vec();
- assert_eq!(TemplateModule::collection_id(id).unwrap().owner, owner);
assert_eq!(
- TemplateModule::collection_id(id).unwrap().name,
+ <pallet_common::CollectionById<Test>>::get(id)
+ .unwrap()
+ .owner,
+ owner
+ );
+ assert_eq!(
+ <pallet_common::CollectionById<Test>>::get(id).unwrap().name,
saved_col_name
);
- assert_eq!(TemplateModule::collection_id(id).unwrap().mode, *mode);
assert_eq!(
- TemplateModule::collection_id(id).unwrap().description,
+ <pallet_common::CollectionById<Test>>::get(id).unwrap().mode,
+ *mode
+ );
+ assert_eq!(
+ <pallet_common::CollectionById<Test>>::get(id)
+ .unwrap()
+ .description,
saved_description
);
assert_eq!(
- TemplateModule::collection_id(id).unwrap().token_prefix,
+ <pallet_common::CollectionById<Test>>::get(id)
+ .unwrap()
+ .token_prefix,
saved_prefix
);
id
@@ -91,7 +104,7 @@
fn set_version_schema() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
assert_ok!(TemplateModule::set_schema_version(
origin1,
@@ -99,7 +112,7 @@
SchemaVersion::Unique
));
assert_eq!(
- TemplateModule::collection_id(collection_id)
+ <pallet_common::CollectionById<Test>>::get(collection_id)
.unwrap()
.schema_version,
SchemaVersion::Unique
@@ -131,11 +144,12 @@
#[test]
fn create_nft_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let data = default_nft_data();
create_test_item(collection_id, &data.clone().into());
- let item = TemplateModule::nft_item_id(collection_id, 1).unwrap();
+
+ let item = <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1)).unwrap();
assert_eq!(item.const_data, data.const_data.into_inner());
assert_eq!(item.variable_data, data.variable_data.into_inner());
});
@@ -146,7 +160,7 @@
#[test]
fn create_nft_multiple_items() {
new_test_ext().execute_with(|| {
- create_test_collection(&CollectionMode::NFT, 1);
+ create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -154,7 +168,7 @@
assert_ok!(TemplateModule::create_multiple_items(
origin1,
- 1,
+ CollectionId(1),
account(1),
items_data
.clone()
@@ -163,7 +177,11 @@
.collect()
));
for (index, data) in items_data.into_iter().enumerate() {
- let item = TemplateModule::nft_item_id(1, (index + 1) as TokenId).unwrap();
+ let item = <pallet_nonfungible::TokenData<Test>>::get((
+ CollectionId(1),
+ TokenId((index + 1) as u32),
+ ))
+ .unwrap();
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
}
@@ -173,27 +191,23 @@
#[test]
fn create_refungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let data = default_re_fungible_data();
create_test_item(collection_id, &data.clone().into());
- let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();
+ let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
+ let balance =
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
assert_eq!(item.const_data, data.const_data.into_inner());
assert_eq!(item.variable_data, data.variable_data.into_inner());
- assert_eq!(
- item.owner[0],
- Ownership {
- owner: account(1),
- fraction: 1023
- }
- );
+ assert_eq!(balance, 1023);
});
}
#[test]
fn create_multiple_refungible_items() {
new_test_ext().execute_with(|| {
- create_test_collection(&CollectionMode::ReFungible, 1);
+ create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -205,7 +219,7 @@
assert_ok!(TemplateModule::create_multiple_items(
origin1,
- 1,
+ CollectionId(1),
account(1),
items_data
.clone()
@@ -214,16 +228,15 @@
.collect()
));
for (index, data) in items_data.into_iter().enumerate() {
- let item = TemplateModule::refungible_item_id(1, (index + 1) as TokenId).unwrap();
+ let item = <pallet_refungible::TokenData<Test>>::get((
+ CollectionId(1),
+ TokenId((index + 1) as u32),
+ ));
+ let balance =
+ <pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
- assert_eq!(
- item.owner[0],
- Ownership {
- owner: account(1),
- fraction: 1023
- }
- );
+ assert_eq!(balance, 1023);
}
});
}
@@ -231,12 +244,15 @@
#[test]
fn create_fungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
let data = default_fungible_data();
create_test_item(collection_id, &data.into());
- assert_eq!(TemplateModule::fungible_item_id(collection_id, 1).value, 5);
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+ 5
+ );
});
}
@@ -245,7 +261,7 @@
// new_test_ext().execute_with(|| {
// default_limits();
-// create_test_collection(&CollectionMode::Fungible(3), 1);
+// create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
// let origin1 = Origin::signed(1);
@@ -269,7 +285,7 @@
#[test]
fn transfer_fungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -277,155 +293,287 @@
let data = default_fungible_data();
create_test_item(collection_id, &data.into());
- assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 5);
- assert_eq!(TemplateModule::balance_count(1, 1), 5);
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((CollectionId(1), account(1))),
+ 5
+ );
// change owner scenario
- assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 5));
- assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 0);
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
- assert_eq!(TemplateModule::balance_count(1, 2), 5);
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(0),
+ 5
+ ));
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((CollectionId(1), account(1))),
+ 0
+ );
// split item scenario
assert_ok!(TemplateModule::transfer(
origin2.clone(),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(0),
3
));
- assert_eq!(TemplateModule::balance_count(1, 2), 2);
- assert_eq!(TemplateModule::balance_count(1, 3), 3);
// split item and new owner has account scenario
- assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 1));
- assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 1);
- assert_eq!(TemplateModule::fungible_item_id(1, 3).value, 4);
- assert_eq!(TemplateModule::balance_count(1, 2), 1);
- assert_eq!(TemplateModule::balance_count(1, 3), 4);
+ assert_ok!(TemplateModule::transfer(
+ origin2,
+ account(3),
+ CollectionId(1),
+ TokenId(0),
+ 1
+ ));
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((CollectionId(1), account(2))),
+ 1
+ );
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((CollectionId(1), account(3))),
+ 4
+ );
});
}
#[test]
fn transfer_refungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
+ // Create RFT 1 in 1023 pieces for account 1
let data = default_re_fungible_data();
create_test_item(collection_id, &data.clone().into());
+ let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
+ assert_eq!(item.const_data, data.const_data.into_inner());
+ assert_eq!(item.variable_data, data.variable_data.into_inner());
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+ 1023
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ // Account 1 transfers all 1023 pieces of RFT 1 to account 2
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
- {
- let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();
- assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
- assert_eq!(
- item.owner[0],
- Ownership {
- owner: account(1),
- fraction: 1023
- }
- );
- }
- assert_eq!(TemplateModule::balance_count(1, 1), 1023);
- assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
-
- // change owner scenario
- assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1023));
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1023
+ ));
assert_eq!(
- TemplateModule::refungible_item_id(1, 1).unwrap().owner[0],
- Ownership {
- owner: account(2),
- fraction: 1023
- }
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+ 1023
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ false
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ true
);
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
- assert_eq!(TemplateModule::balance_count(1, 2), 1023);
- // assert_eq!(TemplateModule::address_tokens(1, 1), []);
- assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
- // split item scenario
+ // Account 2 transfers 500 pieces of RFT 1 to account 3
assert_ok!(TemplateModule::transfer(
origin2.clone(),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
500
));
- {
- let item = TemplateModule::refungible_item_id(1, 1).unwrap();
- assert_eq!(
- item.owner[0],
- Ownership {
- owner: account(2),
- fraction: 523
- }
- );
- assert_eq!(
- item.owner[1],
- Ownership {
- owner: account(3),
- fraction: 500
- }
- );
- }
- assert_eq!(TemplateModule::balance_count(1, 2), 523);
- assert_eq!(TemplateModule::balance_count(1, 3), 500);
- assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
- assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+ 523
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+ 500
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(3), TokenId(1))),
+ true
+ );
- // split item and new owner has account scenario
- assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 200));
- {
- let item = TemplateModule::refungible_item_id(1, 1).unwrap();
- assert_eq!(
- item.owner[0],
- Ownership {
- owner: account(2),
- fraction: 323
- }
- );
- assert_eq!(
- item.owner[1],
- Ownership {
- owner: account(3),
- fraction: 700
- }
- );
- }
- assert_eq!(TemplateModule::balance_count(1, 2), 323);
- assert_eq!(TemplateModule::balance_count(1, 3), 700);
- assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
- assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
+ // Account 2 transfers 200 more pieces of RFT 1 to account 3 with pre-existing balance
+ assert_ok!(TemplateModule::transfer(
+ origin2,
+ account(3),
+ CollectionId(1),
+ TokenId(1),
+ 200
+ ));
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+ 323
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+ 700
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(3), TokenId(1))),
+ true
+ );
});
}
#[test]
fn transfer_nft_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
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]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
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, 1), []);
- assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ ));
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ false
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ true
+ );
+ });
+}
+
+#[test]
+fn transfer_nft_item_wrong_value() {
+ new_test_ext().execute_with(|| {
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+
+ let origin1 = Origin::signed(1);
+
+ assert_noop!(
+ TemplateModule::transfer(origin1, account(2), CollectionId(1), TokenId(1), 2)
+ .map_err(|e| e.error),
+ <pallet_nonfungible::Error::<Test>>::NonfungibleItemsHaveNoAmount
+ );
});
}
#[test]
+fn transfer_nft_item_zero_value() {
+ new_test_ext().execute_with(|| {
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+
+ let origin1 = Origin::signed(1);
+
+ // Transferring 0 amount works on NFT...
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 0
+ ));
+ // ... and results in no transfer
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ });
+}
+
+#[test]
fn nft_approve_and_transfer_from() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let data = default_nft_data();
create_test_item(collection_id, &data.into());
@@ -433,197 +581,286 @@
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
- assert_eq!(TemplateModule::balance_count(1, 1), 1);
- assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
- // neg transfer
+ // neg transfer_from
assert_noop!(
- TemplateModule::transfer_from(origin2.clone(), account(1), account(2), 1, 1, 1),
- Error::<Test>::NoPermission
+ TemplateModule::transfer_from(
+ origin2.clone(),
+ account(1),
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenValueNotEnough
);
// do approve
- assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 5));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
+ assert_ok!(TemplateModule::approve(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ ));
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(2)
+ );
assert_ok!(TemplateModule::transfer_from(
origin2,
account(1),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);
+ assert!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).is_none()
+ );
});
}
#[test]
fn nft_approve_and_transfer_from_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ // Create NFT 1 for account 1
let data = default_nft_data();
create_test_item(collection_id, &data.clone().into());
-
assert_eq!(
- &TemplateModule::nft_item_id(1, 1).unwrap().const_data,
+ &<pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
+ .unwrap()
+ .const_data,
&data.const_data.into_inner()
);
- assert_eq!(TemplateModule::balance_count(1, 1), 1);
- assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ // Allow allow-list users to mint and add accounts 1, 2, and 3 to allow-list
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
- 1,
+ CollectionId(1),
true
));
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 1,
+ CollectionId(1),
AccessMode::AllowList
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(1)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(2)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(3)
));
- // do approve
+ // Account 1 approves account 2 for NFT 1
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(2),
- 1,
- 1,
- 5
+ CollectionId(1),
+ TokenId(1),
+ 1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
- assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));
- assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(2)
+ );
+ // Account 2 transfers NFT 1 from account 1 to account 3
assert_ok!(TemplateModule::transfer_from(
origin2,
account(1),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);
+ assert!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).is_none()
+ );
});
}
#[test]
fn refungible_approve_and_transfer_from() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ // Create RFT 1 in 1023 pieces for account 1
let data = default_re_fungible_data();
create_test_item(collection_id, &data.into());
- assert_eq!(TemplateModule::balance_count(1, 1), 1023);
- assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+ 1023
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ // Allow public minting, enable allow-list and add accounts 1, 2, 3 to allow-list
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
- 1,
+ CollectionId(1),
true
));
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 1,
+ CollectionId(1),
AccessMode::AllowList
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(1)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(2)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(3)
));
- // do approve
- assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1023));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1023);
+ // Account 1 approves account 2 for 1023 pieces of RFT 1
+ assert_ok!(TemplateModule::approve(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1023
+ ));
+ assert_eq!(
+ <pallet_refungible::Allowance<Test>>::get((
+ CollectionId(1),
+ TokenId(1),
+ account(1),
+ account(2)
+ )),
+ 1023
+ );
+ // Account 2 transfers 100 pieces of RFT 1 from account 1 to account 3
assert_ok!(TemplateModule::transfer_from(
origin2,
account(1),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
100
));
- assert_eq!(TemplateModule::balance_count(1, 1), 923);
- assert_eq!(TemplateModule::balance_count(1, 3), 100);
- assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
-
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 923);
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+ 923
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+ 100
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_refungible::Allowance<Test>>::get((
+ CollectionId(1),
+ TokenId(1),
+ account(1),
+ account(2)
+ )),
+ 923
+ );
});
}
#[test]
fn fungible_approve_and_transfer_from() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
let data = default_fungible_data();
create_test_item(collection_id, &data.into());
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
-
- assert_eq!(TemplateModule::balance_count(1, 1), 5);
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
- 1,
+ CollectionId(1),
true
));
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 1,
+ CollectionId(1),
AccessMode::AllowList
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(1)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(2)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(3)
));
@@ -631,31 +868,55 @@
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(2),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(0),
5
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
- assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));
- assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
+ assert_eq!(
+ <pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+ 5
+ );
+ assert_ok!(TemplateModule::approve(
+ origin1,
+ account(3),
+ CollectionId(1),
+ TokenId(0),
+ 5
+ ));
+ assert_eq!(
+ <pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+ 5
+ );
+ assert_eq!(
+ <pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(3))),
+ 5
+ );
assert_ok!(TemplateModule::transfer_from(
origin2.clone(),
account(1),
account(3),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(0),
4
));
- assert_eq!(TemplateModule::balance_count(1, 1), 1);
- assert_eq!(TemplateModule::balance_count(1, 3), 4);
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+ assert_eq!(
+ <pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+ 1
+ );
assert_noop!(
- TemplateModule::transfer_from(origin2, account(1), account(3), 1, 1, 4),
- Error::<Test>::NoPermission
+ TemplateModule::transfer_from(
+ origin2,
+ account(1),
+ account(3),
+ CollectionId(1),
+ TokenId(0),
+ 4
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenValueNotEnough
);
});
}
@@ -663,7 +924,7 @@
#[test]
fn change_collection_owner() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::change_collection_owner(
@@ -672,7 +933,9 @@
2
));
assert_eq!(
- TemplateModule::collection_id(collection_id).unwrap().owner,
+ <pallet_common::CollectionById<Test>>::get(collection_id)
+ .unwrap()
+ .owner,
2
);
});
@@ -681,7 +944,7 @@
#[test]
fn destroy_collection() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));
@@ -691,41 +954,74 @@
#[test]
fn burn_nft_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
- assert_ok!(TemplateModule::add_collection_admin(
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+
+ // check balance (collection with id = 1, user id = 1)
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+
+ // burn item
+ assert_ok!(TemplateModule::burn_item(
origin1.clone(),
collection_id,
- account(2)
+ TokenId(1),
+ 1
));
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 0
+ );
+ });
+}
+
+#[test]
+fn burn_same_nft_item_twice() {
+ new_test_ext().execute_with(|| {
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+ let origin1 = Origin::signed(1);
let data = default_nft_data();
create_test_item(collection_id, &data.into());
// check balance (collection with id = 1, user id = 1)
- assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
// burn item
assert_ok!(TemplateModule::burn_item(
origin1.clone(),
collection_id,
- 1,
+ TokenId(1),
1
));
+
+ // burn item again
assert_noop!(
- TemplateModule::burn_item(origin1, collection_id, 1, 1),
- Error::<Test>::TokenNotFound
+ TemplateModule::burn_item(origin1, collection_id, TokenId(1), 1).map_err(|e| e.error),
+ CommonError::<Test>::TokenNotFound
);
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 0
+ );
});
}
#[test]
fn burn_fungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::add_collection_admin(
@@ -738,23 +1034,62 @@
create_test_item(collection_id, &data.into());
// check balance (collection with id = 1, user id = 1)
- assert_eq!(TemplateModule::balance_count(1, 1), 5);
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+ 5
+ );
// burn item
- assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
+ assert_ok!(TemplateModule::burn_item(
+ origin1.clone(),
+ CollectionId(1),
+ TokenId(0),
+ 5
+ ));
assert_noop!(
- TemplateModule::burn_item(origin1, 1, 1, 5),
- Error::<Test>::TokenValueNotEnough
+ TemplateModule::burn_item(origin1, CollectionId(1), TokenId(0), 5).map_err(|e| e.error),
+ CommonError::<Test>::TokenValueTooLow
);
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+ 0
+ );
});
}
#[test]
+fn burn_fungible_item_with_token_id() {
+ new_test_ext().execute_with(|| {
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
+
+ let origin1 = Origin::signed(1);
+ assert_ok!(TemplateModule::add_collection_admin(
+ origin1.clone(),
+ collection_id,
+ account(2)
+ ));
+
+ let data = default_fungible_data();
+ create_test_item(collection_id, &data.into());
+
+ // check balance (collection with id = 1, user id = 1)
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+ 5
+ );
+
+ // Try to burn item using Token ID
+ assert_noop!(
+ TemplateModule::burn_item(origin1, CollectionId(1), TokenId(1), 5).map_err(|e| e.error),
+ <pallet_fungible::Error::<Test>>::FungibleItemsHaveNoId
+ );
+ });
+}
+#[test]
fn burn_refungible_item() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_mint_permission(
@@ -769,13 +1104,13 @@
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ collection_id,
account(1)
));
assert_ok!(TemplateModule::add_collection_admin(
origin1.clone(),
- 1,
+ collection_id,
account(2)
));
@@ -783,29 +1118,43 @@
create_test_item(collection_id, &data.into());
// check balance (collection with id = 1, user id = 2)
- assert_eq!(TemplateModule::balance_count(1, 1), 1023);
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+ 1023
+ );
// burn item
- assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));
+ assert_ok!(TemplateModule::burn_item(
+ origin1.clone(),
+ collection_id,
+ TokenId(1),
+ 1023
+ ));
assert_noop!(
- TemplateModule::burn_item(origin1, 1, 1, 1023),
- Error::<Test>::TokenNotFound
+ TemplateModule::burn_item(origin1, collection_id, TokenId(1), 1023)
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenValueTooLow
);
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(
+ <pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+ 0
+ );
});
}
#[test]
fn add_collection_admin() {
new_test_ext().execute_with(|| {
- let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
- create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);
- create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);
-
+ let collection1_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
let origin1 = Origin::signed(1);
- // collection admin
+ // Add collection admins
assert_ok!(TemplateModule::add_collection_admin(
origin1.clone(),
collection1_id,
@@ -817,22 +1166,31 @@
account(3)
));
- assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(2)),);
- assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(3)),);
+ // Owner is not an admin by default
+ assert_eq!(
+ <pallet_common::IsAdmin<Test>>::get((CollectionId(1), account(1))),
+ false
+ );
+ assert!(<pallet_common::IsAdmin<Test>>::get((
+ CollectionId(1),
+ account(2)
+ )));
+ assert!(<pallet_common::IsAdmin<Test>>::get((
+ CollectionId(1),
+ account(3)
+ )));
});
}
#[test]
fn remove_collection_admin() {
new_test_ext().execute_with(|| {
- let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
- create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);
- create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);
-
+ let collection1_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
- // collection admin
+ // Add collection admins 2 and 3
assert_ok!(TemplateModule::add_collection_admin(
origin1.clone(),
collection1_id,
@@ -844,31 +1202,54 @@
account(3)
));
- assert!(TemplateModule::admin_list_collection(1).contains(&account(2)),);
- assert!(TemplateModule::admin_list_collection(1).contains(&account(3)),);
+ assert!(<pallet_common::IsAdmin<Test>>::get((
+ CollectionId(1),
+ account(2)
+ )));
+ assert!(<pallet_common::IsAdmin<Test>>::get((
+ CollectionId(1),
+ account(3)
+ )));
- // remove admin
+ // remove admin 3
assert_ok!(TemplateModule::remove_collection_admin(
origin2,
- 1,
+ CollectionId(1),
account(3)
));
- assert!(!TemplateModule::admin_list_collection(1).contains(&account(3)),);
+
+ // 2 is still admin, 3 is not an admin anymore
+ assert!(<pallet_common::IsAdmin<Test>>::get((
+ CollectionId(1),
+ account(2)
+ )));
+ assert_eq!(
+ <pallet_common::IsAdmin<Test>>::get((CollectionId(1), account(3))),
+ false
+ );
});
}
#[test]
fn balance_of() {
new_test_ext().execute_with(|| {
- let nft_collection_id = create_test_collection(&CollectionMode::NFT, 1);
- let fungible_collection_id = create_test_collection(&CollectionMode::Fungible(3), 2);
- let re_fungible_collection_id = create_test_collection(&CollectionMode::ReFungible, 3);
+ let nft_collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+ let fungible_collection_id =
+ create_test_collection(&CollectionMode::Fungible(3), CollectionId(2));
+ let re_fungible_collection_id =
+ create_test_collection(&CollectionMode::ReFungible, CollectionId(3));
// check balance before
- assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 0);
- assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 0);
assert_eq!(
- TemplateModule::balance_count(re_fungible_collection_id, 1),
+ <pallet_nonfungible::AccountBalance<Test>>::get((nft_collection_id, account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_fungible::Balance<Test>>::get((fungible_collection_id, account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_refungible::AccountBalance<Test>>::get((re_fungible_collection_id, account(1))),
0
);
@@ -882,28 +1263,30 @@
create_test_item(re_fungible_collection_id, &re_fungible_data.into());
// check balance (collection with id = 1, user id = 1)
- assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 1);
- assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 5);
assert_eq!(
- TemplateModule::balance_count(re_fungible_collection_id, 1),
- 1023
+ <pallet_nonfungible::AccountBalance<Test>>::get((nft_collection_id, account(1))),
+ 1
);
assert_eq!(
- TemplateModule::nft_item_id(nft_collection_id, 1)
- .unwrap()
- .owner,
- account(1)
+ <pallet_fungible::Balance<Test>>::get((fungible_collection_id, account(1))),
+ 5
);
assert_eq!(
- TemplateModule::fungible_item_id(fungible_collection_id, 1).value,
- 5
+ <pallet_refungible::AccountBalance<Test>>::get((re_fungible_collection_id, account(1))),
+ 1
);
+
assert_eq!(
- TemplateModule::refungible_item_id(re_fungible_collection_id, 1)
- .unwrap()
- .owner[0]
- .owner,
- account(1)
+ <pallet_nonfungible::Owned<Test>>::get((nft_collection_id, account(1), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_refungible::Owned<Test>>::get((
+ re_fungible_collection_id,
+ account(1),
+ TokenId(1)
+ )),
+ true
);
});
}
@@ -911,7 +1294,7 @@
#[test]
fn approve() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let data = default_nft_data();
create_test_item(collection_id, &data.into());
@@ -919,15 +1302,24 @@
let origin1 = Origin::signed(1);
// approve
- assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+ assert_ok!(TemplateModule::approve(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ ));
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(2)
+ );
});
}
#[test]
fn transfer_from() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -938,46 +1330,59 @@
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(2),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(2)
+ );
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
- 1,
+ CollectionId(1),
true
));
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
- 1,
+ CollectionId(1),
AccessMode::AllowList
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(1)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ CollectionId(1),
account(2)
));
- assert_ok!(TemplateModule::add_to_allow_list(origin1, 1, account(3)));
+ assert_ok!(TemplateModule::add_to_allow_list(
+ origin1,
+ CollectionId(1),
+ account(3)
+ ));
assert_ok!(TemplateModule::transfer_from(
origin2,
account(1),
account(2),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
1
));
// after transfer
- assert_eq!(TemplateModule::balance_count(1, 1), 0);
- assert_eq!(TemplateModule::balance_count(1, 2), 1);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((CollectionId(1), account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((CollectionId(1), account(2))),
+ 1
+ );
});
}
@@ -989,7 +1394,7 @@
#[test]
fn owner_can_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::add_to_allow_list(
@@ -997,14 +1402,17 @@
collection_id,
account(2)
));
- assert!(TemplateModule::allow_list(collection_id, 2));
+ assert!(<pallet_common::Allowlist<Test>>::get((
+ collection_id,
+ account(2)
+ )));
});
}
#[test]
fn admin_can_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1018,19 +1426,22 @@
collection_id,
account(3)
));
- assert!(TemplateModule::allow_list(collection_id, 3));
+ assert!(<pallet_common::Allowlist<Test>>::get((
+ collection_id,
+ account(3)
+ )));
});
}
#[test]
fn nonprivileged_user_cannot_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin2 = Origin::signed(2);
assert_noop!(
TemplateModule::add_to_allow_list(origin2, collection_id, account(3)),
- Error::<Test>::NoPermission
+ CommonError::<Test>::NoPermission
);
});
}
@@ -1041,8 +1452,8 @@
let origin1 = Origin::signed(1);
assert_noop!(
- TemplateModule::add_to_allow_list(origin1, 1, account(2)),
- Error::<Test>::CollectionNotFound
+ TemplateModule::add_to_allow_list(origin1, CollectionId(1), account(2)),
+ CommonError::<Test>::CollectionNotFound
);
});
}
@@ -1050,7 +1461,7 @@
#[test]
fn nobody_can_add_address_to_allow_list_of_deleted_collection() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::destroy_collection(
@@ -1059,7 +1470,7 @@
));
assert_noop!(
TemplateModule::add_to_allow_list(origin1, collection_id, account(2)),
- Error::<Test>::CollectionNotFound
+ CommonError::<Test>::CollectionNotFound
);
});
}
@@ -1068,7 +1479,7 @@
#[test]
fn address_is_already_added_to_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::add_to_allow_list(
@@ -1081,14 +1492,17 @@
collection_id,
account(2)
));
- assert!(TemplateModule::allow_list(collection_id, 2));
+ assert!(<pallet_common::Allowlist<Test>>::get((
+ collection_id,
+ account(2)
+ )));
});
}
#[test]
fn owner_can_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::add_to_allow_list(
@@ -1101,41 +1515,51 @@
collection_id,
account(2)
));
- assert!(!TemplateModule::allow_list(collection_id, 2));
+ assert_eq!(
+ <pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+ false
+ );
});
}
#[test]
fn admin_can_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ // Owner adds admin
assert_ok!(TemplateModule::add_collection_admin(
origin1.clone(),
collection_id,
account(2)
));
+ // Owner adds address 3 to allow list
assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(3)
));
+
+ // Admin removes address 3 from allow list
assert_ok!(TemplateModule::remove_from_allow_list(
origin2,
collection_id,
account(3)
));
- assert!(!TemplateModule::allow_list(collection_id, 3));
+ assert_eq!(
+ <pallet_common::Allowlist<Test>>::get((collection_id, account(3))),
+ false
+ );
});
}
#[test]
fn nonprivileged_user_cannot_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1146,9 +1570,12 @@
));
assert_noop!(
TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
- Error::<Test>::NoPermission
+ CommonError::<Test>::NoPermission
);
- assert!(TemplateModule::allow_list(collection_id, 2));
+ assert!(<pallet_common::Allowlist<Test>>::get((
+ collection_id,
+ account(2)
+ )));
});
}
@@ -1158,8 +1585,8 @@
let origin1 = Origin::signed(1);
assert_noop!(
- TemplateModule::remove_from_allow_list(origin1, 1, account(2)),
- Error::<Test>::CollectionNotFound
+ TemplateModule::remove_from_allow_list(origin1, CollectionId(1), account(2)),
+ CommonError::<Test>::CollectionNotFound
);
});
}
@@ -1167,21 +1594,37 @@
#[test]
fn nobody_can_remove_address_from_allow_list_of_deleted_collection() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
+ // Add account 2 to allow list
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
));
+
+ // Account 2 is in collection allow-list
+ assert!(<pallet_common::Allowlist<Test>>::get((
+ collection_id,
+ account(2)
+ )));
+
+ // Destroy collection
assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));
+
+ // Attempt to remove account 2 from collection allow-list => error
assert_noop!(
TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
- Error::<Test>::CollectionNotFound
+ CommonError::<Test>::CollectionNotFound
+ );
+
+ // Account 2 is not found in collection allow-list anyway
+ assert_eq!(
+ <pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+ false
);
- assert!(!TemplateModule::allow_list(collection_id, 2));
});
}
@@ -1189,7 +1632,7 @@
#[test]
fn address_is_already_removed_from_allow_list() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::add_to_allow_list(
@@ -1202,12 +1645,19 @@
collection_id,
account(2)
));
+ assert_eq!(
+ <pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+ false
+ );
assert_ok!(TemplateModule::remove_from_allow_list(
origin1,
collection_id,
account(2)
));
- assert!(!TemplateModule::allow_list(collection_id, 2));
+ assert_eq!(
+ <pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+ false
+ );
});
}
@@ -1215,7 +1665,7 @@
#[test]
fn allow_list_test_1() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1234,8 +1684,9 @@
));
assert_noop!(
- TemplateModule::transfer(origin1, account(3), 1, 1, 1),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::transfer(origin1, account(3), CollectionId(1), TokenId(1), 1)
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1243,7 +1694,7 @@
#[test]
fn allow_list_test_2() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_nft_data();
@@ -1256,12 +1707,12 @@
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ collection_id,
account(1)
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ collection_id,
account(2)
));
@@ -1269,21 +1720,32 @@
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(1),
- 1,
- 1,
+ collection_id,
+ TokenId(1),
1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(1)
+ );
assert_ok!(TemplateModule::remove_from_allow_list(
origin1.clone(),
- 1,
+ collection_id,
account(1)
));
assert_noop!(
- TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::transfer_from(
+ origin1,
+ account(1),
+ account(3),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1292,7 +1754,7 @@
#[test]
fn allow_list_test_3() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1306,13 +1768,14 @@
));
assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
- 1,
+ collection_id,
account(1)
));
assert_noop!(
- TemplateModule::transfer(origin1, account(3), 1, 1, 1),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::transfer(origin1, account(3), collection_id, TokenId(1), 1)
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1320,7 +1783,7 @@
#[test]
fn allow_list_test_4() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1347,11 +1810,14 @@
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(1),
- 1,
- 1,
+ collection_id,
+ TokenId(1),
1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(1)
+ );
assert_ok!(TemplateModule::remove_from_allow_list(
origin1.clone(),
@@ -1360,8 +1826,16 @@
));
assert_noop!(
- TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::transfer_from(
+ origin1,
+ account(1),
+ account(3),
+ collection_id,
+ TokenId(1),
+ 1
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1370,7 +1844,7 @@
#[test]
fn allow_list_test_5() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1383,8 +1857,9 @@
AccessMode::AllowList
));
assert_noop!(
- TemplateModule::burn_item(origin1.clone(), 1, 1, 5),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::burn_item(origin1.clone(), CollectionId(1), TokenId(1), 1)
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1393,7 +1868,7 @@
#[test]
fn allow_list_test_6() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1408,8 +1883,9 @@
// do approve
assert_noop!(
- TemplateModule::approve(origin1, account(1), 1, 1, 5),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::approve(origin1, account(1), CollectionId(1), TokenId(1), 1)
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1419,7 +1895,7 @@
#[test]
fn allow_list_test_7() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let data = default_nft_data();
create_test_item(collection_id, &data.into());
@@ -1442,20 +1918,28 @@
account(2)
));
- assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1));
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ CollectionId(1),
+ TokenId(1),
+ 1
+ ));
});
}
#[test]
fn allow_list_test_8() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+ // Create NFT for account 1
let data = default_nft_data();
create_test_item(collection_id, &data.into());
let origin1 = Origin::signed(1);
+ // Toggle Allow List mode and add accounts 1 and 2
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
@@ -1472,22 +1956,26 @@
account(2)
));
- // do approve
+ // Sself-approve account 1 for NFT 1
assert_ok!(TemplateModule::approve(
origin1.clone(),
account(1),
- 1,
- 1,
- 5
+ CollectionId(1),
+ TokenId(1),
+ 1
));
- assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 5);
+ assert_eq!(
+ <pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+ account(1)
+ );
+ // Transfer from 1 to 2
assert_ok!(TemplateModule::transfer_from(
origin1,
account(1),
account(2),
- 1,
- 1,
+ CollectionId(1),
+ TokenId(1),
1
));
});
@@ -1497,7 +1985,7 @@
#[test]
fn allow_list_test_9() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_public_access_mode(
@@ -1520,7 +2008,7 @@
#[test]
fn allow_list_test_10() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1555,7 +2043,7 @@
#[test]
fn allow_list_test_11() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1577,8 +2065,14 @@
));
assert_noop!(
- TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
- Error::<Test>::PublicMintingNotAllowed
+ TemplateModule::create_item(
+ origin2,
+ CollectionId(1),
+ account(2),
+ default_nft_data().into()
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::PublicMintingNotAllowed
);
});
}
@@ -1587,7 +2081,7 @@
#[test]
fn allow_list_test_12() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1604,8 +2098,14 @@
));
assert_noop!(
- TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
- Error::<Test>::PublicMintingNotAllowed
+ TemplateModule::create_item(
+ origin2,
+ CollectionId(1),
+ account(2),
+ default_nft_data().into()
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::PublicMintingNotAllowed
);
});
}
@@ -1614,7 +2114,7 @@
#[test]
fn allow_list_test_13() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1638,7 +2138,7 @@
#[test]
fn allow_list_test_14() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1662,7 +2162,7 @@
assert_ok!(TemplateModule::create_item(
origin2,
- 1,
+ collection_id,
account(2),
default_nft_data().into()
));
@@ -1673,7 +2173,7 @@
#[test]
fn allow_list_test_15() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1690,8 +2190,14 @@
));
assert_noop!(
- TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
- Error::<Test>::AddresNotInAllowList
+ TemplateModule::create_item(
+ origin2,
+ collection_id,
+ account(2),
+ default_nft_data().into()
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::AddressNotInAllowlist
);
});
}
@@ -1700,7 +2206,7 @@
#[test]
fn allow_list_test_16() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -1723,7 +2229,7 @@
assert_ok!(TemplateModule::create_item(
origin2,
- 1,
+ collection_id,
account(2),
default_nft_data().into()
));
@@ -1734,18 +2240,27 @@
#[test]
fn total_number_collections_bound() {
new_test_ext().execute_with(|| {
- create_test_collection(&CollectionMode::NFT, 1);
+ create_test_collection(&CollectionMode::NFT, CollectionId(1));
});
}
-// Total number of collections. Negotive test
#[test]
+fn create_max_collections() {
+ new_test_ext().execute_with(|| {
+ for i in 1..=COLLECTION_NUMBER_LIMIT {
+ create_test_collection(&CollectionMode::NFT, CollectionId(i));
+ }
+ });
+}
+
+// Total number of collections. Negative test
+#[test]
fn total_number_collections_bound_neg() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
- for i in 0..COLLECTION_NUMBER_LIMIT {
- create_test_collection(&CollectionMode::NFT, i + 1);
+ for i in 1..=COLLECTION_NUMBER_LIMIT {
+ create_test_collection(&CollectionMode::NFT, CollectionId(i));
}
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
@@ -1761,7 +2276,7 @@
token_prefix1,
CollectionMode::NFT
),
- Error::<Test>::TotalCollectionsLimitExceeded
+ CommonError::<Test>::TotalCollectionsLimitExceeded
);
});
}
@@ -1770,7 +2285,7 @@
#[test]
fn owned_tokens_bound() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let data = default_nft_data();
create_test_item(collection_id, &data.clone().into());
@@ -1782,19 +2297,20 @@
#[test]
fn owned_tokens_bound_neg() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
- for _ in 0..ACCOUNT_TOKEN_OWNERSHIP_LIMIT {
+ for _ in 1..=MAX_TOKEN_OWNERSHIP {
let data = default_nft_data();
create_test_item(collection_id, &data.clone().into());
}
let data = default_nft_data();
assert_noop!(
- TemplateModule::create_item(origin1, 1, account(1), data.into()),
- Error::<Test>::AccountTokenLimitExceeded
+ TemplateModule::create_item(origin1, CollectionId(1), account(1), data.into())
+ .map_err(|e| e.error),
+ CommonError::<Test>::AccountTokenLimitExceeded
);
});
}
@@ -1803,7 +2319,7 @@
#[test]
fn collection_admins_bound() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1824,7 +2340,7 @@
#[test]
fn collection_admins_bound_neg() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -1832,16 +2348,16 @@
assert_ok!(TemplateModule::add_collection_admin(
origin1.clone(),
collection_id,
- account(2 + i)
+ account((2 + i).into())
));
}
assert_noop!(
TemplateModule::add_collection_admin(
origin1,
collection_id,
- account(3 + COLLECTION_ADMINS_LIMIT)
+ account((3 + COLLECTION_ADMINS_LIMIT).into())
),
- Error::<Test>::CollectionAdminsLimitExceeded
+ CommonError::<Test>::CollectionAdminCountExceeded
);
});
}
@@ -1850,7 +2366,7 @@
#[test]
fn set_const_on_chain_schema() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_const_on_chain_schema(
@@ -1860,13 +2376,13 @@
));
assert_eq!(
- TemplateModule::collection_id(collection_id)
+ <pallet_common::CollectionById<Test>>::get(collection_id)
.unwrap()
.const_on_chain_schema,
b"test const on chain schema".to_vec()
);
assert_eq!(
- TemplateModule::collection_id(collection_id)
+ <pallet_common::CollectionById<Test>>::get(collection_id)
.unwrap()
.variable_on_chain_schema,
b"".to_vec()
@@ -1877,7 +2393,7 @@
#[test]
fn set_variable_on_chain_schema() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_variable_on_chain_schema(
@@ -1887,13 +2403,13 @@
));
assert_eq!(
- TemplateModule::collection_id(collection_id)
+ <pallet_common::CollectionById<Test>>::get(collection_id)
.unwrap()
.const_on_chain_schema,
b"".to_vec()
);
assert_eq!(
- TemplateModule::collection_id(collection_id)
+ <pallet_common::CollectionById<Test>>::get(collection_id)
.unwrap()
.variable_on_chain_schema,
b"test variable on chain schema".to_vec()
@@ -1904,23 +2420,23 @@
#[test]
fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(CollectionId(1), &data.into());
let variable_data = b"test data".to_vec();
assert_ok!(TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
));
assert_eq!(
- TemplateModule::nft_item_id(collection_id, 1)
+ <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
.unwrap()
.variable_data,
variable_data
@@ -1931,25 +2447,23 @@
#[test]
fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_re_fungible_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
let variable_data = b"test data".to_vec();
assert_ok!(TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
));
assert_eq!(
- TemplateModule::refungible_item_id(collection_id, 1)
- .unwrap()
- .variable_data,
+ <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1))).variable_data,
variable_data
);
});
@@ -1958,17 +2472,23 @@
#[test]
fn set_variable_meta_data_on_fungible_token_fails() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+ let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_fungible_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
let variable_data = b"test data".to_vec();
assert_noop!(
- TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
- Error::<Test>::CantStoreMetadataInFungibleTokens
+ TemplateModule::set_variable_meta_data(
+ origin1,
+ collection_id,
+ TokenId(0),
+ variable_data
+ )
+ .map_err(|e| e.error),
+ <pallet_fungible::Error<Test>>::FungibleItemsDontHaveData
);
});
}
@@ -1976,17 +2496,23 @@
#[test]
fn set_variable_meta_data_on_nft_token_fails_for_big_data() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
assert_noop!(
- TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
- Error::<Test>::TokenVariableDataLimitExceeded
+ TemplateModule::set_variable_meta_data(
+ origin1,
+ collection_id,
+ TokenId(1),
+ variable_data
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenVariableDataLimitExceeded
);
});
}
@@ -1994,17 +2520,23 @@
#[test]
fn set_variable_meta_data_on_re_fungible_token_fails_for_big_data() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+ let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_re_fungible_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
assert_noop!(
- TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
- Error::<Test>::TokenVariableDataLimitExceeded
+ TemplateModule::set_variable_meta_data(
+ origin1,
+ collection_id,
+ TokenId(1),
+ variable_data
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenVariableDataLimitExceeded
);
});
}
@@ -2014,12 +2546,12 @@
new_test_ext().execute_with(|| {
//default_limits();
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
assert_ok!(TemplateModule::set_meta_update_permission_flag(
origin1.clone(),
@@ -2031,12 +2563,12 @@
assert_ok!(TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
));
assert_eq!(
- TemplateModule::nft_item_id(collection_id, 1)
+ <pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
.unwrap()
.variable_data,
variable_data
@@ -2047,7 +2579,8 @@
#[test]
fn set_variable_meta_data_on_nft_with_item_owner_permission_flag_neg() {
new_test_ext().execute_with(|| {
- let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
+ let collection_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
let origin1 = Origin::signed(1);
@@ -2063,7 +2596,7 @@
));
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
assert_ok!(TemplateModule::set_meta_update_permission_flag(
origin1.clone(),
@@ -2076,10 +2609,11 @@
TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
- ),
- Error::<Test>::TokenVariableDataLimitExceeded
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::TokenVariableDataLimitExceeded
);
})
}
@@ -2089,23 +2623,50 @@
new_test_ext().execute_with(|| {
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 collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+ assert_ok!(TemplateModule::set_transfers_enabled_flag(
+ origin1,
+ collection_id,
+ 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]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
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]);
+ assert_ok!(TemplateModule::transfer(
+ origin1,
+ account(2),
+ collection_id,
+ TokenId(1),
+ 1
+ ));
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ false
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 0
+ );
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 1
+ );
});
}
@@ -2114,7 +2675,8 @@
new_test_ext().execute_with(|| {
// default_limits();
- let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+ let collection_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -2137,7 +2699,7 @@
));
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
assert_ok!(TemplateModule::set_meta_update_permission_flag(
origin2.clone(),
@@ -2149,12 +2711,12 @@
assert_ok!(TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
));
assert_eq!(
- TemplateModule::nft_item_id(collection_id, 1)
+ <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
.unwrap()
.variable_data,
variable_data
@@ -2167,7 +2729,8 @@
new_test_ext().execute_with(|| {
// default_limits();
- let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+ let collection_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -2184,7 +2747,7 @@
));
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
assert_ok!(TemplateModule::set_meta_update_permission_flag(
origin2.clone(),
@@ -2197,10 +2760,11 @@
TemplateModule::set_variable_meta_data(
origin1,
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
- ),
- Error::<Test>::NoPermission
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::NoPermission
);
});
}
@@ -2210,7 +2774,8 @@
new_test_ext().execute_with(|| {
// default_limits();
- let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+ let collection_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
let origin2 = Origin::signed(2);
@@ -2225,7 +2790,7 @@
collection_id,
MetaUpdatePermission::Admin
),
- Error::<Test>::MetadataFlagFrozen
+ CommonError::<Test>::MetadataFlagFrozen
);
});
}
@@ -2235,11 +2800,12 @@
new_test_ext().execute_with(|| {
// default_limits();
- let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
+ let collection_id =
+ create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
let origin1 = Origin::signed(1);
let data = default_nft_data();
- create_test_item(1, &data.into());
+ create_test_item(collection_id, &data.into());
assert_ok!(TemplateModule::set_meta_update_permission_flag(
origin1.clone(),
@@ -2252,10 +2818,11 @@
TemplateModule::set_variable_meta_data(
origin1.clone(),
collection_id,
- 1,
+ TokenId(1),
variable_data.clone()
- ),
- Error::<Test>::MetadataUpdateDenied
+ )
+ .map_err(|e| e.error),
+ CommonError::<Test>::NoPermission
);
});
}
@@ -2265,27 +2832,47 @@
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
- let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
assert_ok!(TemplateModule::set_transfers_enabled_flag(
- origin1, 1, false
+ origin1,
+ collection_id,
+ 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]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
let origin1 = Origin::signed(1);
// default scenario
assert_noop!(
- TemplateModule::transfer(origin1, account(2), 1, 1, 1000),
- Error::<Test>::TransferNotAllowed
+ TemplateModule::transfer(origin1, account(2), CollectionId(1), TokenId(1), 1)
+ .map_err(|e| e.error),
+ CommonError::<Test>::TransferNotAllowed
+ );
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+ 1
);
- 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]);
+ assert_eq!(
+ <pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+ 0
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+ true
+ );
+ assert_eq!(
+ <pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+ false
+ );
});
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -29,10 +29,14 @@
pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
-pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;
+pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {
+ 10_000_000
+} else {
+ 10
+};
pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
- 100000
+ 100_000
} else {
10
};
@@ -44,7 +48,7 @@
pub const COLLECTION_ADMINS_LIMIT: u32 = 5;
pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;
pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
- 1000000
+ 1_000_000
} else {
10
};