Skip to content

Commit

Permalink
Kusama coretime revenue integration (#384)
Browse files Browse the repository at this point in the history
Based on #381 

CC @ggwpez
  • Loading branch information
s0me0ne-unkn0wn authored Jul 17, 2024
1 parent 0265664 commit 36c9a7f
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 13 deletions.
2 changes: 1 addition & 1 deletion relay/kusama/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ metadata-hash = ["substrate-wasm-builder?/metadata-hash"]
on-chain-release-build = ["sp-api/disable-logging", "metadata-hash"]

# Set timing constants (e.g. session period) to faster versions to speed up testing.
fast-runtime = []
fast-runtime = ["kusama-runtime-constants/fast-runtime"]

runtime-metrics = ["runtime-parachains/runtime-metrics", "sp-io/with-tracing"]

Expand Down
1 change: 1 addition & 0 deletions relay/kusama/constants/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ std = [
"sp-weights/std",
"xcm-builder/std",
]
fast-runtime = []
2 changes: 1 addition & 1 deletion relay/kusama/constants/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub mod system_parachain {
/// WARNING: This constant is used accross chains, so additional care should be taken
/// when changing it.
#[cfg(feature = "fast-runtime")]
pub const TIMESLICE_PERIOD: u32 = 10;
pub const TIMESLICE_PERIOD: u32 = 20;
#[cfg(not(feature = "fast-runtime"))]
pub const TIMESLICE_PERIOD: u32 = 80;
}
Expand Down
2 changes: 1 addition & 1 deletion system-parachains/coretime/coretime-kusama/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ try-runtime = [
"sp-runtime/try-runtime",
]

fast-runtime = []
fast-runtime = ["kusama-runtime-constants/fast-runtime"]

# Enable metadata hash generation at compile time for the `CheckMetadataHash` extension.
metadata-hash = ["substrate-wasm-builder?/metadata-hash"]
Expand Down
81 changes: 71 additions & 10 deletions system-parachains/coretime/coretime-kusama/src/coretime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,18 @@ 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 kusama_runtime_constants::system_parachain::coretime;
use pallet_broker::{CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600, RCBlockNumberOf};
use parachains_common::{AccountId, Balance};
use sp_runtime::traits::AccountIdConversion;
use xcm::latest::prelude::*;
use xcm_executor::traits::TransactAsset;

/// 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
Expand Down Expand Up @@ -65,13 +69,52 @@ parameter_types! {

/// Burn revenue from coretime sales. See
/// [RFC-010](https://polkadot-fellows.github.io/RFCs/approved/0010-burn-coretime-revenue.html).
pub struct BurnRevenue;
impl OnUnbalanced<Credit<AccountId, Balances>> for BurnRevenue {
fn on_nonzero_unbalanced(credit: Credit<AccountId, Balances>) {
let _ = <Balances as Balanced<_>>::resolve(&CoretimeBurnAccount::get(), credit);
pub struct BurnCoretimeRevenue;
impl OnUnbalanced<Credit<AccountId, Balances>> for BurnCoretimeRevenue {
fn on_nonzero_unbalanced(amount: Credit<AccountId, Balances>) {
let acc = CoretimeBurnAccount::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(())
}

parameter_types! {
/// The revenue from on-demand coretime sales. This is distributed amonst those who contributed
/// regions to the pool.
Expand Down Expand Up @@ -184,9 +227,27 @@ impl CoretimeInterface for CoretimeAllocator {
}
}

#[cfg(feature = "runtime-benchmarks")]
fn ensure_notify_revenue_info(when: RCBlockNumberOf<Self>, revenue: Self::Balance) {
CoretimeRevenue::set(&Some((when, revenue)));
fn on_new_timeslice(t: pallet_broker::Timeslice) {
// Burn roughly once per day. Unchecked math: RHS hardcoded as non-zero.
if t % 180 != 0 {
return
}

let stash = CoretimeBurnAccount::get();
let value =
Balances::reducible_balance(&stash, Preservation::Expendable, Fortitude::Polite);

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:?}");
},
}
}
}
}

Expand All @@ -197,7 +258,7 @@ parameter_types! {
impl pallet_broker::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type OnRevenue = BurnRevenue;
type OnRevenue = BurnCoretimeRevenue;
type TimeslicePeriod = ConstU32<{ coretime::TIMESLICE_PERIOD }>;
type MaxLeasedCores = ConstU32<50>;
type MaxReservedCores = ConstU32<10>;
Expand Down
1 change: 1 addition & 0 deletions system-parachains/coretime/coretime-kusama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,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>,
);

/// Executive: handles dispatch to the various modules.
Expand Down

0 comments on commit 36c9a7f

Please sign in to comment.