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

difftreelog

refactor move evm-coder impl to its own crate

Yaroslav Bolyukin2021-06-02parent: #0a660b9.patch.diff
in: master

6 files changed

addedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "evm-coder"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+evm-coder-macros = { path = "../evm-coder-macros" }
+primitive-types = { version = "0.9", default-features = false }
+hex-literal = "0.3"
+ethereum = { version = "0.7.1", default-features = false }
+
+[dev-dependencies]
+hex = "0.4.3"
+
+[features]
+default = ["std"]
+std = ["ethereum/std", "primitive-types/std"]
\ No newline at end of file
addedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
after · crates/evm-coder/src/abi.rs
1//! TODO: I misunterstood therminology, abi IS rlp encoded, so2//! this module should be replaced with rlp crate34#![allow(dead_code)]56#[cfg(not(feature = "std"))]7use alloc::{8	string::{String, ToString},9	vec::Vec,10};11use primitive_types::{H160, U256};1213use crate::types::string;1415const ABI_ALIGNMENT: usize = 32;1617pub type Result<T> = core::result::Result<T, &'static str>;1819#[derive(Clone)]20pub struct AbiReader<'i> {21	buf: &'i [u8],22	offset: usize,23}24impl<'i> AbiReader<'i> {25	pub fn new(buf: &'i [u8]) -> Self {26		Self { buf, offset: 0 }27	}28	pub fn new_call(buf: &'i [u8]) -> Result<(u32, Self)> {29		if buf.len() < 4 {30			return Err("missing method id");31		}32		let mut method_id = [0; 4];33		method_id.copy_from_slice(&buf[0..4]);3435		Ok((u32::from_be_bytes(method_id), Self { buf, offset: 4 }))36	}3738	fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {39		if self.buf.len() - self.offset < 32 {40			return Err("missing padding");41		}42		let mut block = [0; S];43		// Verify padding is empty44		if !self.buf[self.offset..self.offset + ABI_ALIGNMENT - S]45			.iter()46			.all(|&v| v == 0)47		{48			return Err("non zero padding (wrong types?)");49		}50		block.copy_from_slice(51			&self.buf[self.offset + ABI_ALIGNMENT - S..self.offset + ABI_ALIGNMENT],52		);53		self.offset += ABI_ALIGNMENT;54		Ok(block)55	}5657	pub fn address(&mut self) -> Result<H160> {58		Ok(H160(self.read_padleft()?))59	}6061	pub fn bool(&mut self) -> Result<bool> {62		let data: [u8; 1] = self.read_padleft()?;63		match data[0] {64			0 => Ok(false),65			1 => Ok(true),66			_ => Err("wrong bool value"),67		}68	}6970	pub fn bytes4(&mut self) -> Result<[u8; 4]> {71		self.read_padleft()72	}7374	pub fn bytes(&mut self) -> Result<Vec<u8>> {75		let mut subresult = self.subresult()?;76		let length = subresult.read_usize()?;77		if subresult.buf.len() <= subresult.offset + length {78			return Err("bytes out of bounds");79		}80		Ok(subresult.buf[subresult.offset..subresult.offset + length].into())81	}8283	pub fn uint32(&mut self) -> Result<u32> {84		Ok(u32::from_be_bytes(self.read_padleft()?))85	}8687	pub fn uint128(&mut self) -> Result<u128> {88		Ok(u128::from_be_bytes(self.read_padleft()?))89	}9091	pub fn uint256(&mut self) -> Result<U256> {92		let buf: [u8; 32] = self.read_padleft()?;93		Ok(U256::from_big_endian(&buf))94	}9596	pub fn uint64(&mut self) -> Result<u64> {97		Ok(u64::from_be_bytes(self.read_padleft()?))98	}99100	pub fn read_usize(&mut self) -> Result<usize> {101		Ok(usize::from_be_bytes(self.read_padleft()?))102	}103104	fn subresult(&mut self) -> Result<AbiReader<'i>> {105		let offset = self.read_usize()?;106		Ok(AbiReader {107			buf: &self.buf,108			offset: offset + self.offset,109		})110	}111112	pub fn is_finished(&self) -> bool {113		self.buf.len() == self.offset114	}115}116117#[derive(Default)]118pub struct AbiWriter {119	static_part: Vec<u8>,120	dynamic_part: Vec<(usize, AbiWriter)>,121}122impl AbiWriter {123	pub fn new() -> Self {124		Self::default()125	}126	pub fn new_call(method_id: u32) -> Self {127		let mut val = Self::new();128		val.static_part.extend(&method_id.to_be_bytes());129		val130	}131132	fn write_padleft(&mut self, block: &[u8]) {133		assert!(block.len() <= ABI_ALIGNMENT);134		self.static_part135			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);136		self.static_part.extend(block);137	}138139	fn write_padright(&mut self, bytes: &[u8]) {140		assert!(bytes.len() <= ABI_ALIGNMENT);141		self.static_part.extend(bytes);142		self.static_part143			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);144	}145146	pub fn address(&mut self, address: &H160) {147		self.write_padleft(&address.0)148	}149150	pub fn bool(&mut self, value: &bool) {151		self.write_padleft(&[if *value { 1 } else { 0 }])152	}153154	pub fn uint8(&mut self, value: &u8) {155		self.write_padleft(&[*value])156	}157158	pub fn uint32(&mut self, value: &u32) {159		self.write_padleft(&u32::to_be_bytes(*value))160	}161162	pub fn uint128(&mut self, value: &u128) {163		self.write_padleft(&u128::to_be_bytes(*value))164	}165166	/// This method writes u128, and exists only for convenience, because there is167	/// no u256 support in rust168	pub fn uint256(&mut self, value: &U256) {169		let mut out = [0; 32];170		value.to_big_endian(&mut out);171		self.write_padleft(&out)172	}173174	pub fn write_usize(&mut self, value: &usize) {175		self.write_padleft(&usize::to_be_bytes(*value))176	}177178	pub fn write_subresult(&mut self, result: Self) {179		self.dynamic_part.push((self.static_part.len(), result));180		// Empty block, to be filled later181		self.write_padleft(&[]);182	}183184	pub fn memory(&mut self, value: &[u8]) {185		let mut sub = Self::new();186		sub.write_usize(&value.len());187		for chunk in value.chunks(ABI_ALIGNMENT) {188			sub.write_padright(chunk);189		}190		self.write_subresult(sub);191	}192193	pub fn string(&mut self, value: &str) {194		self.memory(value.as_bytes())195	}196197	pub fn finish(mut self) -> Vec<u8> {198		for (static_offset, part) in self.dynamic_part {199			let part_offset = self.static_part.len();200201			let encoded_dynamic_offset = usize::to_be_bytes(part_offset - static_offset);202			self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()203				..static_offset + ABI_ALIGNMENT]204				.copy_from_slice(&encoded_dynamic_offset);205			self.static_part.extend(part.finish())206		}207		self.static_part208	}209}210211pub trait AbiRead<T> {212	fn abi_read(&mut self) -> Result<T>;213}214215macro_rules! impl_abi_readable {216	($ty:ty, $method:ident) => {217		impl AbiRead<$ty> for AbiReader<'_> {218			fn abi_read(&mut self) -> Result<$ty> {219				self.$method()220			}221		}222	};223}224225impl_abi_readable!(u32, uint32);226impl_abi_readable!(u128, uint128);227impl_abi_readable!(U256, uint256);228impl_abi_readable!(H160, address);229impl_abi_readable!(Vec<u8>, bytes);230impl_abi_readable!(bool, bool);231232pub trait AbiWrite {233	fn abi_write(&self, writer: &mut AbiWriter);234}235236macro_rules! impl_abi_writeable {237	($ty:ty, $method:ident) => {238		impl AbiWrite for $ty {239			fn abi_write(&self, writer: &mut AbiWriter) {240				writer.$method(&self)241			}242		}243	};244}245246impl_abi_writeable!(u8, uint8);247impl_abi_writeable!(u32, uint32);248impl_abi_writeable!(u128, uint128);249impl_abi_writeable!(U256, uint256);250impl_abi_writeable!(H160, address);251impl_abi_writeable!(bool, bool);252impl_abi_writeable!(&str, string);253impl AbiWrite for &string {254	fn abi_write(&self, writer: &mut AbiWriter) {255		writer.string(&self)256	}257}258259impl AbiWrite for () {260	fn abi_write(&self, _writer: &mut AbiWriter) {}261}262263/// Error, which can be constructed from any ToString type264/// Encoded to Abi as Error(string)265#[derive(Debug)]266pub struct StringError(String);267268impl<E> From<E> for StringError269where270	E: ToString,271{272	fn from(e: E) -> Self {273		Self(e.to_string())274	}275}276277impl From<StringError> for AbiWriter {278	fn from(v: StringError) -> Self {279		let mut out = AbiWriter::new_call(crate::fn_selector!(Error(string)));280		out.string(&v.0);281		out282	}283}284285#[macro_export]286macro_rules! abi_decode {287	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {288		$(289			let $name = $reader.$typ()?;290		)+291	}292}293#[macro_export]294macro_rules! abi_encode {295	($($typ:ident($value:expr)),* $(,)?) => {{296		#[allow(unused_mut)]297		let mut writer = ::evm_coder::abi::AbiWriter::new();298		$(299			writer.$typ($value);300		)*301		writer302	}};303	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{304		#[allow(unused_mut)]305		let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);306		$(307			writer.$typ($value);308		)*309		writer310	}}311}
addedcrates/evm-coder/src/events.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/src/events.rs
@@ -0,0 +1,42 @@
+use ethereum::Log;
+use primitive_types::{H160, H256};
+
+use crate::types::*;
+
+pub trait ToLog {
+	fn to_log(&self, contract: H160) -> Log;
+}
+
+pub trait ToTopic {
+	fn to_topic(&self) -> H256;
+}
+
+impl ToTopic for H256 {
+	fn to_topic(&self) -> H256 {
+		*self
+	}
+}
+
+impl ToTopic for uint256 {
+	fn to_topic(&self) -> H256 {
+		let mut out = [0u8; 32];
+		self.to_big_endian(&mut out);
+		H256(out)
+	}
+}
+
+impl ToTopic for address {
+	fn to_topic(&self) -> H256 {
+		let mut out = [0u8; 32];
+		out[12..32].copy_from_slice(&self.0);
+		H256(out)
+	}
+}
+
+impl ToTopic for uint32 {
+	fn to_topic(&self) -> H256 {
+		let mut out = [0u8; 32];
+		out[28..32].copy_from_slice(&self.to_be_bytes());
+		H256(out)
+	}
+}
addedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/src/lib.rs
@@ -0,0 +1,69 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+#[cfg(not(feature = "std"))]
+extern crate alloc;
+
+pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, ToLog};
+pub mod abi;
+pub mod events;
+pub use events::ToLog;
+
+/// Solidity type definitions
+pub mod types {
+	#![allow(non_camel_case_types)]
+
+	#[cfg(not(feature = "std"))]
+	use alloc::{vec::Vec};
+	use primitive_types::{U256, H160, H256};
+
+	pub type address = H160;
+
+	pub type uint8 = u8;
+	pub type uint16 = u16;
+	pub type uint32 = u32;
+	pub type uint64 = u64;
+	pub type uint128 = u128;
+	pub type uint256 = U256;
+
+	pub type bytes4 = u32;
+
+	pub type topic = H256;
+
+	#[cfg(not(feature = "std"))]
+	pub type string = ::alloc::string::String;
+	#[cfg(feature = "std")]
+	pub type string = ::std::string::String;
+	pub type bytes = Vec<u8>;
+
+	pub type void = ();
+
+	//#region Special types
+	/// Makes function payable
+	pub type value = U256;
+	/// Makes function caller-sensitive
+	pub type caller = address;
+	//#endregion
+
+	pub struct Msg<C> {
+		pub call: C,
+		pub caller: H160,
+		pub value: U256,
+	}
+}
+
+#[cfg(test)]
+mod tests {
+	use super::*;
+
+	#[test]
+	fn function_selector_generation() {
+		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
+	}
+
+	#[test]
+	fn event_topic_generation() {
+		assert_eq!(
+			hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),
+			"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
+		);
+	}
+}
addedcrates/evm-coder/tests/a.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/evm-coder/tests/a.rs
@@ -0,0 +1,69 @@
+use evm_coder::{solidity_interface, types::*, ToLog};
+use evm_coder_macros::solidity;
+
+#[solidity_interface]
+trait OurInterface {
+	type Error;
+	fn fn_a(&self, input: uint256) -> Result<bool, Self::Error>;
+}
+
+#[solidity_interface]
+trait OurInterface1 {
+	type Error;
+	fn fn_b(&self, input: uint128) -> Result<uint32, Self::Error>;
+}
+
+#[solidity_interface(is(OurInterface), inline_is(OurInterface1), events(ERC721Log))]
+trait OurInterface2 {
+	type Error;
+	#[solidity(rename_selector = "fnK")]
+	fn fn_c(&self, input: uint32) -> Result<uint8, Self::Error>;
+	fn fn_d(&self, value: uint32) -> Result<uint32, Self::Error>;
+
+	fn caller_sensitive(&self, caller: caller) -> Result<uint8, Self::Error>;
+	fn payable(&mut self, value: value) -> Result<uint8, Self::Error>;
+}
+
+#[derive(ToLog)]
+enum ERC721Log {
+	Transfer {
+		#[indexed]
+		from: address,
+		#[indexed]
+		to: address,
+		value: uint256,
+	},
+	Eee {
+		#[indexed]
+		aaa: address,
+		bbb: uint256,
+	},
+}
+
+#[solidity_interface]
+trait ERC20 {
+	type Error;
+
+	fn decimals(&self) -> Result<uint8, Self::Error>;
+	fn balance_of(&self, owner: address) -> Result<uint256, Self::Error>;
+	fn transfer(
+		&mut self,
+		caller: caller,
+		to: address,
+		value: uint256,
+	) -> Result<bool, Self::Error>;
+	fn transfer_from(
+		&mut self,
+		caller: caller,
+		from: address,
+		to: address,
+		value: uint256,
+	) -> Result<bool, Self::Error>;
+	fn approve(
+		&mut self,
+		caller: caller,
+		spender: address,
+		value: uint256,
+	) -> Result<bool, Self::Error>;
+	fn allowance(&self, owner: address, spender: address) -> Result<uint256, Self::Error>;
+}
deletedpallets/nft/src/eth/abi.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/abi.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-//! TODO: I misunterstood therminology, abi IS rlp encoded, so
-//! this module should be replaced with rlp crate
-
-use sp_core::H160;
-
-#[cfg(feature = "std")]
-use std;
-#[cfg(not(feature = "std"))]
-use sp_std as std;
-
-use std::vec::Vec;
-
-const ABI_ALIGNMENT: usize = 32;
-
-type Result<T> = std::result::Result<T, &'static str>;
-
-pub struct AbiReader<'i> {
-	buf: &'i [u8],
-	offset: usize,
-}
-impl<'i> AbiReader<'i> {
-	pub fn new_call(buf: &'i [u8]) -> Result<(u32, Self)> {
-		if buf.len() < 4 {
-			return Err("missing method id")
-		}
-		let mut method_id = [0; 4];
-		method_id.copy_from_slice(&buf[0..4]);
-
-		Ok((u32::from_be_bytes(method_id), Self {
-			buf,
-			offset: 4,
-		}))
-	}
-
-	fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {
-		if self.buf.len() - self.offset < 32 {
-			return Err("missing padding")
-		}
-		let mut block = [0; S];
-		// Verify padding is empty
-		if !self.buf[self.offset..self.offset + ABI_ALIGNMENT - S].iter().all(|&v| v == 0) {
-			return Err("non zero padding (wrong types?)")
-		}
-		block.copy_from_slice(&self.buf[self.offset + ABI_ALIGNMENT - S..self.offset + ABI_ALIGNMENT]);
-		self.offset += ABI_ALIGNMENT;
-		Ok(block)
-	}
-
-	pub fn address(&mut self) -> Result<H160> {
-		Ok(H160(self.read_padleft()?))
-	}
-
-	pub fn uint32(&mut self) -> Result<u32> {
-		Ok(u32::from_be_bytes(self.read_padleft()?))
-	}
-
-	pub fn uint128(&mut self) -> Result<u128> {
-		Ok(u128::from_be_bytes(self.read_padleft()?))
-	}
-
-	pub fn uint256(&mut self) -> Result<u128> {
-		self.uint128()
-	}
-
-	pub fn uint64(&mut self) -> Result<usize> {
-		Ok(usize::from_be_bytes(self.read_padleft()?))
-	}
-	
-	fn subresult(&mut self) -> Result<AbiReader<'i>> {
-		let offset = self.uint64()?;
-		if offset > usize::MAX {
-			return Err("subresult overflow");
-		}
-		Ok(AbiReader {
-			buf: &self.buf,
-			offset: offset + self.offset,
-		})
-	}
-
-	pub fn is_finished(&self) -> bool {
-		self.buf.len() == self.offset
-	}
-}
-
-pub struct AbiWriter {
-	static_part: Vec<u8>,
-	dynamic_part: Vec<(usize, AbiWriter)>,
-}
-impl AbiWriter {
-	pub fn new() -> Self {
-		Self {
-			static_part: Vec::new(),
-			dynamic_part: Vec::new(),
-		}
-	}
-	pub fn new_call(method_id: u32) -> Self {
-		let mut val = Self::new();
-		val.static_part.extend(&method_id.to_be_bytes());
-		val
-	}
-
-	fn write_padleft(&mut self, block: &[u8]) {
-		assert!(block.len() <= ABI_ALIGNMENT);
-		self.static_part.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
-		self.static_part.extend(block);
-	}
-
-	fn write_padright(&mut self, bytes: &[u8]) {
-		assert!(bytes.len() <= ABI_ALIGNMENT);
-		self.static_part.extend(bytes);
-		self.static_part.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);
-	}
-
-	pub fn address(&mut self, address: H160) {
-		self.write_padleft(&address.0)	
-	}
-
-	pub fn bool(&mut self, value: bool) {
-		self.write_padleft(&[if value { 1 } else { 0 }])
-	}
-
-	pub fn uint8(&mut self, value: u8) {
-		self.write_padleft(&[value])
-	}
-
-	pub fn uint128(&mut self, value: u128) {
-		self.write_padleft(&u128::to_be_bytes(value))
-	}
-	
-	/// This method writes u128, and exists only for convenience, because there is
-	/// no u256 support in rust
-	pub fn uint256(&mut self, value: u128) {
-		self.uint128(value)
-	}
-
-	pub fn write_usize(&mut self, value: usize) {
-		self.write_padleft(&usize::to_be_bytes(value))
-	}
-
-	pub fn write_u8(&mut self, value: u8) {
-		self.write_padleft(&[value])
-	}
-
-	pub fn write_subresult(&mut self, result: Self) {
-		self.dynamic_part.push((self.static_part.len(), result));
-		// Empty block, to be filled later
-		self.write_padleft(&[]);
-	}
-
-	pub fn memory(&mut self, value: &[u8]) {
-		let mut sub = Self::new();
-		sub.write_usize(value.len());
-		for chunk in value.chunks(ABI_ALIGNMENT) {
-			sub.write_padright(chunk);
-		}
-		self.write_subresult(sub);
-	}
-
-	pub fn string(&mut self, value: &str) {
-		self.memory(value.as_bytes())
-	}
-
-	pub fn finish(mut self) -> Vec<u8> {
-		for (static_offset, part) in self.dynamic_part {
-			let part_offset = self.static_part.len();
-
-			let encoded_dynamic_offset = usize::to_be_bytes(part_offset - static_offset);
-			self.static_part
-				[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()..static_offset + ABI_ALIGNMENT]
-				.copy_from_slice(&encoded_dynamic_offset);
-			self.static_part.extend(part.finish())
-		}
-		self.static_part
-	}
-}
-
-#[macro_export]
-macro_rules! abi_decode {
-	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {
-		$(
-			let $name = $reader.$typ()?;
-		)+
-	}
-}
-
-#[macro_export]
-macro_rules! abi_encode {
-	($($typ:ident($value:expr)),* $(,)?) => {{
-		#[allow(unused_mut)]
-		let mut writer = crate::eth::abi::AbiWriter::new();
-		$(
-			writer.$typ($value);
-		)*
-		writer
-	}};
-	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{
-		#[allow(unused_mut)]
-		let mut writer = AbiWriter::new_call($val);
-		$(
-			writer.$typ($value);
-		)*
-		writer
-	}}
-}
\ No newline at end of file