difftreelog
refactor rmrk proxy, add add_theme rmrk proxy
in: master
8 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -30,7 +30,7 @@
// RMRK
use rmrk_rpc::RmrkApi as RmrkRuntimeApi;
use up_data_structs::{
- RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkPropertyKey,
+ RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName,
RmrkResourceId,
};
@@ -248,7 +248,7 @@
fn collection_properties(
&self,
collection_id: RmrkCollectionId,
- filter_keys: Option<Vec<RmrkPropertyKey>>, //String
+ filter_keys: Option<Vec<String>>,
at: Option<BlockHash>,
) -> Result<Vec<PropertyInfo>>;
@@ -258,7 +258,7 @@
&self,
collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
- filter_keys: Option<Vec<RmrkPropertyKey>>,
+ filter_keys: Option<Vec<String>>,
at: Option<BlockHash>,
) -> Result<Vec<PropertyInfo>>;
@@ -299,8 +299,8 @@
fn theme(
&self,
base_id: RmrkBaseId,
- theme_name: RmrkThemeName, // String
- filter_keys: Option<Vec<RmrkPropertyKey>>,
+ theme_name: String,
+ filter_keys: Option<Vec<String>>,
at: Option<BlockHash>,
) -> Result<Option<Theme>>;
}
@@ -523,11 +523,22 @@
pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);
pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);
pass_method!(
- collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,
+ collection_properties(
+ collection_id: RmrkCollectionId,
+
+ #[map(|keys| string_keys_to_bytes_keys(keys))]
+ filter_keys: Option<Vec<String>>
+ ) -> Vec<PropertyInfo>,
rmrk_api
);
pass_method!(
- nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,
+ nft_properties(
+ collection_id: RmrkCollectionId,
+ nft_id: RmrkNftId,
+
+ #[map(|keys| string_keys_to_bytes_keys(keys))]
+ filter_keys: Option<Vec<String>>
+ ) -> Vec<PropertyInfo>,
rmrk_api
);
pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);
@@ -535,7 +546,16 @@
pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);
pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);
pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);
- pass_method!(theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Option<Theme>, rmrk_api);
+ pass_method!(
+ theme(
+ base_id: RmrkBaseId,
+
+ #[map(|n| n.into_bytes())]
+ theme_name: String,
+
+ #[map(|keys| string_keys_to_bytes_keys(keys))]
+ filter_keys: Option<Vec<String>>
+ ) -> Option<Theme>, rmrk_api);
}
fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -795,11 +795,11 @@
}
pub fn set_scoped_collection_property(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
scope: PropertyScope,
property: Property,
) -> DispatchResult {
- CollectionProperties::<T>::try_mutate(collection.id, |properties| {
+ CollectionProperties::<T>::try_mutate(collection_id, |properties| {
properties.try_scoped_set(scope, property.key, property.value)
})
.map_err(<Error<T>>::from)?;
@@ -807,13 +807,12 @@
Ok(())
}
- #[transactional]
pub fn set_scoped_collection_properties(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
scope: PropertyScope,
properties: impl Iterator<Item = Property>,
) -> DispatchResult {
- CollectionProperties::<T>::try_mutate(collection.id, |stored_properties| {
+ CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {
stored_properties.try_scoped_set_from_iter(scope, properties)
})
.map_err(<Error<T>>::from)?;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55 pub const_data: BoundedVec<u8, CustomDataLimit>,5657 #[version(..2)]58 pub variable_data: BoundedVec<u8, CustomDataLimit>,5960 pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65 use super::*;66 use frame_support::{67 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68 };69 use frame_system::pallet_prelude::*;70 use up_data_structs::{CollectionId, TokenId};71 use super::weights::WeightInfo;7273 #[pallet::error]74 pub enum Error<T> {75 /// Not Nonfungible item data used to mint in Nonfungible collection.76 NotNonfungibleDataUsedToMintFungibleCollectionToken,77 /// Used amount > 1 with NFT78 NonfungibleItemsHaveNoAmount,79 }8081 #[pallet::config]82 pub trait Config:83 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84 {85 type WeightInfo: WeightInfo;86 }8788 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990 #[pallet::pallet]91 #[pallet::storage_version(STORAGE_VERSION)]92 #[pallet::generate_store(pub(super) trait Store)]93 pub struct Pallet<T>(_);9495 #[pallet::storage]96 pub type TokensMinted<T: Config> =97 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98 #[pallet::storage]99 pub type TokensBurnt<T: Config> =100 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102 #[pallet::storage]103 pub type TokenData<T: Config> = StorageNMap<104 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105 Value = ItemData<T::CrossAccountId>,106 QueryKind = OptionQuery,107 >;108109 #[pallet::storage]110 #[pallet::getter(fn token_properties)]111 pub type TokenProperties<T: Config> = StorageNMap<112 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113 Value = Properties,114 QueryKind = ValueQuery,115 OnEmpty = up_data_structs::TokenProperties,116 >;117118 /// Used to enumerate tokens owned by account119 #[pallet::storage]120 pub type Owned<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 Key<Twox64Concat, TokenId>,125 ),126 Value = bool,127 QueryKind = ValueQuery,128 >;129130 #[pallet::storage]131 pub type AccountBalance<T: Config> = StorageNMap<132 Key = (133 Key<Twox64Concat, CollectionId>,134 Key<Blake2_128Concat, T::CrossAccountId>,135 ),136 Value = u32,137 QueryKind = ValueQuery,138 >;139140 #[pallet::storage]141 pub type Allowance<T: Config> = StorageNMap<142 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143 Value = T::CrossAccountId,144 QueryKind = OptionQuery,145 >;146147 #[pallet::hooks]148 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149 fn on_runtime_upgrade() -> Weight {150 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151 <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {152 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))153 })154 }155156 0157 }158 }159}160161pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);162impl<T: Config> NonfungibleHandle<T> {163 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {164 Self(inner)165 }166 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {167 self.0168 }169 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {170 &mut self.0171 }172}173impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {174 fn recorder(&self) -> &SubstrateRecorder<T> {175 self.0.recorder()176 }177 fn into_recorder(self) -> SubstrateRecorder<T> {178 self.0.into_recorder()179 }180}181impl<T: Config> Deref for NonfungibleHandle<T> {182 type Target = pallet_common::CollectionHandle<T>;183184 fn deref(&self) -> &Self::Target {185 &self.0186 }187}188189impl<T: Config> Pallet<T> {190 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {191 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)192 }193 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {194 <TokenData<T>>::contains_key((collection.id, token))195 }196197 pub fn set_scoped_token_property(198 collection: &CollectionHandle<T>,199 token_id: TokenId,200 scope: PropertyScope,201 property: Property,202 ) -> DispatchResult {203 TokenProperties::<T>::try_mutate((collection.id, token_id), |properties| {204 properties.try_scoped_set(scope, property.key, property.value)205 })206 .map_err(<CommonError<T>>::from)?;207208 Ok(())209 }210211 pub fn set_scoped_token_properties(212 collection: &CollectionHandle<T>,213 token_id: TokenId,214 scope: PropertyScope,215 properties: impl Iterator<Item=Property>,216 ) -> DispatchResult {217 TokenProperties::<T>::try_mutate((collection.id, token_id), |stored_properties| {218 stored_properties.try_scoped_set_from_iter(scope, properties)219 })220 .map_err(<CommonError<T>>::from)?;221222 Ok(())223 }224225 pub fn current_token_id(collection: &CollectionHandle<T>) -> TokenId {226 TokenId(<TokensMinted<T>>::get(collection.id))227 }228}229230// unchecked calls skips any permission checks231impl<T: Config> Pallet<T> {232 pub fn init_collection(233 owner: T::AccountId,234 data: CreateCollectionData<T::AccountId>,235 ) -> Result<CollectionId, DispatchError> {236 <PalletCommon<T>>::init_collection(owner, data)237 }238 pub fn destroy_collection(239 collection: NonfungibleHandle<T>,240 sender: &T::CrossAccountId,241 ) -> DispatchResult {242 let id = collection.id;243244 // =========245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <TokenData<T>>::remove_prefix((id,), None);249 <Owned<T>>::remove_prefix((id,), None);250 <TokensMinted<T>>::remove(id);251 <TokensBurnt<T>>::remove(id);252 <Allowance<T>>::remove_prefix((id,), None);253 <AccountBalance<T>>::remove_prefix((id,), None);254 Ok(())255 }256257 pub fn burn(258 collection: &NonfungibleHandle<T>,259 sender: &T::CrossAccountId,260 token: TokenId,261 ) -> DispatchResult {262 let token_data =263 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;264 ensure!(265 &token_data.owner == sender266 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),267 <CommonError<T>>::NoPermission268 );269270 if collection.access == AccessMode::AllowList {271 collection.check_allowlist(sender)?;272 }273274 let burnt = <TokensBurnt<T>>::get(collection.id)275 .checked_add(1)276 .ok_or(ArithmeticError::Overflow)?;277278 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))279 .checked_sub(1)280 .ok_or(ArithmeticError::Overflow)?;281282 if balance == 0 {283 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));284 } else {285 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);286 }287 // =========288289 <Owned<T>>::remove((collection.id, &token_data.owner, token));290 <TokensBurnt<T>>::insert(collection.id, burnt);291 <TokenData<T>>::remove((collection.id, token));292 <TokenProperties<T>>::remove((collection.id, token));293 let old_spender = <Allowance<T>>::take((collection.id, token));294295 if let Some(old_spender) = old_spender {296 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(297 collection.id,298 token,299 sender.clone(),300 old_spender,301 0,302 ));303 }304305 <PalletEvm<T>>::deposit_log(306 ERC721Events::Transfer {307 from: *token_data.owner.as_eth(),308 to: H160::default(),309 token_id: token.into(),310 }311 .to_log(collection_id_to_address(collection.id)),312 );313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 token_data.owner,317 1,318 ));319 Ok(())320 }321322 pub fn set_token_property(323 collection: &NonfungibleHandle<T>,324 sender: &T::CrossAccountId,325 token_id: TokenId,326 property: Property,327 ) -> DispatchResult {328 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;329330 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {331 let property = property.clone();332 properties.try_set(property.key, property.value)333 })334 .map_err(<CommonError<T>>::from)?;335336 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(337 collection.id,338 token_id,339 property.key,340 ));341342 Ok(())343 }344345 #[transactional]346 pub fn set_token_properties(347 collection: &NonfungibleHandle<T>,348 sender: &T::CrossAccountId,349 token_id: TokenId,350 properties: Vec<Property>,351 ) -> DispatchResult {352 for property in properties {353 Self::set_token_property(collection, sender, token_id, property)?;354 }355356 Ok(())357 }358359 pub fn delete_token_property(360 collection: &NonfungibleHandle<T>,361 sender: &T::CrossAccountId,362 token_id: TokenId,363 property_key: PropertyKey,364 ) -> DispatchResult {365 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;366367 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {368 properties.remove(&property_key)369 })370 .map_err(<CommonError<T>>::from)?;371372 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(373 collection.id,374 token_id,375 property_key,376 ));377378 Ok(())379 }380381 fn check_token_change_permission(382 collection: &NonfungibleHandle<T>,383 sender: &T::CrossAccountId,384 token_id: TokenId,385 property_key: &PropertyKey,386 ) -> DispatchResult {387 let permission = <PalletCommon<T>>::property_permissions(collection.id)388 .get(property_key)389 .cloned()390 .unwrap_or_else(PropertyPermission::none);391392 let token_data = <TokenData<T>>::get((collection.id, token_id))393 .ok_or(<CommonError<T>>::TokenNotFound)?;394395 let check_token_owner = || -> DispatchResult {396 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);397 Ok(())398 };399400 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))401 .get(property_key)402 .is_some();403404 match permission {405 PropertyPermission { mutable: false, .. } if is_property_exists => {406 Err(<CommonError<T>>::NoPermission.into())407 }408409 PropertyPermission {410 collection_admin,411 token_owner,412 ..413 } => {414 let mut check_result = Err(<CommonError<T>>::NoPermission.into());415416 if collection_admin {417 check_result = collection.check_is_owner_or_admin(sender);418 }419420 if token_owner {421 check_result.or_else(|_| check_token_owner())422 } else {423 check_result424 }425 }426 }427 }428429 #[transactional]430 pub fn delete_token_properties(431 collection: &NonfungibleHandle<T>,432 sender: &T::CrossAccountId,433 token_id: TokenId,434 property_keys: Vec<PropertyKey>,435 ) -> DispatchResult {436 for key in property_keys {437 Self::delete_token_property(collection, sender, token_id, key)?;438 }439440 Ok(())441 }442443 pub fn set_collection_properties(444 collection: &NonfungibleHandle<T>,445 sender: &T::CrossAccountId,446 properties: Vec<Property>,447 ) -> DispatchResult {448 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)449 }450451 pub fn delete_collection_properties(452 collection: &CollectionHandle<T>,453 sender: &T::CrossAccountId,454 property_keys: Vec<PropertyKey>,455 ) -> DispatchResult {456 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)457 }458459 pub fn set_property_permissions(460 collection: &CollectionHandle<T>,461 sender: &T::CrossAccountId,462 property_permissions: Vec<PropertyKeyPermission>,463 ) -> DispatchResult {464 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)465 }466467 pub fn set_property_permission(468 collection: &CollectionHandle<T>,469 sender: &T::CrossAccountId,470 permission: PropertyKeyPermission,471 ) -> DispatchResult {472 <PalletCommon<T>>::set_property_permission(collection, sender, permission)473 }474475 pub fn transfer(476 collection: &NonfungibleHandle<T>,477 from: &T::CrossAccountId,478 to: &T::CrossAccountId,479 token: TokenId,480 nesting_budget: &dyn Budget,481 ) -> DispatchResult {482 ensure!(483 collection.limits.transfers_enabled(),484 <CommonError<T>>::TransferNotAllowed485 );486487 let token_data =488 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;489 // TODO: require sender to be token, owner, require admins to go through transfer_from490 ensure!(491 &token_data.owner == from492 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),493 <CommonError<T>>::NoPermission494 );495496 if collection.access == AccessMode::AllowList {497 collection.check_allowlist(from)?;498 collection.check_allowlist(to)?;499 }500 <PalletCommon<T>>::ensure_correct_receiver(to)?;501502 let balance_from = <AccountBalance<T>>::get((collection.id, from))503 .checked_sub(1)504 .ok_or(<CommonError<T>>::TokenValueTooLow)?;505 let balance_to = if from != to {506 let balance_to = <AccountBalance<T>>::get((collection.id, to))507 .checked_add(1)508 .ok_or(ArithmeticError::Overflow)?;509510 ensure!(511 balance_to < collection.limits.account_token_ownership_limit(),512 <CommonError<T>>::AccountTokenLimitExceeded,513 );514515 Some(balance_to)516 } else {517 None518 };519520 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {521 let handle = <CollectionHandle<T>>::try_get(target.0)?;522 let dispatch = T::CollectionDispatch::dispatch(handle);523 let dispatch = dispatch.as_dyn();524525 dispatch.check_nesting(526 from.clone(),527 (collection.id, token),528 target.1,529 nesting_budget,530 )?;531 }532533 // =========534535 <TokenData<T>>::insert(536 (collection.id, token),537 ItemData {538 owner: to.clone(),539 ..token_data540 },541 );542543 if let Some(balance_to) = balance_to {544 // from != to545 if balance_from == 0 {546 <AccountBalance<T>>::remove((collection.id, from));547 } else {548 <AccountBalance<T>>::insert((collection.id, from), balance_from);549 }550 <AccountBalance<T>>::insert((collection.id, to), balance_to);551 <Owned<T>>::remove((collection.id, from, token));552 <Owned<T>>::insert((collection.id, to, token), true);553 }554 Self::set_allowance_unchecked(collection, from, token, None, true);555556 <PalletEvm<T>>::deposit_log(557 ERC721Events::Transfer {558 from: *from.as_eth(),559 to: *to.as_eth(),560 token_id: token.into(),561 }562 .to_log(collection_id_to_address(collection.id)),563 );564 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(565 collection.id,566 token,567 from.clone(),568 to.clone(),569 1,570 ));571 Ok(())572 }573574 pub fn create_multiple_items(575 collection: &NonfungibleHandle<T>,576 sender: &T::CrossAccountId,577 data: Vec<CreateItemData<T>>,578 nesting_budget: &dyn Budget,579 ) -> DispatchResult {580 if !collection.is_owner_or_admin(sender) {581 ensure!(582 collection.mint_mode,583 <CommonError<T>>::PublicMintingNotAllowed584 );585 collection.check_allowlist(sender)?;586587 for item in data.iter() {588 collection.check_allowlist(&item.owner)?;589 }590 }591592 for data in data.iter() {593 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;594 }595596 let first_token = <TokensMinted<T>>::get(collection.id);597 let tokens_minted = first_token598 .checked_add(data.len() as u32)599 .ok_or(ArithmeticError::Overflow)?;600 ensure!(601 tokens_minted <= collection.limits.token_limit(),602 <CommonError<T>>::CollectionTokenLimitExceeded603 );604605 let mut balances = BTreeMap::new();606 for data in &data {607 let balance = balances608 .entry(&data.owner)609 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));610 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;611612 ensure!(613 *balance <= collection.limits.account_token_ownership_limit(),614 <CommonError<T>>::AccountTokenLimitExceeded,615 );616 }617618 for (i, data) in data.iter().enumerate() {619 let token = TokenId(first_token + i as u32 + 1);620 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {621 let handle = <CollectionHandle<T>>::try_get(target.0)?;622 let dispatch = T::CollectionDispatch::dispatch(handle);623 let dispatch = dispatch.as_dyn();624 dispatch.check_nesting(625 sender.clone(),626 (collection.id, token),627 target.1,628 nesting_budget,629 )?;630 }631 }632633 // =========634635 with_transaction(|| {636 for (i, data) in data.iter().enumerate() {637 let token = first_token + i as u32 + 1;638639 <TokenData<T>>::insert(640 (collection.id, token),641 ItemData {642 const_data: data.const_data.clone(),643 owner: data.owner.clone(),644 },645 );646647 if let Err(e) = Self::set_token_properties(648 collection,649 sender,650 TokenId(token),651 data.properties.clone().into_inner(),652 ) {653 return TransactionOutcome::Rollback(Err(e));654 }655 }656 TransactionOutcome::Commit(Ok(()))657 })?;658659 <TokensMinted<T>>::insert(collection.id, tokens_minted);660 for (account, balance) in balances {661 <AccountBalance<T>>::insert((collection.id, account), balance);662 }663 for (i, data) in data.into_iter().enumerate() {664 let token = first_token + i as u32 + 1;665 <Owned<T>>::insert((collection.id, &data.owner, token), true);666667 <PalletEvm<T>>::deposit_log(668 ERC721Events::Transfer {669 from: H160::default(),670 to: *data.owner.as_eth(),671 token_id: token.into(),672 }673 .to_log(collection_id_to_address(collection.id)),674 );675 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(676 collection.id,677 TokenId(token),678 data.owner.clone(),679 1,680 ));681 }682 Ok(())683 }684685 pub fn set_allowance_unchecked(686 collection: &NonfungibleHandle<T>,687 sender: &T::CrossAccountId,688 token: TokenId,689 spender: Option<&T::CrossAccountId>,690 assume_implicit_eth: bool,691 ) {692 if let Some(spender) = spender {693 let old_spender = <Allowance<T>>::get((collection.id, token));694 <Allowance<T>>::insert((collection.id, token), spender);695 // In ERC721 there is only one possible approved user of token, so we set696 // approved user to spender697 <PalletEvm<T>>::deposit_log(698 ERC721Events::Approval {699 owner: *sender.as_eth(),700 approved: *spender.as_eth(),701 token_id: token.into(),702 }703 .to_log(collection_id_to_address(collection.id)),704 );705 // In Unique chain, any token can have any amount of approved users, so we need to706 // set allowance of old owner to 0, and allowance of new owner to 1707 if old_spender.as_ref() != Some(spender) {708 if let Some(old_owner) = old_spender {709 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(710 collection.id,711 token,712 sender.clone(),713 old_owner,714 0,715 ));716 }717 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(718 collection.id,719 token,720 sender.clone(),721 spender.clone(),722 1,723 ));724 }725 } else {726 let old_spender = <Allowance<T>>::take((collection.id, token));727 if !assume_implicit_eth {728 // In ERC721 there is only one possible approved user of token, so we set729 // approved user to zero address730 <PalletEvm<T>>::deposit_log(731 ERC721Events::Approval {732 owner: *sender.as_eth(),733 approved: H160::default(),734 token_id: token.into(),735 }736 .to_log(collection_id_to_address(collection.id)),737 );738 }739 // In Unique chain, any token can have any amount of approved users, so we need to740 // set allowance of old owner to 0741 if let Some(old_spender) = old_spender {742 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(743 collection.id,744 token,745 sender.clone(),746 old_spender,747 0,748 ));749 }750 }751 }752753 pub fn set_allowance(754 collection: &NonfungibleHandle<T>,755 sender: &T::CrossAccountId,756 token: TokenId,757 spender: Option<&T::CrossAccountId>,758 ) -> DispatchResult {759 if collection.access == AccessMode::AllowList {760 collection.check_allowlist(sender)?;761 if let Some(spender) = spender {762 collection.check_allowlist(spender)?;763 }764 }765766 if let Some(spender) = spender {767 <PalletCommon<T>>::ensure_correct_receiver(spender)?;768 }769 let token_data =770 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;771 if &token_data.owner != sender {772 ensure!(773 collection.ignores_owned_amount(sender),774 <CommonError<T>>::CantApproveMoreThanOwned775 );776 }777778 // =========779780 Self::set_allowance_unchecked(collection, sender, token, spender, false);781 Ok(())782 }783784 fn check_allowed(785 collection: &NonfungibleHandle<T>,786 spender: &T::CrossAccountId,787 from: &T::CrossAccountId,788 token: TokenId,789 nesting_budget: &dyn Budget,790 ) -> DispatchResult {791 if spender.conv_eq(from) {792 return Ok(());793 }794 if collection.access == AccessMode::AllowList {795 // `from`, `to` checked in [`transfer`]796 collection.check_allowlist(spender)?;797 }798 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {799 // TODO: should collection owner be allowed to perform this transfer?800 ensure!(801 <PalletStructure<T>>::check_indirectly_owned(802 spender.clone(),803 source.0,804 source.1,805 None,806 nesting_budget807 )?,808 <CommonError<T>>::ApprovedValueTooLow,809 );810 return Ok(());811 }812 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {813 return Ok(());814 }815 ensure!(816 collection.ignores_allowance(spender),817 <CommonError<T>>::ApprovedValueTooLow818 );819 Ok(())820 }821822 pub fn transfer_from(823 collection: &NonfungibleHandle<T>,824 spender: &T::CrossAccountId,825 from: &T::CrossAccountId,826 to: &T::CrossAccountId,827 token: TokenId,828 nesting_budget: &dyn Budget,829 ) -> DispatchResult {830 Self::check_allowed(collection, spender, from, token, nesting_budget)?;831832 // =========833834 // Allowance is reset in [`transfer`]835 Self::transfer(collection, from, to, token, nesting_budget)836 }837838 pub fn burn_from(839 collection: &NonfungibleHandle<T>,840 spender: &T::CrossAccountId,841 from: &T::CrossAccountId,842 token: TokenId,843 nesting_budget: &dyn Budget,844 ) -> DispatchResult {845 Self::check_allowed(collection, spender, from, token, nesting_budget)?;846847 // =========848849 Self::burn(collection, from, token)850 }851852 pub fn check_nesting(853 handle: &NonfungibleHandle<T>,854 sender: T::CrossAccountId,855 from: (CollectionId, TokenId),856 under: TokenId,857 nesting_budget: &dyn Budget,858 ) -> DispatchResult {859 fn ensure_sender_allowed<T: Config>(860 collection: CollectionId,861 token: TokenId,862 for_nest: (CollectionId, TokenId),863 sender: T::CrossAccountId,864 budget: &dyn Budget,865 ) -> DispatchResult {866 ensure!(867 <PalletStructure<T>>::check_indirectly_owned(868 sender,869 collection,870 token,871 Some(for_nest),872 budget873 )?,874 <CommonError<T>>::OnlyOwnerAllowedToNest,875 );876 Ok(())877 }878 match handle.limits.nesting_rule() {879 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),880 NestingRule::Owner => {881 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?882 }883 NestingRule::OwnerRestricted(whitelist) => {884 ensure!(885 whitelist.contains(&from.0),886 <CommonError<T>>::SourceCollectionIsNotAllowedToNest887 );888 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?889 }890 }891 Ok(())892 }893894 /// Delegated to `create_multiple_items`895 pub fn create_item(896 collection: &NonfungibleHandle<T>,897 sender: &T::CrossAccountId,898 data: CreateItemData<T>,899 nesting_budget: &dyn Budget,900 ) -> DispatchResult {901 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)902 }903}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25 PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30 dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55 pub const_data: BoundedVec<u8, CustomDataLimit>,5657 #[version(..2)]58 pub variable_data: BoundedVec<u8, CustomDataLimit>,5960 pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65 use super::*;66 use frame_support::{67 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68 };69 use frame_system::pallet_prelude::*;70 use up_data_structs::{CollectionId, TokenId};71 use super::weights::WeightInfo;7273 #[pallet::error]74 pub enum Error<T> {75 /// Not Nonfungible item data used to mint in Nonfungible collection.76 NotNonfungibleDataUsedToMintFungibleCollectionToken,77 /// Used amount > 1 with NFT78 NonfungibleItemsHaveNoAmount,79 }8081 #[pallet::config]82 pub trait Config:83 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84 {85 type WeightInfo: WeightInfo;86 }8788 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990 #[pallet::pallet]91 #[pallet::storage_version(STORAGE_VERSION)]92 #[pallet::generate_store(pub(super) trait Store)]93 pub struct Pallet<T>(_);9495 #[pallet::storage]96 pub type TokensMinted<T: Config> =97 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98 #[pallet::storage]99 pub type TokensBurnt<T: Config> =100 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102 #[pallet::storage]103 pub type TokenData<T: Config> = StorageNMap<104 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105 Value = ItemData<T::CrossAccountId>,106 QueryKind = OptionQuery,107 >;108109 #[pallet::storage]110 #[pallet::getter(fn token_properties)]111 pub type TokenProperties<T: Config> = StorageNMap<112 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113 Value = Properties,114 QueryKind = ValueQuery,115 OnEmpty = up_data_structs::TokenProperties,116 >;117118 /// Used to enumerate tokens owned by account119 #[pallet::storage]120 pub type Owned<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 Key<Twox64Concat, TokenId>,125 ),126 Value = bool,127 QueryKind = ValueQuery,128 >;129130 #[pallet::storage]131 pub type AccountBalance<T: Config> = StorageNMap<132 Key = (133 Key<Twox64Concat, CollectionId>,134 Key<Blake2_128Concat, T::CrossAccountId>,135 ),136 Value = u32,137 QueryKind = ValueQuery,138 >;139140 #[pallet::storage]141 pub type Allowance<T: Config> = StorageNMap<142 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143 Value = T::CrossAccountId,144 QueryKind = OptionQuery,145 >;146147 #[pallet::hooks]148 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149 fn on_runtime_upgrade() -> Weight {150 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151 <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {152 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))153 })154 }155156 0157 }158 }159}160161pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);162impl<T: Config> NonfungibleHandle<T> {163 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {164 Self(inner)165 }166 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {167 self.0168 }169 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {170 &mut self.0171 }172}173impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {174 fn recorder(&self) -> &SubstrateRecorder<T> {175 self.0.recorder()176 }177 fn into_recorder(self) -> SubstrateRecorder<T> {178 self.0.into_recorder()179 }180}181impl<T: Config> Deref for NonfungibleHandle<T> {182 type Target = pallet_common::CollectionHandle<T>;183184 fn deref(&self) -> &Self::Target {185 &self.0186 }187}188189impl<T: Config> Pallet<T> {190 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {191 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)192 }193 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {194 <TokenData<T>>::contains_key((collection.id, token))195 }196197 pub fn set_scoped_token_property(198 collection_id: CollectionId,199 token_id: TokenId,200 scope: PropertyScope,201 property: Property,202 ) -> DispatchResult {203 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {204 properties.try_scoped_set(scope, property.key, property.value)205 })206 .map_err(<CommonError<T>>::from)?;207208 Ok(())209 }210211 pub fn set_scoped_token_properties(212 collection_id: CollectionId,213 token_id: TokenId,214 scope: PropertyScope,215 properties: impl Iterator<Item=Property>,216 ) -> DispatchResult {217 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {218 stored_properties.try_scoped_set_from_iter(scope, properties)219 })220 .map_err(<CommonError<T>>::from)?;221222 Ok(())223 }224225 pub fn current_token_id(collection_id: CollectionId) -> TokenId {226 TokenId(<TokensMinted<T>>::get(collection_id))227 }228}229230// unchecked calls skips any permission checks231impl<T: Config> Pallet<T> {232 pub fn init_collection(233 owner: T::AccountId,234 data: CreateCollectionData<T::AccountId>,235 ) -> Result<CollectionId, DispatchError> {236 <PalletCommon<T>>::init_collection(owner, data)237 }238 pub fn destroy_collection(239 collection: NonfungibleHandle<T>,240 sender: &T::CrossAccountId,241 ) -> DispatchResult {242 let id = collection.id;243244 // =========245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <TokenData<T>>::remove_prefix((id,), None);249 <Owned<T>>::remove_prefix((id,), None);250 <TokensMinted<T>>::remove(id);251 <TokensBurnt<T>>::remove(id);252 <Allowance<T>>::remove_prefix((id,), None);253 <AccountBalance<T>>::remove_prefix((id,), None);254 Ok(())255 }256257 pub fn burn(258 collection: &NonfungibleHandle<T>,259 sender: &T::CrossAccountId,260 token: TokenId,261 ) -> DispatchResult {262 let token_data =263 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;264 ensure!(265 &token_data.owner == sender266 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),267 <CommonError<T>>::NoPermission268 );269270 if collection.access == AccessMode::AllowList {271 collection.check_allowlist(sender)?;272 }273274 let burnt = <TokensBurnt<T>>::get(collection.id)275 .checked_add(1)276 .ok_or(ArithmeticError::Overflow)?;277278 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))279 .checked_sub(1)280 .ok_or(ArithmeticError::Overflow)?;281282 if balance == 0 {283 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));284 } else {285 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);286 }287 // =========288289 <Owned<T>>::remove((collection.id, &token_data.owner, token));290 <TokensBurnt<T>>::insert(collection.id, burnt);291 <TokenData<T>>::remove((collection.id, token));292 <TokenProperties<T>>::remove((collection.id, token));293 let old_spender = <Allowance<T>>::take((collection.id, token));294295 if let Some(old_spender) = old_spender {296 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(297 collection.id,298 token,299 sender.clone(),300 old_spender,301 0,302 ));303 }304305 <PalletEvm<T>>::deposit_log(306 ERC721Events::Transfer {307 from: *token_data.owner.as_eth(),308 to: H160::default(),309 token_id: token.into(),310 }311 .to_log(collection_id_to_address(collection.id)),312 );313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 token_data.owner,317 1,318 ));319 Ok(())320 }321322 pub fn set_token_property(323 collection: &NonfungibleHandle<T>,324 sender: &T::CrossAccountId,325 token_id: TokenId,326 property: Property,327 ) -> DispatchResult {328 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;329330 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {331 let property = property.clone();332 properties.try_set(property.key, property.value)333 })334 .map_err(<CommonError<T>>::from)?;335336 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(337 collection.id,338 token_id,339 property.key,340 ));341342 Ok(())343 }344345 #[transactional]346 pub fn set_token_properties(347 collection: &NonfungibleHandle<T>,348 sender: &T::CrossAccountId,349 token_id: TokenId,350 properties: Vec<Property>,351 ) -> DispatchResult {352 for property in properties {353 Self::set_token_property(collection, sender, token_id, property)?;354 }355356 Ok(())357 }358359 pub fn delete_token_property(360 collection: &NonfungibleHandle<T>,361 sender: &T::CrossAccountId,362 token_id: TokenId,363 property_key: PropertyKey,364 ) -> DispatchResult {365 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;366367 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {368 properties.remove(&property_key)369 })370 .map_err(<CommonError<T>>::from)?;371372 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(373 collection.id,374 token_id,375 property_key,376 ));377378 Ok(())379 }380381 fn check_token_change_permission(382 collection: &NonfungibleHandle<T>,383 sender: &T::CrossAccountId,384 token_id: TokenId,385 property_key: &PropertyKey,386 ) -> DispatchResult {387 let permission = <PalletCommon<T>>::property_permissions(collection.id)388 .get(property_key)389 .cloned()390 .unwrap_or_else(PropertyPermission::none);391392 let token_data = <TokenData<T>>::get((collection.id, token_id))393 .ok_or(<CommonError<T>>::TokenNotFound)?;394395 let check_token_owner = || -> DispatchResult {396 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);397 Ok(())398 };399400 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))401 .get(property_key)402 .is_some();403404 match permission {405 PropertyPermission { mutable: false, .. } if is_property_exists => {406 Err(<CommonError<T>>::NoPermission.into())407 }408409 PropertyPermission {410 collection_admin,411 token_owner,412 ..413 } => {414 let mut check_result = Err(<CommonError<T>>::NoPermission.into());415416 if collection_admin {417 check_result = collection.check_is_owner_or_admin(sender);418 }419420 if token_owner {421 check_result.or_else(|_| check_token_owner())422 } else {423 check_result424 }425 }426 }427 }428429 #[transactional]430 pub fn delete_token_properties(431 collection: &NonfungibleHandle<T>,432 sender: &T::CrossAccountId,433 token_id: TokenId,434 property_keys: Vec<PropertyKey>,435 ) -> DispatchResult {436 for key in property_keys {437 Self::delete_token_property(collection, sender, token_id, key)?;438 }439440 Ok(())441 }442443 pub fn set_collection_properties(444 collection: &NonfungibleHandle<T>,445 sender: &T::CrossAccountId,446 properties: Vec<Property>,447 ) -> DispatchResult {448 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)449 }450451 pub fn delete_collection_properties(452 collection: &CollectionHandle<T>,453 sender: &T::CrossAccountId,454 property_keys: Vec<PropertyKey>,455 ) -> DispatchResult {456 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)457 }458459 pub fn set_property_permissions(460 collection: &CollectionHandle<T>,461 sender: &T::CrossAccountId,462 property_permissions: Vec<PropertyKeyPermission>,463 ) -> DispatchResult {464 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)465 }466467 pub fn set_property_permission(468 collection: &CollectionHandle<T>,469 sender: &T::CrossAccountId,470 permission: PropertyKeyPermission,471 ) -> DispatchResult {472 <PalletCommon<T>>::set_property_permission(collection, sender, permission)473 }474475 pub fn transfer(476 collection: &NonfungibleHandle<T>,477 from: &T::CrossAccountId,478 to: &T::CrossAccountId,479 token: TokenId,480 nesting_budget: &dyn Budget,481 ) -> DispatchResult {482 ensure!(483 collection.limits.transfers_enabled(),484 <CommonError<T>>::TransferNotAllowed485 );486487 let token_data =488 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;489 // TODO: require sender to be token, owner, require admins to go through transfer_from490 ensure!(491 &token_data.owner == from492 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),493 <CommonError<T>>::NoPermission494 );495496 if collection.access == AccessMode::AllowList {497 collection.check_allowlist(from)?;498 collection.check_allowlist(to)?;499 }500 <PalletCommon<T>>::ensure_correct_receiver(to)?;501502 let balance_from = <AccountBalance<T>>::get((collection.id, from))503 .checked_sub(1)504 .ok_or(<CommonError<T>>::TokenValueTooLow)?;505 let balance_to = if from != to {506 let balance_to = <AccountBalance<T>>::get((collection.id, to))507 .checked_add(1)508 .ok_or(ArithmeticError::Overflow)?;509510 ensure!(511 balance_to < collection.limits.account_token_ownership_limit(),512 <CommonError<T>>::AccountTokenLimitExceeded,513 );514515 Some(balance_to)516 } else {517 None518 };519520 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {521 let handle = <CollectionHandle<T>>::try_get(target.0)?;522 let dispatch = T::CollectionDispatch::dispatch(handle);523 let dispatch = dispatch.as_dyn();524525 dispatch.check_nesting(526 from.clone(),527 (collection.id, token),528 target.1,529 nesting_budget,530 )?;531 }532533 // =========534535 <TokenData<T>>::insert(536 (collection.id, token),537 ItemData {538 owner: to.clone(),539 ..token_data540 },541 );542543 if let Some(balance_to) = balance_to {544 // from != to545 if balance_from == 0 {546 <AccountBalance<T>>::remove((collection.id, from));547 } else {548 <AccountBalance<T>>::insert((collection.id, from), balance_from);549 }550 <AccountBalance<T>>::insert((collection.id, to), balance_to);551 <Owned<T>>::remove((collection.id, from, token));552 <Owned<T>>::insert((collection.id, to, token), true);553 }554 Self::set_allowance_unchecked(collection, from, token, None, true);555556 <PalletEvm<T>>::deposit_log(557 ERC721Events::Transfer {558 from: *from.as_eth(),559 to: *to.as_eth(),560 token_id: token.into(),561 }562 .to_log(collection_id_to_address(collection.id)),563 );564 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(565 collection.id,566 token,567 from.clone(),568 to.clone(),569 1,570 ));571 Ok(())572 }573574 pub fn create_multiple_items(575 collection: &NonfungibleHandle<T>,576 sender: &T::CrossAccountId,577 data: Vec<CreateItemData<T>>,578 nesting_budget: &dyn Budget,579 ) -> DispatchResult {580 if !collection.is_owner_or_admin(sender) {581 ensure!(582 collection.mint_mode,583 <CommonError<T>>::PublicMintingNotAllowed584 );585 collection.check_allowlist(sender)?;586587 for item in data.iter() {588 collection.check_allowlist(&item.owner)?;589 }590 }591592 for data in data.iter() {593 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;594 }595596 let first_token = <TokensMinted<T>>::get(collection.id);597 let tokens_minted = first_token598 .checked_add(data.len() as u32)599 .ok_or(ArithmeticError::Overflow)?;600 ensure!(601 tokens_minted <= collection.limits.token_limit(),602 <CommonError<T>>::CollectionTokenLimitExceeded603 );604605 let mut balances = BTreeMap::new();606 for data in &data {607 let balance = balances608 .entry(&data.owner)609 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));610 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;611612 ensure!(613 *balance <= collection.limits.account_token_ownership_limit(),614 <CommonError<T>>::AccountTokenLimitExceeded,615 );616 }617618 for (i, data) in data.iter().enumerate() {619 let token = TokenId(first_token + i as u32 + 1);620 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {621 let handle = <CollectionHandle<T>>::try_get(target.0)?;622 let dispatch = T::CollectionDispatch::dispatch(handle);623 let dispatch = dispatch.as_dyn();624 dispatch.check_nesting(625 sender.clone(),626 (collection.id, token),627 target.1,628 nesting_budget,629 )?;630 }631 }632633 // =========634635 with_transaction(|| {636 for (i, data) in data.iter().enumerate() {637 let token = first_token + i as u32 + 1;638639 <TokenData<T>>::insert(640 (collection.id, token),641 ItemData {642 const_data: data.const_data.clone(),643 owner: data.owner.clone(),644 },645 );646647 if let Err(e) = Self::set_token_properties(648 collection,649 sender,650 TokenId(token),651 data.properties.clone().into_inner(),652 ) {653 return TransactionOutcome::Rollback(Err(e));654 }655 }656 TransactionOutcome::Commit(Ok(()))657 })?;658659 <TokensMinted<T>>::insert(collection.id, tokens_minted);660 for (account, balance) in balances {661 <AccountBalance<T>>::insert((collection.id, account), balance);662 }663 for (i, data) in data.into_iter().enumerate() {664 let token = first_token + i as u32 + 1;665 <Owned<T>>::insert((collection.id, &data.owner, token), true);666667 <PalletEvm<T>>::deposit_log(668 ERC721Events::Transfer {669 from: H160::default(),670 to: *data.owner.as_eth(),671 token_id: token.into(),672 }673 .to_log(collection_id_to_address(collection.id)),674 );675 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(676 collection.id,677 TokenId(token),678 data.owner.clone(),679 1,680 ));681 }682 Ok(())683 }684685 pub fn set_allowance_unchecked(686 collection: &NonfungibleHandle<T>,687 sender: &T::CrossAccountId,688 token: TokenId,689 spender: Option<&T::CrossAccountId>,690 assume_implicit_eth: bool,691 ) {692 if let Some(spender) = spender {693 let old_spender = <Allowance<T>>::get((collection.id, token));694 <Allowance<T>>::insert((collection.id, token), spender);695 // In ERC721 there is only one possible approved user of token, so we set696 // approved user to spender697 <PalletEvm<T>>::deposit_log(698 ERC721Events::Approval {699 owner: *sender.as_eth(),700 approved: *spender.as_eth(),701 token_id: token.into(),702 }703 .to_log(collection_id_to_address(collection.id)),704 );705 // In Unique chain, any token can have any amount of approved users, so we need to706 // set allowance of old owner to 0, and allowance of new owner to 1707 if old_spender.as_ref() != Some(spender) {708 if let Some(old_owner) = old_spender {709 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(710 collection.id,711 token,712 sender.clone(),713 old_owner,714 0,715 ));716 }717 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(718 collection.id,719 token,720 sender.clone(),721 spender.clone(),722 1,723 ));724 }725 } else {726 let old_spender = <Allowance<T>>::take((collection.id, token));727 if !assume_implicit_eth {728 // In ERC721 there is only one possible approved user of token, so we set729 // approved user to zero address730 <PalletEvm<T>>::deposit_log(731 ERC721Events::Approval {732 owner: *sender.as_eth(),733 approved: H160::default(),734 token_id: token.into(),735 }736 .to_log(collection_id_to_address(collection.id)),737 );738 }739 // In Unique chain, any token can have any amount of approved users, so we need to740 // set allowance of old owner to 0741 if let Some(old_spender) = old_spender {742 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(743 collection.id,744 token,745 sender.clone(),746 old_spender,747 0,748 ));749 }750 }751 }752753 pub fn set_allowance(754 collection: &NonfungibleHandle<T>,755 sender: &T::CrossAccountId,756 token: TokenId,757 spender: Option<&T::CrossAccountId>,758 ) -> DispatchResult {759 if collection.access == AccessMode::AllowList {760 collection.check_allowlist(sender)?;761 if let Some(spender) = spender {762 collection.check_allowlist(spender)?;763 }764 }765766 if let Some(spender) = spender {767 <PalletCommon<T>>::ensure_correct_receiver(spender)?;768 }769 let token_data =770 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;771 if &token_data.owner != sender {772 ensure!(773 collection.ignores_owned_amount(sender),774 <CommonError<T>>::CantApproveMoreThanOwned775 );776 }777778 // =========779780 Self::set_allowance_unchecked(collection, sender, token, spender, false);781 Ok(())782 }783784 fn check_allowed(785 collection: &NonfungibleHandle<T>,786 spender: &T::CrossAccountId,787 from: &T::CrossAccountId,788 token: TokenId,789 nesting_budget: &dyn Budget,790 ) -> DispatchResult {791 if spender.conv_eq(from) {792 return Ok(());793 }794 if collection.access == AccessMode::AllowList {795 // `from`, `to` checked in [`transfer`]796 collection.check_allowlist(spender)?;797 }798 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {799 // TODO: should collection owner be allowed to perform this transfer?800 ensure!(801 <PalletStructure<T>>::check_indirectly_owned(802 spender.clone(),803 source.0,804 source.1,805 None,806 nesting_budget807 )?,808 <CommonError<T>>::ApprovedValueTooLow,809 );810 return Ok(());811 }812 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {813 return Ok(());814 }815 ensure!(816 collection.ignores_allowance(spender),817 <CommonError<T>>::ApprovedValueTooLow818 );819 Ok(())820 }821822 pub fn transfer_from(823 collection: &NonfungibleHandle<T>,824 spender: &T::CrossAccountId,825 from: &T::CrossAccountId,826 to: &T::CrossAccountId,827 token: TokenId,828 nesting_budget: &dyn Budget,829 ) -> DispatchResult {830 Self::check_allowed(collection, spender, from, token, nesting_budget)?;831832 // =========833834 // Allowance is reset in [`transfer`]835 Self::transfer(collection, from, to, token, nesting_budget)836 }837838 pub fn burn_from(839 collection: &NonfungibleHandle<T>,840 spender: &T::CrossAccountId,841 from: &T::CrossAccountId,842 token: TokenId,843 nesting_budget: &dyn Budget,844 ) -> DispatchResult {845 Self::check_allowed(collection, spender, from, token, nesting_budget)?;846847 // =========848849 Self::burn(collection, from, token)850 }851852 pub fn check_nesting(853 handle: &NonfungibleHandle<T>,854 sender: T::CrossAccountId,855 from: (CollectionId, TokenId),856 under: TokenId,857 nesting_budget: &dyn Budget,858 ) -> DispatchResult {859 fn ensure_sender_allowed<T: Config>(860 collection: CollectionId,861 token: TokenId,862 for_nest: (CollectionId, TokenId),863 sender: T::CrossAccountId,864 budget: &dyn Budget,865 ) -> DispatchResult {866 ensure!(867 <PalletStructure<T>>::check_indirectly_owned(868 sender,869 collection,870 token,871 Some(for_nest),872 budget873 )?,874 <CommonError<T>>::OnlyOwnerAllowedToNest,875 );876 Ok(())877 }878 match handle.limits.nesting_rule() {879 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),880 NestingRule::Owner => {881 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?882 }883 NestingRule::OwnerRestricted(whitelist) => {884 ensure!(885 whitelist.contains(&from.0),886 <CommonError<T>>::SourceCollectionIsNotAllowedToNest887 );888 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?889 }890 }891 Ok(())892 }893894 /// Delegated to `create_multiple_items`895 pub fn create_item(896 collection: &NonfungibleHandle<T>,897 sender: &T::CrossAccountId,898 data: CreateItemData<T>,899 nesting_budget: &dyn Budget,900 ) -> DispatchResult {901 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)902 }903}pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -33,6 +33,8 @@
use misc::*;
pub use property::*;
+use RmrkProperty::*;
+
#[frame_support::pallet]
pub mod pallet {
use super::*;
@@ -135,15 +137,13 @@
}
let collection_id = collection_id_res?;
-
- let collection = Self::get_nft_collection(collection_id)?.into_inner();
<PalletCommon<T>>::set_scoped_collection_properties(
- &collection,
+ collection_id,
PropertyScope::Rmrk,
[
- rmrk_property!(Config=T, Metadata: metadata)?,
- rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,
+ Self::rmrk_property(Metadata, &metadata)?,
+ Self::rmrk_property(CollectionType, &misc::CollectionType::Regular)?,
].into_iter()
)?;
@@ -168,7 +168,7 @@
let unique_collection_id = collection_id.into();
- let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;
+ let collection = Self::get_typed_nft_collection(unique_collection_id, misc::CollectionType::Regular)?;
ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
@@ -193,7 +193,7 @@
Self::change_collection_owner(
collection_id.into(),
- CollectionType::Regular,
+ misc::CollectionType::Regular,
sender.clone(),
new_issuer.clone()
)?;
@@ -218,7 +218,7 @@
let collection = Self::get_typed_nft_collection(
collection_id.into(),
- CollectionType::Regular
+ misc::CollectionType::Regular
)?;
Self::check_collection_owner(&collection, &cross_sender)?;
@@ -253,20 +253,27 @@
amount
});
+ let collection = Self::get_typed_nft_collection(
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ )?;
+
let nft_id = Self::create_nft(
&sender,
&cross_owner,
- collection_id.into(),
- CollectionType::Regular,
+ &collection,
NftType::Regular,
[
- rmrk_property!(Config=T, RoyaltyInfo: royalty_info)?,
- rmrk_property!(Config=T, Metadata: metadata)?,
- rmrk_property!(Config=T, Equipped: false)?,
- rmrk_property!(Config=T, ResourceCollection: None::<CollectionId>)?,
- rmrk_property!(Config=T, ResourcePriorities: <Vec<u8>>::new())?,
+ 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,
@@ -290,7 +297,7 @@
Self::destroy_nft(
cross_sender,
collection_id.into(),
- CollectionType::Regular,
+ misc::CollectionType::Regular,
nft_id.into()
)?;
@@ -302,19 +309,37 @@
}
impl<T: Config> Pallet<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)?;
+
+ Ok(scoped_key)
+ }
+
+ 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 property = Property {
+ key,
+ value,
+ };
+
+ Ok(property)
+ }
+
pub fn create_nft(
sender: &T::CrossAccountId,
owner: &T::CrossAccountId,
- collection_id: CollectionId,
- collection_type: CollectionType,
+ collection: &NonfungibleHandle<T>,
nft_type: NftType,
properties: impl Iterator<Item=Property>
) -> Result<TokenId, DispatchError> {
- let collection = Self::get_typed_nft_collection(
- collection_id,
- collection_type
- )?;
-
let data = CreateNftExData {
const_data: nft_type.encode()
.try_into()
@@ -326,16 +351,16 @@
let budget = budget::Value::new(2);
<PalletNft<T>>::create_item(
- &collection,
+ collection,
sender,
data,
&budget,
- ).map_err(Self::map_common_err_to_proxy)?;
+ )?;
- let nft_id = <PalletNft<T>>::current_token_id(&collection);
+ let nft_id = <PalletNft<T>>::current_token_id(collection.id);
<PalletNft<T>>::set_scoped_token_properties(
- &collection,
+ collection.id,
nft_id,
PropertyScope::Rmrk,
properties
@@ -347,7 +372,7 @@
fn destroy_nft(
sender: T::CrossAccountId,
collection_id: CollectionId,
- collection_type: CollectionType,
+ collection_type: misc::CollectionType,
token_id: TokenId
) -> DispatchResult {
let collection = Self::get_typed_nft_collection(
@@ -363,7 +388,7 @@
fn change_collection_owner(
collection_id: CollectionId,
- collection_type: CollectionType,
+ collection_type: misc::CollectionType,
sender: T::AccountId,
new_owner: T::AccountId,
) -> DispatchResult {
@@ -390,10 +415,12 @@
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)?
- .into_nft_collection()?;
+ .map_err(|_| <Error<T>>::CollectionUnknown)?;
- Ok(collection)
+ match collection.mode {
+ CollectionMode::NFT => Ok(NonfungibleHandle::cast(collection)),
+ _ => Err(<Error<T>>::CollectionUnknown.into())
+ }
}
// should this even be here, might displace it to common/nonfungible -- but they did not need it, only rmrk does
@@ -407,23 +434,23 @@
pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
- .get(&rmrk_property!(Config=T, key)?)
+ .get(&Self::rmrk_property_key(key)?)
.ok_or(<Error<T>>::CollectionUnknown)?
.clone();
Ok(collection_property)
}
- pub fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {
- let value = Self::get_collection_property(collection_id, RmrkProperty::CollectionType)?;
- let collection_type: CollectionType = (&value)
- .try_into()
- .map_err(<Error<T>>::from)?;
+ 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();
- Ok(collection_type)
+ misc::CollectionType::decode(&mut value)
+ .map_err(|_| <Error<T>>::CorruptedCollectionType.into())
}
- pub fn ensure_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
+ 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);
@@ -432,7 +459,7 @@
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(&rmrk_property!(Config=T, key)?)
+ .get(&Self::rmrk_property_key(key)?)
.ok_or(<Error<T>>::NoAvailableNftId)?
.clone();
@@ -440,10 +467,12 @@
}
pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
- <TokenData<T>>::get((collection_id, token_id))
- .unwrap()
- .rmrk_nft_type()
- .ok_or_else(|| <Error<T>>::NoAvailableNftId.into())
+ let token_data = <TokenData<T>>::get((collection_id, token_id))
+ .ok_or(<Error<T>>::NoAvailableNftId)?;
+
+ let mut const_data = token_data.const_data.as_slice();
+
+ NftType::decode(&mut const_data).map_err(|_| <Error<T>>::NoAvailableNftId.into())
}
pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
@@ -466,7 +495,7 @@
let value = Self::get_nft_property(
collection_id,
token_id,
- RmrkProperty::ThemeProperty(&key)
+ ThemeProperty(&key)
).ok()?.decode_or_default();
let property = RmrkThemeProperty {
@@ -491,7 +520,7 @@
collection_id: CollectionId,
token_id: TokenId
) -> Result<impl Iterator<Item=RmrkThemeProperty>, DispatchError> {
- let key_prefix = rmrk_property!(Config=T, key: ThemeProperty(&RmrkString::default()))?;
+ let key_prefix = Self::rmrk_property_key(ThemeProperty(&RmrkString::default()))?;
let properties = <PalletNft<T>>::token_properties((collection_id, token_id))
.into_iter()
@@ -514,7 +543,7 @@
pub fn get_typed_nft_collection(
collection_id: CollectionId,
- collection_type: CollectionType
+ collection_type: misc::CollectionType
) -> Result<NonfungibleHandle<T>, DispatchError> {
Self::ensure_collection_type(collection_id, collection_type)?;
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -1,23 +1,6 @@
use super::*;
use codec::{Encode, Decode};
-use pallet_nonfungible::{NonfungibleHandle, ItemData};
-
-macro_rules! impl_rmrk_value {
- ($enum_name:path, decode_error: $error:ident) => {
- impl TryFrom<&PropertyValue> for $enum_name {
- type Error = MiscError;
-
- fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
- let mut value = value.as_slice();
- <$enum_name>::decode(&mut value)
- .map_err(|_| MiscError::$error)
- }
- }
-
- };
-}
-
#[macro_export]
macro_rules! map_common_err_to_proxy {
(match $err:ident { $($common_err:ident => $proxy_err:ident),+ }) => {
@@ -29,59 +12,8 @@
$err
}
};
-}
-
-pub enum MiscError {
- RmrkPropertyValueIsTooLong,
- CorruptedCollectionType,
-}
-
-impl<T: Config> From<MiscError> for Error<T> {
- fn from(error: MiscError) -> Self {
- match error {
- MiscError::RmrkPropertyValueIsTooLong => Self::RmrkPropertyValueIsTooLong,
- MiscError::CorruptedCollectionType => Self::CorruptedCollectionType,
- }
- }
-}
-
-pub trait IntoNftCollection<T: Config> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>>;
}
-impl<T: Config> IntoNftCollection<T> for CollectionHandle<T> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>> {
- match self.mode {
- CollectionMode::NFT => Ok(NonfungibleHandle::cast(self)),
- _ => Err(<Error<T>>::CollectionUnknown)
- }
- }
-}
-
-pub trait IntoPropertyValue {
- fn into_property_value(self) -> Result<PropertyValue, MiscError>;
-}
-
-impl<T: Encode> IntoPropertyValue for T {
- fn into_property_value(self) -> Result<PropertyValue, MiscError> {
- self.encode()
- .try_into()
- .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
- }
-}
-
-pub trait RmrkNft {
- fn rmrk_nft_type(&self) -> Option<NftType>;
-}
-
-impl<CrossAccountId> RmrkNft for ItemData<CrossAccountId> {
- fn rmrk_nft_type(&self) -> Option<NftType> {
- let mut value = self.const_data.as_slice();
-
- NftType::decode(&mut value).ok()
- }
-}
-
pub trait RmrkDecode<T: Decode + Default, S> {
fn decode_or_default(&self) -> T;
}
@@ -121,5 +53,3 @@
SlotPart,
Theme
}
-
-impl_rmrk_value!(CollectionType, decode_error: CorruptedCollectionType);
pallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/property.rs
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -71,31 +71,3 @@
}
}
}
-
-#[macro_export]
-macro_rules! rmrk_property {
- (Config=$cfg:ty, key: $key:ident $(($key_ext:expr))?) => {
- rmrk_property!(Config=$cfg, $crate::RmrkProperty::$key $(($key_ext))?)
- };
-
- (Config=$cfg:ty, $key:ident $(($key_ext:expr))?: $value:expr) => {{
- let key = rmrk_property!(@$cfg, $crate::RmrkProperty::$key $(($key_ext))?)?;
-
- let value = $value.into_property_value()
- .map_err(<$crate::Error<$cfg>>::from)?;
-
- Ok::<_, $crate::Error<$cfg>>(Property {
- key,
- value,
- })
- }};
-
- (@$cfg:ty, $key_enum:expr) => {
- $key_enum.to_key::<$cfg>()
- };
-
- (Config=$cfg:ty, $key_enum:expr) => {
- PropertyScope::Rmrk.apply(rmrk_property!(@$cfg, $key_enum)?)
- .map_err(|_| <$crate::Error<$cfg>>::RmrkPropertyKeyIsTooLong)
- };
-}
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -20,9 +20,9 @@
use frame_system::{pallet_prelude::*, ensure_signed};
use sp_runtime::DispatchError;
use up_data_structs::*;
-use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle};
-use pallet_rmrk_core::{Pallet as PalletCore, rmrk_property, misc::*};
-use pallet_nonfungible::{Pallet as PalletNft};
+use pallet_common::{Pallet as PalletCommon, Error as CommonError};
+use pallet_rmrk_core::{Pallet as PalletCore, misc::{self, *}, property::RmrkProperty::*};
+use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
use pallet_evm::account::CrossAccountId;
pub use pallet::*;
@@ -48,6 +48,16 @@
TokenId
>;
+ #[pallet::storage]
+ #[pallet::getter(fn base_has_default_theme)]
+ pub type BaseHasDefaultTheme<T: Config> = StorageMap<
+ _,
+ Twox64Concat,
+ CollectionId,
+ bool,
+ ValueQuery
+ >;
+
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -63,7 +73,11 @@
#[pallet::error]
pub enum Error<T> {
+ PermissionError,
NoAvailableBaseId,
+ NoAvailablePartId,
+ BaseDoesntExist,
+ NeedsDefaultThemeFirst,
}
#[pallet::call]
@@ -95,17 +109,17 @@
let collection_id = collection_id_res?;
- let collection = <PalletCore<T>>::get_nft_collection(collection_id)?.into_inner();
-
<PalletCommon<T>>::set_scoped_collection_properties(
- &collection,
+ collection_id,
PropertyScope::Rmrk,
[
- rmrk_property!(Config=T, CollectionType: CollectionType::Base)?,
- rmrk_property!(Config=T, BaseType: base_type)?,
+ <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)?;
+
for part in parts {
let part_id = part.id();
let part_token_id = Self::create_part(
@@ -117,10 +131,10 @@
<InernalPartId<T>>::insert(collection_id, part_id, part_token_id);
<PalletNft<T>>::set_scoped_token_property(
- &collection,
+ collection_id,
part_token_id,
PropertyScope::Rmrk,
- rmrk_property!(Config=T, ExternalPartId: part_id)?
+ <PalletCore<T>>::rmrk_property(ExternalPartId, &part_id)?
)?;
}
@@ -128,13 +142,64 @@
Ok(())
}
+
+ #[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 = T::CrossAccountId::from_sub(sender);
+ let owner = &sender;
+
+ 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)?;
+
+ 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)?;
+
+ for property in theme.properties {
+ <PalletNft<T>>::set_scoped_token_property(
+ collection_id,
+ token_id,
+ PropertyScope::Rmrk,
+ <PalletCore<T>>::rmrk_property(
+ ThemeProperty(&property.key),
+ &property.value
+ )?
+ )?;
+ }
+
+ Ok(())
+ }
}
}
impl<T: Config> Pallet<T> {
fn create_part(
sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
+ collection: &NonfungibleHandle<T>,
part: RmrkPartType
) -> Result<TokenId, DispatchError> {
let owner = sender;
@@ -150,21 +215,23 @@
let token_id = <PalletCore<T>>::create_nft(
sender,
owner,
- collection.id,
- CollectionType::Base,
+ collection,
nft_type,
[
- rmrk_property!(Config=T, Src: src)?,
- rmrk_property!(Config=T, ZIndex: z_index)?
+ <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,
+ collection.id,
token_id,
PropertyScope::Rmrk,
- rmrk_property!(Config=T, EquippableList: part.equippable)?
+ <PalletCore<T>>::rmrk_property(EquippableList, &part.equippable)?
)?;
}
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -347,7 +347,7 @@
fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkNft, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};
let collection_id = CollectionId(base_id);
if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }
@@ -379,7 +379,7 @@
fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
let collection_id = CollectionId(base_id);
if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {
@@ -407,7 +407,7 @@
use frame_support::BoundedVec;
use pallet_proxy_rmrk_core::{
RmrkProperty,
- misc::{CollectionType, NftType, RmrkNft, RmrkDecode}
+ misc::{CollectionType, NftType, RmrkDecode}
};
let collection_id = CollectionId(base_id);