difftreelog
Merge pull request #355 from UniqueNetwork/feature/nft-children
in: master
Structure children map
12 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -353,6 +353,8 @@
MustBeTokenOwner,
/// No permission to perform action
NoPermission,
+ /// Destroying only empty collections is allowed
+ CantDestroyNotEmptyCollection,
/// Collection is not in mint mode.
PublicMintingNotAllowed,
/// Address is not in allow list.
@@ -1268,6 +1270,18 @@
budget: &dyn Budget,
) -> DispatchResult;
+ fn nest(
+ &self,
+ under: TokenId,
+ to_nest: (CollectionId, TokenId)
+ );
+
+ fn unnest(
+ &self,
+ under: TokenId,
+ to_nest: (CollectionId, TokenId)
+ );
+
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
fn collection_tokens(&self) -> Vec<TokenId>;
fn token_exists(&self, token: TokenId) -> bool;
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -298,6 +298,18 @@
fail!(<Error<T>>::FungibleDisallowsNesting)
}
+ fn nest(
+ &self,
+ _under: TokenId,
+ _to_nest: (CollectionId, TokenId)
+ ) {}
+
+ fn unnest(
+ &self,
+ _under: TokenId,
+ _to_nest: (CollectionId, TokenId)
+ ) {}
+
fn collection_tokens(&self) -> Vec<TokenId> {
vec![TokenId::default()]
}
pallets/fungible/src/lib.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 core::ops::Deref;20use evm_coder::ToLog;21use frame_support::{ensure};22use pallet_evm::account::CrossAccountId;23use up_data_structs::{24 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,25 budget::Budget,26};27use pallet_common::{28 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,29 dispatch::CollectionDispatch, eth::collection_id_to_address,30};31use pallet_evm::Pallet as PalletEvm;32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::WithRecorder;34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{collections::btree_map::BTreeMap};3738pub use pallet::*;3940use crate::erc::ERC20Events;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[frame_support::pallet]51pub mod pallet {52 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};53 use up_data_structs::CollectionId;54 use super::weights::WeightInfo;5556 #[pallet::error]57 pub enum Error<T> {58 /// Not Fungible item data used to mint in Fungible collection.59 NotFungibleDataUsedToMintFungibleCollectionToken,60 /// Not default id passed as TokenId argument61 FungibleItemsHaveNoId,62 /// Tried to set data for fungible item63 FungibleItemsDontHaveData,64 /// Fungible token does not support nested65 FungibleDisallowsNesting,66 /// Setting item properties is not allowed67 SettingPropertiesNotAllowed,68 }6970 #[pallet::config]71 pub trait Config:72 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config73 {74 type WeightInfo: WeightInfo;75 }7677 #[pallet::pallet]78 #[pallet::generate_store(pub(super) trait Store)]79 pub struct Pallet<T>(_);8081 #[pallet::storage]82 pub type TotalSupply<T: Config> =83 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8485 #[pallet::storage]86 pub type Balance<T: Config> = StorageNMap<87 Key = (88 Key<Twox64Concat, CollectionId>,89 Key<Blake2_128Concat, T::CrossAccountId>,90 ),91 Value = u128,92 QueryKind = ValueQuery,93 >;9495 #[pallet::storage]96 pub type Allowance<T: Config> = StorageNMap<97 Key = (98 Key<Twox64Concat, CollectionId>,99 Key<Blake2_128, T::CrossAccountId>,100 Key<Blake2_128Concat, T::CrossAccountId>,101 ),102 Value = u128,103 QueryKind = ValueQuery,104 >;105}106107pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);108impl<T: Config> FungibleHandle<T> {109 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {110 Self(inner)111 }112 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {113 self.0114 }115 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {116 &mut self.0117 }118}119impl<T: Config> WithRecorder<T> for FungibleHandle<T> {120 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {121 self.0.recorder()122 }123 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {124 self.0.into_recorder()125 }126}127impl<T: Config> Deref for FungibleHandle<T> {128 type Target = pallet_common::CollectionHandle<T>;129130 fn deref(&self) -> &Self::Target {131 &self.0132 }133}134135impl<T: Config> Pallet<T> {136 pub fn init_collection(137 owner: T::AccountId,138 data: CreateCollectionData<T::AccountId>,139 ) -> Result<CollectionId, DispatchError> {140 <PalletCommon<T>>::init_collection(owner, data)141 }142 pub fn destroy_collection(143 collection: FungibleHandle<T>,144 sender: &T::CrossAccountId,145 ) -> DispatchResult {146 let id = collection.id;147148 // =========149150 PalletCommon::destroy_collection(collection.0, sender)?;151152 <TotalSupply<T>>::remove(id);153 <Balance<T>>::remove_prefix((id,), None);154 <Allowance<T>>::remove_prefix((id,), None);155 Ok(())156 }157158 pub fn burn(159 collection: &FungibleHandle<T>,160 owner: &T::CrossAccountId,161 amount: u128,162 ) -> DispatchResult {163 let total_supply = <TotalSupply<T>>::get(collection.id)164 .checked_sub(amount)165 .ok_or(<CommonError<T>>::TokenValueTooLow)?;166167 let balance = <Balance<T>>::get((collection.id, owner))168 .checked_sub(amount)169 .ok_or(<CommonError<T>>::TokenValueTooLow)?;170171 if collection.permissions.access() == AccessMode::AllowList {172 collection.check_allowlist(owner)?;173 }174175 // =========176177 if balance == 0 {178 <Balance<T>>::remove((collection.id, owner));179 } else {180 <Balance<T>>::insert((collection.id, owner), balance);181 }182 <TotalSupply<T>>::insert(collection.id, total_supply);183184 <PalletEvm<T>>::deposit_log(185 ERC20Events::Transfer {186 from: *owner.as_eth(),187 to: H160::default(),188 value: amount.into(),189 }190 .to_log(collection_id_to_address(collection.id)),191 );192 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(193 collection.id,194 TokenId::default(),195 owner.clone(),196 amount,197 ));198 Ok(())199 }200201 pub fn transfer(202 collection: &FungibleHandle<T>,203 from: &T::CrossAccountId,204 to: &T::CrossAccountId,205 amount: u128,206 nesting_budget: &dyn Budget,207 ) -> DispatchResult {208 ensure!(209 collection.limits.transfers_enabled(),210 <CommonError<T>>::TransferNotAllowed,211 );212213 if collection.permissions.access() == AccessMode::AllowList {214 collection.check_allowlist(from)?;215 collection.check_allowlist(to)?;216 }217 <PalletCommon<T>>::ensure_correct_receiver(to)?;218219 let balance_from = <Balance<T>>::get((collection.id, from))220 .checked_sub(amount)221 .ok_or(<CommonError<T>>::TokenValueTooLow)?;222 let balance_to = if from != to {223 Some(224 <Balance<T>>::get((collection.id, to))225 .checked_add(amount)226 .ok_or(ArithmeticError::Overflow)?,227 )228 } else {229 None230 };231232 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {233 let handle = <CollectionHandle<T>>::try_get(target.0)?;234 let dispatch = T::CollectionDispatch::dispatch(handle);235 let dispatch = dispatch.as_dyn();236237 dispatch.check_nesting(238 from.clone(),239 (collection.id, TokenId::default()),240 target.1,241 nesting_budget,242 )?;243 }244245 // =========246247 if let Some(balance_to) = balance_to {248 // from != to249 if balance_from == 0 {250 <Balance<T>>::remove((collection.id, from));251 } else {252 <Balance<T>>::insert((collection.id, from), balance_from);253 }254 <Balance<T>>::insert((collection.id, to), balance_to);255 }256257 <PalletEvm<T>>::deposit_log(258 ERC20Events::Transfer {259 from: *from.as_eth(),260 to: *to.as_eth(),261 value: amount.into(),262 }263 .to_log(collection_id_to_address(collection.id)),264 );265 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(266 collection.id,267 TokenId::default(),268 from.clone(),269 to.clone(),270 amount,271 ));272 Ok(())273 }274275 pub fn create_multiple_items(276 collection: &FungibleHandle<T>,277 sender: &T::CrossAccountId,278 data: BTreeMap<T::CrossAccountId, u128>,279 nesting_budget: &dyn Budget,280 ) -> DispatchResult {281 if !collection.is_owner_or_admin(sender) {282 ensure!(283 collection.permissions.mint_mode(),284 <CommonError<T>>::PublicMintingNotAllowed285 );286 collection.check_allowlist(sender)?;287288 for (owner, _) in data.iter() {289 collection.check_allowlist(owner)?;290 }291 }292293 let total_supply = data294 .iter()295 .map(|(_, v)| *v)296 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {297 acc.checked_add(v)298 })299 .ok_or(ArithmeticError::Overflow)?;300301 let mut balances = data;302 for (k, v) in balances.iter_mut() {303 *v = <Balance<T>>::get((collection.id, &k))304 .checked_add(*v)305 .ok_or(ArithmeticError::Overflow)?;306 }307308 for (to, _) in balances.iter() {309 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {310 let handle = <CollectionHandle<T>>::try_get(target.0)?;311 let dispatch = T::CollectionDispatch::dispatch(handle);312 let dispatch = dispatch.as_dyn();313314 dispatch.check_nesting(315 sender.clone(),316 (collection.id, TokenId::default()),317 target.1,318 nesting_budget,319 )?;320 }321 }322323 // =========324325 <TotalSupply<T>>::insert(collection.id, total_supply);326 for (user, amount) in balances {327 <Balance<T>>::insert((collection.id, &user), amount);328329 <PalletEvm<T>>::deposit_log(330 ERC20Events::Transfer {331 from: H160::default(),332 to: *user.as_eth(),333 value: amount.into(),334 }335 .to_log(collection_id_to_address(collection.id)),336 );337 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(338 collection.id,339 TokenId::default(),340 user.clone(),341 amount,342 ));343 }344345 Ok(())346 }347348 fn set_allowance_unchecked(349 collection: &FungibleHandle<T>,350 owner: &T::CrossAccountId,351 spender: &T::CrossAccountId,352 amount: u128,353 ) {354 if amount == 0 {355 <Allowance<T>>::remove((collection.id, owner, spender));356 } else {357 <Allowance<T>>::insert((collection.id, owner, spender), amount);358 }359360 <PalletEvm<T>>::deposit_log(361 ERC20Events::Approval {362 owner: *owner.as_eth(),363 spender: *spender.as_eth(),364 value: amount.into(),365 }366 .to_log(collection_id_to_address(collection.id)),367 );368 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(369 collection.id,370 TokenId(0),371 owner.clone(),372 spender.clone(),373 amount,374 ));375 }376377 pub fn set_allowance(378 collection: &FungibleHandle<T>,379 owner: &T::CrossAccountId,380 spender: &T::CrossAccountId,381 amount: u128,382 ) -> DispatchResult {383 if collection.permissions.access() == AccessMode::AllowList {384 collection.check_allowlist(owner)?;385 collection.check_allowlist(spender)?;386 }387388 if <Balance<T>>::get((collection.id, owner)) < amount {389 ensure!(390 collection.ignores_owned_amount(owner),391 <CommonError<T>>::CantApproveMoreThanOwned392 );393 }394395 // =========396397 Self::set_allowance_unchecked(collection, owner, spender, amount);398 Ok(())399 }400401 fn check_allowed(402 collection: &FungibleHandle<T>,403 spender: &T::CrossAccountId,404 from: &T::CrossAccountId,405 amount: u128,406 nesting_budget: &dyn Budget,407 ) -> Result<Option<u128>, DispatchError> {408 if spender.conv_eq(from) {409 return Ok(None);410 }411 if collection.permissions.access() == AccessMode::AllowList {412 // `from`, `to` checked in [`transfer`]413 collection.check_allowlist(spender)?;414 }415 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {416 // TODO: should collection owner be allowed to perform this transfer?417 ensure!(418 <PalletStructure<T>>::check_indirectly_owned(419 spender.clone(),420 source.0,421 source.1,422 None,423 nesting_budget424 )?,425 <CommonError<T>>::ApprovedValueTooLow,426 );427 return Ok(None);428 }429 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);430 if allowance.is_none() {431 ensure!(432 collection.ignores_allowance(spender),433 <CommonError<T>>::ApprovedValueTooLow434 );435 }436437 Ok(allowance)438 }439440 pub fn transfer_from(441 collection: &FungibleHandle<T>,442 spender: &T::CrossAccountId,443 from: &T::CrossAccountId,444 to: &T::CrossAccountId,445 amount: u128,446 nesting_budget: &dyn Budget,447 ) -> DispatchResult {448 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;449450 // =========451452 Self::transfer(collection, from, to, amount, nesting_budget)?;453 if let Some(allowance) = allowance {454 Self::set_allowance_unchecked(collection, from, spender, allowance);455 }456 Ok(())457 }458459 pub fn burn_from(460 collection: &FungibleHandle<T>,461 spender: &T::CrossAccountId,462 from: &T::CrossAccountId,463 amount: u128,464 nesting_budget: &dyn Budget,465 ) -> DispatchResult {466 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;467468 // =========469470 Self::burn(collection, from, amount)?;471 if let Some(allowance) = allowance {472 Self::set_allowance_unchecked(collection, from, spender, allowance);473 }474 Ok(())475 }476477 /// Delegated to `create_multiple_items`478 pub fn create_item(479 collection: &FungibleHandle<T>,480 sender: &T::CrossAccountId,481 data: CreateItemData<T>,482 nesting_budget: &dyn Budget,483 ) -> DispatchResult {484 Self::create_multiple_items(485 collection,486 sender,487 [(data.0, data.1)].into_iter().collect(),488 nesting_budget,489 )490 }491}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 core::ops::Deref;20use evm_coder::ToLog;21use frame_support::{ensure};22use pallet_evm::account::CrossAccountId;23use up_data_structs::{24 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,25 budget::Budget,26};27use pallet_common::{28 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,29 eth::collection_id_to_address,30};31use pallet_evm::Pallet as PalletEvm;32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::WithRecorder;34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{collections::btree_map::BTreeMap};3738pub use pallet::*;3940use crate::erc::ERC20Events;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[frame_support::pallet]51pub mod pallet {52 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};53 use up_data_structs::CollectionId;54 use super::weights::WeightInfo;5556 #[pallet::error]57 pub enum Error<T> {58 /// Not Fungible item data used to mint in Fungible collection.59 NotFungibleDataUsedToMintFungibleCollectionToken,60 /// Not default id passed as TokenId argument61 FungibleItemsHaveNoId,62 /// Tried to set data for fungible item63 FungibleItemsDontHaveData,64 /// Fungible token does not support nested65 FungibleDisallowsNesting,66 /// Setting item properties is not allowed67 SettingPropertiesNotAllowed,68 }6970 #[pallet::config]71 pub trait Config:72 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config73 {74 type WeightInfo: WeightInfo;75 }7677 #[pallet::pallet]78 #[pallet::generate_store(pub(super) trait Store)]79 pub struct Pallet<T>(_);8081 #[pallet::storage]82 pub type TotalSupply<T: Config> =83 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8485 #[pallet::storage]86 pub type Balance<T: Config> = StorageNMap<87 Key = (88 Key<Twox64Concat, CollectionId>,89 Key<Blake2_128Concat, T::CrossAccountId>,90 ),91 Value = u128,92 QueryKind = ValueQuery,93 >;9495 #[pallet::storage]96 pub type Allowance<T: Config> = StorageNMap<97 Key = (98 Key<Twox64Concat, CollectionId>,99 Key<Blake2_128, T::CrossAccountId>,100 Key<Blake2_128Concat, T::CrossAccountId>,101 ),102 Value = u128,103 QueryKind = ValueQuery,104 >;105}106107pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);108impl<T: Config> FungibleHandle<T> {109 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {110 Self(inner)111 }112 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {113 self.0114 }115 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {116 &mut self.0117 }118}119impl<T: Config> WithRecorder<T> for FungibleHandle<T> {120 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {121 self.0.recorder()122 }123 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {124 self.0.into_recorder()125 }126}127impl<T: Config> Deref for FungibleHandle<T> {128 type Target = pallet_common::CollectionHandle<T>;129130 fn deref(&self) -> &Self::Target {131 &self.0132 }133}134135impl<T: Config> Pallet<T> {136 pub fn init_collection(137 owner: T::AccountId,138 data: CreateCollectionData<T::AccountId>,139 ) -> Result<CollectionId, DispatchError> {140 <PalletCommon<T>>::init_collection(owner, data)141 }142 pub fn destroy_collection(143 collection: FungibleHandle<T>,144 sender: &T::CrossAccountId,145 ) -> DispatchResult {146 let id = collection.id;147148 if Self::collection_has_tokens(id) {149 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());150 }151152 // =========153154 PalletCommon::destroy_collection(collection.0, sender)?;155156 <TotalSupply<T>>::remove(id);157 <Balance<T>>::remove_prefix((id,), None);158 <Allowance<T>>::remove_prefix((id,), None);159 Ok(())160 }161162 fn collection_has_tokens(collection_id: CollectionId) -> bool {163 <TotalSupply<T>>::get(collection_id) != 0164 }165166 pub fn burn(167 collection: &FungibleHandle<T>,168 owner: &T::CrossAccountId,169 amount: u128,170 ) -> DispatchResult {171 let total_supply = <TotalSupply<T>>::get(collection.id)172 .checked_sub(amount)173 .ok_or(<CommonError<T>>::TokenValueTooLow)?;174175 let balance = <Balance<T>>::get((collection.id, owner))176 .checked_sub(amount)177 .ok_or(<CommonError<T>>::TokenValueTooLow)?;178179 if collection.permissions.access() == AccessMode::AllowList {180 collection.check_allowlist(owner)?;181 }182183 // =========184185 if balance == 0 {186 <Balance<T>>::remove((collection.id, owner));187 <PalletStructure<T>>::unnest_if_nested(188 owner,189 collection.id,190 TokenId::default()191 );192 } else {193 <Balance<T>>::insert((collection.id, owner), balance);194 }195 <TotalSupply<T>>::insert(collection.id, total_supply);196197 <PalletEvm<T>>::deposit_log(198 ERC20Events::Transfer {199 from: *owner.as_eth(),200 to: H160::default(),201 value: amount.into(),202 }203 .to_log(collection_id_to_address(collection.id)),204 );205 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(206 collection.id,207 TokenId::default(),208 owner.clone(),209 amount,210 ));211 Ok(())212 }213214 pub fn transfer(215 collection: &FungibleHandle<T>,216 from: &T::CrossAccountId,217 to: &T::CrossAccountId,218 amount: u128,219 nesting_budget: &dyn Budget,220 ) -> DispatchResult {221 ensure!(222 collection.limits.transfers_enabled(),223 <CommonError<T>>::TransferNotAllowed,224 );225226 if collection.permissions.access() == AccessMode::AllowList {227 collection.check_allowlist(from)?;228 collection.check_allowlist(to)?;229 }230 <PalletCommon<T>>::ensure_correct_receiver(to)?;231232 let balance_from = <Balance<T>>::get((collection.id, from))233 .checked_sub(amount)234 .ok_or(<CommonError<T>>::TokenValueTooLow)?;235 let balance_to = if from != to {236 Some(237 <Balance<T>>::get((collection.id, to))238 .checked_add(amount)239 .ok_or(ArithmeticError::Overflow)?,240 )241 } else {242 None243 };244245 // =========246247 <PalletStructure<T>>::nest_if_sent_to_token(248 from.clone(),249 to,250 collection.id,251 TokenId::default(),252 nesting_budget253 )?;254255 if let Some(balance_to) = balance_to {256 // from != to257 if balance_from == 0 {258 <Balance<T>>::remove((collection.id, from));259 <PalletStructure<T>>::unnest_if_nested(260 from,261 collection.id,262 TokenId::default()263 );264 } else {265 <Balance<T>>::insert((collection.id, from), balance_from);266 }267 <Balance<T>>::insert((collection.id, to), balance_to);268 }269270 <PalletEvm<T>>::deposit_log(271 ERC20Events::Transfer {272 from: *from.as_eth(),273 to: *to.as_eth(),274 value: amount.into(),275 }276 .to_log(collection_id_to_address(collection.id)),277 );278 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(279 collection.id,280 TokenId::default(),281 from.clone(),282 to.clone(),283 amount,284 ));285 Ok(())286 }287288 pub fn create_multiple_items(289 collection: &FungibleHandle<T>,290 sender: &T::CrossAccountId,291 data: BTreeMap<T::CrossAccountId, u128>,292 nesting_budget: &dyn Budget,293 ) -> DispatchResult {294 if !collection.is_owner_or_admin(sender) {295 ensure!(296 collection.permissions.mint_mode(),297 <CommonError<T>>::PublicMintingNotAllowed298 );299 collection.check_allowlist(sender)?;300301 for (owner, _) in data.iter() {302 collection.check_allowlist(owner)?;303 }304 }305306 let total_supply = data307 .iter()308 .map(|(_, v)| *v)309 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {310 acc.checked_add(v)311 })312 .ok_or(ArithmeticError::Overflow)?;313314 let mut balances = data;315 for (k, v) in balances.iter_mut() {316 *v = <Balance<T>>::get((collection.id, &k))317 .checked_add(*v)318 .ok_or(ArithmeticError::Overflow)?;319 }320321 for (to, _) in balances.iter() {322 <PalletStructure<T>>::check_nesting(323 sender.clone(),324 to,325 collection.id,326 TokenId::default(),327 nesting_budget,328 )?;329 }330331 // =========332333 <TotalSupply<T>>::insert(collection.id, total_supply);334 for (user, amount) in balances {335 <Balance<T>>::insert((collection.id, &user), amount);336 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId::default());337 <PalletEvm<T>>::deposit_log(338 ERC20Events::Transfer {339 from: H160::default(),340 to: *user.as_eth(),341 value: amount.into(),342 }343 .to_log(collection_id_to_address(collection.id)),344 );345 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(346 collection.id,347 TokenId::default(),348 user.clone(),349 amount,350 ));351 }352353 Ok(())354 }355356 fn set_allowance_unchecked(357 collection: &FungibleHandle<T>,358 owner: &T::CrossAccountId,359 spender: &T::CrossAccountId,360 amount: u128,361 ) {362 if amount == 0 {363 <Allowance<T>>::remove((collection.id, owner, spender));364 } else {365 <Allowance<T>>::insert((collection.id, owner, spender), amount);366 }367368 <PalletEvm<T>>::deposit_log(369 ERC20Events::Approval {370 owner: *owner.as_eth(),371 spender: *spender.as_eth(),372 value: amount.into(),373 }374 .to_log(collection_id_to_address(collection.id)),375 );376 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(377 collection.id,378 TokenId(0),379 owner.clone(),380 spender.clone(),381 amount,382 ));383 }384385 pub fn set_allowance(386 collection: &FungibleHandle<T>,387 owner: &T::CrossAccountId,388 spender: &T::CrossAccountId,389 amount: u128,390 ) -> DispatchResult {391 if collection.permissions.access() == AccessMode::AllowList {392 collection.check_allowlist(owner)?;393 collection.check_allowlist(spender)?;394 }395396 if <Balance<T>>::get((collection.id, owner)) < amount {397 ensure!(398 collection.ignores_owned_amount(owner),399 <CommonError<T>>::CantApproveMoreThanOwned400 );401 }402403 // =========404405 Self::set_allowance_unchecked(collection, owner, spender, amount);406 Ok(())407 }408409 fn check_allowed(410 collection: &FungibleHandle<T>,411 spender: &T::CrossAccountId,412 from: &T::CrossAccountId,413 amount: u128,414 nesting_budget: &dyn Budget,415 ) -> Result<Option<u128>, DispatchError> {416 if spender.conv_eq(from) {417 return Ok(None);418 }419 if collection.permissions.access() == AccessMode::AllowList {420 // `from`, `to` checked in [`transfer`]421 collection.check_allowlist(spender)?;422 }423 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {424 // TODO: should collection owner be allowed to perform this transfer?425 ensure!(426 <PalletStructure<T>>::check_indirectly_owned(427 spender.clone(),428 source.0,429 source.1,430 None,431 nesting_budget432 )?,433 <CommonError<T>>::ApprovedValueTooLow,434 );435 return Ok(None);436 }437 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);438 if allowance.is_none() {439 ensure!(440 collection.ignores_allowance(spender),441 <CommonError<T>>::ApprovedValueTooLow442 );443 }444445 Ok(allowance)446 }447448 pub fn transfer_from(449 collection: &FungibleHandle<T>,450 spender: &T::CrossAccountId,451 from: &T::CrossAccountId,452 to: &T::CrossAccountId,453 amount: u128,454 nesting_budget: &dyn Budget,455 ) -> DispatchResult {456 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;457458 // =========459460 Self::transfer(collection, from, to, amount, nesting_budget)?;461 if let Some(allowance) = allowance {462 Self::set_allowance_unchecked(collection, from, spender, allowance);463 }464 Ok(())465 }466467 pub fn burn_from(468 collection: &FungibleHandle<T>,469 spender: &T::CrossAccountId,470 from: &T::CrossAccountId,471 amount: u128,472 nesting_budget: &dyn Budget,473 ) -> DispatchResult {474 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;475476 // =========477478 Self::burn(collection, from, amount)?;479 if let Some(allowance) = allowance {480 Self::set_allowance_unchecked(collection, from, spender, allowance);481 }482 Ok(())483 }484485 /// Delegated to `create_multiple_items`486 pub fn create_item(487 collection: &FungibleHandle<T>,488 sender: &T::CrossAccountId,489 data: CreateItemData<T>,490 nesting_budget: &dyn Budget,491 ) -> DispatchResult {492 Self::create_multiple_items(493 collection,494 sender,495 [(data.0, data.1)].into_iter().collect(),496 nesting_budget,497 )498 }499}pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -353,6 +353,22 @@
<Pallet<T>>::check_nesting(self, sender, from, under, budget)
}
+ fn nest(
+ &self,
+ under: TokenId,
+ to_nest: (CollectionId, TokenId)
+ ) {
+ <Pallet<T>>::nest((self.id, under), to_nest);
+ }
+
+ fn unnest(
+ &self,
+ under: TokenId,
+ to_unnest: (CollectionId, TokenId)
+ ) {
+ <Pallet<T>>::unnest((self.id, under), to_unnest);
+ }
+
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
<Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -27,7 +27,7 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
- dispatch::CollectionDispatch, eth::collection_id_to_address,
+ eth::collection_id_to_address,
};
use pallet_structure::Pallet as PalletStructure;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -76,6 +76,8 @@
NotNonfungibleDataUsedToMintFungibleCollectionToken,
/// Used amount > 1 with NFT
NonfungibleItemsHaveNoAmount,
+ /// Unable to burn NFT with children
+ CantBurnNftWithChildren,
}
#[pallet::config]
@@ -127,7 +129,20 @@
QueryKind = ValueQuery,
>;
+ /// Used to enumerate token's children
#[pallet::storage]
+ #[pallet::getter(fn token_children)]
+ pub type TokenChildren<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Twox64Concat, TokenId>,
+ Key<Twox64Concat, (CollectionId, TokenId)>,
+ ),
+ Value = bool,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
pub type AccountBalance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
@@ -277,11 +292,16 @@
) -> DispatchResult {
let id = collection.id;
+ if Self::collection_has_tokens(id) {
+ return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+ }
+
// =========
PalletCommon::destroy_collection(collection.0, sender)?;
<TokenData<T>>::remove_prefix((id,), None);
+ <TokenChildren<T>>::remove_prefix((id,), None);
<Owned<T>>::remove_prefix((id,), None);
<TokensMinted<T>>::remove(id);
<TokensBurnt<T>>::remove(id);
@@ -307,6 +327,10 @@
collection.check_allowlist(sender)?;
}
+ if Self::token_has_children(collection.id, token) {
+ return Err(<Error<T>>::CantBurnNftWithChildren.into());
+ }
+
let burnt = <TokensBurnt<T>>::get(collection.id)
.checked_add(1)
.ok_or(ArithmeticError::Overflow)?;
@@ -315,13 +339,20 @@
.checked_sub(1)
.ok_or(ArithmeticError::Overflow)?;
+ // =========
+
if balance == 0 {
<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));
} else {
<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);
}
- // =========
+ <PalletStructure<T>>::unnest_if_nested(
+ &token_data.owner,
+ collection.id,
+ token
+ );
+
<Owned<T>>::remove((collection.id, &token_data.owner, token));
<TokensBurnt<T>>::insert(collection.id, burnt);
<TokenData<T>>::remove((collection.id, token));
@@ -553,20 +584,21 @@
None
};
- if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
- let handle = <CollectionHandle<T>>::try_get(target.0)?;
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ token,
+ nesting_budget
+ )?;
- dispatch.check_nesting(
- from.clone(),
- (collection.id, token),
- target.1,
- nesting_budget,
- )?;
- }
+ // =========
- // =========
+ <PalletStructure<T>>::unnest_if_nested(
+ from,
+ collection.id,
+ token
+ );
<TokenData<T>>::insert(
(collection.id, token),
@@ -653,17 +685,14 @@
for (i, data) in data.iter().enumerate() {
let token = TokenId(first_token + i as u32 + 1);
- if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {
- let handle = <CollectionHandle<T>>::try_get(target.0)?;
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(
- sender.clone(),
- (collection.id, token),
- target.1,
- nesting_budget,
- )?;
- }
+
+ <PalletStructure<T>>::check_nesting(
+ sender.clone(),
+ &data.owner,
+ collection.id,
+ token,
+ nesting_budget,
+ )?;
}
// =========
@@ -680,6 +709,8 @@
},
);
+ <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));
+
if let Err(e) = Self::set_token_properties(
collection,
sender,
@@ -927,6 +958,33 @@
Ok(())
}
+ fn nest(
+ under: (CollectionId, TokenId),
+ to_nest: (CollectionId, TokenId),
+ ) {
+ <TokenChildren<T>>::insert(
+ (under.0, under.1, (to_nest.0, to_nest.1)),
+ true
+ );
+ }
+
+ fn unnest(
+ under: (CollectionId, TokenId),
+ to_unnest: (CollectionId, TokenId),
+ ) {
+ <TokenChildren<T>>::remove(
+ (under.0, under.1, to_unnest)
+ );
+ }
+
+ fn collection_has_tokens(collection_id: CollectionId) -> bool {
+ <TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+ }
+
+ fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {
+ <TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()
+ }
+
/// Delegated to `create_multiple_items`
pub fn create_item(
collection: &NonfungibleHandle<T>,
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -26,6 +26,18 @@
}
}
+pub trait RmrkRebind<T, S> {
+ fn rebind(&self) -> BoundedVec<u8, S>;
+}
+
+impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
+ fn rebind(&self) -> BoundedVec<u8, S> {
+ BoundedVec::<u8, S>::try_from(
+ self.clone().into_inner()
+ ).unwrap_or_default()
+ }
+}
+
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
Regular,
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -313,6 +313,18 @@
fail!(<Error<T>>::RefungibleDisallowsNesting)
}
+ fn nest(
+ &self,
+ _under: TokenId,
+ _to_nest: (CollectionId, TokenId)
+ ) {}
+
+ fn unnest(
+ &self,
+ _under: TokenId,
+ _to_nest: (CollectionId, TokenId)
+ ) {}
+
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
<Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -23,8 +23,7 @@
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
- dispatch::CollectionDispatch,
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
@@ -211,6 +210,10 @@
) -> DispatchResult {
let id = collection.id;
+ if Self::collection_has_tokens(id) {
+ return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+ }
+
// =========
PalletCommon::destroy_collection(collection.0, sender)?;
@@ -226,6 +229,10 @@
Ok(())
}
+ fn collection_has_tokens(collection_id: CollectionId) -> bool {
+ <TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+ }
+
pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
let burnt = <TokensBurnt<T>>::get(collection.id)
.checked_add(1)
@@ -265,6 +272,7 @@
// =========
<Owned<T>>::remove((collection.id, owner, token));
+ <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
<AccountBalance<T>>::insert((collection.id, owner), account_balance);
Self::burn_token(collection, token)?;
<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
@@ -292,6 +300,7 @@
if balance == 0 {
<Owned<T>>::remove((collection.id, owner, token));
+ <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
<Balance<T>>::remove((collection.id, token, owner));
<AccountBalance<T>>::insert((collection.id, owner), account_balance);
} else {
@@ -372,25 +381,25 @@
None
};
- if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
- let handle = <CollectionHandle<T>>::try_get(target.0)?;
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
+ // =========
- dispatch.check_nesting(
- from.clone(),
- (collection.id, token),
- target.1,
- nesting_budget,
- )?;
- }
-
- // =========
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ token,
+ nesting_budget
+ )?;
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
<Balance<T>>::remove((collection.id, token, from));
+ <PalletStructure<T>>::unnest_if_nested(
+ from,
+ collection.id,
+ token
+ );
} else {
<Balance<T>>::insert((collection.id, token, from), balance_from);
}
@@ -488,18 +497,14 @@
for (i, token) in data.iter().enumerate() {
let token_id = TokenId(first_token_id + i as u32 + 1);
for (to, _) in token.users.iter() {
- if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
- let handle = <CollectionHandle<T>>::try_get(target.0)?;
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(
- sender.clone(),
- (collection.id, token_id),
- target.1,
- nesting_budget,
- )?;
- }
+ <PalletStructure<T>>::check_nesting(
+ sender.clone(),
+ to,
+ collection.id,
+ token_id,
+ nesting_budget,
+ )?;
}
}
@@ -519,12 +524,15 @@
const_data: token.const_data,
},
);
+
for (user, amount) in token.users.into_iter() {
if amount == 0 {
continue;
}
<Balance<T>>::insert((collection.id, token_id, &user), amount);
<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
+ <PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId(token_id));
+
// TODO: ERC20 transfer event
<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
collection.id,
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -1,8 +1,9 @@
#![cfg_attr(not(feature = "std"), no_std)]
+use pallet_common::CommonCollectionOperations;
use sp_std::collections::btree_set::BTreeSet;
-use frame_support::dispatch::DispatchError;
+use frame_support::dispatch::{DispatchError, DispatchResult};
use frame_support::fail;
pub use pallet::*;
use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
@@ -155,8 +156,8 @@
budget: &dyn Budget,
) -> Result<bool, DispatchError> {
let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
- Some((collection, token)) => Parent::Token(collection, token),
- None => Parent::User(user),
+ Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+ None => user,
};
// Tried to nest token in itself
@@ -171,10 +172,10 @@
return Err(<Error<T>>::OuroborosDetected.into())
}
// Found needed parent, token is indirecty owned
- v if v == target_parent => return Ok(true),
+ Parent::User(user) if user == target_parent => return Ok(true),
// Token is owned by other user
Parent::User(_) => return Ok(false),
- Parent::TokenNotFound => return Ok(false),
+ Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
// Continue parent chain
Parent::Token(_, _) => {}
}
@@ -182,4 +183,113 @@
Err(<Error<T>>::DepthLimit.into())
}
+
+ pub fn check_nesting(
+ from: T::CrossAccountId,
+ under: &T::CrossAccountId,
+ collection_id: CollectionId,
+ token_id: TokenId,
+ nesting_budget: &dyn Budget
+ ) -> DispatchResult {
+ Self::try_exec_if_owner_is_valid_nft(
+ under,
+ |d, parent_id| d.check_nesting(
+ from,
+ (collection_id, token_id),
+ parent_id,
+ nesting_budget
+ )
+ )
+ }
+
+ pub fn nest_if_sent_to_token(
+ from: T::CrossAccountId,
+ under: &T::CrossAccountId,
+ collection_id: CollectionId,
+ token_id: TokenId,
+ nesting_budget: &dyn Budget
+ ) -> DispatchResult {
+ Self::try_exec_if_owner_is_valid_nft(
+ under,
+ |d, parent_id| {
+ d.check_nesting(
+ from,
+ (collection_id, token_id),
+ parent_id,
+ nesting_budget
+ )?;
+
+ d.nest(parent_id, (collection_id, token_id));
+
+ Ok(())
+ }
+ )
+ }
+
+ pub fn nest_if_sent_to_token_unchecked(
+ owner: &T::CrossAccountId,
+ collection_id: CollectionId,
+ token_id: TokenId
+ ) {
+ Self::exec_if_owner_is_valid_nft(
+ owner,
+ |d, parent_id| d.nest(
+ parent_id,
+ (collection_id, token_id)
+ )
+ );
+ }
+
+ pub fn unnest_if_nested(
+ owner: &T::CrossAccountId,
+ collection_id: CollectionId,
+ token_id: TokenId
+ ) {
+ Self::exec_if_owner_is_valid_nft(
+ owner,
+ |d, parent_id| d.unnest(
+ parent_id,
+ (collection_id, token_id)
+ )
+ );
+ }
+
+ fn exec_if_owner_is_valid_nft(
+ account: &T::CrossAccountId,
+ action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId)
+ ) {
+ Self::try_exec_if_owner_is_valid_nft(
+ account,
+ |d, id| {
+ action(d, id);
+ Ok(())
+ }
+ ).unwrap();
+ }
+
+ fn try_exec_if_owner_is_valid_nft(
+ account: &T::CrossAccountId,
+ action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult
+ ) -> DispatchResult {
+ let account = T::CrossTokenAddressMapping::address_to_token(account);
+
+ if account.is_none() {
+ return Ok(());
+ }
+
+ let account = account.unwrap();
+
+ let handle = <CollectionHandle<T>>::try_get(account.0);
+
+ if handle.is_err() {
+ return Ok(());
+ }
+
+ let handle = handle.unwrap();
+
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+
+ action(dispatch, account.1)
+ }
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -55,6 +55,8 @@
pub mod weights;
use weights::WeightInfo;
+const NESTING_BUDGET: u32 = 5;
+
decl_error! {
/// Error for non-fungible-token module.
pub enum Error for Module<T: Config> {
@@ -569,7 +571,7 @@
#[transactional]
pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))
}
@@ -597,7 +599,7 @@
pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
}
@@ -678,7 +680,7 @@
#[transactional]
pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))
}
@@ -758,7 +760,7 @@
#[transactional]
pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))
}
@@ -790,7 +792,7 @@
#[transactional]
pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))
}
@@ -841,7 +843,7 @@
#[transactional]
pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let budget = budget::Value::new(2);
+ let budget = budget::Value::new(NESTING_BUDGET);
dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
}
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -25,7 +25,7 @@
dispatch_unique_runtime!(collection.token_owner(token))
}
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
- let budget = up_data_structs::budget::Value::new(5);
+ let budget = up_data_structs::budget::Value::new(10);
Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
}
@@ -142,7 +142,7 @@
}
fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind}};
let collection_id = CollectionId(collection_id);
let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {
@@ -156,7 +156,7 @@
issuer: collection.owner.clone(),
metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),
max: collection.limits.token_limit,
- symbol: collection.token_prefix.decode_or_default(),
+ symbol: collection.token_prefix.rebind(),
nfts_count
}))
}
@@ -204,22 +204,21 @@
}
fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {
- use up_data_structs::mapping::TokenAddressMapping;
-
let collection_id = CollectionId(collection_id);
let nft_id = TokenId(nft_id);
if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }
- let cross_account_id = CrossAccountId::from_eth(
- EvmTokenAddressMapping::token_to_address(collection_id, nft_id)
- );
-
Ok(
- pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))
- .map(|(child_id, _)| RmrkNftChild {
- collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not
- nft_id: child_id.0,
- }).collect()
+ pallet_nonfungible::TokenChildren::<Runtime>::iter_prefix((collection_id, nft_id))
+ .filter_map(|(child_id, is_child)|
+ match is_child {
+ true => Some(RmrkNftChild {
+ collection_id: child_id.0.0,
+ nft_id: child_id.1.0,
+ }),
+ false => None,
+ }
+ ).collect()
)
}
@@ -332,7 +331,7 @@
fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
use pallet_proxy_rmrk_core::{
- RmrkProperty, misc::{CollectionType, RmrkDecode},
+ RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind},
};
let collection_id = CollectionId(base_id);
@@ -344,7 +343,7 @@
Ok(Some(RmrkBaseInfo {
issuer: collection.owner.clone(),
base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),
- symbol: collection.token_prefix.decode_or_default(),
+ symbol: collection.token_prefix.rebind(),
}))
}
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -41,7 +41,7 @@
// Create a token to be nested
const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
+
// Nest
await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
@@ -111,8 +111,8 @@
// Create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
))).to.not.be.rejected;
@@ -134,8 +134,8 @@
// Create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
))).to.not.be.rejected;
@@ -158,8 +158,8 @@
// Create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
+ collectionRFT,
+ targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
))).to.not.be.rejected;
@@ -181,7 +181,7 @@
// Create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
+ collectionRFT,
targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
))).to.not.be.rejected;
@@ -207,17 +207,29 @@
await setCollectionPermissionsExceptSuccess(alice, collection, {nesting: 'Owner'});
const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+ const maxNestingLevel = 5;
+ let prevToken = targetToken;
+
// Create a nested-token matryoshka
- const nestedToken1 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
- const nestedToken2 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, nestedToken1)});
- // The nesting depth is limited by 2
+ for (let i = 0; i < maxNestingLevel; i++) {
+ const nestedToken = await createItemExpectSuccess(
+ alice,
+ collection,
+ 'NFT',
+ {Ethereum: tokenIdToAddress(collection, prevToken)},
+ );
+
+ prevToken = nestedToken;
+ }
+
+ // The nesting depth is limited by `maxNestingLevel`
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, nestedToken2)},
+ collection,
+ {Ethereum: tokenIdToAddress(collection, prevToken)},
{nft: {const_data: [], variable_data: []}} as any,
)), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
- expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
+ expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});
});
});
@@ -231,8 +243,8 @@
// Try to create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
+ collection,
+ {Ethereum: tokenIdToAddress(collection, targetToken)},
{nft: {const_data: [], variable_data: []}} as any,
)), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
@@ -259,8 +271,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
+ collection,
+ {Ethereum: tokenIdToAddress(collection, targetToken)},
{nft: {const_data: [], variable_data: []}} as any,
)), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -285,8 +297,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
+ collection,
+ {Ethereum: tokenIdToAddress(collection, targetToken)},
{nft: {const_data: [], variable_data: []}} as any,
)), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -307,8 +319,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collection,
- {Ethereum: tokenIdToAddress(collection, targetToken)},
+ collection,
+ {Ethereum: tokenIdToAddress(collection, targetToken)},
{nft: {const_data: [], variable_data: []}} as any,
)), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
@@ -332,11 +344,11 @@
// Try to create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
)), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
-
+
// Create a token to be nested
const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
// Try to nest
@@ -366,8 +378,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
)), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -393,8 +405,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
)), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -417,8 +429,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionFT,
- targetAddress,
+ collectionFT,
+ targetAddress,
{Fungible: {Value: 10}},
)), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
@@ -441,8 +453,8 @@
// Create a nested token
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
+ collectionRFT,
+ targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
)), 'while creating a nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
@@ -477,8 +489,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
+ collectionRFT,
+ targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
)), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -504,8 +516,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
+ collectionRFT,
+ targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
)), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
@@ -528,8 +540,8 @@
// Try to create a nested token in the wrong collection
await expect(executeTransaction(api, alice, api.tx.unique.createItem(
- collectionRFT,
- targetAddress,
+ collectionRFT,
+ targetAddress,
{ReFungible: {const_data: [], pieces: 100}},
)), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);