difftreelog
refactor move properties around
in: master
18 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -73,13 +73,6 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Option<CrossAccountId>>;
- #[rpc(name = "unique_constMetadata")]
- fn const_metadata(
- &self,
- collection: CollectionId,
- token: TokenId,
- at: Option<BlockHash>,
- ) -> Result<Vec<u8>>;
#[rpc(name = "unique_collectionProperties")]
fn collection_properties(
@@ -418,9 +411,6 @@
);
pass_method!(
topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
- );
- pass_method!(
- const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>, unique_api
);
pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -86,8 +86,6 @@
let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
- let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
- let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
handler(
owner,
CreateCollectionData {
@@ -95,8 +93,6 @@
name,
description,
token_prefix,
- offchain_schema,
- const_on_chain_schema,
..Default::default()
},
)
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -55,7 +55,6 @@
SponsoringRateLimit,
budget::Budget,
COLLECTION_FIELD_LIMIT,
- CollectionField,
PhantomType,
Property,
Properties,
@@ -77,6 +76,8 @@
RmrkPartType,
RmrkTheme,
RmrkNftChild,
+ CollectionPermissions,
+ SchemaVersion,
};
pub use pallet::*;
@@ -433,17 +434,6 @@
Hasher = Blake2_128Concat,
Key = CollectionId,
Value = PropertiesPermissionMap,
- QueryKind = ValueQuery,
- >;
-
- /// Large variable-size collection fields are extracted here
- #[pallet::storage]
- pub type CollectionData<T> = StorageNMap<
- Key = (
- Key<Twox64Concat, CollectionId>,
- Key<Twox64Concat, CollectionField>,
- ),
- Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,
QueryKind = ValueQuery,
>;
@@ -505,19 +495,37 @@
if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
use up_data_structs::{CollectionVersion1, CollectionVersion2};
<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {
- Self::set_field_raw(
- id,
- CollectionField::OffchainSchema,
- v.offchain_schema.clone().into_inner(),
- )
- .expect("data has lower bounds than field");
- Self::set_field_raw(
+ let mut props = Vec::new();
+ if !v.offchain_schema.is_empty() {
+ props.push(Property {
+ key: b"_old_offchainSchema".to_vec().try_into().unwrap(),
+ value: v.offchain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+ });
+ }
+ if !v.variable_on_chain_schema.is_empty() {
+ props.push(Property {
+ key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),
+ value: v.variable_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+ });
+ }
+ if !v.const_on_chain_schema.is_empty() {
+ props.push(Property {
+ key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),
+ value: v.const_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
+ });
+ }
+ props.push(Property {
+ key: b"_old_schemaVersion".to_vec().try_into().unwrap(),
+ value: match v.schema_version {
+ SchemaVersion::ImageURL => b"ImageUrl".as_slice(),
+ SchemaVersion::Unique => b"Unique".as_slice(),
+ }.to_vec().try_into().unwrap(),
+ });
+ Self::set_scoped_collection_properties(
id,
- CollectionField::ConstOnChainSchema,
- v.const_on_chain_schema.clone().into_inner(),
- )
- .expect("data has lower bounds than field");
-
+ PropertyScope::None,
+ props.into_iter(),
+ ).expect("existing data larger than properties");
Some(CollectionVersion2::from(v))
});
}
@@ -587,7 +595,6 @@
owner_can_transfer: Some(limits.owner_can_transfer()),
owner_can_destroy: Some(limits.owner_can_destroy()),
transfers_enabled: Some(limits.transfers_enabled()),
- nesting_rule: Some(limits.nesting_rule().clone()),
};
Some(effective_limits)
@@ -599,12 +606,10 @@
description,
owner,
mode,
- access,
token_prefix,
- mint_mode,
- schema_version,
sponsorship,
limits,
+ permissions,
} = <CollectionById<T>>::get(collection)?;
let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
@@ -628,28 +633,45 @@
description: description.into_inner(),
owner,
mode,
- access,
token_prefix: token_prefix.into_inner(),
- mint_mode,
- schema_version,
sponsorship,
limits,
- offchain_schema: <CollectionData<T>>::get((
- collection,
- CollectionField::OffchainSchema,
- ))
- .into_inner(),
- const_on_chain_schema: <CollectionData<T>>::get((
- collection,
- CollectionField::ConstOnChainSchema,
- ))
- .into_inner(),
+ permissions,
token_property_permissions,
properties,
})
}
}
+macro_rules! limit_default {
+ ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+ $(
+ if let Some($new) = $new.$field {
+ let $old = $old.$field($($arg)?);
+ let _ = $new;
+ let _ = $old;
+ $check
+ } else {
+ $new.$field = $old.$field
+ }
+ )*
+ }};
+}
+macro_rules! limit_default_clone {
+ ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+ $(
+ if let Some($new) = $new.$field.clone() {
+ let $old = $old.$field($($arg)?);
+ let _ = $new;
+ let _ = $old;
+ $check
+ } else {
+ $new.$field = $old.$field.clone()
+ }
+ )*
+ }};
+}
+
impl<T: Config> Pallet<T> {
pub fn init_collection(
owner: T::AccountId,
@@ -681,11 +703,8 @@
owner: owner.clone(),
name: data.name,
mode: data.mode.clone(),
- mint_mode: false,
- access: data.access.unwrap_or_default(),
description: data.description,
token_prefix: data.token_prefix,
- schema_version: data.schema_version.unwrap_or_default(),
sponsorship: data
.pending_sponsor
.map(SponsorshipState::Unconfirmed)
@@ -694,6 +713,10 @@
.limits
.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+ permissions: data
+ .permissions
+ .map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))
+ .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
};
let mut collection_properties = up_data_structs::CollectionProperties::get();
@@ -732,18 +755,6 @@
<CreatedCollectionCount<T>>::put(created_count);
<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
<CollectionById<T>>::insert(id, collection);
- Self::set_field_raw(
- id,
- CollectionField::OffchainSchema,
- data.offchain_schema.into_inner(),
- )
- .expect("data has lower bounds than field");
- Self::set_field_raw(
- id,
- CollectionField::ConstOnChainSchema,
- data.const_on_chain_schema.into_inner(),
- )
- .expect("data has lower bounds than field");
Ok(id)
}
@@ -766,7 +777,6 @@
<DestroyedCollectionCount<T>>::put(destroyed_collections);
<CollectionById<T>>::remove(collection.id);
- <CollectionData<T>>::remove_prefix((collection.id,), None);
<AdminAmount<T>>::remove(collection.id);
<IsAdmin<T>>::remove_prefix((collection.id,), None);
<Allowlist<T>>::remove_prefix((collection.id,), None);
@@ -866,6 +876,18 @@
Ok(())
}
+ // For migrations
+ pub fn set_property_permission_unchecked(
+ collection: CollectionId,
+ property_permission: PropertyKeyPermission,
+ ) -> DispatchResult {
+ <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {
+ permissions.try_set(property_permission.key, property_permission.permission)
+ })
+ .map_err(<Error<T>>::from)?;
+ Ok(())
+ }
+
pub fn set_property_permission(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -989,35 +1011,6 @@
Ok(key_permissions)
}
- fn set_field_raw(
- collection_id: CollectionId,
- field: CollectionField,
- value: Vec<u8>,
- ) -> DispatchResult {
- if !value.is_empty() {
- <CollectionData<T>>::insert(
- (collection_id, field),
- BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,
- )
- } else {
- <CollectionData<T>>::remove((collection_id, field));
- }
- Ok(())
- }
-
- pub fn set_field(
- collection: &CollectionHandle<T>,
- sender: &T::CrossAccountId,
- field: CollectionField,
- value: Vec<u8>,
- ) -> DispatchResult {
- collection.check_is_owner_or_admin(sender)?;
-
- // =========
-
- Self::set_field_raw(collection.id, field, value)
- }
-
pub fn toggle_allowlist(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -1077,21 +1070,6 @@
old_limit: &CollectionLimits,
mut new_limit: CollectionLimits,
) -> Result<CollectionLimits, DispatchError> {
- macro_rules! limit_default {
- ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
- $(
- if let Some($new) = $new.$field {
- let $old = $old.$field($($arg)?);
- let _ = $new;
- let _ = $old;
- $check
- } else {
- $new.$field = $old.$field
- }
- )*
- }};
- }
-
limit_default!(old_limit, new_limit,
account_token_ownership_limit => ensure!(
new_limit <= MAX_TOKEN_OWNERSHIP,
@@ -1126,6 +1104,15 @@
);
Ok(new_limit)
}
+ pub fn clamp_permissions(
+ mode: CollectionMode,
+ old_limit: &CollectionPermissions,
+ mut new_limit: CollectionPermissions,
+ ) -> Result<CollectionPermissions, DispatchError> {
+ limit_default_clone!(old_limit, new_limit,
+ );
+ Ok(new_limit)
+ }
}
#[macro_export]
@@ -1253,7 +1240,6 @@
fn last_token_id(&self) -> TokenId;
fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
- fn const_metadata(&self, token: TokenId) -> Vec<u8>;
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;
/// Amount of unique collection tokens
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -51,27 +51,27 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_collection_properties(amount: u32) -> Weight {
+ fn set_collection_properties(_amount: u32) -> Weight {
// Error
0
}
- fn delete_collection_properties(amount: u32) -> Weight {
+ fn delete_collection_properties(_amount: u32) -> Weight {
// Error
0
}
- fn set_token_properties(amount: u32) -> Weight {
+ fn set_token_properties(_amount: u32) -> Weight {
// Error
0
}
- fn delete_token_properties(amount: u32) -> Weight {
+ fn delete_token_properties(_amount: u32) -> Weight {
// Error
0
}
- fn set_property_permissions(amount: u32) -> Weight {
+ fn set_property_permissions(_amount: u32) -> Weight {
// Error
0
}
@@ -320,9 +320,6 @@
fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
None
- }
- fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
- Vec::new()
}
fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -168,7 +168,7 @@
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(owner)?;
}
@@ -210,7 +210,7 @@
<CommonError<T>>::TransferNotAllowed,
);
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -280,7 +280,7 @@
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
- collection.mint_mode,
+ collection.permissions.mint_mode(),
<CommonError<T>>::PublicMintingNotAllowed
);
collection.check_allowlist(sender)?;
@@ -380,7 +380,7 @@
spender: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(owner)?;
collection.check_allowlist(spender)?;
}
@@ -408,7 +408,7 @@
if spender.conv_eq(from) {
return Ok(None);
}
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -29,9 +29,7 @@
const SEED: u32 = 1;
fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
- let const_data = create_data::<CUSTOM_DATA_LIMIT>();
CreateItemData::<T> {
- const_data,
owner,
properties: Default::default(),
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -116,7 +116,6 @@
) -> Result<CreateItemData<T>, DispatchError> {
match data {
up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
- const_data: data.const_data,
properties: data.properties,
owner: to.clone(),
}),
@@ -376,12 +375,6 @@
fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
<TokenData<T>>::get((self.id, token)).map(|t| t.owner)
- }
- fn const_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .map(|t| t.const_data)
- .unwrap_or_default()
- .into_inner()
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -109,15 +109,6 @@
}
}
-fn error_unsupported_schema_version() -> Error {
- alloc::format!(
- "Unsupported schema version! Support only {:?}",
- SchemaVersion::ImageURL
- )
- .as_str()
- .into()
-}
-
#[derive(ToLog)]
pub enum ERC721Events {
Transfer {
@@ -167,16 +158,10 @@
/// Returns token's const_metadata
#[solidity(rename_selector = "tokenURI")]
fn token_uri(&self, token_id: uint256) -> Result<string> {
- if !matches!(self.schema_version, SchemaVersion::ImageURL) {
- return Err(error_unsupported_schema_version());
- }
-
self.consume_store_reads(1)?;
- let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+ let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
Ok(string::from_utf8_lossy(
- &<TokenData<T>>::get((self.id, token_id))
- .ok_or("token not found")?
- .const_data,
+ todo!()
)
.into())
}
@@ -344,7 +329,6 @@
self,
&caller,
CreateItemData::<T> {
- const_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to,
},
@@ -366,10 +350,6 @@
token_id: uint256,
token_uri: string,
) -> Result<bool> {
- if !matches!(self.schema_version, SchemaVersion::ImageURL) {
- return Err(error_unsupported_schema_version());
- }
-
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
@@ -385,13 +365,12 @@
return Err("item id should be next".into());
}
+ todo!("token uri");
+
<Pallet<T>>::create_item(
self,
&caller,
CreateItemData::<T> {
- const_data: Vec::<u8>::from(token_uri)
- .try_into()
- .map_err(|_| "token uri is too long")?,
properties: BoundedVec::default(),
owner: to,
},
@@ -477,7 +456,6 @@
}
let data = (0..total_tokens)
.map(|_| CreateItemData::<T> {
- const_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to.clone(),
})
@@ -496,10 +474,6 @@
to: address,
tokens: Vec<(uint256, string)>,
) -> Result<bool> {
- if !matches!(self.schema_version, SchemaVersion::ImageURL) {
- return Err(error_unsupported_schema_version());
- }
-
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let mut expected_index = <TokensMinted<T>>::get(self.id)
@@ -517,10 +491,8 @@
}
expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+ todo!("token uri");
data.push(CreateItemData::<T> {
- const_data: Vec::<u8>::from(token_uri)
- .try_into()
- .map_err(|_| "token uri is too long")?,
properties: BoundedVec::default(),
owner: to.clone(),
});
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55 pub const_data: BoundedVec<u8, CustomDataLimit>,5657 #[version(..2)]58 pub variable_data: BoundedVec<u8, CustomDataLimit>,5960 pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65 use super::*;66 use frame_support::{67 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68 };69 use frame_system::pallet_prelude::*;70 use up_data_structs::{CollectionId, TokenId};71 use super::weights::WeightInfo;7273 #[pallet::error]74 pub enum Error<T> {75 /// Not Nonfungible item data used to mint in Nonfungible collection.76 NotNonfungibleDataUsedToMintFungibleCollectionToken,77 /// Used amount > 1 with NFT78 NonfungibleItemsHaveNoAmount,79 }8081 #[pallet::config]82 pub trait Config:83 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84 {85 type WeightInfo: WeightInfo;86 }8788 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990 #[pallet::pallet]91 #[pallet::storage_version(STORAGE_VERSION)]92 #[pallet::generate_store(pub(super) trait Store)]93 pub struct Pallet<T>(_);9495 #[pallet::storage]96 pub type TokensMinted<T: Config> =97 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98 #[pallet::storage]99 pub type TokensBurnt<T: Config> =100 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102 #[pallet::storage]103 pub type TokenData<T: Config> = StorageNMap<104 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105 Value = ItemData<T::CrossAccountId>,106 QueryKind = OptionQuery,107 >;108109 #[pallet::storage]110 #[pallet::getter(fn token_properties)]111 pub type TokenProperties<T: Config> = StorageNMap<112 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113 Value = Properties,114 QueryKind = ValueQuery,115 OnEmpty = up_data_structs::TokenProperties,116 >;117118 /// Used to enumerate tokens owned by account119 #[pallet::storage]120 pub type Owned<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 Key<Twox64Concat, TokenId>,125 ),126 Value = bool,127 QueryKind = ValueQuery,128 >;129130 #[pallet::storage]131 pub type AccountBalance<T: Config> = StorageNMap<132 Key = (133 Key<Twox64Concat, CollectionId>,134 Key<Blake2_128Concat, T::CrossAccountId>,135 ),136 Value = u32,137 QueryKind = ValueQuery,138 >;139140 #[pallet::storage]141 pub type Allowance<T: Config> = StorageNMap<142 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143 Value = T::CrossAccountId,144 QueryKind = OptionQuery,145 >;146147 #[pallet::hooks]148 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149 fn on_runtime_upgrade() -> Weight {150 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151 <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {152 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))153 })154 }155156 0157 }158 }159}160161pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);162impl<T: Config> NonfungibleHandle<T> {163 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {164 Self(inner)165 }166 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {167 self.0168 }169 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {170 &mut self.0171 }172}173impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {174 fn recorder(&self) -> &SubstrateRecorder<T> {175 self.0.recorder()176 }177 fn into_recorder(self) -> SubstrateRecorder<T> {178 self.0.into_recorder()179 }180}181impl<T: Config> Deref for NonfungibleHandle<T> {182 type Target = pallet_common::CollectionHandle<T>;183184 fn deref(&self) -> &Self::Target {185 &self.0186 }187}188189impl<T: Config> Pallet<T> {190 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {191 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)192 }193 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {194 <TokenData<T>>::contains_key((collection.id, token))195 }196197 pub fn set_scoped_token_property(198 collection_id: CollectionId,199 token_id: TokenId,200 scope: PropertyScope,201 property: Property,202 ) -> DispatchResult {203 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {204 properties.try_scoped_set(scope, property.key, property.value)205 })206 .map_err(<CommonError<T>>::from)?;207208 Ok(())209 }210211 pub fn set_scoped_token_properties(212 collection_id: CollectionId,213 token_id: TokenId,214 scope: PropertyScope,215 properties: impl Iterator<Item=Property>,216 ) -> DispatchResult {217 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {218 stored_properties.try_scoped_set_from_iter(scope, properties)219 })220 .map_err(<CommonError<T>>::from)?;221222 Ok(())223 }224225 pub fn current_token_id(collection_id: CollectionId) -> TokenId {226 TokenId(<TokensMinted<T>>::get(collection_id))227 }228}229230// unchecked calls skips any permission checks231impl<T: Config> Pallet<T> {232 pub fn init_collection(233 owner: T::AccountId,234 data: CreateCollectionData<T::AccountId>,235 ) -> Result<CollectionId, DispatchError> {236 <PalletCommon<T>>::init_collection(owner, data)237 }238 pub fn destroy_collection(239 collection: NonfungibleHandle<T>,240 sender: &T::CrossAccountId,241 ) -> DispatchResult {242 let id = collection.id;243244 // =========245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <TokenData<T>>::remove_prefix((id,), None);249 <Owned<T>>::remove_prefix((id,), None);250 <TokensMinted<T>>::remove(id);251 <TokensBurnt<T>>::remove(id);252 <Allowance<T>>::remove_prefix((id,), None);253 <AccountBalance<T>>::remove_prefix((id,), None);254 Ok(())255 }256257 pub fn burn(258 collection: &NonfungibleHandle<T>,259 sender: &T::CrossAccountId,260 token: TokenId,261 ) -> DispatchResult {262 let token_data =263 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;264 ensure!(265 &token_data.owner == sender266 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),267 <CommonError<T>>::NoPermission268 );269270 if collection.access == AccessMode::AllowList {271 collection.check_allowlist(sender)?;272 }273274 let burnt = <TokensBurnt<T>>::get(collection.id)275 .checked_add(1)276 .ok_or(ArithmeticError::Overflow)?;277278 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))279 .checked_sub(1)280 .ok_or(ArithmeticError::Overflow)?;281282 if balance == 0 {283 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));284 } else {285 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);286 }287 // =========288289 <Owned<T>>::remove((collection.id, &token_data.owner, token));290 <TokensBurnt<T>>::insert(collection.id, burnt);291 <TokenData<T>>::remove((collection.id, token));292 <TokenProperties<T>>::remove((collection.id, token));293 let old_spender = <Allowance<T>>::take((collection.id, token));294295 if let Some(old_spender) = old_spender {296 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(297 collection.id,298 token,299 sender.clone(),300 old_spender,301 0,302 ));303 }304305 <PalletEvm<T>>::deposit_log(306 ERC721Events::Transfer {307 from: *token_data.owner.as_eth(),308 to: H160::default(),309 token_id: token.into(),310 }311 .to_log(collection_id_to_address(collection.id)),312 );313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 token_data.owner,317 1,318 ));319 Ok(())320 }321322 pub fn set_token_property(323 collection: &NonfungibleHandle<T>,324 sender: &T::CrossAccountId,325 token_id: TokenId,326 property: Property,327 ) -> DispatchResult {328 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;329330 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {331 let property = property.clone();332 properties.try_set(property.key, property.value)333 })334 .map_err(<CommonError<T>>::from)?;335336 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(337 collection.id,338 token_id,339 property.key,340 ));341342 Ok(())343 }344345 #[transactional]346 pub fn set_token_properties(347 collection: &NonfungibleHandle<T>,348 sender: &T::CrossAccountId,349 token_id: TokenId,350 properties: Vec<Property>,351 ) -> DispatchResult {352 for property in properties {353 Self::set_token_property(collection, sender, token_id, property)?;354 }355356 Ok(())357 }358359 pub fn delete_token_property(360 collection: &NonfungibleHandle<T>,361 sender: &T::CrossAccountId,362 token_id: TokenId,363 property_key: PropertyKey,364 ) -> DispatchResult {365 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;366367 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {368 properties.remove(&property_key)369 })370 .map_err(<CommonError<T>>::from)?;371372 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(373 collection.id,374 token_id,375 property_key,376 ));377378 Ok(())379 }380381 fn check_token_change_permission(382 collection: &NonfungibleHandle<T>,383 sender: &T::CrossAccountId,384 token_id: TokenId,385 property_key: &PropertyKey,386 ) -> DispatchResult {387 let permission = <PalletCommon<T>>::property_permissions(collection.id)388 .get(property_key)389 .cloned()390 .unwrap_or_else(PropertyPermission::none);391392 let token_data = <TokenData<T>>::get((collection.id, token_id))393 .ok_or(<CommonError<T>>::TokenNotFound)?;394395 let check_token_owner = || -> DispatchResult {396 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);397 Ok(())398 };399400 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))401 .get(property_key)402 .is_some();403404 match permission {405 PropertyPermission { mutable: false, .. } if is_property_exists => {406 Err(<CommonError<T>>::NoPermission.into())407 }408409 PropertyPermission {410 collection_admin,411 token_owner,412 ..413 } => {414 let mut check_result = Err(<CommonError<T>>::NoPermission.into());415416 if collection_admin {417 check_result = collection.check_is_owner_or_admin(sender);418 }419420 if token_owner {421 check_result.or_else(|_| check_token_owner())422 } else {423 check_result424 }425 }426 }427 }428429 #[transactional]430 pub fn delete_token_properties(431 collection: &NonfungibleHandle<T>,432 sender: &T::CrossAccountId,433 token_id: TokenId,434 property_keys: Vec<PropertyKey>,435 ) -> DispatchResult {436 for key in property_keys {437 Self::delete_token_property(collection, sender, token_id, key)?;438 }439440 Ok(())441 }442443 pub fn set_collection_properties(444 collection: &NonfungibleHandle<T>,445 sender: &T::CrossAccountId,446 properties: Vec<Property>,447 ) -> DispatchResult {448 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)449 }450451 pub fn delete_collection_properties(452 collection: &CollectionHandle<T>,453 sender: &T::CrossAccountId,454 property_keys: Vec<PropertyKey>,455 ) -> DispatchResult {456 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)457 }458459 pub fn set_property_permissions(460 collection: &CollectionHandle<T>,461 sender: &T::CrossAccountId,462 property_permissions: Vec<PropertyKeyPermission>,463 ) -> DispatchResult {464 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)465 }466467 pub fn set_property_permission(468 collection: &CollectionHandle<T>,469 sender: &T::CrossAccountId,470 permission: PropertyKeyPermission,471 ) -> DispatchResult {472 <PalletCommon<T>>::set_property_permission(collection, sender, permission)473 }474475 pub fn transfer(476 collection: &NonfungibleHandle<T>,477 from: &T::CrossAccountId,478 to: &T::CrossAccountId,479 token: TokenId,480 nesting_budget: &dyn Budget,481 ) -> DispatchResult {482 ensure!(483 collection.limits.transfers_enabled(),484 <CommonError<T>>::TransferNotAllowed485 );486487 let token_data =488 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;489 // TODO: require sender to be token, owner, require admins to go through transfer_from490 ensure!(491 &token_data.owner == from492 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),493 <CommonError<T>>::NoPermission494 );495496 if collection.access == AccessMode::AllowList {497 collection.check_allowlist(from)?;498 collection.check_allowlist(to)?;499 }500 <PalletCommon<T>>::ensure_correct_receiver(to)?;501502 let balance_from = <AccountBalance<T>>::get((collection.id, from))503 .checked_sub(1)504 .ok_or(<CommonError<T>>::TokenValueTooLow)?;505 let balance_to = if from != to {506 let balance_to = <AccountBalance<T>>::get((collection.id, to))507 .checked_add(1)508 .ok_or(ArithmeticError::Overflow)?;509510 ensure!(511 balance_to < collection.limits.account_token_ownership_limit(),512 <CommonError<T>>::AccountTokenLimitExceeded,513 );514515 Some(balance_to)516 } else {517 None518 };519520 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {521 let handle = <CollectionHandle<T>>::try_get(target.0)?;522 let dispatch = T::CollectionDispatch::dispatch(handle);523 let dispatch = dispatch.as_dyn();524525 dispatch.check_nesting(526 from.clone(),527 (collection.id, token),528 target.1,529 nesting_budget,530 )?;531 }532533 // =========534535 <TokenData<T>>::insert(536 (collection.id, token),537 ItemData {538 owner: to.clone(),539 ..token_data540 },541 );542543 if let Some(balance_to) = balance_to {544 // from != to545 if balance_from == 0 {546 <AccountBalance<T>>::remove((collection.id, from));547 } else {548 <AccountBalance<T>>::insert((collection.id, from), balance_from);549 }550 <AccountBalance<T>>::insert((collection.id, to), balance_to);551 <Owned<T>>::remove((collection.id, from, token));552 <Owned<T>>::insert((collection.id, to, token), true);553 }554 Self::set_allowance_unchecked(collection, from, token, None, true);555556 <PalletEvm<T>>::deposit_log(557 ERC721Events::Transfer {558 from: *from.as_eth(),559 to: *to.as_eth(),560 token_id: token.into(),561 }562 .to_log(collection_id_to_address(collection.id)),563 );564 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(565 collection.id,566 token,567 from.clone(),568 to.clone(),569 1,570 ));571 Ok(())572 }573574 pub fn create_multiple_items(575 collection: &NonfungibleHandle<T>,576 sender: &T::CrossAccountId,577 data: Vec<CreateItemData<T>>,578 nesting_budget: &dyn Budget,579 ) -> DispatchResult {580 if !collection.is_owner_or_admin(sender) {581 ensure!(582 collection.mint_mode,583 <CommonError<T>>::PublicMintingNotAllowed584 );585 collection.check_allowlist(sender)?;586587 for item in data.iter() {588 collection.check_allowlist(&item.owner)?;589 }590 }591592 for data in data.iter() {593 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;594 }595596 let first_token = <TokensMinted<T>>::get(collection.id);597 let tokens_minted = first_token598 .checked_add(data.len() as u32)599 .ok_or(ArithmeticError::Overflow)?;600 ensure!(601 tokens_minted <= collection.limits.token_limit(),602 <CommonError<T>>::CollectionTokenLimitExceeded603 );604605 let mut balances = BTreeMap::new();606 for data in &data {607 let balance = balances608 .entry(&data.owner)609 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));610 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;611612 ensure!(613 *balance <= collection.limits.account_token_ownership_limit(),614 <CommonError<T>>::AccountTokenLimitExceeded,615 );616 }617618 for (i, data) in data.iter().enumerate() {619 let token = TokenId(first_token + i as u32 + 1);620 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {621 let handle = <CollectionHandle<T>>::try_get(target.0)?;622 let dispatch = T::CollectionDispatch::dispatch(handle);623 let dispatch = dispatch.as_dyn();624 dispatch.check_nesting(625 sender.clone(),626 (collection.id, token),627 target.1,628 nesting_budget,629 )?;630 }631 }632633 // =========634635 with_transaction(|| {636 for (i, data) in data.iter().enumerate() {637 let token = first_token + i as u32 + 1;638639 <TokenData<T>>::insert(640 (collection.id, token),641 ItemData {642 const_data: data.const_data.clone(),643 owner: data.owner.clone(),644 },645 );646647 if let Err(e) = Self::set_token_properties(648 collection,649 sender,650 TokenId(token),651 data.properties.clone().into_inner(),652 ) {653 return TransactionOutcome::Rollback(Err(e));654 }655 }656 TransactionOutcome::Commit(Ok(()))657 })?;658659 <TokensMinted<T>>::insert(collection.id, tokens_minted);660 for (account, balance) in balances {661 <AccountBalance<T>>::insert((collection.id, account), balance);662 }663 for (i, data) in data.into_iter().enumerate() {664 let token = first_token + i as u32 + 1;665 <Owned<T>>::insert((collection.id, &data.owner, token), true);666667 <PalletEvm<T>>::deposit_log(668 ERC721Events::Transfer {669 from: H160::default(),670 to: *data.owner.as_eth(),671 token_id: token.into(),672 }673 .to_log(collection_id_to_address(collection.id)),674 );675 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(676 collection.id,677 TokenId(token),678 data.owner.clone(),679 1,680 ));681 }682 Ok(())683 }684685 pub fn set_allowance_unchecked(686 collection: &NonfungibleHandle<T>,687 sender: &T::CrossAccountId,688 token: TokenId,689 spender: Option<&T::CrossAccountId>,690 assume_implicit_eth: bool,691 ) {692 if let Some(spender) = spender {693 let old_spender = <Allowance<T>>::get((collection.id, token));694 <Allowance<T>>::insert((collection.id, token), spender);695 // In ERC721 there is only one possible approved user of token, so we set696 // approved user to spender697 <PalletEvm<T>>::deposit_log(698 ERC721Events::Approval {699 owner: *sender.as_eth(),700 approved: *spender.as_eth(),701 token_id: token.into(),702 }703 .to_log(collection_id_to_address(collection.id)),704 );705 // In Unique chain, any token can have any amount of approved users, so we need to706 // set allowance of old owner to 0, and allowance of new owner to 1707 if old_spender.as_ref() != Some(spender) {708 if let Some(old_owner) = old_spender {709 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(710 collection.id,711 token,712 sender.clone(),713 old_owner,714 0,715 ));716 }717 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(718 collection.id,719 token,720 sender.clone(),721 spender.clone(),722 1,723 ));724 }725 } else {726 let old_spender = <Allowance<T>>::take((collection.id, token));727 if !assume_implicit_eth {728 // In ERC721 there is only one possible approved user of token, so we set729 // approved user to zero address730 <PalletEvm<T>>::deposit_log(731 ERC721Events::Approval {732 owner: *sender.as_eth(),733 approved: H160::default(),734 token_id: token.into(),735 }736 .to_log(collection_id_to_address(collection.id)),737 );738 }739 // In Unique chain, any token can have any amount of approved users, so we need to740 // set allowance of old owner to 0741 if let Some(old_spender) = old_spender {742 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(743 collection.id,744 token,745 sender.clone(),746 old_spender,747 0,748 ));749 }750 }751 }752753 pub fn set_allowance(754 collection: &NonfungibleHandle<T>,755 sender: &T::CrossAccountId,756 token: TokenId,757 spender: Option<&T::CrossAccountId>,758 ) -> DispatchResult {759 if collection.access == AccessMode::AllowList {760 collection.check_allowlist(sender)?;761 if let Some(spender) = spender {762 collection.check_allowlist(spender)?;763 }764 }765766 if let Some(spender) = spender {767 <PalletCommon<T>>::ensure_correct_receiver(spender)?;768 }769 let token_data =770 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;771 if &token_data.owner != sender {772 ensure!(773 collection.ignores_owned_amount(sender),774 <CommonError<T>>::CantApproveMoreThanOwned775 );776 }777778 // =========779780 Self::set_allowance_unchecked(collection, sender, token, spender, false);781 Ok(())782 }783784 fn check_allowed(785 collection: &NonfungibleHandle<T>,786 spender: &T::CrossAccountId,787 from: &T::CrossAccountId,788 token: TokenId,789 nesting_budget: &dyn Budget,790 ) -> DispatchResult {791 if spender.conv_eq(from) {792 return Ok(());793 }794 if collection.access == AccessMode::AllowList {795 // `from`, `to` checked in [`transfer`]796 collection.check_allowlist(spender)?;797 }798 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {799 // TODO: should collection owner be allowed to perform this transfer?800 ensure!(801 <PalletStructure<T>>::check_indirectly_owned(802 spender.clone(),803 source.0,804 source.1,805 None,806 nesting_budget807 )?,808 <CommonError<T>>::ApprovedValueTooLow,809 );810 return Ok(());811 }812 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {813 return Ok(());814 }815 ensure!(816 collection.ignores_allowance(spender),817 <CommonError<T>>::ApprovedValueTooLow818 );819 Ok(())820 }821822 pub fn transfer_from(823 collection: &NonfungibleHandle<T>,824 spender: &T::CrossAccountId,825 from: &T::CrossAccountId,826 to: &T::CrossAccountId,827 token: TokenId,828 nesting_budget: &dyn Budget,829 ) -> DispatchResult {830 Self::check_allowed(collection, spender, from, token, nesting_budget)?;831832 // =========833834 // Allowance is reset in [`transfer`]835 Self::transfer(collection, from, to, token, nesting_budget)836 }837838 pub fn burn_from(839 collection: &NonfungibleHandle<T>,840 spender: &T::CrossAccountId,841 from: &T::CrossAccountId,842 token: TokenId,843 nesting_budget: &dyn Budget,844 ) -> DispatchResult {845 Self::check_allowed(collection, spender, from, token, nesting_budget)?;846847 // =========848849 Self::burn(collection, from, token)850 }851852 pub fn check_nesting(853 handle: &NonfungibleHandle<T>,854 sender: T::CrossAccountId,855 from: (CollectionId, TokenId),856 under: TokenId,857 nesting_budget: &dyn Budget,858 ) -> DispatchResult {859 fn ensure_sender_allowed<T: Config>(860 collection: CollectionId,861 token: TokenId,862 for_nest: (CollectionId, TokenId),863 sender: T::CrossAccountId,864 budget: &dyn Budget,865 ) -> DispatchResult {866 ensure!(867 <PalletStructure<T>>::check_indirectly_owned(868 sender,869 collection,870 token,871 Some(for_nest),872 budget873 )?,874 <CommonError<T>>::OnlyOwnerAllowedToNest,875 );876 Ok(())877 }878 match handle.limits.nesting_rule() {879 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),880 NestingRule::Owner => {881 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?882 }883 NestingRule::OwnerRestricted(whitelist) => {884 ensure!(885 whitelist.contains(&from.0),886 <CommonError<T>>::SourceCollectionIsNotAllowedToNest887 );888 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?889 }890 }891 Ok(())892 }893894 /// Delegated to `create_multiple_items`895 pub fn create_item(896 collection: &NonfungibleHandle<T>,897 sender: &T::CrossAccountId,898 data: CreateItemData<T>,899 nesting_budget: &dyn Budget,900 ) -> DispatchResult {901 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)902 }903}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55 #[version(..2)]56 pub const_data: BoundedVec<u8, CustomDataLimit>,5758 #[version(..2)]59 pub variable_data: BoundedVec<u8, CustomDataLimit>,6061 pub owner: CrossAccountId,62}6364#[frame_support::pallet]65pub mod pallet {66 use super::*;67 use frame_support::{68 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,69 };70 use frame_system::pallet_prelude::*;71 use up_data_structs::{CollectionId, TokenId};72 use super::weights::WeightInfo;7374 #[pallet::error]75 pub enum Error<T> {76 /// Not Nonfungible item data used to mint in Nonfungible collection.77 NotNonfungibleDataUsedToMintFungibleCollectionToken,78 /// Used amount > 1 with NFT79 NonfungibleItemsHaveNoAmount,80 }8182 #[pallet::config]83 pub trait Config:84 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config85 {86 type WeightInfo: WeightInfo;87 }8889 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);9091 #[pallet::pallet]92 #[pallet::storage_version(STORAGE_VERSION)]93 #[pallet::generate_store(pub(super) trait Store)]94 pub struct Pallet<T>(_);9596 #[pallet::storage]97 pub type TokensMinted<T: Config> =98 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;99 #[pallet::storage]100 pub type TokensBurnt<T: Config> =101 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;102103 #[pallet::storage]104 pub type TokenData<T: Config> = StorageNMap<105 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),106 Value = ItemData<T::CrossAccountId>,107 QueryKind = OptionQuery,108 >;109110 #[pallet::storage]111 #[pallet::getter(fn token_properties)]112 pub type TokenProperties<T: Config> = StorageNMap<113 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),114 Value = Properties,115 QueryKind = ValueQuery,116 OnEmpty = up_data_structs::TokenProperties,117 >;118119 /// Used to enumerate tokens owned by account120 #[pallet::storage]121 pub type Owned<T: Config> = StorageNMap<122 Key = (123 Key<Twox64Concat, CollectionId>,124 Key<Blake2_128Concat, T::CrossAccountId>,125 Key<Twox64Concat, TokenId>,126 ),127 Value = bool,128 QueryKind = ValueQuery,129 >;130131 #[pallet::storage]132 pub type AccountBalance<T: Config> = StorageNMap<133 Key = (134 Key<Twox64Concat, CollectionId>,135 Key<Blake2_128Concat, T::CrossAccountId>,136 ),137 Value = u32,138 QueryKind = ValueQuery,139 >;140141 #[pallet::storage]142 pub type Allowance<T: Config> = StorageNMap<143 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),144 Value = T::CrossAccountId,145 QueryKind = OptionQuery,146 >;147148 #[pallet::hooks]149 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {150 fn on_runtime_upgrade() -> Weight {151 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {152 let mut had_consts = BTreeSet::new();153 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {154 let mut props = vec![];155 if !v.const_data.is_empty() {156 props.push(Property {157 key: b"_old_constData".to_vec().try_into().unwrap(),158 value: v.const_data.clone().into_inner().try_into().expect("const too long"),159 });160 had_consts.insert(collection);161 }162 if !v.variable_data.is_empty() {163 props.push(Property {164 key: b"_old_variableData".to_vec().try_into().unwrap(),165 value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),166 })167 }168 if !props.is_empty() {169 Self::set_scoped_token_properties(170 collection,171 token,172 PropertyScope::None,173 props.into_iter(),174 ).expect("existing token data exceeds property storage");175 }176 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))177 });178 for collection in had_consts {179 <PalletCommon<T>>::set_property_permission_unchecked(180 collection,181 PropertyKeyPermission {182 key: b"_old_constData".to_vec().try_into().unwrap(),183 permission: PropertyPermission {184 mutable: false,185 collection_admin: true,186 token_owner: false,187 },188 }189 ).expect("failed to configure permission");190 }191 }192193 0194 }195 }196}197198pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);199impl<T: Config> NonfungibleHandle<T> {200 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {201 Self(inner)202 }203 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {204 self.0205 }206 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {207 &mut self.0208 }209}210impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {211 fn recorder(&self) -> &SubstrateRecorder<T> {212 self.0.recorder()213 }214 fn into_recorder(self) -> SubstrateRecorder<T> {215 self.0.into_recorder()216 }217}218impl<T: Config> Deref for NonfungibleHandle<T> {219 type Target = pallet_common::CollectionHandle<T>;220221 fn deref(&self) -> &Self::Target {222 &self.0223 }224}225226impl<T: Config> Pallet<T> {227 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {228 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)229 }230 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {231 <TokenData<T>>::contains_key((collection.id, token))232 }233234 pub fn set_scoped_token_property(235 collection_id: CollectionId,236 token_id: TokenId,237 scope: PropertyScope,238 property: Property,239 ) -> DispatchResult {240 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {241 properties.try_scoped_set(scope, property.key, property.value)242 })243 .map_err(<CommonError<T>>::from)?;244245 Ok(())246 }247248 pub fn set_scoped_token_properties(249 collection_id: CollectionId,250 token_id: TokenId,251 scope: PropertyScope,252 properties: impl Iterator<Item=Property>,253 ) -> DispatchResult {254 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {255 stored_properties.try_scoped_set_from_iter(scope, properties)256 })257 .map_err(<CommonError<T>>::from)?;258259 Ok(())260 }261262 pub fn current_token_id(collection_id: CollectionId) -> TokenId {263 TokenId(<TokensMinted<T>>::get(collection_id))264 }265}266267// unchecked calls skips any permission checks268impl<T: Config> Pallet<T> {269 pub fn init_collection(270 owner: T::AccountId,271 data: CreateCollectionData<T::AccountId>,272 ) -> Result<CollectionId, DispatchError> {273 <PalletCommon<T>>::init_collection(owner, data)274 }275 pub fn destroy_collection(276 collection: NonfungibleHandle<T>,277 sender: &T::CrossAccountId,278 ) -> DispatchResult {279 let id = collection.id;280281 // =========282283 PalletCommon::destroy_collection(collection.0, sender)?;284285 <TokenData<T>>::remove_prefix((id,), None);286 <Owned<T>>::remove_prefix((id,), None);287 <TokensMinted<T>>::remove(id);288 <TokensBurnt<T>>::remove(id);289 <Allowance<T>>::remove_prefix((id,), None);290 <AccountBalance<T>>::remove_prefix((id,), None);291 Ok(())292 }293294 pub fn burn(295 collection: &NonfungibleHandle<T>,296 sender: &T::CrossAccountId,297 token: TokenId,298 ) -> DispatchResult {299 let token_data =300 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;301 ensure!(302 &token_data.owner == sender303 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),304 <CommonError<T>>::NoPermission305 );306307 if collection.permissions.access() == AccessMode::AllowList {308 collection.check_allowlist(sender)?;309 }310311 let burnt = <TokensBurnt<T>>::get(collection.id)312 .checked_add(1)313 .ok_or(ArithmeticError::Overflow)?;314315 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))316 .checked_sub(1)317 .ok_or(ArithmeticError::Overflow)?;318319 if balance == 0 {320 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));321 } else {322 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);323 }324 // =========325326 <Owned<T>>::remove((collection.id, &token_data.owner, token));327 <TokensBurnt<T>>::insert(collection.id, burnt);328 <TokenData<T>>::remove((collection.id, token));329 <TokenProperties<T>>::remove((collection.id, token));330 let old_spender = <Allowance<T>>::take((collection.id, token));331332 if let Some(old_spender) = old_spender {333 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(334 collection.id,335 token,336 sender.clone(),337 old_spender,338 0,339 ));340 }341342 <PalletEvm<T>>::deposit_log(343 ERC721Events::Transfer {344 from: *token_data.owner.as_eth(),345 to: H160::default(),346 token_id: token.into(),347 }348 .to_log(collection_id_to_address(collection.id)),349 );350 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(351 collection.id,352 token,353 token_data.owner,354 1,355 ));356 Ok(())357 }358359 pub fn set_token_property(360 collection: &NonfungibleHandle<T>,361 sender: &T::CrossAccountId,362 token_id: TokenId,363 property: Property,364 ) -> DispatchResult {365 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;366367 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {368 let property = property.clone();369 properties.try_set(property.key, property.value)370 })371 .map_err(<CommonError<T>>::from)?;372373 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(374 collection.id,375 token_id,376 property.key,377 ));378379 Ok(())380 }381382 #[transactional]383 pub fn set_token_properties(384 collection: &NonfungibleHandle<T>,385 sender: &T::CrossAccountId,386 token_id: TokenId,387 properties: Vec<Property>,388 ) -> DispatchResult {389 for property in properties {390 Self::set_token_property(collection, sender, token_id, property)?;391 }392393 Ok(())394 }395396 pub fn delete_token_property(397 collection: &NonfungibleHandle<T>,398 sender: &T::CrossAccountId,399 token_id: TokenId,400 property_key: PropertyKey,401 ) -> DispatchResult {402 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;403404 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {405 properties.remove(&property_key)406 })407 .map_err(<CommonError<T>>::from)?;408409 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(410 collection.id,411 token_id,412 property_key,413 ));414415 Ok(())416 }417418 fn check_token_change_permission(419 collection: &NonfungibleHandle<T>,420 sender: &T::CrossAccountId,421 token_id: TokenId,422 property_key: &PropertyKey,423 ) -> DispatchResult {424 let permission = <PalletCommon<T>>::property_permissions(collection.id)425 .get(property_key)426 .cloned()427 .unwrap_or_else(PropertyPermission::none);428429 let token_data = <TokenData<T>>::get((collection.id, token_id))430 .ok_or(<CommonError<T>>::TokenNotFound)?;431432 let check_token_owner = || -> DispatchResult {433 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);434 Ok(())435 };436437 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))438 .get(property_key)439 .is_some();440441 match permission {442 PropertyPermission { mutable: false, .. } if is_property_exists => {443 Err(<CommonError<T>>::NoPermission.into())444 }445446 PropertyPermission {447 collection_admin,448 token_owner,449 ..450 } => {451 let mut check_result = Err(<CommonError<T>>::NoPermission.into());452453 if collection_admin {454 check_result = collection.check_is_owner_or_admin(sender);455 }456457 if token_owner {458 check_result.or_else(|_| check_token_owner())459 } else {460 check_result461 }462 }463 }464 }465466 #[transactional]467 pub fn delete_token_properties(468 collection: &NonfungibleHandle<T>,469 sender: &T::CrossAccountId,470 token_id: TokenId,471 property_keys: Vec<PropertyKey>,472 ) -> DispatchResult {473 for key in property_keys {474 Self::delete_token_property(collection, sender, token_id, key)?;475 }476477 Ok(())478 }479480 pub fn set_collection_properties(481 collection: &NonfungibleHandle<T>,482 sender: &T::CrossAccountId,483 properties: Vec<Property>,484 ) -> DispatchResult {485 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)486 }487488 pub fn delete_collection_properties(489 collection: &CollectionHandle<T>,490 sender: &T::CrossAccountId,491 property_keys: Vec<PropertyKey>,492 ) -> DispatchResult {493 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)494 }495496 pub fn set_property_permissions(497 collection: &CollectionHandle<T>,498 sender: &T::CrossAccountId,499 property_permissions: Vec<PropertyKeyPermission>,500 ) -> DispatchResult {501 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)502 }503504 pub fn set_property_permission(505 collection: &CollectionHandle<T>,506 sender: &T::CrossAccountId,507 permission: PropertyKeyPermission,508 ) -> DispatchResult {509 <PalletCommon<T>>::set_property_permission(collection, sender, permission)510 }511512 pub fn transfer(513 collection: &NonfungibleHandle<T>,514 from: &T::CrossAccountId,515 to: &T::CrossAccountId,516 token: TokenId,517 nesting_budget: &dyn Budget,518 ) -> DispatchResult {519 ensure!(520 collection.limits.transfers_enabled(),521 <CommonError<T>>::TransferNotAllowed522 );523524 let token_data =525 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;526 // TODO: require sender to be token, owner, require admins to go through transfer_from527 ensure!(528 &token_data.owner == from529 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),530 <CommonError<T>>::NoPermission531 );532533 if collection.permissions.access() == AccessMode::AllowList {534 collection.check_allowlist(from)?;535 collection.check_allowlist(to)?;536 }537 <PalletCommon<T>>::ensure_correct_receiver(to)?;538539 let balance_from = <AccountBalance<T>>::get((collection.id, from))540 .checked_sub(1)541 .ok_or(<CommonError<T>>::TokenValueTooLow)?;542 let balance_to = if from != to {543 let balance_to = <AccountBalance<T>>::get((collection.id, to))544 .checked_add(1)545 .ok_or(ArithmeticError::Overflow)?;546547 ensure!(548 balance_to < collection.limits.account_token_ownership_limit(),549 <CommonError<T>>::AccountTokenLimitExceeded,550 );551552 Some(balance_to)553 } else {554 None555 };556557 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {558 let handle = <CollectionHandle<T>>::try_get(target.0)?;559 let dispatch = T::CollectionDispatch::dispatch(handle);560 let dispatch = dispatch.as_dyn();561562 dispatch.check_nesting(563 from.clone(),564 (collection.id, token),565 target.1,566 nesting_budget,567 )?;568 }569570 // =========571572 <TokenData<T>>::insert(573 (collection.id, token),574 ItemData {575 owner: to.clone(),576 ..token_data577 },578 );579580 if let Some(balance_to) = balance_to {581 // from != to582 if balance_from == 0 {583 <AccountBalance<T>>::remove((collection.id, from));584 } else {585 <AccountBalance<T>>::insert((collection.id, from), balance_from);586 }587 <AccountBalance<T>>::insert((collection.id, to), balance_to);588 <Owned<T>>::remove((collection.id, from, token));589 <Owned<T>>::insert((collection.id, to, token), true);590 }591 Self::set_allowance_unchecked(collection, from, token, None, true);592593 <PalletEvm<T>>::deposit_log(594 ERC721Events::Transfer {595 from: *from.as_eth(),596 to: *to.as_eth(),597 token_id: token.into(),598 }599 .to_log(collection_id_to_address(collection.id)),600 );601 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(602 collection.id,603 token,604 from.clone(),605 to.clone(),606 1,607 ));608 Ok(())609 }610611 pub fn create_multiple_items(612 collection: &NonfungibleHandle<T>,613 sender: &T::CrossAccountId,614 data: Vec<CreateItemData<T>>,615 nesting_budget: &dyn Budget,616 ) -> DispatchResult {617 if !collection.is_owner_or_admin(sender) {618 ensure!(619 collection.permissions.mint_mode(),620 <CommonError<T>>::PublicMintingNotAllowed621 );622 collection.check_allowlist(sender)?;623624 for item in data.iter() {625 collection.check_allowlist(&item.owner)?;626 }627 }628629 for data in data.iter() {630 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;631 }632633 let first_token = <TokensMinted<T>>::get(collection.id);634 let tokens_minted = first_token635 .checked_add(data.len() as u32)636 .ok_or(ArithmeticError::Overflow)?;637 ensure!(638 tokens_minted <= collection.limits.token_limit(),639 <CommonError<T>>::CollectionTokenLimitExceeded640 );641642 let mut balances = BTreeMap::new();643 for data in &data {644 let balance = balances645 .entry(&data.owner)646 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));647 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;648649 ensure!(650 *balance <= collection.limits.account_token_ownership_limit(),651 <CommonError<T>>::AccountTokenLimitExceeded,652 );653 }654655 for (i, data) in data.iter().enumerate() {656 let token = TokenId(first_token + i as u32 + 1);657 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {658 let handle = <CollectionHandle<T>>::try_get(target.0)?;659 let dispatch = T::CollectionDispatch::dispatch(handle);660 let dispatch = dispatch.as_dyn();661 dispatch.check_nesting(662 sender.clone(),663 (collection.id, token),664 target.1,665 nesting_budget,666 )?;667 }668 }669670 // =========671672 with_transaction(|| {673 for (i, data) in data.iter().enumerate() {674 let token = first_token + i as u32 + 1;675676 <TokenData<T>>::insert(677 (collection.id, token),678 ItemData {679 // const_data: data.const_data.clone(),680 owner: data.owner.clone(),681 },682 );683684 if let Err(e) = Self::set_token_properties(685 collection,686 sender,687 TokenId(token),688 data.properties.clone().into_inner(),689 ) {690 return TransactionOutcome::Rollback(Err(e));691 }692 }693 TransactionOutcome::Commit(Ok(()))694 })?;695696 <TokensMinted<T>>::insert(collection.id, tokens_minted);697 for (account, balance) in balances {698 <AccountBalance<T>>::insert((collection.id, account), balance);699 }700 for (i, data) in data.into_iter().enumerate() {701 let token = first_token + i as u32 + 1;702 <Owned<T>>::insert((collection.id, &data.owner, token), true);703704 <PalletEvm<T>>::deposit_log(705 ERC721Events::Transfer {706 from: H160::default(),707 to: *data.owner.as_eth(),708 token_id: token.into(),709 }710 .to_log(collection_id_to_address(collection.id)),711 );712 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(713 collection.id,714 TokenId(token),715 data.owner.clone(),716 1,717 ));718 }719 Ok(())720 }721722 pub fn set_allowance_unchecked(723 collection: &NonfungibleHandle<T>,724 sender: &T::CrossAccountId,725 token: TokenId,726 spender: Option<&T::CrossAccountId>,727 assume_implicit_eth: bool,728 ) {729 if let Some(spender) = spender {730 let old_spender = <Allowance<T>>::get((collection.id, token));731 <Allowance<T>>::insert((collection.id, token), spender);732 // In ERC721 there is only one possible approved user of token, so we set733 // approved user to spender734 <PalletEvm<T>>::deposit_log(735 ERC721Events::Approval {736 owner: *sender.as_eth(),737 approved: *spender.as_eth(),738 token_id: token.into(),739 }740 .to_log(collection_id_to_address(collection.id)),741 );742 // In Unique chain, any token can have any amount of approved users, so we need to743 // set allowance of old owner to 0, and allowance of new owner to 1744 if old_spender.as_ref() != Some(spender) {745 if let Some(old_owner) = old_spender {746 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(747 collection.id,748 token,749 sender.clone(),750 old_owner,751 0,752 ));753 }754 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(755 collection.id,756 token,757 sender.clone(),758 spender.clone(),759 1,760 ));761 }762 } else {763 let old_spender = <Allowance<T>>::take((collection.id, token));764 if !assume_implicit_eth {765 // In ERC721 there is only one possible approved user of token, so we set766 // approved user to zero address767 <PalletEvm<T>>::deposit_log(768 ERC721Events::Approval {769 owner: *sender.as_eth(),770 approved: H160::default(),771 token_id: token.into(),772 }773 .to_log(collection_id_to_address(collection.id)),774 );775 }776 // In Unique chain, any token can have any amount of approved users, so we need to777 // set allowance of old owner to 0778 if let Some(old_spender) = old_spender {779 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(780 collection.id,781 token,782 sender.clone(),783 old_spender,784 0,785 ));786 }787 }788 }789790 pub fn set_allowance(791 collection: &NonfungibleHandle<T>,792 sender: &T::CrossAccountId,793 token: TokenId,794 spender: Option<&T::CrossAccountId>,795 ) -> DispatchResult {796 if collection.permissions.access() == AccessMode::AllowList {797 collection.check_allowlist(sender)?;798 if let Some(spender) = spender {799 collection.check_allowlist(spender)?;800 }801 }802803 if let Some(spender) = spender {804 <PalletCommon<T>>::ensure_correct_receiver(spender)?;805 }806 let token_data =807 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;808 if &token_data.owner != sender {809 ensure!(810 collection.ignores_owned_amount(sender),811 <CommonError<T>>::CantApproveMoreThanOwned812 );813 }814815 // =========816817 Self::set_allowance_unchecked(collection, sender, token, spender, false);818 Ok(())819 }820821 fn check_allowed(822 collection: &NonfungibleHandle<T>,823 spender: &T::CrossAccountId,824 from: &T::CrossAccountId,825 token: TokenId,826 nesting_budget: &dyn Budget,827 ) -> DispatchResult {828 if spender.conv_eq(from) {829 return Ok(());830 }831 if collection.permissions.access() == AccessMode::AllowList {832 // `from`, `to` checked in [`transfer`]833 collection.check_allowlist(spender)?;834 }835 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {836 // TODO: should collection owner be allowed to perform this transfer?837 ensure!(838 <PalletStructure<T>>::check_indirectly_owned(839 spender.clone(),840 source.0,841 source.1,842 None,843 nesting_budget844 )?,845 <CommonError<T>>::ApprovedValueTooLow,846 );847 return Ok(());848 }849 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {850 return Ok(());851 }852 ensure!(853 collection.ignores_allowance(spender),854 <CommonError<T>>::ApprovedValueTooLow855 );856 Ok(())857 }858859 pub fn transfer_from(860 collection: &NonfungibleHandle<T>,861 spender: &T::CrossAccountId,862 from: &T::CrossAccountId,863 to: &T::CrossAccountId,864 token: TokenId,865 nesting_budget: &dyn Budget,866 ) -> DispatchResult {867 Self::check_allowed(collection, spender, from, token, nesting_budget)?;868869 // =========870871 // Allowance is reset in [`transfer`]872 Self::transfer(collection, from, to, token, nesting_budget)873 }874875 pub fn burn_from(876 collection: &NonfungibleHandle<T>,877 spender: &T::CrossAccountId,878 from: &T::CrossAccountId,879 token: TokenId,880 nesting_budget: &dyn Budget,881 ) -> DispatchResult {882 Self::check_allowed(collection, spender, from, token, nesting_budget)?;883884 // =========885886 Self::burn(collection, from, token)887 }888889 pub fn check_nesting(890 handle: &NonfungibleHandle<T>,891 sender: T::CrossAccountId,892 from: (CollectionId, TokenId),893 under: TokenId,894 nesting_budget: &dyn Budget,895 ) -> DispatchResult {896 fn ensure_sender_allowed<T: Config>(897 collection: CollectionId,898 token: TokenId,899 for_nest: (CollectionId, TokenId),900 sender: T::CrossAccountId,901 budget: &dyn Budget,902 ) -> DispatchResult {903 ensure!(904 <PalletStructure<T>>::check_indirectly_owned(905 sender,906 collection,907 token,908 Some(for_nest),909 budget910 )?,911 <CommonError<T>>::OnlyOwnerAllowedToNest,912 );913 Ok(())914 }915 match handle.permissions.nesting() {916 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),917 NestingRule::Owner => {918 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?919 }920 NestingRule::OwnerRestricted(whitelist) => {921 ensure!(922 whitelist.contains(&from.0),923 <CommonError<T>>::SourceCollectionIsNotAllowedToNest924 );925 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?926 }927 }928 Ok(())929 }930931 /// Delegated to `create_multiple_items`932 pub fn create_item(933 collection: &NonfungibleHandle<T>,934 sender: &T::CrossAccountId,935 data: CreateItemData<T>,936 nesting_budget: &dyn Budget,937 ) -> DispatchResult {938 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)939 }940}pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -403,10 +403,8 @@
nft_type: NftType,
properties: impl Iterator<Item=Property>
) -> Result<TokenId, DispatchError> {
+ todo!("store nft type");
let data = CreateNftExData {
- const_data: nft_type.encode()
- .try_into()
- .map_err(|_| <Error<T>>::NftTypeEncodeError)?,
properties: BoundedVec::default(),
owner: owner.clone(),
};
@@ -528,13 +526,8 @@
Ok(nft_property)
}
- pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
- let token_data = <TokenData<T>>::get((collection_id, token_id))
- .ok_or(<Error<T>>::NoAvailableNftId)?;
-
- let mut const_data = token_data.const_data.as_slice();
-
- NftType::decode(&mut const_data).map_err(|_| <Error<T>>::NoAvailableNftId.into())
+ pub fn get_nft_type(_collection_id: CollectionId, _token_id: TokenId) -> Result<NftType, DispatchError> {
+ todo!("should get it from properties?")
}
pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -336,11 +336,6 @@
fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
None
}
- fn const_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .const_data
- .into_inner()
- }
fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
None
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -321,7 +321,7 @@
<CommonError<T>>::TransferNotAllowed
);
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -424,7 +424,7 @@
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
- collection.mint_mode,
+ collection.permissions.mint_mode(),
<CommonError<T>>::PublicMintingNotAllowed
);
collection.check_allowlist(sender)?;
@@ -566,7 +566,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(sender)?;
collection.check_allowlist(spender)?;
}
@@ -598,7 +598,7 @@
if spender.conv_eq(from) {
return Ok(None);
}
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
pallets/unique/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -130,26 +130,6 @@
let collection = create_nft_collection::<T>(caller.clone())?;
}: _(RawOrigin::Signed(caller.clone()), collection, false)
- set_offchain_schema {
- let b in 0..OFFCHAIN_SCHEMA_LIMIT;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = create_var_data(b);
- }: set_offchain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
- set_const_on_chain_schema {
- let b in 0..CONST_ON_CHAIN_SCHEMA_LIMIT;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = create_var_data(b);
- }: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
-
- set_schema_version {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- }: set_schema_version(RawOrigin::Signed(caller.clone()), collection, SchemaVersion::Unique)
set_collection_limits{
let caller: T::AccountId = account("caller", 0, SEED);
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,10 +35,10 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH,
+ MAX_COLLECTION_NAME_LENGTH,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,
- CollectionLimits, CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState,
- CreateCollectionData, CreateItemExData, budget, CollectionField, Property, PropertyKey,
+ CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId, SponsorshipState,
+ CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
PropertyKeyPermission,
};
use pallet_evm::account::CrossAccountId;
@@ -162,6 +162,8 @@
/// * collection_id: Globally unique collection identifier.
CollectionLimitSet(CollectionId),
+ CollectionPermissionSet(CollectionId),
+
/// Mint permission was set
///
/// # Arguments
@@ -417,67 +419,6 @@
));
Ok(())
- }
-
- /// Toggle between normal and allow list access for the methods with access for `Anyone`.
- ///
- /// # Permissions
- ///
- /// * Collection Owner.
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * mode: [AccessMode]
- #[weight = <SelfWeightOf<T>>::set_public_access_mode()]
- #[transactional]
- pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
- {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
- let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_owner(&sender)?;
-
- target_collection.access = mode.clone();
-
- <Pallet<T>>::deposit_event(Event::<T>::PublicAccessModeSet(
- collection_id,
- mode
- ));
-
- target_collection.save()
- }
-
- /// Allows Anyone to create tokens if:
- /// * Allow List is enabled, and
- /// * Address is added to allow list, and
- /// * This method was called with True parameter
- ///
- /// # Permissions
- /// * Collection Owner
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.
- #[weight = <SelfWeightOf<T>>::set_mint_permission()]
- #[transactional]
- pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
- {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
- let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_owner(&sender)?;
-
- target_collection.mint_mode = mint_permission;
-
- <Pallet<T>>::deposit_event(Event::<T>::MintPermissionSet(
- collection_id
- ));
-
- target_collection.save()
}
/// Change the owner of the collection.
@@ -941,118 +882,42 @@
dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
}
- /// Set schema standard
- /// ImageURL
- /// Unique
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: SchemaVersion: enum
- #[weight = <SelfWeightOf<T>>::set_schema_version()]
+ #[weight = <SelfWeightOf<T>>::set_collection_limits()]
#[transactional]
- pub fn set_schema_version(
+ pub fn set_collection_limits(
origin,
collection_id: CollectionId,
- version: SchemaVersion
+ new_limit: CollectionLimits,
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_owner_or_admin(&sender)?;
- target_collection.schema_version = version;
-
- <Pallet<T>>::deposit_event(Event::<T>::SchemaVersionSet(
- collection_id
- ));
-
- target_collection.save()
- }
-
- /// Set off-chain data schema.
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: String representing the offchain data schema.
- #[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]
- #[transactional]
- pub fn set_offchain_schema(
- origin,
- collection_id: CollectionId,
- schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
- ) -> DispatchResult {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
+ let old_limit = &target_collection.limits;
- // =========
+ target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
- <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::OffchainSchema, schema.into_inner())?;
-
- <Pallet<T>>::deposit_event(Event::<T>::OffchainSchemaSet(
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
collection_id
));
- Ok(())
- }
- /// Set const on-chain data schema.
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: String representing the const on-chain data schema.
- #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]
- #[transactional]
- pub fn set_const_on_chain_schema (
- origin,
- collection_id: CollectionId,
- schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>
- ) -> DispatchResult {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
- // =========
-
- <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
-
- <Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(
- collection_id
- ));
- Ok(())
+ target_collection.save()
}
#[weight = <SelfWeightOf<T>>::set_collection_limits()]
#[transactional]
- pub fn set_collection_limits(
+ pub fn set_collection_permissions(
origin,
collection_id: CollectionId,
- new_limit: CollectionLimits,
+ new_limit: CollectionPermissions,
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
- let old_limit = &target_collection.limits;
+ let old_limit = &target_collection.permissions;
- target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
+ target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_limit)?;
- <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(
collection_id
));
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -186,7 +186,6 @@
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct TokenData<CrossAccountId> {
- pub const_data: Vec<u8>,
pub properties: Vec<Property>,
pub owner: Option<CrossAccountId>,
}
@@ -223,7 +222,7 @@
fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;
}
-#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub enum AccessMode {
Normal,
@@ -296,22 +295,26 @@
pub struct Collection<AccountId> {
pub owner: AccountId,
pub mode: CollectionMode,
+ #[version(..2)]
pub access: AccessMode,
pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
+
+ #[version(..2)]
pub mint_mode: bool,
#[version(..2)]
pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
+ #[version(..2)]
pub schema_version: SchemaVersion,
pub sponsorship: SponsorshipState<AccountId>,
- #[version(..2)]
- pub limits: CollectionLimitsVersion1, // Collection private restrictions
- #[version(2.., upper(limits.into()))]
- pub limits: CollectionLimitsVersion2,
+ pub limits: CollectionLimits,
+
+ #[version(2.., upper(Default::default()))]
+ pub permissions: CollectionPermissions,
#[version(..2)]
pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
@@ -329,27 +332,16 @@
pub struct RpcCollection<AccountId> {
pub owner: AccountId,
pub mode: CollectionMode,
- pub access: AccessMode,
pub name: Vec<u16>,
pub description: Vec<u16>,
pub token_prefix: Vec<u8>,
- pub mint_mode: bool,
- pub offchain_schema: Vec<u8>,
- pub schema_version: SchemaVersion,
pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits,
- pub const_on_chain_schema: Vec<u8>,
+ pub permissions: CollectionPermissions,
pub token_property_permissions: Vec<PropertyKeyPermission>,
pub properties: Vec<Property>,
}
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub enum CollectionField {
- ConstOnChainSchema,
- OffchainSchema,
-}
-
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
#[derivative(Debug, Default(bound = ""))]
pub struct CreateCollectionData<AccountId> {
@@ -359,11 +351,9 @@
pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
- pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
- pub schema_version: Option<SchemaVersion>,
pub pending_sponsor: Option<AccountId>,
pub limits: Option<CollectionLimits>,
- pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
+ pub permissions: Option<CollectionPermissions>,
pub token_property_permissions: CollectionPropertiesPermissionsVec,
pub properties: CollectionPropertiesVec,
}
@@ -375,7 +365,6 @@
BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
/// All fields are wrapped in `Option`s, where None means chain default
-#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionLimits {
@@ -395,9 +384,6 @@
pub owner_can_transfer: Option<bool>,
pub owner_can_destroy: Option<bool>,
pub transfers_enabled: Option<bool>,
-
- #[version(2.., upper(None))]
- pub nesting_rule: Option<NestingRule>,
}
impl CollectionLimits {
@@ -444,9 +430,26 @@
SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),
}
}
- pub fn nesting_rule(&self) -> &NestingRule {
+}
+
+#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionPermissions {
+ pub access: Option<AccessMode>,
+ pub mint_mode: Option<bool>,
+ pub nesting: Option<NestingRule>,
+}
+
+impl CollectionPermissions {
+ pub fn access(&self) -> AccessMode {
+ self.access.unwrap_or(AccessMode::Normal)
+ }
+ pub fn mint_mode(&self) -> bool {
+ self.mint_mode.unwrap_or(false)
+ }
+ pub fn nesting(&self) -> &NestingRule {
static DEFAULT: NestingRule = NestingRule::Disabled;
- self.nesting_rule.as_ref().unwrap_or(&DEFAULT)
+ self.nesting.as_ref().unwrap_or(&DEFAULT)
}
}
@@ -520,8 +523,6 @@
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
#[derivative(Debug)]
pub struct CreateNftExData<CrossAccountId> {
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub const_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub properties: CollectionPropertiesVec,
pub owner: CrossAccountId,
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -41,7 +41,6 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
- fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -29,9 +29,6 @@
Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
}
- fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {
- dispatch_unique_runtime!(collection.const_metadata(token))
- }
fn collection_properties(
collection: CollectionId,
@@ -73,7 +70,6 @@
keys: Option<Vec<Vec<u8>>>
) -> Result<TokenData<CrossAccountId>, DispatchError> {
let token_data = TokenData {
- const_data: Self::const_metadata(collection, token_id)?,
properties: Self::token_properties(collection, token_id, keys)?,
owner: Self::token_owner(collection, token_id)?
};
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -2399,28 +2399,6 @@
// #endregion
#[test]
-fn set_const_on_chain_schema() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- assert_ok!(Unique::set_const_on_chain_schema(
- origin1,
- collection_id,
- b"test const on chain schema".to_vec().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_common::CollectionData<Test>>::get((
- collection_id,
- CollectionField::ConstOnChainSchema
- )),
- b"test const on chain schema".to_vec()
- );
- });
-}
-
-#[test]
fn collection_transfer_flag_works() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);