stellar-macros 0.4.1

Macros for Stellar contracts.
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
mod access_control;
mod default_impl_macro;
mod helpers;
mod pausable;
mod upgradeable;

use access_control::{generate_any_role_check, generate_role_check};
use default_impl_macro::generate_default_impl;
use helpers::*;
use pausable::generate_pause_check;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, ItemFn};
use upgradeable::*;

/* DEFAULT_IMPL_MACRO */

/// Generates the missing default implementations for the traits provided by
/// OpenZeppelin Stellar library.
///
/// `#[contractimpl]` macro requires all the default implementations to be
/// provided under the code block:
///
/// ```ignore
/// #[contractimpl]
/// impl Trait for MyContract {
///     /*
///         The client generated by the `#[contractimpl]` macro will have access only
///         to the methods specified in here. Which means, if you do not provide the
///         default implementations of the methods, the client generated by the
///         `#[contractimpl]` macro won't have access to those methods.
///
///         This is due to how macros work in Rust. They cannot access the default
///         implementations of the methods of this trait, since they are not in the
///         scope of the macro.
///
///         To overcome this, we provide a macro for our traits, that generates the
///         missing default implementations for the methods of the trait, so
///         you can only focus on the overrides, and leave the default implementations
///         out as per usual.
///     */
/// }
/// ```
///
/// # Example:
///
/// ```ignore
/// #[default_impl] // IMPORTANT: place this above `#[contractimpl]`
/// #[contractimpl]
/// impl NonFungibleToken for MyContract {
///     /* your overrides here */
/// }
/// ```
///
/// This macro works for the following traits:
/// - `FungibleToken`
/// - `FungibleBurnable`
/// - `NonFungibleToken`
/// - `NonFungibleBurnable`
/// - `NonFungibleEnumerable`
/// - `AccessControl`
/// - `Ownable`
///
/// # Notes
///
/// This macro does not support the below traits on purpose:
/// - `FungibleAllowList`
/// - `FungibleBlockList`
/// - `NonFungibleRoyalties`
///
/// Because, there are no default implementation to enforce how the
/// authorization should be configured. Not providing a default implementation
/// for these traits is a reminder for the implementor to provide the
/// authorization logic for these traits.
#[proc_macro_attribute]
pub fn default_impl(attrs: TokenStream, item: TokenStream) -> TokenStream {
    assert!(attrs.is_empty(), "This macro does not accept any arguments");

    generate_default_impl(item)
}

/* ACCESS CONTROL MACROS */

/// A procedural macro that retrieves the admin from storage and requires
/// authorization from the admin before executing the function body.
///
/// # Usage
///
/// ```rust
/// #[only_admin]
/// pub fn restricted_function(e: &Env, other_param: u32) {
///     // Function body
/// }
/// ```
///
/// This will expand to:
///
/// ```rust
/// pub fn restricted_function(e: &Env, other_param: u32) {
///     stellar_access::access_control::enforce_admin_auth(e);
///     // Function body
/// }
/// ```
#[proc_macro_attribute]
pub fn only_admin(attrs: TokenStream, input: TokenStream) -> TokenStream {
    assert!(attrs.is_empty(), "This macro does not accept any arguments");

    let input_fn = parse_macro_input!(input as ItemFn);

    // Generate the function with the admin authorization check
    let auth_check_path = quote! { stellar_access::access_control::enforce_admin_auth };
    let expanded = generate_auth_check(&input_fn, auth_check_path);

    TokenStream::from(expanded)
}

/// A procedural macro that ensures the parameter has the specified role.
///
/// # Security Warning
///
/// **IMPORTANT**: This macro checks role membership but does NOT enforce
/// authorization. This design prevents duplicate `require_auth()` calls which
/// would cause panics in Stellar contracts. Use this macro when:
///
/// 1. Your function already contains a `require_auth()` call
/// 2. You need additional role-based access control
///
/// If you need both role checking AND authorization, use `#[only_role]`
/// instead.
///
/// # Usage
///
/// ```rust
/// #[has_role(account, "minter")]
/// pub fn mint_tokens(e: &Env, amount: u32, account: Address) {
///     // Function body
/// }
/// ```
///
/// This will expand to:
///
/// ```rust
/// pub fn mint_tokens(e: &Env, amount: u32, account: Address) {
///     stellar_access::access_control::ensure_role(
///         e,
///         &account,
///         &soroban_sdk::Symbol::new(e, "minter"),
///     );
///     // Function body
/// }
/// ```
#[proc_macro_attribute]
pub fn has_role(args: TokenStream, input: TokenStream) -> TokenStream {
    generate_role_check(args, input, false)
}

/// A procedural macro that ensures the parameter has the specified role and
/// requires authorization.
///
/// **IMPORTANT**: This macro both checks role membership AND enforces
/// authorization. Be aware that in Stellar contracts, duplicate
/// `require_auth()` calls for the same account will cause panics. If your
/// function already contains a `require_auth()` call for the same account, use
/// `#[has_role]` instead to avoid duplicate authorization checks.
///
/// # Usage
///
/// ```rust
/// #[only_role(account, "minter")]
/// pub fn mint_tokens(e: &Env, amount: u32, account: Address) {
///     // Function body
/// }
/// ```
///
/// This will expand to:
///
/// ```rust
/// pub fn mint_tokens(e: &Env, amount: u32, account: Address) {
///     stellar_access::access_control::ensure_role(
///         e,
///         &account,
///         &soroban_sdk::Symbol::new(e, "minter"),
///     );
///     account.require_auth();
///     // Function body
/// }
/// ```
#[proc_macro_attribute]
pub fn only_role(args: TokenStream, input: TokenStream) -> TokenStream {
    generate_role_check(args, input, true)
}

/// A procedural macro that ensures the parameter has any of the specified
/// roles.
///
/// # Security Warning
///
/// **IMPORTANT**: This macro checks role membership but does NOT enforce
/// authorization. This design prevents duplicate `require_auth()` calls which
/// would cause panics in Stellar contracts. Use this macro when:
///
/// 1. Your function already contains a `require_auth()` call
/// 2. You need additional role-based access control
///
/// If you need both role checking AND authorization, use `#[only_any_role]`
/// instead.
///
/// # Usage
///
/// ```rust
/// #[has_any_role(account, ["minter", "admin", "operator"])]
/// pub fn manage_tokens(e: &Env, amount: u32, account: Address) {
///     // Function body
/// }
/// ```
///
/// This will expand to code that checks if the account has any of the specified
/// roles.
#[proc_macro_attribute]
pub fn has_any_role(args: TokenStream, input: TokenStream) -> TokenStream {
    generate_any_role_check(args, input, false)
}

/// A procedural macro that ensures the parameter has any of the specified roles
/// and requires authorization.
///
/// **IMPORTANT**: This macro both checks role membership AND enforces
/// authorization. Be aware that in Stellar contracts, duplicate
/// `require_auth()` calls for the same account will cause panics. If your
/// function already contains a `require_auth()` call for the same account, use
/// `#[has_any_role]` instead to avoid duplicate authorization checks.
///
/// # Usage
///
/// ```rust
/// #[only_any_role(account, ["minter", "admin", "operator"])]
/// pub fn manage_tokens(e: &Env, amount: u32, account: Address) {
///     // Function body
/// }
/// ```
///
/// This will expand to code that checks if the account has any of the specified
/// roles and requires authorization from the account.
#[proc_macro_attribute]
pub fn only_any_role(args: TokenStream, input: TokenStream) -> TokenStream {
    generate_any_role_check(args, input, true)
}

/// A procedural macro that retrieves the owner from storage and requires
/// authorization from the owner before executing the function body.
///
/// # Usage
///
/// ```rust
/// #[only_owner]
/// pub fn restricted_function(e: &Env, other_param: u32) {
///     // Function body
/// }
/// ```
///
/// This will expand to:
///
/// ```rust
/// pub fn restricted_function(e: &Env, other_param: u32) {
///     let owner: soroban_sdk::Address =
///         e.storage().instance().get(&stellar_access::ownable::OwnableStorageKey::Owner).unwrap();
///     owner.require_auth();
///     // Function body
/// }
/// ```
#[proc_macro_attribute]
pub fn only_owner(attrs: TokenStream, input: TokenStream) -> TokenStream {
    assert!(attrs.is_empty(), "This macro does not accept any arguments");

    let input_fn = parse_macro_input!(input as ItemFn);

    // Generate the function with the owner authorization check
    let auth_check_path = quote! { stellar_access::ownable::enforce_owner_auth };
    let expanded = generate_auth_check(&input_fn, auth_check_path);

    TokenStream::from(expanded)
}

/// Adds a pause check at the beginning of the function that ensures the
/// contract is not paused.
///
/// This macro will inject a `when_not_paused` check at the start of the
/// function body. If the contract is paused, the function will return early
/// with a panic.
///
/// # Requirement:
///
/// - The first argument of the decorated function must be of type `Env` or
///   `&Env`
///
/// # Example:
///
/// ```ignore
/// #[when_not_paused]
/// pub fn my_function(env: &Env) {
///     // This code will only execute if the contract is not paused
/// }
/// ```
#[proc_macro_attribute]
pub fn when_not_paused(attrs: TokenStream, item: TokenStream) -> TokenStream {
    assert!(attrs.is_empty(), "This macro does not accept any arguments");

    generate_pause_check(item, "when_not_paused")
}

/* PAUSABLE MACROS */

/// Adds a pause check at the beginning of the function that ensures the
/// contract is paused.
///
/// This macro will inject a `when_paused` check at the start of the function
/// body. If the contract is not paused, the function will return early with a
/// panic.
///
/// # Requirement:
///
/// - The first argument of the decorated function must be of type `Env` or
///   `&Env`
///
/// # Example:
///
/// ```ignore
/// #[when_paused]
/// pub fn my_function(env: &Env) {
///     // This code will only execute if the contract is paused
/// }
/// ```
#[proc_macro_attribute]
pub fn when_paused(attrs: TokenStream, item: TokenStream) -> TokenStream {
    assert!(attrs.is_empty(), "This macro does not accept any arguments");

    generate_pause_check(item, "when_paused")
}

/* UPGRADEABLE MACROS */

/// 1. Derives `Upgradeable` a) implements the interface; requires only the auth
///    to be defined b) sets wasm version by taking the version from Cargo.toml
///
/// 2. Derives `UpgradeableMigratable` when both an upgrade and a migration are
///    needed a) implements the interface; requires the auth and the migration
///    logic to be defined b) sets wasm version by taking the version from
///    Cargo.toml
///
/// Example for upgrade only:
/// ```rust,ignore
/// #[derive(Upgradeable)]
/// #[contract]
/// pub struct ExampleContract;
///
/// impl UpgradeableInternal for ExampleContract {
///     fn _require_auth(e: &Env, operator: &Address) {
///         operator.require_auth();
///         let owner = e.storage().instance().get::<_, Address>(&OWNER).unwrap();
///         if *operator != owner {
///             panic_with_error!(e, ExampleContractError::Unauthorized)
///         }
///     }
/// }
/// ```
///
/// Example for upgrade and migration:
/// ```rust,ignore
/// #[contracttype]
/// pub struct Data {
///     pub num1: u32,
///     pub num2: u32,
/// }
///
/// #[derive(UpgradeableMigratable)]
/// #[contract]
/// pub struct ExampleContract;
///
///
/// impl UpgradeableMigratableInternal for ExampleContract {
///     type MigrationData = Data;
///
///     fn _require_auth(e: &Env, operator: &Address) {
///         operator.require_auth();
///         let owner = e.storage().instance().get::<_, Address>(&OWNER).unwrap();
///         if *operator != owner {
///             panic_with_error!(e, ExampleContractError::Unauthorized)
///         }
///     }
///
///     fn _migrate(e: &Env, data: &Self::MigrationData) {
///         e.storage().instance().set(&DATA_KEY, data);
///     }
/// }
/// ```
#[proc_macro_derive(Upgradeable)]
pub fn upgradeable_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    derive_upgradeable(&input).into()
}

#[proc_macro_derive(UpgradeableMigratable)]
pub fn upgradeable_migratable_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    derive_upgradeable_migratable(&input).into()
}