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

difftreelog

misk: Documentation, test fixes, refactor

Trubnikov Sergey2022-10-27parent: #6afd9fe.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
1095source = "registry+https://github.com/rust-lang/crates.io-index"1095source = "registry+https://github.com/rust-lang/crates.io-index"
1096checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"1096checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
1097
1098[[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]
1106
1107[[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]
11171097
1118[[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)",
modifiedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
5edition = "2021"5edition = "2021"
66
7[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 selectors
11# sha3 = "0.10.1"10# sha3 = "0.10.1"
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
20// 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.html
2222
23use 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;
modifiedcrates/evm-coder/src/custom_signature.rsdiffbeforeafterboth
1//! # A module for custom signature support.
2//!
3//! ## Overview
4//! This module allows you to create arbitrary signatures for types and functions in compile time.
5//!
6//! ### Type signatures
7//! 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//! #### Example
10//! ```
11//! use std::str::from_utf8;
12//! use evm_coder::make_signature;
13//! use evm_coder::custom_signature::{
14//! SignatureUnit,
15//! SIGNATURE_SIZE_LIMIT
16//! };
17//!
18//! // Create trait for our signature
19//! 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 types
28//! 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 signatures
50//! To create a function signature, the macro [`make_signature`] is also used, which accepts
51//! settings for the function format [`SignaturePreferences`] and function parameters [`SignatureUnit`]
52//! #### Example
53//! ```
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 signature
62//! 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 types
71//! 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 settings
79//! 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 signatures
88//! 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;
2108
109/// The maximum length of the signature.
3pub const SIGNATURE_SIZE_LIMIT: usize = 256;110pub const SIGNATURE_SIZE_LIMIT: usize = 256;
4111
112/// 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}
13126
127/// 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}
19134
20impl FunctionSignature {135impl FunctionSignature {
136 /// Start constructing the signature. It is written to the storage
137 /// [`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 }
38155
156 /// Add a function parameter to the signature. It is written to the storage
157 /// `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 }
57176
177 /// Complete signature construction. It is written to the storage
178 /// [`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 }
75196
197 /// 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}
80202
203/// 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}
86211
87impl 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}
100226
227/// ### Macro to create signatures of types and functions.
228///
229/// Format for creating a type of signature:
230/// ```ignore
231/// make_signature!(new fixed("uint8")); // Simple type
232/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
233/// ```
234/// Format for creating a function of the function:
235/// ```ignore
236/// 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 }
285425
286 // 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 // }
291434
292 #[test]435 #[test]
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
15// 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/>.
1616
17#![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;
9997
100/// Derives [`ToLog`] for enum98/// Derives [`ToLog`] for enum
385 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);383 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
386 }384 }
387
388 // #[test]
389 // fn function_selector_generation_1() {
390 // assert_eq!(
391 // fn_selector!(transferFromCrossAccountToCrossAccount(
392 // EthCrossAccount,
393 // EthCrossAccount,
394 // uint256
395 // )),
396 // 2543295963
397 // );
398 // }
399385
400 #[test]386 #[test]
401 fn event_topic_generation() {387 fn event_topic_generation() {
modifiedcrates/evm-coder/tests/conditional_is.rsdiffbeforeafterboth
1use 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};
29
3pub struct Contract(bool);10pub struct Contract(bool);
411
modifiedcrates/evm-coder/tests/generics.rsdiffbeforeafterboth
1616
17use 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};
1925
20pub struct Generic<T>(PhantomData<T>);26pub struct Generic<T>(PhantomData<T>);
2127
modifiedcrates/evm-coder/tests/random.rsdiffbeforeafterboth
17#![allow(dead_code)] // This test only checks that macros is not panicking17#![allow(dead_code)] // This test only checks that macros is not panicking
1818
19use 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};
2027
21pub struct Impls;28pub struct Impls;
2229
modifiedcrates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth
15// 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/>.
1616
17use 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};
1825
19pub struct ERC20;26pub struct ERC20;
2027
modifiedtests/src/eth/base.test.tsdiffbeforeafterboth
116 await checkInterface(helper, '0x780e9d63', true, true);116 await checkInterface(helper, '0x780e9d63', true, true);
117 });117 });
118118
119 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 });
122122
123 itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {123 itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
410 });410 });
411411
412 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'});
415414
416 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');
419418
420 const token = await collection.mintToken(alice, {Substrate: owner.address});419 const token = await collection.mintToken(donor, {Substrate: owner.address});
421420
422 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');
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
295 });295 });
296296
297 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'});
300299
301 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');
304303
305 const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});304 const token = await collection.mintToken(donor, 100n, {Substrate: owner.address});
306305
307 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');