difftreelog
refactor abi module
in: master
17 files changed
crates/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
@@ -328,14 +328,14 @@
}
}
-trait AbiType {
+trait AbiTypeHelper {
fn plain(&self) -> syn::Result<&Ident>;
fn is_value(&self) -> bool;
fn is_caller(&self) -> bool;
fn is_special(&self) -> bool;
}
-impl AbiType for Type {
+impl AbiTypeHelper for Type {
fn plain(&self) -> syn::Result<&Ident> {
let path = parse_path(self)?;
let segment = parse_path_segment(path)?;
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ /dev/null
@@ -1,968 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-//! Implementation of EVM RLP reader/writer
-
-#![allow(dead_code)]
-
-#[cfg(not(feature = "std"))]
-use alloc::vec::Vec;
-use evm_core::ExitError;
-use primitive_types::{H160, U256};
-
-use crate::{
- execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
- types::*,
- make_signature,
- custom_signature::{SignatureUnit},
-};
-use crate::execution::Result;
-
-const ABI_ALIGNMENT: usize = 32;
-
-trait TypeHelper {
- /// Is type dynamic sized.
- fn is_dynamic() -> bool;
-
- /// Size for type aligned to [`ABI_ALIGNMENT`].
- fn size() -> usize;
-}
-
-/// View into RLP data, which provides method to read typed items from it
-#[derive(Clone)]
-pub struct AbiReader<'i> {
- buf: &'i [u8],
- subresult_offset: usize,
- offset: usize,
-}
-impl<'i> AbiReader<'i> {
- /// Start reading RLP buffer, assuming there is no padding bytes
- pub fn new(buf: &'i [u8]) -> Self {
- Self {
- buf,
- subresult_offset: 0,
- offset: 0,
- }
- }
- /// Start reading RLP buffer, parsing first 4 bytes as selector
- pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {
- if buf.len() < 4 {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- let mut method_id = [0; 4];
- method_id.copy_from_slice(&buf[0..4]);
-
- Ok((
- method_id,
- Self {
- buf,
- subresult_offset: 4,
- offset: 4,
- },
- ))
- }
-
- fn read_pad<const S: usize>(
- buf: &[u8],
- offset: usize,
- pad_start: usize,
- pad_size: usize,
- block_start: usize,
- block_size: usize,
- ) -> Result<[u8; S]> {
- if buf.len() - offset < ABI_ALIGNMENT {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- let mut block = [0; S];
- let is_pad_zeroed = buf[pad_start..pad_size].iter().all(|&v| v == 0);
- if !is_pad_zeroed {
- return Err(Error::Error(ExitError::InvalidRange));
- }
- block.copy_from_slice(&buf[block_start..block_size]);
- Ok(block)
- }
-
- fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {
- let offset = self.offset;
- self.offset += ABI_ALIGNMENT;
- Self::read_pad(
- self.buf,
- offset,
- offset,
- offset + ABI_ALIGNMENT - S,
- offset + ABI_ALIGNMENT - S,
- offset + ABI_ALIGNMENT,
- )
- }
-
- fn read_padright<const S: usize>(&mut self) -> Result<[u8; S]> {
- let offset = self.offset;
- self.offset += ABI_ALIGNMENT;
- Self::read_pad(
- self.buf,
- offset,
- offset + S,
- offset + ABI_ALIGNMENT,
- offset,
- offset + S,
- )
- }
-
- /// Read [`H160`] at current position, then advance
- pub fn address(&mut self) -> Result<H160> {
- Ok(H160(self.read_padleft()?))
- }
-
- /// Read [`bool`] at current position, then advance
- pub fn bool(&mut self) -> Result<bool> {
- let data: [u8; 1] = self.read_padleft()?;
- match data[0] {
- 0 => Ok(false),
- 1 => Ok(true),
- _ => Err(Error::Error(ExitError::InvalidRange)),
- }
- }
-
- /// Read [`[u8; 4]`] at current position, then advance
- pub fn bytes4(&mut self) -> Result<[u8; 4]> {
- self.read_padright()
- }
-
- /// Read [`Vec<u8>`] at current position, then advance
- pub fn bytes(&mut self) -> Result<Vec<u8>> {
- let mut subresult = self.subresult(None)?;
- let length = subresult.uint32()? as usize;
- if subresult.buf.len() < subresult.offset + length {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- Ok(subresult.buf[subresult.offset..subresult.offset + length].into())
- }
-
- /// Read [`string`] at current position, then advance
- pub fn string(&mut self) -> Result<string> {
- string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))
- }
-
- /// Read [`u8`] at current position, then advance
- pub fn uint8(&mut self) -> Result<u8> {
- Ok(self.read_padleft::<1>()?[0])
- }
-
- /// Read [`u32`] at current position, then advance
- pub fn uint32(&mut self) -> Result<u32> {
- Ok(u32::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`u128`] at current position, then advance
- pub fn uint128(&mut self) -> Result<u128> {
- Ok(u128::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`U256`] at current position, then advance
- pub fn uint256(&mut self) -> Result<U256> {
- let buf: [u8; 32] = self.read_padleft()?;
- Ok(U256::from_big_endian(&buf))
- }
-
- /// Read [`u64`] at current position, then advance
- pub fn uint64(&mut self) -> Result<u64> {
- Ok(u64::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`usize`] at current position, then advance
- #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
- pub fn read_usize(&mut self) -> Result<usize> {
- Ok(usize::from_be_bytes(self.read_padleft()?))
- }
-
- /// Slice recursive buffer, advance one word for buffer offset
- /// If `size` is [`None`] then [`Self::offset`] and [`Self::subresult_offset`] evals from [`Self::buf`].
- fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
- let subresult_offset = self.subresult_offset;
- let offset = if let Some(size) = size {
- self.offset += size;
- self.subresult_offset += size;
- 0
- } else {
- self.uint32()? as usize
- };
-
- if offset + self.subresult_offset > self.buf.len() {
- return Err(Error::Error(ExitError::InvalidRange));
- }
-
- let new_offset = offset + subresult_offset;
- Ok(AbiReader {
- buf: self.buf,
- subresult_offset: new_offset,
- offset: new_offset,
- })
- }
-
- /// Is this parser reached end of buffer?
- pub fn is_finished(&self) -> bool {
- self.buf.len() == self.offset
- }
-}
-
-/// Writer for RLP encoded data
-#[derive(Default)]
-pub struct AbiWriter {
- static_part: Vec<u8>,
- dynamic_part: Vec<(usize, AbiWriter)>,
- had_call: bool,
- is_dynamic: bool,
-}
-impl AbiWriter {
- /// Initialize internal buffers for output data, assuming no padding required
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Initialize internal buffers with data size
- pub fn new_dynamic(is_dynamic: bool) -> Self {
- Self {
- is_dynamic,
- ..Default::default()
- }
- }
- /// Initialize internal buffers, inserting method selector at beginning
- pub fn new_call(method_id: u32) -> Self {
- let mut val = Self::new();
- val.static_part.extend(&method_id.to_be_bytes());
- val.had_call = true;
- 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, block: &[u8]) {
- assert!(block.len() <= ABI_ALIGNMENT);
- self.static_part.extend(block);
- self.static_part
- .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
- }
-
- /// Write [`H160`] to end of buffer
- pub fn address(&mut self, address: &H160) {
- self.write_padleft(&address.0)
- }
-
- /// Write [`bool`] to end of buffer
- pub fn bool(&mut self, value: &bool) {
- self.write_padleft(&[if *value { 1 } else { 0 }])
- }
-
- /// Write [`u8`] to end of buffer
- pub fn uint8(&mut self, value: &u8) {
- self.write_padleft(&[*value])
- }
-
- /// Write [`u32`] to end of buffer
- pub fn uint32(&mut self, value: &u32) {
- self.write_padleft(&u32::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))
- }
-
- /// Write [`U256`] to end of buffer
- pub fn uint256(&mut self, value: &U256) {
- let mut out = [0; 32];
- value.to_big_endian(&mut out);
- self.write_padleft(&out)
- }
-
- /// Write [`usize`] to end of buffer
- #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
- pub fn write_usize(&mut self, value: &usize) {
- self.write_padleft(&usize::to_be_bytes(*value))
- }
-
- /// Append recursive data, writing pending offset at end of buffer
- 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(&[]);
- }
-
- fn memory(&mut self, value: &[u8]) {
- let mut sub = Self::new();
- sub.uint32(&(value.len() as u32));
- for chunk in value.chunks(ABI_ALIGNMENT) {
- sub.write_padright(chunk);
- }
- self.write_subresult(sub);
- }
-
- /// Append recursive [`str`] at end of buffer
- pub fn string(&mut self, value: &str) {
- self.memory(value.as_bytes())
- }
-
- /// Append recursive [`[u8]`] at end of buffer
- pub fn bytes(&mut self, value: &[u8]) {
- self.memory(value)
- }
-
- /// Finish writer, concatenating all internal buffers
- pub fn finish(mut self) -> Vec<u8> {
- for (static_offset, part) in self.dynamic_part {
- let part_offset = self.static_part.len()
- - if self.had_call { 4 } else { 0 }
- - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };
-
- let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
- let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();
- let stop = static_offset + ABI_ALIGNMENT;
- self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);
- self.static_part.extend(part.finish())
- }
- self.static_part
- }
-}
-
-/// [`AbiReader`] implements reading of many types.
-pub trait AbiRead {
- /// Read item from current position, advanding decoder
- fn abi_read(reader: &mut AbiReader) -> Result<Self>
- where
- Self: Sized;
-}
-
-macro_rules! impl_abi_readable {
- ($ty:ty, $method:ident, $dynamic:literal) => {
- impl sealed::CanBePlacedInVec for $ty {}
-
- impl TypeHelper for $ty {
- fn is_dynamic() -> bool {
- $dynamic
- }
-
- fn size() -> usize {
- ABI_ALIGNMENT
- }
- }
-
- impl AbiRead for $ty {
- fn abi_read(reader: &mut AbiReader) -> Result<$ty> {
- reader.$method()
- }
- }
- };
-}
-
-impl_abi_readable!(bool, bool, false);
-impl_abi_readable!(uint32, uint32, false);
-impl_abi_readable!(uint64, uint64, false);
-impl_abi_readable!(uint128, uint128, false);
-impl_abi_readable!(uint256, uint256, false);
-impl_abi_readable!(bytes4, bytes4, false);
-impl_abi_readable!(address, address, false);
-impl_abi_readable!(string, string, true);
-
-impl TypeHelper for uint8 {
- fn is_dynamic() -> bool {
- false
- }
- fn size() -> usize {
- ABI_ALIGNMENT
- }
-}
-impl AbiRead for uint8 {
- fn abi_read(reader: &mut AbiReader) -> Result<uint8> {
- reader.uint8()
- }
-}
-
-impl TypeHelper for bytes {
- fn is_dynamic() -> bool {
- true
- }
- fn size() -> usize {
- ABI_ALIGNMENT
- }
-}
-impl AbiRead for bytes {
- fn abi_read(reader: &mut AbiReader) -> Result<bytes> {
- Ok(bytes(reader.bytes()?))
- }
-}
-
-mod sealed {
- /// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead
- pub trait CanBePlacedInVec {}
-}
-
-impl<R: AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {
- fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {
- let mut sub = reader.subresult(None)?;
- let size = sub.uint32()? as usize;
- sub.subresult_offset = sub.offset;
- let mut out = Vec::with_capacity(size);
- for _ in 0..size {
- out.push(<R>::abi_read(&mut sub)?);
- }
- Ok(out)
- }
-}
-
-impl<R: Signature> Signature for Vec<R> {
- const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));
-}
-
-impl sealed::CanBePlacedInVec for EthCrossAccount {}
-
-impl TypeHelper for EthCrossAccount {
- fn is_dynamic() -> bool {
- address::is_dynamic() || uint256::is_dynamic()
- }
-
- fn size() -> usize {
- <address as TypeHelper>::size() + <uint256 as TypeHelper>::size()
- }
-}
-
-impl AbiRead for EthCrossAccount {
- fn abi_read(reader: &mut AbiReader) -> Result<EthCrossAccount> {
- let size = if !EthCrossAccount::is_dynamic() {
- Some(<EthCrossAccount as TypeHelper>::size())
- } else {
- None
- };
- let mut subresult = reader.subresult(size)?;
- let eth = <address>::abi_read(&mut subresult)?;
- let sub = <uint256>::abi_read(&mut subresult)?;
-
- Ok(EthCrossAccount { eth, sub })
- }
-}
-
-impl AbiWrite for EthCrossAccount {
- fn abi_write(&self, writer: &mut AbiWriter) {
- self.eth.abi_write(writer);
- self.sub.abi_write(writer);
- }
-}
-
-macro_rules! impl_tuples {
- ($($ident:ident)+) => {
- impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+)
- where
- $(
- $ident: TypeHelper,
- )+
- {
- fn is_dynamic() -> bool {
- false
- $(
- || <$ident>::is_dynamic()
- )*
- }
-
- fn size() -> usize {
- 0 $(+ <$ident>::size())+
- }
- }
-
- impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
-
- impl<$($ident),+> AbiRead for ($($ident,)+)
- where
- $($ident: AbiRead,)+
- ($($ident,)+): TypeHelper,
- {
- fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {
- let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
- let mut subresult = reader.subresult(size)?;
- Ok((
- $(<$ident>::abi_read(&mut subresult)?,)+
- ))
- }
- }
-
- #[allow(non_snake_case)]
- impl<$($ident),+> AbiWrite for ($($ident,)+)
- where
- $($ident: AbiWrite,)+
- {
- fn abi_write(&self, writer: &mut AbiWriter) {
- let ($($ident,)+) = self;
- if writer.is_dynamic {
- let mut sub = AbiWriter::new();
- $($ident.abi_write(&mut sub);)+
- writer.write_subresult(sub);
- } else {
- $($ident.abi_write(writer);)+
- }
- }
- }
-
- impl<$($ident),+> Signature for ($($ident,)+)
- where
- $($ident: Signature,)+
- {
- const SIGNATURE: SignatureUnit = make_signature!(
- new fixed("(")
- $(nameof(<$ident>::SIGNATURE) fixed(","))+
- shift_left(1)
- fixed(")")
- );
- }
- };
-}
-
-impl_tuples! {A}
-impl_tuples! {A B}
-impl_tuples! {A B C}
-impl_tuples! {A B C D}
-impl_tuples! {A B C D E}
-impl_tuples! {A B C D E F}
-impl_tuples! {A B C D E F G}
-impl_tuples! {A B C D E F G H}
-impl_tuples! {A B C D E F G H I}
-impl_tuples! {A B C D E F G H I J}
-
-/// For questions about inability to provide custom implementations,
-/// see [`AbiRead`]
-pub trait AbiWrite {
- /// Write value to end of specified encoder
- fn abi_write(&self, writer: &mut AbiWriter);
- /// Specialization for [`crate::solidity_interface`] implementation,
- /// see comment in `impl AbiWrite for ResultWithPostInfo`
- fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
- let mut writer = AbiWriter::new();
- self.abi_write(&mut writer);
- Ok(writer.into())
- }
-}
-
-/// This particular AbiWrite implementation should be split to another trait,
-/// which only implements `to_result`, but due to lack of specialization feature
-/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,
-/// so here we abusing default trait methods for it
-impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
- fn abi_write(&self, _writer: &mut AbiWriter) {
- debug_assert!(false, "shouldn't be called, see comment")
- }
- fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
- match self {
- Ok(v) => Ok(WithPostDispatchInfo {
- post_info: v.post_info.clone(),
- data: {
- let mut out = AbiWriter::new();
- v.data.abi_write(&mut out);
- out
- },
- }),
- Err(e) => Err(e.clone()),
- }
- }
-}
-
-macro_rules! impl_abi_writeable {
- ($ty:ty, $method:ident) => {
- impl AbiWrite for $ty {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.$method(&self)
- }
- }
- };
-}
-
-impl_abi_writeable!(u8, uint8);
-impl_abi_writeable!(u32, uint32);
-impl_abi_writeable!(u128, uint128);
-impl_abi_writeable!(U256, uint256);
-impl_abi_writeable!(H160, address);
-impl_abi_writeable!(bool, bool);
-impl_abi_writeable!(&str, string);
-
-impl AbiWrite for string {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.string(self)
- }
-}
-
-impl AbiWrite for bytes {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.bytes(self.0.as_slice())
- }
-}
-
-impl<T: AbiWrite + TypeHelper> AbiWrite for Vec<T> {
- fn abi_write(&self, writer: &mut AbiWriter) {
- let is_dynamic = T::is_dynamic();
- let mut sub = if is_dynamic {
- AbiWriter::new_dynamic(is_dynamic)
- } else {
- AbiWriter::new()
- };
-
- // Write items count
- (self.len() as u32).abi_write(&mut sub);
-
- for item in self {
- item.abi_write(&mut sub);
- }
- writer.write_subresult(sub);
- }
-}
-
-impl AbiWrite for () {
- fn abi_write(&self, _writer: &mut AbiWriter) {}
-}
-
-/// Helper macros to parse reader into variables
-#[deprecated]
-#[macro_export]
-macro_rules! abi_decode {
- ($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {
- $(
- let $name = $reader.$typ()?;
- )+
- }
-}
-
-/// Helper macros to construct RLP-encoded buffer
-#[deprecated]
-#[macro_export]
-macro_rules! abi_encode {
- ($($typ:ident($value:expr)),* $(,)?) => {{
- #[allow(unused_mut)]
- let mut writer = ::evm_coder::abi::AbiWriter::new();
- $(
- writer.$typ($value);
- )*
- writer
- }};
- (call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{
- #[allow(unused_mut)]
- let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);
- $(
- writer.$typ($value);
- )*
- writer
- }}
-}
-
-#[cfg(test)]
-pub mod test {
- use crate::{
- abi::{AbiRead, AbiWrite},
- types::*,
- };
-
- use super::{AbiReader, AbiWriter};
- use hex_literal::hex;
- use primitive_types::{H160, U256};
- use concat_idents::concat_idents;
-
- macro_rules! test_impl {
- ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {
- concat_idents!(test_name = encode_decode_, $name {
- #[test]
- fn test_name() {
- let function_identifier: u32 = $function_identifier;
- let decoded_data = $decoded_data;
- let encoded_data = $encoded_data;
-
- let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
- assert_eq!(call, u32::to_be_bytes(function_identifier));
- let data = <$type>::abi_read(&mut decoder).unwrap();
- assert_eq!(data, decoded_data);
-
- let mut writer = AbiWriter::new_call(function_identifier);
- decoded_data.abi_write(&mut writer);
- let ed = writer.finish();
- similar_asserts::assert_eq!(encoded_data, ed.as_slice());
- }
- });
- };
- }
-
- macro_rules! test_impl_uint {
- ($type:ident) => {
- test_impl!(
- $type,
- $type,
- 0xdeadbeef,
- 255 as $type,
- &hex!(
- "
- deadbeef
- 00000000000000000000000000000000000000000000000000000000000000ff
- "
- )
- );
- };
- }
-
- test_impl_uint!(uint8);
- test_impl_uint!(uint32);
- test_impl_uint!(uint128);
-
- test_impl!(
- uint256,
- uint256,
- 0xdeadbeef,
- U256([255, 0, 0, 0]),
- &hex!(
- "
- deadbeef
- 00000000000000000000000000000000000000000000000000000000000000ff
- "
- )
- );
-
- test_impl!(
- vec_tuple_address_uint256,
- Vec<(address, uint256)>,
- 0x1ACF2D55,
- vec![
- (
- H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
- U256([10, 0, 0, 0]),
- ),
- (
- H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
- U256([20, 0, 0, 0]),
- ),
- (
- H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
- U256([30, 0, 0, 0]),
- ),
- ],
- &hex!(
- "
- 1ACF2D55
- 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
- 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
- 000000000000000000000000000000000000000000000000000000000000000A // uint256
-
- 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
- 0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
- 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
- 000000000000000000000000000000000000000000000000000000000000001E // uint256
- "
- )
- );
-
- test_impl!(
- vec_tuple_uint256_string,
- Vec<(uint256, string)>,
- 0xdeadbeef,
- vec![
- (1.into(), "Test URI 0".to_string()),
- (11.into(), "Test URI 1".to_string()),
- (12.into(), "Test URI 2".to_string()),
- ],
- &hex!(
- "
- deadbeef
- 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
-
- 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
- 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
- 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
-
- 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203000000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203100000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203200000000000000000000000000000000000000000000 // string
- "
- )
- );
-
- test_impl!(
- vec_tuple_string_bytes,
- Vec<(string, bytes)>,
- 0xdeadbeef,
- vec![
- (
- "Test URI 0".to_string(),
- bytes(vec![
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
- ])
- ),
- (
- "Test URI 1".to_string(),
- bytes(vec![
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
- ])
- ),
- ("Test URI 2".to_string(), bytes(vec![0x33, 0x33])),
- ],
- &hex!(
- "
- deadbeef
- 0000000000000000000000000000000000000000000000000000000000000020
- 0000000000000000000000000000000000000000000000000000000000000003
-
- 0000000000000000000000000000000000000000000000000000000000000060
- 0000000000000000000000000000000000000000000000000000000000000140
- 0000000000000000000000000000000000000000000000000000000000000220
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203000000000000000000000000000000000000000000000
- 0000000000000000000000000000000000000000000000000000000000000030
- 1111111111111111111111111111111111111111111111111111111111111111
- 1111111111111111111111111111111100000000000000000000000000000000
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203100000000000000000000000000000000000000000000
- 000000000000000000000000000000000000000000000000000000000000002f
- 2222222222222222222222222222222222222222222222222222222222222222
- 2222222222222222222222222222220000000000000000000000000000000000
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203200000000000000000000000000000000000000000000
- 0000000000000000000000000000000000000000000000000000000000000002
- 3333000000000000000000000000000000000000000000000000000000000000
- "
- )
- );
-
- #[test]
- fn dynamic_after_static() {
- let mut encoder = AbiWriter::new();
- encoder.bool(&true);
- encoder.string("test");
- let encoded = encoder.finish();
-
- let mut encoder = AbiWriter::new();
- encoder.bool(&true);
- // Offset to subresult
- encoder.uint32(&(32 * 2));
- // Len of "test"
- encoder.uint32(&4);
- encoder.write_padright(&[b't', b'e', b's', b't']);
- let alternative_encoded = encoder.finish();
-
- assert_eq!(encoded, alternative_encoded);
-
- let mut decoder = AbiReader::new(&encoded);
- assert!(decoder.bool().unwrap());
- assert_eq!(decoder.string().unwrap(), "test");
- }
-
- #[test]
- fn mint_sample() {
- let (call, mut decoder) = AbiReader::new_call(&hex!(
- "
- 50bb4e7f
- 000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374
- 0000000000000000000000000000000000000000000000000000000000000001
- 0000000000000000000000000000000000000000000000000000000000000060
- 0000000000000000000000000000000000000000000000000000000000000008
- 5465737420555249000000000000000000000000000000000000000000000000
- "
- ))
- .unwrap();
- assert_eq!(call, u32::to_be_bytes(0x50bb4e7f));
- assert_eq!(
- format!("{:?}", decoder.address().unwrap()),
- "0xad2c0954693c2b5404b7e50967d3481bea432374"
- );
- assert_eq!(decoder.uint32().unwrap(), 1);
- assert_eq!(decoder.string().unwrap(), "Test URI");
- }
-
- #[test]
- fn parse_vec_with_dynamic_type() {
- let decoded_data = (
- 0x36543006,
- vec![
- (1.into(), "Test URI 0".to_string()),
- (11.into(), "Test URI 1".to_string()),
- (12.into(), "Test URI 2".to_string()),
- ],
- );
-
- let encoded_data = &hex!(
- "
- 36543006
- 00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
-
- 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
- 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
- 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
-
- 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203000000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203100000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203200000000000000000000000000000000000000000000 // string
- "
- );
-
- let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
- assert_eq!(call, u32::to_be_bytes(decoded_data.0));
- let address = decoder.address().unwrap();
- let data = <Vec<(uint256, string)>>::abi_read(&mut decoder).unwrap();
- assert_eq!(data, decoded_data.1);
-
- let mut writer = AbiWriter::new_call(decoded_data.0);
- address.abi_write(&mut writer);
- decoded_data.1.abi_write(&mut writer);
- let ed = writer.finish();
- similar_asserts::assert_eq!(encoded_data, ed.as_slice());
- }
-}
crates/evm-coder/src/abi/impls.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/impls.rs
@@ -0,0 +1,303 @@
+use crate::{
+ execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},
+ types::*,
+ make_signature,
+ custom_signature::SignatureUnit,
+};
+use super::{traits::*, ABI_ALIGNMENT, AbiReader, AbiWriter};
+use primitive_types::{U256, H160};
+
+#[cfg(not(feature = "std"))]
+use alloc::vec::Vec;
+
+macro_rules! impl_abi_readable {
+ ($ty:ty, $method:ident, $dynamic:literal) => {
+ impl sealed::CanBePlacedInVec for $ty {}
+
+ impl AbiType for $ty {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ty)));
+
+ fn is_dynamic() -> bool {
+ $dynamic
+ }
+
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+ }
+
+ impl AbiRead for $ty {
+ fn abi_read(reader: &mut AbiReader) -> Result<$ty> {
+ reader.$method()
+ }
+ }
+ };
+}
+
+impl_abi_readable!(uint32, uint32, false);
+impl_abi_readable!(uint64, uint64, false);
+impl_abi_readable!(uint128, uint128, false);
+impl_abi_readable!(uint256, uint256, false);
+impl_abi_readable!(bytes4, bytes4, false);
+impl_abi_readable!(address, address, false);
+impl_abi_readable!(string, string, true);
+
+impl sealed::CanBePlacedInVec for bool {}
+
+impl AbiType for bool {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
+
+ fn is_dynamic() -> bool {
+ false
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for bool {
+ fn abi_read(reader: &mut AbiReader) -> Result<bool> {
+ reader.bool()
+ }
+}
+
+impl AbiType for uint8 {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
+
+ fn is_dynamic() -> bool {
+ false
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for uint8 {
+ fn abi_read(reader: &mut AbiReader) -> Result<uint8> {
+ reader.uint8()
+ }
+}
+
+impl AbiType for bytes {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
+
+ fn is_dynamic() -> bool {
+ true
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for bytes {
+ fn abi_read(reader: &mut AbiReader) -> Result<bytes> {
+ Ok(bytes(reader.bytes()?))
+ }
+}
+
+impl<R: AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {
+ fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {
+ let mut sub = reader.subresult(None)?;
+ let size = sub.uint32()? as usize;
+ sub.subresult_offset = sub.offset;
+ let mut out = Vec::with_capacity(size);
+ for _ in 0..size {
+ out.push(<R>::abi_read(&mut sub)?);
+ }
+ Ok(out)
+ }
+}
+
+impl<R: AbiType> AbiType for Vec<R> {
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));
+
+ fn is_dynamic() -> bool {
+ true
+ }
+
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+
+impl sealed::CanBePlacedInVec for EthCrossAccount {}
+
+impl AbiType for EthCrossAccount {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
+
+ fn is_dynamic() -> bool {
+ address::is_dynamic() || uint256::is_dynamic()
+ }
+
+ fn size() -> usize {
+ <address as AbiType>::size() + <uint256 as AbiType>::size()
+ }
+}
+
+impl AbiRead for EthCrossAccount {
+ fn abi_read(reader: &mut AbiReader) -> Result<EthCrossAccount> {
+ let size = if !EthCrossAccount::is_dynamic() {
+ Some(<EthCrossAccount as AbiType>::size())
+ } else {
+ None
+ };
+ let mut subresult = reader.subresult(size)?;
+ let eth = <address>::abi_read(&mut subresult)?;
+ let sub = <uint256>::abi_read(&mut subresult)?;
+
+ Ok(EthCrossAccount { eth, sub })
+ }
+}
+
+impl AbiWrite for EthCrossAccount {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ self.eth.abi_write(writer);
+ self.sub.abi_write(writer);
+ }
+}
+
+macro_rules! impl_abi_writeable {
+ ($ty:ty, $method:ident) => {
+ impl AbiWrite for $ty {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.$method(&self)
+ }
+ }
+ };
+}
+
+impl_abi_writeable!(u8, uint8);
+impl_abi_writeable!(u32, uint32);
+impl_abi_writeable!(u128, uint128);
+impl_abi_writeable!(U256, uint256);
+impl_abi_writeable!(H160, address);
+impl_abi_writeable!(bool, bool);
+impl_abi_writeable!(&str, string);
+
+impl AbiWrite for string {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.string(self)
+ }
+}
+
+impl AbiWrite for bytes {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.bytes(self.0.as_slice())
+ }
+}
+
+impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ let is_dynamic = T::is_dynamic();
+ let mut sub = if is_dynamic {
+ AbiWriter::new_dynamic(is_dynamic)
+ } else {
+ AbiWriter::new()
+ };
+
+ // Write items count
+ (self.len() as u32).abi_write(&mut sub);
+
+ for item in self {
+ item.abi_write(&mut sub);
+ }
+ writer.write_subresult(sub);
+ }
+}
+
+impl AbiWrite for () {
+ fn abi_write(&self, _writer: &mut AbiWriter) {}
+}
+
+/// This particular AbiWrite implementation should be split to another trait,
+/// which only implements `to_result`, but due to lack of specialization feature
+/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,
+/// so here we abusing default trait methods for it
+impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
+ fn abi_write(&self, _writer: &mut AbiWriter) {
+ debug_assert!(false, "shouldn't be called, see comment")
+ }
+ fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ match self {
+ Ok(v) => Ok(WithPostDispatchInfo {
+ post_info: v.post_info.clone(),
+ data: {
+ let mut out = AbiWriter::new();
+ v.data.abi_write(&mut out);
+ out
+ },
+ }),
+ Err(e) => Err(e.clone()),
+ }
+ }
+}
+
+macro_rules! impl_tuples {
+ ($($ident:ident)+) => {
+ impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)
+ where
+ $(
+ $ident: AbiType,
+ )+
+ {
+ const SIGNATURE: SignatureUnit = make_signature!(
+ new fixed("(")
+ $(nameof(<$ident>::SIGNATURE) fixed(","))+
+ shift_left(1)
+ fixed(")")
+ );
+
+ fn is_dynamic() -> bool {
+ false
+ $(
+ || <$ident>::is_dynamic()
+ )*
+ }
+
+ fn size() -> usize {
+ 0 $(+ <$ident>::size())+
+ }
+ }
+
+ impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
+
+ impl<$($ident),+> AbiRead for ($($ident,)+)
+ where
+ $($ident: AbiRead,)+
+ ($($ident,)+): AbiType,
+ {
+ fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {
+ let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
+ let mut subresult = reader.subresult(size)?;
+ Ok((
+ $(<$ident>::abi_read(&mut subresult)?,)+
+ ))
+ }
+ }
+
+ #[allow(non_snake_case)]
+ impl<$($ident),+> AbiWrite for ($($ident,)+)
+ where
+ $($ident: AbiWrite,)+
+ {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ let ($($ident,)+) = self;
+ if writer.is_dynamic {
+ let mut sub = AbiWriter::new();
+ $($ident.abi_write(&mut sub);)+
+ writer.write_subresult(sub);
+ } else {
+ $($ident.abi_write(writer);)+
+ }
+ }
+ }
+ };
+}
+
+impl_tuples! {A}
+impl_tuples! {A B}
+impl_tuples! {A B C}
+impl_tuples! {A B C D}
+impl_tuples! {A B C D E}
+impl_tuples! {A B C D E F}
+impl_tuples! {A B C D E F G}
+impl_tuples! {A B C D E F G H}
+impl_tuples! {A B C D E F G H I}
+impl_tuples! {A B C D E F G H I J}
crates/evm-coder/src/abi/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/mod.rs
@@ -0,0 +1,339 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+//! Implementation of EVM RLP reader/writer
+
+#![allow(dead_code)]
+
+mod traits;
+pub use traits::*;
+mod impls;
+
+#[cfg(test)]
+mod test;
+
+#[cfg(not(feature = "std"))]
+use alloc::vec::Vec;
+use evm_core::ExitError;
+use primitive_types::{H160, U256};
+
+use crate::{
+ execution::{Result, Error},
+ types::*,
+};
+
+const ABI_ALIGNMENT: usize = 32;
+
+/// View into RLP data, which provides method to read typed items from it
+#[derive(Clone)]
+pub struct AbiReader<'i> {
+ buf: &'i [u8],
+ subresult_offset: usize,
+ offset: usize,
+}
+impl<'i> AbiReader<'i> {
+ /// Start reading RLP buffer, assuming there is no padding bytes
+ pub fn new(buf: &'i [u8]) -> Self {
+ Self {
+ buf,
+ subresult_offset: 0,
+ offset: 0,
+ }
+ }
+ /// Start reading RLP buffer, parsing first 4 bytes as selector
+ pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {
+ if buf.len() < 4 {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ let mut method_id = [0; 4];
+ method_id.copy_from_slice(&buf[0..4]);
+
+ Ok((
+ method_id,
+ Self {
+ buf,
+ subresult_offset: 4,
+ offset: 4,
+ },
+ ))
+ }
+
+ fn read_pad<const S: usize>(
+ buf: &[u8],
+ offset: usize,
+ pad_start: usize,
+ pad_size: usize,
+ block_start: usize,
+ block_size: usize,
+ ) -> Result<[u8; S]> {
+ if buf.len() - offset < ABI_ALIGNMENT {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ let mut block = [0; S];
+ let is_pad_zeroed = buf[pad_start..pad_size].iter().all(|&v| v == 0);
+ if !is_pad_zeroed {
+ return Err(Error::Error(ExitError::InvalidRange));
+ }
+ block.copy_from_slice(&buf[block_start..block_size]);
+ Ok(block)
+ }
+
+ fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {
+ let offset = self.offset;
+ self.offset += ABI_ALIGNMENT;
+ Self::read_pad(
+ self.buf,
+ offset,
+ offset,
+ offset + ABI_ALIGNMENT - S,
+ offset + ABI_ALIGNMENT - S,
+ offset + ABI_ALIGNMENT,
+ )
+ }
+
+ fn read_padright<const S: usize>(&mut self) -> Result<[u8; S]> {
+ let offset = self.offset;
+ self.offset += ABI_ALIGNMENT;
+ Self::read_pad(
+ self.buf,
+ offset,
+ offset + S,
+ offset + ABI_ALIGNMENT,
+ offset,
+ offset + S,
+ )
+ }
+
+ /// Read [`H160`] at current position, then advance
+ pub fn address(&mut self) -> Result<H160> {
+ Ok(H160(self.read_padleft()?))
+ }
+
+ /// Read [`bool`] at current position, then advance
+ pub fn bool(&mut self) -> Result<bool> {
+ let data: [u8; 1] = self.read_padleft()?;
+ match data[0] {
+ 0 => Ok(false),
+ 1 => Ok(true),
+ _ => Err(Error::Error(ExitError::InvalidRange)),
+ }
+ }
+
+ /// Read [`[u8; 4]`] at current position, then advance
+ pub fn bytes4(&mut self) -> Result<[u8; 4]> {
+ self.read_padright()
+ }
+
+ /// Read [`Vec<u8>`] at current position, then advance
+ pub fn bytes(&mut self) -> Result<Vec<u8>> {
+ let mut subresult = self.subresult(None)?;
+ let length = subresult.uint32()? as usize;
+ if subresult.buf.len() < subresult.offset + length {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ Ok(subresult.buf[subresult.offset..subresult.offset + length].into())
+ }
+
+ /// Read [`string`] at current position, then advance
+ pub fn string(&mut self) -> Result<string> {
+ string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))
+ }
+
+ /// Read [`u8`] at current position, then advance
+ pub fn uint8(&mut self) -> Result<u8> {
+ Ok(self.read_padleft::<1>()?[0])
+ }
+
+ /// Read [`u32`] at current position, then advance
+ pub fn uint32(&mut self) -> Result<u32> {
+ Ok(u32::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`u128`] at current position, then advance
+ pub fn uint128(&mut self) -> Result<u128> {
+ Ok(u128::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`U256`] at current position, then advance
+ pub fn uint256(&mut self) -> Result<U256> {
+ let buf: [u8; 32] = self.read_padleft()?;
+ Ok(U256::from_big_endian(&buf))
+ }
+
+ /// Read [`u64`] at current position, then advance
+ pub fn uint64(&mut self) -> Result<u64> {
+ Ok(u64::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`usize`] at current position, then advance
+ #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
+ pub fn read_usize(&mut self) -> Result<usize> {
+ Ok(usize::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Slice recursive buffer, advance one word for buffer offset
+ /// If `size` is [`None`] then [`Self::offset`] and [`Self::subresult_offset`] evals from [`Self::buf`].
+ fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
+ let subresult_offset = self.subresult_offset;
+ let offset = if let Some(size) = size {
+ self.offset += size;
+ self.subresult_offset += size;
+ 0
+ } else {
+ self.uint32()? as usize
+ };
+
+ if offset + self.subresult_offset > self.buf.len() {
+ return Err(Error::Error(ExitError::InvalidRange));
+ }
+
+ let new_offset = offset + subresult_offset;
+ Ok(AbiReader {
+ buf: self.buf,
+ subresult_offset: new_offset,
+ offset: new_offset,
+ })
+ }
+
+ /// Is this parser reached end of buffer?
+ pub fn is_finished(&self) -> bool {
+ self.buf.len() == self.offset
+ }
+}
+
+/// Writer for RLP encoded data
+#[derive(Default)]
+pub struct AbiWriter {
+ static_part: Vec<u8>,
+ dynamic_part: Vec<(usize, AbiWriter)>,
+ had_call: bool,
+ is_dynamic: bool,
+}
+impl AbiWriter {
+ /// Initialize internal buffers for output data, assuming no padding required
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Initialize internal buffers with data size
+ pub fn new_dynamic(is_dynamic: bool) -> Self {
+ Self {
+ is_dynamic,
+ ..Default::default()
+ }
+ }
+ /// Initialize internal buffers, inserting method selector at beginning
+ pub fn new_call(method_id: u32) -> Self {
+ let mut val = Self::new();
+ val.static_part.extend(&method_id.to_be_bytes());
+ val.had_call = true;
+ 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, block: &[u8]) {
+ assert!(block.len() <= ABI_ALIGNMENT);
+ self.static_part.extend(block);
+ self.static_part
+ .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
+ }
+
+ /// Write [`H160`] to end of buffer
+ pub fn address(&mut self, address: &H160) {
+ self.write_padleft(&address.0)
+ }
+
+ /// Write [`bool`] to end of buffer
+ pub fn bool(&mut self, value: &bool) {
+ self.write_padleft(&[if *value { 1 } else { 0 }])
+ }
+
+ /// Write [`u8`] to end of buffer
+ pub fn uint8(&mut self, value: &u8) {
+ self.write_padleft(&[*value])
+ }
+
+ /// Write [`u32`] to end of buffer
+ pub fn uint32(&mut self, value: &u32) {
+ self.write_padleft(&u32::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))
+ }
+
+ /// Write [`U256`] to end of buffer
+ pub fn uint256(&mut self, value: &U256) {
+ let mut out = [0; 32];
+ value.to_big_endian(&mut out);
+ self.write_padleft(&out)
+ }
+
+ /// Write [`usize`] to end of buffer
+ #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
+ pub fn write_usize(&mut self, value: &usize) {
+ self.write_padleft(&usize::to_be_bytes(*value))
+ }
+
+ /// Append recursive data, writing pending offset at end of buffer
+ 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(&[]);
+ }
+
+ fn memory(&mut self, value: &[u8]) {
+ let mut sub = Self::new();
+ sub.uint32(&(value.len() as u32));
+ for chunk in value.chunks(ABI_ALIGNMENT) {
+ sub.write_padright(chunk);
+ }
+ self.write_subresult(sub);
+ }
+
+ /// Append recursive [`str`] at end of buffer
+ pub fn string(&mut self, value: &str) {
+ self.memory(value.as_bytes())
+ }
+
+ /// Append recursive [`[u8]`] at end of buffer
+ pub fn bytes(&mut self, value: &[u8]) {
+ self.memory(value)
+ }
+
+ /// Finish writer, concatenating all internal buffers
+ pub fn finish(mut self) -> Vec<u8> {
+ for (static_offset, part) in self.dynamic_part {
+ let part_offset = self.static_part.len()
+ - if self.had_call { 4 } else { 0 }
+ - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };
+
+ let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
+ let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();
+ let stop = static_offset + ABI_ALIGNMENT;
+ self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);
+ self.static_part.extend(part.finish())
+ }
+ self.static_part
+ }
+}
crates/evm-coder/src/abi/test.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/test.rs
@@ -0,0 +1,297 @@
+use crate::{
+ abi::{AbiRead, AbiWrite},
+ types::*,
+};
+
+use super::{AbiReader, AbiWriter};
+use hex_literal::hex;
+use primitive_types::{H160, U256};
+use concat_idents::concat_idents;
+
+macro_rules! test_impl {
+ ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {
+ concat_idents!(test_name = encode_decode_, $name {
+ #[test]
+ fn test_name() {
+ let function_identifier: u32 = $function_identifier;
+ let decoded_data = $decoded_data;
+ let encoded_data = $encoded_data;
+
+ let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
+ assert_eq!(call, u32::to_be_bytes(function_identifier));
+ let data = <$type>::abi_read(&mut decoder).unwrap();
+ assert_eq!(data, decoded_data);
+
+ let mut writer = AbiWriter::new_call(function_identifier);
+ decoded_data.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
+ }
+ });
+ };
+}
+
+macro_rules! test_impl_uint {
+ ($type:ident) => {
+ test_impl!(
+ $type,
+ $type,
+ 0xdeadbeef,
+ 255 as $type,
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+ );
+ };
+}
+
+test_impl_uint!(uint8);
+test_impl_uint!(uint32);
+test_impl_uint!(uint128);
+
+test_impl!(
+ uint256,
+ uint256,
+ 0xdeadbeef,
+ U256([255, 0, 0, 0]),
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+);
+
+test_impl!(
+ vec_tuple_address_uint256,
+ Vec<(address, uint256)>,
+ 0x1ACF2D55,
+ vec![
+ (
+ H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
+ U256([10, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
+ U256([20, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
+ U256([30, 0, 0, 0]),
+ ),
+ ],
+ &hex!(
+ "
+ 1ACF2D55
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
+
+ 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
+ 000000000000000000000000000000000000000000000000000000000000000A // uint256
+
+ 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
+ 0000000000000000000000000000000000000000000000000000000000000014 // uint256
+
+ 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
+ 000000000000000000000000000000000000000000000000000000000000001E // uint256
+ "
+ )
+);
+
+test_impl!(
+ vec_tuple_uint256_string,
+ Vec<(uint256, string)>,
+ 0xdeadbeef,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
+
+ 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
+ 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
+ 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
+
+ 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203000000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203100000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203200000000000000000000000000000000000000000000 // string
+ "
+ )
+);
+
+#[test]
+fn dynamic_after_static() {
+ let mut encoder = AbiWriter::new();
+ encoder.bool(&true);
+ encoder.string("test");
+ let encoded = encoder.finish();
+
+ let mut encoder = AbiWriter::new();
+ encoder.bool(&true);
+ // Offset to subresult
+ encoder.uint32(&(32 * 2));
+ // Len of "test"
+ encoder.uint32(&4);
+ encoder.write_padright(&[b't', b'e', b's', b't']);
+ let alternative_encoded = encoder.finish();
+
+ assert_eq!(encoded, alternative_encoded);
+
+ let mut decoder = AbiReader::new(&encoded);
+ assert!(decoder.bool().unwrap());
+ assert_eq!(decoder.string().unwrap(), "test");
+}
+
+#[test]
+fn mint_sample() {
+ let (call, mut decoder) = AbiReader::new_call(&hex!(
+ "
+ 50bb4e7f
+ 000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374
+ 0000000000000000000000000000000000000000000000000000000000000001
+ 0000000000000000000000000000000000000000000000000000000000000060
+ 0000000000000000000000000000000000000000000000000000000000000008
+ 5465737420555249000000000000000000000000000000000000000000000000
+ "
+ ))
+ .unwrap();
+ assert_eq!(call, u32::to_be_bytes(0x50bb4e7f));
+ assert_eq!(
+ format!("{:?}", decoder.address().unwrap()),
+ "0xad2c0954693c2b5404b7e50967d3481bea432374"
+ );
+ assert_eq!(decoder.uint32().unwrap(), 1);
+ assert_eq!(decoder.string().unwrap(), "Test URI");
+}
+
+#[test]
+fn parse_vec_with_dynamic_type() {
+ let decoded_data = (
+ 0x36543006,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ );
+
+ let encoded_data = &hex!(
+ "
+ 36543006
+ 00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
+
+ 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
+ 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
+ 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
+
+ 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203000000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203100000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203200000000000000000000000000000000000000000000 // string
+ "
+ );
+
+ let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
+ assert_eq!(call, u32::to_be_bytes(decoded_data.0));
+ let address = decoder.address().unwrap();
+ let data = <Vec<(uint256, string)>>::abi_read(&mut decoder).unwrap();
+ assert_eq!(data, decoded_data.1);
+
+ let mut writer = AbiWriter::new_call(decoded_data.0);
+ address.abi_write(&mut writer);
+ decoded_data.1.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
+}
+
+test_impl!(
+ vec_tuple_string_bytes,
+ Vec<(string, bytes)>,
+ 0xdeadbeef,
+ vec![
+ (
+ "Test URI 0".to_string(),
+ bytes(vec![
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
+ ])
+ ),
+ (
+ "Test URI 1".to_string(),
+ bytes(vec![
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22
+ ])
+ ),
+ ("Test URI 2".to_string(), bytes(vec![0x33, 0x33])),
+ ],
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020
+ 0000000000000000000000000000000000000000000000000000000000000003
+
+ 0000000000000000000000000000000000000000000000000000000000000060
+ 0000000000000000000000000000000000000000000000000000000000000140
+ 0000000000000000000000000000000000000000000000000000000000000220
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203000000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000030
+ 1111111111111111111111111111111111111111111111111111111111111111
+ 1111111111111111111111111111111100000000000000000000000000000000
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203100000000000000000000000000000000000000000000
+ 000000000000000000000000000000000000000000000000000000000000002f
+ 2222222222222222222222222222222222222222222222222222222222222222
+ 2222222222222222222222222222220000000000000000000000000000000000
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203200000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000002
+ 3333000000000000000000000000000000000000000000000000000000000000
+ "
+ )
+);
crates/evm-coder/src/abi/traits.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/traits.rs
@@ -0,0 +1,51 @@
+use super::{AbiReader, AbiWriter};
+use crate::{
+ custom_signature::*,
+ execution::{Result, ResultWithPostInfo},
+};
+use core::str::from_utf8;
+
+/// Helper for type.
+pub trait AbiType {
+ /// Signature for Etherium ABI.
+ const SIGNATURE: SignatureUnit;
+
+ /// Signature as str.
+ fn as_str() -> &'static str {
+ from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+ }
+
+ /// Is type dynamic sized.
+ fn is_dynamic() -> bool;
+
+ /// Size for type aligned to [`ABI_ALIGNMENT`].
+ fn size() -> usize;
+}
+
+/// Sealed traits.
+pub mod sealed {
+ /// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead
+ pub trait CanBePlacedInVec {}
+}
+
+/// [`AbiReader`] implements reading of many types.
+pub trait AbiRead {
+ /// Read item from current position, advanding decoder
+ fn abi_read(reader: &mut AbiReader) -> Result<Self>
+ where
+ Self: Sized;
+}
+
+/// For questions about inability to provide custom implementations,
+/// see [`AbiRead`]
+pub trait AbiWrite {
+ /// Write value to end of specified encoder
+ fn abi_write(&self, writer: &mut AbiWriter);
+ /// Specialization for [`crate::solidity_interface`] implementation,
+ /// see comment in `impl AbiWrite for ResultWithPostInfo`
+ fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ let mut writer = AbiWriter::new();
+ self.abi_write(&mut writer);
+ Ok(writer.into())
+ }
+}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -121,53 +121,24 @@
use alloc::{vec::Vec};
use pallet_evm::account::CrossAccountId;
use primitive_types::{U256, H160, H256};
- use core::str::from_utf8;
-
- use crate::custom_signature::SignatureUnit;
-
- pub trait Signature {
- const SIGNATURE: SignatureUnit;
-
- fn as_str() -> &'static str {
- from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
- }
- }
-
- impl Signature for bool {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
- }
-
- macro_rules! define_simple_type {
- (type $ident:ident = $ty:ty) => {
- pub type $ident = $ty;
- impl Signature for $ty {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
- }
- };
- }
- define_simple_type!(type address = H160);
-
- define_simple_type!(type uint8 = u8);
- define_simple_type!(type uint16 = u16);
- define_simple_type!(type uint32 = u32);
- define_simple_type!(type uint64 = u64);
- define_simple_type!(type uint128 = u128);
- define_simple_type!(type uint256 = U256);
- define_simple_type!(type bytes4 = [u8; 4]);
-
- define_simple_type!(type topic = 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 = [u8; 4];
+ pub type topic = H256;
#[cfg(not(feature = "std"))]
- define_simple_type!(type string = ::alloc::string::String);
+ pub type string = ::alloc::string::String;
#[cfg(feature = "std")]
- define_simple_type!(type string = ::std::string::String);
+ pub type string = ::std::string::String;
#[derive(Default, Debug, PartialEq)]
pub struct bytes(pub Vec<u8>);
- impl Signature for bytes {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
- }
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
@@ -257,10 +228,6 @@
Err("All fields of cross account is non zeroed".into())
}
}
- }
-
- impl Signature for EthCrossAccount {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -16,8 +16,9 @@
#![allow(dead_code)] // This test only checks that macros is not panicking
-use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
-use evm_coder::{types::Signature};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::Result, solidity_interface, types::*, solidity, weight,
+};
pub struct Impls;
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -14,8 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
-use evm_coder::{types::Signature};
+use evm_coder::{abi::AbiType, execution::Result, generate_stubgen, solidity_interface, types::*};
pub struct ERC20;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -17,6 +17,7 @@
//! This module contains the implementation of pallet methods for evm.
use evm_coder::{
+ abi::AbiType,
solidity_interface, solidity, ToLog,
types::*,
execution::{Result, Error},
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,7 +19,11 @@
extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
+ abi::{AbiWriter, AbiType},
+ execution::Result,
+ generate_stubgen, solidity_interface,
+ types::*,
+ ToLog,
};
use pallet_evm::{
ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,7 +19,9 @@
extern crate alloc;
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight,
+};
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
use sp_std::vec::Vec;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -24,7 +24,10 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,
+ weight,
+};
use frame_support::BoundedVec;
use up_data_structs::{
TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,
pallets/refungible/src/erc.rsdiffbeforeafterboth1// 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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions,32 erc::{CommonEvmHandler, CollectionCall, static_property::key},33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::{call, dispatch_to_evm};36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};37use sp_core::H160;38use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};39use up_data_structs::{40 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,41 PropertyKeyPermission, PropertyPermission, TokenId,42};4344use crate::{45 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,46 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,47};4849pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5051/// @title A contract that allows to set and delete token properties and change token property permissions.52#[solidity_interface(name = TokenProperties)]53impl<T: Config> RefungibleHandle<T> {54 /// @notice Set permissions for token property.55 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.56 /// @param key Property key.57 /// @param isMutable Permission to mutate property.58 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.59 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.60 fn set_token_property_permission(61 &mut self,62 caller: caller,63 key: string,64 is_mutable: bool,65 collection_admin: bool,66 token_owner: bool,67 ) -> Result<()> {68 let caller = T::CrossAccountId::from_eth(caller);69 <Pallet<T>>::set_token_property_permissions(70 self,71 &caller,72 vec![PropertyKeyPermission {73 key: <Vec<u8>>::from(key)74 .try_into()75 .map_err(|_| "too long key")?,76 permission: PropertyPermission {77 mutable: is_mutable,78 collection_admin,79 token_owner,80 },81 }],82 )83 .map_err(dispatch_to_evm::<T>)84 }8586 /// @notice Set token property value.87 /// @dev Throws error if `msg.sender` has no permission to edit the property.88 /// @param tokenId ID of the token.89 /// @param key Property key.90 /// @param value Property value.91 fn set_property(92 &mut self,93 caller: caller,94 token_id: uint256,95 key: string,96 value: bytes,97 ) -> Result<()> {98 let caller = T::CrossAccountId::from_eth(caller);99 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;100 let key = <Vec<u8>>::from(key)101 .try_into()102 .map_err(|_| "key too long")?;103 let value = value.0.try_into().map_err(|_| "value too long")?;104105 let nesting_budget = self106 .recorder107 .weight_calls_budget(<StructureWeight<T>>::find_parent());108109 <Pallet<T>>::set_token_property(110 self,111 &caller,112 TokenId(token_id),113 Property { key, value },114 &nesting_budget,115 )116 .map_err(dispatch_to_evm::<T>)117 }118119 /// @notice Set token properties value.120 /// @dev Throws error if `msg.sender` has no permission to edit the property.121 /// @param tokenId ID of the token.122 /// @param properties settable properties123 fn set_properties(124 &mut self,125 caller: caller,126 token_id: uint256,127 properties: Vec<(string, bytes)>,128 ) -> Result<()> {129 let caller = T::CrossAccountId::from_eth(caller);130 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;131132 let nesting_budget = self133 .recorder134 .weight_calls_budget(<StructureWeight<T>>::find_parent());135136 let properties = properties137 .into_iter()138 .map(|(key, value)| {139 let key = <Vec<u8>>::from(key)140 .try_into()141 .map_err(|_| "key too large")?;142143 let value = value.0.try_into().map_err(|_| "value too large")?;144145 Ok(Property { key, value })146 })147 .collect::<Result<Vec<_>>>()?;148149 <Pallet<T>>::set_token_properties(150 self,151 &caller,152 TokenId(token_id),153 properties.into_iter(),154 <Pallet<T>>::token_exists(&self, TokenId(token_id)),155 &nesting_budget,156 )157 .map_err(dispatch_to_evm::<T>)158 }159160 /// @notice Delete token property value.161 /// @dev Throws error if `msg.sender` has no permission to edit the property.162 /// @param tokenId ID of the token.163 /// @param key Property key.164 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {165 let caller = T::CrossAccountId::from_eth(caller);166 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;167 let key = <Vec<u8>>::from(key)168 .try_into()169 .map_err(|_| "key too long")?;170171 let nesting_budget = self172 .recorder173 .weight_calls_budget(<StructureWeight<T>>::find_parent());174175 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)176 .map_err(dispatch_to_evm::<T>)177 }178179 /// @notice Get token property value.180 /// @dev Throws error if key not found181 /// @param tokenId ID of the token.182 /// @param key Property key.183 /// @return Property value bytes184 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {185 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;186 let key = <Vec<u8>>::from(key)187 .try_into()188 .map_err(|_| "key too long")?;189190 let props = <TokenProperties<T>>::get((self.id, token_id));191 let prop = props.get(&key).ok_or("key not found")?;192193 Ok(prop.to_vec().into())194 }195}196197#[derive(ToLog)]198pub enum ERC721Events {199 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed200 /// (`to` == 0). Exception: during contract creation, any number of RFTs201 /// may be created and assigned without emitting Transfer.202 Transfer {203 #[indexed]204 from: address,205 #[indexed]206 to: address,207 #[indexed]208 token_id: uint256,209 },210 /// @dev Not supported211 Approval {212 #[indexed]213 owner: address,214 #[indexed]215 approved: address,216 #[indexed]217 token_id: uint256,218 },219 /// @dev Not supported220 #[allow(dead_code)]221 ApprovalForAll {222 #[indexed]223 owner: address,224 #[indexed]225 operator: address,226 approved: bool,227 },228}229230#[derive(ToLog)]231pub enum ERC721UniqueMintableEvents {232 /// @dev Not supported233 #[allow(dead_code)]234 MintingFinished {},235}236237#[solidity_interface(name = ERC721Metadata)]238impl<T: Config> RefungibleHandle<T>239where240 T::AccountId: From<[u8; 32]>,241{242 /// @notice A descriptive name for a collection of NFTs in this contract243 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`244 #[solidity(hide, rename_selector = "name")]245 fn name_proxy(&self) -> Result<string> {246 self.name()247 }248249 /// @notice An abbreviated name for NFTs in this contract250 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`251 #[solidity(hide, rename_selector = "symbol")]252 fn symbol_proxy(&self) -> Result<string> {253 self.symbol()254 }255256 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.257 ///258 /// @dev If the token has a `url` property and it is not empty, it is returned.259 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.260 /// If the collection property `baseURI` is empty or absent, return "" (empty string)261 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix262 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).263 ///264 /// @return token's const_metadata265 #[solidity(rename_selector = "tokenURI")]266 fn token_uri(&self, token_id: uint256) -> Result<string> {267 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;268269 match get_token_property(self, token_id_u32, &key::url()).as_deref() {270 Err(_) | Ok("") => (),271 Ok(url) => {272 return Ok(url.into());273 }274 };275276 let base_uri =277 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())278 .map(BoundedVec::into_inner)279 .map(string::from_utf8)280 .transpose()281 .map_err(|e| {282 Error::Revert(alloc::format!(283 "Can not convert value \"baseURI\" to string with error \"{}\"",284 e285 ))286 })?;287288 let base_uri = match base_uri.as_deref() {289 None | Some("") => {290 return Ok("".into());291 }292 Some(base_uri) => base_uri.into(),293 };294295 Ok(296 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {297 Err(_) | Ok("") => base_uri,298 Ok(suffix) => base_uri + suffix,299 },300 )301 }302}303304/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension305/// @dev See https://eips.ethereum.org/EIPS/eip-721306#[solidity_interface(name = ERC721Enumerable)]307impl<T: Config> RefungibleHandle<T> {308 /// @notice Enumerate valid RFTs309 /// @param index A counter less than `totalSupply()`310 /// @return The token identifier for the `index`th NFT,311 /// (sort order not specified)312 fn token_by_index(&self, index: uint256) -> Result<uint256> {313 Ok(index)314 }315316 /// Not implemented317 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {318 // TODO: Not implemetable319 Err("not implemented".into())320 }321322 /// @notice Count RFTs tracked by this contract323 /// @return A count of valid RFTs tracked by this contract, where each one of324 /// them has an assigned and queryable owner not equal to the zero address325 fn total_supply(&self) -> Result<uint256> {326 self.consume_store_reads(1)?;327 Ok(<Pallet<T>>::total_supply(self).into())328 }329}330331/// @title ERC-721 Non-Fungible Token Standard332/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md333#[solidity_interface(name = ERC721, events(ERC721Events))]334impl<T: Config> RefungibleHandle<T> {335 /// @notice Count all RFTs assigned to an owner336 /// @dev RFTs assigned to the zero address are considered invalid, and this337 /// function throws for queries about the zero address.338 /// @param owner An address for whom to query the balance339 /// @return The number of RFTs owned by `owner`, possibly zero340 fn balance_of(&self, owner: address) -> Result<uint256> {341 self.consume_store_reads(1)?;342 let owner = T::CrossAccountId::from_eth(owner);343 let balance = <AccountBalance<T>>::get((self.id, owner));344 Ok(balance.into())345 }346347 /// @notice Find the owner of an RFT348 /// @dev RFTs assigned to zero address are considered invalid, and queries349 /// about them do throw.350 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for351 /// the tokens that are partially owned.352 /// @param tokenId The identifier for an RFT353 /// @return The address of the owner of the RFT354 fn owner_of(&self, token_id: uint256) -> Result<address> {355 self.consume_store_reads(2)?;356 let token = token_id.try_into()?;357 let owner = <Pallet<T>>::token_owner(self.id, token);358 Ok(owner359 .map(|address| *address.as_eth())360 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))361 }362363 /// @dev Not implemented364 fn safe_transfer_from_with_data(365 &mut self,366 _from: address,367 _to: address,368 _token_id: uint256,369 _data: bytes,370 ) -> Result<void> {371 // TODO: Not implemetable372 Err("not implemented".into())373 }374375 /// @dev Not implemented376 fn safe_transfer_from(377 &mut self,378 _from: address,379 _to: address,380 _token_id: uint256,381 ) -> Result<void> {382 // TODO: Not implemetable383 Err("not implemented".into())384 }385386 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE387 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE388 /// THEY MAY BE PERMANENTLY LOST389 /// @dev Throws unless `msg.sender` is the current owner or an authorized390 /// operator for this RFT. Throws if `from` is not the current owner. Throws391 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.392 /// Throws if RFT pieces have multiple owners.393 /// @param from The current owner of the NFT394 /// @param to The new owner395 /// @param tokenId The NFT to transfer396 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]397 fn transfer_from(398 &mut self,399 caller: caller,400 from: address,401 to: address,402 token_id: uint256,403 ) -> Result<void> {404 let caller = T::CrossAccountId::from_eth(caller);405 let from = T::CrossAccountId::from_eth(from);406 let to = T::CrossAccountId::from_eth(to);407 let token = token_id.try_into()?;408 let budget = self409 .recorder410 .weight_calls_budget(<StructureWeight<T>>::find_parent());411412 let balance = balance(&self, token, &from)?;413 ensure_single_owner(&self, token, balance)?;414415 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)416 .map_err(dispatch_to_evm::<T>)?;417418 Ok(())419 }420421 /// @dev Not implemented422 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {423 Err("not implemented".into())424 }425426 /// @dev Not implemented427 fn set_approval_for_all(428 &mut self,429 _caller: caller,430 _operator: address,431 _approved: bool,432 ) -> Result<void> {433 // TODO: Not implemetable434 Err("not implemented".into())435 }436437 /// @dev Not implemented438 fn get_approved(&self, _token_id: uint256) -> Result<address> {439 // TODO: Not implemetable440 Err("not implemented".into())441 }442443 /// @dev Not implemented444 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {445 // TODO: Not implemetable446 Err("not implemented".into())447 }448}449450/// Returns amount of pieces of `token` that `owner` have451pub fn balance<T: Config>(452 collection: &RefungibleHandle<T>,453 token: TokenId,454 owner: &T::CrossAccountId,455) -> Result<u128> {456 collection.consume_store_reads(1)?;457 let balance = <Balance<T>>::get((collection.id, token, &owner));458 Ok(balance)459}460461/// Throws if `owner_balance` is lower than total amount of `token` pieces462pub fn ensure_single_owner<T: Config>(463 collection: &RefungibleHandle<T>,464 token: TokenId,465 owner_balance: u128,466) -> Result<()> {467 collection.consume_store_reads(1)?;468 let total_supply = <TotalSupply<T>>::get((collection.id, token));469 if total_supply != owner_balance {470 return Err("token has multiple owners".into());471 }472 Ok(())473}474475/// @title ERC721 Token that can be irreversibly burned (destroyed).476#[solidity_interface(name = ERC721Burnable)]477impl<T: Config> RefungibleHandle<T> {478 /// @notice Burns a specific ERC721 token.479 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized480 /// operator of the current owner.481 /// @param tokenId The RFT to approve482 #[weight(<SelfWeightOf<T>>::burn_item_fully())]483 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {484 let caller = T::CrossAccountId::from_eth(caller);485 let token = token_id.try_into()?;486487 let balance = balance(&self, token, &caller)?;488 ensure_single_owner(&self, token, balance)?;489490 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;491 Ok(())492 }493}494495/// @title ERC721 minting logic.496#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]497impl<T: Config> RefungibleHandle<T> {498 fn minting_finished(&self) -> Result<bool> {499 Ok(false)500 }501502 /// @notice Function to mint token.503 /// @param to The new owner504 /// @return uint256 The id of the newly minted token505 #[weight(<SelfWeightOf<T>>::create_item())]506 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {507 let token_id: uint256 = <TokensMinted<T>>::get(self.id)508 .checked_add(1)509 .ok_or("item id overflow")?510 .into();511 self.mint_check_id(caller, to, token_id)?;512 Ok(token_id)513 }514515 /// @notice Function to mint token.516 /// @dev `tokenId` should be obtained with `nextTokenId` method,517 /// unlike standard, you can't specify it manually518 /// @param to The new owner519 /// @param tokenId ID of the minted RFT520 #[solidity(hide, rename_selector = "mint")]521 #[weight(<SelfWeightOf<T>>::create_item())]522 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {523 let caller = T::CrossAccountId::from_eth(caller);524 let to = T::CrossAccountId::from_eth(to);525 let token_id: u32 = token_id.try_into()?;526 let budget = self527 .recorder528 .weight_calls_budget(<StructureWeight<T>>::find_parent());529530 if <TokensMinted<T>>::get(self.id)531 .checked_add(1)532 .ok_or("item id overflow")?533 != token_id534 {535 return Err("item id should be next".into());536 }537538 let users = [(to.clone(), 1)]539 .into_iter()540 .collect::<BTreeMap<_, _>>()541 .try_into()542 .unwrap();543 <Pallet<T>>::create_item(544 self,545 &caller,546 CreateItemData::<T::CrossAccountId> {547 users,548 properties: CollectionPropertiesVec::default(),549 },550 &budget,551 )552 .map_err(dispatch_to_evm::<T>)?;553554 Ok(true)555 }556557 /// @notice Function to mint token with the given tokenUri.558 /// @param to The new owner559 /// @param tokenUri Token URI that would be stored in the NFT properties560 /// @return uint256 The id of the newly minted token561 #[solidity(rename_selector = "mintWithTokenURI")]562 #[weight(<SelfWeightOf<T>>::create_item())]563 fn mint_with_token_uri(564 &mut self,565 caller: caller,566 to: address,567 token_uri: string,568 ) -> Result<uint256> {569 let token_id: uint256 = <TokensMinted<T>>::get(self.id)570 .checked_add(1)571 .ok_or("item id overflow")?572 .into();573 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;574 Ok(token_id)575 }576577 /// @notice Function to mint token with the given tokenUri.578 /// @dev `tokenId` should be obtained with `nextTokenId` method,579 /// unlike standard, you can't specify it manually580 /// @param to The new owner581 /// @param tokenId ID of the minted RFT582 /// @param tokenUri Token URI that would be stored in the RFT properties583 #[solidity(hide, rename_selector = "mintWithTokenURI")]584 #[weight(<SelfWeightOf<T>>::create_item())]585 fn mint_with_token_uri_check_id(586 &mut self,587 caller: caller,588 to: address,589 token_id: uint256,590 token_uri: string,591 ) -> Result<bool> {592 let key = key::url();593 let permission = get_token_permission::<T>(self.id, &key)?;594 if !permission.collection_admin {595 return Err("Operation is not allowed".into());596 }597598 let caller = T::CrossAccountId::from_eth(caller);599 let to = T::CrossAccountId::from_eth(to);600 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;601 let budget = self602 .recorder603 .weight_calls_budget(<StructureWeight<T>>::find_parent());604605 if <TokensMinted<T>>::get(self.id)606 .checked_add(1)607 .ok_or("item id overflow")?608 != token_id609 {610 return Err("item id should be next".into());611 }612613 let mut properties = CollectionPropertiesVec::default();614 properties615 .try_push(Property {616 key,617 value: token_uri618 .into_bytes()619 .try_into()620 .map_err(|_| "token uri is too long")?,621 })622 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;623624 let users = [(to.clone(), 1)]625 .into_iter()626 .collect::<BTreeMap<_, _>>()627 .try_into()628 .unwrap();629 <Pallet<T>>::create_item(630 self,631 &caller,632 CreateItemData::<T::CrossAccountId> { users, properties },633 &budget,634 )635 .map_err(dispatch_to_evm::<T>)?;636 Ok(true)637 }638639 /// @dev Not implemented640 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {641 Err("not implementable".into())642 }643}644645fn get_token_property<T: Config>(646 collection: &CollectionHandle<T>,647 token_id: u32,648 key: &up_data_structs::PropertyKey,649) -> Result<string> {650 collection.consume_store_reads(1)?;651 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))652 .map_err(|_| Error::Revert("Token properties not found".into()))?;653 if let Some(property) = properties.get(key) {654 return Ok(string::from_utf8_lossy(property).into());655 }656657 Err("Property tokenURI not found".into())658}659660fn get_token_permission<T: Config>(661 collection_id: CollectionId,662 key: &PropertyKey,663) -> Result<PropertyPermission> {664 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)665 .map_err(|_| Error::Revert("No permissions for collection".into()))?;666 let a = token_property_permissions667 .get(key)668 .map(Clone::clone)669 .ok_or_else(|| {670 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();671 Error::Revert(alloc::format!("No permission for key {}", key))672 })?;673 Ok(a)674}675676/// @title Unique extensions for ERC721.677#[solidity_interface(name = ERC721UniqueExtensions)]678impl<T: Config> RefungibleHandle<T>679where680 T::AccountId: From<[u8; 32]>,681{682 /// @notice A descriptive name for a collection of NFTs in this contract683 fn name(&self) -> Result<string> {684 Ok(decode_utf16(self.name.iter().copied())685 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))686 .collect::<string>())687 }688689 /// @notice An abbreviated name for NFTs in this contract690 fn symbol(&self) -> Result<string> {691 Ok(string::from_utf8_lossy(&self.token_prefix).into())692 }693694 /// @notice Transfer ownership of an RFT695 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`696 /// is the zero address. Throws if `tokenId` is not a valid RFT.697 /// Throws if RFT pieces have multiple owners.698 /// @param to The new owner699 /// @param tokenId The RFT to transfer700 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]701 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {702 let caller = T::CrossAccountId::from_eth(caller);703 let to = T::CrossAccountId::from_eth(to);704 let token = token_id.try_into()?;705 let budget = self706 .recorder707 .weight_calls_budget(<StructureWeight<T>>::find_parent());708709 let balance = balance(self, token, &caller)?;710 ensure_single_owner(self, token, balance)?;711712 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)713 .map_err(dispatch_to_evm::<T>)?;714 Ok(())715 }716717 /// @notice Transfer ownership of an RFT718 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`719 /// is the zero address. Throws if `tokenId` is not a valid RFT.720 /// Throws if RFT pieces have multiple owners.721 /// @param to The new owner722 /// @param tokenId The RFT to transfer723 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]724 fn transfer_from_cross(725 &mut self,726 caller: caller,727 from: EthCrossAccount,728 to: EthCrossAccount,729 token_id: uint256,730 ) -> Result<void> {731 let caller = T::CrossAccountId::from_eth(caller);732 let from = from.into_sub_cross_account::<T>()?;733 let to = to.into_sub_cross_account::<T>()?;734 let token_id = token_id.try_into()?;735 let budget = self736 .recorder737 .weight_calls_budget(<StructureWeight<T>>::find_parent());738739 let balance = balance(self, token_id, &from)?;740 ensure_single_owner(self, token_id, balance)?;741742 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)743 .map_err(dispatch_to_evm::<T>)?;744 Ok(())745 }746747 /// @notice Burns a specific ERC721 token.748 /// @dev Throws unless `msg.sender` is the current owner or an authorized749 /// operator for this RFT. Throws if `from` is not the current owner. Throws750 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.751 /// Throws if RFT pieces have multiple owners.752 /// @param from The current owner of the RFT753 /// @param tokenId The RFT to transfer754 #[weight(<SelfWeightOf<T>>::burn_from())]755 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {756 let caller = T::CrossAccountId::from_eth(caller);757 let from = T::CrossAccountId::from_eth(from);758 let token = token_id.try_into()?;759 let budget = self760 .recorder761 .weight_calls_budget(<StructureWeight<T>>::find_parent());762763 let balance = balance(self, token, &from)?;764 ensure_single_owner(self, token, balance)?;765766 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)767 .map_err(dispatch_to_evm::<T>)?;768 Ok(())769 }770771 /// @notice Burns a specific ERC721 token.772 /// @dev Throws unless `msg.sender` is the current owner or an authorized773 /// operator for this RFT. Throws if `from` is not the current owner. Throws774 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.775 /// Throws if RFT pieces have multiple owners.776 /// @param from The current owner of the RFT777 /// @param tokenId The RFT to transfer778 #[weight(<SelfWeightOf<T>>::burn_from())]779 fn burn_from_cross(780 &mut self,781 caller: caller,782 from: EthCrossAccount,783 token_id: uint256,784 ) -> Result<void> {785 let caller = T::CrossAccountId::from_eth(caller);786 let from = from.into_sub_cross_account::<T>()?;787 let token = token_id.try_into()?;788 let budget = self789 .recorder790 .weight_calls_budget(<StructureWeight<T>>::find_parent());791792 let balance = balance(self, token, &from)?;793 ensure_single_owner(self, token, balance)?;794795 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)796 .map_err(dispatch_to_evm::<T>)?;797 Ok(())798 }799800 /// @notice Returns next free RFT ID.801 fn next_token_id(&self) -> Result<uint256> {802 self.consume_store_reads(1)?;803 Ok(<TokensMinted<T>>::get(self.id)804 .checked_add(1)805 .ok_or("item id overflow")?806 .into())807 }808809 /// @notice Function to mint multiple tokens.810 /// @dev `tokenIds` should be an array of consecutive numbers and first number811 /// should be obtained with `nextTokenId` method812 /// @param to The new owner813 /// @param tokenIds IDs of the minted RFTs814 #[solidity(hide)]815 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]816 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {817 let caller = T::CrossAccountId::from_eth(caller);818 let to = T::CrossAccountId::from_eth(to);819 let mut expected_index = <TokensMinted<T>>::get(self.id)820 .checked_add(1)821 .ok_or("item id overflow")?;822 let budget = self823 .recorder824 .weight_calls_budget(<StructureWeight<T>>::find_parent());825826 let total_tokens = token_ids.len();827 for id in token_ids.into_iter() {828 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;829 if id != expected_index {830 return Err("item id should be next".into());831 }832 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;833 }834 let users = [(to.clone(), 1)]835 .into_iter()836 .collect::<BTreeMap<_, _>>()837 .try_into()838 .unwrap();839 let create_item_data = CreateItemData::<T::CrossAccountId> {840 users,841 properties: CollectionPropertiesVec::default(),842 };843 let data = (0..total_tokens)844 .map(|_| create_item_data.clone())845 .collect();846847 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)848 .map_err(dispatch_to_evm::<T>)?;849 Ok(true)850 }851852 /// @notice Function to mint multiple tokens with the given tokenUris.853 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive854 /// numbers and first number should be obtained with `nextTokenId` method855 /// @param to The new owner856 /// @param tokens array of pairs of token ID and token URI for minted tokens857 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]858 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]859 fn mint_bulk_with_token_uri(860 &mut self,861 caller: caller,862 to: address,863 tokens: Vec<(uint256, string)>,864 ) -> Result<bool> {865 let key = key::url();866 let caller = T::CrossAccountId::from_eth(caller);867 let to = T::CrossAccountId::from_eth(to);868 let mut expected_index = <TokensMinted<T>>::get(self.id)869 .checked_add(1)870 .ok_or("item id overflow")?;871 let budget = self872 .recorder873 .weight_calls_budget(<StructureWeight<T>>::find_parent());874875 let mut data = Vec::with_capacity(tokens.len());876 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]877 .into_iter()878 .collect::<BTreeMap<_, _>>()879 .try_into()880 .unwrap();881 for (id, token_uri) in tokens {882 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;883 if id != expected_index {884 return Err("item id should be next".into());885 }886 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;887888 let mut properties = CollectionPropertiesVec::default();889 properties890 .try_push(Property {891 key: key.clone(),892 value: token_uri893 .into_bytes()894 .try_into()895 .map_err(|_| "token uri is too long")?,896 })897 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;898899 let create_item_data = CreateItemData::<T::CrossAccountId> {900 users: users.clone(),901 properties,902 };903 data.push(create_item_data);904 }905906 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)907 .map_err(dispatch_to_evm::<T>)?;908 Ok(true)909 }910911 /// Returns EVM address for refungible token912 ///913 /// @param token ID of the token914 fn token_contract_address(&self, token: uint256) -> Result<address> {915 Ok(T::EvmTokenAddressMapping::token_to_address(916 self.id,917 token.try_into().map_err(|_| "token id overflow")?,918 ))919 }920}921922#[solidity_interface(923 name = UniqueRefungible,924 is(925 ERC721,926 ERC721Enumerable,927 ERC721UniqueExtensions,928 ERC721UniqueMintable,929 ERC721Burnable,930 ERC721Metadata(if(this.flags.erc721metadata)),931 Collection(via(common_mut returns CollectionHandle<T>)),932 TokenProperties,933 )934)]935impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}936937// Not a tests, but code generators938generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);939generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);940941impl<T: Config> CommonEvmHandler for RefungibleHandle<T>942where943 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,944{945 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");946 fn call(947 self,948 handle: &mut impl PrecompileHandle,949 ) -> Option<pallet_common::erc::PrecompileResult> {950 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)951 }952}pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,7 +29,9 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight,
+};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -35,6 +35,7 @@
try-runtime = ["frame-support/try-runtime"]
limit-testing = ["up-data-structs/limit-testing"]
stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
+
################################################################################
# Standart Dependencies
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,14 +18,16 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight,
+};
use frame_support::traits::Get;
use crate::Pallet;
use pallet_common::{
CollectionById,
dispatch::CollectionDispatch,
- erc::{static_property::key, CollectionHelpersEvents},
+ erc::{CollectionHelpersEvents, static_property::key},
Pallet as PalletCommon,
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};