From 985eab30636b0a418908c77961cd22f48a4b5840 Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 15:29:04 +0100 Subject: [PATCH 1/6] remove ct token requirement --- integration-tests/src/lib.rs | 4 +- pallets/funding/src/benchmarking.rs | 147 +----------- pallets/funding/src/functions.rs | 117 +--------- pallets/funding/src/impls.rs | 80 +------ pallets/funding/src/instantiator.rs | 83 +------ pallets/funding/src/lib.rs | 13 +- pallets/funding/src/mock.rs | 15 +- pallets/funding/src/tests.rs | 234 +------------------- pallets/funding/src/types.rs | 1 - pallets/funding/src/weights.rs | 130 +---------- runtimes/base/src/lib.rs | 2 +- runtimes/shared-configuration/src/assets.rs | 1 + runtimes/testnet/src/lib.rs | 12 +- 13 files changed, 55 insertions(+), 784 deletions(-) diff --git a/integration-tests/src/lib.rs b/integration-tests/src/lib.rs index e3957a334..d3c1b804e 100644 --- a/integration-tests/src/lib.rs +++ b/integration-tests/src/lib.rs @@ -92,7 +92,7 @@ decl_test_parachains! { }, pallets_extra = { PolkadotXcm: polimec_parachain_runtime::PolkadotXcm, - LocalAssets: polimec_parachain_runtime::LocalAssets, + ContributionTokens: polimec_parachain_runtime::ContributionTokens, ForeignAssets: polimec_parachain_runtime::ForeignAssets, FundingPallet: polimec_parachain_runtime::PolimecFunding, } @@ -182,7 +182,7 @@ pub mod shortcuts { pub type AssetHubBalances = ::Balances; pub type BaseBalances = ::Balances; - pub type PolimecLocalAssets = ::LocalAssets; + pub type PolimecContributionTokens = ::ContributionTokens; pub type PolimecForeignAssets = ::ForeignAssets; pub type PenpalAssets = ::Assets; pub type AssetHubAssets = ::LocalAssets; diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index d8bbb6fee..c881e57b8 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -350,15 +350,6 @@ pub fn fill_projects_to_update( } } -// returns how much PLMC was minted and held to the user -pub fn make_ct_deposit_for(user: AccountIdOf, project_id: ProjectId) { - let ct_deposit = T::ContributionTokenCurrency::deposit_required(project_id); - // Reserve plmc deposit to create a contribution token account for this project - if T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), &user) < ct_deposit { - T::NativeCurrency::hold(&HoldReason::FutureDeposit(project_id).into(), &user, ct_deposit).unwrap(); - } -} - pub fn run_blocks_to_execute_next_transition( project_id: ProjectId, update_type: UpdateType, @@ -532,10 +523,8 @@ mod benchmarks { let evaluations = default_evaluations(); let plmc_for_evaluating = BenchInstantiator::::calculate_evaluation_plmc_spent(evaluations.clone()); let existential_plmc: Vec> = plmc_for_evaluating.accounts().existential_deposits(); - let ct_account_deposits: Vec> = plmc_for_evaluating.accounts().ct_account_deposits(); inst.mint_plmc_to(existential_plmc); - inst.mint_plmc_to(ct_account_deposits); inst.mint_plmc_to(plmc_for_evaluating); inst.advance_time(One::one()).unwrap(); @@ -604,11 +593,8 @@ mod benchmarks { BenchInstantiator::::calculate_evaluation_plmc_spent(vec![extrinsic_evaluation.clone()]); let existential_plmc: Vec> = plmc_for_extrinsic_evaluation.accounts().existential_deposits(); - let ct_account_deposits: Vec> = - plmc_for_extrinsic_evaluation.accounts().ct_account_deposits(); inst.mint_plmc_to(existential_plmc); - inst.mint_plmc_to(ct_account_deposits); inst.mint_plmc_to(plmc_for_existing_evaluations.clone()); inst.mint_plmc_to(plmc_for_extrinsic_evaluation.clone()); @@ -682,45 +668,12 @@ mod benchmarks { ); } - // - We know how many iterations it does in storage - // - We know that it requires a ct deposit - // - We know that it does not require to unbond the lowest evaluation - #[benchmark] - pub fn first_evaluation() { - // How many other evaluations the user did for that same project - let x = 0; - let (inst, project_id, extrinsic_evaluation, extrinsic_plmc_bonded, total_expected_plmc_bonded) = - evaluation_setup::(x); - - let jwt = get_mock_jwt( - extrinsic_evaluation.account.clone(), - InvestorType::Institutional, - generate_did_from_account(extrinsic_evaluation.account.clone()), - ); - #[extrinsic_call] - evaluate( - RawOrigin::Signed(extrinsic_evaluation.account.clone()), - jwt, - project_id, - extrinsic_evaluation.usd_amount, - ); - - evaluation_verification::( - inst, - project_id, - extrinsic_evaluation, - extrinsic_plmc_bonded, - total_expected_plmc_bonded, - ); - } - - // - We know that it does not require a ct deposit // - We know that it does not require to unbond the lowest evaluation. // - We don't know how many iterations it does in storage (i.e "x") #[benchmark] - fn second_to_limit_evaluation( + fn evaluation_to_limit( // How many other evaluations the user did for that same project - x: Linear<1, { T::MaxEvaluationsPerUser::get() - 1 }>, + x: Linear<0, { T::MaxEvaluationsPerUser::get() - 1 }>, ) { let (inst, project_id, extrinsic_evaluation, extrinsic_plmc_bonded, total_expected_plmc_bonded) = evaluation_setup::(x); @@ -748,7 +701,6 @@ mod benchmarks { } // - We know how many iterations it does in storage - // - We know that it does not require a ct deposit // - We know that it requires to unbond the lowest evaluation #[benchmark] fn evaluation_over_limit() { @@ -832,7 +784,6 @@ mod benchmarks { ); let existential_deposits: Vec> = vec![bidder.clone()].existential_deposits(); - let ct_account_deposits = vec![bidder.clone()].ct_account_deposits(); let usdt_for_existing_bids: Vec> = BenchInstantiator::::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( @@ -846,7 +797,6 @@ mod benchmarks { inst.mint_plmc_to(plmc_for_existing_bids.clone()); inst.mint_plmc_to(existential_deposits.clone()); - inst.mint_plmc_to(ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_for_existing_bids.clone()); // do "x" contributions for this user @@ -874,7 +824,6 @@ mod benchmarks { current_bucket.current_price, ); let plmc_ed = plmc_for_new_bidder.accounts().existential_deposits(); - let plmc_ct_deposit = plmc_for_new_bidder.accounts().ct_account_deposits(); let usdt_for_new_bidder = BenchInstantiator::::calculate_auction_funding_asset_charged_with_given_price( &vec![bid_params.clone()], current_bucket.current_price, @@ -882,7 +831,6 @@ mod benchmarks { inst.mint_plmc_to(plmc_for_new_bidder); inst.mint_plmc_to(plmc_ed); - inst.mint_plmc_to(plmc_ct_deposit); inst.mint_foreign_asset_to(usdt_for_new_bidder.clone()); inst.bid_for_users(project_id, vec![bid_params]).unwrap(); @@ -1056,7 +1004,7 @@ mod benchmarks { } #[benchmark] - fn bid_no_ct_deposit( + fn bid( // amount of already made bids by the same user x: Linear<0, { T::MaxBidsPerUser::get() - 1 }>, // amount of times where `perform_bid` is called (i.e how many buckets) @@ -1076,58 +1024,6 @@ mod benchmarks { total_usdt_locked, ) = bid_setup::(x, y); - let _new_plmc_minted = make_ct_deposit_for::(original_extrinsic_bid.bidder.clone(), project_id); - - let jwt = get_mock_jwt( - original_extrinsic_bid.bidder.clone(), - InvestorType::Institutional, - generate_did_from_account(original_extrinsic_bid.bidder.clone()), - ); - #[extrinsic_call] - bid( - RawOrigin::Signed(original_extrinsic_bid.bidder.clone()), - jwt, - project_id, - original_extrinsic_bid.amount, - original_extrinsic_bid.multiplier, - original_extrinsic_bid.asset, - ); - - bid_verification::( - inst, - project_id, - project_metadata, - maybe_filler_bid, - extrinsic_bids_post_bucketing, - existing_bids_post_bucketing, - total_free_plmc, - total_plmc_bonded, - total_free_usdt, - total_usdt_locked, - ); - } - - #[benchmark] - fn bid_with_ct_deposit( - // amount of times where `perform_bid` is called (i.e how many buckets) - y: Linear<0, 10>, - ) { - // if x were > 0, then the ct deposit would already be paid - let x = 0; - let ( - inst, - project_id, - project_metadata, - original_extrinsic_bid, - maybe_filler_bid, - extrinsic_bids_post_bucketing, - existing_bids_post_bucketing, - total_free_plmc, - total_plmc_bonded, - total_free_usdt, - total_usdt_locked, - ) = bid_setup::(x, y); - let jwt = get_mock_jwt( original_extrinsic_bid.bidder.clone(), InvestorType::Institutional, @@ -1231,8 +1127,6 @@ mod benchmarks { let existential_deposits: Vec> = plmc_for_extrinsic_contribution.accounts().existential_deposits(); - let ct_account_deposits: Vec> = - plmc_for_extrinsic_contribution.accounts().ct_account_deposits(); let escrow_account = Pallet::::fund_account_id(project_id); let prev_total_usdt_locked = inst.get_free_foreign_asset_balances_for(usdt_id(), vec![escrow_account.clone()]); @@ -1240,7 +1134,6 @@ mod benchmarks { inst.mint_plmc_to(plmc_for_existing_contributions.clone()); inst.mint_plmc_to(plmc_for_extrinsic_contribution.clone()); inst.mint_plmc_to(existential_deposits.clone()); - inst.mint_plmc_to(ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_for_existing_contributions.clone()); inst.mint_foreign_asset_to(usdt_for_extrinsic_contribution.clone()); @@ -1329,8 +1222,8 @@ mod benchmarks { let stored_project_details = ProjectsDetails::::get(project_id).unwrap(); - let bid_ct_sold = Bids::::iter_prefix_values((project_id,)) - .map(|bid| bid.final_ct_amount) + let bid_ct_sold = crate::Bids::::iter_prefix_values((project_id,)) + .map(|bid_in_project: BidInfoOf| bid_in_project.final_ct_amount) .fold(Zero::zero(), |acc, x| acc + x); assert_eq!( @@ -2646,10 +2539,8 @@ mod benchmarks { let evaluations = default_evaluations(); let plmc_for_evaluating = BenchInstantiator::::calculate_evaluation_plmc_spent(evaluations.clone()); let existential_plmc: Vec> = plmc_for_evaluating.accounts().existential_deposits(); - let ct_account_deposits: Vec> = plmc_for_evaluating.accounts().ct_account_deposits(); inst.mint_plmc_to(existential_plmc); - inst.mint_plmc_to(ct_account_deposits); inst.mint_plmc_to(plmc_for_evaluating); inst.advance_time(One::one()).unwrap(); @@ -2709,10 +2600,8 @@ mod benchmarks { ]; let plmc_for_evaluating = BenchInstantiator::::calculate_evaluation_plmc_spent(evaluations.clone()); let existential_plmc: Vec> = plmc_for_evaluating.accounts().existential_deposits(); - let ct_account_deposits: Vec> = plmc_for_evaluating.accounts().ct_account_deposits(); inst.mint_plmc_to(existential_plmc); - inst.mint_plmc_to(ct_account_deposits); inst.mint_plmc_to(plmc_for_evaluating); inst.advance_time(One::one()).unwrap(); @@ -2873,7 +2762,6 @@ mod benchmarks { None, ); let plmc_ed = all_bids.accounts().existential_deposits(); - let plmc_ct_account_deposit = all_bids.accounts().ct_account_deposits(); let funding_asset_needed_for_bids = BenchInstantiator::::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( &all_bids, @@ -2883,7 +2771,6 @@ mod benchmarks { inst.mint_plmc_to(plmc_needed_for_bids); inst.mint_plmc_to(plmc_ed); - inst.mint_plmc_to(plmc_ct_account_deposit); inst.mint_foreign_asset_to(funding_asset_needed_for_bids); inst.bid_for_users(project_id, accepted_bids).unwrap(); @@ -3233,11 +3120,9 @@ mod benchmarks { let plmc_needed_for_evaluating = BenchInstantiator::::calculate_evaluation_plmc_spent(evaluations.clone()); let plmc_ed = evaluations.accounts().existential_deposits(); - let plmc_ct_account_deposit = evaluations.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_needed_for_evaluating); inst.mint_plmc_to(plmc_ed); - inst.mint_plmc_to(plmc_ct_account_deposit); let bids: Vec> = BenchInstantiator::generate_bids_from_total_usd( (automatically_rejected_threshold * target_funding_amount) / 2.into(), @@ -3484,16 +3369,9 @@ mod benchmarks { } #[test] - fn bench_first_evaluation() { - new_test_ext().execute_with(|| { - assert_ok!(PalletFunding::::test_first_evaluation()); - }); - } - - #[test] - fn bench_second_to_limit_evaluation() { + fn bench_evaluation_to_limit() { new_test_ext().execute_with(|| { - assert_ok!(PalletFunding::::test_second_to_limit_evaluation()); + assert_ok!(PalletFunding::::test_evaluation_to_limit()); }); } @@ -3512,16 +3390,9 @@ mod benchmarks { } #[test] - fn bench_bid_with_ct_deposit() { - new_test_ext().execute_with(|| { - assert_ok!(PalletFunding::::test_bid_with_ct_deposit()); - }); - } - - #[test] - fn bench_bid_no_ct_deposit() { + fn bench_bid() { new_test_ext().execute_with(|| { - assert_ok!(PalletFunding::::test_bid_no_ct_deposit()); + assert_ok!(PalletFunding::::test_bid()); }); } diff --git a/pallets/funding/src/functions.rs b/pallets/funding/src/functions.rs index 6f7caeb75..18a772246 100644 --- a/pallets/funding/src/functions.rs +++ b/pallets/funding/src/functions.rs @@ -23,7 +23,7 @@ use frame_support::{ ensure, pallet_prelude::*, traits::{ - fungible::{InspectHold, Mutate, MutateHold as FungibleMutateHold}, + fungible::{Mutate, MutateHold as FungibleMutateHold}, fungibles::{ metadata::{MetadataDeposit, Mutate as MetadataMutate}, Create, Inspect, Mutate as FungiblesMutate, @@ -135,19 +135,6 @@ impl Pallet { ) .map_err(|_| Error::::NotEnoughFundsForEscrowCreation)?; - // Each project's contribution token requires a deposit on the account that stores the tokens. - // We make the issuer pay that deposit for the contribution token treasury account. - let contribution_token_treasury_account = ::ContributionTreasury::get(); - let deposit = T::ContributionTokenCurrency::deposit_required(project_id); - T::NativeCurrency::transfer(issuer, &contribution_token_treasury_account, deposit, Preservation::Preserve) - .map_err(|_| Error::::NotEnoughFundsForCTDeposit)?; - T::NativeCurrency::hold( - &HoldReason::FutureDeposit(project_id).into(), - &contribution_token_treasury_account, - deposit, - ) - .map_err(|_| Error::::NotEnoughFundsForCTDeposit)?; - // Each project needs a new token type to be created (i.e contribution token). // This creation is done automatically in the project transition on success, but someone needs to pay for the storage // of the metadata associated with it. @@ -865,13 +852,6 @@ impl Pallet { )?; let contribution_token_treasury_account = T::ContributionTreasury::get(); - let deposit = T::ContributionTokenCurrency::deposit_required(project_id); - T::NativeCurrency::release( - &HoldReason::FutureDeposit(project_id).into(), - &contribution_token_treasury_account, - deposit, - Precision::BestEffort, - )?; T::ContributionTokenCurrency::touch( project_id, contribution_token_treasury_account.clone(), @@ -962,7 +942,6 @@ impl Pallet { let early_evaluation_reward_threshold_usd = T::EvaluationSuccessThreshold::get() * project_details.fundraising_target; let evaluation_round_info = &mut project_details.evaluation_round_info; - let ct_deposit = T::ContributionTokenCurrency::deposit_required(project_id); let evaluations_count = EvaluationCounts::::get(project_id); // * Validity Checks * @@ -1003,12 +982,6 @@ impl Pallet { ct_migration_status: MigrationStatus::NotStarted, }; - // * Update Storage * - // Reserve plmc deposit to create a contribution token account for this project - if T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), evaluator) < ct_deposit { - T::NativeCurrency::hold(&HoldReason::FutureDeposit(project_id).into(), evaluator, ct_deposit)?; - } - if caller_existing_evaluations.len() < T::MaxEvaluationsPerUser::get() as usize { T::NativeCurrency::hold(&HoldReason::Evaluation(project_id).into(), evaluator, plmc_bond)?; } else { @@ -1047,10 +1020,8 @@ impl Pallet { Self::deposit_event(Event::FundsBonded { project_id, amount: plmc_bond, bonder: evaluator.clone() }); let existing_evaluations_count = caller_existing_evaluations.len() as u32; - let actual_weight = if existing_evaluations_count.is_zero() { - WeightInfoOf::::first_evaluation() - } else if existing_evaluations_count < T::MaxEvaluationsPerUser::get() { - WeightInfoOf::::second_to_limit_evaluation(existing_evaluations_count) + let actual_weight = if existing_evaluations_count < T::MaxEvaluationsPerUser::get() { + WeightInfoOf::::evaluation_to_limit(existing_evaluations_count) } else { WeightInfoOf::::evaluation_over_limit() }; @@ -1084,7 +1055,6 @@ impl Pallet { let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectNotFound)?; let plmc_usd_price = T::PriceProvider::get_price(PLMC_FOREIGN_ID).ok_or(Error::::PriceNotFound)?; - let ct_deposit = T::ContributionTokenCurrency::deposit_required(project_id); let existing_bids = Bids::::iter_prefix_values((project_id, bidder)).collect::>(); let bid_count = BidCounts::::get(project_id); // User will spend at least this amount of USD for his bid(s). More if the bid gets split into different buckets @@ -1092,7 +1062,6 @@ impl Pallet { project_metadata.minimum_price.checked_mul_int(ct_amount).ok_or(Error::::BadMath)?; // weight return variables let mut perform_bid_calls = 0; - let mut ct_deposit_required = false; let existing_bids_amount = existing_bids.len() as u32; let metadata_bidder_ticket_size_bounds = match investor_type { InvestorType::Institutional => project_metadata.bidding_ticket_sizes.institutional, @@ -1127,12 +1096,6 @@ impl Pallet { ); ensure!(existing_bids.len() < T::MaxBidsPerUser::get() as usize, Error::::TooManyBidsForUser); - // Reserve plmc deposit to create a contribution token account for this project - if T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), &bidder) < ct_deposit { - T::NativeCurrency::hold(&HoldReason::FutureDeposit(project_id).into(), &bidder, ct_deposit)?; - ct_deposit_required = true - } - // Fetch current bucket details and other required info let mut current_bucket = Buckets::::get(project_id).ok_or(Error::::ProjectNotFound)?; let now = >::block_number(); @@ -1173,18 +1136,10 @@ impl Pallet { // Note: If the bucket has been exhausted, the 'update' function has already made the 'current_bucket' point to the next one. Buckets::::insert(project_id, current_bucket); - // if ct deposit was required, we already know it can only be the first bid, so existing_bids_amount == 0 - if ct_deposit_required { - Ok(PostDispatchInfo { - actual_weight: Some(WeightInfoOf::::bid_with_ct_deposit(perform_bid_calls)), - pays_fee: Pays::Yes, - }) - } else { - Ok(PostDispatchInfo { - actual_weight: Some(WeightInfoOf::::bid_no_ct_deposit(existing_bids_amount, perform_bid_calls)), - pays_fee: Pays::Yes, - }) - } + Ok(PostDispatchInfo { + actual_weight: Some(WeightInfoOf::::bid(existing_bids_amount, perform_bid_calls)), + pays_fee: Pays::Yes, + }) } fn perform_do_bid( @@ -1402,13 +1357,6 @@ impl Pallet { ct_migration_status: MigrationStatus::NotStarted, }; - // * Update storage * - let ct_deposit = T::ContributionTokenCurrency::deposit_required(project_id); - // Reserve plmc deposit to create a contribution token account for this project - if T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), &contributor) < ct_deposit - { - T::NativeCurrency::hold(&HoldReason::FutureDeposit(project_id).into(), &contributor, ct_deposit)?; - } // Try adding the new contribution to the system Self::try_plmc_participation_lock(contributor, project_id, plmc_bond)?; @@ -1515,12 +1463,6 @@ impl Pallet { // * Update storage * if !T::ContributionTokenCurrency::contains(&project_id, &bid.bidder) { ct_account_created = true; - T::NativeCurrency::release( - &HoldReason::FutureDeposit(project_id).into(), - &bid.bidder, - T::ContributionTokenCurrency::deposit_required(project_id), - Precision::Exact, - )?; T::ContributionTokenCurrency::touch(project_id, bid.bidder.clone(), bid.bidder.clone())?; } T::ContributionTokenCurrency::mint_into(project_id, &bid.bidder, ct_amount)?; @@ -1570,12 +1512,6 @@ impl Pallet { // * Update storage * if !T::ContributionTokenCurrency::contains(&project_id, &contribution.contributor) { ct_account_created = true; - T::NativeCurrency::release( - &HoldReason::FutureDeposit(project_id).into(), - &contribution.contributor, - T::ContributionTokenCurrency::deposit_required(project_id), - Precision::Exact, - )?; T::ContributionTokenCurrency::touch( project_id, contribution.contributor.clone(), @@ -1692,12 +1628,6 @@ impl Pallet { // * Update storage * if !T::ContributionTokenCurrency::contains(&project_id, &evaluation.evaluator) { ct_account_created = true; - T::NativeCurrency::release( - &HoldReason::FutureDeposit(project_id).into(), - &evaluation.evaluator, - T::ContributionTokenCurrency::deposit_required(project_id), - Precision::Exact, - )?; T::ContributionTokenCurrency::touch( project_id, evaluation.evaluator.clone(), @@ -2148,39 +2078,6 @@ impl Pallet { Ok(()) } - pub fn do_release_future_ct_deposit_for( - caller: &AccountIdOf, - project_id: ProjectId, - participant: &AccountIdOf, - ) -> DispatchResult { - // * Get variables * - let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; - let held_plmc = T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), participant); - // * Validity checks * - ensure!( - matches!(project_details.status, ProjectStatus::EvaluationFailed | ProjectStatus::FundingFailed), - Error::::NotAllowed - ); - ensure!(held_plmc > Zero::zero(), Error::::NoFutureDepositHeld); - - // * Update storage * - T::NativeCurrency::release( - &HoldReason::FutureDeposit(project_id).into(), - participant, - T::ContributionTokenCurrency::deposit_required(project_id), - Precision::Exact, - )?; - - // * Emit events * - Self::deposit_event(Event::FutureCTDepositReleased { - project_id, - participant: participant.clone(), - caller: caller.clone(), - }); - - Ok(()) - } - pub fn do_set_para_id_for_project( caller: &AccountIdOf, project_id: ProjectId, diff --git a/pallets/funding/src/impls.rs b/pallets/funding/src/impls.rs index b7f583d6b..76c3929ac 100644 --- a/pallets/funding/src/impls.rs +++ b/pallets/funding/src/impls.rs @@ -16,13 +16,12 @@ use frame_support::{ dispatch::{DispatchErrorWithPostInfo, GetDispatchInfo}, - traits::{fungible::InspectHold, Get}, + traits::Get, weights::Weight, }; -use itertools::Itertools; use sp_arithmetic::traits::Zero; use sp_runtime::{traits::AccountIdConversion, DispatchError}; -use sp_std::{collections::btree_set::BTreeSet, marker::PhantomData}; +use sp_std::marker::PhantomData; use crate::{traits::DoRemainingOperation, *}; @@ -187,8 +186,8 @@ impl DoRemainingOperation for CleanerState { CleanerState::EvaluationRewardOrSlash(remaining, PhantomData::) => if *remaining == 0 { - *self = CleanerState::FutureDepositRelease( - remaining_participants_with_future_ct_deposit::(project_id), + *self = CleanerState::EvaluationUnbonding( + remaining_evaluations::(project_id), PhantomData::, ); Ok(base_weight) @@ -199,20 +198,6 @@ impl DoRemainingOperation for CleanerState { Ok(consumed_weight) }, - CleanerState::FutureDepositRelease(remaining, PhantomData::) => - if *remaining == 0 { - *self = CleanerState::EvaluationUnbonding( - remaining_evaluations::(project_id), - PhantomData::, - ); - Ok(base_weight) - } else { - let (consumed_weight, remaining_participants) = - release_future_ct_deposit_one_participant::(project_id); - *self = CleanerState::FutureDepositRelease(remaining_participants, PhantomData::); - Ok(consumed_weight) - }, - CleanerState::EvaluationUnbonding(remaining, PhantomData::) => if *remaining == 0 { *self = CleanerState::BidFundingRelease( @@ -334,21 +319,6 @@ fn remaining_contributions_without_issuer_payout(project_id: ProjectI Contributions::::iter_prefix_values((project_id,)).filter(|bid| !bid.funds_released).count() as u64 } -fn remaining_participants_with_future_ct_deposit(project_id: ProjectId) -> u64 { - let evaluators = Evaluations::::iter_key_prefix((project_id,)).map(|(evaluator, _evaluation_id)| evaluator); - let bidders = Bids::::iter_key_prefix((project_id,)).map(|(bidder, _bid_id)| bidder); - let contributors = - Contributions::::iter_key_prefix((project_id,)).map(|(contributor, _contribution_id)| contributor); - let all_participants = evaluators.chain(bidders).chain(contributors).collect::>>(); - all_participants - .into_iter() - .filter(|account| { - ::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), account) > - Zero::zero() - }) - .count() as u64 -} - fn reward_or_slash_one_evaluation( project_id: ProjectId, ) -> Result<(Weight, u64), DispatchErrorWithPostInfo> { @@ -505,48 +475,6 @@ fn unbond_one_bid(project_id: ProjectId) -> (Weight, u64) { } } -fn release_future_ct_deposit_one_participant(project_id: ProjectId) -> (Weight, u64) { - let base_weight = Weight::from_parts(10_000_000, 0); - let evaluators = Evaluations::::iter_key_prefix((project_id,)).map(|(evaluator, _evaluation_id)| evaluator); - let bidders = Bids::::iter_key_prefix((project_id,)).map(|(bidder, _bid_id)| bidder); - let contributors = - Contributions::::iter_key_prefix((project_id,)).map(|(contributor, _contribution_id)| contributor); - let all_participants = evaluators.chain(bidders).chain(contributors).collect::>>(); - let remaining_participants = all_participants - .into_iter() - .filter(|account| { - ::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), account) > - Zero::zero() - }) - .collect_vec(); - let mut iter_participants = remaining_participants.into_iter(); - - if let Some(account) = iter_participants.next() { - match Pallet::::do_release_future_ct_deposit_for( - &T::PalletId::get().into_account_truncating(), - project_id, - &account, - ) { - // TODO: replace when benchmark is done - // Ok(_) => return (base_weight.saturating_add(WeightInfoOf::::release_future_ct_deposit_for()), iter_participants.collect_vec()), - Ok(_) => return (base_weight, iter_participants.count() as u64), - // TODO: use when storing remaining accounts in outer function calling do_one_operation https://linear.app/polimec/issue/PLMC-410/cleaner-remaining-users-calculation - // Err(e) if e == Error::::NoFutureDepositHeld.into() => continue, - Err(e) => { - Pallet::::deposit_event(Event::ReleaseFutureCTDepositFailed { - project_id, - participant: account.clone(), - error: e, - }); - // TODO: replace when benchmark is done - // return (base_weight.saturating_add(WeightInfoOf::::release_future_ct_deposit_for()), iter_participants.collect_vec()); - return (base_weight, iter_participants.count() as u64); - }, - }; - } - (base_weight, 0u64) -} - fn release_funds_one_contribution(project_id: ProjectId) -> (Weight, u64) { let project_contributions = Contributions::::iter_prefix_values((project_id,)); let mut remaining_contributions = project_contributions.filter(|contribution| !contribution.funds_released); diff --git a/pallets/funding/src/instantiator.rs b/pallets/funding/src/instantiator.rs index e625e325c..61cde1db5 100644 --- a/pallets/funding/src/instantiator.rs +++ b/pallets/funding/src/instantiator.rs @@ -51,7 +51,6 @@ use sp_std::{ collections::{btree_map::*, btree_set::*}, iter::zip, marker::PhantomData, - ops::Not, }; pub type RuntimeOriginOf = ::RuntimeOrigin; @@ -399,20 +398,11 @@ impl< Self::generic_map_operation(vec![expected_reserved_plmc_balances], MergeOperation::Add); let project_details = self.get_project_details(project_id); - let accounts = expected_reserved_plmc_balances.accounts(); - let expected_ct_account_deposits = accounts - .into_iter() - .map(|account| UserToPLMCBalance { - account, - plmc_amount: ::ContributionTokenCurrency::deposit_required(One::one()), - }) - .collect::>>(); assert_eq!(project_details.status, ProjectStatus::EvaluationRound); assert_eq!(self.get_plmc_total_supply(), total_plmc_supply); self.do_free_plmc_assertions(expected_free_plmc_balances); self.do_reserved_plmc_assertions(expected_reserved_plmc_balances, HoldReason::Evaluation(project_id).into()); - self.do_reserved_plmc_assertions(expected_ct_account_deposits, HoldReason::FutureDeposit(project_id).into()); } pub fn finalized_bids_assertions( @@ -1038,11 +1028,10 @@ impl< project_metadata.token_information.name.as_slice(), project_metadata.token_information.symbol.as_slice(), ); - let ct_deposit = Self::get_ct_account_deposit(); // 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() + metadata_deposit + ct_deposit, + Self::get_ed() * 2u64.into() + metadata_deposit, )]); self.execute(|| { @@ -1126,7 +1115,6 @@ impl< let plmc_eval_deposits: Vec> = Self::calculate_evaluation_plmc_spent(evaluations.clone()); let plmc_existential_deposits: Vec> = evaluators.existential_deposits(); - let plmc_ct_account_deposits: Vec> = evaluators.ct_account_deposits(); let expected_remaining_plmc: Vec> = Self::generic_map_operation( vec![prev_plmc_balances, plmc_existential_deposits.clone()], @@ -1135,14 +1123,12 @@ impl< self.mint_plmc_to(plmc_eval_deposits.clone()); self.mint_plmc_to(plmc_existential_deposits.clone()); - self.mint_plmc_to(plmc_ct_account_deposits.clone()); self.bond_for_users(project_id, evaluations).unwrap(); let expected_evaluator_balances = Self::sum_balance_mappings(vec![ plmc_eval_deposits.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits, ]); let expected_total_supply = prev_supply + expected_evaluator_balances; @@ -1212,8 +1198,6 @@ impl< let project_id = self.create_auctioning_project(project_metadata.clone(), issuer, evaluations.clone()); let bidders = bids.accounts(); - let bidders_non_evaluators = - bidders.clone().into_iter().filter(|account| evaluations.accounts().contains(account).not()).collect_vec(); let asset_id = bids[0].asset.to_assethub_id(); let prev_plmc_balances = self.get_free_plmc_balances_for(bidders.clone()); let prev_funding_asset_balances = self.get_free_foreign_asset_balances_for(asset_id, bidders.clone()); @@ -1237,7 +1221,6 @@ impl< ); let total_plmc_participation_locked = plmc_bid_deposits; let plmc_existential_deposits: Vec> = bidders.existential_deposits(); - let plmc_ct_account_deposits: Vec> = bidders_non_evaluators.ct_account_deposits(); let funding_asset_deposits = Self::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( &bids, project_metadata.clone(), @@ -1247,7 +1230,6 @@ impl< let bidder_balances = Self::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = Self::generic_map_operation( @@ -1260,7 +1242,6 @@ impl< self.mint_plmc_to(necessary_plmc_mint.clone()); self.mint_plmc_to(plmc_existential_deposits.clone()); - self.mint_plmc_to(plmc_ct_account_deposits.clone()); self.mint_foreign_asset_to(funding_asset_deposits.clone()); self.bid_for_users(project_id, bids.clone()).unwrap(); @@ -1389,11 +1370,6 @@ impl< let ct_price = self.get_project_details(project_id).weighted_average_price.unwrap(); let contributors = contributions.accounts(); - let contributors_non_evaluators = contributors - .clone() - .into_iter() - .filter(|account| evaluations.accounts().contains(account).not()) - .collect_vec(); let asset_id = contributions[0].asset.to_assethub_id(); @@ -1412,13 +1388,11 @@ impl< let total_plmc_participation_locked = Self::generic_map_operation(vec![plmc_bid_deposits, plmc_contribution_deposits], MergeOperation::Add); let plmc_existential_deposits = contributors.existential_deposits(); - let plmc_ct_account_deposits = contributors_non_evaluators.ct_account_deposits(); let funding_asset_deposits = Self::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); let contributor_balances = Self::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = Self::generic_map_operation( @@ -1431,7 +1405,6 @@ impl< self.mint_plmc_to(necessary_plmc_mint.clone()); self.mint_plmc_to(plmc_existential_deposits.clone()); - self.mint_plmc_to(plmc_ct_account_deposits.clone()); self.mint_foreign_asset_to(funding_asset_deposits.clone()); self.contribute_for_users(project_id, contributions).expect("Contributing should work"); @@ -1480,15 +1453,6 @@ impl< let ct_price = self.get_project_details(project_id).weighted_average_price.unwrap(); let contributors = remainder_contributions.accounts(); - let new_contributors = contributors - .clone() - .into_iter() - .filter(|account| { - evaluations.accounts().contains(account).not() && - bids.accounts().contains(account).not() && - community_contributions.accounts().contains(account).not() - }) - .collect_vec(); let asset_id = remainder_contributions[0].asset.to_assethub_id(); let prev_plmc_balances = self.get_free_plmc_balances_for(contributors.clone()); let prev_funding_asset_balances = self.get_free_foreign_asset_balances_for(asset_id, contributors.clone()); @@ -1509,14 +1473,12 @@ impl< MergeOperation::Add, ); let plmc_existential_deposits = contributors.existential_deposits(); - let plmc_ct_account_deposits = new_contributors.ct_account_deposits(); let funding_asset_deposits = Self::calculate_contributed_funding_asset_spent(remainder_contributions.clone(), ct_price); let contributor_balances = Self::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = Self::generic_map_operation( @@ -1529,7 +1491,6 @@ impl< self.mint_plmc_to(necessary_plmc_mint.clone()); self.mint_plmc_to(plmc_existential_deposits.clone()); - self.mint_plmc_to(plmc_ct_account_deposits.clone()); self.mint_foreign_asset_to(funding_asset_deposits.clone()); self.contribute_for_users(project_id, remainder_contributions.clone()) @@ -1864,7 +1825,6 @@ pub mod async_features { evaluations.clone(), ); let plmc_existential_deposits: Vec> = evaluators.existential_deposits(); - let plmc_ct_account_deposits: Vec> = evaluators.ct_account_deposits(); let expected_remaining_plmc: Vec> = Instantiator::::generic_map_operation( @@ -1874,7 +1834,6 @@ pub mod async_features { inst.mint_plmc_to(plmc_eval_deposits.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.bond_for_users(project_id, evaluations).unwrap(); @@ -1882,7 +1841,6 @@ pub mod async_features { Instantiator::::sum_balance_mappings(vec![ plmc_eval_deposits.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits, ]); let expected_total_supply = prev_supply + expected_evaluator_balances; @@ -1901,7 +1859,6 @@ pub mod async_features { None ); let plmc_existential_deposits: Vec> = bids.accounts().existential_deposits(); - let plmc_ct_account_deposits: Vec> = bids.accounts().ct_account_deposits(); let usdt_for_bids = Instantiator::::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( &bids, @@ -1911,7 +1868,6 @@ pub mod async_features { inst.mint_plmc_to(plmc_for_bids.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_for_bids.clone()); inst.bid_for_users(project_id, bids).unwrap(); @@ -1992,8 +1948,6 @@ pub mod async_features { let mut inst = instantiator.lock().await; let bidders = bids.accounts(); - let bidders_non_evaluators = - bidders.clone().into_iter().filter(|account| evaluations.accounts().contains(account).not()).collect_vec(); let asset_id = bids[0].asset.to_assethub_id(); let prev_plmc_balances = inst.get_free_plmc_balances_for(bidders.clone()); let prev_funding_asset_balances = inst.get_free_foreign_asset_balances_for(asset_id, bidders.clone()); @@ -2018,7 +1972,6 @@ pub mod async_features { ); let total_plmc_participation_locked = plmc_bid_deposits; let plmc_existential_deposits: Vec> = bidders.existential_deposits(); - let plmc_ct_account_deposits: Vec> = bidders_non_evaluators.ct_account_deposits(); let funding_asset_deposits = Instantiator::::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( &bids, @@ -2029,7 +1982,6 @@ pub mod async_features { let bidder_balances = Instantiator::::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = @@ -2043,7 +1995,6 @@ pub mod async_features { inst.mint_plmc_to(necessary_plmc_mint.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(funding_asset_deposits.clone()); inst.bid_for_users(project_id, bids.clone()).unwrap(); @@ -2154,11 +2105,6 @@ pub mod async_features { let ct_price = inst.get_project_details(project_id).weighted_average_price.unwrap(); let contributors = contributions.accounts(); - let contributors_non_evaluators = contributors - .clone() - .into_iter() - .filter(|account| evaluations.accounts().contains(account).not()) - .collect_vec(); let asset_id = contributions[0].asset.to_assethub_id(); let prev_plmc_balances = inst.get_free_plmc_balances_for(contributors.clone()); let prev_funding_asset_balances = inst.get_free_foreign_asset_balances_for(asset_id, contributors.clone()); @@ -2187,7 +2133,6 @@ pub mod async_features { MergeOperation::Add, ); let plmc_existential_deposits = contributors.existential_deposits(); - let plmc_ct_account_deposits = contributors_non_evaluators.ct_account_deposits(); let funding_asset_deposits = Instantiator::::calculate_contributed_funding_asset_spent( @@ -2198,7 +2143,6 @@ pub mod async_features { Instantiator::::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = @@ -2212,7 +2156,6 @@ pub mod async_features { inst.mint_plmc_to(necessary_plmc_mint.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(funding_asset_deposits.clone()); inst.contribute_for_users(project_id, contributions).expect("Contributing should work"); @@ -2305,15 +2248,6 @@ pub mod async_features { let ct_price = inst.get_project_details(project_id).weighted_average_price.unwrap(); let contributors = remainder_contributions.accounts(); - let new_contributors = contributors - .clone() - .into_iter() - .filter(|account| { - evaluations.accounts().contains(account).not() && - bids.accounts().contains(account).not() && - community_contributions.accounts().contains(account).not() - }) - .collect_vec(); let asset_id = remainder_contributions[0].asset.to_assethub_id(); let prev_plmc_balances = inst.get_free_plmc_balances_for(contributors.clone()); let prev_funding_asset_balances = inst.get_free_foreign_asset_balances_for(asset_id, contributors.clone()); @@ -2347,7 +2281,6 @@ pub mod async_features { MergeOperation::Add, ); let plmc_existential_deposits = contributors.existential_deposits(); - let plmc_ct_account_deposits = new_contributors.ct_account_deposits(); let funding_asset_deposits = Instantiator::::calculate_contributed_funding_asset_spent( remainder_contributions.clone(), @@ -2358,7 +2291,6 @@ pub mod async_features { Instantiator::::sum_balance_mappings(vec![ necessary_plmc_mint.clone(), plmc_existential_deposits.clone(), - plmc_ct_account_deposits.clone(), ]); let expected_free_plmc_balances = @@ -2372,7 +2304,6 @@ pub mod async_features { inst.mint_plmc_to(necessary_plmc_mint.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(funding_asset_deposits.clone()); inst.contribute_for_users(project_id, remainder_contributions.clone()) @@ -2663,7 +2594,6 @@ pub trait AccountMerge { pub trait Deposits { fn existential_deposits(&self) -> Vec>; - fn ct_account_deposits(&self) -> Vec>; } impl Deposits for Vec> { @@ -2672,17 +2602,6 @@ impl Deposits for Vec> { .map(|x| UserToPLMCBalance::new(x.clone(), ::ExistentialDeposit::get())) .collect::>() } - - fn ct_account_deposits(&self) -> Vec> { - self.iter() - .map(|x| { - UserToPLMCBalance::new( - x.clone(), - ::ContributionTokenCurrency::deposit_required(One::one()), - ) - }) - .collect::>() - } } #[derive(Clone, PartialEq, Debug)] pub struct UserToPLMCBalance { diff --git a/pallets/funding/src/lib.rs b/pallets/funding/src/lib.rs index 4f30aa0ba..2237dc514 100644 --- a/pallets/funding/src/lib.rs +++ b/pallets/funding/src/lib.rs @@ -217,9 +217,6 @@ pub mod pallet { pub enum HoldReason { Evaluation(ProjectId), Participation(ProjectId), - // We require a PLMC deposit to create an account for minting the CTs to this user. - // Here we make sure the user has this amount before letting him participate. - FutureDeposit(ProjectId), } #[pallet::pallet] @@ -948,8 +945,6 @@ pub mod pallet { XcmFailed, // Tried to convert one type into another and failed. i.e try_into failed BadConversion, - /// Tried to release the PLMC deposit held for a future CT mint, but there was nothing to release - NoFutureDepositHeld, /// The issuer doesn't have enough funds (ExistentialDeposit), to create the escrow account NotEnoughFundsForEscrowCreation, /// The issuer doesn't have enough funds to pay for the metadata of their contribution token @@ -1033,8 +1028,7 @@ pub mod pallet { /// Bond PLMC for a project in the evaluation stage #[pallet::call_index(4)] #[pallet::weight( - WeightInfoOf::::first_evaluation() - .max(WeightInfoOf::::second_to_limit_evaluation(T::MaxEvaluationsPerUser::get() - 1)) + WeightInfoOf::::evaluation_to_limit(T::MaxEvaluationsPerUser::get() - 1) .max(WeightInfoOf::::evaluation_over_limit()) )] pub fn evaluate( @@ -1051,14 +1045,13 @@ pub mod pallet { /// Bid for a project in the Auction round #[pallet::call_index(5)] #[pallet::weight( - WeightInfoOf::::bid_no_ct_deposit( + WeightInfoOf::::bid( ::MaxBidsPerUser::get() - 1, // Assuming the current bucket is full, and has a price higher than the minimum. // This user is buying 100% of the bid allocation. // Since each bucket has 10% of the allocation, one bid can be split into a max of 10 10 - ) - .max(WeightInfoOf::::bid_with_ct_deposit(10)))] + ))] pub fn bid( origin: OriginFor, jwt: UntrustedToken, diff --git a/pallets/funding/src/mock.rs b/pallets/funding/src/mock.rs index 095763a40..efc5f8295 100644 --- a/pallets/funding/src/mock.rs +++ b/pallets/funding/src/mock.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system as system; use frame_system::EnsureRoot; -use polimec_common::credentials::{EnsureInvestor, Institutional, Professional, Retail}; +use polimec_common::credentials::EnsureInvestor; use sp_arithmetic::Percent; use sp_core::H256; use sp_runtime::{ @@ -53,7 +53,7 @@ pub const EXISTENTIAL_DEPOSIT: Balance = 10 * MILLI_PLMC; const US_DOLLAR: u128 = 1_0_000_000_000u128; -pub type LocalAssetsInstance = pallet_assets::Instance1; +pub type ContributionTokensInstance = pallet_assets::Instance1; pub type ForeignAssetsInstance = pallet_assets::Instance2; pub type AssetId = u32; @@ -146,6 +146,7 @@ impl pallet_xcm::Config for TestRuntime { parameter_types! { pub const AssetDeposit: Balance = PLMC; // 1 UNIT deposit to create asset pub const AssetAccountDeposit: Balance = deposit(1, 16); + pub const ZeroAssetAccountDeposit: Balance = free_deposit(); pub const AssetsStringLimit: u32 = 50; // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 pub const MetadataDepositBase: Balance = free_deposit(); @@ -153,9 +154,9 @@ parameter_types! { pub const ApprovalDeposit: Balance = EXISTENTIAL_DEPOSIT; } -impl pallet_assets::Config for TestRuntime { +impl pallet_assets::Config for TestRuntime { type ApprovalDeposit = ApprovalDeposit; - type AssetAccountDeposit = AssetAccountDeposit; + type AssetAccountDeposit = ZeroAssetAccountDeposit; type AssetDeposit = AssetDeposit; type AssetId = AssetId; type AssetIdParameter = parity_scale_codec::Compact; @@ -344,14 +345,14 @@ impl ConvertBack for DummyConverter { impl Config for TestRuntime { type AccountId32Conversion = DummyConverter; type AllPalletsWithoutSystem = - (Balances, LocalAssets, ForeignAssets, PolimecFunding, Vesting, RandomnessCollectiveFlip); + (Balances, ContributionTokens, ForeignAssets, PolimecFunding, Vesting, RandomnessCollectiveFlip); type AuctionInitializePeriodDuration = AuctionInitializePeriodDuration; type Balance = Balance; type BlockNumber = BlockNumber; type BlockNumberToBalance = ConvertInto; type CandleAuctionDuration = CandleAuctionDuration; type CommunityFundingDuration = CommunityRoundDuration; - type ContributionTokenCurrency = LocalAssets; + type ContributionTokenCurrency = ContributionTokens; type ContributionTreasury = ContributionTreasury; type DaysToBlocks = DaysToBlocks; type EnglishAuctionDuration = EnglishAuctionDuration; @@ -405,7 +406,7 @@ construct_runtime!( RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, Balances: pallet_balances, Vesting: pallet_linear_release, - LocalAssets: pallet_assets::::{Pallet, Call, Storage, Event}, + ContributionTokens: pallet_assets::::{Pallet, Call, Storage, Event}, ForeignAssets: pallet_assets::::{Pallet, Call, Storage, Event, Config}, PolkadotXcm: pallet_xcm, PolimecFunding: pallet_funding::{Pallet, Call, Storage, Event, Config, HoldReason} = 52, diff --git a/pallets/funding/src/tests.rs b/pallets/funding/src/tests.rs index 8c19f2db7..bd4a1d66e 100644 --- a/pallets/funding/src/tests.rs +++ b/pallets/funding/src/tests.rs @@ -35,7 +35,7 @@ use frame_support::{ }; use itertools::Itertools; use parachains_common::DAYS; -use polimec_common::{credentials::*, ReleaseSchedule}; +use polimec_common::ReleaseSchedule; use polimec_common_test_utils::{generate_did_from_account, get_mock_jwt}; use sp_arithmetic::{traits::Zero, Percent, Perquintill}; use sp_runtime::{BuildStorage, TokenError}; @@ -694,16 +694,14 @@ mod evaluation { let plmc_eval_deposits: Vec> = MockInstantiator::calculate_evaluation_plmc_spent(evaluations); let plmc_existential_deposits = plmc_eval_deposits.accounts().existential_deposits(); - let ct_account_deposits = plmc_eval_deposits.accounts().ct_account_deposits(); let expected_evaluator_balances = MockInstantiator::generic_map_operation( - vec![plmc_eval_deposits.clone(), plmc_existential_deposits.clone(), ct_account_deposits.clone()], + vec![plmc_eval_deposits.clone(), plmc_existential_deposits.clone()], MergeOperation::Add, ); inst.mint_plmc_to(plmc_eval_deposits.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(ct_account_deposits.clone()); let project_id = inst.create_evaluating_project(project_metadata, issuer); @@ -750,75 +748,6 @@ mod evaluation { assert_err!(dispatch_error, TokenError::FundsUnavailable) } - #[test] - fn evaluation_ct_account_deposits_are_returned_on_evaluation_failed() { - let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); - let project_metadata = default_project_metadata(0, ISSUER); - let project_id = inst.create_evaluating_project(project_metadata.clone(), ISSUER); - let evaluation_success_threshold = ::EvaluationSuccessThreshold::get(); - let evaluation_min_success_amount = evaluation_success_threshold * - project_metadata.minimum_price.saturating_mul_int(project_metadata.total_allocation_size); - let evaluation_fail_amount = evaluation_min_success_amount - 100 * ASSET_UNIT; - let evaluator_bond = evaluation_fail_amount / 4; - let evaluations = vec![ - (EVALUATOR_1, evaluator_bond).into(), - (EVALUATOR_1, evaluator_bond).into(), - (EVALUATOR_2, evaluator_bond).into(), - (EVALUATOR_3, evaluator_bond).into(), - ]; - let deposit_required = <::ContributionTokenCurrency as AccountTouch< - ProjectId, - AccountIdOf, - >>::deposit_required(project_id); - inst.do_free_plmc_assertions(vec![ - (EVALUATOR_1, 0u128).into(), - (EVALUATOR_2, 0u128).into(), - (EVALUATOR_3, 0u128).into(), - ]); - inst.do_reserved_plmc_assertions( - vec![(EVALUATOR_1, 0u128).into(), (EVALUATOR_2, 0u128).into(), (EVALUATOR_3, 0u128).into()], - HoldReason::FutureDeposit(project_id).into(), - ); - - let required_plmc_bonds = MockInstantiator::calculate_evaluation_plmc_spent(evaluations.clone()); - let plmc_existential_deposits = required_plmc_bonds.accounts().existential_deposits(); - let plmc_ct_account_deposits = required_plmc_bonds.accounts().ct_account_deposits(); - - inst.mint_plmc_to(required_plmc_bonds.clone()); - inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); - - let _ = inst.bond_for_users(project_id, evaluations); - - inst.do_free_plmc_assertions(vec![ - (EVALUATOR_1, MockInstantiator::get_ed()).into(), - (EVALUATOR_2, MockInstantiator::get_ed()).into(), - (EVALUATOR_3, MockInstantiator::get_ed()).into(), - ]); - inst.do_reserved_plmc_assertions( - vec![ - (EVALUATOR_1, deposit_required).into(), - (EVALUATOR_2, deposit_required).into(), - (EVALUATOR_3, deposit_required).into(), - ], - HoldReason::FutureDeposit(project_id).into(), - ); - - inst.advance_time(::EvaluationDuration::get() + 1).unwrap(); - inst.advance_time(::SuccessToSettlementTime::get() + 1).unwrap(); - assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::EvaluationFailed); - - let final_plmc_amounts = MockInstantiator::generic_map_operation( - vec![required_plmc_bonds, plmc_existential_deposits, plmc_ct_account_deposits], - MergeOperation::Add, - ); - inst.do_free_plmc_assertions(final_plmc_amounts); - inst.do_reserved_plmc_assertions( - vec![(EVALUATOR_1, 0u128).into(), (EVALUATOR_2, 0u128).into(), (EVALUATOR_3, 0u128).into()], - HoldReason::FutureDeposit(project_id).into(), - ); - } - #[test] fn cannot_evaluate_more_than_project_limit() { let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); @@ -832,22 +761,18 @@ mod evaluation { let plmc_for_evaluating = MockInstantiator::calculate_evaluation_plmc_spent(evaluations.clone()); let plmc_existential_deposits = evaluations.accounts().existential_deposits(); - let plmc_ct_account_deposits = evaluations.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_for_evaluating.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.bond_for_users(project_id, evaluations.clone()).unwrap(); let plmc_for_failing_evaluating = MockInstantiator::calculate_evaluation_plmc_spent(vec![failing_evaluation.clone()]); let plmc_existential_deposits = plmc_for_failing_evaluating.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_for_failing_evaluating.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_for_failing_evaluating.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); assert_err!( inst.bond_for_users(project_id, vec![failing_evaluation]), @@ -1085,7 +1010,6 @@ mod auction { assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionRound(AuctionPhase::Candle)); inst.mint_plmc_to(vec![UserToPLMCBalance::new(bidding_account, plmc_necessary_funding * 10)]); inst.mint_plmc_to(vec![bidding_account].existential_deposits()); - inst.mint_plmc_to(vec![bidding_account].ct_account_deposits()); inst.mint_foreign_asset_to(vec![UserToForeignAssets::new( bidding_account, @@ -1160,10 +1084,9 @@ mod auction { let evaluations = default_evaluations(); let required_plmc = MockInstantiator::calculate_evaluation_plmc_spent(evaluations.clone()); let ed_plmc = required_plmc.accounts().existential_deposits(); - let ct_acount_deposits = required_plmc.accounts().ct_account_deposits(); + inst.mint_plmc_to(required_plmc); inst.mint_plmc_to(ed_plmc); - inst.mint_plmc_to(ct_acount_deposits); inst.bond_for_users(project_id, evaluations).unwrap(); inst.advance_time(::EvaluationDuration::get() + 1).unwrap(); assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionInitializePeriod); @@ -1178,10 +1101,8 @@ mod auction { let evaluations = default_evaluations(); let required_plmc = MockInstantiator::calculate_evaluation_plmc_spent(evaluations.clone()); let ed_plmc = required_plmc.accounts().existential_deposits(); - let ct_acount_deposits = required_plmc.accounts().ct_account_deposits(); inst.mint_plmc_to(required_plmc); inst.mint_plmc_to(ed_plmc); - inst.mint_plmc_to(ct_acount_deposits); inst.bond_for_users(project_id, evaluations).unwrap(); inst.advance_time(::EvaluationDuration::get() + 1).unwrap(); assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionInitializePeriod); @@ -1197,10 +1118,8 @@ mod auction { let evaluations = default_evaluations(); let required_plmc = MockInstantiator::calculate_evaluation_plmc_spent(evaluations.clone()); let ed_plmc = required_plmc.accounts().existential_deposits(); - let ct_acount_deposits = required_plmc.accounts().ct_account_deposits(); inst.mint_plmc_to(required_plmc); inst.mint_plmc_to(ed_plmc); - inst.mint_plmc_to(ct_acount_deposits); inst.bond_for_users(project_id, evaluations).unwrap(); inst.advance_time(::EvaluationDuration::get() + 1).unwrap(); assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionInitializePeriod); @@ -1288,10 +1207,8 @@ mod auction { None, ); let bidders_existential_deposits = bidders_plmc.accounts().existential_deposits(); - let bidders_ct_account_deposits = bidders_plmc.accounts().ct_account_deposits(); inst.mint_plmc_to(bidders_plmc.clone()); inst.mint_plmc_to(bidders_existential_deposits); - inst.mint_plmc_to(bidders_ct_account_deposits); let bidders_funding_assets = MockInstantiator::calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( @@ -1309,10 +1226,8 @@ mod auction { let contributors_plmc = MockInstantiator::calculate_contributed_plmc_spent(community_contributions.clone(), final_price); let contributors_existential_deposits = contributors_plmc.accounts().existential_deposits(); - let contributors_ct_account_deposits = contributors_plmc.accounts().ct_account_deposits(); inst.mint_plmc_to(contributors_plmc.clone()); inst.mint_plmc_to(contributors_existential_deposits); - inst.mint_plmc_to(contributors_ct_account_deposits); let contributors_funding_assets = MockInstantiator::calculate_contributed_funding_asset_spent(community_contributions.clone(), final_price); @@ -1388,11 +1303,9 @@ mod auction { ); let plmc_existential_amounts = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_amounts.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_fundings.clone()); inst.bid_for_users(project_id, bids.clone()).unwrap(); @@ -1508,7 +1421,6 @@ mod auction { project_metadata.minimum_price, ); let plmc_existential_deposits = bids.accounts().existential_deposits(); - let plmc_ct_account_deposits = bids.accounts().ct_account_deposits(); let usdt_for_bidding = MockInstantiator::calculate_auction_funding_asset_charged_with_given_price( &bids.clone(), project_metadata.minimum_price, @@ -1516,7 +1428,6 @@ mod auction { inst.mint_plmc_to(plmc_for_bidding.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_for_bidding.clone()); inst.bid_for_users(project_id, bids.clone()).unwrap(); @@ -1526,7 +1437,6 @@ mod auction { project_metadata.minimum_price, ); let plmc_existential_deposits = plmc_for_failing_bid.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_for_failing_bid.accounts().ct_account_deposits(); let usdt_for_bidding = MockInstantiator::calculate_auction_funding_asset_charged_with_given_price( &vec![failing_bid.clone()], project_metadata.minimum_price, @@ -1534,7 +1444,6 @@ mod auction { inst.mint_plmc_to(plmc_for_failing_bid.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_for_bidding.clone()); assert_err!(inst.bid_for_users(project_id, vec![failing_bid]), Error::::TooManyBidsForProject); @@ -1621,7 +1530,6 @@ mod auction { project_metadata.minimum_price, ); let plmc_existential_amounts = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let usdt_fundings = MockInstantiator::calculate_auction_funding_asset_charged_with_given_price( &vec![bid_in.clone(), bid_out.clone()], @@ -1630,7 +1538,6 @@ mod auction { inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_amounts.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(usdt_fundings.clone()); inst.bid_for_users(project_id, vec![bid_in]).unwrap(); @@ -1983,10 +1890,9 @@ mod auction { project_metadata_all.minimum_price, ); let plmc_existential_deposits = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let plmc_all_mints = MockInstantiator::generic_map_operation( - vec![plmc_fundings, plmc_existential_deposits, plmc_ct_account_deposits], + vec![plmc_fundings, plmc_existential_deposits], MergeOperation::Add, ); inst.mint_plmc_to(plmc_all_mints.clone()); @@ -2125,13 +2031,11 @@ mod community_contribution { let plmc_funding = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), token_price); let plmc_existential_deposit = plmc_funding.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_funding.accounts().ct_account_deposits(); let foreign_funding = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), token_price); inst.mint_plmc_to(plmc_funding); inst.mint_plmc_to(plmc_existential_deposit); - inst.mint_plmc_to(plmc_ct_account_deposits); inst.mint_foreign_asset_to(foreign_funding); inst.contribute_for_users(project_id, vec![contributions[0].clone()]) @@ -2174,13 +2078,11 @@ mod community_contribution { let contributions = vec![ContributionParams::new(BOB, remaining_ct, 1u8, AcceptedFundingAsset::USDT)]; let plmc_fundings = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), ct_price); let plmc_existential_deposits = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let foreign_asset_fundings = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(foreign_asset_fundings.clone()); // Buy remaining CTs @@ -2229,13 +2131,11 @@ mod community_contribution { let contributions = vec![ContributionParams::new(BOB, remaining_ct, 1u8, AcceptedFundingAsset::USDT)]; let mut plmc_fundings = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), ct_price); let plmc_existential_deposits = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let mut foreign_asset_fundings = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(foreign_asset_fundings.clone()); // Buy remaining CTs @@ -2304,14 +2204,12 @@ mod community_contribution { let plmc_funding = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), token_price); let plmc_existential_deposits = plmc_funding.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_funding.accounts().ct_account_deposits(); let foreign_funding = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), token_price); inst.mint_plmc_to(plmc_funding.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(foreign_funding.clone()); @@ -2526,10 +2424,8 @@ mod community_contribution { project_details.weighted_average_price.unwrap(), ); let plmc_existential_deposits = plmc_contribution_funding.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_contribution_funding.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_contribution_funding.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); let foreign_asset_contribution_funding = MockInstantiator::calculate_contributed_funding_asset_spent( contributions.clone(), @@ -2899,10 +2795,9 @@ mod community_contribution { wap, ); let plmc_existential_deposits = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let plmc_all_mints = MockInstantiator::generic_map_operation( - vec![plmc_fundings, plmc_existential_deposits, plmc_ct_account_deposits], + vec![plmc_fundings, plmc_existential_deposits], MergeOperation::Add, ); inst.mint_plmc_to(plmc_all_mints.clone()); @@ -3058,13 +2953,11 @@ mod remainder_contribution { let contributions = vec![ContributionParams::new(BOB, remaining_ct, 1u8, AcceptedFundingAsset::USDT)]; let plmc_fundings = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), ct_price); let plmc_existential_deposits = contributions.accounts().existential_deposits(); - let plmc_ct_account_deposits = contributions.accounts().ct_account_deposits(); let foreign_asset_fundings = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(foreign_asset_fundings.clone()); // Buy remaining CTs @@ -3111,13 +3004,11 @@ mod remainder_contribution { let contributions = vec![ContributionParams::new(BOB, remaining_ct, 1u8, AcceptedFundingAsset::USDT)]; let mut plmc_fundings = MockInstantiator::calculate_contributed_plmc_spent(contributions.clone(), ct_price); let plmc_existential_deposits = contributions.accounts().existential_deposits(); - let plmc_ct_account_deposits = contributions.accounts().ct_account_deposits(); let mut foreign_asset_fundings = MockInstantiator::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); inst.mint_plmc_to(plmc_fundings.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); inst.mint_foreign_asset_to(foreign_asset_fundings.clone()); // Buy remaining CTs @@ -3191,10 +3082,8 @@ mod remainder_contribution { project_details.weighted_average_price.unwrap(), ); let plmc_existential_deposits = plmc_contribution_funding.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_contribution_funding.accounts().ct_account_deposits(); inst.mint_plmc_to(plmc_contribution_funding.clone()); inst.mint_plmc_to(plmc_existential_deposits.clone()); - inst.mint_plmc_to(plmc_ct_account_deposits.clone()); let foreign_asset_contribution_funding = MockInstantiator::calculate_contributed_funding_asset_spent( contributions.clone(), @@ -3573,10 +3462,9 @@ mod remainder_contribution { wap, ); let plmc_existential_deposits = plmc_fundings.accounts().existential_deposits(); - let plmc_ct_account_deposits = plmc_fundings.accounts().ct_account_deposits(); let plmc_all_mints = MockInstantiator::generic_map_operation( - vec![plmc_fundings, plmc_existential_deposits, plmc_ct_account_deposits], + vec![plmc_fundings, plmc_existential_deposits], MergeOperation::Add, ); inst.mint_plmc_to(plmc_all_mints.clone()); @@ -5145,11 +5033,6 @@ mod funding_end { let issuer_funding_delta = post_issuer_funding_balance - prev_issuer_funding_balance; - let participants = all_participants_plmc_deltas.accounts(); - for participant in participants { - let future_deposit_reserved = inst.execute(||{<::NativeCurrency as fungible::InspectHold>>::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), &participant)}); - println!("participant {:?} has future deposit reserved {:?}", participant, future_deposit_reserved); - } assert_eq!(issuer_funding_delta, 0); assert_eq!(all_participants_plmc_deltas, all_expected_payouts); } @@ -5330,11 +5213,6 @@ mod funding_end { ); let issuer_funding_delta = post_issuer_funding_balance - prev_issuer_funding_balance; - let participants = all_participants_plmc_deltas.accounts(); - for participant in participants { - let future_deposit_reserved = inst.execute(||{<::NativeCurrency as fungible::InspectHold>>::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), &participant)}); - println!("participant {:?} has future deposit reserved {:?}", participant, future_deposit_reserved); - } assert_eq!( inst.get_project_details(project_id).cleanup, Cleaner::Failure(CleanerState::Initialized(PhantomData)) @@ -5646,103 +5524,6 @@ mod funding_end { } } - #[test] - fn ct_account_deposits_are_returned() { - let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); - let project_metadata = default_project_metadata(0, ISSUER); - let automatic_fail_funding_percent = Percent::from_percent(30); - let deposit_required = <::ContributionTokenCurrency as AccountTouch< - ProjectId, - AccountIdOf, - >>::deposit_required(0); - - let _remainder_contributors = vec![EVALUATOR_1, BIDDER_3, BUYER_4, BUYER_6, BIDDER_6]; - - let funding_target = project_metadata.minimum_price.saturating_mul_int(project_metadata.total_allocation_size); - - let bids = MockInstantiator::generate_bids_from_total_usd( - automatic_fail_funding_percent * funding_target / 3, - project_metadata.minimum_price, - default_weights(), - default_bidders(), - default_bidder_multipliers(), - ); - - let community_contributions = MockInstantiator::generate_contributions_from_total_usd( - automatic_fail_funding_percent * funding_target / 3, - project_metadata.minimum_price, - default_weights(), - default_community_contributors(), - default_community_contributor_multipliers(), - ); - - let remainder_contributions = MockInstantiator::generate_contributions_from_total_usd( - automatic_fail_funding_percent * funding_target / 3, - project_metadata.minimum_price, - default_weights(), - default_remainder_contributors(), - default_remainder_contributor_multipliers(), - ); - - let zero_balances = remainder_contributions - .clone() - .accounts() - .into_iter() - .map(|acc| UserToPLMCBalance::new(acc, 0u128)) - .collect_vec(); - inst.do_free_plmc_assertions(zero_balances.clone()); - inst.do_reserved_plmc_assertions(zero_balances.clone(), HoldReason::FutureDeposit(0).into()); - - let project_id = inst.create_finished_project( - project_metadata, - ISSUER, - default_evaluations(), - bids.clone(), - community_contributions.clone(), - remainder_contributions.clone(), - ); - let wap = inst.get_project_details(project_id).weighted_average_price.unwrap(); - - let bidder_plmc_bonds = MockInstantiator::calculate_auction_plmc_charged_with_given_price(&bids, wap); - let community_contributor_plmc_bonds = - MockInstantiator::calculate_contributed_plmc_spent(community_contributions.clone(), wap); - let evaluators_and_contributors_plmc_bonds = - MockInstantiator::calculate_total_plmc_locked_from_evaluations_and_remainder_contributions( - default_evaluations(), - remainder_contributions, - wap, - true, - ); - - let mut expected_final_plmc_balances = MockInstantiator::generic_map_operation( - vec![bidder_plmc_bonds, community_contributor_plmc_bonds, evaluators_and_contributors_plmc_bonds], - MergeOperation::Add, - ); - expected_final_plmc_balances.iter_mut().for_each(|UserToPLMCBalance { account: _, plmc_amount }| { - *plmc_amount += deposit_required; - }); - - let prev_balances = inst.get_free_plmc_balances_for(expected_final_plmc_balances.accounts()); - let ct_deposit_balances = expected_final_plmc_balances - .accounts() - .into_iter() - .map(|acc| UserToPLMCBalance::new(acc, deposit_required)) - .collect_vec(); - inst.do_reserved_plmc_assertions(ct_deposit_balances, HoldReason::FutureDeposit(project_id).into()); - - assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::FundingFailed); - inst.advance_time(::SuccessToSettlementTime::get() + 1).unwrap(); - assert_eq!(inst.get_project_details(project_id).cleanup, Cleaner::Failure(CleanerState::Finished(PhantomData))); - - let post_balances = inst.get_free_plmc_balances_for(expected_final_plmc_balances.accounts()); - - let plmc_deltas = - MockInstantiator::generic_map_operation(vec![post_balances, prev_balances], MergeOperation::Subtract); - - assert_eq!(plmc_deltas, expected_final_plmc_balances); - inst.do_reserved_plmc_assertions(zero_balances, HoldReason::FutureDeposit(project_id).into()); - } - #[test] fn ct_treasury_mints() { let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); @@ -5878,7 +5659,7 @@ mod funding_end { // we want to test ct mints on treasury of 1 over the consumer limit, // and we already minted 3 contribution tokens on previous tests. for i in 0..consumer_limit + 1u32 - 3u32 { - let project_98_percent = inst.create_finished_project( + let _project_98_percent = inst.create_finished_project( with_different_metadata(project_metadata.clone()), ISSUER + i + 1000, default_evaluations(), @@ -6221,7 +6002,6 @@ mod inner_functions { // test the parallel instantiation of projects mod async_tests { use super::*; - use instantiator::async_features::*; #[test] fn prototype_2() { diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index fbcc240a6..85df355a7 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -741,7 +741,6 @@ pub mod inner_types { BidUnbonding(u64, PhantomData), ContributionFundingRelease(u64, PhantomData), ContributionUnbonding(u64, PhantomData), - FutureDepositRelease(u64, PhantomData), // Merge // Success or Failure Finished(PhantomData), diff --git a/pallets/funding/src/weights.rs b/pallets/funding/src/weights.rs index e3def4dad..aa2b0b9a2 100644 --- a/pallets/funding/src/weights.rs +++ b/pallets/funding/src/weights.rs @@ -53,11 +53,9 @@ pub trait WeightInfo { fn edit_metadata() -> Weight; fn start_evaluation(x: u32, ) -> Weight; fn start_auction_manually(x: u32 ) -> Weight; - fn first_evaluation() -> Weight; - fn second_to_limit_evaluation(x: u32, ) -> Weight; + fn evaluation_to_limit(x: u32, ) -> Weight; fn evaluation_over_limit() -> Weight; - fn bid_no_ct_deposit(x: u32, y: u32, ) -> Weight; - fn bid_with_ct_deposit(y: u32, ) -> Weight; + fn bid(x: u32, y: u32, ) -> Weight; fn contribution(x: u32, ) -> Weight; fn contribution_ends_round(x: u32, y: u32 ) -> Weight; fn evaluation_unbond_for() -> Weight; @@ -176,27 +174,6 @@ impl WeightInfo for SubstrateWeight { /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::NextEvaluationId` (r:1 w:1) /// Proof: `PolimecFunding::NextEvaluationId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Evaluations` (r:1 w:1) - /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) - /// Storage: `Oracle::Values` (r:1 w:0) - /// Proof: `Oracle::Values` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::EvaluationCounts` (r:1 w:1) - /// Proof: `PolimecFunding::EvaluationCounts` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) - fn first_evaluation() -> Weight { - // Proof Size summary in bytes: - // Measured: `745` - // Estimated: `4614` - // Minimum execution time: 90_000_000 picoseconds. - Weight::from_parts(97_000_000, 4614) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) - } - /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:1) - /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::NextEvaluationId` (r:1 w:1) - /// Proof: `PolimecFunding::NextEvaluationId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::Evaluations` (r:16 w:1) /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) /// Storage: `Oracle::Values` (r:1 w:0) @@ -206,7 +183,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Balances::Holds` (r:1 w:1) /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) /// The range of component `x` is `[1, 15]`. - fn second_to_limit_evaluation(x: u32, ) -> Weight { + fn evaluation_to_limit(x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `941 + x * (137 ±0)` // Estimated: `4614 + x * (2820 ±0)` @@ -264,7 +241,7 @@ impl WeightInfo for SubstrateWeight { /// Proof: `StatemintAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// The range of component `x` is `[0, 127]`. /// The range of component `y` is `[0, 10]`. - fn bid_no_ct_deposit(x: u32, y: u32, ) -> Weight { + fn bid(x: u32, y: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `2278 + x * (164 ±0)` // Estimated: `6208 + x * (2893 ±0)` @@ -280,43 +257,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(y.into()))) .saturating_add(Weight::from_parts(0, 2893).saturating_mul(x.into())) } - /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:0) - /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::ProjectsMetadata` (r:1 w:0) - /// Proof: `PolimecFunding::ProjectsMetadata` (`max_values`: None, `max_size`: Some(334), added: 2809, mode: `MaxEncodedLen`) - /// Storage: `Oracle::Values` (r:2 w:0) - /// Proof: `Oracle::Values` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Bids` (r:1 w:10) - /// Proof: `PolimecFunding::Bids` (`max_values`: None, `max_size`: Some(418), added: 2893, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::BidCounts` (r:1 w:1) - /// Proof: `PolimecFunding::BidCounts` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Buckets` (r:1 w:1) - /// Proof: `PolimecFunding::Buckets` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::NextBidId` (r:1 w:1) - /// Proof: `PolimecFunding::NextBidId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Evaluations` (r:1 w:0) - /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) - /// Storage: `StatemintAssets::Asset` (r:1 w:1) - /// Proof: `StatemintAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `StatemintAssets::Account` (r:2 w:2) - /// Proof: `StatemintAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// The range of component `y` is `[0, 10]`. - fn bid_with_ct_deposit(y: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2184` - // Estimated: `6208` - // Minimum execution time: 143_000_000 picoseconds. - Weight::from_parts(110_639_424, 6208) - // Standard Error: 314_196 - .saturating_add(Weight::from_parts(70_855_879, 0).saturating_mul(y.into())) - .saturating_add(T::DbWeight::get().reads(13_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(y.into()))) - } /// Storage: `PolimecFunding::ProjectsMetadata` (r:1 w:0) /// Proof: `PolimecFunding::ProjectsMetadata` (`max_values`: None, `max_size`: Some(334), added: 2809, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:1) @@ -1057,27 +997,6 @@ impl WeightInfo for () { /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::NextEvaluationId` (r:1 w:1) /// Proof: `PolimecFunding::NextEvaluationId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Evaluations` (r:1 w:1) - /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) - /// Storage: `Oracle::Values` (r:1 w:0) - /// Proof: `Oracle::Values` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::EvaluationCounts` (r:1 w:1) - /// Proof: `PolimecFunding::EvaluationCounts` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) - fn first_evaluation() -> Weight { - // Proof Size summary in bytes: - // Measured: `745` - // Estimated: `4614` - // Minimum execution time: 90_000_000 picoseconds. - Weight::from_parts(97_000_000, 4614) - .saturating_add(RocksDbWeight::get().reads(6_u64)) - .saturating_add(RocksDbWeight::get().writes(5_u64)) - } - /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:1) - /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::NextEvaluationId` (r:1 w:1) - /// Proof: `PolimecFunding::NextEvaluationId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::Evaluations` (r:16 w:1) /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) /// Storage: `Oracle::Values` (r:1 w:0) @@ -1087,7 +1006,7 @@ impl WeightInfo for () { /// Storage: `Balances::Holds` (r:1 w:1) /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) /// The range of component `x` is `[1, 15]`. - fn second_to_limit_evaluation(x: u32, ) -> Weight { + fn evaluation_to_limit(x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `941 + x * (137 ±0)` // Estimated: `4614 + x * (2820 ±0)` @@ -1145,7 +1064,7 @@ impl WeightInfo for () { /// Proof: `StatemintAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// The range of component `x` is `[0, 127]`. /// The range of component `y` is `[0, 10]`. - fn bid_no_ct_deposit(x: u32, y: u32, ) -> Weight { + fn bid(x: u32, y: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `2278 + x * (164 ±0)` // Estimated: `6208 + x * (2893 ±0)` @@ -1161,43 +1080,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(y.into()))) .saturating_add(Weight::from_parts(0, 2893).saturating_mul(x.into())) } - /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:0) - /// Proof: `PolimecFunding::ProjectsDetails` (`max_values`: None, `max_size`: Some(349), added: 2824, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::ProjectsMetadata` (r:1 w:0) - /// Proof: `PolimecFunding::ProjectsMetadata` (`max_values`: None, `max_size`: Some(334), added: 2809, mode: `MaxEncodedLen`) - /// Storage: `Oracle::Values` (r:2 w:0) - /// Proof: `Oracle::Values` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Bids` (r:1 w:10) - /// Proof: `PolimecFunding::Bids` (`max_values`: None, `max_size`: Some(418), added: 2893, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::BidCounts` (r:1 w:1) - /// Proof: `PolimecFunding::BidCounts` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(1149), added: 3624, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Buckets` (r:1 w:1) - /// Proof: `PolimecFunding::Buckets` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::NextBidId` (r:1 w:1) - /// Proof: `PolimecFunding::NextBidId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `PolimecFunding::Evaluations` (r:1 w:0) - /// Proof: `PolimecFunding::Evaluations` (`max_values`: None, `max_size`: Some(345), added: 2820, mode: `MaxEncodedLen`) - /// Storage: `StatemintAssets::Asset` (r:1 w:1) - /// Proof: `StatemintAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `StatemintAssets::Account` (r:2 w:2) - /// Proof: `StatemintAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// The range of component `y` is `[0, 10]`. - fn bid_with_ct_deposit(y: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2184` - // Estimated: `6208` - // Minimum execution time: 143_000_000 picoseconds. - Weight::from_parts(110_639_424, 6208) - // Standard Error: 314_196 - .saturating_add(Weight::from_parts(70_855_879, 0).saturating_mul(y.into())) - .saturating_add(RocksDbWeight::get().reads(13_u64)) - .saturating_add(RocksDbWeight::get().writes(8_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(y.into()))) - } /// Storage: `PolimecFunding::ProjectsMetadata` (r:1 w:0) /// Proof: `PolimecFunding::ProjectsMetadata` (`max_values`: None, `max_size`: Some(334), added: 2809, mode: `MaxEncodedLen`) /// Storage: `PolimecFunding::ProjectsDetails` (r:1 w:1) diff --git a/runtimes/base/src/lib.rs b/runtimes/base/src/lib.rs index 6629d60d9..9860c9452 100644 --- a/runtimes/base/src/lib.rs +++ b/runtimes/base/src/lib.rs @@ -856,7 +856,7 @@ construct_runtime!( Balances: pallet_balances = 10, TransactionPayment: pallet_transaction_payment = 11, Vesting: pallet_vesting = 12, - // Leave room for LocalAssets = 13 + // Leave room for ContributionTokens = 13 ForeignAssets: pallet_assets:: = 14, // Collator support. the order of these 5 are important and shall not change. diff --git a/runtimes/shared-configuration/src/assets.rs b/runtimes/shared-configuration/src/assets.rs index e7b91f5f0..ec7f0238a 100644 --- a/runtimes/shared-configuration/src/assets.rs +++ b/runtimes/shared-configuration/src/assets.rs @@ -32,6 +32,7 @@ parameter_types! { pub const MetadataDepositBase: Balance = deposit(1, 68); pub const MetadataDepositPerByte: Balance = deposit(0, 1); pub const AssetAccountDeposit: Balance = deposit(1, 18); + pub const ZeroAssetAccountDeposit: Balance = 0; } pub struct OraclePriceProvider(PhantomData<(AssetId, Price, Oracle)>); diff --git a/runtimes/testnet/src/lib.rs b/runtimes/testnet/src/lib.rs index 28f61456e..cc69a5fb9 100644 --- a/runtimes/testnet/src/lib.rs +++ b/runtimes/testnet/src/lib.rs @@ -565,12 +565,12 @@ impl pallet_identity::Config for Runtime { type WeightInfo = pallet_identity::weights::SubstrateWeight; } -pub type LocalAssetsInstance = pallet_assets::Instance1; +pub type ContributionTokensInstance = pallet_assets::Instance1; pub type ForeignAssetsInstance = pallet_assets::Instance2; -impl pallet_assets::Config for Runtime { +impl pallet_assets::Config for Runtime { type ApprovalDeposit = ExistentialDeposit; - type AssetAccountDeposit = AssetAccountDeposit; + type AssetAccountDeposit = ZeroAssetAccountDeposit; type AssetDeposit = AssetDeposit; type AssetId = AssetId; type AssetIdParameter = parity_scale_codec::Compact; @@ -643,14 +643,14 @@ impl pallet_funding::Config for Runtime { type AccountId32Conversion = ConvertSelf; #[cfg(any(test, feature = "runtime-benchmarks", feature = "std"))] type AllPalletsWithoutSystem = - (Balances, LocalAssets, ForeignAssets, Oracle, PolimecFunding, LinearRelease, Random); + (Balances, ContributionTokens, ForeignAssets, Oracle, PolimecFunding, LinearRelease, Random); type AuctionInitializePeriodDuration = AuctionInitializePeriodDuration; type Balance = Balance; type BlockNumber = BlockNumber; type BlockNumberToBalance = ConvertInto; type CandleAuctionDuration = CandleAuctionDuration; type CommunityFundingDuration = CommunityFundingDuration; - type ContributionTokenCurrency = LocalAssets; + type ContributionTokenCurrency = ContributionTokens; type ContributionTreasury = TreasuryAccount; type DaysToBlocks = DaysToBlocks; type EnglishAuctionDuration = EnglishAuctionDuration; @@ -896,7 +896,7 @@ construct_runtime!( Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, AssetTxPayment: pallet_asset_tx_payment::{Pallet, Storage, Event} = 12, - LocalAssets: pallet_assets::::{Pallet, Storage, Event} = 13, + ContributionTokens: pallet_assets::::{Pallet, Storage, Event} = 13, ForeignAssets: pallet_assets::::{Pallet, Call, Config, Storage, Event} = 14, From 1722e34302011ef61eeab342824ba9605f97884a Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 15:42:17 +0100 Subject: [PATCH 2/6] fmt --- pallets/funding/src/functions.rs | 1 - pallets/funding/src/instantiator.rs | 26 +++++++++----------------- pallets/funding/src/lib.rs | 5 +---- pallets/funding/src/types.rs | 2 +- runtimes/testnet/src/lib.rs | 2 +- 5 files changed, 12 insertions(+), 24 deletions(-) diff --git a/pallets/funding/src/functions.rs b/pallets/funding/src/functions.rs index 18a772246..0aad21546 100644 --- a/pallets/funding/src/functions.rs +++ b/pallets/funding/src/functions.rs @@ -1357,7 +1357,6 @@ impl Pallet { ct_migration_status: MigrationStatus::NotStarted, }; - // 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, asset_id)?; diff --git a/pallets/funding/src/instantiator.rs b/pallets/funding/src/instantiator.rs index 61cde1db5..e334f33f5 100644 --- a/pallets/funding/src/instantiator.rs +++ b/pallets/funding/src/instantiator.rs @@ -35,7 +35,7 @@ use frame_support::{ use frame_system::pallet_prelude::BlockNumberFor; use itertools::Itertools; use parity_scale_codec::Decode; -use polimec_common::credentials::{InvestorType}; +use polimec_common::credentials::InvestorType; #[cfg(any(test, feature = "std", feature = "runtime-benchmarks"))] use polimec_common_test_utils::generate_did_from_account; use sp_arithmetic::{ @@ -1126,10 +1126,8 @@ impl< self.bond_for_users(project_id, evaluations).unwrap(); - let expected_evaluator_balances = Self::sum_balance_mappings(vec![ - plmc_eval_deposits.clone(), - plmc_existential_deposits.clone(), - ]); + let expected_evaluator_balances = + Self::sum_balance_mappings(vec![plmc_eval_deposits.clone(), plmc_existential_deposits.clone()]); let expected_total_supply = prev_supply + expected_evaluator_balances; @@ -1227,10 +1225,8 @@ impl< None, ); - let bidder_balances = Self::sum_balance_mappings(vec![ - necessary_plmc_mint.clone(), - plmc_existential_deposits.clone(), - ]); + let bidder_balances = + Self::sum_balance_mappings(vec![necessary_plmc_mint.clone(), plmc_existential_deposits.clone()]); let expected_free_plmc_balances = Self::generic_map_operation( vec![prev_plmc_balances, plmc_existential_deposits.clone()], @@ -1390,10 +1386,8 @@ impl< let plmc_existential_deposits = contributors.existential_deposits(); let funding_asset_deposits = Self::calculate_contributed_funding_asset_spent(contributions.clone(), ct_price); - let contributor_balances = Self::sum_balance_mappings(vec![ - necessary_plmc_mint.clone(), - plmc_existential_deposits.clone(), - ]); + let contributor_balances = + Self::sum_balance_mappings(vec![necessary_plmc_mint.clone(), plmc_existential_deposits.clone()]); let expected_free_plmc_balances = Self::generic_map_operation( vec![prev_plmc_balances, plmc_existential_deposits.clone()], @@ -1476,10 +1470,8 @@ impl< let funding_asset_deposits = Self::calculate_contributed_funding_asset_spent(remainder_contributions.clone(), ct_price); - let contributor_balances = Self::sum_balance_mappings(vec![ - necessary_plmc_mint.clone(), - plmc_existential_deposits.clone(), - ]); + let contributor_balances = + Self::sum_balance_mappings(vec![necessary_plmc_mint.clone(), plmc_existential_deposits.clone()]); let expected_free_plmc_balances = Self::generic_map_operation( vec![prev_plmc_balances, plmc_existential_deposits.clone()], diff --git a/pallets/funding/src/lib.rs b/pallets/funding/src/lib.rs index 2237dc514..9ee5a6ee9 100644 --- a/pallets/funding/src/lib.rs +++ b/pallets/funding/src/lib.rs @@ -132,10 +132,7 @@ use polimec_common::{ }; use polkadot_parachain::primitives::Id as ParaId; use sp_arithmetic::traits::{One, Saturating}; -use sp_runtime::{ - traits::{AccountIdConversion}, - FixedPointNumber, FixedPointOperand, FixedU128, -}; +use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedPointOperand, FixedU128}; use sp_std::{marker::PhantomData, prelude::*}; use traits::DoRemainingOperation; pub use types::*; diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index 85df355a7..4c2c24e49 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -157,12 +157,12 @@ pub mod config_types { } pub mod storage_types { + use super::*; use crate::US_DOLLAR; use sp_arithmetic::{ traits::{One, Saturating, Zero}, Percent, }; - use super::*; #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] diff --git a/runtimes/testnet/src/lib.rs b/runtimes/testnet/src/lib.rs index cc69a5fb9..9b450aa58 100644 --- a/runtimes/testnet/src/lib.rs +++ b/runtimes/testnet/src/lib.rs @@ -37,7 +37,7 @@ pub use parachains_common::{ NORMAL_DISPATCH_RATIO, SLOT_DURATION, }; use parity_scale_codec::Encode; -use polimec_common::credentials::{EnsureInvestor}; +use polimec_common::credentials::EnsureInvestor; // Polkadot imports use polkadot_runtime_common::{BlockHashCount, CurrencyToVote, SlowAdjustingFeeUpdate}; From 72435dfbc2f88a093e3a46f602777d812fc8663e Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 15:59:38 +0100 Subject: [PATCH 3/6] add basecall filter to disable contribution token calls --- runtimes/testnet/src/lib.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/runtimes/testnet/src/lib.rs b/runtimes/testnet/src/lib.rs index 9b450aa58..2ed04e053 100644 --- a/runtimes/testnet/src/lib.rs +++ b/runtimes/testnet/src/lib.rs @@ -26,7 +26,7 @@ use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, traits::{ fungible::{Credit, Inspect}, - tokens, AsEnsureOriginWithArg, ConstU32, Currency, EitherOfDiverse, Everything, PrivilegeCmp, WithdrawReasons, + tokens, AsEnsureOriginWithArg, ConstU32, Contains, Currency, EitherOfDiverse, PrivilegeCmp, WithdrawReasons, }, weights::{ConstantMultiplier, Weight}, }; @@ -190,15 +190,24 @@ parameter_types! { pub const SS58Prefix: u8 = 41; } -// Configure FRAME pallets to include in runtime. +pub struct BaseCallFilter; +impl Contains for BaseCallFilter { + fn contains(c: &RuntimeCall) -> bool { + match *c { + RuntimeCall::ContributionTokens(_) => false, + _ => true, + } + } +} +// Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; /// The identifier used to distinguish between accounts. type AccountId = AccountId; /// The basic call filter to use in dispatchable. - type BaseCallFilter = Everything; + type BaseCallFilter = BaseCallFilter; /// The block type. type Block = Block; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). @@ -896,7 +905,7 @@ construct_runtime!( Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, AssetTxPayment: pallet_asset_tx_payment::{Pallet, Storage, Event} = 12, - ContributionTokens: pallet_assets::::{Pallet, Storage, Event} = 13, + ContributionTokens: pallet_assets::::{Pallet, Call, Storage, Event} = 13, ForeignAssets: pallet_assets::::{Pallet, Call, Config, Storage, Event} = 14, From 62605b448b1c3964ac7aff1b0ae35dc1aa3238c2 Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 16:50:26 +0100 Subject: [PATCH 4/6] remove metadata deposit for project token + some left deposits --- pallets/funding/src/benchmarking.rs | 13 +++---------- pallets/funding/src/functions.rs | 9 --------- pallets/funding/src/instantiator.rs | 14 ++------------ pallets/funding/src/tests.rs | 15 --------------- runtimes/shared-configuration/src/assets.rs | 2 +- runtimes/testnet/src/lib.rs | 6 +++--- 6 files changed, 9 insertions(+), 50 deletions(-) diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index c881e57b8..9f977d780 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -393,14 +393,10 @@ mod benchmarks { whitelist_account!(issuer); let project_metadata = default_project::(inst.get_new_nonce(), issuer.clone()); - let metadata_deposit = T::ContributionTokenCurrency::calc_metadata_deposit( - project_metadata.token_information.name.as_slice(), - project_metadata.token_information.symbol.as_slice(), - ); - let ct_account_deposit = T::ContributionTokenCurrency::deposit_required(0); + inst.mint_plmc_to(vec![UserToPLMCBalance::new( issuer.clone(), - ed * 2u64.into() + metadata_deposit + ct_account_deposit, + ed * 2u64.into() )]); let jwt = get_mock_jwt(issuer.clone(), InvestorType::Institutional, generate_did_from_account(issuer.clone())); @@ -557,11 +553,8 @@ mod benchmarks { } // possible branches: - // - pays ct account deposit - // - we know this happens only if param x = 0, but we cannot fit it in the linear regression + // - is under max evals per user, and needs to bond the evaluation // - is over max evals per user, and needs to unbond the lowest evaluation - // - this case, we know they paid already for ct account deposit - fn evaluation_setup(x: u32) -> (BenchInstantiator, ProjectId, UserToUSDBalance, BalanceOf, BalanceOf) where T: Config, diff --git a/pallets/funding/src/functions.rs b/pallets/funding/src/functions.rs index 0aad21546..552a850fc 100644 --- a/pallets/funding/src/functions.rs +++ b/pallets/funding/src/functions.rs @@ -135,15 +135,6 @@ impl Pallet { ) .map_err(|_| Error::::NotEnoughFundsForEscrowCreation)?; - // Each project needs a new token type to be created (i.e contribution token). - // This creation is done automatically in the project transition on success, but someone needs to pay for the storage - // of the metadata associated with it. - let metadata_deposit = T::ContributionTokenCurrency::calc_metadata_deposit( - initial_metadata.token_information.name.as_slice(), - initial_metadata.token_information.symbol.as_slice(), - ); - T::NativeCurrency::transfer(&issuer, &escrow_account, metadata_deposit, Preservation::Preserve) - .map_err(|_| Error::::NotEnoughFundsForCTMetadata)?; // * Update storage * ProjectsMetadata::::insert(project_id, &initial_metadata); diff --git a/pallets/funding/src/instantiator.rs b/pallets/funding/src/instantiator.rs index e334f33f5..0ab39aa16 100644 --- a/pallets/funding/src/instantiator.rs +++ b/pallets/funding/src/instantiator.rs @@ -1024,14 +1024,10 @@ impl< pub fn create_new_project(&mut self, project_metadata: ProjectMetadataOf, issuer: AccountIdOf) -> ProjectId { let now = self.current_block(); - let metadata_deposit = T::ContributionTokenCurrency::calc_metadata_deposit( - project_metadata.token_information.name.as_slice(), - project_metadata.token_information.symbol.as_slice(), - ); // 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() + metadata_deposit, + Self::get_ed() * 2u64.into(), )]); self.execute(|| { @@ -1711,16 +1707,10 @@ pub mod async_features { let mut inst = instantiator.lock().await; let now = inst.current_block(); - let metadata_deposit = T::ContributionTokenCurrency::calc_metadata_deposit( - project_metadata.token_information.name.as_slice(), - project_metadata.token_information.symbol.as_slice(), - ); - let ct_deposit = Instantiator::::get_ct_account_deposit(); // One ED for the issuer, one for the escrow account inst.mint_plmc_to(vec![UserToPLMCBalance::new( issuer.clone(), - Instantiator::::get_ed() * 2u64.into() + - metadata_deposit + ct_deposit, + Instantiator::::get_ed() * 2u64.into() )]); inst.execute(|| { crate::Pallet::::do_create( diff --git a/pallets/funding/src/tests.rs b/pallets/funding/src/tests.rs index bd4a1d66e..880243a9d 100644 --- a/pallets/funding/src/tests.rs +++ b/pallets/funding/src/tests.rs @@ -3848,14 +3848,6 @@ mod funding_end { vec![slashed_evaluation_locked_plmc, old_participation_locked_plmc, old_free_plmc], MergeOperation::Add, ); - let ct_deposit_required = <::ContributionTokenCurrency as AccountTouch< - ProjectId, - AccountIdOf, - >>::deposit_required(project_id); - expected_evaluator_free_balances - .iter_mut() - .for_each(|UserToPLMCBalance { plmc_amount, .. }| *plmc_amount += ct_deposit_required); - let actual_evaluator_free_balances = inst.get_free_plmc_balances_for(evaluators.clone()); assert_eq!(actual_evaluator_free_balances, expected_evaluator_free_balances); @@ -3890,13 +3882,6 @@ mod funding_end { vec![slashed_evaluation_locked_plmc, old_participation_locked_plmc, old_free_plmc], MergeOperation::Add, ); - let ct_deposit_required = <::ContributionTokenCurrency as AccountTouch< - ProjectId, - AccountIdOf, - >>::deposit_required(project_id); - expected_evaluator_free_balances - .iter_mut() - .for_each(|UserToPLMCBalance { plmc_amount, .. }| *plmc_amount += ct_deposit_required); let actual_evaluator_free_balances = inst.get_free_plmc_balances_for(evaluators.clone()); diff --git a/runtimes/shared-configuration/src/assets.rs b/runtimes/shared-configuration/src/assets.rs index ec7f0238a..8ac426322 100644 --- a/runtimes/shared-configuration/src/assets.rs +++ b/runtimes/shared-configuration/src/assets.rs @@ -32,7 +32,7 @@ parameter_types! { pub const MetadataDepositBase: Balance = deposit(1, 68); pub const MetadataDepositPerByte: Balance = deposit(0, 1); pub const AssetAccountDeposit: Balance = deposit(1, 18); - pub const ZeroAssetAccountDeposit: Balance = 0; + pub const ZeroDeposit: Balance = 0; } pub struct OraclePriceProvider(PhantomData<(AssetId, Price, Oracle)>); diff --git a/runtimes/testnet/src/lib.rs b/runtimes/testnet/src/lib.rs index 2ed04e053..14b1f490a 100644 --- a/runtimes/testnet/src/lib.rs +++ b/runtimes/testnet/src/lib.rs @@ -579,7 +579,7 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type ApprovalDeposit = ExistentialDeposit; - type AssetAccountDeposit = ZeroAssetAccountDeposit; + type AssetAccountDeposit = ZeroDeposit; type AssetDeposit = AssetDeposit; type AssetId = AssetId; type AssetIdParameter = parity_scale_codec::Compact; @@ -592,8 +592,8 @@ impl pallet_assets::Config for Runtime { type Extra = (); type ForceOrigin = EnsureRoot; type Freezer = (); - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; + type MetadataDepositBase = ZeroDeposit; + type MetadataDepositPerByte = ZeroDeposit; type RemoveItemsLimit = frame_support::traits::ConstU32<1000>; type RuntimeEvent = RuntimeEvent; type StringLimit = AssetsStringLimit; From 36a09f0197f91c21127c36f1755f57ec2af99354 Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 16:52:39 +0100 Subject: [PATCH 5/6] fmt --- pallets/funding/src/benchmarking.rs | 6 +----- pallets/funding/src/functions.rs | 6 +----- pallets/funding/src/instantiator.rs | 12 ++++-------- 3 files changed, 6 insertions(+), 18 deletions(-) diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index 9f977d780..d92b4c511 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -393,11 +393,7 @@ mod benchmarks { whitelist_account!(issuer); let project_metadata = default_project::(inst.get_new_nonce(), issuer.clone()); - - inst.mint_plmc_to(vec![UserToPLMCBalance::new( - issuer.clone(), - ed * 2u64.into() - )]); + inst.mint_plmc_to(vec![UserToPLMCBalance::new(issuer.clone(), ed * 2u64.into())]); let jwt = get_mock_jwt(issuer.clone(), InvestorType::Institutional, generate_did_from_account(issuer.clone())); #[extrinsic_call] diff --git a/pallets/funding/src/functions.rs b/pallets/funding/src/functions.rs index 552a850fc..5330bd4ac 100644 --- a/pallets/funding/src/functions.rs +++ b/pallets/funding/src/functions.rs @@ -24,10 +24,7 @@ use frame_support::{ pallet_prelude::*, traits::{ fungible::{Mutate, MutateHold as FungibleMutateHold}, - fungibles::{ - metadata::{MetadataDeposit, Mutate as MetadataMutate}, - Create, Inspect, Mutate as FungiblesMutate, - }, + fungibles::{metadata::Mutate as MetadataMutate, Create, Inspect, Mutate as FungiblesMutate}, tokens::{Fortitude, Precision, Preservation, Restriction}, Get, }, @@ -135,7 +132,6 @@ impl Pallet { ) .map_err(|_| Error::::NotEnoughFundsForEscrowCreation)?; - // * Update storage * ProjectsMetadata::::insert(project_id, &initial_metadata); ProjectsDetails::::insert(project_id, project_details); diff --git a/pallets/funding/src/instantiator.rs b/pallets/funding/src/instantiator.rs index 0ab39aa16..c972fee9b 100644 --- a/pallets/funding/src/instantiator.rs +++ b/pallets/funding/src/instantiator.rs @@ -23,9 +23,8 @@ use frame_support::{ traits::{ fungible::{Inspect as FungibleInspect, InspectHold as FungibleInspectHold, Mutate as FungibleMutate}, fungibles::{ - metadata::{Inspect as MetadataInspect, MetadataDeposit}, - roles::Inspect as RolesInspect, - Inspect as FungiblesInspect, Mutate as FungiblesMutate, + metadata::Inspect as MetadataInspect, roles::Inspect as RolesInspect, Inspect as FungiblesInspect, + Mutate as FungiblesMutate, }, AccountTouch, Get, OnFinalize, OnIdle, OnInitialize, }, @@ -1025,10 +1024,7 @@ impl< pub fn create_new_project(&mut self, project_metadata: ProjectMetadataOf, issuer: AccountIdOf) -> ProjectId { let now = self.current_block(); // 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() * 2u64.into())]); self.execute(|| { crate::Pallet::::do_create(&issuer, project_metadata.clone(), generate_did_from_account(issuer.clone())) @@ -1710,7 +1706,7 @@ pub mod async_features { // One ED for the issuer, one for the escrow account inst.mint_plmc_to(vec![UserToPLMCBalance::new( issuer.clone(), - Instantiator::::get_ed() * 2u64.into() + Instantiator::::get_ed() * 2u64.into(), )]); inst.execute(|| { crate::Pallet::::do_create( From f29a4264e89633152b0aef67f00addfaeb073495 Mon Sep 17 00:00:00 2001 From: Just van Stam Date: Wed, 20 Mar 2024 17:27:32 +0100 Subject: [PATCH 6/6] fix warnings --- pallets/funding/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/funding/src/tests.rs b/pallets/funding/src/tests.rs index 880243a9d..e37f40c92 100644 --- a/pallets/funding/src/tests.rs +++ b/pallets/funding/src/tests.rs @@ -3844,7 +3844,7 @@ mod funding_end { ); let slashed_evaluation_locked_plmc = MockInstantiator::slash_evaluator_balances(old_evaluation_locked_plmc); - let mut expected_evaluator_free_balances = MockInstantiator::generic_map_operation( + let expected_evaluator_free_balances = MockInstantiator::generic_map_operation( vec![slashed_evaluation_locked_plmc, old_participation_locked_plmc, old_free_plmc], MergeOperation::Add, ); @@ -3878,7 +3878,7 @@ mod funding_end { ); let slashed_evaluation_locked_plmc = MockInstantiator::slash_evaluator_balances(old_evaluation_locked_plmc); - let mut expected_evaluator_free_balances = MockInstantiator::generic_map_operation( + let expected_evaluator_free_balances = MockInstantiator::generic_map_operation( vec![slashed_evaluation_locked_plmc, old_participation_locked_plmc, old_free_plmc], MergeOperation::Add, );