difftreelog
doc: fix PR
in: master
3 files changed
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -25,7 +25,7 @@
/// Helper function to implement substrate calls for common collection methods.
///
/// * `collection` - The collection on which to call the method.
-/// * `call` - The function in which to call the corresponding method from [CommonCollectionOperations].
+/// * `call` - The function in which to call the corresponding method from [`CommonCollectionOperations`].
pub fn dispatch_tx<
T: Config,
C: FnOnce(&dyn CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
pallets/common/src/erc.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//! This module contains the implementation of pallet methods for evm.1819use evm_coder::{20 solidity_interface, solidity, ToLog,21 types::*,22 execution::{Result, Error},23};24pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_std::vec::Vec;27use up_data_structs::{28 Property, SponsoringRateLimit, OwnerRestrictedSet, AccessMode, CollectionPermissions,29};30use alloc::format;3132use crate::{Pallet, CollectionHandle, Config, CollectionProperties};3334/// Events for ethereum collection helper.35#[derive(ToLog)]36pub enum CollectionHelpersEvents {37 /// The collection has been created.38 CollectionCreated {39 /// Collection owner.40 #[indexed]41 owner: address,4243 /// Collection ID.44 #[indexed]45 collection_id: address,46 },47}4849/// Does not always represent a full collection, for RFT it is either50/// collection (Implementing ERC721), or specific collection token (Implementing ERC20).51pub trait CommonEvmHandler {52 const CODE: &'static [u8];5354 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;55}5657/// @title A contract that allows you to work with collections.58#[solidity_interface(name = "Collection")]59impl<T: Config> CollectionHandle<T>60where61 T::AccountId: From<[u8; 32]>,62{63 /// Set collection property.64 ///65 /// @param key Property key.66 /// @param value Propery value.67 fn set_collection_property(68 &mut self,69 caller: caller,70 key: string,71 value: bytes,72 ) -> Result<void> {73 let caller = T::CrossAccountId::from_eth(caller);74 let key = <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "key too large")?;77 let value = value.try_into().map_err(|_| "value too large")?;7879 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })80 .map_err(dispatch_to_evm::<T>)81 }8283 /// Delete collection property.84 ///85 /// @param key Property key.86 fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {87 let caller = T::CrossAccountId::from_eth(caller);88 let key = <Vec<u8>>::from(key)89 .try_into()90 .map_err(|_| "key too large")?;9192 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)93 }9495 /// Get collection property.96 ///97 /// @dev Throws error if key not found.98 ///99 /// @param key Property key.100 /// @return bytes The property corresponding to the key.101 fn collection_property(&self, key: string) -> Result<bytes> {102 let key = <Vec<u8>>::from(key)103 .try_into()104 .map_err(|_| "key too large")?;105106 let props = <CollectionProperties<T>>::get(self.id);107 let prop = props.get(&key).ok_or("key not found")?;108109 Ok(prop.to_vec())110 }111112 /// Set the sponsor of the collection.113 ///114 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.115 ///116 /// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.117 fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {118 check_is_owner_or_admin(caller, self)?;119120 let sponsor = T::CrossAccountId::from_eth(sponsor);121 self.set_sponsor(sponsor.as_sub().clone())122 .map_err(dispatch_to_evm::<T>)?;123 save(self)124 }125126 /// Collection sponsorship confirmation.127 ///128 /// @dev After setting the sponsor for the collection, it must be confirmed with this function.129 fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {130 let caller = T::CrossAccountId::from_eth(caller);131 if !self132 .confirm_sponsorship(caller.as_sub())133 .map_err(dispatch_to_evm::<T>)?134 {135 return Err("caller is not set as sponsor".into());136 }137 save(self)138 }139140 /// Set limits for the collection.141 /// @dev Throws error if limit not found.142 /// @param limit Name of the limit. Valid names:143 /// "accountTokenOwnershipLimit",144 /// "sponsoredDataSize",145 /// "sponsoredDataRateLimit",146 /// "tokenLimit",147 /// "sponsorTransferTimeout",148 /// "sponsorApproveTimeout"149 /// @param value Value of the limit.150 #[solidity(rename_selector = "setCollectionLimit")]151 fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {152 check_is_owner_or_admin(caller, self)?;153 let mut limits = self.limits.clone();154155 match limit.as_str() {156 "accountTokenOwnershipLimit" => {157 limits.account_token_ownership_limit = Some(value);158 }159 "sponsoredDataSize" => {160 limits.sponsored_data_size = Some(value);161 }162 "sponsoredDataRateLimit" => {163 limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));164 }165 "tokenLimit" => {166 limits.token_limit = Some(value);167 }168 "sponsorTransferTimeout" => {169 limits.sponsor_transfer_timeout = Some(value);170 }171 "sponsorApproveTimeout" => {172 limits.sponsor_approve_timeout = Some(value);173 }174 _ => {175 return Err(Error::Revert(format!(176 "unknown integer limit \"{}\"",177 limit178 )))179 }180 }181 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)182 .map_err(dispatch_to_evm::<T>)?;183 save(self)184 }185186 /// Set limits for the collection.187 /// @dev Throws error if limit not found.188 /// @param limit Name of the limit. Valid names:189 /// "ownerCanTransfer",190 /// "ownerCanDestroy",191 /// "transfersEnabled"192 /// @param value Value of the limit.193 #[solidity(rename_selector = "setCollectionLimit")]194 fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {195 check_is_owner_or_admin(caller, self)?;196 let mut limits = self.limits.clone();197198 match limit.as_str() {199 "ownerCanTransfer" => {200 limits.owner_can_transfer = Some(value);201 }202 "ownerCanDestroy" => {203 limits.owner_can_destroy = Some(value);204 }205 "transfersEnabled" => {206 limits.transfers_enabled = Some(value);207 }208 _ => {209 return Err(Error::Revert(format!(210 "unknown boolean limit \"{}\"",211 limit212 )))213 }214 }215 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)216 .map_err(dispatch_to_evm::<T>)?;217 save(self)218 }219220 /// Get contract address.221 fn contract_address(&self, _caller: caller) -> Result<address> {222 Ok(crate::eth::collection_id_to_address(self.id))223 }224225 /// Add collection admin by substrate address.226 /// @param new_admin Substrate administrator address.227 fn add_collection_admin_substrate(&self, caller: caller, new_admin: uint256) -> Result<void> {228 let caller = T::CrossAccountId::from_eth(caller);229 let mut new_admin_arr: [u8; 32] = Default::default();230 new_admin.to_big_endian(&mut new_admin_arr);231 let account_id = T::AccountId::from(new_admin_arr);232 let new_admin = T::CrossAccountId::from_sub(account_id);233 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;234 Ok(())235 }236237 /// Remove collection admin by substrate address.238 /// @param admin Substrate administrator address.239 fn remove_collection_admin_substrate(&self, caller: caller, admin: uint256) -> Result<void> {240 let caller = T::CrossAccountId::from_eth(caller);241 let mut admin_arr: [u8; 32] = Default::default();242 admin.to_big_endian(&mut admin_arr);243 let account_id = T::AccountId::from(admin_arr);244 let admin = T::CrossAccountId::from_sub(account_id);245 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;246 Ok(())247 }248249 /// Add collection admin.250 /// @param new_admin Address of the added administrator.251 fn add_collection_admin(&self, caller: caller, new_admin: address) -> Result<void> {252 let caller = T::CrossAccountId::from_eth(caller);253 let new_admin = T::CrossAccountId::from_eth(new_admin);254 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;255 Ok(())256 }257258 /// Remove collection admin.259 ///260 /// @param new_admin Address of the removed administrator.261 fn remove_collection_admin(&self, caller: caller, admin: address) -> Result<void> {262 let caller = T::CrossAccountId::from_eth(caller);263 let admin = T::CrossAccountId::from_eth(admin);264 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;265 Ok(())266 }267268 /// Toggle accessibility of collection nesting.269 ///270 /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'271 #[solidity(rename_selector = "setCollectionNesting")]272 fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {273 check_is_owner_or_admin(caller, self)?;274275 let mut permissions = self.collection.permissions.clone();276 let mut nesting = permissions.nesting().clone();277 nesting.token_owner = enable;278 nesting.restricted = None;279 permissions.nesting = Some(nesting);280281 self.collection.permissions = <Pallet<T>>::clamp_permissions(282 self.collection.mode.clone(),283 &self.collection.permissions,284 permissions,285 )286 .map_err(dispatch_to_evm::<T>)?;287288 save(self)289 }290291 /// Toggle accessibility of collection nesting.292 ///293 /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'294 /// @param collections Addresses of collections that will be available for nesting.295 #[solidity(rename_selector = "setCollectionNesting")]296 fn set_nesting(297 &mut self,298 caller: caller,299 enable: bool,300 collections: Vec<address>,301 ) -> Result<void> {302 if collections.is_empty() {303 return Err("no addresses provided".into());304 }305 check_is_owner_or_admin(caller, self)?;306307 let mut permissions = self.collection.permissions.clone();308 match enable {309 false => {310 let mut nesting = permissions.nesting().clone();311 nesting.token_owner = false;312 nesting.restricted = None;313 permissions.nesting = Some(nesting);314 }315 true => {316 let mut bv = OwnerRestrictedSet::new();317 for i in collections {318 bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or(Error::Revert(319 "Can't convert address into collection id".into(),320 ))?)321 .map_err(|_| "too many collections")?;322 }323 let mut nesting = permissions.nesting().clone();324 nesting.token_owner = true;325 nesting.restricted = Some(bv);326 permissions.nesting = Some(nesting);327 }328 };329330 self.collection.permissions = <Pallet<T>>::clamp_permissions(331 self.collection.mode.clone(),332 &self.collection.permissions,333 permissions,334 )335 .map_err(dispatch_to_evm::<T>)?;336337 save(self)338 }339340 /// Set the collection access method.341 /// @param mode Access mode342 /// 0 for Normal343 /// 1 for AllowList344 fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {345 check_is_owner_or_admin(caller, self)?;346 let permissions = CollectionPermissions {347 access: Some(match mode {348 0 => AccessMode::Normal,349 1 => AccessMode::AllowList,350 _ => return Err("not supported access mode".into()),351 }),352 ..Default::default()353 };354 self.collection.permissions = <Pallet<T>>::clamp_permissions(355 self.collection.mode.clone(),356 &self.collection.permissions,357 permissions,358 )359 .map_err(dispatch_to_evm::<T>)?;360361 save(self)362 }363364 /// Add the user to the allowed list.365 ///366 /// @param user Address of a trusted user.367 fn add_to_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {368 let caller = T::CrossAccountId::from_eth(caller);369 let user = T::CrossAccountId::from_eth(user);370 <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;371 Ok(())372 }373374 /// Remove the user from the allowed list.375 ///376 /// @param user Address of a removed user.377 fn remove_from_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {378 let caller = T::CrossAccountId::from_eth(caller);379 let user = T::CrossAccountId::from_eth(user);380 <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;381 Ok(())382 }383384 /// Switch permission for minting.385 ///386 /// @param mode Enable if "true".387 fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {388 check_is_owner_or_admin(caller, self)?;389 let permissions = CollectionPermissions {390 mint_mode: Some(mode),391 ..Default::default()392 };393 self.collection.permissions = <Pallet<T>>::clamp_permissions(394 self.collection.mode.clone(),395 &self.collection.permissions,396 permissions,397 )398 .map_err(dispatch_to_evm::<T>)?;399400 save(self)401 }402}403404fn check_is_owner_or_admin<T: Config>(405 caller: caller,406 collection: &CollectionHandle<T>,407) -> Result<T::CrossAccountId> {408 let caller = T::CrossAccountId::from_eth(caller);409 collection410 .check_is_owner_or_admin(&caller)411 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;412 Ok(caller)413}414415fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {416 // TODO possibly delete for the lack of transaction417 collection418 .check_is_internal()419 .map_err(dispatch_to_evm::<T>)?;420 <crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());421 Ok(())422}423424/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).425pub fn token_uri_key() -> up_data_structs::PropertyKey {426 b"tokenURI"427 .to_vec()428 .try_into()429 .expect("length < limit; qed")430}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//! This module contains the implementation of pallet methods for evm.1819use evm_coder::{20 solidity_interface, solidity, ToLog,21 types::*,22 execution::{Result, Error},23};24pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_std::vec::Vec;27use up_data_structs::{28 Property, SponsoringRateLimit, OwnerRestrictedSet, AccessMode, CollectionPermissions,29};30use alloc::format;3132use crate::{Pallet, CollectionHandle, Config, CollectionProperties};3334/// Events for ethereum collection helper.35#[derive(ToLog)]36pub enum CollectionHelpersEvents {37 /// The collection has been created.38 CollectionCreated {39 /// Collection owner.40 #[indexed]41 owner: address,4243 /// Collection ID.44 #[indexed]45 collection_id: address,46 },47}4849/// Does not always represent a full collection, for RFT it is either50/// collection (Implementing ERC721), or specific collection token (Implementing ERC20).51pub trait CommonEvmHandler {52 const CODE: &'static [u8];5354 /// Call precompiled handle.55 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;56}5758/// @title A contract that allows you to work with collections.59#[solidity_interface(name = "Collection")]60impl<T: Config> CollectionHandle<T>61where62 T::AccountId: From<[u8; 32]>,63{64 /// Set collection property.65 ///66 /// @param key Property key.67 /// @param value Propery value.68 fn set_collection_property(69 &mut self,70 caller: caller,71 key: string,72 value: bytes,73 ) -> Result<void> {74 let caller = T::CrossAccountId::from_eth(caller);75 let key = <Vec<u8>>::from(key)76 .try_into()77 .map_err(|_| "key too large")?;78 let value = value.try_into().map_err(|_| "value too large")?;7980 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })81 .map_err(dispatch_to_evm::<T>)82 }8384 /// Delete collection property.85 ///86 /// @param key Property key.87 fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {88 let caller = T::CrossAccountId::from_eth(caller);89 let key = <Vec<u8>>::from(key)90 .try_into()91 .map_err(|_| "key too large")?;9293 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)94 }9596 /// Get collection property.97 ///98 /// @dev Throws error if key not found.99 ///100 /// @param key Property key.101 /// @return bytes The property corresponding to the key.102 fn collection_property(&self, key: string) -> Result<bytes> {103 let key = <Vec<u8>>::from(key)104 .try_into()105 .map_err(|_| "key too large")?;106107 let props = <CollectionProperties<T>>::get(self.id);108 let prop = props.get(&key).ok_or("key not found")?;109110 Ok(prop.to_vec())111 }112113 /// Set the sponsor of the collection.114 ///115 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.116 ///117 /// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.118 fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {119 check_is_owner_or_admin(caller, self)?;120121 let sponsor = T::CrossAccountId::from_eth(sponsor);122 self.set_sponsor(sponsor.as_sub().clone())123 .map_err(dispatch_to_evm::<T>)?;124 save(self)125 }126127 /// Collection sponsorship confirmation.128 ///129 /// @dev After setting the sponsor for the collection, it must be confirmed with this function.130 fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {131 let caller = T::CrossAccountId::from_eth(caller);132 if !self133 .confirm_sponsorship(caller.as_sub())134 .map_err(dispatch_to_evm::<T>)?135 {136 return Err("caller is not set as sponsor".into());137 }138 save(self)139 }140141 /// Set limits for the collection.142 /// @dev Throws error if limit not found.143 /// @param limit Name of the limit. Valid names:144 /// "accountTokenOwnershipLimit",145 /// "sponsoredDataSize",146 /// "sponsoredDataRateLimit",147 /// "tokenLimit",148 /// "sponsorTransferTimeout",149 /// "sponsorApproveTimeout"150 /// @param value Value of the limit.151 #[solidity(rename_selector = "setCollectionLimit")]152 fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {153 check_is_owner_or_admin(caller, self)?;154 let mut limits = self.limits.clone();155156 match limit.as_str() {157 "accountTokenOwnershipLimit" => {158 limits.account_token_ownership_limit = Some(value);159 }160 "sponsoredDataSize" => {161 limits.sponsored_data_size = Some(value);162 }163 "sponsoredDataRateLimit" => {164 limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));165 }166 "tokenLimit" => {167 limits.token_limit = Some(value);168 }169 "sponsorTransferTimeout" => {170 limits.sponsor_transfer_timeout = Some(value);171 }172 "sponsorApproveTimeout" => {173 limits.sponsor_approve_timeout = Some(value);174 }175 _ => {176 return Err(Error::Revert(format!(177 "unknown integer limit \"{}\"",178 limit179 )))180 }181 }182 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)183 .map_err(dispatch_to_evm::<T>)?;184 save(self)185 }186187 /// Set limits for the collection.188 /// @dev Throws error if limit not found.189 /// @param limit Name of the limit. Valid names:190 /// "ownerCanTransfer",191 /// "ownerCanDestroy",192 /// "transfersEnabled"193 /// @param value Value of the limit.194 #[solidity(rename_selector = "setCollectionLimit")]195 fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {196 check_is_owner_or_admin(caller, self)?;197 let mut limits = self.limits.clone();198199 match limit.as_str() {200 "ownerCanTransfer" => {201 limits.owner_can_transfer = Some(value);202 }203 "ownerCanDestroy" => {204 limits.owner_can_destroy = Some(value);205 }206 "transfersEnabled" => {207 limits.transfers_enabled = Some(value);208 }209 _ => {210 return Err(Error::Revert(format!(211 "unknown boolean limit \"{}\"",212 limit213 )))214 }215 }216 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)217 .map_err(dispatch_to_evm::<T>)?;218 save(self)219 }220221 /// Get contract address.222 fn contract_address(&self, _caller: caller) -> Result<address> {223 Ok(crate::eth::collection_id_to_address(self.id))224 }225226 /// Add collection admin by substrate address.227 /// @param new_admin Substrate administrator address.228 fn add_collection_admin_substrate(&self, caller: caller, new_admin: uint256) -> Result<void> {229 let caller = T::CrossAccountId::from_eth(caller);230 let mut new_admin_arr: [u8; 32] = Default::default();231 new_admin.to_big_endian(&mut new_admin_arr);232 let account_id = T::AccountId::from(new_admin_arr);233 let new_admin = T::CrossAccountId::from_sub(account_id);234 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;235 Ok(())236 }237238 /// Remove collection admin by substrate address.239 /// @param admin Substrate administrator address.240 fn remove_collection_admin_substrate(&self, caller: caller, admin: uint256) -> Result<void> {241 let caller = T::CrossAccountId::from_eth(caller);242 let mut admin_arr: [u8; 32] = Default::default();243 admin.to_big_endian(&mut admin_arr);244 let account_id = T::AccountId::from(admin_arr);245 let admin = T::CrossAccountId::from_sub(account_id);246 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;247 Ok(())248 }249250 /// Add collection admin.251 /// @param new_admin Address of the added administrator.252 fn add_collection_admin(&self, caller: caller, new_admin: address) -> Result<void> {253 let caller = T::CrossAccountId::from_eth(caller);254 let new_admin = T::CrossAccountId::from_eth(new_admin);255 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;256 Ok(())257 }258259 /// Remove collection admin.260 ///261 /// @param new_admin Address of the removed administrator.262 fn remove_collection_admin(&self, caller: caller, admin: address) -> Result<void> {263 let caller = T::CrossAccountId::from_eth(caller);264 let admin = T::CrossAccountId::from_eth(admin);265 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;266 Ok(())267 }268269 /// Toggle accessibility of collection nesting.270 ///271 /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'272 #[solidity(rename_selector = "setCollectionNesting")]273 fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {274 check_is_owner_or_admin(caller, self)?;275276 let mut permissions = self.collection.permissions.clone();277 let mut nesting = permissions.nesting().clone();278 nesting.token_owner = enable;279 nesting.restricted = None;280 permissions.nesting = Some(nesting);281282 self.collection.permissions = <Pallet<T>>::clamp_permissions(283 self.collection.mode.clone(),284 &self.collection.permissions,285 permissions,286 )287 .map_err(dispatch_to_evm::<T>)?;288289 save(self)290 }291292 /// Toggle accessibility of collection nesting.293 ///294 /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'295 /// @param collections Addresses of collections that will be available for nesting.296 #[solidity(rename_selector = "setCollectionNesting")]297 fn set_nesting(298 &mut self,299 caller: caller,300 enable: bool,301 collections: Vec<address>,302 ) -> Result<void> {303 if collections.is_empty() {304 return Err("no addresses provided".into());305 }306 check_is_owner_or_admin(caller, self)?;307308 let mut permissions = self.collection.permissions.clone();309 match enable {310 false => {311 let mut nesting = permissions.nesting().clone();312 nesting.token_owner = false;313 nesting.restricted = None;314 permissions.nesting = Some(nesting);315 }316 true => {317 let mut bv = OwnerRestrictedSet::new();318 for i in collections {319 bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or(Error::Revert(320 "Can't convert address into collection id".into(),321 ))?)322 .map_err(|_| "too many collections")?;323 }324 let mut nesting = permissions.nesting().clone();325 nesting.token_owner = true;326 nesting.restricted = Some(bv);327 permissions.nesting = Some(nesting);328 }329 };330331 self.collection.permissions = <Pallet<T>>::clamp_permissions(332 self.collection.mode.clone(),333 &self.collection.permissions,334 permissions,335 )336 .map_err(dispatch_to_evm::<T>)?;337338 save(self)339 }340341 /// Set the collection access method.342 /// @param mode Access mode343 /// 0 for Normal344 /// 1 for AllowList345 fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {346 check_is_owner_or_admin(caller, self)?;347 let permissions = CollectionPermissions {348 access: Some(match mode {349 0 => AccessMode::Normal,350 1 => AccessMode::AllowList,351 _ => return Err("not supported access mode".into()),352 }),353 ..Default::default()354 };355 self.collection.permissions = <Pallet<T>>::clamp_permissions(356 self.collection.mode.clone(),357 &self.collection.permissions,358 permissions,359 )360 .map_err(dispatch_to_evm::<T>)?;361362 save(self)363 }364365 /// Add the user to the allowed list.366 ///367 /// @param user Address of a trusted user.368 fn add_to_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {369 let caller = T::CrossAccountId::from_eth(caller);370 let user = T::CrossAccountId::from_eth(user);371 <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;372 Ok(())373 }374375 /// Remove the user from the allowed list.376 ///377 /// @param user Address of a removed user.378 fn remove_from_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let user = T::CrossAccountId::from_eth(user);381 <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;382 Ok(())383 }384385 /// Switch permission for minting.386 ///387 /// @param mode Enable if "true".388 fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {389 check_is_owner_or_admin(caller, self)?;390 let permissions = CollectionPermissions {391 mint_mode: Some(mode),392 ..Default::default()393 };394 self.collection.permissions = <Pallet<T>>::clamp_permissions(395 self.collection.mode.clone(),396 &self.collection.permissions,397 permissions,398 )399 .map_err(dispatch_to_evm::<T>)?;400401 save(self)402 }403}404405fn check_is_owner_or_admin<T: Config>(406 caller: caller,407 collection: &CollectionHandle<T>,408) -> Result<T::CrossAccountId> {409 let caller = T::CrossAccountId::from_eth(caller);410 collection411 .check_is_owner_or_admin(&caller)412 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;413 Ok(caller)414}415416fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {417 // TODO possibly delete for the lack of transaction418 collection419 .check_is_internal()420 .map_err(dispatch_to_evm::<T>)?;421 <crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());422 Ok(())423}424425/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).426pub fn token_uri_key() -> up_data_structs::PropertyKey {427 b"tokenURI"428 .to_vec()429 .try_into()430 .expect("length < limit; qed")431}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -16,7 +16,9 @@
//! # Common pallet
//!
-//! The Common pallet provides functionality for handling collections.
+//! The Common pallet provides an interface for common collection operations for different collection types
+//! (see [CommonCollectionOperations], as well as a generic dispatcher for these, see [dispatch] module.
+//! It also provides this functionality to EVM, see [erc] and [eth] modules.
//!
//! ## Overview
//!
@@ -42,11 +44,8 @@
//! **Collection properties** - Collection properties are simply key-value stores where various
//! metadata can be placed.
//!
-//! **Collection property permissions** - For each property in the collection can be set permission
+//! **Permissions on token properties** - For each property in the token can be set permission
//! to change, see [PropertyPermission].
-//!
-//! **Permissions on token properties** - Similar to _permissions on collection properties_,
-//! only restrictions apply to token properties.
//!
//! **Collection administrator** - For a collection, you can set administrators who have the right
//! to most actions on the collection.
@@ -132,9 +131,10 @@
/// Collection handle contains information about collection data and id.
/// Also provides functionality to count consumed gas.
+///
/// CollectionHandle is used as a generic wrapper for collections of all types.
/// It allows to perform common operations and queries on any collection type,
-/// both completely general for all, as well as their respective implementations of [CommonCollectionOperations].
+/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].
#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
pub struct CollectionHandle<T: Config> {
/// Collection id
@@ -163,7 +163,7 @@
})
}
- /// Same as [CollectionHandle::new] but with an existed [SubstrateRecorder].
+ /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].
pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {
<CollectionById<T>>::get(id).map(|collection| Self {
id,
@@ -178,7 +178,7 @@
Self::new_with_gas_limit(id, u64::MAX)
}
- /// Same as [CollectionHandle::new] but if collection not found [Error::CollectionNotFound] returned.
+ /// Same as [`CollectionHandle::new`] but if collection not found [`Error::CollectionNotFound`] returned.
pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {
Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)
}
@@ -213,7 +213,7 @@
///
/// Unique collections allows sponsoring for certain actions.
/// This method allows you to set the sponsor of the collection.
- /// In order for sponsorship to become active, it must be confirmed through [Self::confirm_sponsorship].
+ /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].
pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
Ok(())
@@ -222,7 +222,7 @@
/// Confirm sponsorship
///
/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.
- /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [Self::set_sponsor].
+ /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].
pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {
if self.collection.sponsorship.pending_sponsor() != Some(sender) {
return Ok(false);
@@ -233,7 +233,7 @@
}
/// 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 [Error::CollectionIsExternal] error.
+ /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.
pub fn check_is_internal(&self) -> DispatchResult {
if self.external_collection {
return Err(<Error<T>>::CollectionIsExternal)?;
@@ -243,7 +243,7 @@
}
/// 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 [Error::CollectionIsInternal] error.
+ /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.
pub fn check_is_external(&self) -> DispatchResult {
if !self.external_collection {
return Err(<Error<T>>::CollectionIsInternal)?;
@@ -325,10 +325,10 @@
+ TypeInfo
+ account::Config
{
- /// Weight info.
+ /// Weight information for functions of this pallet.
type WeightInfo: WeightInfo;
- /// Events compatible with [frame_system::Config::Event].
+ /// Events compatible with [`frame_system::Config::Event`].
type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;
/// Currency.
@@ -340,19 +340,19 @@
<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
>;
- /// Collection dispatcher.
+ /// Dispatcher of operations on collections.
type CollectionDispatch: CollectionDispatch<Self>;
/// Treasury account id getter.
type TreasuryAccountId: Get<Self::AccountId>;
- /// Contract address getter.
+ /// Address under which the CollectionHelper contract would be available.
type ContractAddress: Get<H160>;
/// Mapper for tokens to Etherium addresses.
type EvmTokenAddressMapping: TokenAddressMapping<H160>;
- /// Mapper for tokens to [CrossAccountId].
+ /// Mapper for tokens to [`CrossAccountId`].
type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;
}
@@ -378,7 +378,7 @@
CollectionCreated(
/// Globally unique identifier of newly created collection.
CollectionId,
- /// [CollectionMode] converted into _u8_.
+ /// [`CollectionMode`] converted into _u8_.
u8,
/// Collection owner.
T::AccountId,
@@ -1469,19 +1469,20 @@
fn burn_from() -> Weight;
/// Differs from burn_item in case of Fungible and Refungible, as it should burn
- /// whole users's balance
+ /// whole users's balance.
///
/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead
fn burn_recursively_self_raw() -> Weight;
- /// Cost of iterating over `amount` children while burning, without counting child burning itself
+ /// Cost of iterating over `amount` children while burning, without counting child burning itself.
///
/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead
fn burn_recursively_breadth_raw(amount: u32) -> Weight;
/// The price of recursive burning a token.
///
- /// `max_selfs` -
+ /// `max_selfs` - The maximum burning weight of the token itself.
+ /// `max_breadth` - The maximum number of nested tokens to burn.
fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {
Self::burn_recursively_self_raw()
.saturating_mul(max_selfs.max(1) as u64)
@@ -1589,8 +1590,8 @@
/// Set token properties.
///
- /// The appropriate [PropertyPermission] for the token property
- /// must be set with [Self::set_token_property_permissions].
+ /// The appropriate [`PropertyPermission`] for the token property
+ /// must be set with [`Self::set_token_property_permissions`].
///
/// * `sender` - Must be either the owner of the token or its admin.
/// * `token_id` - The token for which the properties are being set.
@@ -1606,8 +1607,8 @@
/// Remove token properties.
///
- /// The appropriate [PropertyPermission] for the token property
- /// must be set with [Self::set_token_property_permissions].
+ /// The appropriate [`PropertyPermission`] for the token property
+ /// must be set with [`Self::set_token_property_permissions`].
///
/// * `sender` - Must be either the owner of the token or its admin.
/// * `token_id` - The token for which the properties are being remove.
@@ -1665,9 +1666,9 @@
/// Send parts of a token owned by another user.
///
- /// Before calling this method, you must grant rights to the calling user via [Self::approve].
+ /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].
///
- /// * `sender` - The user who has access to the token.
+ /// * `sender` - The user who must have access to the token (see [`Self::approve`]).
/// * `from` - The user who owns the token.
/// * `to` - Recepient user.
/// * `token` - The token of which parts are being sent.
@@ -1685,9 +1686,9 @@
/// Burn parts of a token owned by another user.
///
- /// Before calling this method, you must grant rights to the calling user via [Self::approve].
+ /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].
///
- /// * `sender` - The user who has access to the token.
+ /// * `sender` - The user who must have access to the token (see [`Self::approve`]).
/// * `from` - The user who owns the token.
/// * `token` - The token of which parts are being sent.
/// * `amount` - The number of parts of the token that will be transferred.
@@ -1750,14 +1751,14 @@
/// Get the value of the token property by key.
///
- /// * `token` - Token property to get.
+ /// * `token` - Token with the property to get.
/// * `key` - Property name.
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;
/// Get a set of token properties by key vector.
///
- /// * `token` - Token property to get.
- /// * `keys` - Vector of keys. If this parameter is [None](sp_std::result::Result),
+ /// * `token` - Token with the property to get.
+ /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),
/// then all properties are returned.
fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;
@@ -1811,9 +1812,9 @@
) -> DispatchResultWithPostInfo;
}
-/// Merge [DispatchResult] with [Weight] into [DispatchResultWithPostInfo].
+/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].
///
-/// Used for [CommonCollectionOperations] implementations and flexible enough to do so.
+/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.
pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {
let post_info = PostDispatchInfo {
actual_weight: Some(weight),