difftreelog
doc: add documentation for nonfungible palette
in: master
2 files changed
pallets/nonfungible/src/common.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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};20use up_data_structs::{21 TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22 PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,26 weights::WeightInfo as _,27};28use sp_runtime::DispatchError;29use sp_std::vec::Vec;3031use crate::{32 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,33 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,34};3536pub struct CommonWeights<T: Config>(PhantomData<T>);37impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {38 fn create_item() -> Weight {39 <SelfWeightOf<T>>::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::NFT(t) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)46 + t.iter()47 .map(|t| {48 if t.properties.len() > 0 {49 Self::set_token_properties(t.properties.len() as u32)50 } else {51 052 }53 })54 .sum::<u64>()55 }56 _ => 0,57 }58 }5960 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {61 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)62 + data63 .iter()64 .filter_map(|t| match t {65 up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {66 Some(Self::set_token_properties(n.properties.len() as u32))67 }68 _ => None,69 })70 .sum::<u64>()71 }7273 fn burn_item() -> Weight {74 <SelfWeightOf<T>>::burn_item()75 }7677 fn set_collection_properties(amount: u32) -> Weight {78 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)79 }8081 fn delete_collection_properties(amount: u32) -> Weight {82 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)83 }8485 fn set_token_properties(amount: u32) -> Weight {86 <SelfWeightOf<T>>::set_token_properties(amount)87 }8889 fn delete_token_properties(amount: u32) -> Weight {90 <SelfWeightOf<T>>::delete_token_properties(amount)91 }9293 fn set_token_property_permissions(amount: u32) -> Weight {94 <SelfWeightOf<T>>::set_token_property_permissions(amount)95 }9697 fn transfer() -> Weight {98 <SelfWeightOf<T>>::transfer()99 }100101 fn approve() -> Weight {102 <SelfWeightOf<T>>::approve()103 }104105 fn transfer_from() -> Weight {106 <SelfWeightOf<T>>::transfer_from()107 }108109 fn burn_from() -> Weight {110 <SelfWeightOf<T>>::burn_from()111 }112113 fn burn_recursively_self_raw() -> Weight {114 <SelfWeightOf<T>>::burn_recursively_self_raw()115 }116117 fn burn_recursively_breadth_raw(amount: u32) -> Weight {118 <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)119 .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))120 }121}122123fn map_create_data<T: Config>(124 data: up_data_structs::CreateItemData,125 to: &T::CrossAccountId,126) -> Result<CreateItemData<T>, DispatchError> {127 match data {128 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {129 properties: data.properties,130 owner: to.clone(),131 }),132 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),133 }134}135136impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {137 fn create_item(138 &self,139 sender: T::CrossAccountId,140 to: T::CrossAccountId,141 data: up_data_structs::CreateItemData,142 nesting_budget: &dyn Budget,143 ) -> DispatchResultWithPostInfo {144 with_weight(145 <Pallet<T>>::create_item(146 self,147 &sender,148 map_create_data::<T>(data, &to)?,149 nesting_budget,150 ),151 <CommonWeights<T>>::create_item(),152 )153 }154155 fn create_multiple_items(156 &self,157 sender: T::CrossAccountId,158 to: T::CrossAccountId,159 data: Vec<up_data_structs::CreateItemData>,160 nesting_budget: &dyn Budget,161 ) -> DispatchResultWithPostInfo {162 let weight = <CommonWeights<T>>::create_multiple_items(&data);163 let data = data164 .into_iter()165 .map(|d| map_create_data::<T>(d, &to))166 .collect::<Result<Vec<_>, DispatchError>>()?;167168 with_weight(169 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),170 weight,171 )172 }173174 fn create_multiple_items_ex(175 &self,176 sender: <T>::CrossAccountId,177 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,178 nesting_budget: &dyn Budget,179 ) -> DispatchResultWithPostInfo {180 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);181 let data = match data {182 up_data_structs::CreateItemExData::NFT(nft) => nft,183 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),184 };185186 with_weight(187 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),188 weight,189 )190 }191192 fn set_collection_properties(193 &self,194 sender: T::CrossAccountId,195 properties: Vec<Property>,196 ) -> DispatchResultWithPostInfo {197 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);198199 with_weight(200 <Pallet<T>>::set_collection_properties(self, &sender, properties),201 weight,202 )203 }204205 fn delete_collection_properties(206 &self,207 sender: &T::CrossAccountId,208 property_keys: Vec<PropertyKey>,209 ) -> DispatchResultWithPostInfo {210 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);211212 with_weight(213 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),214 weight,215 )216 }217218 fn set_token_properties(219 &self,220 sender: T::CrossAccountId,221 token_id: TokenId,222 properties: Vec<Property>,223 nesting_budget: &dyn Budget,224 ) -> DispatchResultWithPostInfo {225 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);226227 with_weight(228 <Pallet<T>>::set_token_properties(229 self,230 &sender,231 token_id,232 properties.into_iter(),233 false,234 nesting_budget,235 ),236 weight,237 )238 }239240 fn delete_token_properties(241 &self,242 sender: T::CrossAccountId,243 token_id: TokenId,244 property_keys: Vec<PropertyKey>,245 nesting_budget: &dyn Budget,246 ) -> DispatchResultWithPostInfo {247 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);248249 with_weight(250 <Pallet<T>>::delete_token_properties(251 self,252 &sender,253 token_id,254 property_keys.into_iter(),255 nesting_budget,256 ),257 weight,258 )259 }260261 fn set_token_property_permissions(262 &self,263 sender: &T::CrossAccountId,264 property_permissions: Vec<PropertyKeyPermission>,265 ) -> DispatchResultWithPostInfo {266 let weight =267 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);268269 with_weight(270 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),271 weight,272 )273 }274275 fn burn_item(276 &self,277 sender: T::CrossAccountId,278 token: TokenId,279 amount: u128,280 ) -> DispatchResultWithPostInfo {281 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);282 if amount == 1 {283 with_weight(284 <Pallet<T>>::burn(self, &sender, token),285 <CommonWeights<T>>::burn_item(),286 )287 } else {288 Ok(().into())289 }290 }291292 fn burn_item_recursively(293 &self,294 sender: T::CrossAccountId,295 token: TokenId,296 self_budget: &dyn Budget,297 breadth_budget: &dyn Budget,298 ) -> DispatchResultWithPostInfo {299 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)300 }301302 fn transfer(303 &self,304 from: T::CrossAccountId,305 to: T::CrossAccountId,306 token: TokenId,307 amount: u128,308 nesting_budget: &dyn Budget,309 ) -> DispatchResultWithPostInfo {310 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);311 if amount == 1 {312 with_weight(313 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),314 <CommonWeights<T>>::transfer(),315 )316 } else {317 Ok(().into())318 }319 }320321 fn approve(322 &self,323 sender: T::CrossAccountId,324 spender: T::CrossAccountId,325 token: TokenId,326 amount: u128,327 ) -> DispatchResultWithPostInfo {328 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);329330 with_weight(331 if amount == 1 {332 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))333 } else {334 <Pallet<T>>::set_allowance(self, &sender, token, None)335 },336 <CommonWeights<T>>::approve(),337 )338 }339340 fn transfer_from(341 &self,342 sender: T::CrossAccountId,343 from: T::CrossAccountId,344 to: T::CrossAccountId,345 token: TokenId,346 amount: u128,347 nesting_budget: &dyn Budget,348 ) -> DispatchResultWithPostInfo {349 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);350351 if amount == 1 {352 with_weight(353 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),354 <CommonWeights<T>>::transfer_from(),355 )356 } else {357 Ok(().into())358 }359 }360361 fn burn_from(362 &self,363 sender: T::CrossAccountId,364 from: T::CrossAccountId,365 token: TokenId,366 amount: u128,367 nesting_budget: &dyn Budget,368 ) -> DispatchResultWithPostInfo {369 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);370371 if amount == 1 {372 with_weight(373 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),374 <CommonWeights<T>>::burn_from(),375 )376 } else {377 Ok(().into())378 }379 }380381 fn check_nesting(382 &self,383 sender: T::CrossAccountId,384 from: (CollectionId, TokenId),385 under: TokenId,386 nesting_budget: &dyn Budget,387 ) -> sp_runtime::DispatchResult {388 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)389 }390391 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {392 <Pallet<T>>::nest((self.id, under), to_nest);393 }394395 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {396 <Pallet<T>>::unnest((self.id, under), to_unnest);397 }398399 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {400 <Owned<T>>::iter_prefix((self.id, account))401 .map(|(id, _)| id)402 .collect()403 }404405 fn collection_tokens(&self) -> Vec<TokenId> {406 <TokenData<T>>::iter_prefix((self.id,))407 .map(|(id, _)| id)408 .collect()409 }410411 fn token_exists(&self, token: TokenId) -> bool {412 <Pallet<T>>::token_exists(self, token)413 }414415 fn last_token_id(&self) -> TokenId {416 TokenId(<TokensMinted<T>>::get(self.id))417 }418419 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {420 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)421 }422423 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {424 <Pallet<T>>::token_properties((self.id, token_id))425 .get(key)426 .cloned()427 }428429 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {430 let properties = <Pallet<T>>::token_properties((self.id, token_id));431432 keys.map(|keys| {433 keys.into_iter()434 .filter_map(|key| {435 properties.get(&key).map(|value| Property {436 key,437 value: value.clone(),438 })439 })440 .collect()441 })442 .unwrap_or_else(|| {443 properties444 .into_iter()445 .map(|(key, value)| Property { key, value })446 .collect()447 })448 }449450 fn total_supply(&self) -> u32 {451 <Pallet<T>>::total_supply(self)452 }453454 fn account_balance(&self, account: T::CrossAccountId) -> u32 {455 <AccountBalance<T>>::get((self.id, account))456 }457458 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {459 if <TokenData<T>>::get((self.id, token))460 .map(|a| a.owner == account)461 .unwrap_or(false)462 {463 1464 } else {465 0466 }467 }468469 fn allowance(470 &self,471 sender: T::CrossAccountId,472 spender: T::CrossAccountId,473 token: TokenId,474 ) -> u128 {475 if <TokenData<T>>::get((self.id, token))476 .map(|a| a.owner != sender)477 .unwrap_or(true)478 {479 0480 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {481 1482 } else {483 0484 }485 }486487 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {488 None489 }490491 fn total_pieces(&self, token: TokenId) -> Option<u128> {492 if <TokenData<T>>::contains_key((self.id, token)) {493 Some(1)494 } else {495 None496 }497 }498}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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};20use up_data_structs::{21 TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22 PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,26 weights::WeightInfo as _,27};28use sp_runtime::DispatchError;29use sp_std::vec::Vec;3031use crate::{32 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,33 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,34};3536pub struct CommonWeights<T: Config>(PhantomData<T>);37impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {38 fn create_item() -> Weight {39 <SelfWeightOf<T>>::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::NFT(t) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)46 + t.iter()47 .map(|t| {48 if t.properties.len() > 0 {49 Self::set_token_properties(t.properties.len() as u32)50 } else {51 052 }53 })54 .sum::<u64>()55 }56 _ => 0,57 }58 }5960 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {61 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)62 + data63 .iter()64 .filter_map(|t| match t {65 up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {66 Some(Self::set_token_properties(n.properties.len() as u32))67 }68 _ => None,69 })70 .sum::<u64>()71 }7273 fn burn_item() -> Weight {74 <SelfWeightOf<T>>::burn_item()75 }7677 fn set_collection_properties(amount: u32) -> Weight {78 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)79 }8081 fn delete_collection_properties(amount: u32) -> Weight {82 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)83 }8485 fn set_token_properties(amount: u32) -> Weight {86 <SelfWeightOf<T>>::set_token_properties(amount)87 }8889 fn delete_token_properties(amount: u32) -> Weight {90 <SelfWeightOf<T>>::delete_token_properties(amount)91 }9293 fn set_token_property_permissions(amount: u32) -> Weight {94 <SelfWeightOf<T>>::set_token_property_permissions(amount)95 }9697 fn transfer() -> Weight {98 <SelfWeightOf<T>>::transfer()99 }100101 fn approve() -> Weight {102 <SelfWeightOf<T>>::approve()103 }104105 fn transfer_from() -> Weight {106 <SelfWeightOf<T>>::transfer_from()107 }108109 fn burn_from() -> Weight {110 <SelfWeightOf<T>>::burn_from()111 }112113 fn burn_recursively_self_raw() -> Weight {114 <SelfWeightOf<T>>::burn_recursively_self_raw()115 }116117 fn burn_recursively_breadth_raw(amount: u32) -> Weight {118 <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)119 .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))120 }121}122123fn map_create_data<T: Config>(124 data: up_data_structs::CreateItemData,125 to: &T::CrossAccountId,126) -> Result<CreateItemData<T>, DispatchError> {127 match data {128 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {129 properties: data.properties,130 owner: to.clone(),131 }),132 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),133 }134}135136/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete137/// methods and adds weight info.138impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {139 fn create_item(140 &self,141 sender: T::CrossAccountId,142 to: T::CrossAccountId,143 data: up_data_structs::CreateItemData,144 nesting_budget: &dyn Budget,145 ) -> DispatchResultWithPostInfo {146 with_weight(147 <Pallet<T>>::create_item(148 self,149 &sender,150 map_create_data::<T>(data, &to)?,151 nesting_budget,152 ),153 <CommonWeights<T>>::create_item(),154 )155 }156157 fn create_multiple_items(158 &self,159 sender: T::CrossAccountId,160 to: T::CrossAccountId,161 data: Vec<up_data_structs::CreateItemData>,162 nesting_budget: &dyn Budget,163 ) -> DispatchResultWithPostInfo {164 let weight = <CommonWeights<T>>::create_multiple_items(&data);165 let data = data166 .into_iter()167 .map(|d| map_create_data::<T>(d, &to))168 .collect::<Result<Vec<_>, DispatchError>>()?;169170 with_weight(171 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),172 weight,173 )174 }175176 fn create_multiple_items_ex(177 &self,178 sender: <T>::CrossAccountId,179 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,180 nesting_budget: &dyn Budget,181 ) -> DispatchResultWithPostInfo {182 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);183 let data = match data {184 up_data_structs::CreateItemExData::NFT(nft) => nft,185 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),186 };187188 with_weight(189 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),190 weight,191 )192 }193194 fn set_collection_properties(195 &self,196 sender: T::CrossAccountId,197 properties: Vec<Property>,198 ) -> DispatchResultWithPostInfo {199 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);200201 with_weight(202 <Pallet<T>>::set_collection_properties(self, &sender, properties),203 weight,204 )205 }206207 fn delete_collection_properties(208 &self,209 sender: &T::CrossAccountId,210 property_keys: Vec<PropertyKey>,211 ) -> DispatchResultWithPostInfo {212 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);213214 with_weight(215 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),216 weight,217 )218 }219220 fn set_token_properties(221 &self,222 sender: T::CrossAccountId,223 token_id: TokenId,224 properties: Vec<Property>,225 nesting_budget: &dyn Budget,226 ) -> DispatchResultWithPostInfo {227 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);228229 with_weight(230 <Pallet<T>>::set_token_properties(231 self,232 &sender,233 token_id,234 properties.into_iter(),235 false,236 nesting_budget,237 ),238 weight,239 )240 }241242 fn delete_token_properties(243 &self,244 sender: T::CrossAccountId,245 token_id: TokenId,246 property_keys: Vec<PropertyKey>,247 nesting_budget: &dyn Budget,248 ) -> DispatchResultWithPostInfo {249 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);250251 with_weight(252 <Pallet<T>>::delete_token_properties(253 self,254 &sender,255 token_id,256 property_keys.into_iter(),257 nesting_budget,258 ),259 weight,260 )261 }262263 fn set_token_property_permissions(264 &self,265 sender: &T::CrossAccountId,266 property_permissions: Vec<PropertyKeyPermission>,267 ) -> DispatchResultWithPostInfo {268 let weight =269 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);270271 with_weight(272 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),273 weight,274 )275 }276277 fn burn_item(278 &self,279 sender: T::CrossAccountId,280 token: TokenId,281 amount: u128,282 ) -> DispatchResultWithPostInfo {283 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);284 if amount == 1 {285 with_weight(286 <Pallet<T>>::burn(self, &sender, token),287 <CommonWeights<T>>::burn_item(),288 )289 } else {290 Ok(().into())291 }292 }293294 fn burn_item_recursively(295 &self,296 sender: T::CrossAccountId,297 token: TokenId,298 self_budget: &dyn Budget,299 breadth_budget: &dyn Budget,300 ) -> DispatchResultWithPostInfo {301 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)302 }303304 fn transfer(305 &self,306 from: T::CrossAccountId,307 to: T::CrossAccountId,308 token: TokenId,309 amount: u128,310 nesting_budget: &dyn Budget,311 ) -> DispatchResultWithPostInfo {312 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);313 if amount == 1 {314 with_weight(315 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),316 <CommonWeights<T>>::transfer(),317 )318 } else {319 Ok(().into())320 }321 }322323 fn approve(324 &self,325 sender: T::CrossAccountId,326 spender: T::CrossAccountId,327 token: TokenId,328 amount: u128,329 ) -> DispatchResultWithPostInfo {330 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);331332 with_weight(333 if amount == 1 {334 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))335 } else {336 <Pallet<T>>::set_allowance(self, &sender, token, None)337 },338 <CommonWeights<T>>::approve(),339 )340 }341342 fn transfer_from(343 &self,344 sender: T::CrossAccountId,345 from: T::CrossAccountId,346 to: T::CrossAccountId,347 token: TokenId,348 amount: u128,349 nesting_budget: &dyn Budget,350 ) -> DispatchResultWithPostInfo {351 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);352353 if amount == 1 {354 with_weight(355 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),356 <CommonWeights<T>>::transfer_from(),357 )358 } else {359 Ok(().into())360 }361 }362363 fn burn_from(364 &self,365 sender: T::CrossAccountId,366 from: T::CrossAccountId,367 token: TokenId,368 amount: u128,369 nesting_budget: &dyn Budget,370 ) -> DispatchResultWithPostInfo {371 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);372373 if amount == 1 {374 with_weight(375 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),376 <CommonWeights<T>>::burn_from(),377 )378 } else {379 Ok(().into())380 }381 }382383 fn check_nesting(384 &self,385 sender: T::CrossAccountId,386 from: (CollectionId, TokenId),387 under: TokenId,388 nesting_budget: &dyn Budget,389 ) -> sp_runtime::DispatchResult {390 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)391 }392393 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {394 <Pallet<T>>::nest((self.id, under), to_nest);395 }396397 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {398 <Pallet<T>>::unnest((self.id, under), to_unnest);399 }400401 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {402 <Owned<T>>::iter_prefix((self.id, account))403 .map(|(id, _)| id)404 .collect()405 }406407 fn collection_tokens(&self) -> Vec<TokenId> {408 <TokenData<T>>::iter_prefix((self.id,))409 .map(|(id, _)| id)410 .collect()411 }412413 fn token_exists(&self, token: TokenId) -> bool {414 <Pallet<T>>::token_exists(self, token)415 }416417 fn last_token_id(&self) -> TokenId {418 TokenId(<TokensMinted<T>>::get(self.id))419 }420421 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {422 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)423 }424425 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {426 <Pallet<T>>::token_properties((self.id, token_id))427 .get(key)428 .cloned()429 }430431 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {432 let properties = <Pallet<T>>::token_properties((self.id, token_id));433434 keys.map(|keys| {435 keys.into_iter()436 .filter_map(|key| {437 properties.get(&key).map(|value| Property {438 key,439 value: value.clone(),440 })441 })442 .collect()443 })444 .unwrap_or_else(|| {445 properties446 .into_iter()447 .map(|(key, value)| Property { key, value })448 .collect()449 })450 }451452 fn total_supply(&self) -> u32 {453 <Pallet<T>>::total_supply(self)454 }455456 fn account_balance(&self, account: T::CrossAccountId) -> u32 {457 <AccountBalance<T>>::get((self.id, account))458 }459460 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {461 if <TokenData<T>>::get((self.id, token))462 .map(|a| a.owner == account)463 .unwrap_or(false)464 {465 1466 } else {467 0468 }469 }470471 fn allowance(472 &self,473 sender: T::CrossAccountId,474 spender: T::CrossAccountId,475 token: TokenId,476 ) -> u128 {477 if <TokenData<T>>::get((self.id, token))478 .map(|a| a.owner != sender)479 .unwrap_or(true)480 {481 0482 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {483 1484 } else {485 0486 }487 }488489 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {490 None491 }492493 fn total_pieces(&self, token: TokenId) -> Option<u128> {494 if <TokenData<T>>::contains_key((self.id, token)) {495 Some(1)496 } else {497 None498 }499 }500}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -14,6 +14,81 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+//! # Nonfungible Pallet
+//!
+//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.
+//!
+//! - [`Config`]
+//! - [`NonfungibleHandle`]
+//! - [`Pallet`]
+//! - [`CommonWeights`]
+//!
+//! ## Overview
+//!
+//! The Nonfungible pallet provides functions for:
+//!
+//! - NFT collection creation and removal
+//! - Minting and burning of NFT tokens
+//! - Retrieving account balances
+//! - Transfering NFT tokens
+//! - Setting and checking allowance for NFT tokens
+//! - Setting properties and permissions for NFT collections and tokens
+//! - Nesting and unnesting tokens
+//!
+//! ### Terminology
+//!
+//! - **NFT token:** Non fungible token.
+//!
+//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.
+//! Each collection can define it's own properties, properties for it's tokens and set of permissions.
+//!
+//! - **Balance:** Number of NFT tokens owned by an account
+//!
+//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on
+//!
+//! - **Burning:** The process of “deleting” a token from a collection and from
+//! an account balance of the owner.
+//!
+//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting
+//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in
+//! it's child token i.e. parent-child relationship graph shouldn't have cycles.
+//!
+//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are
+//! attached to a collection. Set of permissions could be defined for each property.
+//!
+//! ### Implementations
+//!
+//! The Nonfungible pallet provides implementations for the following traits. If these traits provide
+//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.
+//!
+//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight
+//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing
+//! with collections
+//!
+//! ## Interface
+//!
+//! ### Dispatchable Functions
+//!
+//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for
+//! some accounts.
+//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.
+//! - `burn` - Burn NFT token owned by account.
+//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.
+//! Nests the NFT token if it is sent to another token.
+//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.
+//! - `set_allowance` - Set allowance for another account.
+//! - `set_token_property` - Set token property value.
+//! - `delete_token_property` - Remove property from the token.
+//! - `set_collection_properties` - Set collection properties.
+//! - `delete_collection_properties` - Remove properties from the collection.
+//! - `set_property_permission` - Set collection property permission.
+//! - `set_token_property_permissions` - Set token property permissions.
+//!
+//! ## Assumptions
+//!
+//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.
+//! * Sender should be in collection's allow list to perform operations on tokens.
+
#![cfg_attr(not(feature = "std"), no_std)]
use erc::ERC721Events;
@@ -102,13 +177,17 @@
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
+ /// Amount of tokens minted for collection.
#[pallet::storage]
pub type TokensMinted<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+
+ /// Amount of burnt tokens for collection.
#[pallet::storage]
pub type TokensBurnt<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+ /// Custom data serialized to bytes for token.
#[pallet::storage]
pub type TokenData<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
@@ -116,6 +195,7 @@
QueryKind = OptionQuery,
>;
+ /// Key-Value map stored for token.
#[pallet::storage]
#[pallet::getter(fn token_properties)]
pub type TokenProperties<T: Config> = StorageNMap<
@@ -125,6 +205,7 @@
OnEmpty = up_data_structs::TokenProperties,
>;
+ /// Custom data that is serialized to bytes and attached to a token property.
#[pallet::storage]
#[pallet::getter(fn token_aux_property)]
pub type TokenAuxProperties<T: Config> = StorageNMap<
@@ -138,7 +219,7 @@
QueryKind = OptionQuery,
>;
- /// Used to enumerate tokens owned by account
+ /// Used to enumerate tokens owned by account.
#[pallet::storage]
pub type Owned<T: Config> = StorageNMap<
Key = (
@@ -150,7 +231,7 @@
QueryKind = ValueQuery,
>;
- /// Used to enumerate token's children
+ /// Used to enumerate token's children.
#[pallet::storage]
#[pallet::getter(fn token_children)]
pub type TokenChildren<T: Config> = StorageNMap<
@@ -163,6 +244,7 @@
QueryKind = ValueQuery,
>;
+ /// Amount of tokens owned by account.
#[pallet::storage]
pub type AccountBalance<T: Config> = StorageNMap<
Key = (
@@ -173,6 +255,7 @@
QueryKind = ValueQuery,
>;
+ /// Allowance set by an owner for a spender for a token.
#[pallet::storage]
pub type Allowance<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
@@ -273,13 +356,21 @@
}
impl<T: Config> Pallet<T> {
+ /// Get number of NFT tokens in collection.
pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {
<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)
}
+
+ /// Check that NFT token exists.
+ ///
+ /// - `token`: Token ID.
pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {
<TokenData<T>>::contains_key((collection.id, token))
}
+ /// Set the token property with the scope.
+ ///
+ /// - `property`: Contains key-value pair.
pub fn set_scoped_token_property(
collection_id: CollectionId,
token_id: TokenId,
@@ -294,6 +385,7 @@
Ok(())
}
+ /// Batch operation to set multiple properties with the same scope.
pub fn set_scoped_token_properties(
collection_id: CollectionId,
token_id: TokenId,
@@ -308,6 +400,9 @@
Ok(())
}
+ /// Add or edit auxiliary data for the property.
+ ///
+ /// - `f`: function that adds or edits auxiliary data.
pub fn try_mutate_token_aux_property<R, E>(
collection_id: CollectionId,
token_id: TokenId,
@@ -318,6 +413,7 @@
<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)
}
+ /// Remove auxiliary data for the property.
pub fn remove_token_aux_property(
collection_id: CollectionId,
token_id: TokenId,
@@ -327,6 +423,9 @@
<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));
}
+ /// Get all auxiliary data in a given scope.
+ ///
+ /// Returns iterator over Property Key - Data pairs.
pub fn iterate_token_aux_properties(
collection_id: CollectionId,
token_id: TokenId,
@@ -335,6 +434,7 @@
<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))
}
+ /// Get ID of the last minted token
pub fn current_token_id(collection_id: CollectionId) -> TokenId {
TokenId(<TokensMinted<T>>::get(collection_id))
}
@@ -342,6 +442,11 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
+ /// Create ТFT collection
+ ///
+ /// `init_collection` will take non-refundable deposit for collection creation.
+ ///
+ /// - `data`: Contains settings for collection limits and permissions.
pub fn init_collection(
owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
@@ -349,6 +454,11 @@
) -> Result<CollectionId, DispatchError> {
<PalletCommon<T>>::init_collection(owner, data, is_external)
}
+
+ /// Destroy ТFT collection
+ ///
+ /// `destroy_collection` will throw error if collection contains any tokens.
+ /// Only owner can destroy collection.
pub fn destroy_collection(
collection: NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -373,6 +483,15 @@
Ok(())
}
+ /// Burn NFT token
+ ///
+ /// `burn` removes `token` from the `collection`, from it's owner and from the parent token
+ /// if the token is nested.
+ /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.
+ /// Also removes all corresponding properties and auxiliary properties.
+ ///
+ /// - `token`: Token that should be burned
+ /// - `collection`: Collection that contains the token
pub fn burn(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -442,6 +561,12 @@
Ok(())
}
+ /// Same as [`burn`] but burns all the tokens that are nested in the token first
+ ///
+ /// - `self_budget`: Limit for searching children in depth.
+ /// - `breadth_budget`: Limit of breadth of searching children.
+ ///
+ /// [`burn`]: struct.Pallet.html#method.burn
#[transactional]
pub fn burn_recursively(
collection: &NonfungibleHandle<T>,
@@ -481,6 +606,14 @@
})
}
+ /// Batch operation to add, edit or remove properties for the token
+ ///
+ /// All affected properties should have mutable permission and sender should have
+ /// permission to edit those properties.
+ ///
+ /// - `nesting_budget`: Limit for searching parents in depth to check ownership.
+ /// - `is_token_create`: Indicates that method is called during token initialization.
+ /// Allows to bypass ownership check.
#[transactional]
fn modify_token_properties(
collection: &NonfungibleHandle<T>,
@@ -574,6 +707,11 @@
Ok(())
}
+ /// Batch operation to add or edit properties for the token
+ ///
+ /// Same as [`modify_token_properties`] but doesn't allow to remove properties
+ ///
+ /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties
pub fn set_token_properties(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -592,6 +730,11 @@
)
}
+ /// Add or edit single property for the token
+ ///
+ /// Calls [`set_token_properties`] internally
+ ///
+ /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties
pub fn set_token_property(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -611,6 +754,11 @@
)
}
+ /// Batch operation to remove properties from the token
+ ///
+ /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties
+ ///
+ /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties
pub fn delete_token_properties(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -630,6 +778,11 @@
)
}
+ /// Remove single property from the token
+ ///
+ /// Calls [`delete_token_properties`] internally
+ ///
+ /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties
pub fn delete_token_property(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -646,6 +799,7 @@
)
}
+ /// Add or edit properties for the collection
pub fn set_collection_properties(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -654,6 +808,7 @@
<PalletCommon<T>>::set_collection_properties(collection, sender, properties)
}
+ /// Remove properties from the collection
pub fn delete_collection_properties(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -662,6 +817,9 @@
<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
}
+ /// Set property permissions for the token.
+ ///
+ /// Sender should be the owner or admin of token's collection.
pub fn set_token_property_permissions(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -670,6 +828,9 @@
<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
}
+ /// Set property permissions for the collection.
+ ///
+ /// Sender should be the owner or admin of the collection.
pub fn set_property_permission(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -678,6 +839,14 @@
<PalletCommon<T>>::set_property_permission(collection, sender, permission)
}
+ /// Transfer NFT token from one account to another.
+ ///
+ /// `from` account stops being the owner and `to` account becomes the owner of the token.
+ /// If `to` is token than `to` becomes owner of the token and the token become nested.
+ /// Unnests token from previous parent if it was nested before.
+ /// Removes allowance for the token if there was any.
+ ///
+ /// - `nesting_budget`: Limit for token nesting depth
pub fn transfer(
collection: &NonfungibleHandle<T>,
from: &T::CrossAccountId,
@@ -769,6 +938,13 @@
Ok(())
}
+ /// Batch operation to mint multiple NFT tokens.
+ ///
+ /// The sender should be the owner/admin of the collection or collection should be configured
+ /// to allow public minting.
+ ///
+ /// - `data`: Contains list of token properties and users who will become the owners of the corresponging tokens.
+ /// - `nesting_budget`: Limit for token nesting depth
pub fn create_multiple_items(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -953,6 +1129,9 @@
}
}
+ /// Set allowance for the spender to `transfer` or `burn` sender's token.
+ ///
+ /// - `token`: Token the spender is allowed to `transfer` or `burn`.
pub fn set_allowance(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -985,6 +1164,7 @@
Ok(())
}
+ /// Checks allowance for the spender to use the token.
fn check_allowed(
collection: &NonfungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -1027,6 +1207,12 @@
Ok(())
}
+ /// Transfer NFT token from one account to another.
+ ///
+ /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.
+ /// The owner should set allowance for the spender to transfer token.
+ ///
+ /// [`transfer`]: struct.Pallet.html#method.transfer
pub fn transfer_from(
collection: &NonfungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -1043,6 +1229,12 @@
Self::transfer(collection, from, to, token, nesting_budget)
}
+ /// Burn NFT token for `from` account.
+ ///
+ /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should
+ /// set allowance for the spender to burn token.
+ ///
+ /// [`burn`]: struct.Pallet.html#method.burn
pub fn burn_from(
collection: &NonfungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -1057,6 +1249,8 @@
Self::burn(collection, from, token)
}
+ /// Check that `from` token could be nested in `under` token.
+ ///
pub fn check_nesting(
handle: &NonfungibleHandle<T>,
sender: T::CrossAccountId,
@@ -1126,7 +1320,11 @@
.collect()
}
- /// Delegated to `create_multiple_items`
+ /// Mint single NFT token.
+ ///
+ /// Delegated to [`create_multiple_items`]
+ ///
+ /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items
pub fn create_item(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,