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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Note: The tests are located in the `stellar-axelar-std` package instead of `stellar-axelar-std-derive`
//!
//! This ensures compatibility and prevents cyclic dependency issues during testing and release.

mod axelar_executable;
mod contractimpl;
mod contractstorage;
mod into_event;
mod its_executable;
mod operatable;
mod ownable;
mod pausable;
mod upgradable;
mod utils;

use proc_macro::TokenStream;
use syn::{parse_macro_input, Attribute, DeriveInput, ItemFn, ItemImpl, Path};

/// Designates functions in an `impl` block as contract entrypoints.
///
/// This is a wrapper around the soroban-sdk's `#[contractimpl]` attribute.
/// It adds additional checks to ensure entrypoints don't get accidentally, or maliciously, called
/// after a contract upgrade, but before the data migration is complete.
///
/// # Example
/// ```rust, ignore
/// # mod test {
/// # use stellar_axelar_std::{contract, contracterror};
/// use stellar_axelar_std_derive::{contractimpl, Upgradable};
///
/// #[contract]
/// #[derive(Upgradable)]
/// pub struct Contract;
///
/// // any function in this impl block will panic if called during migration
/// #[contractimpl]
/// impl Contract {
///     pub fn __constructor(env: &Env) {
///         // constructor code
///     }
///
///     pub fn do_something(env: &Env, arg: String) {
///         // entrypoint code
///     }
/// }
///
/// #[contracterror]
/// #[derive(Copy, Clone, Debug, Eq, PartialEq)]
/// #[repr(u32)]
/// pub enum ContractError {
///     MigrationInProgress = 1,
/// }
///
/// // if an entrypoint is able to return a Result<_, ContractError>,
/// // it will return ContractError::MigrationInProgress instead of panicking when called during migration
/// #[contractimpl]
/// impl Contract {
///     pub fn return_result(env: &Env, arg: String) -> Result<u32, ContractError> {
///         // entrypoint code
///     }
/// }
/// # }
/// ```
#[proc_macro_attribute]
pub fn contractimpl(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(item as ItemImpl);

    contractimpl::contractimpl(&mut input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Implements the Operatable interface for a Soroban contract.
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// # use stellar_axelar_std::{contract, contractimpl, Address, Env};
/// use stellar_axelar_std_derive::Operatable;
///
/// #[contract]
/// #[derive(Operatable)]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     pub fn __constructor(env: &Env, owner: Address) {
///         stellar_axelar_std::interfaces::set_operator(env, &owner);
///     }
/// }
/// # }
/// ```
#[proc_macro_derive(Operatable)]
pub fn derive_operatable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    operatable::operatable(name).into()
}

/// Implements the Ownable interface for a Soroban contract.
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// # use stellar_axelar_std::{contract, contractimpl, Address, Env};
/// use stellar_axelar_std_derive::Ownable;
///
/// #[contract]
/// #[derive(Ownable)]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     pub fn __constructor(env: &Env, owner: Address) {
///         stellar_axelar_std::interfaces::set_owner(env, &owner);
///     }
/// }
/// # }
/// ```
#[proc_macro_derive(Ownable)]
pub fn derive_ownable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    ownable::ownable(name).into()
}

/// Implements the Pausable interface for a Soroban contract.
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// # use stellar_axelar_std::{contract, contractimpl, Address, Env};
/// use stellar_axelar_std_derive::Pausable;
///
/// #[contract]
/// #[derive(Pausable)]
/// pub struct Contract;
/// # }
/// ```
#[proc_macro_derive(Pausable)]
pub fn derive_pausable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    pausable::pausable(name).into()
}

/// Ensure that the Stellar contract is not paused before executing the function.
///
/// The first argument to the function must be `env`, and a `ContractError` error type must be defined in scope,
/// with a `ContractPaused` variant.
///
/// # Example
/// ```rust,ignore
/// # use stellar_axelar_std::{contract, contractimpl, contracttype, Address, Env};
/// use stellar_axelar_std::{Pausable, when_not_paused};
///
/// #[contracttype]
/// pub enum ContractError {
///     ContractPaused = 1,
/// }
///
/// #[contract]
/// #[derive(Pausable)]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     #[when_not_paused]
///     pub fn transfer(env: &Env, to: Address, amount: String) {
///         // ... transfer logic ...
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn when_not_paused(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    pausable::when_not_paused_impl(input_fn)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Implements the Upgradable and Migratable interfaces for a Soroban contract.
///
/// A `ContractError` error type must be defined in scope, and have a `MigrationNotAllowed` variant.
/// A default migration implementation is automatically provided. If custom migration code is required,
/// the `#[migratable]` attribute can be applied to the contract struct.
/// In that case, the contract must implement the `CustomMigratableInterface` trait. The associated `Error` type
/// must implement the `Into<ContractError>` trait. The `ContractError` type itself implements it implicitly,
/// so that is an easy way to use it.
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// # use stellar_axelar_std::{contract, contractimpl, contracterror, Address, Env};
/// use stellar_axelar_std_derive::{Ownable, Upgradable};
/// # #[contracterror]
/// # #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
/// # #[repr(u32)]
/// # pub enum ContractError {
/// #     MigrationNotAllowed = 1,
/// # }
///
/// #[contract]
/// #[derive(Ownable, Upgradable)]
/// #[migratable]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     pub fn __constructor(env: &Env, owner: Address) {
///         stellar_axelar_std::interfaces::set_owner(env, &owner);
///     }
/// }
///
/// impl CustomMigratableInterface for Contract {
///     type MigrationData = Address;
///     type Error = ContractError;
///
///     fn __migrate(env: &Env, new_owner: Self::MigrationData) -> Result<(), Self::Error> {
///         Self::transfer_ownership(env, new_owner);
///         Ok(())
///     }
/// }
/// # }
/// ```
#[proc_macro_derive(Upgradable, attributes(migratable))]
pub fn derive_upgradable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    upgradable::upgradable(&input).into()
}

fn ensure_no_args(attr: &Attribute) -> syn::Result<&Path> {
    attr.meta.require_path_only()
}

/// Implements the Event trait for a Stellar contract event.
///
/// Fields without a `#[data]` attribute are used as topics, while fields with `#[data]` are used as event data.
/// The event name can be specified with `#[event_name(...)]` or will default to the struct name in snake_case (minus "Event" suffix).
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// use core::fmt::Debug;
/// use stellar_axelar_std::events::Event;
/// use stellar_axelar_std::IntoEvent;
/// use stellar_axelar_std::{Address, contract, contractimpl, Env, String};
///
/// #[derive(Debug, PartialEq, IntoEvent)]
/// #[event_name("transfer")]
/// pub struct TransferEvent {
///     pub from: Address,
///     pub to: Address,
///     #[data]
///     pub amount: String,
/// }
///
/// #[contract]
/// pub struct Token;
///
/// #[contractimpl]
/// impl Token {
///     pub fn transfer(env: &Env, to: Address, amount: String) {
///         // ... transfer logic ...
///
///         // Generates event with:
///         // - Topics: ["transfer", contract_address, to]
///         // - Data: [amount]
///         TransferEvent {
///             from: env.current_contract_address(),
///             to,
///             amount,
///         }.emit(env);
///     }
/// }
/// }
/// ```
#[proc_macro_derive(IntoEvent, attributes(event_name, datum, data))]
pub fn derive_into_event(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    into_event::into_event(&input).into()
}

#[proc_macro_derive(InterchainTokenExecutable)]
pub fn derive_its_executable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    its_executable::its_executable(name).into()
}

#[proc_macro_derive(AxelarExecutable)]
pub fn derive_axelar_executable(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    axelar_executable::axelar_executable(name).into()
}

/// Ensures that only a contract's owner can execute the attributed function.
///
/// The first argument to the function must be `env`
///
/// # Example
/// ```rust,ignore
/// # use stellar_axelar_std::{contract, contractimpl, Address, Env};
/// use stellar_axelar_std::only_owner;
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     #[only_owner]
///     pub fn transfer(env: &Env, to: Address, amount: String) {
///         // ... transfer logic ...
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn only_owner(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    ownable::only_owner_impl(input_fn)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Ensures that only a contract's operator can execute the attributed function.
///
/// The first argument to the function must be `env`
///
/// # Example
/// ```rust,ignore
/// # use stellar_axelar_std::{contract, contractimpl, Address, Env};
/// use stellar_axelar_std::only_operator;
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     #[only_operator]
///     pub fn transfer(env: &Env, to: Address, amount: String) {
///         // ... transfer logic ...
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn only_operator(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    operatable::only_operator_impl(input_fn)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Implements a storage interface for a Stellar contract storage enum.
///
/// The enum variants define contract data keys, with optional named fields as contract data map keys.
/// Each variant requires a `#[value(Type)]` xor `#[status]` attribute to specify the stored value type.
/// Storage type can be specified with `#[instance]`, `#[persistent]`, or `#[temporary]` attributes (defaults to instance).
///
/// Certain types have default behaviors for TTL extensions:
/// - `#[persistent]`: This is extended by default every time a data key is accessed, for that data key.
///                    The persistent data type does not share the same TTL as the contract instance.
/// - `#[instance]`: This is extended by default for all contract endpoints, so it does not need to be included in generated data key access functions.
///                  This also serves to extend the lifetime of the contract's bytecode, since the instance data type does share the same TTL as the contract instance.
/// - `#[temporary]`: This is not extended by default, since this data type can be easily recreated or only valid for a certain period of time.
///                   In the special case that temporary data needs to be extended, a user may call the generated #ttl_extender function for that temporary data key.
///
/// More on Stellar data types: <https://developers.stellar.org/docs/learn/encyclopedia/storage/state-archival#contract-data-type-descriptions>
///
/// # Example
/// ```rust,ignore
/// # mod test {
/// use stellar_axelar_std::{contract, contractimpl, contractype, Address, Env, String};
/// use stellar_axelar_std::contractstorage;
///
/// #[contractstorage]
/// #[derive(Clone, Debug)]
/// enum DataKey {
///     #[instance]
///     #[value(Address)]
///     Owner,
///
///     #[persistent]
///     #[value(String)]
///     TokenName { token_id: u32 },
///
///     #[temporary]
///     #[value(u64)]
///     LastUpdate { account: Address },
///
///     #[instance]
///     #[status]
///     Paused,
/// }
///
/// #[contract]
/// pub struct Contract;
///
/// #[contractimpl]
/// impl Contract {
///     pub fn __constructor(
///         env: &Env,
///         token_id: u32,
///         name: String,
///     ) {
///         storage::set_token_name(env, token_id, &name);
///     }
///
///     pub fn foo(env: &Env, token_id: u32) -> Option<String> {
///         storage::token_name(env, token_id);
///     }
///
///     pub fn bar(env: &Env, token_id: u32) -> Option<String> {
///         storage::remove_token_name(env, token_id)
///     }
/// }
/// # }
/// ```
#[proc_macro_attribute]
pub fn contractstorage(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);

    contractstorage::contract_storage(&input).into()
}

trait MapTranspose<T> {
    fn map_transpose<U, E, F: FnOnce(T) -> Result<U, E>>(self, f: F) -> Result<Option<U>, E>;
}

impl<T> MapTranspose<T> for Option<T> {
    fn map_transpose<U, E, F: FnOnce(T) -> Result<U, E>>(self, f: F) -> Result<Option<U>, E> {
        self.map(f).transpose()
    }
}