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

difftreelog

refacator: Move Property from evm_codet into pallet_common and derive AbiCoder

Trubnikov Sergey2022-12-19parent: #14137a1.patch.diff
in: master

6 files changed

modifiedcrates/evm-coder/src/abi/impls.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi/impls.rs
+++ b/crates/evm-coder/src/abi/impls.rs
@@ -138,42 +138,6 @@
 	}
 }
 
-impl sealed::CanBePlacedInVec for Property {}
-
-impl AbiType for Property {
-	const SIGNATURE: SignatureUnit = make_signature!(new fixed("(string,bytes)"));
-	const FIELDS_COUNT: usize = 2;
-
-	fn is_dynamic() -> bool {
-		string::is_dynamic() || bytes::is_dynamic()
-	}
-
-	fn size() -> usize {
-		<string as AbiType>::size() + <bytes as AbiType>::size()
-	}
-}
-
-impl AbiRead for Property {
-	fn abi_read(reader: &mut AbiReader) -> Result<Property> {
-		let size = if !Property::is_dynamic() {
-			Some(<Property as AbiType>::size())
-		} else {
-			None
-		};
-		let mut subresult = reader.subresult(size)?;
-		let key = <string>::abi_read(&mut subresult)?;
-		let value = <bytes>::abi_read(&mut subresult)?;
-
-		Ok(Property { key, value })
-	}
-}
-
-impl AbiWrite for Property {
-	fn abi_write(&self, writer: &mut AbiWriter) {
-		(&self.key, &self.value).abi_write(writer);
-	}
-}
-
 impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {
 	fn abi_write(&self, writer: &mut AbiWriter) {
 		let is_dynamic = T::is_dynamic();
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -196,12 +196,6 @@
 			self.len() == 0
 		}
 	}
-
-	#[derive(Debug, Default)]
-	pub struct Property {
-		pub key: string,
-		pub value: bytes,
-	}
 }
 
 /// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,7 +21,6 @@
 	abi::AbiType,
 	solidity_interface, solidity, ToLog,
 	types::*,
-	types::Property as PropertyStruct,
 	execution::{Result, Error},
 	weight,
 };
@@ -36,7 +35,7 @@
 use crate::{
 	Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
 	eth::{
-		EthCrossAccount, CollectionPermissions as EvmPermissions,
+		Property as PropertyStruct, EthCrossAccount, CollectionPermissions as EvmPermissions,
 		CollectionLimits as EvmCollectionLimits,
 	},
 	weights::WeightInfo,
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
before · pallets/common/src/eth.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/>.1617//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20	AbiCoder,21	types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35	if eth[0..16] != ETH_COLLECTION_PREFIX {36		return None;37	}38	let mut id_bytes = [0; 4];39	id_bytes.copy_from_slice(&eth[16..20]);40	Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45	let mut out = [0; 20];46	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);47	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48	H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53	address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `uint256` to `CrossAccountId`.57pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId58where59	T::AccountId: From<[u8; 32]>,60{61	let mut new_admin_arr = [0_u8; 32];62	from.to_big_endian(&mut new_admin_arr);63	let account_id = T::AccountId::from(new_admin_arr);64	T::CrossAccountId::from_sub(account_id)65}6667/// Cross account struct68#[derive(Debug, Default, AbiCoder)]69pub struct EthCrossAccount {70	pub(crate) eth: address,71	pub(crate) sub: uint256,72}7374impl EthCrossAccount {75	/// Converts `CrossAccountId` to `EthCrossAccountId`76	pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self77	where78		T: pallet_evm::Config,79		T::AccountId: AsRef<[u8; 32]>,80	{81		if cross_account_id.is_canonical_substrate() {82			Self::from_sub::<T>(cross_account_id.as_sub())83		} else {84			Self {85				eth: *cross_account_id.as_eth(),86				sub: Default::default(),87			}88		}89	}90	/// Creates `EthCrossAccount` from substrate account91	pub fn from_sub<T>(account_id: &T::AccountId) -> Self92	where93		T: pallet_evm::Config,94		T::AccountId: AsRef<[u8; 32]>,95	{96		Self {97			eth: Default::default(),98			sub: uint256::from_big_endian(account_id.as_ref()),99		}100	}101	/// Converts `EthCrossAccount` to `CrossAccountId`102	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>103	where104		T: pallet_evm::Config,105		T::AccountId: From<[u8; 32]>,106	{107		if self.eth == Default::default() && self.sub == Default::default() {108			Err("All fields of cross account is zeroed".into())109		} else if self.eth == Default::default() {110			Ok(convert_uint256_to_cross_account::<T>(self.sub))111		} else if self.sub == Default::default() {112			Ok(T::CrossAccountId::from_eth(self.eth))113		} else {114			Err("All fields of cross account is non zeroed".into())115		}116	}117}118119/// [`CollectionLimits`](up_data_structs::CollectionLimits) representation for EVM.120#[derive(Debug, Default, Clone, Copy, AbiCoder)]121#[repr(u8)]122pub enum CollectionLimits {123	/// How many tokens can a user have on one account.124	#[default]125	AccountTokenOwnership,126127	/// How many bytes of data are available for sponsorship.128	SponsoredDataSize,129130	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]131	SponsoredDataRateLimit,132133	/// How many tokens can be mined into this collection.134	TokenLimit,135136	/// Timeouts for transfer sponsoring.137	SponsorTransferTimeout,138139	/// Timeout for sponsoring an approval in passed blocks.140	SponsorApproveTimeout,141142	/// Whether the collection owner of the collection can send tokens (which belong to other users).143	OwnerCanTransfer,144145	/// Can the collection owner burn other people's tokens.146	OwnerCanDestroy,147148	/// Is it possible to send tokens from this collection between users.149	TransferEnabled,150}151/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.152#[derive(Default, Debug, Clone, Copy, AbiCoder)]153#[repr(u8)]154pub enum CollectionPermissions {155	/// Owner of token can nest tokens under it.156	#[default]157	TokenOwner,158159	/// Admin of token collection can nest tokens under token.160	CollectionAdmin,161}162163/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.164#[derive(AbiCoder, Copy, Clone, Default, Debug)]165#[repr(u8)]166pub enum EthTokenPermissions {167	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]168	#[default]169	Mutable,170171	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]172	TokenOwner,173174	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]175	CollectionAdmin,176}
after · pallets/common/src/eth.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/>.1617//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20	AbiCoder,21	types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35	if eth[0..16] != ETH_COLLECTION_PREFIX {36		return None;37	}38	let mut id_bytes = [0; 4];39	id_bytes.copy_from_slice(&eth[16..20]);40	Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45	let mut out = [0; 20];46	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);47	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48	H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53	address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `uint256` to `CrossAccountId`.57pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId58where59	T::AccountId: From<[u8; 32]>,60{61	let mut new_admin_arr = [0_u8; 32];62	from.to_big_endian(&mut new_admin_arr);63	let account_id = T::AccountId::from(new_admin_arr);64	T::CrossAccountId::from_sub(account_id)65}6667/// Cross account struct68#[derive(Debug, Default, AbiCoder)]69pub struct EthCrossAccount {70	pub(crate) eth: address,71	pub(crate) sub: uint256,72}7374impl EthCrossAccount {75	/// Converts `CrossAccountId` to `EthCrossAccountId`76	pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self77	where78		T: pallet_evm::Config,79		T::AccountId: AsRef<[u8; 32]>,80	{81		if cross_account_id.is_canonical_substrate() {82			Self::from_sub::<T>(cross_account_id.as_sub())83		} else {84			Self {85				eth: *cross_account_id.as_eth(),86				sub: Default::default(),87			}88		}89	}90	/// Creates `EthCrossAccount` from substrate account91	pub fn from_sub<T>(account_id: &T::AccountId) -> Self92	where93		T: pallet_evm::Config,94		T::AccountId: AsRef<[u8; 32]>,95	{96		Self {97			eth: Default::default(),98			sub: uint256::from_big_endian(account_id.as_ref()),99		}100	}101	/// Converts `EthCrossAccount` to `CrossAccountId`102	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>103	where104		T: pallet_evm::Config,105		T::AccountId: From<[u8; 32]>,106	{107		if self.eth == Default::default() && self.sub == Default::default() {108			Err("All fields of cross account is zeroed".into())109		} else if self.eth == Default::default() {110			Ok(convert_uint256_to_cross_account::<T>(self.sub))111		} else if self.sub == Default::default() {112			Ok(T::CrossAccountId::from_eth(self.eth))113		} else {114			Err("All fields of cross account is non zeroed".into())115		}116	}117}118119/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).120#[derive(Debug, Default, AbiCoder)]121pub struct Property {122	/// Property key.123	pub key: evm_coder::types::string,124	/// Property value.125	pub value: evm_coder::types::bytes,126}127128/// [`CollectionLimits`](up_data_structs::CollectionLimits) representation for EVM.129#[derive(Debug, Default, Clone, Copy, AbiCoder)]130#[repr(u8)]131pub enum CollectionLimits {132	/// How many tokens can a user have on one account.133	#[default]134	AccountTokenOwnership,135136	/// How many bytes of data are available for sponsorship.137	SponsoredDataSize,138139	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]140	SponsoredDataRateLimit,141142	/// How many tokens can be mined into this collection.143	TokenLimit,144145	/// Timeouts for transfer sponsoring.146	SponsorTransferTimeout,147148	/// Timeout for sponsoring an approval in passed blocks.149	SponsorApproveTimeout,150151	/// Whether the collection owner of the collection can send tokens (which belong to other users).152	OwnerCanTransfer,153154	/// Can the collection owner burn other people's tokens.155	OwnerCanDestroy,156157	/// Is it possible to send tokens from this collection between users.158	TransferEnabled,159}160/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.161#[derive(Default, Debug, Clone, Copy, AbiCoder)]162#[repr(u8)]163pub enum CollectionPermissions {164	/// Owner of token can nest tokens under it.165	#[default]166	TokenOwner,167168	/// Admin of token collection can nest tokens under token.169	CollectionAdmin,170}171172/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.173#[derive(AbiCoder, Copy, Clone, Default, Debug)]174#[repr(u8)]175pub enum EthTokenPermissions {176	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]177	#[default]178	Mutable,179180	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]181	TokenOwner,182183	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]184	CollectionAdmin,185}
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -26,7 +26,7 @@
 };
 use evm_coder::{
 	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,
-	types::Property as PropertyStruct, weight,
+	weight,
 };
 use frame_support::BoundedVec;
 use up_data_structs::{
@@ -38,7 +38,7 @@
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
-	eth::{EthCrossAccount, EthTokenPermissions},
+	eth::{Property as PropertyStruct, EthCrossAccount, EthTokenPermissions},
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::call;
@@ -97,17 +97,15 @@
 		permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
 	) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
-		const PERMISSIONS_FIELDS_COUNT: usize = 3;
-
 		let mut perms = Vec::new();
 
 		for (key, pp) in permissions {
-			if pp.len() > PERMISSIONS_FIELDS_COUNT {
+			if pp.len() > EthTokenPermissions::FIELDS_COUNT {
 				return Err(alloc::format!(
 					"Actual number of fields {} for {}, which exceeds the maximum value of {}",
 					pp.len(),
 					stringify!(EthTokenPermissions),
-					PERMISSIONS_FIELDS_COUNT
+					EthTokenPermissions::FIELDS_COUNT
 				)
 				.as_str()
 				.into());
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -27,13 +27,13 @@
 };
 use evm_coder::{
 	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,
-	types::Property as PropertyStruct, weight,
+	weight,
 };
 use frame_support::{BoundedBTreeMap, BoundedVec};
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, CollectionCall, static_property::key},
-	eth::{EthCrossAccount, EthTokenPermissions},
+	eth::{Property as PropertyStruct, EthCrossAccount, EthTokenPermissions},
 	Error as CommonError,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};