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
before · crates/evm-coder/src/abi/impls.rs
1use crate::{2	custom_signature::SignatureUnit,3	execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},4	make_signature, sealed,5	types::*,6};7use super::{traits::*, ABI_ALIGNMENT, AbiReader, AbiWriter};8use primitive_types::{U256, H160};910#[cfg(not(feature = "std"))]11use alloc::vec::Vec;1213macro_rules! impl_abi_type {14	($ty:ty, $name:ident, $dynamic:literal) => {15		impl sealed::CanBePlacedInVec for $ty {}1617		impl AbiType for $ty {18			const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($name)));19			const FIELDS_COUNT: usize = 1;2021			fn is_dynamic() -> bool {22				$dynamic23			}2425			fn size() -> usize {26				ABI_ALIGNMENT27			}28		}29	};30}3132macro_rules! impl_abi_readable {33	($ty:ty, $method:ident) => {34		impl AbiRead for $ty {35			fn abi_read(reader: &mut AbiReader) -> Result<$ty> {36				reader.$method()37			}38		}39	};40}4142macro_rules! impl_abi_writeable {43	($ty:ty, $method:ident) => {44		impl AbiWrite for $ty {45			fn abi_write(&self, writer: &mut AbiWriter) {46				writer.$method(&self)47			}48		}49	};50}5152macro_rules! impl_abi {53	($ty:ty, $method:ident, $dynamic:literal) => {54		impl_abi_type!($ty, $method, $dynamic);55		impl_abi_readable!($ty, $method);56		impl_abi_writeable!($ty, $method);57	};58}5960impl_abi!(bool, bool, false);61impl_abi!(u8, uint8, false);62impl_abi!(u32, uint32, false);63impl_abi!(u64, uint64, false);64impl_abi!(u128, uint128, false);65impl_abi!(U256, uint256, false);66impl_abi!(H160, address, false);67impl_abi!(string, string, true);6869impl_abi_writeable!(&str, string);7071impl_abi_type!(bytes, bytes, true);7273impl AbiRead for bytes {74	fn abi_read(reader: &mut AbiReader) -> Result<bytes> {75		Ok(bytes(reader.bytes()?))76	}77}7879impl AbiWrite for bytes {80	fn abi_write(&self, writer: &mut AbiWriter) {81		writer.bytes(self.0.as_slice())82	}83}8485impl_abi_type!(bytes4, bytes4, false);86impl AbiRead for bytes4 {87	fn abi_read(reader: &mut AbiReader) -> Result<bytes4> {88		reader.bytes4()89	}90}9192impl<T: AbiWrite> AbiWrite for &T {93	fn abi_write(&self, writer: &mut AbiWriter) {94		T::abi_write(self, writer);95	}96}9798impl<T: AbiType> AbiType for &T {99	const SIGNATURE: SignatureUnit = T::SIGNATURE;100	const FIELDS_COUNT: usize = T::FIELDS_COUNT;101102	fn is_dynamic() -> bool {103		T::is_dynamic()104	}105106	fn size() -> usize {107		T::size()108	}109}110111impl<T: AbiType + AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<T> {112	fn abi_read(reader: &mut AbiReader) -> Result<Vec<T>> {113		let mut sub = reader.subresult(None)?;114		let size = sub.uint32()? as usize;115		sub.subresult_offset = sub.offset;116		let is_dynamic = <T as AbiType>::is_dynamic();117		let mut out = Vec::with_capacity(size);118		for _ in 0..size {119			out.push(<T as AbiRead>::abi_read(&mut sub)?);120			if !is_dynamic {121				sub.bytes_read(<T as AbiType>::size());122			};123		}124		Ok(out)125	}126}127128impl<T: AbiType> AbiType for Vec<T> {129	const SIGNATURE: SignatureUnit = make_signature!(new nameof(T::SIGNATURE) fixed("[]"));130	const FIELDS_COUNT: usize = 1;131132	fn is_dynamic() -> bool {133		true134	}135136	fn size() -> usize {137		ABI_ALIGNMENT138	}139}140141impl sealed::CanBePlacedInVec for Property {}142143impl AbiType for Property {144	const SIGNATURE: SignatureUnit = make_signature!(new fixed("(string,bytes)"));145	const FIELDS_COUNT: usize = 2;146147	fn is_dynamic() -> bool {148		string::is_dynamic() || bytes::is_dynamic()149	}150151	fn size() -> usize {152		<string as AbiType>::size() + <bytes as AbiType>::size()153	}154}155156impl AbiRead for Property {157	fn abi_read(reader: &mut AbiReader) -> Result<Property> {158		let size = if !Property::is_dynamic() {159			Some(<Property as AbiType>::size())160		} else {161			None162		};163		let mut subresult = reader.subresult(size)?;164		let key = <string>::abi_read(&mut subresult)?;165		let value = <bytes>::abi_read(&mut subresult)?;166167		Ok(Property { key, value })168	}169}170171impl AbiWrite for Property {172	fn abi_write(&self, writer: &mut AbiWriter) {173		(&self.key, &self.value).abi_write(writer);174	}175}176177impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {178	fn abi_write(&self, writer: &mut AbiWriter) {179		let is_dynamic = T::is_dynamic();180		let mut sub = if is_dynamic {181			AbiWriter::new_dynamic(is_dynamic)182		} else {183			AbiWriter::new()184		};185186		// Write items count187		(self.len() as u32).abi_write(&mut sub);188189		for item in self {190			item.abi_write(&mut sub);191		}192		writer.write_subresult(sub);193	}194}195196impl AbiWrite for () {197	fn abi_write(&self, _writer: &mut AbiWriter) {}198}199200/// This particular AbiWrite implementation should be split to another trait,201/// which only implements `to_result`, but due to lack of specialization feature202/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,203/// so here we abusing default trait methods for it204impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {205	fn abi_write(&self, _writer: &mut AbiWriter) {206		debug_assert!(false, "shouldn't be called, see comment")207	}208	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {209		match self {210			Ok(v) => Ok(WithPostDispatchInfo {211				post_info: v.post_info.clone(),212				data: {213					let mut out = AbiWriter::new();214					v.data.abi_write(&mut out);215					out216				},217			}),218			Err(e) => Err(e.clone()),219		}220	}221}222223macro_rules! impl_tuples {224	($($ident:ident)+) => {225		impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)226		where227        $(228            $ident: AbiType,229        )+230		{231            const SIGNATURE: SignatureUnit = make_signature!(232                new fixed("(")233                $(nameof(<$ident>::SIGNATURE) fixed(","))+234                shift_left(1)235                fixed(")")236            );237			const FIELDS_COUNT: usize = 0 $(+ {let _ = <$ident as AbiType>::FIELDS_COUNT; 1})+;238239			fn is_dynamic() -> bool {240				false241				$(242					|| <$ident>::is_dynamic()243				)*244			}245246			fn size() -> usize {247				0 $(+ <$ident>::size())+248			}249		}250251		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}252253		impl<$($ident),+> AbiRead for ($($ident,)+)254		where255			Self: AbiType,256			$($ident: AbiRead + AbiType,)+257		{258			fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {259				let is_dynamic = <Self>::is_dynamic();260				let size = if !is_dynamic { Some(<Self>::size()) } else { None };261				let mut subresult = reader.subresult(size)?;262				Ok((263					$({264						let value = <$ident>::abi_read(&mut subresult)?;265						if !is_dynamic {subresult.bytes_read(<$ident as AbiType>::size())};266						value267					},)+268				))269			}270		}271272		#[allow(non_snake_case)]273		impl<$($ident),+> AbiWrite for ($($ident,)+)274		where275			$($ident: AbiWrite + AbiType,)+276		{277			fn abi_write(&self, writer: &mut AbiWriter) {278				let ($($ident,)+) = self;279				if <Self as AbiType>::is_dynamic() {280					let mut sub = AbiWriter::new();281					$($ident.abi_write(&mut sub);)+282					writer.write_subresult(sub);283				} else {284					$($ident.abi_write(writer);)+285				}286			}287		}288	};289}290291impl_tuples! {A}292impl_tuples! {A B}293impl_tuples! {A B C}294impl_tuples! {A B C D}295impl_tuples! {A B C D E}296impl_tuples! {A B C D E F}297impl_tuples! {A B C D E F G}298impl_tuples! {A B C D E F G H}299impl_tuples! {A B C D E F G H I}300impl_tuples! {A B C D E F G H I J}
after · crates/evm-coder/src/abi/impls.rs
1use crate::{2	custom_signature::SignatureUnit,3	execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},4	make_signature, sealed,5	types::*,6};7use super::{traits::*, ABI_ALIGNMENT, AbiReader, AbiWriter};8use primitive_types::{U256, H160};910#[cfg(not(feature = "std"))]11use alloc::vec::Vec;1213macro_rules! impl_abi_type {14	($ty:ty, $name:ident, $dynamic:literal) => {15		impl sealed::CanBePlacedInVec for $ty {}1617		impl AbiType for $ty {18			const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($name)));19			const FIELDS_COUNT: usize = 1;2021			fn is_dynamic() -> bool {22				$dynamic23			}2425			fn size() -> usize {26				ABI_ALIGNMENT27			}28		}29	};30}3132macro_rules! impl_abi_readable {33	($ty:ty, $method:ident) => {34		impl AbiRead for $ty {35			fn abi_read(reader: &mut AbiReader) -> Result<$ty> {36				reader.$method()37			}38		}39	};40}4142macro_rules! impl_abi_writeable {43	($ty:ty, $method:ident) => {44		impl AbiWrite for $ty {45			fn abi_write(&self, writer: &mut AbiWriter) {46				writer.$method(&self)47			}48		}49	};50}5152macro_rules! impl_abi {53	($ty:ty, $method:ident, $dynamic:literal) => {54		impl_abi_type!($ty, $method, $dynamic);55		impl_abi_readable!($ty, $method);56		impl_abi_writeable!($ty, $method);57	};58}5960impl_abi!(bool, bool, false);61impl_abi!(u8, uint8, false);62impl_abi!(u32, uint32, false);63impl_abi!(u64, uint64, false);64impl_abi!(u128, uint128, false);65impl_abi!(U256, uint256, false);66impl_abi!(H160, address, false);67impl_abi!(string, string, true);6869impl_abi_writeable!(&str, string);7071impl_abi_type!(bytes, bytes, true);7273impl AbiRead for bytes {74	fn abi_read(reader: &mut AbiReader) -> Result<bytes> {75		Ok(bytes(reader.bytes()?))76	}77}7879impl AbiWrite for bytes {80	fn abi_write(&self, writer: &mut AbiWriter) {81		writer.bytes(self.0.as_slice())82	}83}8485impl_abi_type!(bytes4, bytes4, false);86impl AbiRead for bytes4 {87	fn abi_read(reader: &mut AbiReader) -> Result<bytes4> {88		reader.bytes4()89	}90}9192impl<T: AbiWrite> AbiWrite for &T {93	fn abi_write(&self, writer: &mut AbiWriter) {94		T::abi_write(self, writer);95	}96}9798impl<T: AbiType> AbiType for &T {99	const SIGNATURE: SignatureUnit = T::SIGNATURE;100	const FIELDS_COUNT: usize = T::FIELDS_COUNT;101102	fn is_dynamic() -> bool {103		T::is_dynamic()104	}105106	fn size() -> usize {107		T::size()108	}109}110111impl<T: AbiType + AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<T> {112	fn abi_read(reader: &mut AbiReader) -> Result<Vec<T>> {113		let mut sub = reader.subresult(None)?;114		let size = sub.uint32()? as usize;115		sub.subresult_offset = sub.offset;116		let is_dynamic = <T as AbiType>::is_dynamic();117		let mut out = Vec::with_capacity(size);118		for _ in 0..size {119			out.push(<T as AbiRead>::abi_read(&mut sub)?);120			if !is_dynamic {121				sub.bytes_read(<T as AbiType>::size());122			};123		}124		Ok(out)125	}126}127128impl<T: AbiType> AbiType for Vec<T> {129	const SIGNATURE: SignatureUnit = make_signature!(new nameof(T::SIGNATURE) fixed("[]"));130	const FIELDS_COUNT: usize = 1;131132	fn is_dynamic() -> bool {133		true134	}135136	fn size() -> usize {137		ABI_ALIGNMENT138	}139}140141impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {142	fn abi_write(&self, writer: &mut AbiWriter) {143		let is_dynamic = T::is_dynamic();144		let mut sub = if is_dynamic {145			AbiWriter::new_dynamic(is_dynamic)146		} else {147			AbiWriter::new()148		};149150		// Write items count151		(self.len() as u32).abi_write(&mut sub);152153		for item in self {154			item.abi_write(&mut sub);155		}156		writer.write_subresult(sub);157	}158}159160impl AbiWrite for () {161	fn abi_write(&self, _writer: &mut AbiWriter) {}162}163164/// This particular AbiWrite implementation should be split to another trait,165/// which only implements `to_result`, but due to lack of specialization feature166/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,167/// so here we abusing default trait methods for it168impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {169	fn abi_write(&self, _writer: &mut AbiWriter) {170		debug_assert!(false, "shouldn't be called, see comment")171	}172	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {173		match self {174			Ok(v) => Ok(WithPostDispatchInfo {175				post_info: v.post_info.clone(),176				data: {177					let mut out = AbiWriter::new();178					v.data.abi_write(&mut out);179					out180				},181			}),182			Err(e) => Err(e.clone()),183		}184	}185}186187macro_rules! impl_tuples {188	($($ident:ident)+) => {189		impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)190		where191        $(192            $ident: AbiType,193        )+194		{195            const SIGNATURE: SignatureUnit = make_signature!(196                new fixed("(")197                $(nameof(<$ident>::SIGNATURE) fixed(","))+198                shift_left(1)199                fixed(")")200            );201			const FIELDS_COUNT: usize = 0 $(+ {let _ = <$ident as AbiType>::FIELDS_COUNT; 1})+;202203			fn is_dynamic() -> bool {204				false205				$(206					|| <$ident>::is_dynamic()207				)*208			}209210			fn size() -> usize {211				0 $(+ <$ident>::size())+212			}213		}214215		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}216217		impl<$($ident),+> AbiRead for ($($ident,)+)218		where219			Self: AbiType,220			$($ident: AbiRead + AbiType,)+221		{222			fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {223				let is_dynamic = <Self>::is_dynamic();224				let size = if !is_dynamic { Some(<Self>::size()) } else { None };225				let mut subresult = reader.subresult(size)?;226				Ok((227					$({228						let value = <$ident>::abi_read(&mut subresult)?;229						if !is_dynamic {subresult.bytes_read(<$ident as AbiType>::size())};230						value231					},)+232				))233			}234		}235236		#[allow(non_snake_case)]237		impl<$($ident),+> AbiWrite for ($($ident,)+)238		where239			$($ident: AbiWrite + AbiType,)+240		{241			fn abi_write(&self, writer: &mut AbiWriter) {242				let ($($ident,)+) = self;243				if <Self as AbiType>::is_dynamic() {244					let mut sub = AbiWriter::new();245					$($ident.abi_write(&mut sub);)+246					writer.write_subresult(sub);247				} else {248					$($ident.abi_write(writer);)+249				}250			}251		}252	};253}254255impl_tuples! {A}256impl_tuples! {A B}257impl_tuples! {A B C}258impl_tuples! {A B C D}259impl_tuples! {A B C D E}260impl_tuples! {A B C D E F}261impl_tuples! {A B C D E F G}262impl_tuples! {A B C D E F G H}263impl_tuples! {A B C D E F G H I}264impl_tuples! {A B C D E F G H I J}
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
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -116,6 +116,15 @@
 	}
 }
 
+/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
+#[derive(Debug, Default, AbiCoder)]
+pub struct Property {
+	/// Property key.
+	pub key: evm_coder::types::string,
+	/// Property value.
+	pub value: evm_coder::types::bytes,
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) representation for EVM.
 #[derive(Debug, Default, Clone, Copy, AbiCoder)]
 #[repr(u8)]
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};