diff --git a/Cargo.lock b/Cargo.lock
index 5d85799bb..d63627496 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8422,6 +8422,7 @@ dependencies = [
"macros",
"pallet-funding",
"pallet-transaction-payment-rpc",
+ "polimec-common",
"polimec-runtime",
"politest-runtime",
"polkadot-cli",
diff --git a/integration-tests/src/constants.rs b/integration-tests/src/constants.rs
index 42dfac528..f14796e94 100644
--- a/integration-tests/src/constants.rs
+++ b/integration-tests/src/constants.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
+use frame_support::BoundedVec;
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
pub use parachains_common::{AccountId, AssetHubPolkadotAuraId, AuraId, Balance, BlockNumber};
use politest_runtime::{
@@ -26,13 +27,14 @@ use politest_runtime::{
use polkadot_primitives::{AssignmentId, ValidatorId};
pub use polkadot_runtime_parachains::configuration::HostConfiguration;
use sc_consensus_grandpa::AuthorityId as GrandpaId;
-use sp_arithmetic::Percent;
+use sp_arithmetic::{FixedU128, Percent};
use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
use sp_consensus_babe::AuthorityId as BabeId;
use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId;
use sp_core::{sr25519, storage::Storage, Pair, Public};
use sp_runtime::{bounded_vec, BuildStorage, Perbill};
+use pallet_funding::AcceptedFundingAsset;
pub use xcm;
use xcm_emulator::{helpers::get_account_id_from_seed, Chain, Parachain};
@@ -318,10 +320,10 @@ pub mod asset_hub {
// Polimec
pub mod politest {
use super::*;
- use crate::{Polimec, PolitestRuntime, PolkadotNet};
- use pallet_funding::AcceptedFundingAsset;
+ use crate::{Polimec, PolitestNet, PolitestOrigin, PolitestRuntime, PolkadotNet};
use sp_runtime::traits::AccountIdConversion;
use xcm::v3::Parent;
+ use xcm_emulator::TestExt;
pub const PARA_ID: u32 = 3344;
pub const ED: Balance = politest_runtime::EXISTENTIAL_DEPOSIT;
@@ -331,6 +333,45 @@ pub mod politest {
const GENESIS_PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(0);
const GENESIS_NUM_SELECTED_CANDIDATES: u32 = 5;
+ pub fn set_prices() {
+ PolitestNet::execute_with(|| {
+ let dot = (AcceptedFundingAsset::DOT.to_assethub_id(), FixedU128::from_rational(69, 1));
+ let usdc = (AcceptedFundingAsset::USDC.to_assethub_id(), FixedU128::from_rational(1, 1));
+ let usdt = (AcceptedFundingAsset::USDT.to_assethub_id(), FixedU128::from_rational(1, 1));
+ let plmc = (pallet_funding::PLMC_FOREIGN_ID, FixedU128::from_rational(840, 100));
+
+ let values: BoundedVec<(u32, FixedU128), ::MaxFeedValues> =
+ vec![dot, usdc, usdt, plmc].try_into().expect("benchmarks can panic");
+ let alice: [u8; 32] = [
+ 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205,
+ 227, 154, 86, 132, 231, 165, 109, 162, 125,
+ ];
+ let bob: [u8; 32] = [
+ 142, 175, 4, 21, 22, 135, 115, 99, 38, 201, 254, 161, 126, 37, 252, 82, 135, 97, 54, 147, 201, 18, 144,
+ 156, 178, 38, 170, 71, 148, 242, 106, 72,
+ ];
+ let charlie: [u8; 32] = [
+ 144, 181, 171, 32, 92, 105, 116, 201, 234, 132, 27, 230, 136, 134, 70, 51, 220, 156, 168, 163, 87, 132,
+ 62, 234, 207, 35, 20, 100, 153, 101, 254, 34,
+ ];
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolitestOrigin::signed(alice.clone().into()),
+ values.clone()
+ ));
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolitestOrigin::signed(bob.clone().into()),
+ values.clone()
+ ));
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolitestOrigin::signed(charlie.clone().into()),
+ values.clone()
+ ));
+ });
+ }
+
pub fn genesis() -> Storage {
let dot_asset_id = AcceptedFundingAsset::DOT.to_assethub_id();
let usdt_asset_id = AcceptedFundingAsset::USDT.to_assethub_id();
@@ -437,7 +478,6 @@ pub mod politest {
],
accounts: vec![],
},
- funding: Default::default(),
vesting: Default::default(),
transaction_payment: Default::default(),
contribution_tokens: Default::default(),
@@ -506,10 +546,11 @@ pub mod penpal {
// Polimec Runtime
pub mod polimec {
use super::*;
- use crate::PolimecNet;
+ use crate::{PolimecNet, PolimecOrigin, PolimecRuntime};
use pallet_funding::AcceptedFundingAsset;
use polimec_runtime::PayMaster;
use xcm::v3::Parent;
+ use xcm_emulator::TestExt;
pub const PARA_ID: u32 = 3344;
pub const ED: Balance = polimec_runtime::EXISTENTIAL_DEPOSIT;
@@ -519,6 +560,46 @@ pub mod polimec {
const GENESIS_PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(0);
const GENESIS_NUM_SELECTED_CANDIDATES: u32 = 5;
+ #[allow(unused)]
+ pub fn set_prices() {
+ PolimecNet::execute_with(|| {
+ let dot = (AcceptedFundingAsset::DOT.to_assethub_id(), FixedU128::from_rational(69, 1));
+ let usdc = (AcceptedFundingAsset::USDC.to_assethub_id(), FixedU128::from_rational(1, 1));
+ let usdt = (AcceptedFundingAsset::USDT.to_assethub_id(), FixedU128::from_rational(1, 1));
+ let plmc = (pallet_funding::PLMC_FOREIGN_ID, FixedU128::from_rational(840, 100));
+
+ let values: BoundedVec<(u32, FixedU128), ::MaxFeedValues> =
+ vec![dot, usdc, usdt, plmc].try_into().expect("benchmarks can panic");
+ let alice: [u8; 32] = [
+ 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205,
+ 227, 154, 86, 132, 231, 165, 109, 162, 125,
+ ];
+ let bob: [u8; 32] = [
+ 142, 175, 4, 21, 22, 135, 115, 99, 38, 201, 254, 161, 126, 37, 252, 82, 135, 97, 54, 147, 201, 18, 144,
+ 156, 178, 38, 170, 71, 148, 242, 106, 72,
+ ];
+ let charlie: [u8; 32] = [
+ 144, 181, 171, 32, 92, 105, 116, 201, 234, 132, 27, 230, 136, 134, 70, 51, 220, 156, 168, 163, 87, 132,
+ 62, 234, 207, 35, 20, 100, 153, 101, 254, 34,
+ ];
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolimecOrigin::signed(alice.clone().into()),
+ values.clone()
+ ));
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolimecOrigin::signed(bob.clone().into()),
+ values.clone()
+ ));
+
+ frame_support::assert_ok!(orml_oracle::Pallet::::feed_values(
+ PolimecOrigin::signed(charlie.clone().into()),
+ values.clone()
+ ));
+ });
+ }
+
pub fn genesis() -> Storage {
let dot_asset_id = AcceptedFundingAsset::DOT.to_assethub_id();
let usdt_asset_id = AcceptedFundingAsset::USDT.to_assethub_id();
@@ -548,7 +629,6 @@ pub mod polimec {
system: Default::default(),
balances: polimec_runtime::BalancesConfig { balances: funded_accounts },
contribution_tokens: Default::default(),
- funding: Default::default(),
foreign_assets: polimec_runtime::ForeignAssetsConfig {
assets: vec![
(dot_asset_id, alice_account.clone(), true, 0_0_010_000_000u128),
diff --git a/integration-tests/src/tests/basic_comms.rs b/integration-tests/src/tests/basic_comms.rs
deleted file mode 100644
index 0d40d82a0..000000000
--- a/integration-tests/src/tests/basic_comms.rs
+++ /dev/null
@@ -1,145 +0,0 @@
-// Polimec Blockchain – https://www.polimec.org/
-// Copyright (C) Polimec 2022. All rights reserved.
-
-// The Polimec Blockchain is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// The Polimec Blockchain is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-
-#[allow(unused_imports)]
-use crate::*;
-
-const MAX_REF_TIME: u64 = 300_000_000;
-const MAX_PROOF_SIZE: u64 = 10_000;
-
-// Ignored for now as we are not allowing "Transact" execution on our parachain
-#[ignore]
-#[test]
-fn dmp() {
- let remark = PolimecCall::System(frame_system::Call::::remark_with_event {
- remark: "Hello from Polkadot!".as_bytes().to_vec(),
- });
- let sudo_origin = PolkadotOrigin::root();
- let para_id = PolimecNet::para_id();
- let xcm = VersionedXcm::from(Xcm(vec![
- UnpaidExecution { weight_limit: Unlimited, check_origin: None },
- Transact {
- origin_kind: OriginKind::SovereignAccount,
- require_weight_at_most: Weight::from_parts(MAX_REF_TIME, MAX_PROOF_SIZE),
- call: remark.encode().into(),
- },
- ]));
-
- PolkaNet::execute_with(|| {
- assert_ok!(PolkadotXcmPallet::send(sudo_origin, bx!(Parachain(para_id.into()).into()), bx!(xcm),));
-
- assert_expected_events!(
- PolkaNet,
- vec![
- PolkadotEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {},
- ]
- );
- });
-
- PolimecNet::execute_with(|| {
- assert_expected_events!(
- PolimecNet,
- vec![
- PolimecEvent::System(frame_system::Event::Remarked { sender: _, hash: _ }) => {},
- ]
- );
- });
-}
-#[ignore]
-#[test]
-fn ump() {
- use polkadot_runtime_parachains::inclusion::{AggregateMessageOrigin, UmpQueueId};
- let burn_transfer = PolkadotCall::Balances(pallet_balances::Call::::transfer_allow_death {
- dest: PolkadotAccountId::from([0u8; 32]).into(),
- value: 1_000,
- });
-
- let here_asset: MultiAsset = (MultiLocation::here(), 1_0_000_000_000u128).into();
-
- PolimecNet::execute_with(|| {
- assert_ok!(PolimecXcmPallet::force_default_xcm_version(PolimecOrigin::root(), Some(3)));
-
- assert_ok!(PolimecXcmPallet::send_xcm(
- Here,
- Parent,
- Xcm(vec![
- WithdrawAsset(vec![here_asset.clone()].into()),
- BuyExecution { fees: here_asset.clone(), weight_limit: Unlimited },
- Transact {
- origin_kind: OriginKind::SovereignAccount,
- require_weight_at_most: Weight::from_parts(MAX_REF_TIME, MAX_PROOF_SIZE),
- call: burn_transfer.encode().into(),
- }
- ]),
- ));
- });
-
- PolkaNet::execute_with(|| {
- assert_expected_events!(
- PolkaNet,
- vec![
- PolkadotEvent::MessageQueue(pallet_message_queue::Event::Processed {
- id: _,
- origin: AggregateMessageOrigin::Ump(
- UmpQueueId::Para(_para_id)
- ),
- weight_used: _,
- success: false
- }) => {},
- ]
- );
- });
-}
-
-// Ignored for now as we are not allowing "Transact" execution on our parachain
-#[ignore]
-#[test]
-fn xcmp() {
- let burn_transfer = PolimecCall::Balances(pallet_balances::Call::::transfer_allow_death {
- dest: PolimecAccountId::from([0u8; 32]).into(),
- value: 1_000,
- });
-
- let here_asset: MultiAsset = (MultiLocation::here(), 1_0_000_000_000u128).into();
-
- PenNet::execute_with(|| {
- assert_ok!(PenpalXcmPallet::send_xcm(
- Here,
- MultiLocation::new(1, X1(Parachain(PolimecNet::para_id().into()))),
- Xcm(vec![
- WithdrawAsset(vec![here_asset.clone()].into()),
- BuyExecution { fees: here_asset.clone(), weight_limit: Unlimited },
- Transact {
- origin_kind: OriginKind::SovereignAccount,
- require_weight_at_most: Weight::from_parts(MAX_REF_TIME, MAX_PROOF_SIZE),
- call: burn_transfer.encode().into(),
- }
- ]),
- ));
- });
-
- let penpal_account = PolimecNet::sovereign_account_id_of((Parent, Parachain(PenNet::para_id().into())).into());
- let penpal_balance = PolimecNet::account_data_of(penpal_account.clone()).free;
-
- PolimecNet::execute_with(|| {
- assert_expected_events!(
- PolimecNet,
- vec![
- PolimecEvent::MessageQueue(pallet_message_queue::Event::Processed {success: true, ..}) => {},
- ]
- );
- });
-}
diff --git a/integration-tests/src/tests/build_spec.rs b/integration-tests/src/tests/build_spec.rs
deleted file mode 100644
index 52fed43ed..000000000
--- a/integration-tests/src/tests/build_spec.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Polimec Blockchain – https://www.polimec.org/
-// Copyright (C) Polimec 2022. All rights reserved.
-
-// The Polimec Blockchain is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// The Polimec Blockchain is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with this program. If not, see .
-#[ignore]
-#[test]
-fn build_spec_testing_node() {
- // run the polimec-node compiled with "std" with the build-spec command and --raw flag
- // This makes sure our async parallel instantiation of projects is working as intended.
- // We need this to test the protocol with the UI.
-
- match std::env::current_dir() {
- Ok(path) => {
- println!("The current directory is {}", path.display());
- },
- Err(e) => {
- println!("Error getting the current directory: {}", e);
- },
- }
-
- let output = std::process::Command::new("../target/release/polimec-node")
- .arg("build-spec")
- .arg("--chain=politest-populated")
- .arg("--disable-default-bootnode")
- .arg("--raw")
- .output()
- .expect("failed to execute process");
-
- dbg!(output.clone());
- assert_eq!(
- output.status.success(),
- true,
- "Make sure you compile the polimec-node with \"--release\" and \"--features std,fast-mode\" before running this test."
- );
-}
diff --git a/integration-tests/src/tests/ct_migration.rs b/integration-tests/src/tests/ct_migration.rs
index 307c762e8..8dce49cb4 100644
--- a/integration-tests/src/tests/ct_migration.rs
+++ b/integration-tests/src/tests/ct_migration.rs
@@ -179,6 +179,7 @@ fn create_settled_project() -> (ProjectId, Vec) {
#[test]
fn full_migration_test() {
+ politest::set_prices();
let (project_id, participants) = create_settled_project();
mock_hrmp_establishment(project_id);
diff --git a/integration-tests/src/tests/e2e.rs b/integration-tests/src/tests/e2e.rs
index f8e263498..aa75e9691 100644
--- a/integration-tests/src/tests/e2e.rs
+++ b/integration-tests/src/tests/e2e.rs
@@ -26,7 +26,6 @@ use itertools::Itertools;
use macros::generate_accounts;
use pallet_funding::{traits::ProvideAssetPrice, *};
use polimec_common::{USD_DECIMALS, USD_UNIT};
-use polimec_runtime::PLMC;
use sp_arithmetic::{traits::Zero, Percent, Perquintill};
use sp_runtime::{FixedPointNumber, FixedU128};
use xcm_emulator::log;
@@ -272,6 +271,8 @@ fn excel_ct_amounts() -> UserToCTBalance {
#[test]
fn evaluation_round_completed() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
let issuer = ISSUER.into();
@@ -285,6 +286,8 @@ fn evaluation_round_completed() {
#[test]
fn auction_round_completed() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
let issuer = ISSUER.into();
@@ -323,6 +326,8 @@ fn auction_round_completed() {
#[test]
fn community_round_completed() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
PolitestNet::execute_with(|| {
@@ -338,19 +343,21 @@ fn community_round_completed() {
let contributions = Contributions::::iter_prefix_values((0,))
.sorted_by_key(|bid| bid.contributor.clone())
.collect_vec();
- let total_contribution =
+ let _total_contribution =
contributions.clone().into_iter().fold(0, |acc, bid| acc + bid.funding_asset_amount);
- let total_contribution_as_fixed = FixedU128::from_rational(total_contribution, PLMC);
+ // TODO: add test for exact amount contributed
})
});
}
#[test]
fn remainder_round_completed() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
PolitestNet::execute_with(|| {
- let project_id = inst.create_finished_project(
+ inst.create_finished_project(
excel_project(),
ISSUER.into(),
excel_evaluators(),
@@ -359,16 +366,6 @@ fn remainder_round_completed() {
excel_remainders(),
);
- let price = inst.get_project_details(project_id).weighted_average_price.unwrap();
- let funding_necessary_1 = inst.calculate_contributed_funding_asset_spent(excel_contributions(), price);
- let funding_necessary_2 = inst.calculate_contributed_funding_asset_spent(excel_remainders(), price);
- let mut total = 0u128;
- for item in funding_necessary_1 {
- total += item.asset_amount;
- }
- for item in funding_necessary_2 {
- total += item.asset_amount;
- }
let contributions = Contributions::::iter_prefix_values((0,))
.sorted_by_key(|contribution| contribution.contributor.clone())
.collect_vec();
@@ -388,6 +385,8 @@ fn remainder_round_completed() {
#[test]
fn funds_raised() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
PolitestNet::execute_with(|| {
@@ -417,6 +416,8 @@ fn funds_raised() {
#[test]
fn ct_minted() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
PolitestNet::execute_with(|| {
@@ -443,6 +444,8 @@ fn ct_minted() {
#[test]
fn ct_migrated() {
+ politest::set_prices();
+
let mut inst = IntegrationInstantiator::new(None);
let project_id = PolitestNet::execute_with(|| {
diff --git a/integration-tests/src/tests/mod.rs b/integration-tests/src/tests/mod.rs
index fafd86d16..0888699c3 100644
--- a/integration-tests/src/tests/mod.rs
+++ b/integration-tests/src/tests/mod.rs
@@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
-mod basic_comms;
-mod build_spec;
mod credentials;
mod ct_migration;
mod defaults;
diff --git a/nodes/parachain/Cargo.toml b/nodes/parachain/Cargo.toml
index 522a5c9c8..48c19b65b 100644
--- a/nodes/parachain/Cargo.toml
+++ b/nodes/parachain/Cargo.toml
@@ -25,6 +25,7 @@ politest-runtime.workspace = true
polimec-runtime.workspace = true
pallet-funding.workspace = true
macros = { workspace = true }
+polimec-common.workspace = true
# Substrate
frame-benchmarking.workspace = true
@@ -110,7 +111,6 @@ std = [
"frame-benchmarking/std",
"frame-support/std",
"log/std",
- "pallet-funding/std",
"polkadot-primitives/std",
"serde/std",
"sp-api/std",
diff --git a/nodes/parachain/src/chain_spec/politest.rs b/nodes/parachain/src/chain_spec/politest.rs
index c4e33ab87..d1528e236 100644
--- a/nodes/parachain/src/chain_spec/politest.rs
+++ b/nodes/parachain/src/chain_spec/politest.rs
@@ -45,6 +45,7 @@ const COLLATOR_COMMISSION: Perbill = Perbill::from_percent(30);
const PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(0);
const BLOCKS_PER_ROUND: u32 = 2 * 10;
const NUM_SELECTED_CANDIDATES: u32 = 5;
+
pub fn polimec_inflation_config() -> InflationInfo {
fn to_round_inflation(annual: Range) -> Range {
perbill_annual_to_perbill_round(
@@ -70,49 +71,6 @@ pub fn get_politest_session_keys(keys: AuthorityId) -> politest_runtime::Session
politest_runtime::SessionKeys { aura: keys }
}
-#[cfg(feature = "std")]
-pub fn get_populated_chain_spec() -> Result {
- let properties = get_properties("PLMC", 10, 41);
- let wasm = politest_runtime::WASM_BINARY.ok_or("No WASM")?;
-
- #[allow(deprecated)]
- Ok(ChainSpec::from_genesis(
- "Polimec Develop",
- "polimec",
- ChainType::Local,
- move || {
- testing_genesis(
- vec![
- (get_account_id_from_seed::("Alice"), None, 2 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Bob"), None, 2 * MinCandidateStk::get()),
- ],
- polimec_inflation_config(),
- vec![
- get_account_id_from_seed::("Alice"),
- get_account_id_from_seed::("Bob"),
- ],
- vec![
- (get_account_id_from_seed::("Alice"), 5 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Bob"), 5 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Charlie"), 5 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Dave"), 5 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Eve"), 5 * MinCandidateStk::get()),
- (get_account_id_from_seed::("Ferdie"), 5 * MinCandidateStk::get()),
- ],
- get_account_id_from_seed::("Alice"),
- DEFAULT_PARA_ID,
- )
- },
- vec![],
- None,
- None,
- None,
- Some(properties),
- Extensions { relay_chain: "rococo-local".into(), para_id: DEFAULT_PARA_ID.into() },
- wasm,
- ))
-}
-
pub fn get_local_chain_spec() -> GenericChainSpec {
let properties = get_properties("RLMC", 10, 41);
@@ -289,272 +247,3 @@ fn testnet_genesis(
},
})
}
-
-#[cfg(feature = "std")]
-mod testing_helpers {
- use super::*;
- pub use macros::generate_accounts;
- pub use pallet_funding::{instantiator::UserToUSDBalance, ProjectStatus, *};
- pub use sp_runtime::{
- traits::{ConstU32, Get, PhantomData},
- BoundedVec, FixedPointNumber,
- };
-
- pub const IPFS_CID: &str = "QmeuJ24ffwLAZppQcgcggJs3n689bewednYkuc8Bx5Gngz";
- pub const ASSET_DECIMALS: u8 = 10;
- pub const ASSET_UNIT: u128 = 10_u128.pow(10 as u32);
-
- generate_accounts!(
- ALICE, BOB, CHARLIE, ISSUER, ISSUER_1, ISSUER_2, ISSUER_3, ISSUER_4, ISSUER_5, ISSUER_6, EVAL_1, EVAL_2,
- EVAL_3, EVAL_4, BIDDER_1, BIDDER_2, BIDDER_3, BIDDER_4, BIDDER_5, BIDDER_6, BUYER_1, BUYER_2, BUYER_3, BUYER_4,
- BUYER_5, BUYER_6,
- );
-
- pub fn bounded_name() -> BoundedVec> {
- BoundedVec::try_from("Contribution Token TEST".as_bytes().to_vec()).unwrap()
- }
- pub fn bounded_symbol() -> BoundedVec> {
- BoundedVec::try_from("CTEST".as_bytes().to_vec()).unwrap()
- }
- pub fn ipfs_hash() -> BoundedVec> {
- BoundedVec::try_from(IPFS_CID.as_bytes().to_vec()).unwrap()
- }
- pub fn default_weights() -> Vec {
- vec![20u8, 15u8, 10u8, 25u8, 30u8]
- }
-
- pub fn project_metadata(issuer: AccountId) -> ProjectMetadataOf {
- ProjectMetadata {
- token_information: CurrencyMetadata {
- name: bounded_name(),
- symbol: bounded_symbol(),
- decimals: ASSET_DECIMALS,
- },
- mainnet_token_max_supply: 8_000_000 * ASSET_UNIT,
- total_allocation_size: 1_000_000 * ASSET_UNIT,
- auction_round_allocation_percentage: Percent::from_percent(50u8),
- minimum_price: PriceOf::::from_float(10.0),
- bidding_ticket_sizes: BiddingTicketSizes {
- professional: TicketSize::new(Some(5000 * USD_UNIT), None),
- institutional: TicketSize::new(Some(5000 * USD_UNIT), None),
- phantom: Default::default(),
- },
- contributing_ticket_sizes: ContributingTicketSizes {
- retail: TicketSize::new(None, None),
- professional: TicketSize::new(None, None),
- institutional: TicketSize::new(None, None),
- phantom: Default::default(),
- },
- participation_currencies: vec![AcceptedFundingAsset::USDT].try_into().unwrap(),
- funding_destination_account: issuer,
- policy_ipfs_cid: Some(ipfs_hash()),
- }
- }
- pub fn default_evaluations() -> Vec> {
- vec![
- UserToUSDBalance::new(EVAL_1.into(), 500_000 * PLMC),
- UserToUSDBalance::new(EVAL_2.into(), 250_000 * PLMC),
- UserToUSDBalance::new(EVAL_3.into(), 320_000 * PLMC),
- ]
- }
- pub fn default_bidders() -> Vec {
- vec![BIDDER_1.into(), BIDDER_2.into(), BIDDER_3.into(), BIDDER_4.into(), BIDDER_5.into()]
- }
- pub fn default_bidder_multipliers() -> Vec {
- vec![10u8, 3u8, 8u8, 7u8, 9u8]
- }
- pub fn default_community_contributor_multipliers() -> Vec {
- vec![1u8, 1u8, 1u8, 1u8, 1u8]
- }
- pub fn default_remainder_contributor_multipliers() -> Vec {
- vec![1u8, 1u8, 1u8, 1u8, 1u8]
- }
-
- pub fn default_community_contributors() -> Vec {
- vec![BUYER_1.into(), BUYER_2.into(), BUYER_3.into(), BUYER_4.into(), BUYER_5.into()]
- }
-
- pub fn default_remainder_contributors() -> Vec {
- vec![EVAL_1.into(), BIDDER_3.into(), BUYER_4.into(), BUYER_6.into(), BIDDER_6.into()]
- }
-
- use politest_runtime::Runtime as T;
- pub type GenesisInstantiator = pallet_funding::instantiator::Instantiator<
- T,
- ::AllPalletsWithoutSystem,
- ::RuntimeEvent,
- >;
-}
-
-#[cfg(feature = "std")]
-#[allow(clippy::too_many_arguments)]
-fn testing_genesis(
- stakers: Vec<(AccountId, Option, Balance)>,
- inflation_config: InflationInfo,
- initial_authorities: Vec,
- mut endowed_accounts: Vec<(AccountId, Balance)>,
- sudo_account: AccountId,
- id: ParaId,
-) -> RuntimeGenesisConfig {
- use pallet_funding::instantiator::TestProjectParams;
- use politest_runtime::{
- BalancesConfig, CouncilConfig, ForeignAssetsConfig, ParachainInfoConfig, ParachainStakingConfig,
- PolkadotXcmConfig, SessionConfig, SudoConfig, TechnicalCommitteeConfig, EXISTENTIAL_DEPOSIT,
- };
- use sp_runtime::bounded_vec;
- use testing_helpers::*;
-
- // only used to generate some values, and not for chain interactions
- let default_project_metadata = project_metadata(ISSUER.into());
- let min_price = default_project_metadata.minimum_price;
- let usdt_funding_amount =
- default_project_metadata.minimum_price.checked_mul_int(default_project_metadata.total_allocation_size).unwrap();
- let evaluations = default_evaluations();
- let bids = GenesisInstantiator::generate_bids_from_total_usd(
- Percent::from_percent(40u8) * usdt_funding_amount,
- min_price,
- default_weights(),
- default_bidders(),
- default_bidder_multipliers(),
- );
- let community_contributions = GenesisInstantiator::generate_contributions_from_total_usd(
- Percent::from_percent(50u8) * usdt_funding_amount,
- min_price,
- default_weights(),
- default_community_contributors(),
- default_community_contributor_multipliers(),
- );
- let remainder_contributions = GenesisInstantiator::generate_contributions_from_total_usd(
- Percent::from_percent(5u8) * usdt_funding_amount,
- min_price,
- default_weights(),
- default_remainder_contributors(),
- default_remainder_contributor_multipliers(),
- );
-
- let accounts = endowed_accounts.iter().map(|(account, _)| account.clone()).collect::>();
- endowed_accounts
- .push((::PalletId::get().into_account_truncating(), EXISTENTIAL_DEPOSIT));
- endowed_accounts.push((::ContributionTreasury::get(), EXISTENTIAL_DEPOSIT));
- RuntimeGenesisConfig {
- system: Default::default(),
- oracle_providers_membership: OracleProvidersMembershipConfig {
- members: bounded_vec![
- get_account_id_from_seed::("Alice"),
- get_account_id_from_seed::("Bob"),
- get_account_id_from_seed::("Charlie"),
- ],
- phantom: Default::default(),
- },
- funding: politest_runtime::FundingConfig {
- starting_projects: vec![
- TestProjectParams:: {
- expected_state: ProjectStatus::FundingSuccessful,
- metadata: project_metadata(ISSUER_1.into()),
- issuer: ISSUER_1.into(),
- evaluations: evaluations.clone(),
- bids: bids.clone(),
- community_contributions: community_contributions.clone(),
- remainder_contributions: remainder_contributions.clone(),
- },
- TestProjectParams:: {
- expected_state: ProjectStatus::RemainderRound,
- metadata: project_metadata(ISSUER_2.into()),
- issuer: ISSUER_2.into(),
- evaluations: evaluations.clone(),
- bids: bids.clone(),
- community_contributions: community_contributions.clone(),
- remainder_contributions: vec![],
- },
- TestProjectParams:: {
- expected_state: ProjectStatus::CommunityRound,
- metadata: project_metadata(ISSUER_3.into()),
- issuer: ISSUER_3.into(),
- evaluations: evaluations.clone(),
- bids: bids.clone(),
- community_contributions: vec![],
- remainder_contributions: vec![],
- },
- TestProjectParams:: {
- expected_state: ProjectStatus::AuctionOpening,
- metadata: project_metadata(ISSUER_4.into()),
- issuer: ISSUER_4.into(),
- evaluations: evaluations.clone(),
- bids: vec![],
- community_contributions: vec![],
- remainder_contributions: vec![],
- },
- TestProjectParams:: {
- expected_state: ProjectStatus::EvaluationRound,
- metadata: project_metadata(ISSUER_5.into()),
- issuer: ISSUER_5.into(),
- evaluations: vec![],
- bids: vec![],
- community_contributions: vec![],
- remainder_contributions: vec![],
- },
- TestProjectParams:: {
- expected_state: ProjectStatus::Application,
- metadata: project_metadata(ISSUER_6.into()),
- issuer: ISSUER_6.into(),
- evaluations: vec![],
- bids: vec![],
- community_contributions: vec![],
- remainder_contributions: vec![],
- },
- ],
- phantom: PhantomData,
- },
- balances: BalancesConfig { balances: endowed_accounts.clone() },
- foreign_assets: ForeignAssetsConfig {
- assets: vec![(
- pallet_funding::types::AcceptedFundingAsset::USDT.to_assethub_id(),
- ::PalletId::get().into_account_truncating(),
- false,
- 10,
- )],
- metadata: vec![],
- accounts: vec![],
- },
- parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() },
- parachain_staking: ParachainStakingConfig {
- candidates: stakers.iter().map(|(accunt, _, balance)| (accunt.clone(), *balance)).collect::>(),
- inflation_config,
- delegations: vec![],
- collator_commission: COLLATOR_COMMISSION,
- parachain_bond_reserve_percent: PARACHAIN_BOND_RESERVE_PERCENT,
- blocks_per_round: BLOCKS_PER_ROUND,
- num_selected_candidates: NUM_SELECTED_CANDIDATES,
- },
- // no need to pass anything to aura, in fact it will panic if we do. Session will take care
- // of this.
- aura: Default::default(),
- aura_ext: Default::default(),
- parachain_system: Default::default(),
- session: SessionConfig {
- keys: initial_authorities
- .iter()
- .map(|acc| {
- (
- acc.clone(),
- acc.clone(),
- get_politest_session_keys(Into::<[u8; 32]>::into(acc.clone()).unchecked_into()),
- )
- })
- .collect::>(),
- },
- polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION), ..Default::default() },
- treasury: Default::default(),
- sudo: SudoConfig { key: Some(sudo_account) },
- council: CouncilConfig { members: accounts.clone(), phantom: Default::default() },
- technical_committee: TechnicalCommitteeConfig {
- members: accounts.clone().into_iter().take(5).collect(),
- phantom: Default::default(),
- },
- democracy: Default::default(),
- elections: Default::default(),
- vesting: Default::default(),
- contribution_tokens: Default::default(),
- transaction_payment: Default::default(),
- }
-}
diff --git a/nodes/parachain/src/command.rs b/nodes/parachain/src/command.rs
index df98f3c4d..0b0742675 100644
--- a/nodes/parachain/src/command.rs
+++ b/nodes/parachain/src/command.rs
@@ -97,8 +97,6 @@ fn load_spec(id: &str) -> std::result::Result, String> {
"polimec-local" => Box::new(chain_spec::polimec::get_local_chain_spec()),
"rolimec-local" => Box::new(chain_spec::polimec::get_rococo_chain_spec()),
"politest-local" => Box::new(chain_spec::politest::get_local_chain_spec()),
- #[cfg(feature = "std")]
- "politest-populated" => Box::new(chain_spec::politest::get_populated_chain_spec()?),
// -- Fallback (generic chainspec)
"" => {
log::warn!("No ChainSpec.id specified, so using default one, based on polimec-rococo-local");
diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs
index eb4e17ef9..d7f2177fc 100644
--- a/pallets/funding/src/benchmarking.rs
+++ b/pallets/funding/src/benchmarking.rs
@@ -32,7 +32,6 @@ use frame_support::{
use pallet::Pallet as PalletFunding;
use parity_scale_codec::{Decode, Encode};
use polimec_common::{credentials::InvestorType, USD_DECIMALS, USD_UNIT};
-use scale_info::prelude::format;
use sp_arithmetic::Percent;
use sp_core::H256;
use sp_io::hashing::blake2_256;
@@ -282,53 +281,6 @@ pub fn string_account(
.expect("infinite length input; no invalid inputs for type; qed")
}
-#[cfg(feature = "std")]
-pub fn populate_with_projects(amount: u32, inst: BenchInstantiator) -> BenchInstantiator
-where
- T: Config
- + frame_system::Config::RuntimeEvent>
- + pallet_balances::Config>,
- ::RuntimeEvent: TryInto> + Parameter + Member,
- ::Price: From,
- ::Balance: From,
- T::Hash: From,
- ::AccountId:
- Into<<::RuntimeOrigin as OriginTrait>::AccountId> + sp_std::fmt::Debug,
- ::Balance: Into>,
-{
- let states = vec![
- ProjectStatus::Application,
- ProjectStatus::EvaluationRound,
- ProjectStatus::AuctionOpening,
- ProjectStatus::CommunityRound,
- ProjectStatus::RemainderRound,
- ProjectStatus::FundingSuccessful,
- ]
- .into_iter()
- .cycle()
- .take(amount as usize);
-
- let instantiation_details = states
- .map(|state| {
- let nonce = inst.get_new_nonce();
- let issuer_name: String = format!("issuer_{}", nonce);
-
- let issuer = string_account::>(issuer_name, 0, 0);
- TestProjectParams:: {
- expected_state: state,
- metadata: default_project_metadata::(issuer.clone()),
- issuer: issuer.clone(),
- evaluations: default_evaluations::(),
- bids: default_bids::(),
- community_contributions: default_community_contributions::(),
- remainder_contributions: default_remainder_contributions::(),
- }
- })
- .collect::>>();
-
- async_features::create_multiple_projects_at(inst, instantiation_details).1
-}
-
// IMPORTANT: make sure your project starts at (block 1 + `total_vecs_in_storage` - `fully_filled_vecs_from_insertion`) to always have room to insert new vecs
pub fn fill_projects_to_update(
fully_filled_vecs_from_insertion: u32,
@@ -363,6 +315,7 @@ pub fn run_blocks_to_execute_next_transition(
)]
mod benchmarks {
use super::*;
+ use crate::traits::SetPrices;
use itertools::Itertools;
use polimec_common_test_utils::{generate_did_from_account, get_mock_jwt_with_cid};
@@ -375,6 +328,7 @@ mod benchmarks {
fn create_project() {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -425,6 +379,7 @@ mod benchmarks {
fn remove_project() {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -456,6 +411,7 @@ mod benchmarks {
fn edit_project() {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -559,6 +515,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -611,6 +568,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// We need to leave enough block numbers to fill `ProjectsToUpdate` before our project insertion
let time_advance: u32 = x + 2;
@@ -671,6 +629,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -782,6 +741,7 @@ mod benchmarks {
{
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1110,6 +1070,7 @@ mod benchmarks {
{
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// We need to leave enough block numbers to fill `ProjectsToUpdate` before our project insertion
let mut time_advance: u32 = 1;
@@ -1403,6 +1364,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// We need to leave enough block numbers to fill `ProjectsToUpdate` before our project insertion
@@ -1474,6 +1436,7 @@ mod benchmarks {
fn settle_successful_evaluation() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1537,6 +1500,7 @@ mod benchmarks {
fn settle_failed_evaluation() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1619,6 +1583,7 @@ mod benchmarks {
fn settle_successful_bid() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1665,6 +1630,7 @@ mod benchmarks {
fn settle_failed_bid() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1724,6 +1690,7 @@ mod benchmarks {
fn settle_successful_contribution() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1781,6 +1748,7 @@ mod benchmarks {
fn settle_failed_contribution() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1857,6 +1825,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1901,6 +1870,7 @@ mod benchmarks {
fn end_evaluation_failure() {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -1962,6 +1932,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -2008,6 +1979,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -2139,6 +2111,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -2263,6 +2236,7 @@ mod benchmarks {
) {
// * setup *
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
// real benchmark starts at block 0, and we can't call `events()` at block 0
inst.advance_time(1u32.into()).unwrap();
@@ -2314,6 +2288,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2371,6 +2346,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2429,6 +2405,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2489,6 +2466,7 @@ mod benchmarks {
) {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2563,6 +2541,7 @@ mod benchmarks {
fn project_decision() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2612,6 +2591,7 @@ mod benchmarks {
fn start_settlement_funding_success() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
@@ -2642,6 +2622,7 @@ mod benchmarks {
fn start_settlement_funding_failure() {
// setup
let mut inst = BenchInstantiator::::new(None);
+ ::SetPrices::set_prices();
let issuer = account::>("issuer", 0, 0);
diff --git a/pallets/funding/src/instantiator/async_features.rs b/pallets/funding/src/instantiator/async_features.rs
deleted file mode 100644
index 7e1947479..000000000
--- a/pallets/funding/src/instantiator/async_features.rs
+++ /dev/null
@@ -1,907 +0,0 @@
-use super::*;
-use assert_matches2::assert_matches;
-use futures::FutureExt;
-use std::{
- collections::HashMap,
- sync::{
- atomic::{AtomicBool, AtomicU32, Ordering},
- Arc,
- },
- time::Duration,
-};
-use tokio::{
- sync::{Mutex, Notify},
- time::sleep,
-};
-
-pub struct BlockOrchestrator {
- pub current_block: Arc,
- // used for resuming execution of a project that is waiting for a certain block to be reached
- pub awaiting_projects: Mutex, Vec>>>,
- pub should_continue: Arc,
- pub instantiator_phantom: PhantomData<(T, AllPalletsWithoutSystem, RuntimeEvent)>,
-}
-pub async fn block_controller<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- block_orchestrator: Arc>,
- instantiator: Arc>>,
-) {
- loop {
- if !block_orchestrator.continue_running() {
- break;
- }
-
- let maybe_target_reached = block_orchestrator.advance_to_next_target(instantiator.clone()).await;
-
- if let Some(target_reached) = maybe_target_reached {
- block_orchestrator.execute_callbacks(target_reached).await;
- }
- // leaves some time for the projects to submit their targets to the orchestrator
- sleep(Duration::from_millis(100)).await;
- }
-}
-
-impl<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
- > Default for BlockOrchestrator
-{
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
- > BlockOrchestrator
-{
- pub fn new() -> Self {
- BlockOrchestrator:: {
- current_block: Arc::new(AtomicU32::new(0)),
- awaiting_projects: Mutex::new(HashMap::new()),
- should_continue: Arc::new(AtomicBool::new(true)),
- instantiator_phantom: PhantomData,
- }
- }
-
- pub async fn add_awaiting_project(&self, block_number: BlockNumberFor, notify: Arc) {
- let mut awaiting_projects = self.awaiting_projects.lock().await;
- awaiting_projects.entry(block_number).or_default().push(notify);
- drop(awaiting_projects);
- }
-
- pub async fn advance_to_next_target(
- &self,
- instantiator: Arc>>,
- ) -> Option> {
- let mut inst = instantiator.lock().await;
- let now: u32 = inst.current_block().try_into().unwrap_or_else(|_| panic!("Block number should fit into u32"));
- self.current_block.store(now, Ordering::SeqCst);
-
- let awaiting_projects = self.awaiting_projects.lock().await;
-
- if let Some(&next_block) = awaiting_projects.keys().min() {
- drop(awaiting_projects);
-
- while self.get_current_block() < next_block {
- inst.advance_time(One::one()).unwrap();
- let current_block: u32 =
- self.get_current_block().try_into().unwrap_or_else(|_| panic!("Block number should fit into u32"));
- self.current_block.store(current_block + 1u32, Ordering::SeqCst);
- }
- Some(next_block)
- } else {
- None
- }
- }
-
- pub async fn execute_callbacks(&self, block_number: BlockNumberFor) {
- let mut awaiting_projects = self.awaiting_projects.lock().await;
- if let Some(notifies) = awaiting_projects.remove(&block_number) {
- for notify in notifies {
- notify.notify_one();
- }
- }
- }
-
- pub async fn is_empty(&self) -> bool {
- self.awaiting_projects.lock().await.is_empty()
- }
-
- // Method to check if the loop should continue
- pub fn continue_running(&self) -> bool {
- self.should_continue.load(Ordering::SeqCst)
- }
-
- // Method to get the current block number
- pub fn get_current_block(&self) -> BlockNumberFor {
- self.current_block.load(Ordering::SeqCst).into()
- }
-}
-
-// async instantiations for parallel testing
-pub async fn async_create_new_project<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- instantiator: Arc>>,
- project_metadata: ProjectMetadataOf,
- issuer: AccountIdOf,
-) -> ProjectId {
- let mut inst = instantiator.lock().await;
-
- let now = inst.current_block();
- let ed = inst.get_ed();
- // One ED for the issuer, one for the escrow account
- inst.mint_plmc_to(vec![UserToPLMCBalance::new(issuer.clone(), ed * 2u64.into())]);
- inst.execute(|| {
- crate::Pallet::::do_create_project(
- &issuer.clone(),
- project_metadata.clone(),
- generate_did_from_account(issuer.clone()),
- )
- .unwrap();
- let last_project_metadata = ProjectsMetadata::::iter().last().unwrap();
- log::trace!("Last project metadata: {:?}", last_project_metadata);
- });
-
- let created_project_id = inst.execute(|| NextProjectId::::get().saturating_sub(One::one()));
- inst.creation_assertions(created_project_id, project_metadata, now);
- created_project_id
-}
-
-pub async fn async_create_evaluating_project<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- instantiator: Arc>>,
- project_metadata: ProjectMetadataOf,
- issuer: AccountIdOf,
-) -> ProjectId {
- let project_id = async_create_new_project(instantiator.clone(), project_metadata, issuer.clone()).await;
-
- let mut inst = instantiator.lock().await;
-
- inst.start_evaluation(project_id, issuer).unwrap();
- project_id
-}
-
-pub async fn async_start_auction<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- instantiator: Arc>>,
- block_orchestrator: Arc>,
- project_id: ProjectId,
- caller: AccountIdOf,
-) -> Result<(), DispatchError> {
- let mut inst = instantiator.lock().await;
-
- let project_details = inst.get_project_details(project_id);
-
- if project_details.status == ProjectStatus::EvaluationRound {
- let update_block = inst.get_update_block(project_id, &UpdateType::EvaluationEnd).unwrap();
- let notify = Arc::new(Notify::new());
- block_orchestrator.add_awaiting_project(update_block, notify.clone()).await;
-
- // Wait for the notification that our desired block was reached to continue
- drop(inst);
-
- notify.notified().await;
-
- inst = instantiator.lock().await;
- };
-
- assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionInitializePeriod);
-
- inst.execute(|| crate::Pallet::::do_start_auction_opening(caller.clone(), project_id).unwrap());
-
- assert_eq!(inst.get_project_details(project_id).status, ProjectStatus::AuctionOpening);
-
- Ok(())
-}
-
-pub async fn async_create_auctioning_project<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- instantiator: Arc>>,
- block_orchestrator: Arc>,
- project_metadata: ProjectMetadataOf,
- issuer: AccountIdOf,
- evaluations: Vec>,
- bids: Vec>,
-) -> ProjectId {
- let project_id =
- async_create_evaluating_project(instantiator.clone(), project_metadata.clone(), issuer.clone()).await;
-
- let mut inst = instantiator.lock().await;
-
- let evaluators = evaluations.accounts();
- let prev_supply = inst.get_plmc_total_supply();
- let prev_plmc_balances = inst.get_free_plmc_balances_for(evaluators.clone());
-
- let plmc_eval_deposits: Vec> = inst.calculate_evaluation_plmc_spent(evaluations.clone());
- let plmc_existential_deposits: Vec> = evaluators.existential_deposits();
-
- let expected_remaining_plmc: Vec> =
- inst.generic_map_operation(vec![prev_plmc_balances, plmc_existential_deposits.clone()], MergeOperation::Add);
-
- inst.mint_plmc_to(plmc_eval_deposits.clone());
- inst.mint_plmc_to(plmc_existential_deposits.clone());
-
- inst.evaluate_for_users(project_id, evaluations).unwrap();
-
- let expected_evaluator_balances =
- inst.sum_balance_mappings(vec![plmc_eval_deposits.clone(), plmc_existential_deposits.clone()]);
-
- let expected_total_supply = prev_supply + expected_evaluator_balances;
-
- inst.evaluation_assertions(project_id, expected_remaining_plmc, plmc_eval_deposits, expected_total_supply);
-
- drop(inst);
-
- async_start_auction(instantiator.clone(), block_orchestrator, project_id, issuer).await.unwrap();
-
- inst = instantiator.lock().await;
- let plmc_for_bids =
- inst.calculate_auction_plmc_charged_from_all_bids_made_or_with_bucket(&bids, project_metadata.clone(), None);
- let plmc_existential_deposits: Vec> = bids.accounts().existential_deposits();
- let usdt_for_bids =
- inst.calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket(&bids, project_metadata, None);
-
- inst.mint_plmc_to(plmc_for_bids.clone());
- inst.mint_plmc_to(plmc_existential_deposits.clone());
- inst.mint_foreign_asset_to(usdt_for_bids.clone());
-
- inst.bid_for_users(project_id, bids).unwrap();
- drop(inst);
-
- project_id
-}
-
-pub async fn async_start_community_funding<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>,
->(
- instantiator: Arc>>,
- block_orchestrator: Arc>,
- project_id: ProjectId,
-) -> Result<(), DispatchError> {
- let mut inst = instantiator.lock().await;
- if let Some(update_block) = inst.get_update_block(project_id, &UpdateType::AuctionClosingStart) {
- let notify = Arc::new(Notify::new());
- block_orchestrator.add_awaiting_project(update_block, notify.clone()).await;
- drop(inst);
- notify.notified().await;
- }
- let mut inst = instantiator.lock().await;
- if let Some(update_block) = inst.get_update_block(project_id, &UpdateType::AuctionClosingEnd) {
- let notify = Arc::new(Notify::new());
- block_orchestrator.add_awaiting_project(update_block, notify.clone()).await;
- drop(inst);
- notify.notified().await;
- }
- let mut inst = instantiator.lock().await;
- if let Some(update_block) = inst.get_update_block(project_id, &UpdateType::CommunityFundingStart) {
- let notify = Arc::new(Notify::new());
- block_orchestrator.add_awaiting_project(update_block, notify.clone()).await;
- drop(inst);
- notify.notified().await;
- }
- let mut inst = instantiator.lock().await;
-
- ensure!(
- inst.get_project_details(project_id).status == ProjectStatus::CommunityRound,
- DispatchError::from("Auction failed")
- );
-
- Ok(())
-}
-
-pub async fn async_create_community_contributing_project<
- T: Config + pallet_balances::Config>,
- AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>,
- RuntimeEvent: From