difftreelog
feat external-internal api collection creation segreation
in: master
11 files changed
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -36,6 +36,13 @@
},
error,
})?;
+ handle.check_is_internal().map_err(|error| DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: Some(dispatch_weight::<T>()),
+ pays_fee: Pays::Yes,
+ },
+ error,
+ })?;
let dispatched = T::CollectionDispatch::dispatch(handle);
let mut result = call(dispatched.as_dyn());
match &mut result {
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -316,8 +316,9 @@
}
fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {
+ // TODO possibly delete for the lack of transaction
collection
- .check_is_mutable()
+ .check_is_internal()
.map_err(dispatch_to_evm::<T>)?;
<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
Ok(())
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -149,20 +149,16 @@
))
}
pub fn save(self) -> Result<(), DispatchError> {
- self.check_is_mutable()?;
<CollectionById<T>>::insert(self.id, self.collection);
Ok(())
}
pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
- self.check_is_mutable()?;
self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
Ok(())
}
pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {
- self.check_is_mutable()?;
-
if self.collection.sponsorship.pending_sponsor() != Some(sender) {
return Ok(false);
}
@@ -171,11 +167,21 @@
Ok(true)
}
- /// Checks that collection is can be mutate.
- /// Now check only `external_collection` flag and if it **true**, than return `CollectionIsReadOnly` error.
- pub fn check_is_mutable(&self) -> DispatchResult {
+ /// Checks that the collection was created with, and must be operated upon through **Unique API**.
+ /// Now check only the `external_collection` flag and if it's **true**, then return `CollectionIsExternal` error.
+ pub fn check_is_internal(&self) -> DispatchResult {
if self.external_collection {
- return Err(<Error<T>>::CollectionIsReadOnly)?;
+ return Err(<Error<T>>::CollectionIsExternal)?;
+ }
+
+ Ok(())
+ }
+
+ /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.
+ /// Now check only the `external_collection` flag and if it's **false**, then return `CollectionIsInternal` error.
+ pub fn check_is_external(&self) -> DispatchResult {
+ if !self.external_collection {
+ return Err(<Error<T>>::CollectionIsInternal)?;
}
Ok(())
@@ -449,8 +455,11 @@
/// Empty property keys are forbidden
EmptyPropertyKey,
- /// Collection is read only
- CollectionIsReadOnly,
+ /// Tried to access an external collection with an internal API
+ CollectionIsExternal,
+
+ /// Tried to access an internal collection with an external API
+ CollectionIsInternal,
}
#[pallet::storage]
@@ -754,6 +763,7 @@
pub fn init_collection(
owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ is_external: bool,
) -> Result<CollectionId, DispatchError> {
{
ensure!(
@@ -797,7 +807,7 @@
Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)
})
.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
- external_collection: false,
+ external_collection: is_external,
};
let mut collection_properties = up_data_structs::CollectionProperties::get();
@@ -854,7 +864,6 @@
collection: CollectionHandle<T>,
sender: &T::CrossAccountId,
) -> DispatchResult {
- collection.check_is_mutable()?;
ensure!(
collection.limits.owner_can_destroy(),
<Error<T>>::NoPermission,
@@ -884,7 +893,6 @@
sender: &T::CrossAccountId,
property: Property,
) -> DispatchResult {
- collection.check_is_mutable()?;
collection.check_is_owner_or_admin(sender)?;
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
@@ -930,8 +938,6 @@
sender: &T::CrossAccountId,
properties: Vec<Property>,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
for property in properties {
Self::set_collection_property(collection, sender, property)?;
}
@@ -944,7 +950,6 @@
sender: &T::CrossAccountId,
property_key: PropertyKey,
) -> DispatchResult {
- collection.check_is_mutable()?;
collection.check_is_owner_or_admin(sender)?;
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
@@ -966,8 +971,6 @@
sender: &T::CrossAccountId,
property_keys: Vec<PropertyKey>,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
for key in property_keys {
Self::delete_collection_property(collection, sender, key)?;
}
@@ -992,7 +995,6 @@
sender: &T::CrossAccountId,
property_permission: PropertyKeyPermission,
) -> DispatchResult {
- collection.check_is_mutable()?;
collection.check_is_owner_or_admin(sender)?;
let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);
@@ -1024,8 +1026,6 @@
sender: &T::CrossAccountId,
property_permissions: Vec<PropertyKeyPermission>,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
for prop_pemission in property_permissions {
Self::set_property_permission(collection, sender, prop_pemission)?;
}
@@ -1113,7 +1113,6 @@
user: &T::CrossAccountId,
allowed: bool,
) -> DispatchResult {
- collection.check_is_mutable()?;
collection.check_is_owner_or_admin(sender)?;
// =========
@@ -1133,7 +1132,6 @@
user: &T::CrossAccountId,
admin: bool,
) -> DispatchResult {
- collection.check_is_mutable()?;
collection.check_is_owner_or_admin(sender)?;
let was_admin = <IsAdmin<T>>::get((collection.id, user));
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -137,7 +137,7 @@
owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, data)
+ <PalletCommon<T>>::init_collection(owner, data, false)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
@@ -168,8 +168,6 @@
owner: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
let total_supply = <TotalSupply<T>>::get(collection.id)
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -216,8 +214,6 @@
amount: u128,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
ensure!(
collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed,
@@ -287,8 +283,6 @@
data: BTreeMap<T::CrossAccountId, u128>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
if !collection.is_owner_or_admin(sender) {
ensure!(
collection.permissions.mint_mode(),
@@ -390,7 +384,6 @@
spender: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- collection.check_is_mutable()?;
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(owner)?;
collection.check_allowlist(spender)?;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -304,8 +304,9 @@
pub fn init_collection(
owner: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ is_external: bool,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, data)
+ <PalletCommon<T>>::init_collection(owner, data, is_external)
}
pub fn destroy_collection(
collection: NonfungibleHandle<T>,
@@ -336,8 +337,6 @@
sender: &T::CrossAccountId,
token: TokenId,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
let token_data =
<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
ensure!(
@@ -458,7 +457,6 @@
&property.key,
is_token_create,
)?;
- collection.check_is_mutable()?;
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
let property = property.clone();
@@ -496,7 +494,6 @@
token_id: TokenId,
property_key: PropertyKey,
) -> DispatchResult {
- collection.check_is_mutable()?;
Self::check_token_change_permission(collection, sender, token_id, &property_key, false)?;
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
@@ -574,8 +571,6 @@
token_id: TokenId,
property_keys: Vec<PropertyKey>,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
for key in property_keys {
Self::delete_token_property(collection, sender, token_id, key)?;
}
@@ -622,8 +617,6 @@
token: TokenId,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
ensure!(
collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed
@@ -902,8 +895,6 @@
token: TokenId,
spender: Option<&T::CrossAccountId>,
) -> DispatchResult {
- collection.check_is_mutable()?;
-
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(sender)?;
if let Some(spender) = spender {
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -235,6 +235,7 @@
Self::unique_collection_id(collection_id)?,
misc::CollectionType::Regular,
)?;
+ collection.check_is_external()?;
<PalletNft<T>>::destroy_collection(collection, &cross_sender)
.map_err(Self::map_unique_err_to_proxy)?;
@@ -256,6 +257,9 @@
) -> DispatchResult {
let sender = ensure_signed(origin)?;
+ let collection = Self::get_nft_collection(Self::unique_collection_id(collection_id)?)?;
+ collection.check_is_external()?;
+
let new_issuer = T::Lookup::lookup(new_issuer)?;
Self::change_collection_owner(
@@ -287,6 +291,7 @@
Self::unique_collection_id(collection_id)?,
misc::CollectionType::Regular,
)?;
+ collection.check_is_external()?;
Self::check_collection_owner(&collection, &cross_sender)?;
@@ -318,17 +323,18 @@
let sender = ensure_signed(origin)?;
let sender = T::CrossAccountId::from_sub(sender);
let cross_owner = T::CrossAccountId::from_sub(owner.clone());
-
- let royalty_info = royalty_amount.map(|amount| rmrk_traits::RoyaltyInfo {
- recipient: recipient.unwrap_or_else(|| owner.clone()),
- amount,
- });
let collection = Self::get_typed_nft_collection(
Self::unique_collection_id(collection_id)?,
misc::CollectionType::Regular,
)?;
+ collection.check_is_external()?;
+ let royalty_info = royalty_amount.map(|amount| rmrk_traits::RoyaltyInfo {
+ recipient: recipient.unwrap_or_else(|| owner.clone()),
+ amount,
+ });
+
let nft_id = Self::create_nft(
&sender,
&cross_owner,
@@ -382,6 +388,12 @@
let sender = ensure_signed(origin)?;
let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+ let collection = Self::get_typed_nft_collection(
+ Self::unique_collection_id(collection_id)?,
+ misc::CollectionType::Regular,
+ )?;
+ collection.check_is_external()?;
+
Self::destroy_nft(
cross_sender,
Self::unique_collection_id(collection_id)?,
@@ -411,13 +423,14 @@
let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
let nft_id = rmrk_nft_id.into();
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let token_data =
<TokenData<T>>::get((collection_id, nft_id)).ok_or(<Error<T>>::NoAvailableNftId)?;
let from = token_data.owner;
-
- let collection =
- Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
ensure!(
Self::get_nft_property_decoded(collection_id, nft_id, RmrkProperty::Transferable)?,
@@ -516,6 +529,7 @@
let collection =
Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
let new_cross_owner = match new_owner {
RmrkAccountIdOrCollectionNftTuple::AccountId(ref account_id) => {
@@ -581,6 +595,10 @@
let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
let nft_id = rmrk_nft_id.into();
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
Self::destroy_nft(cross_sender, collection_id, nft_id).map_err(|err| {
if err == <CommonError<T>>::NoPermission.into()
|| err == <CommonError<T>>::ApprovedValueTooLow.into()
@@ -613,6 +631,9 @@
let collection_id = Self::unique_collection_id(rmrk_collection_id)
.map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
let nft_id = rmrk_nft_id.into();
let resource_id = rmrk_resource_id.into();
@@ -666,6 +687,9 @@
let collection_id = Self::unique_collection_id(rmrk_collection_id)
.map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
let nft_id = rmrk_nft_id.into();
let resource_id = rmrk_resource_id.into();
@@ -720,6 +744,10 @@
let sender = T::CrossAccountId::from_sub(sender);
let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let budget = budget::Value::new(NESTING_BUDGET);
match maybe_nft_id {
@@ -775,6 +803,11 @@
let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
let nft_id = rmrk_nft_id.into();
+
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let budget = budget::Value::new(NESTING_BUDGET);
Self::ensure_nft_type(collection_id, nft_id, NftType::Regular)?;
@@ -799,15 +832,20 @@
#[transactional]
pub fn add_basic_resource(
origin: OriginFor<T>,
- collection_id: RmrkCollectionId,
+ rmrk_collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
resource: RmrkBasicResource,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
+ let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let resource_id = Self::resource_add(
sender,
- Self::unique_collection_id(collection_id)?,
+ collection_id,
nft_id.into(),
[
Self::rmrk_property(TokenType, &NftType::Resource)?,
@@ -831,16 +869,21 @@
#[transactional]
pub fn add_composable_resource(
origin: OriginFor<T>,
- collection_id: RmrkCollectionId,
+ rmrk_collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
_resource_id: RmrkBoundedResource,
resource: RmrkComposableResource,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
+ let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let resource_id = Self::resource_add(
sender,
- Self::unique_collection_id(collection_id)?,
+ collection_id,
nft_id.into(),
[
Self::rmrk_property(TokenType, &NftType::Resource)?,
@@ -866,15 +909,20 @@
#[transactional]
pub fn add_slot_resource(
origin: OriginFor<T>,
- collection_id: RmrkCollectionId,
+ rmrk_collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
resource: RmrkSlotResource,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
+ let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
let resource_id = Self::resource_add(
sender,
- Self::unique_collection_id(collection_id)?,
+ collection_id,
nft_id.into(),
[
Self::rmrk_property(TokenType, &NftType::Resource)?,
@@ -900,18 +948,18 @@
#[transactional]
pub fn remove_resource(
origin: OriginFor<T>,
- collection_id: RmrkCollectionId,
+ rmrk_collection_id: RmrkCollectionId,
nft_id: RmrkNftId,
resource_id: RmrkResourceId,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
- Self::resource_remove(
- sender,
- Self::unique_collection_id(collection_id)?,
- nft_id.into(),
- resource_id.into(),
- )?;
+ let collection_id = Self::unique_collection_id(rmrk_collection_id)?;
+ let collection =
+ Self::get_typed_nft_collection(collection_id, misc::CollectionType::Regular)?;
+ collection.check_is_external()?;
+
+ Self::resource_remove(sender, collection_id, nft_id.into(), resource_id.into())?;
Self::deposit_event(Event::ResourceRemoval {
nft_id,
@@ -968,7 +1016,7 @@
data: CreateCollectionData<T::AccountId>,
properties: impl Iterator<Item = Property>,
) -> Result<CollectionId, DispatchError> {
- let collection_id = <PalletNft<T>>::init_collection(sender, data);
+ let collection_id = <PalletNft<T>>::init_collection(sender, data, true);
if let Err(DispatchError::Arithmetic(_)) = &collection_id {
return Err(<Error<T>>::NoAvailableCollectionId.into());
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -94,7 +94,8 @@
..Default::default()
};
- let collection_id_res = <PalletNft<T>>::init_collection(cross_sender.clone(), data);
+ let collection_id_res =
+ <PalletNft<T>>::init_collection(cross_sender.clone(), data, true);
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
return Err(<Error<T>>::NoAvailableBaseId.into());
@@ -155,6 +156,7 @@
misc::CollectionType::Base,
)
.map_err(|_| <Error<T>>::BaseDoesntExist)?;
+ collection.check_is_external()?;
if theme.name.as_slice() == b"default" {
<BaseHasDefaultTheme<T>>::insert(collection_id, true);
pallets/refungible/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 frame_support::{ensure, BoundedVec};20use up_data_structs::{21 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,22 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,23};24use pallet_evm::account::CrossAccountId;25use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};26use pallet_structure::Pallet as PalletStructure;27use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};28use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};29use core::ops::Deref;30use codec::{Encode, Decode, MaxEncodedLen};31use scale_info::TypeInfo;3233pub use pallet::*;34#[cfg(feature = "runtime-benchmarks")]35pub mod benchmarking;36pub mod common;37pub mod erc;38pub mod weights;39pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4041#[struct_versioning::versioned(version = 2, upper)]42#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]43pub struct ItemData {44 pub const_data: BoundedVec<u8, CustomDataLimit>,4546 #[version(..2)]47 pub variable_data: BoundedVec<u8, CustomDataLimit>,48}4950#[frame_support::pallet]51pub mod pallet {52 use super::*;53 use frame_support::{54 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,55 traits::StorageVersion,56 };57 use frame_system::pallet_prelude::*;58 use up_data_structs::{CollectionId, TokenId};59 use super::weights::WeightInfo;6061 #[pallet::error]62 pub enum Error<T> {63 /// Not Refungible item data used to mint in Refungible collection.64 NotRefungibleDataUsedToMintFungibleCollectionToken,65 /// Maximum refungibility exceeded66 WrongRefungiblePieces,67 /// Refungible token can't nest other tokens68 RefungibleDisallowsNesting,69 /// Setting item properties is not allowed70 SettingPropertiesNotAllowed,71 }7273 #[pallet::config]74 pub trait Config:75 frame_system::Config + pallet_common::Config + pallet_structure::Config76 {77 type WeightInfo: WeightInfo;78 }7980 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8182 #[pallet::pallet]83 #[pallet::storage_version(STORAGE_VERSION)]84 #[pallet::generate_store(pub(super) trait Store)]85 pub struct Pallet<T>(_);8687 #[pallet::storage]88 pub type TokensMinted<T: Config> =89 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;90 #[pallet::storage]91 pub type TokensBurnt<T: Config> =92 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9394 #[pallet::storage]95 pub type TokenData<T: Config> = StorageNMap<96 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),97 Value = ItemData,98 QueryKind = ValueQuery,99 >;100101 #[pallet::storage]102 pub type TotalSupply<T: Config> = StorageNMap<103 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),104 Value = u128,105 QueryKind = ValueQuery,106 >;107108 /// Used to enumerate tokens owned by account109 #[pallet::storage]110 pub type Owned<T: Config> = StorageNMap<111 Key = (112 Key<Twox64Concat, CollectionId>,113 Key<Blake2_128Concat, T::CrossAccountId>,114 Key<Twox64Concat, TokenId>,115 ),116 Value = bool,117 QueryKind = ValueQuery,118 >;119120 #[pallet::storage]121 pub type AccountBalance<T: Config> = StorageNMap<122 Key = (123 Key<Twox64Concat, CollectionId>,124 // Owner125 Key<Blake2_128Concat, T::CrossAccountId>,126 ),127 Value = u32,128 QueryKind = ValueQuery,129 >;130131 #[pallet::storage]132 pub type Balance<T: Config> = StorageNMap<133 Key = (134 Key<Twox64Concat, CollectionId>,135 Key<Twox64Concat, TokenId>,136 // Owner137 Key<Blake2_128Concat, T::CrossAccountId>,138 ),139 Value = u128,140 QueryKind = ValueQuery,141 >;142143 #[pallet::storage]144 pub type Allowance<T: Config> = StorageNMap<145 Key = (146 Key<Twox64Concat, CollectionId>,147 Key<Twox64Concat, TokenId>,148 // Owner149 Key<Blake2_128, T::CrossAccountId>,150 // Spender151 Key<Blake2_128Concat, T::CrossAccountId>,152 ),153 Value = u128,154 QueryKind = ValueQuery,155 >;156157 #[pallet::hooks]158 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {159 fn on_runtime_upgrade() -> Weight {160 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {161 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {162 Some(<ItemDataVersion2>::from(v))163 })164 }165166 0167 }168 }169}170171pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);172impl<T: Config> RefungibleHandle<T> {173 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {174 Self(inner)175 }176 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {177 self.0178 }179}180impl<T: Config> Deref for RefungibleHandle<T> {181 type Target = pallet_common::CollectionHandle<T>;182183 fn deref(&self) -> &Self::Target {184 &self.0185 }186}187188impl<T: Config> Pallet<T> {189 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {190 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)191 }192 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {193 <TotalSupply<T>>::contains_key((collection.id, token))194 }195}196197// unchecked calls skips any permission checks198impl<T: Config> Pallet<T> {199 pub fn init_collection(200 owner: T::CrossAccountId,201 data: CreateCollectionData<T::AccountId>,202 ) -> Result<CollectionId, DispatchError> {203 <PalletCommon<T>>::init_collection(owner, data)204 }205 pub fn destroy_collection(206 collection: RefungibleHandle<T>,207 sender: &T::CrossAccountId,208 ) -> DispatchResult {209 let id = collection.id;210211 if Self::collection_has_tokens(id) {212 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());213 }214215 // =========216217 PalletCommon::destroy_collection(collection.0, sender)?;218219 <TokensMinted<T>>::remove(id);220 <TokensBurnt<T>>::remove(id);221 <TokenData<T>>::remove_prefix((id,), None);222 <TotalSupply<T>>::remove_prefix((id,), None);223 <Balance<T>>::remove_prefix((id,), None);224 <Allowance<T>>::remove_prefix((id,), None);225 <Owned<T>>::remove_prefix((id,), None);226 <AccountBalance<T>>::remove_prefix((id,), None);227 Ok(())228 }229230 fn collection_has_tokens(collection_id: CollectionId) -> bool {231 <TokenData<T>>::iter_prefix((collection_id,))232 .next()233 .is_some()234 }235236 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {237 collection.check_is_mutable()?;238 let burnt = <TokensBurnt<T>>::get(collection.id)239 .checked_add(1)240 .ok_or(ArithmeticError::Overflow)?;241242 <TokensBurnt<T>>::insert(collection.id, burnt);243 <TokenData<T>>::remove((collection.id, token_id));244 <TotalSupply<T>>::remove((collection.id, token_id));245 <Balance<T>>::remove_prefix((collection.id, token_id), None);246 <Allowance<T>>::remove_prefix((collection.id, token_id), None);247 // TODO: ERC721 transfer event248 Ok(())249 }250251 pub fn burn(252 collection: &RefungibleHandle<T>,253 owner: &T::CrossAccountId,254 token: TokenId,255 amount: u128,256 ) -> DispatchResult {257 collection.check_is_mutable()?;258 let total_supply = <TotalSupply<T>>::get((collection.id, token))259 .checked_sub(amount)260 .ok_or(<CommonError<T>>::TokenValueTooLow)?;261262 // This was probally last owner of this token?263 if total_supply == 0 {264 // Ensure user actually owns this amount265 ensure!(266 <Balance<T>>::get((collection.id, token, owner)) == amount,267 <CommonError<T>>::TokenValueTooLow268 );269 let account_balance = <AccountBalance<T>>::get((collection.id, owner))270 .checked_sub(1)271 // Should not occur272 .ok_or(ArithmeticError::Underflow)?;273274 // =========275276 <Owned<T>>::remove((collection.id, owner, token));277 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);278 <AccountBalance<T>>::insert((collection.id, owner), account_balance);279 Self::burn_token(collection, token)?;280 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(281 collection.id,282 token,283 owner.clone(),284 amount,285 ));286 return Ok(());287 }288289 let balance = <Balance<T>>::get((collection.id, token, owner))290 .checked_sub(amount)291 .ok_or(<CommonError<T>>::TokenValueTooLow)?;292 let account_balance = if balance == 0 {293 <AccountBalance<T>>::get((collection.id, owner))294 .checked_sub(1)295 // Should not occur296 .ok_or(ArithmeticError::Underflow)?297 } else {298 0299 };300301 // =========302303 if balance == 0 {304 <Owned<T>>::remove((collection.id, owner, token));305 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);306 <Balance<T>>::remove((collection.id, token, owner));307 <AccountBalance<T>>::insert((collection.id, owner), account_balance);308 } else {309 <Balance<T>>::insert((collection.id, token, owner), balance);310 }311 <TotalSupply<T>>::insert((collection.id, token), total_supply);312 // TODO: ERC20 transfer event313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 owner.clone(),317 amount,318 ));319 Ok(())320 }321322 pub fn transfer(323 collection: &RefungibleHandle<T>,324 from: &T::CrossAccountId,325 to: &T::CrossAccountId,326 token: TokenId,327 amount: u128,328 nesting_budget: &dyn Budget,329 ) -> DispatchResult {330 collection.check_is_mutable()?;331 ensure!(332 collection.limits.transfers_enabled(),333 <CommonError<T>>::TransferNotAllowed334 );335336 if collection.permissions.access() == AccessMode::AllowList {337 collection.check_allowlist(from)?;338 collection.check_allowlist(to)?;339 }340 <PalletCommon<T>>::ensure_correct_receiver(to)?;341342 let balance_from = <Balance<T>>::get((collection.id, token, from))343 .checked_sub(amount)344 .ok_or(<CommonError<T>>::TokenValueTooLow)?;345 let mut create_target = false;346 let from_to_differ = from != to;347 let balance_to = if from != to {348 let old_balance = <Balance<T>>::get((collection.id, token, to));349 if old_balance == 0 {350 create_target = true;351 }352 Some(353 old_balance354 .checked_add(amount)355 .ok_or(ArithmeticError::Overflow)?,356 )357 } else {358 None359 };360361 let account_balance_from = if balance_from == 0 {362 Some(363 <AccountBalance<T>>::get((collection.id, from))364 .checked_sub(1)365 // Should not occur366 .ok_or(ArithmeticError::Underflow)?,367 )368 } else {369 None370 };371 // Account data is created in token, AccountBalance should be increased372 // But only if from != to as we shouldn't check overflow in this case373 let account_balance_to = if create_target && from_to_differ {374 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))375 .checked_add(1)376 .ok_or(ArithmeticError::Overflow)?;377 ensure!(378 account_balance_to < collection.limits.account_token_ownership_limit(),379 <CommonError<T>>::AccountTokenLimitExceeded,380 );381382 Some(account_balance_to)383 } else {384 None385 };386387 // =========388389 <PalletStructure<T>>::nest_if_sent_to_token(390 from.clone(),391 to,392 collection.id,393 token,394 nesting_budget,395 )?;396397 if let Some(balance_to) = balance_to {398 // from != to399 if balance_from == 0 {400 <Balance<T>>::remove((collection.id, token, from));401 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);402 } else {403 <Balance<T>>::insert((collection.id, token, from), balance_from);404 }405 <Balance<T>>::insert((collection.id, token, to), balance_to);406 if let Some(account_balance_from) = account_balance_from {407 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);408 <Owned<T>>::remove((collection.id, from, token));409 }410 if let Some(account_balance_to) = account_balance_to {411 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);412 <Owned<T>>::insert((collection.id, to, token), true);413 }414 }415416 // TODO: ERC20 transfer event417 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(418 collection.id,419 token,420 from.clone(),421 to.clone(),422 amount,423 ));424 Ok(())425 }426427 pub fn create_multiple_items(428 collection: &RefungibleHandle<T>,429 sender: &T::CrossAccountId,430 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,431 nesting_budget: &dyn Budget,432 ) -> DispatchResult {433 if !collection.is_owner_or_admin(sender) {434 ensure!(435 collection.permissions.mint_mode(),436 <CommonError<T>>::PublicMintingNotAllowed437 );438 collection.check_allowlist(sender)?;439440 for item in data.iter() {441 for user in item.users.keys() {442 collection.check_allowlist(user)?;443 }444 }445 }446447 for item in data.iter() {448 for (owner, _) in item.users.iter() {449 <PalletCommon<T>>::ensure_correct_receiver(owner)?;450 }451 }452453 // Total pieces per tokens454 let totals = data455 .iter()456 .map(|data| {457 Ok(data458 .users459 .iter()460 .map(|u| u.1)461 .try_fold(0u128, |acc, v| acc.checked_add(*v))462 .ok_or(ArithmeticError::Overflow)?)463 })464 .collect::<Result<Vec<_>, DispatchError>>()?;465 for total in &totals {466 ensure!(467 *total <= MAX_REFUNGIBLE_PIECES,468 <Error<T>>::WrongRefungiblePieces469 );470 }471472 let first_token_id = <TokensMinted<T>>::get(collection.id);473 let tokens_minted = first_token_id474 .checked_add(data.len() as u32)475 .ok_or(ArithmeticError::Overflow)?;476 ensure!(477 tokens_minted < collection.limits.token_limit(),478 <CommonError<T>>::CollectionTokenLimitExceeded479 );480481 let mut balances = BTreeMap::new();482 for data in &data {483 for owner in data.users.keys() {484 let balance = balances485 .entry(owner)486 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));487 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;488489 ensure!(490 *balance <= collection.limits.account_token_ownership_limit(),491 <CommonError<T>>::AccountTokenLimitExceeded,492 );493 }494 }495496 for (i, token) in data.iter().enumerate() {497 let token_id = TokenId(first_token_id + i as u32 + 1);498 for (to, _) in token.users.iter() {499 <PalletStructure<T>>::check_nesting(500 sender.clone(),501 to,502 collection.id,503 token_id,504 nesting_budget,505 )?;506 }507 }508509 // =========510511 <TokensMinted<T>>::insert(collection.id, tokens_minted);512 for (account, balance) in balances {513 <AccountBalance<T>>::insert((collection.id, account), balance);514 }515 for (i, token) in data.into_iter().enumerate() {516 let token_id = first_token_id + i as u32 + 1;517 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);518519 <TokenData<T>>::insert(520 (collection.id, token_id),521 ItemData {522 const_data: token.const_data,523 },524 );525526 for (user, amount) in token.users.into_iter() {527 if amount == 0 {528 continue;529 }530 <Balance<T>>::insert((collection.id, token_id, &user), amount);531 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);532 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(533 &user,534 collection.id,535 TokenId(token_id),536 );537538 // TODO: ERC20 transfer event539 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(540 collection.id,541 TokenId(token_id),542 user,543 amount,544 ));545 }546 }547 Ok(())548 }549550 pub fn set_allowance_unchecked(551 collection: &RefungibleHandle<T>,552 sender: &T::CrossAccountId,553 spender: &T::CrossAccountId,554 token: TokenId,555 amount: u128,556 ) {557 if amount == 0 {558 <Allowance<T>>::remove((collection.id, token, sender, spender));559 } else {560 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);561 }562 // TODO: ERC20 approval event563 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(564 collection.id,565 token,566 sender.clone(),567 spender.clone(),568 amount,569 ))570 }571572 pub fn set_allowance(573 collection: &RefungibleHandle<T>,574 sender: &T::CrossAccountId,575 spender: &T::CrossAccountId,576 token: TokenId,577 amount: u128,578 ) -> DispatchResult {579 collection.check_is_mutable()?;580 if collection.permissions.access() == AccessMode::AllowList {581 collection.check_allowlist(sender)?;582 collection.check_allowlist(spender)?;583 }584585 <PalletCommon<T>>::ensure_correct_receiver(spender)?;586587 if <Balance<T>>::get((collection.id, token, sender)) < amount {588 ensure!(589 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),590 <CommonError<T>>::CantApproveMoreThanOwned591 );592 }593594 // =========595596 Self::set_allowance_unchecked(collection, sender, spender, token, amount);597 Ok(())598 }599600 /// Returns allowance, which should be set after transaction601 fn check_allowed(602 collection: &RefungibleHandle<T>,603 spender: &T::CrossAccountId,604 from: &T::CrossAccountId,605 token: TokenId,606 amount: u128,607 nesting_budget: &dyn Budget,608 ) -> Result<Option<u128>, DispatchError> {609 if spender.conv_eq(from) {610 return Ok(None);611 }612 if collection.permissions.access() == AccessMode::AllowList {613 // `from`, `to` checked in [`transfer`]614 collection.check_allowlist(spender)?;615 }616 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {617 // TODO: should collection owner be allowed to perform this transfer?618 ensure!(619 <PalletStructure<T>>::check_indirectly_owned(620 spender.clone(),621 source.0,622 source.1,623 None,624 nesting_budget625 )?,626 <CommonError<T>>::ApprovedValueTooLow,627 );628 return Ok(None);629 }630 let allowance =631 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);632 if allowance.is_none() {633 ensure!(634 collection.ignores_allowance(spender),635 <CommonError<T>>::ApprovedValueTooLow636 );637 }638 Ok(allowance)639 }640641 pub fn transfer_from(642 collection: &RefungibleHandle<T>,643 spender: &T::CrossAccountId,644 from: &T::CrossAccountId,645 to: &T::CrossAccountId,646 token: TokenId,647 amount: u128,648 nesting_budget: &dyn Budget,649 ) -> DispatchResult {650 let allowance =651 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;652653 // =========654655 Self::transfer(collection, from, to, token, amount, nesting_budget)?;656 if let Some(allowance) = allowance {657 Self::set_allowance_unchecked(collection, from, spender, token, allowance);658 }659 Ok(())660 }661662 pub fn burn_from(663 collection: &RefungibleHandle<T>,664 spender: &T::CrossAccountId,665 from: &T::CrossAccountId,666 token: TokenId,667 amount: u128,668 nesting_budget: &dyn Budget,669 ) -> DispatchResult {670 let allowance =671 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;672673 // =========674675 Self::burn(collection, from, token, amount)?;676 if let Some(allowance) = allowance {677 Self::set_allowance_unchecked(collection, from, spender, token, allowance);678 }679 Ok(())680 }681682 /// Delegated to `create_multiple_items`683 pub fn create_item(684 collection: &RefungibleHandle<T>,685 sender: &T::CrossAccountId,686 data: CreateRefungibleExData<T::CrossAccountId>,687 nesting_budget: &dyn Budget,688 ) -> DispatchResult {689 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)690 }691}pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -92,8 +92,9 @@
..Default::default()
};
- let collection_id = <pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id =
+ <pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -304,7 +304,7 @@
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- collection.check_is_mutable()?;
+ collection.check_is_internal()?;
// =========
@@ -339,6 +339,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_internal()?;
<PalletCommon<T>>::toggle_allowlist(
&collection,
@@ -373,6 +374,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_internal()?;
<PalletCommon<T>>::toggle_allowlist(
&collection,
@@ -407,7 +409,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_mutable()?;
+ target_collection.check_is_internal()?;
target_collection.check_is_owner(&sender)?;
target_collection.owner = new_owner.clone();
@@ -437,6 +439,7 @@
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_internal()?;
<Pallet<T>>::deposit_event(Event::<T>::CollectionAdminAdded(
collection_id,
@@ -463,6 +466,7 @@
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_internal()?;
<Pallet<T>>::deposit_event(Event::<T>::CollectionAdminRemoved(
collection_id,
@@ -488,6 +492,7 @@
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
+ target_collection.check_is_internal()?;
target_collection.set_sponsor(new_sponsor.clone())?;
@@ -512,6 +517,7 @@
let sender = ensure_signed(origin)?;
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_internal()?;
ensure!(
target_collection.confirm_sponsorship(&sender)?,
Error::<T>::ConfirmUnsetSponsorFail
@@ -540,6 +546,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_internal()?;
target_collection.check_is_owner(&sender)?;
target_collection.sponsorship = SponsorshipState::Disabled;
@@ -704,6 +711,7 @@
pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_internal()?;
target_collection.check_is_owner(&sender)?;
// =========
@@ -858,6 +866,7 @@
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_internal()?;
target_collection.check_is_owner(&sender)?;
let old_limit = &target_collection.limits;
@@ -879,6 +888,7 @@
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_internal()?;
target_collection.check_is_owner(&sender)?;
let old_limit = &target_collection.permissions;
runtime/common/src/dispatch.rsdiffbeforeafterboth--- a/runtime/common/src/dispatch.rs
+++ b/runtime/common/src/dispatch.rs
@@ -35,7 +35,7 @@
data: CreateCollectionData<T::AccountId>,
) -> DispatchResult {
let _id = match data.mode {
- CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data)?,
+ CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data, false)?,
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(