git.delta.rocks / unique-network / refs/commits / 7d68ab6c6ac0

difftreelog

CORE-346 Add static tokenURI key

Trubnikov Sergey2022-05-27parent: #ffa590c.patch.diff
in: master

5 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4290,6 +4290,9 @@
 version = "1.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+dependencies = [
+ "spin",
+]
 
 [[package]]
 name = "lazycell"
@@ -5917,6 +5920,7 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "lazy_static",
  "pallet-evm",
  "pallet-evm-coder-substrate",
  "parity-scale-codec 3.1.2",
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -16,16 +16,18 @@
 sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
 sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
 sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
 pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
 pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
+
 serde = { version = "1.0.130", default-features = false }
 scale-info = { version = "2.0.1", default-features = false, features = [
     "derive",
 ] }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+lazy_static = { version = "1.4.0", default-features = false, features = ["spin_no_std"] }
 
 [features]
 default = ["std"]
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -17,6 +17,14 @@
 use up_data_structs::CollectionId;
 use sp_core::H160;
 
+lazy_static::lazy_static! {
+	pub static ref KEY_TOKEN_URI: up_data_structs::PropertyKey = {
+		let key: evm_coder::types::string = "tokenURI".into(); //TODO: make static
+		let key: up_data_structs::PropertyKey = key.into_bytes().try_into().expect("Can't create \"tokenURI\" key");
+		key
+	};
+}
+
 // 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
 // TODO: Unhardcode prefix
 const ETH_COLLECTION_PREFIX: [u8; 16] = [
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
before · pallets/nonfungible/src/erc.rs
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, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey, CollectionPropertiesVec};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::vec::Vec;28use pallet_common::{29	erc::{CommonEvmHandler, PrecompileResult, CollectionCall},30	CollectionHandle, CollectionPropertyPermissions,31};32use pallet_evm::account::CrossAccountId;33use pallet_evm_coder_substrate::call;34use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3536use crate::{37	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,38	SelfWeightOf, weights::WeightInfo, TokenProperties,39};4041#[solidity_interface(name = "TokenProperties")]42impl<T: Config> NonfungibleHandle<T> {43	fn set_token_property_permission(44		&mut self,45		caller: caller,46		key: string,47		is_mutable: bool,48		collection_admin: bool,49		token_owner: bool,50	) -> Result<()> {51		let caller = T::CrossAccountId::from_eth(caller);52		<Pallet<T>>::set_property_permission(53			self,54			&caller,55			PropertyKeyPermission {56				key: <Vec<u8>>::from(key)57					.try_into()58					.map_err(|_| "too long key")?,59				permission: PropertyPermission {60					mutable: is_mutable,61					collection_admin,62					token_owner,63				},64			},65		)66		.map_err(dispatch_to_evm::<T>)67	}6869	fn set_property(70		&mut self,71		caller: caller,72		token_id: uint256,73		key: string,74		value: bytes,75	) -> Result<()> {76		let caller = T::CrossAccountId::from_eth(caller);77		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;78		let key = <Vec<u8>>::from(key)79			.try_into()80			.map_err(|_| "key too long")?;81		let value = value.try_into().map_err(|_| "value too long")?;8283		<Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })84			.map_err(dispatch_to_evm::<T>)85	}8687	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {88		let caller = T::CrossAccountId::from_eth(caller);89		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;90		let key = <Vec<u8>>::from(key)91			.try_into()92			.map_err(|_| "key too long")?;9394		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)95			.map_err(dispatch_to_evm::<T>)96	}9798	/// Throws error if key not found99	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {100		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101		let key = <Vec<u8>>::from(key)102			.try_into()103			.map_err(|_| "key too long")?;104105		let props = <TokenProperties<T>>::get((self.id, token_id));106		let prop = props.get(&key).ok_or("key not found")?;107108		Ok(prop.to_vec())109	}110}111112#[derive(ToLog)]113pub enum ERC721Events {114	Transfer {115		#[indexed]116		from: address,117		#[indexed]118		to: address,119		#[indexed]120		token_id: uint256,121	},122	Approval {123		#[indexed]124		owner: address,125		#[indexed]126		approved: address,127		#[indexed]128		token_id: uint256,129	},130	#[allow(dead_code)]131	ApprovalForAll {132		#[indexed]133		owner: address,134		#[indexed]135		operator: address,136		approved: bool,137	},138}139140#[derive(ToLog)]141pub enum ERC721MintableEvents {142	#[allow(dead_code)]143	MintingFinished {},144}145146#[solidity_interface(name = "ERC721Metadata")]147impl<T: Config> NonfungibleHandle<T> {148	fn name(&self) -> Result<string> {149		Ok(decode_utf16(self.name.iter().copied())150			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))151			.collect::<string>())152	}153154	fn symbol(&self) -> Result<string> {155		Ok(string::from_utf8_lossy(&self.token_prefix).into())156	}157158	/// Returns token's const_metadata159	#[solidity(rename_selector = "tokenURI")]160	fn token_uri(&self, token_id: uint256) -> Result<string> {161		let key: string = "tokenURI".into(); //TODO: make static162		let key: up_data_structs::PropertyKey = key.into_bytes().try_into()163			.map_err(|_| Error::Revert("".into()))?;164		let permission = get_token_permission::<T>(self.id, &key)?;165		if !permission.collection_admin {166			return Err("Operation is not allowed".into());167		}168169		self.consume_store_reads(1)?;170		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;171172		let properties = <TokenProperties<T>>::try_get((self.id, token_id))173			.map_err(|_| Error::Revert("Token properties not found".into()))?;174		if let Some(property) = properties.get(&key) {175			return Ok(string::from_utf8_lossy(property).into());176		}177178		Err("Property tokenURI not found".into())179	}180}181182#[solidity_interface(name = "ERC721Enumerable")]183impl<T: Config> NonfungibleHandle<T> {184	fn token_by_index(&self, index: uint256) -> Result<uint256> {185		Ok(index)186	}187188	/// Not implemented189	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {190		// TODO: Not implemetable191		Err("not implemented".into())192	}193194	fn total_supply(&self) -> Result<uint256> {195		self.consume_store_reads(1)?;196		Ok(<Pallet<T>>::total_supply(self).into())197	}198}199200#[solidity_interface(name = "ERC721", events(ERC721Events))]201impl<T: Config> NonfungibleHandle<T> {202	fn balance_of(&self, owner: address) -> Result<uint256> {203		self.consume_store_reads(1)?;204		let owner = T::CrossAccountId::from_eth(owner);205		let balance = <AccountBalance<T>>::get((self.id, owner));206		Ok(balance.into())207	}208	fn owner_of(&self, token_id: uint256) -> Result<address> {209		self.consume_store_reads(1)?;210		let token: TokenId = token_id.try_into()?;211		Ok(*<TokenData<T>>::get((self.id, token))212			.ok_or("token not found")?213			.owner214			.as_eth())215	}216	/// Not implemented217	fn safe_transfer_from_with_data(218		&mut self,219		_from: address,220		_to: address,221		_token_id: uint256,222		_data: bytes,223		_value: value,224	) -> Result<void> {225		// TODO: Not implemetable226		Err("not implemented".into())227	}228	/// Not implemented229	fn safe_transfer_from(230		&mut self,231		_from: address,232		_to: address,233		_token_id: uint256,234		_value: value,235	) -> Result<void> {236		// TODO: Not implemetable237		Err("not implemented".into())238	}239240	#[weight(<SelfWeightOf<T>>::transfer_from())]241	fn transfer_from(242		&mut self,243		caller: caller,244		from: address,245		to: address,246		token_id: uint256,247		_value: value,248	) -> Result<void> {249		let caller = T::CrossAccountId::from_eth(caller);250		let from = T::CrossAccountId::from_eth(from);251		let to = T::CrossAccountId::from_eth(to);252		let token = token_id.try_into()?;253		let budget = self254			.recorder255			.weight_calls_budget(<StructureWeight<T>>::find_parent());256257		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)258			.map_err(dispatch_to_evm::<T>)?;259		Ok(())260	}261262	#[weight(<SelfWeightOf<T>>::approve())]263	fn approve(264		&mut self,265		caller: caller,266		approved: address,267		token_id: uint256,268		_value: value,269	) -> Result<void> {270		let caller = T::CrossAccountId::from_eth(caller);271		let approved = T::CrossAccountId::from_eth(approved);272		let token = token_id.try_into()?;273274		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))275			.map_err(dispatch_to_evm::<T>)?;276		Ok(())277	}278279	/// Not implemented280	fn set_approval_for_all(281		&mut self,282		_caller: caller,283		_operator: address,284		_approved: bool,285	) -> Result<void> {286		// TODO: Not implemetable287		Err("not implemented".into())288	}289290	/// Not implemented291	fn get_approved(&self, _token_id: uint256) -> Result<address> {292		// TODO: Not implemetable293		Err("not implemented".into())294	}295296	/// Not implemented297	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {298		// TODO: Not implemetable299		Err("not implemented".into())300	}301}302303#[solidity_interface(name = "ERC721Burnable")]304impl<T: Config> NonfungibleHandle<T> {305	#[weight(<SelfWeightOf<T>>::burn_item())]306	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {307		let caller = T::CrossAccountId::from_eth(caller);308		let token = token_id.try_into()?;309310		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;311		Ok(())312	}313}314315#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]316impl<T: Config> NonfungibleHandle<T> {317	fn minting_finished(&self) -> Result<bool> {318		Ok(false)319	}320321	/// `token_id` should be obtained with `next_token_id` method,322	/// unlike standard, you can't specify it manually323	#[weight(<SelfWeightOf<T>>::create_item())]324	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {325		let caller = T::CrossAccountId::from_eth(caller);326		let to = T::CrossAccountId::from_eth(to);327		let token_id: u32 = token_id.try_into()?;328		let budget = self329			.recorder330			.weight_calls_budget(<StructureWeight<T>>::find_parent());331332		if <TokensMinted<T>>::get(self.id)333			.checked_add(1)334			.ok_or("item id overflow")?335			!= token_id336		{337			return Err("item id should be next".into());338		}339340		<Pallet<T>>::create_item(341			self,342			&caller,343			CreateItemData::<T> {344				properties: BoundedVec::default(),345				owner: to,346			},347			&budget,348		)349		.map_err(dispatch_to_evm::<T>)?;350351		Ok(true)352	}353354	/// `token_id` should be obtained with `next_token_id` method,355	/// unlike standard, you can't specify it manually356	#[solidity(rename_selector = "mintWithTokenURI")]357	#[weight(<SelfWeightOf<T>>::create_item())]358	fn mint_with_token_uri(359		&mut self,360		caller: caller,361		to: address,362		token_id: uint256,363		token_uri: string,364	) -> Result<bool> {365		let key: string = "tokenURI".into(); //TODO: make static366		let key: up_data_structs::PropertyKey = key.into_bytes().try_into()367			.map_err(|_| Error::Revert("".into()))?;368		let permission = get_token_permission::<T>(self.id, &key)?;369		if !permission.collection_admin {370			return Err("Operation is not allowed".into());371		}372373		let caller = T::CrossAccountId::from_eth(caller);374		let to = T::CrossAccountId::from_eth(to);375		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;376		let budget = self377			.recorder378			.weight_calls_budget(<StructureWeight<T>>::find_parent());379380		if <TokensMinted<T>>::get(self.id)381			.checked_add(1)382			.ok_or("item id overflow")?383			!= token_id384		{385			return Err("item id should be next".into());386		}387388		let mut properties = CollectionPropertiesVec::default();389		properties.try_push(Property{390			key,391			value: token_uri.into_bytes().try_into()392				.map_err(|_| "token uri is too long")?393		}).map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;394395		<Pallet<T>>::create_item(396			self,397			&caller,398			CreateItemData::<T> {399				properties,400				owner: to,401			},402			&budget,403		)404		.map_err(dispatch_to_evm::<T>)?;405		Ok(true)406	}407408	/// Not implemented409	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {410		Err("not implementable".into())411	}412}413414fn get_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> Result<PropertyPermission> {415	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)416		.map_err(|_| Error::Revert("No permissions for collection".into()))?;417	let a = token_property_permissions.get(key)418		.map(|p| p.clone())419		.ok_or_else(|| Error::Revert("No permission for tokenURI".into()))?;420	Ok(a)421}422423#[solidity_interface(name = "ERC721UniqueExtensions")]424impl<T: Config> NonfungibleHandle<T> {425	#[weight(<SelfWeightOf<T>>::transfer())]426	fn transfer(427		&mut self,428		caller: caller,429		to: address,430		token_id: uint256,431		_value: value,432	) -> Result<void> {433		let caller = T::CrossAccountId::from_eth(caller);434		let to = T::CrossAccountId::from_eth(to);435		let token = token_id.try_into()?;436		let budget = self437			.recorder438			.weight_calls_budget(<StructureWeight<T>>::find_parent());439440		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;441		Ok(())442	}443444	#[weight(<SelfWeightOf<T>>::burn_from())]445	fn burn_from(446		&mut self,447		caller: caller,448		from: address,449		token_id: uint256,450		_value: value,451	) -> Result<void> {452		let caller = T::CrossAccountId::from_eth(caller);453		let from = T::CrossAccountId::from_eth(from);454		let token = token_id.try_into()?;455		let budget = self456			.recorder457			.weight_calls_budget(<StructureWeight<T>>::find_parent());458459		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)460			.map_err(dispatch_to_evm::<T>)?;461		Ok(())462	}463464	fn next_token_id(&self) -> Result<uint256> {465		self.consume_store_reads(1)?;466		Ok(<TokensMinted<T>>::get(self.id)467			.checked_add(1)468			.ok_or("item id overflow")?469			.into())470	}471472	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]473	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {474		let caller = T::CrossAccountId::from_eth(caller);475		let to = T::CrossAccountId::from_eth(to);476		let mut expected_index = <TokensMinted<T>>::get(self.id)477			.checked_add(1)478			.ok_or("item id overflow")?;479		let budget = self480			.recorder481			.weight_calls_budget(<StructureWeight<T>>::find_parent());482483		let total_tokens = token_ids.len();484		for id in token_ids.into_iter() {485			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;486			if id != expected_index {487				return Err("item id should be next".into());488			}489			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;490		}491		let data = (0..total_tokens)492			.map(|_| CreateItemData::<T> {493				properties: BoundedVec::default(),494				owner: to.clone(),495			})496			.collect();497498		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)499			.map_err(dispatch_to_evm::<T>)?;500		Ok(true)501	}502503	#[solidity(rename_selector = "mintBulkWithTokenURI")]504	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]505	fn mint_bulk_with_token_uri(506		&mut self,507		caller: caller,508		to: address,509		tokens: Vec<(uint256, string)>,510	) -> Result<bool> {511		let caller = T::CrossAccountId::from_eth(caller);512		let to = T::CrossAccountId::from_eth(to);513		let mut expected_index = <TokensMinted<T>>::get(self.id)514			.checked_add(1)515			.ok_or("item id overflow")?;516		let budget = self517			.recorder518			.weight_calls_budget(<StructureWeight<T>>::find_parent());519520		let mut data = Vec::with_capacity(tokens.len());521		for (id, token_uri) in tokens {522			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;523			if id != expected_index {524				return Err("item id should be next".into());525			}526			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;527528			todo!("token uri");529			data.push(CreateItemData::<T> {530				properties: BoundedVec::default(),531				owner: to.clone(),532			});533		}534535		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)536			.map_err(dispatch_to_evm::<T>)?;537		Ok(true)538	}539}540541#[solidity_interface(542	name = "UniqueNFT",543	is(544		ERC721,545		ERC721Metadata,546		ERC721Enumerable,547		ERC721UniqueExtensions,548		ERC721Mintable,549		ERC721Burnable,550		via("CollectionHandle<T>", common_mut, Collection),551		TokenProperties,552	)553)]554impl<T: Config> NonfungibleHandle<T> {}555556// Not a tests, but code generators557generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);558generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);559560impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {561	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");562563	fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {564		call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)565	}566}
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -77,8 +77,7 @@
 			.try_into()
 			.map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;
 
-		let key: string = "tokenURI".into(); //TODO: make static
-		let key: up_data_structs::PropertyKey = key.into_bytes().try_into().map_err(|_| Error::Revert("".into()))?;
+		let key = pallet_common::eth::KEY_TOKEN_URI.clone();
 		let permission = up_data_structs::PropertyPermission {
 			mutable: true,
 			collection_admin: true,