Skip to main content

miden_standards/account/interface/
extension.rs

1use alloc::collections::BTreeSet;
2use alloc::vec::Vec;
3
4use miden_protocol::account::{Account, AccountCode, AccountId, AccountProcedureRoot};
5
6use crate::account::components::StandardAccountComponent;
7use crate::account::interface::{AccountComponentInterface, AccountInterface};
8
9// ACCOUNT INTERFACE EXTENSION TRAIT
10// ================================================================================================
11
12/// An extension for [`AccountInterface`] that allows instantiation from higher-level types.
13pub trait AccountInterfaceExt {
14    /// Creates a new [`AccountInterface`] instance from the provided account ID and account code.
15    fn from_code(account_id: AccountId, code: &AccountCode) -> Self;
16
17    /// Creates a new [`AccountInterface`] instance from the provided [`Account`].
18    fn from_account(account: &Account) -> Self;
19}
20
21impl AccountInterfaceExt for AccountInterface {
22    fn from_code(account_id: AccountId, code: &AccountCode) -> Self {
23        let components = AccountComponentInterface::from_procedures(code.procedures());
24        Self::new(account_id, components)
25    }
26
27    fn from_account(account: &Account) -> Self {
28        let components = AccountComponentInterface::from_procedures(account.code().procedures());
29        Self::new(account.id(), components)
30    }
31}
32
33/// An extension for [`AccountComponentInterface`] that allows instantiation from a set of procedure
34/// roots.
35pub trait AccountComponentInterfaceExt {
36    /// Creates a vector of [`AccountComponentInterface`] instances from the provided set of
37    /// procedures.
38    fn from_procedures(procedures: &[AccountProcedureRoot]) -> Vec<AccountComponentInterface>;
39}
40
41impl AccountComponentInterfaceExt for AccountComponentInterface {
42    fn from_procedures(procedures: &[AccountProcedureRoot]) -> Vec<Self> {
43        let mut component_interface_vec = Vec::new();
44
45        let mut procedures = BTreeSet::from_iter(procedures.iter().copied());
46
47        // Standard component interfaces
48        // ----------------------------------------------------------------------------------------
49
50        // Get all available standard components which could be constructed from the
51        // `procedures` map and push them to the `component_interface_vec`
52        StandardAccountComponent::extract_standard_components(
53            &mut procedures,
54            &mut component_interface_vec,
55        );
56
57        // Custom component interfaces
58        // ----------------------------------------------------------------------------------------
59
60        // All remaining procedures are put into the custom bucket.
61        component_interface_vec
62            .push(AccountComponentInterface::Custom(procedures.into_iter().collect()));
63
64        component_interface_vec
65    }
66}