difftreelog
Add properties extrinsics
in: master
10 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -736,7 +736,24 @@
) -> DispatchResult {
collection.check_is_owner_or_admin(sender)?;
- CollectionProperties::<T>::get(collection.id).try_change_property(property)?;
+ CollectionProperties::<T>::try_mutate(
+ collection.id,
+ |properties| properties.try_change_property(property.clone())
+ )?;
+
+ <Pallet<T>>::deposit_event(Event::CollectionPropertySet(collection.id, property));
+
+ Ok(())
+ }
+
+ pub fn change_collection_properties(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ properties: Vec<Property>,
+ ) -> DispatchResult {
+ for property in properties {
+ Self::change_collection_property(collection, sender, property)?;
+ }
Ok(())
}
@@ -909,7 +926,8 @@
fn create_multiple_items(amount: u32) -> Weight;
fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;
fn burn_item() -> Weight;
- fn set_property() -> Weight;
+ fn change_collection_properties(amount: u32) -> Weight;
+ fn change_token_properties(amount: u32) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -945,17 +963,17 @@
amount: u128,
) -> DispatchResultWithPostInfo;
- fn change_collection_property(
+ fn change_collection_properties(
&self,
sender: T::CrossAccountId,
- property: Property,
+ properties: Vec<Property>,
) -> DispatchResultWithPostInfo;
- fn change_token_property(
+ fn change_token_properties(
&self,
sender: T::CrossAccountId,
token_id: TokenId,
- property: Property,
+ property: Vec<Property>,
) -> DispatchResultWithPostInfo;
fn transfer(
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -50,8 +50,12 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_property() -> Weight {
- <SelfWeightOf<T>>::set_property()
+ fn change_collection_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_collection_properties(amount)
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_token_properties(amount)
}
fn transfer() -> Weight {
@@ -229,19 +233,19 @@
)
}
- fn change_collection_property(
+ fn change_collection_properties(
&self,
_sender: T::CrossAccountId,
- _property: Property,
+ _property: Vec<Property>,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::PropertiesNotAllowed)
}
- fn change_token_property(
+ fn change_token_properties(
&self,
_sender: T::CrossAccountId,
_token_id: TokenId,
- _property: Property,
+ _property: Vec<Property>,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::PropertiesNotAllowed)
}
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -35,7 +35,8 @@
fn create_item() -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
- fn set_property() -> Weight;
+ fn change_collection_properties(amount: u32) -> Weight;
+ fn change_token_properties(amount: u32) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -71,11 +72,16 @@
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
// Error
0
}
+ fn change_token_properties(amount: u32) -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Fungible Balance (r:2 w:2)
fn transfer() -> Weight {
(17_713_000 as Weight)
@@ -134,7 +140,12 @@
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
+ // Error
+ 0
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
// Error
0
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -50,8 +50,12 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_property() -> Weight {
- <SelfWeightOf<T>>::set_property()
+ fn change_collection_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_collection_properties(amount)
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_token_properties(amount)
}
fn transfer() -> Weight {
@@ -145,6 +149,33 @@
)
}
+ fn change_collection_properties(
+ &self,
+ sender: T::CrossAccountId,
+ properties: Vec<Property>,
+ ) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::change_collection_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::change_collection_properties(self, &sender, properties),
+ weight
+ )
+ }
+
+ fn change_token_properties(
+ &self,
+ sender: T::CrossAccountId,
+ token_id: TokenId,
+ properties: Vec<Property>,
+ ) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::change_token_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::change_token_properties(self, &sender, token_id, properties),
+ weight
+ )
+ }
+
fn burn_item(
&self,
sender: T::CrossAccountId,
@@ -239,32 +270,6 @@
} else {
Ok(().into())
}
- }
-
- fn change_collection_property(
- &self,
- sender: T::CrossAccountId,
- property: Property,
- ) -> DispatchResultWithPostInfo {
- // let token_id = None;
- with_weight(
- // <Pallet<T>>::change_property(self, &sender, token_id, property),
- Ok(()),
- <CommonWeights<T>>::set_property(),
- )
- }
-
- fn change_token_property(
- &self,
- sender: T::CrossAccountId,
- token_id: TokenId,
- property: Property,
- ) -> DispatchResultWithPostInfo {
- with_weight(
- // <Pallet<T>>::change_property(self, &sender, Some(token_id), property),
- Ok(()),
- <CommonWeights<T>>::set_property(),
- )
}
fn set_variable_metadata(
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52 pub const_data: BoundedVec<u8, CustomDataLimit>,53 pub variable_data: BoundedVec<u8, CustomDataLimit>,54 pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59 use super::*;60 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61 use up_data_structs::{CollectionId, TokenId};62 use super::weights::WeightInfo;6364 #[pallet::error]65 pub enum Error<T> {66 /// Not Nonfungible item data used to mint in Nonfungible collection.67 NotNonfungibleDataUsedToMintFungibleCollectionToken,68 /// Used amount > 1 with NFT69 NonfungibleItemsHaveNoAmount,70 }7172 #[pallet::config]73 pub trait Config:74 frame_system::Config + pallet_common::Config + pallet_structure::Config75 {76 type WeightInfo: WeightInfo;77 }7879 #[pallet::pallet]80 #[pallet::generate_store(pub(super) trait Store)]81 pub struct Pallet<T>(_);8283 #[pallet::storage]84 pub type TokensMinted<T: Config> =85 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86 #[pallet::storage]87 pub type TokensBurnt<T: Config> =88 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990 #[pallet::storage]91 pub type TokenData<T: Config> = StorageNMap<92 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93 Value = ItemData<T::CrossAccountId>,94 QueryKind = OptionQuery,95 >;9697 #[pallet::storage]98 pub type TokenProperties<T: Config> = StorageNMap<99 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),100 Value = up_data_structs::Properties,101 QueryKind = ValueQuery,102 OnEmpty = up_data_structs::TokenProperties,103 >;104105 /// Used to enumerate tokens owned by account106 #[pallet::storage]107 pub type Owned<T: Config> = StorageNMap<108 Key = (109 Key<Twox64Concat, CollectionId>,110 Key<Blake2_128Concat, T::CrossAccountId>,111 Key<Twox64Concat, TokenId>,112 ),113 Value = bool,114 QueryKind = ValueQuery,115 >;116117 #[pallet::storage]118 pub type AccountBalance<T: Config> = StorageNMap<119 Key = (120 Key<Twox64Concat, CollectionId>,121 Key<Blake2_128Concat, T::CrossAccountId>,122 ),123 Value = u32,124 QueryKind = ValueQuery,125 >;126127 #[pallet::storage]128 pub type Allowance<T: Config> = StorageNMap<129 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),130 Value = T::CrossAccountId,131 QueryKind = OptionQuery,132 >;133}134135pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);136impl<T: Config> NonfungibleHandle<T> {137 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {138 Self(inner)139 }140 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {141 self.0142 }143}144impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {145 fn recorder(&self) -> &SubstrateRecorder<T> {146 self.0.recorder()147 }148 fn into_recorder(self) -> SubstrateRecorder<T> {149 self.0.into_recorder()150 }151}152impl<T: Config> Deref for NonfungibleHandle<T> {153 type Target = pallet_common::CollectionHandle<T>;154155 fn deref(&self) -> &Self::Target {156 &self.0157 }158}159160impl<T: Config> Pallet<T> {161 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {162 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)163 }164 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {165 <TokenData<T>>::contains_key((collection.id, token))166 }167}168169// unchecked calls skips any permission checks170impl<T: Config> Pallet<T> {171 pub fn init_collection(172 owner: T::AccountId,173 data: CreateCollectionData<T::AccountId>,174 ) -> Result<CollectionId, DispatchError> {175 <PalletCommon<T>>::init_collection(owner, data)176 }177 pub fn destroy_collection(178 collection: NonfungibleHandle<T>,179 sender: &T::CrossAccountId,180 ) -> DispatchResult {181 let id = collection.id;182183 // =========184185 PalletCommon::destroy_collection(collection.0, sender)?;186187 <TokenData<T>>::remove_prefix((id,), None);188 <Owned<T>>::remove_prefix((id,), None);189 <TokensMinted<T>>::remove(id);190 <TokensBurnt<T>>::remove(id);191 <Allowance<T>>::remove_prefix((id,), None);192 <AccountBalance<T>>::remove_prefix((id,), None);193 Ok(())194 }195196 pub fn burn(197 collection: &NonfungibleHandle<T>,198 sender: &T::CrossAccountId,199 token: TokenId,200 ) -> DispatchResult {201 let token_data =202 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;203 ensure!(204 &token_data.owner == sender205 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),206 <CommonError<T>>::NoPermission207 );208209 if collection.access == AccessMode::AllowList {210 collection.check_allowlist(sender)?;211 }212213 let burnt = <TokensBurnt<T>>::get(collection.id)214 .checked_add(1)215 .ok_or(ArithmeticError::Overflow)?;216217 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))218 .checked_sub(1)219 .ok_or(ArithmeticError::Overflow)?;220221 if balance == 0 {222 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));223 } else {224 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);225 }226 // =========227228 <Owned<T>>::remove((collection.id, &token_data.owner, token));229 <TokensBurnt<T>>::insert(collection.id, burnt);230 <TokenData<T>>::remove((collection.id, token));231 let old_spender = <Allowance<T>>::take((collection.id, token));232233 if let Some(old_spender) = old_spender {234 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(235 collection.id,236 token,237 sender.clone(),238 old_spender,239 0,240 ));241 }242243 collection.log_mirrored(ERC721Events::Transfer {244 from: *token_data.owner.as_eth(),245 to: H160::default(),246 token_id: token.into(),247 });248 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(249 collection.id,250 token,251 token_data.owner,252 1,253 ));254 Ok(())255 }256257 pub fn change_token_property(258 collection: &NonfungibleHandle<T>,259 sender: &T::CrossAccountId,260 token_id: TokenId,261 property: Property,262 ) -> DispatchResult {263 let permission = <PalletCommon<T>>::property_permission(collection.id)264 .get(&property.key)265 .map(|p| p.clone())266 .unwrap_or(PropertyPermission::None);267268 let check_token_owner = || -> DispatchResult {269 let token_data = <TokenData<T>>::get((collection.id, token_id))270 .ok_or(<CommonError<T>>::TokenNotFound)?;271272 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);273274 Ok(())275 };276277 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))278 .get_property(&property.key)279 .is_some();280281 match (permission, is_property_exists) {282 (PropertyPermission::AdminConst, false) => {283 collection.check_is_owner_or_admin(sender)?284 }285 (PropertyPermission::Admin, _) => collection.check_is_owner_or_admin(sender)?,286 (PropertyPermission::ItemOwnerConst, false) => check_token_owner()?,287 (PropertyPermission::ItemOwner, _) => check_token_owner()?,288 (PropertyPermission::ItemOwnerOrAdmin, _) => {289 check_token_owner().or(collection.check_is_owner_or_admin(sender))?;290 }291 _ => return Err(<CommonError<T>>::NoPermission.into()),292 }293294 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {295 properties.try_change_property(property.clone())296 })?;297298 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(299 collection.id,300 token_id,301 property,302 ));303304 Ok(())305 }306307 pub fn transfer(308 collection: &NonfungibleHandle<T>,309 from: &T::CrossAccountId,310 to: &T::CrossAccountId,311 token: TokenId,312 nesting_budget: &dyn Budget,313 ) -> DispatchResult {314 ensure!(315 collection.limits.transfers_enabled(),316 <CommonError<T>>::TransferNotAllowed317 );318319 let token_data =320 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;321 // TODO: require sender to be token, owner, require admins to go through transfer_from322 ensure!(323 &token_data.owner == from324 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),325 <CommonError<T>>::NoPermission326 );327328 if collection.access == AccessMode::AllowList {329 collection.check_allowlist(from)?;330 collection.check_allowlist(to)?;331 }332 <PalletCommon<T>>::ensure_correct_receiver(to)?;333334 let balance_from = <AccountBalance<T>>::get((collection.id, from))335 .checked_sub(1)336 .ok_or(<CommonError<T>>::TokenValueTooLow)?;337 let balance_to = if from != to {338 let balance_to = <AccountBalance<T>>::get((collection.id, to))339 .checked_add(1)340 .ok_or(ArithmeticError::Overflow)?;341342 ensure!(343 balance_to < collection.limits.account_token_ownership_limit(),344 <CommonError<T>>::AccountTokenLimitExceeded,345 );346347 Some(balance_to)348 } else {349 None350 };351352 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {353 let handle = <CollectionHandle<T>>::try_get(target.0)?;354 let dispatch = T::CollectionDispatch::dispatch(handle);355 let dispatch = dispatch.as_dyn();356357 dispatch.check_nesting(358 from.clone(),359 (collection.id, token),360 target.1,361 nesting_budget,362 )?;363 }364365 // =========366367 <TokenData<T>>::insert(368 (collection.id, token),369 ItemData {370 owner: to.clone(),371 ..token_data372 },373 );374375 if let Some(balance_to) = balance_to {376 // from != to377 if balance_from == 0 {378 <AccountBalance<T>>::remove((collection.id, from));379 } else {380 <AccountBalance<T>>::insert((collection.id, from), balance_from);381 }382 <AccountBalance<T>>::insert((collection.id, to), balance_to);383 <Owned<T>>::remove((collection.id, from, token));384 <Owned<T>>::insert((collection.id, to, token), true);385 }386 Self::set_allowance_unchecked(collection, from, token, None, true);387388 collection.log_mirrored(ERC721Events::Transfer {389 from: *from.as_eth(),390 to: *to.as_eth(),391 token_id: token.into(),392 });393 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(394 collection.id,395 token,396 from.clone(),397 to.clone(),398 1,399 ));400 Ok(())401 }402403 pub fn create_multiple_items(404 collection: &NonfungibleHandle<T>,405 sender: &T::CrossAccountId,406 data: Vec<CreateItemData<T>>,407 nesting_budget: &dyn Budget,408 ) -> DispatchResult {409 if !collection.is_owner_or_admin(sender) {410 ensure!(411 collection.mint_mode,412 <CommonError<T>>::PublicMintingNotAllowed413 );414 collection.check_allowlist(sender)?;415416 for item in data.iter() {417 collection.check_allowlist(&item.owner)?;418 }419 }420421 for data in data.iter() {422 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;423 }424425 let first_token = <TokensMinted<T>>::get(collection.id);426 let tokens_minted = first_token427 .checked_add(data.len() as u32)428 .ok_or(ArithmeticError::Overflow)?;429 ensure!(430 tokens_minted <= collection.limits.token_limit(),431 <CommonError<T>>::CollectionTokenLimitExceeded432 );433434 let mut balances = BTreeMap::new();435 for data in &data {436 let balance = balances437 .entry(&data.owner)438 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));439 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;440441 ensure!(442 *balance <= collection.limits.account_token_ownership_limit(),443 <CommonError<T>>::AccountTokenLimitExceeded,444 );445 }446447 for (i, data) in data.iter().enumerate() {448 let token = TokenId(first_token + i as u32 + 1);449 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {450 let handle = <CollectionHandle<T>>::try_get(target.0)?;451 let dispatch = T::CollectionDispatch::dispatch(handle);452 let dispatch = dispatch.as_dyn();453 dispatch.check_nesting(454 sender.clone(),455 (collection.id, token),456 target.1,457 nesting_budget,458 )?;459 }460 }461462 // =========463464 <TokensMinted<T>>::insert(collection.id, tokens_minted);465 for (account, balance) in balances {466 <AccountBalance<T>>::insert((collection.id, account), balance);467 }468 for (i, data) in data.into_iter().enumerate() {469 let token = first_token + i as u32 + 1;470471 <TokenData<T>>::insert(472 (collection.id, token),473 ItemData {474 const_data: data.const_data,475 variable_data: data.variable_data,476 owner: data.owner.clone(),477 },478 );479 <Owned<T>>::insert((collection.id, &data.owner, token), true);480481 collection.log_mirrored(ERC721Events::Transfer {482 from: H160::default(),483 to: *data.owner.as_eth(),484 token_id: token.into(),485 });486 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(487 collection.id,488 TokenId(token),489 data.owner.clone(),490 1,491 ));492 }493 Ok(())494 }495496 pub fn set_allowance_unchecked(497 collection: &NonfungibleHandle<T>,498 sender: &T::CrossAccountId,499 token: TokenId,500 spender: Option<&T::CrossAccountId>,501 assume_implicit_eth: bool,502 ) {503 if let Some(spender) = spender {504 let old_spender = <Allowance<T>>::get((collection.id, token));505 <Allowance<T>>::insert((collection.id, token), spender);506 // In ERC721 there is only one possible approved user of token, so we set507 // approved user to spender508 collection.log_mirrored(ERC721Events::Approval {509 owner: *sender.as_eth(),510 approved: *spender.as_eth(),511 token_id: token.into(),512 });513 // In Unique chain, any token can have any amount of approved users, so we need to514 // set allowance of old owner to 0, and allowance of new owner to 1515 if old_spender.as_ref() != Some(spender) {516 if let Some(old_owner) = old_spender {517 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(518 collection.id,519 token,520 sender.clone(),521 old_owner,522 0,523 ));524 }525 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(526 collection.id,527 token,528 sender.clone(),529 spender.clone(),530 1,531 ));532 }533 } else {534 let old_spender = <Allowance<T>>::take((collection.id, token));535 if !assume_implicit_eth {536 // In ERC721 there is only one possible approved user of token, so we set537 // approved user to zero address538 collection.log_mirrored(ERC721Events::Approval {539 owner: *sender.as_eth(),540 approved: H160::default(),541 token_id: token.into(),542 });543 }544 // In Unique chain, any token can have any amount of approved users, so we need to545 // set allowance of old owner to 0546 if let Some(old_spender) = old_spender {547 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(548 collection.id,549 token,550 sender.clone(),551 old_spender,552 0,553 ));554 }555 }556 }557558 pub fn set_allowance(559 collection: &NonfungibleHandle<T>,560 sender: &T::CrossAccountId,561 token: TokenId,562 spender: Option<&T::CrossAccountId>,563 ) -> DispatchResult {564 if collection.access == AccessMode::AllowList {565 collection.check_allowlist(sender)?;566 if let Some(spender) = spender {567 collection.check_allowlist(spender)?;568 }569 }570571 if let Some(spender) = spender {572 <PalletCommon<T>>::ensure_correct_receiver(spender)?;573 }574 let token_data =575 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;576 if &token_data.owner != sender {577 ensure!(578 collection.ignores_owned_amount(sender),579 <CommonError<T>>::CantApproveMoreThanOwned580 );581 }582583 // =========584585 Self::set_allowance_unchecked(collection, sender, token, spender, false);586 Ok(())587 }588589 fn check_allowed(590 collection: &NonfungibleHandle<T>,591 spender: &T::CrossAccountId,592 from: &T::CrossAccountId,593 token: TokenId,594 nesting_budget: &dyn Budget,595 ) -> DispatchResult {596 if spender.conv_eq(from) {597 return Ok(());598 }599 if collection.access == AccessMode::AllowList {600 // `from`, `to` checked in [`transfer`]601 collection.check_allowlist(spender)?;602 }603 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {604 // TODO: should collection owner be allowed to perform this transfer?605 ensure!(606 <PalletStructure<T>>::check_indirectly_owned(607 spender.clone(),608 source.0,609 source.1,610 None,611 nesting_budget612 )?,613 <CommonError<T>>::ApprovedValueTooLow,614 );615 return Ok(());616 }617 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {618 return Ok(());619 }620 ensure!(621 collection.ignores_allowance(spender),622 <CommonError<T>>::ApprovedValueTooLow623 );624 Ok(())625 }626627 pub fn transfer_from(628 collection: &NonfungibleHandle<T>,629 spender: &T::CrossAccountId,630 from: &T::CrossAccountId,631 to: &T::CrossAccountId,632 token: TokenId,633 nesting_budget: &dyn Budget,634 ) -> DispatchResult {635 Self::check_allowed(collection, spender, from, token, nesting_budget)?;636637 // =========638639 // Allowance is reset in [`transfer`]640 Self::transfer(collection, from, to, token, nesting_budget)641 }642643 pub fn burn_from(644 collection: &NonfungibleHandle<T>,645 spender: &T::CrossAccountId,646 from: &T::CrossAccountId,647 token: TokenId,648 nesting_budget: &dyn Budget,649 ) -> DispatchResult {650 Self::check_allowed(collection, spender, from, token, nesting_budget)?;651652 // =========653654 Self::burn(collection, from, token)655 }656657 pub fn set_variable_metadata(658 collection: &NonfungibleHandle<T>,659 sender: &T::CrossAccountId,660 token: TokenId,661 data: BoundedVec<u8, CustomDataLimit>,662 ) -> DispatchResult {663 let token_data =664 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;665 collection.check_can_update_meta(sender, &token_data.owner)?;666667 // =========668669 <TokenData<T>>::insert(670 (collection.id, token),671 ItemData {672 variable_data: data,673 ..token_data674 },675 );676 Ok(())677 }678679 pub fn check_nesting(680 handle: &NonfungibleHandle<T>,681 sender: T::CrossAccountId,682 from: (CollectionId, TokenId),683 under: TokenId,684 nesting_budget: &dyn Budget,685 ) -> DispatchResult {686 fn ensure_sender_allowed<T: Config>(687 collection: CollectionId,688 token: TokenId,689 for_nest: (CollectionId, TokenId),690 sender: T::CrossAccountId,691 budget: &dyn Budget,692 ) -> DispatchResult {693 ensure!(694 <PalletStructure<T>>::check_indirectly_owned(695 sender,696 collection,697 token,698 Some(for_nest),699 budget700 )?,701 <CommonError<T>>::OnlyOwnerAllowedToNest,702 );703 Ok(())704 }705 match handle.limits.nesting_rule() {706 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),707 NestingRule::Owner => {708 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?709 }710 NestingRule::OwnerRestricted(whitelist) => {711 ensure!(712 whitelist.contains(&from.0),713 <CommonError<T>>::SourceCollectionIsNotAllowedToNest714 );715 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?716 }717 }718 Ok(())719 }720721 /// Delegated to `create_multiple_items`722 pub fn create_item(723 collection: &NonfungibleHandle<T>,724 sender: &T::CrossAccountId,725 data: CreateItemData<T>,726 nesting_budget: &dyn Budget,727 ) -> DispatchResult {728 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)729 }730}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52 pub const_data: BoundedVec<u8, CustomDataLimit>,53 pub variable_data: BoundedVec<u8, CustomDataLimit>,54 pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59 use super::*;60 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61 use up_data_structs::{CollectionId, TokenId};62 use super::weights::WeightInfo;6364 #[pallet::error]65 pub enum Error<T> {66 /// Not Nonfungible item data used to mint in Nonfungible collection.67 NotNonfungibleDataUsedToMintFungibleCollectionToken,68 /// Used amount > 1 with NFT69 NonfungibleItemsHaveNoAmount,70 }7172 #[pallet::config]73 pub trait Config:74 frame_system::Config + pallet_common::Config + pallet_structure::Config75 {76 type WeightInfo: WeightInfo;77 }7879 #[pallet::pallet]80 #[pallet::generate_store(pub(super) trait Store)]81 pub struct Pallet<T>(_);8283 #[pallet::storage]84 pub type TokensMinted<T: Config> =85 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86 #[pallet::storage]87 pub type TokensBurnt<T: Config> =88 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990 #[pallet::storage]91 pub type TokenData<T: Config> = StorageNMap<92 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93 Value = ItemData<T::CrossAccountId>,94 QueryKind = OptionQuery,95 >;9697 #[pallet::storage]98 pub type TokenProperties<T: Config> = StorageNMap<99 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),100 Value = up_data_structs::Properties,101 QueryKind = ValueQuery,102 OnEmpty = up_data_structs::TokenProperties,103 >;104105 /// Used to enumerate tokens owned by account106 #[pallet::storage]107 pub type Owned<T: Config> = StorageNMap<108 Key = (109 Key<Twox64Concat, CollectionId>,110 Key<Blake2_128Concat, T::CrossAccountId>,111 Key<Twox64Concat, TokenId>,112 ),113 Value = bool,114 QueryKind = ValueQuery,115 >;116117 #[pallet::storage]118 pub type AccountBalance<T: Config> = StorageNMap<119 Key = (120 Key<Twox64Concat, CollectionId>,121 Key<Blake2_128Concat, T::CrossAccountId>,122 ),123 Value = u32,124 QueryKind = ValueQuery,125 >;126127 #[pallet::storage]128 pub type Allowance<T: Config> = StorageNMap<129 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),130 Value = T::CrossAccountId,131 QueryKind = OptionQuery,132 >;133}134135pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);136impl<T: Config> NonfungibleHandle<T> {137 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {138 Self(inner)139 }140 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {141 self.0142 }143}144impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {145 fn recorder(&self) -> &SubstrateRecorder<T> {146 self.0.recorder()147 }148 fn into_recorder(self) -> SubstrateRecorder<T> {149 self.0.into_recorder()150 }151}152impl<T: Config> Deref for NonfungibleHandle<T> {153 type Target = pallet_common::CollectionHandle<T>;154155 fn deref(&self) -> &Self::Target {156 &self.0157 }158}159160impl<T: Config> Pallet<T> {161 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {162 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)163 }164 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {165 <TokenData<T>>::contains_key((collection.id, token))166 }167}168169// unchecked calls skips any permission checks170impl<T: Config> Pallet<T> {171 pub fn init_collection(172 owner: T::AccountId,173 data: CreateCollectionData<T::AccountId>,174 ) -> Result<CollectionId, DispatchError> {175 <PalletCommon<T>>::init_collection(owner, data)176 }177 pub fn destroy_collection(178 collection: NonfungibleHandle<T>,179 sender: &T::CrossAccountId,180 ) -> DispatchResult {181 let id = collection.id;182183 // =========184185 PalletCommon::destroy_collection(collection.0, sender)?;186187 <TokenData<T>>::remove_prefix((id,), None);188 <Owned<T>>::remove_prefix((id,), None);189 <TokensMinted<T>>::remove(id);190 <TokensBurnt<T>>::remove(id);191 <Allowance<T>>::remove_prefix((id,), None);192 <AccountBalance<T>>::remove_prefix((id,), None);193 Ok(())194 }195196 pub fn burn(197 collection: &NonfungibleHandle<T>,198 sender: &T::CrossAccountId,199 token: TokenId,200 ) -> DispatchResult {201 let token_data =202 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;203 ensure!(204 &token_data.owner == sender205 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),206 <CommonError<T>>::NoPermission207 );208209 if collection.access == AccessMode::AllowList {210 collection.check_allowlist(sender)?;211 }212213 let burnt = <TokensBurnt<T>>::get(collection.id)214 .checked_add(1)215 .ok_or(ArithmeticError::Overflow)?;216217 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))218 .checked_sub(1)219 .ok_or(ArithmeticError::Overflow)?;220221 if balance == 0 {222 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));223 } else {224 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);225 }226 // =========227228 <Owned<T>>::remove((collection.id, &token_data.owner, token));229 <TokensBurnt<T>>::insert(collection.id, burnt);230 <TokenData<T>>::remove((collection.id, token));231 let old_spender = <Allowance<T>>::take((collection.id, token));232233 if let Some(old_spender) = old_spender {234 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(235 collection.id,236 token,237 sender.clone(),238 old_spender,239 0,240 ));241 }242243 collection.log_mirrored(ERC721Events::Transfer {244 from: *token_data.owner.as_eth(),245 to: H160::default(),246 token_id: token.into(),247 });248 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(249 collection.id,250 token,251 token_data.owner,252 1,253 ));254 Ok(())255 }256257 pub fn change_token_property(258 collection: &NonfungibleHandle<T>,259 sender: &T::CrossAccountId,260 token_id: TokenId,261 property: Property,262 ) -> DispatchResult {263 let permission = <PalletCommon<T>>::property_permission(collection.id)264 .get(&property.key)265 .map(|p| p.clone())266 .unwrap_or(PropertyPermission::None);267268 let token_data = <TokenData<T>>::get((collection.id, token_id))269 .ok_or(<CommonError<T>>::TokenNotFound)?;270271 let check_token_owner = || -> DispatchResult {272 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);273 Ok(())274 };275276 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))277 .get_property(&property.key)278 .is_some();279280 match (permission, is_property_exists) {281 (PropertyPermission::AdminConst, false) => {282 collection.check_is_owner_or_admin(sender)?283 }284 (PropertyPermission::Admin, _) => collection.check_is_owner_or_admin(sender)?,285 (PropertyPermission::ItemOwnerConst, false) => check_token_owner()?,286 (PropertyPermission::ItemOwner, _) => check_token_owner()?,287 (PropertyPermission::ItemOwnerOrAdmin, _) => {288 check_token_owner().or(collection.check_is_owner_or_admin(sender))?;289 }290 _ => return Err(<CommonError<T>>::NoPermission.into()),291 }292293 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {294 properties.try_change_property(property.clone())295 })?;296297 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(298 collection.id,299 token_id,300 property,301 ));302303 Ok(())304 }305306 pub fn change_token_properties(307 collection: &NonfungibleHandle<T>,308 sender: &T::CrossAccountId,309 token_id: TokenId,310 properties: Vec<Property>,311 ) -> DispatchResult {312 for property in properties {313 Self::change_token_property(collection, sender, token_id, property)?;314 }315316 Ok(())317 }318319 pub fn change_collection_properties(320 collection: &NonfungibleHandle<T>,321 sender: &T::CrossAccountId,322 properties: Vec<Property>,323 ) -> DispatchResult {324 <PalletCommon<T>>::change_collection_properties(collection, sender, properties)325 }326327 pub fn transfer(328 collection: &NonfungibleHandle<T>,329 from: &T::CrossAccountId,330 to: &T::CrossAccountId,331 token: TokenId,332 nesting_budget: &dyn Budget,333 ) -> DispatchResult {334 ensure!(335 collection.limits.transfers_enabled(),336 <CommonError<T>>::TransferNotAllowed337 );338339 let token_data =340 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;341 // TODO: require sender to be token, owner, require admins to go through transfer_from342 ensure!(343 &token_data.owner == from344 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),345 <CommonError<T>>::NoPermission346 );347348 if collection.access == AccessMode::AllowList {349 collection.check_allowlist(from)?;350 collection.check_allowlist(to)?;351 }352 <PalletCommon<T>>::ensure_correct_receiver(to)?;353354 let balance_from = <AccountBalance<T>>::get((collection.id, from))355 .checked_sub(1)356 .ok_or(<CommonError<T>>::TokenValueTooLow)?;357 let balance_to = if from != to {358 let balance_to = <AccountBalance<T>>::get((collection.id, to))359 .checked_add(1)360 .ok_or(ArithmeticError::Overflow)?;361362 ensure!(363 balance_to < collection.limits.account_token_ownership_limit(),364 <CommonError<T>>::AccountTokenLimitExceeded,365 );366367 Some(balance_to)368 } else {369 None370 };371372 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {373 let handle = <CollectionHandle<T>>::try_get(target.0)?;374 let dispatch = T::CollectionDispatch::dispatch(handle);375 let dispatch = dispatch.as_dyn();376377 dispatch.check_nesting(378 from.clone(),379 (collection.id, token),380 target.1,381 nesting_budget,382 )?;383 }384385 // =========386387 <TokenData<T>>::insert(388 (collection.id, token),389 ItemData {390 owner: to.clone(),391 ..token_data392 },393 );394395 if let Some(balance_to) = balance_to {396 // from != to397 if balance_from == 0 {398 <AccountBalance<T>>::remove((collection.id, from));399 } else {400 <AccountBalance<T>>::insert((collection.id, from), balance_from);401 }402 <AccountBalance<T>>::insert((collection.id, to), balance_to);403 <Owned<T>>::remove((collection.id, from, token));404 <Owned<T>>::insert((collection.id, to, token), true);405 }406 Self::set_allowance_unchecked(collection, from, token, None, true);407408 collection.log_mirrored(ERC721Events::Transfer {409 from: *from.as_eth(),410 to: *to.as_eth(),411 token_id: token.into(),412 });413 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(414 collection.id,415 token,416 from.clone(),417 to.clone(),418 1,419 ));420 Ok(())421 }422423 pub fn create_multiple_items(424 collection: &NonfungibleHandle<T>,425 sender: &T::CrossAccountId,426 data: Vec<CreateItemData<T>>,427 nesting_budget: &dyn Budget,428 ) -> DispatchResult {429 if !collection.is_owner_or_admin(sender) {430 ensure!(431 collection.mint_mode,432 <CommonError<T>>::PublicMintingNotAllowed433 );434 collection.check_allowlist(sender)?;435436 for item in data.iter() {437 collection.check_allowlist(&item.owner)?;438 }439 }440441 for data in data.iter() {442 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;443 }444445 let first_token = <TokensMinted<T>>::get(collection.id);446 let tokens_minted = first_token447 .checked_add(data.len() as u32)448 .ok_or(ArithmeticError::Overflow)?;449 ensure!(450 tokens_minted <= collection.limits.token_limit(),451 <CommonError<T>>::CollectionTokenLimitExceeded452 );453454 let mut balances = BTreeMap::new();455 for data in &data {456 let balance = balances457 .entry(&data.owner)458 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));459 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;460461 ensure!(462 *balance <= collection.limits.account_token_ownership_limit(),463 <CommonError<T>>::AccountTokenLimitExceeded,464 );465 }466467 for (i, data) in data.iter().enumerate() {468 let token = TokenId(first_token + i as u32 + 1);469 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {470 let handle = <CollectionHandle<T>>::try_get(target.0)?;471 let dispatch = T::CollectionDispatch::dispatch(handle);472 let dispatch = dispatch.as_dyn();473 dispatch.check_nesting(474 sender.clone(),475 (collection.id, token),476 target.1,477 nesting_budget,478 )?;479 }480 }481482 // =========483484 <TokensMinted<T>>::insert(collection.id, tokens_minted);485 for (account, balance) in balances {486 <AccountBalance<T>>::insert((collection.id, account), balance);487 }488 for (i, data) in data.into_iter().enumerate() {489 let token = first_token + i as u32 + 1;490491 <TokenData<T>>::insert(492 (collection.id, token),493 ItemData {494 const_data: data.const_data,495 variable_data: data.variable_data,496 owner: data.owner.clone(),497 },498 );499 <Owned<T>>::insert((collection.id, &data.owner, token), true);500501 collection.log_mirrored(ERC721Events::Transfer {502 from: H160::default(),503 to: *data.owner.as_eth(),504 token_id: token.into(),505 });506 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(507 collection.id,508 TokenId(token),509 data.owner.clone(),510 1,511 ));512 }513 Ok(())514 }515516 pub fn set_allowance_unchecked(517 collection: &NonfungibleHandle<T>,518 sender: &T::CrossAccountId,519 token: TokenId,520 spender: Option<&T::CrossAccountId>,521 assume_implicit_eth: bool,522 ) {523 if let Some(spender) = spender {524 let old_spender = <Allowance<T>>::get((collection.id, token));525 <Allowance<T>>::insert((collection.id, token), spender);526 // In ERC721 there is only one possible approved user of token, so we set527 // approved user to spender528 collection.log_mirrored(ERC721Events::Approval {529 owner: *sender.as_eth(),530 approved: *spender.as_eth(),531 token_id: token.into(),532 });533 // In Unique chain, any token can have any amount of approved users, so we need to534 // set allowance of old owner to 0, and allowance of new owner to 1535 if old_spender.as_ref() != Some(spender) {536 if let Some(old_owner) = old_spender {537 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(538 collection.id,539 token,540 sender.clone(),541 old_owner,542 0,543 ));544 }545 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(546 collection.id,547 token,548 sender.clone(),549 spender.clone(),550 1,551 ));552 }553 } else {554 let old_spender = <Allowance<T>>::take((collection.id, token));555 if !assume_implicit_eth {556 // In ERC721 there is only one possible approved user of token, so we set557 // approved user to zero address558 collection.log_mirrored(ERC721Events::Approval {559 owner: *sender.as_eth(),560 approved: H160::default(),561 token_id: token.into(),562 });563 }564 // In Unique chain, any token can have any amount of approved users, so we need to565 // set allowance of old owner to 0566 if let Some(old_spender) = old_spender {567 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(568 collection.id,569 token,570 sender.clone(),571 old_spender,572 0,573 ));574 }575 }576 }577578 pub fn set_allowance(579 collection: &NonfungibleHandle<T>,580 sender: &T::CrossAccountId,581 token: TokenId,582 spender: Option<&T::CrossAccountId>,583 ) -> DispatchResult {584 if collection.access == AccessMode::AllowList {585 collection.check_allowlist(sender)?;586 if let Some(spender) = spender {587 collection.check_allowlist(spender)?;588 }589 }590591 if let Some(spender) = spender {592 <PalletCommon<T>>::ensure_correct_receiver(spender)?;593 }594 let token_data =595 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;596 if &token_data.owner != sender {597 ensure!(598 collection.ignores_owned_amount(sender),599 <CommonError<T>>::CantApproveMoreThanOwned600 );601 }602603 // =========604605 Self::set_allowance_unchecked(collection, sender, token, spender, false);606 Ok(())607 }608609 fn check_allowed(610 collection: &NonfungibleHandle<T>,611 spender: &T::CrossAccountId,612 from: &T::CrossAccountId,613 token: TokenId,614 nesting_budget: &dyn Budget,615 ) -> DispatchResult {616 if spender.conv_eq(from) {617 return Ok(());618 }619 if collection.access == AccessMode::AllowList {620 // `from`, `to` checked in [`transfer`]621 collection.check_allowlist(spender)?;622 }623 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {624 // TODO: should collection owner be allowed to perform this transfer?625 ensure!(626 <PalletStructure<T>>::check_indirectly_owned(627 spender.clone(),628 source.0,629 source.1,630 None,631 nesting_budget632 )?,633 <CommonError<T>>::ApprovedValueTooLow,634 );635 return Ok(());636 }637 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {638 return Ok(());639 }640 ensure!(641 collection.ignores_allowance(spender),642 <CommonError<T>>::ApprovedValueTooLow643 );644 Ok(())645 }646647 pub fn transfer_from(648 collection: &NonfungibleHandle<T>,649 spender: &T::CrossAccountId,650 from: &T::CrossAccountId,651 to: &T::CrossAccountId,652 token: TokenId,653 nesting_budget: &dyn Budget,654 ) -> DispatchResult {655 Self::check_allowed(collection, spender, from, token, nesting_budget)?;656657 // =========658659 // Allowance is reset in [`transfer`]660 Self::transfer(collection, from, to, token, nesting_budget)661 }662663 pub fn burn_from(664 collection: &NonfungibleHandle<T>,665 spender: &T::CrossAccountId,666 from: &T::CrossAccountId,667 token: TokenId,668 nesting_budget: &dyn Budget,669 ) -> DispatchResult {670 Self::check_allowed(collection, spender, from, token, nesting_budget)?;671672 // =========673674 Self::burn(collection, from, token)675 }676677 pub fn set_variable_metadata(678 collection: &NonfungibleHandle<T>,679 sender: &T::CrossAccountId,680 token: TokenId,681 data: BoundedVec<u8, CustomDataLimit>,682 ) -> DispatchResult {683 let token_data =684 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;685 collection.check_can_update_meta(sender, &token_data.owner)?;686687 // =========688689 <TokenData<T>>::insert(690 (collection.id, token),691 ItemData {692 variable_data: data,693 ..token_data694 },695 );696 Ok(())697 }698699 pub fn check_nesting(700 handle: &NonfungibleHandle<T>,701 sender: T::CrossAccountId,702 from: (CollectionId, TokenId),703 under: TokenId,704 nesting_budget: &dyn Budget,705 ) -> DispatchResult {706 fn ensure_sender_allowed<T: Config>(707 collection: CollectionId,708 token: TokenId,709 for_nest: (CollectionId, TokenId),710 sender: T::CrossAccountId,711 budget: &dyn Budget,712 ) -> DispatchResult {713 ensure!(714 <PalletStructure<T>>::check_indirectly_owned(715 sender,716 collection,717 token,718 Some(for_nest),719 budget720 )?,721 <CommonError<T>>::OnlyOwnerAllowedToNest,722 );723 Ok(())724 }725 match handle.limits.nesting_rule() {726 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),727 NestingRule::Owner => {728 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?729 }730 NestingRule::OwnerRestricted(whitelist) => {731 ensure!(732 whitelist.contains(&from.0),733 <CommonError<T>>::SourceCollectionIsNotAllowedToNest734 );735 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?736 }737 }738 Ok(())739 }740741 /// Delegated to `create_multiple_items`742 pub fn create_item(743 collection: &NonfungibleHandle<T>,744 sender: &T::CrossAccountId,745 data: CreateItemData<T>,746 nesting_budget: &dyn Budget,747 ) -> DispatchResult {748 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)749 }750}pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -36,7 +36,8 @@
fn create_multiple_items(b: u32, ) -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
- fn set_property() -> Weight;
+ fn change_collection_properties(amount: u32) -> Weight;
+ fn change_token_properties(amount: u32) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -92,11 +93,16 @@
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
// TODO calculate appropriate weight
- 50_000_000 as Weight
+ (50_000_000 as Weight).saturating_mul(amount as Weight)
}
+ fn change_token_properties(amount: u32) -> Weight {
+ // TODO calculate appropriate weight
+ (50_000_000 as Weight).saturating_mul(amount as Weight)
+ }
+
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Allowance (r:1 w:0)
@@ -187,9 +193,14 @@
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
+ // TODO calculate appropriate weight
+ (50_000_000 as Weight).saturating_mul(amount as Weight)
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
// TODO calculate appropriate weight
- 50_000_000 as Weight
+ (50_000_000 as Weight).saturating_mul(amount as Weight)
}
// Storage: Nonfungible TokenData (r:1 w:1)
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -66,8 +66,12 @@
max_weight_of!(burn_item_partial(), burn_item_fully())
}
- fn set_property() -> Weight {
- <SelfWeightOf<T>>::set_property()
+ fn change_collection_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_collection_properties(amount)
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::change_token_properties(amount)
}
fn transfer() -> Weight {
@@ -248,19 +252,19 @@
)
}
- fn change_collection_property(
+ fn change_collection_properties(
&self,
_sender: T::CrossAccountId,
- _property: Property,
+ _property: Vec<Property>,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::PropertiesNotAllowed)
}
- fn change_token_property(
+ fn change_token_properties(
&self,
_sender: T::CrossAccountId,
_token_id: TokenId,
- _property: Property,
+ _property: Vec<Property>,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::PropertiesNotAllowed)
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -38,7 +38,8 @@
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight;
fn burn_item_partial() -> Weight;
fn burn_item_fully() -> Weight;
- fn set_property() -> Weight;
+ fn change_collection_properties(amount: u32) -> Weight;
+ fn change_token_properties(amount: u32) -> Weight;
fn transfer_normal() -> Weight;
fn transfer_creating() -> Weight;
fn transfer_removing() -> Weight;
@@ -131,11 +132,16 @@
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
// Error
0
}
+ fn change_token_properties(amount: u32) -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
(19_766_000 as Weight)
@@ -305,7 +311,12 @@
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
- fn set_property() -> Weight {
+ fn change_collection_properties(amount: u32) -> Weight {
+ // Error
+ 0
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
// Error
0
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -694,6 +694,35 @@
dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
}
+ #[weight = T::CommonWeightInfo::change_collection_properties(properties.len() as u32)]
+ #[transactional]
+ pub fn change_collection_properties(
+ origin,
+ collection_id: CollectionId,
+ properties: Vec<Property>
+ ) -> DispatchResultWithPostInfo {
+ ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);
+
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ dispatch_call::<T, _>(collection_id, |d| d.change_collection_properties(sender, properties))
+ }
+
+ #[weight = T::CommonWeightInfo::change_token_properties(properties.len() as u32)]
+ #[transactional]
+ pub fn change_token_properties(
+ origin,
+ collection_id: CollectionId,
+ token_id: TokenId,
+ properties: Vec<Property>
+ ) -> DispatchResultWithPostInfo {
+ ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);
+
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ dispatch_call::<T, _>(collection_id, |d| d.change_token_properties(sender, token_id, properties))
+ }
+
#[weight = T::CommonWeightInfo::create_multiple_items_ex(&data)]
#[transactional]
pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -54,8 +54,12 @@
dispatch_weight::<T>() + max_weight_of!(burn_item())
}
- fn set_property() -> Weight {
- dispatch_weight::<T>() + max_weight_of!(set_property())
+ fn change_collection_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(change_collection_properties(amount))
+ }
+
+ fn change_token_properties(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(change_token_properties(amount))
}
fn transfer() -> Weight {