From bf07617880d5383c81a1bb06500c85e25e90ece2 Mon Sep 17 00:00:00 2001 From: Juan Ignacio Rios Date: Tue, 13 Aug 2024 14:01:39 +0200 Subject: [PATCH] clippy-changes --- Cargo.toml | 15 ++ clippy.toml | 0 integration-tests/Cargo.toml | 3 + integration-tests/penpal/Cargo.toml | 3 + integration-tests/src/tests/ct_migration.rs | 1 - integration-tests/src/tests/e2e.rs | 5 +- macros/Cargo.toml | 3 + macros/src/generate_accounts.rs | 6 +- macros/src/lib.rs | 2 +- macros/tests/Cargo.toml | 3 + nodes/parachain/Cargo.toml | 4 + .../parachain/src/chain_spec/polimec_paseo.rs | 5 +- pallets/democracy/Cargo.toml | 4 + pallets/democracy/src/lib.rs | 2 + pallets/dispenser/Cargo.toml | 3 + pallets/dispenser/src/extensions.rs | 16 +- pallets/dispenser/src/lib.rs | 9 +- pallets/elections-phragmen/Cargo.toml | 4 + pallets/elections-phragmen/src/lib.rs | 3 +- pallets/elections-phragmen/src/weights.rs | 4 +- pallets/funding/Cargo.toml | 6 + pallets/funding/src/benchmarking.rs | 4 +- .../funding/src/functions/1_application.rs | 3 + pallets/funding/src/functions/2_evaluation.rs | 1 + pallets/funding/src/functions/3_auction.rs | 89 +++++------ .../funding/src/functions/4_contribution.rs | 64 ++++---- .../funding/src/functions/5_funding_end.rs | 1 + pallets/funding/src/functions/6_settlement.rs | 27 ++-- .../funding/src/functions/7_ct_migration.rs | 6 +- pallets/funding/src/functions/misc.rs | 10 +- pallets/funding/src/functions/mod.rs | 5 +- .../funding/src/instantiator/calculations.rs | 14 +- .../src/instantiator/chain_interactions.rs | 45 +++--- pallets/funding/src/instantiator/macros.rs | 4 +- pallets/funding/src/instantiator/mod.rs | 9 +- pallets/funding/src/instantiator/traits.rs | 2 +- pallets/funding/src/instantiator/types.rs | 5 +- pallets/funding/src/lib.rs | 44 ++++-- pallets/funding/src/runtime_api.rs | 11 +- pallets/funding/src/tests/3_auction.rs | 137 +++++++++-------- pallets/funding/src/tests/4_contribution.rs | 20 +-- pallets/funding/src/tests/5_funding_end.rs | 3 - pallets/funding/src/tests/6_settlement.rs | 1 - pallets/funding/src/tests/misc.rs | 14 +- pallets/funding/src/tests/runtime_api.rs | 5 +- pallets/funding/src/traits.rs | 2 +- pallets/funding/src/types.rs | 138 +++++++++++++----- pallets/linear-release/Cargo.toml | 3 + pallets/linear-release/src/impls.rs | 21 +-- pallets/linear-release/src/lib.rs | 25 ++-- pallets/linear-release/src/tests.rs | 18 +-- pallets/linear-release/src/types.rs | 20 ++- pallets/oracle-ocw/Cargo.toml | 3 + pallets/oracle-ocw/src/crypto.rs | 6 +- pallets/oracle-ocw/src/lib.rs | 39 ++--- pallets/oracle-ocw/src/mock.rs | 2 +- pallets/oracle-ocw/src/traits.rs | 2 +- pallets/oracle-ocw/src/types.rs | 13 +- pallets/parachain-staking/Cargo.toml | 4 + pallets/parachain-staking/src/lib.rs | 2 + pallets/polimec-receiver/Cargo.toml | 3 + pallets/polimec-receiver/src/lib.rs | 3 + pallets/xcm-executor/Cargo.toml | 4 + polimec-common/common/Cargo.toml | 3 + polimec-common/common/src/credentials/mod.rs | 12 +- polimec-common/common/src/lib.rs | 8 +- polimec-common/test-utils/Cargo.toml | 3 + polimec-common/test-utils/src/lib.rs | 8 +- runtimes/polimec/Cargo.toml | 3 + runtimes/polimec/build.rs | 2 +- runtimes/polimec/src/benchmarks/mod.rs | 29 ---- .../src/custom_migrations/deposit_dust.rs | 63 -------- .../src/custom_migrations/init_pallet.rs | 19 +-- runtimes/polimec/src/custom_migrations/mod.rs | 2 - .../custom_migrations/unhashed_migration.rs | 104 ------------- runtimes/polimec/src/lib.rs | 25 ++-- runtimes/shared-configuration/Cargo.toml | 3 + runtimes/shared-configuration/src/currency.rs | 3 +- runtimes/shared-configuration/src/fee.rs | 3 + runtimes/shared-configuration/src/proxy.rs | 4 +- .../shared-configuration/src/weights/mod.rs | 2 +- 81 files changed, 617 insertions(+), 612 deletions(-) create mode 100644 clippy.toml delete mode 100644 runtimes/polimec/src/custom_migrations/deposit_dust.rs delete mode 100644 runtimes/polimec/src/custom_migrations/unhashed_migration.rs diff --git a/Cargo.toml b/Cargo.toml index 7a73c298a..6d9774634 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,21 @@ members = [ default-members = ["nodes/*", "pallets/*"] resolver = "2" +[workspace.lints.clippy] +all = { level = "warn", priority = -1} +#all = { level = "allow", priority = -1} +#pedantic = { level = "warn", priority = -1} +#pedantic = { level = "allow", priority = -1} + +inconsistent_digit_grouping = "allow" +zero_prefixed_literal = "allow" +missing_errors_doc = "allow" +must_use_candidate = "allow" +identity_op = "allow" + +[workspace.lints.rust] +unreachable_patterns = "deny" + [workspace.package] authors = ['Polimec Foundation '] documentation = "https://wiki.polimec.org/" diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 000000000..e69de29bb diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 78e5a199e..9c239c6aa 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + [build-dependencies] substrate-wasm-builder.workspace = true diff --git a/integration-tests/penpal/Cargo.toml b/integration-tests/penpal/Cargo.toml index f676cfbf0..9921e67f4 100644 --- a/integration-tests/penpal/Cargo.toml +++ b/integration-tests/penpal/Cargo.toml @@ -8,6 +8,9 @@ homepage = "https://substrate.io" repository.workspace = true edition.workspace = true +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/integration-tests/src/tests/ct_migration.rs b/integration-tests/src/tests/ct_migration.rs index 2019ad1d3..5a3360ead 100644 --- a/integration-tests/src/tests/ct_migration.rs +++ b/integration-tests/src/tests/ct_migration.rs @@ -201,7 +201,6 @@ fn full_pallet_migration_test() { let (project_id, participants) = create_settled_project(); let project_status = PolimecNet::execute_with(|| pallet_funding::ProjectsDetails::::get(project_id).unwrap().status); - dbg!(project_status); mock_hrmp_establishment(project_id); diff --git a/integration-tests/src/tests/e2e.rs b/integration-tests/src/tests/e2e.rs index 180045cc5..25892d84b 100644 --- a/integration-tests/src/tests/e2e.rs +++ b/integration-tests/src/tests/e2e.rs @@ -499,7 +499,6 @@ fn ct_migrated() { PenNet::execute_with(|| { println!("penpal events:"); - dbg!(PenNet::events()); }); // Migration is ready @@ -519,10 +518,8 @@ fn ct_migrated() { // Migrate CTs let accounts = excel_ct_amounts().iter().map(|item| item.0.clone()).unique().collect::>(); let total_ct_sold = excel_ct_amounts().iter().fold(FixedU128::zero(), |acc, item| acc + item.1); - dbg!(total_ct_sold); let polimec_sov_acc = PenNet::sovereign_account_id_of((Parent, Parachain(polimec::PARA_ID)).into()); let polimec_fund_balance = PenNet::account_data_of(polimec_sov_acc); - dbg!(polimec_fund_balance); let names = names(); @@ -550,7 +547,7 @@ fn ct_migrated() { let data = PenNet::account_data_of(item.0.clone()); let key: [u8; 32] = item.0.clone().into(); println!("Participant {} has {} CTs. Expected {}", names[&key], data.free.clone(), item.1); - dbg!(data.clone()); + let amount_as_balance = item.1.saturating_mul_int(CT_UNIT); assert_close_enough!( data.free, diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 4b1113d49..23c8df381 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -3,6 +3,9 @@ name = "macros" version.workspace = true edition.workspace = true +[lints] +workspace = true + [lib] name = "macros" path = "src/lib.rs" diff --git a/macros/src/generate_accounts.rs b/macros/src/generate_accounts.rs index a55b0d649..3f83dd37d 100644 --- a/macros/src/generate_accounts.rs +++ b/macros/src/generate_accounts.rs @@ -31,7 +31,7 @@ use syn::{ Expr, GenericArgument, GenericParam, Generics, Ident, ItemMod, Result, Token, Type, Visibility, WhereClause, }; -pub fn generate_accounts_impl(input: TokenStream) -> TokenStream { +pub fn macro_impl(input: TokenStream) -> TokenStream { let inputs = parse_macro_input!(input with Punctuated::::parse_terminated); let mut output = quote! {}; let mut insertions = Vec::new(); @@ -40,9 +40,7 @@ pub fn generate_accounts_impl(input: TokenStream) -> TokenStream { let name = input.to_string(); // Ensure the name is all uppercase - if name != name.to_uppercase() { - panic!("Name must be in all uppercase"); - } + assert_eq!(name, name.to_uppercase(), "Name must be in all uppercase"); // Generate a unique [u8; 32] value for the constant let mut value = [0u8; 32]; diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 450287d26..6bd11d912 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -21,5 +21,5 @@ mod generate_accounts; #[proc_macro] pub fn generate_accounts(input: TokenStream) -> TokenStream { - generate_accounts::generate_accounts_impl(input) + generate_accounts::macro_impl(input) } diff --git a/macros/tests/Cargo.toml b/macros/tests/Cargo.toml index 399ccba17..c9d93fd10 100644 --- a/macros/tests/Cargo.toml +++ b/macros/tests/Cargo.toml @@ -3,6 +3,9 @@ name = "macros-tests" version.workspace = true edition.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/nodes/parachain/Cargo.toml b/nodes/parachain/Cargo.toml index f2db29fd2..16b1b0d8b 100644 --- a/nodes/parachain/Cargo.toml +++ b/nodes/parachain/Cargo.toml @@ -10,6 +10,10 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +clippy.all = "allow" +clippy.pedantic = "allow" + [dependencies] clap = { workspace = true, features = ["derive"] } log.workspace = true diff --git a/nodes/parachain/src/chain_spec/polimec_paseo.rs b/nodes/parachain/src/chain_spec/polimec_paseo.rs index 7387bf20b..7266468a3 100644 --- a/nodes/parachain/src/chain_spec/polimec_paseo.rs +++ b/nodes/parachain/src/chain_spec/polimec_paseo.rs @@ -20,7 +20,10 @@ use sc_service::ChainType; -use crate::chain_spec::{common::*, get_properties, Extensions, GenericChainSpec, DEFAULT_PARA_ID}; +use crate::chain_spec::{ + common::{alice, bob, charlie, dave, eve, genesis_config, GenesisConfigParams}, + get_properties, Extensions, GenericChainSpec, DEFAULT_PARA_ID, +}; use polimec_runtime::{AccountId, MinCandidateStk}; pub fn get_local_chain_spec() -> GenericChainSpec { diff --git a/pallets/democracy/Cargo.toml b/pallets/democracy/Cargo.toml index e90d491a2..ed657078f 100644 --- a/pallets/democracy/Cargo.toml +++ b/pallets/democracy/Cargo.toml @@ -9,6 +9,10 @@ repository.workspace = true description = "FRAME pallet for democracy" readme = "README.md" +[lints] +clippy.all = "allow" +clippy.pedantic = "allow" + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/democracy/src/lib.rs b/pallets/democracy/src/lib.rs index 552e6167a..c96b6407b 100644 --- a/pallets/democracy/src/lib.rs +++ b/pallets/democracy/src/lib.rs @@ -145,6 +145,8 @@ #![recursion_limit = "256"] #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] use frame_support::{ ensure, diff --git a/pallets/dispenser/Cargo.toml b/pallets/dispenser/Cargo.toml index 08f08d953..1ee47c4bc 100644 --- a/pallets/dispenser/Cargo.toml +++ b/pallets/dispenser/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/dispenser/src/extensions.rs b/pallets/dispenser/src/extensions.rs index b56e92b1a..65b960dc7 100644 --- a/pallets/dispenser/src/extensions.rs +++ b/pallets/dispenser/src/extensions.rs @@ -16,7 +16,7 @@ // If you feel like getting in touch with us, you can do so at info@polimec.org -use crate::*; +use crate::{Call, Config}; use frame_support::{ dispatch::{CheckIfFeeless, DispatchInfo}, pallet_prelude::*, @@ -120,13 +120,7 @@ where let provides = vec![Encode::encode(&(who, self.0))]; let requires = if account.nonce < self.0 { vec![Encode::encode(&(who, self.0 - One::one()))] } else { vec![] }; - Ok(ValidTransaction { - priority: 0, - requires, - provides, - longevity: TransactionLongevity::max_value(), - propagate: true, - }) + Ok(ValidTransaction { priority: 0, requires, provides, longevity: TransactionLongevity::MAX, propagate: true }) } } @@ -219,10 +213,8 @@ where len: usize, result: &DispatchResult, ) -> Result<(), TransactionValidityError> { - if let Some(pre) = pre { - if let Some(pre) = pre { - S::post_dispatch(Some(pre), info, post_info, len, result)?; - } + if let Some(Some(pre)) = pre { + S::post_dispatch(Some(pre), info, post_info, len, result)?; } Ok(()) } diff --git a/pallets/dispenser/src/lib.rs b/pallets/dispenser/src/lib.rs index 5b3982a02..827ca9ea8 100644 --- a/pallets/dispenser/src/lib.rs +++ b/pallets/dispenser/src/lib.rs @@ -17,6 +17,10 @@ // If you feel like getting in touch with us, you can do so at info@polimec.org #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] +#![allow(clippy::large_enum_variant)] + pub use pallet::*; pub use crate::weights::WeightInfo; @@ -45,6 +49,7 @@ pub type AccountIdOf = ::AccountId; type CurrencyOf = <::VestingSchedule as VestingSchedule>>::Currency; #[frame_support::pallet] pub mod pallet { + #[allow(clippy::wildcard_imports)] use super::*; use crate::weights::WeightInfo; use frame_support::{ @@ -145,9 +150,9 @@ pub mod pallet { impl Pallet { #[pallet::feeless_if( | origin: &OriginFor, jwt: &UntrustedToken | -> bool { if let Ok((_, did, _, _)) = T::InvestorOrigin::ensure_origin(origin.clone(), jwt, T::VerifierPublicKey::get()) { - return Dispensed::::get(did).is_none() + Dispensed::::get(did).is_none() } else { - return false + false } })] #[pallet::call_index(0)] diff --git a/pallets/elections-phragmen/Cargo.toml b/pallets/elections-phragmen/Cargo.toml index 4f33d2d14..863d10a16 100644 --- a/pallets/elections-phragmen/Cargo.toml +++ b/pallets/elections-phragmen/Cargo.toml @@ -9,6 +9,10 @@ repository.workspace = true description = "FRAME pallet based on seq-Phragmén election method." readme = "README.md" +[lints] +clippy.all = "allow" +clippy.pedantic = "allow" + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/elections-phragmen/src/lib.rs b/pallets/elections-phragmen/src/lib.rs index 304d14b4b..395a3a89e 100644 --- a/pallets/elections-phragmen/src/lib.rs +++ b/pallets/elections-phragmen/src/lib.rs @@ -91,6 +91,8 @@ //! - [`Module`] #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] use frame_support::{ pallet_prelude::DispatchResult, @@ -102,7 +104,6 @@ use frame_support::{ }, weights::Weight, }; -use log; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_npos_elections::{ElectionResult, ExtendedBalance}; diff --git a/pallets/elections-phragmen/src/weights.rs b/pallets/elections-phragmen/src/weights.rs index 96c0c73c3..7707b5c32 100644 --- a/pallets/elections-phragmen/src/weights.rs +++ b/pallets/elections-phragmen/src/weights.rs @@ -302,7 +302,7 @@ impl WeightInfo for SubstrateWeight { // Measured: `0 + e * (28 ±0) + v * (606 ±0)` // Estimated: `178887 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` // Minimum execution time: 1_281_877_000 picoseconds. - Weight::from_parts(1_288_147_000, 178887) + Weight::from_parts(1_288_147_000, 178_887) // Standard Error: 528_851 .saturating_add(Weight::from_parts(17_761_407, 0).saturating_mul(v.into())) // Standard Error: 33_932 @@ -559,7 +559,7 @@ impl WeightInfo for () { // Measured: `0 + e * (28 ±0) + v * (606 ±0)` // Estimated: `178887 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` // Minimum execution time: 1_281_877_000 picoseconds. - Weight::from_parts(1_288_147_000, 178887) + Weight::from_parts(1_288_147_000, 178_887) // Standard Error: 528_851 .saturating_add(Weight::from_parts(17_761_407, 0).saturating_mul(v.into())) // Standard Error: 33_932 diff --git a/pallets/funding/Cargo.toml b/pallets/funding/Cargo.toml index ad77bdab3..83adfa447 100644 --- a/pallets/funding/Cargo.toml +++ b/pallets/funding/Cargo.toml @@ -10,6 +10,12 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + +#[lints.clippy] +#inconsistent_digit_grouping = "allow" + [dependencies] serde = { workspace = true } parity-scale-codec = { workspace = true, features = [ diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index 598e9beed..002e9149e 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -510,7 +510,7 @@ mod benchmarks { project_metadata.clone().policy_ipfs_cid.unwrap(), ); #[extrinsic_call] - start_evaluation(RawOrigin::Signed(issuer), jwt, project_id); + start_evaluation(RawOrigin::Signed(issuer), jwt, probject_id); // * validity checks * // Storage @@ -1396,7 +1396,7 @@ mod benchmarks { account: bidder.clone(), id: bid_to_settle.id, final_ct_amount: bid_to_settle.original_ct_amount, - final_ct_price: wap, + final_ct_usd_price: wap, } .into(), ); diff --git a/pallets/funding/src/functions/1_application.rs b/pallets/funding/src/functions/1_application.rs index 22e17f37f..fdcdc1967 100644 --- a/pallets/funding/src/functions/1_application.rs +++ b/pallets/funding/src/functions/1_application.rs @@ -1,3 +1,6 @@ +#![allow(clippy::wildcard_imports)] +#![allow(clippy::type_complexity)] + use super::*; impl Pallet { diff --git a/pallets/funding/src/functions/2_evaluation.rs b/pallets/funding/src/functions/2_evaluation.rs index b4ac49342..fd8545fbb 100644 --- a/pallets/funding/src/functions/2_evaluation.rs +++ b/pallets/funding/src/functions/2_evaluation.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; impl Pallet { diff --git a/pallets/funding/src/functions/3_auction.rs b/pallets/funding/src/functions/3_auction.rs index b27506e3e..855ff5063 100644 --- a/pallets/funding/src/functions/3_auction.rs +++ b/pallets/funding/src/functions/3_auction.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; impl Pallet { @@ -57,17 +58,18 @@ impl Pallet { /// * [`BiddingBonds`] - Update the storage with the bidder's PLMC bond for that bid /// * [`Bids`] - Check previous bids by that user, and update the storage with the new bid #[transactional] - pub fn do_bid( - bidder: &AccountIdOf, - project_id: ProjectId, - ct_amount: BalanceOf, - multiplier: MultiplierOf, - funding_asset: AcceptedFundingAsset, - did: Did, - investor_type: InvestorType, - whitelisted_policy: Cid, - ) -> DispatchResultWithPostInfo { + pub fn do_bid(params: DoBidParams) -> DispatchResultWithPostInfo { // * Get variables * + let DoBidParams { + bidder, + project_id, + ct_amount, + multiplier, + funding_asset, + investor_type, + did, + whitelisted_policy, + } = params; let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; @@ -84,10 +86,10 @@ impl Pallet { // weight return variables let mut perform_bid_calls = 0; - let existing_bids = Bids::::iter_prefix_values((project_id, bidder)).collect::>(); + let existing_bids = Bids::::iter_prefix_values((project_id, bidder.clone())).collect::>(); let existing_bids_amount = existing_bids.len() as u32; - let metadata_bidder_ticket_size_bounds = match investor_type { + let metadata_ticket_size_bounds = match investor_type { InvestorType::Institutional => project_metadata.bidding_ticket_sizes.institutional, InvestorType::Professional => project_metadata.bidding_ticket_sizes.professional, _ => return Err(Error::::WrongInvestorType.into()), @@ -115,7 +117,7 @@ impl Pallet { ); ensure!( - metadata_bidder_ticket_size_bounds.usd_ticket_above_minimum_per_participation(min_total_ticket_size), + metadata_ticket_size_bounds.usd_ticket_above_minimum_per_participation(min_total_ticket_size), Error::::TooLow ); ensure!(multiplier.into() <= max_multiplier && multiplier.into() > 0u8, Error::::ForbiddenMultiplier); @@ -129,7 +131,7 @@ impl Pallet { // While there's a remaining amount to bid for while !amount_to_bid.is_zero() { - let bid_amount = if amount_to_bid <= current_bucket.amount_left { + let ct_amount = if amount_to_bid <= current_bucket.amount_left { // Simple case, the bucket has enough to cover the bid amount_to_bid } else { @@ -138,26 +140,27 @@ impl Pallet { }; let bid_id = NextBidId::::get(); - Self::perform_do_bid( - bidder, + let perform_params = DoPerformBidParams { + bidder: bidder.clone(), project_id, - bid_amount, - current_bucket.current_price, + ct_amount, + ct_usd_price: current_bucket.current_price, multiplier, funding_asset, bid_id, now, - did.clone(), - metadata_bidder_ticket_size_bounds, - existing_bids_amount.saturating_add(perform_bid_calls), - total_bids_for_project.saturating_add(perform_bid_calls), - )?; + did: did.clone(), + metadata_ticket_size_bounds, + total_bids_by_bidder: existing_bids_amount.saturating_add(perform_bid_calls), + total_bids_for_project: total_bids_for_project.saturating_add(perform_bid_calls), + }; + Self::do_perform_bid(perform_params)?; perform_bid_calls += 1; // Update the current bucket and reduce the amount to bid by the amount we just bid - current_bucket.update(bid_amount); - amount_to_bid.saturating_reduce(bid_amount); + current_bucket.update(ct_amount); + amount_to_bid.saturating_reduce(ct_amount); } // Note: If the bucket has been exhausted, the 'update' function has already made the 'current_bucket' point to the next one. @@ -170,20 +173,22 @@ impl Pallet { } #[transactional] - fn perform_do_bid( - bidder: &AccountIdOf, - project_id: ProjectId, - ct_amount: BalanceOf, - ct_usd_price: T::Price, - multiplier: MultiplierOf, - funding_asset: AcceptedFundingAsset, - bid_id: u32, - now: BlockNumberFor, - did: Did, - metadata_ticket_size_bounds: TicketSizeOf, - total_bids_by_bidder: u32, - total_bids_for_project: u32, - ) -> Result, DispatchError> { + fn do_perform_bid(do_perform_bid_params: DoPerformBidParams) -> Result, DispatchError> { + let DoPerformBidParams { + bidder, + project_id, + ct_amount, + ct_usd_price, + multiplier, + funding_asset, + bid_id, + now, + did, + metadata_ticket_size_bounds, + total_bids_by_bidder, + total_bids_for_project, + } = do_perform_bid_params; + let ticket_size = ct_usd_price.checked_mul_int(ct_amount).ok_or(Error::::BadMath)?; let total_usd_bid_by_did = AuctionBoughtUSD::::get((project_id, did.clone())); @@ -214,10 +219,10 @@ impl Pallet { when: now, }; - Self::try_plmc_participation_lock(bidder, project_id, plmc_bond)?; - Self::try_funding_asset_hold(bidder, project_id, funding_asset_amount_locked, funding_asset.id())?; + Self::try_plmc_participation_lock(&bidder, project_id, plmc_bond)?; + Self::try_funding_asset_hold(&bidder, project_id, funding_asset_amount_locked, funding_asset.id())?; - Bids::::insert((project_id, bidder, bid_id), &new_bid); + Bids::::insert((project_id, bidder.clone(), bid_id), &new_bid); NextBidId::::set(bid_id.saturating_add(One::one())); BidCounts::::mutate(project_id, |c| *c += 1); AuctionBoughtUSD::::mutate((project_id, did), |amount| *amount += ticket_size); diff --git a/pallets/funding/src/functions/4_contribution.rs b/pallets/funding/src/functions/4_contribution.rs index 1e967ce7c..381b232bc 100644 --- a/pallets/funding/src/functions/4_contribution.rs +++ b/pallets/funding/src/functions/4_contribution.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; impl Pallet { @@ -11,16 +12,17 @@ impl Pallet { /// * multiplier: Decides how much PLMC bonding is required for buying that amount of tokens /// * asset: The asset used for the contribution #[transactional] - pub fn do_contribute( - contributor: &AccountIdOf, - project_id: ProjectId, - token_amount: BalanceOf, - multiplier: MultiplierOf, - asset: AcceptedFundingAsset, - did: Did, - investor_type: InvestorType, - whitelisted_policy: Cid, - ) -> DispatchResultWithPostInfo { + pub fn do_contribute(params: DoContributeParams) -> DispatchResultWithPostInfo { + let DoContributeParams { + contributor, + project_id, + ct_amount: token_amount, + multiplier, + funding_asset, + investor_type, + did, + whitelisted_policy, + } = params; let mut project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let did_has_winning_bid = DidWithWinningBids::::get(project_id, did.clone()); @@ -38,34 +40,38 @@ impl Pallet { let buyable_tokens = token_amount.min(project_details.remaining_contribution_tokens); project_details.remaining_contribution_tokens.saturating_reduce(buyable_tokens); - Self::do_perform_contribution( + let perform_params = DoPerformContributionParams { contributor, project_id, - &mut project_details, + project_details: &mut project_details, buyable_tokens, multiplier, - asset, + funding_asset, investor_type, did, whitelisted_policy, - ) + }; + + Self::do_perform_contribution(perform_params) } #[transactional] - fn do_perform_contribution( - contributor: &AccountIdOf, - project_id: ProjectId, - project_details: &mut ProjectDetailsOf, - buyable_tokens: BalanceOf, - multiplier: MultiplierOf, - funding_asset: AcceptedFundingAsset, - investor_type: InvestorType, - did: Did, - whitelisted_policy: Cid, - ) -> DispatchResultWithPostInfo { + fn do_perform_contribution(params: DoPerformContributionParams) -> DispatchResultWithPostInfo { + let DoPerformContributionParams { + contributor, + project_id, + project_details, + buyable_tokens, + multiplier, + funding_asset, + investor_type, + did, + whitelisted_policy, + } = params; + let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; let caller_existing_contributions = - Contributions::::iter_prefix_values((project_id, contributor)).collect::>(); + Contributions::::iter_prefix_values((project_id, contributor.clone())).collect::>(); let total_usd_bought_by_did = ContributionBoughtUSD::::get((project_id, did.clone())); let now = >::block_number(); let ct_usd_price = project_details.weighted_average_price.ok_or(Error::::WapNotSet)?; @@ -124,10 +130,10 @@ impl Pallet { }; // Try adding the new contribution to the system - Self::try_plmc_participation_lock(contributor, project_id, plmc_bond)?; - Self::try_funding_asset_hold(contributor, project_id, funding_asset_amount, funding_asset.id())?; + Self::try_plmc_participation_lock(&contributor, project_id, plmc_bond)?; + Self::try_funding_asset_hold(&contributor, project_id, funding_asset_amount, funding_asset.id())?; - Contributions::::insert((project_id, contributor, contribution_id), &new_contribution); + Contributions::::insert((project_id, contributor.clone(), contribution_id), &new_contribution); NextContributionId::::set(contribution_id.saturating_add(One::one())); ContributionBoughtUSD::::mutate((project_id, did), |amount| *amount += ticket_size); diff --git a/pallets/funding/src/functions/5_funding_end.rs b/pallets/funding/src/functions/5_funding_end.rs index d1dc7fb2a..9c94a4f50 100644 --- a/pallets/funding/src/functions/5_funding_end.rs +++ b/pallets/funding/src/functions/5_funding_end.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; impl Pallet { diff --git a/pallets/funding/src/functions/6_settlement.rs b/pallets/funding/src/functions/6_settlement.rs index eca7da42d..c2b9af9e7 100644 --- a/pallets/funding/src/functions/6_settlement.rs +++ b/pallets/funding/src/functions/6_settlement.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; use crate::traits::VestingDurationCalculation; use frame_support::{ @@ -135,10 +136,8 @@ impl Pallet { pub fn do_settle_bid(bid: BidInfoOf, project_id: ProjectId) -> DispatchResult { let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; - let funding_success = match project_details.status { - ProjectStatus::SettlementStarted(FundingOutcome::Success) => true, - _ => false, - }; + let funding_success = + matches!(project_details.status, ProjectStatus::SettlementStarted(FundingOutcome::Success)); let wap = project_details.weighted_average_price.ok_or(Error::::ImpossibleState)?; ensure!( @@ -148,7 +147,7 @@ impl Pallet { // Return either the full amount to refund if bid is rejected/project failed, // or a partial amount when the wap > paid price/bid is partially accepted - let (final_ct_price, final_ct_amount, refunded_plmc, refunded_funding_asset_amount) = + let BidRefund { final_ct_usd_price, final_ct_amount, refunded_plmc, refunded_funding_asset_amount } = Self::calculate_refund(&bid, funding_success, wap)?; Self::release_participation_bond(project_id, &bid.bidder, refunded_plmc)?; @@ -195,7 +194,7 @@ impl Pallet { account: bid.bidder, id: bid.id, final_ct_amount, - final_ct_price, + final_ct_usd_price, }); Ok(()) @@ -207,22 +206,26 @@ impl Pallet { bid: &BidInfoOf, funding_success: bool, wap: PriceOf, - ) -> Result<(PriceOf, BalanceOf, BalanceOf, BalanceOf), DispatchError> { + ) -> Result, DispatchError> { let final_ct_usd_price = if bid.original_ct_usd_price > wap { wap } else { bid.original_ct_usd_price }; if bid.status == BidStatus::Rejected || !funding_success { - return Ok((final_ct_usd_price, Zero::zero(), bid.plmc_bond, bid.funding_asset_amount_locked)); + return Ok(BidRefund:: { + final_ct_usd_price, + final_ct_amount: Zero::zero(), + refunded_plmc: bid.plmc_bond, + refunded_funding_asset_amount: bid.funding_asset_amount_locked, + }); } - let final_ct_amount = bid.final_ct_amount(); let new_ticket_size = final_ct_usd_price.checked_mul_int(final_ct_amount).ok_or(Error::::BadMath)?; let new_plmc_bond = Self::calculate_plmc_bond(new_ticket_size, bid.multiplier)?; let new_funding_asset_amount = Self::calculate_funding_asset_amount(new_ticket_size, bid.funding_asset)?; - let refund_plmc = bid.plmc_bond.saturating_sub(new_plmc_bond); - let refund_funding_asset = bid.funding_asset_amount_locked.saturating_sub(new_funding_asset_amount); + let refunded_plmc = bid.plmc_bond.saturating_sub(new_plmc_bond); + let refunded_funding_asset_amount = bid.funding_asset_amount_locked.saturating_sub(new_funding_asset_amount); - Ok((final_ct_usd_price, final_ct_amount, refund_plmc, refund_funding_asset)) + Ok(BidRefund:: { final_ct_usd_price, final_ct_amount, refunded_plmc, refunded_funding_asset_amount }) } pub fn do_settle_contribution(contribution: ContributionInfoOf, project_id: ProjectId) -> DispatchResult { diff --git a/pallets/funding/src/functions/7_ct_migration.rs b/pallets/funding/src/functions/7_ct_migration.rs index 310fcd6f5..3e17ecb7d 100644 --- a/pallets/funding/src/functions/7_ct_migration.rs +++ b/pallets/funding/src/functions/7_ct_migration.rs @@ -1,4 +1,6 @@ +#[allow(clippy::wildcard_imports)] use super::*; + use xcm::v3::MaxPalletNameLen; // Offchain migration functions @@ -372,7 +374,7 @@ impl Pallet { }, ), ) => { - let ct_sold_as_u128: u128 = contribution_tokens_sold.try_into().map_err(|_| Error::::BadMath)?; + let ct_sold_as_u128: u128 = contribution_tokens_sold.into(); let assets: Vec = assets.into_inner(); let asset_1 = assets[0].clone(); match asset_1 { @@ -466,7 +468,7 @@ impl Pallet { Self::change_migration_status(project_id, participant.clone(), MigrationStatus::Sent(query_id))?; // * Process Data * - let xcm = Self::construct_migration_xcm_message(migrations.into(), query_id, pallet_index); + let xcm = Self::construct_migration_xcm_message(migrations, query_id, pallet_index); >::send_xcm(Here, project_multilocation, xcm).map_err(|_| Error::::XcmFailed)?; ActiveMigrationQueue::::insert(query_id, (project_id, participant.clone())); diff --git a/pallets/funding/src/functions/misc.rs b/pallets/funding/src/functions/misc.rs index a94f20305..cbe196f45 100644 --- a/pallets/funding/src/functions/misc.rs +++ b/pallets/funding/src/functions/misc.rs @@ -1,5 +1,6 @@ use sp_runtime::traits::CheckedAdd; +#[allow(clippy::wildcard_imports)] use super::*; // Helper functions @@ -34,7 +35,7 @@ impl Pallet { ) -> Result, DispatchError> { let plmc_usd_price = T::PriceProvider::get_decimals_aware_price(PLMC_FOREIGN_ID, USD_DECIMALS, PLMC_DECIMALS) .ok_or(Error::::PriceNotFound)?; - let usd_bond = multiplier.calculate_bonding_requirement::(ticket_size).map_err(|_| Error::::BadMath)?; + let usd_bond = multiplier.calculate_bonding_requirement::(ticket_size).ok_or(Error::::BadMath)?; plmc_usd_price .reciprocal() .ok_or(Error::::BadMath)? @@ -393,11 +394,8 @@ impl Pallet { ensure!(project_details.status == current_round, Error::::IncorrectRound); ensure!(project_details.round_duration.ended(now) || skip_end_check, Error::::TooEarlyForRound); - let round_end = if let Some(round_duration) = maybe_round_duration { - Some(now.saturating_add(round_duration).saturating_sub(One::one())) - } else { - None - }; + let round_end = + maybe_round_duration.map(|round_duration| now.saturating_add(round_duration).saturating_sub(One::one())); project_details.round_duration = BlockNumberPair::new(Some(now), round_end); project_details.status = next_round.clone(); diff --git a/pallets/funding/src/functions/mod.rs b/pallets/funding/src/functions/mod.rs index d7db28bb8..1aaa82ee7 100644 --- a/pallets/funding/src/functions/mod.rs +++ b/pallets/funding/src/functions/mod.rs @@ -1,6 +1,5 @@ -use super::*; - -use crate::traits::{BondingRequirementCalculation, ProvideAssetPrice, VestingDurationCalculation}; +#[allow(clippy::wildcard_imports)] +use super::{traits::*, *}; use core::ops::Not; use frame_support::{ dispatch::{DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, PostDispatchInfo}, diff --git a/pallets/funding/src/instantiator/calculations.rs b/pallets/funding/src/instantiator/calculations.rs index 36cd3a257..2e715dc91 100644 --- a/pallets/funding/src/instantiator/calculations.rs +++ b/pallets/funding/src/instantiator/calculations.rs @@ -1,4 +1,6 @@ +#[allow(clippy::wildcard_imports)] use super::*; +use core::cmp::Ordering; use itertools::GroupBy; use polimec_common::USD_DECIMALS; @@ -502,6 +504,7 @@ impl< let ordered_list = flattened_list.into_iter().sorted_by(|a, b| a.asset_id.cmp(&b.asset_id)).collect_vec(); + #[allow(clippy::type_complexity)] let asset_lists: GroupBy, _, fn(&UserToFundingAsset) -> AssetIdOf> = ordered_list.into_iter().group_by(|item| item.asset_id); @@ -676,12 +679,11 @@ impl< bucket.amount_left = mid_point; let new_wap = bucket.calculate_wap(auction_allocation); - if new_wap == target_wap { - return bucket - } else if new_wap < target_wap { - upper_bound = mid_point.saturating_sub(1u32.into()); - } else { - lower_bound = mid_point.saturating_add(1u32.into()); + // refactor as match + match new_wap.cmp(&target_wap) { + Ordering::Equal => return bucket, + Ordering::Less => upper_bound = mid_point - 1u32.into(), + Ordering::Greater => lower_bound = mid_point + 1u32.into(), } } diff --git a/pallets/funding/src/instantiator/chain_interactions.rs b/pallets/funding/src/instantiator/chain_interactions.rs index 12a8798e3..cddde0505 100644 --- a/pallets/funding/src/instantiator/chain_interactions.rs +++ b/pallets/funding/src/instantiator/chain_interactions.rs @@ -1,3 +1,6 @@ +#![allow(clippy::too_many_arguments)] + +#[allow(clippy::wildcard_imports)] use super::*; // general chain interactions @@ -511,16 +514,17 @@ impl< for bid in bids { self.execute(|| { let did = generate_did_from_account(bid.bidder.clone()); - crate::Pallet::::do_bid( - &bid.bidder, + let params = DoBidParams:: { + bidder: bid.bidder, project_id, - bid.amount, - bid.multiplier, - bid.asset, + ct_amount: bid.amount, + multiplier: bid.multiplier, + funding_asset: bid.asset, did, - InvestorType::Institutional, - project_policy.clone(), - ) + investor_type: InvestorType::Institutional, + whitelisted_policy: project_policy.clone(), + }; + crate::Pallet::::do_bid(params) })?; } Ok(().into()) @@ -617,18 +621,17 @@ impl< for cont in contributions { let did = generate_did_from_account(cont.contributor.clone()); let investor_type = InvestorType::Retail; - self.execute(|| { - crate::Pallet::::do_contribute( - &cont.contributor, - project_id, - cont.amount, - cont.multiplier, - cont.asset, - did, - investor_type, - project_policy.clone(), - ) - })?; + let params = DoContributeParams:: { + contributor: cont.contributor, + project_id, + ct_amount: cont.amount, + multiplier: cont.multiplier, + funding_asset: cont.asset, + did, + investor_type, + whitelisted_policy: project_policy.clone(), + }; + self.execute(|| crate::Pallet::::do_contribute(params))?; }, _ => panic!("Project should be in Community or Remainder status"), } @@ -735,7 +738,7 @@ impl< let amount = if let EvaluatorsOutcome::Rewarded(ref info) = evaluators_outcome { assert!(is_successful); - Pallet::::calculate_evaluator_reward(&evaluation, &info) + Pallet::::calculate_evaluator_reward(&evaluation, info) } else { assert!(!is_successful); Zero::zero() diff --git a/pallets/funding/src/instantiator/macros.rs b/pallets/funding/src/instantiator/macros.rs index 4f7bba1be..1862e962d 100644 --- a/pallets/funding/src/instantiator/macros.rs +++ b/pallets/funding/src/instantiator/macros.rs @@ -58,8 +58,8 @@ macro_rules! find_event { let events = frame_system::Pallet::<$runtime>::events(); events.iter().find_map(|event_record| { let runtime_event = event_record.event.clone(); - let runtime_event = <<$runtime as crate::Config>::RuntimeEvent>::from(runtime_event); - if let Ok(funding_event) = TryInto::>::try_into(runtime_event) { + let runtime_event = <<$runtime as Config>::RuntimeEvent>::from(runtime_event); + if let Ok(funding_event) = TryInto::>::try_into(runtime_event) { if let $pattern = funding_event { let mut is_match = true; $( diff --git a/pallets/funding/src/instantiator/mod.rs b/pallets/funding/src/instantiator/mod.rs index a5291fa91..3c4e8f0e1 100644 --- a/pallets/funding/src/instantiator/mod.rs +++ b/pallets/funding/src/instantiator/mod.rs @@ -13,11 +13,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - -use crate::{ - traits::{BondingRequirementCalculation, ProvideAssetPrice}, - *, -}; +#[allow(clippy::wildcard_imports)] +use crate::{traits::*, *}; use frame_support::{ pallet_prelude::*, traits::{ @@ -42,7 +39,7 @@ use sp_arithmetic::{ use sp_runtime::traits::{Convert, Member, One}; use sp_std::{ cell::RefCell, - collections::{btree_map::*, btree_set::*}, + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, iter::zip, marker::PhantomData, }; diff --git a/pallets/funding/src/instantiator/traits.rs b/pallets/funding/src/instantiator/traits.rs index 5eee8ccaa..cfbe9a378 100644 --- a/pallets/funding/src/instantiator/traits.rs +++ b/pallets/funding/src/instantiator/traits.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Config, UserToPLMCBalance, Vec}; pub trait Deposits { fn existential_deposits(&self) -> Vec>; diff --git a/pallets/funding/src/instantiator/types.rs b/pallets/funding/src/instantiator/types.rs index ab219e4c1..a4e34549a 100644 --- a/pallets/funding/src/instantiator/types.rs +++ b/pallets/funding/src/instantiator/types.rs @@ -1,3 +1,4 @@ +#[allow(clippy::wildcard_imports)] use super::*; use frame_support::{Deserialize, Serialize}; @@ -205,7 +206,7 @@ impl AccountMerge for Vec> { let mut btree = BTreeMap::new(); for UserToFundingAsset { account, asset_amount, asset_id } in self.iter() { btree - .entry((account.clone(), asset_id.clone())) + .entry((account.clone(), asset_id)) .and_modify(|e: &mut BalanceOf| { *e = match ops { MergeOperation::Add => e.saturating_add(*asset_amount), @@ -216,7 +217,7 @@ impl AccountMerge for Vec> { } btree .into_iter() - .map(|((account, asset_id), asset_amount)| UserToFundingAsset::new(account, asset_amount, asset_id)) + .map(|((account, asset_id), asset_amount)| UserToFundingAsset::new(account, asset_amount, *asset_id)) .collect() } diff --git a/pallets/funding/src/lib.rs b/pallets/funding/src/lib.rs index 6b6b5c692..59dfef17f 100644 --- a/pallets/funding/src/lib.rs +++ b/pallets/funding/src/lib.rs @@ -111,6 +111,8 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] // This recursion limit is needed because we have too many benchmarks and benchmarking will fail if // we add more without this limit. #![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "512")] @@ -129,7 +131,7 @@ pub use pallet::*; use pallet_xcm::ensure_response; use polimec_common::{ credentials::{Cid, Did, EnsureOriginWithCredentials, InvestorType, UntrustedToken}, - migration_types::*, + migration_types::{Migration, MigrationStatus, ParticipationType}, }; use polkadot_parachain_primitives::primitives::Id as ParaId; use sp_arithmetic::traits::{One, Saturating}; @@ -193,6 +195,7 @@ pub const PLMC_DECIMALS: u8 = 10; #[frame_support::pallet] pub mod pallet { + #[allow(clippy::wildcard_imports)] use super::*; use crate::traits::{BondingRequirementCalculation, ProvideAssetPrice, VestingDurationCalculation}; use frame_support::{ @@ -614,7 +617,7 @@ pub mod pallet { account: AccountIdOf, id: u32, final_ct_amount: BalanceOf, - final_ct_price: PriceOf, + final_ct_usd_price: PriceOf, }, ContributionSettled { project_id: ProjectId, @@ -881,12 +884,21 @@ pub mod pallet { project_id: ProjectId, #[pallet::compact] ct_amount: BalanceOf, multiplier: T::Multiplier, - asset: AcceptedFundingAsset, + funding_asset: AcceptedFundingAsset, ) -> DispatchResultWithPostInfo { - let (account, did, investor_type, whitelisted_policy) = + let (bidder, did, investor_type, whitelisted_policy) = T::InvestorOrigin::ensure_origin(origin, &jwt, T::VerifierPublicKey::get())?; - - Self::do_bid(&account, project_id, ct_amount, multiplier, asset, did, investor_type, whitelisted_policy) + let params = DoBidParams:: { + bidder, + project_id, + ct_amount, + multiplier, + funding_asset, + did, + investor_type, + whitelisted_policy, + }; + Self::do_bid(params) } #[pallet::call_index(8)] @@ -916,14 +928,23 @@ pub mod pallet { origin: OriginFor, jwt: UntrustedToken, project_id: ProjectId, - #[pallet::compact] amount: BalanceOf, + #[pallet::compact] ct_amount: BalanceOf, multiplier: MultiplierOf, - asset: AcceptedFundingAsset, + funding_asset: AcceptedFundingAsset, ) -> DispatchResultWithPostInfo { - let (account, did, investor_type, whitelisted_policy) = + let (contributor, did, investor_type, whitelisted_policy) = T::InvestorOrigin::ensure_origin(origin, &jwt, T::VerifierPublicKey::get())?; - - Self::do_contribute(&account, project_id, amount, multiplier, asset, did, investor_type, whitelisted_policy) + let params = DoContributeParams:: { + contributor, + project_id, + ct_amount, + multiplier, + funding_asset, + did, + investor_type, + whitelisted_policy, + }; + Self::do_contribute(params) } #[pallet::call_index(10)] @@ -1090,6 +1111,7 @@ pub mod pallet { } pub mod xcm_executor_impl { + #[allow(clippy::wildcard_imports)] use super::*; pub struct HrmpHandler(PhantomData); diff --git a/pallets/funding/src/runtime_api.rs b/pallets/funding/src/runtime_api.rs index 61edaa376..7c87835aa 100644 --- a/pallets/funding/src/runtime_api.rs +++ b/pallets/funding/src/runtime_api.rs @@ -1,4 +1,5 @@ -use crate::{traits::ProvideAssetPrice, *}; +#[allow(clippy::wildcard_imports)] +use crate::{traits::*, *}; use alloc::collections::BTreeMap; use frame_support::traits::fungibles::{metadata::Inspect as MetadataInspect, Inspect, InspectEnumerable}; use itertools::Itertools; @@ -184,6 +185,7 @@ impl Pallet { .map(|((account_id, contribution_id), _contribution)| (account_id, contribution_id)) .collect_vec(); + #[allow(clippy::type_complexity)] let mut map: BTreeMap, (Vec, Vec, Vec)> = BTreeMap::new(); for (account_id, evaluation_id) in evaluations { @@ -198,17 +200,14 @@ impl Pallet { map.entry(account_id).or_insert_with(|| (Vec::new(), Vec::new(), Vec::new())).2.push(contribution_id); } - let output = map - .into_iter() + map.into_iter() .map(|(account, (evaluation_ids, bid_ids, contribution_ids))| ProjectParticipationIds { account, evaluation_ids, bid_ids, contribution_ids, }) - .collect(); - - output + .collect() } pub fn usd_target_percent_reached(project_id: ProjectId) -> FixedU128 { diff --git a/pallets/funding/src/tests/3_auction.rs b/pallets/funding/src/tests/3_auction.rs index 2024ea21f..ab43d0e3a 100644 --- a/pallets/funding/src/tests/3_auction.rs +++ b/pallets/funding/src/tests/3_auction.rs @@ -328,16 +328,16 @@ mod round_flow { let investor_type = InvestorType::Retail; inst.execute(|| { assert_noop!( - PolimecFunding::do_contribute( - &BIDDER_1, + PolimecFunding::do_contribute(DoContributeParams:: { + contributor: BIDDER_1, project_id, - 100, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, + ct_amount: 100, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, did, investor_type, - project_metadata.clone().policy_ipfs_cid.unwrap(), - ), + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + }), Error::::IncorrectRound ); }); @@ -872,7 +872,7 @@ mod bid_extrinsic { assert_eq!(frozen_balance, frozen_amount); let vest_duration = - MultiplierOf::::new(5u8).unwrap().calculate_vesting_duration::(); + MultiplierOf::::try_from(5u8).unwrap().calculate_vesting_duration::(); let now = inst.current_block(); inst.jump_to_block(now + vest_duration + 1u64); inst.execute(|| { @@ -994,16 +994,16 @@ mod bid_extrinsic { inst.execute(|| { assert_noop!( - PolimecFunding::do_bid( - &BIDDER_2, - 0, - 1, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, + PolimecFunding::do_bid(DoBidParams:: { + bidder: BIDDER_2, + project_id: 0, + ct_amount: 1, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, did, investor_type, - project_metadata.clone().policy_ipfs_cid.unwrap(), - ), + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + }), Error::::IncorrectRound ); }); @@ -1244,32 +1244,32 @@ mod bid_extrinsic { // bid below 800 CT (8k USD) should fail for professionals inst.execute(|| { assert_noop!( - Pallet::::do_bid( - &BIDDER_1, + Pallet::::do_bid(DoBidParams:: { + bidder: BIDDER_1, project_id, - 799 * CT_UNIT, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(BIDDER_1), - InvestorType::Professional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - ), + ct_amount: 799 * CT_UNIT, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(BIDDER_1), + investor_type: InvestorType::Professional, + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + }), Error::::TooLow ); }); // bid below 2000 CT (20k USD) should fail for institutionals inst.execute(|| { assert_noop!( - Pallet::::do_bid( - &BIDDER_2, + Pallet::::do_bid(DoBidParams:: { + bidder: BIDDER_2, project_id, - 1999 * CT_UNIT, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(BIDDER_1), - InvestorType::Institutional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - ), + ct_amount: 1999 * CT_UNIT, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(BIDDER_1), + investor_type: InvestorType::Institutional, + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + }), Error::::TooLow ); }); @@ -1327,16 +1327,16 @@ mod bid_extrinsic { .unwrap() + 1; assert!(smallest_ct_amount_at_8k_usd < 8000 * CT_UNIT); inst.execute(|| { - assert_ok!(Pallet::::do_bid( - &BIDDER_1, + assert_ok!(Pallet::::do_bid(DoBidParams:: { + bidder: BIDDER_2, project_id, - smallest_ct_amount_at_8k_usd, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(BIDDER_1), - InvestorType::Professional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - )); + ct_amount: smallest_ct_amount_at_8k_usd, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(BIDDER_1), + investor_type: InvestorType::Professional, + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + })); }); let smallest_ct_amount_at_20k_usd = bucket_increase_price .reciprocal() @@ -1346,16 +1346,16 @@ mod bid_extrinsic { .unwrap() + 1; assert!(smallest_ct_amount_at_20k_usd < 20_000 * CT_UNIT); inst.execute(|| { - assert_ok!(Pallet::::do_bid( - &BIDDER_2, + assert_ok!(Pallet::::do_bid(DoBidParams:: { + bidder: BIDDER_3, project_id, - smallest_ct_amount_at_20k_usd, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(BIDDER_1), - InvestorType::Institutional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - )); + ct_amount: smallest_ct_amount_at_20k_usd, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(BIDDER_1), + investor_type: InvestorType::Institutional, + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + })); }); } @@ -1497,16 +1497,16 @@ mod bid_extrinsic { let project_id = inst.create_auctioning_project(project_metadata.clone(), ISSUER_1, None, default_evaluations()); assert_err!( - inst.execute(|| crate::Pallet::::do_bid( - &(&ISSUER_1 + 1), + inst.execute(|| crate::Pallet::::do_bid(DoBidParams:: { + bidder: ISSUER_1, project_id, - 500 * CT_UNIT, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(ISSUER_1), - InvestorType::Institutional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - )), + ct_amount: 5000 * CT_UNIT, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(ISSUER_1), + investor_type: InvestorType::Professional, + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + })), Error::::ParticipationToOwnProject ); } @@ -1523,16 +1523,16 @@ mod bid_extrinsic { let investor_type = InvestorType::Institutional; let outcome = inst.execute(|| { - Pallet::::do_bid( - &bids[0].bidder, + Pallet::::do_bid(DoBidParams:: { + bidder: bids[0].bidder, project_id, - bids[0].amount, - bids[0].multiplier, - bids[0].asset, + ct_amount: bids[0].amount, + multiplier: bids[0].multiplier, + funding_asset: bids[0].asset, did, investor_type, - project_metadata.clone().policy_ipfs_cid.unwrap(), - ) + whitelisted_policy: project_metadata.clone().policy_ipfs_cid.unwrap(), + }) }); frame_support::assert_err!(outcome, Error::::FundingAssetNotAccepted); } @@ -1657,7 +1657,6 @@ mod end_auction_extrinsic { assert!(matches!(inst.go_to_next_state(project_id), ProjectStatus::CommunityRound(..))); let project_details = inst.get_project_details(project_id); - dbg!(&project_details); let token_price = inst.get_project_details(project_id).weighted_average_price.unwrap(); let normalized_wap = PriceProviderOf::::convert_back_to_normal_price(token_price, USD_DECIMALS, CT_DECIMALS) diff --git a/pallets/funding/src/tests/4_contribution.rs b/pallets/funding/src/tests/4_contribution.rs index 67c003c71..29f8cd79f 100644 --- a/pallets/funding/src/tests/4_contribution.rs +++ b/pallets/funding/src/tests/4_contribution.rs @@ -965,7 +965,7 @@ mod contribute_extrinsic { assert_eq!(frozen_balance, frozen_amount); let vest_duration = - MultiplierOf::::new(5u8).unwrap().calculate_vesting_duration::(); + MultiplierOf::::try_from(5u8).unwrap().calculate_vesting_duration::(); let now = inst.current_block(); inst.jump_to_block(now + vest_duration + 1u64); inst.execute(|| { @@ -1107,16 +1107,16 @@ mod contribute_extrinsic { default_bids(), ); assert_err!( - inst.execute(|| crate::Pallet::::do_contribute( - &(&ISSUER_1 + 1), + inst.execute(|| crate::Pallet::::do_contribute(DoContributeParams:: { + contributor: ISSUER_1, project_id, - 500 * CT_UNIT, - 1u8.try_into().unwrap(), - AcceptedFundingAsset::USDT, - generate_did_from_account(ISSUER_1), - InvestorType::Institutional, - project_metadata.clone().policy_ipfs_cid.unwrap(), - )), + ct_amount: 500 * CT_UNIT, + multiplier: 1u8.try_into().unwrap(), + funding_asset: AcceptedFundingAsset::USDT, + did: generate_did_from_account(ISSUER_1), + investor_type: InvestorType::Institutional, + whitelisted_policy: project_metadata.policy_ipfs_cid.unwrap(), + })), Error::::ParticipationToOwnProject ); } diff --git a/pallets/funding/src/tests/5_funding_end.rs b/pallets/funding/src/tests/5_funding_end.rs index 2accd6cb6..4b28497bc 100644 --- a/pallets/funding/src/tests/5_funding_end.rs +++ b/pallets/funding/src/tests/5_funding_end.rs @@ -36,7 +36,6 @@ mod round_flow { ); let wap = inst.get_project_details(project_id).weighted_average_price.unwrap(); - dbg!(wap); assert!(wap > project_metadata.minimum_price); } } @@ -99,7 +98,6 @@ mod end_funding_extrinsic { fn evaluator_outcome_bounds() { let try_for_percentage = |percentage: u8, should_slash: bool| { let (mut inst, project_id) = create_project_with_funding_percentage(percentage.into(), true); - dbg!(percentage); if should_slash { assert_eq!( inst.get_project_details(project_id).status, @@ -190,7 +188,6 @@ mod end_funding_extrinsic { let funding_threshold: u128 = funding_threshold.deconstruct() as u128 * 100u128 / Perquintill::ACCURACY as u128; - dbg!(funding_threshold); let (mut inst, project_id) = create_project_with_funding_percentage(funding_threshold as u64 - 1, true); assert_eq!( inst.get_project_details(project_id).status, diff --git a/pallets/funding/src/tests/6_settlement.rs b/pallets/funding/src/tests/6_settlement.rs index 83b640c6d..4ce66fc91 100644 --- a/pallets/funding/src/tests/6_settlement.rs +++ b/pallets/funding/src/tests/6_settlement.rs @@ -281,7 +281,6 @@ mod settle_evaluation_extrinsic { Some(EvaluatorsOutcomeOf::::Slashed) ); - dbg!(inst.get_project_details(project_id).status); assert_ok!(inst.execute(|| PolimecFunding::settle_evaluation( RuntimeOrigin::signed(evaluator), project_id, diff --git a/pallets/funding/src/tests/misc.rs b/pallets/funding/src/tests/misc.rs index a7550667d..456cee4c1 100644 --- a/pallets/funding/src/tests/misc.rs +++ b/pallets/funding/src/tests/misc.rs @@ -337,31 +337,31 @@ mod inner_functions { let default_multiplier_duration = default_multiplier.calculate_vesting_duration::(); assert_eq!(default_multiplier_duration, 1u64); - let multiplier_1 = MultiplierOf::::new(1u8).unwrap(); + let multiplier_1 = MultiplierOf::::try_from(1u8).unwrap(); let multiplier_1_duration = multiplier_1.calculate_vesting_duration::(); assert_eq!(multiplier_1_duration, 1u64); - let multiplier_2 = MultiplierOf::::new(2u8).unwrap(); + let multiplier_2 = MultiplierOf::::try_from(2u8).unwrap(); let multiplier_2_duration = multiplier_2.calculate_vesting_duration::(); assert_eq!(multiplier_2_duration, FixedU128::from_rational(2167, 1000).saturating_mul_int((DAYS * 7) as u64)); - let multiplier_3 = MultiplierOf::::new(3u8).unwrap(); + let multiplier_3 = MultiplierOf::::try_from(3u8).unwrap(); let multiplier_3_duration = multiplier_3.calculate_vesting_duration::(); assert_eq!(multiplier_3_duration, FixedU128::from_rational(4334, 1000).saturating_mul_int((DAYS * 7) as u64)); - let multiplier_19 = MultiplierOf::::new(19u8).unwrap(); + let multiplier_19 = MultiplierOf::::try_from(19u8).unwrap(); let multiplier_19_duration = multiplier_19.calculate_vesting_duration::(); assert_eq!(multiplier_19_duration, FixedU128::from_rational(39006, 1000).saturating_mul_int((DAYS * 7) as u64)); - let multiplier_20 = MultiplierOf::::new(20u8).unwrap(); + let multiplier_20 = MultiplierOf::::try_from(20u8).unwrap(); let multiplier_20_duration = multiplier_20.calculate_vesting_duration::(); assert_eq!(multiplier_20_duration, FixedU128::from_rational(41173, 1000).saturating_mul_int((DAYS * 7) as u64)); - let multiplier_24 = MultiplierOf::::new(24u8).unwrap(); + let multiplier_24 = MultiplierOf::::try_from(24u8).unwrap(); let multiplier_24_duration = multiplier_24.calculate_vesting_duration::(); assert_eq!(multiplier_24_duration, FixedU128::from_rational(49841, 1000).saturating_mul_int((DAYS * 7) as u64)); - let multiplier_25 = MultiplierOf::::new(25u8).unwrap(); + let multiplier_25 = MultiplierOf::::try_from(25u8).unwrap(); let multiplier_25_duration = multiplier_25.calculate_vesting_duration::(); assert_eq!(multiplier_25_duration, FixedU128::from_rational(52008, 1000).saturating_mul_int((DAYS * 7) as u64)); } diff --git a/pallets/funding/src/tests/runtime_api.rs b/pallets/funding/src/tests/runtime_api.rs index e0c20bc45..1b0119d6f 100644 --- a/pallets/funding/src/tests/runtime_api.rs +++ b/pallets/funding/src/tests/runtime_api.rs @@ -430,8 +430,6 @@ fn funding_asset_to_ct_amount() { let current_bucket = inst.execute(|| Buckets::::get(project_id_3).unwrap()); assert_eq!(current_bucket.current_price, decimal_aware_expected_price); - dbg!(current_bucket.current_price.saturating_mul_int(current_bucket.amount_left)); - let dot_amount: u128 = 217_0_000_000_000; let expected_ct_amount: u128 = 935_812_500_000_000_000; @@ -600,7 +598,6 @@ fn all_project_participations_by_did() { let block_hash = System::block_hash(System::block_number()); let items = TestRuntime::all_project_participations_by_did(&TestRuntime, block_hash, project_id, did_user).unwrap(); - dbg!(items); }); } @@ -701,7 +698,7 @@ fn projects_by_did() { inst.execute(|| { let projects = ProjectsDetails::::iter().collect_vec(); - dbg!(projects); + let block_hash = System::block_hash(System::block_number()); let project_ids = TestRuntime::projects_by_did(&TestRuntime, block_hash, did_user).unwrap(); assert_eq!(project_ids, vec![project_id_1, project_id_3]); diff --git a/pallets/funding/src/traits.rs b/pallets/funding/src/traits.rs index 932c26a07..94af27f2d 100644 --- a/pallets/funding/src/traits.rs +++ b/pallets/funding/src/traits.rs @@ -24,7 +24,7 @@ use sp_arithmetic::{ use sp_runtime::DispatchError; pub trait BondingRequirementCalculation { - fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Result, ()>; + fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Option>; } pub trait VestingDurationCalculation { diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index 30159362b..72964d05d 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -19,25 +19,27 @@ //! Types for Funding pallet. use crate::{traits::BondingRequirementCalculation, BalanceOf}; -pub use config_types::*; +pub use config::*; +pub use extrinsic::*; use frame_support::{pallet_prelude::*, traits::tokens::Balance as BalanceT}; use frame_system::pallet_prelude::BlockNumberFor; -pub use inner_types::*; +pub use inner::*; +use parachains_common::DAYS; use polimec_common::USD_DECIMALS; use polkadot_parachain_primitives::primitives::Id as ParaId; use serde::{Deserialize, Serialize}; -use sp_arithmetic::{FixedPointNumber, FixedPointOperand, Percent}; -use sp_runtime::traits::{CheckedDiv, CheckedMul, One}; +use sp_arithmetic::{traits::Saturating, FixedPointNumber, FixedPointOperand, FixedU128, Percent}; +use sp_runtime::traits::{CheckedDiv, CheckedMul, Convert, One}; use sp_std::{cmp::Eq, prelude::*}; -pub use storage_types::*; +pub use storage::*; -pub mod config_types { - use parachains_common::DAYS; - use sp_arithmetic::{traits::Saturating, FixedU128}; - use sp_runtime::traits::{Convert, One}; +use crate::{traits::VestingDurationCalculation, Config}; - use crate::{traits::VestingDurationCalculation, Config}; +use sp_runtime::traits::Zero; +use variant_count::VariantCount; +pub mod config { + #[allow(clippy::wildcard_imports)] use super::*; #[derive( @@ -58,28 +60,15 @@ pub mod config_types { pub struct Multiplier(u8); impl Multiplier { - /// Creates a new `Multiplier` if the value is between 1 and 25, otherwise returns an error. - pub const fn new(x: u8) -> Result { - // The minimum and maximum values are chosen to be 1 and 25 respectively, as defined in the Knowledge Hub. - const MIN_VALID: u8 = 1; - const MAX_VALID: u8 = 25; - - if x >= MIN_VALID && x <= MAX_VALID { - Ok(Self(x)) - } else { - Err(()) - } - } - pub const fn force_new(x: u8) -> Self { Self(x) } } impl BondingRequirementCalculation for Multiplier { - fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Result, ()> { + fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Option> { let balance_multiplier = BalanceOf::::from(self.0); - ticket_size.checked_div(&balance_multiplier).ok_or(()) + ticket_size.checked_div(&balance_multiplier) } } @@ -104,16 +93,24 @@ pub mod config_types { } impl TryFrom for Multiplier { - type Error = (); + type Error = &'static str; - fn try_from(x: u8) -> Result { - Self::new(x) + fn try_from(x: u8) -> Result { + // The minimum and maximum values are chosen to be 1 and 25 respectively, as defined in the Knowledge Hub. + const MIN_VALID: u8 = 1; + const MAX_VALID: u8 = 25; + + if (MIN_VALID..=MAX_VALID).contains(&x) { + Ok(Self(x)) + } else { + Err("u8 outside the allowed multiplier range") + } } } - impl Into for Multiplier { - fn into(self) -> u8 { - self.0 + impl From for u8 { + fn from(val: Multiplier) -> Self { + val.0 } } @@ -154,9 +151,9 @@ pub mod config_types { pub const INSTITUTIONAL_MAX_MULTIPLIER: u8 = 25u8; } -pub mod storage_types { +pub mod storage { + #[allow(clippy::wildcard_imports)] use super::*; - use sp_runtime::traits::Zero; #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo, Serialize, Deserialize)] pub struct ProjectMetadata { @@ -504,19 +501,17 @@ pub mod storage_types { let sum = bucket_sizes.iter().map(|x| x.0).fold(Balance::zero(), |acc, x| acc.saturating_add(x)); - let wap = bucket_sizes + bucket_sizes .into_iter() .map(|x| ::saturating_from_rational(x.0, sum).saturating_mul(x.1)) - .fold(Price::zero(), |acc: Price, p: Price| acc.saturating_add(p)); - - return wap + .fold(Price::zero(), |acc: Price, p: Price| acc.saturating_add(p)) } } } -pub mod inner_types { +pub mod inner { + #[allow(clippy::wildcard_imports)] use super::*; - use variant_count::VariantCount; pub enum MetadataError { /// The minimum price per token is too low. @@ -833,3 +828,68 @@ pub mod inner_types { pub migration_origins: MigrationOrigins, } } + +pub mod extrinsic { + use crate::{ + AcceptedFundingAsset, AccountIdOf, BalanceOf, Config, MultiplierOf, PriceOf, ProjectDetailsOf, ProjectId, + TicketSizeOf, + }; + use frame_system::pallet_prelude::BlockNumberFor; + use polimec_common::credentials::{Cid, Did, InvestorType}; + + pub struct DoBidParams { + pub bidder: AccountIdOf, + pub project_id: ProjectId, + pub ct_amount: BalanceOf, + pub multiplier: MultiplierOf, + pub funding_asset: AcceptedFundingAsset, + pub did: Did, + pub investor_type: InvestorType, + pub whitelisted_policy: Cid, + } + + pub struct DoPerformBidParams { + pub bidder: AccountIdOf, + pub project_id: ProjectId, + pub ct_amount: BalanceOf, + pub ct_usd_price: PriceOf, + pub multiplier: MultiplierOf, + pub funding_asset: AcceptedFundingAsset, + pub bid_id: u32, + pub now: BlockNumberFor, + pub did: Did, + pub metadata_ticket_size_bounds: TicketSizeOf, + pub total_bids_by_bidder: u32, + pub total_bids_for_project: u32, + } + + pub struct DoContributeParams { + pub contributor: AccountIdOf, + pub project_id: ProjectId, + pub ct_amount: BalanceOf, + pub multiplier: MultiplierOf, + pub funding_asset: AcceptedFundingAsset, + pub did: Did, + pub investor_type: InvestorType, + pub whitelisted_policy: Cid, + } + + pub struct DoPerformContributionParams<'a, T: Config> { + pub contributor: AccountIdOf, + pub project_id: ProjectId, + pub project_details: &'a mut ProjectDetailsOf, + pub buyable_tokens: BalanceOf, + pub multiplier: MultiplierOf, + pub funding_asset: AcceptedFundingAsset, + pub investor_type: InvestorType, + pub did: Did, + pub whitelisted_policy: Cid, + } + + pub struct BidRefund { + pub final_ct_usd_price: PriceOf, + pub final_ct_amount: BalanceOf, + pub refunded_plmc: BalanceOf, + pub refunded_funding_asset_amount: BalanceOf, + } +} diff --git a/pallets/linear-release/Cargo.toml b/pallets/linear-release/Cargo.toml index 07879f547..7cc437dc4 100644 --- a/pallets/linear-release/Cargo.toml +++ b/pallets/linear-release/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/linear-release/src/impls.rs b/pallets/linear-release/src/impls.rs index 6ad347ac0..bb89b643a 100644 --- a/pallets/linear-release/src/impls.rs +++ b/pallets/linear-release/src/impls.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +#[allow(clippy::wildcard_imports)] use super::*; impl Pallet { @@ -21,9 +22,9 @@ impl Pallet { // NOTE: We assume both schedules have had funds unlocked up through the current block. pub fn merge_vesting_info( now: BlockNumberFor, - schedule1: VestingInfo, BlockNumberFor>, - schedule2: VestingInfo, BlockNumberFor>, - ) -> Option, BlockNumberFor>> { + schedule1: VestingInfoOf, + schedule2: VestingInfoOf, + ) -> Option> { let schedule1_ending_block = schedule1.ending_block_as_balance::(); let schedule2_ending_block = schedule2.ending_block_as_balance::(); let now_as_balance = T::BlockNumberToBalance::convert(now); @@ -66,7 +67,7 @@ impl Pallet { pub fn do_vested_transfer( source: AccountIdOf, target: AccountIdOf, - schedule: VestingInfo, BlockNumberFor>, + schedule: VestingInfoOf, reason: ReasonOf, ) -> DispatchResult { // Validate user inputs. @@ -120,9 +121,9 @@ impl Pallet { /// /// NOTE: the amount locked does not include any schedules that are filtered out via `action`. pub fn report_schedule_updates( - schedules: Vec, BlockNumberFor>>, + schedules: Vec>, action: VestingAction, - ) -> (Vec, BlockNumberFor>>, BalanceOf) { + ) -> (Vec>, BalanceOf) { let now = >::block_number(); let mut total_releasable: BalanceOf = Zero::zero(); @@ -163,10 +164,10 @@ impl Pallet { /// Write an accounts updated vesting schedules to storage. pub fn write_vesting_schedule( who: &T::AccountId, - schedules: Vec, BlockNumberFor>>, + schedules: Vec>, reason: ReasonOf, ) -> Result<(), DispatchError> { - let schedules: BoundedVec, BlockNumberFor>, MaxVestingSchedulesGet> = + let schedules: BoundedVec, MaxVestingSchedulesGet> = schedules.try_into().map_err(|_| Error::::AtMaxVestingSchedules)?; if schedules.len() == 0 { @@ -192,9 +193,9 @@ impl Pallet { /// Execute a `VestingAction` against the given `schedules`. Returns the updated schedules /// and locked amount. pub fn exec_action( - schedules: Vec, BlockNumberFor>>, + schedules: Vec>, action: VestingAction, - ) -> Result<(Vec, BlockNumberFor>>, BalanceOf), DispatchError> { + ) -> Result<(Vec>, BalanceOf), DispatchError> { let (schedules, locked_now) = match action { VestingAction::Merge { index1: idx1, index2: idx2 } => { // The schedule index is based off of the schedule ordering prior to filtering out diff --git a/pallets/linear-release/src/lib.rs b/pallets/linear-release/src/lib.rs index 86ffb8c02..9b0298b94 100644 --- a/pallets/linear-release/src/lib.rs +++ b/pallets/linear-release/src/lib.rs @@ -16,6 +16,9 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] +#![allow(clippy::type_complexity)] mod benchmarking; pub mod weights; @@ -25,19 +28,15 @@ use frame_support::{ ensure, pallet_prelude::*, traits::{ - fungible::*, + fungible::{BalancedHold, Inspect, InspectHold, Mutate, MutateHold}, tokens::{Balance, Precision}, Get, WithdrawReasons, }, }; use frame_system::pallet_prelude::*; -use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +use parity_scale_codec::MaxEncodedLen; use polimec_common::ReleaseSchedule; -use scale_info::TypeInfo; -use sp_runtime::{ - traits::{AtLeast32BitUnsigned, Bounded, Convert, One, Saturating, Zero}, - RuntimeDebug, -}; +use sp_runtime::traits::{Convert, One, Saturating, Zero}; use sp_std::{marker::PhantomData, prelude::*}; // Re-export pallet items so that they can be accessed from the crate namespace. @@ -60,6 +59,7 @@ mod types; pub type BalanceOf = ::Balance; pub type ReasonOf = ::RuntimeHoldReason; pub type AccountIdOf = ::AccountId; +pub type VestingInfoOf = VestingInfo, BlockNumberFor>; /// Actions to take against a user's `Vesting` storage entry. #[derive(Clone, Copy)] @@ -85,8 +85,8 @@ impl VestingAction { /// Pick the schedules that this action dictates should continue vesting undisturbed. fn pick_schedules( &self, - schedules: Vec, BlockNumberFor>>, - ) -> impl Iterator, BlockNumberFor>> + '_ { + schedules: Vec>, + ) -> impl Iterator> + '_ { schedules.into_iter().enumerate().filter_map( move |(index, schedule)| { if self.should_remove(index) { @@ -110,6 +110,7 @@ impl Get for MaxVestingSchedulesGet { /// Enable `dev_mode` for this pallet. #[frame_support::pallet(dev_mode)] pub mod pallet { + #[allow(clippy::wildcard_imports)] use super::*; #[pallet::config] @@ -213,7 +214,7 @@ pub mod pallet { AccountIdOf, Blake2_128Concat, ReasonOf, - BoundedVec, BlockNumberFor>, MaxVestingSchedulesGet>, + BoundedVec, MaxVestingSchedulesGet>, >; #[pallet::call] @@ -274,7 +275,7 @@ pub mod pallet { pub fn vested_transfer( origin: OriginFor, target: AccountIdOf, - schedule: VestingInfo, BlockNumberFor>, + schedule: VestingInfoOf, reason: ReasonOf, ) -> DispatchResult { let transactor = ensure_signed(origin)?; @@ -301,7 +302,7 @@ pub mod pallet { origin: OriginFor, source: AccountIdOf, target: AccountIdOf, - schedule: VestingInfo, BlockNumberFor>, + schedule: VestingInfoOf, reason: ReasonOf, ) -> DispatchResult { ensure_root(origin)?; diff --git a/pallets/linear-release/src/tests.rs b/pallets/linear-release/src/tests.rs index 901e860b3..d5d81baa9 100644 --- a/pallets/linear-release/src/tests.rs +++ b/pallets/linear-release/src/tests.rs @@ -125,9 +125,9 @@ fn check_vesting_status_for_multi_schedule_account() { assert_eq!(Balances::balance_on_hold(&MockRuntimeHoldReason::Reason, &2), 20 * ED); assert_ok!(Vesting::vested_transfer(Some(4).into(), 2, sched1, MockRuntimeHoldReason::Reason)); assert_eq!(Balances::balance_on_hold(&MockRuntimeHoldReason::Reason, &2), 29 * ED); // Why 29 and not 30? Because sched1 is already unlocking. - // Free balance is the one set in Genesis inside the Balances pallet - // + the one from the vested transfer. - // BUT NOT the one in sched0, since the vesting will start at block #10. + // Free balance is the one set in Genesis inside the Balances pallet + // + the one from the vested transfer. + // BUT NOT the one in sched0, since the vesting will start at block #10. let balance = Balances::balance(&2); assert_eq!(balance, ED * (2)); // The most recently added schedule exists. @@ -193,7 +193,7 @@ fn unvested_balance_should_not_transfer() { ExtBuilder::default().existential_deposit(10).build().execute_with(|| { let user1_free_balance = Balances::free_balance(1); assert_eq!(user1_free_balance, 50); // Account 1 has free balance - // Account 1 has only 5 units vested at block 1 (plus 50 unvested) + // Account 1 has only 5 units vested at block 1 (plus 50 unvested) assert_eq!(Vesting::vesting_balance(&1, MockRuntimeHoldReason::Reason), Some(5)); // Account 1 cannot send more than vested amount... assert_noop!(Balances::transfer_allow_death(Some(1).into(), 2, 56), TokenError::FundsUnavailable); }); @@ -205,13 +205,13 @@ fn vested_balance_should_transfer() { assert_eq!(System::block_number(), 1); let user1_free_balance = Balances::free_balance(1); assert_eq!(user1_free_balance, 50); // Account 1 has free balance - // Account 1 has only 5 units vested at block 1 (plus 50 unvested) + // Account 1 has only 5 units vested at block 1 (plus 50 unvested) assert_eq!(Vesting::vesting_balance(&1, MockRuntimeHoldReason::Reason), Some(5)); assert_noop!(Balances::transfer_allow_death(Some(1).into(), 2, 45), TokenError::Frozen); // Account 1 free balance - ED is < 45 assert_ok!(Vesting::vest(Some(1).into(), MockRuntimeHoldReason::Reason)); let user1_free_balance = Balances::free_balance(1); assert_eq!(user1_free_balance, 55); // Account 1 has free balance - // Account 1 has vested 1 unit at block 1 (plus 50 unvested) + // Account 1 has vested 1 unit at block 1 (plus 50 unvested) assert_ok!(Balances::transfer_allow_death(Some(1).into(), 2, 45)); // After the vest it can now send the 45 UNIT }); } @@ -259,7 +259,7 @@ fn vested_balance_should_transfer_using_vest_other() { ExtBuilder::default().existential_deposit(10).build().execute_with(|| { let user1_free_balance = Balances::free_balance(1); assert_eq!(user1_free_balance, 50); // Account 1 has free balance - // Account 1 has only 5 units vested at block 1 (plus 50 unvested) + // Account 1 has only 5 units vested at block 1 (plus 50 unvested) assert_eq!(Vesting::vesting_balance(&1, MockRuntimeHoldReason::Reason), Some(5)); assert_ok!(Vesting::vest_other(Some(2).into(), 1, MockRuntimeHoldReason::Reason)); assert_ok!(Balances::transfer_allow_death(Some(1).into(), 2, 55 - 10)); @@ -317,7 +317,7 @@ fn extra_balance_should_transfer() { // Account 2 has no units vested at block 1, but gained 100 assert_ok!(Balances::transfer_allow_death(Some(2).into(), 3, 100 - 10)); // Account 2 can send extra - // units gained + // units gained }); } @@ -327,7 +327,7 @@ fn liquid_funds_should_transfer_with_delayed_vesting() { let user12_free_balance = Balances::free_balance(12); assert_eq!(user12_free_balance, 1280); // Account 12 has free balance - // Account 12 has liquid funds + // Account 12 has liquid funds assert_eq!(Vesting::vesting_balance(&12, MockRuntimeHoldReason::Reason), Some(0)); // Account 12 has delayed vesting diff --git a/pallets/linear-release/src/types.rs b/pallets/linear-release/src/types.rs index afdb779bc..09ca6e6ac 100644 --- a/pallets/linear-release/src/types.rs +++ b/pallets/linear-release/src/types.rs @@ -14,7 +14,25 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::*; +use sp_runtime::traits::Zero; + +use sp_runtime::traits::Convert; + +use sp_runtime::traits::One; + +use sp_runtime::traits::Bounded; + +use sp_runtime::traits::AtLeast32BitUnsigned; + +use frame_support::pallet_prelude::TypeInfo; + +use frame_support::pallet_prelude::MaxEncodedLen; + +use frame_support::pallet_prelude::RuntimeDebug; + +use frame_support::pallet_prelude::Decode; + +use frame_support::pallet_prelude::Encode; /// Struct to encode the vesting schedule of an individual account. #[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)] diff --git a/pallets/oracle-ocw/Cargo.toml b/pallets/oracle-ocw/Cargo.toml index ac25baf86..84a11f701 100644 --- a/pallets/oracle-ocw/Cargo.toml +++ b/pallets/oracle-ocw/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/oracle-ocw/src/crypto.rs b/pallets/oracle-ocw/src/crypto.rs index 7c827bef3..5881d5923 100644 --- a/pallets/oracle-ocw/src/crypto.rs +++ b/pallets/oracle-ocw/src/crypto.rs @@ -35,16 +35,16 @@ mod app_sr25519 { pub type AuthorityId = app_sr25519::Public; -pub struct PolimecCrypto; +pub struct Polimec; -impl frame_system::offchain::AppCrypto for PolimecCrypto { +impl frame_system::offchain::AppCrypto for Polimec { type GenericPublic = sp_core::sr25519::Public; type GenericSignature = sp_core::sr25519::Signature; type RuntimeAppPublic = AuthorityId; } // implemented for mock runtime in test -impl frame_system::offchain::AppCrypto<::Signer, Sr25519Signature> for PolimecCrypto { +impl frame_system::offchain::AppCrypto<::Signer, Sr25519Signature> for Polimec { type GenericPublic = sp_core::sr25519::Public; type GenericSignature = sp_core::sr25519::Signature; type RuntimeAppPublic = AuthorityId; diff --git a/pallets/oracle-ocw/src/lib.rs b/pallets/oracle-ocw/src/lib.rs index c39de5abc..0138759d3 100644 --- a/pallets/oracle-ocw/src/lib.rs +++ b/pallets/oracle-ocw/src/lib.rs @@ -16,6 +16,9 @@ //! Offchain Worker for Oracle price feed #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] + use crate::{ traits::FetchPrice, types::{ @@ -24,10 +27,20 @@ use crate::{ }, }; use core::ops::Rem; -use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SendSignedTransaction, Signer}; +use frame_support::{pallet_prelude::*, traits::Contains}; +use frame_system::{ + offchain::{AppCrypto, CreateSignedTransaction, SendSignedTransaction, Signer, SigningTypes}, + pallet_prelude::*, +}; +use orml_oracle::Call as OracleCall; pub use pallet::*; use sp_runtime::{ - traits::{Convert, Saturating, Zero}, + offchain::{ + storage::{StorageRetrievalError, StorageValueRef}, + storage_lock::{StorageLock, Time}, + Duration, + }, + traits::{Convert, IdentifyAccount, Saturating, Zero}, FixedU128, RuntimeAppPublic, }; use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec}; @@ -47,18 +60,8 @@ pub(crate) const NUMBER_OF_CANDLES: usize = 15; #[frame_support::pallet] pub mod pallet { + #[allow(clippy::wildcard_imports)] use super::*; - use frame_support::{pallet_prelude::*, traits::Contains}; - use frame_system::{offchain::SigningTypes, pallet_prelude::*}; - use orml_oracle::Call as OracleCall; - use sp_runtime::{ - offchain::{ - storage::{StorageRetrievalError, StorageValueRef}, - storage_lock::{StorageLock, Time}, - Duration, - }, - traits::{IdentifyAccount, Zero}, - }; const LOCK_TIMEOUT_EXPIRATION: u64 = 30_000; // 30 seconds @@ -151,10 +154,10 @@ pub mod pallet { (AssetName::PLMC, Zero::zero()), ]), }; + // Fix for missing PLMC in last_send_for_assets for old nodes, that did not have PLMC in the list. - if !last_send_for_assets.contains_key(&AssetName::PLMC) { - last_send_for_assets.insert(AssetName::PLMC, Zero::zero()); - }; + last_send_for_assets.entry(AssetName::PLMC).or_insert_with(Zero::zero); + let assets = last_send_for_assets .iter() .filter_map(|(asset_name, last_send)| { @@ -254,11 +257,11 @@ pub mod pallet { match result { Some((_, Ok(_))) => { log::trace!(target: LOG_TARGET, "offchain tx sent successfully"); - return Ok(()); + Ok(()) }, _ => { log::trace!(target: LOG_TARGET, "failure: offchain_signed_tx"); - return Err(()); + Err(()) }, } } diff --git a/pallets/oracle-ocw/src/mock.rs b/pallets/oracle-ocw/src/mock.rs index 6b0f701f4..1c253ba3e 100644 --- a/pallets/oracle-ocw/src/mock.rs +++ b/pallets/oracle-ocw/src/mock.rs @@ -116,7 +116,7 @@ parameter_types! { ]; } impl Config for Test { - type AppCrypto = crate::crypto::PolimecCrypto; + type AppCrypto = crate::crypto::Polimec; type ConvertAssetPricePair = AssetPriceConverter; type FetchInterval = ConstU64<5u64>; type FetchWindow = ConstU64<1u64>; diff --git a/pallets/oracle-ocw/src/traits.rs b/pallets/oracle-ocw/src/traits.rs index 708d3b19e..a09a3555e 100644 --- a/pallets/oracle-ocw/src/traits.rs +++ b/pallets/oracle-ocw/src/traits.rs @@ -13,7 +13,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::*; +use super::{AssetName, AssetRequest, OpenCloseVolume, Vec, Zero}; use sp_runtime::{ offchain::{ diff --git a/pallets/oracle-ocw/src/types.rs b/pallets/oracle-ocw/src/types.rs index 7f8dfcf89..dba09f69d 100644 --- a/pallets/oracle-ocw/src/types.rs +++ b/pallets/oracle-ocw/src/types.rs @@ -13,7 +13,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::*; +use super::{FetchPrice, FixedU128, LOG_TARGET, NUMBER_OF_CANDLES}; use core::{ops::Mul, str::FromStr}; use heapless::{LinearMap, Vec as HVec}; use parity_scale_codec::{Decode, Encode}; @@ -88,7 +88,7 @@ where { let data = HVec::<(u64, &str, &str, &str, &str, &str, &str, u64), 720>::deserialize(deserializer)?; let mut result = Vec::::with_capacity(data.len()); - for row in data.into_iter() { + for row in data { let ocv = OpenCloseVolume::from_str(row.2, row.3, row.4, row.6) .map_err(|_| serde::de::Error::custom("Error parsing float"))?; result.push(ocv); @@ -130,7 +130,7 @@ impl FetchPrice for KrakenFetcher { AssetName::USDT => "https://api.kraken.com/0/public/OHLC?pair=USDTZUSD&interval=1", AssetName::DOT => "https://api.kraken.com/0/public/OHLC?pair=DOTUSD&interval=1", AssetName::USDC => "https://api.kraken.com/0/public/OHLC?pair=USDCUSD&interval=1", - _ => "", + AssetName::PLMC => "", } } } @@ -173,7 +173,7 @@ where let low_str = "low"; let close_str = "close"; let volume_str = "volume"; - for row in data.into_iter() { + for row in data { if !row.contains_key(&high_str) && !row.contains_key(&close_str) && !row.contains_key(&volume_str) { return Err(serde::de::Error::custom("Row does not contain required data")); } @@ -223,7 +223,7 @@ impl FetchPrice for BitStampFetcher { AssetName::USDT => "https://www.bitstamp.net/api/v2/ohlc/usdtusd/?step=60&limit=15", AssetName::DOT => "https://www.bitstamp.net/api/v2/ohlc/dotusd/?step=60&limit=15", AssetName::USDC => "https://www.bitstamp.net/api/v2/ohlc/usdcusd/?step=60&limit=15", - _ => "", + AssetName::PLMC => "", } } } @@ -254,7 +254,6 @@ impl FetchPrice for CoinbaseFetcher { match name { AssetName::USDT => "https://api.exchange.coinbase.com/products/USDT-USD/candles?granularity=60", AssetName::DOT => "https://api.exchange.coinbase.com/products/DOT-USD/candles?granularity=60", - AssetName::USDC => "", _ => "", } } @@ -277,7 +276,7 @@ where { let data = HVec::::deserialize(deserializer)?; let mut result = Vec::::with_capacity(data.len()); - for row in data.into_iter() { + for row in data { let ocv = OpenCloseVolume::from_str(row.h, row.l, row.c, row.v) .map_err(|_| serde::de::Error::custom("Error parsing float"))?; result.push(ocv); diff --git a/pallets/parachain-staking/Cargo.toml b/pallets/parachain-staking/Cargo.toml index 139857441..ef5cafcb0 100644 --- a/pallets/parachain-staking/Cargo.toml +++ b/pallets/parachain-staking/Cargo.toml @@ -10,6 +10,10 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +clippy.all = "allow" +clippy.pedantic = "allow" + [dependencies] serde = { workspace = true } log = { workspace = true } diff --git a/pallets/parachain-staking/src/lib.rs b/pallets/parachain-staking/src/lib.rs index 8dce7dabd..54798f7d2 100644 --- a/pallets/parachain-staking/src/lib.rs +++ b/pallets/parachain-staking/src/lib.rs @@ -49,6 +49,8 @@ //! To leave the set of delegators and revoke all delegations, call `leave_delegators`. #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] mod auto_compound; mod delegation_requests; diff --git a/pallets/polimec-receiver/Cargo.toml b/pallets/polimec-receiver/Cargo.toml index d8fd00c08..c7861f3be 100644 --- a/pallets/polimec-receiver/Cargo.toml +++ b/pallets/polimec-receiver/Cargo.toml @@ -8,6 +8,9 @@ homepage = "https://substrate.io" repository = "https://github.com/paritytech/substrate/" edition = "2021" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/polimec-receiver/src/lib.rs b/pallets/polimec-receiver/src/lib.rs index 89501a452..5365a7ec2 100644 --- a/pallets/polimec-receiver/src/lib.rs +++ b/pallets/polimec-receiver/src/lib.rs @@ -15,6 +15,9 @@ // along with this program. If not, see . #![cfg_attr(not(feature = "std"), no_std)] +// Needed due to empty sections raising the warning +#![allow(unreachable_patterns)] + /// Edit this file to define custom logic or remove it if it is not needed. /// Learn more about FRAME and the core library of Substrate FRAME pallets: /// diff --git a/pallets/xcm-executor/Cargo.toml b/pallets/xcm-executor/Cargo.toml index 39976363e..44c73eca4 100644 --- a/pallets/xcm-executor/Cargo.toml +++ b/pallets/xcm-executor/Cargo.toml @@ -10,6 +10,10 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +clippy.all = "allow" +clippy.pedantic = "allow" + [dependencies] environmental = { version = "1.1.4", default-features = false } parity-scale-codec = { workspace = true, default-features = false, features = ["derive"] } diff --git a/polimec-common/common/Cargo.toml b/polimec-common/common/Cargo.toml index 542e164ad..53dceb579 100644 --- a/polimec-common/common/Cargo.toml +++ b/polimec-common/common/Cargo.toml @@ -10,6 +10,9 @@ readme = "README.md" repository = "https://github.com/Polimec/polimec-node" version.workspace = true +[lints] +workspace = true + [dependencies] parity-scale-codec = { workspace = true, features = ["derive"] } scale-info = { workspace = true, features = ["derive"] } diff --git a/polimec-common/common/src/credentials/mod.rs b/polimec-common/common/src/credentials/mod.rs index 3a73b10ce..df4b5c2f2 100644 --- a/polimec-common/common/src/credentials/mod.rs +++ b/polimec-common/common/src/credentials/mod.rs @@ -36,6 +36,7 @@ pub enum InvestorType { } impl InvestorType { + #[must_use] pub fn as_str(&self) -> &'static str { match self { InvestorType::Retail => "retail", @@ -82,12 +83,14 @@ where ) -> Result { let Some(who) = origin.clone().into_signer() else { return Err(origin) }; let Ok(token) = Self::verify_token(token, verifying_key) else { return Err(origin) }; - let Ok(claims) = Self::extract_claims(&token) else { return Err(origin) }; + let claims = token.claims(); // Get the current timestamp from the pallet_timestamp. It is in milliseconds. let Ok(now) = Now::::get().try_into() else { return Err(origin) }; let Some(date_time) = claims.expiration else { return Err(origin) }; - if claims.custom.subject == who && (date_time.timestamp_millis() as u64) >= now { + let timestamp: u64 = date_time.timestamp_millis().try_into().map_err(|_| origin.clone())?; + + if claims.custom.subject == who && timestamp >= now { return Ok(( who, claims.custom.did.clone(), @@ -100,6 +103,7 @@ where } } +#[allow(clippy::module_name_repetitions)] pub trait EnsureOriginWithCredentials where OuterOrigin: OriginTrait, @@ -121,10 +125,6 @@ where Self::try_origin(origin, token, verifying_key).map_err(|_| BadOrigin) } - fn extract_claims(token: &jwt_compact::Token) -> Result<&StandardClaims, ()> { - Ok(token.claims()) - } - fn verify_token( token: &jwt_compact::UntrustedToken, verifying_key: [u8; 32], diff --git a/polimec-common/common/src/lib.rs b/polimec-common/common/src/lib.rs index 6c302958d..d30a6df2d 100644 --- a/polimec-common/common/src/lib.rs +++ b/polimec-common/common/src/lib.rs @@ -102,8 +102,8 @@ pub trait ReleaseSchedule { } pub mod migration_types { + #[allow(clippy::wildcard_imports)] use super::*; - use xcm::latest::MultiLocation; #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct MigrationOrigin { @@ -164,7 +164,7 @@ pub mod migration_types { } } - #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] + #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, Default)] pub struct Migrations(Vec); impl FromIterator for Migrations { fn from_iter>(iter: T) -> Self { @@ -197,6 +197,10 @@ pub mod migration_types { self.0.len() } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn origins(&self) -> Vec { self.0.iter().map(|migration| migration.origin.clone()).collect() } diff --git a/polimec-common/test-utils/Cargo.toml b/polimec-common/test-utils/Cargo.toml index ef12a7a58..ad7ea3c83 100644 --- a/polimec-common/test-utils/Cargo.toml +++ b/polimec-common/test-utils/Cargo.toml @@ -10,6 +10,9 @@ readme = "README.md" repository = "https://github.com/Polimec/polimec-node" version.workspace = true +[lints] +workspace = true + [dependencies] parity-scale-codec = { workspace = true, features = ["derive"] } jwt-compact = { workspace = true, features = [ diff --git a/polimec-common/test-utils/src/lib.rs b/polimec-common/test-utils/src/lib.rs index a18ab6fb3..2ca6973bc 100644 --- a/polimec-common/test-utils/src/lib.rs +++ b/polimec-common/test-utils/src/lib.rs @@ -46,8 +46,8 @@ pub fn get_test_jwt( .expect("Failed to perform the HTTP GET") .text() .expect("Failed to get the response body (jwt) from the specified endpoint"); - let res = UntrustedToken::new(&jwt).expect("Failed to parse the JWT"); - res + + UntrustedToken::new(&jwt).expect("Failed to parse the JWT") } fn create_jwt( @@ -118,8 +118,8 @@ pub fn get_fake_jwt( .expect("Failed to perform the HTTP GET") .text() .expect("Failed to get the response body (jwt) from the specified endpoint"); - let res = UntrustedToken::new(&jwt).expect("Failed to parse the JWT"); - res + + UntrustedToken::new(&jwt).expect("Failed to parse the JWT") } pub fn generate_did_from_account(account_id: impl Parameter) -> Did { diff --git a/runtimes/polimec/Cargo.toml b/runtimes/polimec/Cargo.toml index 316d919eb..1ef7573a3 100644 --- a/runtimes/polimec/Cargo.toml +++ b/runtimes/polimec/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + [build-dependencies] substrate-wasm-builder.workspace = true diff --git a/runtimes/polimec/build.rs b/runtimes/polimec/build.rs index 657bcc0d1..fcbbf573c 100644 --- a/runtimes/polimec/build.rs +++ b/runtimes/polimec/build.rs @@ -17,5 +17,5 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new().with_current_project().export_heap_base().import_memory().build() + WasmBuilder::new().with_current_project().export_heap_base().import_memory().build(); } diff --git a/runtimes/polimec/src/benchmarks/mod.rs b/runtimes/polimec/src/benchmarks/mod.rs index 33f8b68c9..487e6140b 100644 --- a/runtimes/polimec/src/benchmarks/mod.rs +++ b/runtimes/polimec/src/benchmarks/mod.rs @@ -16,97 +16,68 @@ fn output_max_pallet_funding_values() { let max_evaluations_per_project: u32 = ::MaxEvaluationsPerProject::get(); let create_project = SubstrateWeight::::create_project(); - dbg!(create_project); let remove_project = SubstrateWeight::::remove_project(); - dbg!(remove_project); let edit_project = SubstrateWeight::::edit_project(); - dbg!(edit_project); let start_evaluation = SubstrateWeight::::start_evaluation(1); - dbg!(start_evaluation); let start_auction_manually = SubstrateWeight::::start_auction_manually(1); - dbg!(start_auction_manually); let evaluation = SubstrateWeight::::evaluation(max_evaluations_per_user - 1); - dbg!(evaluation); let bid = SubstrateWeight::::bid(max_bids_per_user, 10); - dbg!(bid); let contribution = SubstrateWeight::::contribution(max_contributions_per_user); - dbg!(contribution); let contribution_ends_round = SubstrateWeight::::contribution_ends_round(max_contributions_per_user - 1, 1); - dbg!(contribution_ends_round); let settle_successful_evaluation = SubstrateWeight::::settle_successful_evaluation(); - dbg!(settle_successful_evaluation); let settle_failed_evaluation = SubstrateWeight::::settle_failed_evaluation(); - dbg!(settle_failed_evaluation); let settle_successful_bid = SubstrateWeight::::settle_successful_bid(); - dbg!(settle_successful_bid); let settle_failed_bid = SubstrateWeight::::settle_failed_bid(); - dbg!(settle_failed_bid); let settle_successful_contribution = SubstrateWeight::::settle_successful_contribution(); - dbg!(settle_successful_contribution); let settle_failed_contribution = SubstrateWeight::::settle_failed_contribution(); - dbg!(settle_failed_contribution); let end_evaluation_success = SubstrateWeight::::end_evaluation_success(1); - dbg!(end_evaluation_success); let end_evaluation_failure = SubstrateWeight::::end_evaluation_failure(1); - dbg!(end_evaluation_failure); let start_auction_closing_phase = SubstrateWeight::::start_auction_closing_phase(1); - dbg!(start_auction_closing_phase); let end_auction_closing = SubstrateWeight::::end_auction_closing(1, max_bids_per_project, 0); - dbg!(end_auction_closing); let start_community_funding = SubstrateWeight::::start_community_funding(1, max_bids_per_project, 0); - dbg!(start_community_funding); let start_remainder_funding = SubstrateWeight::::start_remainder_funding(1); - dbg!(start_remainder_funding); let end_funding_automatically_rejected_evaluators_slashed = SubstrateWeight::::end_funding_automatically_rejected_evaluators_slashed(1); - dbg!(end_funding_automatically_rejected_evaluators_slashed); let end_funding_awaiting_decision_evaluators_slashed = SubstrateWeight::::end_funding_awaiting_decision_evaluators_slashed(1); - dbg!(end_funding_awaiting_decision_evaluators_slashed); let end_funding_awaiting_decision_evaluators_unchanged = SubstrateWeight::::end_funding_awaiting_decision_evaluators_unchanged(1); - dbg!(end_funding_awaiting_decision_evaluators_unchanged); let end_funding_automatically_accepted_evaluators_rewarded = SubstrateWeight::::end_funding_automatically_accepted_evaluators_rewarded( 1, max_evaluations_per_project, ); - dbg!(end_funding_automatically_accepted_evaluators_rewarded); let project_decision = SubstrateWeight::::project_decision(); - dbg!(project_decision); let start_settlement_funding_success = SubstrateWeight::::start_settlement_funding_success(); - dbg!(start_settlement_funding_success); let start_settlement_funding_failure = SubstrateWeight::::start_settlement_funding_failure(); - dbg!(start_settlement_funding_failure); let total_blockspace = ::BlockWeights::get().max_block; - dbg!(total_blockspace); } diff --git a/runtimes/polimec/src/custom_migrations/deposit_dust.rs b/runtimes/polimec/src/custom_migrations/deposit_dust.rs deleted file mode 100644 index 74ff5a4ec..000000000 --- a/runtimes/polimec/src/custom_migrations/deposit_dust.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Polimec Blockchain – https://www.polimec.org/ -// Copyright (C) Polimec 2022. All rights reserved. - -// The Polimec Blockchain is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Polimec Blockchain is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -#[allow(unused_imports)] -use crate::*; - -// Substrate -use frame_support::traits::tokens::Precision::Exact; -#[cfg(feature = "try-runtime")] -use log; - -pub struct DepositDust; -impl frame_support::traits::OnRuntimeUpgrade for DepositDust { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::DispatchError> { - log::info!("Pre-upgrade"); - Ok(Vec::new()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::DispatchError> { - log::info!("Post-upgrade"); - let total_issuance = Balances::total_issuance(); - assert_eq!(total_issuance, 100_000_000 * PLMC); - Ok(()) - } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - // +1 R - let total_issuance = Balances::total_issuance(); - - // Idempotent check. - if total_issuance != 100_000_000 * PLMC { - log::info!("⚠️ Correcting total issuance from {} to {}", total_issuance, 100_000_000 * PLMC); - // +1 R - let treasury_account = BlockchainOperationTreasury::get(); - // +1 W - // The values are coming from these `DustLost` events: - // - https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.polimec.org#/explorer/query/0x6fec4ce782f42afae1437f53e3382d9e6804692de868a28908ed6b9104bdd536 - // - https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.polimec.org#/explorer/query/0x390d04247334df9d9eb02e1dc7c6d01910c950d99a5d8d17441eb202cd751f42 - let _ = >::deposit( - &treasury_account, - 39988334 + 70094167, - Exact, - ); - } - - ::DbWeight::get().reads_writes(2, 1) - } -} diff --git a/runtimes/polimec/src/custom_migrations/init_pallet.rs b/runtimes/polimec/src/custom_migrations/init_pallet.rs index e8ec37872..5903d0c38 100644 --- a/runtimes/polimec/src/custom_migrations/init_pallet.rs +++ b/runtimes/polimec/src/custom_migrations/init_pallet.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#[allow(unused_imports)] -use crate::*; +#![allow(dead_code)] + +use crate::Runtime; use frame_support::traits::{GetStorageVersion, PalletInfoAccess, StorageVersion}; @@ -28,6 +29,13 @@ pub struct InitializePallet + PalletInfoAccess> frame_support::traits::OnRuntimeUpgrade for InitializePallet { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + if Pallet::on_chain_storage_version() == StorageVersion::new(0) { + Pallet::current_storage_version().put::(); + } + ::DbWeight::get().reads_writes(1, 1) + } + #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, DispatchError> { log::info!("{} migrating from {:#?}", Pallet::name(), Pallet::on_chain_storage_version()); @@ -39,11 +47,4 @@ impl + PalletI log::info!("{} migrated to {:#?}", Pallet::name(), Pallet::on_chain_storage_version()); Ok(()) } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - if Pallet::on_chain_storage_version() == StorageVersion::new(0) { - Pallet::current_storage_version().put::(); - } - ::DbWeight::get().reads_writes(1, 1) - } } diff --git a/runtimes/polimec/src/custom_migrations/mod.rs b/runtimes/polimec/src/custom_migrations/mod.rs index 78b2f04e5..e40ad0560 100644 --- a/runtimes/polimec/src/custom_migrations/mod.rs +++ b/runtimes/polimec/src/custom_migrations/mod.rs @@ -17,6 +17,4 @@ // the generated files do not pass clippy #![allow(clippy::all)] -pub mod deposit_dust; pub mod init_pallet; -pub mod unhashed_migration; diff --git a/runtimes/polimec/src/custom_migrations/unhashed_migration.rs b/runtimes/polimec/src/custom_migrations/unhashed_migration.rs deleted file mode 100644 index 0b74932a2..000000000 --- a/runtimes/polimec/src/custom_migrations/unhashed_migration.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Polimec Blockchain – https://www.polimec.org/ -// Copyright (C) Polimec 2022. All rights reserved. - -// The Polimec Blockchain is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Polimec Blockchain is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -#[allow(unused_imports)] -use crate::*; - -// Substrate -use frame_support::storage::unhashed; -use sp_runtime::AccountId32; - -#[cfg(feature = "try-runtime")] -use sp_core::crypto::Ss58Codec; - -#[cfg(feature = "try-runtime")] -use pallet_vesting::Vesting; - -#[cfg(feature = "try-runtime")] -use log; - -// The `VestingInfo` fields from `pallet_vesting` are private, so we need to define them here. -#[derive(parity_scale_codec::Encode, parity_scale_codec::Decode, sp_runtime::RuntimeDebug, Eq, PartialEq)] -struct VestingInfo { - locked: Balance, - per_block: Balance, - starting_block: BlockNumber, -} - -pub struct UnhashedMigration; -impl frame_support::traits::OnRuntimeUpgrade for UnhashedMigration { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::DispatchError> { - log::info!("Pre-upgrade"); - check_balances(); - Ok(Vec::new()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::DispatchError> { - log::info!("Post-upgrade"); - check_balances(); - Ok(()) - } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - // This account received a wrong vesting schedule. - // Hex encoded representation of 5Ag8zhuoZjKzc3YzmkWFrrmU5GvxdHLtpAN425RW9ZgWS5V7. - let acct: AccountId32 = - hex_literal::hex!["c28dbf096b5acf3c0d87dd8ef8cabea0794cc72200a2368751a0fe470d5f9f69"].into(); - - // The vesting.Vesting(5Ag8zhuoZjKzc3YzmkWFrrmU5GvxdHLtpAN425RW9ZgWS5V7) encoded storage key. - const ENCODED_STORAGE_KEY: &str = -"0x5f27b51b5ec208ee9cb25b55d87282435f27b51b5ec208ee9cb25b55d872824334f5503ce555ea3ee18396f4bde1b40bc28dbf096b5acf3c0d87dd8ef8cabea0794cc72200a2368751a0fe470d5f9f69"; - - if let Ok(k) = array_bytes::hex2bytes(ENCODED_STORAGE_KEY) { - // If `is_some` which means it has a vesting schedule, that we could potentially have to correct. - // +1 R - if let Some(value) = unhashed::get::>(&k) { - let v = vec![ - VestingInfo { locked: 119574300000000, per_block: 182000456, starting_block: 249000 }, - VestingInfo { locked: 6485400000000, per_block: 9870000, starting_block: 249000 }, - ]; - // Idempotent check. - if value != v { - log::info!("⚠️ Correcting storage for {:?}", acct.encode()); - // +1 W - unhashed::put::>(&k, &v); - } else { - log::info!("✅ Storage for {:?} is already correct", acct.encode()); - } - } - } - - ::DbWeight::get().reads_writes(1, 1) - } -} - -#[cfg(feature = "try-runtime")] -fn check_balances() { - let acct: AccountId32 = - hex_literal::hex!["c28dbf096b5acf3c0d87dd8ef8cabea0794cc72200a2368751a0fe470d5f9f69"].into(); - let balance = Balances::balance(&acct); - log::info!("Account: {} | Balance: {}", acct.to_ss58check(), balance); - let vesting_stored = >::get(acct.clone()); - if let Some(vesting) = vesting_stored { - log::info!("Vesting: {:?}", vesting); - } else { - log::info!("Vesting: None"); - } - let total_issuance = Balances::total_issuance(); - log::info!("Total Issuance: {}", total_issuance); -} diff --git a/runtimes/polimec/src/lib.rs b/runtimes/polimec/src/lib.rs index 0a3a18e8b..a0fd6ab03 100644 --- a/runtimes/polimec/src/lib.rs +++ b/runtimes/polimec/src/lib.rs @@ -47,6 +47,7 @@ use polimec_common::credentials::{Did, EnsureInvestor}; use polkadot_runtime_common::{ xcm_sender::NoPriceForMessageDelivery, BlockHashCount, CurrencyToVote, SlowAdjustingFeeUpdate, }; +use shared_configuration::proxy; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ @@ -180,7 +181,7 @@ pub type Executive = frame_executive::Executive< /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { - use super::*; + use super::BlockNumber; use sp_runtime::{ generic, traits::{BlakeTwo256, Hash as HashT}, @@ -257,11 +258,11 @@ impl Contains for BaseCallFilter { } } -impl InstanceFilter for ProxyType { +impl InstanceFilter for Type { fn filter(&self, c: &RuntimeCall) -> bool { match self { - ProxyType::Any => true, - ProxyType::NonTransfer => matches!( + proxy::Type::Any => true, + proxy::Type::NonTransfer => matches!( c, RuntimeCall::System(..) | RuntimeCall::ParachainSystem(..) | @@ -283,7 +284,7 @@ impl InstanceFilter for ProxyType { RuntimeCall::Oracle(..) | RuntimeCall::OracleProvidersMembership(..) ), - ProxyType::Governance => matches!( + proxy::Type::Governance => matches!( c, RuntimeCall::Treasury(..) | RuntimeCall::Democracy(..) | @@ -293,10 +294,10 @@ impl InstanceFilter for ProxyType { RuntimeCall::Preimage(..) | RuntimeCall::Scheduler(..) ), - ProxyType::Staking => { + proxy::Type::Staking => { matches!(c, RuntimeCall::ParachainStaking(..)) }, - ProxyType::IdentityJudgement => + proxy::Type::IdentityJudgement => matches!(c, RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })), } } @@ -304,9 +305,9 @@ impl InstanceFilter for ProxyType { fn is_superset(&self, o: &Self) -> bool { match (self, o) { (x, y) if x == y => true, - (ProxyType::Any, _) => true, - (_, ProxyType::Any) => false, - (ProxyType::NonTransfer, _) => true, + (proxy::Type::Any, _) => true, + (_, proxy::Type::Any) => false, + (proxy::Type::NonTransfer, _) => true, _ => false, } } @@ -834,7 +835,7 @@ parameter_types! { } impl pallet_oracle_ocw::Config for Runtime { - type AppCrypto = pallet_oracle_ocw::crypto::PolimecCrypto; + type AppCrypto = pallet_oracle_ocw::crypto::Polimec; type ConvertAssetPricePair = AssetPriceConverter; type FetchInterval = FetchInterval; type FetchWindow = FetchWindow; @@ -941,7 +942,7 @@ impl pallet_proxy::Config for Runtime { type MaxProxies = MaxProxies; type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; - type ProxyType = ProxyType; + type ProxyType = Type; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type WeightInfo = weights::pallet_proxy::WeightInfo; diff --git a/runtimes/shared-configuration/Cargo.toml b/runtimes/shared-configuration/Cargo.toml index 0e72af673..e370204e1 100644 --- a/runtimes/shared-configuration/Cargo.toml +++ b/runtimes/shared-configuration/Cargo.toml @@ -10,6 +10,9 @@ readme.workspace = true repository.workspace = true version.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/runtimes/shared-configuration/src/currency.rs b/runtimes/shared-configuration/src/currency.rs index 2e1b81ad9..133647402 100644 --- a/runtimes/shared-configuration/src/currency.rs +++ b/runtimes/shared-configuration/src/currency.rs @@ -67,10 +67,9 @@ parameter_types! { } pub mod vesting { + use super::{parameter_types, Balance, PLMC}; use frame_support::traits::WithdrawReasons; - use super::*; - parameter_types! { pub const MinVestedTransfer: Balance = PLMC; pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = diff --git a/runtimes/shared-configuration/src/fee.rs b/runtimes/shared-configuration/src/fee.rs index 2768fdfee..0d650e915 100644 --- a/runtimes/shared-configuration/src/fee.rs +++ b/runtimes/shared-configuration/src/fee.rs @@ -39,6 +39,7 @@ use sp_arithmetic::{ }; use sp_std::prelude::*; +#[allow(clippy::module_name_repetitions)] pub struct WeightToFee; impl frame_support::weights::WeightToFee for WeightToFee { type Balance = Balance; @@ -53,6 +54,7 @@ impl frame_support::weights::WeightToFee for WeightToFee { } /// Maps the reference time component of `Weight` to a fee. +#[allow(clippy::module_name_repetitions)] pub struct RefTimeToFee; impl WeightToFeePolynomial for RefTimeToFee { type Balance = Balance; @@ -73,6 +75,7 @@ impl WeightToFeePolynomial for RefTimeToFee { } /// Maps the proof size component of `Weight` to a fee. +#[allow(clippy::module_name_repetitions)] pub struct ProofSizeToFee; impl WeightToFeePolynomial for ProofSizeToFee { type Balance = Balance; diff --git a/runtimes/shared-configuration/src/proxy.rs b/runtimes/shared-configuration/src/proxy.rs index de4d96a14..f45a13462 100644 --- a/runtimes/shared-configuration/src/proxy.rs +++ b/runtimes/shared-configuration/src/proxy.rs @@ -22,7 +22,7 @@ use sp_runtime::RuntimeDebug; #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo, )] -pub enum ProxyType { +pub enum Type { /// Fully permissioned proxy. Can execute any call on behalf of _proxied_. Any, NonTransfer, @@ -30,7 +30,7 @@ pub enum ProxyType { Staking, IdentityJudgement, } -impl Default for ProxyType { +impl Default for Type { fn default() -> Self { Self::Any } diff --git a/runtimes/shared-configuration/src/weights/mod.rs b/runtimes/shared-configuration/src/weights/mod.rs index ea1fd8720..081833f15 100644 --- a/runtimes/shared-configuration/src/weights/mod.rs +++ b/runtimes/shared-configuration/src/weights/mod.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . //! Expose the auto generated weight files. - +#![allow(clippy::module_name_repetitions)] pub mod block_weights; pub mod extrinsic_weights; pub mod paritydb_weights;