ethcontract_mock/
utils.rs

1//! Convenience utilities for tests.
2
3use ethcontract::{Account, Address, PrivateKey};
4
5/// Generate public address by hashing the given string.
6///
7/// # Safety
8///
9/// This function is intended for tests and should not be used in production.
10///
11/// # Examples
12///
13/// ```
14/// # use ethcontract_mock::utils::address_for;
15/// let address = address_for("Alice");
16/// # assert_eq!(address, "0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea".parse().unwrap());
17/// ```
18pub fn address_for(who: &str) -> Address {
19    account_for(who).address()
20}
21
22/// Shortcut for [`address_for`]`("Alice")`.
23///
24/// # Examples
25///
26/// ```
27/// # use ethcontract_mock::utils::address;
28/// let address = address();
29/// # assert_eq!(address, "0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea".parse().unwrap());
30/// ```
31pub fn address() -> Address {
32    address_for("Alice")
33}
34
35/// Generate a private key by hashing the given string.
36///
37/// # Safety
38///
39/// This function is intended for tests and should not be used in production.
40///
41/// # Examples
42///
43/// ```
44/// # use ethcontract_mock::utils::account_for;
45/// let account = account_for("Bob");
46/// # assert_eq!(account.address(), "0x4dba461ca9342f4a6cf942abd7eacf8ae259108c".parse().unwrap());
47/// ```
48pub fn account_for(who: &str) -> Account {
49    use ethcontract::web3::signing::keccak256;
50    Account::Offline(
51        PrivateKey::from_raw(keccak256(who.as_bytes())).unwrap(),
52        None,
53    )
54}
55
56/// Shortcut for [`account_for`]`("Alice")`.
57///
58/// # Examples
59///
60/// ```
61/// # use ethcontract_mock::utils::account;
62/// let account = account();
63/// # assert_eq!(account.address(), "0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea".parse().unwrap());
64/// ```
65pub fn account() -> Account {
66    account_for("Alice")
67}
68
69/// Deploy a mocked version of a generated contract.
70///
71/// # Parameters
72///
73/// - `mock`: a [Mock] instance.
74/// - `contract` type of the contract.
75///
76/// # Examples
77///
78/// ```
79/// # use ethcontract_mock::{Mock, mock_contract};
80/// # ethcontract::contract!(
81/// #     "../examples/truffle/build/contracts/IERC20.json",
82/// #     contract = IERC20 as ERC20,
83/// # );
84/// # fn main() {
85/// let mock = Mock::new(1234);
86/// let (contract, instance) = mock_contract!(mock, ERC20);
87/// # }
88/// ```
89///
90/// [Mock]: crate::Mock
91#[macro_export]
92macro_rules! mock_contract {
93    ($mock:ident, $contract:ident) => {{
94        let mock = $mock;
95        let contract = mock.deploy($contract::raw_contract().abi.clone());
96        let instance = $contract::at(&contract.web3(), contract.address());
97
98        (contract, instance)
99    }};
100}