Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pallet services payment to runtime #314

Merged
merged 26 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a75b471
Add services payment pallet to runtime, using mock impl
tmpolaczyk Nov 3, 2023
66c1c3a
Burn one credit when a container chain has a new highest block
tmpolaczyk Nov 3, 2023
1ab4997
Do not assign collators to container chains with no credits
tmpolaczyk Nov 6, 2023
a6eebde
typescript-api
tmpolaczyk Nov 6, 2023
e77a27d
Fix zombienet tests
tmpolaczyk Nov 6, 2023
ec59dfb
Add integration tests
tmpolaczyk Nov 7, 2023
e71302f
fix integration tests
girazoki Nov 8, 2023
f435cbf
Fix pr comments
tmpolaczyk Nov 8, 2023
f9ae0ad
Add migration that gives credits to existing parachains
tmpolaczyk Nov 8, 2023
a9da032
Set MaxCreditsStored to 60 days worth of blocks
tmpolaczyk Nov 8, 2023
2b1ca7e
Add benchmarks to pallet_services_payment
tmpolaczyk Nov 8, 2023
72c11d9
Merge remote-tracking branch 'origin/master' into tomasz-pallet-servi…
tmpolaczyk Nov 8, 2023
002fd05
typescript-api
tmpolaczyk Nov 8, 2023
680c132
Merge remote-tracking branch 'origin/master' into tomasz-pallet-servi…
tmpolaczyk Nov 13, 2023
de5fe07
Add set_credits extrinsic for root, and unit tests
tmpolaczyk Nov 13, 2023
613cbd6
typescript-api
tmpolaczyk Nov 13, 2023
3783298
Add dev_tanssi tests
tmpolaczyk Nov 13, 2023
ddf033a
fmt
tmpolaczyk Nov 13, 2023
e36c5c7
Merge remote-tracking branch 'origin/master' into tomasz-pallet-servi…
tmpolaczyk Nov 13, 2023
1494412
Fix collator-assignment benchmark and weights
tmpolaczyk Nov 13, 2023
dea9b94
Fix comments
tmpolaczyk Nov 13, 2023
a8b9b0a
Fix ts tests
tmpolaczyk Nov 13, 2023
ae7d451
Fix collator assignment new_session weight hint
tmpolaczyk Nov 13, 2023
be1321d
impl AuthorNotingHook for tuples
tmpolaczyk Nov 13, 2023
6d06611
Merge remote-tracking branch 'origin/master' into tomasz-pallet-servi…
tmpolaczyk Nov 15, 2023
ef69cde
Undo accidental change to benchmarking script
tmpolaczyk Nov 15, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pallet-invulnerables = { path = "pallets/invulnerables", default-features = fals
pallet-pooled-staking = { path = "pallets/pooled-staking", default-features = false }
pallet-registrar = { path = "pallets/registrar", default-features = false }
pallet-registrar-runtime-api = { path = "pallets/registrar/rpc/runtime-api", default-features = false }
pallet-services-payment = { path = "pallets/services-payment", default-features = false }

ccp-authorities-noting-inherent = { path = "container-chains/primitives/authorities-noting-inherent", default-features = false }
ccp-xcm = { path = "container-chains/primitives/xcm", default-features = false }
Expand Down
43 changes: 24 additions & 19 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use {
cumulus_primitives_core::ParaId,
dancebox_runtime::{
prod_or_fast, AccountId, MaintenanceModeConfig, MigrationsConfig, PolkadotXcmConfig,
RegistrarConfig, Signature, SudoConfig,
RegistrarConfig, ServicesPaymentConfig, Signature, SudoConfig,
},
nimbus_primitives::NimbusId,
pallet_configuration::HostConfiguration,
Expand Down Expand Up @@ -293,6 +293,27 @@ fn testnet_genesis(
mock_container_chains: &[ParaId],
configuration: pallet_configuration::GenesisConfig<dancebox_runtime::Runtime>,
) -> dancebox_runtime::RuntimeGenesisConfig {
let para_ids: Vec<_> = container_chains
.iter()
.map(|x| {
container_chain_genesis_data_from_path(x).unwrap_or_else(|e| {
panic!(
"Failed to build genesis data for container chain {:?}: {}",
x, e
)
})
})
.chain(
mock_container_chains
.iter()
.map(|x| (*x, mock_container_chain_genesis_data(*x), vec![])),
)
.collect();
// Assign max block credits to all container chains registered in genesis
tmpolaczyk marked this conversation as resolved.
Show resolved Hide resolved
let para_id_credits: Vec<_> = para_ids
.iter()
.map(|(para_id, _genesis_data, _boot_nodes)| (*para_id, u32::MAX))
.collect();
dancebox_runtime::RuntimeGenesisConfig {
system: dancebox_runtime::SystemConfig {
code: dancebox_runtime::WASM_BINARY
Expand Down Expand Up @@ -328,24 +349,8 @@ fn testnet_genesis(
},
parachain_system: Default::default(),
configuration,
registrar: RegistrarConfig {
para_ids: container_chains
.iter()
.map(|x| {
container_chain_genesis_data_from_path(x).unwrap_or_else(|e| {
panic!(
"Failed to build genesis data for container chain {:?}: {}",
x, e
)
})
})
.chain(
mock_container_chains
.iter()
.map(|x| (*x, mock_container_chain_genesis_data(*x), vec![])),
)
.collect(),
},
registrar: RegistrarConfig { para_ids },
services_payment: ServicesPaymentConfig { para_id_credits },
sudo: SudoConfig {
key: Some(root_key),
},
Expand Down
7 changes: 6 additions & 1 deletion pallets/collator-assignment/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use {
tp_collator_assignment::AssignedCollators,
tp_traits::{
GetContainerChainAuthor, GetHostConfiguration, GetSessionContainerChains, ParaId,
RemoveInvulnerables, ShouldRotateAllCollators, Slot,
RemoveInvulnerables, RemoveParaIdsWithNoCredits, ShouldRotateAllCollators, Slot,
},
};

Expand Down Expand Up @@ -97,6 +97,7 @@ pub mod pallet {
type ShouldRotateAllCollators: ShouldRotateAllCollators<Self::SessionIndex>;
type GetRandomnessForNextBlock: GetRandomnessForNextBlock<BlockNumberFor<Self>>;
type RemoveInvulnerables: RemoveInvulnerables<Self::AccountId>;
type RemoveParaIdsWithNoCredits: RemoveParaIdsWithNoCredits;
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
}
Expand Down Expand Up @@ -161,6 +162,10 @@ pub mod pallet {
// We get the containerChains that we will have at the target session
let mut container_chain_ids =
T::ContainerChains::session_container_chains(target_session_index);
// Remove the containerChains that do not have enough credits for block production
T::RemoveParaIdsWithNoCredits::remove_para_ids_with_no_credits(
girazoki marked this conversation as resolved.
Show resolved Hide resolved
&mut container_chain_ids,
);

// If the random_seed is all zeros, we don't shuffle the list of collators nor the list
// of container chains.
Expand Down
12 changes: 11 additions & 1 deletion pallets/collator-assignment/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use {
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
},
tp_traits::{ParaId, RemoveInvulnerables},
tp_traits::{ParaId, RemoveInvulnerables, RemoveParaIdsWithNoCredits},
};

type Block = frame_system::mocking::MockBlock<Test>;
Expand Down Expand Up @@ -193,6 +193,7 @@ impl pallet_collator_assignment::Config for Test {
type ShouldRotateAllCollators = RotateCollatorsEveryNSessions<CollatorRotationSessionPeriod>;
type GetRandomnessForNextBlock = MockGetRandomnessForNextBlock;
type RemoveInvulnerables = RemoveAccountIdsAbove100;
type RemoveParaIdsWithNoCredits = RemoveParaIdsAbove5000;
type WeightInfo = ();
}

Expand Down Expand Up @@ -247,3 +248,12 @@ impl RemoveInvulnerables<u64> for RemoveAccountIdsAbove100 {
invulnerables
}
}

/// Any ParaId >= 5000 will be considered to not have enough credits
pub struct RemoveParaIdsAbove5000;

impl RemoveParaIdsWithNoCredits for RemoveParaIdsAbove5000 {
fn remove_para_ids_with_no_credits(para_ids: &mut Vec<ParaId>) {
para_ids.retain(|para_id| *para_id <= ParaId::from(5000));
}
}
4 changes: 2 additions & 2 deletions pallets/services-payment/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ 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-runtime = { workspace = true }

cumulus-primitives-core = { workspace = true }
tp-traits = { workspace = true }

[dev-dependencies]
pallet-balances = { workspace = true }
Expand All @@ -36,3 +35,4 @@ std = [
"sp-runtime/std",
]
try-runtime = [ "frame-support/try-runtime" ]
runtime-benchmarks = []
38 changes: 34 additions & 4 deletions pallets/services-payment/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ use {
traits::Currency,
},
frame_system::pallet_prelude::*,
scale_info::prelude::vec::Vec,
tp_traits::{AuthorNotingHook, BlockNumber},
};

#[cfg(test)]
Expand Down Expand Up @@ -181,21 +183,24 @@ pub mod pallet {

#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
_phantom: PhantomData<T>,
pub para_id_credits: Vec<(ParaId, BlockNumberFor<T>)>,
}

#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
_phantom: Default::default(),
para_id_credits: Default::default(),
}
}
}

#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {}
fn build(&self) {
for (para_id, credits) in &self.para_id_credits {
BlockProductionCredits::<T>::insert(para_id, credits);
}
}
}
}

Expand All @@ -219,3 +224,28 @@ pub trait OnChargeForBlockCredit<T: Config> {
pub trait ProvideBlockProductionCost<T: Config> {
fn block_cost(para_id: &ParaId) -> (BalanceOf<T>, Weight);
}

tmpolaczyk marked this conversation as resolved.
Show resolved Hide resolved
// This function should only be used to **reward** a container author.
// There will be no additional check other than checking if we have already
// rewarded this author for **in this tanssi block**
// Any additional check should be done in the calling function
// TODO: consider passing a vector here
impl<T: Config> AuthorNotingHook<T::AccountId> for Pallet<T> {
fn on_container_author_noted(
_author: &T::AccountId,
_block_number: BlockNumber,
para_id: ParaId,
) -> Weight {
let total_weight = T::DbWeight::get().reads_writes(1, 1);

if let Err(e) = Pallet::<T>::burn_credit_for_para(&para_id) {
log::warn!(
"Failed to burn credits for container chain {}: {:?}",
u32::from(para_id),
e
);
}

total_weight
}
}
18 changes: 9 additions & 9 deletions pallets/services-payment/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@
//! Using those two requirements we can select who the author was based on the collators assigned
//! to that containerChain, by simply assigning the slot position.

use frame_support::traits::{Currency, WithdrawReasons};

use {
crate::{self as payment_services_pallet, OnChargeForBlockCredit, ProvideBlockProductionCost},
crate::{self as pallet_services_payment, OnChargeForBlockCredit, ProvideBlockProductionCost},
cumulus_primitives_core::ParaId,
frame_support::{
pallet_prelude::*,
parameter_types,
traits::{tokens::ExistenceRequirement, ConstU32, ConstU64, Everything},
traits::{
tokens::ExistenceRequirement, ConstU32, ConstU64, Currency, Everything, WithdrawReasons,
},
},
sp_core::H256,
sp_runtime::{
Expand All @@ -54,7 +54,7 @@ frame_support::construct_runtime!(
{
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
PaymentServices: payment_services_pallet::{Pallet, Call, Config<T>, Storage, Event<T>}
PaymentServices: pallet_services_payment::{Pallet, Call, Config<T>, Storage, Event<T>}
}
);

Expand Down Expand Up @@ -108,7 +108,7 @@ parameter_types! {
pub const MaxCreditsStored: u64 = 5;
}

impl payment_services_pallet::Config for Test {
impl pallet_services_payment::Config for Test {
type RuntimeEvent = RuntimeEvent;
type OnChargeForBlockCredit = ChargeForBlockCredit<Test>;
type Currency = Balances;
Expand All @@ -123,7 +123,7 @@ impl OnChargeForBlockCredit<Test> for ChargeForBlockCredit<Test> {
_para_id: &ParaId,
_credits: u64,
fee: u128,
) -> Result<(), payment_services_pallet::Error<Test>> {
) -> Result<(), pallet_services_payment::Error<Test>> {
use frame_support::traits::tokens::imbalance::Imbalance;

let result = Balances::withdraw(
Expand All @@ -133,7 +133,7 @@ impl OnChargeForBlockCredit<Test> for ChargeForBlockCredit<Test> {
ExistenceRequirement::AllowDeath,
);
let imbalance = result
.map_err(|_| payment_services_pallet::Error::InsufficientFundsToPurchaseCredits)?;
.map_err(|_| pallet_services_payment::Error::InsufficientFundsToPurchaseCredits)?;

if imbalance.peek() != fee {
panic!("withdrawn balance incorrect");
Expand Down Expand Up @@ -178,7 +178,7 @@ impl ExtBuilder {
}
}

pub(crate) fn events() -> Vec<payment_services_pallet::Event<Test>> {
pub(crate) fn events() -> Vec<pallet_services_payment::Event<Test>> {
System::events()
.into_iter()
.map(|r| r.event)
Expand Down
22 changes: 11 additions & 11 deletions pallets/services-payment/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
//! to that containerChain, by simply assigning the slot position.

use {
crate::{mock::*, pallet as payment_services_pallet, BlockProductionCredits},
crate::{mock::*, pallet as pallet_services_payment, BlockProductionCredits},
frame_support::{assert_err, assert_ok},
};

Expand All @@ -52,7 +52,7 @@ fn purchase_credits_works() {

assert_eq!(
events(),
vec![payment_services_pallet::Event::CreditsPurchased {
vec![pallet_services_payment::Event::CreditsPurchased {
para_id: 1.into(),
payer: ALICE,
fee: 500,
Expand Down Expand Up @@ -98,14 +98,14 @@ fn purchase_credits_purchases_zero_when_max_already_stored() {
assert_eq!(
events(),
vec![
payment_services_pallet::Event::CreditsPurchased {
pallet_services_payment::Event::CreditsPurchased {
para_id,
payer: ALICE,
fee: 500,
credits_purchased: MaxCreditsStored::get(),
credits_remaining: MaxCreditsStored::get(),
},
payment_services_pallet::Event::CreditsPurchased {
pallet_services_payment::Event::CreditsPurchased {
para_id,
payer: ALICE,
fee: 0,
Expand Down Expand Up @@ -156,14 +156,14 @@ fn purchase_credits_purchases_max_possible_when_cant_purchase_all_requested() {
assert_eq!(
events(),
vec![
payment_services_pallet::Event::CreditsPurchased {
pallet_services_payment::Event::CreditsPurchased {
para_id,
payer: ALICE,
fee: 100,
credits_purchased: amount_purchased,
credits_remaining: amount_purchased,
},
payment_services_pallet::Event::CreditsPurchased {
pallet_services_payment::Event::CreditsPurchased {
para_id,
payer: ALICE,
fee: 400,
Expand All @@ -181,7 +181,7 @@ fn purchase_credits_fails_with_insufficient_balance() {
// 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),
payment_services_pallet::Error::<Test>::InsufficientFundsToPurchaseCredits,
pallet_services_payment::Error::<Test>::InsufficientFundsToPurchaseCredits,
);
});
}
Expand All @@ -191,7 +191,7 @@ fn burn_credit_fails_with_no_credits() {
ExtBuilder::default().build().execute_with(|| {
assert_err!(
PaymentServices::burn_credit_for_para(&1u32.into()),
payment_services_pallet::Error::<Test>::InsufficientCredits,
pallet_services_payment::Error::<Test>::InsufficientCredits,
);
});
}
Expand All @@ -218,7 +218,7 @@ fn burn_credit_works() {
// now should fail
assert_err!(
PaymentServices::burn_credit_for_para(&para_id),
payment_services_pallet::Error::<Test>::InsufficientCredits,
pallet_services_payment::Error::<Test>::InsufficientCredits,
);
});
}
Expand All @@ -241,7 +241,7 @@ fn burn_credit_fails_for_wrong_para() {
let wrong_para_id = 2.into();
assert_err!(
PaymentServices::burn_credit_for_para(&wrong_para_id),
payment_services_pallet::Error::<Test>::InsufficientCredits,
pallet_services_payment::Error::<Test>::InsufficientCredits,
);
});
}
Expand Down Expand Up @@ -274,7 +274,7 @@ fn buy_credits_too_expensive_fails() {
1u64,
Some(FIXED_BLOCK_PRODUCTION_COST - 1),
),
payment_services_pallet::Error::<Test>::CreditPriceTooExpensive,
pallet_services_payment::Error::<Test>::CreditPriceTooExpensive,
);
});
}
Expand Down
Loading
Loading