difftreelog
feat add rmrk proxy nft minting
in: master
5 files changed
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, 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 }196}197198// unchecked calls skips any permission checks199impl<T: Config> Pallet<T> {200 pub fn init_collection(201 owner: T::AccountId,202 data: CreateCollectionData<T::AccountId>,203 ) -> Result<CollectionId, DispatchError> {204 <PalletCommon<T>>::init_collection(owner, data)205 }206 pub fn destroy_collection(207 collection: NonfungibleHandle<T>,208 sender: &T::CrossAccountId,209 ) -> DispatchResult {210 let id = collection.id;211212 // =========213214 PalletCommon::destroy_collection(collection.0, sender)?;215216 <TokenData<T>>::remove_prefix((id,), None);217 <Owned<T>>::remove_prefix((id,), None);218 <TokensMinted<T>>::remove(id);219 <TokensBurnt<T>>::remove(id);220 <Allowance<T>>::remove_prefix((id,), None);221 <AccountBalance<T>>::remove_prefix((id,), None);222 Ok(())223 }224225 pub fn burn(226 collection: &NonfungibleHandle<T>,227 sender: &T::CrossAccountId,228 token: TokenId,229 ) -> DispatchResult {230 let token_data =231 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;232 ensure!(233 &token_data.owner == sender234 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),235 <CommonError<T>>::NoPermission236 );237238 if collection.access == AccessMode::AllowList {239 collection.check_allowlist(sender)?;240 }241242 let burnt = <TokensBurnt<T>>::get(collection.id)243 .checked_add(1)244 .ok_or(ArithmeticError::Overflow)?;245246 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))247 .checked_sub(1)248 .ok_or(ArithmeticError::Overflow)?;249250 if balance == 0 {251 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));252 } else {253 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);254 }255 // =========256257 <Owned<T>>::remove((collection.id, &token_data.owner, token));258 <TokensBurnt<T>>::insert(collection.id, burnt);259 <TokenData<T>>::remove((collection.id, token));260 <TokenProperties<T>>::remove((collection.id, token));261 let old_spender = <Allowance<T>>::take((collection.id, token));262263 if let Some(old_spender) = old_spender {264 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(265 collection.id,266 token,267 sender.clone(),268 old_spender,269 0,270 ));271 }272273 <PalletEvm<T>>::deposit_log(274 ERC721Events::Transfer {275 from: *token_data.owner.as_eth(),276 to: H160::default(),277 token_id: token.into(),278 }279 .to_log(collection_id_to_address(collection.id)),280 );281 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(282 collection.id,283 token,284 token_data.owner,285 1,286 ));287 Ok(())288 }289290 pub fn set_token_property(291 collection: &NonfungibleHandle<T>,292 sender: &T::CrossAccountId,293 token_id: TokenId,294 property: Property,295 ) -> DispatchResult {296 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;297298 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {299 let property = property.clone();300 properties.try_set(property.key, property.value)301 })302 .map_err(<CommonError<T>>::from)?;303304 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(305 collection.id,306 token_id,307 property.key,308 ));309310 Ok(())311 }312313 #[transactional]314 pub fn set_token_properties(315 collection: &NonfungibleHandle<T>,316 sender: &T::CrossAccountId,317 token_id: TokenId,318 properties: Vec<Property>,319 ) -> DispatchResult {320 for property in properties {321 Self::set_token_property(collection, sender, token_id, property)?;322 }323324 Ok(())325 }326327 pub fn delete_token_property(328 collection: &NonfungibleHandle<T>,329 sender: &T::CrossAccountId,330 token_id: TokenId,331 property_key: PropertyKey,332 ) -> DispatchResult {333 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;334335 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {336 properties.remove(&property_key)337 })338 .map_err(<CommonError<T>>::from)?;339340 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(341 collection.id,342 token_id,343 property_key,344 ));345346 Ok(())347 }348349 fn check_token_change_permission(350 collection: &NonfungibleHandle<T>,351 sender: &T::CrossAccountId,352 token_id: TokenId,353 property_key: &PropertyKey,354 ) -> DispatchResult {355 let permission = <PalletCommon<T>>::property_permissions(collection.id)356 .get(property_key)357 .cloned()358 .unwrap_or_else(PropertyPermission::none);359360 let token_data = <TokenData<T>>::get((collection.id, token_id))361 .ok_or(<CommonError<T>>::TokenNotFound)?;362363 let check_token_owner = || -> DispatchResult {364 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);365 Ok(())366 };367368 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))369 .get(property_key)370 .is_some();371372 match permission {373 PropertyPermission { mutable: false, .. } if is_property_exists => {374 Err(<CommonError<T>>::NoPermission.into())375 }376377 PropertyPermission {378 collection_admin,379 token_owner,380 ..381 } => {382 let mut check_result = Err(<CommonError<T>>::NoPermission.into());383384 if collection_admin {385 check_result = collection.check_is_owner_or_admin(sender);386 }387388 if token_owner {389 check_result.or_else(|_| check_token_owner())390 } else {391 check_result392 }393 }394 }395 }396397 #[transactional]398 pub fn delete_token_properties(399 collection: &NonfungibleHandle<T>,400 sender: &T::CrossAccountId,401 token_id: TokenId,402 property_keys: Vec<PropertyKey>,403 ) -> DispatchResult {404 for key in property_keys {405 Self::delete_token_property(collection, sender, token_id, key)?;406 }407408 Ok(())409 }410411 pub fn set_collection_properties(412 collection: &NonfungibleHandle<T>,413 sender: &T::CrossAccountId,414 properties: Vec<Property>,415 ) -> DispatchResult {416 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)417 }418419 pub fn delete_collection_properties(420 collection: &CollectionHandle<T>,421 sender: &T::CrossAccountId,422 property_keys: Vec<PropertyKey>,423 ) -> DispatchResult {424 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)425 }426427 pub fn set_property_permissions(428 collection: &CollectionHandle<T>,429 sender: &T::CrossAccountId,430 property_permissions: Vec<PropertyKeyPermission>,431 ) -> DispatchResult {432 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)433 }434435 pub fn set_property_permission(436 collection: &CollectionHandle<T>,437 sender: &T::CrossAccountId,438 permission: PropertyKeyPermission,439 ) -> DispatchResult {440 <PalletCommon<T>>::set_property_permission(collection, sender, permission)441 }442443 pub fn transfer(444 collection: &NonfungibleHandle<T>,445 from: &T::CrossAccountId,446 to: &T::CrossAccountId,447 token: TokenId,448 nesting_budget: &dyn Budget,449 ) -> DispatchResult {450 ensure!(451 collection.limits.transfers_enabled(),452 <CommonError<T>>::TransferNotAllowed453 );454455 let token_data =456 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;457 // TODO: require sender to be token, owner, require admins to go through transfer_from458 ensure!(459 &token_data.owner == from460 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),461 <CommonError<T>>::NoPermission462 );463464 if collection.access == AccessMode::AllowList {465 collection.check_allowlist(from)?;466 collection.check_allowlist(to)?;467 }468 <PalletCommon<T>>::ensure_correct_receiver(to)?;469470 let balance_from = <AccountBalance<T>>::get((collection.id, from))471 .checked_sub(1)472 .ok_or(<CommonError<T>>::TokenValueTooLow)?;473 let balance_to = if from != to {474 let balance_to = <AccountBalance<T>>::get((collection.id, to))475 .checked_add(1)476 .ok_or(ArithmeticError::Overflow)?;477478 ensure!(479 balance_to < collection.limits.account_token_ownership_limit(),480 <CommonError<T>>::AccountTokenLimitExceeded,481 );482483 Some(balance_to)484 } else {485 None486 };487488 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {489 let handle = <CollectionHandle<T>>::try_get(target.0)?;490 let dispatch = T::CollectionDispatch::dispatch(handle);491 let dispatch = dispatch.as_dyn();492493 dispatch.check_nesting(494 from.clone(),495 (collection.id, token),496 target.1,497 nesting_budget,498 )?;499 }500501 // =========502503 <TokenData<T>>::insert(504 (collection.id, token),505 ItemData {506 owner: to.clone(),507 ..token_data508 },509 );510511 if let Some(balance_to) = balance_to {512 // from != to513 if balance_from == 0 {514 <AccountBalance<T>>::remove((collection.id, from));515 } else {516 <AccountBalance<T>>::insert((collection.id, from), balance_from);517 }518 <AccountBalance<T>>::insert((collection.id, to), balance_to);519 <Owned<T>>::remove((collection.id, from, token));520 <Owned<T>>::insert((collection.id, to, token), true);521 }522 Self::set_allowance_unchecked(collection, from, token, None, true);523524 <PalletEvm<T>>::deposit_log(525 ERC721Events::Transfer {526 from: *from.as_eth(),527 to: *to.as_eth(),528 token_id: token.into(),529 }530 .to_log(collection_id_to_address(collection.id)),531 );532 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(533 collection.id,534 token,535 from.clone(),536 to.clone(),537 1,538 ));539 Ok(())540 }541542 pub fn create_multiple_items(543 collection: &NonfungibleHandle<T>,544 sender: &T::CrossAccountId,545 data: Vec<CreateItemData<T>>,546 nesting_budget: &dyn Budget,547 ) -> DispatchResult {548 if !collection.is_owner_or_admin(sender) {549 ensure!(550 collection.mint_mode,551 <CommonError<T>>::PublicMintingNotAllowed552 );553 collection.check_allowlist(sender)?;554555 for item in data.iter() {556 collection.check_allowlist(&item.owner)?;557 }558 }559560 for data in data.iter() {561 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;562 }563564 let first_token = <TokensMinted<T>>::get(collection.id);565 let tokens_minted = first_token566 .checked_add(data.len() as u32)567 .ok_or(ArithmeticError::Overflow)?;568 ensure!(569 tokens_minted <= collection.limits.token_limit(),570 <CommonError<T>>::CollectionTokenLimitExceeded571 );572573 let mut balances = BTreeMap::new();574 for data in &data {575 let balance = balances576 .entry(&data.owner)577 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));578 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;579580 ensure!(581 *balance <= collection.limits.account_token_ownership_limit(),582 <CommonError<T>>::AccountTokenLimitExceeded,583 );584 }585586 for (i, data) in data.iter().enumerate() {587 let token = TokenId(first_token + i as u32 + 1);588 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {589 let handle = <CollectionHandle<T>>::try_get(target.0)?;590 let dispatch = T::CollectionDispatch::dispatch(handle);591 let dispatch = dispatch.as_dyn();592 dispatch.check_nesting(593 sender.clone(),594 (collection.id, token),595 target.1,596 nesting_budget,597 )?;598 }599 }600601 // =========602603 with_transaction(|| {604 for (i, data) in data.iter().enumerate() {605 let token = first_token + i as u32 + 1;606607 <TokenData<T>>::insert(608 (collection.id, token),609 ItemData {610 const_data: data.const_data.clone(),611 owner: data.owner.clone(),612 },613 );614615 if let Err(e) = Self::set_token_properties(616 collection,617 sender,618 TokenId(token),619 data.properties.clone().into_inner(),620 ) {621 return TransactionOutcome::Rollback(Err(e));622 }623 }624 TransactionOutcome::Commit(Ok(()))625 })?;626627 <TokensMinted<T>>::insert(collection.id, tokens_minted);628 for (account, balance) in balances {629 <AccountBalance<T>>::insert((collection.id, account), balance);630 }631 for (i, data) in data.into_iter().enumerate() {632 let token = first_token + i as u32 + 1;633 <Owned<T>>::insert((collection.id, &data.owner, token), true);634635 <PalletEvm<T>>::deposit_log(636 ERC721Events::Transfer {637 from: H160::default(),638 to: *data.owner.as_eth(),639 token_id: token.into(),640 }641 .to_log(collection_id_to_address(collection.id)),642 );643 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(644 collection.id,645 TokenId(token),646 data.owner.clone(),647 1,648 ));649 }650 Ok(())651 }652653 pub fn set_allowance_unchecked(654 collection: &NonfungibleHandle<T>,655 sender: &T::CrossAccountId,656 token: TokenId,657 spender: Option<&T::CrossAccountId>,658 assume_implicit_eth: bool,659 ) {660 if let Some(spender) = spender {661 let old_spender = <Allowance<T>>::get((collection.id, token));662 <Allowance<T>>::insert((collection.id, token), spender);663 // In ERC721 there is only one possible approved user of token, so we set664 // approved user to spender665 <PalletEvm<T>>::deposit_log(666 ERC721Events::Approval {667 owner: *sender.as_eth(),668 approved: *spender.as_eth(),669 token_id: token.into(),670 }671 .to_log(collection_id_to_address(collection.id)),672 );673 // In Unique chain, any token can have any amount of approved users, so we need to674 // set allowance of old owner to 0, and allowance of new owner to 1675 if old_spender.as_ref() != Some(spender) {676 if let Some(old_owner) = old_spender {677 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(678 collection.id,679 token,680 sender.clone(),681 old_owner,682 0,683 ));684 }685 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(686 collection.id,687 token,688 sender.clone(),689 spender.clone(),690 1,691 ));692 }693 } else {694 let old_spender = <Allowance<T>>::take((collection.id, token));695 if !assume_implicit_eth {696 // In ERC721 there is only one possible approved user of token, so we set697 // approved user to zero address698 <PalletEvm<T>>::deposit_log(699 ERC721Events::Approval {700 owner: *sender.as_eth(),701 approved: H160::default(),702 token_id: token.into(),703 }704 .to_log(collection_id_to_address(collection.id)),705 );706 }707 // In Unique chain, any token can have any amount of approved users, so we need to708 // set allowance of old owner to 0709 if let Some(old_spender) = old_spender {710 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(711 collection.id,712 token,713 sender.clone(),714 old_spender,715 0,716 ));717 }718 }719 }720721 pub fn set_allowance(722 collection: &NonfungibleHandle<T>,723 sender: &T::CrossAccountId,724 token: TokenId,725 spender: Option<&T::CrossAccountId>,726 ) -> DispatchResult {727 if collection.access == AccessMode::AllowList {728 collection.check_allowlist(sender)?;729 if let Some(spender) = spender {730 collection.check_allowlist(spender)?;731 }732 }733734 if let Some(spender) = spender {735 <PalletCommon<T>>::ensure_correct_receiver(spender)?;736 }737 let token_data =738 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;739 if &token_data.owner != sender {740 ensure!(741 collection.ignores_owned_amount(sender),742 <CommonError<T>>::CantApproveMoreThanOwned743 );744 }745746 // =========747748 Self::set_allowance_unchecked(collection, sender, token, spender, false);749 Ok(())750 }751752 fn check_allowed(753 collection: &NonfungibleHandle<T>,754 spender: &T::CrossAccountId,755 from: &T::CrossAccountId,756 token: TokenId,757 nesting_budget: &dyn Budget,758 ) -> DispatchResult {759 if spender.conv_eq(from) {760 return Ok(());761 }762 if collection.access == AccessMode::AllowList {763 // `from`, `to` checked in [`transfer`]764 collection.check_allowlist(spender)?;765 }766 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {767 // TODO: should collection owner be allowed to perform this transfer?768 ensure!(769 <PalletStructure<T>>::check_indirectly_owned(770 spender.clone(),771 source.0,772 source.1,773 None,774 nesting_budget775 )?,776 <CommonError<T>>::ApprovedValueTooLow,777 );778 return Ok(());779 }780 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {781 return Ok(());782 }783 ensure!(784 collection.ignores_allowance(spender),785 <CommonError<T>>::ApprovedValueTooLow786 );787 Ok(())788 }789790 pub fn transfer_from(791 collection: &NonfungibleHandle<T>,792 spender: &T::CrossAccountId,793 from: &T::CrossAccountId,794 to: &T::CrossAccountId,795 token: TokenId,796 nesting_budget: &dyn Budget,797 ) -> DispatchResult {798 Self::check_allowed(collection, spender, from, token, nesting_budget)?;799800 // =========801802 // Allowance is reset in [`transfer`]803 Self::transfer(collection, from, to, token, nesting_budget)804 }805806 pub fn burn_from(807 collection: &NonfungibleHandle<T>,808 spender: &T::CrossAccountId,809 from: &T::CrossAccountId,810 token: TokenId,811 nesting_budget: &dyn Budget,812 ) -> DispatchResult {813 Self::check_allowed(collection, spender, from, token, nesting_budget)?;814815 // =========816817 Self::burn(collection, from, token)818 }819820 pub fn check_nesting(821 handle: &NonfungibleHandle<T>,822 sender: T::CrossAccountId,823 from: (CollectionId, TokenId),824 under: TokenId,825 nesting_budget: &dyn Budget,826 ) -> DispatchResult {827 fn ensure_sender_allowed<T: Config>(828 collection: CollectionId,829 token: TokenId,830 for_nest: (CollectionId, TokenId),831 sender: T::CrossAccountId,832 budget: &dyn Budget,833 ) -> DispatchResult {834 ensure!(835 <PalletStructure<T>>::check_indirectly_owned(836 sender,837 collection,838 token,839 Some(for_nest),840 budget841 )?,842 <CommonError<T>>::OnlyOwnerAllowedToNest,843 );844 Ok(())845 }846 match handle.limits.nesting_rule() {847 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),848 NestingRule::Owner => {849 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?850 }851 NestingRule::OwnerRestricted(whitelist) => {852 ensure!(853 whitelist.contains(&from.0),854 <CommonError<T>>::SourceCollectionIsNotAllowedToNest855 );856 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?857 }858 }859 Ok(())860 }861862 /// Delegated to `create_multiple_items`863 pub fn create_item(864 collection: &NonfungibleHandle<T>,865 sender: &T::CrossAccountId,866 data: CreateItemData<T>,867 nesting_budget: &dyn Budget,868 ) -> DispatchResult {869 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)870 }871}pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -18,7 +18,8 @@
use frame_support::{pallet_prelude::*, transactional, BoundedVec, dispatch::DispatchResult};
use frame_system::{pallet_prelude::*, ensure_signed};
-use sp_runtime::{DispatchError, traits::StaticLookup};
+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_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
@@ -69,19 +70,28 @@
issuer: T::AccountId,
collection_id: RmrkCollectionId,
},
+ NftMinted {
+ owner: T::AccountId,
+ collection_id: RmrkCollectionId,
+ nft_id: RmrkNftId,
+ },
}
#[pallet::error]
pub enum Error<T> {
/* Unique-specific events */
CorruptedCollectionType,
+ NftTypeEncodeError,
RmrkPropertyKeyIsTooLong,
RmrkPropertyValueIsTooLong,
/* RMRK compatible events */
CollectionNotEmpty,
NoAvailableCollectionId,
+ NoAvailableNftId,
CollectionUnknown,
+ NoPermission,
+ CollectionFullOrLocked,
}
#[pallet::call]
@@ -147,9 +157,7 @@
let unique_collection_id = collection_id.into();
- let collection = Self::get_nft_collection(unique_collection_id)?;
-
- Self::check_collection_type(unique_collection_id, CollectionType::Regular)?;
+ let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;
ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
@@ -196,7 +204,10 @@
let sender = ensure_signed(origin)?;
let cross_sender = T::CrossAccountId::from_sub(sender.clone());
- let collection = Self::get_nft_collection(collection_id.into())?;
+ let collection = Self::get_typed_nft_collection(
+ collection_id.into(),
+ CollectionType::Regular
+ )?;
collection.check_is_owner(&cross_sender)?;
let token_count = collection.total_supply();
@@ -209,20 +220,113 @@
Ok(())
}
+
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn mint_nft(
+ origin: OriginFor<T>,
+ owner: T::AccountId,
+ collection_id: RmrkCollectionId,
+ recipient: Option<T::AccountId>,
+ 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 royalty_info = royalty_amount.map(|amount| rmrk::RoyaltyInfo {
+ recipient: recipient.unwrap_or_else(|| owner.clone()),
+ amount
+ });
+
+ let nft_id = Self::create_nft(
+ sender,
+ cross_owner,
+ collection_id.into(),
+ CollectionType::Regular,
+ 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())?,
+ ].into_iter()
+ )?;
+
+ Self::deposit_event(Event::NftMinted {
+ owner,
+ collection_id,
+ nft_id: nft_id.0
+ });
+
+ Ok(())
+ }
}
}
impl<T: Config> Pallet<T> {
+ fn create_nft(
+ sender: T::CrossAccountId,
+ owner: T::CrossAccountId,
+ collection_id: CollectionId,
+ collection_type: CollectionType,
+ 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()
+ .map_err(|_| <Error<T>>::NftTypeEncodeError)?,
+ properties: BoundedVec::default(),
+ owner,
+ };
+
+ let budget = budget::Value::new(2);
+
+ <PalletNft<T>>::create_item(
+ &collection,
+ &sender,
+ data,
+ &budget,
+ ).map_err(|err| {
+ map_common_err_to_proxy!(
+ match err {
+ NoPermission => NoPermission,
+ CollectionTokenLimitExceeded => CollectionFullOrLocked
+ }
+ )
+ })?;
+
+ let nft_id = <PalletNft<T>>::current_token_id(&collection);
+
+ <PalletNft<T>>::set_scoped_token_properties(
+ &collection,
+ nft_id,
+ PropertyScope::Rmrk,
+ properties
+ )?;
+
+ Ok(nft_id)
+ }
+
fn change_collection_owner(
collection_id: CollectionId,
collection_type: CollectionType,
sender: T::AccountId,
new_owner: T::AccountId,
) -> DispatchResult {
- let mut collection = Self::get_nft_collection(collection_id)?.into_inner();
+ let mut collection = Self::get_typed_nft_collection(
+ collection_id,
+ collection_type
+ )?.into_inner();
collection.check_is_owner(&T::CrossAccountId::from_sub(sender))?;
-
- Self::check_collection_type(collection_id, collection_type)?;
collection.owner = new_owner;
collection.save()
@@ -257,7 +361,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)?)
- .ok_or(<Error<T>>::CollectionUnknown)? // todo is that right?
+ .ok_or(<Error<T>>::NoAvailableNftId)?
.clone();
Ok(nft_property)
@@ -269,4 +373,13 @@
Ok(())
}
+
+ fn get_typed_nft_collection(
+ collection_id: CollectionId,
+ collection_type: CollectionType
+ ) -> Result<NonfungibleHandle<T>, DispatchError> {
+ Self::check_collection_type(collection_id, collection_type)?;
+
+ Self::get_nft_collection(collection_id)
+ }
}
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -1,17 +1,9 @@
use super::*;
use codec::{Encode, Decode};
-use pallet_nonfungible::NonfungibleHandle;
+use pallet_nonfungible::{NonfungibleHandle, ItemData};
macro_rules! impl_rmrk_value {
($enum_name:path, decode_error: $error:ident) => {
- impl IntoPropertyValue for $enum_name {
- fn into_property_value(self) -> Result<PropertyValue, MiscError> {
- self.encode()
- .try_into()
- .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
- }
- }
-
impl TryFrom<&PropertyValue> for $enum_name {
type Error = MiscError;
@@ -26,6 +18,19 @@
};
}
+#[macro_export]
+macro_rules! map_common_err_to_proxy {
+ (match $err:ident { $($common_err:ident => $proxy_err:ident),+ }) => {
+ $(
+ if $err == <CommonError<T>>::$common_err.into() {
+ return <Error<T>>::$proxy_err.into()
+ } else
+ )+ {
+ $err
+ }
+ };
+}
+
pub enum MiscError {
RmrkPropertyValueIsTooLong,
CorruptedCollectionType,
@@ -57,14 +62,26 @@
fn into_property_value(self) -> Result<PropertyValue, MiscError>;
}
-impl<L: Get<u32>> IntoPropertyValue for BoundedVec<u8, L> {
+impl<T: Encode> IntoPropertyValue for T {
fn into_property_value(self) -> Result<PropertyValue, MiscError> {
- self.into_inner()
+ 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()
+ }
+}
+
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
Regular,
@@ -72,4 +89,13 @@
Base,
}
+#[derive(Encode, Decode, PartialEq, Eq)]
+pub enum NftType {
+ Regular,
+ Resource,
+ FixedPart,
+ 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
@@ -4,8 +4,7 @@
pub enum RmrkProperty {
Metadata,
CollectionType,
- Recipient,
- Royalty,
+ RoyaltyInfo,
Equipped,
ResourceCollection,
ResourcePriorities,
@@ -48,8 +47,7 @@
match self {
Self::Metadata => key!("metadata"),
Self::CollectionType => key!("collection-type"),
- Self::Recipient => key!("recipient"),
- Self::Royalty => key!("royalty"),
+ Self::RoyaltyInfo => key!("royalty-info"),
Self::Equipped => key!("equipped"),
Self::ResourceCollection => key!("resource-collection"),
Self::ResourcePriorities => key!("resource-priorities"),
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -188,10 +188,9 @@
};
let keys = [
- RmrkProperty::Royalty,
+ RmrkProperty::RoyaltyInfo,
RmrkProperty::Metadata,
RmrkProperty::Equipped,
- RmrkProperty::Pending,
// ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"
];
@@ -315,13 +314,13 @@
let collection_id = CollectionId(collection_id);
let nft_id = TokenId(nft_id);
- let keys = [
- RmrkProperty::Royalty,
- RmrkProperty::Metadata,
- RmrkProperty::Equipped,
- RmrkProperty::Pending,
- // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"
- ];
+ // let keys = [
+ // RmrkProperty::Royalty,
+ // RmrkProperty::Metadata,
+ // RmrkProperty::Equipped,
+ // RmrkProperty::Pending,
+ // // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"
+ // ];
/*let resources = keys.into_iter().map(
|key| BoundedVec::try_from(