Skip to content

Commit

Permalink
Coretime: Add request revenue info (#3940)
Browse files Browse the repository at this point in the history
Enables the `request_revenue` and `notify_revenue` parts of [RFC 5 -
Coretime
Interface](https://polkadot-fellows.github.io/RFCs/approved/0005-coretime-interface.html)

TODO:
- [x] Finish first pass at implementation
- [x] ~~Need to explicitly burn uncollected and dropped revenue~~
Accumulate it instead
- [x] Confirm working on zombienet
- [x] Tests 
- [ ] Enable XCM `request_revenue` sending on Coretime chain on Kusama
and Polkadot

Fixes: #2209

---------

Co-authored-by: Dmitry Sinyavin <dmitry.sinyavin@parity.io>
Co-authored-by: command-bot <>
Co-authored-by: s0me0ne-unkn0wn <48632512+s0me0ne-unkn0wn@users.noreply.github.com>
Co-authored-by: Dónal Murray <donal.murray@parity.io>
Co-authored-by: Bastian Köcher <git@kchr.de>
  • Loading branch information
5 people committed Jun 26, 2024
1 parent 4a7155e commit f1db2c6
Show file tree
Hide file tree
Showing 39 changed files with 1,831 additions and 916 deletions.
34 changes: 8 additions & 26 deletions Cargo.lock

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

Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,6 @@ try-runtime = [
"sp-runtime/try-runtime",
]

fast-runtime = []
fast-runtime = [
"rococo-runtime-constants/fast-runtime",
]
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,65 @@ use cumulus_primitives_core::relay_chain;
use frame_support::{
parameter_types,
traits::{
fungible::{Balanced, Credit},
OnUnbalanced,
fungible::{Balanced, Credit, Inspect},
tokens::{Fortitude, Preservation},
DefensiveResult, OnUnbalanced,
},
};
use frame_system::Pallet as System;
use pallet_broker::{CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600, RCBlockNumberOf};
use parachains_common::{AccountId, Balance, BlockNumber};
use parachains_common::{AccountId, Balance};
use rococo_runtime_constants::system_parachain::coretime;
use sp_runtime::traits::AccountIdConversion;
use xcm::latest::prelude::*;
use xcm_executor::traits::TransactAsset;

pub struct CreditToCollatorPot;
impl OnUnbalanced<Credit<AccountId, Balances>> for CreditToCollatorPot {
fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
let staking_pot = CollatorSelection::account_id();
let _ = <Balances as Balanced<_>>::resolve(&staking_pot, credit);
pub struct BurnCoretimeRevenue;
impl OnUnbalanced<Credit<AccountId, Balances>> for BurnCoretimeRevenue {
fn on_nonzero_unbalanced(amount: Credit<AccountId, Balances>) {
let acc = RevenueAccumulationAccount::get();
if !System::<Runtime>::account_exists(&acc) {
System::<Runtime>::inc_providers(&acc);
}
Balances::resolve(&acc, amount).defensive_ok();
}
}

type AssetTransactor = <xcm_config::XcmConfig as xcm_executor::Config>::AssetTransactor;

fn burn_at_relay(stash: &AccountId, value: Balance) -> Result<(), XcmError> {
let dest = Location::parent();
let stash_location =
Junction::AccountId32 { network: None, id: stash.clone().into() }.into_location();
let asset = Asset { id: AssetId(Location::parent()), fun: Fungible(value) };
let dummy_xcm_context = XcmContext { origin: None, message_id: [0; 32], topic: None };

let withdrawn = AssetTransactor::withdraw_asset(&asset, &stash_location, None)?;

AssetTransactor::can_check_out(&dest, &asset, &dummy_xcm_context)?;

let parent_assets = Into::<Assets>::into(withdrawn)
.reanchored(&dest, &Here.into())
.defensive_map_err(|_| XcmError::ReanchorFailed)?;

PolkadotXcm::send_xcm(
Here,
Location::parent(),
Xcm(vec![
Instruction::UnpaidExecution {
weight_limit: WeightLimit::Unlimited,
check_origin: None,
},
ReceiveTeleportedAsset(parent_assets.clone()),
BurnAsset(parent_assets),
]),
)?;

AssetTransactor::check_out(&dest, &asset, &dummy_xcm_context);

Ok(())
}

/// A type containing the encoding of the coretime pallet in the Relay chain runtime. Used to
/// construct any remote calls. The codec index must correspond to the index of `Coretime` in the
/// `construct_runtime` of the Relay chain.
Expand Down Expand Up @@ -66,11 +109,7 @@ enum CoretimeProviderCalls {

parameter_types! {
pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
}

parameter_types! {
pub storage CoreCount: Option<CoreIndex> = None;
pub storage CoretimeRevenue: Option<(BlockNumber, Balance)> = None;
pub RevenueAccumulationAccount: AccountId = BrokerPalletId::get().into_sub_account_truncating(b"burnstash");
}

/// Type that implements the `CoretimeInterface` for the allocation of Coretime. Meant to operate
Expand Down Expand Up @@ -205,26 +244,30 @@ impl CoretimeInterface for CoretimeAllocator {
}
}

fn check_notify_revenue_info() -> Option<(RCBlockNumberOf<Self>, Self::Balance)> {
let revenue = CoretimeRevenue::get();
CoretimeRevenue::set(&None);
revenue
}
fn on_new_timeslice(_t: pallet_broker::Timeslice) {
let stash = RevenueAccumulationAccount::get();
let value =
Balances::reducible_balance(&stash, Preservation::Expendable, Fortitude::Polite);

#[cfg(feature = "runtime-benchmarks")]
fn ensure_notify_revenue_info(when: RCBlockNumberOf<Self>, revenue: Self::Balance) {
CoretimeRevenue::set(&Some((when, revenue)));
if value > 0 {
log::debug!(target: "runtime::coretime", "Going to burn {value} stashed tokens at RC");
match burn_at_relay(&stash, value) {
Ok(()) => {
log::debug!(target: "runtime::coretime", "Succesfully burnt {value} tokens");
},
Err(err) => {
log::error!(target: "runtime::coretime", "burn_at_relay failed: {err:?}");
},
}
}
}
}

impl pallet_broker::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type OnRevenue = CreditToCollatorPot;
#[cfg(feature = "fast-runtime")]
type TimeslicePeriod = ConstU32<10>;
#[cfg(not(feature = "fast-runtime"))]
type TimeslicePeriod = ConstU32<80>;
type OnRevenue = BurnCoretimeRevenue;
type TimeslicePeriod = ConstU32<{ coretime::TIMESLICE_PERIOD }>;
type MaxLeasedCores = ConstU32<50>;
type MaxReservedCores = ConstU32<10>;
type Coretime = CoretimeAllocator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ pub type Migrations = (
cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,
pallet_broker::migration::MigrateV0ToV1<Runtime>,
pallet_broker::migration::MigrateV1ToV2<Runtime>,
pallet_broker::migration::MigrateV2ToV3<Runtime>,
// permanent
pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,
);
Expand Down
Loading

0 comments on commit f1db2c6

Please sign in to comment.