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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Queue and approve actions

use near_sdk::{
    borsh::{self, BorshDeserialize, BorshSerialize},
    env, require, AccountId, BorshStorageKey,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{slot::Slot, DefaultStorageKey};

/// Error message emitted when the component is used before it is initialized
pub const NOT_INITIALIZED: &str = "init must be called before use";
/// Error message emitted when the init function is called multiple times
pub const ALREADY_INITIALIZED: &str = "init can only be called once";

pub mod native_transaction_action;
pub mod simple_multisig;

/// Actions can be executed after they are approved
pub trait Action<Cont: ?Sized> {
    /// Return type of the action. Useful if the action creates a `Promise`, for example.
    type Output;
    /// Perform the action. One time only.
    fn execute(self, contract: &mut Cont) -> Self::Output;
}

/// Defines the operating parameters for an ApprovalManager and performs
/// approvals
pub trait ApprovalConfiguration<A, S> {
    /// Errors when approving a request
    type ApprovalError;
    /// Errors when removing a request
    type RemovalError;
    /// Errors when authorizing an account
    type AuthorizationError;
    /// Errors when evaluating a request for execution candidacy
    type ExecutionEligibilityError;

    /// Has the request reached full approval?
    fn is_approved_for_execution(
        &self,
        action_request: &ActionRequest<A, S>,
    ) -> Result<(), Self::ExecutionEligibilityError>;

    /// Can this request be removed by an allowed account?
    fn is_removable(&self, action_request: &ActionRequest<A, S>) -> Result<(), Self::RemovalError>;

    /// Is the account allowed to execute, approve, or remove this request?
    fn is_account_authorized(
        &self,
        account_id: &AccountId,
        action_request: &ActionRequest<A, S>,
    ) -> Result<(), Self::AuthorizationError>;

    /// Modify action_request.approval_state in-place to increase approval
    fn try_approve_with_authorized_account(
        &self,
        account_id: AccountId,
        action_request: &mut ActionRequest<A, S>,
    ) -> Result<(), Self::ApprovalError>;
}

/// An action request is composed of an action that will be executed when the
/// associated approval state is satisfied
#[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Debug)]
pub struct ActionRequest<A, S> {
    /// The action that will be executed when the approval state is
    /// fulfilled
    pub action: A,
    /// The associated approval state
    pub approval_state: S,
}

#[derive(BorshSerialize, BorshStorageKey)]
enum ApprovalStorageKey {
    NextRequestId,
    Config,
    Request(u32),
}

/// The account is ineligile to perform an action for some reason
#[derive(Error, Clone, Debug)]
#[error("Unauthorized account: '{0}' for {1}")]
pub struct UnauthorizedAccountError<AuthErr>(AccountId, AuthErr);

/// Top-level errors that may occur when attempting to approve a request
#[derive(Error, Clone, Debug)]
pub enum ApprovalError<AuthErr, AppErr> {
    /// The account is not allowed to act on requests
    #[error(transparent)]
    UnauthorizedAccount(#[from] UnauthorizedAccountError<AuthErr>),
    /// The approval function encountered another error
    #[error("Approval error: {0}")]
    ApprovalError(AppErr),
}

/// Errors that may occur when trying to execute a request
#[derive(Error, Clone, Debug)]
pub enum ExecutionError<AuthErr, ExecErr> {
    /// The account is not allowed to act on requests
    #[error(transparent)]
    UnauthorizedAccount(#[from] UnauthorizedAccountError<AuthErr>),
    /// Unapproved requests cannot be executed
    #[error("Request not approved: {0}")]
    ExecutionEligibility(ExecErr),
}

/// Errors that may occur when trying to create a request
#[derive(Error, Clone, Debug)]
pub enum CreationError<AuthErr> {
    /// The account is not allowed to act on requests
    #[error(transparent)]
    UnauthorizedAccount(#[from] UnauthorizedAccountError<AuthErr>),
}

/// Errors that may occur when trying to remove a request
#[derive(Error, Clone, Debug)]
pub enum RemovalError<AuthErr, RemErr> {
    /// The account is not allowed to act on requests
    #[error(transparent)]
    UnauthorizedAccount(#[from] UnauthorizedAccountError<AuthErr>),
    /// This request is not (yet?) allowed to be removed
    #[error("Removal not allowed: {0}")]
    RemovalNotAllowed(RemErr),
}

/// Collection of action requests that manages their approval state and
/// execution
pub trait ApprovalManager<A, S, C>
where
    A: Action<Self> + BorshSerialize + BorshDeserialize,
    S: BorshSerialize + BorshDeserialize + Serialize,
    C: ApprovalConfiguration<A, S> + BorshDeserialize + BorshSerialize,
{
    /// Storage root
    fn root() -> Slot<()> {
        Slot::new(DefaultStorageKey::ApprovalManager)
    }

    /// Because requests will be deleted from the requests collection,
    /// maintain a simple counter to guarantee unique IDs
    fn slot_next_request_id() -> Slot<u32> {
        Self::root().field(ApprovalStorageKey::NextRequestId)
    }

    /// Approval context included in relevant approval-related calls
    fn slot_config() -> Slot<C> {
        Self::root().field(ApprovalStorageKey::Config)
    }

    /// Reads config from storage. Panics if the component has not been
    /// initialized.
    fn get_config() -> C {
        Self::slot_config()
            .read()
            .unwrap_or_else(|| env::panic_str(NOT_INITIALIZED))
    }

    /// Current list of pending action requests.
    fn slot_request(request_id: u32) -> Slot<ActionRequest<A, S>> {
        Self::root().field(ApprovalStorageKey::Request(request_id))
    }

    /// Get a request by ID
    fn get_request(request_id: u32) -> Option<ActionRequest<A, S>> {
        Self::slot_request(request_id).read()
    }

    /// Must be called before using the Approval construct. Can only be called
    /// once.
    fn init(config: C) {
        require!(
            Self::slot_config().swap(&config).is_none(),
            ALREADY_INITIALIZED,
        );
    }

    /// Creates a new action request initialized with the given approval state
    fn create_request(
        &mut self,
        action: A,
        approval_state: S,
    ) -> Result<u32, CreationError<C::AuthorizationError>> {
        let request_id = Self::slot_next_request_id().read().unwrap_or(0);

        let request = ActionRequest {
            action,
            approval_state,
        };

        let config = Self::get_config();
        let predecessor = env::predecessor_account_id();

        config
            .is_account_authorized(&predecessor, &request)
            .map_err(|e| UnauthorizedAccountError(predecessor, e))?;

        Self::slot_next_request_id().write(&(request_id + 1));
        Self::slot_request(request_id).write(&request);

        Ok(request_id)
    }

    /// Executes an action request and removes it from the collection if the
    /// approval state of the request is fulfilled.
    fn execute_request(
        &mut self,
        request_id: u32,
    ) -> Result<A::Output, ExecutionError<C::AuthorizationError, C::ExecutionEligibilityError>>
    {
        Self::is_approved_for_execution(request_id)
            .map_err(ExecutionError::ExecutionEligibility)?;

        let predecessor = env::predecessor_account_id();
        let config = Self::get_config();

        let mut request_slot = Self::slot_request(request_id);
        let request = request_slot.read().unwrap();

        config
            .is_account_authorized(&predecessor, &request)
            .map_err(|e| UnauthorizedAccountError(predecessor, e))?;

        let result = request.action.execute(self);
        request_slot.remove();

        Ok(result)
    }

    /// Is the given request ID able to be executed if such a request were to
    /// be initiated by an authorized account?
    fn is_approved_for_execution(request_id: u32) -> Result<(), C::ExecutionEligibilityError> {
        let request = Self::slot_request(request_id).read().unwrap();

        let config = Self::get_config();
        config.is_approved_for_execution(&request)
    }

    /// Tries to approve the action request designated by the given request ID
    /// with the given arguments. Panics if the request ID does not exist.
    fn approve_request(
        &mut self,
        request_id: u32,
    ) -> Result<(), ApprovalError<C::AuthorizationError, C::ApprovalError>> {
        let mut request_slot = Self::slot_request(request_id);
        let mut request = request_slot.read().unwrap();

        let predecessor = env::predecessor_account_id();
        let config = Self::get_config();

        config
            .is_account_authorized(&predecessor, &request)
            .map_err(|e| UnauthorizedAccountError(predecessor.clone(), e))?;

        config
            .try_approve_with_authorized_account(predecessor, &mut request)
            .map_err(ApprovalError::ApprovalError)?;

        request_slot.write(&request);

        Ok(())
    }

    /// Tries to remove the action request indicated by request_id.
    fn remove_request(
        &mut self,
        request_id: u32,
    ) -> Result<(), RemovalError<C::AuthorizationError, C::RemovalError>> {
        let mut request_slot = Self::slot_request(request_id);
        let request = request_slot.read().unwrap();
        let predecessor = env::predecessor_account_id();

        let config = Self::get_config();

        config
            .is_removable(&request)
            .map_err(RemovalError::RemovalNotAllowed)?;

        config
            .is_account_authorized(&predecessor, &request)
            .map_err(|e| UnauthorizedAccountError(predecessor, e))?;

        request_slot.remove();

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use near_contract_tools_macros::Rbac;
    use near_sdk::{
        borsh::{self, BorshDeserialize, BorshSerialize},
        near_bindgen,
        test_utils::VMContextBuilder,
        testing_env, AccountId, BorshStorageKey,
    };
    use serde::Serialize;

    use crate::{rbac::Rbac, slot::Slot};

    use super::{Action, ActionRequest, ApprovalConfiguration, ApprovalManager};

    #[derive(BorshSerialize, BorshStorageKey)]
    enum Role {
        Multisig,
    }

    #[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq, Eq, Clone)]
    enum MyAction {
        SayHello,
        SayGoodbye,
    }

    impl Action<Contract> for MyAction {
        type Output = &'static str;

        fn execute(self, _contract: &mut Contract) -> Self::Output {
            match self {
                Self::SayHello => {
                    println!("Hello!");
                    "hello"
                }
                Self::SayGoodbye => {
                    println!("Goodbye!");
                    "goodbye"
                }
            }
        }
    }

    #[derive(Rbac)]
    #[rbac(roles = "Role", crate = "crate")]
    #[near_bindgen]
    struct Contract {}

    #[near_bindgen]
    impl Contract {
        #[init]
        pub fn new(threshold: u8) -> Self {
            let contract = Self {};

            <Self as ApprovalManager<_, _, _>>::init(MultisigConfig { threshold });

            contract
        }
    }

    impl ApprovalManager<MyAction, MultisigApprovalState, MultisigConfig> for Contract {
        fn root() -> Slot<()> {
            Slot::new(b"a")
        }
    }

    #[derive(BorshSerialize, BorshDeserialize, Debug)]
    struct MultisigConfig {
        pub threshold: u8,
    }

    #[derive(BorshSerialize, BorshDeserialize, Serialize, Default, Debug)]
    struct MultisigApprovalState {
        pub approved_by: Vec<AccountId>,
    }

    impl ApprovalConfiguration<MyAction, MultisigApprovalState> for MultisigConfig {
        type ApprovalError = String;
        type RemovalError = ();
        type AuthorizationError = String;
        type ExecutionEligibilityError = String;

        fn is_approved_for_execution(
            &self,
            action_request: &super::ActionRequest<MyAction, MultisigApprovalState>,
        ) -> Result<(), Self::ExecutionEligibilityError> {
            let valid_signatures = action_request
                .approval_state
                .approved_by
                .iter()
                .filter(|account_id| Contract::has_role(account_id, &Role::Multisig))
                .count();

            let threshold = self.threshold as usize;

            if valid_signatures >= threshold {
                Ok(())
            } else {
                Err("Insufficient signatures".to_string())
            }
        }

        fn is_removable(
            &self,
            _action_request: &super::ActionRequest<MyAction, MultisigApprovalState>,
        ) -> Result<(), Self::RemovalError> {
            Ok(())
        }

        fn is_account_authorized(
            &self,
            account_id: &AccountId,
            _action_request: &ActionRequest<MyAction, MultisigApprovalState>,
        ) -> Result<(), Self::AuthorizationError> {
            if Contract::has_role(account_id, &Role::Multisig) {
                Ok(())
            } else {
                Err("Account is missing Multisig role".to_string())
            }
        }

        fn try_approve_with_authorized_account(
            &self,
            account_id: AccountId,
            action_request: &mut ActionRequest<MyAction, MultisigApprovalState>,
        ) -> Result<(), Self::ApprovalError> {
            if action_request
                .approval_state
                .approved_by
                .contains(&account_id)
            {
                return Err("Already approved by account".to_string());
            }

            action_request.approval_state.approved_by.push(account_id);

            Ok(())
        }
    }

    fn predecessor(account_id: &AccountId) {
        let mut context = VMContextBuilder::new();
        context.predecessor_account_id(account_id.clone());
        testing_env!(context.build());
    }

    #[test]
    fn successful_approval() {
        let alice: AccountId = "alice".parse().unwrap();
        let bob: AccountId = "bob_acct".parse().unwrap();
        let charlie: AccountId = "charlie".parse().unwrap();

        let mut contract = Contract::new(2);

        contract.add_role(alice.clone(), &Role::Multisig);
        contract.add_role(bob, &Role::Multisig);
        contract.add_role(charlie.clone(), &Role::Multisig);

        predecessor(&alice);
        let request_id = contract
            .create_request(MyAction::SayHello, Default::default())
            .unwrap();

        assert_eq!(request_id, 0);
        assert!(Contract::is_approved_for_execution(request_id).is_err());

        contract.approve_request(request_id).unwrap();

        assert!(Contract::is_approved_for_execution(request_id).is_err());

        predecessor(&charlie);
        contract.approve_request(request_id).unwrap();

        assert!(Contract::is_approved_for_execution(request_id).is_ok());

        assert_eq!(contract.execute_request(request_id).unwrap(), "hello");
    }

    #[test]
    #[should_panic(expected = "Already approved by account")]
    fn duplicate_approval() {
        let alice: AccountId = "alice".parse().unwrap();

        let mut contract = Contract::new(2);

        contract.add_role(alice.clone(), &Role::Multisig);

        predecessor(&alice);
        let request_id = contract
            .create_request(MyAction::SayHello, Default::default())
            .unwrap();

        contract.approve_request(request_id).unwrap();

        contract.approve_request(request_id).unwrap();
    }

    #[test]
    #[should_panic = "Insufficient signatures"]
    fn no_execution_before_approval() {
        let alice: AccountId = "alice".parse().unwrap();

        let mut contract = Contract::new(2);

        contract.add_role(alice.clone(), &Role::Multisig);

        predecessor(&alice);

        let request_id = contract
            .create_request(MyAction::SayHello, Default::default())
            .unwrap();

        contract.approve_request(request_id).unwrap();

        contract.execute_request(request_id).unwrap();
    }

    #[test]
    fn successful_removal() {
        let alice: AccountId = "alice".parse().unwrap();
        let bob: AccountId = "bob_acct".parse().unwrap();

        let mut contract = Contract::new(2);

        contract.add_role(alice.clone(), &Role::Multisig);
        contract.add_role(bob.clone(), &Role::Multisig);

        predecessor(&alice);

        let request_id = contract
            .create_request(MyAction::SayHello, Default::default())
            .unwrap();

        contract.approve_request(request_id).unwrap();

        predecessor(&bob);

        contract.remove_request(request_id).unwrap();
    }

    #[test]
    fn dynamic_eligibility() {
        let alice: AccountId = "alice".parse().unwrap();
        let bob: AccountId = "bob_acct".parse().unwrap();
        let charlie: AccountId = "charlie".parse().unwrap();

        let mut contract = Contract::new(2);

        contract.add_role(alice.clone(), &Role::Multisig);
        contract.add_role(bob.clone(), &Role::Multisig);
        contract.add_role(charlie.clone(), &Role::Multisig);

        predecessor(&alice);
        let request_id = contract
            .create_request(MyAction::SayGoodbye, Default::default())
            .unwrap();

        contract.approve_request(request_id).unwrap();

        predecessor(&bob);
        contract.approve_request(request_id).unwrap();

        assert!(Contract::is_approved_for_execution(request_id).is_ok());

        contract.remove_role(&alice, &Role::Multisig);

        assert!(Contract::is_approved_for_execution(request_id).is_err());

        predecessor(&charlie);
        contract.approve_request(request_id).unwrap();

        assert!(Contract::is_approved_for_execution(request_id).is_ok());
    }
}