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.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -33,7 +33,7 @@
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec};
+use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};
use core::ops::Deref;
use sp_std::collections::btree_map::BTreeMap;
use codec::{Encode, Decode, MaxEncodedLen};
@@ -52,6 +52,7 @@
#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct ItemData<CrossAccountId> {
+ #[version(..2)]
pub const_data: BoundedVec<u8, CustomDataLimit>,
#[version(..2)]
@@ -148,9 +149,45 @@
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
- <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {
+ let mut had_consts = BTreeSet::new();
+ <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {
+ let mut props = vec![];
+ if !v.const_data.is_empty() {
+ props.push(Property {
+ key: b"_old_constData".to_vec().try_into().unwrap(),
+ value: v.const_data.clone().into_inner().try_into().expect("const too long"),
+ });
+ had_consts.insert(collection);
+ }
+ if !v.variable_data.is_empty() {
+ props.push(Property {
+ key: b"_old_variableData".to_vec().try_into().unwrap(),
+ value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),
+ })
+ }
+ if !props.is_empty() {
+ Self::set_scoped_token_properties(
+ collection,
+ token,
+ PropertyScope::None,
+ props.into_iter(),
+ ).expect("existing token data exceeds property storage");
+ }
Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))
- })
+ });
+ for collection in had_consts {
+ <PalletCommon<T>>::set_property_permission_unchecked(
+ collection,
+ PropertyKeyPermission {
+ key: b"_old_constData".to_vec().try_into().unwrap(),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: false,
+ },
+ }
+ ).expect("failed to configure permission");
+ }
}
0
@@ -267,7 +304,7 @@
<CommonError<T>>::NoPermission
);
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(sender)?;
}
@@ -493,7 +530,7 @@
<CommonError<T>>::NoPermission
);
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -579,7 +616,7 @@
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
- collection.mint_mode,
+ collection.permissions.mint_mode(),
<CommonError<T>>::PublicMintingNotAllowed
);
collection.check_allowlist(sender)?;
@@ -639,7 +676,7 @@
<TokenData<T>>::insert(
(collection.id, token),
ItemData {
- const_data: data.const_data.clone(),
+ // const_data: data.const_data.clone(),
owner: data.owner.clone(),
},
);
@@ -756,7 +793,7 @@
token: TokenId,
spender: Option<&T::CrossAccountId>,
) -> DispatchResult {
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(sender)?;
if let Some(spender) = spender {
collection.check_allowlist(spender)?;
@@ -791,7 +828,7 @@
if spender.conv_eq(from) {
return Ok(());
}
- if collection.access == AccessMode::AllowList {
+ if collection.permissions.access() == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
@@ -875,7 +912,7 @@
);
Ok(())
}
- match handle.limits.nesting_rule() {
+ match handle.permissions.nesting() {
NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
NestingRule::Owner => {
ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
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.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#![recursion_limit = "1024"]18#![cfg_attr(not(feature = "std"), no_std)]19#![allow(20 clippy::too_many_arguments,21 clippy::unnecessary_mut_passed,22 clippy::unused_unit23)]2425use frame_support::{26 decl_module, decl_storage, decl_error, decl_event,27 dispatch::DispatchResult,28 ensure,29 weights::{Weight},30 transactional,31 pallet_prelude::{DispatchResultWithPostInfo, ConstU32},32 BoundedVec,33};34use scale_info::TypeInfo;35use frame_system::{self as system, ensure_signed};36use sp_runtime::{sp_std::prelude::Vec};37use up_data_structs::{38 CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH,39 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,40 CollectionLimits, CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState,41 CreateCollectionData, CreateItemExData, budget, CollectionField, Property, PropertyKey,42 PropertyKeyPermission,43};44use pallet_evm::account::CrossAccountId;45use pallet_common::{46 CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_call,47 dispatch::CollectionDispatch,48};4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;52pub mod weights;53use weights::WeightInfo;5455decl_error! {56 /// Error for non-fungible-token module.57 pub enum Error for Module<T: Config> {58 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.59 CollectionDecimalPointLimitExceeded,60 /// This address is not set as sponsor, use setCollectionSponsor first.61 ConfirmUnsetSponsorFail,62 /// Length of items properties must be greater than 0.63 EmptyArgument,64 }65}6667pub trait Config: system::Config + pallet_common::Config + Sized + TypeInfo {68 type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;6970 /// Weight information for extrinsics in this pallet.71 type WeightInfo: WeightInfo;72 type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;73}7475decl_event! {76 pub enum Event<T>77 where78 <T as frame_system::Config>::AccountId,79 <T as pallet_evm::account::Config>::CrossAccountId,80 {81 /// Collection sponsor was removed82 ///83 /// # Arguments84 ///85 /// * collection_id: Globally unique collection identifier.86 CollectionSponsorRemoved(CollectionId),8788 /// Collection admin was added89 ///90 /// # Arguments91 ///92 /// * collection_id: Globally unique collection identifier.93 ///94 /// * admin: Admin address.95 CollectionAdminAdded(CollectionId, CrossAccountId),9697 /// Collection owned was change98 ///99 /// # Arguments100 ///101 /// * collection_id: Globally unique collection identifier.102 ///103 /// * owner: New owner address.104 CollectionOwnedChanged(CollectionId, AccountId),105106 /// Collection sponsor was set107 ///108 /// # Arguments109 ///110 /// * collection_id: Globally unique collection identifier.111 ///112 /// * owner: New sponsor address.113 CollectionSponsorSet(CollectionId, AccountId),114115 /// const on chain schema was set116 ///117 /// # Arguments118 ///119 /// * collection_id: Globally unique collection identifier.120 ConstOnChainSchemaSet(CollectionId),121122 /// New sponsor was confirm123 ///124 /// # Arguments125 ///126 /// * collection_id: Globally unique collection identifier.127 ///128 /// * sponsor: New sponsor address.129 SponsorshipConfirmed(CollectionId, AccountId),130131 /// Collection admin was removed132 ///133 /// # Arguments134 ///135 /// * collection_id: Globally unique collection identifier.136 ///137 /// * admin: Admin address.138 CollectionAdminRemoved(CollectionId, CrossAccountId),139140 /// Address was remove from allow list141 ///142 /// # Arguments143 ///144 /// * collection_id: Globally unique collection identifier.145 ///146 /// * user: Address.147 AllowListAddressRemoved(CollectionId, CrossAccountId),148149 /// Address was add to allow list150 ///151 /// # Arguments152 ///153 /// * collection_id: Globally unique collection identifier.154 ///155 /// * user: Address.156 AllowListAddressAdded(CollectionId, CrossAccountId),157158 /// Collection limits was set159 ///160 /// # Arguments161 ///162 /// * collection_id: Globally unique collection identifier.163 CollectionLimitSet(CollectionId),164165 /// Mint permission was set166 ///167 /// # Arguments168 ///169 /// * collection_id: Globally unique collection identifier.170 MintPermissionSet(CollectionId),171172 /// Offchain schema was set173 ///174 /// # Arguments175 ///176 /// * collection_id: Globally unique collection identifier.177 OffchainSchemaSet(CollectionId),178179 /// Public access mode was set180 ///181 /// # Arguments182 ///183 /// * collection_id: Globally unique collection identifier.184 ///185 /// * mode: New access state.186 PublicAccessModeSet(CollectionId, AccessMode),187188 /// Schema version was set189 ///190 /// # Arguments191 ///192 /// * collection_id: Globally unique collection identifier.193 SchemaVersionSet(CollectionId),194 }195}196197type SelfWeightOf<T> = <T as Config>::WeightInfo;198199// # Used definitions200//201// ## User control levels202//203// chain-controlled - key is uncontrolled by user204// i.e autoincrementing index205// can use non-cryptographic hash206// real - key is controlled by user207// but it is hard to generate enough colliding values, i.e owner of signed txs208// can use non-cryptographic hash209// controlled - key is completly controlled by users210// i.e maps with mutable keys211// should use cryptographic hash212//213// ## User control level downgrade reasons214//215// ?1 - chain-controlled -> controlled216// collections/tokens can be destroyed, resulting in massive holes217// ?2 - chain-controlled -> controlled218// same as ?1, but can be only added, resulting in easier exploitation219// ?3 - real -> controlled220// no confirmation required, so addresses can be easily generated221decl_storage! {222 trait Store for Module<T: Config> as Unique {223224 //#region Private members225 /// Used for migrations226 ChainVersion: u64;227 //#endregion228229 //#region Tokens transfer rate limit baskets230 /// (Collection id (controlled?2), who created (real))231 /// TODO: Off chain worker should remove from this map when collection gets removed232 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;233 /// Collection id (controlled?2), token id (controlled?2)234 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;235 /// Collection id (controlled?2), owning user (real)236 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;237 /// Collection id (controlled?2), token id (controlled?2)238 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;239 //#endregion240241 /// Variable metadata sponsoring242 /// Collection id (controlled?2), token id (controlled?2)243 #[deprecated]244 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;245 pub TokenPropertyBasket get(fn token_property_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;246247 /// Approval sponsoring248 pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;249 pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;250 pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;251 }252}253254decl_module! {255 pub struct Module<T: Config> for enum Call256 where257 origin: T::Origin258 {259 type Error = Error<T>;260261 fn deposit_event() = default;262263 fn on_initialize(_now: T::BlockNumber) -> Weight {264 0265 }266267 fn on_runtime_upgrade() -> Weight {268 let limit = None;269270 <VariableMetaDataBasket<T>>::remove_all(limit);271272 0273 }274275 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner of the collection is set to the address that signed the transaction and can be changed later.276 ///277 /// # Permissions278 ///279 /// * Anyone.280 ///281 /// # Arguments282 ///283 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.284 ///285 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.286 ///287 /// * token_prefix: UTF-8 string with token prefix.288 ///289 /// * mode: [CollectionMode] collection type and type dependent data.290 // returns collection ID291 #[weight = <SelfWeightOf<T>>::create_collection()]292 #[transactional]293 #[deprecated]294 pub fn create_collection(origin,295 collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,296 collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,297 token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,298 mode: CollectionMode) -> DispatchResult {299 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {300 name: collection_name,301 description: collection_description,302 token_prefix,303 mode,304 ..Default::default()305 };306 Self::create_collection_ex(origin, data)307 }308309 /// This method creates a collection310 ///311 /// Prefer it to deprecated [`created_collection`] method312 #[weight = <SelfWeightOf<T>>::create_collection()]313 #[transactional]314 pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {315 let sender = ensure_signed(origin)?;316317 // =========318319 T::CollectionDispatch::create(sender, data)?;320321 Ok(())322 }323324 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.325 ///326 /// # Permissions327 ///328 /// * Collection Owner.329 ///330 /// # Arguments331 ///332 /// * collection_id: collection to destroy.333 #[weight = <SelfWeightOf<T>>::destroy_collection()]334 #[transactional]335 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {336 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);337 let collection = <CollectionHandle<T>>::try_get(collection_id)?;338339 // =========340341 T::CollectionDispatch::destroy(sender, collection)?;342343 <NftTransferBasket<T>>::remove_prefix(collection_id, None);344 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);345 <ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);346347 <NftApproveBasket<T>>::remove_prefix(collection_id, None);348 <FungibleApproveBasket<T>>::remove_prefix(collection_id, None);349 <RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);350351 Ok(())352 }353354 /// Add an address to allow list.355 ///356 /// # Permissions357 ///358 /// * Collection Owner359 /// * Collection Admin360 ///361 /// # Arguments362 ///363 /// * collection_id.364 ///365 /// * address.366 #[weight = <SelfWeightOf<T>>::add_to_allow_list()]367 #[transactional]368 pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{369370 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);371 let collection = <CollectionHandle<T>>::try_get(collection_id)?;372373 <PalletCommon<T>>::toggle_allowlist(374 &collection,375 &sender,376 &address,377 true,378 )?;379380 Self::deposit_event(Event::<T>::AllowListAddressAdded(381 collection_id,382 address383 ));384385 Ok(())386 }387388 /// Remove an address from allow list.389 ///390 /// # Permissions391 ///392 /// * Collection Owner393 /// * Collection Admin394 ///395 /// # Arguments396 ///397 /// * collection_id.398 ///399 /// * address.400 #[weight = <SelfWeightOf<T>>::remove_from_allow_list()]401 #[transactional]402 pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{403404 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);405 let collection = <CollectionHandle<T>>::try_get(collection_id)?;406407 <PalletCommon<T>>::toggle_allowlist(408 &collection,409 &sender,410 &address,411 false,412 )?;413414 <Pallet<T>>::deposit_event(Event::<T>::AllowListAddressRemoved(415 collection_id,416 address417 ));418419 Ok(())420 }421422 /// Toggle between normal and allow list access for the methods with access for `Anyone`.423 ///424 /// # Permissions425 ///426 /// * Collection Owner.427 ///428 /// # Arguments429 ///430 /// * collection_id.431 ///432 /// * mode: [AccessMode]433 #[weight = <SelfWeightOf<T>>::set_public_access_mode()]434 #[transactional]435 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult436 {437 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);438439 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;440 target_collection.check_is_owner(&sender)?;441442 target_collection.access = mode.clone();443444 <Pallet<T>>::deposit_event(Event::<T>::PublicAccessModeSet(445 collection_id,446 mode447 ));448449 target_collection.save()450 }451452 /// Allows Anyone to create tokens if:453 /// * Allow List is enabled, and454 /// * Address is added to allow list, and455 /// * This method was called with True parameter456 ///457 /// # Permissions458 /// * Collection Owner459 ///460 /// # Arguments461 ///462 /// * collection_id.463 ///464 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.465 #[weight = <SelfWeightOf<T>>::set_mint_permission()]466 #[transactional]467 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult468 {469 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);470471 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;472 target_collection.check_is_owner(&sender)?;473474 target_collection.mint_mode = mint_permission;475476 <Pallet<T>>::deposit_event(Event::<T>::MintPermissionSet(477 collection_id478 ));479480 target_collection.save()481 }482483 /// Change the owner of the collection.484 ///485 /// # Permissions486 ///487 /// * Collection Owner.488 ///489 /// # Arguments490 ///491 /// * collection_id.492 ///493 /// * new_owner.494 #[weight = <SelfWeightOf<T>>::change_collection_owner()]495 #[transactional]496 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {497498 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);499500 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;501 target_collection.check_is_owner(&sender)?;502503 target_collection.owner = new_owner.clone();504 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(505 collection_id,506 new_owner507 ));508509 target_collection.save()510 }511512 /// Adds an admin of the Collection.513 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.514 ///515 /// # Permissions516 ///517 /// * Collection Owner.518 /// * Collection Admin.519 ///520 /// # Arguments521 ///522 /// * collection_id: ID of the Collection to add admin for.523 ///524 /// * new_admin_id: Address of new admin to add.525 #[weight = <SelfWeightOf<T>>::add_collection_admin()]526 #[transactional]527 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {528 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);529 let collection = <CollectionHandle<T>>::try_get(collection_id)?;530531 <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminAdded(532 collection_id,533 new_admin_id.clone()534 ));535536 <PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)537 }538539 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.540 ///541 /// # Permissions542 ///543 /// * Collection Owner.544 /// * Collection Admin.545 ///546 /// # Arguments547 ///548 /// * collection_id: ID of the Collection to remove admin for.549 ///550 /// * account_id: Address of admin to remove.551 #[weight = <SelfWeightOf<T>>::remove_collection_admin()]552 #[transactional]553 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {554 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);555 let collection = <CollectionHandle<T>>::try_get(collection_id)?;556557 <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminRemoved(558 collection_id,559 account_id.clone()560 ));561562 <PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)563 }564565 /// # Permissions566 ///567 /// * Collection Owner568 ///569 /// # Arguments570 ///571 /// * collection_id.572 ///573 /// * new_sponsor.574 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]575 #[transactional]576 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {577 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);578579 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;580 target_collection.check_is_owner(&sender)?;581582 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor.clone());583584 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(585 collection_id,586 new_sponsor587 ));588589 target_collection.save()590 }591592 /// # Permissions593 ///594 /// * Sponsor.595 ///596 /// # Arguments597 ///598 /// * collection_id.599 #[weight = <SelfWeightOf<T>>::confirm_sponsorship()]600 #[transactional]601 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {602 let sender = ensure_signed(origin)?;603604 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;605 ensure!(606 target_collection.sponsorship.pending_sponsor() == Some(&sender),607 Error::<T>::ConfirmUnsetSponsorFail608 );609610 target_collection.sponsorship = SponsorshipState::Confirmed(sender.clone());611612 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(613 collection_id,614 sender615 ));616617 target_collection.save()618 }619620 /// Switch back to pay-per-own-transaction model.621 ///622 /// # Permissions623 ///624 /// * Collection owner.625 ///626 /// # Arguments627 ///628 /// * collection_id.629 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]630 #[transactional]631 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {632 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);633634 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;635 target_collection.check_is_owner(&sender)?;636637 target_collection.sponsorship = SponsorshipState::Disabled;638639 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(640 collection_id641 ));642 target_collection.save()643 }644645 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.646 ///647 /// # Permissions648 ///649 /// * Collection Owner.650 /// * Collection Admin.651 /// * Anyone if652 /// * Allow List is enabled, and653 /// * Address is added to allow list, and654 /// * MintPermission is enabled (see SetMintPermission method)655 ///656 /// # Arguments657 ///658 /// * collection_id: ID of the collection.659 ///660 /// * owner: Address, initial owner of the NFT.661 ///662 /// * data: Token data to store on chain.663 #[weight = T::CommonWeightInfo::create_item()]664 #[transactional]665 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {666 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);667 let budget = budget::Value::new(2);668669 dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))670 }671672 /// This method creates multiple items in a collection created with CreateCollection method.673 ///674 /// # Permissions675 ///676 /// * Collection Owner.677 /// * Collection Admin.678 /// * Anyone if679 /// * Allow List is enabled, and680 /// * Address is added to allow list, and681 /// * MintPermission is enabled (see SetMintPermission method)682 ///683 /// # Arguments684 ///685 /// * collection_id: ID of the collection.686 ///687 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].688 ///689 /// * owner: Address, initial owner of the NFT.690 #[weight = T::CommonWeightInfo::create_multiple_items(&items_data)]691 #[transactional]692 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {693 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);694 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);695 let budget = budget::Value::new(2);696697 dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))698 }699700 #[weight = T::CommonWeightInfo::set_collection_properties(properties.len() as u32)]701 #[transactional]702 pub fn set_collection_properties(703 origin,704 collection_id: CollectionId,705 properties: Vec<Property>706 ) -> DispatchResultWithPostInfo {707 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);708709 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);710711 dispatch_call::<T, _>(collection_id, |d| d.set_collection_properties(sender, properties))712 }713714 #[weight = T::CommonWeightInfo::delete_collection_properties(property_keys.len() as u32)]715 #[transactional]716 pub fn delete_collection_properties(717 origin,718 collection_id: CollectionId,719 property_keys: Vec<PropertyKey>,720 ) -> DispatchResultWithPostInfo {721 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);722723 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);724725 dispatch_call::<T, _>(collection_id, |d| d.delete_collection_properties(&sender, property_keys))726 }727728 #[weight = T::CommonWeightInfo::set_token_properties(properties.len() as u32)]729 #[transactional]730 pub fn set_token_properties(731 origin,732 collection_id: CollectionId,733 token_id: TokenId,734 properties: Vec<Property>735 ) -> DispatchResultWithPostInfo {736 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);737738 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);739740 dispatch_call::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties))741 }742743 #[weight = T::CommonWeightInfo::delete_token_properties(property_keys.len() as u32)]744 #[transactional]745 pub fn delete_token_properties(746 origin,747 collection_id: CollectionId,748 token_id: TokenId,749 property_keys: Vec<PropertyKey>750 ) -> DispatchResultWithPostInfo {751 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);752753 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);754755 dispatch_call::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys))756 }757758 #[weight = T::CommonWeightInfo::set_property_permissions(property_permissions.len() as u32)]759 #[transactional]760 pub fn set_property_permissions(761 origin,762 collection_id: CollectionId,763 property_permissions: Vec<PropertyKeyPermission>,764 ) -> DispatchResultWithPostInfo {765 ensure!(!property_permissions.is_empty(), Error::<T>::EmptyArgument);766767 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);768769 dispatch_call::<T, _>(collection_id, |d| d.set_property_permissions(&sender, property_permissions))770 }771772 #[weight = T::CommonWeightInfo::create_multiple_items_ex(&data)]773 #[transactional]774 pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {775 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);776 let budget = budget::Value::new(2);777778 dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))779 }780781 // TODO! transaction weight782783 /// Set transfers_enabled value for particular collection784 ///785 /// # Permissions786 ///787 /// * Collection Owner.788 ///789 /// # Arguments790 ///791 /// * collection_id: ID of the collection.792 ///793 /// * value: New flag value.794 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]795 #[transactional]796 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {797 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);798 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;799 target_collection.check_is_owner(&sender)?;800801 // =========802803 target_collection.limits.transfers_enabled = Some(value);804 target_collection.save()805 }806807 /// Destroys a concrete instance of NFT.808 ///809 /// # Permissions810 ///811 /// * Collection Owner.812 /// * Collection Admin.813 /// * Current NFT Owner.814 ///815 /// # Arguments816 ///817 /// * collection_id: ID of the collection.818 ///819 /// * item_id: ID of NFT to burn.820 #[weight = T::CommonWeightInfo::burn_item()]821 #[transactional]822 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {823 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);824825 let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;826 if value == 1 {827 <NftTransferBasket<T>>::remove(collection_id, item_id);828 <NftApproveBasket<T>>::remove(collection_id, item_id);829 }830 // Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?831 // <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());832 // <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));833 Ok(post_info)834 }835836 /// Destroys a concrete instance of NFT on behalf of the owner837 /// See also: [`approve`]838 ///839 /// # Permissions840 ///841 /// * Collection Owner.842 /// * Collection Admin.843 /// * Current NFT Owner.844 ///845 /// # Arguments846 ///847 /// * collection_id: ID of the collection.848 ///849 /// * item_id: ID of NFT to burn.850 ///851 /// * from: owner of item852 #[weight = T::CommonWeightInfo::burn_from()]853 #[transactional]854 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {855 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);856 let budget = budget::Value::new(2);857858 dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))859 }860861 /// Change ownership of the token.862 ///863 /// # Permissions864 ///865 /// * Collection Owner866 /// * Collection Admin867 /// * Current NFT owner868 ///869 /// # Arguments870 ///871 /// * recipient: Address of token recipient.872 ///873 /// * collection_id.874 ///875 /// * item_id: ID of the item876 /// * Non-Fungible Mode: Required.877 /// * Fungible Mode: Ignored.878 /// * Re-Fungible Mode: Required.879 ///880 /// * value: Amount to transfer.881 /// * Non-Fungible Mode: Ignored882 /// * Fungible Mode: Must specify transferred amount883 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)884 #[weight = T::CommonWeightInfo::transfer()]885 #[transactional]886 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {887 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);888 let budget = budget::Value::new(2);889890 dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))891 }892893 /// Set, change, or remove approved address to transfer the ownership of the NFT.894 ///895 /// # Permissions896 ///897 /// * Collection Owner898 /// * Collection Admin899 /// * Current NFT owner900 ///901 /// # Arguments902 ///903 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).904 ///905 /// * collection_id.906 ///907 /// * item_id: ID of the item.908 #[weight = T::CommonWeightInfo::approve()]909 #[transactional]910 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {911 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);912913 dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))914 }915916 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.917 ///918 /// # Permissions919 /// * Collection Owner920 /// * Collection Admin921 /// * Current NFT owner922 /// * Address approved by current NFT owner923 ///924 /// # Arguments925 ///926 /// * from: Address that owns token.927 ///928 /// * recipient: Address of token recipient.929 ///930 /// * collection_id.931 ///932 /// * item_id: ID of the item.933 ///934 /// * value: Amount to transfer.935 #[weight = T::CommonWeightInfo::transfer_from()]936 #[transactional]937 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {938 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);939 let budget = budget::Value::new(2);940941 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))942 }943944 /// Set schema standard945 /// ImageURL946 /// Unique947 ///948 /// # Permissions949 ///950 /// * Collection Owner951 /// * Collection Admin952 ///953 /// # Arguments954 ///955 /// * collection_id.956 ///957 /// * schema: SchemaVersion: enum958 #[weight = <SelfWeightOf<T>>::set_schema_version()]959 #[transactional]960 pub fn set_schema_version(961 origin,962 collection_id: CollectionId,963 version: SchemaVersion964 ) -> DispatchResult {965 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);966 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;967 target_collection.check_is_owner_or_admin(&sender)?;968 target_collection.schema_version = version;969970 <Pallet<T>>::deposit_event(Event::<T>::SchemaVersionSet(971 collection_id972 ));973974 target_collection.save()975 }976977 /// Set off-chain data schema.978 ///979 /// # Permissions980 ///981 /// * Collection Owner982 /// * Collection Admin983 ///984 /// # Arguments985 ///986 /// * collection_id.987 ///988 /// * schema: String representing the offchain data schema.989 #[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]990 #[transactional]991 pub fn set_offchain_schema(992 origin,993 collection_id: CollectionId,994 schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,995 ) -> DispatchResult {996 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);997 let collection = <CollectionHandle<T>>::try_get(collection_id)?;998999 // =========10001001 <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::OffchainSchema, schema.into_inner())?;10021003 <Pallet<T>>::deposit_event(Event::<T>::OffchainSchemaSet(1004 collection_id1005 ));1006 Ok(())1007 }10081009 /// Set const on-chain data schema.1010 ///1011 /// # Permissions1012 ///1013 /// * Collection Owner1014 /// * Collection Admin1015 ///1016 /// # Arguments1017 ///1018 /// * collection_id.1019 ///1020 /// * schema: String representing the const on-chain data schema.1021 #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]1022 #[transactional]1023 pub fn set_const_on_chain_schema (1024 origin,1025 collection_id: CollectionId,1026 schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>1027 ) -> DispatchResult {1028 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1029 let collection = <CollectionHandle<T>>::try_get(collection_id)?;10301031 // =========10321033 <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;10341035 <Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(1036 collection_id1037 ));1038 Ok(())1039 }10401041 #[weight = <SelfWeightOf<T>>::set_collection_limits()]1042 #[transactional]1043 pub fn set_collection_limits(1044 origin,1045 collection_id: CollectionId,1046 new_limit: CollectionLimits,1047 ) -> DispatchResult {1048 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1049 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1050 target_collection.check_is_owner(&sender)?;1051 let old_limit = &target_collection.limits;10521053 target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;10541055 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(1056 collection_id1057 ));10581059 target_collection.save()1060 }1061 }1062}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#![recursion_limit = "1024"]18#![cfg_attr(not(feature = "std"), no_std)]19#![allow(20 clippy::too_many_arguments,21 clippy::unnecessary_mut_passed,22 clippy::unused_unit23)]2425use frame_support::{26 decl_module, decl_storage, decl_error, decl_event,27 dispatch::DispatchResult,28 ensure,29 weights::{Weight},30 transactional,31 pallet_prelude::{DispatchResultWithPostInfo, ConstU32},32 BoundedVec,33};34use scale_info::TypeInfo;35use frame_system::{self as system, ensure_signed};36use sp_runtime::{sp_std::prelude::Vec};37use up_data_structs::{38 MAX_COLLECTION_NAME_LENGTH,39 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,40 CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId, SponsorshipState,41 CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,42 PropertyKeyPermission,43};44use pallet_evm::account::CrossAccountId;45use pallet_common::{46 CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_call,47 dispatch::CollectionDispatch,48};4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;52pub mod weights;53use weights::WeightInfo;5455decl_error! {56 /// Error for non-fungible-token module.57 pub enum Error for Module<T: Config> {58 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.59 CollectionDecimalPointLimitExceeded,60 /// This address is not set as sponsor, use setCollectionSponsor first.61 ConfirmUnsetSponsorFail,62 /// Length of items properties must be greater than 0.63 EmptyArgument,64 }65}6667pub trait Config: system::Config + pallet_common::Config + Sized + TypeInfo {68 type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;6970 /// Weight information for extrinsics in this pallet.71 type WeightInfo: WeightInfo;72 type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;73}7475decl_event! {76 pub enum Event<T>77 where78 <T as frame_system::Config>::AccountId,79 <T as pallet_evm::account::Config>::CrossAccountId,80 {81 /// Collection sponsor was removed82 ///83 /// # Arguments84 ///85 /// * collection_id: Globally unique collection identifier.86 CollectionSponsorRemoved(CollectionId),8788 /// Collection admin was added89 ///90 /// # Arguments91 ///92 /// * collection_id: Globally unique collection identifier.93 ///94 /// * admin: Admin address.95 CollectionAdminAdded(CollectionId, CrossAccountId),9697 /// Collection owned was change98 ///99 /// # Arguments100 ///101 /// * collection_id: Globally unique collection identifier.102 ///103 /// * owner: New owner address.104 CollectionOwnedChanged(CollectionId, AccountId),105106 /// Collection sponsor was set107 ///108 /// # Arguments109 ///110 /// * collection_id: Globally unique collection identifier.111 ///112 /// * owner: New sponsor address.113 CollectionSponsorSet(CollectionId, AccountId),114115 /// const on chain schema was set116 ///117 /// # Arguments118 ///119 /// * collection_id: Globally unique collection identifier.120 ConstOnChainSchemaSet(CollectionId),121122 /// New sponsor was confirm123 ///124 /// # Arguments125 ///126 /// * collection_id: Globally unique collection identifier.127 ///128 /// * sponsor: New sponsor address.129 SponsorshipConfirmed(CollectionId, AccountId),130131 /// Collection admin was removed132 ///133 /// # Arguments134 ///135 /// * collection_id: Globally unique collection identifier.136 ///137 /// * admin: Admin address.138 CollectionAdminRemoved(CollectionId, CrossAccountId),139140 /// Address was remove from allow list141 ///142 /// # Arguments143 ///144 /// * collection_id: Globally unique collection identifier.145 ///146 /// * user: Address.147 AllowListAddressRemoved(CollectionId, CrossAccountId),148149 /// Address was add to allow list150 ///151 /// # Arguments152 ///153 /// * collection_id: Globally unique collection identifier.154 ///155 /// * user: Address.156 AllowListAddressAdded(CollectionId, CrossAccountId),157158 /// Collection limits was set159 ///160 /// # Arguments161 ///162 /// * collection_id: Globally unique collection identifier.163 CollectionLimitSet(CollectionId),164165 CollectionPermissionSet(CollectionId),166167 /// Mint permission was set168 ///169 /// # Arguments170 ///171 /// * collection_id: Globally unique collection identifier.172 MintPermissionSet(CollectionId),173174 /// Offchain schema was set175 ///176 /// # Arguments177 ///178 /// * collection_id: Globally unique collection identifier.179 OffchainSchemaSet(CollectionId),180181 /// Public access mode was set182 ///183 /// # Arguments184 ///185 /// * collection_id: Globally unique collection identifier.186 ///187 /// * mode: New access state.188 PublicAccessModeSet(CollectionId, AccessMode),189190 /// Schema version was set191 ///192 /// # Arguments193 ///194 /// * collection_id: Globally unique collection identifier.195 SchemaVersionSet(CollectionId),196 }197}198199type SelfWeightOf<T> = <T as Config>::WeightInfo;200201// # Used definitions202//203// ## User control levels204//205// chain-controlled - key is uncontrolled by user206// i.e autoincrementing index207// can use non-cryptographic hash208// real - key is controlled by user209// but it is hard to generate enough colliding values, i.e owner of signed txs210// can use non-cryptographic hash211// controlled - key is completly controlled by users212// i.e maps with mutable keys213// should use cryptographic hash214//215// ## User control level downgrade reasons216//217// ?1 - chain-controlled -> controlled218// collections/tokens can be destroyed, resulting in massive holes219// ?2 - chain-controlled -> controlled220// same as ?1, but can be only added, resulting in easier exploitation221// ?3 - real -> controlled222// no confirmation required, so addresses can be easily generated223decl_storage! {224 trait Store for Module<T: Config> as Unique {225226 //#region Private members227 /// Used for migrations228 ChainVersion: u64;229 //#endregion230231 //#region Tokens transfer rate limit baskets232 /// (Collection id (controlled?2), who created (real))233 /// TODO: Off chain worker should remove from this map when collection gets removed234 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;235 /// Collection id (controlled?2), token id (controlled?2)236 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;237 /// Collection id (controlled?2), owning user (real)238 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;239 /// Collection id (controlled?2), token id (controlled?2)240 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;241 //#endregion242243 /// Variable metadata sponsoring244 /// Collection id (controlled?2), token id (controlled?2)245 #[deprecated]246 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;247 pub TokenPropertyBasket get(fn token_property_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;248249 /// Approval sponsoring250 pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;251 pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;252 pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;253 }254}255256decl_module! {257 pub struct Module<T: Config> for enum Call258 where259 origin: T::Origin260 {261 type Error = Error<T>;262263 fn deposit_event() = default;264265 fn on_initialize(_now: T::BlockNumber) -> Weight {266 0267 }268269 fn on_runtime_upgrade() -> Weight {270 let limit = None;271272 <VariableMetaDataBasket<T>>::remove_all(limit);273274 0275 }276277 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner of the collection is set to the address that signed the transaction and can be changed later.278 ///279 /// # Permissions280 ///281 /// * Anyone.282 ///283 /// # Arguments284 ///285 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.286 ///287 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.288 ///289 /// * token_prefix: UTF-8 string with token prefix.290 ///291 /// * mode: [CollectionMode] collection type and type dependent data.292 // returns collection ID293 #[weight = <SelfWeightOf<T>>::create_collection()]294 #[transactional]295 #[deprecated]296 pub fn create_collection(origin,297 collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,298 collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,299 token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,300 mode: CollectionMode) -> DispatchResult {301 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {302 name: collection_name,303 description: collection_description,304 token_prefix,305 mode,306 ..Default::default()307 };308 Self::create_collection_ex(origin, data)309 }310311 /// This method creates a collection312 ///313 /// Prefer it to deprecated [`created_collection`] method314 #[weight = <SelfWeightOf<T>>::create_collection()]315 #[transactional]316 pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {317 let sender = ensure_signed(origin)?;318319 // =========320321 T::CollectionDispatch::create(sender, data)?;322323 Ok(())324 }325326 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.327 ///328 /// # Permissions329 ///330 /// * Collection Owner.331 ///332 /// # Arguments333 ///334 /// * collection_id: collection to destroy.335 #[weight = <SelfWeightOf<T>>::destroy_collection()]336 #[transactional]337 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {338 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);339 let collection = <CollectionHandle<T>>::try_get(collection_id)?;340341 // =========342343 T::CollectionDispatch::destroy(sender, collection)?;344345 <NftTransferBasket<T>>::remove_prefix(collection_id, None);346 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);347 <ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);348349 <NftApproveBasket<T>>::remove_prefix(collection_id, None);350 <FungibleApproveBasket<T>>::remove_prefix(collection_id, None);351 <RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);352353 Ok(())354 }355356 /// Add an address to allow list.357 ///358 /// # Permissions359 ///360 /// * Collection Owner361 /// * Collection Admin362 ///363 /// # Arguments364 ///365 /// * collection_id.366 ///367 /// * address.368 #[weight = <SelfWeightOf<T>>::add_to_allow_list()]369 #[transactional]370 pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{371372 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);373 let collection = <CollectionHandle<T>>::try_get(collection_id)?;374375 <PalletCommon<T>>::toggle_allowlist(376 &collection,377 &sender,378 &address,379 true,380 )?;381382 Self::deposit_event(Event::<T>::AllowListAddressAdded(383 collection_id,384 address385 ));386387 Ok(())388 }389390 /// Remove an address from allow list.391 ///392 /// # Permissions393 ///394 /// * Collection Owner395 /// * Collection Admin396 ///397 /// # Arguments398 ///399 /// * collection_id.400 ///401 /// * address.402 #[weight = <SelfWeightOf<T>>::remove_from_allow_list()]403 #[transactional]404 pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{405406 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);407 let collection = <CollectionHandle<T>>::try_get(collection_id)?;408409 <PalletCommon<T>>::toggle_allowlist(410 &collection,411 &sender,412 &address,413 false,414 )?;415416 <Pallet<T>>::deposit_event(Event::<T>::AllowListAddressRemoved(417 collection_id,418 address419 ));420421 Ok(())422 }423424 /// Change the owner of the collection.425 ///426 /// # Permissions427 ///428 /// * Collection Owner.429 ///430 /// # Arguments431 ///432 /// * collection_id.433 ///434 /// * new_owner.435 #[weight = <SelfWeightOf<T>>::change_collection_owner()]436 #[transactional]437 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {438439 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);440441 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;442 target_collection.check_is_owner(&sender)?;443444 target_collection.owner = new_owner.clone();445 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(446 collection_id,447 new_owner448 ));449450 target_collection.save()451 }452453 /// Adds an admin of the Collection.454 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.455 ///456 /// # Permissions457 ///458 /// * Collection Owner.459 /// * Collection Admin.460 ///461 /// # Arguments462 ///463 /// * collection_id: ID of the Collection to add admin for.464 ///465 /// * new_admin_id: Address of new admin to add.466 #[weight = <SelfWeightOf<T>>::add_collection_admin()]467 #[transactional]468 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {469 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);470 let collection = <CollectionHandle<T>>::try_get(collection_id)?;471472 <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminAdded(473 collection_id,474 new_admin_id.clone()475 ));476477 <PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)478 }479480 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.481 ///482 /// # Permissions483 ///484 /// * Collection Owner.485 /// * Collection Admin.486 ///487 /// # Arguments488 ///489 /// * collection_id: ID of the Collection to remove admin for.490 ///491 /// * account_id: Address of admin to remove.492 #[weight = <SelfWeightOf<T>>::remove_collection_admin()]493 #[transactional]494 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {495 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);496 let collection = <CollectionHandle<T>>::try_get(collection_id)?;497498 <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminRemoved(499 collection_id,500 account_id.clone()501 ));502503 <PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)504 }505506 /// # Permissions507 ///508 /// * Collection Owner509 ///510 /// # Arguments511 ///512 /// * collection_id.513 ///514 /// * new_sponsor.515 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]516 #[transactional]517 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {518 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);519520 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;521 target_collection.check_is_owner(&sender)?;522523 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor.clone());524525 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(526 collection_id,527 new_sponsor528 ));529530 target_collection.save()531 }532533 /// # Permissions534 ///535 /// * Sponsor.536 ///537 /// # Arguments538 ///539 /// * collection_id.540 #[weight = <SelfWeightOf<T>>::confirm_sponsorship()]541 #[transactional]542 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {543 let sender = ensure_signed(origin)?;544545 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;546 ensure!(547 target_collection.sponsorship.pending_sponsor() == Some(&sender),548 Error::<T>::ConfirmUnsetSponsorFail549 );550551 target_collection.sponsorship = SponsorshipState::Confirmed(sender.clone());552553 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(554 collection_id,555 sender556 ));557558 target_collection.save()559 }560561 /// Switch back to pay-per-own-transaction model.562 ///563 /// # Permissions564 ///565 /// * Collection owner.566 ///567 /// # Arguments568 ///569 /// * collection_id.570 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]571 #[transactional]572 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {573 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);574575 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;576 target_collection.check_is_owner(&sender)?;577578 target_collection.sponsorship = SponsorshipState::Disabled;579580 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(581 collection_id582 ));583 target_collection.save()584 }585586 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.587 ///588 /// # Permissions589 ///590 /// * Collection Owner.591 /// * Collection Admin.592 /// * Anyone if593 /// * Allow List is enabled, and594 /// * Address is added to allow list, and595 /// * MintPermission is enabled (see SetMintPermission method)596 ///597 /// # Arguments598 ///599 /// * collection_id: ID of the collection.600 ///601 /// * owner: Address, initial owner of the NFT.602 ///603 /// * data: Token data to store on chain.604 #[weight = T::CommonWeightInfo::create_item()]605 #[transactional]606 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {607 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);608 let budget = budget::Value::new(2);609610 dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))611 }612613 /// This method creates multiple items in a collection created with CreateCollection method.614 ///615 /// # Permissions616 ///617 /// * Collection Owner.618 /// * Collection Admin.619 /// * Anyone if620 /// * Allow List is enabled, and621 /// * Address is added to allow list, and622 /// * MintPermission is enabled (see SetMintPermission method)623 ///624 /// # Arguments625 ///626 /// * collection_id: ID of the collection.627 ///628 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].629 ///630 /// * owner: Address, initial owner of the NFT.631 #[weight = T::CommonWeightInfo::create_multiple_items(&items_data)]632 #[transactional]633 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {634 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);635 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);636 let budget = budget::Value::new(2);637638 dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))639 }640641 #[weight = T::CommonWeightInfo::set_collection_properties(properties.len() as u32)]642 #[transactional]643 pub fn set_collection_properties(644 origin,645 collection_id: CollectionId,646 properties: Vec<Property>647 ) -> DispatchResultWithPostInfo {648 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);649650 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);651652 dispatch_call::<T, _>(collection_id, |d| d.set_collection_properties(sender, properties))653 }654655 #[weight = T::CommonWeightInfo::delete_collection_properties(property_keys.len() as u32)]656 #[transactional]657 pub fn delete_collection_properties(658 origin,659 collection_id: CollectionId,660 property_keys: Vec<PropertyKey>,661 ) -> DispatchResultWithPostInfo {662 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);663664 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);665666 dispatch_call::<T, _>(collection_id, |d| d.delete_collection_properties(&sender, property_keys))667 }668669 #[weight = T::CommonWeightInfo::set_token_properties(properties.len() as u32)]670 #[transactional]671 pub fn set_token_properties(672 origin,673 collection_id: CollectionId,674 token_id: TokenId,675 properties: Vec<Property>676 ) -> DispatchResultWithPostInfo {677 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);678679 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);680681 dispatch_call::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties))682 }683684 #[weight = T::CommonWeightInfo::delete_token_properties(property_keys.len() as u32)]685 #[transactional]686 pub fn delete_token_properties(687 origin,688 collection_id: CollectionId,689 token_id: TokenId,690 property_keys: Vec<PropertyKey>691 ) -> DispatchResultWithPostInfo {692 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);693694 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);695696 dispatch_call::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys))697 }698699 #[weight = T::CommonWeightInfo::set_property_permissions(property_permissions.len() as u32)]700 #[transactional]701 pub fn set_property_permissions(702 origin,703 collection_id: CollectionId,704 property_permissions: Vec<PropertyKeyPermission>,705 ) -> DispatchResultWithPostInfo {706 ensure!(!property_permissions.is_empty(), Error::<T>::EmptyArgument);707708 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);709710 dispatch_call::<T, _>(collection_id, |d| d.set_property_permissions(&sender, property_permissions))711 }712713 #[weight = T::CommonWeightInfo::create_multiple_items_ex(&data)]714 #[transactional]715 pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {716 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);717 let budget = budget::Value::new(2);718719 dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))720 }721722 // TODO! transaction weight723724 /// Set transfers_enabled value for particular collection725 ///726 /// # Permissions727 ///728 /// * Collection Owner.729 ///730 /// # Arguments731 ///732 /// * collection_id: ID of the collection.733 ///734 /// * value: New flag value.735 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]736 #[transactional]737 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {738 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);739 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;740 target_collection.check_is_owner(&sender)?;741742 // =========743744 target_collection.limits.transfers_enabled = Some(value);745 target_collection.save()746 }747748 /// Destroys a concrete instance of NFT.749 ///750 /// # Permissions751 ///752 /// * Collection Owner.753 /// * Collection Admin.754 /// * Current NFT Owner.755 ///756 /// # Arguments757 ///758 /// * collection_id: ID of the collection.759 ///760 /// * item_id: ID of NFT to burn.761 #[weight = T::CommonWeightInfo::burn_item()]762 #[transactional]763 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {764 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);765766 let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;767 if value == 1 {768 <NftTransferBasket<T>>::remove(collection_id, item_id);769 <NftApproveBasket<T>>::remove(collection_id, item_id);770 }771 // Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?772 // <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());773 // <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));774 Ok(post_info)775 }776777 /// Destroys a concrete instance of NFT on behalf of the owner778 /// See also: [`approve`]779 ///780 /// # Permissions781 ///782 /// * Collection Owner.783 /// * Collection Admin.784 /// * Current NFT Owner.785 ///786 /// # Arguments787 ///788 /// * collection_id: ID of the collection.789 ///790 /// * item_id: ID of NFT to burn.791 ///792 /// * from: owner of item793 #[weight = T::CommonWeightInfo::burn_from()]794 #[transactional]795 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {796 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);797 let budget = budget::Value::new(2);798799 dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))800 }801802 /// Change ownership of the token.803 ///804 /// # Permissions805 ///806 /// * Collection Owner807 /// * Collection Admin808 /// * Current NFT owner809 ///810 /// # Arguments811 ///812 /// * recipient: Address of token recipient.813 ///814 /// * collection_id.815 ///816 /// * item_id: ID of the item817 /// * Non-Fungible Mode: Required.818 /// * Fungible Mode: Ignored.819 /// * Re-Fungible Mode: Required.820 ///821 /// * value: Amount to transfer.822 /// * Non-Fungible Mode: Ignored823 /// * Fungible Mode: Must specify transferred amount824 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)825 #[weight = T::CommonWeightInfo::transfer()]826 #[transactional]827 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {828 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);829 let budget = budget::Value::new(2);830831 dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))832 }833834 /// Set, change, or remove approved address to transfer the ownership of the NFT.835 ///836 /// # Permissions837 ///838 /// * Collection Owner839 /// * Collection Admin840 /// * Current NFT owner841 ///842 /// # Arguments843 ///844 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).845 ///846 /// * collection_id.847 ///848 /// * item_id: ID of the item.849 #[weight = T::CommonWeightInfo::approve()]850 #[transactional]851 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {852 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);853854 dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))855 }856857 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.858 ///859 /// # Permissions860 /// * Collection Owner861 /// * Collection Admin862 /// * Current NFT owner863 /// * Address approved by current NFT owner864 ///865 /// # Arguments866 ///867 /// * from: Address that owns token.868 ///869 /// * recipient: Address of token recipient.870 ///871 /// * collection_id.872 ///873 /// * item_id: ID of the item.874 ///875 /// * value: Amount to transfer.876 #[weight = T::CommonWeightInfo::transfer_from()]877 #[transactional]878 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {879 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);880 let budget = budget::Value::new(2);881882 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))883 }884885 #[weight = <SelfWeightOf<T>>::set_collection_limits()]886 #[transactional]887 pub fn set_collection_limits(888 origin,889 collection_id: CollectionId,890 new_limit: CollectionLimits,891 ) -> DispatchResult {892 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);893 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;894 target_collection.check_is_owner(&sender)?;895 let old_limit = &target_collection.limits;896897 target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;898899 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(900 collection_id901 ));902903 target_collection.save()904 }905906 #[weight = <SelfWeightOf<T>>::set_collection_limits()]907 #[transactional]908 pub fn set_collection_permissions(909 origin,910 collection_id: CollectionId,911 new_limit: CollectionPermissions,912 ) -> DispatchResult {913 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);914 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;915 target_collection.check_is_owner(&sender)?;916 let old_limit = &target_collection.permissions;917918 target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_limit)?;919920 <Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(921 collection_id922 ));923924 target_collection.save()925 }926 }927}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);