From 056a8c5a363383cb340e1fbac1f07e97dc6ce232 Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 22 Jan 2024 16:23:36 +0100 Subject: [PATCH 01/36] start modifying --- pallets/services-payment/Cargo.toml | 1 + pallets/services-payment/src/lib.rs | 118 +++++++++++----------------- 2 files changed, 47 insertions(+), 72 deletions(-) diff --git a/pallets/services-payment/Cargo.toml b/pallets/services-payment/Cargo.toml index 0fd31ff08..d90a5175b 100644 --- a/pallets/services-payment/Cargo.toml +++ b/pallets/services-payment/Cargo.toml @@ -17,6 +17,7 @@ log = { workspace = true } parity-scale-codec = { workspace = true, features = [ "derive", "max-encoded-len" ] } scale-info = { workspace = true } serde = { workspace = true, optional = true, features = [ "derive" ] } +sp-io = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } tp-traits = { workspace = true } diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 03e3349ab..73f31d59e 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -45,6 +45,8 @@ use { }, frame_system::pallet_prelude::*, scale_info::prelude::vec::Vec, + sp_io::hashing::blake2_256, + sp_runtime::traits::TrailingZeroInput, tp_traits::{AuthorNotingHook, BlockNumber}, }; @@ -68,11 +70,14 @@ pub mod pallet { /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Handler for fees - type OnChargeForBlockCredit: OnChargeForBlockCredit; + type OnChargeForBlock: OnChargeForBlock>; /// Currency type for fee payment type Currency: Currency; /// Provider of a block cost which can adjust from block to block type ProvideBlockProductionCost: ProvideBlockProductionCost; + /// Provider of a session cost which can adjust from session to session + type SessionAssignmentCost: SessionAssignmentCost; + /// The maximum number of credits that can be accumulated type MaxCreditsStored: Get>; @@ -95,9 +100,7 @@ pub mod pallet { CreditsPurchased { para_id: ParaId, payer: T::AccountId, - fee: BalanceOf, - credits_purchased: BlockNumberFor, - credits_remaining: BlockNumberFor, + credit: BalanceOf, }, CreditBurned { para_id: ParaId, @@ -129,44 +132,21 @@ pub mod pallet { pub fn purchase_credits( origin: OriginFor, para_id: ParaId, - credits: BlockNumberFor, - max_price_per_credit: Option>, + credit: BalanceOf, ) -> DispatchResultWithPostInfo { let account = ensure_signed(origin)?; - - let existing_credits = - BlockProductionCredits::::get(para_id).unwrap_or(BlockNumberFor::::zero()); - let credits_purchasable = T::MaxCreditsStored::get().saturating_sub(existing_credits); - let actual_credits_purchased = credits.min(credits_purchasable); - - let updated_credits = existing_credits.saturating_add(actual_credits_purchased); - - // get the current per-credit cost of a block - let (block_cost, _weight) = T::ProvideBlockProductionCost::block_cost(¶_id); - if let Some(max_price_per_credit) = max_price_per_credit { - ensure!( - block_cost <= max_price_per_credit, - Error::::CreditPriceTooExpensive, - ); - } - - let total_fee = block_cost.saturating_mul(actual_credits_purchased.into()); - - T::OnChargeForBlockCredit::charge_credits( + let parachain_tank = Self::parachain_tank(para_id); + T::Currency::transfer( &account, - ¶_id, - actual_credits_purchased, - total_fee, + ¶chain_tank, + credit, + ExistenceRequirement::KeepAlive, )?; - BlockProductionCredits::::insert(para_id, updated_credits); - Self::deposit_event(Event::::CreditsPurchased { para_id, payer: account, - fee: total_fee, - credits_purchased: actual_credits_purchased, - credits_remaining: updated_credits, + credit: credit, }); Ok(().into()) @@ -290,41 +270,16 @@ pub mod pallet { pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type CurrencyOf = + ::Currency; +/// Type alias to conveniently refer to the `Currency::NegativeImbalance` associated type. +pub type NegativeImbalanceOf = + as Currency<::AccountId>>::NegativeImbalance; /// Handler for fee charging. This will be invoked when fees need to be deducted from the fee /// account for a given paraId. -pub trait OnChargeForBlockCredit { - fn charge_credits( - payer: &T::AccountId, - para_id: &ParaId, - credits: BlockNumberFor, - fee: BalanceOf, - ) -> Result<(), Error>; -} - -pub struct ChargeForBlockCredit(PhantomData); -impl OnChargeForBlockCredit for ChargeForBlockCredit { - fn charge_credits( - payer: &T::AccountId, - _para_id: &ParaId, - _credits: BlockNumberFor, - fee: BalanceOf, - ) -> Result<(), crate::Error> { - use frame_support::traits::tokens::imbalance::Imbalance; - - let result = T::Currency::withdraw( - payer, - fee, - WithdrawReasons::FEE, - ExistenceRequirement::AllowDeath, - ); - let imbalance = result.map_err(|_| crate::Error::InsufficientFundsToPurchaseCredits)?; - - if imbalance.peek() != fee { - panic!("withdrawn balance incorrect"); - } - - Ok(()) - } +use frame_support::traits::{tokens::imbalance::Imbalance, TryDrop}; +pub trait OnChargeForBlock { + fn on_charge_for_block(imbalance: Imbalance) -> Result<(), Error>; } /// Returns the cost for a given block credit at the current time. This can be a complex operation, @@ -332,6 +287,9 @@ impl OnChargeForBlockCredit for ChargeForBlockCredit { pub trait ProvideBlockProductionCost { fn block_cost(para_id: &ParaId) -> (BalanceOf, Weight); } +pub trait SessionAssignmentCost { + fn session_assingment_cost(para_id: &ParaId) -> (BalanceOf, Weight); +} impl AuthorNotingHook for Pallet { // This hook is called when pallet_author_noting sees that the block number of a container chain has increased. @@ -345,13 +303,29 @@ impl AuthorNotingHook for Pallet { let total_weight = T::DbWeight::get().reads_writes(1, 1); if let Err(e) = Pallet::::burn_credit_for_para(¶_id) { - log::warn!( - "Failed to burn credits for container chain {}: {:?}", - u32::from(para_id), - e - ); + let (amount_to_charge, weight) = T::ProvideBlockProductionCost::block_cost(¶_id); + let imbalance = T::Currency::withdraw( + &Self::parachain_tank(para_id), + amount_to_charge, + WithdrawReasons::FEE, + ExistenceRequirement::AllowDeath, + ) + .unwrap(); + + T::OnChargeForBlock::on_charge_for_block(imbalance).unwrap(); } + + total_weight } } + +impl Pallet { + /// Derive a derivative account ID from the paraId. + pub fn parachain_tank(para_id: ParaId) -> T::AccountId { + let entropy = (b"modlpy/serpayment", para_id).using_encoded(blake2_256); + Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .expect("infinite length input; no invalid inputs for type; qed") + } +} From a38d9d6b4431b76f7ed5ad091f0ea947304b6f26 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 10:47:30 +0100 Subject: [PATCH 02/36] adapt tests --- pallets/services-payment/src/lib.rs | 27 +-- pallets/services-payment/src/mock.rs | 12 +- pallets/services-payment/src/tests.rs | 262 +++++++++----------------- 3 files changed, 109 insertions(+), 192 deletions(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 73f31d59e..6afd01eda 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -75,8 +75,6 @@ pub mod pallet { type Currency: Currency; /// Provider of a block cost which can adjust from block to block type ProvideBlockProductionCost: ProvideBlockProductionCost; - /// Provider of a session cost which can adjust from session to session - type SessionAssignmentCost: SessionAssignmentCost; /// The maximum number of credits that can be accumulated type MaxCreditsStored: Get>; @@ -270,8 +268,7 @@ pub mod pallet { pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -pub type CurrencyOf = - ::Currency; +pub type CurrencyOf = ::Currency; /// Type alias to conveniently refer to the `Currency::NegativeImbalance` associated type. pub type NegativeImbalanceOf = as Currency<::AccountId>>::NegativeImbalance; @@ -279,7 +276,7 @@ pub type NegativeImbalanceOf = /// account for a given paraId. use frame_support::traits::{tokens::imbalance::Imbalance, TryDrop}; pub trait OnChargeForBlock { - fn on_charge_for_block(imbalance: Imbalance) -> Result<(), Error>; + fn on_charge_for_block(imbalance: Imbalance); } /// Returns the cost for a given block credit at the current time. This can be a complex operation, @@ -302,21 +299,25 @@ impl AuthorNotingHook for Pallet { ) -> Weight { let total_weight = T::DbWeight::get().reads_writes(1, 1); - if let Err(e) = Pallet::::burn_credit_for_para(¶_id) { + if Pallet::::burn_credit_for_para(¶_id).is_err() { let (amount_to_charge, weight) = T::ProvideBlockProductionCost::block_cost(¶_id); - let imbalance = T::Currency::withdraw( + match T::Currency::withdraw( &Self::parachain_tank(para_id), amount_to_charge, WithdrawReasons::FEE, ExistenceRequirement::AllowDeath, - ) - .unwrap(); - - T::OnChargeForBlock::on_charge_for_block(imbalance).unwrap(); + ) { + Err(e) => log::warn!( + "Failed to withdraw credits for container chain {}: {:?}", + u32::from(para_id), + e + ), + Ok(imbalance) => { + T::OnChargeForBlock::on_charge_for_block(imbalance); + } + } } - - total_weight } } diff --git a/pallets/services-payment/src/mock.rs b/pallets/services-payment/src/mock.rs index 329726eba..34604e261 100644 --- a/pallets/services-payment/src/mock.rs +++ b/pallets/services-payment/src/mock.rs @@ -29,13 +29,14 @@ //! to that containerChain, by simply assigning the slot position. use { - crate::{self as pallet_services_payment, ChargeForBlockCredit, ProvideBlockProductionCost}, + crate::{self as pallet_services_payment, OnChargeForBlock, ProvideBlockProductionCost}, cumulus_primitives_core::ParaId, frame_support::{ pallet_prelude::*, parameter_types, traits::{ConstU32, ConstU64, Everything}, }, + pallet_balances::NegativeImbalance, sp_core::H256, sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -107,9 +108,16 @@ parameter_types! { pub const MaxCreditsStored: u64 = 5; } +pub struct BurnOnChargeForBlock; +impl OnChargeForBlock> for BurnOnChargeForBlock { + fn on_charge_for_block(imbalance: NegativeImbalance) { + drop(imbalance); + } +} + impl pallet_services_payment::Config for Test { type RuntimeEvent = RuntimeEvent; - type OnChargeForBlockCredit = ChargeForBlockCredit; + type OnChargeForBlock = BurnOnChargeForBlock; type Currency = Balances; type ProvideBlockProductionCost = BlockProductionCost; type MaxCreditsStored = MaxCreditsStored; diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index 4167e3bf8..401ed02c2 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -31,8 +31,9 @@ use { crate::{mock::*, pallet as pallet_services_payment, BlockProductionCredits}, cumulus_primitives_core::ParaId, - frame_support::{assert_err, assert_ok}, + frame_support::{assert_err, assert_ok, traits::fungible::Inspect}, sp_runtime::DispatchError, + tp_traits::AuthorNotingHook, }; const ALICE: u64 = 1; @@ -48,8 +49,7 @@ fn purchase_credits_works() { assert_ok!(PaymentServices::purchase_credits( RuntimeOrigin::signed(ALICE), 1.into(), - MaxCreditsStored::get(), - None, + 100u128, ),); assert_eq!( @@ -57,137 +57,29 @@ fn purchase_credits_works() { vec![pallet_services_payment::Event::CreditsPurchased { para_id: 1.into(), payer: ALICE, - fee: 500, - credits_purchased: MaxCreditsStored::get(), - credits_remaining: MaxCreditsStored::get(), + credit: 100u128 }] ); - }); -} - -#[test] -fn purchase_credits_purchases_zero_when_max_already_stored() { - ExtBuilder::default() - .with_balances([(ALICE, 1_000)].into()) - .build() - .execute_with(|| { - System::set_block_number(1); - - let para_id = 1.into(); - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - para_id, - MaxCreditsStored::get(), - None, - ),); - assert_eq!( - >::get(para_id), - Some(MaxCreditsStored::get()) - ); - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - para_id, - 1, - None - ),); - assert_eq!( - >::get(para_id), - Some(MaxCreditsStored::get()) - ); - - // should have two purchase events (one with MaxCreditsStored, then one with zero) - assert_eq!( - events(), - vec![ - pallet_services_payment::Event::CreditsPurchased { - para_id, - payer: ALICE, - fee: 500, - credits_purchased: MaxCreditsStored::get(), - credits_remaining: MaxCreditsStored::get(), - }, - pallet_services_payment::Event::CreditsPurchased { - para_id, - payer: ALICE, - fee: 0, - credits_purchased: 0, - credits_remaining: MaxCreditsStored::get(), - }, - ] + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 100u128 ); }); } - #[test] -fn purchase_credits_purchases_max_possible_when_cant_purchase_all_requested() { +fn purchase_credits_fails_with_insufficient_balance() { ExtBuilder::default() .with_balances([(ALICE, 1_000)].into()) .build() .execute_with(|| { - System::set_block_number(1); - - let para_id = 1.into(); - let amount_purchased = 1u64; - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - para_id, - amount_purchased, - None, - )); - - let purchasable = MaxCreditsStored::get() - amount_purchased; - assert_eq!(purchasable, 4); - - assert_eq!( - >::get(para_id), - Some(amount_purchased) - ); - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - para_id, - MaxCreditsStored::get(), - None, - ),); - assert_eq!( - >::get(para_id), - Some(MaxCreditsStored::get()) - ); - - // should have two purchase events (one with amount_purchased, then with purchasable) - assert_eq!( - events(), - vec![ - pallet_services_payment::Event::CreditsPurchased { - para_id, - payer: ALICE, - fee: 100, - credits_purchased: amount_purchased, - credits_remaining: amount_purchased, - }, - pallet_services_payment::Event::CreditsPurchased { - para_id, - payer: ALICE, - fee: 400, - credits_purchased: purchasable, - credits_remaining: MaxCreditsStored::get(), - }, - ] + // cannot purchase if death + assert_err!( + PaymentServices::purchase_credits(RuntimeOrigin::signed(ALICE), 1.into(), 1000u128), + sp_runtime::TokenError::NotExpendable, ); }); } -#[test] -fn purchase_credits_fails_with_insufficient_balance() { - ExtBuilder::default().build().execute_with(|| { - // really what we're testing is that purchase_credits fails when OnChargeForBlockCredits does - assert_err!( - PaymentServices::purchase_credits(RuntimeOrigin::signed(ALICE), 1.into(), 1, None), - pallet_services_payment::Error::::InsufficientFundsToPurchaseCredits, - ); - }); -} - #[test] fn burn_credit_fails_with_no_credits() { ExtBuilder::default().build().execute_with(|| { @@ -205,11 +97,10 @@ fn burn_credit_works() { .build() .execute_with(|| { let para_id = 1.into(); - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), + assert_ok!(PaymentServices::set_credits( + RuntimeOrigin::root(), para_id, 1u64, - None, ),); // should succeed and burn one @@ -232,11 +123,10 @@ fn burn_credit_fails_for_wrong_para() { .build() .execute_with(|| { let para_id = 1.into(); - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), + assert_ok!(PaymentServices::set_credits( + RuntimeOrigin::root(), para_id, 1u64, - None, ),); // fails for wrong para @@ -249,112 +139,130 @@ fn burn_credit_fails_for_wrong_para() { } #[test] -fn buy_credits_no_limit_works() { +fn set_credits_bad_origin() { ExtBuilder::default() .with_balances([(ALICE, 1_000)].into()) .build() .execute_with(|| { - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - 1.into(), - 1u64, - None, - )); + assert_err!( + PaymentServices::set_credits(RuntimeOrigin::signed(ALICE), 1.into(), 1u64,), + DispatchError::BadOrigin + ) }); } #[test] -fn buy_credits_too_expensive_fails() { +fn set_credits_above_max_works() { ExtBuilder::default() .with_balances([(ALICE, 1_000)].into()) .build() .execute_with(|| { - assert_err!( - PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), - 1.into(), - 1u64, - Some(FIXED_BLOCK_PRODUCTION_COST - 1), - ), - pallet_services_payment::Error::::CreditPriceTooExpensive, + assert_ok!(PaymentServices::set_credits( + RuntimeOrigin::root(), + 1.into(), + MaxCreditsStored::get() * 2, + )); + + assert_eq!( + >::get(ParaId::from(1)), + Some(MaxCreditsStored::get() * 2) ); }); } #[test] -fn buy_credits_exact_price_limit_works() { +fn set_credits_to_zero_kills_storage() { ExtBuilder::default() .with_balances([(ALICE, 1_000)].into()) .build() .execute_with(|| { - assert_ok!(PaymentServices::purchase_credits( - RuntimeOrigin::signed(ALICE), + assert_ok!(PaymentServices::set_credits( + RuntimeOrigin::root(), 1.into(), - 1u64, - Some(FIXED_BLOCK_PRODUCTION_COST), - ),); + 0u64, + )); + + assert_eq!(>::get(ParaId::from(1)), None,); }); } #[test] -fn buy_credits_limit_exceeds_price_works() { +fn credits_should_be_substracted_from_tank_if_no_free_credits() { ExtBuilder::default() - .with_balances([(ALICE, 1_000)].into()) + .with_balances([(ALICE, 2_000)].into()) .build() .execute_with(|| { + // this should give 10 block credit assert_ok!(PaymentServices::purchase_credits( RuntimeOrigin::signed(ALICE), 1.into(), - 1u64, - Some(FIXED_BLOCK_PRODUCTION_COST + 1), - ),); - }); -} + 1000u128, + )); -#[test] -fn set_credits_bad_origin() { - ExtBuilder::default() - .with_balances([(ALICE, 1_000)].into()) - .build() - .execute_with(|| { - assert_err!( - PaymentServices::set_credits(RuntimeOrigin::signed(ALICE), 1.into(), 1u64,), - DispatchError::BadOrigin - ) + assert_eq!( + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 1000u128 + ); + + PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + + assert_eq!( + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 900u128 + ); }); } #[test] -fn set_credits_above_max_works() { +fn credits_should_be_substracted_from_tank_even_if_it_involves_death() { ExtBuilder::default() - .with_balances([(ALICE, 1_000)].into()) + .with_balances([(ALICE, 2_000)].into()) .build() .execute_with(|| { - assert_ok!(PaymentServices::set_credits( - RuntimeOrigin::root(), + // this should give 10 block credit + assert_ok!(PaymentServices::purchase_credits( + RuntimeOrigin::signed(ALICE), 1.into(), - MaxCreditsStored::get() * 2, + 100u128, )); assert_eq!( - >::get(ParaId::from(1)), - Some(MaxCreditsStored::get() * 2) + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 100u128 + ); + + PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + + assert_eq!( + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 0u128 ); }); } #[test] -fn set_credits_to_zero_kills_storage() { +fn not_having_enough_tokens_in_tank_should_not_error() { ExtBuilder::default() - .with_balances([(ALICE, 1_000)].into()) + .with_balances([(ALICE, 2_000)].into()) .build() .execute_with(|| { - assert_ok!(PaymentServices::set_credits( - RuntimeOrigin::root(), + // this should give 10 block credit + assert_ok!(PaymentServices::purchase_credits( + RuntimeOrigin::signed(ALICE), 1.into(), - 0u64, + 1u128, )); - assert_eq!(>::get(ParaId::from(1)), None,); + assert_eq!( + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 1u128 + ); + + PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + + assert_eq!( + Balances::balance(&crate::Pallet::::parachain_tank(1.into())), + 1u128 + ); }); } From cfe6a34bdad22b42c39e42a681e5b073c6a48c24 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 11:26:50 +0100 Subject: [PATCH 03/36] change traits to use onunbalanced --- pallets/services-payment/src/lib.rs | 11 ++++------- pallets/services-payment/src/mock.rs | 13 +++---------- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 6afd01eda..ecf3a95a0 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -41,7 +41,7 @@ use { frame_support::{ pallet_prelude::*, sp_runtime::{traits::Zero, Saturating}, - traits::{tokens::ExistenceRequirement, Currency, WithdrawReasons}, + traits::{tokens::ExistenceRequirement, Currency, OnUnbalanced, WithdrawReasons}, }, frame_system::pallet_prelude::*, scale_info::prelude::vec::Vec, @@ -70,7 +70,7 @@ pub mod pallet { /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Handler for fees - type OnChargeForBlock: OnChargeForBlock>; + type OnChargeForBlock: OnUnbalanced>; /// Currency type for fee payment type Currency: Currency; /// Provider of a block cost which can adjust from block to block @@ -274,10 +274,6 @@ pub type NegativeImbalanceOf = as Currency<::AccountId>>::NegativeImbalance; /// Handler for fee charging. This will be invoked when fees need to be deducted from the fee /// account for a given paraId. -use frame_support::traits::{tokens::imbalance::Imbalance, TryDrop}; -pub trait OnChargeForBlock { - fn on_charge_for_block(imbalance: Imbalance); -} /// Returns the cost for a given block credit at the current time. This can be a complex operation, /// so it also returns the weight it consumes. (TODO: or just rely on benchmarking) @@ -313,9 +309,10 @@ impl AuthorNotingHook for Pallet { e ), Ok(imbalance) => { - T::OnChargeForBlock::on_charge_for_block(imbalance); + T::OnChargeForBlock::on_unbalanced(imbalance); } } + total_weight.saturating_add(weight); } total_weight diff --git a/pallets/services-payment/src/mock.rs b/pallets/services-payment/src/mock.rs index 34604e261..0700d4f4f 100644 --- a/pallets/services-payment/src/mock.rs +++ b/pallets/services-payment/src/mock.rs @@ -29,12 +29,12 @@ //! to that containerChain, by simply assigning the slot position. use { - crate::{self as pallet_services_payment, OnChargeForBlock, ProvideBlockProductionCost}, + crate::{self as pallet_services_payment, ProvideBlockProductionCost}, cumulus_primitives_core::ParaId, frame_support::{ pallet_prelude::*, parameter_types, - traits::{ConstU32, ConstU64, Everything}, + traits::{ConstU32, ConstU64, Everything, OnUnbalanced}, }, pallet_balances::NegativeImbalance, sp_core::H256, @@ -108,16 +108,9 @@ parameter_types! { pub const MaxCreditsStored: u64 = 5; } -pub struct BurnOnChargeForBlock; -impl OnChargeForBlock> for BurnOnChargeForBlock { - fn on_charge_for_block(imbalance: NegativeImbalance) { - drop(imbalance); - } -} - impl pallet_services_payment::Config for Test { type RuntimeEvent = RuntimeEvent; - type OnChargeForBlock = BurnOnChargeForBlock; + type OnChargeForBlock = (); type Currency = Balances; type ProvideBlockProductionCost = BlockProductionCost; type MaxCreditsStored = MaxCreditsStored; From 9c4ee4b9b28bf2aa33693eb1244bef90861a82ce Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 15:02:37 +0100 Subject: [PATCH 04/36] integration tests --- runtime/dancebox/src/lib.rs | 13 ++-- runtime/dancebox/tests/integration_test.rs | 72 +++++++++++----------- 2 files changed, 45 insertions(+), 40 deletions(-) diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index 7b4422c4b..03073d18d 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -73,7 +73,7 @@ use { pallet_pooled_staking::traits::{IsCandidateEligible, Timer}, pallet_registrar::RegistrarHooks, pallet_registrar_runtime_api::ContainerChainGenesisData, - pallet_services_payment::{ChargeForBlockCredit, ProvideBlockProductionCost}, + pallet_services_payment::ProvideBlockProductionCost, pallet_session::{SessionManager, ShouldEndSession}, pallet_transaction_payment::{ConstFeeMultiplier, CurrencyAdapter, Multiplier}, polkadot_runtime_common::BlockHashCount, @@ -240,7 +240,6 @@ pub const DAYS: BlockNumber = HOURS * 24; pub const UNIT: Balance = 1_000_000_000_000; pub const MILLIUNIT: Balance = 1_000_000_000; pub const MICROUNIT: Balance = 1_000_000; - /// The existential deposit. Set to 1/10 of the Connected Relay Chain. pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT; @@ -719,10 +718,14 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { let credits_for_2_sessions = 2 * blocks_per_session; para_ids.retain(|para_id| { // Check if the container chain has enough credits for producing blocks for 2 sessions - let credits = pallet_services_payment::BlockProductionCredits::::get(para_id) + let free_credits = pallet_services_payment::BlockProductionCredits::::get(para_id) .unwrap_or_default(); - credits >= credits_for_2_sessions + let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); + let regular_credits = Balances::free_balance(pallet_services_payment::Pallet::::parachain_tank(para_id.clone())) + .saturating_div(block_production_costs); + + (free_credits as u128).saturating_add(regular_credits) >= credits_for_2_sessions.into() }); } @@ -781,7 +784,7 @@ parameter_types! { impl pallet_services_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; /// Handler for fees - type OnChargeForBlockCredit = ChargeForBlockCredit; + type OnChargeForBlock = (); /// Currency type for fee payment type Currency = Balances; /// Provider of a block cost which can adjust from block to block diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index c5843a778..4be3d46bb 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -558,8 +558,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - 100_000, - None, + BlockProductionCost::block_cost(&(1001.into())).0 * 1000 )); assert_ok!(Registrar::register( origin_of(ALICE.into()), @@ -578,8 +577,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1002.into(), - 100_000, - None, + BlockProductionCost::block_cost(&(1002.into())).0 * 1000 )); // Assignment should happen after 2 sessions @@ -653,8 +651,7 @@ fn test_authors_paras_inserted_a_posteriori_with_collators_already_assigned() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - 100_000, - None, + BlockProductionCost::block_cost(&(1001.into())).0 * 1000 )); // Assignment should happen after 2 sessions @@ -783,11 +780,10 @@ fn test_paras_registered_but_not_enough_credits() { assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); // Purchase 1 credit less that what is needed let credits_1001 = dancebox_runtime::Period::get() * 2 - 1; - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - credits_1001, - None, + credits_1001 )); // Assignment should happen after 2 sessions @@ -800,11 +796,10 @@ fn test_paras_registered_but_not_enough_credits() { assert_eq!(assignment.container_chains.get(&1001u32.into()), None); // Now purchase the missing block credit - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - 1, - None, + credits_1001 + 1 )); run_to_session(4u32); @@ -865,11 +860,10 @@ fn test_paras_registered_but_only_credits_for_1_session() { assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); // Purchase only enough credits for 1 session let credits_1001 = dancebox_runtime::Period::get() * 2; - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - credits_1001, - None, + credits_1001 )); // Assignment should happen after 2 sessions @@ -4638,23 +4632,26 @@ fn test_can_buy_credits_before_registering_para() { // Try to buy the maximum amount of credits let balance_before = System::account(AccountId::from(ALICE)).data.free; + assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - u32::MAX, - None, + BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128) )); let balance_after = System::account(AccountId::from(ALICE)).data.free; - // But only up to MaxCreditsStored have actually been purchased - let credits = pallet_services_payment::BlockProductionCredits::::get( - &ParaId::from(1001), - ) - .unwrap_or_default(); - assert_eq!(credits, dancebox_runtime::MaxCreditsStored::get()); + // Now parachain tank should have this amount + let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) + .data + .free; - let expected_cost = BlockProductionCost::::block_cost(&ParaId::from(1001)).0 - * u128::from(dancebox_runtime::MaxCreditsStored::get()); + assert_eq!( + balance_tank, + BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128) + ); + + let expected_cost = + BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128); assert_eq!(balance_before - balance_after, expected_cost); }); } @@ -4717,16 +4714,21 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - dancebox_runtime::MaxCreditsStored::get() - 1, - None, + BlockProductionCost::block_cost(&(1001.into())).0 + * (dancebox_runtime::MaxCreditsStored::get() - 1) as u128 )); let balance_after = System::account(AccountId::from(ALICE)).data.free; - let credits = pallet_services_payment::BlockProductionCredits::::get( - &ParaId::from(1001), - ) - .unwrap_or_default(); - assert_eq!(credits, dancebox_runtime::MaxCreditsStored::get() - 1); + // Now parachain tank should have this amount + let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) + .data + .free; + + assert_eq!( + balance_tank, + BlockProductionCost::block_cost(&(1001.into())).0 + * (dancebox_runtime::MaxCreditsStored::get() - 1) as u128 + ); let expected_cost = BlockProductionCost::::block_cost(&ParaId::from(1001)).0 * u128::from(dancebox_runtime::MaxCreditsStored::get() - 1); From 705e89b555dadba0af7227e95fc57411e807ec2b Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 16:18:14 +0100 Subject: [PATCH 05/36] fix tests --- pallets/services-payment/src/lib.rs | 3 - runtime/dancebox/tests/common/mod.rs | 10 ++- runtime/dancebox/tests/integration_test.rs | 33 +++++---- runtime/flashbox/src/lib.rs | 4 +- runtime/flashbox/tests/common/mod.rs | 10 ++- runtime/flashbox/tests/integration_test.rs | 84 +++++++++++----------- 6 files changed, 83 insertions(+), 61 deletions(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index ecf3a95a0..31ea16ebf 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -280,9 +280,6 @@ pub type NegativeImbalanceOf = pub trait ProvideBlockProductionCost { fn block_cost(para_id: &ParaId) -> (BalanceOf, Weight); } -pub trait SessionAssignmentCost { - fn session_assingment_cost(para_id: &ParaId) -> (BalanceOf, Weight); -} impl AuthorNotingHook for Pallet { // This hook is called when pallet_author_noting sees that the block number of a container chain has increased. diff --git a/runtime/dancebox/tests/common/mod.rs b/runtime/dancebox/tests/common/mod.rs index ce7379d9e..8364a2546 100644 --- a/runtime/dancebox/tests/common/mod.rs +++ b/runtime/dancebox/tests/common/mod.rs @@ -17,7 +17,9 @@ use { cumulus_primitives_core::{ParaId, PersistedValidationData}, cumulus_primitives_parachain_inherent::ParachainInherentData, - dancebox_runtime::{AuthorInherent, MaxBootNodeUrlLen, MaxBootNodes, MaxLengthTokenSymbol}, + dancebox_runtime::{ + AuthorInherent, BlockProductionCost, MaxBootNodeUrlLen, MaxBootNodes, MaxLengthTokenSymbol, + }, frame_support::{ assert_ok, traits::{OnFinalize, OnInitialize}, @@ -25,6 +27,7 @@ use { nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID}, pallet_collator_assignment_runtime_api::runtime_decl_for_collator_assignment_api::CollatorAssignmentApi, pallet_registrar_runtime_api::ContainerChainGenesisData, + pallet_services_payment::ProvideBlockProductionCost, parity_scale_codec::Encode, polkadot_parachain_primitives::primitives::HeadData, sp_consensus_aura::AURA_ENGINE_ID, @@ -514,6 +517,11 @@ pub fn current_author() -> AccountId { .clone() } +pub fn block_credits_to_required_balance(number_of_blocks: u32, para_id: ParaId) -> Balance { + let block_cost = BlockProductionCost::block_cost(¶_id).0; + (number_of_blocks as u128).saturating_mul(block_cost) +} + pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; pub const CHARLIE: [u8; 32] = [6u8; 32]; diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index 4be3d46bb..6efbf09e2 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -558,7 +558,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - BlockProductionCost::block_cost(&(1001.into())).0 * 1000 + block_credits_to_required_balance(1000, 1001.into()) )); assert_ok!(Registrar::register( origin_of(ALICE.into()), @@ -577,7 +577,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1002.into(), - BlockProductionCost::block_cost(&(1002.into())).0 * 1000 + block_credits_to_required_balance(1000, 1002.into()) )); // Assignment should happen after 2 sessions @@ -651,7 +651,7 @@ fn test_authors_paras_inserted_a_posteriori_with_collators_already_assigned() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - BlockProductionCost::block_cost(&(1001.into())).0 * 1000 + block_credits_to_required_balance(1000, 1001.into()) )); // Assignment should happen after 2 sessions @@ -4636,7 +4636,7 @@ fn test_can_buy_credits_before_registering_para() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128) + block_credits_to_required_balance(u32::MAX, 1001.into()) )); let balance_after = System::account(AccountId::from(ALICE)).data.free; @@ -4647,11 +4647,10 @@ fn test_can_buy_credits_before_registering_para() { assert_eq!( balance_tank, - BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128) + block_credits_to_required_balance(u32::MAX, 1001.into()) ); - let expected_cost = - BlockProductionCost::block_cost(&(1001.into())).0 * (u32::MAX as u128); + let expected_cost = block_credits_to_required_balance(u32::MAX, 1001.into()); assert_eq!(balance_before - balance_after, expected_cost); }); } @@ -4714,8 +4713,10 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - BlockProductionCost::block_cost(&(1001.into())).0 - * (dancebox_runtime::MaxCreditsStored::get() - 1) as u128 + block_credits_to_required_balance( + dancebox_runtime::MaxCreditsStored::get() - 1, + 1001.into() + ) )); let balance_after = System::account(AccountId::from(ALICE)).data.free; @@ -4726,12 +4727,16 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { assert_eq!( balance_tank, - BlockProductionCost::block_cost(&(1001.into())).0 - * (dancebox_runtime::MaxCreditsStored::get() - 1) as u128 + block_credits_to_required_balance( + dancebox_runtime::MaxCreditsStored::get() - 1, + 1001.into() + ) ); - let expected_cost = BlockProductionCost::::block_cost(&ParaId::from(1001)).0 - * u128::from(dancebox_runtime::MaxCreditsStored::get() - 1); + let expected_cost = block_credits_to_required_balance( + dancebox_runtime::MaxCreditsStored::get() - 1, + 1001.into(), + ); assert_eq!(balance_before - balance_after, expected_cost); // Now register para @@ -4750,7 +4755,7 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { 1001.into() )); - // We received 1 free credit, because we cannot have more than MaxCreditsStored + // We received aññ free credits, because we cannot have more than MaxCreditsStored let credits = pallet_services_payment::BlockProductionCredits::::get( &ParaId::from(1001), ) diff --git a/runtime/flashbox/src/lib.rs b/runtime/flashbox/src/lib.rs index e70b9cfca..c9f1be0ab 100644 --- a/runtime/flashbox/src/lib.rs +++ b/runtime/flashbox/src/lib.rs @@ -65,7 +65,7 @@ use { pallet_invulnerables::InvulnerableRewardDistribution, pallet_registrar::RegistrarHooks, pallet_registrar_runtime_api::ContainerChainGenesisData, - pallet_services_payment::{ChargeForBlockCredit, ProvideBlockProductionCost}, + pallet_services_payment::ProvideBlockProductionCost, pallet_session::{SessionManager, ShouldEndSession}, pallet_transaction_payment::{ConstFeeMultiplier, CurrencyAdapter, Multiplier}, polkadot_runtime_common::BlockHashCount, @@ -648,7 +648,7 @@ parameter_types! { impl pallet_services_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; /// Handler for fees - type OnChargeForBlockCredit = ChargeForBlockCredit; + type OnChargeForBlock = (); /// Currency type for fee payment type Currency = Balances; /// Provider of a block cost which can adjust from block to block diff --git a/runtime/flashbox/tests/common/mod.rs b/runtime/flashbox/tests/common/mod.rs index ff1db93ba..5f09066bc 100644 --- a/runtime/flashbox/tests/common/mod.rs +++ b/runtime/flashbox/tests/common/mod.rs @@ -17,7 +17,9 @@ use { cumulus_primitives_core::{ParaId, PersistedValidationData}, cumulus_primitives_parachain_inherent::ParachainInherentData, - flashbox_runtime::{AuthorInherent, MaxBootNodeUrlLen, MaxBootNodes, MaxLengthTokenSymbol}, + flashbox_runtime::{ + AuthorInherent, BlockProductionCost, MaxBootNodeUrlLen, MaxBootNodes, MaxLengthTokenSymbol, + }, frame_support::{ assert_ok, traits::{OnFinalize, OnInitialize}, @@ -25,6 +27,7 @@ use { nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID}, pallet_collator_assignment_runtime_api::runtime_decl_for_collator_assignment_api::CollatorAssignmentApi, pallet_registrar_runtime_api::ContainerChainGenesisData, + pallet_services_payment::ProvideBlockProductionCost, parity_scale_codec::Encode, polkadot_parachain_primitives::primitives::HeadData, sp_consensus_aura::AURA_ENGINE_ID, @@ -436,6 +439,11 @@ pub fn current_author() -> AccountId { .clone() } +pub fn block_credits_to_required_balance(number_of_blocks: u32, para_id: ParaId) -> Balance { + let block_cost = BlockProductionCost::block_cost(¶_id).0; + (number_of_blocks as u128).saturating_mul(block_cost) +} + pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; pub const CHARLIE: [u8; 32] = [6u8; 32]; diff --git a/runtime/flashbox/tests/integration_test.rs b/runtime/flashbox/tests/integration_test.rs index 8ff1c6e36..d1c099995 100644 --- a/runtime/flashbox/tests/integration_test.rs +++ b/runtime/flashbox/tests/integration_test.rs @@ -20,7 +20,6 @@ use { common::*, cumulus_primitives_core::ParaId, dp_core::well_known_keys, - flashbox_runtime::BlockProductionCost, frame_support::{assert_noop, assert_ok, BoundedVec}, nimbus_primitives::NIMBUS_KEY_ID, pallet_author_noting::ContainerChainBlockInfo, @@ -29,7 +28,6 @@ use { pallet_registrar_runtime_api::{ runtime_decl_for_registrar_api::RegistrarApi, ContainerChainGenesisData, }, - pallet_services_payment::ProvideBlockProductionCost, parity_scale_codec::Encode, sp_consensus_aura::AURA_ENGINE_ID, sp_core::Get, @@ -544,8 +542,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - 100_000, - None, + block_credits_to_required_balance(1000, 1001.into()) )); assert_ok!(Registrar::register( origin_of(ALICE.into()), @@ -564,8 +561,7 @@ fn test_authors_paras_inserted_a_posteriori() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1002.into(), - 100_000, - None, + block_credits_to_required_balance(1000, 1002.into()) )); // Assignment should happen after 2 sessions @@ -639,8 +635,7 @@ fn test_authors_paras_inserted_a_posteriori_with_collators_already_assigned() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - 100_000, - None, + block_credits_to_required_balance(1000, 1001.into()) )); // Assignment should happen after 2 sessions @@ -769,11 +764,10 @@ fn test_paras_registered_but_not_enough_credits() { assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); // Purchase 1 credit less that what is needed let credits_1001 = flashbox_runtime::Period::get() * 2 - 1; - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - credits_1001, - None, + credits_1001 )); // Assignment should happen after 2 sessions @@ -786,11 +780,10 @@ fn test_paras_registered_but_not_enough_credits() { assert_eq!(assignment.container_chains.get(&1001u32.into()), None); // Now purchase the missing block credit - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - 1, - None, + credits_1001 + 1 )); run_to_session(4u32); @@ -851,11 +844,10 @@ fn test_paras_registered_but_only_credits_for_1_session() { assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); // Purchase only enough credits for 1 session let credits_1001 = flashbox_runtime::Period::get() * 2; - assert_ok!(ServicesPayment::purchase_credits( - origin_of(ALICE.into()), + assert_ok!(ServicesPayment::set_credits( + root_origin(), 1001.into(), - credits_1001, - None, + credits_1001 )); // Assignment should happen after 2 sessions @@ -2506,20 +2498,21 @@ fn test_can_buy_credits_before_registering_para() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - u32::MAX, - None, + block_credits_to_required_balance(u32::MAX, 1001.into()) )); let balance_after = System::account(AccountId::from(ALICE)).data.free; - // But only up to MaxCreditsStored have actually been purchased - let credits = pallet_services_payment::BlockProductionCredits::::get( - &ParaId::from(1001), - ) - .unwrap_or_default(); - assert_eq!(credits, flashbox_runtime::MaxCreditsStored::get()); + // Now parachain tank should have this amount + let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) + .data + .free; - let expected_cost = BlockProductionCost::::block_cost(&ParaId::from(1001)).0 - * u128::from(flashbox_runtime::MaxCreditsStored::get()); + assert_eq!( + balance_tank, + block_credits_to_required_balance(u32::MAX, 1001.into()) + ); + + let expected_cost = block_credits_to_required_balance(u32::MAX, 1001.into()); assert_eq!(balance_before - balance_after, expected_cost); }); } @@ -2582,19 +2575,30 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - flashbox_runtime::MaxCreditsStored::get() - 1, - None, + block_credits_to_required_balance( + flashbox_runtime::MaxCreditsStored::get() - 1, + 1001.into() + ) )); let balance_after = System::account(AccountId::from(ALICE)).data.free; - let credits = pallet_services_payment::BlockProductionCredits::::get( - &ParaId::from(1001), - ) - .unwrap_or_default(); - assert_eq!(credits, flashbox_runtime::MaxCreditsStored::get() - 1); + // Now parachain tank should have this amount + let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) + .data + .free; - let expected_cost = BlockProductionCost::::block_cost(&ParaId::from(1001)).0 - * u128::from(flashbox_runtime::MaxCreditsStored::get() - 1); + assert_eq!( + balance_tank, + block_credits_to_required_balance( + flashbox_runtime::MaxCreditsStored::get() - 1, + 1001.into() + ) + ); + + let expected_cost = block_credits_to_required_balance( + flashbox_runtime::MaxCreditsStored::get() - 1, + 1001.into(), + ); assert_eq!(balance_before - balance_after, expected_cost); // Now register para @@ -2613,7 +2617,7 @@ fn test_can_buy_credits_before_registering_para_and_receive_free_credits() { 1001.into() )); - // We received 1 free credit, because we cannot have more than MaxCreditsStored + // We received aññ free credits, because we cannot have more than MaxCreditsStored let credits = pallet_services_payment::BlockProductionCredits::::get( &ParaId::from(1001), ) From 307f56f3cf309a4aaf87166db062dcd683151d16 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 17:27:50 +0100 Subject: [PATCH 06/36] modify benches --- pallets/services-payment/src/benchmarks.rs | 20 +++++++++----------- pallets/services-payment/src/mock.rs | 15 ++------------- 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/pallets/services-payment/src/benchmarks.rs b/pallets/services-payment/src/benchmarks.rs index 0b0cbf531..10d740a69 100644 --- a/pallets/services-payment/src/benchmarks.rs +++ b/pallets/services-payment/src/benchmarks.rs @@ -18,13 +18,14 @@ //! Benchmarking use { - crate::{BalanceOf, BlockNumberFor, Call, Config, Pallet}, + crate::{BalanceOf, BlockNumberFor, Call, Config, Pallet, ProvideBlockProductionCost}, frame_benchmarking::{account, v2::*}, frame_support::{ assert_ok, traits::{Currency, Get}, }, frame_system::RawOrigin, + sp_runtime::Saturating, sp_std::prelude::*, }; @@ -57,9 +58,9 @@ mod benchmarks { #[benchmark] fn purchase_credits() { - let caller = create_funded_user::("caller", 1, 1000); let para_id = 1001u32.into(); - let credits = T::MaxCreditsStored::get(); + let payment: BalanceOf = T::ProvideBlockProductionCost::block_cost(¶_id).0.saturating_mul(1000u32.into()); + let caller = create_funded_user::("caller", 1, 1_000_000_000u32); // Before call: 0 credits assert_eq!( @@ -71,28 +72,25 @@ mod benchmarks { Pallet::::purchase_credits( RawOrigin::Signed(caller), para_id, - credits, - Some(u32::MAX.into()), + payment, ); // verification code assert_eq!( - crate::BlockProductionCredits::::get(¶_id).unwrap_or_default(), - credits + ::total_balance(&crate::Pallet::::parachain_tank(para_id)), + payment ); } #[benchmark] fn set_credits() { - let caller = create_funded_user::("caller", 1, 1000); let para_id = 1001u32.into(); let credits = T::MaxCreditsStored::get(); - assert_ok!(Pallet::::purchase_credits( - RawOrigin::Signed(caller).into(), + assert_ok!(Pallet::::set_credits( + RawOrigin::Root.into(), para_id, credits, - Some(u32::MAX.into()), )); // Before call: 1000 credits diff --git a/pallets/services-payment/src/mock.rs b/pallets/services-payment/src/mock.rs index 0700d4f4f..2e0de9b9d 100644 --- a/pallets/services-payment/src/mock.rs +++ b/pallets/services-payment/src/mock.rs @@ -34,9 +34,8 @@ use { frame_support::{ pallet_prelude::*, parameter_types, - traits::{ConstU32, ConstU64, Everything, OnUnbalanced}, + traits::{ConstU32, ConstU64, Everything}, }, - pallet_balances::NegativeImbalance, sp_core::H256, sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -164,14 +163,4 @@ pub(crate) fn events() -> Vec> { } }) .collect::>() -} - -// This function basically just builds a genesis storage key/value store according to -// our desired mockup. -#[cfg(feature = "runtime-benchmarks")] -pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::::default() - .build_storage() - .unwrap() - .into() -} +} \ No newline at end of file From eb8fa4f5e809ca94af5cc66954d58927cfbffdef Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 17:32:39 +0100 Subject: [PATCH 07/36] fix clippy --- pallets/services-payment/src/benchmarks.rs | 10 ++++------ pallets/services-payment/src/mock.rs | 2 +- pallets/services-payment/src/tests.rs | 6 +++--- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/pallets/services-payment/src/benchmarks.rs b/pallets/services-payment/src/benchmarks.rs index 10d740a69..c304dfc2d 100644 --- a/pallets/services-payment/src/benchmarks.rs +++ b/pallets/services-payment/src/benchmarks.rs @@ -59,7 +59,9 @@ mod benchmarks { #[benchmark] fn purchase_credits() { let para_id = 1001u32.into(); - let payment: BalanceOf = T::ProvideBlockProductionCost::block_cost(¶_id).0.saturating_mul(1000u32.into()); + let payment: BalanceOf = T::ProvideBlockProductionCost::block_cost(¶_id) + .0 + .saturating_mul(1000u32.into()); let caller = create_funded_user::("caller", 1, 1_000_000_000u32); // Before call: 0 credits @@ -69,11 +71,7 @@ mod benchmarks { ); #[extrinsic_call] - Pallet::::purchase_credits( - RawOrigin::Signed(caller), - para_id, - payment, - ); + Pallet::::purchase_credits(RawOrigin::Signed(caller), para_id, payment); // verification code assert_eq!( diff --git a/pallets/services-payment/src/mock.rs b/pallets/services-payment/src/mock.rs index 2e0de9b9d..07a15aec8 100644 --- a/pallets/services-payment/src/mock.rs +++ b/pallets/services-payment/src/mock.rs @@ -163,4 +163,4 @@ pub(crate) fn events() -> Vec> { } }) .collect::>() -} \ No newline at end of file +} diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index 401ed02c2..8cded6483 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -204,7 +204,7 @@ fn credits_should_be_substracted_from_tank_if_no_free_credits() { 1000u128 ); - PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + PaymentServices::on_container_author_noted(&1, 1, 1.into()); assert_eq!( Balances::balance(&crate::Pallet::::parachain_tank(1.into())), @@ -231,7 +231,7 @@ fn credits_should_be_substracted_from_tank_even_if_it_involves_death() { 100u128 ); - PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + PaymentServices::on_container_author_noted(&1, 1, 1.into()); assert_eq!( Balances::balance(&crate::Pallet::::parachain_tank(1.into())), @@ -258,7 +258,7 @@ fn not_having_enough_tokens_in_tank_should_not_error() { 1u128 ); - PaymentServices::on_container_author_noted((&1).into(), 1, 1.into()); + PaymentServices::on_container_author_noted(&1, 1, 1.into()); assert_eq!( Balances::balance(&crate::Pallet::::parachain_tank(1.into())), From eab766f35a997337ef80ebf608c0b0453f19f73b Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 17:48:57 +0100 Subject: [PATCH 08/36] work clippy please --- runtime/dancebox/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index 03073d18d..75f12e895 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -722,7 +722,7 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { .unwrap_or_default(); let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); - let regular_credits = Balances::free_balance(pallet_services_payment::Pallet::::parachain_tank(para_id.clone())) + let regular_credits = Balances::free_balance(pallet_services_payment::Pallet::::parachain_tank(*para_id)) .saturating_div(block_production_costs); (free_credits as u128).saturating_add(regular_credits) >= credits_for_2_sessions.into() From b569d888aaaca8263edeef2baa90db9e3c71988e Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 18:03:30 +0100 Subject: [PATCH 09/36] typescript api --- .../dancebox/interfaces/augment-api-events.ts | 4 +- .../src/dancebox/interfaces/augment-api-tx.ts | 5 +- .../src/dancebox/interfaces/lookup.ts | 215 +++++++++--------- .../src/dancebox/interfaces/types-lookup.ts | 215 +++++++++--------- 4 files changed, 216 insertions(+), 223 deletions(-) diff --git a/typescript-api/src/dancebox/interfaces/augment-api-events.ts b/typescript-api/src/dancebox/interfaces/augment-api-events.ts index 50b0e88ed..078030ba2 100644 --- a/typescript-api/src/dancebox/interfaces/augment-api-events.ts +++ b/typescript-api/src/dancebox/interfaces/augment-api-events.ts @@ -937,8 +937,8 @@ declare module "@polkadot/api-base/types/events" { >; CreditsPurchased: AugmentedEvent< ApiType, - [paraId: u32, payer: AccountId32, fee: u128, creditsPurchased: u32, creditsRemaining: u32], - { paraId: u32; payer: AccountId32; fee: u128; creditsPurchased: u32; creditsRemaining: u32 } + [paraId: u32, payer: AccountId32, credit: u128], + { paraId: u32; payer: AccountId32; credit: u128 } >; CreditsSet: AugmentedEvent; /** Generic event */ diff --git a/typescript-api/src/dancebox/interfaces/augment-api-tx.ts b/typescript-api/src/dancebox/interfaces/augment-api-tx.ts index 51dbe7124..e84238e67 100644 --- a/typescript-api/src/dancebox/interfaces/augment-api-tx.ts +++ b/typescript-api/src/dancebox/interfaces/augment-api-tx.ts @@ -1541,10 +1541,9 @@ declare module "@polkadot/api-base/types/submittable" { purchaseCredits: AugmentedSubmittable< ( paraId: u32 | AnyNumber | Uint8Array, - credits: u32 | AnyNumber | Uint8Array, - maxPricePerCredit: Option | null | Uint8Array | u128 | AnyNumber + credit: u128 | AnyNumber | Uint8Array ) => SubmittableExtrinsic, - [u32, u32, Option] + [u32, u128] >; /** See [`Pallet::set_credits`]. */ setCredits: AugmentedSubmittable< diff --git a/typescript-api/src/dancebox/interfaces/lookup.ts b/typescript-api/src/dancebox/interfaces/lookup.ts index b1d5a60aa..e820cade0 100644 --- a/typescript-api/src/dancebox/interfaces/lookup.ts +++ b/typescript-api/src/dancebox/interfaces/lookup.ts @@ -475,9 +475,7 @@ export default { CreditsPurchased: { paraId: "u32", payer: "AccountId32", - fee: "u128", - creditsPurchased: "u32", - creditsRemaining: "u32", + credit: "u128", }, CreditBurned: { paraId: "u32", @@ -2290,8 +2288,7 @@ export default { _enum: { purchase_credits: { paraId: "u32", - credits: "u32", - maxPricePerCredit: "Option", + credit: "u128", }, set_credits: { paraId: "u32", @@ -2303,7 +2300,7 @@ export default { }, }, }, - /** Lookup263: pallet_data_preservers::pallet::Call */ + /** Lookup262: pallet_data_preservers::pallet::Call */ PalletDataPreserversCall: { _enum: { set_boot_nodes: { @@ -2312,7 +2309,7 @@ export default { }, }, }, - /** Lookup267: pallet_invulnerables::pallet::Call */ + /** Lookup266: pallet_invulnerables::pallet::Call */ PalletInvulnerablesCall: { _enum: { set_invulnerables: { @@ -2329,7 +2326,7 @@ export default { }, }, }, - /** Lookup268: pallet_session::pallet::Call */ + /** Lookup267: pallet_session::pallet::Call */ PalletSessionCall: { _enum: { set_keys: { @@ -2342,19 +2339,19 @@ export default { purge_keys: "Null", }, }, - /** Lookup269: dancebox_runtime::SessionKeys */ + /** Lookup268: dancebox_runtime::SessionKeys */ DanceboxRuntimeSessionKeys: { nimbus: "NimbusPrimitivesNimbusCryptoPublic", }, - /** Lookup270: nimbus_primitives::nimbus_crypto::Public */ + /** Lookup269: nimbus_primitives::nimbus_crypto::Public */ NimbusPrimitivesNimbusCryptoPublic: "SpCoreSr25519Public", - /** Lookup271: sp_core::sr25519::Public */ + /** Lookup270: sp_core::sr25519::Public */ SpCoreSr25519Public: "[u8;32]", - /** Lookup272: pallet_author_inherent::pallet::Call */ + /** Lookup271: pallet_author_inherent::pallet::Call */ PalletAuthorInherentCall: { _enum: ["kick_off_authorship_validation"], }, - /** Lookup273: pallet_pooled_staking::pallet::Call */ + /** Lookup272: pallet_pooled_staking::pallet::Call */ PalletPooledStakingCall: { _enum: { rebalance_hold: { @@ -2388,16 +2385,16 @@ export default { }, }, }, - /** Lookup274: pallet_pooled_staking::pallet::AllTargetPool */ + /** Lookup273: pallet_pooled_staking::pallet::AllTargetPool */ PalletPooledStakingAllTargetPool: { _enum: ["Joining", "AutoCompounding", "ManualRewards", "Leaving"], }, - /** Lookup276: pallet_pooled_staking::pallet::PendingOperationQuery */ + /** Lookup275: pallet_pooled_staking::pallet::PendingOperationQuery */ PalletPooledStakingPendingOperationQuery: { delegator: "AccountId32", operation: "PalletPooledStakingPendingOperationKey", }, - /** Lookup277: pallet_pooled_staking::pallet::PendingOperationKey */ + /** Lookup276: pallet_pooled_staking::pallet::PendingOperationKey */ PalletPooledStakingPendingOperationKey: { _enum: { JoiningAutoCompounding: { @@ -2414,14 +2411,14 @@ export default { }, }, }, - /** Lookup278: pallet_pooled_staking::pallet::SharesOrStake */ + /** Lookup277: pallet_pooled_staking::pallet::SharesOrStake */ PalletPooledStakingSharesOrStake: { _enum: { Shares: "u128", Stake: "u128", }, }, - /** Lookup281: cumulus_pallet_xcmp_queue::pallet::Call */ + /** Lookup280: cumulus_pallet_xcmp_queue::pallet::Call */ CumulusPalletXcmpQueueCall: { _enum: { service_overweight: { @@ -2468,7 +2465,7 @@ export default { }, }, }, - /** Lookup282: cumulus_pallet_dmp_queue::pallet::Call */ + /** Lookup281: cumulus_pallet_dmp_queue::pallet::Call */ CumulusPalletDmpQueueCall: { _enum: { service_overweight: { @@ -2477,7 +2474,7 @@ export default { }, }, }, - /** Lookup283: pallet_xcm::pallet::Call */ + /** Lookup282: pallet_xcm::pallet::Call */ PalletXcmCall: { _enum: { send: { @@ -2532,7 +2529,7 @@ export default { }, }, }, - /** Lookup284: xcm::VersionedXcm */ + /** Lookup283: xcm::VersionedXcm */ XcmVersionedXcm: { _enum: { __Unused0: "Null", @@ -2541,9 +2538,9 @@ export default { V3: "XcmV3Xcm", }, }, - /** Lookup285: xcm::v2::Xcm */ + /** Lookup284: xcm::v2::Xcm */ XcmV2Xcm: "Vec", - /** Lookup287: xcm::v2::Instruction */ + /** Lookup286: xcm::v2::Instruction */ XcmV2Instruction: { _enum: { WithdrawAsset: "XcmV2MultiassetMultiAssets", @@ -2639,7 +2636,7 @@ export default { UnsubscribeVersion: "Null", }, }, - /** Lookup288: xcm::v2::Response */ + /** Lookup287: xcm::v2::Response */ XcmV2Response: { _enum: { Null: "Null", @@ -2648,7 +2645,7 @@ export default { Version: "u32", }, }, - /** Lookup291: xcm::v2::traits::Error */ + /** Lookup290: xcm::v2::traits::Error */ XcmV2TraitsError: { _enum: { Overflow: "Null", @@ -2679,14 +2676,14 @@ export default { WeightNotComputable: "Null", }, }, - /** Lookup292: xcm::v2::multiasset::MultiAssetFilter */ + /** Lookup291: xcm::v2::multiasset::MultiAssetFilter */ XcmV2MultiassetMultiAssetFilter: { _enum: { Definite: "XcmV2MultiassetMultiAssets", Wild: "XcmV2MultiassetWildMultiAsset", }, }, - /** Lookup293: xcm::v2::multiasset::WildMultiAsset */ + /** Lookup292: xcm::v2::multiasset::WildMultiAsset */ XcmV2MultiassetWildMultiAsset: { _enum: { All: "Null", @@ -2696,18 +2693,18 @@ export default { }, }, }, - /** Lookup294: xcm::v2::multiasset::WildFungibility */ + /** Lookup293: xcm::v2::multiasset::WildFungibility */ XcmV2MultiassetWildFungibility: { _enum: ["Fungible", "NonFungible"], }, - /** Lookup295: xcm::v2::WeightLimit */ + /** Lookup294: xcm::v2::WeightLimit */ XcmV2WeightLimit: { _enum: { Unlimited: "Null", Limited: "Compact", }, }, - /** Lookup304: pallet_assets::pallet::Call */ + /** Lookup303: pallet_assets::pallet::Call */ PalletAssetsCall: { _enum: { create: { @@ -2857,7 +2854,7 @@ export default { }, }, }, - /** Lookup305: pallet_foreign_asset_creator::pallet::Call */ + /** Lookup304: pallet_foreign_asset_creator::pallet::Call */ PalletForeignAssetCreatorCall: { _enum: { create_foreign_asset: { @@ -2879,7 +2876,7 @@ export default { }, }, }, - /** Lookup306: pallet_asset_rate::pallet::Call */ + /** Lookup305: pallet_asset_rate::pallet::Call */ PalletAssetRateCall: { _enum: { create: { @@ -2895,7 +2892,7 @@ export default { }, }, }, - /** Lookup307: pallet_root_testing::pallet::Call */ + /** Lookup306: pallet_root_testing::pallet::Call */ PalletRootTestingCall: { _enum: { fill_block: { @@ -2903,27 +2900,27 @@ export default { }, }, }, - /** Lookup308: pallet_sudo::pallet::Error */ + /** Lookup307: pallet_sudo::pallet::Error */ PalletSudoError: { _enum: ["RequireSudo"], }, - /** Lookup309: pallet_utility::pallet::Error */ + /** Lookup308: pallet_utility::pallet::Error */ PalletUtilityError: { _enum: ["TooManyCalls"], }, - /** Lookup312: pallet_proxy::ProxyDefinition */ + /** Lookup311: pallet_proxy::ProxyDefinition */ PalletProxyProxyDefinition: { delegate: "AccountId32", proxyType: "DanceboxRuntimeProxyType", delay: "u32", }, - /** Lookup316: pallet_proxy::Announcement */ + /** Lookup315: pallet_proxy::Announcement */ PalletProxyAnnouncement: { real: "AccountId32", callHash: "H256", height: "u32", }, - /** Lookup318: pallet_proxy::pallet::Error */ + /** Lookup317: pallet_proxy::pallet::Error */ PalletProxyError: { _enum: [ "TooMany", @@ -2936,34 +2933,34 @@ export default { "NoSelfProxy", ], }, - /** Lookup319: pallet_migrations::pallet::Error */ + /** Lookup318: pallet_migrations::pallet::Error */ PalletMigrationsError: { _enum: ["PreimageMissing", "WrongUpperBound", "PreimageIsTooBig", "PreimageAlreadyExists"], }, - /** Lookup320: pallet_maintenance_mode::pallet::Error */ + /** Lookup319: pallet_maintenance_mode::pallet::Error */ PalletMaintenanceModeError: { _enum: ["AlreadyInMaintenanceMode", "NotInMaintenanceMode"], }, - /** Lookup321: pallet_tx_pause::pallet::Error */ + /** Lookup320: pallet_tx_pause::pallet::Error */ PalletTxPauseError: { _enum: ["IsPaused", "IsUnpaused", "Unpausable", "NotFound"], }, - /** Lookup323: pallet_balances::types::BalanceLock */ + /** Lookup322: pallet_balances::types::BalanceLock */ PalletBalancesBalanceLock: { id: "[u8;8]", amount: "u128", reasons: "PalletBalancesReasons", }, - /** Lookup324: pallet_balances::types::Reasons */ + /** Lookup323: pallet_balances::types::Reasons */ PalletBalancesReasons: { _enum: ["Fee", "Misc", "All"], }, - /** Lookup327: pallet_balances::types::ReserveData */ + /** Lookup326: pallet_balances::types::ReserveData */ PalletBalancesReserveData: { id: "[u8;8]", amount: "u128", }, - /** Lookup331: dancebox_runtime::RuntimeHoldReason */ + /** Lookup330: dancebox_runtime::RuntimeHoldReason */ DanceboxRuntimeRuntimeHoldReason: { _enum: { __Unused0: "Null", @@ -3003,16 +3000,16 @@ export default { PooledStaking: "PalletPooledStakingHoldReason", }, }, - /** Lookup332: pallet_pooled_staking::pallet::HoldReason */ + /** Lookup331: pallet_pooled_staking::pallet::HoldReason */ PalletPooledStakingHoldReason: { _enum: ["PooledStake"], }, - /** Lookup335: pallet_balances::types::IdAmount */ + /** Lookup334: pallet_balances::types::IdAmount */ PalletBalancesIdAmount: { id: "[u8;8]", amount: "u128", }, - /** Lookup337: pallet_balances::pallet::Error */ + /** Lookup336: pallet_balances::pallet::Error */ PalletBalancesError: { _enum: [ "VestingBalance", @@ -3027,18 +3024,18 @@ export default { "TooManyFreezes", ], }, - /** Lookup338: pallet_transaction_payment::Releases */ + /** Lookup337: pallet_transaction_payment::Releases */ PalletTransactionPaymentReleases: { _enum: ["V1Ancient", "V2"], }, - /** Lookup339: pallet_identity::types::Registration> */ + /** Lookup338: pallet_identity::types::Registration> */ PalletIdentityRegistration: { judgements: "Vec<(u32,PalletIdentityJudgement)>", deposit: "u128", info: "PalletIdentitySimpleIdentityInfo", }, /** - * Lookup347: pallet_identity::types::RegistrarInfo */ PalletIdentityRegistrarInfo: { @@ -3046,7 +3043,7 @@ export default { fee: "u128", fields: "PalletIdentityBitFlags", }, - /** Lookup349: pallet_identity::pallet::Error */ + /** Lookup348: pallet_identity::pallet::Error */ PalletIdentityError: { _enum: [ "TooManySubAccounts", @@ -3069,12 +3066,12 @@ export default { "JudgementPaymentFailed", ], }, - /** Lookup354: pallet_registrar::pallet::DepositInfo */ + /** Lookup353: pallet_registrar::pallet::DepositInfo */ PalletRegistrarDepositInfo: { creator: "AccountId32", deposit: "u128", }, - /** Lookup355: pallet_registrar::pallet::Error */ + /** Lookup354: pallet_registrar::pallet::Error */ PalletRegistrarError: { _enum: [ "ParaIdAlreadyRegistered", @@ -3088,7 +3085,7 @@ export default { "NotSufficientDeposit", ], }, - /** Lookup356: pallet_configuration::HostConfiguration */ + /** Lookup355: pallet_configuration::HostConfiguration */ PalletConfigurationHostConfiguration: { maxCollators: "u32", minOrchestratorCollators: "u32", @@ -3099,21 +3096,21 @@ export default { parathreadsPerCollator: "u32", targetContainerChainFullness: "Perbill", }, - /** Lookup359: pallet_configuration::pallet::Error */ + /** Lookup358: pallet_configuration::pallet::Error */ PalletConfigurationError: { _enum: ["InvalidNewValue"], }, - /** Lookup360: dp_collator_assignment::AssignedCollators */ + /** Lookup359: dp_collator_assignment::AssignedCollators */ DpCollatorAssignmentAssignedCollatorsAccountId32: { orchestratorChain: "Vec", containerChains: "BTreeMap>", }, - /** Lookup365: pallet_author_noting::pallet::ContainerChainBlockInfo */ + /** Lookup364: pallet_author_noting::pallet::ContainerChainBlockInfo */ PalletAuthorNotingContainerChainBlockInfo: { blockNumber: "u32", author: "AccountId32", }, - /** Lookup366: pallet_author_noting::pallet::Error */ + /** Lookup365: pallet_author_noting::pallet::Error */ PalletAuthorNotingError: { _enum: [ "FailedReading", @@ -3125,39 +3122,39 @@ export default { "NonAuraDigest", ], }, - /** Lookup367: dp_collator_assignment::AssignedCollators */ + /** Lookup366: dp_collator_assignment::AssignedCollators */ DpCollatorAssignmentAssignedCollatorsPublic: { orchestratorChain: "Vec", containerChains: "BTreeMap>", }, - /** Lookup372: pallet_services_payment::pallet::Error */ + /** Lookup371: pallet_services_payment::pallet::Error */ PalletServicesPaymentError: { _enum: ["InsufficientFundsToPurchaseCredits", "InsufficientCredits", "CreditPriceTooExpensive"], }, - /** Lookup373: pallet_data_preservers::pallet::Error */ + /** Lookup372: pallet_data_preservers::pallet::Error */ PalletDataPreserversError: { _enum: ["NoBootNodes"], }, - /** Lookup375: pallet_invulnerables::pallet::Error */ + /** Lookup374: pallet_invulnerables::pallet::Error */ PalletInvulnerablesError: { _enum: ["TooManyInvulnerables", "AlreadyInvulnerable", "NotInvulnerable"], }, - /** Lookup380: sp_core::crypto::KeyTypeId */ + /** Lookup379: sp_core::crypto::KeyTypeId */ SpCoreCryptoKeyTypeId: "[u8;4]", - /** Lookup381: pallet_session::pallet::Error */ + /** Lookup380: pallet_session::pallet::Error */ PalletSessionError: { _enum: ["InvalidProof", "NoAssociatedValidatorId", "DuplicatedKey", "NoKeys", "NoAccount"], }, - /** Lookup385: pallet_author_inherent::pallet::Error */ + /** Lookup384: pallet_author_inherent::pallet::Error */ PalletAuthorInherentError: { _enum: ["AuthorAlreadySet", "NoAccountId", "CannotBeAuthor"], }, - /** Lookup387: pallet_pooled_staking::candidate::EligibleCandidate */ + /** Lookup386: pallet_pooled_staking::candidate::EligibleCandidate */ PalletPooledStakingCandidateEligibleCandidate: { candidate: "AccountId32", stake: "u128", }, - /** Lookup390: pallet_pooled_staking::pallet::PoolsKey */ + /** Lookup389: pallet_pooled_staking::pallet::PoolsKey */ PalletPooledStakingPoolsKey: { _enum: { CandidateTotalStake: "Null", @@ -3199,7 +3196,7 @@ export default { }, }, }, - /** Lookup392: pallet_pooled_staking::pallet::Error */ + /** Lookup391: pallet_pooled_staking::pallet::Error */ PalletPooledStakingError: { _enum: { InvalidPalletSetting: "Null", @@ -3218,26 +3215,26 @@ export default { SwapResultsInZeroShares: "Null", }, }, - /** Lookup393: pallet_inflation_rewards::pallet::ChainsToRewardValue */ + /** Lookup392: pallet_inflation_rewards::pallet::ChainsToRewardValue */ PalletInflationRewardsChainsToRewardValue: { paraIds: "Vec", rewardsPerChain: "u128", }, - /** Lookup395: cumulus_pallet_xcmp_queue::InboundChannelDetails */ + /** Lookup394: cumulus_pallet_xcmp_queue::InboundChannelDetails */ CumulusPalletXcmpQueueInboundChannelDetails: { sender: "u32", state: "CumulusPalletXcmpQueueInboundState", messageMetadata: "Vec<(u32,PolkadotParachainPrimitivesPrimitivesXcmpMessageFormat)>", }, - /** Lookup396: cumulus_pallet_xcmp_queue::InboundState */ + /** Lookup395: cumulus_pallet_xcmp_queue::InboundState */ CumulusPalletXcmpQueueInboundState: { _enum: ["Ok", "Suspended"], }, - /** Lookup399: polkadot_parachain_primitives::primitives::XcmpMessageFormat */ + /** Lookup398: polkadot_parachain_primitives::primitives::XcmpMessageFormat */ PolkadotParachainPrimitivesPrimitivesXcmpMessageFormat: { _enum: ["ConcatenatedVersionedXcm", "ConcatenatedEncodedBlob", "Signals"], }, - /** Lookup402: cumulus_pallet_xcmp_queue::OutboundChannelDetails */ + /** Lookup401: cumulus_pallet_xcmp_queue::OutboundChannelDetails */ CumulusPalletXcmpQueueOutboundChannelDetails: { recipient: "u32", state: "CumulusPalletXcmpQueueOutboundState", @@ -3245,11 +3242,11 @@ export default { firstIndex: "u16", lastIndex: "u16", }, - /** Lookup403: cumulus_pallet_xcmp_queue::OutboundState */ + /** Lookup402: cumulus_pallet_xcmp_queue::OutboundState */ CumulusPalletXcmpQueueOutboundState: { _enum: ["Ok", "Suspended"], }, - /** Lookup405: cumulus_pallet_xcmp_queue::QueueConfigData */ + /** Lookup404: cumulus_pallet_xcmp_queue::QueueConfigData */ CumulusPalletXcmpQueueQueueConfigData: { suspendThreshold: "u32", dropThreshold: "u32", @@ -3258,27 +3255,27 @@ export default { weightRestrictDecay: "SpWeightsWeightV2Weight", xcmpMaxIndividualWeight: "SpWeightsWeightV2Weight", }, - /** Lookup407: cumulus_pallet_xcmp_queue::pallet::Error */ + /** Lookup406: cumulus_pallet_xcmp_queue::pallet::Error */ CumulusPalletXcmpQueueError: { _enum: ["FailedToSend", "BadXcmOrigin", "BadXcm", "BadOverweightIndex", "WeightOverLimit"], }, - /** Lookup408: cumulus_pallet_xcm::pallet::Error */ + /** Lookup407: cumulus_pallet_xcm::pallet::Error */ CumulusPalletXcmError: "Null", - /** Lookup409: cumulus_pallet_dmp_queue::ConfigData */ + /** Lookup408: cumulus_pallet_dmp_queue::ConfigData */ CumulusPalletDmpQueueConfigData: { maxIndividual: "SpWeightsWeightV2Weight", }, - /** Lookup410: cumulus_pallet_dmp_queue::PageIndexData */ + /** Lookup409: cumulus_pallet_dmp_queue::PageIndexData */ CumulusPalletDmpQueuePageIndexData: { beginUsed: "u32", endUsed: "u32", overweightCount: "u64", }, - /** Lookup413: cumulus_pallet_dmp_queue::pallet::Error */ + /** Lookup412: cumulus_pallet_dmp_queue::pallet::Error */ CumulusPalletDmpQueueError: { _enum: ["Unknown", "OverLimit"], }, - /** Lookup414: pallet_xcm::pallet::QueryStatus */ + /** Lookup413: pallet_xcm::pallet::QueryStatus */ PalletXcmQueryStatus: { _enum: { Pending: { @@ -3297,7 +3294,7 @@ export default { }, }, }, - /** Lookup418: xcm::VersionedResponse */ + /** Lookup417: xcm::VersionedResponse */ XcmVersionedResponse: { _enum: { __Unused0: "Null", @@ -3306,7 +3303,7 @@ export default { V3: "XcmV3Response", }, }, - /** Lookup424: pallet_xcm::pallet::VersionMigrationStage */ + /** Lookup423: pallet_xcm::pallet::VersionMigrationStage */ PalletXcmVersionMigrationStage: { _enum: { MigrateSupportedVersion: "Null", @@ -3315,7 +3312,7 @@ export default { MigrateAndNotifyOldTargets: "Null", }, }, - /** Lookup426: xcm::VersionedAssetId */ + /** Lookup425: xcm::VersionedAssetId */ XcmVersionedAssetId: { _enum: { __Unused0: "Null", @@ -3324,14 +3321,14 @@ export default { V3: "XcmV3MultiassetAssetId", }, }, - /** Lookup427: pallet_xcm::pallet::RemoteLockedFungibleRecord */ + /** Lookup426: pallet_xcm::pallet::RemoteLockedFungibleRecord */ PalletXcmRemoteLockedFungibleRecord: { amount: "u128", owner: "XcmVersionedMultiLocation", locker: "XcmVersionedMultiLocation", consumers: "Vec<(Null,u128)>", }, - /** Lookup434: pallet_xcm::pallet::Error */ + /** Lookup433: pallet_xcm::pallet::Error */ PalletXcmError: { _enum: [ "Unreachable", @@ -3356,7 +3353,7 @@ export default { "InUse", ], }, - /** Lookup435: pallet_assets::types::AssetDetails */ + /** Lookup434: pallet_assets::types::AssetDetails */ PalletAssetsAssetDetails: { owner: "AccountId32", issuer: "AccountId32", @@ -3371,22 +3368,22 @@ export default { approvals: "u32", status: "PalletAssetsAssetStatus", }, - /** Lookup436: pallet_assets::types::AssetStatus */ + /** Lookup435: pallet_assets::types::AssetStatus */ PalletAssetsAssetStatus: { _enum: ["Live", "Frozen", "Destroying"], }, - /** Lookup438: pallet_assets::types::AssetAccount */ + /** Lookup437: pallet_assets::types::AssetAccount */ PalletAssetsAssetAccount: { balance: "u128", status: "PalletAssetsAccountStatus", reason: "PalletAssetsExistenceReason", extra: "Null", }, - /** Lookup439: pallet_assets::types::AccountStatus */ + /** Lookup438: pallet_assets::types::AccountStatus */ PalletAssetsAccountStatus: { _enum: ["Liquid", "Frozen", "Blocked"], }, - /** Lookup440: pallet_assets::types::ExistenceReason */ + /** Lookup439: pallet_assets::types::ExistenceReason */ PalletAssetsExistenceReason: { _enum: { Consumer: "Null", @@ -3396,12 +3393,12 @@ export default { DepositFrom: "(AccountId32,u128)", }, }, - /** Lookup442: pallet_assets::types::Approval */ + /** Lookup441: pallet_assets::types::Approval */ PalletAssetsApproval: { amount: "u128", deposit: "u128", }, - /** Lookup443: pallet_assets::types::AssetMetadata> */ + /** Lookup442: pallet_assets::types::AssetMetadata> */ PalletAssetsAssetMetadata: { deposit: "u128", name: "Bytes", @@ -3409,7 +3406,7 @@ export default { decimals: "u8", isFrozen: "bool", }, - /** Lookup445: pallet_assets::pallet::Error */ + /** Lookup444: pallet_assets::pallet::Error */ PalletAssetsError: { _enum: [ "BalanceLow", @@ -3434,15 +3431,15 @@ export default { "CallbackFailed", ], }, - /** Lookup446: pallet_foreign_asset_creator::pallet::Error */ + /** Lookup445: pallet_foreign_asset_creator::pallet::Error */ PalletForeignAssetCreatorError: { _enum: ["AssetAlreadyExists", "AssetDoesNotExist"], }, - /** Lookup447: pallet_asset_rate::pallet::Error */ + /** Lookup446: pallet_asset_rate::pallet::Error */ PalletAssetRateError: { _enum: ["UnknownAssetKind", "AlreadyExists"], }, - /** Lookup452: sp_runtime::MultiSignature */ + /** Lookup451: sp_runtime::MultiSignature */ SpRuntimeMultiSignature: { _enum: { Ed25519: "SpCoreEd25519Signature", @@ -3450,26 +3447,26 @@ export default { Ecdsa: "SpCoreEcdsaSignature", }, }, - /** Lookup453: sp_core::ed25519::Signature */ + /** Lookup452: sp_core::ed25519::Signature */ SpCoreEd25519Signature: "[u8;64]", - /** Lookup455: sp_core::sr25519::Signature */ + /** Lookup454: sp_core::sr25519::Signature */ SpCoreSr25519Signature: "[u8;64]", - /** Lookup456: sp_core::ecdsa::Signature */ + /** Lookup455: sp_core::ecdsa::Signature */ SpCoreEcdsaSignature: "[u8;65]", - /** Lookup459: frame_system::extensions::check_non_zero_sender::CheckNonZeroSender */ + /** Lookup458: frame_system::extensions::check_non_zero_sender::CheckNonZeroSender */ FrameSystemExtensionsCheckNonZeroSender: "Null", - /** Lookup460: frame_system::extensions::check_spec_version::CheckSpecVersion */ + /** Lookup459: frame_system::extensions::check_spec_version::CheckSpecVersion */ FrameSystemExtensionsCheckSpecVersion: "Null", - /** Lookup461: frame_system::extensions::check_tx_version::CheckTxVersion */ + /** Lookup460: frame_system::extensions::check_tx_version::CheckTxVersion */ FrameSystemExtensionsCheckTxVersion: "Null", - /** Lookup462: frame_system::extensions::check_genesis::CheckGenesis */ + /** Lookup461: frame_system::extensions::check_genesis::CheckGenesis */ FrameSystemExtensionsCheckGenesis: "Null", - /** Lookup465: frame_system::extensions::check_nonce::CheckNonce */ + /** Lookup464: frame_system::extensions::check_nonce::CheckNonce */ FrameSystemExtensionsCheckNonce: "Compact", - /** Lookup466: frame_system::extensions::check_weight::CheckWeight */ + /** Lookup465: frame_system::extensions::check_weight::CheckWeight */ FrameSystemExtensionsCheckWeight: "Null", - /** Lookup467: pallet_transaction_payment::ChargeTransactionPayment */ + /** Lookup466: pallet_transaction_payment::ChargeTransactionPayment */ PalletTransactionPaymentChargeTransactionPayment: "Compact", - /** Lookup468: dancebox_runtime::Runtime */ + /** Lookup467: dancebox_runtime::Runtime */ DanceboxRuntimeRuntime: "Null", }; diff --git a/typescript-api/src/dancebox/interfaces/types-lookup.ts b/typescript-api/src/dancebox/interfaces/types-lookup.ts index ae95d81e7..7513c7444 100644 --- a/typescript-api/src/dancebox/interfaces/types-lookup.ts +++ b/typescript-api/src/dancebox/interfaces/types-lookup.ts @@ -705,9 +705,7 @@ declare module "@polkadot/types/lookup" { readonly asCreditsPurchased: { readonly paraId: u32; readonly payer: AccountId32; - readonly fee: u128; - readonly creditsPurchased: u32; - readonly creditsRemaining: u32; + readonly credit: u128; } & Struct; readonly isCreditBurned: boolean; readonly asCreditBurned: { @@ -3077,8 +3075,7 @@ declare module "@polkadot/types/lookup" { readonly isPurchaseCredits: boolean; readonly asPurchaseCredits: { readonly paraId: u32; - readonly credits: u32; - readonly maxPricePerCredit: Option; + readonly credit: u128; } & Struct; readonly isSetCredits: boolean; readonly asSetCredits: { @@ -3093,7 +3090,7 @@ declare module "@polkadot/types/lookup" { readonly type: "PurchaseCredits" | "SetCredits" | "SetGivenFreeCredits"; } - /** @name PalletDataPreserversCall (263) */ + /** @name PalletDataPreserversCall (262) */ interface PalletDataPreserversCall extends Enum { readonly isSetBootNodes: boolean; readonly asSetBootNodes: { @@ -3103,7 +3100,7 @@ declare module "@polkadot/types/lookup" { readonly type: "SetBootNodes"; } - /** @name PalletInvulnerablesCall (267) */ + /** @name PalletInvulnerablesCall (266) */ interface PalletInvulnerablesCall extends Enum { readonly isSetInvulnerables: boolean; readonly asSetInvulnerables: { @@ -3120,7 +3117,7 @@ declare module "@polkadot/types/lookup" { readonly type: "SetInvulnerables" | "AddInvulnerable" | "RemoveInvulnerable"; } - /** @name PalletSessionCall (268) */ + /** @name PalletSessionCall (267) */ interface PalletSessionCall extends Enum { readonly isSetKeys: boolean; readonly asSetKeys: { @@ -3131,24 +3128,24 @@ declare module "@polkadot/types/lookup" { readonly type: "SetKeys" | "PurgeKeys"; } - /** @name DanceboxRuntimeSessionKeys (269) */ + /** @name DanceboxRuntimeSessionKeys (268) */ interface DanceboxRuntimeSessionKeys extends Struct { readonly nimbus: NimbusPrimitivesNimbusCryptoPublic; } - /** @name NimbusPrimitivesNimbusCryptoPublic (270) */ + /** @name NimbusPrimitivesNimbusCryptoPublic (269) */ interface NimbusPrimitivesNimbusCryptoPublic extends SpCoreSr25519Public {} - /** @name SpCoreSr25519Public (271) */ + /** @name SpCoreSr25519Public (270) */ interface SpCoreSr25519Public extends U8aFixed {} - /** @name PalletAuthorInherentCall (272) */ + /** @name PalletAuthorInherentCall (271) */ interface PalletAuthorInherentCall extends Enum { readonly isKickOffAuthorshipValidation: boolean; readonly type: "KickOffAuthorshipValidation"; } - /** @name PalletPooledStakingCall (273) */ + /** @name PalletPooledStakingCall (272) */ interface PalletPooledStakingCall extends Enum { readonly isRebalanceHold: boolean; readonly asRebalanceHold: { @@ -3196,7 +3193,7 @@ declare module "@polkadot/types/lookup" { | "SwapPool"; } - /** @name PalletPooledStakingAllTargetPool (274) */ + /** @name PalletPooledStakingAllTargetPool (273) */ interface PalletPooledStakingAllTargetPool extends Enum { readonly isJoining: boolean; readonly isAutoCompounding: boolean; @@ -3205,13 +3202,13 @@ declare module "@polkadot/types/lookup" { readonly type: "Joining" | "AutoCompounding" | "ManualRewards" | "Leaving"; } - /** @name PalletPooledStakingPendingOperationQuery (276) */ + /** @name PalletPooledStakingPendingOperationQuery (275) */ interface PalletPooledStakingPendingOperationQuery extends Struct { readonly delegator: AccountId32; readonly operation: PalletPooledStakingPendingOperationKey; } - /** @name PalletPooledStakingPendingOperationKey (277) */ + /** @name PalletPooledStakingPendingOperationKey (276) */ interface PalletPooledStakingPendingOperationKey extends Enum { readonly isJoiningAutoCompounding: boolean; readonly asJoiningAutoCompounding: { @@ -3231,7 +3228,7 @@ declare module "@polkadot/types/lookup" { readonly type: "JoiningAutoCompounding" | "JoiningManualRewards" | "Leaving"; } - /** @name PalletPooledStakingSharesOrStake (278) */ + /** @name PalletPooledStakingSharesOrStake (277) */ interface PalletPooledStakingSharesOrStake extends Enum { readonly isShares: boolean; readonly asShares: u128; @@ -3240,7 +3237,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Shares" | "Stake"; } - /** @name CumulusPalletXcmpQueueCall (281) */ + /** @name CumulusPalletXcmpQueueCall (280) */ interface CumulusPalletXcmpQueueCall extends Enum { readonly isServiceOverweight: boolean; readonly asServiceOverweight: { @@ -3285,7 +3282,7 @@ declare module "@polkadot/types/lookup" { | "UpdateXcmpMaxIndividualWeight"; } - /** @name CumulusPalletDmpQueueCall (282) */ + /** @name CumulusPalletDmpQueueCall (281) */ interface CumulusPalletDmpQueueCall extends Enum { readonly isServiceOverweight: boolean; readonly asServiceOverweight: { @@ -3295,7 +3292,7 @@ declare module "@polkadot/types/lookup" { readonly type: "ServiceOverweight"; } - /** @name PalletXcmCall (283) */ + /** @name PalletXcmCall (282) */ interface PalletXcmCall extends Enum { readonly isSend: boolean; readonly asSend: { @@ -3372,7 +3369,7 @@ declare module "@polkadot/types/lookup" { | "ForceSuspension"; } - /** @name XcmVersionedXcm (284) */ + /** @name XcmVersionedXcm (283) */ interface XcmVersionedXcm extends Enum { readonly isV2: boolean; readonly asV2: XcmV2Xcm; @@ -3381,10 +3378,10 @@ declare module "@polkadot/types/lookup" { readonly type: "V2" | "V3"; } - /** @name XcmV2Xcm (285) */ + /** @name XcmV2Xcm (284) */ interface XcmV2Xcm extends Vec {} - /** @name XcmV2Instruction (287) */ + /** @name XcmV2Instruction (286) */ interface XcmV2Instruction extends Enum { readonly isWithdrawAsset: boolean; readonly asWithdrawAsset: XcmV2MultiassetMultiAssets; @@ -3532,7 +3529,7 @@ declare module "@polkadot/types/lookup" { | "UnsubscribeVersion"; } - /** @name XcmV2Response (288) */ + /** @name XcmV2Response (287) */ interface XcmV2Response extends Enum { readonly isNull: boolean; readonly isAssets: boolean; @@ -3544,7 +3541,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Null" | "Assets" | "ExecutionResult" | "Version"; } - /** @name XcmV2TraitsError (291) */ + /** @name XcmV2TraitsError (290) */ interface XcmV2TraitsError extends Enum { readonly isOverflow: boolean; readonly isUnimplemented: boolean; @@ -3603,7 +3600,7 @@ declare module "@polkadot/types/lookup" { | "WeightNotComputable"; } - /** @name XcmV2MultiassetMultiAssetFilter (292) */ + /** @name XcmV2MultiassetMultiAssetFilter (291) */ interface XcmV2MultiassetMultiAssetFilter extends Enum { readonly isDefinite: boolean; readonly asDefinite: XcmV2MultiassetMultiAssets; @@ -3612,7 +3609,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Definite" | "Wild"; } - /** @name XcmV2MultiassetWildMultiAsset (293) */ + /** @name XcmV2MultiassetWildMultiAsset (292) */ interface XcmV2MultiassetWildMultiAsset extends Enum { readonly isAll: boolean; readonly isAllOf: boolean; @@ -3623,14 +3620,14 @@ declare module "@polkadot/types/lookup" { readonly type: "All" | "AllOf"; } - /** @name XcmV2MultiassetWildFungibility (294) */ + /** @name XcmV2MultiassetWildFungibility (293) */ interface XcmV2MultiassetWildFungibility extends Enum { readonly isFungible: boolean; readonly isNonFungible: boolean; readonly type: "Fungible" | "NonFungible"; } - /** @name XcmV2WeightLimit (295) */ + /** @name XcmV2WeightLimit (294) */ interface XcmV2WeightLimit extends Enum { readonly isUnlimited: boolean; readonly isLimited: boolean; @@ -3638,7 +3635,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Unlimited" | "Limited"; } - /** @name PalletAssetsCall (304) */ + /** @name PalletAssetsCall (303) */ interface PalletAssetsCall extends Enum { readonly isCreate: boolean; readonly asCreate: { @@ -3852,7 +3849,7 @@ declare module "@polkadot/types/lookup" { | "Block"; } - /** @name PalletForeignAssetCreatorCall (305) */ + /** @name PalletForeignAssetCreatorCall (304) */ interface PalletForeignAssetCreatorCall extends Enum { readonly isCreateForeignAsset: boolean; readonly asCreateForeignAsset: { @@ -3882,7 +3879,7 @@ declare module "@polkadot/types/lookup" { | "DestroyForeignAsset"; } - /** @name PalletAssetRateCall (306) */ + /** @name PalletAssetRateCall (305) */ interface PalletAssetRateCall extends Enum { readonly isCreate: boolean; readonly asCreate: { @@ -3901,7 +3898,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Create" | "Update" | "Remove"; } - /** @name PalletRootTestingCall (307) */ + /** @name PalletRootTestingCall (306) */ interface PalletRootTestingCall extends Enum { readonly isFillBlock: boolean; readonly asFillBlock: { @@ -3910,33 +3907,33 @@ declare module "@polkadot/types/lookup" { readonly type: "FillBlock"; } - /** @name PalletSudoError (308) */ + /** @name PalletSudoError (307) */ interface PalletSudoError extends Enum { readonly isRequireSudo: boolean; readonly type: "RequireSudo"; } - /** @name PalletUtilityError (309) */ + /** @name PalletUtilityError (308) */ interface PalletUtilityError extends Enum { readonly isTooManyCalls: boolean; readonly type: "TooManyCalls"; } - /** @name PalletProxyProxyDefinition (312) */ + /** @name PalletProxyProxyDefinition (311) */ interface PalletProxyProxyDefinition extends Struct { readonly delegate: AccountId32; readonly proxyType: DanceboxRuntimeProxyType; readonly delay: u32; } - /** @name PalletProxyAnnouncement (316) */ + /** @name PalletProxyAnnouncement (315) */ interface PalletProxyAnnouncement extends Struct { readonly real: AccountId32; readonly callHash: H256; readonly height: u32; } - /** @name PalletProxyError (318) */ + /** @name PalletProxyError (317) */ interface PalletProxyError extends Enum { readonly isTooMany: boolean; readonly isNotFound: boolean; @@ -3957,7 +3954,7 @@ declare module "@polkadot/types/lookup" { | "NoSelfProxy"; } - /** @name PalletMigrationsError (319) */ + /** @name PalletMigrationsError (318) */ interface PalletMigrationsError extends Enum { readonly isPreimageMissing: boolean; readonly isWrongUpperBound: boolean; @@ -3966,14 +3963,14 @@ declare module "@polkadot/types/lookup" { readonly type: "PreimageMissing" | "WrongUpperBound" | "PreimageIsTooBig" | "PreimageAlreadyExists"; } - /** @name PalletMaintenanceModeError (320) */ + /** @name PalletMaintenanceModeError (319) */ interface PalletMaintenanceModeError extends Enum { readonly isAlreadyInMaintenanceMode: boolean; readonly isNotInMaintenanceMode: boolean; readonly type: "AlreadyInMaintenanceMode" | "NotInMaintenanceMode"; } - /** @name PalletTxPauseError (321) */ + /** @name PalletTxPauseError (320) */ interface PalletTxPauseError extends Enum { readonly isIsPaused: boolean; readonly isIsUnpaused: boolean; @@ -3982,14 +3979,14 @@ declare module "@polkadot/types/lookup" { readonly type: "IsPaused" | "IsUnpaused" | "Unpausable" | "NotFound"; } - /** @name PalletBalancesBalanceLock (323) */ + /** @name PalletBalancesBalanceLock (322) */ interface PalletBalancesBalanceLock extends Struct { readonly id: U8aFixed; readonly amount: u128; readonly reasons: PalletBalancesReasons; } - /** @name PalletBalancesReasons (324) */ + /** @name PalletBalancesReasons (323) */ interface PalletBalancesReasons extends Enum { readonly isFee: boolean; readonly isMisc: boolean; @@ -3997,32 +3994,32 @@ declare module "@polkadot/types/lookup" { readonly type: "Fee" | "Misc" | "All"; } - /** @name PalletBalancesReserveData (327) */ + /** @name PalletBalancesReserveData (326) */ interface PalletBalancesReserveData extends Struct { readonly id: U8aFixed; readonly amount: u128; } - /** @name DanceboxRuntimeRuntimeHoldReason (331) */ + /** @name DanceboxRuntimeRuntimeHoldReason (330) */ interface DanceboxRuntimeRuntimeHoldReason extends Enum { readonly isPooledStaking: boolean; readonly asPooledStaking: PalletPooledStakingHoldReason; readonly type: "PooledStaking"; } - /** @name PalletPooledStakingHoldReason (332) */ + /** @name PalletPooledStakingHoldReason (331) */ interface PalletPooledStakingHoldReason extends Enum { readonly isPooledStake: boolean; readonly type: "PooledStake"; } - /** @name PalletBalancesIdAmount (335) */ + /** @name PalletBalancesIdAmount (334) */ interface PalletBalancesIdAmount extends Struct { readonly id: U8aFixed; readonly amount: u128; } - /** @name PalletBalancesError (337) */ + /** @name PalletBalancesError (336) */ interface PalletBalancesError extends Enum { readonly isVestingBalance: boolean; readonly isLiquidityRestrictions: boolean; @@ -4047,28 +4044,28 @@ declare module "@polkadot/types/lookup" { | "TooManyFreezes"; } - /** @name PalletTransactionPaymentReleases (338) */ + /** @name PalletTransactionPaymentReleases (337) */ interface PalletTransactionPaymentReleases extends Enum { readonly isV1Ancient: boolean; readonly isV2: boolean; readonly type: "V1Ancient" | "V2"; } - /** @name PalletIdentityRegistration (339) */ + /** @name PalletIdentityRegistration (338) */ interface PalletIdentityRegistration extends Struct { readonly judgements: Vec>; readonly deposit: u128; readonly info: PalletIdentitySimpleIdentityInfo; } - /** @name PalletIdentityRegistrarInfo (347) */ + /** @name PalletIdentityRegistrarInfo (346) */ interface PalletIdentityRegistrarInfo extends Struct { readonly account: AccountId32; readonly fee: u128; readonly fields: PalletIdentityBitFlags; } - /** @name PalletIdentityError (349) */ + /** @name PalletIdentityError (348) */ interface PalletIdentityError extends Enum { readonly isTooManySubAccounts: boolean; readonly isNotFound: boolean; @@ -4109,13 +4106,13 @@ declare module "@polkadot/types/lookup" { | "JudgementPaymentFailed"; } - /** @name PalletRegistrarDepositInfo (354) */ + /** @name PalletRegistrarDepositInfo (353) */ interface PalletRegistrarDepositInfo extends Struct { readonly creator: AccountId32; readonly deposit: u128; } - /** @name PalletRegistrarError (355) */ + /** @name PalletRegistrarError (354) */ interface PalletRegistrarError extends Enum { readonly isParaIdAlreadyRegistered: boolean; readonly isParaIdNotRegistered: boolean; @@ -4138,7 +4135,7 @@ declare module "@polkadot/types/lookup" { | "NotSufficientDeposit"; } - /** @name PalletConfigurationHostConfiguration (356) */ + /** @name PalletConfigurationHostConfiguration (355) */ interface PalletConfigurationHostConfiguration extends Struct { readonly maxCollators: u32; readonly minOrchestratorCollators: u32; @@ -4150,25 +4147,25 @@ declare module "@polkadot/types/lookup" { readonly targetContainerChainFullness: Perbill; } - /** @name PalletConfigurationError (359) */ + /** @name PalletConfigurationError (358) */ interface PalletConfigurationError extends Enum { readonly isInvalidNewValue: boolean; readonly type: "InvalidNewValue"; } - /** @name DpCollatorAssignmentAssignedCollatorsAccountId32 (360) */ + /** @name DpCollatorAssignmentAssignedCollatorsAccountId32 (359) */ interface DpCollatorAssignmentAssignedCollatorsAccountId32 extends Struct { readonly orchestratorChain: Vec; readonly containerChains: BTreeMap>; } - /** @name PalletAuthorNotingContainerChainBlockInfo (365) */ + /** @name PalletAuthorNotingContainerChainBlockInfo (364) */ interface PalletAuthorNotingContainerChainBlockInfo extends Struct { readonly blockNumber: u32; readonly author: AccountId32; } - /** @name PalletAuthorNotingError (366) */ + /** @name PalletAuthorNotingError (365) */ interface PalletAuthorNotingError extends Enum { readonly isFailedReading: boolean; readonly isFailedDecodingHeader: boolean; @@ -4187,13 +4184,13 @@ declare module "@polkadot/types/lookup" { | "NonAuraDigest"; } - /** @name DpCollatorAssignmentAssignedCollatorsPublic (367) */ + /** @name DpCollatorAssignmentAssignedCollatorsPublic (366) */ interface DpCollatorAssignmentAssignedCollatorsPublic extends Struct { readonly orchestratorChain: Vec; readonly containerChains: BTreeMap>; } - /** @name PalletServicesPaymentError (372) */ + /** @name PalletServicesPaymentError (371) */ interface PalletServicesPaymentError extends Enum { readonly isInsufficientFundsToPurchaseCredits: boolean; readonly isInsufficientCredits: boolean; @@ -4201,13 +4198,13 @@ declare module "@polkadot/types/lookup" { readonly type: "InsufficientFundsToPurchaseCredits" | "InsufficientCredits" | "CreditPriceTooExpensive"; } - /** @name PalletDataPreserversError (373) */ + /** @name PalletDataPreserversError (372) */ interface PalletDataPreserversError extends Enum { readonly isNoBootNodes: boolean; readonly type: "NoBootNodes"; } - /** @name PalletInvulnerablesError (375) */ + /** @name PalletInvulnerablesError (374) */ interface PalletInvulnerablesError extends Enum { readonly isTooManyInvulnerables: boolean; readonly isAlreadyInvulnerable: boolean; @@ -4215,10 +4212,10 @@ declare module "@polkadot/types/lookup" { readonly type: "TooManyInvulnerables" | "AlreadyInvulnerable" | "NotInvulnerable"; } - /** @name SpCoreCryptoKeyTypeId (380) */ + /** @name SpCoreCryptoKeyTypeId (379) */ interface SpCoreCryptoKeyTypeId extends U8aFixed {} - /** @name PalletSessionError (381) */ + /** @name PalletSessionError (380) */ interface PalletSessionError extends Enum { readonly isInvalidProof: boolean; readonly isNoAssociatedValidatorId: boolean; @@ -4228,7 +4225,7 @@ declare module "@polkadot/types/lookup" { readonly type: "InvalidProof" | "NoAssociatedValidatorId" | "DuplicatedKey" | "NoKeys" | "NoAccount"; } - /** @name PalletAuthorInherentError (385) */ + /** @name PalletAuthorInherentError (384) */ interface PalletAuthorInherentError extends Enum { readonly isAuthorAlreadySet: boolean; readonly isNoAccountId: boolean; @@ -4236,13 +4233,13 @@ declare module "@polkadot/types/lookup" { readonly type: "AuthorAlreadySet" | "NoAccountId" | "CannotBeAuthor"; } - /** @name PalletPooledStakingCandidateEligibleCandidate (387) */ + /** @name PalletPooledStakingCandidateEligibleCandidate (386) */ interface PalletPooledStakingCandidateEligibleCandidate extends Struct { readonly candidate: AccountId32; readonly stake: u128; } - /** @name PalletPooledStakingPoolsKey (390) */ + /** @name PalletPooledStakingPoolsKey (389) */ interface PalletPooledStakingPoolsKey extends Enum { readonly isCandidateTotalStake: boolean; readonly isJoiningShares: boolean; @@ -4312,7 +4309,7 @@ declare module "@polkadot/types/lookup" { | "LeavingSharesHeldStake"; } - /** @name PalletPooledStakingError (392) */ + /** @name PalletPooledStakingError (391) */ interface PalletPooledStakingError extends Enum { readonly isInvalidPalletSetting: boolean; readonly isDisabledFeature: boolean; @@ -4346,27 +4343,27 @@ declare module "@polkadot/types/lookup" { | "SwapResultsInZeroShares"; } - /** @name PalletInflationRewardsChainsToRewardValue (393) */ + /** @name PalletInflationRewardsChainsToRewardValue (392) */ interface PalletInflationRewardsChainsToRewardValue extends Struct { readonly paraIds: Vec; readonly rewardsPerChain: u128; } - /** @name CumulusPalletXcmpQueueInboundChannelDetails (395) */ + /** @name CumulusPalletXcmpQueueInboundChannelDetails (394) */ interface CumulusPalletXcmpQueueInboundChannelDetails extends Struct { readonly sender: u32; readonly state: CumulusPalletXcmpQueueInboundState; readonly messageMetadata: Vec>; } - /** @name CumulusPalletXcmpQueueInboundState (396) */ + /** @name CumulusPalletXcmpQueueInboundState (395) */ interface CumulusPalletXcmpQueueInboundState extends Enum { readonly isOk: boolean; readonly isSuspended: boolean; readonly type: "Ok" | "Suspended"; } - /** @name PolkadotParachainPrimitivesPrimitivesXcmpMessageFormat (399) */ + /** @name PolkadotParachainPrimitivesPrimitivesXcmpMessageFormat (398) */ interface PolkadotParachainPrimitivesPrimitivesXcmpMessageFormat extends Enum { readonly isConcatenatedVersionedXcm: boolean; readonly isConcatenatedEncodedBlob: boolean; @@ -4374,7 +4371,7 @@ declare module "@polkadot/types/lookup" { readonly type: "ConcatenatedVersionedXcm" | "ConcatenatedEncodedBlob" | "Signals"; } - /** @name CumulusPalletXcmpQueueOutboundChannelDetails (402) */ + /** @name CumulusPalletXcmpQueueOutboundChannelDetails (401) */ interface CumulusPalletXcmpQueueOutboundChannelDetails extends Struct { readonly recipient: u32; readonly state: CumulusPalletXcmpQueueOutboundState; @@ -4383,14 +4380,14 @@ declare module "@polkadot/types/lookup" { readonly lastIndex: u16; } - /** @name CumulusPalletXcmpQueueOutboundState (403) */ + /** @name CumulusPalletXcmpQueueOutboundState (402) */ interface CumulusPalletXcmpQueueOutboundState extends Enum { readonly isOk: boolean; readonly isSuspended: boolean; readonly type: "Ok" | "Suspended"; } - /** @name CumulusPalletXcmpQueueQueueConfigData (405) */ + /** @name CumulusPalletXcmpQueueQueueConfigData (404) */ interface CumulusPalletXcmpQueueQueueConfigData extends Struct { readonly suspendThreshold: u32; readonly dropThreshold: u32; @@ -4400,7 +4397,7 @@ declare module "@polkadot/types/lookup" { readonly xcmpMaxIndividualWeight: SpWeightsWeightV2Weight; } - /** @name CumulusPalletXcmpQueueError (407) */ + /** @name CumulusPalletXcmpQueueError (406) */ interface CumulusPalletXcmpQueueError extends Enum { readonly isFailedToSend: boolean; readonly isBadXcmOrigin: boolean; @@ -4410,29 +4407,29 @@ declare module "@polkadot/types/lookup" { readonly type: "FailedToSend" | "BadXcmOrigin" | "BadXcm" | "BadOverweightIndex" | "WeightOverLimit"; } - /** @name CumulusPalletXcmError (408) */ + /** @name CumulusPalletXcmError (407) */ type CumulusPalletXcmError = Null; - /** @name CumulusPalletDmpQueueConfigData (409) */ + /** @name CumulusPalletDmpQueueConfigData (408) */ interface CumulusPalletDmpQueueConfigData extends Struct { readonly maxIndividual: SpWeightsWeightV2Weight; } - /** @name CumulusPalletDmpQueuePageIndexData (410) */ + /** @name CumulusPalletDmpQueuePageIndexData (409) */ interface CumulusPalletDmpQueuePageIndexData extends Struct { readonly beginUsed: u32; readonly endUsed: u32; readonly overweightCount: u64; } - /** @name CumulusPalletDmpQueueError (413) */ + /** @name CumulusPalletDmpQueueError (412) */ interface CumulusPalletDmpQueueError extends Enum { readonly isUnknown: boolean; readonly isOverLimit: boolean; readonly type: "Unknown" | "OverLimit"; } - /** @name PalletXcmQueryStatus (414) */ + /** @name PalletXcmQueryStatus (413) */ interface PalletXcmQueryStatus extends Enum { readonly isPending: boolean; readonly asPending: { @@ -4454,7 +4451,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Pending" | "VersionNotifier" | "Ready"; } - /** @name XcmVersionedResponse (418) */ + /** @name XcmVersionedResponse (417) */ interface XcmVersionedResponse extends Enum { readonly isV2: boolean; readonly asV2: XcmV2Response; @@ -4463,7 +4460,7 @@ declare module "@polkadot/types/lookup" { readonly type: "V2" | "V3"; } - /** @name PalletXcmVersionMigrationStage (424) */ + /** @name PalletXcmVersionMigrationStage (423) */ interface PalletXcmVersionMigrationStage extends Enum { readonly isMigrateSupportedVersion: boolean; readonly isMigrateVersionNotifiers: boolean; @@ -4477,14 +4474,14 @@ declare module "@polkadot/types/lookup" { | "MigrateAndNotifyOldTargets"; } - /** @name XcmVersionedAssetId (426) */ + /** @name XcmVersionedAssetId (425) */ interface XcmVersionedAssetId extends Enum { readonly isV3: boolean; readonly asV3: XcmV3MultiassetAssetId; readonly type: "V3"; } - /** @name PalletXcmRemoteLockedFungibleRecord (427) */ + /** @name PalletXcmRemoteLockedFungibleRecord (426) */ interface PalletXcmRemoteLockedFungibleRecord extends Struct { readonly amount: u128; readonly owner: XcmVersionedMultiLocation; @@ -4492,7 +4489,7 @@ declare module "@polkadot/types/lookup" { readonly consumers: Vec>; } - /** @name PalletXcmError (434) */ + /** @name PalletXcmError (433) */ interface PalletXcmError extends Enum { readonly isUnreachable: boolean; readonly isSendFailure: boolean; @@ -4537,7 +4534,7 @@ declare module "@polkadot/types/lookup" { | "InUse"; } - /** @name PalletAssetsAssetDetails (435) */ + /** @name PalletAssetsAssetDetails (434) */ interface PalletAssetsAssetDetails extends Struct { readonly owner: AccountId32; readonly issuer: AccountId32; @@ -4553,7 +4550,7 @@ declare module "@polkadot/types/lookup" { readonly status: PalletAssetsAssetStatus; } - /** @name PalletAssetsAssetStatus (436) */ + /** @name PalletAssetsAssetStatus (435) */ interface PalletAssetsAssetStatus extends Enum { readonly isLive: boolean; readonly isFrozen: boolean; @@ -4561,7 +4558,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Live" | "Frozen" | "Destroying"; } - /** @name PalletAssetsAssetAccount (438) */ + /** @name PalletAssetsAssetAccount (437) */ interface PalletAssetsAssetAccount extends Struct { readonly balance: u128; readonly status: PalletAssetsAccountStatus; @@ -4569,7 +4566,7 @@ declare module "@polkadot/types/lookup" { readonly extra: Null; } - /** @name PalletAssetsAccountStatus (439) */ + /** @name PalletAssetsAccountStatus (438) */ interface PalletAssetsAccountStatus extends Enum { readonly isLiquid: boolean; readonly isFrozen: boolean; @@ -4577,7 +4574,7 @@ declare module "@polkadot/types/lookup" { readonly type: "Liquid" | "Frozen" | "Blocked"; } - /** @name PalletAssetsExistenceReason (440) */ + /** @name PalletAssetsExistenceReason (439) */ interface PalletAssetsExistenceReason extends Enum { readonly isConsumer: boolean; readonly isSufficient: boolean; @@ -4589,13 +4586,13 @@ declare module "@polkadot/types/lookup" { readonly type: "Consumer" | "Sufficient" | "DepositHeld" | "DepositRefunded" | "DepositFrom"; } - /** @name PalletAssetsApproval (442) */ + /** @name PalletAssetsApproval (441) */ interface PalletAssetsApproval extends Struct { readonly amount: u128; readonly deposit: u128; } - /** @name PalletAssetsAssetMetadata (443) */ + /** @name PalletAssetsAssetMetadata (442) */ interface PalletAssetsAssetMetadata extends Struct { readonly deposit: u128; readonly name: Bytes; @@ -4604,7 +4601,7 @@ declare module "@polkadot/types/lookup" { readonly isFrozen: bool; } - /** @name PalletAssetsError (445) */ + /** @name PalletAssetsError (444) */ interface PalletAssetsError extends Enum { readonly isBalanceLow: boolean; readonly isNoAccount: boolean; @@ -4649,21 +4646,21 @@ declare module "@polkadot/types/lookup" { | "CallbackFailed"; } - /** @name PalletForeignAssetCreatorError (446) */ + /** @name PalletForeignAssetCreatorError (445) */ interface PalletForeignAssetCreatorError extends Enum { readonly isAssetAlreadyExists: boolean; readonly isAssetDoesNotExist: boolean; readonly type: "AssetAlreadyExists" | "AssetDoesNotExist"; } - /** @name PalletAssetRateError (447) */ + /** @name PalletAssetRateError (446) */ interface PalletAssetRateError extends Enum { readonly isUnknownAssetKind: boolean; readonly isAlreadyExists: boolean; readonly type: "UnknownAssetKind" | "AlreadyExists"; } - /** @name SpRuntimeMultiSignature (452) */ + /** @name SpRuntimeMultiSignature (451) */ interface SpRuntimeMultiSignature extends Enum { readonly isEd25519: boolean; readonly asEd25519: SpCoreEd25519Signature; @@ -4674,36 +4671,36 @@ declare module "@polkadot/types/lookup" { readonly type: "Ed25519" | "Sr25519" | "Ecdsa"; } - /** @name SpCoreEd25519Signature (453) */ + /** @name SpCoreEd25519Signature (452) */ interface SpCoreEd25519Signature extends U8aFixed {} - /** @name SpCoreSr25519Signature (455) */ + /** @name SpCoreSr25519Signature (454) */ interface SpCoreSr25519Signature extends U8aFixed {} - /** @name SpCoreEcdsaSignature (456) */ + /** @name SpCoreEcdsaSignature (455) */ interface SpCoreEcdsaSignature extends U8aFixed {} - /** @name FrameSystemExtensionsCheckNonZeroSender (459) */ + /** @name FrameSystemExtensionsCheckNonZeroSender (458) */ type FrameSystemExtensionsCheckNonZeroSender = Null; - /** @name FrameSystemExtensionsCheckSpecVersion (460) */ + /** @name FrameSystemExtensionsCheckSpecVersion (459) */ type FrameSystemExtensionsCheckSpecVersion = Null; - /** @name FrameSystemExtensionsCheckTxVersion (461) */ + /** @name FrameSystemExtensionsCheckTxVersion (460) */ type FrameSystemExtensionsCheckTxVersion = Null; - /** @name FrameSystemExtensionsCheckGenesis (462) */ + /** @name FrameSystemExtensionsCheckGenesis (461) */ type FrameSystemExtensionsCheckGenesis = Null; - /** @name FrameSystemExtensionsCheckNonce (465) */ + /** @name FrameSystemExtensionsCheckNonce (464) */ interface FrameSystemExtensionsCheckNonce extends Compact {} - /** @name FrameSystemExtensionsCheckWeight (466) */ + /** @name FrameSystemExtensionsCheckWeight (465) */ type FrameSystemExtensionsCheckWeight = Null; - /** @name PalletTransactionPaymentChargeTransactionPayment (467) */ + /** @name PalletTransactionPaymentChargeTransactionPayment (466) */ interface PalletTransactionPaymentChargeTransactionPayment extends Compact {} - /** @name DanceboxRuntimeRuntime (468) */ + /** @name DanceboxRuntimeRuntime (467) */ type DanceboxRuntimeRuntime = Null; } // declare module From 72f72e93f54e1510826a8d74e48f416f67babaed Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 18:13:33 +0100 Subject: [PATCH 10/36] typescrip api flashbox --- .../flashbox/interfaces/augment-api-events.ts | 4 +- .../src/flashbox/interfaces/augment-api-tx.ts | 5 +- .../src/flashbox/interfaces/lookup.ts | 113 +++++++++--------- .../src/flashbox/interfaces/types-lookup.ts | 113 +++++++++--------- 4 files changed, 114 insertions(+), 121 deletions(-) diff --git a/typescript-api/src/flashbox/interfaces/augment-api-events.ts b/typescript-api/src/flashbox/interfaces/augment-api-events.ts index 49fb77522..cef25fbed 100644 --- a/typescript-api/src/flashbox/interfaces/augment-api-events.ts +++ b/typescript-api/src/flashbox/interfaces/augment-api-events.ts @@ -348,8 +348,8 @@ declare module "@polkadot/api-base/types/events" { >; CreditsPurchased: AugmentedEvent< ApiType, - [paraId: u32, payer: AccountId32, fee: u128, creditsPurchased: u32, creditsRemaining: u32], - { paraId: u32; payer: AccountId32; fee: u128; creditsPurchased: u32; creditsRemaining: u32 } + [paraId: u32, payer: AccountId32, credit: u128], + { paraId: u32; payer: AccountId32; credit: u128 } >; CreditsSet: AugmentedEvent; /** Generic event */ diff --git a/typescript-api/src/flashbox/interfaces/augment-api-tx.ts b/typescript-api/src/flashbox/interfaces/augment-api-tx.ts index 6bfd8322b..63b4ed6d7 100644 --- a/typescript-api/src/flashbox/interfaces/augment-api-tx.ts +++ b/typescript-api/src/flashbox/interfaces/augment-api-tx.ts @@ -819,10 +819,9 @@ declare module "@polkadot/api-base/types/submittable" { purchaseCredits: AugmentedSubmittable< ( paraId: u32 | AnyNumber | Uint8Array, - credits: u32 | AnyNumber | Uint8Array, - maxPricePerCredit: Option | null | Uint8Array | u128 | AnyNumber + credit: u128 | AnyNumber | Uint8Array ) => SubmittableExtrinsic, - [u32, u32, Option] + [u32, u128] >; /** See [`Pallet::set_credits`]. */ setCredits: AugmentedSubmittable< diff --git a/typescript-api/src/flashbox/interfaces/lookup.ts b/typescript-api/src/flashbox/interfaces/lookup.ts index da1643a02..6ea6cc06c 100644 --- a/typescript-api/src/flashbox/interfaces/lookup.ts +++ b/typescript-api/src/flashbox/interfaces/lookup.ts @@ -475,9 +475,7 @@ export default { CreditsPurchased: { paraId: "u32", payer: "AccountId32", - fee: "u128", - creditsPurchased: "u32", - creditsRemaining: "u32", + credit: "u128", }, CreditBurned: { paraId: "u32", @@ -1223,8 +1221,7 @@ export default { _enum: { purchase_credits: { paraId: "u32", - credits: "u32", - maxPricePerCredit: "Option", + credit: "u128", }, set_credits: { paraId: "u32", @@ -1236,7 +1233,7 @@ export default { }, }, }, - /** Lookup202: pallet_data_preservers::pallet::Call */ + /** Lookup201: pallet_data_preservers::pallet::Call */ PalletDataPreserversCall: { _enum: { set_boot_nodes: { @@ -1245,7 +1242,7 @@ export default { }, }, }, - /** Lookup206: pallet_invulnerables::pallet::Call */ + /** Lookup205: pallet_invulnerables::pallet::Call */ PalletInvulnerablesCall: { _enum: { set_invulnerables: { @@ -1262,7 +1259,7 @@ export default { }, }, }, - /** Lookup207: pallet_session::pallet::Call */ + /** Lookup206: pallet_session::pallet::Call */ PalletSessionCall: { _enum: { set_keys: { @@ -1275,19 +1272,19 @@ export default { purge_keys: "Null", }, }, - /** Lookup208: flashbox_runtime::SessionKeys */ + /** Lookup207: flashbox_runtime::SessionKeys */ FlashboxRuntimeSessionKeys: { nimbus: "NimbusPrimitivesNimbusCryptoPublic", }, - /** Lookup209: nimbus_primitives::nimbus_crypto::Public */ + /** Lookup208: nimbus_primitives::nimbus_crypto::Public */ NimbusPrimitivesNimbusCryptoPublic: "SpCoreSr25519Public", - /** Lookup210: sp_core::sr25519::Public */ + /** Lookup209: sp_core::sr25519::Public */ SpCoreSr25519Public: "[u8;32]", - /** Lookup211: pallet_author_inherent::pallet::Call */ + /** Lookup210: pallet_author_inherent::pallet::Call */ PalletAuthorInherentCall: { _enum: ["kick_off_authorship_validation"], }, - /** Lookup212: pallet_root_testing::pallet::Call */ + /** Lookup211: pallet_root_testing::pallet::Call */ PalletRootTestingCall: { _enum: { fill_block: { @@ -1295,27 +1292,27 @@ export default { }, }, }, - /** Lookup213: pallet_sudo::pallet::Error */ + /** Lookup212: pallet_sudo::pallet::Error */ PalletSudoError: { _enum: ["RequireSudo"], }, - /** Lookup214: pallet_utility::pallet::Error */ + /** Lookup213: pallet_utility::pallet::Error */ PalletUtilityError: { _enum: ["TooManyCalls"], }, - /** Lookup217: pallet_proxy::ProxyDefinition */ + /** Lookup216: pallet_proxy::ProxyDefinition */ PalletProxyProxyDefinition: { delegate: "AccountId32", proxyType: "FlashboxRuntimeProxyType", delay: "u32", }, - /** Lookup221: pallet_proxy::Announcement */ + /** Lookup220: pallet_proxy::Announcement */ PalletProxyAnnouncement: { real: "AccountId32", callHash: "H256", height: "u32", }, - /** Lookup223: pallet_proxy::pallet::Error */ + /** Lookup222: pallet_proxy::pallet::Error */ PalletProxyError: { _enum: [ "TooMany", @@ -1328,41 +1325,41 @@ export default { "NoSelfProxy", ], }, - /** Lookup224: pallet_migrations::pallet::Error */ + /** Lookup223: pallet_migrations::pallet::Error */ PalletMigrationsError: { _enum: ["PreimageMissing", "WrongUpperBound", "PreimageIsTooBig", "PreimageAlreadyExists"], }, - /** Lookup225: pallet_maintenance_mode::pallet::Error */ + /** Lookup224: pallet_maintenance_mode::pallet::Error */ PalletMaintenanceModeError: { _enum: ["AlreadyInMaintenanceMode", "NotInMaintenanceMode"], }, - /** Lookup226: pallet_tx_pause::pallet::Error */ + /** Lookup225: pallet_tx_pause::pallet::Error */ PalletTxPauseError: { _enum: ["IsPaused", "IsUnpaused", "Unpausable", "NotFound"], }, - /** Lookup228: pallet_balances::types::BalanceLock */ + /** Lookup227: pallet_balances::types::BalanceLock */ PalletBalancesBalanceLock: { id: "[u8;8]", amount: "u128", reasons: "PalletBalancesReasons", }, - /** Lookup229: pallet_balances::types::Reasons */ + /** Lookup228: pallet_balances::types::Reasons */ PalletBalancesReasons: { _enum: ["Fee", "Misc", "All"], }, - /** Lookup232: pallet_balances::types::ReserveData */ + /** Lookup231: pallet_balances::types::ReserveData */ PalletBalancesReserveData: { id: "[u8;8]", amount: "u128", }, - /** Lookup236: flashbox_runtime::RuntimeHoldReason */ + /** Lookup235: flashbox_runtime::RuntimeHoldReason */ FlashboxRuntimeRuntimeHoldReason: "Null", - /** Lookup239: pallet_balances::types::IdAmount */ + /** Lookup238: pallet_balances::types::IdAmount */ PalletBalancesIdAmount: { id: "[u8;8]", amount: "u128", }, - /** Lookup241: pallet_balances::pallet::Error */ + /** Lookup240: pallet_balances::pallet::Error */ PalletBalancesError: { _enum: [ "VestingBalance", @@ -1377,18 +1374,18 @@ export default { "TooManyFreezes", ], }, - /** Lookup242: pallet_transaction_payment::Releases */ + /** Lookup241: pallet_transaction_payment::Releases */ PalletTransactionPaymentReleases: { _enum: ["V1Ancient", "V2"], }, - /** Lookup243: pallet_identity::types::Registration> */ + /** Lookup242: pallet_identity::types::Registration> */ PalletIdentityRegistration: { judgements: "Vec<(u32,PalletIdentityJudgement)>", deposit: "u128", info: "PalletIdentitySimpleIdentityInfo", }, /** - * Lookup251: pallet_identity::types::RegistrarInfo */ PalletIdentityRegistrarInfo: { @@ -1396,7 +1393,7 @@ export default { fee: "u128", fields: "PalletIdentityBitFlags", }, - /** Lookup253: pallet_identity::pallet::Error */ + /** Lookup252: pallet_identity::pallet::Error */ PalletIdentityError: { _enum: [ "TooManySubAccounts", @@ -1419,12 +1416,12 @@ export default { "JudgementPaymentFailed", ], }, - /** Lookup258: pallet_registrar::pallet::DepositInfo */ + /** Lookup257: pallet_registrar::pallet::DepositInfo */ PalletRegistrarDepositInfo: { creator: "AccountId32", deposit: "u128", }, - /** Lookup259: pallet_registrar::pallet::Error */ + /** Lookup258: pallet_registrar::pallet::Error */ PalletRegistrarError: { _enum: [ "ParaIdAlreadyRegistered", @@ -1438,7 +1435,7 @@ export default { "NotSufficientDeposit", ], }, - /** Lookup260: pallet_configuration::HostConfiguration */ + /** Lookup259: pallet_configuration::HostConfiguration */ PalletConfigurationHostConfiguration: { maxCollators: "u32", minOrchestratorCollators: "u32", @@ -1449,21 +1446,21 @@ export default { parathreadsPerCollator: "u32", targetContainerChainFullness: "Perbill", }, - /** Lookup263: pallet_configuration::pallet::Error */ + /** Lookup262: pallet_configuration::pallet::Error */ PalletConfigurationError: { _enum: ["InvalidNewValue"], }, - /** Lookup264: dp_collator_assignment::AssignedCollators */ + /** Lookup263: dp_collator_assignment::AssignedCollators */ DpCollatorAssignmentAssignedCollatorsAccountId32: { orchestratorChain: "Vec", containerChains: "BTreeMap>", }, - /** Lookup269: pallet_author_noting::pallet::ContainerChainBlockInfo */ + /** Lookup268: pallet_author_noting::pallet::ContainerChainBlockInfo */ PalletAuthorNotingContainerChainBlockInfo: { blockNumber: "u32", author: "AccountId32", }, - /** Lookup270: pallet_author_noting::pallet::Error */ + /** Lookup269: pallet_author_noting::pallet::Error */ PalletAuthorNotingError: { _enum: [ "FailedReading", @@ -1475,39 +1472,39 @@ export default { "NonAuraDigest", ], }, - /** Lookup271: dp_collator_assignment::AssignedCollators */ + /** Lookup270: dp_collator_assignment::AssignedCollators */ DpCollatorAssignmentAssignedCollatorsPublic: { orchestratorChain: "Vec", containerChains: "BTreeMap>", }, - /** Lookup276: pallet_services_payment::pallet::Error */ + /** Lookup275: pallet_services_payment::pallet::Error */ PalletServicesPaymentError: { _enum: ["InsufficientFundsToPurchaseCredits", "InsufficientCredits", "CreditPriceTooExpensive"], }, - /** Lookup277: pallet_data_preservers::pallet::Error */ + /** Lookup276: pallet_data_preservers::pallet::Error */ PalletDataPreserversError: { _enum: ["NoBootNodes"], }, - /** Lookup279: pallet_invulnerables::pallet::Error */ + /** Lookup278: pallet_invulnerables::pallet::Error */ PalletInvulnerablesError: { _enum: ["TooManyInvulnerables", "AlreadyInvulnerable", "NotInvulnerable"], }, - /** Lookup284: sp_core::crypto::KeyTypeId */ + /** Lookup283: sp_core::crypto::KeyTypeId */ SpCoreCryptoKeyTypeId: "[u8;4]", - /** Lookup285: pallet_session::pallet::Error */ + /** Lookup284: pallet_session::pallet::Error */ PalletSessionError: { _enum: ["InvalidProof", "NoAssociatedValidatorId", "DuplicatedKey", "NoKeys", "NoAccount"], }, - /** Lookup289: pallet_author_inherent::pallet::Error */ + /** Lookup288: pallet_author_inherent::pallet::Error */ PalletAuthorInherentError: { _enum: ["AuthorAlreadySet", "NoAccountId", "CannotBeAuthor"], }, - /** Lookup290: pallet_inflation_rewards::pallet::ChainsToRewardValue */ + /** Lookup289: pallet_inflation_rewards::pallet::ChainsToRewardValue */ PalletInflationRewardsChainsToRewardValue: { paraIds: "Vec", rewardsPerChain: "u128", }, - /** Lookup295: sp_runtime::MultiSignature */ + /** Lookup294: sp_runtime::MultiSignature */ SpRuntimeMultiSignature: { _enum: { Ed25519: "SpCoreEd25519Signature", @@ -1515,26 +1512,26 @@ export default { Ecdsa: "SpCoreEcdsaSignature", }, }, - /** Lookup296: sp_core::ed25519::Signature */ + /** Lookup295: sp_core::ed25519::Signature */ SpCoreEd25519Signature: "[u8;64]", - /** Lookup298: sp_core::sr25519::Signature */ + /** Lookup297: sp_core::sr25519::Signature */ SpCoreSr25519Signature: "[u8;64]", - /** Lookup299: sp_core::ecdsa::Signature */ + /** Lookup298: sp_core::ecdsa::Signature */ SpCoreEcdsaSignature: "[u8;65]", - /** Lookup302: frame_system::extensions::check_non_zero_sender::CheckNonZeroSender */ + /** Lookup301: frame_system::extensions::check_non_zero_sender::CheckNonZeroSender */ FrameSystemExtensionsCheckNonZeroSender: "Null", - /** Lookup303: frame_system::extensions::check_spec_version::CheckSpecVersion */ + /** Lookup302: frame_system::extensions::check_spec_version::CheckSpecVersion */ FrameSystemExtensionsCheckSpecVersion: "Null", - /** Lookup304: frame_system::extensions::check_tx_version::CheckTxVersion */ + /** Lookup303: frame_system::extensions::check_tx_version::CheckTxVersion */ FrameSystemExtensionsCheckTxVersion: "Null", - /** Lookup305: frame_system::extensions::check_genesis::CheckGenesis */ + /** Lookup304: frame_system::extensions::check_genesis::CheckGenesis */ FrameSystemExtensionsCheckGenesis: "Null", - /** Lookup308: frame_system::extensions::check_nonce::CheckNonce */ + /** Lookup307: frame_system::extensions::check_nonce::CheckNonce */ FrameSystemExtensionsCheckNonce: "Compact", - /** Lookup309: frame_system::extensions::check_weight::CheckWeight */ + /** Lookup308: frame_system::extensions::check_weight::CheckWeight */ FrameSystemExtensionsCheckWeight: "Null", - /** Lookup310: pallet_transaction_payment::ChargeTransactionPayment */ + /** Lookup309: pallet_transaction_payment::ChargeTransactionPayment */ PalletTransactionPaymentChargeTransactionPayment: "Compact", - /** Lookup311: flashbox_runtime::Runtime */ + /** Lookup310: flashbox_runtime::Runtime */ FlashboxRuntimeRuntime: "Null", }; diff --git a/typescript-api/src/flashbox/interfaces/types-lookup.ts b/typescript-api/src/flashbox/interfaces/types-lookup.ts index d4a8e0869..25ebb0b8c 100644 --- a/typescript-api/src/flashbox/interfaces/types-lookup.ts +++ b/typescript-api/src/flashbox/interfaces/types-lookup.ts @@ -705,9 +705,7 @@ declare module "@polkadot/types/lookup" { readonly asCreditsPurchased: { readonly paraId: u32; readonly payer: AccountId32; - readonly fee: u128; - readonly creditsPurchased: u32; - readonly creditsRemaining: u32; + readonly credit: u128; } & Struct; readonly isCreditBurned: boolean; readonly asCreditBurned: { @@ -1582,8 +1580,7 @@ declare module "@polkadot/types/lookup" { readonly isPurchaseCredits: boolean; readonly asPurchaseCredits: { readonly paraId: u32; - readonly credits: u32; - readonly maxPricePerCredit: Option; + readonly credit: u128; } & Struct; readonly isSetCredits: boolean; readonly asSetCredits: { @@ -1598,7 +1595,7 @@ declare module "@polkadot/types/lookup" { readonly type: "PurchaseCredits" | "SetCredits" | "SetGivenFreeCredits"; } - /** @name PalletDataPreserversCall (202) */ + /** @name PalletDataPreserversCall (201) */ interface PalletDataPreserversCall extends Enum { readonly isSetBootNodes: boolean; readonly asSetBootNodes: { @@ -1608,7 +1605,7 @@ declare module "@polkadot/types/lookup" { readonly type: "SetBootNodes"; } - /** @name PalletInvulnerablesCall (206) */ + /** @name PalletInvulnerablesCall (205) */ interface PalletInvulnerablesCall extends Enum { readonly isSetInvulnerables: boolean; readonly asSetInvulnerables: { @@ -1625,7 +1622,7 @@ declare module "@polkadot/types/lookup" { readonly type: "SetInvulnerables" | "AddInvulnerable" | "RemoveInvulnerable"; } - /** @name PalletSessionCall (207) */ + /** @name PalletSessionCall (206) */ interface PalletSessionCall extends Enum { readonly isSetKeys: boolean; readonly asSetKeys: { @@ -1636,24 +1633,24 @@ declare module "@polkadot/types/lookup" { readonly type: "SetKeys" | "PurgeKeys"; } - /** @name FlashboxRuntimeSessionKeys (208) */ + /** @name FlashboxRuntimeSessionKeys (207) */ interface FlashboxRuntimeSessionKeys extends Struct { readonly nimbus: NimbusPrimitivesNimbusCryptoPublic; } - /** @name NimbusPrimitivesNimbusCryptoPublic (209) */ + /** @name NimbusPrimitivesNimbusCryptoPublic (208) */ interface NimbusPrimitivesNimbusCryptoPublic extends SpCoreSr25519Public {} - /** @name SpCoreSr25519Public (210) */ + /** @name SpCoreSr25519Public (209) */ interface SpCoreSr25519Public extends U8aFixed {} - /** @name PalletAuthorInherentCall (211) */ + /** @name PalletAuthorInherentCall (210) */ interface PalletAuthorInherentCall extends Enum { readonly isKickOffAuthorshipValidation: boolean; readonly type: "KickOffAuthorshipValidation"; } - /** @name PalletRootTestingCall (212) */ + /** @name PalletRootTestingCall (211) */ interface PalletRootTestingCall extends Enum { readonly isFillBlock: boolean; readonly asFillBlock: { @@ -1662,33 +1659,33 @@ declare module "@polkadot/types/lookup" { readonly type: "FillBlock"; } - /** @name PalletSudoError (213) */ + /** @name PalletSudoError (212) */ interface PalletSudoError extends Enum { readonly isRequireSudo: boolean; readonly type: "RequireSudo"; } - /** @name PalletUtilityError (214) */ + /** @name PalletUtilityError (213) */ interface PalletUtilityError extends Enum { readonly isTooManyCalls: boolean; readonly type: "TooManyCalls"; } - /** @name PalletProxyProxyDefinition (217) */ + /** @name PalletProxyProxyDefinition (216) */ interface PalletProxyProxyDefinition extends Struct { readonly delegate: AccountId32; readonly proxyType: FlashboxRuntimeProxyType; readonly delay: u32; } - /** @name PalletProxyAnnouncement (221) */ + /** @name PalletProxyAnnouncement (220) */ interface PalletProxyAnnouncement extends Struct { readonly real: AccountId32; readonly callHash: H256; readonly height: u32; } - /** @name PalletProxyError (223) */ + /** @name PalletProxyError (222) */ interface PalletProxyError extends Enum { readonly isTooMany: boolean; readonly isNotFound: boolean; @@ -1709,7 +1706,7 @@ declare module "@polkadot/types/lookup" { | "NoSelfProxy"; } - /** @name PalletMigrationsError (224) */ + /** @name PalletMigrationsError (223) */ interface PalletMigrationsError extends Enum { readonly isPreimageMissing: boolean; readonly isWrongUpperBound: boolean; @@ -1718,14 +1715,14 @@ declare module "@polkadot/types/lookup" { readonly type: "PreimageMissing" | "WrongUpperBound" | "PreimageIsTooBig" | "PreimageAlreadyExists"; } - /** @name PalletMaintenanceModeError (225) */ + /** @name PalletMaintenanceModeError (224) */ interface PalletMaintenanceModeError extends Enum { readonly isAlreadyInMaintenanceMode: boolean; readonly isNotInMaintenanceMode: boolean; readonly type: "AlreadyInMaintenanceMode" | "NotInMaintenanceMode"; } - /** @name PalletTxPauseError (226) */ + /** @name PalletTxPauseError (225) */ interface PalletTxPauseError extends Enum { readonly isIsPaused: boolean; readonly isIsUnpaused: boolean; @@ -1734,14 +1731,14 @@ declare module "@polkadot/types/lookup" { readonly type: "IsPaused" | "IsUnpaused" | "Unpausable" | "NotFound"; } - /** @name PalletBalancesBalanceLock (228) */ + /** @name PalletBalancesBalanceLock (227) */ interface PalletBalancesBalanceLock extends Struct { readonly id: U8aFixed; readonly amount: u128; readonly reasons: PalletBalancesReasons; } - /** @name PalletBalancesReasons (229) */ + /** @name PalletBalancesReasons (228) */ interface PalletBalancesReasons extends Enum { readonly isFee: boolean; readonly isMisc: boolean; @@ -1749,22 +1746,22 @@ declare module "@polkadot/types/lookup" { readonly type: "Fee" | "Misc" | "All"; } - /** @name PalletBalancesReserveData (232) */ + /** @name PalletBalancesReserveData (231) */ interface PalletBalancesReserveData extends Struct { readonly id: U8aFixed; readonly amount: u128; } - /** @name FlashboxRuntimeRuntimeHoldReason (236) */ + /** @name FlashboxRuntimeRuntimeHoldReason (235) */ type FlashboxRuntimeRuntimeHoldReason = Null; - /** @name PalletBalancesIdAmount (239) */ + /** @name PalletBalancesIdAmount (238) */ interface PalletBalancesIdAmount extends Struct { readonly id: U8aFixed; readonly amount: u128; } - /** @name PalletBalancesError (241) */ + /** @name PalletBalancesError (240) */ interface PalletBalancesError extends Enum { readonly isVestingBalance: boolean; readonly isLiquidityRestrictions: boolean; @@ -1789,28 +1786,28 @@ declare module "@polkadot/types/lookup" { | "TooManyFreezes"; } - /** @name PalletTransactionPaymentReleases (242) */ + /** @name PalletTransactionPaymentReleases (241) */ interface PalletTransactionPaymentReleases extends Enum { readonly isV1Ancient: boolean; readonly isV2: boolean; readonly type: "V1Ancient" | "V2"; } - /** @name PalletIdentityRegistration (243) */ + /** @name PalletIdentityRegistration (242) */ interface PalletIdentityRegistration extends Struct { readonly judgements: Vec>; readonly deposit: u128; readonly info: PalletIdentitySimpleIdentityInfo; } - /** @name PalletIdentityRegistrarInfo (251) */ + /** @name PalletIdentityRegistrarInfo (250) */ interface PalletIdentityRegistrarInfo extends Struct { readonly account: AccountId32; readonly fee: u128; readonly fields: PalletIdentityBitFlags; } - /** @name PalletIdentityError (253) */ + /** @name PalletIdentityError (252) */ interface PalletIdentityError extends Enum { readonly isTooManySubAccounts: boolean; readonly isNotFound: boolean; @@ -1851,13 +1848,13 @@ declare module "@polkadot/types/lookup" { | "JudgementPaymentFailed"; } - /** @name PalletRegistrarDepositInfo (258) */ + /** @name PalletRegistrarDepositInfo (257) */ interface PalletRegistrarDepositInfo extends Struct { readonly creator: AccountId32; readonly deposit: u128; } - /** @name PalletRegistrarError (259) */ + /** @name PalletRegistrarError (258) */ interface PalletRegistrarError extends Enum { readonly isParaIdAlreadyRegistered: boolean; readonly isParaIdNotRegistered: boolean; @@ -1880,7 +1877,7 @@ declare module "@polkadot/types/lookup" { | "NotSufficientDeposit"; } - /** @name PalletConfigurationHostConfiguration (260) */ + /** @name PalletConfigurationHostConfiguration (259) */ interface PalletConfigurationHostConfiguration extends Struct { readonly maxCollators: u32; readonly minOrchestratorCollators: u32; @@ -1892,25 +1889,25 @@ declare module "@polkadot/types/lookup" { readonly targetContainerChainFullness: Perbill; } - /** @name PalletConfigurationError (263) */ + /** @name PalletConfigurationError (262) */ interface PalletConfigurationError extends Enum { readonly isInvalidNewValue: boolean; readonly type: "InvalidNewValue"; } - /** @name DpCollatorAssignmentAssignedCollatorsAccountId32 (264) */ + /** @name DpCollatorAssignmentAssignedCollatorsAccountId32 (263) */ interface DpCollatorAssignmentAssignedCollatorsAccountId32 extends Struct { readonly orchestratorChain: Vec; readonly containerChains: BTreeMap>; } - /** @name PalletAuthorNotingContainerChainBlockInfo (269) */ + /** @name PalletAuthorNotingContainerChainBlockInfo (268) */ interface PalletAuthorNotingContainerChainBlockInfo extends Struct { readonly blockNumber: u32; readonly author: AccountId32; } - /** @name PalletAuthorNotingError (270) */ + /** @name PalletAuthorNotingError (269) */ interface PalletAuthorNotingError extends Enum { readonly isFailedReading: boolean; readonly isFailedDecodingHeader: boolean; @@ -1929,13 +1926,13 @@ declare module "@polkadot/types/lookup" { | "NonAuraDigest"; } - /** @name DpCollatorAssignmentAssignedCollatorsPublic (271) */ + /** @name DpCollatorAssignmentAssignedCollatorsPublic (270) */ interface DpCollatorAssignmentAssignedCollatorsPublic extends Struct { readonly orchestratorChain: Vec; readonly containerChains: BTreeMap>; } - /** @name PalletServicesPaymentError (276) */ + /** @name PalletServicesPaymentError (275) */ interface PalletServicesPaymentError extends Enum { readonly isInsufficientFundsToPurchaseCredits: boolean; readonly isInsufficientCredits: boolean; @@ -1943,13 +1940,13 @@ declare module "@polkadot/types/lookup" { readonly type: "InsufficientFundsToPurchaseCredits" | "InsufficientCredits" | "CreditPriceTooExpensive"; } - /** @name PalletDataPreserversError (277) */ + /** @name PalletDataPreserversError (276) */ interface PalletDataPreserversError extends Enum { readonly isNoBootNodes: boolean; readonly type: "NoBootNodes"; } - /** @name PalletInvulnerablesError (279) */ + /** @name PalletInvulnerablesError (278) */ interface PalletInvulnerablesError extends Enum { readonly isTooManyInvulnerables: boolean; readonly isAlreadyInvulnerable: boolean; @@ -1957,10 +1954,10 @@ declare module "@polkadot/types/lookup" { readonly type: "TooManyInvulnerables" | "AlreadyInvulnerable" | "NotInvulnerable"; } - /** @name SpCoreCryptoKeyTypeId (284) */ + /** @name SpCoreCryptoKeyTypeId (283) */ interface SpCoreCryptoKeyTypeId extends U8aFixed {} - /** @name PalletSessionError (285) */ + /** @name PalletSessionError (284) */ interface PalletSessionError extends Enum { readonly isInvalidProof: boolean; readonly isNoAssociatedValidatorId: boolean; @@ -1970,7 +1967,7 @@ declare module "@polkadot/types/lookup" { readonly type: "InvalidProof" | "NoAssociatedValidatorId" | "DuplicatedKey" | "NoKeys" | "NoAccount"; } - /** @name PalletAuthorInherentError (289) */ + /** @name PalletAuthorInherentError (288) */ interface PalletAuthorInherentError extends Enum { readonly isAuthorAlreadySet: boolean; readonly isNoAccountId: boolean; @@ -1978,13 +1975,13 @@ declare module "@polkadot/types/lookup" { readonly type: "AuthorAlreadySet" | "NoAccountId" | "CannotBeAuthor"; } - /** @name PalletInflationRewardsChainsToRewardValue (290) */ + /** @name PalletInflationRewardsChainsToRewardValue (289) */ interface PalletInflationRewardsChainsToRewardValue extends Struct { readonly paraIds: Vec; readonly rewardsPerChain: u128; } - /** @name SpRuntimeMultiSignature (295) */ + /** @name SpRuntimeMultiSignature (294) */ interface SpRuntimeMultiSignature extends Enum { readonly isEd25519: boolean; readonly asEd25519: SpCoreEd25519Signature; @@ -1995,36 +1992,36 @@ declare module "@polkadot/types/lookup" { readonly type: "Ed25519" | "Sr25519" | "Ecdsa"; } - /** @name SpCoreEd25519Signature (296) */ + /** @name SpCoreEd25519Signature (295) */ interface SpCoreEd25519Signature extends U8aFixed {} - /** @name SpCoreSr25519Signature (298) */ + /** @name SpCoreSr25519Signature (297) */ interface SpCoreSr25519Signature extends U8aFixed {} - /** @name SpCoreEcdsaSignature (299) */ + /** @name SpCoreEcdsaSignature (298) */ interface SpCoreEcdsaSignature extends U8aFixed {} - /** @name FrameSystemExtensionsCheckNonZeroSender (302) */ + /** @name FrameSystemExtensionsCheckNonZeroSender (301) */ type FrameSystemExtensionsCheckNonZeroSender = Null; - /** @name FrameSystemExtensionsCheckSpecVersion (303) */ + /** @name FrameSystemExtensionsCheckSpecVersion (302) */ type FrameSystemExtensionsCheckSpecVersion = Null; - /** @name FrameSystemExtensionsCheckTxVersion (304) */ + /** @name FrameSystemExtensionsCheckTxVersion (303) */ type FrameSystemExtensionsCheckTxVersion = Null; - /** @name FrameSystemExtensionsCheckGenesis (305) */ + /** @name FrameSystemExtensionsCheckGenesis (304) */ type FrameSystemExtensionsCheckGenesis = Null; - /** @name FrameSystemExtensionsCheckNonce (308) */ + /** @name FrameSystemExtensionsCheckNonce (307) */ interface FrameSystemExtensionsCheckNonce extends Compact {} - /** @name FrameSystemExtensionsCheckWeight (309) */ + /** @name FrameSystemExtensionsCheckWeight (308) */ type FrameSystemExtensionsCheckWeight = Null; - /** @name PalletTransactionPaymentChargeTransactionPayment (310) */ + /** @name PalletTransactionPaymentChargeTransactionPayment (309) */ interface PalletTransactionPaymentChargeTransactionPayment extends Compact {} - /** @name FlashboxRuntimeRuntime (311) */ + /** @name FlashboxRuntimeRuntime (310) */ type FlashboxRuntimeRuntime = Null; } // declare module From 0f06e01a34b8b78e6eceeda158b79efb85ec2c79 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 23 Jan 2024 18:13:41 +0100 Subject: [PATCH 11/36] modify --- .../services-payment/test_services_payment.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/test/suites/common-tanssi/services-payment/test_services_payment.ts b/test/suites/common-tanssi/services-payment/test_services_payment.ts index 6a1270c53..548245fc5 100644 --- a/test/suites/common-tanssi/services-payment/test_services_payment.ts +++ b/test/suites/common-tanssi/services-payment/test_services_payment.ts @@ -3,7 +3,8 @@ import { describeSuite, expect, beforeAll } from "@moonwall/cli"; import { ApiPromise } from "@polkadot/api"; import { generateKeyringPair, KeyringPair } from "@moonwall/util"; import { jumpSessions } from "util/block"; - +import { bnToU8a, stringToU8a } from "@polkadot/util"; +import { blake2AsU8a } from "@polkadot/util-crypto"; describeSuite({ id: "CT0601", title: "Services payment test suite", @@ -195,15 +196,23 @@ describeSuite({ const credits1 = (await polkadotJs.query.servicesPayment.blockProductionCredits(paraId)).toJSON(); const purchasedCredits = 100n * blocksPerSession; - const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId, purchasedCredits, null); + const requiredBalance = purchasedCredits * 1_000_000n; + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId, requiredBalance); await context.createBlock([await tx.signAsync(randomAccount)]); const balanceAfter = ( await polkadotJs.query.system.account(randomAccount.address) ).data.free.toBigInt(); expect(balanceAfter).toBeLessThan(balanceBefore); - const credits2 = (await polkadotJs.query.servicesPayment.blockProductionCredits(paraId)).toJSON(); - expect(BigInt(credits2)).toBe(BigInt(credits1) + purchasedCredits); + // Tank account is b"para" + encode(parahain ID) + trailling zeros + let seedBytes = stringToU8a("modlpy/serpayment"); + let paraIdBytes = bnToU8a(paraId, { bitLength: 32 }); + let combinedBytes = new Uint8Array(seedBytes.length + paraIdBytes.length); + let para_tank = blake2AsU8a(combinedBytes, 256); + const balanceTank = ( + await polkadotJs.query.system.account(para_tank) + ).data.free.toBigInt(); + expect(balanceTank).toBe(requiredBalance); // Check that after 2 sessions, container chain 2000 has collators and is producing blocks await jumpSessions(context, 2); From 3cc4536676320c1f81a5dfab9ce98cb712075dc4 Mon Sep 17 00:00:00 2001 From: girazoki Date: Wed, 24 Jan 2024 15:57:51 +0100 Subject: [PATCH 12/36] adapt test --- .../services-payment/test_services_payment.ts | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/test/suites/common-tanssi/services-payment/test_services_payment.ts b/test/suites/common-tanssi/services-payment/test_services_payment.ts index 548245fc5..29e93800e 100644 --- a/test/suites/common-tanssi/services-payment/test_services_payment.ts +++ b/test/suites/common-tanssi/services-payment/test_services_payment.ts @@ -193,8 +193,7 @@ describeSuite({ const balanceBefore = ( await polkadotJs.query.system.account(randomAccount.address) ).data.free.toBigInt(); - const credits1 = (await polkadotJs.query.servicesPayment.blockProductionCredits(paraId)).toJSON(); - const purchasedCredits = 100n * blocksPerSession; + const purchasedCredits = 1000n * blocksPerSession; const requiredBalance = purchasedCredits * 1_000_000n; const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId, requiredBalance); @@ -205,13 +204,13 @@ describeSuite({ ).data.free.toBigInt(); expect(balanceAfter).toBeLessThan(balanceBefore); // Tank account is b"para" + encode(parahain ID) + trailling zeros - let seedBytes = stringToU8a("modlpy/serpayment"); - let paraIdBytes = bnToU8a(paraId, { bitLength: 32 }); - let combinedBytes = new Uint8Array(seedBytes.length + paraIdBytes.length); - let para_tank = blake2AsU8a(combinedBytes, 256); - const balanceTank = ( - await polkadotJs.query.system.account(para_tank) - ).data.free.toBigInt(); + const seedBytes = stringToU8a("modlpy/serpayment"); + const paraIdBytes = bnToU8a(paraId, { bitLength: 32 }); + const combinedBytes = new Uint8Array(seedBytes.length + paraIdBytes.length); + combinedBytes.set(seedBytes); + combinedBytes.set(paraIdBytes, seedBytes.length); + const para_tank = blake2AsU8a(combinedBytes, 256); + const balanceTank = (await polkadotJs.query.system.account(para_tank)).data.free.toBigInt(); expect(balanceTank).toBe(requiredBalance); // Check that after 2 sessions, container chain 2000 has collators and is producing blocks @@ -222,20 +221,21 @@ describeSuite({ collators.toJSON().containerChains[paraId].length, `Container chain ${paraId} has 0 collators` ).toBeGreaterThan(0); + expect(balanceTank).toBe(requiredBalance); // Create a block, the block number should increase, and the number of credits should decrease - const credits3 = (await polkadotJs.query.servicesPayment.blockProductionCredits(paraId)).toJSON(); const containerBlockNum3 = await (await polkadotJs.query.authorNoting.latestAuthor(paraId)).toJSON() .blockNumber; await context.createBlock(); - const credits4 = (await polkadotJs.query.servicesPayment.blockProductionCredits(paraId)).toJSON(); + const containerBlockNum4 = await (await polkadotJs.query.authorNoting.latestAuthor(paraId)).toJSON() .blockNumber; expect(containerBlockNum3, "container chain 2000 did not create a block").toBeLessThan( containerBlockNum4 ); - expect(credits3, "container chain 2000 created a block without burning any credits").toBeGreaterThan( - credits4 + const balanceTankAfter = (await polkadotJs.query.system.account(para_tank)).data.free.toBigInt(); + expect(balanceTank, "container chain 2000 created a block without burning any credits").toBeGreaterThan( + balanceTankAfter ); }, }); From 3f7938b13169b7a250c54574966cd6ec49d8f579 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 16:55:08 +0100 Subject: [PATCH 13/36] testing further --- runtime/dancebox/src/lib.rs | 18 +- runtime/dancebox/tests/integration_test.rs | 245 ++++++++++++++++++ runtime/flashbox/src/lib.rs | 18 +- runtime/flashbox/tests/integration_test.rs | 240 +++++++++++++++++ .../services-payment/test_services_payment.ts | 16 +- 5 files changed, 516 insertions(+), 21 deletions(-) diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index 75f12e895..f0e539ad9 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -48,7 +48,7 @@ use { pallet_prelude::DispatchResult, parameter_types, traits::{ - fungible::{Balanced, Credit}, + fungible::{Balanced, Credit, Inspect}, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse, InsideBoth, InstanceFilter, OffchainWorker, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade, ValidatorRegistration, @@ -85,7 +85,7 @@ use { sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ - AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT, + AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT, Zero, }, transaction_validity::{TransactionSource, TransactionValidity}, AccountId32, ApplyExtrinsicResult, @@ -721,11 +721,17 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { let free_credits = pallet_services_payment::BlockProductionCredits::::get(para_id) .unwrap_or_default(); + let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); + // Return if we can survive with free credits + if remaining_credits.is_zero() { + return true + } let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); - let regular_credits = Balances::free_balance(pallet_services_payment::Pallet::::parachain_tank(*para_id)) - .saturating_div(block_production_costs); - - (free_credits as u128).saturating_add(regular_credits) >= credits_for_2_sessions.into() + // let's check if we can withdraw + let remaining_to_pay = (remaining_credits as u128).saturating_mul(block_production_costs); + // This should take into account whether we tank goes below ED + // The true refers to keepAlive + Balances::can_withdraw(&pallet_services_payment::Pallet::::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok() }); } diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index 6efbf09e2..129b23d34 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -4641,6 +4641,11 @@ fn test_can_buy_credits_before_registering_para() { let balance_after = System::account(AccountId::from(ALICE)).data.free; // Now parachain tank should have this amount + println!("encoded {:?}", (b"modlpy/serpayment", 2000u32).encode()); + println!( + "parachain tank address {:?}", + ServicesPayment::parachain_tank(2000.into()) + ); let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) .data .free; @@ -4998,3 +5003,243 @@ fn test_division_by_0() { assert!(balance.is_err()); }); } + +#[test] +fn test_ed_plus_two_sessions_purchase_works() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); + let credits_1001 = + block_credits_to_required_balance(dancebox_runtime::Period::get() * 2, 1001.into()) + + dancebox_runtime::EXISTENTIAL_DEPOSIT; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!( + assignment.container_chains[&1001u32.into()], + vec![CHARLIE.into(), DAVE.into()] + ); + + // Simulate block inclusion from container chain 1001 + let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default(); + let slot: u64 = 5; + let mut s = ParaHeaderSproofBuilderItem::default(); + s.para_id = 1001.into(); + s.author_id = HeaderAs::NonEncoded(sp_runtime::generic::Header:: { + parent_hash: Default::default(), + number: 1, + state_root: Default::default(), + extrinsics_root: Default::default(), + digest: sp_runtime::generic::Digest { + logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())], + }, + }); + sproof.items.push(s); + set_author_noting_inherent_data(sproof); + + run_block(); + + // After this it should not be assigned anymore, since credits are not payable + run_to_session(4u32); + // Nobody should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!(assignment.container_chains.get(&1001u32.into()), None,); + }); +} + +#[test] +fn test_ed_plus_two_sessions_minus_1_purchase_fails() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); + let credits_1001 = + block_credits_to_required_balance(dancebox_runtime::Period::get() * 2, 1001.into()) + + dancebox_runtime::EXISTENTIAL_DEPOSIT + - 1; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should not be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!(assignment.container_chains.get(&1001u32.into()), None,); + }); +} + +#[test] +fn test_credits_with_purchase_can_be_combined() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits( + root_origin(), + 1001.into(), + dancebox_runtime::Period::get() + )); + let credits_1001 = + block_credits_to_required_balance(dancebox_runtime::Period::get(), 1001.into()) + + dancebox_runtime::EXISTENTIAL_DEPOSIT; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!( + assignment.container_chains[&1001u32.into()], + vec![CHARLIE.into(), DAVE.into()] + ); + }); +} diff --git a/runtime/flashbox/src/lib.rs b/runtime/flashbox/src/lib.rs index c9f1be0ab..2c699a7f0 100644 --- a/runtime/flashbox/src/lib.rs +++ b/runtime/flashbox/src/lib.rs @@ -42,7 +42,7 @@ use { pallet_prelude::DispatchResult, parameter_types, traits::{ - fungible::{Balanced, Credit}, + fungible::{Balanced, Credit, Inspect}, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EitherOfDiverse, InsideBoth, InstanceFilter, OffchainWorker, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade, @@ -76,7 +76,7 @@ use { sp_core::{crypto::KeyTypeId, Decode, Encode, Get, MaxEncodedLen, OpaqueMetadata}, sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT}, + traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Zero}, transaction_validity::{TransactionSource, TransactionValidity}, AccountId32, ApplyExtrinsicResult, }, @@ -579,10 +579,20 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { let credits_for_2_sessions = 2 * blocks_per_session; para_ids.retain(|para_id| { // Check if the container chain has enough credits for producing blocks for 2 sessions - let credits = pallet_services_payment::BlockProductionCredits::::get(para_id) + let free_credits = pallet_services_payment::BlockProductionCredits::::get(para_id) .unwrap_or_default(); - credits >= credits_for_2_sessions + let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); + // Return if we can survive with free credits + if remaining_credits.is_zero() { + return true + } + let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); + // let's check if we can withdraw + let remaining_to_pay = (remaining_credits as u128).saturating_mul(block_production_costs); + // This should take into account whether we tank goes below ED + // The true refers to keepAlive + Balances::can_withdraw(&pallet_services_payment::Pallet::::parachain_tank(*para_id), remaining_to_pay).into_result(true).is_ok() }); } diff --git a/runtime/flashbox/tests/integration_test.rs b/runtime/flashbox/tests/integration_test.rs index d1c099995..15189594c 100644 --- a/runtime/flashbox/tests/integration_test.rs +++ b/runtime/flashbox/tests/integration_test.rs @@ -2705,3 +2705,243 @@ fn test_deregister_and_register_again_does_not_give_free_credits() { assert_eq!(credits, credits_before_2nd_register); }); } + +#[test] +fn test_ed_plus_two_sessions_purchase_works() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); + let credits_1001 = + block_credits_to_required_balance(flashbox_runtime::Period::get() * 2, 1001.into()) + + flashbox_runtime::EXISTENTIAL_DEPOSIT; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!( + assignment.container_chains[&1001u32.into()], + vec![CHARLIE.into(), DAVE.into()] + ); + + // Simulate block inclusion from container chain 1001 + let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default(); + let slot: u64 = 5; + let mut s = ParaHeaderSproofBuilderItem::default(); + s.para_id = 1001.into(); + s.author_id = HeaderAs::NonEncoded(sp_runtime::generic::Header:: { + parent_hash: Default::default(), + number: 1, + state_root: Default::default(), + extrinsics_root: Default::default(), + digest: sp_runtime::generic::Digest { + logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())], + }, + }); + sproof.items.push(s); + set_author_noting_inherent_data(sproof); + + run_block(); + + // After this it should not be assigned anymore, since credits are not payable + run_to_session(4u32); + // Nobody should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!(assignment.container_chains.get(&1001u32.into()), None,); + }); +} + +#[test] +fn test_ed_plus_two_sessions_minus_1_purchase_fails() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits(root_origin(), 1001.into(), 0)); + let credits_1001 = + block_credits_to_required_balance(flashbox_runtime::Period::get() * 2, 1001.into()) + + flashbox_runtime::EXISTENTIAL_DEPOSIT + - 1; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should not be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!(assignment.container_chains.get(&1001u32.into()), None,); + }); +} + +#[test] +fn test_credits_with_purchase_can_be_combined() { + ExtBuilder::default() + .with_balances(vec![ + // Alice gets 10k extra tokens for her mapping deposit + (AccountId::from(ALICE), 210_000 * UNIT), + (AccountId::from(BOB), 100_000 * UNIT), + (AccountId::from(CHARLIE), 100_000 * UNIT), + (AccountId::from(DAVE), 100_000 * UNIT), + ]) + .with_collators(vec![ + (AccountId::from(ALICE), 210 * UNIT), + (AccountId::from(BOB), 100 * UNIT), + (AccountId::from(CHARLIE), 100 * UNIT), + (AccountId::from(DAVE), 100 * UNIT), + ]) + .with_config(default_config()) + .build() + .execute_with(|| { + run_to_block(2); + // Assert current slot gets updated + assert_eq!(current_slot(), 1u64); + assert!(current_author() == AccountId::from(BOB)); + + // Alice and Bob collate in our chain + let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string()); + let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string()); + + assert_eq!(authorities(), vec![alice_id, bob_id]); + + assert_ok!(Registrar::register( + origin_of(ALICE.into()), + 1001.into(), + empty_genesis_data() + )); + assert_ok!(DataPreservers::set_boot_nodes( + origin_of(ALICE.into()), + 1001.into(), + dummy_boot_nodes() + )); + assert_ok!(Registrar::mark_valid_for_collating( + root_origin(), + 1001.into() + )); + // Need to reset credits to 0 because now parachains are given free credits on register + assert_ok!(ServicesPayment::set_credits( + root_origin(), + 1001.into(), + flashbox_runtime::Period::get() + )); + let credits_1001 = + block_credits_to_required_balance(flashbox_runtime::Period::get(), 1001.into()) + + flashbox_runtime::EXISTENTIAL_DEPOSIT; + + // Fill the tank + assert_ok!(ServicesPayment::purchase_credits( + origin_of(ALICE.into()), + 1001.into(), + credits_1001 as u128 + )); + + // Assignment should happen after 2 sessions + run_to_session(1u32); + let assignment = CollatorAssignment::collator_container_chain(); + assert!(assignment.container_chains.is_empty()); + run_to_session(2u32); + // Charlie and Dave should be assigned to para 1001 + let assignment = CollatorAssignment::collator_container_chain(); + assert_eq!( + assignment.container_chains[&1001u32.into()], + vec![CHARLIE.into(), DAVE.into()] + ); + }); +} diff --git a/test/suites/common-tanssi/services-payment/test_services_payment.ts b/test/suites/common-tanssi/services-payment/test_services_payment.ts index 29e93800e..28c5fdf61 100644 --- a/test/suites/common-tanssi/services-payment/test_services_payment.ts +++ b/test/suites/common-tanssi/services-payment/test_services_payment.ts @@ -3,8 +3,8 @@ import { describeSuite, expect, beforeAll } from "@moonwall/cli"; import { ApiPromise } from "@polkadot/api"; import { generateKeyringPair, KeyringPair } from "@moonwall/util"; import { jumpSessions } from "util/block"; -import { bnToU8a, stringToU8a } from "@polkadot/util"; -import { blake2AsU8a } from "@polkadot/util-crypto"; +import { paraIdTank } from "util/payment"; + describeSuite({ id: "CT0601", title: "Services payment test suite", @@ -203,14 +203,8 @@ describeSuite({ await polkadotJs.query.system.account(randomAccount.address) ).data.free.toBigInt(); expect(balanceAfter).toBeLessThan(balanceBefore); - // Tank account is b"para" + encode(parahain ID) + trailling zeros - const seedBytes = stringToU8a("modlpy/serpayment"); - const paraIdBytes = bnToU8a(paraId, { bitLength: 32 }); - const combinedBytes = new Uint8Array(seedBytes.length + paraIdBytes.length); - combinedBytes.set(seedBytes); - combinedBytes.set(paraIdBytes, seedBytes.length); - const para_tank = blake2AsU8a(combinedBytes, 256); - const balanceTank = (await polkadotJs.query.system.account(para_tank)).data.free.toBigInt(); + + const balanceTank = (await polkadotJs.query.system.account(paraIdTank(paraId))).data.free.toBigInt(); expect(balanceTank).toBe(requiredBalance); // Check that after 2 sessions, container chain 2000 has collators and is producing blocks @@ -233,7 +227,7 @@ describeSuite({ expect(containerBlockNum3, "container chain 2000 did not create a block").toBeLessThan( containerBlockNum4 ); - const balanceTankAfter = (await polkadotJs.query.system.account(para_tank)).data.free.toBigInt(); + const balanceTankAfter = (await polkadotJs.query.system.account(paraIdTank(paraId))).data.free.toBigInt(); expect(balanceTank, "container chain 2000 created a block without burning any credits").toBeGreaterThan( balanceTankAfter ); From 4a67b0fc2fd15c2d0aa3dcefc8413e5415c6bed1 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 17:40:32 +0100 Subject: [PATCH 14/36] more tests --- ...ices_pament_credit_buying_free_combined.ts | 90 +++++++++++++++++++ .../test_services_payment credit_buying.ts | 88 ++++++++++++++++++ .../services-payment/test_services_payment.ts | 6 +- 3 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts create mode 100644 test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts diff --git a/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts b/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts new file mode 100644 index 000000000..1a87941e6 --- /dev/null +++ b/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts @@ -0,0 +1,90 @@ +import "@tanssi/api-augment"; +import { describeSuite, expect, beforeAll } from "@moonwall/cli"; +import { ApiPromise } from "@polkadot/api"; +import { KeyringPair } from "@moonwall/util"; +import { jumpSessions } from "util/block"; + +describeSuite({ + id: "CT0603", + title: "Services payment test suite", + foundationMethods: "dev", + testCases: ({ it, context }) => { + let polkadotJs: ApiPromise; + let alice: KeyringPair; + const blocksPerSession = 5n; + const paraId2000 = 2000n; + const paraId2001 = 2001n; + const costPerBlock = 1_000_000n; + beforeAll(async () => { + polkadotJs = context.polkadotJs(); + alice = context.keyring.alice; + }); + + it({ + id: "E01", + title: "Collators are unassigned when a container chain does not have enough credits", + test: async function () { + // Create blocks until authorNoting.blockNum does not increase anymore. + // Check that collatorAssignment does not have collators and num credits is less than 2 sessions. + + const tx2000free = polkadotJs.tx.servicesPayment.setCredits(paraId2000, 0n); + const tx2001free = polkadotJs.tx.servicesPayment.setCredits(paraId2001, 0n); + + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2000free).signAsync(alice)]); + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2001free).signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000], + `Container chain ${paraId2000} should have 0 collators` + ).toBeUndefined(); + }, + }); + it({ + id: "E02", + title: "Collators are not assigned when we buy 2 session + ED -1", + test: async function () { + const tx2000OneSession = polkadotJs.tx.servicesPayment.setCredits(paraId2000, blocksPerSession); + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2000OneSession).signAsync(alice)]); + const existentialDeposit = await polkadotJs.consts.balances.existentialDeposit.toBigInt(); + // Now, buy some credits for container chain 2000. we only buy ones session -1 + const purchasedCredits = blocksPerSession * costPerBlock + existentialDeposit - 1n; + // Check that after 2 sessions, container chain 2000 has not collators + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); + await context.createBlock([await tx.signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000], + `Container chain ${paraId2000} should have 0 collators` + ).toBeUndefined(); + }, + }); + it({ + id: "E03", + title: "Collators are assigned when we buy at least 2 session + ED", + test: async function () { + // Now, buy the remaining + const purchasedCredits = 1n; + // Purchase the remaining 1 + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); + await context.createBlock([await tx.signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000].length, + `Container chain ${paraId2000} has 0 collators` + ).toBeGreaterThan(0); + }, + }); + }, +}); diff --git a/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts b/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts new file mode 100644 index 000000000..5d3e02c1e --- /dev/null +++ b/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts @@ -0,0 +1,88 @@ +import "@tanssi/api-augment"; +import { describeSuite, expect, beforeAll } from "@moonwall/cli"; +import { ApiPromise } from "@polkadot/api"; +import { KeyringPair } from "@moonwall/util"; +import { jumpSessions } from "util/block"; + +describeSuite({ + id: "CT0603", + title: "Services payment test suite", + foundationMethods: "dev", + testCases: ({ it, context }) => { + let polkadotJs: ApiPromise; + let alice: KeyringPair; + const blocksPerSession = 5n; + const paraId2000 = 2000n; + const paraId2001 = 2001n; + const costPerBlock = 1_000_000n; + beforeAll(async () => { + polkadotJs = context.polkadotJs(); + alice = context.keyring.alice; + }); + + it({ + id: "E01", + title: "Collators are unassigned when a container chain does not have enough credits", + test: async function () { + // Create blocks until authorNoting.blockNum does not increase anymore. + // Check that collatorAssignment does not have collators and num credits is less than 2 sessions. + + const tx2000free = polkadotJs.tx.servicesPayment.setCredits(paraId2000, 0n); + const tx2001free = polkadotJs.tx.servicesPayment.setCredits(paraId2001, 0n); + + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2000free).signAsync(alice)]); + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2001free).signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000], + `Container chain ${paraId2000} should have 0 collators` + ).toBeUndefined(); + }, + }); + it({ + id: "E02", + title: "Collators are not assigned when we buy 2 session + ED -1", + test: async function () { + const existentialDeposit = await polkadotJs.consts.balances.existentialDeposit.toBigInt(); + // Now, buy some credits for container chain 2000 + const purchasedCredits = 2n * blocksPerSession * costPerBlock + existentialDeposit - 1n; + // Check that after 2 sessions, container chain 2000 has not collators + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); + await context.createBlock([await tx.signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000], + `Container chain ${paraId2000} should have 0 collators` + ).toBeUndefined(); + }, + }); + it({ + id: "E03", + title: "Collators are assigned when we buy at least 2 session + ED", + test: async function () { + // Now, buy the remaining + const purchasedCredits = 1n; + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); + await context.createBlock([await tx.signAsync(alice)]); + + // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + await jumpSessions(context, 2); + + const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); + expect( + collators.toJSON().containerChains[paraId2000].length, + `Container chain ${paraId2000} has 0 collators` + ).toBeGreaterThan(0); + }, + }); + }, +}); diff --git a/test/suites/common-tanssi/services-payment/test_services_payment.ts b/test/suites/common-tanssi/services-payment/test_services_payment.ts index 28c5fdf61..bd2170426 100644 --- a/test/suites/common-tanssi/services-payment/test_services_payment.ts +++ b/test/suites/common-tanssi/services-payment/test_services_payment.ts @@ -203,7 +203,7 @@ describeSuite({ await polkadotJs.query.system.account(randomAccount.address) ).data.free.toBigInt(); expect(balanceAfter).toBeLessThan(balanceBefore); - + const balanceTank = (await polkadotJs.query.system.account(paraIdTank(paraId))).data.free.toBigInt(); expect(balanceTank).toBe(requiredBalance); @@ -227,7 +227,9 @@ describeSuite({ expect(containerBlockNum3, "container chain 2000 did not create a block").toBeLessThan( containerBlockNum4 ); - const balanceTankAfter = (await polkadotJs.query.system.account(paraIdTank(paraId))).data.free.toBigInt(); + const balanceTankAfter = ( + await polkadotJs.query.system.account(paraIdTank(paraId)) + ).data.free.toBigInt(); expect(balanceTank, "container chain 2000 created a block without burning any credits").toBeGreaterThan( balanceTankAfter ); From 8fd33bceb133c93314d8c71911298cd8aae6d287 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 17:51:59 +0100 Subject: [PATCH 15/36] clippy --- runtime/dancebox/tests/integration_test.rs | 6 +++--- runtime/flashbox/tests/integration_test.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index 129b23d34..5dd1c9266 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -5058,7 +5058,7 @@ fn test_ed_plus_two_sessions_purchase_works() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions @@ -5155,7 +5155,7 @@ fn test_ed_plus_two_sessions_minus_1_purchase_fails() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions @@ -5227,7 +5227,7 @@ fn test_credits_with_purchase_can_be_combined() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions diff --git a/runtime/flashbox/tests/integration_test.rs b/runtime/flashbox/tests/integration_test.rs index 15189594c..75e206ff5 100644 --- a/runtime/flashbox/tests/integration_test.rs +++ b/runtime/flashbox/tests/integration_test.rs @@ -2760,7 +2760,7 @@ fn test_ed_plus_two_sessions_purchase_works() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions @@ -2857,7 +2857,7 @@ fn test_ed_plus_two_sessions_minus_1_purchase_fails() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions @@ -2929,7 +2929,7 @@ fn test_credits_with_purchase_can_be_combined() { assert_ok!(ServicesPayment::purchase_credits( origin_of(ALICE.into()), 1001.into(), - credits_1001 as u128 + credits_1001 )); // Assignment should happen after 2 sessions From 2edb516714dd6f3983e0ad746b80895baa0d2733 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 18:12:25 +0100 Subject: [PATCH 16/36] unused variable --- runtime/dancebox/tests/integration_test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index 5dd1c9266..f070bba48 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -26,7 +26,7 @@ use { CollatorSelectionInvulnerablesValue, MigrateBootNodes, MigrateConfigurationParathreads, MigrateInvulnerables, MigrateServicesPaymentAddCredits, }, - BlockProductionCost, RewardsCollatorCommission, + RewardsCollatorCommission, }, dp_core::well_known_keys, frame_support::{assert_noop, assert_ok, BoundedVec}, From 207f6b151b5932eea946271813fc9dbaf6ae5da9 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 18:15:14 +0100 Subject: [PATCH 17/36] more unused --- runtime/dancebox/tests/integration_test.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index f070bba48..9f107bab3 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -42,7 +42,6 @@ use { pallet_registrar_runtime_api::{ runtime_decl_for_registrar_api::RegistrarApi, ContainerChainGenesisData, }, - pallet_services_payment::ProvideBlockProductionCost, parity_scale_codec::Encode, sp_consensus_aura::AURA_ENGINE_ID, sp_core::Get, From d68f8caff5724d9cde4c95fd3820ac867199f15d Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 19:03:12 +0100 Subject: [PATCH 18/36] Benchmark entire on_container_author_noted --- pallets/services-payment/src/benchmarks.rs | 24 +++++++++++++++++++ pallets/services-payment/src/lib.rs | 9 +++---- pallets/services-payment/src/tests.rs | 4 ++++ pallets/services-payment/src/weights.rs | 28 ++++++++++++++++++++++ 4 files changed, 59 insertions(+), 6 deletions(-) diff --git a/pallets/services-payment/src/benchmarks.rs b/pallets/services-payment/src/benchmarks.rs index c304dfc2d..5655a4f10 100644 --- a/pallets/services-payment/src/benchmarks.rs +++ b/pallets/services-payment/src/benchmarks.rs @@ -27,6 +27,7 @@ use { frame_system::RawOrigin, sp_runtime::Saturating, sp_std::prelude::*, + tp_traits::AuthorNotingHook, }; // Build genesis storage according to the mock runtime. @@ -121,5 +122,28 @@ mod benchmarks { assert!(crate::GivenFreeCredits::::get(¶_id).is_some()); } + #[benchmark] + fn on_container_author_noted() { + let para_id = 1001u32; + let block_cost = T::ProvideBlockProductionCost::block_cost(¶_id.into()).0; + let max_credit_stored = T::MaxCreditsStored::get(); + let balance_to_purchase = block_cost.saturating_mul(max_credit_stored.into()); + let caller = create_funded_user::("caller", 1, 1_000_000_000u32); + let existential_deposit = ::minimum_balance(); + assert_ok!(Pallet::::purchase_credits( + RawOrigin::Signed(caller.clone()).into(), + para_id.into(), + balance_to_purchase + existential_deposit + )); + #[block] + { + as AuthorNotingHook>::on_container_author_noted( + &caller, + 0, + para_id.into(), + ); + } + } + impl_benchmark_test_suite!(Pallet, crate::benchmarks::new_test_ext(), crate::mock::Test); } diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 31ea16ebf..0273eec9e 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -290,10 +290,8 @@ impl AuthorNotingHook for Pallet { _block_number: BlockNumber, para_id: ParaId, ) -> Weight { - let total_weight = T::DbWeight::get().reads_writes(1, 1); - if Pallet::::burn_credit_for_para(¶_id).is_err() { - let (amount_to_charge, weight) = T::ProvideBlockProductionCost::block_cost(¶_id); + let (amount_to_charge, _weight) = T::ProvideBlockProductionCost::block_cost(¶_id); match T::Currency::withdraw( &Self::parachain_tank(para_id), amount_to_charge, @@ -309,17 +307,16 @@ impl AuthorNotingHook for Pallet { T::OnChargeForBlock::on_unbalanced(imbalance); } } - total_weight.saturating_add(weight); } - total_weight + T::WeightInfo::on_container_author_noted() } } impl Pallet { /// Derive a derivative account ID from the paraId. pub fn parachain_tank(para_id: ParaId) -> T::AccountId { - let entropy = (b"modlpy/serpayment", para_id).using_encoded(blake2_256); + let entropy = code..using_encoded(blake2_256); Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) .expect("infinite length input; no invalid inputs for type; qed") } diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index 8cded6483..f41857b32 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -264,5 +264,9 @@ fn not_having_enough_tokens_in_tank_should_not_error() { Balances::balance(&crate::Pallet::::parachain_tank(1.into())), 1u128 ); + println!( + "address is {:?}", + crate::Pallet::::parachain_tank(2000.into()) + ) }); } diff --git a/pallets/services-payment/src/weights.rs b/pallets/services-payment/src/weights.rs index 9323b9822..d28639959 100644 --- a/pallets/services-payment/src/weights.rs +++ b/pallets/services-payment/src/weights.rs @@ -55,6 +55,7 @@ pub trait WeightInfo { fn purchase_credits() -> Weight; fn set_credits() -> Weight; fn set_given_free_credits() -> Weight; + fn on_container_author_noted() -> Weight; } /// Weights for pallet_services_payment using the Substrate node and recommended hardware. @@ -93,6 +94,20 @@ impl WeightInfo for SubstrateWeight { Weight::from_parts(2_691_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } + + /// Storage: `ServicesPayment::BlockProductionCredits` (r:1 w:0) + /// Proof: `ServicesPayment::BlockProductionCredits` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn on_container_author_noted() -> Weight { + // Proof Size summary in bytes: + // Measured: `224` + // Estimated: `3593` + // Minimum execution time: 19_043_000 picoseconds. + Weight::from_parts(19_499_000, 3593) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } } // For backwards compatibility and tests @@ -130,4 +145,17 @@ impl WeightInfo for () { Weight::from_parts(2_691_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `ServicesPayment::BlockProductionCredits` (r:1 w:0) + /// Proof: `ServicesPayment::BlockProductionCredits` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn on_container_author_noted() -> Weight { + // Proof Size summary in bytes: + // Measured: `224` + // Estimated: `3593` + // Minimum execution time: 19_043_000 picoseconds. + Weight::from_parts(19_499_000, 3593) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } } From 212ed0f8069180a635c6d84b2ac39dbc5373d70e Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 25 Jan 2024 19:04:54 +0100 Subject: [PATCH 19/36] fix error --- pallets/services-payment/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 0273eec9e..28a488d5c 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -316,7 +316,7 @@ impl AuthorNotingHook for Pallet { impl Pallet { /// Derive a derivative account ID from the paraId. pub fn parachain_tank(para_id: ParaId) -> T::AccountId { - let entropy = code..using_encoded(blake2_256); + let entropy = (b"modlpy/serpayment", para_id).using_encoded(blake2_256); Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) .expect("infinite length input; no invalid inputs for type; qed") } From 6c77973e158586e8e3a41521d9ddc31fd6b4f355 Mon Sep 17 00:00:00 2001 From: girazoki Date: Fri, 26 Jan 2024 09:20:18 +0100 Subject: [PATCH 20/36] put payment file --- test/util/payment.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 test/util/payment.ts diff --git a/test/util/payment.ts b/test/util/payment.ts new file mode 100644 index 000000000..4cfc48cda --- /dev/null +++ b/test/util/payment.ts @@ -0,0 +1,13 @@ +import { bnToU8a, stringToU8a } from "@polkadot/util"; +import { blake2AsU8a } from "@polkadot/util-crypto"; + +// Tank account is blake2(b"modlpy/serpayment" + parahain ID) +export function paraIdTank(paraId: any): any { + const seedBytes = stringToU8a("modlpy/serpayment"); + const paraIdBytes = bnToU8a(paraId, { bitLength: 32 }); + const combinedBytes = new Uint8Array(seedBytes.length + paraIdBytes.length); + combinedBytes.set(seedBytes); + combinedBytes.set(paraIdBytes, seedBytes.length); + const para_tank = blake2AsU8a(combinedBytes, 256); + return para_tank; +} From 248f5535f111bd1d9dd7ffd7c0949a9146513171 Mon Sep 17 00:00:00 2001 From: girazoki Date: Fri, 26 Jan 2024 10:07:54 +0100 Subject: [PATCH 21/36] modify purchase credits --- test/suites/para/test_tanssi_containers.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/suites/para/test_tanssi_containers.ts b/test/suites/para/test_tanssi_containers.ts index 7cf7a8823..d914ddf3e 100644 --- a/test/suites/para/test_tanssi_containers.ts +++ b/test/suites/para/test_tanssi_containers.ts @@ -239,7 +239,10 @@ describeSuite({ const chainSpec2002 = JSON.parse(spec2002); const containerChainGenesisData = chainSpecToContainerChainGenesisData(paraApi, chainSpec2002); const tx1 = paraApi.tx.registrar.register(2002, containerChainGenesisData); - const tx2 = paraApi.tx.servicesPayment.purchaseCredits(2002, 100000, null); + const purchasedCredits =100000n; + const requiredBalance = purchasedCredits * 1_000_000n; + + const tx2 = paraApi.tx.servicesPayment.purchaseCredits(2002, requiredBalance); const tx12 = paraApi.tx.utility.batchAll([tx1, tx2]); await signAndSendAndInclude(tx12, alice); const bootNodes = [ From c42a752563b925105ac506f6b86fd864a9f7d8f2 Mon Sep 17 00:00:00 2001 From: girazoki Date: Fri, 26 Jan 2024 10:17:57 +0100 Subject: [PATCH 22/36] fmt --- test/suites/para/test_tanssi_containers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/suites/para/test_tanssi_containers.ts b/test/suites/para/test_tanssi_containers.ts index d914ddf3e..7a79ce017 100644 --- a/test/suites/para/test_tanssi_containers.ts +++ b/test/suites/para/test_tanssi_containers.ts @@ -239,7 +239,7 @@ describeSuite({ const chainSpec2002 = JSON.parse(spec2002); const containerChainGenesisData = chainSpecToContainerChainGenesisData(paraApi, chainSpec2002); const tx1 = paraApi.tx.registrar.register(2002, containerChainGenesisData); - const purchasedCredits =100000n; + const purchasedCredits = 100000n; const requiredBalance = purchasedCredits * 1_000_000n; const tx2 = paraApi.tx.servicesPayment.purchaseCredits(2002, requiredBalance); From c54f7ca6b4e630906c8c860026405bb1f06c9577 Mon Sep 17 00:00:00 2001 From: girazoki Date: Fri, 26 Jan 2024 12:05:25 +0100 Subject: [PATCH 23/36] dev tests --- .../dev-tanssi/weights/test_set_latest_author_data_weight.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/suites/dev-tanssi/weights/test_set_latest_author_data_weight.ts b/test/suites/dev-tanssi/weights/test_set_latest_author_data_weight.ts index ac8a12e5d..28bee03e3 100644 --- a/test/suites/dev-tanssi/weights/test_set_latest_author_data_weight.ts +++ b/test/suites/dev-tanssi/weights/test_set_latest_author_data_weight.ts @@ -12,8 +12,8 @@ describeSuite({ id: "E01", title: "Weight should be match expected", test: async function () { - const expectedRefTime = new BN(1_064_263_621); - const expectedProofSize = new BN(6_745); + const expectedRefTime = new BN(1_108_762_621); + const expectedProofSize = new BN(9_212); await context.createBlock(); From 04af11e4684b178407ca78d1dae7b999e591d638 Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 29 Jan 2024 15:38:06 +0100 Subject: [PATCH 24/36] implement burn and leave it prepared on deregister --- pallets/services-payment/src/lib.rs | 17 +++++++++++++++++ runtime/dancebox/src/lib.rs | 2 ++ runtime/flashbox/src/lib.rs | 2 ++ 3 files changed, 21 insertions(+) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 28a488d5c..3de33a18f 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -320,4 +320,21 @@ impl Pallet { Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) .expect("infinite length input; no invalid inputs for type; qed") } + + /// Hook to perform things on deregister + pub fn on_deregister(para_id: ParaId) { + // Drain the para-id account from tokens + let parachain_tank_balance = T::Currency::total_balance(&Self::parachain_tank(para_id)); + if !parachain_tank_balance.is_zero() { + if let Ok(imbalance) = T::Currency::withdraw( + &Self::parachain_tank(para_id), + parachain_tank_balance, + WithdrawReasons::FEE, + ExistenceRequirement::AllowDeath, + ) { + // Burn for now, we might be able to pass something to do with this + drop(imbalance); + } + } + } } diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index f0e539ad9..f772092d6 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -893,6 +893,8 @@ impl RegistrarHooks for DanceboxRegistrarHooks { // Remove bootnodes from pallet_data_preservers DataPreservers::para_deregistered(para_id); + ServicesPayment::on_deregister(para_id); + Weight::default() } diff --git a/runtime/flashbox/src/lib.rs b/runtime/flashbox/src/lib.rs index 2c699a7f0..6d15e2bef 100644 --- a/runtime/flashbox/src/lib.rs +++ b/runtime/flashbox/src/lib.rs @@ -761,6 +761,8 @@ impl RegistrarHooks for FlashboxRegistrarHooks { // Remove bootnodes from pallet_data_preservers DataPreservers::para_deregistered(para_id); + ServicesPayment::on_deregister(para_id); + Weight::default() } From 742aebf7ea50e4cadab14db137c8640f32901b9b Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 29 Jan 2024 16:24:23 +0100 Subject: [PATCH 25/36] add test to see we remove money form tank on deregister --- ...test_service_payment_removes_tank_money.ts | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts diff --git a/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts b/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts new file mode 100644 index 000000000..b04196ce6 --- /dev/null +++ b/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts @@ -0,0 +1,47 @@ +import "@tanssi/api-augment"; +import { describeSuite, expect, beforeAll } from "@moonwall/cli"; +import { ApiPromise } from "@polkadot/api"; +import { KeyringPair } from "@moonwall/util"; +import { jumpSessions } from "util/block"; +import { paraIdTank } from "util/payment"; + +describeSuite({ + id: "CT0604", + title: "Services payment test suite", + foundationMethods: "dev", + testCases: ({ it, context }) => { + let polkadotJs: ApiPromise; + let alice: KeyringPair; + const blocksPerSession = 5n; + const paraId2001 = 2001n; + const costPerBlock = 1_000_000n; + beforeAll(async () => { + polkadotJs = context.polkadotJs(); + alice = context.keyring.alice; + const tx2000OneSession = polkadotJs.tx.servicesPayment.setCredits(paraId2001, 0); + await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2000OneSession).signAsync(alice)]); + const existentialDeposit = await polkadotJs.consts.balances.existentialDeposit.toBigInt(); + // Now, buy some credits for container chain 2001 + const purchasedCredits = blocksPerSession * costPerBlock + existentialDeposit; + const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2001, purchasedCredits); + await context.createBlock([await tx.signAsync(alice)]); + const balanceTank = (await polkadotJs.query.system.account(paraIdTank(paraId2001))).data.free.toBigInt(); + expect(balanceTank, `Tank should have been filled`).toBe(purchasedCredits); + }); + it({ + id: "E01", + title: "We deregister 2000, check the issuance drops", + test: async function () { + // We deregister the chain + const deregister2001 = polkadotJs.tx.sudo.sudo(polkadotJs.tx.registrar.deregister(paraId2001)); + await context.createBlock([await deregister2001.signAsync(alice)]); + // Check that after 2 sessions, tank is empty and chain is deregistered + await jumpSessions(context, 2); + const balanceTank = ( + await polkadotJs.query.system.account(paraIdTank(paraId2001)) + ).data.free.toBigInt(); + expect(balanceTank, `Tank should have been removed`).toBe(0n); + }, + }); + }, +}); From 51556a51398f30d95c42756c2d82a2f71409c6ca Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 29 Jan 2024 17:11:06 +0100 Subject: [PATCH 26/36] move things to pallet-service-payment and rename function --- pallets/services-payment/src/lib.rs | 5 ++++- runtime/dancebox/src/lib.rs | 10 +--------- runtime/flashbox/src/lib.rs | 10 +--------- 3 files changed, 6 insertions(+), 19 deletions(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 3de33a18f..11d516cb9 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -322,7 +322,7 @@ impl Pallet { } /// Hook to perform things on deregister - pub fn on_deregister(para_id: ParaId) { + pub fn para_deregistered(para_id: ParaId) { // Drain the para-id account from tokens let parachain_tank_balance = T::Currency::total_balance(&Self::parachain_tank(para_id)); if !parachain_tank_balance.is_zero() { @@ -336,5 +336,8 @@ impl Pallet { drop(imbalance); } } + + // Clean credits + BlockProductionCredits::::remove(para_id); } } diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index f772092d6..9dab74778 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -882,18 +882,10 @@ impl RegistrarHooks for DanceboxRegistrarHooks { e, ); } - // Remove all credits from pallet_services_payment - if let Err(e) = ServicesPayment::set_credits(RuntimeOrigin::root(), para_id, 0) { - log::warn!( - "Failed to set_credits to 0 after para id {} deregistered: {:?}", - u32::from(para_id), - e, - ); - } // Remove bootnodes from pallet_data_preservers DataPreservers::para_deregistered(para_id); - ServicesPayment::on_deregister(para_id); + ServicesPayment::para_deregistered(para_id); Weight::default() } diff --git a/runtime/flashbox/src/lib.rs b/runtime/flashbox/src/lib.rs index 6d15e2bef..381931abb 100644 --- a/runtime/flashbox/src/lib.rs +++ b/runtime/flashbox/src/lib.rs @@ -750,18 +750,10 @@ impl RegistrarHooks for FlashboxRegistrarHooks { e, ); } - // Remove all credits from pallet_services_payment - if let Err(e) = ServicesPayment::set_credits(RuntimeOrigin::root(), para_id, 0) { - log::warn!( - "Failed to set_credits to 0 after para id {} deregistered: {:?}", - u32::from(para_id), - e, - ); - } // Remove bootnodes from pallet_data_preservers DataPreservers::para_deregistered(para_id); - ServicesPayment::on_deregister(para_id); + ServicesPayment::para_deregistered(para_id); Weight::default() } From a3049bf884b89c309cda516fe685c5d8ea937e3b Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 29 Jan 2024 17:37:50 +0100 Subject: [PATCH 27/36] make sure we are burning --- .../test_service_payment_removes_tank_money.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts b/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts index b04196ce6..3a1475d2e 100644 --- a/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts +++ b/test/suites/common-tanssi/services-payment/test_service_payment_removes_tank_money.ts @@ -2,7 +2,7 @@ import "@tanssi/api-augment"; import { describeSuite, expect, beforeAll } from "@moonwall/cli"; import { ApiPromise } from "@polkadot/api"; import { KeyringPair } from "@moonwall/util"; -import { jumpSessions } from "util/block"; +import { jumpSessions, fetchIssuance } from "util/block"; import { paraIdTank } from "util/payment"; describeSuite({ @@ -15,6 +15,7 @@ describeSuite({ const blocksPerSession = 5n; const paraId2001 = 2001n; const costPerBlock = 1_000_000n; + let balanceTankBefore; beforeAll(async () => { polkadotJs = context.polkadotJs(); alice = context.keyring.alice; @@ -25,8 +26,8 @@ describeSuite({ const purchasedCredits = blocksPerSession * costPerBlock + existentialDeposit; const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2001, purchasedCredits); await context.createBlock([await tx.signAsync(alice)]); - const balanceTank = (await polkadotJs.query.system.account(paraIdTank(paraId2001))).data.free.toBigInt(); - expect(balanceTank, `Tank should have been filled`).toBe(purchasedCredits); + balanceTankBefore = (await polkadotJs.query.system.account(paraIdTank(paraId2001))).data.free.toBigInt(); + expect(balanceTankBefore, `Tank should have been filled`).toBe(purchasedCredits); }); it({ id: "E01", @@ -41,6 +42,16 @@ describeSuite({ await polkadotJs.query.system.account(paraIdTank(paraId2001)) ).data.free.toBigInt(); expect(balanceTank, `Tank should have been removed`).toBe(0n); + + const blockNumber = (await polkadotJs.rpc.chain.getHeader()).number.toNumber(); + const apiAtBlockBefore = await polkadotJs.at(await polkadotJs.rpc.chain.getBlockHash(blockNumber - 1)); + const supplyBefore = (await apiAtBlockBefore.query.balances.totalIssuance()).toBigInt(); + const supplyAfter = (await polkadotJs.query.balances.totalIssuance()).toBigInt(); + const blockIssuance = await fetchIssuance(await polkadotJs.query.system.events()); + const issuanceDiff = supplyAfter - supplyBefore; + expect(issuanceDiff, `Tank should have been removed`).toBe( + blockIssuance.amount.toBigInt() - balanceTankBefore + ); }, }); }, From 6838e393c76fc37551d8605e7151cf2897c44989 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 30 Jan 2024 08:40:51 +0100 Subject: [PATCH 28/36] free credits rename --- runtime/dancebox/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index 9dab74778..d6f74c004 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -721,11 +721,13 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { let free_credits = pallet_services_payment::BlockProductionCredits::::get(para_id) .unwrap_or_default(); - let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); // Return if we can survive with free credits - if remaining_credits.is_zero() { + if free_credits >= credits_for_2_sessions { return true } + + let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); + let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); // let's check if we can withdraw let remaining_to_pay = (remaining_credits as u128).saturating_mul(block_production_costs); From c9f66d21b4899e4e336fe25497ec05e5cca6c401 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 30 Jan 2024 08:56:04 +0100 Subject: [PATCH 29/36] clippy --- runtime/flashbox/src/lib.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/runtime/flashbox/src/lib.rs b/runtime/flashbox/src/lib.rs index 381931abb..71da12364 100644 --- a/runtime/flashbox/src/lib.rs +++ b/runtime/flashbox/src/lib.rs @@ -76,7 +76,7 @@ use { sp_core::{crypto::KeyTypeId, Decode, Encode, Get, MaxEncodedLen, OpaqueMetadata}, sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Zero}, + traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, AccountId32, ApplyExtrinsicResult, }, @@ -582,11 +582,13 @@ impl RemoveParaIdsWithNoCredits for RemoveParaIdsWithNoCreditsImpl { let free_credits = pallet_services_payment::BlockProductionCredits::::get(para_id) .unwrap_or_default(); - let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); // Return if we can survive with free credits - if remaining_credits.is_zero() { + if free_credits >= credits_for_2_sessions { return true } + + let remaining_credits = credits_for_2_sessions.saturating_sub(free_credits); + let (block_production_costs, _) = ::ProvideBlockProductionCost::block_cost(para_id); // let's check if we can withdraw let remaining_to_pay = (remaining_credits as u128).saturating_mul(block_production_costs); From 3f751520c6e3205264ffc369625470b026d20641 Mon Sep 17 00:00:00 2001 From: girazoki Date: Tue, 30 Jan 2024 10:01:49 +0100 Subject: [PATCH 30/36] more clippy --- runtime/dancebox/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/dancebox/src/lib.rs b/runtime/dancebox/src/lib.rs index d6f74c004..c56978b8a 100644 --- a/runtime/dancebox/src/lib.rs +++ b/runtime/dancebox/src/lib.rs @@ -85,7 +85,7 @@ use { sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ - AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT, Zero, + AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT, }, transaction_validity::{TransactionSource, TransactionValidity}, AccountId32, ApplyExtrinsicResult, From 00d90b24fe664302e4e784375f4421c1de941cac Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 1 Feb 2024 11:39:18 +0100 Subject: [PATCH 31/36] burn free credit para --- pallets/services-payment/src/lib.rs | 4 ++-- pallets/services-payment/src/tests.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 11d516cb9..7e7fb2c80 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -195,7 +195,7 @@ pub mod pallet { impl Pallet { /// Burn a credit for the given para. Deducts one credit if possible, errors otherwise. - pub fn burn_credit_for_para(para_id: &ParaId) -> DispatchResultWithPostInfo { + pub fn burn_free_credit_for_para(para_id: &ParaId) -> DispatchResultWithPostInfo { let existing_credits = BlockProductionCredits::::get(para_id).unwrap_or(BlockNumberFor::::zero()); @@ -290,7 +290,7 @@ impl AuthorNotingHook for Pallet { _block_number: BlockNumber, para_id: ParaId, ) -> Weight { - if Pallet::::burn_credit_for_para(¶_id).is_err() { + if Pallet::::burn_free_credit_for_para(¶_id).is_err() { let (amount_to_charge, _weight) = T::ProvideBlockProductionCost::block_cost(¶_id); match T::Currency::withdraw( &Self::parachain_tank(para_id), diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index f41857b32..088ced254 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -84,7 +84,7 @@ fn purchase_credits_fails_with_insufficient_balance() { fn burn_credit_fails_with_no_credits() { ExtBuilder::default().build().execute_with(|| { assert_err!( - PaymentServices::burn_credit_for_para(&1u32.into()), + PaymentServices::burn_free_credit_for_para(&1u32.into()), pallet_services_payment::Error::::InsufficientCredits, ); }); @@ -105,12 +105,12 @@ fn burn_credit_works() { // should succeed and burn one assert_eq!(>::get(para_id), Some(1u64)); - assert_ok!(PaymentServices::burn_credit_for_para(¶_id)); + assert_ok!(PaymentServices::burn_free_credit_for_para(¶_id)); assert_eq!(>::get(para_id), Some(0u64)); // now should fail assert_err!( - PaymentServices::burn_credit_for_para(¶_id), + PaymentServices::burn_free_credit_for_para(¶_id), pallet_services_payment::Error::::InsufficientCredits, ); }); @@ -132,7 +132,7 @@ fn burn_credit_fails_for_wrong_para() { // fails for wrong para let wrong_para_id = 2.into(); assert_err!( - PaymentServices::burn_credit_for_para(&wrong_para_id), + PaymentServices::burn_free_credit_for_para(&wrong_para_id), pallet_services_payment::Error::::InsufficientCredits, ); }); From f5a4c4a57e335f5fea9272047391c8bf9855ae9b Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 1 Feb 2024 13:52:20 +0100 Subject: [PATCH 32/36] change to keep alive --- pallets/services-payment/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 7e7fb2c80..132e94d0e 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -296,7 +296,7 @@ impl AuthorNotingHook for Pallet { &Self::parachain_tank(para_id), amount_to_charge, WithdrawReasons::FEE, - ExistenceRequirement::AllowDeath, + ExistenceRequirement::KeepAlive, ) { Err(e) => log::warn!( "Failed to withdraw credits for container chain {}: {:?}", From 0d65172b6eeeaa13211e2fecb468abdb64d67778 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 1 Feb 2024 14:09:27 +0100 Subject: [PATCH 33/36] fix test --- pallets/services-payment/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index 088ced254..1631e4b01 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -214,7 +214,7 @@ fn credits_should_be_substracted_from_tank_if_no_free_credits() { } #[test] -fn credits_should_be_substracted_from_tank_even_if_it_involves_death() { +fn credits_should_not_be_substracted_from_tank_if_it_involves_death() { ExtBuilder::default() .with_balances([(ALICE, 2_000)].into()) .build() @@ -235,7 +235,7 @@ fn credits_should_be_substracted_from_tank_even_if_it_involves_death() { assert_eq!( Balances::balance(&crate::Pallet::::parachain_tank(1.into())), - 0u128 + 100u128 ); }); } From a5947df93d7078d34fac79b796938703e72680a8 Mon Sep 17 00:00:00 2001 From: girazoki Date: Thu, 1 Feb 2024 14:36:42 +0100 Subject: [PATCH 34/36] free credits getter fixed --- pallets/services-payment/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/services-payment/src/lib.rs b/pallets/services-payment/src/lib.rs index 132e94d0e..6fa73ade4 100644 --- a/pallets/services-payment/src/lib.rs +++ b/pallets/services-payment/src/lib.rs @@ -111,7 +111,7 @@ pub mod pallet { } #[pallet::storage] - #[pallet::getter(fn collator_commission)] + #[pallet::getter(fn free_block_production_credits)] pub type BlockProductionCredits = StorageMap<_, Blake2_128Concat, ParaId, BlockNumberFor, OptionQuery>; From 1c1ca545825576ad1abad041eb667580d069a25f Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 5 Feb 2024 11:59:15 +0100 Subject: [PATCH 35/36] final review --- runtime/dancebox/tests/integration_test.rs | 7 +- runtime/flashbox/tests/integration_test.rs | 2 +- ...ices_pament_credit_buying_free_combined.ts | 2 +- .../test_services_payment credit_buying.ts | 88 ------------------- 4 files changed, 3 insertions(+), 96 deletions(-) delete mode 100644 test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts diff --git a/runtime/dancebox/tests/integration_test.rs b/runtime/dancebox/tests/integration_test.rs index c38bf22bd..970468e5d 100644 --- a/runtime/dancebox/tests/integration_test.rs +++ b/runtime/dancebox/tests/integration_test.rs @@ -4637,11 +4637,6 @@ fn test_can_buy_credits_before_registering_para() { let balance_after = System::account(AccountId::from(ALICE)).data.free; // Now parachain tank should have this amount - println!("encoded {:?}", (b"modlpy/serpayment", 2000u32).encode()); - println!( - "parachain tank address {:?}", - ServicesPayment::parachain_tank(2000.into()) - ); let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into())) .data .free; @@ -5256,7 +5251,7 @@ fn test_credits_with_purchase_can_be_combined() { root_origin(), 1001.into() )); - // Need to reset credits to 0 because now parachains are given free credits on register + // Set 1 session of free credits and purchase 1 session of credits assert_ok!(ServicesPayment::set_credits( root_origin(), 1001.into(), diff --git a/runtime/flashbox/tests/integration_test.rs b/runtime/flashbox/tests/integration_test.rs index 3b9fa77a6..2309f5b3f 100644 --- a/runtime/flashbox/tests/integration_test.rs +++ b/runtime/flashbox/tests/integration_test.rs @@ -2960,7 +2960,7 @@ fn test_credits_with_purchase_can_be_combined() { root_origin(), 1001.into() )); - // Need to reset credits to 0 because now parachains are given free credits on register + // Set 1 session of free credits and purchase 1 session of credits assert_ok!(ServicesPayment::set_credits( root_origin(), 1001.into(), diff --git a/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts b/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts index 1a87941e6..886e3bf53 100644 --- a/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts +++ b/test/suites/common-tanssi/services-payment/test_services_pament_credit_buying_free_combined.ts @@ -56,7 +56,7 @@ describeSuite({ const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); await context.createBlock([await tx.signAsync(alice)]); - // Check that after 2 sessions, container chain 2000 has collators and is producing blocks + // Check that after 2 sessions, container chain 2000 has 0 collators and is not producing blocks await jumpSessions(context, 2); const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); diff --git a/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts b/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts deleted file mode 100644 index 5d3e02c1e..000000000 --- a/test/suites/common-tanssi/services-payment/test_services_payment credit_buying.ts +++ /dev/null @@ -1,88 +0,0 @@ -import "@tanssi/api-augment"; -import { describeSuite, expect, beforeAll } from "@moonwall/cli"; -import { ApiPromise } from "@polkadot/api"; -import { KeyringPair } from "@moonwall/util"; -import { jumpSessions } from "util/block"; - -describeSuite({ - id: "CT0603", - title: "Services payment test suite", - foundationMethods: "dev", - testCases: ({ it, context }) => { - let polkadotJs: ApiPromise; - let alice: KeyringPair; - const blocksPerSession = 5n; - const paraId2000 = 2000n; - const paraId2001 = 2001n; - const costPerBlock = 1_000_000n; - beforeAll(async () => { - polkadotJs = context.polkadotJs(); - alice = context.keyring.alice; - }); - - it({ - id: "E01", - title: "Collators are unassigned when a container chain does not have enough credits", - test: async function () { - // Create blocks until authorNoting.blockNum does not increase anymore. - // Check that collatorAssignment does not have collators and num credits is less than 2 sessions. - - const tx2000free = polkadotJs.tx.servicesPayment.setCredits(paraId2000, 0n); - const tx2001free = polkadotJs.tx.servicesPayment.setCredits(paraId2001, 0n); - - await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2000free).signAsync(alice)]); - await context.createBlock([await polkadotJs.tx.sudo.sudo(tx2001free).signAsync(alice)]); - - // Check that after 2 sessions, container chain 2000 has collators and is producing blocks - await jumpSessions(context, 2); - - const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); - expect( - collators.toJSON().containerChains[paraId2000], - `Container chain ${paraId2000} should have 0 collators` - ).toBeUndefined(); - }, - }); - it({ - id: "E02", - title: "Collators are not assigned when we buy 2 session + ED -1", - test: async function () { - const existentialDeposit = await polkadotJs.consts.balances.existentialDeposit.toBigInt(); - // Now, buy some credits for container chain 2000 - const purchasedCredits = 2n * blocksPerSession * costPerBlock + existentialDeposit - 1n; - // Check that after 2 sessions, container chain 2000 has not collators - const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); - await context.createBlock([await tx.signAsync(alice)]); - - // Check that after 2 sessions, container chain 2000 has collators and is producing blocks - await jumpSessions(context, 2); - - const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); - expect( - collators.toJSON().containerChains[paraId2000], - `Container chain ${paraId2000} should have 0 collators` - ).toBeUndefined(); - }, - }); - it({ - id: "E03", - title: "Collators are assigned when we buy at least 2 session + ED", - test: async function () { - // Now, buy the remaining - const purchasedCredits = 1n; - // Check that after 2 sessions, container chain 2000 has collators and is producing blocks - const tx = polkadotJs.tx.servicesPayment.purchaseCredits(paraId2000, purchasedCredits); - await context.createBlock([await tx.signAsync(alice)]); - - // Check that after 2 sessions, container chain 2000 has collators and is producing blocks - await jumpSessions(context, 2); - - const collators = await polkadotJs.query.collatorAssignment.collatorContainerChain(); - expect( - collators.toJSON().containerChains[paraId2000].length, - `Container chain ${paraId2000} has 0 collators` - ).toBeGreaterThan(0); - }, - }); - }, -}); From 1e0066c6e9748267d38aeeb0cbdec02c27561b7f Mon Sep 17 00:00:00 2001 From: girazoki Date: Mon, 5 Feb 2024 12:10:41 +0100 Subject: [PATCH 36/36] remove lsat print --- pallets/services-payment/src/tests.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pallets/services-payment/src/tests.rs b/pallets/services-payment/src/tests.rs index 1631e4b01..0b2ec9e41 100644 --- a/pallets/services-payment/src/tests.rs +++ b/pallets/services-payment/src/tests.rs @@ -264,9 +264,5 @@ fn not_having_enough_tokens_in_tank_should_not_error() { Balances::balance(&crate::Pallet::::parachain_tank(1.into())), 1u128 ); - println!( - "address is {:?}", - crate::Pallet::::parachain_tank(2000.into()) - ) }); }