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
use odra::{
    contract_env,
    types::{event::OdraEvent, Address},
    UnwrapOrRevert, Variable
};

use super::{
    errors::Error,
    events::{OwnershipTransferStarted, OwnershipTransferred}
};

/// This module provides a straightforward access control feature that enables
/// exclusive access to particular functions by an account, known as the owner.
/// The account that initiates contract deployment is automatically assigned as
/// the owner. However, ownership can be transferred later by using the
/// `transfer_ownership()` function.
///
/// You can use this module as a standalone contract or integrate it into
/// a custom module by adding it as a field.
///
/// When used in a custom module, the `only_owner()` function is available,
/// allowing you to restrict function usage to the owner.
#[odra::module(events = [OwnershipTransferred])]
pub struct Ownable {
    owner: Variable<Option<Address>>
}

#[odra::module]
impl Ownable {
    /// Initializes the module setting the caller as the initial owner.
    #[odra(init)]
    pub fn init(&mut self) {
        let caller = contract_env::caller();
        let initial_owner = Some(&caller);
        self.unchecked_transfer_ownership(initial_owner);
    }

    /// Transfers ownership of the module to `new_owner`. This function can only
    /// be accessed by the current owner of the module.
    pub fn transfer_ownership(&mut self, new_owner: &Address) {
        self.assert_owner(&contract_env::caller());
        self.unchecked_transfer_ownership(Some(new_owner));
    }

    /// If the contract's owner chooses to renounce their ownership, the contract
    /// will no longer have an owner. This means that any functions that can only
    /// be accessed by the owner will no longer be available.
    ///
    /// The function can only be called by the current owner, and it will permanently
    /// remove the owner's privileges.
    pub fn renounce_ownership(&mut self) {
        self.assert_owner(&contract_env::caller());
        self.unchecked_transfer_ownership(None);
    }

    /// Returns the address of the current owner.
    pub fn get_owner(&self) -> Address {
        self.get_optional_owner()
            .unwrap_or_revert_with(Error::OwnerNotSet)
    }
}

impl Ownable {
    /// Reverts with [`Error::CallerNotTheOwner`] if the function called by
    /// any account other than the owner.
    pub fn assert_owner(&self, address: &Address) {
        if Some(address) != self.get_optional_owner().as_ref() {
            contract_env::revert(Error::CallerNotTheOwner)
        }
    }

    fn get_optional_owner(&self) -> Option<Address> {
        self.owner.get().flatten()
    }

    fn unchecked_transfer_ownership(&mut self, new_owner: Option<&Address>) {
        let previous_owner = self.get_optional_owner();
        self.owner.set(new_owner.cloned());

        OwnershipTransferred {
            previous_owner,
            new_owner: new_owner.cloned()
        }
        .emit();
    }
}

/// This module provides a straightforward access control feature that enables
/// exclusive access to particular functions by an account, known as the owner.
/// The account that initiates contract deployment is automatically assigned as
/// the owner. However, ownership can be transferred later by using the
/// `transfer_ownership()` and `accept_ownership()` functions.
///
/// You can use this module as a standalone contract or integrate it into
/// a custom module by adding it as a field.
///
/// When used in a custom module, the `only_owner()` function is available,
/// allowing you to restrict function usage to the owner.
#[odra::module(events = [OwnershipTransferStarted])]
pub struct Ownable2Step {
    ownable: Ownable,
    pending_owner: Variable<Option<Address>>
}

#[odra::module]
impl Ownable2Step {
    /// Initializes the module setting the caller as the initial owner.
    #[odra(init)]
    pub fn init(&mut self) {
        self.ownable.init();
    }

    /// Returns the address of the current owner.
    pub fn get_owner(&self) -> Address {
        self.ownable.get_owner()
    }

    /// Returns the address of the pending owner.
    pub fn get_pending_owner(&self) -> Option<Address> {
        self.pending_owner.get().flatten()
    }

    /// Starts the ownership transfer of the module to a `new_owner`.
    /// Replaces the `pending_owner`if there is one.
    ///
    /// This function can only be accessed by the current owner of the module.
    pub fn transfer_ownership(&mut self, new_owner: &Address) {
        self.ownable.assert_owner(&contract_env::caller());

        let previous_owner = self.ownable.get_optional_owner();
        let new_owner = &Some(*new_owner);
        self.pending_owner.set(*new_owner);

        OwnershipTransferStarted {
            previous_owner,
            new_owner: *new_owner
        }
        .emit();
    }

    /// If the contract's owner chooses to renounce their ownership, the contract
    /// will no longer have an owner. This means that any functions that can only
    /// be accessed by the owner will no longer be available.
    ///
    /// The function can only be called by the current owner, and it will permanently
    /// remove the owner's privileges.
    pub fn renounce_ownership(&mut self) {
        self.ownable.renounce_ownership()
    }

    /// The new owner accepts the ownership transfer. Replaces the current owner and clears
    /// the pending owner.
    pub fn accept_ownership(&mut self) {
        let caller = &contract_env::caller();
        let caller = Some(caller);
        let pending_owner = self.pending_owner.get().flatten();
        if pending_owner.as_ref() != caller {
            contract_env::revert(Error::CallerNotTheNewOwner)
        }
        self.pending_owner.set(None);
        self.ownable.unchecked_transfer_ownership(caller);
    }
}

#[cfg(test)]
mod test {
    use odra::{assert_events, external_contract, test_env};

    use super::*;

    #[test]
    fn init() {
        // given new contacts
        let (contracts, deployer) = setup_owned();

        contracts.iter().for_each(|contract: &OwnedRef| {
            // then the deployer is the owner
            assert_eq!(deployer, contract.get_owner());
            // then a OwnershipTransferred event was emitted
            assert_events!(
                contract,
                OwnershipTransferred {
                    previous_owner: None,
                    new_owner: Some(deployer)
                }
            );
        });
    }

    #[test]
    fn plain_ownership_transfer() {
        // given a new contract
        let (mut contract, initial_owner) = setup_ownable();

        // when the current owner transfers ownership
        let new_owner = test_env::get_account(1);
        contract.transfer_ownership(&new_owner);

        // then the new owner is set
        assert_eq!(new_owner, contract.get_owner());
        // then a OwnershipTransferred event was emitted
        assert_events!(
            contract,
            OwnershipTransferred {
                previous_owner: Some(initial_owner),
                new_owner: Some(new_owner)
            }
        );
    }

    #[test]
    fn two_step_ownership_transfer() {
        // given a new contract
        let (mut contract, initial_owner) = setup_ownable_2_step();

        // when the current owner transfers ownership
        let new_owner = test_env::get_account(1);
        contract.transfer_ownership(&new_owner);

        // when the pending owner accepts the transfer
        test_env::set_caller(new_owner);
        contract.accept_ownership();

        // then the new owner is set
        assert_eq!(new_owner, contract.get_owner());
        // then the pending owner is unset
        assert_eq!(None, contract.get_pending_owner());
        // then OwnershipTransferStarted and OwnershipTransferred events were emitted
        assert_events!(
            contract,
            OwnershipTransferStarted {
                previous_owner: Some(initial_owner),
                new_owner: Some(new_owner)
            },
            OwnershipTransferred {
                previous_owner: Some(initial_owner),
                new_owner: Some(new_owner)
            }
        );
    }

    #[test]
    fn failing_plain_ownership_transfer() {
        // given a new contract
        let (mut contract, _) = setup_ownable();

        // when a non-owner account is the caller
        let (caller, new_owner) = (test_env::get_account(1), test_env::get_account(2));
        test_env::set_caller(caller);

        // then ownership transfer fails
        test_env::assert_exception(Error::CallerNotTheOwner, || {
            contract.transfer_ownership(&new_owner);
        });
    }

    #[test]
    fn failing_two_step_transfer() {
        // given a new contract
        let (mut contract, initial_owner) = setup_ownable_2_step();

        // when a non-owner account is the caller
        let (caller, new_owner) = (test_env::get_account(1), test_env::get_account(2));
        test_env::set_caller(caller);

        // then ownership transfer fails
        test_env::assert_exception(Error::CallerNotTheOwner, || {
            contract.transfer_ownership(&new_owner);
        });

        // when the owner is the caller
        test_env::set_caller(initial_owner);
        contract.transfer_ownership(&new_owner);

        // then the pending owner is set
        assert_eq!(contract.get_pending_owner(), Some(new_owner));

        // when someone else than the pending owner accepts the ownership
        // transfer, it should fail
        test_env::assert_exception(Error::CallerNotTheNewOwner, || {
            contract.accept_ownership();
        });

        // then the owner remain the same
        assert_eq!(contract.get_owner(), initial_owner);
        // then the pending owner remain the same
        assert_eq!(contract.get_pending_owner(), Some(new_owner));
    }

    #[test]
    fn renounce_ownership() {
        // given new contracts
        let (mut contracts, initial_owner) = setup_renounceable();

        contracts
            .iter_mut()
            .for_each(|contract: &mut RenounceableRef| {
                // when the current owner renounce ownership
                contract.renounce_ownership();

                // then an event is emitted
                assert_events!(
                    contract,
                    OwnershipTransferred {
                        previous_owner: Some(initial_owner),
                        new_owner: None
                    }
                );
                // then the owner is not set
                test_env::assert_exception(Error::OwnerNotSet, || {
                    contract.get_owner();
                });
                // then cannot renounce ownership again
                test_env::assert_exception(Error::CallerNotTheOwner, || {
                    contract.renounce_ownership();
                });
            });
    }

    #[test]
    fn renounce_ownership_fail() {
        // given new contracts
        let (mut contracts, _) = setup_renounceable();

        contracts.iter_mut().for_each(|contract| {
            // when a non-owner account is the caller
            let caller = test_env::get_account(1);
            test_env::set_caller(caller);

            // then renounce ownership fails
            test_env::assert_exception(Error::CallerNotTheOwner, || {
                contract.renounce_ownership();
            });
        });
    }

    #[external_contract]
    trait Owned {
        fn get_owner(&self) -> Address;
    }

    #[external_contract]
    trait Renounceable {
        fn renounce_ownership(&mut self);
        fn get_owner(&self) -> Address;
    }

    fn setup_ownable() -> (OwnableRef, Address) {
        (OwnableDeployer::init(), test_env::get_account(0))
    }

    fn setup_ownable_2_step() -> (Ownable2StepRef, Address) {
        (Ownable2StepDeployer::init(), test_env::get_account(0))
    }

    fn setup_renounceable() -> (Vec<RenounceableRef>, Address) {
        let ownable = OwnableDeployer::init();
        let ownable_2_step = Ownable2StepDeployer::init();
        (
            vec![
                RenounceableRef::at(ownable.address()),
                RenounceableRef::at(ownable_2_step.address()),
            ],
            test_env::get_account(0)
        )
    }

    fn setup_owned() -> (Vec<OwnedRef>, Address) {
        let ownable = OwnableDeployer::init();
        let ownable_2_step = Ownable2StepDeployer::init();
        (
            vec![
                OwnedRef::at(ownable.address()),
                OwnedRef::at(ownable_2_step.address()),
            ],
            test_env::get_account(0)
        )
    }
}