From 1402eff08dd5142704db3b6b83922b46021f8ba8 Mon Sep 17 00:00:00 2001 From: Henrique Nogara Date: Fri, 7 Feb 2025 13:28:22 -0300 Subject: [PATCH 1/3] Remove getters - part 1 --- pallets/balances/src/lib.rs | 16 +- pallets/bridge/src/lib.rs | 5 - .../compliance-manager/src/benchmarking.rs | 20 +-- pallets/compliance-manager/src/lib.rs | 27 ++- pallets/contracts/src/lib.rs | 5 +- pallets/corporate-actions/src/ballot/mod.rs | 6 - .../corporate-actions/src/distribution/mod.rs | 8 +- pallets/corporate-actions/src/lib.rs | 27 ++- pallets/external-agents/src/lib.rs | 11 +- pallets/identity/src/auth.rs | 10 +- pallets/identity/src/benchmarking.rs | 12 +- pallets/identity/src/keys.rs | 27 +-- pallets/identity/src/lib.rs | 18 -- pallets/multisig/src/benchmarking.rs | 6 +- pallets/multisig/src/lib.rs | 40 ++--- pallets/nft/src/benchmarking.rs | 2 +- pallets/nft/src/lib.rs | 11 +- pallets/permissions/src/lib.rs | 10 +- pallets/protocol-fee/src/lib.rs | 6 +- .../tests/src/compliance_manager_test.rs | 28 +-- .../tests/src/corporate_actions_test.rs | 70 ++++---- .../runtime/tests/src/external_agents_test.rs | 34 ++-- pallets/runtime/tests/src/identity_test.rs | 37 ++-- pallets/runtime/tests/src/multisig.rs | 42 ++--- pallets/runtime/tests/src/portfolio.rs | 5 +- .../tests/src/settlement_pallet/setup.rs | 3 +- pallets/runtime/tests/src/settlement_test.rs | 164 +++++++++++------- pallets/runtime/tests/src/staking/mod.rs | 9 +- pallets/runtime/tests/src/sto_test.rs | 29 ++-- .../tests/src/transaction_payment_test.rs | 6 +- .../tests/src/transfer_compliance_test.rs | 5 +- pallets/runtime/tests/src/treasury_test.rs | 16 +- pallets/runtime/tests/src/utility_test.rs | 9 +- pallets/settlement/src/benchmarking.rs | 18 +- pallets/settlement/src/lib.rs | 73 +++----- pallets/statistics/src/benchmarking.rs | 2 +- pallets/statistics/src/lib.rs | 14 +- pallets/sto/src/benchmarking.rs | 3 +- pallets/sto/src/lib.rs | 9 +- pallets/sudo/src/extension.rs | 5 +- pallets/sudo/src/lib.rs | 5 +- pallets/sudo/src/mock.rs | 6 +- pallets/sudo/src/tests.rs | 30 ++-- pallets/transaction-payment/src/lib.rs | 4 +- pallets/utility/src/benchmarking.rs | 2 +- pallets/utility/src/lib.rs | 3 +- 46 files changed, 434 insertions(+), 464 deletions(-) diff --git a/pallets/balances/src/lib.rs b/pallets/balances/src/lib.rs index d573d9b8a4..922f6b33ee 100644 --- a/pallets/balances/src/lib.rs +++ b/pallets/balances/src/lib.rs @@ -411,15 +411,13 @@ pub mod pallet { /// The total units issued in the system. #[pallet::storage] - #[pallet::getter(fn total_issuance)] - pub(super) type TotalIssuance = StorageValue<_, Balance, ValueQuery>; + pub type TotalIssuance = StorageValue<_, Balance, ValueQuery>; /// Any liquidity locks on some account balances. /// NOTE: Should only be accessed when setting, changing and freeing a lock. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn locks)] - pub(super) type Locks = + pub type Locks = StorageMap<_, Blake2_128Concat, T::AccountId, Vec>, ValueQuery>; #[pallet::genesis_config] @@ -1398,7 +1396,7 @@ impl LockableCurrency for Pallet { amount, reasons: reasons.into(), }; - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); if let Some(pos) = locks.iter().position(|l| l.id == id) { locks[pos] = new_lock; } else { @@ -1419,7 +1417,7 @@ impl LockableCurrency for Pallet { return; } let reasons = reasons.into(); - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); if let Some(pos) = locks.iter().position(|l| l.id == id) { let slot = &mut locks[pos]; slot.amount = slot.amount.max(amount); @@ -1435,7 +1433,7 @@ impl LockableCurrency for Pallet { } fn remove_lock(id: LockIdentifier, who: &T::AccountId) { - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); locks.retain(|l| l.id != id); Self::update_locks(who, &locks[..]); } @@ -1446,7 +1444,7 @@ impl LockableCurrencyExt for Pallet { if amount.is_zero() { return Ok(()); } - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); locks .iter() .position(|l| l.id == id) @@ -1474,7 +1472,7 @@ impl LockableCurrencyExt for Pallet { return Ok(()); } let reasons = reasons.into(); - let mut locks = Self::locks(who); + let mut locks = Locks::::get(who); check_sum(if let Some(pos) = locks.iter().position(|l| l.id == id) { let slot = &mut locks[pos]; slot.amount = slot diff --git a/pallets/bridge/src/lib.rs b/pallets/bridge/src/lib.rs index d240952173..6251bcda40 100644 --- a/pallets/bridge/src/lib.rs +++ b/pallets/bridge/src/lib.rs @@ -129,31 +129,26 @@ pub mod pallet { /// The bridge transaction timelock period, in blocks, since the acceptance of the /// transaction proposal during which the admin key can freeze the transaction. #[pallet::storage] - #[pallet::getter(fn timelock)] pub(super) type Timelock = StorageValue<_, T::BlockNumber, ValueQuery>; /// The maximum number of bridged POLYX per identity within a set interval of /// blocks. Fields: POLYX amount and the block interval duration. #[pallet::storage] - #[pallet::getter(fn bridge_limit)] pub(super) type BridgeLimit = StorageValue<_, (Balance, T::BlockNumber), ValueQuery>; /// Amount of POLYX bridged by the identity in last block interval. Fields: the bridged /// amount and the last interval number. #[pallet::storage] - #[pallet::getter(fn polyx_bridged)] pub(super) type PolyxBridged = StorageMap<_, Identity, IdentityId, (Balance, T::BlockNumber), ValueQuery>; /// Identities not constrained by the bridge limit. #[pallet::storage] - #[pallet::getter(fn bridge_exempted)] pub(super) type BridgeLimitExempted = StorageMap<_, Twox64Concat, IdentityId, bool, ValueQuery>; /// Storage version. #[pallet::storage] - #[pallet::getter(fn storage_version)] pub(super) type StorageVersion = StorageValue<_, Version, ValueQuery>; #[pallet::genesis_config] diff --git a/pallets/compliance-manager/src/benchmarking.rs b/pallets/compliance-manager/src/benchmarking.rs index 5a88052677..98364b8187 100644 --- a/pallets/compliance-manager/src/benchmarking.rs +++ b/pallets/compliance-manager/src/benchmarking.rs @@ -361,7 +361,7 @@ benchmarks! { }: _(d.owner.origin, d.asset_id, d.sender_conditions.clone(), d.receiver_conditions.clone()) verify { - let req = Pallet::::asset_compliance(d.asset_id).requirements.pop().unwrap(); + let req = AssetCompliances::::get(d.asset_id).requirements.pop().unwrap(); assert_eq!( req.sender_conditions, d.sender_conditions, "Sender conditions not expected"); assert_eq!( req.receiver_conditions, d.receiver_conditions, "Sender conditions not expected"); } @@ -377,7 +377,7 @@ benchmarks! { let id = Pallet::::get_latest_requirement_id(d.asset_id); }: _(d.owner.origin, d.asset_id, id) verify { - let is_removed = Pallet::::asset_compliance(d.asset_id) + let is_removed = AssetCompliances::::get(d.asset_id) .requirements .into_iter() .find(|r| r.id == id) @@ -393,7 +393,7 @@ benchmarks! { .add_compliance_requirement().build(); }: _(d.owner.origin, d.asset_id) verify { - assert!( Pallet::::asset_compliance(d.asset_id).paused, "Asset compliance is not paused"); + assert!( AssetCompliances::::get(d.asset_id).paused, "Asset compliance is not paused"); } resume_asset_compliance { @@ -405,7 +405,7 @@ benchmarks! { d.asset_id.clone()).unwrap(); }: _(d.owner.origin, d.asset_id) verify { - assert!( !Pallet::::asset_compliance(d.asset_id).paused, "Asset compliance is paused"); + assert!( !AssetCompliances::::get(d.asset_id).paused, "Asset compliance is paused"); } add_default_trusted_claim_issuer { @@ -419,7 +419,7 @@ benchmarks! { let new_issuer = make_issuer::(MAX_DEFAULT_TRUSTED_CLAIM_ISSUERS, None); }: _(d.owner.origin, d.asset_id, new_issuer.clone()) verify { - let trusted_issuers = Pallet::::trusted_claim_issuer(d.asset_id); + let trusted_issuers = TrustedClaimIssuer::::get(d.asset_id); assert!( trusted_issuers.contains(&new_issuer), "Default trusted claim issuer was not added"); @@ -434,10 +434,10 @@ benchmarks! { d.add_default_trusted_claim_issuer(MAX_DEFAULT_TRUSTED_CLAIM_ISSUERS); // Delete the latest trusted issuer. - let issuer = Pallet::::trusted_claim_issuer(d.asset_id).pop().unwrap(); + let issuer = TrustedClaimIssuer::::get(d.asset_id).pop().unwrap(); }: _(d.owner.origin, d.asset_id, issuer.issuer.clone()) verify { - let trusted_issuers = Pallet::::trusted_claim_issuer(d.asset_id); + let trusted_issuers = TrustedClaimIssuer::::get(d.asset_id); assert!( !trusted_issuers.contains(&issuer), "Default trusted claim issuer was not removed" @@ -466,7 +466,7 @@ benchmarks! { }; }: _(d.owner.origin, d.asset_id, new_req.clone()) verify { - let req = Pallet::::asset_compliance(d.asset_id) + let req = AssetCompliances::::get(d.asset_id) .requirements .into_iter() .find(|req| req.id == new_req.id) @@ -506,7 +506,7 @@ benchmarks! { }}).collect::>(); }: _(d.owner.origin, d.asset_id, asset_compliance.clone()) verify { - let reqs = Pallet::::asset_compliance(d.asset_id).requirements; + let reqs = AssetCompliances::::get(d.asset_id).requirements; assert_eq!( reqs, asset_compliance, "Asset compliance was not replaced"); } @@ -519,7 +519,7 @@ benchmarks! { }: _(d.owner.origin, d.asset_id) verify { assert!( - Pallet::::asset_compliance(d.asset_id).requirements.is_empty(), + AssetCompliances::::get(d.asset_id).requirements.is_empty(), "Compliance Requeriment was not reset"); } diff --git a/pallets/compliance-manager/src/lib.rs b/pallets/compliance-manager/src/lib.rs index ec8e378058..fd8286b1db 100644 --- a/pallets/compliance-manager/src/lib.rs +++ b/pallets/compliance-manager/src/lib.rs @@ -83,7 +83,7 @@ use frame_support::traits::Get; use frame_support::weights::Weight; use frame_system::pallet_prelude::OriginFor; use pallet_base::ensure_length_ok; -use pallet_external_agents::Config as EAConfig; +use pallet_external_agents::{Config as EAConfig, GroupOfAgent}; use polymesh_common_utilities::protocol_fee::{ChargeProtocolFee, ProtocolOp}; use polymesh_primitives::asset::AssetId; use polymesh_primitives::compliance_manager::{ @@ -91,11 +91,10 @@ use polymesh_primitives::compliance_manager::{ ConditionReport, ConditionResult, RequirementReport, }; use polymesh_primitives::condition::{conditions_total_counts, Condition}; +use polymesh_primitives::traits::{AssetFnConfig, ComplianceFnConfig}; use polymesh_primitives::{ - proposition, storage_migration_ver, - traits::{AssetFnConfig, ComplianceFnConfig}, - Claim, ConditionType, Context, IdentityId, TargetIdentity, TrustedFor, TrustedIssuer, - WeightMeter, + proposition, storage_migration_ver, Claim, ConditionType, Context, IdentityId, TargetIdentity, + TrustedFor, TrustedIssuer, WeightMeter, }; use sp_std::{convert::From, prelude::*}; @@ -220,15 +219,13 @@ pub mod pallet { /// Compliance for an asset ([`AssetId`] -> [`AssetCompliance`]) #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_compliance)] - pub(super) type AssetCompliances = + pub type AssetCompliances = StorageMap<_, Blake2_128Concat, AssetId, AssetCompliance, ValueQuery>; /// List of trusted claim issuer [`AssetId`] -> Issuer Identity #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn trusted_claim_issuer)] - pub(super) type TrustedClaimIssuer = + pub type TrustedClaimIssuer = StorageMap<_, Blake2_128Concat, AssetId, Vec, ValueQuery>; /// Storage version. @@ -646,7 +643,7 @@ impl Pallet { slot: &'a mut Option>, ) -> &'a [TrustedIssuer] { if condition.issuers.is_empty() { - slot.get_or_insert_with(|| Self::trusted_claim_issuer(asset_id)) + slot.get_or_insert_with(|| TrustedClaimIssuer::::get(asset_id)) } else { &condition.issuers } @@ -740,7 +737,7 @@ impl Pallet { weight_meter: &mut WeightMeter, ) -> Result { let context = Self::fetch_context(did, asset_id, slot, &condition, weight_meter)?; - let any_ea = |ctx: Context<_>| ExternalAgents::::agents(asset_id, ctx.id).is_some(); + let any_ea = |ctx: Context<_>| GroupOfAgent::::get(asset_id, ctx.id).is_some(); Ok(proposition::run(&condition, context, any_ea)) } @@ -781,7 +778,7 @@ impl Pallet { /// Compute the id of the last requirement in an asset's compliance rules. fn get_latest_requirement_id(asset_id: AssetId) -> u32 { - Self::asset_compliance(asset_id) + AssetCompliances::::get(asset_id) .requirements .last() .map(|r| r.id) @@ -899,7 +896,7 @@ impl ComplianceFnConfig for Pallet { receiver_did: IdentityId, weight_meter: &mut WeightMeter, ) -> Result { - let asset_compliance = Self::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); // If there are no requirements or compliance is paused, no rules are checked. if asset_compliance.paused || asset_compliance.requirements.is_empty() { @@ -925,7 +922,7 @@ impl ComplianceFnConfig for Pallet { weight_meter: &mut WeightMeter, ) -> Result { let mut compliance_with_results = - AssetComplianceResult::from(Self::asset_compliance(asset_id)); + AssetComplianceResult::from(AssetCompliances::::get(asset_id)); // Evaluates all conditions. // False result in any of the conditions => False requirement result. @@ -969,7 +966,7 @@ impl Pallet { receiver_identity: &IdentityId, weight_meter: &mut WeightMeter, ) -> Result { - let asset_compliance = Self::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); if asset_compliance.requirements.is_empty() { return Ok(ComplianceReport::new( diff --git a/pallets/contracts/src/lib.rs b/pallets/contracts/src/lib.rs index 534e7aa96f..84409b5d19 100644 --- a/pallets/contracts/src/lib.rs +++ b/pallets/contracts/src/lib.rs @@ -383,7 +383,6 @@ pub mod pallet { /// Whitelist of extrinsics allowed to be called from contracts. #[pallet::storage] - #[pallet::getter(fn call_runtime_whitelist)] pub type CallRuntimeWhitelist = StorageMap<_, Identity, ExtrinsicId, bool, ValueQuery>; /// Storage version. @@ -392,12 +391,10 @@ pub mod pallet { /// Stores the chain version and code hash for the next chain upgrade. #[pallet::storage] - #[pallet::getter(fn next_upgrade)] pub type ApiNextUpgrade = StorageMap<_, Twox64Concat, Api, NextUpgrade, OptionQuery>; /// Stores the code hash for the current api. #[pallet::storage] - #[pallet::getter(fn current_api_hash)] pub type CurrentApiHash = StorageMap<_, Twox64Concat, Api, ApiCodeHash, OptionQuery>; /// GenesisConfig for the contracts module. @@ -665,7 +662,7 @@ where pub fn ensure_call_runtime(ext_id: ExtrinsicId) -> DispatchResult { ensure!( - Self::call_runtime_whitelist(ext_id), + CallRuntimeWhitelist::::get(ext_id), Error::::RuntimeCallDenied ); Ok(()) diff --git a/pallets/corporate-actions/src/ballot/mod.rs b/pallets/corporate-actions/src/ballot/mod.rs index cc6339ecbf..dea3a8411f 100644 --- a/pallets/corporate-actions/src/ballot/mod.rs +++ b/pallets/corporate-actions/src/ballot/mod.rs @@ -287,7 +287,6 @@ pub mod pallet { /// /// (CAId) => BallotMeta #[pallet::storage] - #[pallet::getter(fn metas)] #[pallet::unbounded] pub type Metas = StorageMap<_, Blake2_128Concat, CAId, BallotMeta>; @@ -296,7 +295,6 @@ pub mod pallet { /// /// (CAId) => BallotTimeRange #[pallet::storage] - #[pallet::getter(fn time_ranges)] pub type TimeRanges = StorageMap<_, Blake2_128Concat, CAId, BallotTimeRange>; /// Stores how many choices there are in each motion. @@ -309,7 +307,6 @@ pub mod pallet { /// /// (CAId) => Number of choices in each motion. #[pallet::storage] - #[pallet::getter(fn motion_choices)] #[pallet::unbounded] pub type MotionNumChoices = StorageMap<_, Blake2_128Concat, CAId, Vec, ValueQuery>; @@ -319,7 +316,6 @@ pub mod pallet { /// /// (CAId) => bool #[pallet::storage] - #[pallet::getter(fn rcv)] pub type RCV = StorageMap<_, Blake2_128Concat, CAId, bool, ValueQuery>; /// Stores the total vote tally on each choice. @@ -330,7 +326,6 @@ pub mod pallet { /// /// (CAId) => [current vote weights] #[pallet::storage] - #[pallet::getter(fn results)] #[pallet::unbounded] pub type Results = StorageMap<_, Blake2_128Concat, CAId, Vec, ValueQuery>; @@ -341,7 +336,6 @@ pub mod pallet { /// /// User must enter 0 vote weight if they don't want to vote for a choice. #[pallet::storage] - #[pallet::getter(fn votes)] #[pallet::unbounded] pub type Votes = StorageDoubleMap< _, diff --git a/pallets/corporate-actions/src/distribution/mod.rs b/pallets/corporate-actions/src/distribution/mod.rs index 52a5e60bff..551f0163bd 100644 --- a/pallets/corporate-actions/src/distribution/mod.rs +++ b/pallets/corporate-actions/src/distribution/mod.rs @@ -172,20 +172,18 @@ pub mod pallet { /// /// (CAId) => Distribution #[pallet::storage] - #[pallet::getter(fn distributions)] - pub(super) type Distributions = StorageMap<_, Blake2_128Concat, CAId, Distribution>; + pub type Distributions = StorageMap<_, Blake2_128Concat, CAId, Distribution>; /// Has an asset holder been paid yet? /// /// (CAId, DID) -> Was DID paid in the CAId? #[pallet::storage] - #[pallet::getter(fn holder_paid)] - pub(super) type HolderPaid = + pub(crate) type HolderPaid = StorageMap<_, Blake2_128Concat, (CAId, IdentityId), bool, ValueQuery>; /// Storage version. #[pallet::storage] - pub(super) type StorageVersion = StorageValue<_, Version, ValueQuery>; + pub(crate) type StorageVersion = StorageValue<_, Version, ValueQuery>; #[pallet::genesis_config] #[derive(Default)] diff --git a/pallets/corporate-actions/src/lib.rs b/pallets/corporate-actions/src/lib.rs index 9d90306538..97c6954743 100644 --- a/pallets/corporate-actions/src/lib.rs +++ b/pallets/corporate-actions/src/lib.rs @@ -91,8 +91,9 @@ pub mod benchmarking; pub mod ballot; pub mod distribution; +use ballot::TimeRanges; use codec::{Decode, Encode, MaxEncodedLen}; -use distribution::WeightInfo as DistWeightInfoTrait; +use distribution::{Distributions, WeightInfo as DistWeightInfoTrait}; use frame_support::{ dispatch::{DispatchError, DispatchResult}, ensure, @@ -444,7 +445,6 @@ pub mod pallet { /// /// [graphemes]: https://en.wikipedia.org/wiki/Grapheme #[pallet::storage] - #[pallet::getter(fn max_details_length)] pub type MaxDetailsLength = StorageValue<_, u32, ValueQuery>; /// The identities targeted by default for CAs for this asset, @@ -453,7 +453,6 @@ pub mod pallet { /// (AssetId => target identities) #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn default_target_identities)] pub type DefaultTargetIdentities = StorageMap<_, Blake2_128Concat, AssetId, TargetIdentities, ValueQuery>; @@ -466,7 +465,6 @@ pub mod pallet { /// /// (AssetId => % to withhold) #[pallet::storage] - #[pallet::getter(fn default_withholding_tax)] pub type DefaultWithholdingTax = StorageMap<_, Blake2_128Concat, AssetId, Tax, ValueQuery>; /// The amount of tax to withhold ("withholding tax", WT) for a certain AssetId x DID. @@ -475,14 +473,12 @@ pub mod pallet { /// (AssetId => [(did, % to withhold)] #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn did_withholding_tax)] pub type DidWithholdingTax = StorageMap<_, Blake2_128Concat, AssetId, Vec<(IdentityId, Tax)>, ValueQuery>; /// The next per-`AssetId` CA ID in the sequence. /// The full ID is defined as a combination of `AssetId` and a number in this sequence. #[pallet::storage] - #[pallet::getter(fn ca_id_sequence)] pub type CAIdSequence = StorageMap<_, Blake2_128Concat, AssetId, LocalCAId, ValueQuery>; /// All recorded CAs thus far. @@ -492,7 +488,6 @@ pub mod pallet { /// (AssetId => local ID => the corporate action) #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn corporate_actions)] pub type CorporateActions = StorageDoubleMap< _, Blake2_128Concat, @@ -510,14 +505,12 @@ pub mod pallet { /// so we can infer `AssetId => CAId`. Therefore, we don't need a double map. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn ca_doc_link)] pub type CADocLink = StorageMap<_, Blake2_128Concat, CAId, Vec, ValueQuery>; /// Associates details in free-form text with a CA by its ID. /// (CAId => CADetails) #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn record_dates)] pub type Details = StorageMap<_, Blake2_128Concat, CAId, CADetails, ValueQuery>; /// Storage version. @@ -785,12 +778,12 @@ pub mod pallet { match ca.kind { CAKind::Other | CAKind::Reorganization => {} CAKind::IssuerNotice => { - if let Some(range) = >::time_ranges(ca_id) { + if let Some(range) = TimeRanges::::get(ca_id) { >::remove_ballot_base(agent, ca_id, range)?; } } CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => { - if let Some(dist) = >::distributions(ca_id) { + if let Some(dist) = Distributions::::get(ca_id) { >::unverified_remove_distribution(agent, ca_id, &dist)?; } } @@ -844,13 +837,13 @@ pub mod pallet { match ca.kind { CAKind::Other | CAKind::Reorganization => {} CAKind::IssuerNotice => { - if let Some(range) = >::time_ranges(ca_id) { + if let Some(range) = TimeRanges::::get(ca_id) { Self::ensure_record_date_before_start(&ca, range.start)?; >::ensure_ballot_not_started(range)?; } } CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => { - if let Some(dist) = >::distributions(ca_id) { + if let Some(dist) = Distributions::::get(ca_id) { Self::ensure_record_date_before_start(&ca, dist.payment_at)?; >::ensure_distribution_not_started(&dist)?; } @@ -997,7 +990,7 @@ impl Pallet { let agent = caller_did.for_event(); // Ensure that `details` is short enough. ensure!( - details.len() <= Self::max_details_length() as usize, + details.len() <= MaxDetailsLength::::get() as usize, Error::::DetailsTooLong ); @@ -1045,11 +1038,11 @@ impl Pallet { // Use asset level defaults if data not provided here. let targets = targets .map(|t| t.dedup()) - .unwrap_or_else(|| Self::default_target_identities(asset_id)); + .unwrap_or_else(|| DefaultTargetIdentities::::get(asset_id)); let default_withholding_tax = - default_withholding_tax.unwrap_or_else(|| Self::default_withholding_tax(asset_id)); + default_withholding_tax.unwrap_or_else(|| DefaultWithholdingTax::::get(asset_id)); let withholding_tax = - withholding_tax.unwrap_or_else(|| Self::did_withholding_tax(asset_id)); + withholding_tax.unwrap_or_else(|| DidWithholdingTax::::get(asset_id)); // Commit CA to storage. let ca = CorporateAction { diff --git a/pallets/external-agents/src/lib.rs b/pallets/external-agents/src/lib.rs index 06f8911736..1064ba5236 100644 --- a/pallets/external-agents/src/lib.rs +++ b/pallets/external-agents/src/lib.rs @@ -55,9 +55,11 @@ pub mod benchmarking; use codec::{Decode, Encode}; use frame_support::{pallet_prelude::*, weights::Weight}; use frame_system::pallet_prelude::*; + use pallet_base::{try_next_post, try_next_pre}; use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData}; use pallet_permissions::Config as PermConfig; +use pallet_permissions::{CurrentDispatchableName, CurrentPalletName}; use polymesh_primitives::agent::{AGId, AgentGroup}; use polymesh_primitives::asset::AssetId; use polymesh_primitives::{ @@ -68,7 +70,6 @@ use polymesh_primitives::{ use sp_std::prelude::*; type Identity = pallet_identity::Pallet; -type Permissions = pallet_permissions::Pallet; pub use pallet::*; @@ -104,7 +105,6 @@ pub mod pallet { /// The full ID is defined as a combination of `AssetId` and a number in this sequence, /// which starts from 1, rather than 0. #[pallet::storage] - #[pallet::getter(fn agent_group_id_sequence)] pub type AGIdSequence = StorageMap<_, Blake2_128Concat, AssetId, AGId, ValueQuery>; /// Maps an agent (`IdentityId`) to all assets they belong to, if any. @@ -121,19 +121,16 @@ pub mod pallet { /// Maps agents (`IdentityId`) for an `AssetId` to what AG they belong to, if any. #[pallet::storage] - #[pallet::getter(fn agents)] pub type GroupOfAgent = StorageDoubleMap<_, Blake2_128Concat, AssetId, Twox64Concat, IdentityId, AgentGroup>; /// Maps an `AssetId` to the number of `Full` agents for it. #[pallet::storage] - #[pallet::getter(fn num_full_agents)] pub type NumFullAgents = StorageMap<_, Blake2_128Concat, AssetId, u32, ValueQuery>; /// For custom AGs of an `AssetId`, maps to what permissions an agent in that AG would have. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn permissions)] pub type GroupPermissions = StorageDoubleMap<_, Blake2_128Concat, AssetId, Twox64Concat, AGId, ExtrinsicPermissions>; @@ -619,8 +616,8 @@ impl Pallet { pub fn ensure_agent_permissioned(asset_id: &AssetId, agent: IdentityId) -> DispatchResult { ensure!( Self::agent_permissions(asset_id, agent).sufficient_for( - &>::current_pallet_name(), - &>::current_dispatchable_name() + &CurrentPalletName::::get(), + &CurrentDispatchableName::::get() ), Error::::UnauthorizedAgent ); diff --git a/pallets/identity/src/auth.rs b/pallets/identity/src/auth.rs index f4dd6b902b..7e018650ad 100644 --- a/pallets/identity/src/auth.rs +++ b/pallets/identity/src/auth.rs @@ -15,7 +15,7 @@ use crate::{ AuthorizationType, Authorizations, AuthorizationsGiven, Config, CurrentAuthId, Error, Event, - KeyRecords, NumberOfGivenAuths, Pallet, + KeyRecords, NumberOfGivenAuths, OutdatedAuthorizations, Pallet, }; use frame_support::dispatch::DispatchResult; use frame_support::ensure; @@ -63,7 +63,7 @@ impl Pallet { ); NumberOfGivenAuths::::insert(from, number_of_given_auths.saturating_add(1)); - let new_auth_id = Self::current_auth_id().saturating_add(1); + let new_auth_id = CurrentAuthId::::get().saturating_add(1); CurrentAuthId::::put(new_auth_id); let auth = Authorization { @@ -163,7 +163,7 @@ impl Pallet { target: &Signatory, auth_id: &u64, ) -> Option> { - Self::authorizations(target, *auth_id).filter(|auth| { + Authorizations::::get(target, *auth_id).filter(|auth| { auth.expiry .filter(|&expiry| >::get() > expiry) .is_none() @@ -216,9 +216,9 @@ impl Pallet { auth_id: u64, ) -> Result, DispatchError> { let auth = - Self::authorizations(target, auth_id).ok_or_else(|| AuthorizationError::Invalid)?; + Authorizations::::get(target, auth_id).ok_or_else(|| AuthorizationError::Invalid)?; // Ensures the authorization is not outdated - if let Some(outdated_id) = Self::outdated_authorizations(target) { + if let Some(outdated_id) = OutdatedAuthorizations::::get(target) { if auth_id <= outdated_id { return Err(AuthorizationError::Invalid.into()); } diff --git a/pallets/identity/src/benchmarking.rs b/pallets/identity/src/benchmarking.rs index 2eb38c696a..067aea8f3c 100644 --- a/pallets/identity/src/benchmarking.rs +++ b/pallets/identity/src/benchmarking.rs @@ -73,7 +73,7 @@ benchmarks! { let expires_at: T::Moment = 600u32.into(); let authorization = TargetIdAuthorization:: { target_id: parent_did, - nonce: Pallet::::offchain_authorization_nonce(parent_did), + nonce: OffChainAuthorizationNonce::::get(parent_did), expires_at, }; let auth_encoded = authorization.encode(); @@ -205,13 +205,13 @@ benchmarks! { change_cdd_requirement_for_mk_rotation { assert!( - !Pallet::::cdd_auth_for_primary_key_rotation(), + !CddAuthForPrimaryKeyRotation::::get(), "CDD auth for primary key rotation is enabled" ); }: _(RawOrigin::Root, true) verify { assert!( - Pallet::::cdd_auth_for_primary_key_rotation(), + CddAuthForPrimaryKeyRotation::::get(), "CDD auth for primary key rotation did not change" ); } @@ -376,7 +376,7 @@ benchmarks! { let expires_at: T::Moment = 600u32.into(); let authorization = TargetIdAuthorization:: { target_id: caller.did(), - nonce: Pallet::::offchain_authorization_nonce(caller.did()), + nonce: OffChainAuthorizationNonce::::get(caller.did()), expires_at, }; let auth_encoded = authorization.encode(); @@ -393,12 +393,12 @@ benchmarks! { register_custom_claim_type { let n in 1 .. T::MaxLen::get() as u32; - let id = Pallet::::custom_claim_id_seq(); + let id = CustomClaimIdSequence::::get(); let caller = user::("caller", 0); let ty = vec![b'X'; n as usize]; }: _(caller.origin, ty) verify { - assert_ne!(id, Pallet::::custom_claim_id_seq()); + assert_ne!(id, CustomClaimIdSequence::::get()); } } diff --git a/pallets/identity/src/keys.rs b/pallets/identity/src/keys.rs index 520c2fd457..811c985d02 100644 --- a/pallets/identity/src/keys.rs +++ b/pallets/identity/src/keys.rs @@ -14,10 +14,11 @@ // along with this program. If not, see . use crate::{ - types, AccountKeyRefCount, ChildDid, Claim, Config, CurrentAuthId, DidKeys, DidRecords, Error, - Event, IsDidFrozen, KeyAssetPermissions, KeyExtrinsicPermissions, KeyPortfolioPermissions, - KeyRecords, MultiPurposeNonce, OffChainAuthorizationNonce, OutdatedAuthorizations, Pallet, - ParentDid, PermissionedCallOriginData, RpcDidRecords, + types, AccountKeyRefCount, CddAuthForPrimaryKeyRotation, ChildDid, Claim, Config, + CurrentAuthId, DidKeys, DidRecords, Error, Event, IsDidFrozen, KeyAssetPermissions, + KeyExtrinsicPermissions, KeyPortfolioPermissions, KeyRecords, MultiPurposeNonce, + OffChainAuthorizationNonce, OutdatedAuthorizations, Pallet, ParentDid, + PermissionedCallOriginData, RpcDidRecords, }; use codec::{Decode, Encode as _}; use frame_support::dispatch::DispatchResult; @@ -85,7 +86,7 @@ impl Pallet { pub fn get_identity(key: &T::AccountId) -> Option { match KeyRecords::::get(key)? { KeyRecord::PrimaryKey(did) => Some(did), - KeyRecord::SecondaryKey(did) if !Self::is_did_frozen(did) => Some(did), + KeyRecord::SecondaryKey(did) if !IsDidFrozen::::get(did) => Some(did), // Is a multisig signer, or frozen secondary key. _ => None, } @@ -348,7 +349,7 @@ impl Pallet { let signer = Signatory::Account(new_primary_key.clone()); // Accept authorization from CDD service provider. - if Self::cdd_auth_for_primary_key_rotation() { + if CddAuthForPrimaryKeyRotation::::get() { let auth_id = optional_cdd_auth_id .ok_or_else(|| Error::::InvalidAuthorizationFromCddProvider)?; @@ -518,7 +519,7 @@ impl Pallet { ensure!(now < expires_at, Error::::AuthorizationExpired); let authorization = TargetIdAuthorization { target_id: parent_did, - nonce: Self::offchain_authorization_nonce(parent_did), + nonce: OffChainAuthorizationNonce::::get(parent_did), expires_at, }; let auth_encoded = authorization.encode(); @@ -657,7 +658,7 @@ impl Pallet { // Create authorization data that the keys need to sign. let authorization = TargetIdAuthorization { target_id: did, - nonce: Self::offchain_authorization_nonce(did), + nonce: OffChainAuthorizationNonce::::get(did), expires_at, }; let auth_encoded = authorization.encode(); @@ -779,7 +780,7 @@ impl Pallet { /// Create a new DID out of the parent block hash and a `nonce`. fn make_did() -> Result { - let nonce = Self::multi_purpose_nonce() + 7u64; + let nonce = MultiPurposeNonce::::get() + 7u64; // Even if this transaction fails, nonce should be increased for added unpredictability of dids MultiPurposeNonce::::put(&nonce); @@ -890,7 +891,7 @@ impl Pallet { /// Ensure the `key` is a secondary key of the identity `did`. fn ensure_secondary_key(did: IdentityId, key: &T::AccountId) -> DispatchResult { - let key_did = Self::key_records(key).and_then(|rec| rec.is_secondary_key()); + let key_did = KeyRecords::::get(key).and_then(|rec| rec.is_secondary_key()); ensure!(key_did == Some(did), Error::::NotASigner); Ok(()) } @@ -900,8 +901,8 @@ impl Pallet { origin: T::RuntimeOrigin, ) -> Result<(T::AccountId, IdentityId), DispatchError> { let sender = ensure_signed(origin)?; - let key_rec = - Self::key_records(&sender).ok_or(pallet_permissions::Error::::UnauthorizedCaller)?; + let key_rec = KeyRecords::::get(&sender) + .ok_or(pallet_permissions::Error::::UnauthorizedCaller)?; let did = key_rec.is_primary_key().ok_or(Error::::KeyNotAllowed)?; Ok((sender, did)) } @@ -988,7 +989,7 @@ impl CheckAccountCallPermissions for Pallet { // Primary keys do not have / require further permission checks. KeyRecord::PrimaryKey(did) => Some(data(did, None)), // Secondary Key. Ensure DID isn't frozen + key has sufficient permissions. - KeyRecord::SecondaryKey(did) if !Self::is_did_frozen(&did) => { + KeyRecord::SecondaryKey(did) if !IsDidFrozen::::get(&did) => { let permissions = Self::get_key_permissions(who); let sk = SecondaryKey { key: who.clone(), diff --git a/pallets/identity/src/lib.rs b/pallets/identity/src/lib.rs index 93330ced77..3922eba07d 100644 --- a/pallets/identity/src/lib.rs +++ b/pallets/identity/src/lib.rs @@ -393,13 +393,11 @@ pub mod pallet { /// DID -> identity info #[pallet::storage] - #[pallet::getter(fn did_records)] pub type DidRecords = StorageMap<_, Identity, IdentityId, DidRecord, OptionQuery>; /// DID -> bool that indicates if secondary keys are frozen. #[pallet::storage] - #[pallet::getter(fn is_did_frozen)] pub type IsDidFrozen = StorageMap<_, Identity, IdentityId, bool, ValueQuery>; /// It stores the current gas fee payer for the current transaction. @@ -433,57 +431,48 @@ pub mod pallet { /// The next `CustomClaimTypeId`. #[pallet::storage] - #[pallet::getter(fn custom_claim_id_seq)] pub type CustomClaimIdSequence = StorageValue<_, CustomClaimTypeId, ValueQuery>; /// Map from AccountId to `KeyRecord` that holds the key's type and identity. #[pallet::storage] - #[pallet::getter(fn key_records)] pub type KeyRecords = StorageMap<_, Twox64Concat, T::AccountId, KeyRecord, OptionQuery>; /// A secondary key's extrinsic permissions. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn key_extrinsic_permissions)] pub type KeyExtrinsicPermissions = StorageMap<_, Twox64Concat, T::AccountId, ExtrinsicPermissions, OptionQuery>; /// A secondary key's asset permissions. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn key_asset_permissions)] pub type KeyAssetPermissions = StorageMap<_, Twox64Concat, T::AccountId, AssetPermissions, OptionQuery>; /// A secondary key's portfolio permissions. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn key_portfolio_permissions)] pub type KeyPortfolioPermissions = StorageMap<_, Twox64Concat, T::AccountId, PortfolioPermissions, OptionQuery>; /// A reverse double map to allow finding all keys for an identity. #[pallet::storage] - #[pallet::getter(fn did_keys)] pub type DidKeys = StorageDoubleMap<_, Identity, IdentityId, Twox64Concat, T::AccountId, bool, ValueQuery>; /// Nonce to ensure unique actions. starts from 1. #[pallet::storage] - #[pallet::getter(fn multi_purpose_nonce)] pub type MultiPurposeNonce = StorageValue<_, u64, ValueQuery>; /// Authorization nonce per Identity. Initially is 0. #[pallet::storage] - #[pallet::getter(fn offchain_authorization_nonce)] pub type OffChainAuthorizationNonce = StorageMap<_, Identity, IdentityId, AuthorizationNonce, ValueQuery>; /// All authorizations that an identity/key has #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn authorizations)] pub type Authorizations = StorageDoubleMap< _, Blake2_128Concat, @@ -509,7 +498,6 @@ pub mod pallet { /// A config flag that, if set, instructs an authorization from a CDD provider in order to /// change the primary key of an identity. #[pallet::storage] - #[pallet::getter(fn cdd_auth_for_primary_key_rotation)] pub type CddAuthForPrimaryKeyRotation = StorageValue<_, bool, ValueQuery>; /// Storage version. @@ -524,35 +512,29 @@ pub mod pallet { /// * Relayer: For `user_key` and `paying_key` /// #[pallet::storage] - #[pallet::getter(fn account_key_ref_count)] pub type AccountKeyRefCount = StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>; /// Parent identity if the DID is a child Identity. #[pallet::storage] - #[pallet::getter(fn parent_did)] pub type ParentDid = StorageMap<_, Identity, IdentityId, IdentityId, OptionQuery>; /// All child identities of a parent (i.e ParentDID, ChildDID, true) #[pallet::storage] - #[pallet::getter(fn child_did)] pub type ChildDid = StorageDoubleMap<_, Identity, IdentityId, Identity, IdentityId, bool, ValueQuery>; /// Track the number of authorizations given by each identity. #[pallet::storage] - #[pallet::getter(fn number_of_given_auths)] pub type NumberOfGivenAuths = StorageMap<_, Identity, IdentityId, u32, ValueQuery>; /// Tracks all authorizations that must be deleted #[pallet::storage] - #[pallet::getter(fn outdated_authorizations)] pub type OutdatedAuthorizations = StorageMap<_, Blake2_128Concat, Signatory, u64, OptionQuery>; /// Controls the authorization id. #[pallet::storage] - #[pallet::getter(fn current_auth_id)] pub type CurrentAuthId = StorageValue<_, u64, ValueQuery>; /// GenesisConfig for the identity pallet. diff --git a/pallets/multisig/src/benchmarking.rs b/pallets/multisig/src/benchmarking.rs index 9fefcb8ec3..d4f046eafa 100644 --- a/pallets/multisig/src/benchmarking.rs +++ b/pallets/multisig/src/benchmarking.rs @@ -152,7 +152,7 @@ fn generate_multisig_and_proposal_for_alice( > { let (alice, multisig, signers, users, _) = generate_multisig_for_alice::(total_signers, signers_required).unwrap(); - let proposal_id = MultiSig::::next_proposal_id(multisig.clone()); + let proposal_id = NextProposalId::::get(multisig.clone()); let proposal = Box::new(frame_system::Call::::remark { remark: vec![] }.into()); Ok(( alice, @@ -195,13 +195,13 @@ fn generate_multisig_and_create_proposal( macro_rules! assert_proposal_created { ($proposal_id:ident, $multisig:ident) => { - assert!($proposal_id < MultiSig::::next_proposal_id($multisig)); + assert!($proposal_id < NextProposalId::::get($multisig)); }; } macro_rules! assert_vote_cast { ($proposal_id:ident, $multisig:ident, $signatory:expr) => { - assert!(MultiSig::::votes(($multisig, $proposal_id), $signatory)); + assert!(Votes::::get(($multisig, $proposal_id), $signatory)); }; } diff --git a/pallets/multisig/src/lib.rs b/pallets/multisig/src/lib.rs index fc53c119dc..1addb71e75 100644 --- a/pallets/multisig/src/lib.rs +++ b/pallets/multisig/src/lib.rs @@ -83,7 +83,9 @@ use sp_runtime::traits::{Dispatchable, Hash}; use sp_std::convert::TryFrom; use sp_std::prelude::*; -use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData}; +use pallet_identity::{ + CddAuthForPrimaryKeyRotation, Config as IdentityConfig, PermissionedCallOriginData, +}; use pallet_permissions::with_call_metadata; use polymesh_primitives::multisig::{ProposalState, ProposalVoteCount}; use polymesh_primitives::{ @@ -544,7 +546,7 @@ pub mod pallet { }) } else { let proposal = Call::::join_identity { auth_id }.into(); - let proposal_id = Self::next_proposal_id(&multisig); + let proposal_id = NextProposalId::::get(&multisig); AuthToProposalId::::insert(&multisig, auth_id, proposal_id); with_base_weight(::WeightInfo::create_join_identity(), || { Self::base_create_proposal(&multisig, signer, &proposal, None) @@ -731,7 +733,6 @@ pub mod pallet { /// Nonce to ensure unique MultiSig addresses are generated; starts from 1. #[pallet::storage] - #[pallet::getter(fn ms_nonce)] pub type MultiSigNonce = StorageValue<_, u64, ValueQuery>; /// Signers of a multisig. (multisig, signer) => bool. @@ -741,12 +742,10 @@ pub mod pallet { /// Number of approved/accepted signers of a multisig. #[pallet::storage] - #[pallet::getter(fn number_of_signers)] pub type NumberOfSigners = StorageMap<_, Identity, T::AccountId, u64, ValueQuery>; /// Confirmations required before processing a multisig tx. #[pallet::storage] - #[pallet::getter(fn ms_signs_required)] pub type MultiSigSignsRequired = StorageMap<_, Identity, T::AccountId, u64, ValueQuery>; @@ -754,14 +753,12 @@ pub mod pallet { /// /// multisig => next proposal id #[pallet::storage] - #[pallet::getter(fn next_proposal_id)] pub type NextProposalId = StorageMap<_, Identity, T::AccountId, u64, ValueQuery>; /// Proposals presented for voting to a multisig. /// /// multisig -> proposal id => Option. #[pallet::storage] - #[pallet::getter(fn proposals)] pub type Proposals = StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, u64, ::Proposal>; @@ -769,7 +766,6 @@ pub mod pallet { /// /// (multisig, proposal_id) -> signer => vote. #[pallet::storage] - #[pallet::getter(fn votes)] pub type Votes = StorageDoubleMap< _, Twox64Concat, @@ -798,7 +794,6 @@ pub mod pallet { /// /// multisig -> proposal id => Option. #[pallet::storage] - #[pallet::getter(fn proposal_vote_counts)] pub type ProposalVoteCounts = StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, u64, ProposalVoteCount>; @@ -806,7 +801,6 @@ pub mod pallet { /// /// multisig -> proposal id => Option. #[pallet::storage] - #[pallet::getter(fn proposal_states)] pub type ProposalStates = StorageDoubleMap< _, Twox64Concat, @@ -818,7 +812,6 @@ pub mod pallet { /// Proposal execution reentry guard. #[pallet::storage] - #[pallet::getter(fn execution_reentry)] pub(super) type ExecutionReentry = StorageValue<_, bool, ValueQuery>; /// Pending join identity authorization proposals. @@ -830,20 +823,17 @@ pub mod pallet { /// The last transaction version, used for `on_runtime_upgrade`. #[pallet::storage] - #[pallet::getter(fn transaction_version)] pub(super) type TransactionVersion = StorageValue<_, u32, ValueQuery>; /// The last proposal id before the multisig changed signers or signatures required. /// /// multisig => Option #[pallet::storage] - #[pallet::getter(fn last_invalid_proposal)] pub type LastInvalidProposal = StorageMap<_, Identity, T::AccountId, u64, OptionQuery>; /// Storage version. #[pallet::storage] - #[pallet::getter(fn storage_version)] pub(super) type StorageVersion = StorageValue<_, Version, ValueQuery>; #[pallet::genesis_config] @@ -1029,7 +1019,7 @@ impl Pallet { permissions: Permissions, ) -> DispatchResult { // Generate new MultiSig address. - let new_nonce = Self::ms_nonce() + let new_nonce = MultiSigNonce::::get() .checked_add(1) .ok_or(Error::::NonceOverflow)?; MultiSigNonce::::put(new_nonce); @@ -1066,7 +1056,7 @@ impl Pallet { Self::ensure_ms_signer(multisig, &signer)?; let max_weight = proposal.get_dispatch_info().weight; let caller_did = Self::ensure_ms_get_did(multisig)?; - let proposal_id = Self::next_proposal_id(multisig); + let proposal_id = NextProposalId::::get(multisig); Self::ensure_valid_expiry(&expiry)?; Proposals::::insert(multisig, proposal_id, &*proposal); @@ -1095,7 +1085,7 @@ impl Pallet { Self::ensure_ms_signer(multisig, &signer)?; let caller_did = Self::ensure_ms_get_did(multisig)?; ensure!( - !Self::votes((multisig, proposal_id), &signer), + !Votes::::get((multisig, proposal_id), &signer), Error::::AlreadyVoted ); ensure!( @@ -1106,7 +1096,7 @@ impl Pallet { let mut vote_count = ProposalVoteCounts::::try_get(multisig, proposal_id) .map_err(|_| Error::::ProposalMissing)?; vote_count.approvals += 1u64; - let execute_proposal = vote_count.approvals >= Self::ms_signs_required(multisig); + let execute_proposal = vote_count.approvals >= MultiSigSignsRequired::::get(multisig); // Update storage Votes::::insert((multisig, proposal_id), &signer, true); @@ -1152,7 +1142,7 @@ impl Pallet { let (result, actual_weight) = match with_call_metadata::(proposal.get_call_metadata(), || { // Check execution reentry guard. - ensure!(!Self::execution_reentry(), Error::::NestingNotAllowed,); + ensure!(!ExecutionReentry::::get(), Error::::NestingNotAllowed,); // Enable reentry guard before executing the proposal. ExecutionReentry::::set(true); @@ -1228,8 +1218,8 @@ impl Pallet { Votes::::insert((multisig, proposal_id), &signer, true); vote_count.rejections += 1u64; - let approvals_needed = Self::ms_signs_required(&multisig); - let ms_signers = Self::number_of_signers(&multisig); + let approvals_needed = MultiSigSignsRequired::::get(&multisig); + let ms_signers = NumberOfSigners::::get(&multisig); if vote_count.rejections > ms_signers.saturating_sub(approvals_needed) || proposal_owner { if proposal_owner { vote_count.approvals = 0; @@ -1308,7 +1298,7 @@ impl Pallet { pub fn get_next_multisig_address(caller: T::AccountId) -> Result { // Nonce is always only incremented by small numbers and hence can never overflow 64 bits. // Also, this is just a helper function that does not modify state. - let new_nonce = Self::ms_nonce() + 1; + let new_nonce = MultiSigNonce::::get() + 1; Self::get_multisig_address(&caller, new_nonce) } @@ -1328,7 +1318,7 @@ impl Pallet { /// Checks whether changing the list of signers is allowed in a multisig. pub fn is_changing_signers_allowed(multisig: &T::AccountId) -> bool { - if IdentityPallet::::cdd_auth_for_primary_key_rotation() { + if CddAuthForPrimaryKeyRotation::::get() { if let Some(did) = IdentityPallet::::get_identity(multisig) { if IdentityPallet::::is_primary_key(&did, multisig) { return false; @@ -1374,7 +1364,7 @@ impl Pallet { /// Returns `Ok` if `proposal_id` is valid. Otherwise, returns [`Error::InvalidatedProposal`]. fn ensure_valid_proposal(multisig: &T::AccountId, proposal_id: u64) -> DispatchResult { - if let Some(last_invalid_proposal) = Self::last_invalid_proposal(multisig) { + if let Some(last_invalid_proposal) = LastInvalidProposal::::get(multisig) { ensure!( proposal_id > last_invalid_proposal, Error::::InvalidatedProposal @@ -1385,7 +1375,7 @@ impl Pallet { /// Sets [`LastInvalidProposal`] with the proposal id of the last proposal. fn set_invalid_proposals(multisig: &T::AccountId) { - let next_proposal_id = Self::next_proposal_id(multisig); + let next_proposal_id = NextProposalId::::get(multisig); // There are no proposals for the multisig if next_proposal_id == 0 { diff --git a/pallets/nft/src/benchmarking.rs b/pallets/nft/src/benchmarking.rs index ab02f03f73..1a3b3fb268 100644 --- a/pallets/nft/src/benchmarking.rs +++ b/pallets/nft/src/benchmarking.rs @@ -35,7 +35,7 @@ fn create_collection(collection_owner: &User, n: u32) -> (AssetId, collection_keys, ) .expect("failed to create nft collection"); - (asset_id, Pallet::::current_collection_id().unwrap()) + (asset_id, CurrentCollectionId::::get().unwrap()) } /// Creates a set of `NFTCollectionKeys` made of `n` global keys and registers `n` global asset metadata types. diff --git a/pallets/nft/src/lib.rs b/pallets/nft/src/lib.rs index 6a2caa2c1e..27c647af7f 100644 --- a/pallets/nft/src/lib.rs +++ b/pallets/nft/src/lib.rs @@ -90,33 +90,28 @@ pub mod pallet { /// The total number of NFTs per identity. #[pallet::storage] - #[pallet::getter(fn number_of_nfts)] pub type NumberOfNFTs = StorageDoubleMap<_, Blake2_128Concat, AssetId, Identity, IdentityId, NFTCount, ValueQuery>; /// The collection id corresponding to each asset. #[pallet::storage] - #[pallet::getter(fn collection_asset)] pub type CollectionAsset = StorageMap<_, Blake2_128Concat, AssetId, NFTCollectionId, ValueQuery>; /// All collection details for a given collection id. #[pallet::storage] - #[pallet::getter(fn collection)] pub type Collection = StorageMap<_, Blake2_128Concat, NFTCollectionId, NFTCollection, ValueQuery>; /// All mandatory metadata keys for a given collection. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn collection_keys)] pub type CollectionKeys = StorageMap<_, Blake2_128Concat, NFTCollectionId, BTreeSet, ValueQuery>; /// The metadata value of an nft given its collection id, token id and metadata key. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn metadata_value)] pub type MetadataValue = StorageDoubleMap< _, Blake2_128Concat, @@ -129,13 +124,11 @@ pub mod pallet { /// The total number of NFTs in a collection. #[pallet::storage] - #[pallet::getter(fn nfts_in_collection)] pub type NFTsInCollection = StorageMap<_, Blake2_128Concat, AssetId, NFTCount, ValueQuery>; /// Tracks the owner of an NFT #[pallet::storage] - #[pallet::getter(fn nft_owner)] pub type NFTOwner = StorageDoubleMap< _, Blake2_128Concat, @@ -148,13 +141,11 @@ pub mod pallet { /// The last `NFTId` used for an NFT. #[pallet::storage] - #[pallet::getter(fn current_nft_id)] pub type CurrentNFTId = StorageMap<_, Blake2_128Concat, NFTCollectionId, NFTId, OptionQuery>; /// The last `NFTCollectionId` used for a collection. #[pallet::storage] - #[pallet::getter(fn current_collection_id)] pub type CurrentCollectionId = StorageValue<_, NFTCollectionId, OptionQuery>; #[pallet::genesis_config] @@ -457,7 +448,7 @@ impl Pallet { Portfolio::::ensure_portfolio_validity(&caller_portfolio)?; // Verifies that all mandatory keys are being set and that there are no duplicated keys - let mandatory_keys: BTreeSet = Self::collection_keys(&collection_id); + let mandatory_keys: BTreeSet = CollectionKeys::::get(&collection_id); ensure!( mandatory_keys.len() == metadata_attributes.len(), Error::::InvalidMetadataAttribute diff --git a/pallets/permissions/src/lib.rs b/pallets/permissions/src/lib.rs index 6171fb2cb6..330820498e 100644 --- a/pallets/permissions/src/lib.rs +++ b/pallets/permissions/src/lib.rs @@ -86,14 +86,12 @@ pub mod pallet { /// The name of the current pallet (aka module name). #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn current_pallet_name)] - pub(super) type CurrentPalletName = StorageValue<_, PalletName, ValueQuery>; + pub type CurrentPalletName = StorageValue<_, PalletName, ValueQuery>; /// The name of the current function (aka extrinsic). #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn current_dispatchable_name)] - pub(super) type CurrentDispatchableName = StorageValue<_, ExtrinsicName, ValueQuery>; + pub type CurrentDispatchableName = StorageValue<_, ExtrinsicName, ValueQuery>; #[pallet::error] pub enum Error { @@ -109,8 +107,8 @@ pub mod pallet { ) -> Result, DispatchError> { T::Checker::check_account_call_permissions( who, - || Self::current_pallet_name(), - || Self::current_dispatchable_name(), + || CurrentPalletName::::get(), + || CurrentDispatchableName::::get(), ) .ok_or_else(|| Error::::UnauthorizedCaller.into()) } diff --git a/pallets/protocol-fee/src/lib.rs b/pallets/protocol-fee/src/lib.rs index 80b982f369..81c0d18111 100644 --- a/pallets/protocol-fee/src/lib.rs +++ b/pallets/protocol-fee/src/lib.rs @@ -101,12 +101,10 @@ pub mod pallet { /// The mapping of operation names to the base fees of those operations. #[pallet::storage] - #[pallet::getter(fn base_fees)] pub type BaseFees = StorageMap<_, Twox64Concat, ProtocolOp, Balance, ValueQuery>; /// The fee coefficient as a positive rational (numerator, denominator). #[pallet::storage] - #[pallet::getter(fn coefficient)] pub type Coefficient = StorageValue<_, PosRatio, ValueQuery>; #[pallet::genesis_config] @@ -184,11 +182,11 @@ pub mod pallet { impl Pallet { /// Computes the fee of the operation as `(base_fee * coefficient.0) / coefficient.1`. pub fn compute_fee(ops: &[ProtocolOp]) -> Balance { - let coefficient = Self::coefficient(); + let coefficient = Coefficient::::get(); let ratio = Perbill::from_rational(coefficient.0, coefficient.1); let base = ops .iter() - .fold(Zero::zero(), |a: Balance, e| a + Self::base_fees(e)); + .fold(Zero::zero(), |a: Balance, e| a + BaseFees::::get(e)); ratio * base } diff --git a/pallets/runtime/tests/src/compliance_manager_test.rs b/pallets/runtime/tests/src/compliance_manager_test.rs index 4b966c1120..478dbb6ca1 100644 --- a/pallets/runtime/tests/src/compliance_manager_test.rs +++ b/pallets/runtime/tests/src/compliance_manager_test.rs @@ -3,7 +3,7 @@ use frame_support::traits::Currency; use frame_support::{assert_noop, assert_ok}; use sp_std::prelude::*; -use pallet_compliance_manager::Error as CMError; +use pallet_compliance_manager::{AssetCompliances, Error as CMError, TrustedClaimIssuer}; use polymesh_primitives::agent::AgentGroup; use polymesh_primitives::asset::AssetId; use polymesh_primitives::compliance_manager::{ @@ -71,7 +71,7 @@ macro_rules! assert_add_claim { } fn get_latest_requirement_id(asset_id: AssetId) -> u32 { - ComplianceManager::asset_compliance(asset_id) + AssetCompliances::::get(asset_id) .requirements .last() .map(|r| r.id) @@ -442,7 +442,7 @@ fn should_replace_asset_compliance_we() { Balances::make_free_balance_be(&owner.acc(), 1_000_000); - let asset_compliance = ComplianceManager::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance.requirements.len(), 1); // Create three requirements with different requirement IDs. @@ -463,7 +463,7 @@ fn should_replace_asset_compliance_we() { new_asset_compliance.clone(), )); - let asset_compliance = ComplianceManager::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance.requirements, new_asset_compliance); } @@ -485,7 +485,7 @@ fn test_dedup_replace_asset_compliance_we() { Balances::make_free_balance_be(&owner.acc(), 1_000_000); - let asset_compliance = ComplianceManager::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance.requirements.len(), 1); let make_req = |id: u32| ComplianceRequirement { @@ -533,7 +533,7 @@ fn should_reset_asset_compliance_we() { Balances::make_free_balance_be(&owner.acc(), 1_000_000); - let asset_compliance = ComplianceManager::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance.requirements.len(), 1); assert_ok!(ComplianceManager::reset_asset_compliance( @@ -541,7 +541,7 @@ fn should_reset_asset_compliance_we() { asset_id )); - let asset_compliance_new = ComplianceManager::asset_compliance(asset_id); + let asset_compliance_new = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance_new.requirements.len(), 0); } @@ -661,9 +661,9 @@ fn should_successfully_add_and_use_default_issuers_we() { add_issuer(ti); } - assert_eq!(ComplianceManager::trusted_claim_issuer(asset_id).len(), 3); + assert_eq!(TrustedClaimIssuer::::get(asset_id).len(), 3); assert_eq!( - ComplianceManager::trusted_claim_issuer(asset_id), + TrustedClaimIssuer::::get(asset_id), trusted_issuers ); assert_ok!(Identity::add_claim( @@ -760,9 +760,9 @@ fn should_modify_vector_of_trusted_issuer_we() { trusted_issuer_2.issuer() )); - assert_eq!(ComplianceManager::trusted_claim_issuer(asset_id).len(), 2); + assert_eq!(TrustedClaimIssuer::::get(asset_id).len(), 2); assert_eq!( - ComplianceManager::trusted_claim_issuer(asset_id), + TrustedClaimIssuer::::get(asset_id), vec![trusted_issuer_1.issuer(), trusted_issuer_2.issuer()] ); @@ -825,9 +825,9 @@ fn should_modify_vector_of_trusted_issuer_we() { trusted_issuer_1.did )); - assert_eq!(ComplianceManager::trusted_claim_issuer(asset_id).len(), 1); + assert_eq!(TrustedClaimIssuer::::get(asset_id).len(), 1); assert_eq!( - ComplianceManager::trusted_claim_issuer(asset_id), + TrustedClaimIssuer::::get(asset_id), vec![trusted_issuer_2.issuer()] ); @@ -1561,7 +1561,7 @@ fn should_limit_compliance_requirements_complexity_we() { CMError::::ComplianceRequirementTooComplex ); - let asset_compliance = ComplianceManager::asset_compliance(asset_id); + let asset_compliance = AssetCompliances::::get(asset_id); assert_eq!(asset_compliance.requirements.len(), 1); } diff --git a/pallets/runtime/tests/src/corporate_actions_test.rs b/pallets/runtime/tests/src/corporate_actions_test.rs index 8a31aa6cb5..ee8e2f749a 100644 --- a/pallets/runtime/tests/src/corporate_actions_test.rs +++ b/pallets/runtime/tests/src/corporate_actions_test.rs @@ -12,10 +12,14 @@ use frame_support::{ }; use pallet_asset::Assets; use pallet_corporate_actions::{ - ballot::{BallotMeta, BallotTimeRange, BallotVote, Motion, Votes}, - distribution::{self, Distribution, PER_SHARE_PRECISION}, - CACheckpoint, CADetails, CAId, CAKind, CorporateAction, LocalCAId, RecordDate, RecordDateSpec, - TargetIdentities, TargetTreatment, + ballot::{ + BallotMeta, BallotTimeRange, BallotVote, Metas, Motion, MotionNumChoices, Results, + TimeRanges, Votes, RCV, + }, + distribution::{self, Distribution, Distributions, PER_SHARE_PRECISION}, + CACheckpoint, CADetails, CADocLink, CAId, CAKind, CorporateAction, DefaultTargetIdentities, + DefaultWithholdingTax, DidWithholdingTax, LocalCAId, MaxDetailsLength, RecordDate, + RecordDateSpec, TargetIdentities, TargetTreatment, TargetTreatment::{Exclude, Include}, Tax, }; @@ -131,7 +135,7 @@ fn transfer_caa(asset_id: AssetId, from: User, to: User) -> DispatchResult { type CAResult = Result; fn get_ca(id: CAId) -> Option { - CA::corporate_actions(id.asset_id, id.local_id) + CorporateActions::get(id.asset_id, id.local_id) } fn init_ca( @@ -195,7 +199,7 @@ fn set_schedule_complexity() { } fn next_ca_id(asset_id: AssetId) -> CAId { - let local_id = CA::ca_id_sequence(asset_id); + let local_id = CAIdSequence::get(asset_id); CAId { asset_id, local_id } } @@ -216,11 +220,11 @@ struct BallotData { fn ballot_data(id: CAId) -> BallotData { BallotData { - meta: Ballot::metas(id), - range: Ballot::time_ranges(id), - choices: Ballot::motion_choices(id), - rcv: Ballot::rcv(id), - results: Ballot::results(id), + meta: Metas::::get(id), + range: TimeRanges::::get(id), + choices: MotionNumChoices::::get(id), + rcv: RCV::::get(id), + results: Results::::get(id), votes: Votes::::iter_prefix(id).collect(), } } @@ -391,7 +395,7 @@ fn set_default_targets_works() { treatment, identities: expect_ids, }; - assert_eq!(CA::default_target_identities(asset_id), ids); + assert_eq!(DefaultTargetIdentities::::get(asset_id), ids); }; let expect = vec![foo.did, bar.did]; set(Exclude, expect.clone(), expect.clone()); @@ -403,13 +407,13 @@ fn set_default_targets_works() { #[test] fn set_default_withholding_tax_works() { test(|asset_id, [owner, ..]| { - assert_eq!(CA::default_withholding_tax(asset_id), P0); + assert_eq!(DefaultWithholdingTax::::get(asset_id), P0); assert_ok!(CA::set_default_withholding_tax( owner.origin(), asset_id, P50 )); - assert_eq!(CA::default_withholding_tax(asset_id), P50); + assert_eq!(DefaultWithholdingTax::::get(asset_id), P50); }); } @@ -457,7 +461,7 @@ fn set_did_withholding_tax_works() { user.did, tax )); - assert_eq!(CA::did_withholding_tax(asset_id), expect); + assert_eq!(DidWithholdingTax::::get(asset_id), expect); }; check(bar, Some(P25), vec![(bar.did, P25)]); check(foo, Some(P75), vec![(foo.did, P75), (bar.did, P25)]); @@ -475,7 +479,7 @@ fn set_max_details_length_only_root() { DispatchError::BadOrigin, ); assert_ok!(CA::set_max_details_length(root(), 10)); - assert_eq!(CA::max_details_length(), 10); + assert_eq!(MaxDetailsLength::::get(), 10); }); } @@ -722,7 +726,7 @@ fn link_ca_docs_works() { let link = |docs| CA::link_ca_doc(owner.origin(), id, docs); let link_ok = |docs: Vec<_>| { assert_ok!(link(docs.clone())); - assert_eq!(CA::ca_doc_link(id), docs); + assert_eq!(CADocLink::::get(id), docs); }; // Link to a CA that doesn't exist, and ensure failure. @@ -757,7 +761,7 @@ fn remove_ca_works() { let assert_no_ca = |id: CAId| { assert_eq!(None, get_ca(id)); - assert_eq!(CA::ca_doc_link(id), vec![]); + assert_eq!(CADocLink::::get(id), vec![]); }; // Remove a CA that doesn't exist, and ensure failure. @@ -769,7 +773,7 @@ fn remove_ca_works() { add_doc(owner, asset_id); let docs = vec![DocumentId(0)]; assert_ok!(CA::link_ca_doc(owner.origin(), id, docs.clone())); - assert_eq!(docs, CA::ca_doc_link(id)); + assert_eq!(docs, CADocLink::::get(id)); assert_ok!(remove(id)); assert_no_ca(id); @@ -848,7 +852,7 @@ fn remove_ca_works() { let id = mk_dist(); // Ensure the details are right. assert_eq!( - Dist::distributions(id), + Distributions::::get(id), Some(Distribution { from: PortfolioId::default_portfolio(owner.did), currency, @@ -865,7 +869,7 @@ fn remove_ca_works() { assert_ok!(remove(id)); // And ensure all details were removed. assert_no_ca(id); - assert_eq!(Dist::distributions(id), None); + assert_eq!(Distributions::::get(id), None); }); } @@ -1862,7 +1866,7 @@ fn dist_distribute_works() { assert_noop!(dist(AMOUNT + 1), PError::InsufficientPortfolioBalance); assert_ok!(dist(AMOUNT)); assert_eq!( - Dist::distributions(id), + Distributions::::get(id), Some(Distribution { from: PortfolioId::default_portfolio(other.did), currency, @@ -1906,7 +1910,7 @@ fn dist_remove_works() { // Not started, and can remove. set_timestamp(4); assert_ok!(remove(id)); - assert_eq!(Dist::distributions(id), None); + assert_eq!(Distributions::::get(id), None); }); } @@ -1963,12 +1967,12 @@ fn dist_reclaim_works() { let ensure = |x| Portfolio::ensure_sufficient_balance(&pid, ¤cy, x); assert_noop!(ensure(1), PError::InsufficientPortfolioBalance); - let dist = Dist::distributions(id).unwrap(); + let dist = Distributions::::get(id).unwrap(); assert_ok!(reclaim(id, other)); assert_ok!(ensure(AMOUNT)); assert_noop!(ensure(AMOUNT + 1), PError::InsufficientPortfolioBalance); assert_eq!( - Dist::distributions(id).unwrap(), + Distributions::::get(id).unwrap(), Distribution { reclaimed: true, remaining: 0, @@ -2121,8 +2125,12 @@ fn dist_claim_works() { let benefit_foo = AMOUNT * per_share / PER_SHARE_PRECISION; let post_tax_foo = benefit_foo - benefit_foo * 1 / 4; assert_eq!(Asset::balance_of(¤cy, foo.did), post_tax_foo); - let assert_rem = - |removed| assert_eq!(Dist::distributions(id).unwrap().remaining, amount - removed); + let assert_rem = |removed| { + assert_eq!( + Distributions::::get(id).unwrap().remaining, + amount - removed + ) + }; assert_rem(benefit_foo); // `bar` is pushed to with 1/3 tax. @@ -2188,8 +2196,12 @@ fn dist_claim_rounding_indivisible() { let benefit = |x| x * per_share / PER_SHARE_PRECISION; let rounded = |x| x / ONE_UNIT * ONE_UNIT; - let assert_rem = - |removed| assert_eq!(Dist::distributions(id).unwrap().remaining, amount - removed); + let assert_rem = |removed| { + assert_eq!( + Distributions::::get(id).unwrap().remaining, + amount - removed + ) + }; let balance = |u: User| Asset::balance_of(¤cy, u.did); // `foo` claims. 3 / 2 units are rounded down to 1. diff --git a/pallets/runtime/tests/src/external_agents_test.rs b/pallets/runtime/tests/src/external_agents_test.rs index e33fbf4dff..3891375db8 100644 --- a/pallets/runtime/tests/src/external_agents_test.rs +++ b/pallets/runtime/tests/src/external_agents_test.rs @@ -1,17 +1,17 @@ -use crate::asset_pallet::setup::create_and_issue_sample_asset; -use crate::ext_builder::ExtBuilder; -use crate::identity_test::test_with_bad_ext_perms; -use crate::storage::{TestStorage, User}; use frame_support::dispatch::DispatchResult; use frame_support::{assert_noop, assert_ok}; +use pallet_external_agents::GroupPermissions; use pallet_permissions::StoreCallMetadata; +use polymesh_primitives::agent::{AGId, AgentGroup}; use polymesh_primitives::asset::AssetId; -use polymesh_primitives::{ - agent::{AGId, AgentGroup}, - AuthorizationData, ExtrinsicPermissions, PalletPermissions, Signatory, -}; +use polymesh_primitives::{AuthorizationData, ExtrinsicPermissions, PalletPermissions, Signatory}; use sp_keyring::AccountKeyring; +use crate::asset_pallet::setup::create_and_issue_sample_asset; +use crate::ext_builder::ExtBuilder; +use crate::identity_test::test_with_bad_ext_perms; +use crate::storage::{TestStorage, User}; + type ExternalAgents = pallet_external_agents::Pallet; type BaseError = pallet_base::Error; type Error = pallet_external_agents::Error; @@ -108,13 +108,19 @@ fn create_group_set_perms_works() { // Add a group successfully. let perms = make_perms("foo"); assert_ok!(create(perms.clone())); - assert_eq!(Some(perms), ExternalAgents::permissions(asset_id, AGId(1))); - assert_eq!(AGId(1), ExternalAgents::agent_group_id_sequence(asset_id)); + assert_eq!( + Some(perms), + GroupPermissions::::get(asset_id, AGId(1)) + ); + assert_eq!(AGId(1), AGIdSequence::get(asset_id)); // Now that the group does exist, modify its perms. let perms = make_perms("pallet_external_agent"); assert_ok!(set(AGId(1), perms.clone())); - assert_eq!(Some(perms), ExternalAgents::permissions(asset_id, AGId(1))); + assert_eq!( + Some(perms), + GroupPermissions::::get(asset_id, AGId(1)) + ); // Below we also test agent permissions checking logic. @@ -249,7 +255,7 @@ fn add_works() { let dave = User::new(AccountKeyring::Dave); let asset_id = create_and_issue_sample_asset(&owner); - let check_num = |n| assert_eq!(ExternalAgents::num_full_agents(asset_id), n); + let check_num = |n| assert_eq!(NumFullAgents::get(asset_id), n); check_num(1); @@ -347,7 +353,7 @@ fn agent_of_mapping_works() { add_become_agent(*asset_id, owner, bob, AgentGroup::Full, Ok(())); add_become_agent(*asset_id, owner, charlie, AgentGroup::ExceptMeta, Ok(())); add_become_agent(*asset_id, owner, dave, AgentGroup::PolymeshV1CAA, Ok(())); - assert_eq!(ExternalAgents::num_full_agents(asset_id), 2); + assert_eq!(NumFullAgents::get(asset_id), 2); } // Check the reverse mappings @@ -361,7 +367,7 @@ fn agent_of_mapping_works() { remove(*asset_id, bob); remove(*asset_id, charlie); remove(*asset_id, dave); - assert_eq!(ExternalAgents::num_full_agents(asset_id), 1); + assert_eq!(NumFullAgents::get(asset_id), 1); } // Check the reverse mappings are correct or empty diff --git a/pallets/runtime/tests/src/identity_test.rs b/pallets/runtime/tests/src/identity_test.rs index 86f1ae668c..7332cb788f 100644 --- a/pallets/runtime/tests/src/identity_test.rs +++ b/pallets/runtime/tests/src/identity_test.rs @@ -16,7 +16,8 @@ use codec::Encode; use frame_support::{assert_noop, assert_ok, dispatch::DispatchResult, traits::Currency}; use pallet_balances as balances; use pallet_identity::{ - ChildDid, CustomClaimIdSequence, CustomClaims, CustomClaimsInverse, ParentDid, + Authorizations, ChildDid, CurrentAuthId, CustomClaimIdSequence, CustomClaims, + CustomClaimsInverse, OffChainAuthorizationNonce, ParentDid, }; use pallet_identity::{Config as IdentityConfig, Event}; use polymesh_common_utilities::identity::{ @@ -84,7 +85,7 @@ fn target_id_auth(user: User) -> (TargetIdAuthorization, u64) { ( TargetIdAuthorization { target_id: user.did, - nonce: Identity::offchain_authorization_nonce(user.did), + nonce: OffChainAuthorizationNonce::::get(user.did), expires_at, }, expires_at, @@ -1013,7 +1014,7 @@ fn add_secondary_keys_with_authorization_duplicate_keys() { let auth = || { let auth = TargetIdAuthorization { target_id: user.did, - nonce: Identity::offchain_authorization_nonce(user.did), + nonce: OffChainAuthorizationNonce::::get(user.did), expires_at, }; auth.encode() @@ -1050,7 +1051,7 @@ fn add_secondary_keys_with_authorization_too_many_sks() { let auth = || { let auth = TargetIdAuthorization { target_id: user.did, - nonce: Identity::offchain_authorization_nonce(user.did), + nonce: OffChainAuthorizationNonce::::get(user.did), expires_at, }; auth.encode() @@ -1153,8 +1154,8 @@ fn adding_authorizations() { AuthorizationsGiven::get(alice.did, auth_id), bob.signatory_did(), ); - let mut auth = - Identity::authorizations(&bob.signatory_did(), auth_id).expect("Missing authorization"); + let mut auth = Authorizations::::get(&bob.signatory_did(), auth_id) + .expect("Missing authorization"); assert_eq!(auth.authorized_by, alice.did); assert_eq!(auth.expiry, None); assert_eq!( @@ -1172,8 +1173,8 @@ fn adding_authorizations() { AuthorizationsGiven::get(alice.did, auth_id), bob.signatory_did() ); - auth = - Identity::authorizations(&bob.signatory_did(), auth_id).expect("Missing authorization"); + auth = Authorizations::::get(&bob.signatory_did(), auth_id) + .expect("Missing authorization"); assert_eq!(auth.authorized_by, alice.did); assert_eq!(auth.expiry, Some(100)); assert_eq!( @@ -1218,8 +1219,8 @@ fn removing_authorizations() { AuthorizationsGiven::get(alice.did, auth_id), bob.signatory_did() ); - let auth = - Identity::authorizations(&bob.signatory_did(), auth_id).expect("Missing authorization"); + let auth = Authorizations::::get(&bob.signatory_did(), auth_id) + .expect("Missing authorization"); assert_eq!( auth.authorization_data, AuthorizationData::TransferTicker(ticker50) @@ -1231,12 +1232,10 @@ fn removing_authorizations() { false, )); assert!(!AuthorizationsGiven::contains_key(alice.did, auth_id)); - assert!( - !>::contains_key( - bob.signatory_did(), - auth_id - ) - ); + assert!(!Authorizations::::contains_key( + bob.signatory_did(), + auth_id + )); }); } @@ -2045,7 +2044,7 @@ fn cdd_register_did_events() { alice_did, None, Some(AccountKeyring::Charlie.to_account_id()), - Identity::current_auth_id(), + CurrentAuthId::::get(), AuthorizationData::JoinIdentity(alice_secundary_keys[1].permissions.clone()), None, )) @@ -2056,7 +2055,7 @@ fn cdd_register_did_events() { alice_did, None, Some(AccountKeyring::Dave.to_account_id()), - Identity::current_auth_id() - 1, + CurrentAuthId::::get() - 1, AuthorizationData::JoinIdentity(alice_secundary_keys[0].permissions.clone()), None, )) @@ -2244,7 +2243,7 @@ fn do_create_child_identities_with_auth_test() { let auth = || { let auth = TargetIdAuthorization { target_id: alice.did, - nonce: Identity::offchain_authorization_nonce(alice.did), + nonce: OffChainAuthorizationNonce::::get(alice.did), expires_at, }; auth.encode() diff --git a/pallets/runtime/tests/src/multisig.rs b/pallets/runtime/tests/src/multisig.rs index 5fc61b2e1b..2552d2e182 100644 --- a/pallets/runtime/tests/src/multisig.rs +++ b/pallets/runtime/tests/src/multisig.rs @@ -3,8 +3,10 @@ use frame_support::{ dispatch::DispatchResult, BoundedVec, }; +use pallet_identity::MultiPurposeNonce; use pallet_multisig::{ - self as multisig, AdminDid, LastInvalidProposal, ProposalStates, ProposalVoteCounts, Votes, + self as multisig, AdminDid, LastInvalidProposal, MultiSigSignsRequired, NextProposalId, + NumberOfSigners, ProposalStates, ProposalVoteCounts, Votes, }; use polymesh_primitives::constants::currency::POLY; use polymesh_primitives::multisig::ProposalState; @@ -94,7 +96,7 @@ fn create_multisig_required_signers() { let create = |signers, nsigs| create_multisig_result(alice.acc(), signers, nsigs); assert_ok!(create(signers(), 1)); - assert_eq!(MultiSig::ms_signs_required(ms_address), 1); + assert_eq!(MultiSigSignsRequired::::get(ms_address), 1); assert_noop!(create(create_signers(vec![]), 10), Error::NotEnoughSigners); assert_noop!(create(signers(), 0), Error::RequiredSignersIsZero); @@ -239,7 +241,7 @@ fn change_multisig_sigs_required() { None, )); - assert_eq!(MultiSig::ms_signs_required(ms_address.clone()), 2); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 2); let proposal_state = ProposalStates::::get(&ms_address, 0).unwrap(); assert_eq!(proposal_state, ProposalState::Active { until: None }); @@ -251,7 +253,7 @@ fn change_multisig_sigs_required() { None )); next_block(); - assert_eq!(MultiSig::ms_signs_required(ms_address), 1); + assert_eq!(MultiSigSignsRequired::::get(ms_address), 1); }); } @@ -270,7 +272,7 @@ fn remove_multisig_signers() { 1, ); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 0); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 0); let charlie_auth_id = get_last_auth_id(&charlie_signer); assert_ok!(MultiSig::accept_multisig_signer( @@ -278,13 +280,13 @@ fn remove_multisig_signers() { charlie_auth_id )); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 1); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 1); let bob_auth_id = get_last_auth_id(&bob_signer); assert_ok!(MultiSig::accept_multisig_signer(bob.clone(), bob_auth_id)); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 2); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 2); assert_eq!( MultiSig::ms_signers(ms_address.clone(), charlie_signer.clone()), @@ -317,7 +319,7 @@ fn remove_multisig_signers() { next_block(); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 1); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 1); assert_eq!( MultiSig::ms_signers(ms_address.clone(), charlie_signer.clone()), @@ -561,7 +563,7 @@ fn remove_multisig_signers_via_admin() { 1, ); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 0); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 0); let charlie_auth_id = get_last_auth_id(&charlie_signer.clone()); @@ -570,13 +572,13 @@ fn remove_multisig_signers_via_admin() { charlie_auth_id )); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 1); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 1); let bob_auth_id = get_last_auth_id(&bob_signer.clone()); assert_ok!(MultiSig::accept_multisig_signer(bob.clone(), bob_auth_id)); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 2); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 2); assert_eq!( MultiSig::ms_signers(ms_address.clone(), charlie_signer.clone()), @@ -612,7 +614,7 @@ fn remove_multisig_signers_via_admin() { create_signers(vec![bob_signer.clone()]) )); - assert_eq!(MultiSig::number_of_signers(ms_address.clone()), 1); + assert_eq!(NumberOfSigners::::get(ms_address.clone()), 1); assert_eq!( MultiSig::ms_signers(ms_address.clone(), charlie_signer.clone()), @@ -767,9 +769,9 @@ fn check_for_approval_closure() { None, )); next_block(); - let proposal_id = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id = NextProposalId::::get(ms_address.clone()) - 1; let bob_auth_id = get_last_auth_id(&bob_signer.clone()); - let multi_purpose_nonce = Identity::multi_purpose_nonce(); + let multi_purpose_nonce = MultiPurposeNonce::::get(); assert_storage_noop!(assert_err_ignore_postinfo!( MultiSig::approve(dave.clone(), ms_address.clone(), proposal_id, None), @@ -778,7 +780,7 @@ fn check_for_approval_closure() { next_block(); let after_extra_approval_auth_id = get_last_auth_id(&bob_signer.clone()); - let after_extra_approval_multi_purpose_nonce = Identity::multi_purpose_nonce(); + let after_extra_approval_multi_purpose_nonce = MultiPurposeNonce::::get(); // To validate that no new auth is created assert_eq!(bob_auth_id, after_extra_approval_auth_id); assert_eq!( @@ -832,14 +834,14 @@ fn reject_proposals() { call1, None, )); - let proposal_id1 = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id1 = NextProposalId::::get(ms_address.clone()) - 1; assert_ok!(MultiSig::create_proposal( ferdie.clone(), ms_address.clone(), call2, None, )); - let proposal_id2 = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id2 = NextProposalId::::get(ms_address.clone()) - 1; // Proposals can't be voted on even after rejection. assert_ok!(MultiSig::reject( @@ -1153,7 +1155,7 @@ fn proposal_owner_rejection() { call1, None, )); - let proposal_id = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id = NextProposalId::::get(ms_address.clone()) - 1; // The owner of the proposal should be able to reject it if no one else has voted assert_ok!(MultiSig::reject( @@ -1219,7 +1221,7 @@ fn proposal_owner_rejection_denied() { call1, None, )); - let proposal_id = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id = NextProposalId::::get(ms_address.clone()) - 1; // The owner of the proposal shouldn't be able to reject it since bob has already voted assert_ok!(MultiSig::reject( @@ -1331,7 +1333,7 @@ fn expired_proposals() { Some(100u64), )); - let proposal_id = MultiSig::next_proposal_id(ms_address.clone()) - 1; + let proposal_id = NextProposalId::::get(ms_address.clone()) - 1; let mut vote_count = ProposalVoteCounts::::get(&ms_address, proposal_id).unwrap(); let mut proposal_state = diff --git a/pallets/runtime/tests/src/portfolio.rs b/pallets/runtime/tests/src/portfolio.rs index 4fb4c34b6a..219e55c5db 100644 --- a/pallets/runtime/tests/src/portfolio.rs +++ b/pallets/runtime/tests/src/portfolio.rs @@ -1,10 +1,12 @@ use frame_support::{assert_noop, assert_ok}; +use sp_keyring::AccountKeyring; use pallet_nft::NFTOwner; use pallet_portfolio::{ AllowedCustodians, Event, NameToNumber, PortfolioAssetBalances, PortfolioCustodian, PortfolioNFT, Portfolios, PreApprovedPortfolios, }; +use pallet_settlement::VenueCounter; use polymesh_primitives::asset::{AssetId, AssetType, NonFungibleType}; use polymesh_primitives::asset_metadata::{ AssetMetadataKey, AssetMetadataLocalKey, AssetMetadataValue, @@ -15,7 +17,6 @@ use polymesh_primitives::{ NFTCollectionKeys, NFTId, NFTMetadataAttribute, NFTs, PortfolioId, PortfolioKind, PortfolioName, PortfolioNumber, Signatory, }; -use sp_keyring::AccountKeyring; use super::asset_pallet::setup::{create_and_issue_sample_asset, ISSUE_AMOUNT}; use super::asset_test::max_len_bytes; @@ -660,7 +661,7 @@ fn delete_portfolio_with_locked_nfts() { nfts_metadata, PortfolioKind::User(PortfolioNumber(1)), ); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); assert_ok!(Settlement::create_venue( alice.origin(), Default::default(), diff --git a/pallets/runtime/tests/src/settlement_pallet/setup.rs b/pallets/runtime/tests/src/settlement_pallet/setup.rs index 5f598110b4..ac91e0b328 100644 --- a/pallets/runtime/tests/src/settlement_pallet/setup.rs +++ b/pallets/runtime/tests/src/settlement_pallet/setup.rs @@ -1,5 +1,6 @@ use frame_support::assert_ok; +use pallet_settlement::VenueCounter; use polymesh_primitives::asset::AssetId; use polymesh_primitives::settlement::{VenueDetails, VenueId, VenueType}; @@ -15,7 +16,7 @@ type Settlement = pallet_settlement::Pallet; pub fn create_and_issue_sample_asset_with_venue(asset_owner: &User) -> (AssetId, Option) { let asset_id = create_and_issue_sample_asset(&asset_owner); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); assert_ok!(Settlement::create_venue( asset_owner.origin(), VenueDetails::default(), diff --git a/pallets/runtime/tests/src/settlement_test.rs b/pallets/runtime/tests/src/settlement_test.rs index 4e1f11ae42..8f3bf5fafd 100644 --- a/pallets/runtime/tests/src/settlement_test.rs +++ b/pallets/runtime/tests/src/settlement_test.rs @@ -17,9 +17,10 @@ use pallet_nft::NumberOfNFTs; use pallet_portfolio::{PortfolioLockedNFT, PortfolioNFT}; use pallet_scheduler as scheduler; use pallet_settlement::{ - AffirmsReceived, Event, InstructionAffirmsPending, InstructionLegs, - InstructionMediatorsAffirmations, InstructionMemos, NumberOfVenueSigners, OffChainAffirmations, - UserAffirmations, UserVenues, VenueInstructions, + AffirmsReceived, Details, Event, InstructionAffirmsPending, InstructionCounter, + InstructionDetails, InstructionLegStatus, InstructionLegs, InstructionMediatorsAffirmations, + InstructionMemos, InstructionStatuses, NumberOfVenueSigners, OffChainAffirmations, + UserAffirmations, UserVenues, VenueCounter, VenueInfo, VenueInstructions, VenueSigners, }; use polymesh_primitives::asset::{AssetId, AssetType, NonFungibleType}; use polymesh_primitives::asset_metadata::{ @@ -185,7 +186,7 @@ pub fn set_current_block_number(block: u32) { fn venue_details_length_limited() { ExtBuilder::default().build().execute_with(|| { let actor = User::new(AccountKeyring::Alice); - let id = Settlement::venue_counter(); + let id = VenueCounter::::get(); let create = |d| Settlement::create_venue(actor.origin(), d, vec![], VenueType::Exchange); let update = |d| Settlement::update_venue_details(actor.origin(), id, d); assert_too_long!(create(max_len_bytes(1))); @@ -213,7 +214,7 @@ fn user_venues(did: IdentityId) -> Vec { fn venue_registration() { ExtBuilder::default().build().execute_with(|| { let alice = User::new(AccountKeyring::Alice); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); assert_ok!(Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -223,23 +224,32 @@ fn venue_registration() { ], VenueType::Exchange )); - let venue_info = Settlement::venue_info(venue_counter).unwrap(); + let venue_info = VenueInfo::::get(venue_counter).unwrap(); assert_eq!( - Settlement::venue_counter(), + VenueCounter::::get(), venue_counter.checked_inc().unwrap() ); assert_eq!(user_venues(alice.did), [venue_counter]); assert_eq!(venue_info.creator, alice.did); assert_eq!(venue_instructions(venue_counter).len(), 0); - assert_eq!(Settlement::details(venue_counter), VenueDetails::default()); + assert_eq!( + Details::::get(venue_counter), + VenueDetails::default() + ); assert_eq!(venue_info.venue_type, VenueType::Exchange); - assert_eq!(Settlement::venue_signers(venue_counter, alice.acc()), true); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Bob.to_account_id()), + VenueSigners::::get(venue_counter, alice.acc()), + true + ); + assert_eq!( + VenueSigners::::get(venue_counter, AccountKeyring::Bob.to_account_id()), true ); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Charlie.to_account_id()), + VenueSigners::::get( + venue_counter, + AccountKeyring::Charlie.to_account_id() + ), false ); @@ -261,10 +271,10 @@ fn venue_registration() { venue_counter, [0x01].into(), )); - let venue_info = Settlement::venue_info(venue_counter).unwrap(); + let venue_info = VenueInfo::::get(venue_counter).unwrap(); assert_eq!(venue_info.creator, alice.did); assert_eq!(venue_instructions(venue_counter).len(), 0); - assert_eq!(Settlement::details(venue_counter), [0x01].into()); + assert_eq!(Details::::get(venue_counter), [0x01].into()); assert_eq!(venue_info.venue_type, VenueType::Exchange); }); } @@ -287,7 +297,7 @@ fn basic_settlement() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -333,7 +343,7 @@ fn create_and_affirm_instruction() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -390,7 +400,7 @@ fn overdraft_failure() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = ISSUE_AMOUNT + 1; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -435,7 +445,7 @@ fn token_swap() { let mut alice = UserWithBalance::new(alice, &[asset_id, asset_id2]); let mut bob = UserWithBalance::new(bob, &[asset_id, asset_id2]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -562,7 +572,7 @@ fn settle_on_block() { let mut alice = UserWithBalance::new(alice, &[asset_id, asset_id2]); let mut bob = UserWithBalance::new(bob, &[asset_id, asset_id2]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let block_number = System::block_number() + 1; let amount = 100u128; alice.refresh_init_balances(); @@ -615,7 +625,7 @@ fn settle_on_block() { }; assert_instruction_status(instruction_id, InstructionStatus::Pending); assert_eq!( - Settlement::instruction_details(instruction_id), + InstructionDetails::::get(instruction_id), instruction_details ); @@ -679,7 +689,7 @@ fn failed_execution() { let mut alice = UserWithBalance::new(alice, &[asset_id, asset_id2]); let mut bob = UserWithBalance::new(bob, &[asset_id, asset_id2]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); assert_ok!(ComplianceManager::reset_asset_compliance( Origin::signed(AccountKeyring::Bob.to_account_id()), asset_id2, @@ -751,7 +761,7 @@ fn failed_execution() { }; assert_instruction_status(instruction_id, InstructionStatus::Pending); assert_eq!( - Settlement::instruction_details(instruction_id), + InstructionDetails::::get(instruction_id), instruction_details ); assert_affirms_pending(instruction_id, 2); @@ -839,7 +849,7 @@ fn venue_filtering() { let bob = User::new(AccountKeyring::Bob); let (asset_id, venue_counter) = create_and_issue_sample_asset_with_venue(&alice); let block_number = System::block_number() + 1; - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let legs = vec![Leg::Fungible { sender: PortfolioId::default_portfolio(alice.did), @@ -913,7 +923,7 @@ fn basic_fuzzing() { let bob = User::new(AccountKeyring::Bob); let charlie = User::new(AccountKeyring::Charlie); let dave = User::new(AccountKeyring::Dave); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); assert_ok!(Settlement::create_venue( Origin::signed(AccountKeyring::Alice.to_account_id()), VenueDetails::default(), @@ -932,7 +942,7 @@ fn basic_fuzzing() { } let block_number = System::block_number() + 1; - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); // initialize balances for i in 0..10 { @@ -1072,7 +1082,7 @@ fn basic_fuzzing() { if fail { assert_eq!( - Settlement::instruction_status(instruction_id), + InstructionStatuses::::get(instruction_id), InstructionStatus::Failed ); check_locked_assets(&locked_assets, &assets, &users); @@ -1128,7 +1138,7 @@ fn basic_fuzzing() { PortfolioId::default_portfolio(users[0].did), )); assert_eq!( - Settlement::instruction_status(instruction_id), + InstructionStatuses::::get(instruction_id), InstructionStatus::Rejected(System::block_number()) ); } @@ -1155,7 +1165,7 @@ fn claim_multiple_receipts_during_authorization() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let id = Settlement::instruction_counter(); + let id = InstructionCounter::::get(); alice.refresh_init_balances(); bob.refresh_init_balances(); let amount = 100; @@ -1357,7 +1367,7 @@ fn test_weights_for_settlement_transaction() { let dave = AccountKeyring::Dave.to_account_id(); let (dave_signed, dave_did) = make_account_with_balance(dave, 10_000).unwrap(); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); // Add claim rules for settlement assert_ok!(ComplianceManager::add_compliance_requirement( @@ -1454,7 +1464,7 @@ fn cross_portfolio_settlement() { let name = PortfolioName::from([42u8].to_vec()); let num = Portfolio::next_portfolio_number(&bob.did); assert_ok!(Portfolio::create_portfolio(bob.origin(), name.clone())); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -1534,7 +1544,7 @@ fn multiple_portfolio_settlement() { let bob_num = Portfolio::next_portfolio_number(&bob.did); assert_ok!(Portfolio::create_portfolio(bob.origin(), name.clone())); assert_ok!(Portfolio::create_portfolio(alice.origin(), name.clone())); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -1686,7 +1696,7 @@ fn multiple_custodian_settlement() { assert_ok!(Portfolio::accept_portfolio_custody(alice.origin(), auth_id)); // Create a token - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -1844,14 +1854,14 @@ fn reject_instruction() { let assert_user_affirmations = |instruction_id, alice_status, bob_status| { assert_eq!( - Settlement::user_affirmations( + UserAffirmations::::get( PortfolioId::default_portfolio(alice.did), instruction_id ), alice_status ); assert_eq!( - Settlement::user_affirmations( + UserAffirmations::::get( PortfolioId::default_portfolio(bob.did), instruction_id ), @@ -1904,7 +1914,7 @@ fn dirty_storage_with_tx() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount1 = 100u128; let amount2 = 50u128; alice.refresh_init_balances(); @@ -1941,7 +1951,10 @@ fn dirty_storage_with_tx() { // Advances the block no. to execute the instruction. let total_amount = amount1 + amount2; - assert_eq!(Settlement::instruction_affirms_pending(instruction_id), 0); + assert_eq!( + InstructionAffirmsPending::::get(instruction_id), + 0 + ); next_block(); assert_eq!( InstructionLegs::::iter_prefix(instruction_id).count(), @@ -2023,7 +2036,7 @@ fn modify_venue_signers() { ExtBuilder::default().build().execute_with(|| { let alice = User::new(AccountKeyring::Alice); let charlie = User::new(AccountKeyring::Charlie); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); assert_ok!(Settlement::create_venue( alice.origin(), @@ -2085,13 +2098,19 @@ fn modify_venue_signers() { )); // this checks if the signer is already in the signer list - assert_eq!(Settlement::venue_signers(venue_counter, alice.acc()), true); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Bob.to_account_id()), + VenueSigners::::get(venue_counter, alice.acc()), true ); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Charlie.to_account_id()), + VenueSigners::::get(venue_counter, AccountKeyring::Bob.to_account_id()), + true + ); + assert_eq!( + VenueSigners::::get( + venue_counter, + AccountKeyring::Charlie.to_account_id() + ), false ); @@ -2135,21 +2154,27 @@ fn modify_venue_signers() { Error::SignerAlreadyExists ); - assert_eq!(Settlement::venue_signers(venue_counter, alice.acc()), true); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Bob.to_account_id()), + VenueSigners::::get(venue_counter, alice.acc()), true ); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Charlie.to_account_id()), + VenueSigners::::get(venue_counter, AccountKeyring::Bob.to_account_id()), + true + ); + assert_eq!( + VenueSigners::::get( + venue_counter, + AccountKeyring::Charlie.to_account_id() + ), false ); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Dave.to_account_id()), + VenueSigners::::get(venue_counter, AccountKeyring::Dave.to_account_id()), false ); assert_eq!( - Settlement::venue_signers(venue_counter, AccountKeyring::Eve.to_account_id()), + VenueSigners::::get(venue_counter, AccountKeyring::Eve.to_account_id()), false ); }); @@ -2268,7 +2293,7 @@ fn basic_settlement_with_memo() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let amount = 100u128; alice.refresh_init_balances(); bob.refresh_init_balances(); @@ -2291,7 +2316,10 @@ fn basic_settlement_with_memo() { bob.assert_all_balances_unchanged(); // check that the memo was stored correctly - assert_eq!(Settlement::memo(instruction_id).unwrap(), Memo::default()); + assert_eq!( + InstructionMemos::::get(instruction_id).unwrap(), + Memo::default() + ); assert_affirm_instruction!(alice.origin(), instruction_id, alice.did); @@ -2315,7 +2343,7 @@ fn create_instruction( asset_id: AssetId, amount: u128, ) -> InstructionId { - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); set_current_block_number(10); assert_ok!(Settlement::add_and_affirm_instruction( alice.origin(), @@ -2344,7 +2372,7 @@ fn settle_manual_instruction() { let mut alice = UserWithBalance::new(alice, &[asset_id]); let mut bob = UserWithBalance::new(bob, &[asset_id]); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let block_number = System::block_number() + 1; let amount = 10u128; alice.refresh_init_balances(); @@ -2456,7 +2484,7 @@ fn settle_manual_instruction_with_portfolio() { let alice_portfolio = PortfolioId::default_portfolio(alice.did); let charlie_portfolio = PortfolioId::default_portfolio(charlie.did); - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let block_number = System::block_number() + 1; let amount = 10u128; alice.refresh_init_balances(); @@ -2694,7 +2722,7 @@ fn add_and_affirm_nft_instruction() { PortfolioKind::Default, ); ComplianceManager::pause_asset_compliance(alice.origin(), asset_id).unwrap(); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -2704,7 +2732,7 @@ fn add_and_affirm_nft_instruction() { .unwrap(); // Adds and affirms the instruction - let instruction_id = Settlement::instruction_counter(); + let instruction_id = InstructionCounter::::get(); let nfts = NFTs::new_unverified(asset_id, vec![NFTId(1)]); let legs: Vec = vec![Leg::NonFungible { sender: PortfolioId::default_portfolio(alice.did), @@ -2803,7 +2831,7 @@ fn add_and_affirm_nft_not_owned() { nfts_metadata, PortfolioKind::Default, ); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -2865,7 +2893,7 @@ fn add_same_nft_different_legs() { nfts_metadata, PortfolioKind::Default, ); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -2929,7 +2957,7 @@ fn add_and_affirm_with_receipts_nfts() { nfts_metadata, PortfolioKind::Default, ); - let venue_id = Settlement::venue_counter(); + let venue_id = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -2982,7 +3010,7 @@ fn add_instruction_unexpected_offchain_asset() { ExtBuilder::default().build().execute_with(|| { let alice = User::new(AccountKeyring::Alice); let bob = User::new(AccountKeyring::Bob); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -3109,7 +3137,7 @@ fn affirm_offchain_asset_without_receipt() { ExtBuilder::default().build().execute_with(|| { let alice = User::new(AccountKeyring::Alice); let bob = User::new(AccountKeyring::Bob); - let venue = Settlement::venue_counter(); + let venue = VenueCounter::::get(); Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -4256,7 +4284,10 @@ fn assert_instruction_details( instruction_id: InstructionId, details: Instruction, ) { - assert_eq!(Settlement::instruction_details(instruction_id), details); + assert_eq!( + InstructionDetails::::get(instruction_id), + details + ); } #[track_caller] @@ -4264,7 +4295,10 @@ fn assert_instruction_status( instruction_id: InstructionId, status: InstructionStatus, ) { - assert_eq!(Settlement::instruction_status(instruction_id), status); + assert_eq!( + InstructionStatuses::::get(instruction_id), + status + ); } #[track_caller] @@ -4275,7 +4309,10 @@ fn assert_balance(asset_id: &AssetId, user: &User, balance: Balance) { #[track_caller] fn assert_user_affirms(instruction_id: InstructionId, user: &User, status: AffirmationStatus) { assert_eq!( - Settlement::user_affirmations(PortfolioId::default_portfolio(user.did), instruction_id), + UserAffirmations::::get( + PortfolioId::default_portfolio(user.did), + instruction_id + ), status ); @@ -4286,7 +4323,10 @@ fn assert_user_affirms(instruction_id: InstructionId, user: &User, status: Affir }; assert_eq!( - Settlement::affirms_received(instruction_id, PortfolioId::default_portfolio(user.did)), + AffirmsReceived::::get( + instruction_id, + PortfolioId::default_portfolio(user.did) + ), affirms_received_status ); } @@ -4294,7 +4334,7 @@ fn assert_user_affirms(instruction_id: InstructionId, user: &User, status: Affir #[track_caller] fn assert_leg_status(instruction_id: InstructionId, leg: LegId, status: LegStatus) { assert_eq!( - Settlement::instruction_leg_status(instruction_id, leg), + InstructionLegStatus::::get(instruction_id, leg), status ); } @@ -4302,7 +4342,7 @@ fn assert_leg_status(instruction_id: InstructionId, leg: LegId, status: LegStatu #[track_caller] fn assert_affirms_pending(instruction_id: InstructionId, pending: u64) { assert_eq!( - Settlement::instruction_affirms_pending(instruction_id), + InstructionAffirmsPending::::get(instruction_id), pending ); } diff --git a/pallets/runtime/tests/src/staking/mod.rs b/pallets/runtime/tests/src/staking/mod.rs index d8666c3b75..f95780fb26 100644 --- a/pallets/runtime/tests/src/staking/mod.rs +++ b/pallets/runtime/tests/src/staking/mod.rs @@ -27,7 +27,8 @@ use frame_support::{ traits::{Currency, Get, ReservableCurrency}, }; use mock::*; -use pallet_balances::Error as BalancesError; + +use pallet_balances::{Error as BalancesError, Locks}; use pallet_pips::{ProposalVotes, Proposals}; use polymesh_primitives::IdentityId; use sp_runtime::{ @@ -2209,7 +2210,7 @@ fn bond_with_no_staked_value() { 5, RewardDestination::Controller )); - assert_eq!(Balances::locks(&1)[0].amount, 5); + assert_eq!(Locks::::get(&1)[0].amount, 5); // unbonding even 1 will cause all to be unbonded. assert_ok!(Staking::unbond(RuntimeOrigin::signed(2), 1)); @@ -2234,14 +2235,14 @@ fn bond_with_no_staked_value() { // not yet removed. assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); assert!(Staking::ledger(2).is_some()); - assert_eq!(Balances::locks(&1)[0].amount, 5); + assert_eq!(Locks::::get(&1)[0].amount, 5); mock::start_active_era(3); // poof. Account 1 is removed from the staking system. assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0)); assert!(Staking::ledger(2).is_some()); - assert_eq!(Balances::locks(&1).len(), 1); + assert_eq!(Locks::::get(&1).len(), 1); }); } diff --git a/pallets/runtime/tests/src/sto_test.rs b/pallets/runtime/tests/src/sto_test.rs index 9218c6b308..2d89c42acb 100644 --- a/pallets/runtime/tests/src/sto_test.rs +++ b/pallets/runtime/tests/src/sto_test.rs @@ -1,15 +1,16 @@ use frame_support::{assert_noop, assert_ok}; +use sp_keyring::AccountKeyring; use sp_runtime::DispatchError; +use pallet_settlement::{InstructionCounter, InstructionStatuses, VenueCounter}; use pallet_sto::{ - Fundraiser, FundraiserId, FundraiserName, FundraiserStatus, FundraiserTier, PriceTier, - MAX_TIERS, + Fundraiser, FundraiserCount, FundraiserId, FundraiserName, FundraiserNames, FundraiserStatus, + FundraiserTier, Fundraisers, PriceTier, MAX_TIERS, }; use polymesh_primitives::asset::AssetId; use polymesh_primitives::checked_inc::CheckedInc; use polymesh_primitives::settlement::{InstructionStatus, VenueDetails, VenueId, VenueType}; use polymesh_primitives::{IdentityId, PortfolioId, WeightMeter}; -use sp_keyring::AccountKeyring; use crate::asset_pallet::setup::create_and_issue_sample_asset; @@ -123,8 +124,8 @@ fn raise_happy_path() { )); // Register a venue - let venue_counter = Settlement::venue_counter(); - let instruction_id = Settlement::instruction_counter(); + let venue_counter = VenueCounter::::get(); + let instruction_id = InstructionCounter::::get(); exec_ok!(Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -139,7 +140,7 @@ fn raise_happy_path() { let bob_init_raise = Asset::balance_of(&raise_asset, bob.did); // Alice starts a fundraiser - let fundraiser_id = Sto::fundraiser_count(offering_asset); + let fundraiser_id = FundraiserCount::::get(offering_asset); let fundraiser_name: FundraiserName = max_len_bytes(0); exec_ok!(Sto::create_fundraiser( alice.origin(), @@ -160,7 +161,7 @@ fn raise_happy_path() { let check_fundraiser = |remaining| { assert_eq!( - Sto::fundraisers(offering_asset, fundraiser_id), + Fundraisers::::get(offering_asset, fundraiser_id), Some(Fundraiser { creator: alice.did, offering_portfolio: alice_portfolio, @@ -194,7 +195,7 @@ fn raise_happy_path() { assert_eq!(Asset::balance_of(&raise_asset, alice.did), alice_init_raise); assert_eq!(Asset::balance_of(&raise_asset, bob.did), bob_init_raise); assert_eq!( - Sto::fundraiser_name(offering_asset, fundraiser_id), + FundraiserNames::::get(offering_asset, fundraiser_id), Some(fundraiser_name) ); let sto_invest = |purchase_amount, max_price, err: Error| { @@ -235,11 +236,11 @@ fn raise_happy_path() { )); check_fundraiser(1_000_000u128 - amount); assert_eq!( - Some(Settlement::instruction_counter()), + Some(InstructionCounter::::get()), instruction_id.checked_inc() ); assert_eq!( - Settlement::instruction_status(instruction_id), + InstructionStatuses::::get(instruction_id), InstructionStatus::Success(System::block_number()) ); @@ -307,7 +308,7 @@ fn raise_unhappy_path() { }; let create_venue = |user: User, type_| { - let bad_venue = Settlement::venue_counter(); + let bad_venue = VenueCounter::::get(); assert_ok!(Settlement::create_venue( user.origin(), VenueDetails::default(), @@ -413,7 +414,7 @@ fn invalid_fundraiser() { .. } = init_raise_context(); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); assert_ok!(Settlement::create_venue( alice.origin(), VenueDetails::default(), @@ -476,14 +477,14 @@ fn invalid_fundraiser() { fn basic_fundraiser() -> (FundraiserId, RaiseContext) { let context = init_raise_context(); - let venue_counter = Settlement::venue_counter(); + let venue_counter = VenueCounter::::get(); assert_ok!(Settlement::create_venue( context.alice.origin(), VenueDetails::default(), vec![AccountKeyring::Alice.to_account_id()], VenueType::Sto )); - let fundraiser_id = Sto::fundraiser_count(context.offering_asset); + let fundraiser_id = FundraiserCount::::get(context.offering_asset); assert_ok!(Sto::create_fundraiser( context.alice.origin(), context.alice_portfolio, diff --git a/pallets/runtime/tests/src/transaction_payment_test.rs b/pallets/runtime/tests/src/transaction_payment_test.rs index 44b71482b4..0f01e1ecb7 100644 --- a/pallets/runtime/tests/src/transaction_payment_test.rs +++ b/pallets/runtime/tests/src/transaction_payment_test.rs @@ -7,7 +7,9 @@ use frame_support::{ weights::WeightToFee, }; use pallet_balances::Call as BalancesCall; -use pallet_transaction_payment::{ChargeTransactionPayment, Multiplier, RuntimeDispatchInfo}; +use pallet_transaction_payment::{ + ChargeTransactionPayment, Multiplier, NextFeeMultiplier, RuntimeDispatchInfo, +}; use polymesh_primitives::AccountId; use polymesh_primitives::TransactionError; use sp_arithmetic::traits::One; @@ -258,7 +260,7 @@ fn compute_fee_works_without_multiplier() { .build() .execute_with(|| { // Next fee multiplier is zero - assert_eq!(TransactionPayment::next_fee_multiplier(), Multiplier::one()); + assert_eq!(NextFeeMultiplier::::get(), Multiplier::one()); // Tip only, no fees works let dispatch_info = DispatchInfo { diff --git a/pallets/runtime/tests/src/transfer_compliance_test.rs b/pallets/runtime/tests/src/transfer_compliance_test.rs index 88ed5ab08d..9ec6f30871 100644 --- a/pallets/runtime/tests/src/transfer_compliance_test.rs +++ b/pallets/runtime/tests/src/transfer_compliance_test.rs @@ -7,6 +7,7 @@ use frame_support::{ dispatch::{DispatchError, DispatchResult}, }; use pallet_external_agents::Event; +use pallet_statistics::AssetStats; use polymesh_primitives::asset::AssetId; use polymesh_primitives::{ asset::AssetType, jurisdiction::CountryCode, statistics::*, transfer_compliance::*, AccountId, @@ -523,7 +524,7 @@ impl AssetTracker { StatOpType::Balance => self.calculate_stat_balance(claim_issuer, &key2), }; // Get stat from pallet. - let value = Statistics::asset_stats(key1, key2.clone()); + let value = AssetStats::::get(key1, key2.clone()); (cal_value, value) }) .collect() @@ -569,7 +570,7 @@ impl AssetTracker { stat_type: *stat_type, }; for key2 in self.fetch_stats_key2(stat_type).iter() { - let value = Statistics::asset_stats(key1, key2); + let value = AssetStats::::get(key1, key2); match (stat_type.operation_type, stat_type.claim_issuer) { (StatOpType::Count, claim_issuer) => { let cal_value = self.calculate_stat_count(claim_issuer, &key2); diff --git a/pallets/runtime/tests/src/treasury_test.rs b/pallets/runtime/tests/src/treasury_test.rs index 77c4b3b876..b5a3cf8c67 100644 --- a/pallets/runtime/tests/src/treasury_test.rs +++ b/pallets/runtime/tests/src/treasury_test.rs @@ -8,6 +8,8 @@ use polymesh_primitives::{Beneficiary, IdentityId}; use sp_keyring::AccountKeyring; use sp_runtime::DispatchError; +use pallet_balances::TotalIssuance; + pub type Balances = pallet_balances::Pallet; pub type Treasury = pallet_treasury::Pallet; type TreasuryError = pallet_treasury::Error; @@ -32,13 +34,13 @@ fn reimbursement_and_disbursement_we() { let charlie_acc = AccountKeyring::Charlie.to_account_id(); let (_, charlie_did) = make_account_without_cdd(charlie_acc.clone()).unwrap(); - let total_issuance = Balances::total_issuance(); + let total_issuance = TotalIssuance::::get(); // Verify reimbursement. assert_eq!(Treasury::balance(), 0); exec_ok!(Treasury::reimbursement(alice.origin(), 1_000)); assert_eq!(Treasury::balance(), 1_000); - assert_eq!(total_issuance, Balances::total_issuance()); + assert_eq!(total_issuance, TotalIssuance::::get()); // Disbursement: Only root can do that. exec_noop!( @@ -70,14 +72,14 @@ fn reimbursement_and_disbursement_we() { ); assert_eq!(Balances::free_balance(&bob.acc()), before_bob_balance + 500); assert_eq!(Balances::free_balance(&charlie_acc), before_charlie_balance); - assert_eq!(total_issuance, Balances::total_issuance()); + assert_eq!(total_issuance, TotalIssuance::::get()); // Alice cannot make a disbursement to herself. exec_noop!( Treasury::disbursement(alice.origin(), vec![beneficiary(alice.did, 500)]), DispatchError::BadOrigin ); - assert_eq!(total_issuance, Balances::total_issuance()); + assert_eq!(total_issuance, TotalIssuance::::get()); // Repeat disbursement. This time there is not enough POLYX in the treasury. exec_noop!( @@ -99,14 +101,14 @@ fn bad_disbursement_did_we() { let bob = User::new(AccountKeyring::Bob); let default_key = pallet_identity::types::zero_account_id(); - let total_issuance = Balances::total_issuance(); + let total_issuance = TotalIssuance::::get(); let treasury_balance = 10_000; // Give the Treasury some POLYX. assert_eq!(Treasury::balance(), 0); exec_ok!(Treasury::reimbursement(alice.origin(), treasury_balance)); assert_eq!(Treasury::balance(), treasury_balance); - assert_eq!(total_issuance, Balances::total_issuance()); + assert_eq!(total_issuance, TotalIssuance::::get()); let beneficiaries = vec![ // Valid identities. @@ -139,5 +141,5 @@ fn bad_disbursement_did_we() { ); // Make sure total POLYX issuance hasn't changed. - assert_eq!(total_issuance, Balances::total_issuance()); + assert_eq!(total_issuance, TotalIssuance::::get()); } diff --git a/pallets/runtime/tests/src/utility_test.rs b/pallets/runtime/tests/src/utility_test.rs index 9dc9bc6667..31b137d4b9 100644 --- a/pallets/runtime/tests/src/utility_test.rs +++ b/pallets/runtime/tests/src/utility_test.rs @@ -16,7 +16,8 @@ use pallet_balances::Call as BalancesCall; use pallet_pips::{PipIdSequence, ProposalState, SnapshotResult}; use pallet_portfolio::Call as PortfolioCall; use pallet_utility::{ - self as utility, Call as UtilityCall, Config as UtilityConfig, Event, UniqueCall, WeightInfo, + self as utility, Call as UtilityCall, Config as UtilityConfig, Event, Nonces, UniqueCall, + WeightInfo, }; use polymesh_primitives::{ traits::CddAndFeeDetails, AccountId, Balance, ExtrinsicPermissions, PalletPermissions, @@ -231,7 +232,7 @@ fn _relay_happy_case() { let origin = RuntimeOrigin::signed(alice); let transaction = UniqueCall::new( - Utility::nonce(bob.clone()), + Nonces::::get(bob.clone()), RuntimeCall::Balances(BalancesCall::transfer { dest: charlie.clone().into(), value: 50, @@ -266,7 +267,7 @@ fn _relay_unhappy_cases() { let origin = RuntimeOrigin::signed(alice); let transaction = UniqueCall::new( - Utility::nonce(bob.clone()), + Nonces::::get(bob.clone()), RuntimeCall::Balances(BalancesCall::transfer { dest: charlie.clone().into(), value: 59, @@ -296,7 +297,7 @@ fn _relay_unhappy_cases() { let _ = register_keyring_account_with_balance(AccountKeyring::Bob, 1_000).unwrap(); let transaction = UniqueCall::new( - Utility::nonce(bob.clone()) + 1, + Nonces::::get(bob.clone()) + 1, RuntimeCall::Balances(BalancesCall::transfer { dest: charlie.into(), value: 59, diff --git a/pallets/settlement/src/benchmarking.rs b/pallets/settlement/src/benchmarking.rs index 46e759d4df..8e29b35c08 100644 --- a/pallets/settlement/src/benchmarking.rs +++ b/pallets/settlement/src/benchmarking.rs @@ -95,7 +95,7 @@ fn create_venue_(did: IdentityId, signers: Vec) -> Venu venue_type: VenueType::Distribution, }; // NB: Venue counter starts with 1. - let venue_counter = Pallet::::venue_counter(); + let venue_counter = VenueCounter::::get(); VenueInfo::::insert(venue_counter, venue); for signer in signers { VenueSigners::::insert(venue_counter, signer, true); @@ -343,9 +343,9 @@ benchmarks! { } }: _(origin, venue_details, signers, venue_type) verify { - assert_eq!(Pallet::::venue_counter(), VenueId(2), "Invalid venue counter"); + assert_eq!(VenueCounter::::get(), VenueId(2), "Invalid venue counter"); assert!(UserVenues::::contains_key(did.unwrap(), VenueId(1)), "Invalid venue id"); - assert!(Pallet::::venue_info(VenueId(1)).is_some(), "Incorrect venue info set"); + assert!(VenueInfo::::get(VenueId(1)).is_some(), "Incorrect venue info set"); } update_venue_details { @@ -358,7 +358,7 @@ benchmarks! { let venue_id = create_venue_::(did.unwrap(), vec![]); }: _(origin, venue_id, details1) verify { - assert_eq!(Pallet::::details(venue_id), details2, "Incorrect venue details"); + assert_eq!(Details::::get(venue_id), details2, "Incorrect venue details"); } update_venue_type { @@ -368,7 +368,7 @@ benchmarks! { let venue_id = create_venue_::(did.unwrap(), vec![]); }: _(origin, venue_id, ty) verify { - assert_eq!(Pallet::::venue_info(VenueId(1)).unwrap().venue_type, ty, "Incorrect venue type value"); + assert_eq!(VenueInfo::::get(VenueId(1)).unwrap().venue_type, ty, "Incorrect venue type value"); } update_venue_signers { @@ -384,7 +384,7 @@ benchmarks! { }: _(origin, venue_id, signers.clone(), true) verify { for signer in signers.iter() { - assert_eq!(Pallet::::venue_signers(venue_id, signer), true, "Incorrect venue signer"); + assert_eq!(VenueSigners::::get(venue_id, signer), true, "Incorrect venue signer"); } } @@ -394,7 +394,7 @@ benchmarks! { let ticker = create_asset_::(&user); }: _(user.origin, ticker, true) verify { - assert!(Pallet::::venue_filtering(ticker), "Fail: set_venue_filtering failed"); + assert!(VenueFiltering::::get(ticker), "Fail: set_venue_filtering failed"); } allow_venues { @@ -410,7 +410,7 @@ benchmarks! { }: _(user.origin, ticker, s_venues) verify { for v in venues.iter() { - assert!(Pallet::::venue_allow_list(ticker, v), "Fail: allow_venue dispatch"); + assert!(VenueAllowList::::get(ticker, v), "Fail: allow_venue dispatch"); } } @@ -427,7 +427,7 @@ benchmarks! { }: _(user.origin, ticker, s_venues) verify { for v in venues.iter() { - assert!(!Pallet::::venue_allow_list(ticker, v), "Fail: allow_venue dispatch"); + assert!(!VenueAllowList::::get(ticker, v), "Fail: allow_venue dispatch"); } } diff --git a/pallets/settlement/src/lib.rs b/pallets/settlement/src/lib.rs index 010a3c5a15..8491345a55 100644 --- a/pallets/settlement/src/lib.rs +++ b/pallets/settlement/src/lib.rs @@ -551,7 +551,6 @@ pub mod pallet { pub struct Pallet(_); #[pallet::storage] - #[pallet::getter(fn venue_info)] /// Info about a venue. venue_id -> venue pub type VenueInfo = StorageMap<_, Twox64Concat, VenueId, Venue, OptionQuery>; @@ -559,7 +558,6 @@ pub mod pallet { /// Only needed for the UI. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn details)] pub type Details = StorageMap<_, Twox64Concat, VenueId, VenueDetails, ValueQuery>; /// Instructions under a venue. @@ -567,14 +565,12 @@ pub mod pallet { /// /// venue_id -> instruction_id -> () #[pallet::storage] - #[pallet::getter(fn venue_instructions)] pub type VenueInstructions = StorageDoubleMap<_, Twox64Concat, VenueId, Twox64Concat, InstructionId, (), ValueQuery>; /// Signers allowed by the venue. (venue_id, signer) -> bool #[pallet::storage] - #[pallet::getter(fn venue_signers)] - pub(super) type VenueSigners = + pub type VenueSigners = StorageDoubleMap<_, Twox64Concat, VenueId, Twox64Concat, T::AccountId, bool, ValueQuery>; /// Venues create by an identity. @@ -582,13 +578,11 @@ pub mod pallet { /// /// identity -> venue_id -> () #[pallet::storage] - #[pallet::getter(fn user_venues)] pub type UserVenues = StorageDoubleMap<_, Twox64Concat, IdentityId, Twox64Concat, VenueId, (), ValueQuery>; /// Details about an instruction. instruction_id -> instruction_details #[pallet::storage] - #[pallet::getter(fn instruction_details)] pub type InstructionDetails = StorageMap< _, Twox64Concat, @@ -599,7 +593,6 @@ pub mod pallet { /// Status of a leg under an instruction. (instruction_id, leg_id) -> LegStatus #[pallet::storage] - #[pallet::getter(fn instruction_leg_status)] pub type InstructionLegStatus = StorageDoubleMap< _, Twox64Concat, @@ -612,13 +605,11 @@ pub mod pallet { /// Number of affirmations pending before instruction is executed. instruction_id -> affirm_pending #[pallet::storage] - #[pallet::getter(fn instruction_affirms_pending)] pub type InstructionAffirmsPending = StorageMap<_, Twox64Concat, InstructionId, u64, ValueQuery>; /// Tracks affirmations received for an instruction. (instruction_id, counter_party) -> AffirmationStatus #[pallet::storage] - #[pallet::getter(fn affirms_received)] pub type AffirmsReceived = StorageDoubleMap< _, Twox64Concat, @@ -632,7 +623,6 @@ pub mod pallet { /// Helps a user track their pending instructions and affirmations (only needed for UI). /// (counter_party, instruction_id) -> AffirmationStatus #[pallet::storage] - #[pallet::getter(fn user_affirmations)] pub type UserAffirmations = StorageDoubleMap< _, Twox64Concat, @@ -645,55 +635,46 @@ pub mod pallet { /// Tracks redemption of receipts. (signer, receipt_uid) -> receipt_used #[pallet::storage] - #[pallet::getter(fn receipts_used)] pub(super) type ReceiptsUsed = StorageDoubleMap<_, Twox64Concat, T::AccountId, Blake2_128Concat, u64, bool, ValueQuery>; /// Tracks if a token has enabled filtering venues that can create instructions involving their token. AssetId -> filtering_enabled #[pallet::storage] - #[pallet::getter(fn venue_filtering)] pub(super) type VenueFiltering = StorageMap<_, Blake2_128Concat, AssetId, bool, ValueQuery>; /// Venues that are allowed to create instructions involving a particular asset. Only used if filtering is enabled. /// ([`AssetId`], venue_id) -> allowed #[pallet::storage] - #[pallet::getter(fn venue_allow_list)] pub(super) type VenueAllowList = StorageDoubleMap<_, Blake2_128Concat, AssetId, Twox64Concat, VenueId, bool, ValueQuery>; /// Number of venues in the system (It's one more than the actual number) #[pallet::storage] - #[pallet::getter(fn venue_counter)] pub type VenueCounter = StorageValue<_, VenueId, ValueQuery>; /// Number of instructions in the system (It's one more than the actual number) #[pallet::storage] - #[pallet::getter(fn instruction_counter)] pub type InstructionCounter = StorageValue<_, InstructionId, ValueQuery>; /// Instruction memo #[pallet::storage] - #[pallet::getter(fn memo)] pub type InstructionMemos = StorageMap<_, Twox64Concat, InstructionId, Memo, OptionQuery>; /// Instruction statuses. instruction_id -> InstructionStatus #[pallet::storage] - #[pallet::getter(fn instruction_status)] pub type InstructionStatuses = StorageMap<_, Twox64Concat, InstructionId, InstructionStatus, ValueQuery>; /// Legs under an instruction. (instruction_id, leg_id) -> Leg #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn instruction_legs)] pub type InstructionLegs = StorageDoubleMap<_, Twox64Concat, InstructionId, Twox64Concat, LegId, Leg, OptionQuery>; /// Tracks the affirmation status for offchain legs in a instruction. [`(InstructionId, LegId)`] -> [`AffirmationStatus`] #[pallet::storage] - #[pallet::getter(fn offchain_affirmations)] pub type OffChainAffirmations = StorageDoubleMap< _, Twox64Concat, @@ -706,13 +687,11 @@ pub mod pallet { /// Tracks the number of signers each venue has. #[pallet::storage] - #[pallet::getter(fn number_of_venue_signers)] pub type NumberOfVenueSigners = StorageMap<_, Twox64Concat, VenueId, u32, ValueQuery>; /// The status for the mediators affirmation. #[pallet::storage] - #[pallet::getter(fn venue_mediators_affirmations)] pub type InstructionMediatorsAffirmations = StorageDoubleMap< _, Twox64Concat, @@ -1437,7 +1416,7 @@ impl Pallet { // Extract `Venue` with `id`, assuming it was created by `did`, or error. fn venue_for_management(id: VenueId, did: IdentityId) -> Result { // Ensure venue exists & that DID created it. - let venue = Self::venue_info(id).ok_or(Error::::InvalidVenue)?; + let venue = VenueInfo::::get(id).ok_or(Error::::InvalidVenue)?; ensure!(venue.creator == did, Error::::Unauthorized); Ok(venue) } @@ -1662,7 +1641,7 @@ impl Pallet { Self::ensure_valid_affirmation_count(&filtered_legs, &affirmation_count)?; } for (leg_id, leg) in filtered_legs.sender_subset() { - match Self::instruction_leg_status(id, leg_id) { + match InstructionLegStatus::::get(id, leg_id) { LegStatus::ExecutionToBeSkipped(_, _) => { return Err(Error::::UnexpectedLegStatus.into()) } @@ -1693,9 +1672,9 @@ impl Pallet { id: InstructionId, is_execute: bool, ) -> Result, DispatchError> { - let details = Self::instruction_details(id); + let details = InstructionDetails::::get(id); ensure!( - Self::instruction_status(id) != InstructionStatus::Unknown, + InstructionStatuses::::get(id) != InstructionStatus::Unknown, Error::::UnknownInstruction ); @@ -1926,7 +1905,8 @@ impl Pallet { weight_meter: &mut WeightMeter, ) -> Result<(), LegId> { for (leg_id, leg) in instruction_legs { - if Self::instruction_leg_status(instruction_id, leg_id) == LegStatus::ExecutionPending { + if InstructionLegStatus::::get(instruction_id, leg_id) == LegStatus::ExecutionPending + { match leg { Leg::Fungible { sender, @@ -2047,7 +2027,7 @@ impl Pallet { >::insert(id, leg_id, LegStatus::ExecutionPending); } - let affirms_pending = Self::instruction_affirms_pending(id); + let affirms_pending = InstructionAffirmsPending::::get(id); // Updates storage for portfolio in &portfolios { @@ -2064,7 +2044,7 @@ impl Pallet { fn release_locks(id: InstructionId, instruction_legs: &[(LegId, Leg)]) -> DispatchResult { for (leg_id, leg) in instruction_legs { - if let LegStatus::ExecutionPending = Self::instruction_leg_status(id, leg_id) { + if let LegStatus::ExecutionPending = InstructionLegStatus::::get(id, leg_id) { Self::unlock_via_leg(&leg)?; } } @@ -2075,7 +2055,8 @@ impl Pallet { /// settlement type is `SettleOnAffirmation` and no. of affirms pending is 0. fn maybe_schedule_instruction(affirms_pending: u64, id: InstructionId, weight_limit: Weight) { if affirms_pending == 0 - && Self::instruction_details(id).settlement_type == SettlementType::SettleOnAffirmation + && InstructionDetails::::get(id).settlement_type + == SettlementType::SettleOnAffirmation { // Schedule instruction to be executed in the next block. let execution_at = System::::block_number() + One::one(); @@ -2229,7 +2210,7 @@ impl Pallet { instruction_asset_count.off_chain(), ); // Schedule instruction to be executed in the next block (expected) if conditions are met. - Self::maybe_schedule_instruction(Self::instruction_affirms_pending(id), id, weight_limit); + Self::maybe_schedule_instruction(InstructionAffirmsPending::::get(id), id, weight_limit); Ok(PostDispatchInfo::from(Some( Self::affirm_with_receipts_actual_weight( filtered_legs.sender_asset_count().clone(), @@ -2258,7 +2239,7 @@ impl Pallet { instruction_asset_count.off_chain(), ); // Schedule the instruction if conditions are met - Self::maybe_schedule_instruction(Self::instruction_affirms_pending(id), id, weight_limit); + Self::maybe_schedule_instruction(InstructionAffirmsPending::::get(id), id, weight_limit); Ok(PostDispatchInfo::from(Some( Self::affirm_instruction_actual_weight( filtered_legs.sender_asset_count().clone(), @@ -2286,8 +2267,8 @@ impl Pallet { }; Self::execute_settle_on_affirmation_instruction( id, - Self::instruction_affirms_pending(id), - Self::instruction_details(id).settlement_type, + InstructionAffirmsPending::::get(id), + InstructionDetails::::get(id).settlement_type, caller_did, weight_meter, )?; @@ -2325,7 +2306,7 @@ impl Pallet { custodian, secondary_key, )?; - let user_affirmation = Self::user_affirmations(portfolio, id); + let user_affirmation = UserAffirmations::::get(portfolio, id); ensure!( expected_statuses.contains(&user_affirmation), Error::::UnexpectedAffirmationStatus @@ -2365,7 +2346,7 @@ impl Pallet { ); for signer in &signers { ensure!( - !Self::venue_signers(&id, &signer), + !VenueSigners::::get(&id, &signer), Error::::SignerAlreadyExists ); } @@ -2376,7 +2357,7 @@ impl Pallet { } else { for signer in &signers { ensure!( - Self::venue_signers(&id, &signer), + VenueSigners::::get(&id, &signer), Error::::SignerDoesNotExist ); } @@ -2402,7 +2383,7 @@ impl Pallet { ) -> DispatchResultWithPostInfo { // Makes sure the instruction exists ensure!( - Self::instruction_status(instruction_id) != InstructionStatus::Unknown, + InstructionStatuses::::get(instruction_id) != InstructionStatus::Unknown, Error::::UnknownInstruction ); // Get all legs for the instruction @@ -2501,9 +2482,9 @@ impl Pallet { venue_id: &Option, ) -> DispatchResult { if let Some(venue_id) = venue_id { - if tickers.insert(asset_id) && Self::venue_filtering(asset_id) { + if tickers.insert(asset_id) && VenueFiltering::::get(asset_id) { ensure!( - Self::venue_allow_list(asset_id, venue_id), + VenueAllowList::::get(asset_id, venue_id), Error::::UnauthorizedVenue ); } @@ -2773,13 +2754,13 @@ impl Pallet { if let Some(venue_id) = venue_id { ensure!( - Self::venue_signers(venue_id, receipt_details.signer()), + VenueSigners::::get(venue_id, receipt_details.signer()), Error::::UnauthorizedSigner ); } ensure!( - !Self::receipts_used(receipt_details.signer(), &receipt_details.uid()), + !ReceiptsUsed::::get(receipt_details.signer(), &receipt_details.uid()), Error::::ReceiptAlreadyClaimed ); @@ -3166,7 +3147,7 @@ impl Pallet { ) -> Vec { let mut execution_errors = Vec::new(); - if Self::instruction_affirms_pending(instruction_id) != 0 { + if InstructionAffirmsPending::::get(instruction_id) != 0 { execution_errors.push(Error::::NotAllAffirmationsHaveBeenReceived.into()); } @@ -3174,7 +3155,7 @@ impl Pallet { execution_errors.push(e); } - match Self::instruction_status(instruction_id) { + match InstructionStatuses::::get(instruction_id) { InstructionStatus::Unknown | InstructionStatus::Success(_) | InstructionStatus::Rejected(_) => { @@ -3185,13 +3166,13 @@ impl Pallet { let instruction_legs: Vec<(LegId, Leg)> = InstructionLegs::::iter_prefix(&instruction_id).collect(); - let venue_id = Self::instruction_details(instruction_id).venue_id; + let venue_id = InstructionDetails::::get(instruction_id).venue_id; if let Err(e) = Self::ensure_allowed_venue(&instruction_legs, venue_id) { execution_errors.push(e); } for (leg_id, leg) in instruction_legs { - let leg_status = Self::instruction_leg_status(instruction_id, leg_id); + let leg_status = InstructionLegStatus::::get(instruction_id, leg_id); if leg_status == LegStatus::ExecutionPending { let transfer_errors = Self::transfer_report(leg, true, weight_meter); execution_errors.extend_from_slice(&transfer_errors); diff --git a/pallets/statistics/src/benchmarking.rs b/pallets/statistics/src/benchmarking.rs index 7993131cbe..fd00850226 100644 --- a/pallets/statistics/src/benchmarking.rs +++ b/pallets/statistics/src/benchmarking.rs @@ -496,7 +496,7 @@ benchmarks! { let statistics: BoundedBTreeSet = statistics.try_into().unwrap(); ActiveAssetStats::::insert(&asset_id, statistics); }: { - Pallet::::active_asset_stats(asset_id).into_iter(); + ActiveAssetStats::::get(asset_id).into_iter(); } is_exempt { diff --git a/pallets/statistics/src/lib.rs b/pallets/statistics/src/lib.rs index d573ece4fb..ed6097f6dc 100644 --- a/pallets/statistics/src/lib.rs +++ b/pallets/statistics/src/lib.rs @@ -138,7 +138,6 @@ pub mod pallet { /// Maps a set of [`StatType`] for each [`AssetId`]. #[pallet::storage] - #[pallet::getter(fn active_asset_stats)] pub(super) type ActiveAssetStats = StorageMap< _, Blake2_128Concat, @@ -149,7 +148,6 @@ pub mod pallet { /// Asset stats. #[pallet::storage] - #[pallet::getter(fn asset_stats)] pub type AssetStats = StorageDoubleMap< _, Blake2_128Concat, @@ -162,7 +160,6 @@ pub mod pallet { /// The [`AssetTransferCompliance`] for each [`AssetId`]. #[pallet::storage] - #[pallet::getter(fn asset_transfer_compliances)] pub(super) type AssetTransferCompliances = StorageMap< _, Blake2_128Concat, @@ -173,7 +170,6 @@ pub mod pallet { /// Entities exempt from a Transfer Compliance rule. #[pallet::storage] - #[pallet::getter(fn transfer_condition_exempt_entities)] pub(super) type TransferConditionExemptEntities = StorageDoubleMap< _, Blake2_128Concat, @@ -313,7 +309,7 @@ impl Pallet { } fn is_asset_stat_active(asset_id: &AssetId, stat_type: &StatType) -> bool { - Self::active_asset_stats(asset_id).contains(stat_type) + ActiveAssetStats::::get(asset_id).contains(stat_type) } fn base_set_active_asset_stats( @@ -336,7 +332,7 @@ impl Pallet { .collect::>(); // Check if removed StatTypes are needed by TransferConditions. - let remove_types = Self::active_asset_stats(&asset_id) + let remove_types = ActiveAssetStats::::get(&asset_id) .into_iter() // Only remove stats that are not in the new `stat_types` set. .filter(|stat_type| !stat_types.contains(&stat_type)) @@ -652,7 +648,7 @@ impl Pallet { let count_changes = Self::investor_count_changes(from_balance, to_balance, amount); // Update active asset stats. - for stat_type in Self::active_asset_stats(asset_id).into_iter() { + for stat_type in ActiveAssetStats::::get(asset_id).into_iter() { let key1 = Stat1stKey { asset_id, stat_type, @@ -973,10 +969,10 @@ impl Pallet { match transfer_condition_exempt_key.op { // Count transfer conditions require the sender to be exempt. StatOpType::Count => { - Self::transfer_condition_exempt_entities(transfer_condition_exempt_key, sender_did) + TransferConditionExemptEntities::::get(transfer_condition_exempt_key, sender_did) } // Percent ownersip transfer conditions require the receiver to be exempt. - StatOpType::Balance => Self::transfer_condition_exempt_entities( + StatOpType::Balance => TransferConditionExemptEntities::::get( transfer_condition_exempt_key, receiver_did, ), diff --git a/pallets/sto/src/benchmarking.rs b/pallets/sto/src/benchmarking.rs index 2a82569bc9..b7b404c012 100644 --- a/pallets/sto/src/benchmarking.rs +++ b/pallets/sto/src/benchmarking.rs @@ -4,6 +4,7 @@ use scale_info::prelude::format; use pallet_asset::benchmarking::setup_asset_transfer; use pallet_identity::benchmarking::{User, UserBuilder}; +use pallet_settlement::VenueCounter; use polymesh_primitives::settlement::VenueDetails; use polymesh_primitives::TrustedIssuer; @@ -87,7 +88,7 @@ fn generate_tiers(n: u32) -> Vec { } fn create_venue(user: &User) -> Result { - let venue_id = >::venue_counter(); + let venue_id = VenueCounter::::get(); >::create_venue( user.origin().into(), VenueDetails::default(), diff --git a/pallets/sto/src/lib.rs b/pallets/sto/src/lib.rs index 92a96457dc..6e7f264530 100644 --- a/pallets/sto/src/lib.rs +++ b/pallets/sto/src/lib.rs @@ -269,8 +269,7 @@ pub mod pallet { /// (AssetId, fundraiser_id) -> Fundraiser #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn fundraisers)] - pub(super) type Fundraisers = StorageDoubleMap< + pub type Fundraisers = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -282,16 +281,14 @@ pub mod pallet { /// Total fundraisers created for a token. #[pallet::storage] - #[pallet::getter(fn fundraiser_count)] - pub(super) type FundraiserCount = + pub type FundraiserCount = StorageMap<_, Blake2_128Concat, AssetId, FundraiserId, ValueQuery>; /// Name for the Fundraiser. Only used offchain. /// (AssetId, fundraiser_id) -> Fundraiser name #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn fundraiser_name)] - pub(super) type FundraiserNames = StorageDoubleMap< + pub type FundraiserNames = StorageDoubleMap< _, Blake2_128Concat, AssetId, diff --git a/pallets/sudo/src/extension.rs b/pallets/sudo/src/extension.rs index 3f408e6ddc..6eccb0146c 100644 --- a/pallets/sudo/src/extension.rs +++ b/pallets/sudo/src/extension.rs @@ -15,7 +15,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{Config, Pallet}; use codec::{Decode, Encode}; use frame_support::{dispatch::DispatchInfo, ensure}; use scale_info::TypeInfo; @@ -28,6 +27,8 @@ use sp_runtime::{ }; use sp_std::{fmt, marker::PhantomData}; +use crate::{Config, Key}; + /// Ensure that signed transactions are only valid if they are signed by sudo account. /// /// In the initial phase of a chain without any tokens you can not prevent accounts from sending @@ -86,7 +87,7 @@ where info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - let sudo_key: T::AccountId = >::key().ok_or(UnknownTransaction::CannotLookup)?; + let sudo_key: T::AccountId = Key::::get().ok_or(UnknownTransaction::CannotLookup)?; ensure!(*who == sudo_key, InvalidTransaction::BadSigner); Ok(ValidTransaction { diff --git a/pallets/sudo/src/lib.rs b/pallets/sudo/src/lib.rs index 99eac09510..40952d5ff6 100644 --- a/pallets/sudo/src/lib.rs +++ b/pallets/sudo/src/lib.rs @@ -258,7 +258,7 @@ pub mod pallet { // Only allow signed origins. let sender = ensure_signed(origin)?; // Ensure the signer is the current Sudo key. - if Some(sender) != Self::key() { + if Some(sender) != Key::::get() { // roughly same as a 4 byte remark since perbill is u32. return Err(DispatchErrorWithPostInfo { post_info: Some(MIN_WEIGHT).into(), @@ -289,8 +289,7 @@ pub mod pallet { /// The `AccountId` of the sudo key. #[pallet::storage] - #[pallet::getter(fn key)] - pub(super) type Key = StorageValue<_, T::AccountId, OptionQuery>; + pub type Key = StorageValue<_, T::AccountId, OptionQuery>; #[pallet::genesis_config] pub struct GenesisConfig { diff --git a/pallets/sudo/src/mock.rs b/pallets/sudo/src/mock.rs index ab0ff6f4a8..bf43e49636 100644 --- a/pallets/sudo/src/mock.rs +++ b/pallets/sudo/src/mock.rs @@ -92,13 +92,11 @@ pub mod logger { } #[pallet::storage] - #[pallet::getter(fn account_log)] - pub(super) type AccountLog = + pub type AccountLog = StorageValue<_, BoundedVec>, ValueQuery>; #[pallet::storage] - #[pallet::getter(fn i32_log)] - pub(super) type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; + pub type I32Log = StorageValue<_, BoundedVec>, ValueQuery>; } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/pallets/sudo/src/tests.rs b/pallets/sudo/src/tests.rs index e9f89aa400..c11f692b38 100644 --- a/pallets/sudo/src/tests.rs +++ b/pallets/sudo/src/tests.rs @@ -17,20 +17,22 @@ //! Tests for the module. -use super::*; use frame_support::{assert_noop, assert_ok, weights::Weight}; -use mock::{ - new_test_ext, Logger, LoggerCall, RuntimeCall, RuntimeEvent as TestEvent, RuntimeOrigin, Sudo, + +use crate::mock::logger::{AccountLog, I32Log}; +use crate::mock::{ + new_test_ext, LoggerCall, RuntimeCall, RuntimeEvent as TestEvent, RuntimeOrigin, Sudo, SudoCall, System, Test, }; +use crate::*; #[test] fn test_setup_works() { // Environment setup, logger storage, and sudo `key` retrieval should work as expected. new_test_ext(1).execute_with(|| { - assert_eq!(Sudo::key(), Some(1u64)); - assert!(Logger::i32_log().is_empty()); - assert!(Logger::account_log().is_empty()); + assert_eq!(Key::::get(), Some(1u64)); + assert!(I32Log::::get().is_empty()); + assert!(AccountLog::::get().is_empty()); }); } @@ -44,7 +46,7 @@ fn sudo_basics() { weight: Weight::from_ref_time(1_000), })); assert_ok!(Sudo::sudo(RuntimeOrigin::signed(1), call)); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // A privileged function should not work when `sudo` is passed a non-root `key` as `origin`. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -92,7 +94,7 @@ fn sudo_unchecked_weight_basics() { call, Weight::from_ref_time(1_000) )); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // A privileged function should not work when called with a non-root `key`. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -111,7 +113,7 @@ fn sudo_unchecked_weight_basics() { } ); // `I32Log` is unchanged after unsuccessful call. - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // Controls the dispatched weight. let call = Box::new(RuntimeCall::Logger(LoggerCall::privileged_i32_log { @@ -154,7 +156,7 @@ fn set_key_basics() { new_test_ext(1).execute_with(|| { // A root `key` can change the root `key` assert_ok!(Sudo::set_key(RuntimeOrigin::signed(1), 2)); - assert_eq!(Sudo::key(), Some(2u64)); + assert_eq!(Key::::get(), Some(2u64)); }); new_test_ext(1).execute_with(|| { @@ -198,8 +200,8 @@ fn sudo_as_basics() { weight: Weight::from_ref_time(1_000), })); assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); - assert!(Logger::i32_log().is_empty()); - assert!(Logger::account_log().is_empty()); + assert!(I32Log::::get().is_empty()); + assert!(AccountLog::::get().is_empty()); // A non-privileged function should not work when called with a non-root `key`. let call = Box::new(RuntimeCall::Logger(LoggerCall::non_privileged_log { @@ -220,9 +222,9 @@ fn sudo_as_basics() { weight: Weight::from_ref_time(1), })); assert_ok!(Sudo::sudo_as(RuntimeOrigin::signed(1), 2, call)); - assert_eq!(Logger::i32_log(), vec![42i32]); + assert_eq!(I32Log::::get(), vec![42i32]); // The correct user makes the call within `sudo_as`. - assert_eq!(Logger::account_log(), vec![2]); + assert_eq!(AccountLog::::get(), vec![2]); }); } diff --git a/pallets/transaction-payment/src/lib.rs b/pallets/transaction-payment/src/lib.rs index b0dfc4318d..b71f229c80 100644 --- a/pallets/transaction-payment/src/lib.rs +++ b/pallets/transaction-payment/src/lib.rs @@ -375,13 +375,11 @@ pub mod pallet { } #[pallet::storage] - #[pallet::getter(fn next_fee_multiplier)] pub type NextFeeMultiplier = StorageValue<_, Multiplier, ValueQuery, NextFeeMultiplierOnEmpty>; #[cfg(feature = "disable_fees")] #[pallet::storage] - #[pallet::getter(fn disable_fees)] pub type DisableFees = StorageValue<_, bool, ValueQuery>; #[pallet::storage] @@ -676,7 +674,7 @@ where if pays_fee == Pays::Yes { // the adjustable part of the fee. let unadjusted_weight_fee = Self::weight_to_fee(weight); - let multiplier = Self::next_fee_multiplier(); + let multiplier = NextFeeMultiplier::::get(); // final adjusted weight fee. let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee); diff --git a/pallets/utility/src/benchmarking.rs b/pallets/utility/src/benchmarking.rs index d206334097..8929087d48 100644 --- a/pallets/utility/src/benchmarking.rs +++ b/pallets/utility/src/benchmarking.rs @@ -62,7 +62,7 @@ fn remark_call_builder( _: T::AccountId, ) -> (UniqueCall<::RuntimeCall>, Vec) { let call = make_calls::(1).pop().unwrap(); - let nonce: AuthorizationNonce = Pallet::::nonce(signer.account()); + let nonce: AuthorizationNonce = Nonces::::get(signer.account()); let call = UniqueCall::new(nonce, call); // Signer signs the relay call. diff --git a/pallets/utility/src/lib.rs b/pallets/utility/src/lib.rs index aa92de1154..e11dd09118 100644 --- a/pallets/utility/src/lib.rs +++ b/pallets/utility/src/lib.rs @@ -251,8 +251,7 @@ pub mod pallet { /// Nonce for `relay_tx`. /// POLYMESH: added. #[pallet::storage] - #[pallet::getter(fn nonce)] - pub(super) type Nonces = + pub type Nonces = StorageMap<_, Twox64Concat, T::AccountId, AuthorizationNonce, ValueQuery>; #[pallet::call] From eca0bd16075cce5a03024fa64e1258c9462f439c Mon Sep 17 00:00:00 2001 From: Henrique Nogara Date: Mon, 10 Feb 2025 11:46:12 -0300 Subject: [PATCH 2/3] Remove getters - part 2 --- pallets/asset/src/benchmarking.rs | 10 ++--- pallets/asset/src/lib.rs | 36 +++------------ pallets/corporate-actions/src/lib.rs | 4 +- pallets/portfolio/src/lib.rs | 29 ++++-------- .../runtime/tests/src/asset_metadata_test.rs | 5 ++- pallets/runtime/tests/src/asset_test.rs | 38 ++++++++++------ .../tests/src/corporate_actions_test.rs | 20 ++++++--- pallets/runtime/tests/src/portfolio.rs | 36 ++++++++------- pallets/runtime/tests/src/settlement_test.rs | 45 ++++++++++++------- pallets/runtime/tests/src/sto_test.rs | 31 ++++++++----- pallets/runtime/tests/src/utility_test.rs | 4 +- pallets/sto/src/benchmarking.rs | 3 +- 12 files changed, 135 insertions(+), 126 deletions(-) diff --git a/pallets/asset/src/benchmarking.rs b/pallets/asset/src/benchmarking.rs index 48c2464311..4f2fe01c6c 100644 --- a/pallets/asset/src/benchmarking.rs +++ b/pallets/asset/src/benchmarking.rs @@ -84,7 +84,7 @@ fn register_metadata_global_name() -> AssetMetadataKey { Pallet::::register_asset_metadata_global_type(root, name, spec).unwrap(); - let key = Pallet::::current_asset_metadata_global_key().unwrap(); + let key = CurrentAssetMetadataGlobalKey::::get().unwrap(); AssetMetadataKey::Global(key) } @@ -435,7 +435,7 @@ benchmarks! { verify { for i in 1..d { assert_eq!( - Pallet::::asset_documents(asset_id, DocumentId(i)).unwrap(), + AssetDocuments::::get(asset_id, DocumentId(i)).unwrap(), docs[i as usize] ); } @@ -515,7 +515,7 @@ benchmarks! { }: _(bob.origin.clone(), asset_id, 1_000, PortfolioId::default_portfolio(alice.did())) verify { assert_eq!( - Pallet::::balance_of(asset_id, bob.did()), + BalanceOf::::get(asset_id, bob.did()), 1_000 ); } @@ -525,10 +525,10 @@ benchmarks! { let alice = UserBuilder::::default().generate_did().build("Alice"); let ty = vec![b'X'; n as usize]; - assert_eq!(Pallet::::custom_type_id_seq(), CustomAssetTypeId(0)); + assert_eq!(CustomTypeIdSequence::::get(), CustomAssetTypeId(0)); }: _(alice.origin, ty) verify { - assert_eq!(Pallet::::custom_type_id_seq(), CustomAssetTypeId(1)); + assert_eq!(CustomTypeIdSequence::::get(), CustomAssetTypeId(1)); } set_asset_metadata { diff --git a/pallets/asset/src/lib.rs b/pallets/asset/src/lib.rs index ad060a152a..e7ed0dad9d 100644 --- a/pallets/asset/src/lib.rs +++ b/pallets/asset/src/lib.rs @@ -334,41 +334,35 @@ pub mod pallet { /// Map each [`Ticker`] to its registration details ([`TickerRegistration`]). #[pallet::storage] - #[pallet::getter(fn unique_ticker_registration)] pub type UniqueTickerRegistration = StorageMap<_, Blake2_128Concat, Ticker, TickerRegistration, OptionQuery>; /// Returns [`TickerRegistrationConfig`] for assessing if a ticker is valid. #[pallet::storage] - #[pallet::getter(fn ticker_registration_config)] pub type TickerConfig = StorageValue<_, TickerRegistrationConfig, ValueQuery>; /// Maps each [`AssetId`] to its underling [`AssetDetails`]. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn assets_details)] pub type Assets = StorageMap<_, Blake2_128Concat, AssetId, AssetDetails, OptionQuery>; /// Maps each [`AssetId`] to its underling [`AssetName`]. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_names)] pub type AssetNames = StorageMap<_, Blake2_128Concat, AssetId, AssetName, OptionQuery>; /// Tracks the total [`Balance`] for each [`AssetId`] per [`IdentityId`]. // NB: It is safe to use `identity` hasher here because assets can not be distributed to non-existent identities. #[pallet::storage] - #[pallet::getter(fn balance_of)] pub type BalanceOf = StorageDoubleMap<_, Blake2_128Concat, AssetId, Identity, IdentityId, Balance, ValueQuery>; /// Maps each [`AssetId`] to its asset identifiers ([`AssetIdentifier`]). #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_identifiers)] pub type AssetIdentifiers = StorageMap<_, Blake2_128Concat, AssetId, Vec, ValueQuery>; @@ -376,46 +370,39 @@ pub mod pallet { /// /// Numbers in the sequence start from 1 rather than 0. #[pallet::storage] - #[pallet::getter(fn custom_type_id_seq)] pub type CustomTypeIdSequence = StorageValue<_, CustomAssetTypeId, ValueQuery>; /// Maps custom asset type ids to the registered string contents. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn custom_types)] pub type CustomTypes = StorageMap<_, Twox64Concat, CustomAssetTypeId, Vec, ValueQuery>; /// Inverse map of `CustomTypes`, from registered string contents to custom asset type ids. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn custom_types_inverse)] pub type CustomTypesInverse = StorageMap<_, Blake2_128Concat, Vec, CustomAssetTypeId, OptionQuery>; /// Maps each [`AssetId`] to the name of its founding round ([`FundingRoundName`]). #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn funding_round)] pub type FundingRound = StorageMap<_, Blake2_128Concat, AssetId, FundingRoundName, ValueQuery>; /// The total [`Balance`] of tokens issued in all recorded funding rounds ([`FundingRoundName`]). #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn issued_in_funding_round)] pub type IssuedInFundingRound = StorageMap<_, Blake2_128Concat, (AssetId, FundingRoundName), Balance, ValueQuery>; /// Returns `true` if transfers for the asset are frozen. Otherwise, returns `false`. #[pallet::storage] - #[pallet::getter(fn frozen)] pub type Frozen = StorageMap<_, Blake2_128Concat, AssetId, bool, ValueQuery>; /// All [`Document`] attached to an asset. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_documents)] pub type AssetDocuments = StorageDoubleMap< _, Blake2_128Concat, @@ -428,14 +415,12 @@ pub mod pallet { /// [`DocumentId`] counter per [`AssetId`]. #[pallet::storage] - #[pallet::getter(fn asset_documents_id_sequence)] pub type AssetDocumentsIdSequence = StorageMap<_, Blake2_128Concat, AssetId, DocumentId, ValueQuery>; /// Metatdata values for an asset. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_values)] pub type AssetMetadataValues = StorageDoubleMap< _, Blake2_128Concat, @@ -448,7 +433,6 @@ pub mod pallet { /// Details for an asset's Metadata values. #[pallet::storage] - #[pallet::getter(fn asset_metadata_value_details)] pub type AssetMetadataValueDetails = StorageDoubleMap< _, Blake2_128Concat, @@ -462,7 +446,6 @@ pub mod pallet { /// Asset Metadata Local Name -> Key. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_local_name_to_key)] pub type AssetMetadataLocalNameToKey = StorageDoubleMap< _, Blake2_128Concat, @@ -476,14 +459,12 @@ pub mod pallet { /// Asset Metadata Global Name -> Key. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_global_name_to_key)] pub type AssetMetadataGlobalNameToKey = StorageMap<_, Blake2_128Concat, AssetMetadataName, AssetMetadataGlobalKey, OptionQuery>; /// Asset Metadata Local Key -> Name. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_local_key_to_name)] pub type AssetMetadataLocalKeyToName = StorageDoubleMap< _, Blake2_128Concat, @@ -497,14 +478,12 @@ pub mod pallet { /// Asset Metadata Global Key -> Name. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_global_key_to_name)] pub type AssetMetadataGlobalKeyToName = StorageMap<_, Twox64Concat, AssetMetadataGlobalKey, AssetMetadataName, OptionQuery>; /// Asset Metadata Local Key specs. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_local_specs)] pub type AssetMetadataLocalSpecs = StorageDoubleMap< _, Blake2_128Concat, @@ -518,7 +497,6 @@ pub mod pallet { /// Asset Metadata Global Key specs. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn asset_metadata_global_specs)] pub type AssetMetadataGlobalSpecs = StorageMap<_, Twox64Concat, AssetMetadataGlobalKey, AssetMetadataSpec, OptionQuery>; @@ -544,13 +522,11 @@ pub mod pallet { /// The last [`AssetMetadataLocalKey`] used for [`AssetId`]. #[pallet::storage] - #[pallet::getter(fn current_asset_metadata_local_key)] pub type CurrentAssetMetadataLocalKey = StorageMap<_, Blake2_128Concat, AssetId, AssetMetadataLocalKey, OptionQuery>; /// The last [`AssetMetadataGlobalKey`] used for a global key. #[pallet::storage] - #[pallet::getter(fn current_asset_metadata_global_key)] pub type CurrentAssetMetadataGlobalKey = StorageValue<_, AssetMetadataGlobalKey, OptionQuery>; @@ -1945,10 +1921,10 @@ impl Pallet { >::advance_update_balances( &asset_id, - &[(portfolio.did, Self::balance_of(asset_id, portfolio.did))], + &[(portfolio.did, BalanceOf::::get(asset_id, portfolio.did))], )?; - let updated_balance = Self::balance_of(asset_id, portfolio.did) - value; + let updated_balance = BalanceOf::::get(asset_id, portfolio.did) - value; // Update identity balances and total supply BalanceOf::::insert(asset_id, &portfolio.did, updated_balance); @@ -2855,7 +2831,7 @@ impl Pallet { pub fn get_balance_at(asset_id: AssetId, did: IdentityId, at: CheckpointId) -> Balance { >::balance_at(asset_id, did, at) - .unwrap_or_else(|| Self::balance_of(&asset_id, &did)) + .unwrap_or_else(|| BalanceOf::::get(&asset_id, &did)) } pub fn validate_asset_transfer( @@ -2917,8 +2893,8 @@ impl Pallet { asset_id, &sender_portfolio.did, &receiver_portfolio.did, - Self::balance_of(asset_id, sender_portfolio.did), - Self::balance_of(asset_id, receiver_portfolio.did), + BalanceOf::::get(asset_id, sender_portfolio.did), + BalanceOf::::get(asset_id, receiver_portfolio.did), transfer_value, asset_details.total_supply, weight_meter, @@ -3257,7 +3233,7 @@ impl Pallet { // No check since the total balance is always <= the total supply let new_issuer_portfolio_balance = - Portfolio::::portfolio_asset_balances(issuer_portfolio, asset_id) + amount_to_issue; + PortfolioAssetBalances::::get(issuer_portfolio, asset_id) + amount_to_issue; Portfolio::::set_portfolio_balance( issuer_portfolio, asset_id, diff --git a/pallets/corporate-actions/src/lib.rs b/pallets/corporate-actions/src/lib.rs index 97c6954743..9d5a72d8e5 100644 --- a/pallets/corporate-actions/src/lib.rs +++ b/pallets/corporate-actions/src/lib.rs @@ -101,7 +101,7 @@ use frame_support::{ weights::Weight, }; use frame_system::ensure_root; -use pallet_asset::checkpoint; +use pallet_asset::{checkpoint, BalanceOf}; use pallet_base::try_next_post; use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData}; use polymesh_common_utilities::checkpoint::ScheduleId; @@ -1099,7 +1099,7 @@ impl Pallet { Some(cp_id) => >::get_balance_at(asset_id, did, cp_id), // Although record date has passed, no transfers have happened yet for `asset_id`. // Thus, there is no checkpoint ID, and we must use current balance instead. - None => >::balance_of(asset_id, did), + None => BalanceOf::::get(asset_id, did), } } diff --git a/pallets/portfolio/src/lib.rs b/pallets/portfolio/src/lib.rs index 474a78cf37..b876a001d8 100644 --- a/pallets/portfolio/src/lib.rs +++ b/pallets/portfolio/src/lib.rs @@ -224,7 +224,6 @@ pub mod pallet { /// pair maps to `Some(name)` then such a portfolio exists and is called `name`. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn portfolios)] pub type Portfolios = StorageDoubleMap< _, Identity, @@ -239,7 +238,6 @@ pub mod pallet { /// and uniqueness of names in `Portfolios`. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn name_to_number)] pub type NameToNumber = StorageDoubleMap< _, Identity, @@ -252,13 +250,11 @@ pub mod pallet { /// How many assets with non-zero balance this portfolio contains. #[pallet::storage] - #[pallet::getter(fn portfolio_has_assets)] pub type PortfolioAssetCount = StorageMap<_, Twox64Concat, PortfolioId, u64, ValueQuery>; /// The asset balances of portfolios. #[pallet::storage] - #[pallet::getter(fn portfolio_asset_balances)] pub type PortfolioAssetBalances = StorageDoubleMap< _, Twox64Concat, @@ -272,7 +268,6 @@ pub mod pallet { /// Amount of assets locked in a portfolio. /// These assets show up in portfolio balance but can not be transferred away. #[pallet::storage] - #[pallet::getter(fn locked_assets)] pub type PortfolioLockedAssets = StorageDoubleMap< _, Twox64Concat, @@ -285,7 +280,6 @@ pub mod pallet { /// The custodian of a particular portfolio. None implies that the identity owner is the custodian. #[pallet::storage] - #[pallet::getter(fn portfolio_custodian)] pub type PortfolioCustodian = StorageMap<_, Twox64Concat, PortfolioId, IdentityId, OptionQuery>; @@ -293,13 +287,11 @@ pub mod pallet { /// When `true` is stored as the value for a given `(did, pid)`, it means that `pid` is in custody of `did`. /// `false` values are never explicitly stored in the map, and are instead inferred by the absence of a key. #[pallet::storage] - #[pallet::getter(fn portfolios_in_custody)] pub type PortfoliosInCustody = StorageDoubleMap<_, Identity, IdentityId, Twox64Concat, PortfolioId, bool, ValueQuery>; /// The nft associated to the portfolio. #[pallet::storage] - #[pallet::getter(fn portfolio_nft)] pub type PortfolioNFT = StorageDoubleMap< _, Twox64Concat, @@ -312,7 +304,6 @@ pub mod pallet { /// All locked nft for a given portfolio. #[pallet::storage] - #[pallet::getter(fn portfolio_locked_nft)] pub type PortfolioLockedNFT = StorageDoubleMap< _, Twox64Concat, @@ -325,13 +316,11 @@ pub mod pallet { /// All portfolios that don't need to affirm the receivement of a given [`AssetId`]. #[pallet::storage] - #[pallet::getter(fn pre_approved_portfolios)] pub type PreApprovedPortfolios = StorageDoubleMap<_, Twox64Concat, PortfolioId, Blake2_128Concat, AssetId, bool, ValueQuery>; /// Custodians allowed to create and take custody of portfolios on an id's behalf. #[pallet::storage] - #[pallet::getter(fn allowed_custodians)] pub type AllowedCustodians = StorageDoubleMap<_, Identity, IdentityId, Identity, IdentityId, bool, ValueQuery>; @@ -684,7 +673,7 @@ impl Pallet { /// Returns the asset balance of the identity's default portfolio. pub fn default_portfolio_balance(did: IdentityId, asset_id: &AssetId) -> Balance { - Self::portfolio_asset_balances(PortfolioId::default_portfolio(did), asset_id) + PortfolioAssetBalances::::get(PortfolioId::default_portfolio(did), asset_id) } /// Returns the asset balance of an identity's user portfolio. @@ -693,7 +682,7 @@ impl Pallet { num: PortfolioNumber, asset_id: &AssetId, ) -> Balance { - Self::portfolio_asset_balances(PortfolioId::user_portfolio(did, num), asset_id) + PortfolioAssetBalances::::get(PortfolioId::user_portfolio(did, num), asset_id) } /// Sets the asset balance of the specified portfolio to `new_balance`. @@ -799,7 +788,7 @@ impl Pallet { // If a custodian is assigned, only they are allowed. // Else, only the portfolio owner is allowed ensure!( - Self::portfolio_custodian(portfolio).unwrap_or(portfolio.did) == custodian, + PortfolioCustodian::::get(portfolio).unwrap_or(portfolio.did) == custodian, Error::::UnauthorizedCustodian ); @@ -861,8 +850,8 @@ impl Pallet { amount: Balance, ) -> DispatchResult { // Ensure portfolio has enough free balance - let total_balance = Self::portfolio_asset_balances(&pid, asset_id); - let locked_balance = Self::locked_assets(&pid, asset_id); + let total_balance = PortfolioAssetBalances::::get(&pid, asset_id); + let locked_balance = PortfolioLockedAssets::::get(&pid, asset_id); let remaining_balance = total_balance .checked_sub(amount) .filter(|rb| rb >= &locked_balance) @@ -890,8 +879,8 @@ impl Pallet { amount: Balance, ) -> DispatchResult { T::AssetFn::ensure_granular(asset_id, amount)?; - Self::portfolio_asset_balances(portfolio, asset_id) - .saturating_sub(Self::locked_assets(portfolio, asset_id)) + PortfolioAssetBalances::::get(portfolio, asset_id) + .saturating_sub(PortfolioLockedAssets::::get(portfolio, asset_id)) .checked_sub(amount) .ok_or_else(|| Error::::InsufficientPortfolioBalance.into()) .map(drop) @@ -1180,7 +1169,7 @@ impl PortfolioSubTrait for Pallet { amount: Balance, ) -> DispatchResult { // 1. Ensure portfolio has enough locked tokens - let locked = Self::locked_assets(portfolio, asset_id); + let locked = PortfolioLockedAssets::::get(portfolio, asset_id); ensure!(locked >= amount, Error::::InsufficientTokensLocked); // 2. Unlock tokens. Can not underflow due to above ensure. @@ -1253,7 +1242,7 @@ impl PortfolioSubTrait for Pallet { } fn skip_portfolio_affirmation(portfolio_id: &PortfolioId, asset_id: &AssetId) -> bool { - if Self::portfolio_custodian(portfolio_id).is_some() { + if PortfolioCustodian::::get(portfolio_id).is_some() { if T::AssetFn::asset_affirmation_exemption(asset_id) { return true; } diff --git a/pallets/runtime/tests/src/asset_metadata_test.rs b/pallets/runtime/tests/src/asset_metadata_test.rs index d416d394f7..da83c32fd1 100644 --- a/pallets/runtime/tests/src/asset_metadata_test.rs +++ b/pallets/runtime/tests/src/asset_metadata_test.rs @@ -6,6 +6,7 @@ use super::{ ExtBuilder, }; use frame_support::{assert_noop, assert_ok, dispatch::DispatchError}; +use pallet_asset::{AssetMetadataGlobalNameToKey, AssetMetadataLocalNameToKey}; use polymesh_primitives::asset::AssetId; use polymesh_primitives::asset_metadata::{ AssetMetadataKey, AssetMetadataLockStatus, AssetMetadataName, AssetMetadataSpec, @@ -87,7 +88,7 @@ fn register_metadata_type(owner: User, asset_id: Option, name: &str) -> spec, )); - Asset::asset_metadata_local_name_to_key(asset_id, name) + AssetMetadataLocalNameToKey::::get(asset_id, name) .map(AssetMetadataKey::from) .expect("Failed to register metadata") } else { @@ -99,7 +100,7 @@ fn register_metadata_type(owner: User, asset_id: Option, name: &str) -> spec, )); - Asset::asset_metadata_global_name_to_key(name) + AssetMetadataGlobalNameToKey::::get(name) .map(AssetMetadataKey::from) .expect("Failed to register metadata") } diff --git a/pallets/runtime/tests/src/asset_test.rs b/pallets/runtime/tests/src/asset_test.rs index 7fa0dcf8fe..4878bc3abd 100644 --- a/pallets/runtime/tests/src/asset_test.rs +++ b/pallets/runtime/tests/src/asset_test.rs @@ -12,13 +12,14 @@ use sp_std::iter; use pallet_asset::{ AssetDetails, AssetDocuments, AssetIdentifiers, AssetMetadataLocalKeyToName, - AssetMetadataLocalNameToKey, AssetMetadataLocalSpecs, AssetMetadataValues, Assets, + AssetMetadataLocalNameToKey, AssetMetadataLocalSpecs, AssetMetadataValues, AssetNames, Assets, AssetsExemptFromAffirmation, BalanceOf, Config as AssetConfig, CustomTypeIdSequence, - CustomTypes, CustomTypesInverse, MandatoryMediators, PreApprovedAsset, + CustomTypes, CustomTypesInverse, FundingRound, MandatoryMediators, PreApprovedAsset, SecurityTokensOwnedByUser, }; use pallet_portfolio::{ - NextPortfolioNumber, PortfolioAssetBalances, PortfolioAssetCount, PortfolioLockedAssets, + NextPortfolioNumber, PortfolioAssetBalances, PortfolioAssetCount, PortfolioCustodian, + PortfolioLockedAssets, }; use pallet_statistics::AssetStats; use polymesh_common_utilities::checkpoint::{NextCheckpoints, ScheduleCheckpoints, ScheduleId}; @@ -243,7 +244,10 @@ fn issuers_can_create_and_rename_tokens() { SecurityTokensOwnedByUser::::get(owner.did, asset_id), true ); - assert_eq!(Asset::funding_round(asset_id), funding_round_name.clone()); + assert_eq!( + FundingRound::::get(asset_id), + funding_round_name.clone() + ); // Unauthorized agents cannot rename the token. let eve = User::new(AccountKeyring::Eve); @@ -256,8 +260,8 @@ fn issuers_can_create_and_rename_tokens() { // Rename the token and check storage has been updated. let new: AssetName = [0x42].into(); assert_ok!(Asset::rename_asset(owner.origin(), asset_id, new.clone())); - assert_eq!(Asset::asset_names(asset_id), Some(new)); - assert!(Asset::asset_identifiers(asset_id).is_empty()); + assert_eq!(AssetNames::::get(asset_id), Some(new)); + assert!(AssetIdentifiers::::get(asset_id).is_empty()); }); } @@ -278,8 +282,11 @@ fn valid_transfers_pass() { ); assert_ok!(transfer(owner, alice)); - assert_eq!(Asset::balance_of(&asset_id, owner.did), ISSUE_AMOUNT - 500); - assert_eq!(Asset::balance_of(&asset_id, alice.did), 500); + assert_eq!( + BalanceOf::::get(&asset_id, owner.did), + ISSUE_AMOUNT - 500 + ); + assert_eq!(BalanceOf::::get(&asset_id, alice.did), 500); }) } @@ -325,7 +332,7 @@ fn issuers_can_redeem_tokens() { PortfolioAssetCount::::get(owner_portfolio_id), 0 ); - assert_eq!(Asset::balance_of(&asset_id, owner.did), 0); + assert_eq!(BalanceOf::::get(&asset_id, owner.did), 0); assert_eq!(get_asset_details(&asset_id).total_supply, 0); assert_noop!( @@ -398,7 +405,7 @@ fn controller_transfer() { assert_ok!(transfer(asset_id, owner, alice, 500)); - let balance_of = |did| Asset::balance_of(&asset_id, did); + let balance_of = |did| BalanceOf::::get(&asset_id, did); let balance_alice = balance_of(alice.did); let balance_owner = balance_of(owner.did); assert_eq!(balance_owner, ISSUE_AMOUNT - 500); @@ -611,7 +618,7 @@ fn adding_removing_documents() { for (idx, doc) in documents.into_iter().enumerate() { assert_eq!( Some(doc), - Asset::asset_documents(asset_id, DocumentId(idx as u32)) + AssetDocuments::::get(asset_id, DocumentId(idx as u32)) ); } @@ -770,7 +777,7 @@ fn next_checkpoint_is_updated_we() { // After this transfer Alice's balance is 0. transfer(checkpoint2); // The balance after checkpoint 2. - assert_eq!(0, Asset::balance_of(&asset_id, owner.did)); + assert_eq!(0, BalanceOf::::get(&asset_id, owner.did)); // Balances at checkpoint 2. let id = CheckpointId(2); assert_eq!(vec![start + 2 * period_ms], checkpoint_ats(asset_id)); @@ -1289,7 +1296,10 @@ fn issuers_can_redeem_tokens_from_portfolio() { PortfolioKind::User(next_portfolio_num) )); - assert_eq!(Asset::balance_of(&asset_id, owner.did), ISSUE_AMOUNT / 2); + assert_eq!( + BalanceOf::::get(&asset_id, owner.did), + ISSUE_AMOUNT / 2 + ); assert_eq!(get_asset_details(&asset_id).total_supply, ISSUE_AMOUNT / 2); // Add auth for custody to be moved to bob @@ -1305,7 +1315,7 @@ fn issuers_can_redeem_tokens_from_portfolio() { assert_ok!(Portfolio::accept_portfolio_custody(bob.origin(), auth_id)); assert_eq!( - Portfolio::portfolio_custodian(user_portfolio), + PortfolioCustodian::::get(user_portfolio), Some(bob.did) ); diff --git a/pallets/runtime/tests/src/corporate_actions_test.rs b/pallets/runtime/tests/src/corporate_actions_test.rs index ee8e2f749a..0185d9f182 100644 --- a/pallets/runtime/tests/src/corporate_actions_test.rs +++ b/pallets/runtime/tests/src/corporate_actions_test.rs @@ -10,7 +10,7 @@ use frame_support::{ assert_noop, assert_ok, dispatch::{DispatchError, DispatchResult}, }; -use pallet_asset::Assets; +use pallet_asset::{Assets, BalanceOf}; use pallet_corporate_actions::{ ballot::{ BallotMeta, BallotTimeRange, BallotVote, Metas, Motion, MotionNumChoices, Results, @@ -1626,7 +1626,7 @@ fn vote_works() { // Total asset balance voter == AMOUNT. transfer(&asset_id, owner, voter); transfer(&asset_id, owner, other); - assert_eq!(Asset::balance_of(&asset_id, voter.did), AMOUNT); + assert_eq!(BalanceOf::::get(&asset_id, voter.did), AMOUNT); let id = notice_ca(owner, asset_id, Some(1)).unwrap(); assert_ok!(attach(owner, id, false)); @@ -2124,7 +2124,10 @@ fn dist_claim_works() { already(foo); let benefit_foo = AMOUNT * per_share / PER_SHARE_PRECISION; let post_tax_foo = benefit_foo - benefit_foo * 1 / 4; - assert_eq!(Asset::balance_of(¤cy, foo.did), post_tax_foo); + assert_eq!( + BalanceOf::::get(¤cy, foo.did), + post_tax_foo + ); let assert_rem = |removed| { assert_eq!( Distributions::::get(id).unwrap().remaining, @@ -2138,7 +2141,10 @@ fn dist_claim_works() { already(bar); let benefit_bar = AMOUNT * 2 * per_share / PER_SHARE_PRECISION; let post_tax_bar = benefit_bar * 2 / 3; // Using 1/3 tax to test rounding. - assert_eq!(Asset::balance_of(¤cy, bar.did), post_tax_bar); + assert_eq!( + BalanceOf::::get(¤cy, bar.did), + post_tax_bar + ); assert_rem(benefit_foo + benefit_bar); // Owner should have some free currency balance due to withheld taxes. @@ -2202,7 +2208,7 @@ fn dist_claim_rounding_indivisible() { amount - removed ) }; - let balance = |u: User| Asset::balance_of(¤cy, u.did); + let balance = |u: User| BalanceOf::::get(¤cy, u.did); // `foo` claims. 3 / 2 units are rounded down to 1. assert_ok!(Dist::claim(foo.origin(), id)); @@ -2296,10 +2302,10 @@ fn dist_claim_cp_test(mk_ca: impl FnOnce(AssetId, User) -> CAId) { // Check the balances; tax is 0%. assert_eq!( - Asset::balance_of(¤cy, claimant.did), + BalanceOf::::get(¤cy, claimant.did), AMOUNT * per_share / PER_SHARE_PRECISION ); - assert_eq!(Asset::balance_of(¤cy, other.did), 0); + assert_eq!(BalanceOf::::get(¤cy, other.did), 0); }); } diff --git a/pallets/runtime/tests/src/portfolio.rs b/pallets/runtime/tests/src/portfolio.rs index 219e55c5db..9eacbf6acb 100644 --- a/pallets/runtime/tests/src/portfolio.rs +++ b/pallets/runtime/tests/src/portfolio.rs @@ -4,7 +4,7 @@ use sp_keyring::AccountKeyring; use pallet_nft::NFTOwner; use pallet_portfolio::{ AllowedCustodians, Event, NameToNumber, PortfolioAssetBalances, PortfolioCustodian, - PortfolioNFT, Portfolios, PreApprovedPortfolios, + PortfolioLockedAssets, PortfolioNFT, Portfolios, PortfoliosInCustody, PreApprovedPortfolios, }; use pallet_settlement::VenueCounter; use polymesh_primitives::asset::{AssetId, AssetType, NonFungibleType}; @@ -37,7 +37,7 @@ fn create_portfolio() -> (User, PortfolioNumber) { let num = Portfolio::next_portfolio_number(&owner.did); assert_eq!(num, PortfolioNumber(1)); assert_ok!(Portfolio::create_portfolio(owner.origin(), name.clone())); - assert_eq!(Portfolio::portfolios(&owner.did, num), Some(name)); + assert_eq!(Portfolios::::get(&owner.did, num), Some(name)); (owner, num) } @@ -57,7 +57,7 @@ fn set_custodian_ok(current_custodian: User, new_custodian: User, portfolio_id: macro_rules! assert_owner_is_custodian { ($p:expr) => {{ - assert_eq!(Portfolio::portfolios_in_custody($p.did, $p), false); + assert_eq!(PortfoliosInCustody::::get($p.did, $p), false); assert_eq!( pallet_portfolio::PortfolioCustodian::::contains_key(&$p), false @@ -101,8 +101,8 @@ fn can_create_rename_delete_portfolio() { ExtBuilder::default().build().execute_with(|| { let (owner, num) = create_portfolio(); - let name = || Portfolio::portfolios(owner.did, num).unwrap(); - let num_of = |name| Portfolio::name_to_number(owner.did, name); + let name = || Portfolios::::get(owner.did, num).unwrap(); + let num_of = |name| NameToNumber::::get(owner.did, name); let first_name = name(); assert_eq!(num_of(&first_name), Some(num)); @@ -128,8 +128,8 @@ fn can_delete_recreate_portfolio() { ExtBuilder::default().build().execute_with(|| { let (owner, num) = create_portfolio(); - let name = || Portfolio::portfolios(owner.did, num).unwrap(); - let num_of = |name| Portfolio::name_to_number(owner.did, name); + let name = || Portfolios::::get(owner.did, num).unwrap(); + let num_of = |name| NameToNumber::::get(owner.did, name); let first_name = name(); assert_eq!(num_of(&first_name), Some(num)); @@ -379,7 +379,7 @@ fn can_lock_unlock_assets() { ISSUE_AMOUNT, ); assert_eq!( - Portfolio::locked_assets(owner_default_portfolio, &asset_id), + PortfolioLockedAssets::::get(owner_default_portfolio, &asset_id), lock_amount, ); @@ -421,7 +421,7 @@ fn can_lock_unlock_assets() { lock_amount, ); assert_eq!( - Portfolio::locked_assets(owner_default_portfolio, &asset_id), + PortfolioLockedAssets::::get(owner_default_portfolio, &asset_id), lock_amount, ); @@ -458,7 +458,7 @@ fn can_lock_unlock_assets() { lock_amount, ); assert_eq!( - Portfolio::locked_assets(owner_default_portfolio, &asset_id), + PortfolioLockedAssets::::get(owner_default_portfolio, &asset_id), 0, ); @@ -484,7 +484,7 @@ fn can_lock_unlock_assets() { ISSUE_AMOUNT, ); assert_eq!( - Portfolio::locked_assets(owner_default_portfolio, &asset_id), + PortfolioLockedAssets::::get(owner_default_portfolio, &asset_id), 0, ); }); @@ -499,7 +499,8 @@ fn can_take_custody_of_portfolios() { let owner_default_portfolio = PortfolioId::default_portfolio(owner.did); let owner_user_portfolio = PortfolioId::user_portfolio(owner.did, num); - let has_custody = |u: User| Portfolio::portfolios_in_custody(u.did, owner_user_portfolio); + let has_custody = + |u: User| PortfoliosInCustody::::get(u.did, owner_user_portfolio); // Custody of all portfolios is with the owner identity by default assert_ok!(Portfolio::ensure_portfolio_custody( @@ -511,10 +512,13 @@ fn can_take_custody_of_portfolios() { owner.did )); assert_eq!( - Portfolio::portfolio_custodian(owner_default_portfolio), + PortfolioCustodian::::get(owner_default_portfolio), + None + ); + assert_eq!( + PortfolioCustodian::::get(owner_user_portfolio), None ); - assert_eq!(Portfolio::portfolio_custodian(owner_user_portfolio), None); assert!(!has_custody(bob)); // Bob can not issue authorization for custody transfer of a portfolio they don't have custody of @@ -552,11 +556,11 @@ fn can_take_custody_of_portfolios() { Error::UnauthorizedCustodian ); assert_eq!( - Portfolio::portfolio_custodian(owner_default_portfolio), + PortfolioCustodian::::get(owner_default_portfolio), None ); assert_eq!( - Portfolio::portfolio_custodian(owner_user_portfolio), + PortfolioCustodian::::get(owner_user_portfolio), Some(bob.did) ); assert!(has_custody(bob)); diff --git a/pallets/runtime/tests/src/settlement_test.rs b/pallets/runtime/tests/src/settlement_test.rs index 8f3bf5fafd..e9ead58e03 100644 --- a/pallets/runtime/tests/src/settlement_test.rs +++ b/pallets/runtime/tests/src/settlement_test.rs @@ -14,7 +14,7 @@ use sp_std::collections::btree_set::BTreeSet; use pallet_asset::BalanceOf; use pallet_nft::NumberOfNFTs; -use pallet_portfolio::{PortfolioLockedNFT, PortfolioNFT}; +use pallet_portfolio::{PortfolioLockedAssets, PortfolioLockedNFT, PortfolioNFT}; use pallet_scheduler as scheduler; use pallet_settlement::{ AffirmsReceived, Details, Event, InstructionAffirmsPending, InstructionCounter, @@ -95,7 +95,7 @@ impl UserWithBalance { Self { init_balances: assets .iter() - .map(|asset_id| (*asset_id, Asset::balance_of(asset_id, user.did))) + .map(|asset_id| (*asset_id, BalanceOf::::get(asset_id, user.did))) .collect(), user, } @@ -103,7 +103,7 @@ impl UserWithBalance { fn refresh_init_balances(&mut self) { for (asset_id, balance) in &mut self.init_balances { - *balance = Asset::balance_of(asset_id, self.user.did); + *balance = BalanceOf::::get(asset_id, self.user.did); } } @@ -904,7 +904,7 @@ fn venue_filtering() { assert_affirm_instruction!(bob.origin(), instruction_id.checked_inc().unwrap(), bob.did); next_block(); - assert_eq!(Asset::balance_of(&asset_id, bob.did), 10); + assert_eq!(BalanceOf::::get(&asset_id, bob.did), 10); assert_ok!(Settlement::disallow_venues( alice.origin(), asset_id, @@ -1044,14 +1044,17 @@ fn basic_fuzzing() { ) { for ((did, asset_id), balance) in locked_assets { assert_eq!( - Portfolio::locked_assets(PortfolioId::default_portfolio(*did), asset_id), + PortfolioLockedAssets::::get( + PortfolioId::default_portfolio(*did), + asset_id + ), *balance as u128 ); } for asset_id in assets { for user in users { assert_eq!( - Portfolio::locked_assets( + PortfolioLockedAssets::::get( PortfolioId::default_portfolio(user.did), &asset_id ), @@ -1092,7 +1095,7 @@ fn basic_fuzzing() { for user in &users { if fail { assert_eq!( - Asset::balance_of(&asset_id, user.did), + BalanceOf::::get(&asset_id, user.did), u128::try_from( *balances .get(&(asset_id, user.did, "init").encode()) @@ -1101,7 +1104,7 @@ fn basic_fuzzing() { .unwrap() ); assert_eq!( - Portfolio::locked_assets( + PortfolioLockedAssets::::get( PortfolioId::default_portfolio(user.did), &asset_id ), @@ -1112,7 +1115,7 @@ fn basic_fuzzing() { ); } else { assert_eq!( - Asset::balance_of(&asset_id, user.did), + BalanceOf::::get(&asset_id, user.did), u128::try_from( *balances .get(&(asset_id, user.did, "final").encode()) @@ -1121,7 +1124,7 @@ fn basic_fuzzing() { .unwrap() ); assert_eq!( - Portfolio::locked_assets( + PortfolioLockedAssets::::get( PortfolioId::default_portfolio(user.did), &asset_id ), @@ -1146,7 +1149,10 @@ fn basic_fuzzing() { for asset_id in &assets { for user in &users { assert_eq!( - Portfolio::locked_assets(PortfolioId::default_portfolio(user.did), asset_id), + PortfolioLockedAssets::::get( + PortfolioId::default_portfolio(user.did), + asset_id + ), 0 ); } @@ -1637,7 +1643,10 @@ fn multiple_portfolio_settlement() { bob.assert_portfolio_bal(bob_num, 0, &asset_id); assert_locked_assets(&asset_id, &alice, amount); assert_eq!( - Portfolio::locked_assets(PortfolioId::user_portfolio(alice.did, alice_num), &asset_id), + PortfolioLockedAssets::::get( + PortfolioId::user_portfolio(alice.did, alice_num), + &asset_id + ), amount ); @@ -1762,7 +1771,10 @@ fn multiple_custodian_settlement() { bob.assert_portfolio_bal(bob_num, 0, &asset_id); assert_locked_assets(&asset_id, &alice, amount); assert_eq!( - Portfolio::locked_assets(PortfolioId::user_portfolio(alice.did, alice_num), &asset_id), + PortfolioLockedAssets::::get( + PortfolioId::user_portfolio(alice.did, alice_num), + &asset_id + ), amount ); @@ -4303,7 +4315,7 @@ fn assert_instruction_status( #[track_caller] fn assert_balance(asset_id: &AssetId, user: &User, balance: Balance) { - assert_eq!(Asset::balance_of(asset_id, user.did), balance); + assert_eq!(BalanceOf::::get(asset_id, user.did), balance); } #[track_caller] @@ -4350,7 +4362,10 @@ fn assert_affirms_pending(instruction_id: InstructionId, pending: u64) { #[track_caller] fn assert_locked_assets(asset_id: &AssetId, user: &User, num_of_assets: Balance) { assert_eq!( - Portfolio::locked_assets(PortfolioId::default_portfolio(user.did), asset_id), + PortfolioLockedAssets::::get( + PortfolioId::default_portfolio(user.did), + asset_id + ), num_of_assets ); } diff --git a/pallets/runtime/tests/src/sto_test.rs b/pallets/runtime/tests/src/sto_test.rs index 2d89c42acb..fc362d686d 100644 --- a/pallets/runtime/tests/src/sto_test.rs +++ b/pallets/runtime/tests/src/sto_test.rs @@ -2,6 +2,7 @@ use frame_support::{assert_noop, assert_ok}; use sp_keyring::AccountKeyring; use sp_runtime::DispatchError; +use pallet_asset::BalanceOf; use pallet_settlement::{InstructionCounter, InstructionStatuses, VenueCounter}; use pallet_sto::{ Fundraiser, FundraiserCount, FundraiserId, FundraiserName, FundraiserNames, FundraiserStatus, @@ -134,10 +135,10 @@ fn raise_happy_path() { )); let amount = 100u128; - let alice_init_offering = Asset::balance_of(&offering_asset, alice.did); - let bob_init_offering = Asset::balance_of(&offering_asset, bob.did); - let alice_init_raise = Asset::balance_of(&raise_asset, alice.did); - let bob_init_raise = Asset::balance_of(&raise_asset, bob.did); + let alice_init_offering = BalanceOf::::get(&offering_asset, alice.did); + let bob_init_offering = BalanceOf::::get(&offering_asset, bob.did); + let alice_init_raise = BalanceOf::::get(&raise_asset, alice.did); + let bob_init_raise = BalanceOf::::get(&raise_asset, bob.did); // Alice starts a fundraiser let fundraiser_id = FundraiserCount::::get(offering_asset); @@ -185,15 +186,21 @@ fn raise_happy_path() { check_fundraiser(1_000_000u128); assert_eq!( - Asset::balance_of(&offering_asset, alice.did), + BalanceOf::::get(&offering_asset, alice.did), alice_init_offering ); assert_eq!( - Asset::balance_of(&offering_asset, bob.did), + BalanceOf::::get(&offering_asset, bob.did), bob_init_offering ); - assert_eq!(Asset::balance_of(&raise_asset, alice.did), alice_init_raise); - assert_eq!(Asset::balance_of(&raise_asset, bob.did), bob_init_raise); + assert_eq!( + BalanceOf::::get(&raise_asset, alice.did), + alice_init_raise + ); + assert_eq!( + BalanceOf::::get(&raise_asset, bob.did), + bob_init_raise + ); assert_eq!( FundraiserNames::::get(offering_asset, fundraiser_id), Some(fundraiser_name) @@ -245,19 +252,19 @@ fn raise_happy_path() { ); assert_eq!( - Asset::balance_of(&offering_asset, alice.did), + BalanceOf::::get(&offering_asset, alice.did), alice_init_offering - amount ); assert_eq!( - Asset::balance_of(&offering_asset, bob.did), + BalanceOf::::get(&offering_asset, bob.did), bob_init_offering + amount ); assert_eq!( - Asset::balance_of(&raise_asset, alice.did), + BalanceOf::::get(&raise_asset, alice.did), alice_init_raise + amount ); assert_eq!( - Asset::balance_of(&raise_asset, bob.did), + BalanceOf::::get(&raise_asset, bob.did), bob_init_raise - amount ); } diff --git a/pallets/runtime/tests/src/utility_test.rs b/pallets/runtime/tests/src/utility_test.rs index 31b137d4b9..d901df6b0f 100644 --- a/pallets/runtime/tests/src/utility_test.rs +++ b/pallets/runtime/tests/src/utility_test.rs @@ -14,7 +14,7 @@ use pallet_timestamp::Call as TimestampCall; use pallet_asset::UniqueTickerRegistration; use pallet_balances::Call as BalancesCall; use pallet_pips::{PipIdSequence, ProposalState, SnapshotResult}; -use pallet_portfolio::Call as PortfolioCall; +use pallet_portfolio::{Call as PortfolioCall, Portfolios}; use pallet_utility::{ self as utility, Call as UtilityCall, Config as UtilityConfig, Event, Nonces, UniqueCall, WeightInfo, @@ -323,7 +323,7 @@ fn batch_secondary_with_permissions() { let bob = User::new_with(alice.did, AccountKeyring::Bob); let check_name = |name| { assert_eq!( - Portfolio::portfolios(&alice.did, &PortfolioNumber(1)), + Portfolios::::get(&alice.did, &PortfolioNumber(1)), Some(name) ); }; diff --git a/pallets/sto/src/benchmarking.rs b/pallets/sto/src/benchmarking.rs index b7b404c012..a540067605 100644 --- a/pallets/sto/src/benchmarking.rs +++ b/pallets/sto/src/benchmarking.rs @@ -3,6 +3,7 @@ use frame_support::dispatch::DispatchError; use scale_info::prelude::format; use pallet_asset::benchmarking::setup_asset_transfer; +use pallet_asset::BalanceOf; use pallet_identity::benchmarking::{User, UserBuilder}; use pallet_settlement::VenueCounter; use polymesh_primitives::settlement::VenueDetails; @@ -167,7 +168,7 @@ benchmarks! { None ) verify { - assert!(>::balance_of(&setup_portfolios.offering_asset_id, bob.did()) > 0u32.into(), "invest"); + assert!(BalanceOf::::get(&setup_portfolios.offering_asset_id, bob.did()) > 0u32.into(), "invest"); } freeze_fundraiser { From 72891ebd379a52e2d83ac3d17d4d6fa5262fe3c1 Mon Sep 17 00:00:00 2001 From: Henrique Nogara Date: Mon, 10 Feb 2025 15:03:22 -0300 Subject: [PATCH 3/3] Remove getters - part 3 --- pallets/asset/src/benchmarking.rs | 3 +- pallets/asset/src/checkpoint/benchmarking.rs | 12 +- pallets/asset/src/checkpoint/mod.rs | 36 ++---- pallets/committee/src/benchmarking.rs | 12 +- pallets/committee/src/lib.rs | 34 ++--- pallets/corporate-actions/src/lib.rs | 5 +- pallets/group/src/lib.rs | 7 +- pallets/portfolio/src/lib.rs | 1 - pallets/runtime/tests/src/asset_test.rs | 65 ++++++---- pallets/runtime/tests/src/committee_test.rs | 119 +++++++++++++----- .../tests/src/corporate_actions_test.rs | 22 ++-- pallets/runtime/tests/src/portfolio.rs | 13 +- pallets/runtime/tests/src/settlement_test.rs | 14 ++- 13 files changed, 199 insertions(+), 144 deletions(-) diff --git a/pallets/asset/src/benchmarking.rs b/pallets/asset/src/benchmarking.rs index 4f2fe01c6c..071822ed21 100644 --- a/pallets/asset/src/benchmarking.rs +++ b/pallets/asset/src/benchmarking.rs @@ -20,6 +20,7 @@ use sp_std::collections::btree_set::BTreeSet; use sp_std::{convert::TryInto, iter, prelude::*}; use pallet_identity::benchmarking::{user, User, UserBuilder}; +use pallet_portfolio::NextPortfolioNumber; use pallet_statistics::benchmarking::setup_transfer_restrictions; use polymesh_primitives::agent::AgentGroup; use polymesh_primitives::asset::{AssetName, NonFungibleType}; @@ -198,7 +199,7 @@ pub fn setup_asset_transfer( /// Creates a user portfolio for `user`. pub fn create_portfolio(user: &User, portofolio_name: &str) -> PortfolioId { - let portfolio_number = Portfolio::::next_portfolio_number(user.did()).0; + let portfolio_number = NextPortfolioNumber::::get(user.did()).0; Portfolio::::create_portfolio( user.origin().clone().into(), diff --git a/pallets/asset/src/checkpoint/benchmarking.rs b/pallets/asset/src/checkpoint/benchmarking.rs index 2c90f26bb2..a11e740afa 100644 --- a/pallets/asset/src/checkpoint/benchmarking.rs +++ b/pallets/asset/src/checkpoint/benchmarking.rs @@ -39,7 +39,7 @@ fn init_with_existing(asset_owner: &User, existing: u64) -> AssetI benchmarks! { set_schedules_max_complexity {}: _(RawOrigin::Root, 7) verify { - assert_eq!(Pallet::::schedules_max_complexity(), 7) + assert_eq!(SchedulesMaxComplexity::::get(), 7) } create_checkpoint { @@ -48,14 +48,14 @@ benchmarks! { let asset_id = create_sample_asset::(&alice, true); }: _(alice.origin, asset_id) verify { - assert_eq!(Pallet::::checkpoint_id_sequence(asset_id), CheckpointId(1)) + assert_eq!(CheckpointIdSequence::::get(asset_id), CheckpointId(1)) } create_schedule { >::set(1000u32.into()); let alice = UserBuilder::::default().generate_did().build("Alice"); - let max = Pallet::::schedules_max_complexity(); + let max = SchedulesMaxComplexity::::get(); let schedule = ScheduleCheckpoints::new_checkpoints( (0..max).into_iter().map(|n| CP_BASE + n).collect() ); @@ -69,17 +69,17 @@ benchmarks! { let asset_id = init_with_existing::(&alice, max); }: _(alice.origin, asset_id, schedule) verify { - assert_eq!(Pallet::::schedule_id_sequence(asset_id), ScheduleId(max + 1)) + assert_eq!(ScheduleIdSequence::::get(asset_id), ScheduleId(max + 1)) } remove_schedule { let alice = UserBuilder::::default().generate_did().build("Alice"); - let max = Pallet::::schedules_max_complexity(); + let max = SchedulesMaxComplexity::::get(); let id = ScheduleId(max); let asset_id = init_with_existing::(&alice, max); }: _(alice.origin, asset_id, id) verify { - assert_eq!(Pallet::::scheduled_checkpoints(asset_id, id), None); + assert_eq!(ScheduledCheckpoints::::get(asset_id, id), None); } } diff --git a/pallets/asset/src/checkpoint/mod.rs b/pallets/asset/src/checkpoint/mod.rs index 4d3842eef9..1aa398a6cf 100644 --- a/pallets/asset/src/checkpoint/mod.rs +++ b/pallets/asset/src/checkpoint/mod.rs @@ -124,8 +124,7 @@ pub mod pallet { /// /// ([`AssetId`], checkpointId) -> total supply at given checkpoint #[pallet::storage] - #[pallet::getter(fn total_supply_at)] - pub(super) type TotalSupply = StorageDoubleMap< + pub type TotalSupply = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -139,8 +138,7 @@ pub mod pallet { /// /// ([`AssetId`], did, checkpoint ID) -> Balance of a DID at a checkpoint #[pallet::storage] - #[pallet::getter(fn balance_at_checkpoint)] - pub(super) type Balance = StorageDoubleMap< + pub type Balance = StorageDoubleMap< _, Blake2_128Concat, (AssetId, CheckpointId), @@ -157,16 +155,14 @@ pub mod pallet { /// /// ([`AssetId`]) -> no. of checkpoints #[pallet::storage] - #[pallet::getter(fn checkpoint_id_sequence)] - pub(super) type CheckpointIdSequence = + pub type CheckpointIdSequence = StorageMap<_, Blake2_128Concat, AssetId, CheckpointId, ValueQuery>; /// Checkpoints where a DID's balance was updated. /// ([`AssetId`], did) -> [checkpoint ID where user balance changed] #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn balance_updates)] - pub(super) type BalanceUpdates = StorageDoubleMap< + pub type BalanceUpdates = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -183,8 +179,7 @@ pub mod pallet { /// /// ([`AssetId`]) -> (checkpoint ID) -> checkpoint timestamp #[pallet::storage] - #[pallet::getter(fn timestamps)] - pub(super) type Timestamps = StorageDoubleMap< + pub type Timestamps = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -198,15 +193,13 @@ pub mod pallet { /// The maximum complexity allowed for an asset's schedules. #[pallet::storage] - #[pallet::getter(fn schedules_max_complexity)] - pub(super) type SchedulesMaxComplexity = StorageValue<_, u64, ValueQuery>; + pub type SchedulesMaxComplexity = StorageValue<_, u64, ValueQuery>; /// Checkpoint schedule ID sequence for assets. /// /// ([`AssetId`]) -> schedule ID #[pallet::storage] - #[pallet::getter(fn schedule_id_sequence)] - pub(super) type ScheduleIdSequence = + pub type ScheduleIdSequence = StorageMap<_, Blake2_128Concat, AssetId, ScheduleId, ValueQuery>; /// Cached next checkpoint for each schedule. @@ -216,8 +209,7 @@ pub mod pallet { /// ([`AssetId`]) -> next checkpoints #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn cached_next_checkpoints)] - pub(super) type CachedNextCheckpoints = + pub type CachedNextCheckpoints = StorageMap<_, Blake2_128Concat, AssetId, NextCheckpoints, OptionQuery>; /// Scheduled checkpoints. @@ -225,8 +217,7 @@ pub mod pallet { /// ([`AssetId`], schedule ID) -> schedule checkpoints #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn scheduled_checkpoints)] - pub(super) type ScheduledCheckpoints = StorageDoubleMap< + pub type ScheduledCheckpoints = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -245,8 +236,7 @@ pub mod pallet { /// /// ([`AssetId`], schedule ID) -> strong ref count #[pallet::storage] - #[pallet::getter(fn schedule_ref_count)] - pub(super) type ScheduleRefCount = + pub type ScheduleRefCount = StorageDoubleMap<_, Blake2_128Concat, AssetId, Twox64Concat, ScheduleId, u32, ValueQuery>; /// All the checkpoints a given schedule originated. @@ -254,8 +244,7 @@ pub mod pallet { /// ([`AssetId`], schedule ID) -> [checkpoint ID] #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn schedule_points)] - pub(super) type SchedulePoints = StorageDoubleMap< + pub type SchedulePoints = StorageDoubleMap< _, Blake2_128Concat, AssetId, @@ -267,7 +256,6 @@ pub mod pallet { /// Storage version. #[pallet::storage] - #[pallet::getter(fn storage_version)] pub(super) type StorageVersion = StorageValue<_, Version, ValueQuery>; #[pallet::genesis_config] @@ -429,7 +417,7 @@ impl Pallet { // Use first checkpoint created after target checkpoint. // The user has data for that checkpoint. let id = *find_ceiling(&balance_updates, &cp); - return Some(Self::balance_at_checkpoint((asset_id, id), did)); + return Some(Balance::::get((asset_id, id), did)); } // User has not transacted after checkpoint creation. // This means their current balance = their balance at that cp. diff --git a/pallets/committee/src/benchmarking.rs b/pallets/committee/src/benchmarking.rs index 45e4ddb4f3..12bae2468d 100644 --- a/pallets/committee/src/benchmarking.rs +++ b/pallets/committee/src/benchmarking.rs @@ -59,17 +59,17 @@ where ); // Leave space for one additional proposal to be created for i in 0..(PROPOSALS_MAX - 1) { - let index = Pallet::::proposal_count(); + let index = ProposalCount::::get(); let proposal = make_proposal::(i).0; Pallet::::vote_or_propose(users[0].origin.clone().into(), true, Box::new(proposal)) .unwrap(); if users.len() > 1 { - let hash = *Pallet::::proposals().last().unwrap(); + let hash = *Proposals::::get().last().unwrap(); // cast min(user.len(), N) - 1 additional votes for proposal #N // alternating nay, aye, nay, aye... for (j, user) in users.iter().skip(1).take(i as usize).enumerate() { // Vote for the proposal if it's not finalised. - if Pallet::::voting(&hash).is_some() { + if Voting::::get(&hash).is_some() { Pallet::::vote(user.origin.clone().into(), hash, index, j % 2 != 0) .unwrap(); } @@ -137,7 +137,7 @@ benchmarks_instance_pallet! { call.dispatch_bypass_filter(origin).unwrap(); } verify { - assert_eq!(Pallet::::vote_threshold(), (n, d), "incorrect vote threshold"); + assert_eq!(VoteThreshold::::get(), (n, d), "incorrect vote threshold"); } set_release_coordinator { @@ -167,7 +167,7 @@ benchmarks_instance_pallet! { call.dispatch_bypass_filter(origin).unwrap(); } verify { - assert_eq!(Pallet::::expires_after(), maybe_block, "incorrect expiration"); + assert_eq!(ExpiresAfter::::get(), maybe_block, "incorrect expiration"); } vote_or_propose_new_proposal { @@ -193,7 +193,7 @@ benchmarks_instance_pallet! { if COMMITTEE_MEMBERS_MAX <= 4 { // Proposal was executed. assert!( - Pallet::::voting(&hash).is_none(), + Voting::::get(&hash).is_none(), "votes are present on an executed existing proposal" ); } else { diff --git a/pallets/committee/src/lib.rs b/pallets/committee/src/lib.rs index 7450f3efd5..fd56299bec 100644 --- a/pallets/committee/src/lib.rs +++ b/pallets/committee/src/lib.rs @@ -171,49 +171,41 @@ pub mod pallet { /// The hashes of the active proposals. #[pallet::storage] - #[pallet::getter(fn proposals)] #[pallet::unbounded] pub type Proposals, I: 'static = ()> = StorageValue<_, Vec, ValueQuery>; /// Actual proposal for a given hash. #[pallet::storage] - #[pallet::getter(fn proposal_of)] #[pallet::unbounded] pub type ProposalOf, I: 'static = ()> = StorageMap<_, Identity, T::Hash, >::Proposal, OptionQuery>; /// PolymeshVotes on a given proposal, if it is ongoing. #[pallet::storage] - #[pallet::getter(fn voting)] #[pallet::unbounded] pub type Voting, I: 'static = ()> = StorageMap<_, Identity, T::Hash, PolymeshVotes, OptionQuery>; /// Proposals so far. #[pallet::storage] - #[pallet::getter(fn proposal_count)] pub type ProposalCount, I: 'static = ()> = StorageValue<_, u32, ValueQuery>; /// The current members of the committee. #[pallet::storage] - #[pallet::getter(fn members)] #[pallet::unbounded] pub type Members, I: 'static = ()> = StorageValue<_, Vec, ValueQuery>; /// Vote threshold for an approval. #[pallet::storage] - #[pallet::getter(fn vote_threshold)] pub type VoteThreshold, I: 'static = ()> = StorageValue<_, (u32, u32), ValueQuery>; /// Release cooridinator. #[pallet::storage] - #[pallet::getter(fn release_coordinator)] pub type ReleaseCoordinator, I: 'static = ()> = StorageValue<_, IdentityId, OptionQuery>; /// Time after which a proposal will expire. #[pallet::storage] - #[pallet::getter(fn expires_after)] pub type ExpiresAfter, I: 'static = ()> = StorageValue<_, MaybeBlock, ValueQuery>; @@ -427,7 +419,7 @@ pub mod pallet { ) -> DispatchResult { // Either create a new proposal or vote on an existing one. let hash = T::Hashing::hash_of(&call); - match Self::voting(hash) { + match Voting::::get(hash) { Some(voting) => Self::vote(origin, hash, voting.index, approve), // NOTE: boxing is necessary or the trait system will throw a fit. None if approve => Self::propose(origin, *call), @@ -498,7 +490,7 @@ pub mod pallet { hash: &T::Hash, idx: ProposalIndex, ) -> Result, DispatchError> { - let voting = Self::voting(&hash).ok_or(Error::::NoSuchProposal)?; + let voting = Voting::::get(&hash).ok_or(Error::::NoSuchProposal)?; ensure!(voting.index == idx, Error::::MismatchedVotingIndex); Ok(voting) } @@ -513,14 +505,14 @@ pub mod pallet { /// Returns true if `who` is contained in the set of committee members, and `false` otherwise. pub fn ensure_did_is_member(who: &IdentityId) -> DispatchResult { ensure!( - Self::members().binary_search(who).is_ok(), + Members::::get().binary_search(who).is_ok(), Error::::NotAMember ); Ok(()) } fn seats() -> MemberCount { - Self::members().len() as _ + Members::::get().len() as _ } /// Given `votes` number of votes out of `total` votes, this function compares`votes`/`total` @@ -534,7 +526,7 @@ pub mod pallet { /// # Return /// It returns true if vote was removed. pub(crate) fn remove_vote_from(id: IdentityId, proposal: T::Hash) -> bool { - if let Some(mut voting) = Self::voting(&proposal) { + if let Some(mut voting) = Voting::::get(&proposal) { // If any element is removed, we have to update `voting`. let idx = voting.index; let remove = |from: &mut Vec<_>, sig| { @@ -553,7 +545,7 @@ pub mod pallet { /// Accepts or rejects the proposal if its threshold is satisfied. pub(crate) fn execute_if_passed(did: Option, proposal: T::Hash) { - let voting = match Self::voting(&proposal) { + let voting = match Voting::::get(&proposal) { // Make sure we don't have an expired proposal at this point. Some(v) if Self::ensure_not_expired(&proposal, v.expiry).is_ok() => v, _ => return, @@ -659,7 +651,7 @@ pub mod pallet { // 1.1 Ensure proposal limit has not been reached. ensure!( - Self::proposal_count() < PROPOSALS_MAX, + ProposalCount::::get() < PROPOSALS_MAX, Error::::ProposalsLimitReached ); @@ -682,7 +674,7 @@ pub mod pallet { index, ayes: vec![did], nays: vec![], - expiry: Self::expires_after() + now, + expiry: ExpiresAfter::::get() + now, }; >::insert(proposal_hash, votes); @@ -697,7 +689,7 @@ pub mod pallet { impl, I: 'static> GroupTrait for Pallet { /// Retrieve all members of this committee fn get_members() -> Vec { - Self::members() + Members::::get() } fn get_inactive_members() -> Vec> { @@ -719,12 +711,12 @@ impl, I: 'static> GroupTrait for Pallet { impl, I: 'static> GovernanceGroupTrait for Pallet { fn release_coordinator() -> Option { - Self::release_coordinator() + ReleaseCoordinator::::get() } #[cfg(feature = "runtime-benchmarks")] fn bench_set_release_coordinator(id: IdentityId) { - if !Self::members().contains(&id) { + if !Members::::get().contains(&id) { Self::change_members_sorted(&[id], &[], &[id]); } >::put(id); @@ -743,7 +735,7 @@ impl, I: 'static> ChangeMembers for Pallet { >::put(new); // Remove accounts from all current voting in motions. - Self::proposals() + Proposals::::get() .into_iter() .filter(|proposal| { outgoing @@ -753,7 +745,7 @@ impl, I: 'static> ChangeMembers for Pallet { .for_each(|proposal| Self::execute_if_passed(None, proposal)); // Double check if any `outgoing` is the Release coordinator. - if let Some(curr_rc) = Self::release_coordinator() { + if let Some(curr_rc) = ReleaseCoordinator::::get() { if outgoing.contains(&curr_rc) { >::kill(); Self::deposit_event(Event::ReleaseCoordinatorUpdated(None)); diff --git a/pallets/corporate-actions/src/lib.rs b/pallets/corporate-actions/src/lib.rs index 9d5a72d8e5..dff33b2247 100644 --- a/pallets/corporate-actions/src/lib.rs +++ b/pallets/corporate-actions/src/lib.rs @@ -101,6 +101,7 @@ use frame_support::{ weights::Weight, }; use frame_system::ensure_root; +use pallet_asset::checkpoint::{SchedulePoints, Timestamps}; use pallet_asset::{checkpoint, BalanceOf}; use pallet_base::try_next_post; use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData}; @@ -1117,7 +1118,7 @@ impl Pallet { // since you may attach a pre-existing and recurring schedule to it. // However, the record date stores the index for the CP, // assuming a transfer has happened since the record date. - CACheckpoint::Scheduled(id, idx) => Ok(>::schedule_points(asset_id, id) + CACheckpoint::Scheduled(id, idx) => Ok(SchedulePoints::::get(asset_id, id) .get(idx as usize) .copied()), } @@ -1174,7 +1175,7 @@ impl Pallet { Error::::NoSuchCheckpointId ); ( - >::timestamps(asset_id, id), + Timestamps::::get(asset_id, id), CACheckpoint::Existing(id), ) } diff --git a/pallets/group/src/lib.rs b/pallets/group/src/lib.rs index 7215e6d56d..838343ddb1 100644 --- a/pallets/group/src/lib.rs +++ b/pallets/group/src/lib.rs @@ -197,7 +197,6 @@ pub mod pallet { /// Limit of how many "active" members there can be. #[pallet::storage] - #[pallet::getter(fn active_members_limit)] pub type ActiveMembersLimit, I: 'static = ()> = StorageValue<_, u32, ValueQuery>; #[pallet::genesis_config] @@ -442,7 +441,7 @@ impl, I: 'static> Pallet { /// Ensure that updating the active set to `members` will not exceed the set limit. fn ensure_within_active_members_limit(members: &[IdentityId]) -> DispatchResult { ensure!( - members.len() as MemberCount <= Self::active_members_limit(), + members.len() as MemberCount <= ActiveMembersLimit::::get(), Error::::ActiveMembersLimitExceeded ); Ok(()) @@ -510,14 +509,14 @@ impl, I: 'static> GroupTrait for Pallet { /// Returns the "active members". #[inline] fn get_members() -> Vec { - Self::active_members() + ActiveMembers::::get() } /// Returns inactive members who are not expired yet. #[inline] fn get_inactive_members() -> Vec> { let now = >::get(); - Self::inactive_members() + InactiveMembers::::get() .into_iter() .filter(|member| !Self::is_member_expired(member, now)) .collect::>() diff --git a/pallets/portfolio/src/lib.rs b/pallets/portfolio/src/lib.rs index b876a001d8..8d7ae4cec4 100644 --- a/pallets/portfolio/src/lib.rs +++ b/pallets/portfolio/src/lib.rs @@ -215,7 +215,6 @@ pub mod pallet { /// The next portfolio sequence number of an identity. #[pallet::storage] - #[pallet::getter(fn next_portfolio_number)] pub type NextPortfolioNumber = StorageMap<_, Identity, IdentityId, PortfolioNumber, ValueQuery>; diff --git a/pallets/runtime/tests/src/asset_test.rs b/pallets/runtime/tests/src/asset_test.rs index 4878bc3abd..cb952dc04c 100644 --- a/pallets/runtime/tests/src/asset_test.rs +++ b/pallets/runtime/tests/src/asset_test.rs @@ -10,6 +10,10 @@ use sp_std::collections::btree_set::BTreeSet; use sp_std::convert::{From, TryFrom, TryInto}; use sp_std::iter; +use pallet_asset::checkpoint::{ + CachedNextCheckpoints, CheckpointIdSequence, ScheduleIdSequence, SchedulePoints, + ScheduledCheckpoints, Timestamps, TotalSupply, +}; use pallet_asset::{ AssetDetails, AssetDocuments, AssetIdentifiers, AssetMetadataLocalKeyToName, AssetMetadataLocalNameToKey, AssetMetadataLocalSpecs, AssetMetadataValues, AssetNames, Assets, @@ -175,7 +179,7 @@ fn exceeded_funding_round_name() -> FundingRoundName { } pub fn next_schedule_id(asset_id: AssetId) -> ScheduleId { - let ScheduleId(id) = Checkpoint::schedule_id_sequence(asset_id); + let ScheduleId(id) = ScheduleIdSequence::::get(asset_id); ScheduleId(id + 1) } @@ -184,16 +188,19 @@ pub fn check_schedules(asset_id: AssetId, schedules: &[(ScheduleId, ScheduleChec let mut cached = NextCheckpoints::default(); for (id, schedule) in schedules { assert_eq!( - Checkpoint::scheduled_checkpoints(asset_id, id).as_ref(), + ScheduledCheckpoints::::get(asset_id, id).as_ref(), Some(schedule) ); cached.add_schedule_next(*id, schedule.next().unwrap()); cached.inc_total_pending(schedule.len() as u64); } if cached.is_empty() { - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); } else { - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), Some(cached)); + assert_eq!( + CachedNextCheckpoints::::get(asset_id), + Some(cached) + ); } } @@ -743,7 +750,7 @@ fn next_checkpoint_is_updated_we() { let asset_id = create_and_issue_sample_asset(&owner); - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); let schedule = ScheduleCheckpoints::from_period(start, period, 5); assert_ok!(Checkpoint::set_schedules_max_complexity( root(), @@ -756,9 +763,9 @@ fn next_checkpoint_is_updated_we() { )); assert_ok!(Checkpoint::advance_update_balances(&asset_id, &[])); let id = CheckpointId(1); - assert_eq!(id, Checkpoint::checkpoint_id_sequence(&asset_id)); - assert_eq!(start, Checkpoint::timestamps(asset_id, id)); - assert_eq!(ISSUE_AMOUNT, Checkpoint::total_supply_at(asset_id, id)); + assert_eq!(id, CheckpointIdSequence::::get(&asset_id)); + assert_eq!(start, Timestamps::::get(asset_id, id)); + assert_eq!(ISSUE_AMOUNT, TotalSupply::::get(asset_id, id)); assert_eq!(ISSUE_AMOUNT, Asset::get_balance_at(asset_id, owner.did, id)); assert_eq!(0, Asset::get_balance_at(asset_id, bob.did, id)); let checkpoint2 = start + period_ms; @@ -781,8 +788,11 @@ fn next_checkpoint_is_updated_we() { // Balances at checkpoint 2. let id = CheckpointId(2); assert_eq!(vec![start + 2 * period_ms], checkpoint_ats(asset_id)); - assert_eq!(id, Checkpoint::checkpoint_id_sequence(&asset_id)); - assert_eq!(start + period_ms, Checkpoint::timestamps(asset_id, id)); + assert_eq!(id, CheckpointIdSequence::::get(&asset_id)); + assert_eq!( + start + period_ms, + Timestamps::::get(asset_id, id) + ); assert_eq!( ISSUE_AMOUNT / 2, Asset::get_balance_at(asset_id, owner.did, id) @@ -809,7 +819,7 @@ fn non_recurring_schedule_works_we() { let asset_id = create_and_issue_sample_asset(&owner); - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); let schedule = ScheduleCheckpoints::from_period(start, period, 10); assert_ok!(Checkpoint::set_schedules_max_complexity( root(), @@ -822,27 +832,28 @@ fn non_recurring_schedule_works_we() { )); assert_ok!(Checkpoint::advance_update_balances(&asset_id, &[])); let id = CheckpointId(1); - assert_eq!(id, Checkpoint::checkpoint_id_sequence(&asset_id)); - assert_eq!(start, Checkpoint::timestamps(asset_id, id)); - assert_eq!(ISSUE_AMOUNT, Checkpoint::total_supply_at(asset_id, id)); + assert_eq!(id, CheckpointIdSequence::::get(&asset_id)); + assert_eq!(start, Timestamps::::get(asset_id, id)); + assert_eq!(ISSUE_AMOUNT, TotalSupply::::get(asset_id, id)); assert_eq!(ISSUE_AMOUNT, Asset::get_balance_at(asset_id, owner.did, id)); assert_eq!(0, Asset::get_balance_at(asset_id, bob.did, id)); // The schedule will not recur. - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); }); } fn checkpoint_ats(asset_id: AssetId) -> Vec { - let cached = Checkpoint::cached_next_checkpoints(asset_id).unwrap_or_default(); + let cached = CachedNextCheckpoints::::get(asset_id).unwrap_or_default(); cached.schedules.values().copied().collect() } fn next_checkpoints(asset_id: AssetId) -> Vec> { - let ScheduleId(id) = Checkpoint::schedule_id_sequence(asset_id); + let ScheduleId(id) = ScheduleIdSequence::::get(asset_id); (1..=id) .into_iter() .map(|id| { - Checkpoint::scheduled_checkpoints(asset_id, ScheduleId(id)).and_then(|s| s.next()) + ScheduledCheckpoints::::get(asset_id, ScheduleId(id)) + .and_then(|s| s.next()) }) .collect() } @@ -863,14 +874,14 @@ fn schedule_remaining_works() { transfer(asset_id, owner, bob, 1).unwrap(); }; let collect_ts = |sh_id| { - Checkpoint::schedule_points(asset_id, sh_id) + SchedulePoints::::get(asset_id, sh_id) .into_iter() - .map(|cp| Checkpoint::timestamps(asset_id, cp)) + .map(|cp| Timestamps::::get(asset_id, cp)) .collect::>() }; // No schedules yet. - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); // For simplicity, we use 1s = 1_000ms periods. let period = CalendarPeriod { @@ -896,7 +907,7 @@ fn schedule_remaining_works() { // We had `remaining == 1` and `start == now`, // so since a CP was created, hence `remaining => 0`, // the schedule was immediately evicted. - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); assert_eq!(collect_ts(ScheduleId(1)), vec![start]); // This time, we set `remaining == 5`, but we still have `start == now`, @@ -914,7 +925,7 @@ fn schedule_remaining_works() { let now = (at - 1) * 1_000; let mut schedule = schedule.clone(); schedule.remove_expired(now); - let chain = Checkpoint::scheduled_checkpoints(asset_id, id2).unwrap_or_default(); + let chain = ScheduledCheckpoints::::get(asset_id, id2).unwrap_or_default(); assert_eq!(chain, schedule); assert_eq!(chain.len(), remaining); }; @@ -937,7 +948,7 @@ fn schedule_remaining_works() { // Transfer and move to the 5th (last) recurrence. // We've to the point where there are no ticks left. transfer(5); - assert_eq!(Checkpoint::cached_next_checkpoints(asset_id), None); + assert_eq!(CachedNextCheckpoints::::get(asset_id), None); assert_ts(5); }); } @@ -956,13 +967,13 @@ fn mesh_1531_ts_collission_regression_test() { set_timestamp(1_000); let create = |asset_id| Checkpoint::create_checkpoint(owner.origin(), asset_id); assert_ok!(create(asset_id)); - assert_eq!(Checkpoint::timestamps(asset_id, cp), 1_000); + assert_eq!(Timestamps::::get(asset_id, cp), 1_000); // Second CP is for beta, using same ID. set_timestamp(2_000); assert_ok!(create(asset_id2)); - assert_eq!(Checkpoint::timestamps(asset_id, cp), 1_000); - assert_eq!(Checkpoint::timestamps(asset_id2, cp), 2_000); + assert_eq!(Timestamps::::get(asset_id, cp), 1_000); + assert_eq!(Timestamps::::get(asset_id2, cp), 2_000); }); } diff --git a/pallets/runtime/tests/src/committee_test.rs b/pallets/runtime/tests/src/committee_test.rs index 7166f4567a..ae75187bd1 100644 --- a/pallets/runtime/tests/src/committee_test.rs +++ b/pallets/runtime/tests/src/committee_test.rs @@ -10,7 +10,10 @@ use frame_support::{ dispatch::{DispatchError, DispatchResult}, }; use frame_system::{EventRecord, Phase}; -use pallet_committee::{self as committee, Event as CommitteeRawEvent, PolymeshVotes}; +use pallet_committee::{ + self as committee, Event as CommitteeRawEvent, Members, PolymeshVotes, Proposals, + ReleaseCoordinator, VoteThreshold, Voting, +}; use pallet_group as group; use pallet_identity as identity; use pallet_pips::{PipId, ProposalState, ProposalStates, SnapshotResult}; @@ -48,8 +51,14 @@ fn motions_basic_environment_works_we() { committee.sort(); System::set_block_number(1); - assert_eq!(Committee::members(), committee); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Members::::get(), + committee + ); + assert_eq!( + Proposals::::get(), + vec![] + ); } fn make_proposal(value: u64) -> RuntimeCall { @@ -66,7 +75,10 @@ pub fn set_members(ids: Vec) { } fn assert_mem_len(len: u32) { - assert_ok!(u32::try_from((Committee::members()).len()), len) + assert_ok!( + u32::try_from((Members::::get()).len()), + len + ) } fn assert_mem(who: IdentityId, is: bool) { @@ -139,7 +151,10 @@ fn single_member_committee_works_we() { // Proposal is executed if committee is comprised of a single member prepare_proposal(alice_ring); assert_ok!(Pips::snapshot(alice_signer.clone())); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_ok!(vote(&alice_signer, true)); check_scheduled(PipId(0)); @@ -175,7 +190,10 @@ fn preventing_motions_from_non_members_works_we() { Pips::snapshot(alice_signer.clone()), pallet_pips::Error::::NotACommitteeMember ); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_noop!( vote(&alice_signer, true), committee::Error::::NotAMember @@ -201,7 +219,10 @@ fn preventing_voting_from_non_members_works_we() { set_members(vec![alice_did]); prepare_proposal(alice_ring); assert_ok!(Pips::snapshot(alice_signer.clone())); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_noop!( vote(&bob_signer, true), committee::Error::::NotAMember @@ -228,12 +249,15 @@ fn motions_revoting_works_we() { set_members(vec![alice_did, bob_did, charlie_did]); prepare_proposal(alice_ring); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_ok!(vote(&alice_signer, true)); let enact_hash = hash_enact_snapshot_results(); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![alice_did], @@ -247,7 +271,7 @@ fn motions_revoting_works_we() { ); assert_ok!(vote(&alice_signer, false)); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![], @@ -278,7 +302,10 @@ fn first_vote_cannot_be_reject_we() { set_members(vec![alice_did, bob_did, charlie_did]); prepare_proposal(alice_ring); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_noop!( vote(&Origin::signed(alice_ring.to_account_id()), false), committee::Error::::FirstVoteReject @@ -305,7 +332,10 @@ fn changing_vote_threshold_works_we() { let bob_did = register_keyring_account(AccountKeyring::Bob).unwrap(); set_members(vec![alice_did, bob_did]); - assert_eq!(Committee::vote_threshold(), (1, 1)); + assert_eq!( + VoteThreshold::::get(), + (1, 1) + ); let call_svt = Box::new(RuntimeCall::PolymeshCommittee( pallet_committee::Call::set_vote_threshold { n: 4, d: 17 }, @@ -321,7 +351,10 @@ fn changing_vote_threshold_works_we() { call_svt.clone() )); - assert_eq!(Committee::vote_threshold(), (4, 17)); + assert_eq!( + VoteThreshold::::get(), + (4, 17) + ); } #[test] @@ -357,13 +390,16 @@ fn rage_quit_we() { // Make a proposal... only Alice & Bob approve it. prepare_proposal(alice_ring); assert_ok!(Pips::snapshot(alice_signer.clone())); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_ok!(vote(&bob_signer, true)); assert_ok!(vote(&charlie_signer, false)); let enact_hash = hash_enact_snapshot_results(); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![bob_did], @@ -375,7 +411,7 @@ fn rage_quit_we() { // Bob quits, its vote should be removed. abdicate_membership(bob_did, &bob_signer, 4); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![], @@ -387,7 +423,7 @@ fn rage_quit_we() { // Charlie quits, its vote should be removed. abdicate_membership(charlie_did, &charlie_signer, 3); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![], @@ -403,7 +439,7 @@ fn rage_quit_we() { committee::Error::::DuplicateVote ); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![], @@ -413,7 +449,7 @@ fn rage_quit_we() { ); assert_ok!(vote(&alice_signer, true)); assert_eq!( - Committee::voting(&enact_hash), + Voting::::get(&enact_hash), Some(PolymeshVotes { index: 0, ayes: vec![alice_did], @@ -426,7 +462,10 @@ fn rage_quit_we() { System::reset_events(); abdicate_membership(charlie_did, &charlie_signer, 3); abdicate_membership(bob_did, &bob_signer, 2); - assert_eq!(Committee::voting(&enact_hash), None); + assert_eq!( + Voting::::get(&enact_hash), + None + ); assert_mem(alice_did, true); assert_noop!( CommitteeGroup::abdicate_membership(alice_signer), @@ -467,7 +506,7 @@ fn release_coordinator_we() { let charlie_id = register_keyring_account(AccountKeyring::Charlie).unwrap(); assert_eq!( - Committee::release_coordinator(), + ReleaseCoordinator::::get(), Some(IdentityId::from(999)) ); @@ -482,14 +521,23 @@ fn release_coordinator_we() { ); assert_ok!(Committee::set_release_coordinator(gc_vmo(), bob_id)); - assert_eq!(Committee::release_coordinator(), Some(bob_id)); + assert_eq!( + ReleaseCoordinator::::get(), + Some(bob_id) + ); // Bob abdicates assert_ok!(CommitteeGroup::abdicate_membership(bob)); - assert_eq!(Committee::release_coordinator(), None); + assert_eq!( + ReleaseCoordinator::::get(), + None + ); assert_ok!(Committee::set_release_coordinator(gc_vmo(), alice_id)); - assert_eq!(Committee::release_coordinator(), Some(alice_id)); + assert_eq!( + ReleaseCoordinator::::get(), + Some(alice_id) + ); } #[test] @@ -512,7 +560,7 @@ fn release_coordinator_majority_we() { let bob_id = get_identity_id(AccountKeyring::Bob).expect("Bob is part of the committee"); assert_eq!( - Committee::release_coordinator(), + ReleaseCoordinator::::get(), Some(IdentityId::from(999)) ); @@ -528,7 +576,7 @@ fn release_coordinator_majority_we() { // No majority yet. assert_eq!( - Committee::release_coordinator(), + ReleaseCoordinator::::get(), Some(IdentityId::from(999)) ); @@ -537,7 +585,10 @@ fn release_coordinator_majority_we() { assert_ok!(Committee::vote(bob, hash, 0, true)); // Now we have a new RC. - assert_eq!(Committee::release_coordinator(), Some(bob_id)); + assert_eq!( + ReleaseCoordinator::::get(), + Some(bob_id) + ); } #[test] @@ -567,7 +618,10 @@ fn enact_we() { // 1. Create the PIP. prepare_proposal(alice); assert_ok!(Pips::snapshot(alice_signer.clone())); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); // 2. Alice and Bob vote to enact that pip, they are 2/3 of committee. assert_ok!(vote(&alice_signer, true)); @@ -593,7 +647,7 @@ fn mesh_1065_regression_test() { let assert_ayes = |ayes| { assert_eq!( - Committee::voting(&hash_enact_snapshot_results()), + Voting::::get(&hash_enact_snapshot_results()), Some(PolymeshVotes { index: 0, ayes, @@ -640,11 +694,14 @@ fn expiry_works() { set_members(vec![alice_did, bob_did, charlie_did]); prepare_proposal(alice_ring); - assert_eq!(Committee::proposals(), vec![]); + assert_eq!( + Proposals::::get(), + vec![] + ); assert_ok!(vote(&alice_signer, true)); assert_eq!( - Committee::voting(&hash_enact_snapshot_results()) + Voting::::get(&hash_enact_snapshot_results()) .unwrap() .expiry, MaybeBlock::Some(System::block_number() + 13), diff --git a/pallets/runtime/tests/src/corporate_actions_test.rs b/pallets/runtime/tests/src/corporate_actions_test.rs index 0185d9f182..7ee005f0d1 100644 --- a/pallets/runtime/tests/src/corporate_actions_test.rs +++ b/pallets/runtime/tests/src/corporate_actions_test.rs @@ -10,6 +10,9 @@ use frame_support::{ assert_noop, assert_ok, dispatch::{DispatchError, DispatchResult}, }; +use pallet_asset::checkpoint::{ + CheckpointIdSequence, ScheduleIdSequence, SchedulePoints, ScheduleRefCount, Timestamps, +}; use pallet_asset::{Assets, BalanceOf}; use pallet_corporate_actions::{ ballot::{ @@ -547,10 +550,10 @@ fn initiate_corporate_action_record_date() { transfer(&asset_id, owner, foo); assert_eq!( - Checkpoint::schedule_points(asset_id, schedule_id), + SchedulePoints::::get(asset_id, schedule_id), vec![cp_id] ); - assert_eq!(date, Checkpoint::timestamps(asset_id, cp_id)); + assert_eq!(date, Timestamps::::get(asset_id, cp_id)); } }; @@ -559,7 +562,7 @@ fn initiate_corporate_action_record_date() { check(Some(100_000)); assert_eq!( - Checkpoint::checkpoint_id_sequence(asset_id), + CheckpointIdSequence::::get(asset_id), CheckpointId(2) ); }); @@ -885,8 +888,9 @@ fn change_record_date_works() { assert_eq!(expect, get_ca(id).unwrap().record_date); }; let assert_refs = - |sh_id, count| assert_eq!(Checkpoint::schedule_ref_count(asset_id, sh_id), count); - let assert_fresh = |sh_id| assert_eq!(Checkpoint::schedule_id_sequence(asset_id), sh_id); + |sh_id, count| assert_eq!(ScheduleRefCount::::get(asset_id, sh_id), count); + let assert_fresh = + |sh_id| assert_eq!(ScheduleIdSequence::::get(asset_id), sh_id); // Change for a CA that doesn't exist, and ensure failure. let id = next_ca_id(asset_id); @@ -929,7 +933,7 @@ fn change_record_date_works() { sh_id }; let sh_id1 = change_ok_scheduled(); - assert_eq!(Checkpoint::schedule_ref_count(asset_id, sh_id1), 1); + assert_eq!(ScheduleRefCount::::get(asset_id, sh_id1), 1); // Then use a distinct existing ID. let sh_id2 = change_ok_scheduled(); @@ -1021,7 +1025,7 @@ fn existing_schedule_ref_count() { let sh_id = next_schedule_id(asset_id); let spec = Some(RecordDateSpec::ExistingSchedule(sh_id)); let assert_refs = - |count| assert_eq!(Checkpoint::schedule_ref_count(asset_id, sh_id), count); + |count| assert_eq!(ScheduleRefCount::::get(asset_id, sh_id), count); let remove_ca = |id| CA::remove_ca(owner.origin(), id); let remove_sh = || Checkpoint::remove_schedule(owner.origin(), asset_id, sh_id); @@ -1719,7 +1723,7 @@ fn vote_existing_checkpoint() { vote_cp_test(|asset_id, owner| { assert_ok!(Checkpoint::create_checkpoint(owner.origin(), asset_id)); let rd = Some(RecordDateSpec::Existing( - Checkpoint::checkpoint_id_sequence(asset_id), + CheckpointIdSequence::::get(asset_id), )); let id = notice_ca(owner, asset_id, Some(1000)).unwrap(); assert_ok!(CA::change_record_date(owner.origin(), id, rd)); @@ -2314,7 +2318,7 @@ fn dist_claim_existing_checkpoint() { dist_claim_cp_test(|asset_id, owner| { assert_ok!(Checkpoint::create_checkpoint(owner.origin(), asset_id)); let rd = Some(RecordDateSpec::Existing( - Checkpoint::checkpoint_id_sequence(asset_id), + CheckpointIdSequence::::get(asset_id), )); let id = dist_ca(owner, asset_id, Some(1000)).unwrap(); assert_ok!(CA::change_record_date(owner.origin(), id, rd)); diff --git a/pallets/runtime/tests/src/portfolio.rs b/pallets/runtime/tests/src/portfolio.rs index 9eacbf6acb..100741bb17 100644 --- a/pallets/runtime/tests/src/portfolio.rs +++ b/pallets/runtime/tests/src/portfolio.rs @@ -3,8 +3,9 @@ use sp_keyring::AccountKeyring; use pallet_nft::NFTOwner; use pallet_portfolio::{ - AllowedCustodians, Event, NameToNumber, PortfolioAssetBalances, PortfolioCustodian, - PortfolioLockedAssets, PortfolioNFT, Portfolios, PortfoliosInCustody, PreApprovedPortfolios, + AllowedCustodians, Event, NameToNumber, NextPortfolioNumber, PortfolioAssetBalances, + PortfolioCustodian, PortfolioLockedAssets, PortfolioNFT, Portfolios, PortfoliosInCustody, + PreApprovedPortfolios, }; use pallet_settlement::VenueCounter; use polymesh_primitives::asset::{AssetId, AssetType, NonFungibleType}; @@ -34,7 +35,7 @@ type Settlement = pallet_settlement::Pallet; fn create_portfolio() -> (User, PortfolioNumber) { let owner = User::new(AccountKeyring::Alice); let name = PortfolioName::from([42u8].to_vec()); - let num = Portfolio::next_portfolio_number(&owner.did); + let num = NextPortfolioNumber::::get(&owner.did); assert_eq!(num, PortfolioNumber(1)); assert_ok!(Portfolio::create_portfolio(owner.origin(), name.clone())); assert_eq!(Portfolios::::get(&owner.did, num), Some(name)); @@ -69,7 +70,7 @@ macro_rules! assert_owner_is_custodian { fn portfolio_name_too_long() { ExtBuilder::default().build().execute_with(|| { let owner = User::new(AccountKeyring::Alice); - let id = Portfolio::next_portfolio_number(owner.did); + let id = NextPortfolioNumber::::get(owner.did); let create = |name| Portfolio::create_portfolio(owner.origin(), name); let rename = |name| Portfolio::rename_portfolio(owner.origin(), id, name); assert_too_long!(create(max_len_bytes(1))); @@ -84,7 +85,7 @@ fn portfolio_name_too_long() { fn portfolio_name_taken() { ExtBuilder::default().build().execute_with(|| { let owner = User::new(AccountKeyring::Alice); - let id = Portfolio::next_portfolio_number(owner.did); + let id = NextPortfolioNumber::::get(owner.did); let create = |name: &str| Portfolio::create_portfolio(owner.origin(), name.into()); let rename = |name: &str| Portfolio::rename_portfolio(owner.origin(), id, name.into()); @@ -114,7 +115,7 @@ fn can_create_rename_delete_portfolio() { new_name.clone() )); assert_eq!( - Portfolio::next_portfolio_number(&owner.did), + NextPortfolioNumber::::get(&owner.did), PortfolioNumber(2) ); assert_eq!(name(), new_name); diff --git a/pallets/runtime/tests/src/settlement_test.rs b/pallets/runtime/tests/src/settlement_test.rs index e9ead58e03..54211ae1e6 100644 --- a/pallets/runtime/tests/src/settlement_test.rs +++ b/pallets/runtime/tests/src/settlement_test.rs @@ -14,7 +14,9 @@ use sp_std::collections::btree_set::BTreeSet; use pallet_asset::BalanceOf; use pallet_nft::NumberOfNFTs; -use pallet_portfolio::{PortfolioLockedAssets, PortfolioLockedNFT, PortfolioNFT}; +use pallet_portfolio::{ + NextPortfolioNumber, PortfolioLockedAssets, PortfolioLockedNFT, PortfolioNFT, +}; use pallet_scheduler as scheduler; use pallet_settlement::{ AffirmsReceived, Details, Event, InstructionAffirmsPending, InstructionCounter, @@ -1468,7 +1470,7 @@ fn cross_portfolio_settlement() { let mut bob = UserWithBalance::new(bob, &[asset_id]); let name = PortfolioName::from([42u8].to_vec()); - let num = Portfolio::next_portfolio_number(&bob.did); + let num = NextPortfolioNumber::::get(&bob.did); assert_ok!(Portfolio::create_portfolio(bob.origin(), name.clone())); let instruction_id = InstructionCounter::::get(); let amount = 100u128; @@ -1546,8 +1548,8 @@ fn multiple_portfolio_settlement() { let mut bob = UserWithBalance::new(bob, &[asset_id]); let name = PortfolioName::from([42u8].to_vec()); - let alice_num = Portfolio::next_portfolio_number(&alice.did); - let bob_num = Portfolio::next_portfolio_number(&bob.did); + let alice_num = NextPortfolioNumber::::get(&alice.did); + let bob_num = NextPortfolioNumber::::get(&bob.did); assert_ok!(Portfolio::create_portfolio(bob.origin(), name.clone())); assert_ok!(Portfolio::create_portfolio(alice.origin(), name.clone())); let instruction_id = InstructionCounter::::get(); @@ -1689,8 +1691,8 @@ fn multiple_custodian_settlement() { // Create portfolios let name = PortfolioName::from([42u8].to_vec()); - let alice_num = Portfolio::next_portfolio_number(&alice.did); - let bob_num = Portfolio::next_portfolio_number(&bob.did); + let alice_num = NextPortfolioNumber::::get(&alice.did); + let bob_num = NextPortfolioNumber::::get(&bob.did); assert_ok!(Portfolio::create_portfolio(bob.origin(), name.clone())); assert_ok!(Portfolio::create_portfolio(alice.origin(), name.clone()));