From 56cf9547eabe1d87ed95f2cfef5d2d6e766660ec Mon Sep 17 00:00:00 2001 From: Juan Ignacio Rios Date: Tue, 3 Sep 2024 11:03:39 +0200 Subject: [PATCH] Set balance to u128 instead of config type on pallet_funding --- integration-tests/penpal/src/xcm_config.rs | 14 +- integration-tests/src/tests/ct_migration.rs | 4 +- integration-tests/src/tests/e2e.rs | 6 +- integration-tests/src/tests/governance.rs | 3 +- pallets/funding/src/benchmarking.rs | 111 +++--------- .../funding/src/functions/1_application.rs | 4 +- pallets/funding/src/functions/2_evaluation.rs | 4 +- pallets/funding/src/functions/6_settlement.rs | 22 +-- .../funding/src/functions/7_ct_migration.rs | 4 +- pallets/funding/src/functions/misc.rs | 55 +++--- pallets/funding/src/functions/mod.rs | 5 +- .../funding/src/instantiator/calculations.rs | 36 ++-- .../src/instantiator/chain_interactions.rs | 67 ++++--- pallets/funding/src/instantiator/types.rs | 84 ++++----- pallets/funding/src/lib.rs | 120 +++++-------- pallets/funding/src/mock.rs | 6 +- pallets/funding/src/runtime_api.rs | 14 +- pallets/funding/src/storage_migrations.rs | 2 +- pallets/funding/src/tests/2_evaluation.rs | 2 +- pallets/funding/src/tests/4_contribution.rs | 6 +- pallets/funding/src/tests/5_funding_end.rs | 2 +- pallets/funding/src/tests/6_settlement.rs | 2 +- pallets/funding/src/tests/misc.rs | 24 +-- pallets/funding/src/tests/mod.rs | 4 +- pallets/funding/src/traits.rs | 4 +- pallets/funding/src/types.rs | 164 ++++++++---------- runtimes/polimec/src/lib.rs | 1 - 27 files changed, 313 insertions(+), 457 deletions(-) diff --git a/integration-tests/penpal/src/xcm_config.rs b/integration-tests/penpal/src/xcm_config.rs index 7e67d10d8..e44f8815a 100644 --- a/integration-tests/penpal/src/xcm_config.rs +++ b/integration-tests/penpal/src/xcm_config.rs @@ -31,7 +31,7 @@ use super::{ use crate::{BaseDeliveryFee, FeeAssetId, TransactionByteFee}; use core::marker::PhantomData; use frame_support::{ - match_types, parameter_types, + parameter_types, traits::{ConstU32, Contains, ContainsPair, Everything, EverythingBut, Get, Nothing}, weights::Weight, }; @@ -44,12 +44,12 @@ use sp_runtime::traits::{AccountIdConversion, ConvertInto, Identity, TryConvertI use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, - ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, - FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, NoChecking, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, StartsWith, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount, + AllowKnownQueryResponses, AllowSubscriptionsFrom, AsPrefixedGeneralIndex, ConvertedConcreteId, EnsureXcmOrigin, + FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, LocalMint, + NativeAsset, NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, + StartsWith, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::{traits::JustTry, XcmExecutor}; diff --git a/integration-tests/src/tests/ct_migration.rs b/integration-tests/src/tests/ct_migration.rs index 563e5029b..25ee151d2 100644 --- a/integration-tests/src/tests/ct_migration.rs +++ b/integration-tests/src/tests/ct_migration.rs @@ -192,7 +192,7 @@ fn create_settled_project() -> (ProjectId, Vec) { fn full_pallet_migration_test() { polimec::set_prices(); let (project_id, participants) = create_settled_project(); - let project_status = + let _project_status = PolimecNet::execute_with(|| pallet_funding::ProjectsDetails::::get(project_id).unwrap().status); mock_hrmp_establishment(project_id); @@ -304,7 +304,7 @@ fn cannot_start_pallet_migration_with_unsettled_participations() { let tups = vec![tup_1, tup_2, tup_3]; - for (project_id, participants) in tups.into_iter() { + for (project_id, _participants) in tups.into_iter() { PolimecNet::execute_with(|| { assert_noop!( PolimecFunding::do_start_pallet_migration(&ISSUER.into(), project_id, ParaId::from(6969u32)), diff --git a/integration-tests/src/tests/e2e.rs b/integration-tests/src/tests/e2e.rs index 47ec609e0..dca184454 100644 --- a/integration-tests/src/tests/e2e.rs +++ b/integration-tests/src/tests/e2e.rs @@ -423,7 +423,7 @@ fn ct_minted() { let mut inst = IntegrationInstantiator::new(None); PolimecNet::execute_with(|| { - let project_id = inst.create_settled_project( + let _project_id = inst.create_settled_project( excel_project(), ISSUER.into(), None, @@ -511,10 +511,6 @@ 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); - 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); - let names = names(); for account in accounts { diff --git a/integration-tests/src/tests/governance.rs b/integration-tests/src/tests/governance.rs index 08bed8aec..13153c97c 100644 --- a/integration-tests/src/tests/governance.rs +++ b/integration-tests/src/tests/governance.rs @@ -18,8 +18,7 @@ use frame_support::{ use pallet_democracy::{AccountVote, Conviction, GetElectorate, ReferendumInfo, Vote}; use pallet_vesting::VestingInfo; use polimec_runtime::{ - Balances, Council, Democracy, Elections, ParachainStaking, Preimage, RuntimeOrigin, TechnicalCommittee, Treasury, - Vesting, PLMC, + Balances, Council, Democracy, Elections, ParachainStaking, Preimage, RuntimeOrigin, Treasury, Vesting, PLMC, }; use xcm_emulator::helpers::get_account_id_from_seed; generate_accounts!(PEPE, CARLOS,); diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index 5df91e157..f02fcc179 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -62,38 +62,21 @@ where let metadata_hash = BoundedVec::try_from(IPFS_CID.as_bytes().to_vec()).unwrap(); ProjectMetadata { token_information: CurrencyMetadata { name: bounded_name, symbol: bounded_symbol, decimals: CT_DECIMALS }, - mainnet_token_max_supply: BalanceOf::::try_from(1_000_000 * CT_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - total_allocation_size: BalanceOf::::try_from(1_000_000 * CT_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), + mainnet_token_max_supply: 1_000_000u128 * CT_UNIT, + total_allocation_size: 1_000_000u128 * CT_UNIT, auction_round_allocation_percentage: Percent::from_percent(50u8), minimum_price: PriceProviderOf::::calculate_decimals_aware_price(10u128.into(), USD_DECIMALS, CT_DECIMALS) .unwrap(), bidding_ticket_sizes: BiddingTicketSizes { - professional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - None, - ), - institutional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - None, - ), + professional: TicketSize::new(5000u128 * USD_UNIT, None), + institutional: TicketSize::new(5000u128 * USD_UNIT, None), phantom: Default::default(), }, contributing_ticket_sizes: ContributingTicketSizes { - retail: TicketSize::new( - BalanceOf::::try_from(USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - None, - ), - professional: TicketSize::new( - BalanceOf::::try_from(USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - None, - ), - institutional: TicketSize::new( - BalanceOf::::try_from(USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - None, - ), + retail: TicketSize::new(USD_UNIT, None), + professional: TicketSize::new(USD_UNIT, None), + institutional: TicketSize::new(USD_UNIT, None), phantom: Default::default(), }, participation_currencies: vec![AcceptedFundingAsset::USDT].try_into().unwrap(), @@ -105,7 +88,6 @@ where pub fn default_evaluations() -> Vec> where ::Price: From, - ::Balance: From, T::Hash: From, { let threshold = ::EvaluationSuccessThreshold::get(); @@ -134,7 +116,6 @@ where pub fn default_bids() -> Vec> where ::Price: From, - ::Balance: From, T::Hash: From, { let default_project_metadata = default_project_metadata::(account::>("issuer", 0, 0)); @@ -156,7 +137,6 @@ pub fn full_bids() -> Vec> where T: Config, ::Price: From, - ::Balance: From, T::Hash: From, { let inst = BenchInstantiator::::new(None); @@ -175,7 +155,6 @@ where pub fn default_community_contributions() -> Vec> where ::Price: From, - ::Balance: From, T::Hash: From, { let inst = BenchInstantiator::::new(None); @@ -201,7 +180,6 @@ where pub fn default_remainder_contributions() -> Vec> where ::Price: From, - ::Balance: From, T::Hash: From, { let inst = BenchInstantiator::::new(None); @@ -289,13 +267,12 @@ pub fn string_account( #[benchmarks( where - T: Config + frame_system::Config::RuntimeEvent> + pallet_balances::Config> + sp_std::fmt::Debug, + T: Config + frame_system::Config::RuntimeEvent> + pallet_balances::Config + sp_std::fmt::Debug, ::RuntimeEvent: TryInto> + Parameter + Member, ::Price: From, - ::Balance: From + Into, T::Hash: From, ::AccountId: Into<<::RuntimeOrigin as OriginTrait>::AccountId> + sp_std::fmt::Debug, - ::Balance: Into>, + ::Balance: Into, )] mod benchmarks { use super::*; @@ -327,7 +304,7 @@ mod benchmarks { let ct_treasury_account_deposit = T::ContributionTokenCurrency::deposit_required(0); inst.mint_plmc_to(vec![UserToPLMCBalance::new( issuer.clone(), - ed * 2u64.into() + metadata_deposit + ct_treasury_account_deposit, + ed * 2u128 + metadata_deposit + ct_treasury_account_deposit, )]); let jwt = get_mock_jwt_with_cid( issuer.clone(), @@ -411,10 +388,8 @@ mod benchmarks { symbol: BoundedVec::try_from("CTESTv2".as_bytes().to_vec()).unwrap(), decimals: CT_DECIMALS - 2, }, - mainnet_token_max_supply: BalanceOf::::try_from(200_000 * CT_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - total_allocation_size: BalanceOf::::try_from(200_000 * CT_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), + mainnet_token_max_supply: 200_000u128 * CT_UNIT, + total_allocation_size: 200_000u128 * CT_UNIT, auction_round_allocation_percentage: Percent::from_percent(30u8), minimum_price: PriceProviderOf::::calculate_decimals_aware_price( 11u128.into(), @@ -423,44 +398,14 @@ mod benchmarks { ) .unwrap(), bidding_ticket_sizes: BiddingTicketSizes { - professional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - Some( - BalanceOf::::try_from(10_000 * USD_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - ), - ), - institutional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - Some( - BalanceOf::::try_from(10_000 * USD_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - ), - ), + professional: TicketSize::new(5000 * USD_UNIT, Some(10_000 * USD_UNIT)), + institutional: TicketSize::new(5000 * USD_UNIT, Some(10_000 * USD_UNIT)), phantom: Default::default(), }, contributing_ticket_sizes: ContributingTicketSizes { - retail: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - Some( - BalanceOf::::try_from(10_000 * USD_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - ), - ), - professional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - Some( - BalanceOf::::try_from(10_000 * USD_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - ), - ), - institutional: TicketSize::new( - BalanceOf::::try_from(5000 * USD_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - Some( - BalanceOf::::try_from(10_000 * USD_UNIT) - .unwrap_or_else(|_| panic!("Failed to create BalanceOf")), - ), - ), + retail: TicketSize::new(5000 * USD_UNIT, Some(10_000 * USD_UNIT)), + professional: TicketSize::new(5000 * USD_UNIT, Some(10_000 * USD_UNIT)), + institutional: TicketSize::new(5000 * USD_UNIT, Some(10_000 * USD_UNIT)), phantom: Default::default(), }, participation_currencies: vec![AcceptedFundingAsset::USDT, AcceptedFundingAsset::USDC].try_into().unwrap(), @@ -518,9 +463,9 @@ mod benchmarks { // Storage let stored_details = ProjectsDetails::::get(project_id).unwrap(); assert_eq!(stored_details.status, ProjectStatus::EvaluationRound); - let starting_evaluation_info = EvaluationRoundInfoOf:: { - total_bonded_usd: Zero::zero(), - total_bonded_plmc: Zero::zero(), + let starting_evaluation_info = EvaluationRoundInfo { + total_bonded_usd: Balance::zero(), + total_bonded_plmc: Balance::zero(), evaluators_outcome: None, }; assert_eq!(stored_details.evaluation_round_info, starting_evaluation_info); @@ -706,10 +651,8 @@ mod benchmarks { whitelist_account!(bidder); let mut project_metadata = default_project_metadata::(issuer.clone()); - project_metadata.mainnet_token_max_supply = - (100_000 * CT_UNIT).try_into().unwrap_or_else(|_| panic!("Failed to create BalanceOf")); - project_metadata.total_allocation_size = - (100_000 * CT_UNIT).try_into().unwrap_or_else(|_| panic!("Failed to create BalanceOf")); + project_metadata.mainnet_token_max_supply = 100_000 * CT_UNIT; + project_metadata.total_allocation_size = 100_000 * CT_UNIT; project_metadata.minimum_price = PriceProviderOf::::calculate_decimals_aware_price( PriceOf::::checked_from_rational(100, 1).unwrap(), USD_DECIMALS, @@ -790,7 +733,7 @@ mod benchmarks { let auction_allocation = project_metadata.auction_round_allocation_percentage * project_metadata.total_allocation_size; let bucket_size = Percent::from_percent(10) * auction_allocation; - ct_amount = bucket_size * (y as u128).into(); + ct_amount = bucket_size * (y as u128); usdt_for_filler_bidder = usdt_for_new_bidder; } let extrinsic_bid = BidParams::new(bidder.clone(), ct_amount, 1u8, AcceptedFundingAsset::USDT); @@ -949,10 +892,8 @@ mod benchmarks { whitelist_account!(issuer); let mut project_metadata = default_project_metadata::(issuer.clone()); - project_metadata.mainnet_token_max_supply = - BalanceOf::::try_from(10_000_000 * CT_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")); - project_metadata.total_allocation_size = - BalanceOf::::try_from(10_000_000 * CT_UNIT).unwrap_or_else(|_| panic!("Failed to create BalanceOf")); + project_metadata.mainnet_token_max_supply = 10_000_000 * CT_UNIT; + project_metadata.total_allocation_size = 10_000_000 * CT_UNIT; project_metadata.auction_round_allocation_percentage = Percent::from_percent(100u8); let project_id = inst.create_auctioning_project( @@ -990,7 +931,7 @@ mod benchmarks { // This one needs to fill the remaining with the bucket, so that all "accepted" bids will take the CT from a rejected one let last_rejected_bid = BidParams::::new( account::>("bidder", 0, 420), - auction_allocation - (min_bid_amount * CT_UNIT * (y as u128 - 1u128)).into(), + auction_allocation - (min_bid_amount * CT_UNIT * (y as u128 - 1u128)), 1u8, AcceptedFundingAsset::USDT, ); diff --git a/pallets/funding/src/functions/1_application.rs b/pallets/funding/src/functions/1_application.rs index fdcdc1967..1e91098c1 100644 --- a/pallets/funding/src/functions/1_application.rs +++ b/pallets/funding/src/functions/1_application.rs @@ -38,8 +38,8 @@ impl Pallet { status: ProjectStatus::Application, round_duration: BlockNumberPair::new(None, None), remaining_contribution_tokens: project_metadata.total_allocation_size, - funding_amount_reached_usd: BalanceOf::::zero(), - evaluation_round_info: EvaluationRoundInfoOf:: { + funding_amount_reached_usd: Balance::zero(), + evaluation_round_info: EvaluationRoundInfo { total_bonded_usd: Zero::zero(), total_bonded_plmc: Zero::zero(), evaluators_outcome: None, diff --git a/pallets/funding/src/functions/2_evaluation.rs b/pallets/funding/src/functions/2_evaluation.rs index bf135cc62..2503ce71f 100644 --- a/pallets/funding/src/functions/2_evaluation.rs +++ b/pallets/funding/src/functions/2_evaluation.rs @@ -115,7 +115,7 @@ impl Pallet { pub fn do_evaluate( evaluator: &AccountIdOf, project_id: ProjectId, - usd_amount: BalanceOf, + usd_amount: Balance, did: Did, whitelisted_policy: Cid, ) -> DispatchResultWithPostInfo { @@ -157,7 +157,7 @@ impl Pallet { remaining_bond_to_reach_threshold }; - let late_usd_amount = usd_amount.checked_sub(&early_usd_amount).ok_or(Error::::BadMath)?; + let late_usd_amount = usd_amount.checked_sub(early_usd_amount).ok_or(Error::::BadMath)?; let new_evaluation = EvaluationInfoOf:: { id: evaluation_id, diff --git a/pallets/funding/src/functions/6_settlement.rs b/pallets/funding/src/functions/6_settlement.rs index 89a211983..5aee5e971 100644 --- a/pallets/funding/src/functions/6_settlement.rs +++ b/pallets/funding/src/functions/6_settlement.rs @@ -1,6 +1,6 @@ #[allow(clippy::wildcard_imports)] use super::*; -use crate::traits::VestingDurationCalculation; +use crate::{traits::VestingDurationCalculation, Balance}; use frame_support::{ dispatch::DispatchResult, ensure, @@ -92,7 +92,7 @@ impl Pallet { Error::::SettlementNotStarted ); - let (plmc_released, ct_rewarded): (BalanceOf, BalanceOf) = + let (plmc_released, ct_rewarded): (Balance, Balance) = match project_details.evaluation_round_info.evaluators_outcome { Some(EvaluatorsOutcome::Slashed) => (Self::slash_evaluator(&evaluation)?, Zero::zero()), Some(EvaluatorsOutcome::Rewarded(info)) => Self::reward_evaluator(project_id, &evaluation, &info)?, @@ -334,7 +334,7 @@ impl Pallet { fn mint_contribution_tokens( project_id: ProjectId, participant: &AccountIdOf, - amount: BalanceOf, + amount: Balance, ) -> DispatchResult { if !T::ContributionTokenCurrency::contains(&project_id, participant) { T::ContributionTokenCurrency::touch(project_id, participant, participant)?; @@ -346,7 +346,7 @@ impl Pallet { fn release_funding_asset( project_id: ProjectId, participant: &AccountIdOf, - amount: BalanceOf, + amount: Balance, asset: AcceptedFundingAsset, ) -> DispatchResult { if amount.is_zero() { @@ -357,7 +357,7 @@ impl Pallet { Ok(()) } - fn release_participation_bond(participant: &AccountIdOf, amount: BalanceOf) -> DispatchResult { + fn release_participation_bond(participant: &AccountIdOf, amount: Balance) -> DispatchResult { if amount.is_zero() { return Ok(()); } @@ -366,7 +366,7 @@ impl Pallet { Ok(()) } - fn slash_evaluator(evaluation: &EvaluationInfoOf) -> Result, DispatchError> { + fn slash_evaluator(evaluation: &EvaluationInfoOf) -> Result { let slash_percentage = T::EvaluatorSlash::get(); let treasury_account = T::BlockchainOperationTreasury::get(); @@ -390,15 +390,15 @@ impl Pallet { fn reward_evaluator( project_id: ProjectId, evaluation: &EvaluationInfoOf, - info: &RewardInfoOf, - ) -> Result<(BalanceOf, BalanceOf), DispatchError> { + info: &RewardInfo, + ) -> Result<(Balance, Balance), DispatchError> { let reward = Self::calculate_evaluator_reward(evaluation, info); Self::mint_contribution_tokens(project_id, &evaluation.evaluator, reward)?; Ok((evaluation.current_plmc_bond, reward)) } - pub fn calculate_evaluator_reward(evaluation: &EvaluationInfoOf, info: &RewardInfoOf) -> BalanceOf { + pub fn calculate_evaluator_reward(evaluation: &EvaluationInfoOf, info: &RewardInfo) -> Balance { let early_reward_weight = Perquintill::from_rational(evaluation.early_usd_amount, info.early_evaluator_total_bonded_usd); let normal_reward_weight = Perquintill::from_rational( @@ -415,7 +415,7 @@ impl Pallet { origin: &AccountIdOf, id: u32, participation_type: ParticipationType, - ct_amount: BalanceOf, + ct_amount: Balance, vesting_time: BlockNumberFor, ) -> DispatchResult { UserMigrations::::try_mutate((project_id, origin), |maybe_migrations| -> DispatchResult { @@ -423,7 +423,7 @@ impl Pallet { Location::new(0, AccountId32 { network: None, id: T::AccountId32Conversion::convert(origin.clone()) }); let migration_origin = MigrationOrigin { user: location_user, id, participation_type }; let vesting_time: u64 = vesting_time.try_into().map_err(|_| Error::::BadMath)?; - let migration_info: MigrationInfo = (ct_amount.into(), vesting_time).into(); + let migration_info: MigrationInfo = (ct_amount, vesting_time).into(); let migration = Migration::new(migration_origin, migration_info); if let Some((_, migrations)) = maybe_migrations { migrations.try_push(migration).map_err(|_| Error::::TooManyMigrations)?; diff --git a/pallets/funding/src/functions/7_ct_migration.rs b/pallets/funding/src/functions/7_ct_migration.rs index bda5a22eb..001e50735 100644 --- a/pallets/funding/src/functions/7_ct_migration.rs +++ b/pallets/funding/src/functions/7_ct_migration.rs @@ -270,7 +270,7 @@ impl Pallet { let total_cts_minted = ::ContributionTokenCurrency::total_issuance(project_id); // * Send the migration query * - let expected_tokens: Asset = (Location::here(), total_cts_minted.into()).into(); + let expected_tokens: Asset = (Location::here(), total_cts_minted).into(); log::info!("expected_tokens sold for migrations: {:?}", total_cts_minted); let xcm = Xcm(vec![ UnpaidExecution { weight_limit: WeightLimit::Unlimited, check_origin: None }, @@ -343,7 +343,7 @@ impl Pallet { }, ), ) => { - let ct_sold_as_u128: u128 = contribution_tokens_sold.into(); + let ct_sold_as_u128: u128 = contribution_tokens_sold; let assets: Vec = assets.into_inner(); let asset_1 = assets[0].clone(); match asset_1 { diff --git a/pallets/funding/src/functions/misc.rs b/pallets/funding/src/functions/misc.rs index 1ce4d0c96..eae2539d8 100644 --- a/pallets/funding/src/functions/misc.rs +++ b/pallets/funding/src/functions/misc.rs @@ -1,5 +1,3 @@ -use sp_runtime::traits::CheckedAdd; - #[allow(clippy::wildcard_imports)] use super::*; @@ -29,10 +27,7 @@ impl Pallet { Ok(bucket) } - pub fn calculate_plmc_bond( - ticket_size: BalanceOf, - multiplier: MultiplierOf, - ) -> Result, DispatchError> { + pub fn calculate_plmc_bond(ticket_size: Balance, multiplier: MultiplierOf) -> Result { 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).ok_or(Error::::BadMath)?; @@ -44,9 +39,9 @@ impl Pallet { } pub fn calculate_funding_asset_amount( - ticket_size: BalanceOf, + ticket_size: Balance, asset_id: AcceptedFundingAsset, - ) -> Result, DispatchError> { + ) -> Result { let asset_id = asset_id.id(); let asset_decimals = T::FundingCurrency::decimals(asset_id); let asset_usd_price = T::PriceProvider::get_decimals_aware_price(asset_id, USD_DECIMALS, asset_decimals) @@ -62,14 +57,14 @@ impl Pallet { pub fn calculate_vesting_info( _caller: &AccountIdOf, multiplier: MultiplierOf, - bonded_amount: BalanceOf, - ) -> Result, BalanceOf>, DispatchError> { + bonded_amount: Balance, + ) -> Result>, DispatchError> { let duration: BlockNumberFor = multiplier.calculate_vesting_duration::(); let duration_as_balance = T::BlockNumberToBalance::convert(duration); let amount_per_block = if duration_as_balance == Zero::zero() { bonded_amount } else { - bonded_amount.checked_div(&duration_as_balance).ok_or(Error::::BadMath)? + bonded_amount.checked_div(duration_as_balance).ok_or(Error::::BadMath)? }; Ok(VestingInfo { total_amount: bonded_amount, amount_per_block, duration }) @@ -77,7 +72,7 @@ impl Pallet { pub fn decide_winning_bids( project_id: ProjectId, - auction_allocation_size: BalanceOf, + auction_allocation_size: Balance, wap: PriceOf, ) -> Result<(u32, u32), DispatchError> { let mut bids = Bids::::iter_prefix_values((project_id,)).collect::>(); @@ -110,12 +105,12 @@ impl Pallet { .partition(|bid| matches!(bid.status, BidStatus::Accepted | BidStatus::PartiallyAccepted(..))); let accepted_bid_len = accepted_bids.len() as u32; - let total_auction_allocation_usd: BalanceOf = accepted_bids + let total_auction_allocation_usd: Balance = accepted_bids .into_iter() - .try_fold(Zero::zero(), |acc: BalanceOf, bid: BidInfoOf| { + .try_fold(Zero::zero(), |acc: Balance, bid: BidInfoOf| { let final_ct_usd_price = if bid.original_ct_usd_price > wap { wap } else { bid.original_ct_usd_price }; let final_ct_amount = bid.final_ct_amount(); - final_ct_usd_price.checked_mul_int(final_ct_amount).and_then(|usd_ticket| acc.checked_add(&usd_ticket)) + final_ct_usd_price.checked_mul_int(final_ct_amount).and_then(|usd_ticket| acc.checked_add(usd_ticket)) }) .ok_or(Error::::BadMath)?; @@ -134,11 +129,7 @@ impl Pallet { Ok((accepted_bid_len, rejected_bids.len() as u32)) } - pub fn try_plmc_participation_lock( - who: &T::AccountId, - project_id: ProjectId, - amount: BalanceOf, - ) -> DispatchResult { + pub fn try_plmc_participation_lock(who: &T::AccountId, project_id: ProjectId, amount: Balance) -> DispatchResult { // Check if the user has already locked tokens in the evaluation period let user_evaluations = Evaluations::::iter_prefix_values((project_id, who)); @@ -169,7 +160,7 @@ impl Pallet { pub fn try_funding_asset_hold( who: &T::AccountId, project_id: ProjectId, - amount: BalanceOf, + amount: Balance, asset_id: AssetIdOf, ) -> DispatchResult { let fund_account = Self::fund_account_id(project_id); @@ -184,7 +175,7 @@ impl Pallet { } // Calculate the total fee allocation for a project, based on the funding reached. - fn calculate_fee_allocation(project_id: ProjectId) -> Result, DispatchError> { + fn calculate_fee_allocation(project_id: ProjectId) -> Result { let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; // Fetching the necessary data for a specific project. @@ -200,7 +191,7 @@ impl Pallet { // Calculate the number of tokens sold for the project. let token_sold = initial_token_allocation_size - .checked_sub(&final_remaining_contribution_tokens) + .checked_sub(final_remaining_contribution_tokens) // Ensure safety by providing a default in case of unexpected situations. .unwrap_or(initial_token_allocation_size); let total_fee_allocation = fee_percentage * token_sold; @@ -209,27 +200,23 @@ impl Pallet { } /// Computes the total fee from all defined fee brackets. - fn compute_total_fee_from_brackets(funding_reached: BalanceOf) -> BalanceOf { + fn compute_total_fee_from_brackets(funding_reached: Balance) -> Balance { let mut remaining_for_fee = funding_reached; T::FeeBrackets::get() .into_iter() .map(|(fee, limit)| Self::compute_fee_for_bracket(&mut remaining_for_fee, fee, limit)) - .fold(BalanceOf::::zero(), |acc, fee| acc.saturating_add(fee)) + .fold(Balance::zero(), |acc, fee| acc.saturating_add(fee)) } /// Calculate the fee for a particular bracket. - fn compute_fee_for_bracket( - remaining_for_fee: &mut BalanceOf, - fee: Percent, - limit: BalanceOf, - ) -> BalanceOf { - if let Some(amount_to_bid) = remaining_for_fee.checked_sub(&limit) { + fn compute_fee_for_bracket(remaining_for_fee: &mut Balance, fee: Percent, limit: Balance) -> Balance { + if let Some(amount_to_bid) = remaining_for_fee.checked_sub(limit) { *remaining_for_fee = amount_to_bid; fee * limit } else { let fee_for_this_bracket = fee * *remaining_for_fee; - *remaining_for_fee = BalanceOf::::zero(); + *remaining_for_fee = Balance::zero(); fee_for_this_bracket } } @@ -242,7 +229,7 @@ impl Pallet { /// /// Note: Consider refactoring the `RewardInfo` struct to make it more generic and /// reusable, not just for evaluator rewards. - pub fn generate_evaluator_rewards_info(project_id: ProjectId) -> Result, DispatchError> { + pub fn generate_evaluator_rewards_info(project_id: ProjectId) -> Result { // Fetching the necessary data for a specific project. let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let total_fee_allocation = Self::calculate_fee_allocation(project_id)?; @@ -273,7 +260,7 @@ impl Pallet { pub fn generate_liquidity_pools_and_long_term_holder_rewards( project_id: ProjectId, - ) -> Result<(BalanceOf, BalanceOf), DispatchError> { + ) -> Result<(Balance, Balance), DispatchError> { let total_fee_allocation = Self::calculate_fee_allocation(project_id)?; let liquidity_pools_percentage = Perquintill::from_percent(50); diff --git a/pallets/funding/src/functions/mod.rs b/pallets/funding/src/functions/mod.rs index 1aaa82ee7..c7b452d09 100644 --- a/pallets/funding/src/functions/mod.rs +++ b/pallets/funding/src/functions/mod.rs @@ -22,10 +22,7 @@ use polimec_common::{ migration_types::{MigrationInfo, Migrations}, USD_DECIMALS, }; -use sp_arithmetic::{ - traits::{CheckedDiv, CheckedSub, Zero}, - Percent, Perquintill, -}; +use sp_arithmetic::{traits::Zero, Percent, Perquintill}; use sp_runtime::traits::Convert; const POLIMEC_PARA_ID: u32 = 3344u32; diff --git a/pallets/funding/src/instantiator/calculations.rs b/pallets/funding/src/instantiator/calculations.rs index 2e715dc91..e90deadc1 100644 --- a/pallets/funding/src/instantiator/calculations.rs +++ b/pallets/funding/src/instantiator/calculations.rs @@ -5,16 +5,16 @@ use itertools::GroupBy; use polimec_common::USD_DECIMALS; impl< - T: Config + pallet_balances::Config>, + T: Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator { - pub fn get_ed(&self) -> BalanceOf { + pub fn get_ed(&self) -> Balance { T::ExistentialDeposit::get() } - pub fn get_ct_account_deposit(&self) -> BalanceOf { + pub fn get_ct_account_deposit(&self) -> Balance { ::ContributionTokenCurrency::deposit_required(One::one()) } @@ -320,7 +320,7 @@ impl< } /// Filters the bids that would be rejected after the auction ends. - pub fn filter_bids_after_auction(&self, bids: Vec>, total_cts: BalanceOf) -> Vec> { + pub fn filter_bids_after_auction(&self, bids: Vec>, total_cts: Balance) -> Vec> { let mut filtered_bids: Vec> = Vec::new(); let sorted_bids = bids; let mut total_cts_left = total_cts; @@ -484,14 +484,14 @@ impl< output.merge_accounts(ops) } - pub fn sum_balance_mappings(&self, mut mappings: Vec>>) -> BalanceOf { + pub fn sum_balance_mappings(&self, mut mappings: Vec>>) -> Balance { let mut output = mappings .swap_remove(0) .into_iter() .map(|user_to_plmc| user_to_plmc.plmc_amount) .fold(Zero::zero(), |a, b| a + b); for map in mappings { - output += map.into_iter().map(|user_to_plmc| user_to_plmc.plmc_amount).fold(Zero::zero(), |a, b| a + b); + output += map.into_iter().map(|user_to_plmc| user_to_plmc.plmc_amount).fold(Balance::zero(), |a, b| a + b); } output } @@ -499,7 +499,7 @@ impl< pub fn sum_funding_asset_mappings( &self, mappings: Vec>>, - ) -> Vec<(AssetIdOf, BalanceOf)> { + ) -> Vec<(AssetIdOf, Balance)> { let flattened_list = mappings.into_iter().flatten().collect_vec(); let ordered_list = flattened_list.into_iter().sorted_by(|a, b| a.asset_id.cmp(&b.asset_id)).collect_vec(); @@ -525,7 +525,7 @@ impl< ) -> Vec> { let funding_target = project_metadata.minimum_price.saturating_mul_int(project_metadata.total_allocation_size); let evaluation_success_threshold = ::EvaluationSuccessThreshold::get(); // if we use just the threshold, then for big usd targets we lose the evaluation due to PLMC conversion errors in `evaluation_end` - let usd_threshold = evaluation_success_threshold * funding_target * 2u32.into(); + let usd_threshold = evaluation_success_threshold * funding_target * 2u128; zip(evaluators, weights) .map(|(evaluator, weight)| { @@ -537,7 +537,7 @@ impl< pub fn generate_bids_from_total_usd( &self, - usd_amount: BalanceOf, + usd_amount: Balance, min_price: PriceOf, weights: Vec, bidders: Vec>, @@ -578,7 +578,7 @@ impl< pub fn generate_contributions_from_total_usd( &self, - usd_amount: BalanceOf, + usd_amount: Balance, final_price: PriceOf, weights: Vec, contributors: Vec>, @@ -626,8 +626,8 @@ impl< pub fn calculate_total_reward_for_evaluation( &self, evaluation: EvaluationInfoOf, - reward_info: RewardInfoOf, - ) -> BalanceOf { + reward_info: RewardInfo, + ) -> Balance { let early_reward_weight = Perquintill::from_rational(evaluation.early_usd_amount, reward_info.early_evaluator_total_bonded_usd); let normal_reward_weight = Perquintill::from_rational( @@ -650,7 +650,7 @@ impl< } // Fill first bucket - bucket.update(bucket.delta_amount * 10u32.into()); + bucket.update(bucket.delta_amount * 10u128); // Fill remaining buckets till we pass by the wap loop { @@ -671,19 +671,19 @@ impl< bucket.current_price = bucket.current_price - bucket.delta_price; // Do a binary search on the amount to reach the desired wap - let mut lower_bound: BalanceOf = Zero::zero(); - let mut upper_bound: BalanceOf = bucket.delta_amount; + let mut lower_bound: Balance = Zero::zero(); + let mut upper_bound: Balance = bucket.delta_amount; while lower_bound <= upper_bound { - let mid_point = (lower_bound + upper_bound) / 2u32.into(); + let mid_point = (lower_bound + upper_bound) / 2u128; bucket.amount_left = mid_point; let new_wap = bucket.calculate_wap(auction_allocation); // 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(), + Ordering::Less => upper_bound = mid_point - 1u128, + Ordering::Greater => lower_bound = mid_point + 1u128, } } diff --git a/pallets/funding/src/instantiator/chain_interactions.rs b/pallets/funding/src/instantiator/chain_interactions.rs index 5f0541ddc..a6c93df29 100644 --- a/pallets/funding/src/instantiator/chain_interactions.rs +++ b/pallets/funding/src/instantiator/chain_interactions.rs @@ -5,7 +5,7 @@ use super::*; // general chain interactions impl< - T: Config + pallet_balances::Config>, + T: Config + pallet_balances::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator @@ -44,7 +44,7 @@ impl< }) } - pub fn get_free_plmc_balance_for(&mut self, user: AccountIdOf) -> BalanceOf { + pub fn get_free_plmc_balance_for(&mut self, user: AccountIdOf) -> Balance { self.execute(|| ::NativeCurrency::balance(&user)) } @@ -68,7 +68,7 @@ impl< &mut self, user: AccountIdOf, lock_type: ::RuntimeHoldReason, - ) -> BalanceOf { + ) -> Balance { self.execute(|| ::NativeCurrency::balance_on_hold(&lock_type, &user)) } @@ -88,17 +88,13 @@ impl< }) } - pub fn get_free_funding_asset_balance_for(&mut self, asset_id: AssetIdOf, user: AccountIdOf) -> BalanceOf { + pub fn get_free_funding_asset_balance_for(&mut self, asset_id: AssetIdOf, user: AccountIdOf) -> Balance { self.execute(|| ::FundingCurrency::balance(asset_id, &user)) } - pub fn get_ct_asset_balances_for( - &mut self, - project_id: ProjectId, - user_keys: Vec>, - ) -> Vec> { + pub fn get_ct_asset_balances_for(&mut self, project_id: ProjectId, user_keys: Vec>) -> Vec { self.execute(|| { - let mut balances: Vec> = Vec::new(); + let mut balances: Vec = Vec::new(); for account in user_keys { let asset_amount = ::ContributionTokenCurrency::balance(project_id, &account); balances.push(asset_amount); @@ -107,7 +103,7 @@ impl< }) } - pub fn get_ct_asset_balance_for(&mut self, project_id: ProjectId, user: AccountIdOf) -> BalanceOf { + pub fn get_ct_asset_balance_for(&mut self, project_id: ProjectId, user: AccountIdOf) -> Balance { self.execute(|| ::ContributionTokenCurrency::balance(project_id, &user)) } @@ -129,7 +125,7 @@ impl< self.get_free_funding_asset_balances_for(asset_id, user_keys) } - pub fn get_plmc_total_supply(&mut self) -> BalanceOf { + pub fn get_plmc_total_supply(&mut self) -> Balance { self.execute(::NativeCurrency::total_issuance) } @@ -218,7 +214,7 @@ impl< // assertions impl< - T: Config + pallet_balances::Config>, + T: Config + pallet_balances::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator @@ -271,8 +267,8 @@ impl< .checked_mul_int(expected_metadata.total_allocation_size) .unwrap(), remaining_contribution_tokens: expected_metadata.total_allocation_size, - funding_amount_reached_usd: BalanceOf::::zero(), - evaluation_round_info: EvaluationRoundInfoOf:: { + funding_amount_reached_usd: Balance::zero(), + evaluation_round_info: EvaluationRoundInfo { total_bonded_usd: Zero::zero(), total_bonded_plmc: Zero::zero(), evaluators_outcome: None, @@ -290,7 +286,7 @@ impl< project_id: ProjectId, expected_free_plmc_balances: Vec>, expected_held_plmc_balances: Vec>, - expected_total_plmc_supply: BalanceOf, + expected_total_plmc_supply: Balance, ) { let project_details = self.get_project_details(project_id); @@ -308,7 +304,7 @@ impl< &mut self, project_id: ProjectId, bid_expectations: Vec>, - expected_ct_sold: BalanceOf, + expected_ct_sold: Balance, ) { let project_metadata = self.get_project_metadata(project_id); let project_details = self.get_project_details(project_id); @@ -327,7 +323,7 @@ impl< ); } - pub fn assert_plmc_free_balance(&mut self, account_id: AccountIdOf, expected_balance: BalanceOf) { + pub fn assert_plmc_free_balance(&mut self, account_id: AccountIdOf, expected_balance: Balance) { let real_balance = self.get_free_plmc_balance_for(account_id.clone()); assert_eq!(real_balance, expected_balance, "Unexpected PLMC balance for user {:?}", account_id); } @@ -335,7 +331,7 @@ impl< pub fn assert_plmc_held_balance( &mut self, account_id: AccountIdOf, - expected_balance: BalanceOf, + expected_balance: Balance, hold_reason: ::RuntimeHoldReason, ) { let real_balance = self.get_reserved_plmc_balance_for(account_id.clone(), hold_reason); @@ -346,18 +342,13 @@ impl< &mut self, account_id: AccountIdOf, asset_id: AssetIdOf, - expected_balance: BalanceOf, + expected_balance: Balance, ) { let real_balance = self.get_free_funding_asset_balance_for(asset_id, account_id.clone()); assert_eq!(real_balance, expected_balance, "Unexpected funding asset balance for user {:?}", account_id); } - pub fn assert_ct_balance( - &mut self, - project_id: ProjectId, - account_id: AccountIdOf, - expected_balance: BalanceOf, - ) { + pub fn assert_ct_balance(&mut self, project_id: ProjectId, account_id: AccountIdOf, expected_balance: Balance) { let real_balance = self.get_ct_asset_balance_for(project_id, account_id.clone()); assert_eq!(real_balance, expected_balance, "Unexpected CT balance for user {:?}", account_id); } @@ -365,7 +356,7 @@ impl< // project chain interactions impl< - T: Config + pallet_balances::Config>, + T: Config + pallet_balances::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator @@ -422,7 +413,7 @@ impl< maybe_did: Option, ) -> ProjectId { // one ED for the issuer, one ED for the escrow account - self.mint_plmc_to(vec![UserToPLMCBalance::new(issuer.clone(), self.get_ed() * 2u64.into())]); + self.mint_plmc_to(vec![UserToPLMCBalance::new(issuer.clone(), self.get_ed() * 2u128)]); let did = if let Some(did) = maybe_did.clone() { did } else { generate_did_from_account(issuer.clone()) }; @@ -687,9 +678,9 @@ impl< contributions: Vec>, ) { let project_metadata = self.get_project_metadata(project_id); - let mut total_expected_dot: BalanceOf = Zero::zero(); - let mut total_expected_usdt: BalanceOf = Zero::zero(); - let mut total_expected_usdc: BalanceOf = Zero::zero(); + let mut total_expected_dot: Balance = Zero::zero(); + let mut total_expected_usdt: Balance = Zero::zero(); + let mut total_expected_usdc: Balance = Zero::zero(); for bid in bids { match bid.funding_asset { @@ -776,7 +767,7 @@ impl< for bid in bids { let account = bid.bidder.clone(); assert_eq!(self.execute(|| { Bids::::iter_prefix_values((&project_id, &account)).count() }), 0); - let amount: BalanceOf = bid.final_ct_amount(); + let amount: Balance = bid.final_ct_amount(); self.assert_migration(project_id, account, amount, bid.id, ParticipationType::Bid, is_successful); } } @@ -791,7 +782,7 @@ impl< for contribution in contributions { let account = contribution.contributor.clone(); assert_eq!(self.execute(|| { Bids::::iter_prefix_values((&project_id, &account)).count() }), 0); - let amount: BalanceOf = if is_successful { contribution.ct_amount } else { 0u64.into() }; + let amount: Balance = if is_successful { contribution.ct_amount } else { 0u64.into() }; self.assert_migration( project_id, account, @@ -807,7 +798,7 @@ impl< &mut self, project_id: ProjectId, account: AccountIdOf, - amount: BalanceOf, + amount: Balance, id: u32, participation_type: ParticipationType, should_exist: bool, @@ -826,7 +817,7 @@ impl< assert!(should_exist); assert_close_enough!( migration.info.contribution_token_amount, - amount.into(), + amount, Perquintill::from_percent(99u64) ); }, @@ -1020,12 +1011,12 @@ impl< let auction_bought_tokens = bids .iter() .map(|bid| bid.amount) - .fold(Zero::zero(), |acc, item| item + acc) + .fold(Balance::zero(), |acc, item| item + acc) .min(project_metadata.auction_round_allocation_percentage * project_metadata.total_allocation_size); let community_bought_tokens = - community_contributions.iter().map(|cont| cont.amount).fold(Zero::zero(), |acc, item| item + acc); + community_contributions.iter().map(|cont| cont.amount).fold(Balance::zero(), |acc, item| item + acc); let remainder_bought_tokens = - remainder_contributions.iter().map(|cont| cont.amount).fold(Zero::zero(), |acc, item| item + acc); + remainder_contributions.iter().map(|cont| cont.amount).fold(Balance::zero(), |acc, item| item + acc); assert_eq!( project_details.remaining_contribution_tokens, diff --git a/pallets/funding/src/instantiator/types.rs b/pallets/funding/src/instantiator/types.rs index a4e34549a..d303929e5 100644 --- a/pallets/funding/src/instantiator/types.rs +++ b/pallets/funding/src/instantiator/types.rs @@ -29,7 +29,7 @@ pub type OptionalExternalities = Option>; pub type OptionalExternalities = Option<()>; pub struct Instantiator< - T: Config + pallet_balances::Config>, + T: Config + pallet_balances::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > { @@ -49,10 +49,10 @@ impl Deposits for Vec> { #[derive(Clone, PartialEq, Debug)] pub struct UserToPLMCBalance { pub account: AccountIdOf, - pub plmc_amount: BalanceOf, + pub plmc_amount: Balance, } impl UserToPLMCBalance { - pub fn new(account: AccountIdOf, plmc_amount: BalanceOf) -> Self { + pub fn new(account: AccountIdOf, plmc_amount: Balance) -> Self { Self { account, plmc_amount } } } @@ -67,8 +67,8 @@ impl Accounts for Vec> { btree.into_iter().collect_vec() } } -impl From<(AccountIdOf, BalanceOf)> for UserToPLMCBalance { - fn from((account, plmc_amount): (AccountIdOf, BalanceOf)) -> Self { +impl From<(AccountIdOf, Balance)> for UserToPLMCBalance { + fn from((account, plmc_amount): (AccountIdOf, Balance)) -> Self { UserToPLMCBalance::::new(account, plmc_amount) } } @@ -80,7 +80,7 @@ impl AccountMerge for Vec> { for UserToPLMCBalance { account, plmc_amount } in self.iter() { btree .entry(account.clone()) - .and_modify(|e: &mut BalanceOf| { + .and_modify(|e: &mut Balance| { *e = match ops { MergeOperation::Add => e.saturating_add(*plmc_amount), MergeOperation::Subtract => e.saturating_sub(*plmc_amount), @@ -110,15 +110,15 @@ impl AccountMerge for Vec> { #[serde(rename_all = "camelCase", deny_unknown_fields, bound(serialize = ""), bound(deserialize = ""))] pub struct UserToUSDBalance { pub account: AccountIdOf, - pub usd_amount: BalanceOf, + pub usd_amount: Balance, } impl UserToUSDBalance { - pub fn new(account: AccountIdOf, usd_amount: BalanceOf) -> Self { + pub fn new(account: AccountIdOf, usd_amount: Balance) -> Self { Self { account, usd_amount } } } -impl From<(AccountIdOf, BalanceOf)> for UserToUSDBalance { - fn from((account, usd_amount): (AccountIdOf, BalanceOf)) -> Self { +impl From<(AccountIdOf, Balance)> for UserToUSDBalance { + fn from((account, usd_amount): (AccountIdOf, Balance)) -> Self { UserToUSDBalance::::new(account, usd_amount) } } @@ -141,7 +141,7 @@ impl AccountMerge for Vec> { for UserToUSDBalance { account, usd_amount } in self.iter() { btree .entry(account.clone()) - .and_modify(|e: &mut BalanceOf| { + .and_modify(|e: &mut Balance| { *e = match ops { MergeOperation::Add => e.saturating_add(*usd_amount), MergeOperation::Subtract => e.saturating_sub(*usd_amount), @@ -170,21 +170,21 @@ impl AccountMerge for Vec> { #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] pub struct UserToFundingAsset { pub account: AccountIdOf, - pub asset_amount: BalanceOf, + pub asset_amount: Balance, pub asset_id: AssetIdOf, } impl UserToFundingAsset { - pub fn new(account: AccountIdOf, asset_amount: BalanceOf, asset_id: AssetIdOf) -> Self { + pub fn new(account: AccountIdOf, asset_amount: Balance, asset_id: AssetIdOf) -> Self { Self { account, asset_amount, asset_id } } } -impl From<(AccountIdOf, BalanceOf, AssetIdOf)> for UserToFundingAsset { - fn from((account, asset_amount, asset_id): (AccountIdOf, BalanceOf, AssetIdOf)) -> Self { +impl From<(AccountIdOf, Balance, AssetIdOf)> for UserToFundingAsset { + fn from((account, asset_amount, asset_id): (AccountIdOf, Balance, AssetIdOf)) -> Self { UserToFundingAsset::::new(account, asset_amount, asset_id) } } -impl From<(AccountIdOf, BalanceOf)> for UserToFundingAsset { - fn from((account, asset_amount): (AccountIdOf, BalanceOf)) -> Self { +impl From<(AccountIdOf, Balance)> for UserToFundingAsset { + fn from((account, asset_amount): (AccountIdOf, Balance)) -> Self { UserToFundingAsset::::new(account, asset_amount, AcceptedFundingAsset::USDT.id()) } } @@ -207,7 +207,7 @@ impl AccountMerge for Vec> { for UserToFundingAsset { account, asset_amount, asset_id } in self.iter() { btree .entry((account.clone(), asset_id)) - .and_modify(|e: &mut BalanceOf| { + .and_modify(|e: &mut Balance| { *e = match ops { MergeOperation::Add => e.saturating_add(*asset_amount), MergeOperation::Subtract => e.saturating_sub(*asset_amount), @@ -240,16 +240,16 @@ impl AccountMerge for Vec> { #[serde(rename_all = "camelCase", deny_unknown_fields, bound(serialize = ""), bound(deserialize = ""))] pub struct BidParams { pub bidder: AccountIdOf, - pub amount: BalanceOf, + pub amount: Balance, pub multiplier: MultiplierOf, pub asset: AcceptedFundingAsset, } impl BidParams { - pub fn new(bidder: AccountIdOf, amount: BalanceOf, multiplier: u8, asset: AcceptedFundingAsset) -> Self { + pub fn new(bidder: AccountIdOf, amount: Balance, multiplier: u8, asset: AcceptedFundingAsset) -> Self { Self { bidder, amount, multiplier: multiplier.try_into().map_err(|_| ()).unwrap(), asset } } - pub fn new_with_defaults(bidder: AccountIdOf, amount: BalanceOf) -> Self { + pub fn new_with_defaults(bidder: AccountIdOf, amount: Balance) -> Self { Self { bidder, amount, @@ -258,8 +258,8 @@ impl BidParams { } } } -impl From<(AccountIdOf, BalanceOf)> for BidParams { - fn from((bidder, amount): (AccountIdOf, BalanceOf)) -> Self { +impl From<(AccountIdOf, Balance)> for BidParams { + fn from((bidder, amount): (AccountIdOf, Balance)) -> Self { Self { bidder, amount, @@ -268,8 +268,8 @@ impl From<(AccountIdOf, BalanceOf)> for BidParams { } } } -impl From<(AccountIdOf, BalanceOf, u8)> for BidParams { - fn from((bidder, amount, multiplier): (AccountIdOf, BalanceOf, u8)) -> Self { +impl From<(AccountIdOf, Balance, u8)> for BidParams { + fn from((bidder, amount, multiplier): (AccountIdOf, Balance, u8)) -> Self { Self { bidder, amount, @@ -278,8 +278,8 @@ impl From<(AccountIdOf, BalanceOf, u8)> for BidParams { } } } -impl From<(AccountIdOf, BalanceOf, u8, AcceptedFundingAsset)> for BidParams { - fn from((bidder, amount, multiplier, asset): (AccountIdOf, BalanceOf, u8, AcceptedFundingAsset)) -> Self { +impl From<(AccountIdOf, Balance, u8, AcceptedFundingAsset)> for BidParams { + fn from((bidder, amount, multiplier, asset): (AccountIdOf, Balance, u8, AcceptedFundingAsset)) -> Self { Self { bidder, amount, @@ -288,8 +288,8 @@ impl From<(AccountIdOf, BalanceOf, u8, AcceptedFundingAsset)> f } } } -impl From<(AccountIdOf, BalanceOf, AcceptedFundingAsset)> for BidParams { - fn from((bidder, amount, asset): (AccountIdOf, BalanceOf, AcceptedFundingAsset)) -> Self { +impl From<(AccountIdOf, Balance, AcceptedFundingAsset)> for BidParams { + fn from((bidder, amount, asset): (AccountIdOf, Balance, AcceptedFundingAsset)) -> Self { Self { bidder, amount, @@ -315,16 +315,16 @@ impl Accounts for Vec> { #[serde(rename_all = "camelCase", deny_unknown_fields, bound(serialize = ""), bound(deserialize = ""))] pub struct ContributionParams { pub contributor: AccountIdOf, - pub amount: BalanceOf, + pub amount: Balance, pub multiplier: MultiplierOf, pub asset: AcceptedFundingAsset, } impl ContributionParams { - pub fn new(contributor: AccountIdOf, amount: BalanceOf, multiplier: u8, asset: AcceptedFundingAsset) -> Self { + pub fn new(contributor: AccountIdOf, amount: Balance, multiplier: u8, asset: AcceptedFundingAsset) -> Self { Self { contributor, amount, multiplier: multiplier.try_into().map_err(|_| ()).unwrap(), asset } } - pub fn new_with_defaults(contributor: AccountIdOf, amount: BalanceOf) -> Self { + pub fn new_with_defaults(contributor: AccountIdOf, amount: Balance) -> Self { Self { contributor, amount, @@ -333,8 +333,8 @@ impl ContributionParams { } } } -impl From<(AccountIdOf, BalanceOf)> for ContributionParams { - fn from((contributor, amount): (AccountIdOf, BalanceOf)) -> Self { +impl From<(AccountIdOf, Balance)> for ContributionParams { + fn from((contributor, amount): (AccountIdOf, Balance)) -> Self { Self { contributor, amount, @@ -343,14 +343,14 @@ impl From<(AccountIdOf, BalanceOf)> for ContributionParams { } } } -impl From<(AccountIdOf, BalanceOf, MultiplierOf)> for ContributionParams { - fn from((contributor, amount, multiplier): (AccountIdOf, BalanceOf, MultiplierOf)) -> Self { +impl From<(AccountIdOf, Balance, MultiplierOf)> for ContributionParams { + fn from((contributor, amount, multiplier): (AccountIdOf, Balance, MultiplierOf)) -> Self { Self { contributor, amount, multiplier, asset: AcceptedFundingAsset::USDT } } } -impl From<(AccountIdOf, BalanceOf, MultiplierOf, AcceptedFundingAsset)> for ContributionParams { +impl From<(AccountIdOf, Balance, MultiplierOf, AcceptedFundingAsset)> for ContributionParams { fn from( - (contributor, amount, multiplier, asset): (AccountIdOf, BalanceOf, MultiplierOf, AcceptedFundingAsset), + (contributor, amount, multiplier, asset): (AccountIdOf, Balance, MultiplierOf, AcceptedFundingAsset), ) -> Self { Self { contributor, amount, multiplier, asset } } @@ -372,13 +372,13 @@ pub struct BidInfoFilter { pub id: Option, pub project_id: Option, pub bidder: Option>, - pub status: Option>>, - pub original_ct_amount: Option>, + pub status: Option, + pub original_ct_amount: Option, pub original_ct_usd_price: Option>, pub funding_asset: Option, - pub funding_asset_amount_locked: Option>, + pub funding_asset_amount_locked: Option, pub multiplier: Option>, - pub plmc_bond: Option>, + pub plmc_bond: Option, pub when: Option>, } impl BidInfoFilter { diff --git a/pallets/funding/src/lib.rs b/pallets/funding/src/lib.rs index 9950ece28..47ae6af37 100644 --- a/pallets/funding/src/lib.rs +++ b/pallets/funding/src/lib.rs @@ -78,7 +78,7 @@ extern crate alloc; pub use crate::weights::WeightInfo; use frame_support::{ traits::{ - tokens::{fungible, fungibles, Balance}, + tokens::{fungible, fungibles}, AccountTouch, ContainsPair, Randomness, }, BoundedVec, PalletId, @@ -92,7 +92,7 @@ use polimec_common::{ }; use polkadot_parachain_primitives::primitives::Id as ParaId; use sp_arithmetic::traits::{One, Saturating}; -use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedPointOperand, FixedU128}; +use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedU128}; use sp_std::{marker::PhantomData, prelude::*}; pub use types::*; use xcm::v4::{prelude::*, SendXcm}; @@ -118,32 +118,25 @@ pub mod runtime_api; pub type AccountIdOf = ::AccountId; pub type ProjectId = u32; +pub type Balance = u128; pub type MultiplierOf = ::Multiplier; -pub type BalanceOf = ::Balance; pub type PriceOf = ::Price; pub type PriceProviderOf = ::PriceProvider; pub type StringLimitOf = ::StringLimit; pub type AssetIdOf = <::FundingCurrency as fungibles::Inspect<::AccountId>>::AssetId; -pub type RewardInfoOf = RewardInfo>; -pub type EvaluatorsOutcomeOf = EvaluatorsOutcome>; -pub type VestingInfoOf = VestingInfo, BalanceOf>; - -pub type TicketSizeOf = TicketSize>; -pub type ProjectMetadataOf = - ProjectMetadata>, BalanceOf, PriceOf, AccountIdOf, Cid>; -pub type ProjectDetailsOf = - ProjectDetails, Did, BlockNumberFor, PriceOf, BalanceOf, EvaluationRoundInfoOf>; -pub type EvaluationRoundInfoOf = EvaluationRoundInfo>; -pub type EvaluationInfoOf = EvaluationInfo, BalanceOf, BlockNumberFor>; -pub type BidInfoOf = - BidInfo, PriceOf, AccountIdOf, BlockNumberFor, MultiplierOf>; +pub type VestingInfoOf = VestingInfo>; + +pub type ProjectMetadataOf = ProjectMetadata>, PriceOf, AccountIdOf, Cid>; +pub type ProjectDetailsOf = ProjectDetails, Did, BlockNumberFor, PriceOf, EvaluationRoundInfo>; +pub type EvaluationInfoOf = EvaluationInfo, BlockNumberFor>; +pub type BidInfoOf = BidInfo, AccountIdOf, BlockNumberFor, MultiplierOf>; pub type ContributionInfoOf = - ContributionInfo, BalanceOf, BlockNumberFor, MultiplierOf>; + ContributionInfo, BlockNumberFor, MultiplierOf>; -pub type BucketOf = Bucket, PriceOf>; +pub type BucketOf = Bucket>; pub type WeightInfoOf = ::WeightInfo; pub type VestingOf = pallet_linear_release::Pallet; @@ -181,12 +174,9 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config - + pallet_balances::Config> + + pallet_balances::Config + pallet_xcm::Config - + pallet_linear_release::Config< - Balance = BalanceOf, - RuntimeHoldReason = ::RuntimeHoldReason, - > + + pallet_linear_release::Config::RuntimeHoldReason> { /// A way to convert from and to the account type used in CT migrations type AccountId32Conversion: ConvertBack; @@ -197,9 +187,6 @@ pub mod pallet { + OnIdle> + OnInitialize>; - /// The inner balance type we will use for all of our outer currency types. (e.g native, funding, CTs) - type Balance: Balance + From + FixedPointOperand + MaybeSerializeDeserialize + Into; - // TODO: our local BlockNumber should be removed once we move onto using Moment for time tracking /// BlockNumber used for PLMC vesting durations on this chain, and CT vesting durations on funded chains. type BlockNumber: IsType> + Into; @@ -209,18 +196,18 @@ pub mod pallet { type CommunityRoundDuration: Get>; /// The currency used for minting contribution tokens as fungible assets (i.e pallet-assets) - type ContributionTokenCurrency: fungibles::Create, AssetId = ProjectId, Balance = BalanceOf> - + fungibles::Destroy, AssetId = ProjectId, Balance = BalanceOf> + type ContributionTokenCurrency: fungibles::Create, AssetId = ProjectId, Balance = Balance> + + fungibles::Destroy, AssetId = ProjectId, Balance = Balance> + fungibles::InspectEnumerable< AccountIdOf, - Balance = BalanceOf, + Balance = Balance, AssetsIterator = KeyPrefixIterator>, > + fungibles::metadata::Inspect> + fungibles::metadata::Mutate> - + fungibles::metadata::MetadataDeposit> - + fungibles::Mutate, Balance = BalanceOf> + + fungibles::metadata::MetadataDeposit + + fungibles::Mutate, Balance = Balance> + fungibles::roles::Inspect> - + AccountTouch, Balance = BalanceOf> + + AccountTouch, Balance = Balance> + ContainsPair>; /// Convert 24 hours as FixedU128, to the corresponding amount of blocks in the same type as frame_system @@ -244,13 +231,13 @@ pub mod pallet { /// The fee brackets for the project's funding #[pallet::constant] - type FeeBrackets: Get::Balance)>>; + type FeeBrackets: Get>; /// The currency used for funding projects in bids and contributions - type FundingCurrency: fungibles::InspectEnumerable, Balance = BalanceOf, AssetId = u32> + type FundingCurrency: fungibles::InspectEnumerable, Balance = Balance, AssetId = u32> + fungibles::metadata::Inspect, AssetId = u32> + fungibles::metadata::Mutate, AssetId = u32> - + fungibles::Mutate, Balance = BalanceOf>; + + fungibles::Mutate, Balance = Balance>; type FundingSuccessThreshold: Get; @@ -285,7 +272,7 @@ pub mod pallet { type MaxEvaluationsPerUser: Get; #[pallet::constant] - type MinUsdPerEvaluation: Get>; + type MinUsdPerEvaluation: Get; /// RangeInclusive of max_message_size values for the hrmp config where we accept the incoming channel request #[pallet::constant] @@ -303,14 +290,11 @@ pub mod pallet { + MaybeSerializeDeserialize; /// The chains native currency - type NativeCurrency: fungible::InspectHold, Balance = BalanceOf> - + fungible::MutateHold< - AccountIdOf, - Balance = BalanceOf, - Reason = ::RuntimeHoldReason, - > + fungible::BalancedHold, Balance = BalanceOf> - + fungible::Mutate, Balance = BalanceOf> - + fungible::Inspect, Balance = BalanceOf>; + type NativeCurrency: fungible::InspectHold, Balance = Balance> + + fungible::MutateHold, Balance = Balance, Reason = ::RuntimeHoldReason> + + fungible::BalancedHold, Balance = Balance> + + fungible::Mutate, Balance = Balance> + + fungible::Inspect, Balance = Balance>; /// System account for the funding pallet. Used to derive project escrow accounts. #[pallet::constant] @@ -447,20 +431,12 @@ pub mod pallet { >; #[pallet::storage] - pub type AuctionBoughtUSD = StorageNMap< - _, - (NMapKey, NMapKey), - BalanceOf, - ValueQuery, - >; + pub type AuctionBoughtUSD = + StorageNMap<_, (NMapKey, NMapKey), Balance, ValueQuery>; #[pallet::storage] - pub type ContributionBoughtUSD = StorageNMap< - _, - (NMapKey, NMapKey), - BalanceOf, - ValueQuery, - >; + pub type ContributionBoughtUSD = + StorageNMap<_, (NMapKey, NMapKey), Balance, ValueQuery>; #[pallet::storage] pub type UserMigrations = StorageNMap< @@ -521,18 +497,18 @@ pub mod pallet { project_id: ProjectId, evaluator: AccountIdOf, id: u32, - plmc_amount: BalanceOf, + plmc_amount: Balance, }, /// A bid was made for a project Bid { project_id: ProjectId, bidder: AccountIdOf, id: u32, - ct_amount: BalanceOf, + ct_amount: Balance, ct_price: T::Price, funding_asset: AcceptedFundingAsset, - funding_amount: BalanceOf, - plmc_bond: BalanceOf, + funding_amount: Balance, + plmc_bond: Balance, multiplier: MultiplierOf, }, /// A contribution was made for a project. i.e token purchase @@ -540,39 +516,39 @@ pub mod pallet { project_id: ProjectId, contributor: AccountIdOf, id: u32, - ct_amount: BalanceOf, + ct_amount: Balance, funding_asset: AcceptedFundingAsset, - funding_amount: BalanceOf, - plmc_bond: BalanceOf, + funding_amount: Balance, + plmc_bond: Balance, multiplier: MultiplierOf, }, BidRefunded { project_id: ProjectId, account: AccountIdOf, bid_id: u32, - plmc_amount: BalanceOf, + plmc_amount: Balance, funding_asset: AcceptedFundingAsset, - funding_amount: BalanceOf, + funding_amount: Balance, }, EvaluationSettled { project_id: ProjectId, account: AccountIdOf, id: u32, - ct_rewarded: BalanceOf, - plmc_released: BalanceOf, + ct_rewarded: Balance, + plmc_released: Balance, }, BidSettled { project_id: ProjectId, account: AccountIdOf, id: u32, - final_ct_amount: BalanceOf, + final_ct_amount: Balance, final_ct_usd_price: PriceOf, }, ContributionSettled { project_id: ProjectId, account: AccountIdOf, id: u32, - ct_amount: BalanceOf, + ct_amount: Balance, }, PalletMigrationStarted { project_id: ProjectId, @@ -804,7 +780,7 @@ pub mod pallet { origin: OriginFor, jwt: UntrustedToken, project_id: ProjectId, - #[pallet::compact] usd_amount: BalanceOf, + #[pallet::compact] usd_amount: Balance, ) -> DispatchResultWithPostInfo { let (account, did, _investor_type, whitelisted_policy) = T::InvestorOrigin::ensure_origin(origin, &jwt, T::VerifierPublicKey::get())?; @@ -833,7 +809,7 @@ pub mod pallet { origin: OriginFor, jwt: UntrustedToken, project_id: ProjectId, - #[pallet::compact] ct_amount: BalanceOf, + #[pallet::compact] ct_amount: Balance, multiplier: T::Multiplier, funding_asset: AcceptedFundingAsset, ) -> DispatchResultWithPostInfo { @@ -879,7 +855,7 @@ pub mod pallet { origin: OriginFor, jwt: UntrustedToken, project_id: ProjectId, - #[pallet::compact] ct_amount: BalanceOf, + #[pallet::compact] ct_amount: Balance, multiplier: MultiplierOf, funding_asset: AcceptedFundingAsset, ) -> DispatchResultWithPostInfo { diff --git a/pallets/funding/src/mock.rs b/pallets/funding/src/mock.rs index a0455490c..117558c6a 100644 --- a/pallets/funding/src/mock.rs +++ b/pallets/funding/src/mock.rs @@ -56,7 +56,6 @@ pub const EXISTENTIAL_DEPOSIT: Balance = 10 * MILLI_PLMC; pub type Block = frame_system::mocking::MockBlock; pub type AccountId = u32; -pub type Balance = u128; pub type BlockNumber = u64; pub type Identifier = u32; pub type Price = FixedU128; @@ -396,7 +395,6 @@ impl Config for TestRuntime { type AllPalletsWithoutSystem = (Balances, ContributionTokens, ForeignAssets, PolimecFunding, LinearRelease, RandomnessCollectiveFlip); type AuctionRoundDuration = AuctionRoundDuration; - type Balance = Balance; type BlockNumber = BlockNumber; type BlockchainOperationTreasury = BlockchainOperationTreasuryAccount; type CommunityRoundDuration = CommunityRoundDuration; @@ -531,7 +529,7 @@ sp_api::mock_impl_runtime_apis! { } impl UserInformation for TestRuntime { - fn contribution_tokens(account: AccountId) -> Vec<(ProjectId, BalanceOf)> { + fn contribution_tokens(account: AccountId) -> Vec<(ProjectId, Balance)> { PolimecFunding::contribution_tokens(account) } @@ -551,7 +549,7 @@ sp_api::mock_impl_runtime_apis! { } impl ExtrinsicHelpers for TestRuntime { - fn funding_asset_to_ct_amount(project_id: ProjectId, asset: AcceptedFundingAsset, asset_amount: BalanceOf) -> BalanceOf { + fn funding_asset_to_ct_amount(project_id: ProjectId, asset: AcceptedFundingAsset, asset_amount: Balance) -> Balance { PolimecFunding::funding_asset_to_ct_amount(project_id, asset, asset_amount) } } diff --git a/pallets/funding/src/runtime_api.rs b/pallets/funding/src/runtime_api.rs index 7c87835aa..9ddd81865 100644 --- a/pallets/funding/src/runtime_api.rs +++ b/pallets/funding/src/runtime_api.rs @@ -38,7 +38,7 @@ sp_api::decl_runtime_apis! { #[api_version(1)] pub trait UserInformation { /// Get all the contribution token balances for the participated projects - fn contribution_tokens(account: AccountIdOf) -> Vec<(ProjectId, BalanceOf)>; + fn contribution_tokens(account: AccountIdOf) -> Vec<(ProjectId, Balance)>; /// Get all the project participations made by a single DID. fn all_project_participations_by_did(project_id: ProjectId, did: Did) -> Vec>; @@ -57,7 +57,7 @@ sp_api::decl_runtime_apis! { pub trait ExtrinsicHelpers { /// Get the current price of a contribution token (either current bucket in the auction, or WAP in contribution phase), /// and calculate the amount of tokens that can be bought with the given amount USDT/USDC/DOT. - fn funding_asset_to_ct_amount(project_id: ProjectId, asset: AcceptedFundingAsset, asset_amount: BalanceOf) -> BalanceOf; + fn funding_asset_to_ct_amount(project_id: ProjectId, asset: AcceptedFundingAsset, asset_amount: Balance) -> Balance; } } @@ -101,7 +101,7 @@ impl Pallet { .map(|(project_id, project_details)| { let funding_reached = project_details.funding_amount_reached_usd; let funding_target = project_details.fundraising_target_usd; - let funding_ratio = FixedU128::from_rational(funding_reached.into(), funding_target.into()); + let funding_ratio = FixedU128::from_rational(funding_reached, funding_target); (project_id, project_details, funding_ratio) }) .sorted_by(|a, b| b.2.cmp(&a.2)) @@ -113,7 +113,7 @@ impl Pallet { .collect_vec() } - pub fn contribution_tokens(account: AccountIdOf) -> Vec<(ProjectId, BalanceOf)> { + pub fn contribution_tokens(account: AccountIdOf) -> Vec<(ProjectId, Balance)> { let asset_ids = ::ContributionTokenCurrency::asset_ids(); asset_ids .filter_map(|asset_id| { @@ -131,8 +131,8 @@ impl Pallet { pub fn funding_asset_to_ct_amount( project_id: ProjectId, asset: AcceptedFundingAsset, - asset_amount: BalanceOf, - ) -> BalanceOf { + asset_amount: Balance, + ) -> Balance { let project_details = ProjectsDetails::::get(project_id).expect("Project not found"); let funding_asset_id = asset.id(); let funding_asset_decimals = T::FundingCurrency::decimals(funding_asset_id); @@ -214,7 +214,7 @@ impl Pallet { let project_details = ProjectsDetails::::get(project_id).expect("Project not found"); let funding_reached = project_details.funding_amount_reached_usd; let funding_target = project_details.fundraising_target_usd; - FixedU128::from_rational(funding_reached.into(), funding_target.into()) + FixedU128::from_rational(funding_reached, funding_target) } pub fn projects_by_did(did: Did) -> Vec { diff --git a/pallets/funding/src/storage_migrations.rs b/pallets/funding/src/storage_migrations.rs index e961157b1..841f3f676 100644 --- a/pallets/funding/src/storage_migrations.rs +++ b/pallets/funding/src/storage_migrations.rs @@ -2,4 +2,4 @@ use frame_support::traits::StorageVersion; /// The current storage version pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(5); -pub const LOG: &str = "runtime::funding::migration"; \ No newline at end of file +pub const LOG: &str = "runtime::funding::migration"; diff --git a/pallets/funding/src/tests/2_evaluation.rs b/pallets/funding/src/tests/2_evaluation.rs index 7141bc479..98c8e9f53 100644 --- a/pallets/funding/src/tests/2_evaluation.rs +++ b/pallets/funding/src/tests/2_evaluation.rs @@ -295,7 +295,7 @@ mod start_evaluation_extrinsic { .saturating_mul_int(project_metadata.total_allocation_size), remaining_contribution_tokens: project_metadata.total_allocation_size, funding_amount_reached_usd: 0u128, - evaluation_round_info: EvaluationRoundInfoOf:: { + evaluation_round_info: EvaluationRoundInfo { total_bonded_usd: 0u128, total_bonded_plmc: 0u128, evaluators_outcome: None, diff --git a/pallets/funding/src/tests/4_contribution.rs b/pallets/funding/src/tests/4_contribution.rs index 18e1157a2..ca9cf9b89 100644 --- a/pallets/funding/src/tests/4_contribution.rs +++ b/pallets/funding/src/tests/4_contribution.rs @@ -129,7 +129,7 @@ mod round_flow { default_bids(), ); let project_details = inst.get_project_details(project_id); - let bid_ct_sold: BalanceOf = inst.execute(|| { + let bid_ct_sold: Balance = inst.execute(|| { Bids::::iter_prefix_values((project_id,)).fold(Zero::zero(), |acc, bid| { assert_eq!(bid.status, BidStatus::Accepted); acc + bid.original_ct_amount @@ -1029,7 +1029,7 @@ mod contribute_extrinsic { let token_price = project_details.weighted_average_price.unwrap(); // Create a contribution vector that will reach the limit of contributions for a user-project - let token_amount: BalanceOf = CT_UNIT; + let token_amount: Balance = CT_UNIT; let range = 0..::MaxContributionsPerUser::get(); let contributions: Vec> = range .map(|_| ContributionParams::new(CONTRIBUTOR, token_amount, 1u8, AcceptedFundingAsset::USDT)) @@ -1072,7 +1072,7 @@ mod contribute_extrinsic { let foreign_asset_contributions_stored = inst.execute(|| { Contributions::::iter_prefix_values((project_id, CONTRIBUTOR)) .map(|c| c.funding_asset_amount) - .sum::>() + .sum::() }); assert_eq!(plmc_bond_stored, inst.sum_balance_mappings(vec![plmc_funding.clone()])); diff --git a/pallets/funding/src/tests/5_funding_end.rs b/pallets/funding/src/tests/5_funding_end.rs index 87025e39f..1d6dc8e9a 100644 --- a/pallets/funding/src/tests/5_funding_end.rs +++ b/pallets/funding/src/tests/5_funding_end.rs @@ -82,7 +82,7 @@ mod end_funding_extrinsic { const EARLY_EVALUATOR_TOTAL_USD_BONDED: u128 = 1_000_000 * USD_UNIT; const NORMAL_EVALUATOR_TOTAL_USD_BONDED: u128 = 1_070_000 * USD_UNIT; - let expected_reward_info = RewardInfoOf:: { + let expected_reward_info = RewardInfo { early_evaluator_reward_pot: early_evaluator_reward, normal_evaluator_reward_pot: normal_evaluator_reward, early_evaluator_total_bonded_usd: EARLY_EVALUATOR_TOTAL_USD_BONDED, diff --git a/pallets/funding/src/tests/6_settlement.rs b/pallets/funding/src/tests/6_settlement.rs index 65f16ff18..198e1ad43 100644 --- a/pallets/funding/src/tests/6_settlement.rs +++ b/pallets/funding/src/tests/6_settlement.rs @@ -276,7 +276,7 @@ mod settle_evaluation_extrinsic { assert_eq!( inst.get_project_details(project_id).evaluation_round_info.evaluators_outcome, - Some(EvaluatorsOutcomeOf::::Slashed) + Some(EvaluatorsOutcome::Slashed) ); assert_ok!(inst.execute(|| PolimecFunding::settle_evaluation( diff --git a/pallets/funding/src/tests/misc.rs b/pallets/funding/src/tests/misc.rs index 456cee4c1..76108ff14 100644 --- a/pallets/funding/src/tests/misc.rs +++ b/pallets/funding/src/tests/misc.rs @@ -67,25 +67,25 @@ mod helper_functions { fn calculate_evaluation_plmc_spent() { let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); const EVALUATOR_1: AccountIdOf = 1u32; - const USD_AMOUNT_1: BalanceOf = 150_000 * USD_UNIT; + const USD_AMOUNT_1: Balance = 150_000 * USD_UNIT; const EXPECTED_PLMC_AMOUNT_1: f64 = 17_857.1428571428f64; const EVALUATOR_2: AccountIdOf = 2u32; - const USD_AMOUNT_2: BalanceOf = 50_000 * USD_UNIT; + const USD_AMOUNT_2: Balance = 50_000 * USD_UNIT; const EXPECTED_PLMC_AMOUNT_2: f64 = 5_952.3809523809f64; const EVALUATOR_3: AccountIdOf = 3u32; - const USD_AMOUNT_3: BalanceOf = 75_000 * USD_UNIT; + const USD_AMOUNT_3: Balance = 75_000 * USD_UNIT; const EXPECTED_PLMC_AMOUNT_3: f64 = 8_928.5714285714f64; const EVALUATOR_4: AccountIdOf = 4u32; - const USD_AMOUNT_4: BalanceOf = 100 * USD_UNIT; + const USD_AMOUNT_4: Balance = 100 * USD_UNIT; const EXPECTED_PLMC_AMOUNT_4: f64 = 11.9047619047f64; const EVALUATOR_5: AccountIdOf = 5u32; // 123.7 USD - const USD_AMOUNT_5: BalanceOf = 1237 * USD_UNIT / 10; + const USD_AMOUNT_5: Balance = 1237 * USD_UNIT / 10; const EXPECTED_PLMC_AMOUNT_5: f64 = 14.7261904761f64; const PLMC_PRICE: f64 = 8.4f64; @@ -224,17 +224,17 @@ mod helper_functions { #[test] fn bucket_wap_calculation() { let initial_price = FixedU128::from_float(10.0); - let mut bucket = Bucket::new(100u32, initial_price, FixedU128::from_float(1.0), 10u32); - let wap = bucket.calculate_wap(100u32); + let mut bucket = Bucket::new(100u128, initial_price, FixedU128::from_float(1.0), 10u128); + let wap = bucket.calculate_wap(100u128); assert!(wap == initial_price); // Initial token amount: 100 // Simulate total bidding amount of 128 - bucket.update(100u32); - bucket.update(10u32); - bucket.update(10u32); - bucket.update(8u32); - let wap = bucket.calculate_wap(100u32); + bucket.update(100u128); + bucket.update(10u128); + bucket.update(10u128); + bucket.update(8u128); + let wap = bucket.calculate_wap(100u128); let expected = FixedU128::from_float(10.628); let diff = if wap > expected { wap - expected } else { expected - wap }; assert!(diff <= FixedU128::from_float(0.001)); diff --git a/pallets/funding/src/tests/mod.rs b/pallets/funding/src/tests/mod.rs index 837d9dca5..eb4038028 100644 --- a/pallets/funding/src/tests/mod.rs +++ b/pallets/funding/src/tests/mod.rs @@ -407,8 +407,8 @@ pub fn create_project_with_funding_percentage( pub fn create_finished_project_with_usd_raised( mut inst: MockInstantiator, - usd_raised: BalanceOf, - usd_target: BalanceOf, + usd_raised: Balance, + usd_target: Balance, ) -> (MockInstantiator, ProjectId) { let issuer = inst.get_new_nonce() as u32; let mut project_metadata = default_project_metadata(issuer); diff --git a/pallets/funding/src/traits.rs b/pallets/funding/src/traits.rs index 94af27f2d..fa95b6e29 100644 --- a/pallets/funding/src/traits.rs +++ b/pallets/funding/src/traits.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{BalanceOf, Config, ProjectId}; +use crate::{Balance, Config, ProjectId}; use frame_support::weights::Weight; use frame_system::pallet_prelude::BlockNumberFor; use sp_arithmetic::{ @@ -24,7 +24,7 @@ use sp_arithmetic::{ use sp_runtime::DispatchError; pub trait BondingRequirementCalculation { - fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Option>; + fn calculate_bonding_requirement(&self, ticket_size: Balance) -> Option; } pub trait VestingDurationCalculation { diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index 14205fcc8..a18448195 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -18,18 +18,18 @@ //! Types for Funding pallet. -use crate::{traits::BondingRequirementCalculation, BalanceOf}; +use crate::traits::BondingRequirementCalculation; pub use config::*; pub use extrinsic::*; -use frame_support::{pallet_prelude::*, traits::tokens::Balance as BalanceT}; +use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::BlockNumberFor; 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::{traits::Saturating, FixedPointNumber, FixedPointOperand, FixedU128, Percent}; -use sp_runtime::traits::{CheckedDiv, CheckedMul, Convert, One}; +use sp_arithmetic::{traits::Saturating, FixedPointNumber, FixedU128, Percent}; +use sp_runtime::traits::{Convert, One}; use sp_std::{cmp::Eq, prelude::*}; pub use storage::*; @@ -40,6 +40,7 @@ use sp_runtime::traits::Zero; pub mod config { #[allow(clippy::wildcard_imports)] use super::*; + use crate::Balance; #[derive( Clone, @@ -65,9 +66,9 @@ pub mod config { } impl BondingRequirementCalculation for Multiplier { - fn calculate_bonding_requirement(&self, ticket_size: BalanceOf) -> Option> { - let balance_multiplier = BalanceOf::::from(self.0); - ticket_size.checked_div(&balance_multiplier) + fn calculate_bonding_requirement(&self, ticket_size: Balance) -> Option { + let balance_multiplier = Balance::from(self.0); + ticket_size.checked_div(balance_multiplier) } } @@ -153,9 +154,10 @@ pub mod config { pub mod storage { #[allow(clippy::wildcard_imports)] use super::*; + use crate::Balance; #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo, Serialize, Deserialize)] - pub struct ProjectMetadata { + pub struct ProjectMetadata { /// Token Metadata pub token_information: CurrencyMetadata, /// Mainnet Token Max Supply @@ -167,9 +169,9 @@ pub mod storage { /// The minimum price per token in USD, decimal-aware. See [`calculate_decimals_aware_price()`](crate::traits::ProvideAssetPrice::calculate_decimals_aware_price) for more information. pub minimum_price: Price, /// Maximum and minimum ticket sizes for auction round - pub bidding_ticket_sizes: BiddingTicketSizes, + pub bidding_ticket_sizes: BiddingTicketSizes, /// Maximum and minimum ticket sizes for community/remainder rounds - pub contributing_ticket_sizes: ContributingTicketSizes, + pub contributing_ticket_sizes: ContributingTicketSizes, /// Participation currencies (e.g stablecoin, DOT, KSM) /// e.g. https://github.com/paritytech/substrate/blob/427fd09bcb193c1e79dec85b1e207c718b686c35/frame/uniques/src/types.rs#L110 /// For now is easier to handle the case where only just one Currency is accepted @@ -180,14 +182,7 @@ pub mod storage { pub policy_ipfs_cid: Option, } - impl< - BoundedString, - Balance: From + PartialOrd + Copy + FixedPointOperand + One + CheckedMul, - Price: FixedPointNumber, - AccountId, - Cid, - > ProjectMetadata - { + impl ProjectMetadata { /// Validate issuer metadata for the following checks: /// - Minimum price is not zero /// - Minimum bidding ticket sizes are higher than 5k USD @@ -196,18 +191,16 @@ pub mod storage { if self.minimum_price == Price::zero() { return Err(MetadataError::PriceTooLow); } - let usd_unit = sp_arithmetic::traits::checked_pow(Balance::from(10u64), USD_DECIMALS as usize) + let usd_unit = sp_arithmetic::traits::checked_pow(10u128, USD_DECIMALS as usize) .ok_or(MetadataError::BadTokenomics)?; - let min_bidder_bound_usd: Balance = - usd_unit.checked_mul(&5000u64.into()).ok_or(MetadataError::BadTokenomics)?; + let min_bidder_bound_usd: Balance = usd_unit.checked_mul(5000u128).ok_or(MetadataError::BadTokenomics)?; self.bidding_ticket_sizes.is_valid(vec![ InvestorTypeUSDBounds::Professional((min_bidder_bound_usd, None).into()), InvestorTypeUSDBounds::Institutional((min_bidder_bound_usd, None).into()), ])?; - let min_contributor_bound_usd: Balance = - usd_unit.checked_mul(&1u64.into()).ok_or(MetadataError::BadTokenomics)?; + let min_contributor_bound_usd: Balance = usd_unit.checked_mul(1u128).ok_or(MetadataError::BadTokenomics)?; self.contributing_ticket_sizes.is_valid(vec![ InvestorTypeUSDBounds::Institutional((min_contributor_bound_usd, None).into()), InvestorTypeUSDBounds::Professional((min_contributor_bound_usd, None).into()), @@ -216,8 +209,7 @@ pub mod storage { if self.total_allocation_size == 0u64.into() || self.total_allocation_size > self.mainnet_token_max_supply || - self.total_allocation_size < - Balance::from(10u64).saturating_pow(self.token_information.decimals as usize) + self.total_allocation_size < 10u128.saturating_pow(self.token_information.decimals as u32) { return Err(MetadataError::AllocationSizeError); } @@ -265,21 +257,21 @@ pub mod storage { } } - pub struct Bound { + pub struct Bound { pub lower: Balance, pub upper: Option, } - impl From<(Balance, Option)> for Bound { + impl From<(Balance, Option)> for Bound { fn from(value: (Balance, Option)) -> Self { Self { lower: value.0, upper: value.1 } } } - pub enum InvestorTypeUSDBounds { - Retail(Bound), - Professional(Bound), - Institutional(Bound), + pub enum InvestorTypeUSDBounds { + Retail(Bound), + Professional(Bound), + Institutional(Bound), } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] @@ -299,14 +291,7 @@ pub mod storage { } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] - pub struct ProjectDetails< - AccountId, - Did, - BlockNumber, - Price: FixedPointNumber, - Balance: BalanceT, - EvaluationRoundInfo, - > { + pub struct ProjectDetails { pub issuer_account: AccountId, pub issuer_did: Did, /// Whether the project is frozen, so no `metadata` changes are allowed. @@ -346,7 +331,7 @@ pub mod storage { } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen, Ord, PartialOrd)] - pub struct EvaluationInfo { + pub struct EvaluationInfo { pub id: Id, pub did: Did, pub project_id: ProjectId, @@ -360,12 +345,12 @@ pub mod storage { } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] - pub struct BidInfo { + pub struct BidInfo { pub id: u32, pub project_id: ProjectId, pub bidder: AccountId, pub did: Did, - pub status: BidStatus, + pub status: BidStatus, #[codec(compact)] pub original_ct_amount: Balance, pub original_ct_usd_price: Price, @@ -375,8 +360,8 @@ pub mod storage { pub plmc_bond: Balance, pub when: BlockNumber, } - impl - BidInfo + impl + BidInfo { pub fn final_ct_amount(&self) -> Balance { match self.status { @@ -387,15 +372,8 @@ pub mod storage { } } - impl< - ProjectId: Eq, - Did: Eq, - Balance: BalanceT + FixedPointOperand + Ord, - Price: FixedPointNumber, - AccountId: Eq, - BlockNumber: Eq + Ord, - Multiplier: Eq, - > Ord for BidInfo + impl Ord + for BidInfo { fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering { match self.original_ct_usd_price.cmp(&other.original_ct_usd_price) { @@ -405,15 +383,8 @@ pub mod storage { } } - impl< - ProjectId: Eq, - Did: Eq, - Balance: BalanceT + FixedPointOperand, - Price: FixedPointNumber, - AccountId: Eq, - BlockNumber: Eq + Ord, - Multiplier: Eq, - > PartialOrd for BidInfo + impl + PartialOrd for BidInfo { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) @@ -421,7 +392,7 @@ pub mod storage { } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] - pub struct ContributionInfo { + pub struct ContributionInfo { pub id: Id, pub did: Did, pub project_id: ProjectId, @@ -439,7 +410,7 @@ pub mod storage { /// Each bucket has a unique ID, an amount of tokens left, a current price, an initial price, /// and constants to define price and amount increments for the next buckets. #[derive(Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] - pub struct Bucket { + pub struct Bucket { /// The amount of tokens left in this bucket. pub amount_left: Balance, /// The current price of tokens in this bucket. @@ -452,7 +423,7 @@ pub mod storage { pub delta_amount: Balance, } - impl Bucket { + impl Bucket { /// Creates a new bucket with the given parameters. pub const fn new( amount_left: Balance, @@ -511,6 +482,7 @@ pub mod storage { pub mod inner { #[allow(clippy::wildcard_imports)] use super::*; + use crate::Balance; use variant_count::VariantCount; use xcm::v4::QueryId; @@ -553,11 +525,11 @@ pub mod inner { #[derive( Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo, Serialize, Deserialize, )] - pub struct TicketSize { + pub struct TicketSize { pub usd_minimum_per_participation: Balance, pub usd_maximum_per_did: Option, } - impl TicketSize { + impl TicketSize { pub fn new(usd_minimum_per_participation: Balance, usd_maximum_per_did: Option) -> Self { Self { usd_minimum_per_participation, usd_maximum_per_did } } @@ -573,7 +545,7 @@ pub mod inner { } } - pub fn check_valid(&self, bound: Bound) -> bool { + pub fn check_valid(&self, bound: Bound) -> bool { if let (min, Some(max)) = (self.usd_minimum_per_participation, self.usd_maximum_per_did) { if min > max { return false @@ -597,13 +569,13 @@ pub mod inner { #[derive( Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo, Serialize, Deserialize, )] - pub struct BiddingTicketSizes { - pub professional: TicketSize, - pub institutional: TicketSize, + pub struct BiddingTicketSizes { + pub professional: TicketSize, + pub institutional: TicketSize, pub phantom: PhantomData<(Price, Balance)>, } - impl BiddingTicketSizes { - pub fn is_valid(&self, usd_bounds: Vec>) -> Result<(), MetadataError> { + impl BiddingTicketSizes { + pub fn is_valid(&self, usd_bounds: Vec) -> Result<(), MetadataError> { for bound in usd_bounds { match bound { InvestorTypeUSDBounds::Professional(bound) => @@ -624,14 +596,14 @@ pub mod inner { #[derive( Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo, Serialize, Deserialize, )] - pub struct ContributingTicketSizes { - pub retail: TicketSize, - pub professional: TicketSize, - pub institutional: TicketSize, + pub struct ContributingTicketSizes { + pub retail: TicketSize, + pub professional: TicketSize, + pub institutional: TicketSize, pub phantom: PhantomData<(Price, Balance)>, } - impl ContributingTicketSizes { - pub fn is_valid(&self, usd_bounds: Vec>) -> Result<(), MetadataError> { + impl ContributingTicketSizes { + pub fn is_valid(&self, usd_bounds: Vec) -> Result<(), MetadataError> { for bound in usd_bounds { match bound { InvestorTypeUSDBounds::Professional(bound) => @@ -738,7 +710,7 @@ pub mod inner { } #[derive(Default, Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub enum BidStatus { + pub enum BidStatus { /// The bid is not yet accepted or rejected #[default] YetUnknown, @@ -751,27 +723,27 @@ pub mod inner { } #[derive(Clone, Copy, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub struct VestingInfo { + pub struct VestingInfo { pub total_amount: Balance, pub amount_per_block: Balance, pub duration: BlockNumber, } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub struct EvaluationRoundInfo { + pub struct EvaluationRoundInfo { pub total_bonded_usd: Balance, pub total_bonded_plmc: Balance, - pub evaluators_outcome: Option>, + pub evaluators_outcome: Option, } #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub enum EvaluatorsOutcome { - Rewarded(RewardInfo), + pub enum EvaluatorsOutcome { + Rewarded(RewardInfo), Slashed, } #[derive(Default, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub struct RewardInfo { + pub struct RewardInfo { // Total "Early Evaluators" rewards amount in Contribution Tokens pub early_evaluator_reward_pot: Balance, // Total "Normal Evaluators" rewards amount in Contribution Tokens @@ -832,8 +804,8 @@ pub mod inner { pub mod extrinsic { use crate::{ - AcceptedFundingAsset, AccountIdOf, BalanceOf, Config, MultiplierOf, PriceOf, ProjectDetailsOf, ProjectId, - TicketSizeOf, + AcceptedFundingAsset, AccountIdOf, Balance, Config, MultiplierOf, PriceOf, ProjectDetailsOf, ProjectId, + TicketSize, }; use frame_system::pallet_prelude::BlockNumberFor; use polimec_common::credentials::{Cid, Did, InvestorType}; @@ -841,7 +813,7 @@ pub mod extrinsic { pub struct DoBidParams { pub bidder: AccountIdOf, pub project_id: ProjectId, - pub ct_amount: BalanceOf, + pub ct_amount: Balance, pub multiplier: MultiplierOf, pub funding_asset: AcceptedFundingAsset, pub did: Did, @@ -852,14 +824,14 @@ pub mod extrinsic { pub struct DoPerformBidParams { pub bidder: AccountIdOf, pub project_id: ProjectId, - pub ct_amount: BalanceOf, + pub ct_amount: Balance, 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 metadata_ticket_size_bounds: TicketSize, pub total_bids_by_bidder: u32, pub total_bids_for_project: u32, } @@ -867,7 +839,7 @@ pub mod extrinsic { pub struct DoContributeParams { pub contributor: AccountIdOf, pub project_id: ProjectId, - pub ct_amount: BalanceOf, + pub ct_amount: Balance, pub multiplier: MultiplierOf, pub funding_asset: AcceptedFundingAsset, pub did: Did, @@ -879,7 +851,7 @@ pub mod extrinsic { pub contributor: AccountIdOf, pub project_id: ProjectId, pub project_details: &'a mut ProjectDetailsOf, - pub buyable_tokens: BalanceOf, + pub buyable_tokens: Balance, pub multiplier: MultiplierOf, pub funding_asset: AcceptedFundingAsset, pub investor_type: InvestorType, @@ -889,8 +861,8 @@ pub mod extrinsic { pub struct BidRefund { pub final_ct_usd_price: PriceOf, - pub final_ct_amount: BalanceOf, - pub refunded_plmc: BalanceOf, - pub refunded_funding_asset_amount: BalanceOf, + pub final_ct_amount: Balance, + pub refunded_plmc: Balance, + pub refunded_funding_asset_amount: Balance, } } diff --git a/runtimes/polimec/src/lib.rs b/runtimes/polimec/src/lib.rs index 4bf89f4dd..4257e9ba8 100644 --- a/runtimes/polimec/src/lib.rs +++ b/runtimes/polimec/src/lib.rs @@ -1034,7 +1034,6 @@ impl pallet_funding::Config for Runtime { type AllPalletsWithoutSystem = (Balances, ContributionTokens, ForeignAssets, Oracle, Funding, LinearRelease, Random); type AuctionRoundDuration = AuctionRoundDuration; - type Balance = Balance; type BlockNumber = BlockNumber; type BlockchainOperationTreasury = BlockchainOperationTreasury; type CommunityRoundDuration = CommunityRoundDuration;