From 6f7f587de2e66bf122e09a65a0eeeee88f196c9c Mon Sep 17 00:00:00 2001 From: Antonio Date: Wed, 6 Nov 2024 09:22:07 +0200 Subject: [PATCH] chore: instantiatable linking pallet (#781) Part of https://github.com/KILTprotocol/ticket/issues/3650. Built on top of https://github.com/KILTprotocol/kilt-node/pull/779. --- pallets/pallet-did-lookup/src/benchmarking.rs | 116 +++++------ pallets/pallet-did-lookup/src/lib.rs | 188 +++++++++--------- pallets/pallet-did-lookup/src/migrations.rs | 5 +- pallets/pallet-did-lookup/src/mock.rs | 6 +- pallets/pallet-did-lookup/src/try_state.rs | 10 +- 5 files changed, 165 insertions(+), 160 deletions(-) diff --git a/pallets/pallet-did-lookup/src/benchmarking.rs b/pallets/pallet-did-lookup/src/benchmarking.rs index c35994197..3037e70b8 100644 --- a/pallets/pallet-did-lookup/src/benchmarking.rs +++ b/pallets/pallet-did-lookup/src/benchmarking.rs @@ -19,7 +19,7 @@ //! Benchmarking -use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; +use frame_benchmarking::{account, benchmarks_instance_pallet, impl_benchmark_test_suite}; use frame_support::{ crypto::ecdsa::ECDSAExt, traits::{ @@ -50,23 +50,23 @@ const SEED: u32 = 0; // Free 2x deposit amount + existential deposit so that we can use this function // to link an account two times to two different DIDs. -fn make_free_for_did(account: &AccountIdOf) +fn make_free_for_did, I: 'static>(account: &AccountIdOf) where - ::Currency: Mutate, + >::Currency: Mutate, { - let balance = as Inspect>>::minimum_balance() - + ::Deposit::get() - + ::Deposit::get(); - CurrencyOf::::set_balance(account, balance); + let balance = as Inspect>>::minimum_balance() + + >::Deposit::get() + + >::Deposit::get(); + CurrencyOf::::set_balance(account, balance); } -benchmarks! { +benchmarks_instance_pallet! { where_clause { where T::AccountId: From + From + Into + Into + From, - T::DidIdentifier: From, - T::EnsureOrigin: GenerateBenchmarkOrigin, - ::Currency: Mutate, + >::DidIdentifier: From, + >::EnsureOrigin: GenerateBenchmarkOrigin>::DidIdentifier>, + >::Currency: Mutate, } associate_account_multisig_sr25519 { @@ -87,19 +87,19 @@ benchmarks! { )) .ok_or("Error while building signature.")?; - make_free_for_did::(&caller); + make_free_for_did::(&caller); // Add existing connected_acc -> previous_did connection that will be replaced - Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); + Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); let id_arg = linkable_id.clone(); let req = AssociateAccountRequest::Polkadot(connected_acc_id.into(), sig.into()); }: associate_account(origin, req, expire_at) verify { - assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); + assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); } associate_account_multisig_ed25519 { @@ -120,19 +120,19 @@ benchmarks! { )) .ok_or("Error while building signature.")?; - make_free_for_did::(&caller); + make_free_for_did::(&caller); // Add existing connected_acc -> previous_did connection that will be replaced - Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); + Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); let id_arg = linkable_id.clone(); let req = AssociateAccountRequest::Polkadot(connected_acc_id.into(), sig.into()); }: associate_account(origin, req, expire_at) verify { - assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); + assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); } associate_account_multisig_ecdsa { @@ -153,19 +153,19 @@ benchmarks! { )) .ok_or("Error while building signature.")?; - make_free_for_did::(&caller); + make_free_for_did::(&caller); // Add existing connected_acc -> previous_did connection that will be replaced - Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); + Pallet::::add_association(caller.clone(), previous_did.clone(), linkable_id.clone()).expect("should create previous association"); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_some()); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); let id_arg = linkable_id.clone(); let req = AssociateAccountRequest::Polkadot(connected_acc_id, sig.into()); }: associate_account(origin, req, expire_at) verify { - assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); - assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); + assert!(ConnectedDids::::get(linkable_id.clone()).is_some()); + assert!(ConnectedAccounts::::get(&previous_did, linkable_id.clone()).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); } associate_eth_account { @@ -188,18 +188,18 @@ benchmarks! { &Keccak256::digest(wrapped_payload).try_into().unwrap(), ).ok_or("Error while building signature.")?; - make_free_for_did::(&caller); + make_free_for_did::(&caller); // Add existing connected_acc -> previous_did connection that will be replaced - Pallet::::add_association(caller.clone(), previous_did.clone(), eth_account.into()).expect("should create previous association"); - assert!(ConnectedAccounts::::get(&previous_did, LinkableAccountId::from(eth_account)).is_some()); + Pallet::::add_association(caller.clone(), previous_did.clone(), eth_account.into()).expect("should create previous association"); + assert!(ConnectedAccounts::::get(&previous_did, LinkableAccountId::from(eth_account)).is_some()); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); let req = AssociateAccountRequest::Ethereum(eth_account, sig.into()); }: associate_account(origin, req, expire_at) verify { - assert!(ConnectedDids::::get(LinkableAccountId::from(eth_account)).is_some()); - assert!(ConnectedAccounts::::get(&previous_did, LinkableAccountId::from(eth_account)).is_none()); - assert!(ConnectedAccounts::::get(did, LinkableAccountId::from(eth_account)).is_some()); + assert!(ConnectedDids::::get(LinkableAccountId::from(eth_account)).is_some()); + assert!(ConnectedAccounts::::get(&previous_did, LinkableAccountId::from(eth_account)).is_none()); + assert!(ConnectedAccounts::::get(did, LinkableAccountId::from(eth_account)).is_some()); } associate_sender { @@ -208,17 +208,17 @@ benchmarks! { let did: T::DidIdentifier = account("did", 0, SEED); let previous_did: T::DidIdentifier = account("prev", 0, SEED + 1); - make_free_for_did::(&caller); + make_free_for_did::(&caller); // Add existing sender -> previous_did connection that will be replaced - Pallet::::add_association(caller.clone(), previous_did.clone(), caller.clone().into()).expect("should create previous association"); - assert!(ConnectedAccounts::::get(&previous_did, &linkable_id).is_some()); + Pallet::::add_association(caller.clone(), previous_did.clone(), caller.clone().into()).expect("should create previous association"); + assert!(ConnectedAccounts::::get(&previous_did, &linkable_id).is_some()); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); }: _(origin) verify { - assert!(ConnectedDids::::get(&linkable_id).is_some()); - assert!(ConnectedAccounts::::get(previous_did, &linkable_id).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); + assert!(ConnectedDids::::get(&linkable_id).is_some()); + assert!(ConnectedAccounts::::get(previous_did, &linkable_id).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_some()); } remove_sender_association { @@ -226,30 +226,30 @@ benchmarks! { let linkable_id: LinkableAccountId = caller.clone().into(); let did: T::DidIdentifier = account("did", 0, SEED); - make_free_for_did::(&caller); - Pallet::::add_association(caller.clone(), did.clone(), linkable_id.clone()).expect("should create association"); + make_free_for_did::(&caller); + Pallet::::add_association(caller.clone(), did.clone(), linkable_id.clone()).expect("should create association"); let origin = RawOrigin::Signed(caller); }: _(origin) verify { - assert!(ConnectedDids::::get(&linkable_id).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_none()); + assert!(ConnectedDids::::get(&linkable_id).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_none()); } remove_account_association { let caller: T::AccountId = account("caller", 0, SEED); let linkable_id: LinkableAccountId = caller.clone().into(); let did: T::DidIdentifier = account("did", 0, SEED); - make_free_for_did::(&caller); + make_free_for_did::(&caller); - Pallet::::add_association(caller.clone(), did.clone(), linkable_id.clone()).expect("should create association"); + Pallet::::add_association(caller.clone(), did.clone(), linkable_id.clone()).expect("should create association"); let origin = T::EnsureOrigin::generate_origin(caller, did.clone()); let id_arg = linkable_id.clone(); }: _(origin, id_arg) verify { - assert!(ConnectedDids::::get(&linkable_id).is_none()); - assert!(ConnectedAccounts::::get(did, linkable_id).is_none()); + assert!(ConnectedDids::::get(&linkable_id).is_none()); + assert!(ConnectedAccounts::::get(did, linkable_id).is_none()); } change_deposit_owner { @@ -257,20 +257,20 @@ benchmarks! { let deposit_owner_new: T::AccountId = account("caller", 1, SEED); let linkable_id: LinkableAccountId = deposit_owner_old.clone().into(); let did: T::DidIdentifier = account("did", 0, SEED); - make_free_for_did::(&deposit_owner_old); - make_free_for_did::(&deposit_owner_new); + make_free_for_did::(&deposit_owner_old); + make_free_for_did::(&deposit_owner_new); - Pallet::::add_association(deposit_owner_old, did.clone(), linkable_id.clone()).expect("should create association"); + Pallet::::add_association(deposit_owner_old, did.clone(), linkable_id.clone()).expect("should create association"); let origin = T::EnsureOrigin::generate_origin(deposit_owner_new.clone(), did); let id_arg = linkable_id.clone(); }: _(origin, id_arg) verify { assert_eq!( - ConnectedDids::::get(&linkable_id).expect("should retain link").deposit, + ConnectedDids::::get(&linkable_id).expect("should retain link").deposit, Deposit { owner: deposit_owner_new, - amount: ::Deposit::get(), + amount: >::Deposit::get(), }, ); } @@ -279,9 +279,9 @@ benchmarks! { let deposit_owner: T::AccountId = account("caller", 0, SEED); let linkable_id: LinkableAccountId = deposit_owner.clone().into(); let did: T::DidIdentifier = account("did", 0, SEED); - make_free_for_did::(&deposit_owner); + make_free_for_did::(&deposit_owner); - Pallet::::add_association( + Pallet::::add_association( deposit_owner.clone(), did, linkable_id.clone() @@ -292,10 +292,10 @@ benchmarks! { }: _(origin, id_arg) verify { assert_eq!( - ConnectedDids::::get(&linkable_id).expect("should retain link").deposit, + ConnectedDids::::get(&linkable_id).expect("should retain link").deposit, Deposit { owner: deposit_owner, - amount: ::Deposit::get(), + amount: >::Deposit::get(), }, ); } diff --git a/pallets/pallet-did-lookup/src/lib.rs b/pallets/pallet-did-lookup/src/lib.rs index 4653f04b8..e1f619af2 100644 --- a/pallets/pallet-did-lookup/src/lib.rs +++ b/pallets/pallet-did-lookup/src/lib.rs @@ -85,37 +85,37 @@ pub mod pallet { pub(crate) type AccountIdOf = ::AccountId; /// The identifier to which the accounts can be associated. - pub(crate) type DidIdentifierOf = ::DidIdentifier; + pub(crate) type DidIdentifierOf = >::DidIdentifier; /// The currency module that keeps track of balances. - pub(crate) type CurrencyOf = ::Currency; + pub(crate) type CurrencyOf = >::Currency; - pub type BalanceOf = as Inspect>>::Balance; + pub type BalanceOf = as Inspect>>::Balance; /// The connection record type. - pub(crate) type ConnectionRecordOf = ConnectionRecord, AccountIdOf, BalanceOf>; + pub(crate) type ConnectionRecordOf = ConnectionRecord, AccountIdOf, BalanceOf>; - pub(crate) type BalanceMigrationManagerOf = ::BalanceMigrationManager; + pub(crate) type BalanceMigrationManagerOf = >::BalanceMigrationManager; const STORAGE_VERSION: StorageVersion = StorageVersion::new(4); #[pallet::composite_enum] - pub enum HoldReason { + pub enum HoldReason { Deposit, } #[pallet::config] - pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// The origin that can associate accounts to itself. type EnsureOrigin: EnsureOrigin<::RuntimeOrigin, Success = Self::OriginSuccess>; /// The information that is returned by the origin check. - type OriginSuccess: CallSources, DidIdentifierOf>; + type OriginSuccess: CallSources, DidIdentifierOf>; /// The identifier to which accounts can get associated. type DidIdentifier: Parameter + AsRef<[u8]> + MaxEncodedLen + MaybeSerializeDeserialize; - type RuntimeHoldReason: From; + type RuntimeHoldReason: From>; /// The currency that is used to reserve funds for each did. type Currency: MutateHold, Reason = Self::RuntimeHoldReason>; @@ -124,40 +124,41 @@ pub mod pallet { /// to incentivise fair use of the on chain storage. The deposit can be /// reclaimed when the DID is deleted. #[pallet::constant] - type Deposit: Get>; + type Deposit: Get>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; /// Migration manager to handle new created entries - type BalanceMigrationManager: BalanceMigrationManager, BalanceOf>; + type BalanceMigrationManager: BalanceMigrationManager, BalanceOf>; } #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] - pub struct Pallet(_); + pub struct Pallet(_); /// Mapping from account identifiers to DIDs. #[pallet::storage] #[pallet::getter(fn connected_dids)] - pub type ConnectedDids = StorageMap<_, Blake2_128Concat, LinkableAccountId, ConnectionRecordOf>; + pub type ConnectedDids, I: 'static = ()> = + StorageMap<_, Blake2_128Concat, LinkableAccountId, ConnectionRecordOf>; /// Mapping from (DID + account identifier) -> (). /// The empty tuple is used as a sentinel value to simply indicate the /// presence of a given tuple in the map. #[pallet::storage] #[pallet::getter(fn connected_accounts)] - pub type ConnectedAccounts = - StorageDoubleMap<_, Blake2_128Concat, DidIdentifierOf, Blake2_128Concat, LinkableAccountId, ()>; + pub type ConnectedAccounts, I: 'static = ()> = + StorageDoubleMap<_, Blake2_128Concat, DidIdentifierOf, Blake2_128Concat, LinkableAccountId, ()>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { + pub enum Event, I: 'static = ()> { /// A new association between a DID and an account ID was created. - AssociationEstablished(LinkableAccountId, DidIdentifierOf), + AssociationEstablished(LinkableAccountId, DidIdentifierOf), /// An association between a DID and an account ID was removed. - AssociationRemoved(LinkableAccountId, DidIdentifierOf), + AssociationRemoved(LinkableAccountId, DidIdentifierOf), /// There was some progress in the migration process. MigrationProgress, @@ -167,7 +168,7 @@ pub mod pallet { /// The deposit for an linked account has changed owner. DepositOwnerChanged { /// The tuple of (DID, linked account) whose deposit owner changed. - id: (DidIdentifierOf, LinkableAccountId), + id: (DidIdentifierOf, LinkableAccountId), /// The old deposit owner. from: AccountIdOf, /// The new deposit owner. @@ -176,7 +177,7 @@ pub mod pallet { } #[pallet::error] - pub enum Error { + pub enum Error { /// The association does not exist. NotFound, @@ -199,39 +200,40 @@ pub mod pallet { #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] - pub struct GenesisConfig + pub struct GenesisConfig, I: 'static = ()> where >>::Balance: MaybeSerializeDeserialize, { - pub links: sp_std::vec::Vec<(LinkableAccountId, ConnectionRecordOf)>, + pub links: sp_std::vec::Vec<(LinkableAccountId, ConnectionRecordOf)>, } #[pallet::genesis_build] - impl BuildGenesisConfig for GenesisConfig + impl, I: 'static> BuildGenesisConfig for GenesisConfig where - >>::Balance: MaybeSerializeDeserialize, + <>::Currency as Inspect>>::Balance: MaybeSerializeDeserialize, { fn build(&self) { // populate link records for (acc, connection) in &self.links { - ConnectedDids::::insert(acc, connection); - ConnectedAccounts::::insert(&connection.did, acc, ()); + ConnectedDids::::insert(acc, connection); + ConnectedAccounts::::insert(&connection.did, acc, ()); } } } #[pallet::hooks] - impl Hooks> for Pallet { + impl, I: 'static> Hooks> for Pallet { #[cfg(feature = "try-runtime")] fn try_state(_n: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { - crate::try_state::do_try_state::() + crate::try_state::do_try_state::() } } #[pallet::call] - impl Pallet + impl, I: 'static> Pallet where - T::AccountId: Into + From + Into, + ::AccountId: + Into + From + Into, { /// Associate the given account to the DID that authorized this call. /// @@ -252,37 +254,37 @@ pub mod pallet { /// # #[pallet::call_index(0)] #[pallet::weight( - ::WeightInfo::associate_account_multisig_sr25519().max( - ::WeightInfo::associate_account_multisig_ed25519().max( - ::WeightInfo::associate_account_multisig_ecdsa().max( - ::WeightInfo::associate_eth_account() + >::WeightInfo::associate_account_multisig_sr25519().max( + >::WeightInfo::associate_account_multisig_ed25519().max( + >::WeightInfo::associate_account_multisig_ecdsa().max( + >::WeightInfo::associate_eth_account() ))))] pub fn associate_account( origin: OriginFor, req: AssociateAccountRequest, expiration: BlockNumberFor, ) -> DispatchResult { - let source = ::EnsureOrigin::ensure_origin(origin)?; + let source = >::EnsureOrigin::ensure_origin(origin)?; let did_identifier = source.subject(); let sender = source.sender(); ensure!( frame_system::Pallet::::current_block_number() <= expiration, - Error::::OutdatedProof + Error::::OutdatedProof ); ensure!( - >>::can_hold( + <>::Currency as InspectHold>>::can_hold( &HoldReason::Deposit.into(), &sender, - ::Deposit::get() + >::Deposit::get() ), - Error::::InsufficientFunds + Error::::InsufficientFunds ); ensure!( req.verify::>(&did_identifier, expiration), - Error::::NotAuthorized + Error::::NotAuthorized ); Self::add_association(sender, did_identifier, req.get_linkable_account())?; @@ -302,17 +304,17 @@ pub mod pallet { /// - Writes: ConnectedDids + ConnectedAccounts /// # #[pallet::call_index(1)] - #[pallet::weight(::WeightInfo::associate_sender())] + #[pallet::weight(>::WeightInfo::associate_sender())] pub fn associate_sender(origin: OriginFor) -> DispatchResult { - let source = ::EnsureOrigin::ensure_origin(origin)?; + let source = >::EnsureOrigin::ensure_origin(origin)?; ensure!( - >>::can_hold( + <>::Currency as InspectHold>>::can_hold( &HoldReason::Deposit.into(), &source.sender(), - ::Deposit::get() + >::Deposit::get() ), - Error::::InsufficientFunds + Error::::InsufficientFunds ); Self::add_association(source.sender(), source.subject(), source.sender().into())?; @@ -330,7 +332,7 @@ pub mod pallet { /// - Writes: ConnectedDids + ConnectedAccounts /// # #[pallet::call_index(2)] - #[pallet::weight(::WeightInfo::remove_sender_association())] + #[pallet::weight(>::WeightInfo::remove_sender_association())] pub fn remove_sender_association(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; @@ -349,12 +351,12 @@ pub mod pallet { /// - Writes: ConnectedDids + ConnectedAccounts /// # #[pallet::call_index(3)] - #[pallet::weight(::WeightInfo::remove_account_association())] + #[pallet::weight(>::WeightInfo::remove_account_association())] pub fn remove_account_association(origin: OriginFor, account: LinkableAccountId) -> DispatchResult { - let source = ::EnsureOrigin::ensure_origin(origin)?; + let source = >::EnsureOrigin::ensure_origin(origin)?; - let connection_record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; - ensure!(connection_record.did == source.subject(), Error::::NotAuthorized); + let connection_record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; + ensure!(connection_record.did == source.subject(), Error::::NotAuthorized); Self::remove_association(account) } @@ -371,12 +373,12 @@ pub mod pallet { /// - Writes: ConnectedDids /// # #[pallet::call_index(4)] - #[pallet::weight(::WeightInfo::remove_sender_association())] + #[pallet::weight(>::WeightInfo::remove_sender_association())] pub fn reclaim_deposit(origin: OriginFor, account: LinkableAccountId) -> DispatchResult { let who = ensure_signed(origin)?; - let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; - ensure!(record.deposit.owner == who, Error::::NotAuthorized); + let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; + ensure!(record.deposit.owner == who, Error::::NotAuthorized); Self::remove_association(account) } @@ -388,20 +390,20 @@ pub mod pallet { /// The subject of the call must be linked to the account. /// The sender of the call will be the new deposit owner. #[pallet::call_index(5)] - #[pallet::weight(::WeightInfo::change_deposit_owner())] + #[pallet::weight(>::WeightInfo::change_deposit_owner())] pub fn change_deposit_owner(origin: OriginFor, account: LinkableAccountId) -> DispatchResult { - let source = ::EnsureOrigin::ensure_origin(origin)?; + let source = >::EnsureOrigin::ensure_origin(origin)?; let subject = source.subject(); let sender = source.sender(); - let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; - ensure!(record.did == subject, Error::::NotAuthorized); + let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; + ensure!(record.did == subject, Error::::NotAuthorized); - let old_deposit_owner = LinkableAccountDepositCollector::::change_deposit_owner::< - BalanceMigrationManagerOf, + let old_deposit_owner = LinkableAccountDepositCollector::::change_deposit_owner::< + BalanceMigrationManagerOf, >(&account, sender.clone())?; - Self::deposit_event(Event::::DepositOwnerChanged { + Self::deposit_event(Event::::DepositOwnerChanged { id: (subject, account), from: old_deposit_owner, to: sender, @@ -414,14 +416,14 @@ pub mod pallet { /// /// The sender must be the deposit owner. #[pallet::call_index(6)] - #[pallet::weight(::WeightInfo::update_deposit())] + #[pallet::weight(>::WeightInfo::update_deposit())] pub fn update_deposit(origin: OriginFor, account: LinkableAccountId) -> DispatchResult { let source = ensure_signed(origin)?; - let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; - ensure!(record.deposit.owner == source, Error::::NotAuthorized); + let record = ConnectedDids::::get(&account).ok_or(Error::::NotFound)?; + ensure!(record.deposit.owner == source, Error::::NotAuthorized); - LinkableAccountDepositCollector::::update_deposit::>(&account) + LinkableAccountDepositCollector::::update_deposit::>(&account) } // Old call that was used to migrate @@ -429,10 +431,10 @@ pub mod pallet { // pub fn migrate(origin: OriginFor, limit: u32) -> DispatchResult } - impl Pallet { + impl, I: 'static> Pallet { pub fn add_association( sender: AccountIdOf, - did_identifier: DidIdentifierOf, + did_identifier: DidIdentifierOf, account: LinkableAccountId, ) -> DispatchResult { let deposit = Deposit { @@ -444,68 +446,72 @@ pub mod pallet { did: did_identifier.clone(), }; - LinkableAccountDepositCollector::::create_deposit(record.clone().deposit.owner, record.deposit.amount)?; - ::BalanceMigrationManager::exclude_key_from_migration(&ConnectedDids::::hashed_key_for( - &account, - )); + LinkableAccountDepositCollector::::create_deposit( + record.clone().deposit.owner, + record.deposit.amount, + )?; + >::BalanceMigrationManager::exclude_key_from_migration( + &ConnectedDids::::hashed_key_for(&account), + ); - ConnectedDids::::mutate(&account, |did_entry| -> DispatchResult { + ConnectedDids::::mutate(&account, |did_entry| -> DispatchResult { if let Some(old_connection) = did_entry.replace(record) { - ConnectedAccounts::::remove(&old_connection.did, &account); - Self::deposit_event(Event::::AssociationRemoved(account.clone(), old_connection.did)); - LinkableAccountDepositCollector::::free_deposit(old_connection.deposit)?; + ConnectedAccounts::::remove(&old_connection.did, &account); + Self::deposit_event(Event::::AssociationRemoved(account.clone(), old_connection.did)); + LinkableAccountDepositCollector::::free_deposit(old_connection.deposit)?; } Ok(()) })?; - ConnectedAccounts::::insert(&did_identifier, &account, ()); + ConnectedAccounts::::insert(&did_identifier, &account, ()); Self::deposit_event(Event::AssociationEstablished(account, did_identifier)); Ok(()) } pub(crate) fn remove_association(account: LinkableAccountId) -> DispatchResult { - if let Some(connection) = ConnectedDids::::take(&account) { - let is_key_migrated = ::BalanceMigrationManager::is_key_migrated( - &ConnectedDids::::hashed_key_for(&account), + if let Some(connection) = ConnectedDids::::take(&account) { + let is_key_migrated = >::BalanceMigrationManager::is_key_migrated( + &ConnectedDids::::hashed_key_for(&account), ); if is_key_migrated { - LinkableAccountDepositCollector::::free_deposit(connection.deposit)?; + LinkableAccountDepositCollector::::free_deposit(connection.deposit)?; } else { - ::BalanceMigrationManager::release_reserved_deposit( + >::BalanceMigrationManager::release_reserved_deposit( &connection.deposit.owner, &connection.deposit.amount, ) } - ConnectedAccounts::::remove(&connection.did, &account); + ConnectedAccounts::::remove(&connection.did, &account); Self::deposit_event(Event::AssociationRemoved(account, connection.did)); Ok(()) } else { - Err(Error::::NotFound.into()) + Err(Error::::NotFound.into()) } } } - pub(crate) struct LinkableAccountDepositCollector(PhantomData); - impl StorageDepositCollector, LinkableAccountId, T::RuntimeHoldReason> - for LinkableAccountDepositCollector + pub(crate) struct LinkableAccountDepositCollector, I: 'static = ()>(PhantomData<(T, I)>); + impl, I: 'static> + StorageDepositCollector, LinkableAccountId, >::RuntimeHoldReason> + for LinkableAccountDepositCollector { type Currency = T::Currency; - type Reason = HoldReason; + type Reason = HoldReason; fn reason() -> Self::Reason { HoldReason::Deposit } fn get_hashed_key(key: &LinkableAccountId) -> Result, DispatchError> { - Ok(ConnectedDids::::hashed_key_for(key)) + Ok(ConnectedDids::::hashed_key_for(key)) } fn deposit( key: &LinkableAccountId, ) -> Result, >>::Balance>, DispatchError> { - let record = ConnectedDids::::get(key).ok_or(Error::::NotFound)?; + let record = ConnectedDids::::get(key).ok_or(Error::::NotFound)?; Ok(record.deposit) } @@ -517,8 +523,8 @@ pub mod pallet { key: &LinkableAccountId, deposit: Deposit, >>::Balance>, ) -> Result<(), DispatchError> { - let record = ConnectedDids::::get(key).ok_or(Error::::NotFound)?; - ConnectedDids::::insert(key, ConnectionRecord { deposit, ..record }); + let record = ConnectedDids::::get(key).ok_or(Error::::NotFound)?; + ConnectedDids::::insert(key, ConnectionRecord { deposit, ..record }); Ok(()) } } diff --git a/pallets/pallet-did-lookup/src/migrations.rs b/pallets/pallet-did-lookup/src/migrations.rs index de6b5185e..a8227c1d3 100644 --- a/pallets/pallet-did-lookup/src/migrations.rs +++ b/pallets/pallet-did-lookup/src/migrations.rs @@ -26,11 +26,10 @@ use crate::{linkable_account::LinkableAccountId, AccountIdOf, Config, ConnectedD pub fn update_balance_for_did_lookup(key: &LinkableAccountId) -> DispatchResult where - ::Currency: - ReservableCurrency::Currency as Inspect>>::Balance>, + T::Currency: ReservableCurrency>>::Balance>, { let details = ConnectedDids::::get(key).ok_or(Error::::NotFound)?; - switch_reserved_to_hold::, CurrencyOf>( + switch_reserved_to_hold::, CurrencyOf>( &details.deposit.owner, &HoldReason::Deposit.into(), details.deposit.amount, diff --git a/pallets/pallet-did-lookup/src/mock.rs b/pallets/pallet-did-lookup/src/mock.rs index e8f6e3602..124ce1016 100644 --- a/pallets/pallet-did-lookup/src/mock.rs +++ b/pallets/pallet-did-lookup/src/mock.rs @@ -136,9 +136,9 @@ pub(crate) const LINKABLE_ACCOUNT_01: LinkableAccountId = LinkableAccountId::Acc pub(crate) fn insert_raw_connection( sender: AccountIdOf, - did_identifier: DidIdentifierOf, + did_identifier: DidIdentifierOf, account: LinkableAccountId, - deposit: BalanceOf, + deposit: BalanceOf, ) { let deposit = LinkableAccountDepositCollector::::create_deposit(sender, deposit) .expect("Account should have enough balance"); @@ -204,7 +204,7 @@ impl ExtBuilder { pub fn build_and_execute_with_sanity_tests(self, test: impl FnOnce()) { self.build().execute_with(|| { test(); - crate::try_state::do_try_state::().expect("Sanity test for did lookup failed."); + crate::try_state::do_try_state::().expect("Sanity test for did lookup failed."); }) } diff --git a/pallets/pallet-did-lookup/src/try_state.rs b/pallets/pallet-did-lookup/src/try_state.rs index 3e846943f..a7fb1c6ae 100644 --- a/pallets/pallet-did-lookup/src/try_state.rs +++ b/pallets/pallet-did-lookup/src/try_state.rs @@ -23,19 +23,19 @@ use sp_runtime::TryRuntimeError; use crate::{Config, ConnectedAccounts, ConnectedDids}; -pub(crate) fn do_try_state() -> Result<(), TryRuntimeError> { - ConnectedDids::::iter().try_for_each(|(account, record)| -> Result<(), TryRuntimeError> { +pub(crate) fn do_try_state, I: 'static>() -> Result<(), TryRuntimeError> { + ConnectedDids::::iter().try_for_each(|(account, record)| -> Result<(), TryRuntimeError> { ensure!( - ConnectedAccounts::::contains_key(&record.did, &account), + ConnectedAccounts::::contains_key(&record.did, &account), log_and_return_error_message(format!("Account {:?} with did {:?} not found", record.did, account)) ); Ok(()) })?; - ConnectedAccounts::::iter().try_for_each( + ConnectedAccounts::::iter().try_for_each( |(did_identifier, linked_account_id, _)| -> Result<(), TryRuntimeError> { ensure!( - ConnectedDids::::get(&linked_account_id).expect("Unknown did").did == did_identifier, + ConnectedDids::::get(&linked_account_id).expect("Unknown did").did == did_identifier, log_and_return_error_message(format!( "Linked Account {:?} for did {:?} not match", linked_account_id, did_identifier