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

difftreelog

source

pallets/nonfungible/src/erc.rs13.0 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::{TokenId, SchemaVersion};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::{vec::Vec, vec};28use pallet_common::{29	erc::{CommonEvmHandler, PrecompileResult},30};31use pallet_evm::account::CrossAccountId;32use pallet_evm_coder_substrate::call;33use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3435use crate::{36	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,37	SelfWeightOf, weights::WeightInfo,38};3940fn error_unsupported_schema_version() -> Error {41	alloc::format!(42		"Unsupported schema version! Support only {:?}",43		SchemaVersion::ImageURL44	)45	.as_str()46	.into()47}4849#[derive(ToLog)]50pub enum ERC721Events {51	Transfer {52		#[indexed]53		from: address,54		#[indexed]55		to: address,56		#[indexed]57		token_id: uint256,58	},59	Approval {60		#[indexed]61		owner: address,62		#[indexed]63		approved: address,64		#[indexed]65		token_id: uint256,66	},67	#[allow(dead_code)]68	ApprovalForAll {69		#[indexed]70		owner: address,71		#[indexed]72		operator: address,73		approved: bool,74	},75}7677#[derive(ToLog)]78pub enum ERC721MintableEvents {79	#[allow(dead_code)]80	MintingFinished {},81}8283#[solidity_interface(name = "ERC721Metadata")]84impl<T: Config> NonfungibleHandle<T> {85	fn name(&self) -> Result<string> {86		Ok(decode_utf16(self.name.iter().copied())87			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))88			.collect::<string>())89	}9091	fn symbol(&self) -> Result<string> {92		Ok(string::from_utf8_lossy(&self.token_prefix).into())93	}9495	/// Returns token's const_metadata96	#[solidity(rename_selector = "tokenURI")]97	fn token_uri(&self, token_id: uint256) -> Result<string> {98		if !matches!(self.schema_version, SchemaVersion::ImageURL) {99			return Err(error_unsupported_schema_version());100		}101102		self.consume_store_reads(1)?;103		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104		Ok(string::from_utf8_lossy(105			&<TokenData<T>>::get((self.id, token_id))106				.ok_or("token not found")?107				.const_data,108		)109		.into())110	}111}112113#[solidity_interface(name = "ERC721Enumerable")]114impl<T: Config> NonfungibleHandle<T> {115	fn token_by_index(&self, index: uint256) -> Result<uint256> {116		Ok(index)117	}118119	/// Not implemented120	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {121		// TODO: Not implemetable122		Err("not implemented".into())123	}124125	fn total_supply(&self) -> Result<uint256> {126		self.consume_store_reads(1)?;127		Ok(<Pallet<T>>::total_supply(self).into())128	}129}130131#[solidity_interface(name = "ERC721", events(ERC721Events))]132impl<T: Config> NonfungibleHandle<T> {133	fn balance_of(&self, owner: address) -> Result<uint256> {134		self.consume_store_reads(1)?;135		let owner = T::CrossAccountId::from_eth(owner);136		let balance = <AccountBalance<T>>::get((self.id, owner));137		Ok(balance.into())138	}139	fn owner_of(&self, token_id: uint256) -> Result<address> {140		self.consume_store_reads(1)?;141		let token: TokenId = token_id.try_into()?;142		Ok(*<TokenData<T>>::get((self.id, token))143			.ok_or("token not found")?144			.owner145			.as_eth())146	}147	/// Not implemented148	fn safe_transfer_from_with_data(149		&mut self,150		_from: address,151		_to: address,152		_token_id: uint256,153		_data: bytes,154		_value: value,155	) -> Result<void> {156		// TODO: Not implemetable157		Err("not implemented".into())158	}159	/// Not implemented160	fn safe_transfer_from(161		&mut self,162		_from: address,163		_to: address,164		_token_id: uint256,165		_value: value,166	) -> Result<void> {167		// TODO: Not implemetable168		Err("not implemented".into())169	}170171	#[weight(<SelfWeightOf<T>>::transfer_from())]172	fn transfer_from(173		&mut self,174		caller: caller,175		from: address,176		to: address,177		token_id: uint256,178		_value: value,179	) -> Result<void> {180		let caller = T::CrossAccountId::from_eth(caller);181		let from = T::CrossAccountId::from_eth(from);182		let to = T::CrossAccountId::from_eth(to);183		let token = token_id.try_into()?;184		let budget = self185			.recorder186			.weight_calls_budget(<StructureWeight<T>>::find_parent());187188		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)189			.map_err(dispatch_to_evm::<T>)?;190		Ok(())191	}192193	#[weight(<SelfWeightOf<T>>::approve())]194	fn approve(195		&mut self,196		caller: caller,197		approved: address,198		token_id: uint256,199		_value: value,200	) -> Result<void> {201		let caller = T::CrossAccountId::from_eth(caller);202		let approved = T::CrossAccountId::from_eth(approved);203		let token = token_id.try_into()?;204205		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))206			.map_err(dispatch_to_evm::<T>)?;207		Ok(())208	}209210	/// Not implemented211	fn set_approval_for_all(212		&mut self,213		_caller: caller,214		_operator: address,215		_approved: bool,216	) -> Result<void> {217		// TODO: Not implemetable218		Err("not implemented".into())219	}220221	/// Not implemented222	fn get_approved(&self, _token_id: uint256) -> Result<address> {223		// TODO: Not implemetable224		Err("not implemented".into())225	}226227	/// Not implemented228	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {229		// TODO: Not implemetable230		Err("not implemented".into())231	}232}233234#[solidity_interface(name = "ERC721Burnable")]235impl<T: Config> NonfungibleHandle<T> {236	#[weight(<SelfWeightOf<T>>::burn_item())]237	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {238		let caller = T::CrossAccountId::from_eth(caller);239		let token = token_id.try_into()?;240241		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;242		Ok(())243	}244}245246#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]247impl<T: Config> NonfungibleHandle<T> {248	fn minting_finished(&self) -> Result<bool> {249		Ok(false)250	}251252	/// `token_id` should be obtained with `next_token_id` method,253	/// unlike standard, you can't specify it manually254	#[weight(<SelfWeightOf<T>>::create_item())]255	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {256		let caller = T::CrossAccountId::from_eth(caller);257		let to = T::CrossAccountId::from_eth(to);258		let token_id: u32 = token_id.try_into()?;259		if <TokensMinted<T>>::get(self.id)260			.checked_add(1)261			.ok_or("item id overflow")?262			!= token_id263		{264			return Err("item id should be next".into());265		}266267		<Pallet<T>>::create_item(268			self,269			&caller,270			CreateItemData::<T> {271				const_data: BoundedVec::default(),272				variable_data: BoundedVec::default(),273				owner: to,274			},275		)276		.map_err(dispatch_to_evm::<T>)?;277278		Ok(true)279	}280281	/// `token_id` should be obtained with `next_token_id` method,282	/// unlike standard, you can't specify it manually283	#[solidity(rename_selector = "mintWithTokenURI")]284	#[weight(<SelfWeightOf<T>>::create_item())]285	fn mint_with_token_uri(286		&mut self,287		caller: caller,288		to: address,289		token_id: uint256,290		token_uri: string,291	) -> Result<bool> {292		if !matches!(self.schema_version, SchemaVersion::ImageURL) {293			return Err(error_unsupported_schema_version());294		}295296		let caller = T::CrossAccountId::from_eth(caller);297		let to = T::CrossAccountId::from_eth(to);298		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;299		if <TokensMinted<T>>::get(self.id)300			.checked_add(1)301			.ok_or("item id overflow")?302			!= token_id303		{304			return Err("item id should be next".into());305		}306307		<Pallet<T>>::create_item(308			self,309			&caller,310			CreateItemData::<T> {311				const_data: Vec::<u8>::from(token_uri)312					.try_into()313					.map_err(|_| "token uri is too long")?,314				variable_data: BoundedVec::default(),315				owner: to,316			},317		)318		.map_err(dispatch_to_evm::<T>)?;319		Ok(true)320	}321322	/// Not implemented323	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {324		Err("not implementable".into())325	}326}327328#[solidity_interface(name = "ERC721UniqueExtensions")]329impl<T: Config> NonfungibleHandle<T> {330	#[weight(<SelfWeightOf<T>>::transfer())]331	fn transfer(332		&mut self,333		caller: caller,334		to: address,335		token_id: uint256,336		_value: value,337	) -> Result<void> {338		let caller = T::CrossAccountId::from_eth(caller);339		let to = T::CrossAccountId::from_eth(to);340		let token = token_id.try_into()?;341342		<Pallet<T>>::transfer(self, &caller, &to, token).map_err(dispatch_to_evm::<T>)?;343		Ok(())344	}345346	#[weight(<SelfWeightOf<T>>::burn_from())]347	fn burn_from(348		&mut self,349		caller: caller,350		from: address,351		token_id: uint256,352		_value: value,353	) -> Result<void> {354		let caller = T::CrossAccountId::from_eth(caller);355		let from = T::CrossAccountId::from_eth(from);356		let token = token_id.try_into()?;357		let budget = self358			.recorder359			.weight_calls_budget(<StructureWeight<T>>::find_parent());360361		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)362			.map_err(dispatch_to_evm::<T>)?;363		Ok(())364	}365366	fn next_token_id(&self) -> Result<uint256> {367		self.consume_store_reads(1)?;368		Ok(<TokensMinted<T>>::get(self.id)369			.checked_add(1)370			.ok_or("item id overflow")?371			.into())372	}373374	#[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]375	fn set_variable_metadata(376		&mut self,377		caller: caller,378		token_id: uint256,379		data: bytes,380	) -> Result<void> {381		let caller = T::CrossAccountId::from_eth(caller);382		let token = token_id.try_into()?;383384		<Pallet<T>>::set_variable_metadata(385			self,386			&caller,387			token,388			data.try_into()389				.map_err(|_| "metadata size exceeded limit")?,390		)391		.map_err(dispatch_to_evm::<T>)?;392		Ok(())393	}394395	fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {396		self.consume_store_reads(1)?;397		let token: TokenId = token_id.try_into()?;398399		Ok(<TokenData<T>>::get((self.id, token))400			.ok_or("token not found")?401			.variable_data402			.into_inner())403	}404405	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]406	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {407		let caller = T::CrossAccountId::from_eth(caller);408		let to = T::CrossAccountId::from_eth(to);409		let mut expected_index = <TokensMinted<T>>::get(self.id)410			.checked_add(1)411			.ok_or("item id overflow")?;412413		let total_tokens = token_ids.len();414		for id in token_ids.into_iter() {415			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;416			if id != expected_index {417				return Err("item id should be next".into());418			}419			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;420		}421		let data = (0..total_tokens)422			.map(|_| CreateItemData::<T> {423				const_data: BoundedVec::default(),424				variable_data: BoundedVec::default(),425				owner: to.clone(),426			})427			.collect();428429		<Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;430		Ok(true)431	}432433	#[solidity(rename_selector = "mintBulkWithTokenURI")]434	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]435	fn mint_bulk_with_token_uri(436		&mut self,437		caller: caller,438		to: address,439		tokens: Vec<(uint256, string)>,440	) -> Result<bool> {441		if !matches!(self.schema_version, SchemaVersion::ImageURL) {442			return Err(error_unsupported_schema_version());443		}444445		let caller = T::CrossAccountId::from_eth(caller);446		let to = T::CrossAccountId::from_eth(to);447		let mut expected_index = <TokensMinted<T>>::get(self.id)448			.checked_add(1)449			.ok_or("item id overflow")?;450451		let mut data = Vec::with_capacity(tokens.len());452		for (id, token_uri) in tokens {453			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;454			if id != expected_index {455				return Err("item id should be next".into());456			}457			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;458459			data.push(CreateItemData::<T> {460				const_data: Vec::<u8>::from(token_uri)461					.try_into()462					.map_err(|_| "token uri is too long")?,463				variable_data: vec![].try_into().unwrap(),464				owner: to.clone(),465			});466		}467468		<Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;469		Ok(true)470	}471}472473#[solidity_interface(474	name = "UniqueNFT",475	is(476		ERC721,477		ERC721Metadata,478		ERC721Enumerable,479		ERC721UniqueExtensions,480		ERC721Mintable,481		ERC721Burnable,482	)483)]484impl<T: Config> NonfungibleHandle<T> {}485486// Not a tests, but code generators487generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);488generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);489490impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {491	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");492493	fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {494		call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)495	}496}