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
#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::dispatch::UnfilteredDispatchable;
use frame_support::{decl_event, decl_module, decl_storage, Parameter};
use frame_system::{self as system, ensure_signed, RawOrigin};
use pallet_contracts::{BalanceOf, CodeHash, ContractAddressFor, Gas};
use sp_runtime::{
    traits::{MaybeDisplay, MaybeSerialize, Member},
    DispatchError,
};
use sp_std::prelude::*;

pub mod parameters;
#[cfg(test)]
mod tests;

use crate::parameters::Verifiable;

pub trait ContractFinder<AccountId, Parameter> {
    fn is_exists_contract(contract_id: &AccountId) -> bool;
    fn operator(contract_id: &AccountId) -> Option<AccountId>;
    fn parameters(contract_id: &AccountId) -> Option<Parameter>;
}

pub trait OperatorFinder<AccountId: Parameter> {
    fn contracts(operator_id: &AccountId) -> Vec<AccountId>;
}

pub trait TransferOperator<AccountId: Parameter>: OperatorFinder<AccountId> {
    /// Changes an operator for identified contracts with verify.
    fn transfer_operator(
        current_operator: AccountId,
        contracts: Vec<AccountId>,
        new_operator: AccountId,
    ) -> Result<(), DispatchError> {
        Self::verify_transfer_operator(&current_operator, &contracts)?;
        Self::force_transfer_operator(current_operator, contracts, new_operator);
        Ok(())
    }

    fn verify_transfer_operator(
        current_operator: &AccountId,
        contracts: &Vec<AccountId>,
    ) -> Result<(), DispatchError> {
        let operate_contracts = Self::contracts(current_operator);

        // check the actually operate the contract.
        if !contracts.iter().all(|c| operate_contracts.contains(c)) {
            Err(DispatchError::Other(
                "The sender don't operate the contracts address.",
            ))?
        }
        Ok(())
    }

    /// Force Changes an operator for identified contracts without verify.
    fn force_transfer_operator(
        current_operator: AccountId,
        contracts: Vec<AccountId>,
        new_operator: AccountId,
    );
}

/// The module's configuration trait.
pub trait Trait: pallet_contracts::Trait {
    type Parameters: Parameter
        + Member
        + MaybeSerialize
        + MaybeDisplay
        + Default
        + sp_std::hash::Hash
        + parameters::Verifiable;

    /// The overarching event type.
    type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
}

// This module's storage items.
decl_storage! {
    trait Store for Module<T: Trait> as Operator {
        /// A mapping from operators to operated contracts by them.
        pub OperatorHasContracts get(fn operator_has_contracts): map hasher(blake2_128_concat)
                                                                 T::AccountId => Vec<T::AccountId>;
        /// A mapping from operated contract by operator to it.
        pub ContractHasOperator get(fn contract_has_operator): map hasher(blake2_128_concat)
                                                               T::AccountId => Option<T::AccountId>;
        /// A mapping from contract to it's parameters.
        pub ContractParameters get(fn contract_parameters): map hasher(blake2_128_concat)
                                                            T::AccountId => Option<T::Parameters>;
    }
}

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        // Initializing events
        // this is needed only if you are using events in your module
        fn deposit_event() = default;

        /// Deploys a contact and insert relation of a contract and an operator to mapping.
        #[weight = *gas_limit]
        pub fn instantiate(
            origin,
            #[compact] endowment: BalanceOf<T>,
            #[compact] gas_limit: Gas,
            code_hash: CodeHash<T>,
            data: Vec<u8>,
            parameters: T::Parameters,
        ) {
            let operator = ensure_signed(origin)?;

            // verify parameters.
            parameters.verify()?;

            let contract = T::DetermineContractAddress::contract_address_for(&code_hash, &data, &operator);
            pallet_contracts::Call::<T>::instantiate(endowment, gas_limit, code_hash, data)
                .dispatch_bypass_filter(RawOrigin::Signed(operator.clone()).into())
                .map_err(|e| e.error)?;

            // add operator to contracts
            <OperatorHasContracts<T>>::mutate(&operator, |tree| (*tree).push(contract.clone()));
            // add contract to operator
            <ContractHasOperator<T>>::insert(&contract, operator.clone());
            // add contract to parameters
            <ContractParameters<T>>::insert(&contract, parameters);

            // issue an event operator -> contract
            Self::deposit_event(RawEvent::SetOperator(operator, contract));
        }

        /// Updates parameters for an identified contact.
        /// TODO: weight
        #[weight = 50_000]
        pub fn update_parameters(
            origin,
            contract: T::AccountId,
            parameters: T::Parameters,
        ) {
            let operator = ensure_signed(origin)?;

            // verify parameters
            parameters.verify()?;

            let contracts = <OperatorHasContracts<T>>::get(&operator);

            // check the actually operate the contract.
            if !contracts.contains(&contract) {
                Err("The sender don't operate the contract address.")?
            }

            // update parameters
            <ContractParameters<T>>::insert(&contract, parameters.clone());
            // issue set parameter events
            Self::deposit_event(RawEvent::SetParameters(contract, parameters));
        }

        /// Changes an operator for identified contracts.
        /// TODO: weight
        #[weight = 100_000]
        pub fn change_operator(
            origin,
            contracts: Vec<T::AccountId>,
            new_operator: T::AccountId,
        ) {
            let operator = ensure_signed(origin)?;
            Self::transfer_operator(operator, contracts, new_operator)?;
        }
    }
}

decl_event!(
    pub enum Event<T>
    where
        AccountId = <T as frame_system::Trait>::AccountId,
        Parameters = <T as Trait>::Parameters,
    {
        /// When operator changed,
        /// it is issued that 1-st Operator AccountId and 2-nd Contract AccountId.
        SetOperator(AccountId, AccountId),

        /// When contract's parameters changed,
        /// it is issued that 1-st Contract AccountId and 2-nd the contract's new parameters.
        SetParameters(AccountId, Parameters),
    }
);

impl<T: Trait> ContractFinder<T::AccountId, T::Parameters> for Module<T> {
    fn is_exists_contract(contract_id: &T::AccountId) -> bool {
        <ContractHasOperator<T>>::contains_key(contract_id)
    }
    fn operator(contract_id: &T::AccountId) -> Option<T::AccountId> {
        <ContractHasOperator<T>>::get(contract_id)
    }
    fn parameters(contract_id: &T::AccountId) -> Option<T::Parameters> {
        <ContractParameters<T>>::get(contract_id)
    }
}
impl<T: Trait> OperatorFinder<T::AccountId> for Module<T> {
    fn contracts(operator_id: &T::AccountId) -> Vec<T::AccountId> {
        <OperatorHasContracts<T>>::get(operator_id)
    }
}

impl<T: Trait> TransferOperator<T::AccountId> for Module<T> {
    /// Force Changes an operator for identified contracts without verify.
    fn force_transfer_operator(
        current_operator: T::AccountId,
        contracts: Vec<T::AccountId>,
        new_operator: T::AccountId,
    ) {
        // remove origin operator to contracts
        <OperatorHasContracts<T>>::mutate(&current_operator, |tree| {
            *tree = tree
                .iter()
                .filter(|&x| !contracts.contains(x))
                .cloned()
                .collect()
        });

        // add new_operator to contracts
        <OperatorHasContracts<T>>::mutate(&new_operator, |tree| {
            for c in contracts.iter() {
                (*tree).push(c.clone());
            }
        });
        for c in contracts.iter() {
            // add contract to new_operator
            <ContractHasOperator<T>>::insert(&c, new_operator.clone());
            // issue an event operator -> contract
            Self::deposit_event(RawEvent::SetOperator(new_operator.clone(), c.clone()));
        }
    }
}