git.delta.rocks / unique-network / refs/commits / 263bc691fe1a

difftreelog

source

pallets/common/src/erc.rs13.4 KiBsourcehistory
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 etherium 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")?;78		79		<Pallet<T>>::set_collection_property(self, &caller, Property { key, value })80		.map_err(dispatch_to_evm::<T>)81	}82	83	/// 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(240		&self,241		caller: caller,242		admin: uint256,243	) -> Result<void> {244		let caller = T::CrossAccountId::from_eth(caller);245		let mut admin_arr: [u8; 32] = Default::default();246		admin.to_big_endian(&mut admin_arr);247		let account_id = T::AccountId::from(admin_arr);248		let admin = T::CrossAccountId::from_sub(account_id);249		<Pallet<T>>::toggle_admin(self, &caller, &admin, false)250			.map_err(dispatch_to_evm::<T>)?;251		Ok(())252	}253254	/// Add collection admin.255	/// @param new_admin Address of the added administrator.256	fn add_collection_admin(&self, caller: caller, new_admin: address) -> Result<void> {257		let caller = T::CrossAccountId::from_eth(caller);258		let new_admin = T::CrossAccountId::from_eth(new_admin);259		<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;260		Ok(())261	}262263	/// Remove collection admin.264	/// 265	/// @param new_admin Address of the removed administrator.266	fn remove_collection_admin(&self, caller: caller, admin: address) -> Result<void> {267		let caller = T::CrossAccountId::from_eth(caller);268		let admin = T::CrossAccountId::from_eth(admin);269		<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;270		Ok(())271	}272273	/// Toggle accessibility of collection nesting.274	/// 275	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'276	#[solidity(rename_selector = "setCollectionNesting")]277	fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {278		check_is_owner_or_admin(caller, self)?;279280		let mut permissions = self.collection.permissions.clone();281		let mut nesting = permissions.nesting().clone();282		nesting.token_owner = enable;283		nesting.restricted = None;284		permissions.nesting = Some(nesting);285286		self.collection.permissions = <Pallet<T>>::clamp_permissions(287			self.collection.mode.clone(),288			&self.collection.permissions,289			permissions,290		)291		.map_err(dispatch_to_evm::<T>)?;292293		save(self)294	}295296	/// Toggle accessibility of collection nesting.297	/// 298	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'299	/// @param collections Addresses of collections that will be available for nesting.300	#[solidity(rename_selector = "setCollectionNesting")]301	fn set_nesting(302		&mut self,303		caller: caller,304		enable: bool,305		collections: Vec<address>,306	) -> Result<void> {307		if collections.is_empty() {308			return Err("no addresses provided".into());309		}310		check_is_owner_or_admin(caller, self)?;311312		let mut permissions = self.collection.permissions.clone();313		match enable {314			false => {315				let mut nesting = permissions.nesting().clone();316				nesting.token_owner = false;317				nesting.restricted = None;318				permissions.nesting = Some(nesting);319			}320			true => {321				let mut bv = OwnerRestrictedSet::new();322				for i in collections {323					bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or(Error::Revert(324						"Can't convert address into collection id".into(),325					))?)326					.map_err(|_| "too many collections")?;327				}328				let mut nesting = permissions.nesting().clone();329				nesting.token_owner = true;330				nesting.restricted = Some(bv);331				permissions.nesting = Some(nesting);332			}333		};334335		self.collection.permissions = <Pallet<T>>::clamp_permissions(336			self.collection.mode.clone(),337			&self.collection.permissions,338			permissions,339		)340		.map_err(dispatch_to_evm::<T>)?;341342		save(self)343	}344345	/// Set the collection access method.346	/// @param mode Access mode347	/// 	0 for Normal348	/// 	1 for AllowList349	fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {350		check_is_owner_or_admin(caller, self)?;351		let permissions = CollectionPermissions {352			access: Some(match mode {353				0 => AccessMode::Normal,354				1 => AccessMode::AllowList,355				_ => return Err("not supported access mode".into()),356			}),357			..Default::default()358		};359		self.collection.permissions = <Pallet<T>>::clamp_permissions(360			self.collection.mode.clone(),361			&self.collection.permissions,362			permissions,363		)364		.map_err(dispatch_to_evm::<T>)?;365366		save(self)367	}368369	/// Add the user to the allowed list.370	/// 371	/// @param user Address of a trusted user.372	fn add_to_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {373		let caller = T::CrossAccountId::from_eth(caller);374		let user = T::CrossAccountId::from_eth(user);375		<Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;376		Ok(())377	}378	379	/// Remove the user from the allowed list.380	/// 381	/// @param user Address of a removed user.382	fn remove_from_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {383		let caller = T::CrossAccountId::from_eth(caller);384		let user = T::CrossAccountId::from_eth(user);385		<Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;386		Ok(())387	}388389	/// Switch permission for minting.390	/// 391	/// @param mode Enable if "true".392	fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {393		check_is_owner_or_admin(caller, self)?;394		let permissions = CollectionPermissions {395			mint_mode: Some(mode),396			..Default::default()397		};398		self.collection.permissions = <Pallet<T>>::clamp_permissions(399			self.collection.mode.clone(),400			&self.collection.permissions,401			permissions,402		)403		.map_err(dispatch_to_evm::<T>)?;404405		save(self)406	}407}408409fn check_is_owner_or_admin<T: Config>(410	caller: caller,411	collection: &CollectionHandle<T>,412) -> Result<T::CrossAccountId> {413	let caller = T::CrossAccountId::from_eth(caller);414	collection415		.check_is_owner_or_admin(&caller)416		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;417	Ok(caller)418}419420fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {421	// TODO possibly delete for the lack of transaction422	collection423		.check_is_internal()424		.map_err(dispatch_to_evm::<T>)?;425	<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());426	Ok(())427}428429/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).430pub fn token_uri_key() -> up_data_structs::PropertyKey {431	b"tokenURI"432		.to_vec()433		.try_into()434		.expect("length < limit; qed")435}