stellar_axelar_std/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/// Return with an error if a condition is not met.
///
/// Simplifies the pattern of checking for a condition and returning with an error.
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $e:expr $(,)?) => {
        if !$cond {
            return Err($e);
        }
    };
}

// The following definitions are mostly intended to serve as pseudo-documentation within tests
// and help with convenience/clarity.

/// Assert that a [`Result`] is [`Ok`]
///
/// If the provided expresion evaulates to [`Ok`], then the
/// macro returns the value contained within the [`Ok`]. If
/// the [`Result`] is an [`Err`] then the macro will [`panic`]
/// with a message that includes the expression and the error.
///
/// This function was vendored from [assert_ok](https://docs.rs/assert_ok/1.0.2/assert_ok/).
#[macro_export]
macro_rules! assert_ok {
    ( $x:expr ) => {
        match $x {
            Ok(v) => v,
            Err(e) => {
                panic!("Error calling {}: {:?}", stringify!($x), e);
            }
        }
    };
}

/// Assert that a [`Result`] is [`Err`] and matches an error variant
#[macro_export]
macro_rules! assert_err {
    ( $x:expr, $expected:pat ) => {
        match $x {
            Err(e) => {
                if !matches!(e, $expected) {
                    panic!("Expected error {}: {:?}", stringify!($expected), e);
                }
            }
            Ok(v) => {
                panic!("Expected error {}, found {:?}", stringify!($expected), v)
            }
        }
    };
}

/// Assert that a [`Result`] from a contract call is [`Err`] and matches an error variant
///
/// `given` corresponds to the return type from `try_*` functions in Soroban.
/// For the assert to succeed, the function needs to fail and successfully pass
/// down the intended error type. So, the parameters would be in the form:
///
/// given: `Err(Ok(ContractError))`
/// expected: `ContractError`
///
/// Putting it together in a function call:
///
/// `assert_contract_err(client.try_fun(...), ContractError);`
#[macro_export]
macro_rules! assert_contract_err {
    ($given:expr, $expected:expr) => {
        match $given {
            Ok(v) => panic!(
                "Expected error {:?}, got {:?} instead",
                stringify!($expected),
                v
            ),
            Err(e) => match e {
                Err(e) => panic!("Unexpected error {e:?}"),
                Ok(v) if v != $expected => {
                    panic!("Expected error {:?}, got {:?} instead", $expected, v)
                }
                _ => (),
            },
        }
    };
}

/// Assert that an [`Option`] is [`Some`]
///
/// If the provided expresion evaulates to [`Some`], then the
/// macro returns the value contained within the [`Some`]. If
/// the [`Option`] is [`None`] then the macro will [`panic`]
/// with a message that includes the expression
#[macro_export]
macro_rules! assert_some {
    ( $x:expr ) => {
        match $x {
            core::option::Option::Some(s) => s,
            core::option::Option::None => {
                panic!("Expected value when calling {}, got None", stringify!($x));
            }
        }
    };
}

/// Assert that a contract call with authentication succeeds
///
/// This macro is used to test contract calls that require authentication. It mocks the authentication
/// for the specified caller and executes the contract call. If the call fails or doesn't require the authentication,
/// the macro will panic with an error message.
///
/// # Example
///
/// ```rust,ignore
/// # use soroban_sdk::{Address, Env, contract, contractimpl};
/// # use soroban_sdk::testutils::Address as _;
/// # use stellar_axelar_std::assert_auth;
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///    pub fn set_value(env: &Env, caller: Address, value: u32) {
///        caller.require_auth();
///    }
/// }
///
/// # let env = Env::default();
/// # let caller = Address::generate(&env);
/// # let contract_id = env.register(Contract, ());
/// # let client = ContractClient::new(&env, &contract_id);
///
/// assert_auth!(caller, client.set_value(&caller, &42));
/// ```
#[macro_export]
macro_rules! assert_auth {
    ($caller:expr, $client:ident . $method:ident ( $($arg:expr),* $(,)? )) => {{
        use soroban_sdk::IntoVal;

        // Evaluate the expression before the method call.
        // If the expression itself called the contract, e.g. client.owner(),
        // then this will prevent events from being reset when checking the auth after the call.
        let caller = $caller.clone();

        // Paste is used to concatenate the method name with the `try_` prefix
        paste::paste! {
        let result = $client
            .mock_auths(&[$crate::mock_auth!(
                $client.env,
                caller,
                $client.$method($($arg),*)
            )])
            .[<try_ $method>]($($arg),*);
        }

        let result = match result {
            Ok(outer) => {
                match outer {
                    Ok(inner) => inner,
                    Err(err) => panic!("Expected Ok result, but got an error {:?}", err),
                }
            }
            Err(err) => panic!("Expected Ok result, but got an error {:?}", err),
        };

        assert_eq!(
            $client.env.auths(),
            std::vec![(
                caller,
                soroban_sdk::testutils::AuthorizedInvocation {
                    function: soroban_sdk::testutils::AuthorizedFunction::Contract((
                        $client.address.clone(),
                        soroban_sdk::Symbol::new(&$client.env, stringify!($method)),
                        ($($arg.clone(),)*).into_val(&$client.env)
                    )),
                    sub_invocations: std::vec![]
                }
            )]
        );

        result
    }};
}

#[macro_export]
macro_rules! assert_auth_err {
    ($caller:expr, $client:ident . $method:ident ( $($arg:expr),* $(,)? )) => {{
        use soroban_sdk::xdr::{ScError, ScErrorCode, ScVal};

        let caller = $caller.clone();

        paste::paste! {
        let call_result = $client
            .mock_auths(&[$crate::mock_auth!(
                $client.env,
                caller,
                $client.$method($($arg),*)
            )])
            .[<try_ $method>]($($arg),*);
        }
        match call_result {
            Err(_) => {
                let val = ScVal::Error(ScError::Context(ScErrorCode::InvalidAction));
                match ScError::try_from(val) {
                    Ok(ScError::Context(ScErrorCode::InvalidAction)) => {}
                    _ => panic!("Expected ScErrorCode::InvalidAction"),
                }
            }
            Ok(_) => panic!("Expected error, but got Ok result."),
        }
    }};
}

#[macro_export]
macro_rules! mock_auth {
    (
        $env:expr,
        $caller:expr,
        $client:ident . $method:ident ( $($arg:expr),* $(,)? ),
        $sub_invokes:expr
    ) => {{
        use soroban_sdk::IntoVal;

        soroban_sdk::testutils::MockAuth {
            address: &$caller,
            invoke: &soroban_sdk::testutils::MockAuthInvoke {
                contract: &$client.address,
                fn_name: &stringify!($method).replace("try_", ""),
                args: ($($arg.clone(),)*).into_val(&$env),
                sub_invokes: $sub_invokes,
            },
        }
    }};
    (
        $env:expr,
        $caller:expr,
        $client:ident . $method:ident ( $($arg:expr),* $(,)? )
    ) => {{
        $crate::mock_auth!($env, $caller, $client.$method($($arg),*), &[])
    }};
}