Skip to content

Commit

Permalink
reviews
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Jul 4, 2023
1 parent 2a22aa8 commit 2c11010
Show file tree
Hide file tree
Showing 15 changed files with 343 additions and 72 deletions.
1 change: 0 additions & 1 deletion crates/dyn-abi/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,6 @@ impl DynSolValue {
/// # Examples
///
/// ```ignore (pseudo-code)
///
/// // Encoding for function foo(address)
/// DynSolValue::Address(_).encode_params();
///
Expand Down
13 changes: 0 additions & 13 deletions crates/sol-macro/src/expand/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,10 +401,6 @@ fn generate_variant_methods((variant, ty): (&Ident, &Ident)) -> TokenStream {
"Returns a mutable reference to the inner [`{ty}`] if `self` matches [`{name}`](Self::{name})."
);

let try_into_variant = format_ident!("try_into_{name_snake}");
let try_into_variant_doc =
format!("Unwraps the inner [`{ty}`] if `self` matches [`{name}`](Self::{name}).");

quote! {
#[doc = #is_variant_doc]
#[inline]
Expand All @@ -429,14 +425,5 @@ fn generate_variant_methods((variant, ty): (&Ident, &Ident)) -> TokenStream {
_ => ::core::option::Option::None,
}
}

#[doc = #try_into_variant_doc]
#[inline]
pub const fn #try_into_variant(self) -> ::core::result::Result<#ty, Self> {
match self {
Self::#variant(inner) => ::core::result::Result::Ok(inner),
_ => ::core::result::Result::Err(self),
}
}
}
}
2 changes: 1 addition & 1 deletion crates/sol-macro/src/expand/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ fn expand_from_into_tuples<P>(name: &Ident, fields: &Parameters<P>) -> TokenStre
#[doc(hidden)]
impl ::core::convert::From<UnderlyingRustTuple<'_>> for #name {
fn from(tuple: UnderlyingRustTuple<'_>) -> Self {
#name {
Self {
#(#names2: tuple.#idxs),*
}
}
Expand Down
12 changes: 4 additions & 8 deletions crates/sol-macro/src/expand/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,6 @@ pub(super) fn expand(cx: &ExpCtxt<'_>, s: &ItemStruct) -> Result<TokenStream> {

#[allow(non_camel_case_types, non_snake_case, clippy::style)]
const _: () = {
use ::alloy_sol_types::private::*;

#convert

#[automatically_derived]
Expand All @@ -118,7 +116,7 @@ pub(super) fn expand(cx: &ExpCtxt<'_>, s: &ItemStruct) -> Result<TokenStream> {
#tokenize_impl
}

fn eip712_encode_type() -> Cow<'static, str> {
fn eip712_encode_type() -> ::alloy_sol_types::private::Cow<'static, str> {
#encode_type_impl.into()
}

Expand All @@ -131,19 +129,17 @@ pub(super) fn expand(cx: &ExpCtxt<'_>, s: &ItemStruct) -> Result<TokenStream> {
impl ::alloy_sol_types::EventTopic for #name {
#[inline]
fn topic_preimage_length(rust: &Self::RustType) -> usize {
let b = rust.borrow();
0usize
#(
+ <#field_types as ::alloy_sol_types::EventTopic>::topic_preimage_length(&b.#field_names)
+ <#field_types as ::alloy_sol_types::EventTopic>::topic_preimage_length(&rust.#field_names)
)*
}

#[inline]
fn encode_topic_preimage(rust: &Self::RustType, out: &mut Vec<u8>) {
let b = rust.borrow();
out.reserve(<Self as ::alloy_sol_types::EventTopic>::topic_preimage_length(b));
out.reserve(<Self as ::alloy_sol_types::EventTopic>::topic_preimage_length(rust));
#(
<#field_types as ::alloy_sol_types::EventTopic>::encode_topic_preimage(&b.#field_names, out);
<#field_types as ::alloy_sol_types::EventTopic>::encode_topic_preimage(&rust.#field_names, out);
)*
}

Expand Down
2 changes: 1 addition & 1 deletion crates/sol-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ trybuild = "1.0"
[features]
default = ["std"]
std = ["alloy-primitives/std", "hex/std", "serde?/std"]
sol-json = ["alloy-sol-macro/json"]
json = ["alloy-sol-macro/json"]
eip712-serde = ["dep:serde", "serde?/alloc", "alloy-primitives/serde"]
11 changes: 11 additions & 0 deletions crates/sol-types/tests/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,15 @@
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");

macro_rules! feature_tests {
($($f:literal),* $(,)?) => {$(
#[cfg(feature = $f)]
t.compile_fail(concat!("tests/ui/feature/", $f, "/*.rs"));
#[cfg(not(feature = $f))]
t.compile_fail(concat!("tests/ui/feature/not(", $f, ")/*.rs"));
)*};
}

feature_tests!("json");
}
2 changes: 1 addition & 1 deletion crates/sol-types/tests/doctests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ mod doctests {
mod contracts;
mod events;
mod function_like;
#[cfg(feature = "sol-json")]
#[cfg(feature = "json")]
mod json;
mod structs;
mod types;
Expand Down
196 changes: 161 additions & 35 deletions crates/sol-types/tests/sol.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,40 @@
use alloy_primitives::{keccak256, Address, U256};
use alloy_sol_types::{sol, SolCall, SolError, SolType};

sol! {
struct MyStruct {
uint256 a;
bytes32 b;
address[] c;
#[test]
fn e2e() {
sol! {
struct MyStruct {
uint256 a;
bytes32 b;
address[] c;
}
}
}

// Works only outside of function scope due to rust import rules
sol! {
struct MyStruct2 {
MyStruct a;
bytes32 b;
address[] c;
sol! {
struct MyStruct2 {
MyStruct a;
bytes32 b;
address[] c;
}
}
}

// This works
type MyTuple = sol! {
(MyStruct, bytes32)
};
type MyTuple = sol! {
(MyStruct, bytes32)
};

// This works
type LateBinding<A> = sol! {
(A[], address)
};
type LateBinding<A> = sol! {
(A[], address)
};

// testcase for something i messed up earlier :)
type NestedArray = sol! {
bool[2][]
};
type NestedArray = sol! {
bool[2][]
};

sol! {
type MyValueType is uint256;
}
sol! {
type MyValueType is uint256;
}

#[test]
fn test_sol() {
<sol!(bool)>::hex_encode_single(&true);

let a = MyStruct {
Expand Down Expand Up @@ -146,13 +142,143 @@ fn error() {
assert_eq!(e.encoded_size(), 32);
}

sol! {
interface WETH {
function deposit() external payable;
// https://github.com/alloy-rs/core/issues/158
#[test]
fn empty_call() {
sol! {
interface WETH {
function deposit() external payable;
}
}
use WETH::depositCall;

assert_eq!(depositCall {}.encode(), depositCall::SELECTOR);
assert_eq!(depositCall {}.encoded_size(), 0);
let mut out = vec![];
depositCall {}.encode_raw(&mut out);
assert!(out.is_empty());

let depositCall {} = depositCall::decode(&depositCall::SELECTOR, true).unwrap();
let depositCall {} = depositCall::decode_raw(&[], true).unwrap();
}

#[test]
fn empty_call() {
WETH::depositCall::decode(&WETH::depositCall::SELECTOR, true).expect("it should work");
fn abigen_sol() {
sol!("../syn-solidity/tests/contracts/Multicall.sol");

sol! {
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.12 <0.9.0;

interface IMulticall3_2 {
struct Call {
address target;
bytes callData;
}

struct Call3 {
address target;
bool allowFailure;
bytes callData;
}

struct Call3Value {
address target;
bool allowFailure;
uint256 value;
bytes callData;
}

struct Result {
bool success;
bytes returnData;
}

function aggregate(Call[] calldata calls) external payable returns (uint256 blockNumber, bytes[] memory returnData);

function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);

function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData);

function blockAndAggregate(
Call[] calldata calls
) external payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);

function getBasefee() external view returns (uint256 basefee);

function getBlockHash(uint256 blockNumber) external view returns (bytes32 blockHash);

function getBlockNumber() external view returns (uint256 blockNumber);

function getChainId() external view returns (uint256 chainid);

function getCurrentBlockCoinbase() external view returns (address coinbase);

function getCurrentBlockDifficulty() external view returns (uint256 difficulty);

function getCurrentBlockGasLimit() external view returns (uint256 gaslimit);

function getCurrentBlockTimestamp() external view returns (uint256 timestamp);

function getEthBalance(address addr) external view returns (uint256 balance);

function getLastBlockHash() external view returns (bytes32 blockHash);

function tryAggregate(
bool requireSuccess,
Call[] calldata calls
) external payable returns (Result[] memory returnData);

function tryBlockAndAggregate(
bool requireSuccess,
Call[] calldata calls
) external payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);
}
}

use IMulticall3 as M1;
use IMulticall3_2 as M2;

macro_rules! assert_signatures {
($($t:ident),+ $(,)?) => {$(
assert_eq!(
M1::$t::SIGNATURE,
M2::$t::SIGNATURE,
concat!("signature mismatch for ", stringify!($t))
);
assert_eq!(
M1::$t::SELECTOR,
M2::$t::SELECTOR,
concat!("selector mismatch for ", stringify!($t))
);
)+};
}

assert_signatures!(
aggregate3Call,
aggregate3ValueCall,
blockAndAggregateCall,
getBasefeeCall,
getBlockHashCall,
getBlockNumberCall,
getChainIdCall,
getCurrentBlockCoinbaseCall,
getCurrentBlockDifficultyCall,
getCurrentBlockGasLimitCall,
getCurrentBlockTimestampCall,
getEthBalanceCall,
getLastBlockHashCall,
tryAggregateCall,
tryBlockAndAggregateCall,
);
}

#[test]
#[cfg(feature = "json")]
fn abigen_json() {
sol!(Contract, "../json-abi/tests/abi/LargeArray.json");
assert_eq!(
Contract::callWithLongArrayCall::SIGNATURE,
"callWithLongArray(uint64[128])"
);
}
13 changes: 13 additions & 0 deletions crates/sol-types/tests/ui/features/json/abigen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use alloy_sol_types::sol;

sol!(EmptyStr, "");

sol!(PathDoesNotExist, "???");
sol!("pragma solidity ^0.8.0");
sol!("pragma solidity ^0.8.0;");

sol!(NoJsonFeature1, "{}");
sol!(NoJsonFeature2, "{ \"abi\": [] }");
sol!(NoJsonFeature3, "[]");

fn main() {}
29 changes: 29 additions & 0 deletions crates/sol-types/tests/ui/features/json/abigen.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
error: empty input is not allowed
--> tests/ui/json/abigen.rs:3:16
|
3 | sol!(EmptyStr, "");
| ^^

error: failed to canonicalize path: No such file or directory (os error 2)
--> tests/ui/json/abigen.rs:5:24
|
5 | sol!(PathDoesNotExist, "???");
| ^^^^^

error: failed to canonicalize path: No such file or directory (os error 2)
--> tests/ui/json/abigen.rs:6:6
|
6 | sol!("pragma solidity ^0.8.0");
| ^^^^^^^^^^^^^^^^^^^^^^^^

error: failed to canonicalize path: No such file or directory (os error 2)
--> tests/ui/json/abigen.rs:7:6
|
7 | sol!("pragma solidity ^0.8.0;");
| ^^^^^^^^^^^^^^^^^^^^^^^^^

error: invalid JSON: missing field `abi` at line 1 column 2
--> tests/ui/json/abigen.rs:9:22
|
9 | sol!(NoJsonFeature1, "{}");
| ^^^^
13 changes: 13 additions & 0 deletions crates/sol-types/tests/ui/features/not(json)/abigen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use alloy_sol_types::sol;

sol!(EmptyStr, "");

sol!(PathDoesNotExist, "???");
sol!("pragma solidity ^0.8.0");
sol!("pragma solidity ^0.8.0;");

sol!(NoJsonFeature1, "{}");
sol!(NoJsonFeature2, "{ \"abi\": [] }");
sol!(NoJsonFeature3, "[]");

fn main() {}
Loading

0 comments on commit 2c11010

Please sign in to comment.