git.delta.rocks / unique-network / refs/commits / fdc1b224b1bd

difftreelog

source

pallets/nonfungible/src/erc.rs15.5 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/>.1617extern crate alloc;18use core::{19	char::{REPLACEMENT_CHARACTER, decode_utf16},20	convert::TryInto,21};22use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};23use frame_support::BoundedVec;24use up_data_structs::{25	TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId,26	PropertyKey, CollectionPropertiesVec,27};28use pallet_evm_coder_substrate::dispatch_to_evm;29use sp_core::{H160, U256};30use sp_std::vec::Vec;31use pallet_common::{32	erc::{CommonEvmHandler, PrecompileResult, CollectionCall},33	CollectionHandle, CollectionPropertyPermissions,34};35use pallet_evm::account::CrossAccountId;36use pallet_evm_coder_substrate::call;37use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3839use crate::{40	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,41	SelfWeightOf, weights::WeightInfo, TokenProperties,42};4344#[solidity_interface(name = "TokenProperties")]45impl<T: Config> NonfungibleHandle<T> {46	fn set_token_property_permission(47		&mut self,48		caller: caller,49		key: string,50		is_mutable: bool,51		collection_admin: bool,52		token_owner: bool,53	) -> Result<()> {54		let caller = T::CrossAccountId::from_eth(caller);55		<Pallet<T>>::set_property_permission(56			self,57			&caller,58			PropertyKeyPermission {59				key: <Vec<u8>>::from(key)60					.try_into()61					.map_err(|_| "too long key")?,62				permission: PropertyPermission {63					mutable: is_mutable,64					collection_admin,65					token_owner,66				},67			},68		)69		.map_err(dispatch_to_evm::<T>)70	}7172	fn set_property(73		&mut self,74		caller: caller,75		token_id: uint256,76		key: string,77		value: bytes,78	) -> Result<()> {79		let caller = T::CrossAccountId::from_eth(caller);80		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;81		let key = <Vec<u8>>::from(key)82			.try_into()83			.map_err(|_| "key too long")?;84		let value = value.try_into().map_err(|_| "value too long")?;8586		<Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })87			.map_err(dispatch_to_evm::<T>)88	}8990	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {91		let caller = T::CrossAccountId::from_eth(caller);92		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;93		let key = <Vec<u8>>::from(key)94			.try_into()95			.map_err(|_| "key too long")?;9697		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)98			.map_err(dispatch_to_evm::<T>)99	}100101	/// Throws error if key not found102	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {103		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104		let key = <Vec<u8>>::from(key)105			.try_into()106			.map_err(|_| "key too long")?;107108		let props = <TokenProperties<T>>::get((self.id, token_id));109		let prop = props.get(&key).ok_or("key not found")?;110111		Ok(prop.to_vec())112	}113}114115#[derive(ToLog)]116pub enum ERC721Events {117	Transfer {118		#[indexed]119		from: address,120		#[indexed]121		to: address,122		#[indexed]123		token_id: uint256,124	},125	Approval {126		#[indexed]127		owner: address,128		#[indexed]129		approved: address,130		#[indexed]131		token_id: uint256,132	},133	#[allow(dead_code)]134	ApprovalForAll {135		#[indexed]136		owner: address,137		#[indexed]138		operator: address,139		approved: bool,140	},141}142143#[derive(ToLog)]144pub enum ERC721MintableEvents {145	#[allow(dead_code)]146	MintingFinished {},147}148149#[solidity_interface(name = "ERC721Metadata")]150impl<T: Config> NonfungibleHandle<T> {151	fn name(&self) -> Result<string> {152		Ok(decode_utf16(self.name.iter().copied())153			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))154			.collect::<string>())155	}156157	fn symbol(&self) -> Result<string> {158		Ok(string::from_utf8_lossy(&self.token_prefix).into())159	}160161	/// Returns token's const_metadata162	#[solidity(rename_selector = "tokenURI")]163	fn token_uri(&self, token_id: uint256) -> Result<string> {164		let key = pallet_common::eth::KEY_TOKEN_URI.clone();165		let permission = get_token_permission::<T>(self.id, &key)?;166		if !permission.collection_admin {167			return Err("Operation is not allowed".into());168		}169170		self.consume_store_reads(1)?;171		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;172173		let properties = <TokenProperties<T>>::try_get((self.id, token_id))174			.map_err(|_| Error::Revert("Token properties not found".into()))?;175		if let Some(property) = properties.get(&key) {176			return Ok(string::from_utf8_lossy(property).into());177		}178179		Err("Property tokenURI not found".into())180	}181}182183#[solidity_interface(name = "ERC721Enumerable")]184impl<T: Config> NonfungibleHandle<T> {185	fn token_by_index(&self, index: uint256) -> Result<uint256> {186		Ok(index)187	}188189	/// Not implemented190	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {191		// TODO: Not implemetable192		Err("not implemented".into())193	}194195	fn total_supply(&self) -> Result<uint256> {196		self.consume_store_reads(1)?;197		Ok(<Pallet<T>>::total_supply(self).into())198	}199}200201#[solidity_interface(name = "ERC721", events(ERC721Events))]202impl<T: Config> NonfungibleHandle<T> {203	fn balance_of(&self, owner: address) -> Result<uint256> {204		self.consume_store_reads(1)?;205		let owner = T::CrossAccountId::from_eth(owner);206		let balance = <AccountBalance<T>>::get((self.id, owner));207		Ok(balance.into())208	}209	fn owner_of(&self, token_id: uint256) -> Result<address> {210		self.consume_store_reads(1)?;211		let token: TokenId = token_id.try_into()?;212		Ok(*<TokenData<T>>::get((self.id, token))213			.ok_or("token not found")?214			.owner215			.as_eth())216	}217	/// Not implemented218	fn safe_transfer_from_with_data(219		&mut self,220		_from: address,221		_to: address,222		_token_id: uint256,223		_data: bytes,224		_value: value,225	) -> Result<void> {226		// TODO: Not implemetable227		Err("not implemented".into())228	}229	/// Not implemented230	fn safe_transfer_from(231		&mut self,232		_from: address,233		_to: address,234		_token_id: uint256,235		_value: value,236	) -> Result<void> {237		// TODO: Not implemetable238		Err("not implemented".into())239	}240241	#[weight(<SelfWeightOf<T>>::transfer_from())]242	fn transfer_from(243		&mut self,244		caller: caller,245		from: address,246		to: address,247		token_id: uint256,248		_value: value,249	) -> Result<void> {250		let caller = T::CrossAccountId::from_eth(caller);251		let from = T::CrossAccountId::from_eth(from);252		let to = T::CrossAccountId::from_eth(to);253		let token = token_id.try_into()?;254		let budget = self255			.recorder256			.weight_calls_budget(<StructureWeight<T>>::find_parent());257258		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)259			.map_err(dispatch_to_evm::<T>)?;260		Ok(())261	}262263	#[weight(<SelfWeightOf<T>>::approve())]264	fn approve(265		&mut self,266		caller: caller,267		approved: address,268		token_id: uint256,269		_value: value,270	) -> Result<void> {271		let caller = T::CrossAccountId::from_eth(caller);272		let approved = T::CrossAccountId::from_eth(approved);273		let token = token_id.try_into()?;274275		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))276			.map_err(dispatch_to_evm::<T>)?;277		Ok(())278	}279280	/// Not implemented281	fn set_approval_for_all(282		&mut self,283		_caller: caller,284		_operator: address,285		_approved: bool,286	) -> Result<void> {287		// TODO: Not implemetable288		Err("not implemented".into())289	}290291	/// Not implemented292	fn get_approved(&self, _token_id: uint256) -> Result<address> {293		// TODO: Not implemetable294		Err("not implemented".into())295	}296297	/// Not implemented298	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {299		// TODO: Not implemetable300		Err("not implemented".into())301	}302}303304#[solidity_interface(name = "ERC721Burnable")]305impl<T: Config> NonfungibleHandle<T> {306	#[weight(<SelfWeightOf<T>>::burn_item())]307	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {308		let caller = T::CrossAccountId::from_eth(caller);309		let token = token_id.try_into()?;310311		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;312		Ok(())313	}314}315316#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]317impl<T: Config> NonfungibleHandle<T> {318	fn minting_finished(&self) -> Result<bool> {319		Ok(false)320	}321322	/// `token_id` should be obtained with `next_token_id` method,323	/// unlike standard, you can't specify it manually324	#[weight(<SelfWeightOf<T>>::create_item())]325	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {326		let caller = T::CrossAccountId::from_eth(caller);327		let to = T::CrossAccountId::from_eth(to);328		let token_id: u32 = token_id.try_into()?;329		let budget = self330			.recorder331			.weight_calls_budget(<StructureWeight<T>>::find_parent());332333		if <TokensMinted<T>>::get(self.id)334			.checked_add(1)335			.ok_or("item id overflow")?336			!= token_id337		{338			return Err("item id should be next".into());339		}340341		<Pallet<T>>::create_item(342			self,343			&caller,344			CreateItemData::<T> {345				properties: BoundedVec::default(),346				owner: to,347			},348			&budget,349		)350		.map_err(dispatch_to_evm::<T>)?;351352		Ok(true)353	}354355	/// `token_id` should be obtained with `next_token_id` method,356	/// unlike standard, you can't specify it manually357	#[solidity(rename_selector = "mintWithTokenURI")]358	#[weight(<SelfWeightOf<T>>::create_item())]359	fn mint_with_token_uri(360		&mut self,361		caller: caller,362		to: address,363		token_id: uint256,364		token_uri: string,365	) -> Result<bool> {366		let key = pallet_common::eth::KEY_TOKEN_URI.clone();367		let permission = get_token_permission::<T>(self.id, &key)?;368		if !permission.collection_admin {369			return Err("Operation is not allowed".into());370		}371372		let caller = T::CrossAccountId::from_eth(caller);373		let to = T::CrossAccountId::from_eth(to);374		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;375		let budget = self376			.recorder377			.weight_calls_budget(<StructureWeight<T>>::find_parent());378379		if <TokensMinted<T>>::get(self.id)380			.checked_add(1)381			.ok_or("item id overflow")?382			!= token_id383		{384			return Err("item id should be next".into());385		}386387		let mut properties = CollectionPropertiesVec::default();388		properties389			.try_push(Property {390				key,391				value: token_uri392					.into_bytes()393					.try_into()394					.map_err(|_| "token uri is too long")?,395			})396			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;397398		<Pallet<T>>::create_item(399			self,400			&caller,401			CreateItemData::<T> {402				properties,403				owner: to,404			},405			&budget,406		)407		.map_err(dispatch_to_evm::<T>)?;408		Ok(true)409	}410411	/// Not implemented412	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {413		Err("not implementable".into())414	}415}416417fn get_token_permission<T: Config>(418	collection_id: CollectionId,419	key: &PropertyKey,420) -> Result<PropertyPermission> {421	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)422		.map_err(|_| Error::Revert("No permissions for collection".into()))?;423	let a = token_property_permissions424		.get(key)425		.map(|p| p.clone())426		.ok_or_else(|| Error::Revert("No permission for tokenURI".into()))?;427	Ok(a)428}429430#[solidity_interface(name = "ERC721UniqueExtensions")]431impl<T: Config> NonfungibleHandle<T> {432	#[weight(<SelfWeightOf<T>>::transfer())]433	fn transfer(434		&mut self,435		caller: caller,436		to: address,437		token_id: uint256,438		_value: value,439	) -> Result<void> {440		let caller = T::CrossAccountId::from_eth(caller);441		let to = T::CrossAccountId::from_eth(to);442		let token = token_id.try_into()?;443		let budget = self444			.recorder445			.weight_calls_budget(<StructureWeight<T>>::find_parent());446447		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;448		Ok(())449	}450451	#[weight(<SelfWeightOf<T>>::burn_from())]452	fn burn_from(453		&mut self,454		caller: caller,455		from: address,456		token_id: uint256,457		_value: value,458	) -> Result<void> {459		let caller = T::CrossAccountId::from_eth(caller);460		let from = T::CrossAccountId::from_eth(from);461		let token = token_id.try_into()?;462		let budget = self463			.recorder464			.weight_calls_budget(<StructureWeight<T>>::find_parent());465466		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)467			.map_err(dispatch_to_evm::<T>)?;468		Ok(())469	}470471	fn next_token_id(&self) -> Result<uint256> {472		self.consume_store_reads(1)?;473		Ok(<TokensMinted<T>>::get(self.id)474			.checked_add(1)475			.ok_or("item id overflow")?476			.into())477	}478479	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]480	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {481		let caller = T::CrossAccountId::from_eth(caller);482		let to = T::CrossAccountId::from_eth(to);483		let mut expected_index = <TokensMinted<T>>::get(self.id)484			.checked_add(1)485			.ok_or("item id overflow")?;486		let budget = self487			.recorder488			.weight_calls_budget(<StructureWeight<T>>::find_parent());489490		let total_tokens = token_ids.len();491		for id in token_ids.into_iter() {492			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;493			if id != expected_index {494				return Err("item id should be next".into());495			}496			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;497		}498		let data = (0..total_tokens)499			.map(|_| CreateItemData::<T> {500				properties: BoundedVec::default(),501				owner: to.clone(),502			})503			.collect();504505		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)506			.map_err(dispatch_to_evm::<T>)?;507		Ok(true)508	}509510	#[solidity(rename_selector = "mintBulkWithTokenURI")]511	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]512	fn mint_bulk_with_token_uri(513		&mut self,514		caller: caller,515		to: address,516		tokens: Vec<(uint256, string)>,517	) -> Result<bool> {518		let caller = T::CrossAccountId::from_eth(caller);519		let to = T::CrossAccountId::from_eth(to);520		let mut expected_index = <TokensMinted<T>>::get(self.id)521			.checked_add(1)522			.ok_or("item id overflow")?;523		let budget = self524			.recorder525			.weight_calls_budget(<StructureWeight<T>>::find_parent());526527		let mut data = Vec::with_capacity(tokens.len());528		for (id, token_uri) in tokens {529			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;530			if id != expected_index {531				return Err("item id should be next".into());532			}533			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;534535			todo!("token uri");536			data.push(CreateItemData::<T> {537				properties: BoundedVec::default(),538				owner: to.clone(),539			});540		}541542		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)543			.map_err(dispatch_to_evm::<T>)?;544		Ok(true)545	}546}547548#[solidity_interface(549	name = "UniqueNFT",550	is(551		ERC721,552		ERC721Metadata,553		ERC721Enumerable,554		ERC721UniqueExtensions,555		ERC721Mintable,556		ERC721Burnable,557		via("CollectionHandle<T>", common_mut, Collection),558		TokenProperties,559	)560)]561impl<T: Config> NonfungibleHandle<T> {}562563// Not a tests, but code generators564generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);565generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);566567impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {568	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");569570	fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {571		call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)572	}573}