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.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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4243use crate::{44 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,45 SelfWeightOf, weights::WeightInfo, TokenProperties,46};4748/// @title A contract that allows to set and delete token properties and change token property permissions.49#[solidity_interface(name = TokenProperties)]50impl<T: Config> NonfungibleHandle<T> {51 /// @notice Set permissions for token property.52 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.53 /// @param key Property key.54 /// @param isMutable Permission to mutate property.55 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.56 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.57 fn set_token_property_permission(58 &mut self,59 caller: caller,60 key: string,61 is_mutable: bool,62 collection_admin: bool,63 token_owner: bool,64 ) -> Result<()> {65 let caller = T::CrossAccountId::from_eth(caller);66 <Pallet<T>>::set_property_permission(67 self,68 &caller,69 PropertyKeyPermission {70 key: <Vec<u8>>::from(key)71 .try_into()72 .map_err(|_| "too long key")?,73 permission: PropertyPermission {74 mutable: is_mutable,75 collection_admin,76 token_owner,77 },78 },79 )80 .map_err(dispatch_to_evm::<T>)81 }8283 /// @notice Set token property value.84 /// @dev Throws error if `msg.sender` has no permission to edit the property.85 /// @param tokenId ID of the token.86 /// @param key Property key.87 /// @param value Property value.88 fn set_property(89 &mut self,90 caller: caller,91 token_id: uint256,92 key: string,93 value: bytes,94 ) -> Result<()> {95 let caller = T::CrossAccountId::from_eth(caller);96 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;97 let key = <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "key too long")?;100 let value = value.0.try_into().map_err(|_| "value too long")?;101102 let nesting_budget = self103 .recorder104 .weight_calls_budget(<StructureWeight<T>>::find_parent());105106 <Pallet<T>>::set_token_property(107 self,108 &caller,109 TokenId(token_id),110 Property { key, value },111 &nesting_budget,112 )113 .map_err(dispatch_to_evm::<T>)114 }115116 /// @notice Set token properties value.117 /// @dev Throws error if `msg.sender` has no permission to edit the property.118 /// @param tokenId ID of the token.119 /// @param properties settable properties120 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]121 fn set_properties(122 &mut self,123 caller: caller,124 token_id: uint256,125 properties: Vec<(string, bytes)>,126 ) -> Result<()> {127 let caller = T::CrossAccountId::from_eth(caller);128 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;129130 let nesting_budget = self131 .recorder132 .weight_calls_budget(<StructureWeight<T>>::find_parent());133134 let properties = properties135 .into_iter()136 .map(|(key, value)| {137 let key = <Vec<u8>>::from(key)138 .try_into()139 .map_err(|_| "key too large")?;140141 let value = value.0.try_into().map_err(|_| "value too large")?;142143 Ok(Property { key, value })144 })145 .collect::<Result<Vec<_>>>()?;146147 <Pallet<T>>::set_token_properties(148 self,149 &caller,150 TokenId(token_id),151 properties.into_iter(),152 <Pallet<T>>::token_exists(&self, TokenId(token_id)),153 &nesting_budget,154 )155 .map_err(dispatch_to_evm::<T>)156 }157158 /// @notice Delete token property value.159 /// @dev Throws error if `msg.sender` has no permission to edit the property.160 /// @param tokenId ID of the token.161 /// @param key Property key.162 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {163 let caller = T::CrossAccountId::from_eth(caller);164 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;165 let key = <Vec<u8>>::from(key)166 .try_into()167 .map_err(|_| "key too long")?;168169 let nesting_budget = self170 .recorder171 .weight_calls_budget(<StructureWeight<T>>::find_parent());172173 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)174 .map_err(dispatch_to_evm::<T>)175 }176177 /// @notice Get token property value.178 /// @dev Throws error if key not found179 /// @param tokenId ID of the token.180 /// @param key Property key.181 /// @return Property value bytes182 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {183 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;184 let key = <Vec<u8>>::from(key)185 .try_into()186 .map_err(|_| "key too long")?;187188 let props = <TokenProperties<T>>::get((self.id, token_id));189 let prop = props.get(&key).ok_or("key not found")?;190191 Ok(prop.to_vec().into())192 }193}194195#[derive(ToLog)]196pub enum ERC721Events {197 /// @dev This emits when ownership of any NFT changes by any mechanism.198 /// This event emits when NFTs are created (`from` == 0) and destroyed199 /// (`to` == 0). Exception: during contract creation, any number of NFTs200 /// may be created and assigned without emitting Transfer. At the time of201 /// any transfer, the approved address for that NFT (if any) is reset to none.202 Transfer {203 #[indexed]204 from: address,205 #[indexed]206 to: address,207 #[indexed]208 token_id: uint256,209 },210 /// @dev This emits when the approved address for an NFT is changed or211 /// reaffirmed. The zero address indicates there is no approved address.212 /// When a Transfer event emits, this also indicates that the approved213 /// address for that NFT (if any) is reset to none.214 Approval {215 #[indexed]216 owner: address,217 #[indexed]218 approved: address,219 #[indexed]220 token_id: uint256,221 },222 /// @dev This emits when an operator is enabled or disabled for an owner.223 /// The operator can manage all NFTs of the owner.224 #[allow(dead_code)]225 ApprovalForAll {226 #[indexed]227 owner: address,228 #[indexed]229 operator: address,230 approved: bool,231 },232}233234#[derive(ToLog)]235pub enum ERC721UniqueMintableEvents {236 #[allow(dead_code)]237 MintingFinished {},238}239240/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension241/// @dev See https://eips.ethereum.org/EIPS/eip-721242#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]243impl<T: Config> NonfungibleHandle<T>244where245 T::AccountId: From<[u8; 32]>,246{247 /// @notice A descriptive name for a collection of NFTs in this contract248 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`249 #[solidity(hide, rename_selector = "name")]250 fn name_proxy(&self) -> Result<string> {251 self.name()252 }253254 /// @notice An abbreviated name for NFTs in this contract255 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`256 #[solidity(hide, rename_selector = "symbol")]257 fn symbol_proxy(&self) -> Result<string> {258 self.symbol()259 }260261 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.262 ///263 /// @dev If the token has a `url` property and it is not empty, it is returned.264 /// 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`.265 /// If the collection property `baseURI` is empty or absent, return "" (empty string)266 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix267 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).268 ///269 /// @return token's const_metadata270 #[solidity(rename_selector = "tokenURI")]271 fn token_uri(&self, token_id: uint256) -> Result<string> {272 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;273274 match get_token_property(self, token_id_u32, &key::url()).as_deref() {275 Err(_) | Ok("") => (),276 Ok(url) => {277 return Ok(url.into());278 }279 };280281 let base_uri =282 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())283 .map(BoundedVec::into_inner)284 .map(string::from_utf8)285 .transpose()286 .map_err(|e| {287 Error::Revert(alloc::format!(288 "Can not convert value \"baseURI\" to string with error \"{}\"",289 e290 ))291 })?;292293 let base_uri = match base_uri.as_deref() {294 None | Some("") => {295 return Ok("".into());296 }297 Some(base_uri) => base_uri.into(),298 };299300 Ok(301 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {302 Err(_) | Ok("") => base_uri,303 Ok(suffix) => base_uri + suffix,304 },305 )306 }307}308309/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension310/// @dev See https://eips.ethereum.org/EIPS/eip-721311#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]312impl<T: Config> NonfungibleHandle<T> {313 /// @notice Enumerate valid NFTs314 /// @param index A counter less than `totalSupply()`315 /// @return The token identifier for the `index`th NFT,316 /// (sort order not specified)317 fn token_by_index(&self, index: uint256) -> Result<uint256> {318 Ok(index)319 }320321 /// @dev Not implemented322 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {323 // TODO: Not implemetable324 Err("not implemented".into())325 }326327 /// @notice Count NFTs tracked by this contract328 /// @return A count of valid NFTs tracked by this contract, where each one of329 /// them has an assigned and queryable owner not equal to the zero address330 fn total_supply(&self) -> Result<uint256> {331 self.consume_store_reads(1)?;332 Ok(<Pallet<T>>::total_supply(self).into())333 }334}335336/// @title ERC-721 Non-Fungible Token Standard337/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md338#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]339impl<T: Config> NonfungibleHandle<T> {340 /// @notice Count all NFTs assigned to an owner341 /// @dev NFTs assigned to the zero address are considered invalid, and this342 /// function throws for queries about the zero address.343 /// @param owner An address for whom to query the balance344 /// @return The number of NFTs owned by `owner`, possibly zero345 fn balance_of(&self, owner: address) -> Result<uint256> {346 self.consume_store_reads(1)?;347 let owner = T::CrossAccountId::from_eth(owner);348 let balance = <AccountBalance<T>>::get((self.id, owner));349 Ok(balance.into())350 }351 /// @notice Find the owner of an NFT352 /// @dev NFTs assigned to zero address are considered invalid, and queries353 /// about them do throw.354 /// @param tokenId The identifier for an NFT355 /// @return The address of the owner of the NFT356 fn owner_of(&self, token_id: uint256) -> Result<address> {357 self.consume_store_reads(1)?;358 let token: TokenId = token_id.try_into()?;359 Ok(*<TokenData<T>>::get((self.id, token))360 .ok_or("token not found")?361 .owner362 .as_eth())363 }364 /// @dev Not implemented365 #[solidity(rename_selector = "safeTransferFrom")]366 fn safe_transfer_from_with_data(367 &mut self,368 _from: address,369 _to: address,370 _token_id: uint256,371 _data: bytes,372 ) -> Result<void> {373 // TODO: Not implemetable374 Err("not implemented".into())375 }376 /// @dev Not implemented377 fn safe_transfer_from(378 &mut self,379 _from: address,380 _to: address,381 _token_id: uint256,382 ) -> Result<void> {383 // TODO: Not implemetable384 Err("not implemented".into())385 }386387 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE388 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE389 /// THEY MAY BE PERMANENTLY LOST390 /// @dev Throws unless `msg.sender` is the current owner or an authorized391 /// operator for this NFT. Throws if `from` is not the current owner. Throws392 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.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())]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 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)413 .map_err(dispatch_to_evm::<T>)?;414 Ok(())415 }416417 /// @notice Set or reaffirm the approved address for an NFT418 /// @dev The zero address indicates there is no approved address.419 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized420 /// operator of the current owner.421 /// @param approved The new approved NFT controller422 /// @param tokenId The NFT to approve423 #[weight(<SelfWeightOf<T>>::approve())]424 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {425 let caller = T::CrossAccountId::from_eth(caller);426 let approved = T::CrossAccountId::from_eth(approved);427 let token = token_id.try_into()?;428429 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))430 .map_err(dispatch_to_evm::<T>)?;431 Ok(())432 }433434 /// @dev Not implemented435 fn set_approval_for_all(436 &mut self,437 _caller: caller,438 _operator: address,439 _approved: bool,440 ) -> Result<void> {441 // TODO: Not implemetable442 Err("not implemented".into())443 }444445 /// @dev Not implemented446 fn get_approved(&self, _token_id: uint256) -> Result<address> {447 // TODO: Not implemetable448 Err("not implemented".into())449 }450451 /// @dev Not implemented452 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {453 // TODO: Not implemetable454 Err("not implemented".into())455 }456}457458/// @title ERC721 Token that can be irreversibly burned (destroyed).459#[solidity_interface(name = ERC721Burnable)]460impl<T: Config> NonfungibleHandle<T> {461 /// @notice Burns a specific ERC721 token.462 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized463 /// operator of the current owner.464 /// @param tokenId The NFT to approve465 #[weight(<SelfWeightOf<T>>::burn_item())]466 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {467 let caller = T::CrossAccountId::from_eth(caller);468 let token = token_id.try_into()?;469470 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;471 Ok(())472 }473}474475/// @title ERC721 minting logic.476#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]477impl<T: Config> NonfungibleHandle<T> {478 fn minting_finished(&self) -> Result<bool> {479 Ok(false)480 }481482 /// @notice Function to mint token.483 /// @param to The new owner484 /// @return uint256 The id of the newly minted token485 #[weight(<SelfWeightOf<T>>::create_item())]486 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {487 let token_id: uint256 = <TokensMinted<T>>::get(self.id)488 .checked_add(1)489 .ok_or("item id overflow")?490 .into();491 self.mint_check_id(caller, to, token_id)?;492 Ok(token_id)493 }494495 /// @notice Function to mint token.496 /// @dev `tokenId` should be obtained with `nextTokenId` method,497 /// unlike standard, you can't specify it manually498 /// @param to The new owner499 /// @param tokenId ID of the minted NFT500 #[solidity(hide, rename_selector = "mint")]501 #[weight(<SelfWeightOf<T>>::create_item())]502 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {503 let caller = T::CrossAccountId::from_eth(caller);504 let to = T::CrossAccountId::from_eth(to);505 let token_id: u32 = token_id.try_into()?;506 let budget = self507 .recorder508 .weight_calls_budget(<StructureWeight<T>>::find_parent());509510 if <TokensMinted<T>>::get(self.id)511 .checked_add(1)512 .ok_or("item id overflow")?513 != token_id514 {515 return Err("item id should be next".into());516 }517518 <Pallet<T>>::create_item(519 self,520 &caller,521 CreateItemData::<T> {522 properties: BoundedVec::default(),523 owner: to,524 },525 &budget,526 )527 .map_err(dispatch_to_evm::<T>)?;528529 Ok(true)530 }531532 /// @notice Function to mint token with the given tokenUri.533 /// @param to The new owner534 /// @param tokenUri Token URI that would be stored in the NFT properties535 /// @return uint256 The id of the newly minted token536 #[solidity(rename_selector = "mintWithTokenURI")]537 #[weight(<SelfWeightOf<T>>::create_item())]538 fn mint_with_token_uri(539 &mut self,540 caller: caller,541 to: address,542 token_uri: string,543 ) -> Result<uint256> {544 let token_id: uint256 = <TokensMinted<T>>::get(self.id)545 .checked_add(1)546 .ok_or("item id overflow")?547 .into();548 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;549 Ok(token_id)550 }551552 /// @notice Function to mint token with the given tokenUri.553 /// @dev `tokenId` should be obtained with `nextTokenId` method,554 /// unlike standard, you can't specify it manually555 /// @param to The new owner556 /// @param tokenId ID of the minted NFT557 /// @param tokenUri Token URI that would be stored in the NFT properties558 #[solidity(hide, rename_selector = "mintWithTokenURI")]559 #[weight(<SelfWeightOf<T>>::create_item())]560 fn mint_with_token_uri_check_id(561 &mut self,562 caller: caller,563 to: address,564 token_id: uint256,565 token_uri: string,566 ) -> Result<bool> {567 let key = key::url();568 let permission = get_token_permission::<T>(self.id, &key)?;569 if !permission.collection_admin {570 return Err("Operation is not allowed".into());571 }572573 let caller = T::CrossAccountId::from_eth(caller);574 let to = T::CrossAccountId::from_eth(to);575 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;576 let budget = self577 .recorder578 .weight_calls_budget(<StructureWeight<T>>::find_parent());579580 if <TokensMinted<T>>::get(self.id)581 .checked_add(1)582 .ok_or("item id overflow")?583 != token_id584 {585 return Err("item id should be next".into());586 }587588 let mut properties = CollectionPropertiesVec::default();589 properties590 .try_push(Property {591 key,592 value: token_uri593 .into_bytes()594 .try_into()595 .map_err(|_| "token uri is too long")?,596 })597 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;598599 <Pallet<T>>::create_item(600 self,601 &caller,602 CreateItemData::<T> {603 properties,604 owner: to,605 },606 &budget,607 )608 .map_err(dispatch_to_evm::<T>)?;609 Ok(true)610 }611612 /// @dev Not implemented613 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {614 Err("not implementable".into())615 }616}617618fn get_token_property<T: Config>(619 collection: &CollectionHandle<T>,620 token_id: u32,621 key: &up_data_structs::PropertyKey,622) -> Result<string> {623 collection.consume_store_reads(1)?;624 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))625 .map_err(|_| Error::Revert("Token properties not found".into()))?;626 if let Some(property) = properties.get(key) {627 return Ok(string::from_utf8_lossy(property).into());628 }629630 Err("Property tokenURI not found".into())631}632633fn get_token_permission<T: Config>(634 collection_id: CollectionId,635 key: &PropertyKey,636) -> Result<PropertyPermission> {637 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)638 .map_err(|_| Error::Revert("No permissions for collection".into()))?;639 let a = token_property_permissions640 .get(key)641 .map(Clone::clone)642 .ok_or_else(|| {643 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();644 Error::Revert(alloc::format!("No permission for key {}", key))645 })?;646 Ok(a)647}648649/// @title Unique extensions for ERC721.650#[solidity_interface(name = ERC721UniqueExtensions)]651impl<T: Config> NonfungibleHandle<T>652where653 T::AccountId: From<[u8; 32]>,654{655 /// @notice A descriptive name for a collection of NFTs in this contract656 fn name(&self) -> Result<string> {657 Ok(decode_utf16(self.name.iter().copied())658 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))659 .collect::<string>())660 }661662 /// @notice An abbreviated name for NFTs in this contract663 fn symbol(&self) -> Result<string> {664 Ok(string::from_utf8_lossy(&self.token_prefix).into())665 }666667 /// @notice Set or reaffirm the approved address for an NFT668 /// @dev The zero address indicates there is no approved address.669 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized670 /// operator of the current owner.671 /// @param approved The new substrate address approved NFT controller672 /// @param tokenId The NFT to approve673 #[weight(<SelfWeightOf<T>>::approve())]674 fn approve_cross(675 &mut self,676 caller: caller,677 approved: EthCrossAccount,678 token_id: uint256,679 ) -> Result<void> {680 let caller = T::CrossAccountId::from_eth(caller);681 let approved = approved.into_sub_cross_account::<T>()?;682 let token = token_id.try_into()?;683684 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))685 .map_err(dispatch_to_evm::<T>)?;686 Ok(())687 }688689 /// @notice Transfer ownership of an NFT690 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`691 /// is the zero address. Throws if `tokenId` is not a valid NFT.692 /// @param to The new owner693 /// @param tokenId The NFT to transfer694 #[weight(<SelfWeightOf<T>>::transfer())]695 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {696 let caller = T::CrossAccountId::from_eth(caller);697 let to = T::CrossAccountId::from_eth(to);698 let token = token_id.try_into()?;699 let budget = self700 .recorder701 .weight_calls_budget(<StructureWeight<T>>::find_parent());702703 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;704 Ok(())705 }706707 /// @notice Transfer ownership of an NFT from cross account address to cross account address708 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`709 /// is the zero address. Throws if `tokenId` is not a valid NFT.710 /// @param from Cross acccount address of current owner711 /// @param to Cross acccount address of new owner712 /// @param tokenId The NFT to transfer713 #[weight(<SelfWeightOf<T>>::transfer())]714 fn transfer_from_cross(715 &mut self,716 caller: caller,717 from: EthCrossAccount,718 to: EthCrossAccount,719 token_id: uint256,720 ) -> Result<void> {721 let caller = T::CrossAccountId::from_eth(caller);722 let from = from.into_sub_cross_account::<T>()?;723 let to = to.into_sub_cross_account::<T>()?;724 let token_id = token_id.try_into()?;725 let budget = self726 .recorder727 .weight_calls_budget(<StructureWeight<T>>::find_parent());728 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)729 .map_err(dispatch_to_evm::<T>)?;730 Ok(())731 }732733 /// @notice Burns a specific ERC721 token.734 /// @dev Throws unless `msg.sender` is the current owner or an authorized735 /// operator for this NFT. Throws if `from` is not the current owner. Throws736 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.737 /// @param from The current owner of the NFT738 /// @param tokenId The NFT to transfer739 #[weight(<SelfWeightOf<T>>::burn_from())]740 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {741 let caller = T::CrossAccountId::from_eth(caller);742 let from = T::CrossAccountId::from_eth(from);743 let token = token_id.try_into()?;744 let budget = self745 .recorder746 .weight_calls_budget(<StructureWeight<T>>::find_parent());747748 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)749 .map_err(dispatch_to_evm::<T>)?;750 Ok(())751 }752753 /// @notice Burns a specific ERC721 token.754 /// @dev Throws unless `msg.sender` is the current owner or an authorized755 /// operator for this NFT. Throws if `from` is not the current owner. Throws756 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.757 /// @param from The current owner of the NFT758 /// @param tokenId The NFT to transfer759 #[weight(<SelfWeightOf<T>>::burn_from())]760 fn burn_from_cross(761 &mut self,762 caller: caller,763 from: EthCrossAccount,764 token_id: uint256,765 ) -> Result<void> {766 let caller = T::CrossAccountId::from_eth(caller);767 let from = from.into_sub_cross_account::<T>()?;768 let token = token_id.try_into()?;769 let budget = self770 .recorder771 .weight_calls_budget(<StructureWeight<T>>::find_parent());772773 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)774 .map_err(dispatch_to_evm::<T>)?;775 Ok(())776 }777778 /// @notice Returns next free NFT ID.779 fn next_token_id(&self) -> Result<uint256> {780 self.consume_store_reads(1)?;781 Ok(<TokensMinted<T>>::get(self.id)782 .checked_add(1)783 .ok_or("item id overflow")?784 .into())785 }786787 /// @notice Function to mint multiple tokens.788 /// @dev `tokenIds` should be an array of consecutive numbers and first number789 /// should be obtained with `nextTokenId` method790 /// @param to The new owner791 /// @param tokenIds IDs of the minted NFTs792 #[solidity(hide)]793 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]794 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {795 let caller = T::CrossAccountId::from_eth(caller);796 let to = T::CrossAccountId::from_eth(to);797 let mut expected_index = <TokensMinted<T>>::get(self.id)798 .checked_add(1)799 .ok_or("item id overflow")?;800 let budget = self801 .recorder802 .weight_calls_budget(<StructureWeight<T>>::find_parent());803804 let total_tokens = token_ids.len();805 for id in token_ids.into_iter() {806 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;807 if id != expected_index {808 return Err("item id should be next".into());809 }810 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;811 }812 let data = (0..total_tokens)813 .map(|_| CreateItemData::<T> {814 properties: BoundedVec::default(),815 owner: to.clone(),816 })817 .collect();818819 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)820 .map_err(dispatch_to_evm::<T>)?;821 Ok(true)822 }823824 /// @notice Function to mint multiple tokens with the given tokenUris.825 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive826 /// numbers and first number should be obtained with `nextTokenId` method827 /// @param to The new owner828 /// @param tokens array of pairs of token ID and token URI for minted tokens829 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]830 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]831 fn mint_bulk_with_token_uri(832 &mut self,833 caller: caller,834 to: address,835 tokens: Vec<(uint256, string)>,836 ) -> Result<bool> {837 let key = key::url();838 let caller = T::CrossAccountId::from_eth(caller);839 let to = T::CrossAccountId::from_eth(to);840 let mut expected_index = <TokensMinted<T>>::get(self.id)841 .checked_add(1)842 .ok_or("item id overflow")?;843 let budget = self844 .recorder845 .weight_calls_budget(<StructureWeight<T>>::find_parent());846847 let mut data = Vec::with_capacity(tokens.len());848 for (id, token_uri) in tokens {849 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;850 if id != expected_index {851 return Err("item id should be next".into());852 }853 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;854855 let mut properties = CollectionPropertiesVec::default();856 properties857 .try_push(Property {858 key: key.clone(),859 value: token_uri860 .into_bytes()861 .try_into()862 .map_err(|_| "token uri is too long")?,863 })864 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;865866 data.push(CreateItemData::<T> {867 properties,868 owner: to.clone(),869 });870 }871872 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)873 .map_err(dispatch_to_evm::<T>)?;874 Ok(true)875 }876}877878#[solidity_interface(879 name = UniqueNFT,880 is(881 ERC721,882 ERC721Enumerable,883 ERC721UniqueExtensions,884 ERC721UniqueMintable,885 ERC721Burnable,886 ERC721Metadata(if(this.flags.erc721metadata)),887 Collection(via(common_mut returns CollectionHandle<T>)),888 TokenProperties,889 )890)]891impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}892893// Not a tests, but code generators894generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);895generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);896897impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>898where899 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,900{901 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");902903 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {904 call::<T, UniqueNFTCall<T>, _, _>(handle, self)905 }906}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{28 abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,29 weight,30};31use frame_support::BoundedVec;32use up_data_structs::{33 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,34 CollectionPropertiesVec,35};36use pallet_evm_coder_substrate::dispatch_to_evm;37use sp_std::vec::Vec;38use pallet_common::{39 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},40 CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4546use crate::{47 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,48 SelfWeightOf, weights::WeightInfo, TokenProperties,49};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> NonfungibleHandle<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_property_permission(70 self,71 &caller,72 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 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]124 fn set_properties(125 &mut self,126 caller: caller,127 token_id: uint256,128 properties: Vec<(string, bytes)>,129 ) -> Result<()> {130 let caller = T::CrossAccountId::from_eth(caller);131 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;132133 let nesting_budget = self134 .recorder135 .weight_calls_budget(<StructureWeight<T>>::find_parent());136137 let properties = properties138 .into_iter()139 .map(|(key, value)| {140 let key = <Vec<u8>>::from(key)141 .try_into()142 .map_err(|_| "key too large")?;143144 let value = value.0.try_into().map_err(|_| "value too large")?;145146 Ok(Property { key, value })147 })148 .collect::<Result<Vec<_>>>()?;149150 <Pallet<T>>::set_token_properties(151 self,152 &caller,153 TokenId(token_id),154 properties.into_iter(),155 <Pallet<T>>::token_exists(&self, TokenId(token_id)),156 &nesting_budget,157 )158 .map_err(dispatch_to_evm::<T>)159 }160161 /// @notice Delete token property value.162 /// @dev Throws error if `msg.sender` has no permission to edit the property.163 /// @param tokenId ID of the token.164 /// @param key Property key.165 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {166 let caller = T::CrossAccountId::from_eth(caller);167 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;168 let key = <Vec<u8>>::from(key)169 .try_into()170 .map_err(|_| "key too long")?;171172 let nesting_budget = self173 .recorder174 .weight_calls_budget(<StructureWeight<T>>::find_parent());175176 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)177 .map_err(dispatch_to_evm::<T>)178 }179180 /// @notice Get token property value.181 /// @dev Throws error if key not found182 /// @param tokenId ID of the token.183 /// @param key Property key.184 /// @return Property value bytes185 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {186 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;187 let key = <Vec<u8>>::from(key)188 .try_into()189 .map_err(|_| "key too long")?;190191 let props = <TokenProperties<T>>::get((self.id, token_id));192 let prop = props.get(&key).ok_or("key not found")?;193194 Ok(prop.to_vec().into())195 }196}197198#[derive(ToLog)]199pub enum ERC721Events {200 /// @dev This emits when ownership of any NFT changes by any mechanism.201 /// This event emits when NFTs are created (`from` == 0) and destroyed202 /// (`to` == 0). Exception: during contract creation, any number of NFTs203 /// may be created and assigned without emitting Transfer. At the time of204 /// any transfer, the approved address for that NFT (if any) is reset to none.205 Transfer {206 #[indexed]207 from: address,208 #[indexed]209 to: address,210 #[indexed]211 token_id: uint256,212 },213 /// @dev This emits when the approved address for an NFT is changed or214 /// reaffirmed. The zero address indicates there is no approved address.215 /// When a Transfer event emits, this also indicates that the approved216 /// address for that NFT (if any) is reset to none.217 Approval {218 #[indexed]219 owner: address,220 #[indexed]221 approved: address,222 #[indexed]223 token_id: uint256,224 },225 /// @dev This emits when an operator is enabled or disabled for an owner.226 /// The operator can manage all NFTs of the owner.227 #[allow(dead_code)]228 ApprovalForAll {229 #[indexed]230 owner: address,231 #[indexed]232 operator: address,233 approved: bool,234 },235}236237#[derive(ToLog)]238pub enum ERC721UniqueMintableEvents {239 #[allow(dead_code)]240 MintingFinished {},241}242243/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension244/// @dev See https://eips.ethereum.org/EIPS/eip-721245#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]246impl<T: Config> NonfungibleHandle<T>247where248 T::AccountId: From<[u8; 32]>,249{250 /// @notice A descriptive name for a collection of NFTs in this contract251 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`252 #[solidity(hide, rename_selector = "name")]253 fn name_proxy(&self) -> Result<string> {254 self.name()255 }256257 /// @notice An abbreviated name for NFTs in this contract258 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`259 #[solidity(hide, rename_selector = "symbol")]260 fn symbol_proxy(&self) -> Result<string> {261 self.symbol()262 }263264 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.265 ///266 /// @dev If the token has a `url` property and it is not empty, it is returned.267 /// 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`.268 /// If the collection property `baseURI` is empty or absent, return "" (empty string)269 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix270 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).271 ///272 /// @return token's const_metadata273 #[solidity(rename_selector = "tokenURI")]274 fn token_uri(&self, token_id: uint256) -> Result<string> {275 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;276277 match get_token_property(self, token_id_u32, &key::url()).as_deref() {278 Err(_) | Ok("") => (),279 Ok(url) => {280 return Ok(url.into());281 }282 };283284 let base_uri =285 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())286 .map(BoundedVec::into_inner)287 .map(string::from_utf8)288 .transpose()289 .map_err(|e| {290 Error::Revert(alloc::format!(291 "Can not convert value \"baseURI\" to string with error \"{}\"",292 e293 ))294 })?;295296 let base_uri = match base_uri.as_deref() {297 None | Some("") => {298 return Ok("".into());299 }300 Some(base_uri) => base_uri.into(),301 };302303 Ok(304 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {305 Err(_) | Ok("") => base_uri,306 Ok(suffix) => base_uri + suffix,307 },308 )309 }310}311312/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension313/// @dev See https://eips.ethereum.org/EIPS/eip-721314#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]315impl<T: Config> NonfungibleHandle<T> {316 /// @notice Enumerate valid NFTs317 /// @param index A counter less than `totalSupply()`318 /// @return The token identifier for the `index`th NFT,319 /// (sort order not specified)320 fn token_by_index(&self, index: uint256) -> Result<uint256> {321 Ok(index)322 }323324 /// @dev Not implemented325 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {326 // TODO: Not implemetable327 Err("not implemented".into())328 }329330 /// @notice Count NFTs tracked by this contract331 /// @return A count of valid NFTs tracked by this contract, where each one of332 /// them has an assigned and queryable owner not equal to the zero address333 fn total_supply(&self) -> Result<uint256> {334 self.consume_store_reads(1)?;335 Ok(<Pallet<T>>::total_supply(self).into())336 }337}338339/// @title ERC-721 Non-Fungible Token Standard340/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md341#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]342impl<T: Config> NonfungibleHandle<T> {343 /// @notice Count all NFTs assigned to an owner344 /// @dev NFTs assigned to the zero address are considered invalid, and this345 /// function throws for queries about the zero address.346 /// @param owner An address for whom to query the balance347 /// @return The number of NFTs owned by `owner`, possibly zero348 fn balance_of(&self, owner: address) -> Result<uint256> {349 self.consume_store_reads(1)?;350 let owner = T::CrossAccountId::from_eth(owner);351 let balance = <AccountBalance<T>>::get((self.id, owner));352 Ok(balance.into())353 }354 /// @notice Find the owner of an NFT355 /// @dev NFTs assigned to zero address are considered invalid, and queries356 /// about them do throw.357 /// @param tokenId The identifier for an NFT358 /// @return The address of the owner of the NFT359 fn owner_of(&self, token_id: uint256) -> Result<address> {360 self.consume_store_reads(1)?;361 let token: TokenId = token_id.try_into()?;362 Ok(*<TokenData<T>>::get((self.id, token))363 .ok_or("token not found")?364 .owner365 .as_eth())366 }367 /// @dev Not implemented368 #[solidity(rename_selector = "safeTransferFrom")]369 fn safe_transfer_from_with_data(370 &mut self,371 _from: address,372 _to: address,373 _token_id: uint256,374 _data: bytes,375 ) -> Result<void> {376 // TODO: Not implemetable377 Err("not implemented".into())378 }379 /// @dev Not implemented380 fn safe_transfer_from(381 &mut self,382 _from: address,383 _to: address,384 _token_id: uint256,385 ) -> Result<void> {386 // TODO: Not implemetable387 Err("not implemented".into())388 }389390 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE391 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE392 /// THEY MAY BE PERMANENTLY LOST393 /// @dev Throws unless `msg.sender` is the current owner or an authorized394 /// operator for this NFT. Throws if `from` is not the current owner. Throws395 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.396 /// @param from The current owner of the NFT397 /// @param to The new owner398 /// @param tokenId The NFT to transfer399 #[weight(<SelfWeightOf<T>>::transfer_from())]400 fn transfer_from(401 &mut self,402 caller: caller,403 from: address,404 to: address,405 token_id: uint256,406 ) -> Result<void> {407 let caller = T::CrossAccountId::from_eth(caller);408 let from = T::CrossAccountId::from_eth(from);409 let to = T::CrossAccountId::from_eth(to);410 let token = token_id.try_into()?;411 let budget = self412 .recorder413 .weight_calls_budget(<StructureWeight<T>>::find_parent());414415 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)416 .map_err(dispatch_to_evm::<T>)?;417 Ok(())418 }419420 /// @notice Set or reaffirm the approved address for an NFT421 /// @dev The zero address indicates there is no approved address.422 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized423 /// operator of the current owner.424 /// @param approved The new approved NFT controller425 /// @param tokenId The NFT to approve426 #[weight(<SelfWeightOf<T>>::approve())]427 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {428 let caller = T::CrossAccountId::from_eth(caller);429 let approved = T::CrossAccountId::from_eth(approved);430 let token = token_id.try_into()?;431432 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))433 .map_err(dispatch_to_evm::<T>)?;434 Ok(())435 }436437 /// @dev Not implemented438 fn set_approval_for_all(439 &mut self,440 _caller: caller,441 _operator: address,442 _approved: bool,443 ) -> Result<void> {444 // TODO: Not implemetable445 Err("not implemented".into())446 }447448 /// @dev Not implemented449 fn get_approved(&self, _token_id: uint256) -> Result<address> {450 // TODO: Not implemetable451 Err("not implemented".into())452 }453454 /// @dev Not implemented455 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {456 // TODO: Not implemetable457 Err("not implemented".into())458 }459}460461/// @title ERC721 Token that can be irreversibly burned (destroyed).462#[solidity_interface(name = ERC721Burnable)]463impl<T: Config> NonfungibleHandle<T> {464 /// @notice Burns a specific ERC721 token.465 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized466 /// operator of the current owner.467 /// @param tokenId The NFT to approve468 #[weight(<SelfWeightOf<T>>::burn_item())]469 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {470 let caller = T::CrossAccountId::from_eth(caller);471 let token = token_id.try_into()?;472473 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;474 Ok(())475 }476}477478/// @title ERC721 minting logic.479#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]480impl<T: Config> NonfungibleHandle<T> {481 fn minting_finished(&self) -> Result<bool> {482 Ok(false)483 }484485 /// @notice Function to mint token.486 /// @param to The new owner487 /// @return uint256 The id of the newly minted token488 #[weight(<SelfWeightOf<T>>::create_item())]489 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {490 let token_id: uint256 = <TokensMinted<T>>::get(self.id)491 .checked_add(1)492 .ok_or("item id overflow")?493 .into();494 self.mint_check_id(caller, to, token_id)?;495 Ok(token_id)496 }497498 /// @notice Function to mint token.499 /// @dev `tokenId` should be obtained with `nextTokenId` method,500 /// unlike standard, you can't specify it manually501 /// @param to The new owner502 /// @param tokenId ID of the minted NFT503 #[solidity(hide, rename_selector = "mint")]504 #[weight(<SelfWeightOf<T>>::create_item())]505 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {506 let caller = T::CrossAccountId::from_eth(caller);507 let to = T::CrossAccountId::from_eth(to);508 let token_id: u32 = token_id.try_into()?;509 let budget = self510 .recorder511 .weight_calls_budget(<StructureWeight<T>>::find_parent());512513 if <TokensMinted<T>>::get(self.id)514 .checked_add(1)515 .ok_or("item id overflow")?516 != token_id517 {518 return Err("item id should be next".into());519 }520521 <Pallet<T>>::create_item(522 self,523 &caller,524 CreateItemData::<T> {525 properties: BoundedVec::default(),526 owner: to,527 },528 &budget,529 )530 .map_err(dispatch_to_evm::<T>)?;531532 Ok(true)533 }534535 /// @notice Function to mint token with the given tokenUri.536 /// @param to The new owner537 /// @param tokenUri Token URI that would be stored in the NFT properties538 /// @return uint256 The id of the newly minted token539 #[solidity(rename_selector = "mintWithTokenURI")]540 #[weight(<SelfWeightOf<T>>::create_item())]541 fn mint_with_token_uri(542 &mut self,543 caller: caller,544 to: address,545 token_uri: string,546 ) -> Result<uint256> {547 let token_id: uint256 = <TokensMinted<T>>::get(self.id)548 .checked_add(1)549 .ok_or("item id overflow")?550 .into();551 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;552 Ok(token_id)553 }554555 /// @notice Function to mint token with the given tokenUri.556 /// @dev `tokenId` should be obtained with `nextTokenId` method,557 /// unlike standard, you can't specify it manually558 /// @param to The new owner559 /// @param tokenId ID of the minted NFT560 /// @param tokenUri Token URI that would be stored in the NFT properties561 #[solidity(hide, rename_selector = "mintWithTokenURI")]562 #[weight(<SelfWeightOf<T>>::create_item())]563 fn mint_with_token_uri_check_id(564 &mut self,565 caller: caller,566 to: address,567 token_id: uint256,568 token_uri: string,569 ) -> Result<bool> {570 let key = key::url();571 let permission = get_token_permission::<T>(self.id, &key)?;572 if !permission.collection_admin {573 return Err("Operation is not allowed".into());574 }575576 let caller = T::CrossAccountId::from_eth(caller);577 let to = T::CrossAccountId::from_eth(to);578 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;579 let budget = self580 .recorder581 .weight_calls_budget(<StructureWeight<T>>::find_parent());582583 if <TokensMinted<T>>::get(self.id)584 .checked_add(1)585 .ok_or("item id overflow")?586 != token_id587 {588 return Err("item id should be next".into());589 }590591 let mut properties = CollectionPropertiesVec::default();592 properties593 .try_push(Property {594 key,595 value: token_uri596 .into_bytes()597 .try_into()598 .map_err(|_| "token uri is too long")?,599 })600 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;601602 <Pallet<T>>::create_item(603 self,604 &caller,605 CreateItemData::<T> {606 properties,607 owner: to,608 },609 &budget,610 )611 .map_err(dispatch_to_evm::<T>)?;612 Ok(true)613 }614615 /// @dev Not implemented616 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {617 Err("not implementable".into())618 }619}620621fn get_token_property<T: Config>(622 collection: &CollectionHandle<T>,623 token_id: u32,624 key: &up_data_structs::PropertyKey,625) -> Result<string> {626 collection.consume_store_reads(1)?;627 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))628 .map_err(|_| Error::Revert("Token properties not found".into()))?;629 if let Some(property) = properties.get(key) {630 return Ok(string::from_utf8_lossy(property).into());631 }632633 Err("Property tokenURI not found".into())634}635636fn get_token_permission<T: Config>(637 collection_id: CollectionId,638 key: &PropertyKey,639) -> Result<PropertyPermission> {640 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)641 .map_err(|_| Error::Revert("No permissions for collection".into()))?;642 let a = token_property_permissions643 .get(key)644 .map(Clone::clone)645 .ok_or_else(|| {646 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();647 Error::Revert(alloc::format!("No permission for key {}", key))648 })?;649 Ok(a)650}651652/// @title Unique extensions for ERC721.653#[solidity_interface(name = ERC721UniqueExtensions)]654impl<T: Config> NonfungibleHandle<T>655where656 T::AccountId: From<[u8; 32]>,657{658 /// @notice A descriptive name for a collection of NFTs in this contract659 fn name(&self) -> Result<string> {660 Ok(decode_utf16(self.name.iter().copied())661 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))662 .collect::<string>())663 }664665 /// @notice An abbreviated name for NFTs in this contract666 fn symbol(&self) -> Result<string> {667 Ok(string::from_utf8_lossy(&self.token_prefix).into())668 }669670 /// @notice Set or reaffirm the approved address for an NFT671 /// @dev The zero address indicates there is no approved address.672 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized673 /// operator of the current owner.674 /// @param approved The new substrate address approved NFT controller675 /// @param tokenId The NFT to approve676 #[weight(<SelfWeightOf<T>>::approve())]677 fn approve_cross(678 &mut self,679 caller: caller,680 approved: EthCrossAccount,681 token_id: uint256,682 ) -> Result<void> {683 let caller = T::CrossAccountId::from_eth(caller);684 let approved = approved.into_sub_cross_account::<T>()?;685 let token = token_id.try_into()?;686687 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))688 .map_err(dispatch_to_evm::<T>)?;689 Ok(())690 }691692 /// @notice Transfer ownership of an NFT693 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`694 /// is the zero address. Throws if `tokenId` is not a valid NFT.695 /// @param to The new owner696 /// @param tokenId The NFT to transfer697 #[weight(<SelfWeightOf<T>>::transfer())]698 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {699 let caller = T::CrossAccountId::from_eth(caller);700 let to = T::CrossAccountId::from_eth(to);701 let token = token_id.try_into()?;702 let budget = self703 .recorder704 .weight_calls_budget(<StructureWeight<T>>::find_parent());705706 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;707 Ok(())708 }709710 /// @notice Transfer ownership of an NFT from cross account address to cross account address711 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`712 /// is the zero address. Throws if `tokenId` is not a valid NFT.713 /// @param from Cross acccount address of current owner714 /// @param to Cross acccount address of new owner715 /// @param tokenId The NFT to transfer716 #[weight(<SelfWeightOf<T>>::transfer())]717 fn transfer_from_cross(718 &mut self,719 caller: caller,720 from: EthCrossAccount,721 to: EthCrossAccount,722 token_id: uint256,723 ) -> Result<void> {724 let caller = T::CrossAccountId::from_eth(caller);725 let from = from.into_sub_cross_account::<T>()?;726 let to = to.into_sub_cross_account::<T>()?;727 let token_id = token_id.try_into()?;728 let budget = self729 .recorder730 .weight_calls_budget(<StructureWeight<T>>::find_parent());731 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)732 .map_err(dispatch_to_evm::<T>)?;733 Ok(())734 }735736 /// @notice Burns a specific ERC721 token.737 /// @dev Throws unless `msg.sender` is the current owner or an authorized738 /// operator for this NFT. Throws if `from` is not the current owner. Throws739 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.740 /// @param from The current owner of the NFT741 /// @param tokenId The NFT to transfer742 #[weight(<SelfWeightOf<T>>::burn_from())]743 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {744 let caller = T::CrossAccountId::from_eth(caller);745 let from = T::CrossAccountId::from_eth(from);746 let token = token_id.try_into()?;747 let budget = self748 .recorder749 .weight_calls_budget(<StructureWeight<T>>::find_parent());750751 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)752 .map_err(dispatch_to_evm::<T>)?;753 Ok(())754 }755756 /// @notice Burns a specific ERC721 token.757 /// @dev Throws unless `msg.sender` is the current owner or an authorized758 /// operator for this NFT. Throws if `from` is not the current owner. Throws759 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.760 /// @param from The current owner of the NFT761 /// @param tokenId The NFT to transfer762 #[weight(<SelfWeightOf<T>>::burn_from())]763 fn burn_from_cross(764 &mut self,765 caller: caller,766 from: EthCrossAccount,767 token_id: uint256,768 ) -> Result<void> {769 let caller = T::CrossAccountId::from_eth(caller);770 let from = from.into_sub_cross_account::<T>()?;771 let token = token_id.try_into()?;772 let budget = self773 .recorder774 .weight_calls_budget(<StructureWeight<T>>::find_parent());775776 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)777 .map_err(dispatch_to_evm::<T>)?;778 Ok(())779 }780781 /// @notice Returns next free NFT ID.782 fn next_token_id(&self) -> Result<uint256> {783 self.consume_store_reads(1)?;784 Ok(<TokensMinted<T>>::get(self.id)785 .checked_add(1)786 .ok_or("item id overflow")?787 .into())788 }789790 /// @notice Function to mint multiple tokens.791 /// @dev `tokenIds` should be an array of consecutive numbers and first number792 /// should be obtained with `nextTokenId` method793 /// @param to The new owner794 /// @param tokenIds IDs of the minted NFTs795 #[solidity(hide)]796 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]797 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {798 let caller = T::CrossAccountId::from_eth(caller);799 let to = T::CrossAccountId::from_eth(to);800 let mut expected_index = <TokensMinted<T>>::get(self.id)801 .checked_add(1)802 .ok_or("item id overflow")?;803 let budget = self804 .recorder805 .weight_calls_budget(<StructureWeight<T>>::find_parent());806807 let total_tokens = token_ids.len();808 for id in token_ids.into_iter() {809 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;810 if id != expected_index {811 return Err("item id should be next".into());812 }813 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;814 }815 let data = (0..total_tokens)816 .map(|_| CreateItemData::<T> {817 properties: BoundedVec::default(),818 owner: to.clone(),819 })820 .collect();821822 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)823 .map_err(dispatch_to_evm::<T>)?;824 Ok(true)825 }826827 /// @notice Function to mint multiple tokens with the given tokenUris.828 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive829 /// numbers and first number should be obtained with `nextTokenId` method830 /// @param to The new owner831 /// @param tokens array of pairs of token ID and token URI for minted tokens832 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]833 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]834 fn mint_bulk_with_token_uri(835 &mut self,836 caller: caller,837 to: address,838 tokens: Vec<(uint256, string)>,839 ) -> Result<bool> {840 let key = key::url();841 let caller = T::CrossAccountId::from_eth(caller);842 let to = T::CrossAccountId::from_eth(to);843 let mut expected_index = <TokensMinted<T>>::get(self.id)844 .checked_add(1)845 .ok_or("item id overflow")?;846 let budget = self847 .recorder848 .weight_calls_budget(<StructureWeight<T>>::find_parent());849850 let mut data = Vec::with_capacity(tokens.len());851 for (id, token_uri) in tokens {852 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;853 if id != expected_index {854 return Err("item id should be next".into());855 }856 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;857858 let mut properties = CollectionPropertiesVec::default();859 properties860 .try_push(Property {861 key: key.clone(),862 value: token_uri863 .into_bytes()864 .try_into()865 .map_err(|_| "token uri is too long")?,866 })867 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;868869 data.push(CreateItemData::<T> {870 properties,871 owner: to.clone(),872 });873 }874875 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)876 .map_err(dispatch_to_evm::<T>)?;877 Ok(true)878 }879}880881#[solidity_interface(882 name = UniqueNFT,883 is(884 ERC721,885 ERC721Enumerable,886 ERC721UniqueExtensions,887 ERC721UniqueMintable,888 ERC721Burnable,889 ERC721Metadata(if(this.flags.erc721metadata)),890 Collection(via(common_mut returns CollectionHandle<T>)),891 TokenProperties,892 )893)]894impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}895896// Not a tests, but code generators897generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);898generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);899900impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>901where902 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,903{904 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");905906 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {907 call::<T, UniqueNFTCall<T>, _, _>(handle, self)908 }909}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -25,7 +25,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::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
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};