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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright (c) 2012-2022 Supercolony
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the"Software"),
// to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#![cfg_attr(not(feature = "std"), no_std)]

use proc_macro::TokenStream;

use brush_lang_codegen::{
    contract,
    modifier_definition,
    modifiers,
    storage,
    trait_definition,
    wrapper,
};

/// Entry point for use brush's macros in ink! smart contracts.
///
/// # Description
///
/// The macro consumes brush's macros to simplify the usage of the library.
/// After consumption, it pastes ink! code and then ink!'s macros will be processed.
///
/// This macro consumes impl section for traits defined with [`#[brush::trait_definition]`](`macro@crate::trait_definition`).
#[proc_macro_attribute]
pub fn contract(_attrs: TokenStream, ink_module: TokenStream) -> TokenStream {
    contract::generate(_attrs.into(), ink_module.into()).into()
}

/// Defines extensible trait in the scope of brush::contract.
/// It is a common rust trait, so you can use any features of rust inside of this trait.
/// If this trait contains some methods marked with `#[ink(message)]` or `#[ink(constructor)]` attributes,
/// this macro will extract these attributes and will put them into a separate trait
/// (the separate trait only is used to call methods from the original trait), but the macro will not touch methods.
///
/// This macro stores definition of the trait in a temporary file during build process.
/// Based on this definition [`#[brush::contract]`](`macro@crate::contract`)
/// will generate implementation of additional traits.
///
///  ** Note ** The name of the trait defined via this macro must be unique for the whole project.
///  ** Note ** You can't use aliases, generics, and other rust's stuff in signatures of ink!'s methods.
///
/// # Example: Definition
///
/// ```
/// mod doc {
/// use ink_prelude::collections::BTreeMap;
/// use brush::traits::{AccountId, Balance, InkStorage};
///
/// #[derive(Default, Debug)]
/// pub struct Data {
///     pub balances: BTreeMap<AccountId, Balance>,
/// }
///
/// #[brush::trait_definition]
/// pub trait PSP22Storage: InkStorage {
///     fn get(&self) -> &Data;
///     fn get_mut(&mut self) -> &mut Data;
/// }
///
/// #[brush::trait_definition]
/// pub trait PSP22: PSP22Storage {
///     /// Returns the account Balance for the specified `owner`.
///     #[ink(message)]
///     fn balance_of(&self, owner: AccountId) -> Balance {
///         self.get().balances.get(&owner).copied().unwrap_or(0)
///     }
///
///     /// Transfers `value` amount of tokens from the caller's account to account `to`.
///     #[ink(message)]
///     fn transfer(&mut self, to: AccountId, value: Balance) {
///         self._transfer_from_to(to, to, value)
///     }
///
///     fn _transfer_from_to(&mut self, from: AccountId, to: AccountId, amount: Balance) {
///         let from_balance = self.balance_of(from);
///         assert!(from_balance >= amount, "InsufficientBalance");
///         self.get_mut().balances.insert(from, from_balance - amount);
///         let to_balance = self.balance_of(to);
///         self.get_mut().balances.insert(to, to_balance + amount);
///     }
/// }
/// }
/// ```
///
/// # Example: Implementation
///
/// It uses storage trait from above.
///
/// ```
/// #[brush::contract]
/// mod base_psp22 {
///     use ink_prelude::collections::BTreeMap;
///     use brush::traits::InkStorage;
///     use ink_storage::traits::StorageLayout;
///     use ink_storage::traits::SpreadLayout;
///
///     #[derive(Default, Debug, SpreadLayout)]
///     #[cfg_attr(feature = "std", derive(scale_info::TypeInfo, StorageLayout))]
///     pub struct Data {
///         pub supply: Balance,
///         pub balances: BTreeMap<AccountId, Balance>,
///         pub allowances: BTreeMap<(AccountId, AccountId), Balance>,
///     }
///
///     #[brush::trait_definition]
///     pub trait PSP22ExampleStorage: InkStorage {
///         fn get(&self) -> &Data;
///         fn get_mut(&mut self) -> &mut Data;
///     }
///
///     #[brush::trait_definition]
///     pub trait PSP22Example: PSP22ExampleStorage {
///         /// Returns the account Balance for the specified `owner`.
///         #[ink(message)]
///         fn balance_of(&self, owner: AccountId) -> Balance {
///             self.get().balances.get(&owner).copied().unwrap_or(0)
///         }
///
///         /// Transfers `value` amount of tokens from the caller's account to account `to`.
///         #[ink(message)]
///         fn transfer(&mut self, to: AccountId, value: Balance) {
///             let from = Self::env().caller();
///             self._transfer_from_to(from, to, value)
///         }
///
///         fn _transfer_from_to(&mut self, from: AccountId, to: AccountId, amount: Balance) {
///             let from_balance = self.balance_of(from);
///             assert!(from_balance >= amount, "InsufficientBalance");
///             self.get_mut().balances.insert(from, from_balance - amount);
///             let to_balance = self.balance_of(to);
///             self.get_mut().balances.insert(to, to_balance + amount);
///         }
///     }
///
///     #[ink(storage)]
///     #[derive(Default)]
///     pub struct PSP22Struct {
///         example: Data,
///         hated_account: AccountId,
///     }
///
///     impl PSP22ExampleStorage for PSP22Struct {
///         fn get(&self) -> &Data {
///             &self.example
///         }
///
///         fn get_mut(&mut self) -> &mut Data {
///             &mut self.example
///         }
///     }
///
///     impl PSP22Example for PSP22Struct {
///         // Let's override method to reject transactions to bad account
///         fn _transfer_from_to(&mut self, from: AccountId, to: AccountId, amount: Balance) {
///             assert!(to != self.hated_account, "I hate this account!");
///
///             let from_balance = self.balance_of(from);
///             assert!(from_balance >= amount, "InsufficientBalance");
///             self.get_mut().balances.insert(from, from_balance - amount);
///             let to_balance = self.balance_of(to);
///             self.get_mut().balances.insert(to, to_balance + amount);
///         }
///     }
///
///     impl PSP22Struct {
///         #[ink(constructor)]
///         pub fn new(hated_account: AccountId) -> Self {
///             let mut instance = Self::default();
///             instance.hated_account = hated_account;
///             instance
///         }
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn trait_definition(_attrs: TokenStream, _input: TokenStream) -> TokenStream {
    trait_definition::generate(_attrs.into(), _input.into()).into()
}

/// This macro only checks that some free-standing function satisfies a set of rules.
///
/// Rules:
/// - First argument should not be `self`.
/// - First argument must be a reference to a type `instance: &T`. In most cases it's the instance of contract.
/// - Second argument is function's body(this function contains the main code of method attached to the modifier).
/// The type must be `Fn(&T)`, `FnMut(&T)` or `FnOnce(&T)`.
/// - Every next argument should not be references to object.
/// Because modifier allows only to pass arguments by value(Modifier will pass the clone of argument).
/// - The return type of body function(second argument) must be the same as the return type of modifier.
///
/// # Example: Definition
///
/// ```
/// #[derive(Default)]
/// struct Contract {
///     initialized: bool,
/// }
///
/// #[brush::modifier_definition]
/// fn once<BodyFn: FnOnce(&mut Contract)>(instance: &mut Contract, body: BodyFn, _example_data1: u8, _example_data2: u8) {
///     assert!(!instance.initialized, "Contract is already initialized");
///     body(instance);
///     instance.initialized = true;
/// }
/// ```
#[proc_macro_attribute]
pub fn modifier_definition(_attrs: TokenStream, _input: TokenStream) -> TokenStream {
    modifier_definition::generate(_attrs.into(), _input.into()).into()
}

/// Macro calls every modifier function by passing self and the code of function's body.
/// It means that modifiers must be available in the scope of the marked method.
///
/// Modifiers are designed to be used for methods in impl sections.
/// The method can have several modifiers. They will be expanded from left to right.
/// The modifier can accept arguments from the scope of the method definition
/// (you can pass an argument from the signature of marked method or from the outside scope of function).
/// The modifier accepts arguments only by value and the type of argument must support `Clone` trait,
/// because macro will clone the argument and will pass it to the modifier.
///
/// # Explanation:
///
/// Let's define next modifiers.
/// ```
/// #[brush::modifier_definition]
/// fn A<T>(instance: &T, body: impl FnOnce(&T) -> &'static str) -> &'static str {
///     println!("A before");
///     let result = body(instance);
///     println!("A after");
///     result
/// }
///
/// #[brush::modifier_definition]
/// fn B<T, F: FnOnce(&T) -> &'static str>(instance: &T, body: F, data1: u8, data2: u8) -> &'static str {
///     println!("B before {} {}", data1, data2);
///     let result = body(instance);
///     println!("B after {} {}", data1, data2);
///     result
/// }
///
/// #[brush::modifier_definition]
/// fn C<T, F>(instance: &T, body: F) -> &'static str
///     where F: FnOnce(&T) -> &'static str
/// {
///     println!("C before");
///     let result = body(instance);
///     println!("C after");
///     result
/// }
///
/// struct Contract {}
///
/// impl Contract {
///     #[brush::modifiers(A, B(_data, 13), C)]
///     fn main_logic(&self, _data: u8) -> &'static str {
///         return "Return value";
///     }
/// }
/// ```
/// The code above will be expanded into:
/// ```
/// #[brush::modifier_definition]
/// fn A<T>(instance: &T, body: impl FnOnce(&T) -> &'static str) -> &'static str {
///     println!("A before");
///     let result = body(instance);
///     println!("A after");
///     result
/// }
///
/// #[brush::modifier_definition]
/// fn B<T, F: FnOnce(&T) -> &'static str>(instance: &T, body: F, data1: u8, data2: u8) -> &'static str {
///     println!("B before {} {}", data1, data2);
///     let result = body(instance);
///     println!("B after {} {}", data1, data2);
///     result
/// }
///
/// #[brush::modifier_definition]
/// fn C<T, F>(instance: &T, body: F) -> &'static str
///     where F: FnOnce(&T) -> &'static str
/// {
///     println!("C before");
///     let result = body(instance);
///     println!("C after");
///     result
/// }
///
/// struct Contract {}
///
/// impl Contract {
///     fn main_logic(&self, _data: u8) -> &'static str {
///         let mut __brush_body_2 = |__brush_instance_modifier: &Self| {
///             let __brush_cloned_0 = _data.clone();
///             let __brush_cloned_1 = 13.clone();
///             let mut __brush_body_1 = |__brush_instance_modifier: &Self| {
///                 let mut __brush_body_0 = |__brush_instance_modifier: &Self| return "Return value";;
///                 C(__brush_instance_modifier, __brush_body_0)
///             };
///             B(__brush_instance_modifier, __brush_body_1, __brush_cloned_0, __brush_cloned_1)
///         };
///         A(self, __brush_body_2)
///     }
/// }
/// ```
///
/// # Example: Usage
///
/// ```
/// #[brush::contract]
/// mod example {
///     #[ink(storage)]
///     #[derive(Default)]
///     pub struct Contract {
///         initialized: bool,
///         owner: AccountId,
///     }
///
///     #[brush::modifier_definition]
///     fn once(instance: &mut Contract, body: impl FnOnce(&mut Contract)) {
///         assert!(!instance.initialized, "Contract is already initialized");
///         body(instance);
///         instance.initialized = true;
///     }
///
///     impl Contract {
///         #[ink(constructor)]
///         pub fn new() -> Self {
///             Self::default()
///         }
///
///         #[ink(message)]
///         #[brush::modifiers(once)]
///         pub fn init(&mut self, owner: AccountId) {
///             self.owner = owner;
///         }
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn modifiers(_attrs: TokenStream, method: TokenStream) -> TokenStream {
    modifiers::generate(_attrs.into(), method.into()).into()
}

/// This macro allows you to define a wrapper type for traits defined via
/// [`#[brush::trait_definition]`](`macro@crate::trait_definition`).
/// It is a wrapper for `AccountId` that knows how to do cross-contract calls to another contract.
///
/// To define a wrapper you need to use the follow construction:
/// `type TraitName = dyn Trait_1 + Trait_2 ... + Trait_n`, where `Trait_i` contains ink! messages
/// and defined via [`#[brush::trait_definition]`](`macro@crate::trait_definition`).
/// If `Trait_i` doesn't contain ink! messages, then you don't need to create a wrapper for that trait,
/// because the wrapped methods are created only for ink! messages. Otherwise, you will get an error like
///
/// `use of undeclared crate or module `trait_i_external``
///
///  ** Note ** The first argument of method should be a reference on `AccountId` of callee
/// contract(even if the signature of the method requires a mutable reference).
///  ** Note ** Crated wrapper is only a type, so you can't create an instance of this object.
///  ** Note ** The wrapper contains only ink's methods of the trait, it doesn't include a method of super traits.
/// If you want to wrap them too, you need to explicitly specify them.
///
/// # Example: Definition
///
/// ```should_panic
/// {
/// use brush::traits::AccountId;
///
/// #[brush::trait_definition]
/// pub trait Trait1 {
///     #[ink(message)]
///     fn foo(&mut self) -> bool;
/// }
///
/// #[brush::wrapper]
/// type Trait1Ref = dyn Trait1;
///
/// #[brush::trait_definition]
/// pub trait Trait2 {
///     #[ink(message)]
///     fn bar(&mut self, callee: brush::traits::AccountId) {
///         let foo_bool = Trait1Ref::foo(&callee);
///     }
/// }
///
/// #[brush::wrapper]
/// type Trait1and2Ref = dyn Trait1 + Trait2;
///
/// // Example of explicit call
/// let to: AccountId = [0; 32].into();
/// let callee: AccountId = [0; 32].into();
/// Trait1and2Ref::bar(&to, callee);
///
/// // Example of implicit call
/// let to: &Trait1and2Ref = &to;
/// to.bar(callee);
///
/// // Example how to get ink! call builder
/// let to: AccountId = [0; 32].into();
/// let builder_for_foo: ::ink_env::call::CallBuilder<_, _, _, _> = Trait1and2Ref::foo_builder(&to);
/// let ink_result: Result<bool, ink_env::Error> = builder_for_foo.fire();
/// }
/// ```
#[proc_macro_attribute]
pub fn wrapper(attrs: TokenStream, input: TokenStream) -> TokenStream {
    wrapper::generate(attrs.into(), input.into()).into()
}

synstructure::decl_attribute!(
    [storage] =>
    /// That macro implemented `SpreadLayout`, `SpreadAllocate` and `StorageLayout` with a specified
    /// storage key instead of the default one(All data is stored under the provided storage key).
    ///
    /// Also, that macro adds the code to initialize the structure if it wasn't initialized.
    /// That macro requires one input argument - the storage key. It can be any Rust code that returns [u8; 32].
    ///
    /// # Example:
    /// ```
    /// {
    /// use brush::traits::AccountId;
    /// pub const STORAGE_KEY: [u8; 32] = ink_lang::blake2x256!("brush::OwnableData");
    ///
    /// #[derive(Default, Debug)]
    /// #[brush::storage(STORAGE_KEY)]
    /// pub struct OwnableData {
    ///    pub owner: AccountId,
    ///    pub _reserved: Option<()>,
    /// }
    ///
    /// #[derive(Default, Debug)]
    /// #[brush::storage(ink_lang::blake2x256!("brush::ProxyData"))]
    /// pub struct ProxyData {
    ///    pub forward: AccountId,
    ///    pub _reserved: Option<()>,
    /// }
    ///
    /// }
    /// ```
    storage::storage
);