difftreelog
style reformat code
in: master
19 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -30,8 +30,7 @@
// RMRK
use rmrk_rpc::RmrkApi as RmrkRuntimeApi;
use up_data_structs::{
- RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName,
- RmrkResourceId,
+ RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkResourceId,
};
pub use rmrk_unique_rpc::RmrkApi;
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -364,7 +364,8 @@
RmrkBaseInfo<AccountId>,
RmrkPartType,
RmrkTheme,
- >*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ >*/
+ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ sp_api::Metadata<Block>
+ sp_offchain::OffchainWorkerApi<Block>
+ cumulus_primitives_core::CollectCollationInfo<Block>,
@@ -656,7 +657,8 @@
RmrkBaseInfo<AccountId>,
RmrkPartType,
RmrkTheme,
- >*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ >*/
+ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ sp_api::Metadata<Block>
+ sp_offchain::OffchainWorkerApi<Block>
+ cumulus_primitives_core::CollectCollationInfo<Block>
@@ -800,7 +802,8 @@
RmrkBaseInfo<AccountId>,
RmrkPartType,
RmrkTheme,
- >*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ >*/
+ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
+ sp_api::Metadata<Block>
+ sp_offchain::OffchainWorkerApi<Block>
+ cumulus_primitives_core::CollectCollationInfo<Block>
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -501,7 +501,6 @@
PhantomType<(
TokenData<T::CrossAccountId>,
RpcCollection<T::AccountId>,
-
// RMRK
RmrkCollectionInfo<T::AccountId>,
RmrkInstanceInfo<T::AccountId>,
@@ -526,19 +525,34 @@
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"),
+ 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"),
+ 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"),
+ value: v
+ .const_on_chain_schema
+ .clone()
+ .into_inner()
+ .try_into()
+ .expect("offchain schema too big"),
});
}
props.push(Property {
@@ -546,13 +560,17 @@
value: match v.schema_version {
SchemaVersion::ImageURL => b"ImageUrl".as_slice(),
SchemaVersion::Unique => b"Unique".as_slice(),
- }.to_vec().try_into().unwrap(),
+ }
+ .to_vec()
+ .try_into()
+ .unwrap(),
});
Self::set_scoped_collection_properties(
id,
PropertyScope::None,
props.into_iter(),
- ).expect("existing data larger than properties");
+ )
+ .expect("existing data larger than properties");
let mut new = CollectionVersion2::from(v.clone());
new.permissions.access = Some(v.access);
new.permissions.mint_mode = Some(v.mint_mode);
@@ -644,18 +662,12 @@
let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
.into_iter()
- .map(|(key, permission)| PropertyKeyPermission {
- key,
- permission,
- })
+ .map(|(key, permission)| PropertyKeyPermission { key, permission })
.collect();
let properties = <CollectionProperties<T>>::get(collection)
.into_iter()
- .map(|(key, value)| Property {
- key,
- value,
- })
+ .map(|(key, value)| Property { key, value })
.collect();
let permissions = CollectionPermissions {
@@ -751,7 +763,9 @@
.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
permissions: data
.permissions
- .map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))
+ .map(|permissions| {
+ Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)
+ })
.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
};
@@ -1005,10 +1019,7 @@
.unwrap_or_else(|| {
properties
.into_iter()
- .map(|(key, value)| Property {
- key,
- value,
- })
+ .map(|(key, value)| Property { key, value })
.collect()
});
@@ -1037,10 +1048,7 @@
.unwrap_or_else(|| {
permissions
.into_iter()
- .map(|(key, permission)| PropertyKeyPermission {
- key,
- permission,
- })
+ .map(|(key, permission)| PropertyKeyPermission { key, permission })
.collect()
});
@@ -1276,17 +1284,9 @@
budget: &dyn Budget,
) -> DispatchResult;
- fn nest(
- &self,
- under: TokenId,
- to_nest: (CollectionId, TokenId)
- );
+ fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));
- fn unnest(
- &self,
- under: TokenId,
- to_nest: (CollectionId, TokenId)
- );
+ fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
fn collection_tokens(&self) -> Vec<TokenId>;
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -298,17 +298,9 @@
fail!(<Error<T>>::FungibleDisallowsNesting)
}
- fn nest(
- &self,
- _under: TokenId,
- _to_nest: (CollectionId, TokenId)
- ) {}
+ fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}
- fn unnest(
- &self,
- _under: TokenId,
- _to_nest: (CollectionId, TokenId)
- ) {}
+ fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}
fn collection_tokens(&self) -> Vec<TokenId> {
vec![TokenId::default()]
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -184,11 +184,7 @@
if balance == 0 {
<Balance<T>>::remove((collection.id, owner));
- <PalletStructure<T>>::unnest_if_nested(
- owner,
- collection.id,
- TokenId::default()
- );
+ <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());
} else {
<Balance<T>>::insert((collection.id, owner), balance);
}
@@ -249,18 +245,14 @@
to,
collection.id,
TokenId::default(),
- nesting_budget
+ nesting_budget,
)?;
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
<Balance<T>>::remove((collection.id, from));
- <PalletStructure<T>>::unnest_if_nested(
- from,
- collection.id,
- TokenId::default()
- );
+ <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());
} else {
<Balance<T>>::insert((collection.id, from), balance_from);
}
@@ -333,7 +325,11 @@
<TotalSupply<T>>::insert(collection.id, total_supply);
for (user, amount) in balances {
<Balance<T>>::insert((collection.id, &user), amount);
- <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId::default());
+ <PalletStructure<T>>::nest_if_sent_to_token_unchecked(
+ &user,
+ collection.id,
+ TokenId::default(),
+ );
<PalletEvm<T>>::deposit_log(
ERC20Events::Transfer {
from: H160::default(),
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -22,7 +22,7 @@
PropertyKeyPermission, PropertyValue,
};
use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _
+ CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _,
};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -353,19 +353,11 @@
<Pallet<T>>::check_nesting(self, sender, from, under, budget)
}
- fn nest(
- &self,
- under: TokenId,
- to_nest: (CollectionId, TokenId)
- ) {
+ fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {
<Pallet<T>>::nest((self.id, under), to_nest);
}
- fn unnest(
- &self,
- under: TokenId,
- to_unnest: (CollectionId, TokenId)
- ) {
+ fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {
<Pallet<T>>::unnest((self.id, under), to_unnest);
}
@@ -415,10 +407,7 @@
.unwrap_or_else(|| {
properties
.into_iter()
- .map(|(key, value)| Property {
- key,
- value,
- })
+ .map(|(key, value)| Property { key, value })
.collect()
})
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -426,11 +426,10 @@
Ok(a)
}
-fn has_token_permission<T: Config>(
- collection_id: CollectionId,
- key: &PropertyKey,
-) -> bool {
- if let Ok(token_property_permissions) = CollectionPropertyPermissions::<T>::try_get(collection_id) {
+fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {
+ if let Ok(token_property_permissions) =
+ CollectionPropertyPermissions::<T>::try_get(collection_id)
+ {
return token_property_permissions.contains_key(key);
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};37use core::ops::Deref;38use codec::{Encode, Decode, MaxEncodedLen};39use scale_info::TypeInfo;4041pub use pallet::*;42#[cfg(feature = "runtime-benchmarks")]43pub mod benchmarking;44pub mod common;45pub mod erc;46pub mod weights;4748pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;49pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5051#[struct_versioning::versioned(version = 2, upper)]52#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]53pub struct ItemData<CrossAccountId> {54 #[version(..2)]55 pub const_data: BoundedVec<u8, CustomDataLimit>,5657 #[version(..2)]58 pub variable_data: BoundedVec<u8, CustomDataLimit>,5960 pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65 use super::*;66 use frame_support::{67 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68 };69 use frame_system::pallet_prelude::*;70 use up_data_structs::{CollectionId, TokenId};71 use super::weights::WeightInfo;7273 #[pallet::error]74 pub enum Error<T> {75 /// Not Nonfungible item data used to mint in Nonfungible collection.76 NotNonfungibleDataUsedToMintFungibleCollectionToken,77 /// Used amount > 1 with NFT78 NonfungibleItemsHaveNoAmount,79 /// Unable to burn NFT with children80 CantBurnNftWithChildren,81 }8283 #[pallet::config]84 pub trait Config:85 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config86 {87 type WeightInfo: WeightInfo;88 }8990 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);9192 #[pallet::pallet]93 #[pallet::storage_version(STORAGE_VERSION)]94 #[pallet::generate_store(pub(super) trait Store)]95 pub struct Pallet<T>(_);9697 #[pallet::storage]98 pub type TokensMinted<T: Config> =99 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;100 #[pallet::storage]101 pub type TokensBurnt<T: Config> =102 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;103104 #[pallet::storage]105 pub type TokenData<T: Config> = StorageNMap<106 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),107 Value = ItemData<T::CrossAccountId>,108 QueryKind = OptionQuery,109 >;110111 #[pallet::storage]112 #[pallet::getter(fn token_properties)]113 pub type TokenProperties<T: Config> = StorageNMap<114 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),115 Value = Properties,116 QueryKind = ValueQuery,117 OnEmpty = up_data_structs::TokenProperties,118 >;119120 /// Used to enumerate tokens owned by account121 #[pallet::storage]122 pub type Owned<T: Config> = StorageNMap<123 Key = (124 Key<Twox64Concat, CollectionId>,125 Key<Blake2_128Concat, T::CrossAccountId>,126 Key<Twox64Concat, TokenId>,127 ),128 Value = bool,129 QueryKind = ValueQuery,130 >;131132 /// Used to enumerate token's children133 #[pallet::storage]134 #[pallet::getter(fn token_children)]135 pub type TokenChildren<T: Config> = StorageNMap<136 Key = (137 Key<Twox64Concat, CollectionId>,138 Key<Twox64Concat, TokenId>,139 Key<Twox64Concat, (CollectionId, TokenId)>,140 ),141 Value = bool,142 QueryKind = ValueQuery,143 >;144145 #[pallet::storage]146 pub type AccountBalance<T: Config> = StorageNMap<147 Key = (148 Key<Twox64Concat, CollectionId>,149 Key<Blake2_128Concat, T::CrossAccountId>,150 ),151 Value = u32,152 QueryKind = ValueQuery,153 >;154155 #[pallet::storage]156 pub type Allowance<T: Config> = StorageNMap<157 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),158 Value = T::CrossAccountId,159 QueryKind = OptionQuery,160 >;161162 #[pallet::hooks]163 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {164 fn on_runtime_upgrade() -> Weight {165 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {166 let mut had_consts = BTreeSet::new();167 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {168 let mut props = vec![];169 if !v.const_data.is_empty() {170 props.push(Property {171 key: b"_old_constData".to_vec().try_into().unwrap(),172 value: v.const_data.clone().into_inner().try_into().expect("const too long"),173 });174 had_consts.insert(collection);175 }176 if !v.variable_data.is_empty() {177 props.push(Property {178 key: b"_old_variableData".to_vec().try_into().unwrap(),179 value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),180 })181 }182 if !props.is_empty() {183 Self::set_scoped_token_properties(184 collection,185 token,186 PropertyScope::None,187 props.into_iter(),188 ).expect("existing token data exceeds property storage");189 }190 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))191 });192 for collection in had_consts {193 <PalletCommon<T>>::set_property_permission_unchecked(194 collection,195 PropertyKeyPermission {196 key: b"_old_constData".to_vec().try_into().unwrap(),197 permission: PropertyPermission {198 mutable: false,199 collection_admin: true,200 token_owner: false,201 },202 }203 ).expect("failed to configure permission");204 }205 }206207 0208 }209 }210}211212pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);213impl<T: Config> NonfungibleHandle<T> {214 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {215 Self(inner)216 }217 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {218 self.0219 }220 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {221 &mut self.0222 }223}224impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {225 fn recorder(&self) -> &SubstrateRecorder<T> {226 self.0.recorder()227 }228 fn into_recorder(self) -> SubstrateRecorder<T> {229 self.0.into_recorder()230 }231}232impl<T: Config> Deref for NonfungibleHandle<T> {233 type Target = pallet_common::CollectionHandle<T>;234235 fn deref(&self) -> &Self::Target {236 &self.0237 }238}239240impl<T: Config> Pallet<T> {241 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {242 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)243 }244 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {245 <TokenData<T>>::contains_key((collection.id, token))246 }247248 pub fn set_scoped_token_property(249 collection_id: CollectionId,250 token_id: TokenId,251 scope: PropertyScope,252 property: Property,253 ) -> DispatchResult {254 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {255 properties.try_scoped_set(scope, property.key, property.value)256 })257 .map_err(<CommonError<T>>::from)?;258259 Ok(())260 }261262 pub fn set_scoped_token_properties(263 collection_id: CollectionId,264 token_id: TokenId,265 scope: PropertyScope,266 properties: impl Iterator<Item=Property>,267 ) -> DispatchResult {268 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {269 stored_properties.try_scoped_set_from_iter(scope, properties)270 })271 .map_err(<CommonError<T>>::from)?;272273 Ok(())274 }275276 pub fn current_token_id(collection_id: CollectionId) -> TokenId {277 TokenId(<TokensMinted<T>>::get(collection_id))278 }279}280281// unchecked calls skips any permission checks282impl<T: Config> Pallet<T> {283 pub fn init_collection(284 owner: T::AccountId,285 data: CreateCollectionData<T::AccountId>,286 ) -> Result<CollectionId, DispatchError> {287 <PalletCommon<T>>::init_collection(owner, data)288 }289 pub fn destroy_collection(290 collection: NonfungibleHandle<T>,291 sender: &T::CrossAccountId,292 ) -> DispatchResult {293 let id = collection.id;294295 if Self::collection_has_tokens(id) {296 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());297 }298299 // =========300301 PalletCommon::destroy_collection(collection.0, sender)?;302303 <TokenData<T>>::remove_prefix((id,), None);304 <TokenChildren<T>>::remove_prefix((id,), None);305 <Owned<T>>::remove_prefix((id,), None);306 <TokensMinted<T>>::remove(id);307 <TokensBurnt<T>>::remove(id);308 <Allowance<T>>::remove_prefix((id,), None);309 <AccountBalance<T>>::remove_prefix((id,), None);310 Ok(())311 }312313 pub fn burn(314 collection: &NonfungibleHandle<T>,315 sender: &T::CrossAccountId,316 token: TokenId,317 ) -> DispatchResult {318 let token_data =319 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;320 ensure!(321 &token_data.owner == sender322 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),323 <CommonError<T>>::NoPermission324 );325326 if collection.permissions.access() == AccessMode::AllowList {327 collection.check_allowlist(sender)?;328 }329330 if Self::token_has_children(collection.id, token) {331 return Err(<Error<T>>::CantBurnNftWithChildren.into());332 }333334 let burnt = <TokensBurnt<T>>::get(collection.id)335 .checked_add(1)336 .ok_or(ArithmeticError::Overflow)?;337338 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))339 .checked_sub(1)340 .ok_or(ArithmeticError::Overflow)?;341342 // =========343344 if balance == 0 {345 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));346 } else {347 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);348 }349350 <PalletStructure<T>>::unnest_if_nested(351 &token_data.owner,352 collection.id,353 token354 );355356 <Owned<T>>::remove((collection.id, &token_data.owner, token));357 <TokensBurnt<T>>::insert(collection.id, burnt);358 <TokenData<T>>::remove((collection.id, token));359 <TokenProperties<T>>::remove((collection.id, token));360 let old_spender = <Allowance<T>>::take((collection.id, token));361362 if let Some(old_spender) = old_spender {363 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(364 collection.id,365 token,366 sender.clone(),367 old_spender,368 0,369 ));370 }371372 <PalletEvm<T>>::deposit_log(373 ERC721Events::Transfer {374 from: *token_data.owner.as_eth(),375 to: H160::default(),376 token_id: token.into(),377 }378 .to_log(collection_id_to_address(collection.id)),379 );380 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(381 collection.id,382 token,383 token_data.owner,384 1,385 ));386 Ok(())387 }388389 pub fn set_token_property(390 collection: &NonfungibleHandle<T>,391 sender: &T::CrossAccountId,392 token_id: TokenId,393 property: Property,394 ) -> DispatchResult {395 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;396397 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {398 let property = property.clone();399 properties.try_set(property.key, property.value)400 })401 .map_err(<CommonError<T>>::from)?;402403 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(404 collection.id,405 token_id,406 property.key,407 ));408409 Ok(())410 }411412 #[transactional]413 pub fn set_token_properties(414 collection: &NonfungibleHandle<T>,415 sender: &T::CrossAccountId,416 token_id: TokenId,417 properties: Vec<Property>,418 ) -> DispatchResult {419 for property in properties {420 Self::set_token_property(collection, sender, token_id, property)?;421 }422423 Ok(())424 }425426 pub fn delete_token_property(427 collection: &NonfungibleHandle<T>,428 sender: &T::CrossAccountId,429 token_id: TokenId,430 property_key: PropertyKey,431 ) -> DispatchResult {432 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;433434 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {435 properties.remove(&property_key)436 })437 .map_err(<CommonError<T>>::from)?;438439 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(440 collection.id,441 token_id,442 property_key,443 ));444445 Ok(())446 }447448 fn check_token_change_permission(449 collection: &NonfungibleHandle<T>,450 sender: &T::CrossAccountId,451 token_id: TokenId,452 property_key: &PropertyKey,453 ) -> DispatchResult {454 let permission = <PalletCommon<T>>::property_permissions(collection.id)455 .get(property_key)456 .cloned()457 .unwrap_or_else(PropertyPermission::none);458459 let token_data = <TokenData<T>>::get((collection.id, token_id))460 .ok_or(<CommonError<T>>::TokenNotFound)?;461462 let check_token_owner = || -> DispatchResult {463 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);464 Ok(())465 };466467 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))468 .get(property_key)469 .is_some();470471 match permission {472 PropertyPermission { mutable: false, .. } if is_property_exists => {473 Err(<CommonError<T>>::NoPermission.into())474 }475476 PropertyPermission {477 collection_admin,478 token_owner,479 ..480 } => {481 let mut check_result = Err(<CommonError<T>>::NoPermission.into());482483 if collection_admin {484 check_result = collection.check_is_owner_or_admin(sender);485 }486487 if token_owner {488 check_result.or_else(|_| check_token_owner())489 } else {490 check_result491 }492 }493 }494 }495496 #[transactional]497 pub fn delete_token_properties(498 collection: &NonfungibleHandle<T>,499 sender: &T::CrossAccountId,500 token_id: TokenId,501 property_keys: Vec<PropertyKey>,502 ) -> DispatchResult {503 for key in property_keys {504 Self::delete_token_property(collection, sender, token_id, key)?;505 }506507 Ok(())508 }509510 pub fn set_collection_properties(511 collection: &NonfungibleHandle<T>,512 sender: &T::CrossAccountId,513 properties: Vec<Property>,514 ) -> DispatchResult {515 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)516 }517518 pub fn delete_collection_properties(519 collection: &CollectionHandle<T>,520 sender: &T::CrossAccountId,521 property_keys: Vec<PropertyKey>,522 ) -> DispatchResult {523 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)524 }525526 pub fn set_property_permissions(527 collection: &CollectionHandle<T>,528 sender: &T::CrossAccountId,529 property_permissions: Vec<PropertyKeyPermission>,530 ) -> DispatchResult {531 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)532 }533534 pub fn set_property_permission(535 collection: &CollectionHandle<T>,536 sender: &T::CrossAccountId,537 permission: PropertyKeyPermission,538 ) -> DispatchResult {539 <PalletCommon<T>>::set_property_permission(collection, sender, permission)540 }541542 pub fn transfer(543 collection: &NonfungibleHandle<T>,544 from: &T::CrossAccountId,545 to: &T::CrossAccountId,546 token: TokenId,547 nesting_budget: &dyn Budget,548 ) -> DispatchResult {549 ensure!(550 collection.limits.transfers_enabled(),551 <CommonError<T>>::TransferNotAllowed552 );553554 let token_data =555 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;556 // TODO: require sender to be token, owner, require admins to go through transfer_from557 ensure!(558 &token_data.owner == from559 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),560 <CommonError<T>>::NoPermission561 );562563 if collection.permissions.access() == AccessMode::AllowList {564 collection.check_allowlist(from)?;565 collection.check_allowlist(to)?;566 }567 <PalletCommon<T>>::ensure_correct_receiver(to)?;568569 let balance_from = <AccountBalance<T>>::get((collection.id, from))570 .checked_sub(1)571 .ok_or(<CommonError<T>>::TokenValueTooLow)?;572 let balance_to = if from != to {573 let balance_to = <AccountBalance<T>>::get((collection.id, to))574 .checked_add(1)575 .ok_or(ArithmeticError::Overflow)?;576577 ensure!(578 balance_to < collection.limits.account_token_ownership_limit(),579 <CommonError<T>>::AccountTokenLimitExceeded,580 );581582 Some(balance_to)583 } else {584 None585 };586587 <PalletStructure<T>>::nest_if_sent_to_token(588 from.clone(),589 to,590 collection.id,591 token,592 nesting_budget593 )?;594595 // =========596597 <PalletStructure<T>>::unnest_if_nested(598 from,599 collection.id,600 token601 );602603 <TokenData<T>>::insert(604 (collection.id, token),605 ItemData {606 owner: to.clone(),607 ..token_data608 },609 );610611 if let Some(balance_to) = balance_to {612 // from != to613 if balance_from == 0 {614 <AccountBalance<T>>::remove((collection.id, from));615 } else {616 <AccountBalance<T>>::insert((collection.id, from), balance_from);617 }618 <AccountBalance<T>>::insert((collection.id, to), balance_to);619 <Owned<T>>::remove((collection.id, from, token));620 <Owned<T>>::insert((collection.id, to, token), true);621 }622 Self::set_allowance_unchecked(collection, from, token, None, true);623624 <PalletEvm<T>>::deposit_log(625 ERC721Events::Transfer {626 from: *from.as_eth(),627 to: *to.as_eth(),628 token_id: token.into(),629 }630 .to_log(collection_id_to_address(collection.id)),631 );632 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(633 collection.id,634 token,635 from.clone(),636 to.clone(),637 1,638 ));639 Ok(())640 }641642 pub fn create_multiple_items(643 collection: &NonfungibleHandle<T>,644 sender: &T::CrossAccountId,645 data: Vec<CreateItemData<T>>,646 nesting_budget: &dyn Budget,647 ) -> DispatchResult {648 if !collection.is_owner_or_admin(sender) {649 ensure!(650 collection.permissions.mint_mode(),651 <CommonError<T>>::PublicMintingNotAllowed652 );653 collection.check_allowlist(sender)?;654655 for item in data.iter() {656 collection.check_allowlist(&item.owner)?;657 }658 }659660 for data in data.iter() {661 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;662 }663664 let first_token = <TokensMinted<T>>::get(collection.id);665 let tokens_minted = first_token666 .checked_add(data.len() as u32)667 .ok_or(ArithmeticError::Overflow)?;668 ensure!(669 tokens_minted <= collection.limits.token_limit(),670 <CommonError<T>>::CollectionTokenLimitExceeded671 );672673 let mut balances = BTreeMap::new();674 for data in &data {675 let balance = balances676 .entry(&data.owner)677 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));678 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;679680 ensure!(681 *balance <= collection.limits.account_token_ownership_limit(),682 <CommonError<T>>::AccountTokenLimitExceeded,683 );684 }685686 for (i, data) in data.iter().enumerate() {687 let token = TokenId(first_token + i as u32 + 1);688689 <PalletStructure<T>>::check_nesting(690 sender.clone(),691 &data.owner,692 collection.id,693 token,694 nesting_budget,695 )?;696 }697698 // =========699700 with_transaction(|| {701 for (i, data) in data.iter().enumerate() {702 let token = first_token + i as u32 + 1;703704 <TokenData<T>>::insert(705 (collection.id, token),706 ItemData {707 // const_data: data.const_data.clone(),708 owner: data.owner.clone(),709 },710 );711712 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));713714 if let Err(e) = Self::set_token_properties(715 collection,716 sender,717 TokenId(token),718 data.properties.clone().into_inner(),719 ) {720 return TransactionOutcome::Rollback(Err(e));721 }722 }723 TransactionOutcome::Commit(Ok(()))724 })?;725726 <TokensMinted<T>>::insert(collection.id, tokens_minted);727 for (account, balance) in balances {728 <AccountBalance<T>>::insert((collection.id, account), balance);729 }730 for (i, data) in data.into_iter().enumerate() {731 let token = first_token + i as u32 + 1;732 <Owned<T>>::insert((collection.id, &data.owner, token), true);733734 <PalletEvm<T>>::deposit_log(735 ERC721Events::Transfer {736 from: H160::default(),737 to: *data.owner.as_eth(),738 token_id: token.into(),739 }740 .to_log(collection_id_to_address(collection.id)),741 );742 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(743 collection.id,744 TokenId(token),745 data.owner.clone(),746 1,747 ));748 }749 Ok(())750 }751752 pub fn set_allowance_unchecked(753 collection: &NonfungibleHandle<T>,754 sender: &T::CrossAccountId,755 token: TokenId,756 spender: Option<&T::CrossAccountId>,757 assume_implicit_eth: bool,758 ) {759 if let Some(spender) = spender {760 let old_spender = <Allowance<T>>::get((collection.id, token));761 <Allowance<T>>::insert((collection.id, token), spender);762 // In ERC721 there is only one possible approved user of token, so we set763 // approved user to spender764 <PalletEvm<T>>::deposit_log(765 ERC721Events::Approval {766 owner: *sender.as_eth(),767 approved: *spender.as_eth(),768 token_id: token.into(),769 }770 .to_log(collection_id_to_address(collection.id)),771 );772 // In Unique chain, any token can have any amount of approved users, so we need to773 // set allowance of old owner to 0, and allowance of new owner to 1774 if old_spender.as_ref() != Some(spender) {775 if let Some(old_owner) = old_spender {776 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(777 collection.id,778 token,779 sender.clone(),780 old_owner,781 0,782 ));783 }784 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(785 collection.id,786 token,787 sender.clone(),788 spender.clone(),789 1,790 ));791 }792 } else {793 let old_spender = <Allowance<T>>::take((collection.id, token));794 if !assume_implicit_eth {795 // In ERC721 there is only one possible approved user of token, so we set796 // approved user to zero address797 <PalletEvm<T>>::deposit_log(798 ERC721Events::Approval {799 owner: *sender.as_eth(),800 approved: H160::default(),801 token_id: token.into(),802 }803 .to_log(collection_id_to_address(collection.id)),804 );805 }806 // In Unique chain, any token can have any amount of approved users, so we need to807 // set allowance of old owner to 0808 if let Some(old_spender) = old_spender {809 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(810 collection.id,811 token,812 sender.clone(),813 old_spender,814 0,815 ));816 }817 }818 }819820 pub fn set_allowance(821 collection: &NonfungibleHandle<T>,822 sender: &T::CrossAccountId,823 token: TokenId,824 spender: Option<&T::CrossAccountId>,825 ) -> DispatchResult {826 if collection.permissions.access() == AccessMode::AllowList {827 collection.check_allowlist(sender)?;828 if let Some(spender) = spender {829 collection.check_allowlist(spender)?;830 }831 }832833 if let Some(spender) = spender {834 <PalletCommon<T>>::ensure_correct_receiver(spender)?;835 }836 let token_data =837 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;838 if &token_data.owner != sender {839 ensure!(840 collection.ignores_owned_amount(sender),841 <CommonError<T>>::CantApproveMoreThanOwned842 );843 }844845 // =========846847 Self::set_allowance_unchecked(collection, sender, token, spender, false);848 Ok(())849 }850851 fn check_allowed(852 collection: &NonfungibleHandle<T>,853 spender: &T::CrossAccountId,854 from: &T::CrossAccountId,855 token: TokenId,856 nesting_budget: &dyn Budget,857 ) -> DispatchResult {858 if spender.conv_eq(from) {859 return Ok(());860 }861 if collection.permissions.access() == AccessMode::AllowList {862 // `from`, `to` checked in [`transfer`]863 collection.check_allowlist(spender)?;864 }865 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {866 // TODO: should collection owner be allowed to perform this transfer?867 ensure!(868 <PalletStructure<T>>::check_indirectly_owned(869 spender.clone(),870 source.0,871 source.1,872 None,873 nesting_budget874 )?,875 <CommonError<T>>::ApprovedValueTooLow,876 );877 return Ok(());878 }879 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {880 return Ok(());881 }882 ensure!(883 collection.ignores_allowance(spender),884 <CommonError<T>>::ApprovedValueTooLow885 );886 Ok(())887 }888889 pub fn transfer_from(890 collection: &NonfungibleHandle<T>,891 spender: &T::CrossAccountId,892 from: &T::CrossAccountId,893 to: &T::CrossAccountId,894 token: TokenId,895 nesting_budget: &dyn Budget,896 ) -> DispatchResult {897 Self::check_allowed(collection, spender, from, token, nesting_budget)?;898899 // =========900901 // Allowance is reset in [`transfer`]902 Self::transfer(collection, from, to, token, nesting_budget)903 }904905 pub fn burn_from(906 collection: &NonfungibleHandle<T>,907 spender: &T::CrossAccountId,908 from: &T::CrossAccountId,909 token: TokenId,910 nesting_budget: &dyn Budget,911 ) -> DispatchResult {912 Self::check_allowed(collection, spender, from, token, nesting_budget)?;913914 // =========915916 Self::burn(collection, from, token)917 }918919 pub fn check_nesting(920 handle: &NonfungibleHandle<T>,921 sender: T::CrossAccountId,922 from: (CollectionId, TokenId),923 under: TokenId,924 nesting_budget: &dyn Budget,925 ) -> DispatchResult {926 fn ensure_sender_allowed<T: Config>(927 collection: CollectionId,928 token: TokenId,929 for_nest: (CollectionId, TokenId),930 sender: T::CrossAccountId,931 budget: &dyn Budget,932 ) -> DispatchResult {933 ensure!(934 <PalletStructure<T>>::check_indirectly_owned(935 sender,936 collection,937 token,938 Some(for_nest),939 budget940 )?,941 <CommonError<T>>::OnlyOwnerAllowedToNest,942 );943 Ok(())944 }945 match handle.permissions.nesting() {946 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),947 NestingRule::Owner => {948 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?949 }950 NestingRule::OwnerRestricted(whitelist) => {951 ensure!(952 whitelist.contains(&from.0),953 <CommonError<T>>::SourceCollectionIsNotAllowedToNest954 );955 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?956 }957 }958 Ok(())959 }960961 fn nest(962 under: (CollectionId, TokenId),963 to_nest: (CollectionId, TokenId),964 ) {965 <TokenChildren<T>>::insert(966 (under.0, under.1, (to_nest.0, to_nest.1)),967 true968 );969 }970971 fn unnest(972 under: (CollectionId, TokenId),973 to_unnest: (CollectionId, TokenId),974 ) {975 <TokenChildren<T>>::remove(976 (under.0, under.1, to_unnest)977 );978 }979980 fn collection_has_tokens(collection_id: CollectionId) -> bool {981 <TokenData<T>>::iter_prefix((collection_id,)).next().is_some()982 }983984 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {985 <TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()986 }987988 /// Delegated to `create_multiple_items`989 pub fn create_item(990 collection: &NonfungibleHandle<T>,991 sender: &T::CrossAccountId,992 data: CreateItemData<T>,993 nesting_budget: &dyn Budget,994 ) -> DispatchResult {995 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)996 }997}pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -21,7 +21,9 @@
use sp_runtime::{DispatchError, Permill, traits::StaticLookup};
use sp_std::vec::Vec;
use up_data_structs::*;
-use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};
+use pallet_common::{
+ Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations,
+};
use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle, TokenData};
use pallet_evm::account::CrossAccountId;
use core::convert::AsRef;
@@ -38,18 +40,17 @@
#[frame_support::pallet]
pub mod pallet {
- use super::*;
- use pallet_evm::account;
+ use super::*;
+ use pallet_evm::account;
#[pallet::config]
- pub trait Config: frame_system::Config
- + pallet_common::Config
- + pallet_nonfungible::Config
- + account::Config {
+ pub trait Config:
+ frame_system::Config + pallet_common::Config + pallet_nonfungible::Config + account::Config
+ {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
}
- #[pallet::storage]
+ #[pallet::storage]
#[pallet::getter(fn collection_index)]
pub type CollectionIndex<T: Config> = StorageValue<_, RmrkCollectionId, ValueQuery>;
@@ -60,33 +61,33 @@
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
- CollectionCreated {
+ CollectionCreated {
issuer: T::AccountId,
collection_id: RmrkCollectionId,
},
- CollectionDestroyed {
+ CollectionDestroyed {
issuer: T::AccountId,
collection_id: RmrkCollectionId,
},
- IssuerChanged {
+ IssuerChanged {
old_issuer: T::AccountId,
new_issuer: T::AccountId,
collection_id: RmrkCollectionId,
},
- CollectionLocked {
+ CollectionLocked {
issuer: T::AccountId,
collection_id: RmrkCollectionId,
},
- NftMinted {
+ NftMinted {
owner: T::AccountId,
collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
},
- NFTBurned {
+ NFTBurned {
owner: T::AccountId,
nft_id: RmrkNftId,
},
- PropertySet {
+ PropertySet {
collection_id: RmrkCollectionId,
maybe_nft_id: Option<RmrkNftId>,
key: RmrkKeyString,
@@ -96,24 +97,24 @@
#[pallet::error]
pub enum Error<T> {
- /* Unique-specific events */
- CorruptedCollectionType,
- NftTypeEncodeError,
- RmrkPropertyKeyIsTooLong,
- RmrkPropertyValueIsTooLong,
+ /* Unique-specific events */
+ CorruptedCollectionType,
+ NftTypeEncodeError,
+ RmrkPropertyKeyIsTooLong,
+ RmrkPropertyValueIsTooLong,
- /* RMRK compatible events */
- CollectionNotEmpty,
- NoAvailableCollectionId,
- NoAvailableNftId,
- CollectionUnknown,
- NoPermission,
- CollectionFullOrLocked,
+ /* RMRK compatible events */
+ CollectionNotEmpty,
+ NoAvailableCollectionId,
+ NoAvailableNftId,
+ CollectionUnknown,
+ NoPermission,
+ CollectionFullOrLocked,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn create_collection(
origin: OriginFor<T>,
@@ -121,127 +122,141 @@
max: Option<u32>,
symbol: RmrkCollectionSymbol,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
+ let sender = ensure_signed(origin)?;
- let limits = CollectionLimits {
- owner_can_transfer: Some(false),
- token_limit: max,
- ..Default::default()
- };
+ let limits = CollectionLimits {
+ owner_can_transfer: Some(false),
+ token_limit: max,
+ ..Default::default()
+ };
- let data = CreateCollectionData {
- limits: Some(limits),
- token_prefix: symbol.into_inner()
- .try_into()
- .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,
- ..Default::default()
- };
+ let data = CreateCollectionData {
+ limits: Some(limits),
+ token_prefix: symbol
+ .into_inner()
+ .try_into()
+ .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,
+ ..Default::default()
+ };
- let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
+ let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
- if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
- return Err(<Error<T>>::NoAvailableCollectionId.into());
- }
+ if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
+ return Err(<Error<T>>::NoAvailableCollectionId.into());
+ }
- let collection_id = collection_id_res?;
+ let collection_id = collection_id_res?;
- <PalletCommon<T>>::set_scoped_collection_properties(
- collection_id,
- PropertyScope::Rmrk,
- [
- Self::rmrk_property(Metadata, &metadata)?,
- Self::rmrk_property(CollectionType, &misc::CollectionType::Regular)?,
- ].into_iter()
- )?;
+ <PalletCommon<T>>::set_scoped_collection_properties(
+ collection_id,
+ PropertyScope::Rmrk,
+ [
+ Self::rmrk_property(Metadata, &metadata)?,
+ Self::rmrk_property(CollectionType, &misc::CollectionType::Regular)?,
+ ]
+ .into_iter(),
+ )?;
- <CollectionIndex<T>>::mutate(|n| *n += 1);
+ <CollectionIndex<T>>::mutate(|n| *n += 1);
- Self::deposit_event(Event::CollectionCreated {
- issuer: sender,
- collection_id: collection_id.0
- });
+ Self::deposit_event(Event::CollectionCreated {
+ issuer: sender,
+ collection_id: collection_id.0,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn destroy_collection(
origin: OriginFor<T>,
collection_id: RmrkCollectionId,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+ let sender = ensure_signed(origin)?;
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
- let unique_collection_id = collection_id.into();
+ let unique_collection_id = collection_id.into();
- let collection = Self::get_typed_nft_collection(unique_collection_id, misc::CollectionType::Regular)?;
+ let collection = Self::get_typed_nft_collection(
+ unique_collection_id,
+ misc::CollectionType::Regular,
+ )?;
- ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
+ ensure!(
+ collection.total_supply() == 0,
+ <Error<T>>::CollectionNotEmpty
+ );
- <PalletNft<T>>::destroy_collection(collection, &cross_sender)
- .map_err(Self::map_common_err_to_proxy)?;
+ <PalletNft<T>>::destroy_collection(collection, &cross_sender)
+ .map_err(Self::map_common_err_to_proxy)?;
- Self::deposit_event(Event::CollectionDestroyed { issuer: sender, collection_id });
+ Self::deposit_event(Event::CollectionDestroyed {
+ issuer: sender,
+ collection_id,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn change_collection_issuer(
origin: OriginFor<T>,
collection_id: RmrkCollectionId,
new_issuer: <T::Lookup as StaticLookup>::Source,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
+ let sender = ensure_signed(origin)?;
- let new_issuer = T::Lookup::lookup(new_issuer)?;
+ let new_issuer = T::Lookup::lookup(new_issuer)?;
- Self::change_collection_owner(
- collection_id.into(),
- misc::CollectionType::Regular,
- sender.clone(),
- new_issuer.clone()
- )?;
+ Self::change_collection_owner(
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ sender.clone(),
+ new_issuer.clone(),
+ )?;
- Self::deposit_event(Event::IssuerChanged {
+ Self::deposit_event(Event::IssuerChanged {
old_issuer: sender,
new_issuer,
collection_id,
});
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn lock_collection(
origin: OriginFor<T>,
collection_id: RmrkCollectionId,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+ let sender = ensure_signed(origin)?;
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
- let collection = Self::get_typed_nft_collection(
- collection_id.into(),
- misc::CollectionType::Regular
- )?;
+ let collection = Self::get_typed_nft_collection(
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ )?;
- Self::check_collection_owner(&collection, &cross_sender)?;
+ Self::check_collection_owner(&collection, &cross_sender)?;
- let token_count = collection.total_supply();
+ let token_count = collection.total_supply();
- let mut collection = collection.into_inner();
- collection.limits.token_limit = Some(token_count);
- collection.save()?;
+ let mut collection = collection.into_inner();
+ collection.limits.token_limit = Some(token_count);
+ collection.save()?;
- Self::deposit_event(Event::CollectionLocked { issuer: sender, collection_id });
+ Self::deposit_event(Event::CollectionLocked {
+ issuer: sender,
+ collection_id,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn mint_nft(
origin: OriginFor<T>,
@@ -251,47 +266,49 @@
royalty_amount: Option<Permill>,
metadata: RmrkString,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let sender = T::CrossAccountId::from_sub(sender);
- let cross_owner = T::CrossAccountId::from_sub(owner.clone());
+ let sender = ensure_signed(origin)?;
+ let sender = T::CrossAccountId::from_sub(sender);
+ let cross_owner = T::CrossAccountId::from_sub(owner.clone());
- let royalty_info = royalty_amount.map(|amount| rmrk::RoyaltyInfo {
- recipient: recipient.unwrap_or_else(|| owner.clone()),
- amount
- });
+ let royalty_info = royalty_amount.map(|amount| rmrk::RoyaltyInfo {
+ recipient: recipient.unwrap_or_else(|| owner.clone()),
+ amount,
+ });
- let collection = Self::get_typed_nft_collection(
- collection_id.into(),
- misc::CollectionType::Regular,
- )?;
+ let collection = Self::get_typed_nft_collection(
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ )?;
- let nft_id = Self::create_nft(
- &sender,
- &cross_owner,
- &collection,
- NftType::Regular,
- [
- Self::rmrk_property(RoyaltyInfo, &royalty_info)?,
- Self::rmrk_property(Metadata, &metadata)?,
- Self::rmrk_property(Equipped, &false)?,
- Self::rmrk_property(ResourceCollection, &None::<CollectionId>)?,
- Self::rmrk_property(ResourcePriorities, &<Vec<u8>>::new())?,
- ].into_iter()
- ).map_err(|err| match err {
- DispatchError::Arithmetic(_) => <Error<T>>::NoAvailableNftId.into(),
- err => Self::map_common_err_to_proxy(err)
- })?;
+ let nft_id = Self::create_nft(
+ &sender,
+ &cross_owner,
+ &collection,
+ NftType::Regular,
+ [
+ Self::rmrk_property(RoyaltyInfo, &royalty_info)?,
+ Self::rmrk_property(Metadata, &metadata)?,
+ Self::rmrk_property(Equipped, &false)?,
+ Self::rmrk_property(ResourceCollection, &None::<CollectionId>)?,
+ Self::rmrk_property(ResourcePriorities, &<Vec<u8>>::new())?,
+ ]
+ .into_iter(),
+ )
+ .map_err(|err| match err {
+ DispatchError::Arithmetic(_) => <Error<T>>::NoAvailableNftId.into(),
+ err => Self::map_common_err_to_proxy(err),
+ })?;
- Self::deposit_event(Event::NftMinted {
- owner,
- collection_id,
- nft_id: nft_id.0
- });
+ Self::deposit_event(Event::NftMinted {
+ owner,
+ collection_id,
+ nft_id: nft_id.0,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn burn_nft(
origin: OriginFor<T>,
@@ -299,21 +316,24 @@
nft_id: RmrkNftId,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
- Self::destroy_nft(
- cross_sender,
- collection_id.into(),
- misc::CollectionType::Regular,
- nft_id.into()
- )?;
+ Self::destroy_nft(
+ cross_sender,
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ nft_id.into(),
+ )?;
- Self::deposit_event(Event::NFTBurned { owner: sender, nft_id });
+ Self::deposit_event(Event::NFTBurned {
+ owner: sender,
+ nft_id,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn set_property(
origin: OriginFor<T>,
@@ -322,323 +342,346 @@
key: RmrkKeyString,
value: RmrkValueString,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let sender = T::CrossAccountId::from_sub(sender);
+ let sender = ensure_signed(origin)?;
+ let sender = T::CrossAccountId::from_sub(sender);
- let collection_id: CollectionId = rmrk_collection_id.into();
+ let collection_id: CollectionId = rmrk_collection_id.into();
- match maybe_nft_id {
- Some(nft_id) => {
- let token_id: TokenId = nft_id.into();
+ match maybe_nft_id {
+ Some(nft_id) => {
+ let token_id: TokenId = nft_id.into();
- Self::ensure_nft_owner(collection_id, token_id, &sender)?;
- Self::ensure_nft_type(collection_id, token_id, NftType::Regular)?;
+ Self::ensure_nft_owner(collection_id, token_id, &sender)?;
+ Self::ensure_nft_type(collection_id, token_id, NftType::Regular)?;
- <PalletNft<T>>::set_scoped_token_property(
- collection_id,
- token_id,
- PropertyScope::Rmrk,
- Self::rmrk_property(UserProperty(key.as_slice()), &value)?
- )?;
- },
- None => {
- let collection = Self::get_typed_nft_collection(
- collection_id,
- misc::CollectionType::Regular
- )?;
+ <PalletNft<T>>::set_scoped_token_property(
+ collection_id,
+ token_id,
+ PropertyScope::Rmrk,
+ Self::rmrk_property(UserProperty(key.as_slice()), &value)?,
+ )?;
+ }
+ None => {
+ let collection = Self::get_typed_nft_collection(
+ collection_id,
+ misc::CollectionType::Regular,
+ )?;
- Self::check_collection_owner(&collection, &sender)?;
+ Self::check_collection_owner(&collection, &sender)?;
- <PalletCommon<T>>::set_scoped_collection_property(
- collection_id,
- PropertyScope::Rmrk,
- Self::rmrk_property(UserProperty(key.as_slice()), &value)?
- )?;
- }
- }
+ <PalletCommon<T>>::set_scoped_collection_property(
+ collection_id,
+ PropertyScope::Rmrk,
+ Self::rmrk_property(UserProperty(key.as_slice()), &value)?,
+ )?;
+ }
+ }
- Self::deposit_event(
- Event::PropertySet {
- collection_id: rmrk_collection_id,
- maybe_nft_id,
- key,
- value
- }
- );
+ Self::deposit_event(Event::PropertySet {
+ collection_id: rmrk_collection_id,
+ maybe_nft_id,
+ key,
+ value,
+ });
- Ok(())
- }
+ Ok(())
+ }
}
}
impl<T: Config> Pallet<T> {
- pub fn rmrk_property_key(rmrk_key: RmrkProperty) -> Result<PropertyKey, DispatchError> {
- let key = rmrk_key.to_key::<T>()?;
+ pub fn rmrk_property_key(rmrk_key: RmrkProperty) -> Result<PropertyKey, DispatchError> {
+ let key = rmrk_key.to_key::<T>()?;
- let scoped_key = PropertyScope::Rmrk.apply(key)
- .map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)?;
+ let scoped_key = PropertyScope::Rmrk
+ .apply(key)
+ .map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)?;
- Ok(scoped_key)
- }
+ Ok(scoped_key)
+ }
- pub fn rmrk_property<E: Encode>(rmrk_key: RmrkProperty, value: &E) -> Result<Property, DispatchError> {
- let key = rmrk_key.to_key::<T>()?;
+ pub fn rmrk_property<E: Encode>(
+ rmrk_key: RmrkProperty,
+ value: &E,
+ ) -> Result<Property, DispatchError> {
+ let key = rmrk_key.to_key::<T>()?;
- let value = value.encode()
- .try_into()
- .map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong)?;
+ let value = value
+ .encode()
+ .try_into()
+ .map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong)?;
- let property = Property {
- key,
- value,
- };
+ let property = Property { key, value };
- Ok(property)
- }
+ Ok(property)
+ }
- pub fn create_nft(
- sender: &T::CrossAccountId,
- owner: &T::CrossAccountId,
- collection: &NonfungibleHandle<T>,
- nft_type: NftType,
- properties: impl Iterator<Item=Property>
- ) -> Result<TokenId, DispatchError> {
- todo!("store nft type");
- let data = CreateNftExData {
- properties: BoundedVec::default(),
- owner: owner.clone(),
- };
+ pub fn create_nft(
+ sender: &T::CrossAccountId,
+ owner: &T::CrossAccountId,
+ collection: &NonfungibleHandle<T>,
+ nft_type: NftType,
+ properties: impl Iterator<Item = Property>,
+ ) -> Result<TokenId, DispatchError> {
+ todo!("store nft type");
+ let data = CreateNftExData {
+ properties: BoundedVec::default(),
+ owner: owner.clone(),
+ };
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(2);
- <PalletNft<T>>::create_item(
- collection,
- sender,
- data,
- &budget,
- )?;
+ <PalletNft<T>>::create_item(collection, sender, data, &budget)?;
- let nft_id = <PalletNft<T>>::current_token_id(collection.id);
+ let nft_id = <PalletNft<T>>::current_token_id(collection.id);
- <PalletNft<T>>::set_scoped_token_properties(
- collection.id,
- nft_id,
- PropertyScope::Rmrk,
- properties
- )?;
+ <PalletNft<T>>::set_scoped_token_properties(
+ collection.id,
+ nft_id,
+ PropertyScope::Rmrk,
+ properties,
+ )?;
- Ok(nft_id)
- }
+ Ok(nft_id)
+ }
- fn destroy_nft(
- sender: T::CrossAccountId,
- collection_id: CollectionId,
- collection_type: misc::CollectionType,
- token_id: TokenId
- ) -> DispatchResult {
- let collection = Self::get_typed_nft_collection(
- collection_id,
- collection_type
- )?;
+ fn destroy_nft(
+ sender: T::CrossAccountId,
+ collection_id: CollectionId,
+ collection_type: misc::CollectionType,
+ token_id: TokenId,
+ ) -> DispatchResult {
+ let collection = Self::get_typed_nft_collection(collection_id, collection_type)?;
- <PalletNft<T>>::burn(&collection, &sender, token_id)
- .map_err(Self::map_common_err_to_proxy)?;
+ <PalletNft<T>>::burn(&collection, &sender, token_id)
+ .map_err(Self::map_common_err_to_proxy)?;
- Ok(())
- }
+ Ok(())
+ }
- fn change_collection_owner(
- collection_id: CollectionId,
- collection_type: misc::CollectionType,
- sender: T::AccountId,
- new_owner: T::AccountId,
- ) -> DispatchResult {
- let collection = Self::get_typed_nft_collection(
- collection_id,
- collection_type
- )?;
- Self::check_collection_owner(&collection, &T::CrossAccountId::from_sub(sender))?;
+ fn change_collection_owner(
+ collection_id: CollectionId,
+ collection_type: misc::CollectionType,
+ sender: T::AccountId,
+ new_owner: T::AccountId,
+ ) -> DispatchResult {
+ let collection = Self::get_typed_nft_collection(collection_id, collection_type)?;
+ Self::check_collection_owner(&collection, &T::CrossAccountId::from_sub(sender))?;
- let mut collection = collection.into_inner();
+ let mut collection = collection.into_inner();
- collection.owner = new_owner;
- collection.save()
- }
+ collection.owner = new_owner;
+ collection.save()
+ }
- fn check_collection_owner(collection: &NonfungibleHandle<T>, account: &T::CrossAccountId) -> DispatchResult {
- collection.check_is_owner(account)
- .map_err(Self::map_common_err_to_proxy)
- }
+ fn check_collection_owner(
+ collection: &NonfungibleHandle<T>,
+ account: &T::CrossAccountId,
+ ) -> DispatchResult {
+ collection
+ .check_is_owner(account)
+ .map_err(Self::map_common_err_to_proxy)
+ }
- pub fn last_collection_idx() -> RmrkCollectionId {
- <CollectionIndex<T>>::get()
- }
+ pub fn last_collection_idx() -> RmrkCollectionId {
+ <CollectionIndex<T>>::get()
+ }
- pub fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {
- let collection = <CollectionHandle<T>>::try_get(collection_id)
- .map_err(|_| <Error<T>>::CollectionUnknown)?;
+ pub fn get_nft_collection(
+ collection_id: CollectionId,
+ ) -> Result<NonfungibleHandle<T>, DispatchError> {
+ let collection = <CollectionHandle<T>>::try_get(collection_id)
+ .map_err(|_| <Error<T>>::CollectionUnknown)?;
- match collection.mode {
- CollectionMode::NFT => Ok(NonfungibleHandle::cast(collection)),
- _ => Err(<Error<T>>::CollectionUnknown.into())
- }
- }
+ match collection.mode {
+ CollectionMode::NFT => Ok(NonfungibleHandle::cast(collection)),
+ _ => Err(<Error<T>>::CollectionUnknown.into()),
+ }
+ }
- pub fn collection_exists(collection_id: CollectionId) -> bool {
- <CollectionHandle<T>>::try_get(collection_id).is_ok()
- }
+ pub fn collection_exists(collection_id: CollectionId) -> bool {
+ <CollectionHandle<T>>::try_get(collection_id).is_ok()
+ }
- pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
- <TokenData<T>>::contains_key((collection_id, nft_id))
- }
+ pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
+ <TokenData<T>>::contains_key((collection_id, nft_id))
+ }
- pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
- let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
- .get(&Self::rmrk_property_key(key)?)
- .ok_or(<Error<T>>::CollectionUnknown)?
- .clone();
+ pub fn get_collection_property(
+ collection_id: CollectionId,
+ key: RmrkProperty,
+ ) -> Result<PropertyValue, DispatchError> {
+ let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
+ .get(&Self::rmrk_property_key(key)?)
+ .ok_or(<Error<T>>::CollectionUnknown)?
+ .clone();
- Ok(collection_property)
- }
+ Ok(collection_property)
+ }
- pub fn get_collection_type(collection_id: CollectionId) -> Result<misc::CollectionType, DispatchError> {
- let value = Self::get_collection_property(collection_id, CollectionType)?;
+ pub fn get_collection_type(
+ collection_id: CollectionId,
+ ) -> Result<misc::CollectionType, DispatchError> {
+ let value = Self::get_collection_property(collection_id, CollectionType)?;
- let mut value = value.as_slice();
+ let mut value = value.as_slice();
- misc::CollectionType::decode(&mut value)
- .map_err(|_| <Error<T>>::CorruptedCollectionType.into())
- }
+ misc::CollectionType::decode(&mut value)
+ .map_err(|_| <Error<T>>::CorruptedCollectionType.into())
+ }
- pub fn ensure_collection_type(collection_id: CollectionId, collection_type: misc::CollectionType) -> DispatchResult {
- let actual_type = Self::get_collection_type(collection_id)?;
- ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
+ pub fn ensure_collection_type(
+ collection_id: CollectionId,
+ collection_type: misc::CollectionType,
+ ) -> DispatchResult {
+ let actual_type = Self::get_collection_type(collection_id)?;
+ ensure!(
+ actual_type == collection_type,
+ <CommonError<T>>::NoPermission
+ );
- Ok(())
- }
+ Ok(())
+ }
- pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
- let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
- .get(&Self::rmrk_property_key(key)?)
- .ok_or(<Error<T>>::NoAvailableNftId)?
- .clone();
+ pub fn get_nft_property(
+ collection_id: CollectionId,
+ nft_id: TokenId,
+ key: RmrkProperty,
+ ) -> Result<PropertyValue, DispatchError> {
+ let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
+ .get(&Self::rmrk_property_key(key)?)
+ .ok_or(<Error<T>>::NoAvailableNftId)?
+ .clone();
- Ok(nft_property)
- }
+ Ok(nft_property)
+ }
- pub fn get_nft_type(_collection_id: CollectionId, _token_id: TokenId) -> Result<NftType, DispatchError> {
- todo!("should get it from properties?")
- }
+ 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 {
- let actual_type = Self::get_nft_type(collection_id, token_id)?;
- ensure!(actual_type == nft_type, <Error<T>>::NoPermission);
+ pub fn ensure_nft_type(
+ collection_id: CollectionId,
+ token_id: TokenId,
+ nft_type: NftType,
+ ) -> DispatchResult {
+ let actual_type = Self::get_nft_type(collection_id, token_id)?;
+ ensure!(actual_type == nft_type, <Error<T>>::NoPermission);
- Ok(())
- }
+ Ok(())
+ }
- pub fn ensure_nft_owner(
- collection_id: CollectionId,
- token_id: TokenId,
- possible_owner: &T::CrossAccountId
- ) -> DispatchResult {
- let token_data = <TokenData<T>>::get((collection_id, token_id))
- .ok_or(<Error<T>>::NoAvailableNftId)?;
+ pub fn ensure_nft_owner(
+ collection_id: CollectionId,
+ token_id: TokenId,
+ possible_owner: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let token_data =
+ <TokenData<T>>::get((collection_id, token_id)).ok_or(<Error<T>>::NoAvailableNftId)?;
- ensure!(token_data.owner == *possible_owner, <Error<T>>::NoPermission);
+ ensure!(
+ token_data.owner == *possible_owner,
+ <Error<T>>::NoPermission
+ );
- Ok(())
- }
+ Ok(())
+ }
- pub fn filter_user_properties<Key, Value, R, Mapper>(
- collection_id: CollectionId,
- token_id: Option<TokenId>,
- filter_keys: Option<Vec<RmrkPropertyKey>>,
- mapper: Mapper,
- ) -> Result<Vec<R>, DispatchError>
- where
- Key: TryFrom<RmrkPropertyKey> + AsRef<[u8]>,
- Value: Decode + Default,
- Mapper: Fn(Key, Value) -> R
- {
- filter_keys.map(|keys| {
- let properties = keys.into_iter()
- .filter_map(|key| {
- let key: Key = key.try_into().ok()?;
+ pub fn filter_user_properties<Key, Value, R, Mapper>(
+ collection_id: CollectionId,
+ token_id: Option<TokenId>,
+ filter_keys: Option<Vec<RmrkPropertyKey>>,
+ mapper: Mapper,
+ ) -> Result<Vec<R>, DispatchError>
+ where
+ Key: TryFrom<RmrkPropertyKey> + AsRef<[u8]>,
+ Value: Decode + Default,
+ Mapper: Fn(Key, Value) -> R,
+ {
+ filter_keys
+ .map(|keys| {
+ let properties = keys
+ .into_iter()
+ .filter_map(|key| {
+ let key: Key = key.try_into().ok()?;
- let value = match token_id {
- Some(token_id) => Self::get_nft_property(
- collection_id,
- token_id,
- UserProperty(key.as_ref())
- ),
- None => Self::get_collection_property(
- collection_id,
- UserProperty(key.as_ref())
- )
- }.ok()?.decode_or_default();
+ let value = match token_id {
+ Some(token_id) => Self::get_nft_property(
+ collection_id,
+ token_id,
+ UserProperty(key.as_ref()),
+ ),
+ None => Self::get_collection_property(
+ collection_id,
+ UserProperty(key.as_ref()),
+ ),
+ }
+ .ok()?
+ .decode_or_default();
- Some(mapper(key, value))
- })
- .collect();
+ Some(mapper(key, value))
+ })
+ .collect();
- Ok(properties)
- }).unwrap_or_else(|| {
- let properties = Self::iterate_user_properties(collection_id, token_id, mapper)?
- .collect();
+ Ok(properties)
+ })
+ .unwrap_or_else(|| {
+ let properties =
+ Self::iterate_user_properties(collection_id, token_id, mapper)?.collect();
- Ok(properties)
- })
- }
+ Ok(properties)
+ })
+ }
- pub fn iterate_user_properties<Key, Value, R, Mapper>(
- collection_id: CollectionId,
- token_id: Option<TokenId>,
- mapper: Mapper,
- ) -> Result<impl Iterator<Item=R>, DispatchError>
- where
- Key: TryFrom<RmrkPropertyKey> + AsRef<[u8]>,
- Value: Decode + Default,
- Mapper: Fn(Key, Value) -> R
- {
- let key_prefix = Self::rmrk_property_key(UserProperty(b""))?;
+ pub fn iterate_user_properties<Key, Value, R, Mapper>(
+ collection_id: CollectionId,
+ token_id: Option<TokenId>,
+ mapper: Mapper,
+ ) -> Result<impl Iterator<Item = R>, DispatchError>
+ where
+ Key: TryFrom<RmrkPropertyKey> + AsRef<[u8]>,
+ Value: Decode + Default,
+ Mapper: Fn(Key, Value) -> R,
+ {
+ let key_prefix = Self::rmrk_property_key(UserProperty(b""))?;
- let properties = match token_id {
- Some(token_id) => <PalletNft<T>>::token_properties((collection_id, token_id)),
- None => <PalletCommon<T>>::collection_properties(collection_id)
- };
+ let properties = match token_id {
+ Some(token_id) => <PalletNft<T>>::token_properties((collection_id, token_id)),
+ None => <PalletCommon<T>>::collection_properties(collection_id),
+ };
- let properties = properties
- .into_iter()
- .filter_map(move |(key, value)| {
- let key = key.as_slice().strip_prefix(key_prefix.as_slice())?;
+ let properties = properties.into_iter().filter_map(move |(key, value)| {
+ let key = key.as_slice().strip_prefix(key_prefix.as_slice())?;
- let key: Key = key.to_vec().try_into().ok()?;
- let value: Value = value.decode_or_default();
+ let key: Key = key.to_vec().try_into().ok()?;
+ let value: Value = value.decode_or_default();
- Some(mapper(key, value))
- });
+ Some(mapper(key, value))
+ });
- Ok(properties)
- }
+ Ok(properties)
+ }
- pub fn get_typed_nft_collection(
- collection_id: CollectionId,
- collection_type: misc::CollectionType
- ) -> Result<NonfungibleHandle<T>, DispatchError> {
- Self::ensure_collection_type(collection_id, collection_type)?;
+ pub fn get_typed_nft_collection(
+ collection_id: CollectionId,
+ collection_type: misc::CollectionType,
+ ) -> Result<NonfungibleHandle<T>, DispatchError> {
+ Self::ensure_collection_type(collection_id, collection_type)?;
- Self::get_nft_collection(collection_id)
- }
+ Self::get_nft_collection(collection_id)
+ }
- fn map_common_err_to_proxy(err: DispatchError) -> DispatchError {
- map_common_err_to_proxy! {
- match err {
- NoPermission => NoPermission,
- CollectionTokenLimitExceeded => CollectionFullOrLocked,
- PublicMintingNotAllowed => NoPermission,
- TokenNotFound => NoAvailableNftId
- }
- }
- }
+ fn map_common_err_to_proxy(err: DispatchError) -> DispatchError {
+ map_common_err_to_proxy! {
+ match err {
+ NoPermission => NoPermission,
+ CollectionTokenLimitExceeded => CollectionFullOrLocked,
+ PublicMintingNotAllowed => NoPermission,
+ TokenNotFound => NoAvailableNftId
+ }
+ }
+ }
}
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -15,41 +15,42 @@
}
pub trait RmrkDecode<T: Decode + Default, S> {
- fn decode_or_default(&self) -> T;
+ fn decode_or_default(&self) -> T;
}
impl<T: Decode + Default, S> RmrkDecode<T, S> for BoundedVec<u8, S> {
- fn decode_or_default(&self) -> T {
- let mut value = self.as_slice();
+ fn decode_or_default(&self) -> T {
+ let mut value = self.as_slice();
- T::decode(&mut value).unwrap_or_default()
- }
+ T::decode(&mut value).unwrap_or_default()
+ }
}
pub trait RmrkRebind<T, S> {
- fn rebind(&self) -> BoundedVec<u8, S>;
+ fn rebind(&self) -> BoundedVec<u8, S>;
}
-impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
- fn rebind(&self) -> BoundedVec<u8, S> {
- BoundedVec::<u8, S>::try_from(
- self.clone().into_inner()
- ).unwrap_or_default()
- }
+impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T>
+where
+ BoundedVec<u8, S>: TryFrom<Vec<u8>>,
+{
+ fn rebind(&self) -> BoundedVec<u8, S> {
+ BoundedVec::<u8, S>::try_from(self.clone().into_inner()).unwrap_or_default()
+ }
}
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
- Regular,
- Resource,
- Base,
+ Regular,
+ Resource,
+ Base,
}
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum NftType {
- Regular,
- Resource,
- FixedPart,
- SlotPart,
- Theme
+ Regular,
+ Resource,
+ FixedPart,
+ SlotPart,
+ Theme,
}
pallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/property.rs
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -2,38 +2,38 @@
use core::convert::AsRef;
pub enum RmrkProperty<'r> {
- Metadata,
- CollectionType,
- RoyaltyInfo,
- Equipped,
- ResourceCollection,
- ResourcePriorities,
- ResourceType,
- PendingResourceAccept,
- PendingResourceRemoval,
- Parts,
- Base,
- Src,
- Slot,
- License,
- Thumb,
- EquippedNft,
- BaseType,
- ExternalPartId,
- EquippableList,
- ZIndex,
- ThemeName,
- ThemeInherit,
- UserProperty(&'r [u8]),
+ Metadata,
+ CollectionType,
+ RoyaltyInfo,
+ Equipped,
+ ResourceCollection,
+ ResourcePriorities,
+ ResourceType,
+ PendingResourceAccept,
+ PendingResourceRemoval,
+ Parts,
+ Base,
+ Src,
+ Slot,
+ License,
+ Thumb,
+ EquippedNft,
+ BaseType,
+ ExternalPartId,
+ EquippableList,
+ ZIndex,
+ ThemeName,
+ ThemeInherit,
+ UserProperty(&'r [u8]),
}
impl<'r> RmrkProperty<'r> {
- pub fn to_key<T: Config>(self) -> Result<PropertyKey, Error<T>> {
- fn get_bytes<T: AsRef<[u8]>>(container: &T) -> &[u8] {
- container.as_ref()
- }
+ pub fn to_key<T: Config>(self) -> Result<PropertyKey, Error<T>> {
+ fn get_bytes<T: AsRef<[u8]>>(container: &T) -> &[u8] {
+ container.as_ref()
+ }
- macro_rules! key {
+ macro_rules! key {
($($component:expr),+) => {
PropertyKey::try_from([$(key!(@ &$component)),+].concat())
.map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)
@@ -44,30 +44,30 @@
};
}
- match self {
- Self::Metadata => key!("metadata"),
- Self::CollectionType => key!("collection-type"),
- Self::RoyaltyInfo => key!("royalty-info"),
- Self::Equipped => key!("equipped"),
- Self::ResourceCollection => key!("resource-collection"),
- Self::ResourcePriorities => key!("resource-priorities"),
- Self::ResourceType => key!("resource-type"),
- Self::PendingResourceAccept => key!("pending-accept"),
- Self::PendingResourceRemoval => key!("pending-removal"),
- Self::Parts => key!("parts"),
- Self::Base => key!("base"),
- Self::Src => key!("src"),
- Self::Slot => key!("slot"),
- Self::License => key!("license"),
- Self::Thumb => key!("thumb"),
- Self::EquippedNft => key!("equipped-nft"),
- Self::BaseType => key!("base-type"),
- Self::ExternalPartId => key!("ext-part-id"),
- Self::EquippableList => key!("equippable-list"),
- Self::ZIndex => key!("z-index"),
- Self::ThemeName => key!("theme-name"),
- Self::ThemeInherit => key!("theme-inherit"),
- Self::UserProperty(name) => key!("userprop-", name),
- }
- }
+ match self {
+ Self::Metadata => key!("metadata"),
+ Self::CollectionType => key!("collection-type"),
+ Self::RoyaltyInfo => key!("royalty-info"),
+ Self::Equipped => key!("equipped"),
+ Self::ResourceCollection => key!("resource-collection"),
+ Self::ResourcePriorities => key!("resource-priorities"),
+ Self::ResourceType => key!("resource-type"),
+ Self::PendingResourceAccept => key!("pending-accept"),
+ Self::PendingResourceRemoval => key!("pending-removal"),
+ Self::Parts => key!("parts"),
+ Self::Base => key!("base"),
+ Self::Src => key!("src"),
+ Self::Slot => key!("slot"),
+ Self::License => key!("license"),
+ Self::Thumb => key!("thumb"),
+ Self::EquippedNft => key!("equipped-nft"),
+ Self::BaseType => key!("base-type"),
+ Self::ExternalPartId => key!("ext-part-id"),
+ Self::EquippableList => key!("equippable-list"),
+ Self::ZIndex => key!("z-index"),
+ Self::ThemeName => key!("theme-name"),
+ Self::ThemeInherit => key!("theme-inherit"),
+ Self::UserProperty(name) => key!("userprop-", name),
+ }
+ }
}
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -21,7 +21,11 @@
use sp_runtime::DispatchError;
use up_data_structs::*;
use pallet_common::{Pallet as PalletCommon, Error as CommonError};
-use pallet_rmrk_core::{Pallet as PalletCore, misc::{self, *}, property::RmrkProperty::*};
+use pallet_rmrk_core::{
+ Pallet as PalletCore,
+ misc::{self, *},
+ property::RmrkProperty::*,
+};
use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
use pallet_evm::account::CrossAccountId;
@@ -29,212 +33,206 @@
#[frame_support::pallet]
pub mod pallet {
- use super::*;
+ use super::*;
#[pallet::config]
- pub trait Config: frame_system::Config
- + pallet_rmrk_core::Config {
+ pub trait Config: frame_system::Config + pallet_rmrk_core::Config {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
}
- #[pallet::storage]
+ #[pallet::storage]
#[pallet::getter(fn internal_part_id)]
- pub type InernalPartId<T: Config> = StorageDoubleMap<
- _,
- Twox64Concat,
- CollectionId,
- Twox64Concat,
- RmrkPartId,
- TokenId
- >;
+ pub type InernalPartId<T: Config> =
+ StorageDoubleMap<_, Twox64Concat, CollectionId, Twox64Concat, RmrkPartId, TokenId>;
- #[pallet::storage]
+ #[pallet::storage]
#[pallet::getter(fn base_has_default_theme)]
- pub type BaseHasDefaultTheme<T: Config> = StorageMap<
- _,
- Twox64Concat,
- CollectionId,
- bool,
- ValueQuery
- >;
+ pub type BaseHasDefaultTheme<T: Config> =
+ StorageMap<_, Twox64Concat, CollectionId, bool, ValueQuery>;
- #[pallet::pallet]
+ #[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
- BaseCreated {
+ BaseCreated {
issuer: T::AccountId,
base_id: RmrkBaseId,
},
- }
+ }
- #[pallet::error]
+ #[pallet::error]
pub enum Error<T> {
- PermissionError,
- NoAvailableBaseId,
- NoAvailablePartId,
- BaseDoesntExist,
- NeedsDefaultThemeFirst,
- }
+ PermissionError,
+ NoAvailableBaseId,
+ NoAvailablePartId,
+ BaseDoesntExist,
+ NeedsDefaultThemeFirst,
+ }
- #[pallet::call]
+ #[pallet::call]
impl<T: Config> Pallet<T> {
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
pub fn create_base(
origin: OriginFor<T>,
base_type: RmrkString,
symbol: RmrkString,
parts: BoundedVec<RmrkPartType, RmrkPartsLimit>,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+ let sender = ensure_signed(origin)?;
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
- let data = CreateCollectionData {
- limits: None,
- token_prefix: symbol.into_inner()
- .try_into()
- .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,
- ..Default::default()
- };
+ let data = CreateCollectionData {
+ limits: None,
+ token_prefix: symbol
+ .into_inner()
+ .try_into()
+ .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,
+ ..Default::default()
+ };
- let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
+ let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
- if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
- return Err(<Error<T>>::NoAvailableBaseId.into());
- }
+ if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
+ return Err(<Error<T>>::NoAvailableBaseId.into());
+ }
- let collection_id = collection_id_res?;
+ let collection_id = collection_id_res?;
- <PalletCommon<T>>::set_scoped_collection_properties(
- collection_id,
- PropertyScope::Rmrk,
- [
- <PalletCore<T>>::rmrk_property(CollectionType, &misc::CollectionType::Base)?,
- <PalletCore<T>>::rmrk_property(BaseType, &base_type)?,
- ].into_iter()
- )?;
+ <PalletCommon<T>>::set_scoped_collection_properties(
+ collection_id,
+ PropertyScope::Rmrk,
+ [
+ <PalletCore<T>>::rmrk_property(CollectionType, &misc::CollectionType::Base)?,
+ <PalletCore<T>>::rmrk_property(BaseType, &base_type)?,
+ ]
+ .into_iter(),
+ )?;
- let collection = <PalletCore<T>>::get_nft_collection(collection_id)?;
+ let collection = <PalletCore<T>>::get_nft_collection(collection_id)?;
- for part in parts {
- let part_id = part.id();
- let part_token_id = Self::create_part(
- &cross_sender,
- &collection,
- part
- )?;
+ for part in parts {
+ let part_id = part.id();
+ let part_token_id = Self::create_part(&cross_sender, &collection, part)?;
- <InernalPartId<T>>::insert(collection_id, part_id, part_token_id);
+ <InernalPartId<T>>::insert(collection_id, part_id, part_token_id);
- <PalletNft<T>>::set_scoped_token_property(
- collection_id,
- part_token_id,
- PropertyScope::Rmrk,
- <PalletCore<T>>::rmrk_property(ExternalPartId, &part_id)?
- )?;
- }
+ <PalletNft<T>>::set_scoped_token_property(
+ collection_id,
+ part_token_id,
+ PropertyScope::Rmrk,
+ <PalletCore<T>>::rmrk_property(ExternalPartId, &part_id)?,
+ )?;
+ }
- Self::deposit_event(Event::BaseCreated { issuer: sender, base_id: collection_id.0 });
+ Self::deposit_event(Event::BaseCreated {
+ issuer: sender,
+ base_id: collection_id.0,
+ });
- Ok(())
- }
+ Ok(())
+ }
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
pub fn theme_add(
origin: OriginFor<T>,
base_id: RmrkBaseId,
theme: RmrkTheme,
) -> DispatchResult {
- let sender = ensure_signed(origin)?;
+ let sender = ensure_signed(origin)?;
- let sender = T::CrossAccountId::from_sub(sender);
- let owner = &sender;
+ let sender = T::CrossAccountId::from_sub(sender);
+ let owner = &sender;
- let collection_id: CollectionId = base_id.into();
+ let collection_id: CollectionId = base_id.into();
- let collection = <PalletCore<T>>::get_typed_nft_collection(
- collection_id,
- misc::CollectionType::Base
- ).map_err(|_| <Error<T>>::BaseDoesntExist)?;
+ let collection = <PalletCore<T>>::get_typed_nft_collection(
+ collection_id,
+ misc::CollectionType::Base,
+ )
+ .map_err(|_| <Error<T>>::BaseDoesntExist)?;
- if theme.name.as_slice() == b"default" {
- <BaseHasDefaultTheme<T>>::insert(collection_id, true);
- } else if !Self::base_has_default_theme(collection_id) {
- return Err(<Error<T>>::NeedsDefaultThemeFirst.into());
- }
+ if theme.name.as_slice() == b"default" {
+ <BaseHasDefaultTheme<T>>::insert(collection_id, true);
+ } else if !Self::base_has_default_theme(collection_id) {
+ return Err(<Error<T>>::NeedsDefaultThemeFirst.into());
+ }
- let token_id = <PalletCore<T>>::create_nft(
- &sender,
- owner,
- &collection,
- NftType::Theme,
- [
- <PalletCore<T>>::rmrk_property(ThemeName, &theme.name)?,
- <PalletCore<T>>::rmrk_property(ThemeInherit, &theme.inherit)?
- ].into_iter()
- ).map_err(|_| <Error<T>>::PermissionError)?;
+ let token_id = <PalletCore<T>>::create_nft(
+ &sender,
+ owner,
+ &collection,
+ NftType::Theme,
+ [
+ <PalletCore<T>>::rmrk_property(ThemeName, &theme.name)?,
+ <PalletCore<T>>::rmrk_property(ThemeInherit, &theme.inherit)?,
+ ]
+ .into_iter(),
+ )
+ .map_err(|_| <Error<T>>::PermissionError)?;
- for property in theme.properties {
- <PalletNft<T>>::set_scoped_token_property(
- collection_id,
- token_id,
- PropertyScope::Rmrk,
- <PalletCore<T>>::rmrk_property(
- UserProperty(property.key.as_slice()),
- &property.value
- )?
- )?;
- }
+ for property in theme.properties {
+ <PalletNft<T>>::set_scoped_token_property(
+ collection_id,
+ token_id,
+ PropertyScope::Rmrk,
+ <PalletCore<T>>::rmrk_property(
+ UserProperty(property.key.as_slice()),
+ &property.value,
+ )?,
+ )?;
+ }
- Ok(())
- }
- }
+ Ok(())
+ }
+ }
}
impl<T: Config> Pallet<T> {
- fn create_part(
- sender: &T::CrossAccountId,
- collection: &NonfungibleHandle<T>,
- part: RmrkPartType
- ) -> Result<TokenId, DispatchError> {
- let owner = sender;
+ fn create_part(
+ sender: &T::CrossAccountId,
+ collection: &NonfungibleHandle<T>,
+ part: RmrkPartType,
+ ) -> Result<TokenId, DispatchError> {
+ let owner = sender;
- let src = part.src();
- let z_index = part.z_index();
+ let src = part.src();
+ let z_index = part.z_index();
- let nft_type = match part {
- RmrkPartType::FixedPart(_) => NftType::FixedPart,
- RmrkPartType::SlotPart(_) => NftType::SlotPart,
- };
+ let nft_type = match part {
+ RmrkPartType::FixedPart(_) => NftType::FixedPart,
+ RmrkPartType::SlotPart(_) => NftType::SlotPart,
+ };
- let token_id = <PalletCore<T>>::create_nft(
- sender,
- owner,
- collection,
- nft_type,
- [
- <PalletCore<T>>::rmrk_property(Src, &src)?,
- <PalletCore<T>>::rmrk_property(ZIndex, &z_index)?
- ].into_iter()
- ).map_err(|err| match err {
- DispatchError::Arithmetic(_) => <Error<T>>::NoAvailablePartId.into(),
- err => err
- })?;
+ let token_id = <PalletCore<T>>::create_nft(
+ sender,
+ owner,
+ collection,
+ nft_type,
+ [
+ <PalletCore<T>>::rmrk_property(Src, &src)?,
+ <PalletCore<T>>::rmrk_property(ZIndex, &z_index)?,
+ ]
+ .into_iter(),
+ )
+ .map_err(|err| match err {
+ DispatchError::Arithmetic(_) => <Error<T>>::NoAvailablePartId.into(),
+ err => err,
+ })?;
- if let RmrkPartType::SlotPart(part) = part {
- <PalletNft<T>>::set_scoped_token_property(
- collection.id,
- token_id,
- PropertyScope::Rmrk,
- <PalletCore<T>>::rmrk_property(EquippableList, &part.equippable)?
- )?;
- }
+ if let RmrkPartType::SlotPart(part) = part {
+ <PalletNft<T>>::set_scoped_token_property(
+ collection.id,
+ token_id,
+ PropertyScope::Rmrk,
+ <PalletCore<T>>::rmrk_property(EquippableList, &part.equippable)?,
+ )?;
+ }
- Ok(token_id)
- }
+ Ok(token_id)
+ }
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -313,17 +313,9 @@
fail!(<Error<T>>::RefungibleDisallowsNesting)
}
- fn nest(
- &self,
- _under: TokenId,
- _to_nest: (CollectionId, TokenId)
- ) {}
+ fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}
- fn unnest(
- &self,
- _under: TokenId,
- _to_nest: (CollectionId, TokenId)
- ) {}
+ fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
<Owned<T>>::iter_prefix((self.id, account))
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -22,9 +22,7 @@
CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,
};
use pallet_evm::account::CrossAccountId;
-use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
-};
+use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};
use pallet_structure::Pallet as PalletStructure;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
@@ -230,7 +228,9 @@
}
fn collection_has_tokens(collection_id: CollectionId) -> bool {
- <TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+ <TokenData<T>>::iter_prefix((collection_id,))
+ .next()
+ .is_some()
}
pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
@@ -388,18 +388,14 @@
to,
collection.id,
token,
- nesting_budget
+ nesting_budget,
)?;
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
<Balance<T>>::remove((collection.id, token, from));
- <PalletStructure<T>>::unnest_if_nested(
- from,
- collection.id,
- token
- );
+ <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
} else {
<Balance<T>>::insert((collection.id, token, from), balance_from);
}
@@ -497,7 +493,6 @@
for (i, token) in data.iter().enumerate() {
let token_id = TokenId(first_token_id + i as u32 + 1);
for (to, _) in token.users.iter() {
-
<PalletStructure<T>>::check_nesting(
sender.clone(),
to,
@@ -531,7 +526,11 @@
}
<Balance<T>>::insert((collection.id, token_id, &user), amount);
<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
- <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId(token_id));
+ <PalletStructure<T>>::nest_if_sent_to_token_unchecked(
+ &user,
+ collection.id,
+ TokenId(token_id),
+ );
// TODO: ERC20 transfer event
<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -189,17 +189,11 @@
under: &T::CrossAccountId,
collection_id: CollectionId,
token_id: TokenId,
- nesting_budget: &dyn Budget
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::try_exec_if_owner_is_valid_nft(
- under,
- |d, parent_id| d.check_nesting(
- from,
- (collection_id, token_id),
- parent_id,
- nesting_budget
- )
- )
+ Self::try_exec_if_owner_is_valid_nft(under, |d, parent_id| {
+ d.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)
+ })
}
pub fn nest_if_sent_to_token(
@@ -207,69 +201,51 @@
under: &T::CrossAccountId,
collection_id: CollectionId,
token_id: TokenId,
- nesting_budget: &dyn Budget
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::try_exec_if_owner_is_valid_nft(
- under,
- |d, parent_id| {
- d.check_nesting(
- from,
- (collection_id, token_id),
- parent_id,
- nesting_budget
- )?;
+ Self::try_exec_if_owner_is_valid_nft(under, |d, parent_id| {
+ d.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;
- d.nest(parent_id, (collection_id, token_id));
+ d.nest(parent_id, (collection_id, token_id));
- Ok(())
- }
- )
+ Ok(())
+ })
}
pub fn nest_if_sent_to_token_unchecked(
owner: &T::CrossAccountId,
collection_id: CollectionId,
- token_id: TokenId
+ token_id: TokenId,
) {
- Self::exec_if_owner_is_valid_nft(
- owner,
- |d, parent_id| d.nest(
- parent_id,
- (collection_id, token_id)
- )
- );
+ Self::exec_if_owner_is_valid_nft(owner, |d, parent_id| {
+ d.nest(parent_id, (collection_id, token_id))
+ });
}
pub fn unnest_if_nested(
owner: &T::CrossAccountId,
collection_id: CollectionId,
- token_id: TokenId
+ token_id: TokenId,
) {
- Self::exec_if_owner_is_valid_nft(
- owner,
- |d, parent_id| d.unnest(
- parent_id,
- (collection_id, token_id)
- )
- );
+ Self::exec_if_owner_is_valid_nft(owner, |d, parent_id| {
+ d.unnest(parent_id, (collection_id, token_id))
+ });
}
fn exec_if_owner_is_valid_nft(
account: &T::CrossAccountId,
- action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId)
+ action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),
) {
- Self::try_exec_if_owner_is_valid_nft(
- account,
- |d, id| {
- action(d, id);
- Ok(())
- }
- ).unwrap();
+ Self::try_exec_if_owner_is_valid_nft(account, |d, id| {
+ action(d, id);
+ Ok(())
+ })
+ .unwrap();
}
fn try_exec_if_owner_is_valid_nft(
account: &T::CrossAccountId,
- action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult
+ action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,
) -> DispatchResult {
let account = T::CrossTokenAddressMapping::address_to_token(account);
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -37,11 +37,10 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,
- CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId, SponsorshipState,
- CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
- PropertyKeyPermission,
+ MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ AccessMode, CreateItemData, CollectionLimits, CollectionPermissions, CollectionId,
+ CollectionMode, TokenId, SponsorshipState, CreateCollectionData, CreateItemExData, budget,
+ Property, PropertyKey, PropertyKeyPermission,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -49,7 +49,8 @@
},
NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,
FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,
- BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,
+ BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource,
+ SlotResource as RmrkSlotResource,
};
mod bounded;
@@ -361,8 +362,7 @@
pub type CollectionPropertiesPermissionsVec =
BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
-pub type CollectionPropertiesVec =
- BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
/// All fields are wrapped in `Option`s, where None means chain default
// When adding/removing fields from this struct - don't forget to also update clamp_limits
@@ -790,8 +790,8 @@
>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
- self.0.into_iter()
- }
+ self.0.into_iter()
+ }
}
impl<Value> TrySetProperty for PropertiesMap<Value> {
@@ -853,8 +853,8 @@
type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
- self.map.into_iter()
- }
+ self.map.into_iter()
+ }
}
impl TrySetProperty for Properties {
@@ -932,11 +932,7 @@
pub type RmrkCollectionInfo<AccountId> =
CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;
pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;
-pub type RmrkResourceInfo = ResourceInfo<
- RmrkBoundedResource,
- RmrkString,
- RmrkBoundedParts,
->;
+pub type RmrkResourceInfo = ResourceInfo<RmrkBoundedResource, RmrkString, RmrkBoundedParts>;
pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;
pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;
pub type RmrkPartType =
primitives/data-structs/src/rmrk.rsdiffbeforeafterboth--- a/primitives/data-structs/src/rmrk.rs
+++ b/primitives/data-structs/src/rmrk.rs
@@ -20,37 +20,37 @@
#[cfg(feature = "std")]
mod serialize {
- use core::convert::AsRef;
- use serde::ser::{self, Serialize};
+ use core::convert::AsRef;
+ use serde::ser::{self, Serialize};
- pub mod vec {
- use super::*;
+ pub mod vec {
+ use super::*;
- pub fn serialize<D, V, C>(value: &C, serializer: D) -> Result<D::Ok, D::Error>
- where
- D: ser::Serializer,
- V: Serialize,
- C: AsRef<[V]>,
- {
- value.as_ref().serialize(serializer)
- }
- }
+ pub fn serialize<D, V, C>(value: &C, serializer: D) -> Result<D::Ok, D::Error>
+ where
+ D: ser::Serializer,
+ V: Serialize,
+ C: AsRef<[V]>,
+ {
+ value.as_ref().serialize(serializer)
+ }
+ }
- pub mod opt_vec {
- use super::*;
+ pub mod opt_vec {
+ use super::*;
- pub fn serialize<D, V, C>(value: &Option<C>, serializer: D) -> Result<D::Ok, D::Error>
- where
- D: ser::Serializer,
- V: Serialize,
- C: AsRef<[V]>,
- {
- match value {
- Some(value) => super::vec::serialize(value, serializer),
- None => serializer.serialize_none()
- }
- }
- }
+ pub fn serialize<D, V, C>(value: &Option<C>, serializer: D) -> Result<D::Ok, D::Error>
+ where
+ D: ser::Serializer,
+ V: Serialize,
+ C: AsRef<[V]>,
+ {
+ match value {
+ Some(value) => super::vec::serialize(value, serializer),
+ None => serializer.serialize_none(),
+ }
+ }
+ }
}
/// Collection info.
@@ -58,13 +58,11 @@
#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
AccountId: Serialize,
BoundedString: AsRef<[u8]>,
BoundedSymbol: AsRef<[u8]>
- "#
- )
+ "#)
)]
pub struct CollectionInfo<BoundedString, BoundedSymbol, AccountId> {
/// Current bidder and bid price.
@@ -91,9 +89,9 @@
#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
pub struct RoyaltyInfo<AccountId, RoyaltyAmount> {
/// Recipient (AccountId) of the royalty
- pub recipient: AccountId,
+ pub recipient: AccountId,
/// Amount (Permill) of the royalty
- pub amount: RoyaltyAmount,
+ pub amount: RoyaltyAmount,
}
/// Nft info.
@@ -101,13 +99,11 @@
#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
AccountId: Serialize,
RoyaltyAmount: Serialize,
BoundedString: AsRef<[u8]>
- "#
- )
+ "#)
)]
pub struct NftInfo<AccountId, RoyaltyAmount, BoundedString> {
/// The owner of the NFT, can be either an Account or a tuple (CollectionId, NftId)
@@ -129,22 +125,19 @@
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct NftChild {
pub collection_id: CollectionId,
- pub nft_id: NftId
+ pub nft_id: NftId,
}
#[cfg_attr(feature = "std", derive(Serialize))]
#[derive(Encode, Decode, PartialEq, TypeInfo)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedKey: AsRef<[u8]>,
BoundedValue: AsRef<[u8]>
- "#
- )
+ "#)
)]
-pub struct PropertyInfo<BoundedKey, BoundedValue>
-{
+pub struct PropertyInfo<BoundedKey, BoundedValue> {
/// Key of the property
#[cfg_attr(feature = "std", serde(with = "serialize::vec"))]
pub key: BoundedKey,
@@ -156,10 +149,7 @@
#[derive(Encode, Decode, Default, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize))]
-#[cfg_attr(
- feature = "std",
- serde(bound = "BoundedString: AsRef<[u8]>")
-)]
+#[cfg_attr(feature = "std", serde(bound = "BoundedString: AsRef<[u8]>"))]
pub struct BasicResource<BoundedString> {
/// If the resource is Media, the base property is absent. Media src should be a URI like an
/// IPFS hash.
@@ -188,12 +178,10 @@
#[cfg_attr(feature = "std", derive(Serialize))]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedString: AsRef<[u8]>,
BoundedParts: AsRef<[PartId]>
- "#
- )
+ "#)
)]
pub struct ComposableResource<BoundedString, BoundedParts> {
/// If a resource is composed, it will have an array of parts that compose it
@@ -235,10 +223,7 @@
#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize))]
-#[cfg_attr(
- feature = "std",
- serde(bound = "BoundedString: AsRef<[u8]>")
-)]
+#[cfg_attr(feature = "std", serde(bound = "BoundedString: AsRef<[u8]>"))]
pub struct SlotResource<BoundedString> {
/// A Base is uniquely identified by the combination of the word `base`, its minting block
/// number, and user provided symbol during Base creation, glued by dashes `-`, e.g.
@@ -279,14 +264,12 @@
#[cfg_attr(feature = "std", derive(Serialize))]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedString: AsRef<[u8]>,
BoundedParts: AsRef<[PartId]>
- "#
- )
+ "#)
)]
-#[derivative(Default(bound=""))]
+#[derivative(Default(bound = ""))]
pub enum ResourceTypes<BoundedString: Default, BoundedParts> {
#[derivative(Default)]
Basic(BasicResource<BoundedString>),
@@ -294,18 +277,15 @@
Slot(SlotResource<BoundedString>),
}
-
#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize))]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedResource: AsRef<[u8]>,
BoundedString: AsRef<[u8]>,
BoundedParts: AsRef<[PartId]>
- "#
- )
+ "#)
)]
pub struct ResourceInfo<BoundedResource, BoundedString: Default, BoundedParts> {
/// id is a 5-character string of reasonable uniqueness.
@@ -328,12 +308,10 @@
#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
AccountId: Serialize,
BoundedString: AsRef<[u8]>
- "#
- )
+ "#)
)]
pub struct BaseInfo<AccountId, BoundedString> {
/// Original creator of the Base
@@ -350,10 +328,7 @@
#[cfg_attr(feature = "std", derive(Serialize))]
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)]
-#[cfg_attr(
- feature = "std",
- serde(bound = "BoundedString: AsRef<[u8]>")
-)]
+#[cfg_attr(feature = "std", serde(bound = "BoundedString: AsRef<[u8]>"))]
pub struct FixedPart<BoundedString> {
pub id: PartId,
pub z: ZIndex,
@@ -368,29 +343,24 @@
feature = "std",
serde(bound = "BoundedCollectionList: AsRef<[CollectionId]>")
)]
-#[derivative(Default(bound=""))]
+#[derivative(Default(bound = ""))]
pub enum EquippableList<BoundedCollectionList> {
All,
#[derivative(Default)]
Empty,
- Custom(
- #[cfg_attr(feature = "std", serde(with = "serialize::vec"))]
- BoundedCollectionList
- ),
+ Custom(#[cfg_attr(feature = "std", serde(with = "serialize::vec"))] BoundedCollectionList),
}
#[cfg_attr(feature = "std", derive(Serialize))]
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedString: AsRef<[u8]>,
BoundedCollectionList: AsRef<[CollectionId]>
- "#
- )
+ "#)
)]
pub struct SlotPart<BoundedString, BoundedCollectionList> {
pub id: PartId,
@@ -406,12 +376,10 @@
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedString: AsRef<[u8]>,
BoundedCollectionList: AsRef<[CollectionId]>
- "#
- )
+ "#)
)]
pub enum PartType<BoundedString, BoundedCollectionList> {
FixedPart(FixedPart<BoundedString>),
@@ -422,21 +390,21 @@
pub fn id(&self) -> PartId {
match self {
Self::FixedPart(part) => part.id,
- Self::SlotPart(part) => part.id
+ Self::SlotPart(part) => part.id,
}
}
pub fn src(&self) -> &BoundedString {
match self {
Self::FixedPart(part) => &part.src,
- Self::SlotPart(part) => &part.src
+ Self::SlotPart(part) => &part.src,
}
}
pub fn z_index(&self) -> ZIndex {
match self {
Self::FixedPart(part) => part.z,
- Self::SlotPart(part) => part.z
+ Self::SlotPart(part) => part.z,
}
}
}
@@ -445,12 +413,10 @@
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq)]
#[cfg_attr(
feature = "std",
- serde(
- bound = r#"
+ serde(bound = r#"
BoundedString: AsRef<[u8]>,
PropertyList: AsRef<[ThemeProperty<BoundedString>]>,
- "#
- )
+ "#)
)]
pub struct Theme<BoundedString, PropertyList> {
/// Name of the theme
@@ -466,10 +432,7 @@
#[cfg_attr(feature = "std", derive(Eq, Serialize))]
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq)]
-#[cfg_attr(
- feature = "std",
- serde(bound = "BoundedString: AsRef<[u8]>")
-)]
+#[cfg_attr(feature = "std", serde(bound = "BoundedString: AsRef<[u8]>"))]
pub struct ThemeProperty<BoundedString> {
/// Key of the property
#[cfg_attr(feature = "std", serde(with = "serialize::vec"))]
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -19,9 +19,9 @@
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, TokenId,
- MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionMode,
- AccessMode, CollectionPermissions, PropertyKeyPermission, PropertyPermission,
- Property, CollectionPropertiesVec, CollectionPropertiesPermissionsVec,
+ MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionMode, AccessMode, CollectionPermissions,
+ PropertyKeyPermission, PropertyPermission, Property, CollectionPropertiesVec,
+ CollectionPropertiesPermissionsVec,
};
use frame_support::{assert_noop, assert_ok, assert_err};
use sp_std::convert::TryInto;
@@ -47,12 +47,12 @@
fn default_nft_data() -> CreateNftData {
CreateNftData {
- properties: vec![
- Property {
- key: b"test-prop".to_vec().try_into().unwrap(),
- value: b"test-nft-prop".to_vec().try_into().unwrap(),
- },
- ].try_into().unwrap(),
+ properties: vec![Property {
+ key: b"test-prop".to_vec().try_into().unwrap(),
+ value: b"test-nft-prop".to_vec().try_into().unwrap(),
+ }]
+ .try_into()
+ .unwrap(),
}
}
@@ -77,22 +77,23 @@
let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
- let token_property_permissions: CollectionPropertiesPermissionsVec = vec![
- PropertyKeyPermission {
+ let token_property_permissions: CollectionPropertiesPermissionsVec =
+ vec![PropertyKeyPermission {
key: b"test-prop".to_vec().try_into().unwrap(),
permission: PropertyPermission {
mutable: true,
collection_admin: false,
token_owner: true,
},
- },
- ].try_into().unwrap();
- let properties: CollectionPropertiesVec = vec![
- Property {
- key: b"test-collection-prop".to_vec().try_into().unwrap(),
- value: b"test-collection-value".to_vec().try_into().unwrap(),
- }
- ].try_into().unwrap();
+ }]
+ .try_into()
+ .unwrap();
+ let properties: CollectionPropertiesVec = vec![Property {
+ key: b"test-collection-prop".to_vec().try_into().unwrap(),
+ value: b"test-collection-value".to_vec().try_into().unwrap(),
+ }]
+ .try_into()
+ .unwrap();
let data: CreateCollectionData<u64> = CreateCollectionData {
name: col_name1.try_into().unwrap(),
@@ -150,30 +151,21 @@
fn get_collection_property_permissions(collection_id: CollectionId) -> Vec<PropertyKeyPermission> {
<pallet_common::Pallet<Test>>::property_permissions(collection_id)
.into_iter()
- .map(|(key, permission)| PropertyKeyPermission {
- key,
- permission,
- })
+ .map(|(key, permission)| PropertyKeyPermission { key, permission })
.collect()
}
fn get_collection_properties(collection_id: CollectionId) -> Vec<Property> {
<pallet_common::Pallet<Test>>::collection_properties(collection_id)
.into_iter()
- .map(|(key, value)| Property {
- key,
- value,
- })
+ .map(|(key, value)| Property { key, value })
.collect()
}
fn get_token_properties(collection_id: CollectionId, token_id: TokenId) -> Vec<Property> {
<pallet_nonfungible::Pallet<Test>>::token_properties((collection_id, token_id))
.into_iter()
- .map(|(key, value)| Property {
- key,
- value,
- })
+ .map(|(key, value)| Property { key, value })
.collect()
}