difftreelog
misk: Documentation, test fixes, refactor
in: master
12 files changed
Cargo.lockdiffbeforeafterboth1095source = "registry+https://github.com/rust-lang/crates.io-index"1095source = "registry+https://github.com/rust-lang/crates.io-index"1096checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"1096checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"10971098[[package]]1099name = "const_format"1100version = "0.2.30"1101source = "registry+https://github.com/rust-lang/crates.io-index"1102checksum = "7309d9b4d3d2c0641e018d449232f2e28f1b22933c137f157d3dbc14228b8c0e"1103dependencies = [1104 "const_format_proc_macros",1105]11061107[[package]]1108name = "const_format_proc_macros"1109version = "0.2.29"1110source = "registry+https://github.com/rust-lang/crates.io-index"1111checksum = "d897f47bf7270cf70d370f8f98c1abb6d2d4cf60a6845d30e05bfb90c6568650"1112dependencies = [1113 "proc-macro2",1114 "quote",1115 "unicode-xid",1116]111710971118[[package]]1098[[package]]1119name = "constant_time_eq"1099name = "constant_time_eq"2373version = "0.1.3"2353version = "0.1.3"2374dependencies = [2354dependencies = [2375 "concat-idents",2355 "concat-idents",2376 "const_format",2377 "ethereum",2356 "ethereum",2378 "evm-coder-procedural",2357 "evm-coder-procedural",2379 "evm-core 0.35.0 (git+https://github.com/uniquenetwork/evm?branch=unique-polkadot-v0.9.30)",2358 "evm-core 0.35.0 (git+https://github.com/uniquenetwork/evm?branch=unique-polkadot-v0.9.30)",crates/evm-coder/Cargo.tomldiffbeforeafterboth5edition = "2021"5edition = "2021"667[dependencies]7[dependencies]8const_format = { version = "0.2.26", default-features = false }9sha3-const = { version = "0.1.1", default-features = false }8sha3-const = { version = "0.1.1", default-features = false }10# Ethereum uses keccak (=sha3) for selectors9# Ethereum uses keccak (=sha3) for selectors11# sha3 = "0.10.1"10# sha3 = "0.10.1"crates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth20// about Procedural Macros in Rust book:20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html21// https://doc.rust-lang.org/reference/procedural-macros.html222223use proc_macro2::{TokenStream, token_stream};23use proc_macro2::TokenStream;24use quote::{quote, ToTokens, format_ident};24use quote::{quote, ToTokens, format_ident};25use inflector::cases;25use inflector::cases;26use std::fmt::Write;26use std::fmt::Write;crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth1//! # A module for custom signature support.2//!3//! ## Overview4//! This module allows you to create arbitrary signatures for types and functions in compile time.5//!6//! ### Type signatures7//! To create the desired type signature, you need to create your own trait with the `SIGNATURE` constant.8//! Then in the implementation, for the required type, use the macro [`make_signature`]9//! #### Example10//! ```11//! use std::str::from_utf8;12//! use evm_coder::make_signature;13//! use evm_coder::custom_signature::{14//! SignatureUnit,15//! SIGNATURE_SIZE_LIMIT16//! };17//!18//! // Create trait for our signature19//! trait SoliditySignature {20//! const SIGNATURE: SignatureUnit;21//!22//! fn name() -> &'static str {23//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")24//! }25//! }26//!27//! // Make signatures for some types28//! impl SoliditySignature for u8 {29//! make_signature!(new fixed("uint8"));30//! }31//! impl SoliditySignature for u32 {32//! make_signature!(new fixed("uint32"));33//! }34//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {35//! make_signature!(new nameof(T) fixed("[]"));36//! }37//! impl<A: SoliditySignature, B: SoliditySignature> SoliditySignature for (A, B) {38//! make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));39//! }40//! impl<A: SoliditySignature> SoliditySignature for (A,) {41//! make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));42//! }43//!44//! assert_eq!(u8::name(), "uint8");45//! assert_eq!(<Vec<u8>>::name(), "uint8[]");46//! assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");47//! ```48//!49//! ### Function signatures50//! To create a function signature, the macro [`make_signature`] is also used, which accepts51//! settings for the function format [`SignaturePreferences`] and function parameters [`SignatureUnit`]52//! #### Example53//! ```54//! use core::str::from_utf8;55//! use evm_coder::{56//! make_signature,57//! custom_signature::{58//! SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,59//! },60//! };61//! // Trait for our signature62//! trait SoliditySignature {63//! const SIGNATURE: SignatureUnit;64//!65//! fn name() -> &'static str {66//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")67//! }68//! }69//!70//! // Make signatures for some types71//! impl SoliditySignature for u8 {72//! make_signature!(new fixed("uint8"));73//! }74//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {75//! make_signature!(new nameof(T) fixed("[]"));76//! }77//!78//! // Function signature settings79//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {80//! open_name: Some(SignatureUnit::new("some_funk")),81//! open_delimiter: Some(SignatureUnit::new("(")),82//! param_delimiter: Some(SignatureUnit::new(",")),83//! close_delimiter: Some(SignatureUnit::new(")")),84//! close_name: None,85//! };86//!87//! // Create functions signatures88//! fn make_func_without_args() {89//! const SIG: FunctionSignature = make_signature!(90//! new fn(SIGNATURE_PREFERENCES),91//! );92//! let name = SIG.as_str();93//! similar_asserts::assert_eq!(name, "some_funk()");94//! }95//!96//! fn make_func_with_3_args() {97//! const SIG: FunctionSignature = make_signature!(98//! new fn(SIGNATURE_PREFERENCES),99//! (<u8>::SIGNATURE),100//! (<u8>::SIGNATURE),101//! (<Vec<u8>>::SIGNATURE),102//! );103//! let name = SIG.as_str();104//! similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");105//! }106//! ```1use core::str::from_utf8;107use core::str::from_utf8;2108109/// The maximum length of the signature.3pub const SIGNATURE_SIZE_LIMIT: usize = 256;110pub const SIGNATURE_SIZE_LIMIT: usize = 256;4111112/// Function signature formatting preferences.5#[derive(Debug)]113#[derive(Debug)]6pub struct SignaturePreferences {114pub struct SignaturePreferences {115 /// The name of the function before the list of parameters: `*some*(param1,param2)func`7 pub open_name: Option<SignatureUnit>,116 pub open_name: Option<SignatureUnit>,117 /// Opening separator: `some*(*param1,param2)func`8 pub open_delimiter: Option<SignatureUnit>,118 pub open_delimiter: Option<SignatureUnit>,119 /// Parameters separator: `some(param1*,*param2)func`9 pub param_delimiter: Option<SignatureUnit>,120 pub param_delimiter: Option<SignatureUnit>,121 /// Closinging separator: `some(param1,param2*)*func`10 pub close_delimiter: Option<SignatureUnit>,122 pub close_delimiter: Option<SignatureUnit>,123 /// The name of the function after the list of parameters: `some(param1,param2)*func*`11 pub close_name: Option<SignatureUnit>,124 pub close_name: Option<SignatureUnit>,12}125}13126127/// Constructs and stores the signature of the function.14#[derive(Debug)]128#[derive(Debug)]15pub struct FunctionSignature {129pub struct FunctionSignature {130 /// Storage for function signature.16 pub unit: SignatureUnit,131 pub unit: SignatureUnit,17 preferences: SignaturePreferences,132 preferences: SignaturePreferences,18}133}1913420impl FunctionSignature {135impl FunctionSignature {136 /// Start constructing the signature. It is written to the storage137 /// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].21 pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {138 pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {22 let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];139 let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];23 let mut dst_offset = 0;140 let mut dst_offset = 0;36 }153 }37 }154 }38155156 /// Add a function parameter to the signature. It is written to the storage157 /// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].39 pub const fn add_param(158 pub const fn add_param(40 signature: FunctionSignature,159 signature: FunctionSignature,41 param: SignatureUnit,160 param: SignatureUnit,55 }174 }56 }175 }57176177 /// Complete signature construction. It is written to the storage178 /// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].58 pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {179 pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {59 let mut dst = signature.unit.data;180 let mut dst = signature.unit.data;60 let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };181 let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };73 }194 }74 }195 }75196197 /// Represent the signature as `&str'.76 pub fn as_str(&self) -> &str {198 pub fn as_str(&self) -> &str {77 from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")199 from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")78 }200 }79}201}80202203/// Storage for the signature or its elements.81#[derive(Debug)]204#[derive(Debug)]82pub struct SignatureUnit {205pub struct SignatureUnit {206 /// Signature data.83 pub data: [u8; SIGNATURE_SIZE_LIMIT],207 pub data: [u8; SIGNATURE_SIZE_LIMIT],208 /// The actual size of the data.84 pub len: usize,209 pub len: usize,85}210}8621187impl SignatureUnit {212impl SignatureUnit {213 /// Create a signature from `&str'.88 pub const fn new(name: &'static str) -> SignatureUnit {214 pub const fn new(name: &'static str) -> SignatureUnit {89 let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];215 let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];90 let name = name.as_bytes();216 let name = name.as_bytes();98 }224 }99}225}100226227/// ### Macro to create signatures of types and functions.228///229/// Format for creating a type of signature:230/// ```ignore231/// make_signature!(new fixed("uint8")); // Simple type232/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type233/// ```234/// Format for creating a function of the function:235/// ```ignore236/// const SIG: FunctionSignature = make_signature!(237/// new fn(SIGNATURE_PREFERENCES),238/// (u8::SIGNATURE),239/// (<(u8,u8)>::SIGNATURE),240/// );241/// ```101#[macro_export]242#[macro_export]102#[allow(missing_docs)]103macro_rules! make_signature { // May be "define_signature"?243macro_rules! make_signature {104 (new fn($func:expr)$(,)+) => {244 (new fn($func:expr)$(,)+) => {105 {245 {106 let fs = FunctionSignature::new($func);246 let fs = FunctionSignature::new($func);283 assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));423 assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));284 }424 }285425286 // This test must NOT compile!426 // This test must NOT compile with "index out of bounds"!287 // #[test]427 // #[test]288 // fn over_max_size() {428 // fn over_max_size() {429 // assert_eq!(430 // <Vec<MaxSize>>::name(),289 // assert_eq!(<Vec<MaxSize>>::name(), "!".repeat(SIZE_LIMIT) + "[]");431 // "!".repeat(SIGNATURE_SIZE_LIMIT) + "[]"432 // );290 // }433 // }291434292 #[test]435 #[test]crates/evm-coder/src/lib.rsdiffbeforeafterboth15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617#![doc = include_str!("../README.md")]17#![doc = include_str!("../README.md")]18// #![deny(missing_docs)]19#![warn(missing_docs)]18#![deny(missing_docs)]20#![macro_use]19#![macro_use]21#![cfg_attr(not(feature = "std"), no_std)]20#![cfg_attr(not(feature = "std"), no_std)]22#[cfg(not(feature = "std"))]21#[cfg(not(feature = "std"))]94pub use evm_coder_procedural::solidity;93pub use evm_coder_procedural::solidity;95/// See [`solidity_interface`]94/// See [`solidity_interface`]96pub use evm_coder_procedural::weight;95pub use evm_coder_procedural::weight;97pub use const_format;98pub use sha3_const;96pub use sha3_const;9997100/// Derives [`ToLog`] for enum98/// Derives [`ToLog`] for enum385 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);383 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);386 }384 }387388 // #[test]389 // fn function_selector_generation_1() {390 // assert_eq!(391 // fn_selector!(transferFromCrossAccountToCrossAccount(392 // EthCrossAccount,393 // EthCrossAccount,394 // uint256395 // )),396 // 2543295963397 // );398 // }399385400 #[test]386 #[test]401 fn event_topic_generation() {387 fn event_topic_generation() {crates/evm-coder/tests/conditional_is.rsdiffbeforeafterboth1use evm_coder::{types::*, solidity_interface, execution::Result};1use evm_coder::{types::*, solidity_interface, execution::Result};2use evm_coder::{3 make_signature,4 custom_signature::{5 SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,6 },7 types::Signature,8};293pub struct Contract(bool);10pub struct Contract(bool);411crates/evm-coder/tests/generics.rsdiffbeforeafterboth161617use std::marker::PhantomData;17use std::marker::PhantomData;18use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};18use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};19use evm_coder::{20 make_signature,21 custom_signature::{22 SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,23 },24};192520pub struct Generic<T>(PhantomData<T>);26pub struct Generic<T>(PhantomData<T>);2127crates/evm-coder/tests/random.rsdiffbeforeafterboth17#![allow(dead_code)] // This test only checks that macros is not panicking17#![allow(dead_code)] // This test only checks that macros is not panicking181819use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};19use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};20use evm_coder::{21 make_signature,22 custom_signature::{23 SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,24 },25 types::Signature,26};202721pub struct Impls;28pub struct Impls;2229crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};17use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};18use evm_coder::{19 make_signature,20 custom_signature::{21 SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,22 },23 types::Signature,24};182519pub struct ERC20;26pub struct ERC20;2027tests/src/eth/base.test.tsdiffbeforeafterboth116 await checkInterface(helper, '0x780e9d63', true, true);116 await checkInterface(helper, '0x780e9d63', true, true);117 });117 });118118119 itEth('ERC721UniqueExtensions - 0x244543ee - support', async ({helper}) => {119 itEth('ERC721UniqueExtensions support', async ({helper}) => {120 await checkInterface(helper, '0x244543ee', true, true);120 expect(await contract(helper).methods.supportsInterface('0xb76006ac').call()).to.be.true;121 });121 });122122123 itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {123 itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {tests/src/eth/nonFungible.test.tsdiffbeforeafterboth410 });410 });411411412 itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {412 itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {413 const alice = privateKey('//Alice');414 const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});413 const collection = await helper.nft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});415414416 const owner = privateKey('//Bob');415 const owner = privateKey('//Bob');417 const spender = await helper.eth.createAccountWithBalance(alice, 100n);416 const spender = await helper.eth.createAccountWithBalance(donor, 100n);418 const receiver = privateKey('//Charlie');417 const receiver = privateKey('//Charlie');419418420 const token = await collection.mintToken(alice, {Substrate: owner.address});419 const token = await collection.mintToken(donor, {Substrate: owner.address});421420422 const address = helper.ethAddress.fromCollectionId(collection.collectionId);421 const address = helper.ethAddress.fromCollectionId(collection.collectionId);423 const contract = helper.ethNativeContract.collection(address, 'nft');422 const contract = helper.ethNativeContract.collection(address, 'nft');tests/src/eth/reFungible.test.tsdiffbeforeafterboth295 });295 });296296297 itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {297 itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {298 const alice = privateKey('//Alice');299 const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});298 const collection = await helper.rft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});300299301 const owner = privateKey('//Bob');300 const owner = privateKey('//Bob');302 const spender = await helper.eth.createAccountWithBalance(alice, 100n);301 const spender = await helper.eth.createAccountWithBalance(donor, 100n);303 const receiver = privateKey('//Charlie');302 const receiver = privateKey('//Charlie');304303305 const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});304 const token = await collection.mintToken(donor, 100n, {Substrate: owner.address});306305307 const address = helper.ethAddress.fromCollectionId(collection.collectionId);306 const address = helper.ethAddress.fromCollectionId(collection.collectionId);308 const contract = helper.ethNativeContract.collection(address, 'rft');307 const contract = helper.ethNativeContract.collection(address, 'rft');