git.delta.rocks / unique-network / refs/commits / 6ac8e66dbab7

difftreelog

source

pallets/nonfungible/src/erc.rs13.7 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		let budget = self260			.recorder261			.weight_calls_budget(<StructureWeight<T>>::find_parent());262263		if <TokensMinted<T>>::get(self.id)264			.checked_add(1)265			.ok_or("item id overflow")?266			!= token_id267		{268			return Err("item id should be next".into());269		}270271		<Pallet<T>>::create_item(272			self,273			&caller,274			CreateItemData::<T> {275				const_data: BoundedVec::default(),276				variable_data: BoundedVec::default(),277				properties: BoundedVec::default(),278				owner: to,279			},280			&budget,281		)282		.map_err(dispatch_to_evm::<T>)?;283284		Ok(true)285	}286287	/// `token_id` should be obtained with `next_token_id` method,288	/// unlike standard, you can't specify it manually289	#[solidity(rename_selector = "mintWithTokenURI")]290	#[weight(<SelfWeightOf<T>>::create_item())]291	fn mint_with_token_uri(292		&mut self,293		caller: caller,294		to: address,295		token_id: uint256,296		token_uri: string,297	) -> Result<bool> {298		if !matches!(self.schema_version, SchemaVersion::ImageURL) {299			return Err(error_unsupported_schema_version());300		}301302		let caller = T::CrossAccountId::from_eth(caller);303		let to = T::CrossAccountId::from_eth(to);304		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;305		let budget = self306			.recorder307			.weight_calls_budget(<StructureWeight<T>>::find_parent());308309		if <TokensMinted<T>>::get(self.id)310			.checked_add(1)311			.ok_or("item id overflow")?312			!= token_id313		{314			return Err("item id should be next".into());315		}316317		<Pallet<T>>::create_item(318			self,319			&caller,320			CreateItemData::<T> {321				const_data: Vec::<u8>::from(token_uri)322					.try_into()323					.map_err(|_| "token uri is too long")?,324				variable_data: BoundedVec::default(),325				properties: BoundedVec::default(),326				owner: to,327			},328			&budget,329		)330		.map_err(dispatch_to_evm::<T>)?;331		Ok(true)332	}333334	/// Not implemented335	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {336		Err("not implementable".into())337	}338}339340#[solidity_interface(name = "ERC721UniqueExtensions")]341impl<T: Config> NonfungibleHandle<T> {342	#[weight(<SelfWeightOf<T>>::transfer())]343	fn transfer(344		&mut self,345		caller: caller,346		to: address,347		token_id: uint256,348		_value: value,349	) -> Result<void> {350		let caller = T::CrossAccountId::from_eth(caller);351		let to = T::CrossAccountId::from_eth(to);352		let token = token_id.try_into()?;353		let budget = self354			.recorder355			.weight_calls_budget(<StructureWeight<T>>::find_parent());356357		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;358		Ok(())359	}360361	#[weight(<SelfWeightOf<T>>::burn_from())]362	fn burn_from(363		&mut self,364		caller: caller,365		from: address,366		token_id: uint256,367		_value: value,368	) -> Result<void> {369		let caller = T::CrossAccountId::from_eth(caller);370		let from = T::CrossAccountId::from_eth(from);371		let token = token_id.try_into()?;372		let budget = self373			.recorder374			.weight_calls_budget(<StructureWeight<T>>::find_parent());375376		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)377			.map_err(dispatch_to_evm::<T>)?;378		Ok(())379	}380381	fn next_token_id(&self) -> Result<uint256> {382		self.consume_store_reads(1)?;383		Ok(<TokensMinted<T>>::get(self.id)384			.checked_add(1)385			.ok_or("item id overflow")?386			.into())387	}388389	#[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]390	fn set_variable_metadata(391		&mut self,392		caller: caller,393		token_id: uint256,394		data: bytes,395	) -> Result<void> {396		let caller = T::CrossAccountId::from_eth(caller);397		let token = token_id.try_into()?;398399		<Pallet<T>>::set_variable_metadata(400			self,401			&caller,402			token,403			data.try_into()404				.map_err(|_| "metadata size exceeded limit")?,405		)406		.map_err(dispatch_to_evm::<T>)?;407		Ok(())408	}409410	fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {411		self.consume_store_reads(1)?;412		let token: TokenId = token_id.try_into()?;413414		Ok(<TokenData<T>>::get((self.id, token))415			.ok_or("token not found")?416			.variable_data417			.into_inner())418	}419420	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]421	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {422		let caller = T::CrossAccountId::from_eth(caller);423		let to = T::CrossAccountId::from_eth(to);424		let mut expected_index = <TokensMinted<T>>::get(self.id)425			.checked_add(1)426			.ok_or("item id overflow")?;427		let budget = self428			.recorder429			.weight_calls_budget(<StructureWeight<T>>::find_parent());430431		let total_tokens = token_ids.len();432		for id in token_ids.into_iter() {433			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;434			if id != expected_index {435				return Err("item id should be next".into());436			}437			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;438		}439		let data = (0..total_tokens)440			.map(|_| CreateItemData::<T> {441				const_data: BoundedVec::default(),442				variable_data: BoundedVec::default(),443				properties: BoundedVec::default(),444				owner: to.clone(),445			})446			.collect();447448		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)449			.map_err(dispatch_to_evm::<T>)?;450		Ok(true)451	}452453	#[solidity(rename_selector = "mintBulkWithTokenURI")]454	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]455	fn mint_bulk_with_token_uri(456		&mut self,457		caller: caller,458		to: address,459		tokens: Vec<(uint256, string)>,460	) -> Result<bool> {461		if !matches!(self.schema_version, SchemaVersion::ImageURL) {462			return Err(error_unsupported_schema_version());463		}464465		let caller = T::CrossAccountId::from_eth(caller);466		let to = T::CrossAccountId::from_eth(to);467		let mut expected_index = <TokensMinted<T>>::get(self.id)468			.checked_add(1)469			.ok_or("item id overflow")?;470		let budget = self471			.recorder472			.weight_calls_budget(<StructureWeight<T>>::find_parent());473474		let mut data = Vec::with_capacity(tokens.len());475		for (id, token_uri) in tokens {476			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;477			if id != expected_index {478				return Err("item id should be next".into());479			}480			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;481482			data.push(CreateItemData::<T> {483				const_data: Vec::<u8>::from(token_uri)484					.try_into()485					.map_err(|_| "token uri is too long")?,486				variable_data: vec![].try_into().unwrap(),487				properties: BoundedVec::default(),488				owner: to.clone(),489			});490		}491492		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)493			.map_err(dispatch_to_evm::<T>)?;494		Ok(true)495	}496}497498#[solidity_interface(499	name = "UniqueNFT",500	is(501		ERC721,502		ERC721Metadata,503		ERC721Enumerable,504		ERC721UniqueExtensions,505		ERC721Mintable,506		ERC721Burnable,507	)508)]509impl<T: Config> NonfungibleHandle<T> {}510511// Not a tests, but code generators512generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);513generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);514515impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {516	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");517518	fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {519		call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)520	}521}