git.delta.rocks / unique-network / refs/commits / 068fc8208402

difftreelog

refactor Abi impls

Trubnikov Sergey2022-11-18parent: #e2559ac.patch.diff
in: master

5 files changed

modifiedcrates/evm-coder/procedural/src/abi_derive.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/abi_derive.rs
+++ b/crates/evm-coder/procedural/src/abi_derive.rs
@@ -121,7 +121,7 @@
 				#(
 					let #field_names = {
 						let value = <#field_types as ::evm_coder::abi::AbiRead>::abi_read(&mut subresult)?;
-						if !is_dynamic {subresult.seek(<#field_types as ::evm_coder::abi::AbiType>::size())};
+						if !is_dynamic {subresult.bytes_read(<#field_types as ::evm_coder::abi::AbiType>::size())};
 						value
 					};
 				)*
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -406,7 +406,7 @@
 		quote! {
 			#name: {
 				let value = <#ty as ::evm_coder::abi::AbiRead>::abi_read(reader)?;
-				if !is_dynamic {reader.seek(<#ty as ::evm_coder::abi::AbiType>::size())};
+				if !is_dynamic {reader.bytes_read(<#ty as ::evm_coder::abi::AbiType>::size())};
 				value
 			}
 		}
modifiedcrates/evm-coder/src/abi/impls.rsdiffbeforeafterboth
before · crates/evm-coder/src/abi/impls.rs
1use crate::{2	execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},3	types::*,4	make_signature,5	custom_signature::SignatureUnit,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_readable {14	($ty:ty, $method:ident, $dynamic:literal) => {15		impl sealed::CanBePlacedInVec for $ty {}1617		impl AbiType for $ty {18			const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ty)));1920			fn is_dynamic() -> bool {21				$dynamic22			}2324			fn size() -> usize {25				ABI_ALIGNMENT26			}27		}2829		impl AbiRead for $ty {30			fn abi_read(reader: &mut AbiReader) -> Result<$ty> {31				reader.$method()32			}33		}34	};35}3637impl_abi_readable!(uint32, uint32, false);38impl_abi_readable!(uint64, uint64, false);39impl_abi_readable!(uint128, uint128, false);40impl_abi_readable!(uint256, uint256, false);41impl_abi_readable!(bytes4, bytes4, false);42impl_abi_readable!(address, address, false);43impl_abi_readable!(string, string, true);4445impl sealed::CanBePlacedInVec for bool {}4647impl AbiType for bool {48	const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));4950	fn is_dynamic() -> bool {51		false52	}53	fn size() -> usize {54		ABI_ALIGNMENT55	}56}57impl AbiRead for bool {58	fn abi_read(reader: &mut AbiReader) -> Result<bool> {59		reader.bool()60	}61}6263impl AbiType for uint8 {64	const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));6566	fn is_dynamic() -> bool {67		false68	}69	fn size() -> usize {70		ABI_ALIGNMENT71	}72}73impl AbiRead for uint8 {74	fn abi_read(reader: &mut AbiReader) -> Result<uint8> {75		reader.uint8()76	}77}7879impl AbiType for bytes {80	const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));8182	fn is_dynamic() -> bool {83		true84	}85	fn size() -> usize {86		ABI_ALIGNMENT87	}88}89impl AbiRead for bytes {90	fn abi_read(reader: &mut AbiReader) -> Result<bytes> {91		Ok(bytes(reader.bytes()?))92	}93}9495impl<R: AbiType + AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {96	fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {97		let mut sub = reader.subresult(None)?;98		let size = sub.uint32()? as usize;99		sub.subresult_offset = sub.offset;100		let mut out = Vec::with_capacity(size);101		for _ in 0..size {102			out.push(<R>::abi_read(&mut sub)?);103			if !<R>::is_dynamic() {104				sub.subresult_offset += <R>::size()105			};106		}107		Ok(out)108	}109}110111impl<R: AbiType> AbiType for Vec<R> {112	const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));113114	fn is_dynamic() -> bool {115		true116	}117118	fn size() -> usize {119		ABI_ALIGNMENT120	}121}122123impl sealed::CanBePlacedInVec for Property {}124125impl AbiType for Property {126	const SIGNATURE: SignatureUnit = make_signature!(new fixed("(string,bytes)"));127128	fn is_dynamic() -> bool {129		string::is_dynamic() || bytes::is_dynamic()130	}131132	fn size() -> usize {133		<string as AbiType>::size() + <bytes as AbiType>::size()134	}135}136137impl AbiRead for Property {138	fn abi_read(reader: &mut AbiReader) -> Result<Property> {139		let size = if !Property::is_dynamic() {140			Some(<Property as AbiType>::size())141		} else {142			None143		};144		let mut subresult = reader.subresult(size)?;145		let key = <string>::abi_read(&mut subresult)?;146		let value = <bytes>::abi_read(&mut subresult)?;147148		Ok(Property { key, value })149	}150}151152impl AbiWrite for Property {153	fn abi_write(&self, writer: &mut AbiWriter) {154		(&self.key, &self.value).abi_write(writer);155	}156}157158macro_rules! impl_abi_writeable {159	($ty:ty, $method:ident) => {160		impl AbiWrite for $ty {161			fn abi_write(&self, writer: &mut AbiWriter) {162				writer.$method(&self)163			}164		}165	};166}167168impl_abi_writeable!(u8, uint8);169impl_abi_writeable!(u32, uint32);170impl_abi_writeable!(u128, uint128);171impl_abi_writeable!(U256, uint256);172impl_abi_writeable!(H160, address);173impl_abi_writeable!(bool, bool);174impl_abi_writeable!(&str, string);175176impl AbiWrite for string {177	fn abi_write(&self, writer: &mut AbiWriter) {178		writer.string(self)179	}180}181182impl AbiWrite for bytes {183	fn abi_write(&self, writer: &mut AbiWriter) {184		writer.bytes(self.0.as_slice())185	}186}187188impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {189	fn abi_write(&self, writer: &mut AbiWriter) {190		let is_dynamic = T::is_dynamic();191		let mut sub = if is_dynamic {192			AbiWriter::new_dynamic(is_dynamic)193		} else {194			AbiWriter::new()195		};196197		// Write items count198		(self.len() as u32).abi_write(&mut sub);199200		for item in self {201			item.abi_write(&mut sub);202		}203		writer.write_subresult(sub);204	}205}206207impl AbiWrite for () {208	fn abi_write(&self, _writer: &mut AbiWriter) {}209}210211/// This particular AbiWrite implementation should be split to another trait,212/// which only implements `to_result`, but due to lack of specialization feature213/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,214/// so here we abusing default trait methods for it215impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {216	fn abi_write(&self, _writer: &mut AbiWriter) {217		debug_assert!(false, "shouldn't be called, see comment")218	}219	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {220		match self {221			Ok(v) => Ok(WithPostDispatchInfo {222				post_info: v.post_info.clone(),223				data: {224					let mut out = AbiWriter::new();225					v.data.abi_write(&mut out);226					out227				},228			}),229			Err(e) => Err(e.clone()),230		}231	}232}233234macro_rules! impl_tuples {235	($($ident:ident)+) => {236		impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)237		where238        $(239            $ident: AbiType,240        )+241		{242            const SIGNATURE: SignatureUnit = make_signature!(243                new fixed("(")244                $(nameof(<$ident>::SIGNATURE) fixed(","))+245                shift_left(1)246                fixed(")")247            );248249			fn is_dynamic() -> bool {250				false251				$(252					|| <$ident>::is_dynamic()253				)*254			}255256			fn size() -> usize {257				0 $(+ <$ident>::size())+258			}259		}260261		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}262263		impl<$($ident),+> AbiRead for ($($ident,)+)264		where265			Self: AbiType,266			$($ident: AbiRead + AbiType,)+267		{268			fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {269				let is_dynamic = <Self>::is_dynamic();270				let size = if !is_dynamic { Some(<Self>::size()) } else { None };271				let mut subresult = reader.subresult(size)?;272				Ok((273					$({274						let value = <$ident>::abi_read(&mut subresult)?;275						if !is_dynamic {subresult.seek(<$ident as AbiType>::size())};276						value277					},)+278				))279			}280		}281282		#[allow(non_snake_case)]283		impl<$($ident),+> AbiWrite for ($($ident,)+)284		where285			$($ident: AbiWrite + AbiType,)+286		{287			fn abi_write(&self, writer: &mut AbiWriter) {288				let ($($ident,)+) = self;289				if <Self as AbiType>::is_dynamic() {290					let mut sub = AbiWriter::new();291					$($ident.abi_write(&mut sub);)+292					writer.write_subresult(sub);293				} else {294					$($ident.abi_write(writer);)+295				}296			}297		}298	};299}300301impl_tuples! {A}302impl_tuples! {A B}303impl_tuples! {A B C}304impl_tuples! {A B C D}305impl_tuples! {A B C D E}306impl_tuples! {A B C D E F}307impl_tuples! {A B C D E F G}308impl_tuples! {A B C D E F G H}309impl_tuples! {A B C D E F G H I}310impl_tuples! {A B C D E F G H I J}
after · crates/evm-coder/src/abi/impls.rs
1use crate::{2	execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},3	types::*,4	make_signature,5	custom_signature::SignatureUnit,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)));1920			fn is_dynamic() -> bool {21				$dynamic22			}2324			fn size() -> usize {25				ABI_ALIGNMENT26			}27		}28	};29}3031macro_rules! impl_abi_readable {32	($ty:ty, $method:ident) => {33		impl AbiRead for $ty {34			fn abi_read(reader: &mut AbiReader) -> Result<$ty> {35				reader.$method()36			}37		}38	};39}4041macro_rules! impl_abi_writeable {42	($ty:ty, $method:ident) => {43		impl AbiWrite for $ty {44			fn abi_write(&self, writer: &mut AbiWriter) {45				writer.$method(&self)46			}47		}48	};49}5051macro_rules! impl_abi {52	($ty:ty, $method:ident, $dynamic:literal) => {53		impl_abi_type!($ty, $method, $dynamic);54		impl_abi_readable!($ty, $method);55		impl_abi_writeable!($ty, $method);56	};57}5859impl_abi!(bool, bool, false);60impl_abi!(u8, uint8, false);61impl_abi!(u32, uint32, false);62impl_abi!(u64, uint64, false);63impl_abi!(u128, uint128, false);64impl_abi!(U256, uint256, false);65impl_abi!(H160, address, false);66impl_abi!(string, string, true);6768impl_abi_writeable!(&str, string);6970impl_abi_type!(bytes, bytes, true);7172impl AbiRead for bytes {73	fn abi_read(reader: &mut AbiReader) -> Result<bytes> {74		Ok(bytes(reader.bytes()?))75	}76}7778impl AbiWrite for bytes {79	fn abi_write(&self, writer: &mut AbiWriter) {80		writer.bytes(self.0.as_slice())81	}82}8384impl_abi_type!(bytes4, bytes4, false);85impl AbiRead for bytes4 {86	fn abi_read(reader: &mut AbiReader) -> Result<bytes4> {87		reader.bytes4()88	}89}9091impl<T: AbiType + AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<T> {92	fn abi_read(reader: &mut AbiReader) -> Result<Vec<T>> {93		let mut sub = reader.subresult(None)?;94		let size = sub.uint32()? as usize;95		sub.subresult_offset = sub.offset;96		let is_dynamic = <T as AbiType>::is_dynamic();97		let mut out = Vec::with_capacity(size);98		for _ in 0..size {99			out.push(<T as AbiRead>::abi_read(&mut sub)?);100			if !is_dynamic {101				sub.bytes_read(<T as AbiType>::size());102			};103		}104		Ok(out)105	}106}107108impl<T: AbiType> AbiType for Vec<T> {109	const SIGNATURE: SignatureUnit = make_signature!(new nameof(T::SIGNATURE) fixed("[]"));110111	fn is_dynamic() -> bool {112		true113	}114115	fn size() -> usize {116		ABI_ALIGNMENT117	}118}119120impl sealed::CanBePlacedInVec for Property {}121122impl AbiType for Property {123	const SIGNATURE: SignatureUnit = make_signature!(new fixed("(string,bytes)"));124125	fn is_dynamic() -> bool {126		string::is_dynamic() || bytes::is_dynamic()127	}128129	fn size() -> usize {130		<string as AbiType>::size() + <bytes as AbiType>::size()131	}132}133134impl AbiRead for Property {135	fn abi_read(reader: &mut AbiReader) -> Result<Property> {136		let size = if !Property::is_dynamic() {137			Some(<Property as AbiType>::size())138		} else {139			None140		};141		let mut subresult = reader.subresult(size)?;142		let key = <string>::abi_read(&mut subresult)?;143		let value = <bytes>::abi_read(&mut subresult)?;144145		Ok(Property { key, value })146	}147}148149impl AbiWrite for Property {150	fn abi_write(&self, writer: &mut AbiWriter) {151		(&self.key, &self.value).abi_write(writer);152	}153}154155impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {156	fn abi_write(&self, writer: &mut AbiWriter) {157		let is_dynamic = T::is_dynamic();158		let mut sub = if is_dynamic {159			AbiWriter::new_dynamic(is_dynamic)160		} else {161			AbiWriter::new()162		};163164		// Write items count165		(self.len() as u32).abi_write(&mut sub);166167		for item in self {168			item.abi_write(&mut sub);169		}170		writer.write_subresult(sub);171	}172}173174impl AbiWrite for () {175	fn abi_write(&self, _writer: &mut AbiWriter) {}176}177178/// This particular AbiWrite implementation should be split to another trait,179/// which only implements `to_result`, but due to lack of specialization feature180/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,181/// so here we abusing default trait methods for it182impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {183	fn abi_write(&self, _writer: &mut AbiWriter) {184		debug_assert!(false, "shouldn't be called, see comment")185	}186	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {187		match self {188			Ok(v) => Ok(WithPostDispatchInfo {189				post_info: v.post_info.clone(),190				data: {191					let mut out = AbiWriter::new();192					v.data.abi_write(&mut out);193					out194				},195			}),196			Err(e) => Err(e.clone()),197		}198	}199}200201macro_rules! impl_tuples {202	($($ident:ident)+) => {203		impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)204		where205        $(206            $ident: AbiType,207        )+208		{209            const SIGNATURE: SignatureUnit = make_signature!(210                new fixed("(")211                $(nameof(<$ident>::SIGNATURE) fixed(","))+212                shift_left(1)213                fixed(")")214            );215216			fn is_dynamic() -> bool {217				false218				$(219					|| <$ident>::is_dynamic()220				)*221			}222223			fn size() -> usize {224				0 $(+ <$ident>::size())+225			}226		}227228		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}229230		impl<$($ident),+> AbiRead for ($($ident,)+)231		where232			Self: AbiType,233			$($ident: AbiRead + AbiType,)+234		{235			fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {236				let is_dynamic = <Self>::is_dynamic();237				let size = if !is_dynamic { Some(<Self>::size()) } else { None };238				let mut subresult = reader.subresult(size)?;239				Ok((240					$({241						let value = <$ident>::abi_read(&mut subresult)?;242						if !is_dynamic {subresult.bytes_read(<$ident as AbiType>::size())};243						value244					},)+245				))246			}247		}248249		#[allow(non_snake_case)]250		impl<$($ident),+> AbiWrite for ($($ident,)+)251		where252			$($ident: AbiWrite + AbiType,)+253		{254			fn abi_write(&self, writer: &mut AbiWriter) {255				let ($($ident,)+) = self;256				if <Self as AbiType>::is_dynamic() {257					let mut sub = AbiWriter::new();258					$($ident.abi_write(&mut sub);)+259					writer.write_subresult(sub);260				} else {261					$($ident.abi_write(writer);)+262				}263			}264		}265	};266}267268impl_tuples! {A}269impl_tuples! {A B}270impl_tuples! {A B C}271impl_tuples! {A B C D}272impl_tuples! {A B C D E}273impl_tuples! {A B C D E F}274impl_tuples! {A B C D E F G}275impl_tuples! {A B C D E F G H}276impl_tuples! {A B C D E F G H I}277impl_tuples! {A B C D E F G H I J}
modifiedcrates/evm-coder/src/abi/mod.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi/mod.rs
+++ b/crates/evm-coder/src/abi/mod.rs
@@ -208,7 +208,7 @@
 	}
 
 	/// Notify about readed data portion.
-	pub fn seek(&mut self, size: usize) {
+	pub fn bytes_read(&mut self, size: usize) {
 		self.subresult_offset += size;
 	}
 
@@ -281,6 +281,11 @@
 		self.write_padleft(&u32::to_be_bytes(*value))
 	}
 
+	/// Write [`u64`] to end of buffer
+	pub fn uint64(&mut self, value: &u64) {
+		self.write_padleft(&u64::to_be_bytes(*value))
+	}
+
 	/// Write [`u128`] to end of buffer
 	pub fn uint128(&mut self, value: &u128) {
 		self.write_padleft(&u128::to_be_bytes(*value))
modifiedcrates/evm-coder/src/abi/test.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi/test.rs
+++ b/crates/evm-coder/src/abi/test.rs
@@ -48,11 +48,44 @@
 }
 
 #[test]
+fn encode_decode_uint64() {
+	test_impl_uint!(uint64);
+}
+
+#[test]
 fn encode_decode_uint128() {
 	test_impl_uint!(uint128);
 }
 
 #[test]
+fn encode_decode_bool_true() {
+	test_impl::<bool>(
+		0xdeadbeef,
+		true,
+		&hex!(
+			"
+                deadbeef
+                0000000000000000000000000000000000000000000000000000000000000001
+            "
+		),
+	);
+}
+
+#[test]
+fn encode_decode_bool_false() {
+	test_impl::<bool>(
+		0xdeadbeef,
+		false,
+		&hex!(
+			"
+                deadbeef
+                0000000000000000000000000000000000000000000000000000000000000000
+            "
+		),
+	);
+}
+
+#[test]
 fn encode_decode_uint256() {
 	test_impl::<uint256>(
 		0xdeadbeef,