coretime_rococo_runtime/
coretime.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17use crate::{xcm_config::LocationToAccountId, *};
18use codec::{Decode, Encode};
19use cumulus_pallet_parachain_system::RelaychainDataProvider;
20use cumulus_primitives_core::relay_chain;
21use frame_support::{
22	parameter_types,
23	traits::{
24		fungible::{Balanced, Credit, Inspect},
25		tokens::{Fortitude, Preservation},
26		DefensiveResult, OnUnbalanced,
27	},
28};
29use frame_system::Pallet as System;
30use pallet_broker::{
31	CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600, RCBlockNumberOf, TaskId,
32};
33use parachains_common::{AccountId, Balance};
34use rococo_runtime_constants::system_parachain::coretime;
35use sp_runtime::traits::{AccountIdConversion, MaybeConvert};
36use xcm::latest::prelude::*;
37use xcm_executor::traits::{ConvertLocation, TransactAsset};
38
39pub struct BurnCoretimeRevenue;
40impl OnUnbalanced<Credit<AccountId, Balances>> for BurnCoretimeRevenue {
41	fn on_nonzero_unbalanced(amount: Credit<AccountId, Balances>) {
42		let acc = RevenueAccumulationAccount::get();
43		if !System::<Runtime>::account_exists(&acc) {
44			System::<Runtime>::inc_providers(&acc);
45		}
46		Balances::resolve(&acc, amount).defensive_ok();
47	}
48}
49
50type AssetTransactor = <xcm_config::XcmConfig as xcm_executor::Config>::AssetTransactor;
51
52fn burn_at_relay(stash: &AccountId, value: Balance) -> Result<(), XcmError> {
53	let dest = Location::parent();
54	let stash_location =
55		Junction::AccountId32 { network: None, id: stash.clone().into() }.into_location();
56	let asset = Asset { id: AssetId(Location::parent()), fun: Fungible(value) };
57	let dummy_xcm_context = XcmContext { origin: None, message_id: [0; 32], topic: None };
58
59	let withdrawn = AssetTransactor::withdraw_asset(&asset, &stash_location, None)?;
60
61	AssetTransactor::can_check_out(&dest, &asset, &dummy_xcm_context)?;
62
63	let parent_assets = Into::<Assets>::into(withdrawn)
64		.reanchored(&dest, &Here.into())
65		.defensive_map_err(|_| XcmError::ReanchorFailed)?;
66
67	PolkadotXcm::send_xcm(
68		Here,
69		Location::parent(),
70		Xcm(vec![
71			Instruction::UnpaidExecution {
72				weight_limit: WeightLimit::Unlimited,
73				check_origin: None,
74			},
75			ReceiveTeleportedAsset(parent_assets.clone()),
76			BurnAsset(parent_assets),
77		]),
78	)?;
79
80	AssetTransactor::check_out(&dest, &asset, &dummy_xcm_context);
81
82	Ok(())
83}
84
85/// A type containing the encoding of the coretime pallet in the Relay chain runtime. Used to
86/// construct any remote calls. The codec index must correspond to the index of `Coretime` in the
87/// `construct_runtime` of the Relay chain.
88#[derive(Encode, Decode)]
89enum RelayRuntimePallets {
90	#[codec(index = 74)]
91	Coretime(CoretimeProviderCalls),
92}
93
94/// Call encoding for the calls needed from the relay coretime pallet.
95#[derive(Encode, Decode)]
96enum CoretimeProviderCalls {
97	#[codec(index = 1)]
98	RequestCoreCount(CoreIndex),
99	#[codec(index = 2)]
100	RequestRevenueInfoAt(relay_chain::BlockNumber),
101	#[codec(index = 3)]
102	CreditAccount(AccountId, Balance),
103	#[codec(index = 4)]
104	AssignCore(
105		CoreIndex,
106		relay_chain::BlockNumber,
107		Vec<(CoreAssignment, PartsOf57600)>,
108		Option<relay_chain::BlockNumber>,
109	),
110}
111
112parameter_types! {
113	pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
114	pub const MinimumCreditPurchase: Balance =  UNITS / 10;
115	pub RevenueAccumulationAccount: AccountId = BrokerPalletId::get().into_sub_account_truncating(b"burnstash");
116}
117
118/// Type that implements the `CoretimeInterface` for the allocation of Coretime. Meant to operate
119/// from the parachain context. That is, the parachain provides a market (broker) for the sale of
120/// coretime, but assumes a `CoretimeProvider` (i.e. a Relay Chain) to actually provide cores.
121pub struct CoretimeAllocator;
122impl CoretimeInterface for CoretimeAllocator {
123	type AccountId = AccountId;
124	type Balance = Balance;
125	type RelayChainBlockNumberProvider = RelaychainDataProvider<Runtime>;
126
127	fn request_core_count(count: CoreIndex) {
128		use crate::coretime::CoretimeProviderCalls::RequestCoreCount;
129		let request_core_count_call = RelayRuntimePallets::Coretime(RequestCoreCount(count));
130
131		let message = Xcm(vec![
132			Instruction::UnpaidExecution {
133				weight_limit: WeightLimit::Unlimited,
134				check_origin: None,
135			},
136			Instruction::Transact {
137				origin_kind: OriginKind::Native,
138				call: request_core_count_call.encode().into(),
139				fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
140			},
141		]);
142
143		match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
144			Ok(_) => log::info!(
145				target: "runtime::coretime",
146				"Request to update schedulable cores sent successfully."
147			),
148			Err(e) => log::error!(
149				target: "runtime::coretime",
150				"Failed to send request to update schedulable cores: {:?}",
151				e
152			),
153		}
154	}
155
156	fn request_revenue_info_at(when: RCBlockNumberOf<Self>) {
157		use crate::coretime::CoretimeProviderCalls::RequestRevenueInfoAt;
158		let request_revenue_info_at_call =
159			RelayRuntimePallets::Coretime(RequestRevenueInfoAt(when));
160
161		let message = Xcm(vec![
162			Instruction::UnpaidExecution {
163				weight_limit: WeightLimit::Unlimited,
164				check_origin: None,
165			},
166			Instruction::Transact {
167				origin_kind: OriginKind::Native,
168				call: request_revenue_info_at_call.encode().into(),
169				fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
170			},
171		]);
172
173		match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
174			Ok(_) => log::info!(
175				target: "runtime::coretime",
176				"Request for revenue information sent successfully."
177			),
178			Err(e) => log::error!(
179				target: "runtime::coretime",
180				"Request for revenue information failed to send: {:?}",
181				e
182			),
183		}
184	}
185
186	fn credit_account(who: Self::AccountId, amount: Self::Balance) {
187		use crate::coretime::CoretimeProviderCalls::CreditAccount;
188		let credit_account_call = RelayRuntimePallets::Coretime(CreditAccount(who, amount));
189
190		let message = Xcm(vec![
191			Instruction::UnpaidExecution {
192				weight_limit: WeightLimit::Unlimited,
193				check_origin: None,
194			},
195			Instruction::Transact {
196				origin_kind: OriginKind::Native,
197				call: credit_account_call.encode().into(),
198				fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
199			},
200		]);
201
202		match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
203			Ok(_) => log::info!(
204				target: "runtime::coretime",
205				"Instruction to credit account sent successfully."
206			),
207			Err(e) => log::error!(
208				target: "runtime::coretime",
209				"Instruction to credit account failed to send: {:?}",
210				e
211			),
212		}
213	}
214
215	fn assign_core(
216		core: CoreIndex,
217		begin: RCBlockNumberOf<Self>,
218		assignment: Vec<(CoreAssignment, PartsOf57600)>,
219		end_hint: Option<RCBlockNumberOf<Self>>,
220	) {
221		use crate::coretime::CoretimeProviderCalls::AssignCore;
222
223		// The relay chain currently only allows `assign_core` to be called with a complete mask
224		// and only ever with increasing `begin`. The assignments must be truncated to avoid
225		// dropping that core's assignment completely.
226
227		// This shadowing of `assignment` is temporary and can be removed when the relay can accept
228		// multiple messages to assign a single core.
229		let assignment = if assignment.len() > 28 {
230			let mut total_parts = 0u16;
231			// Account for missing parts with a new `Idle` assignment at the start as
232			// `assign_core` on the relay assumes this is sorted. We'll add the rest of the
233			// assignments and sum the parts in one pass, so this is just initialized to 0.
234			let mut assignment_truncated = vec![(CoreAssignment::Idle, 0)];
235			// Truncate to first 27 non-idle assignments.
236			assignment_truncated.extend(
237				assignment
238					.into_iter()
239					.filter(|(a, _)| *a != CoreAssignment::Idle)
240					.take(27)
241					.inspect(|(_, parts)| total_parts += *parts)
242					.collect::<Vec<_>>(),
243			);
244
245			// Set the parts of the `Idle` assignment we injected at the start of the vec above.
246			assignment_truncated[0].1 = 57_600u16.saturating_sub(total_parts);
247			assignment_truncated
248		} else {
249			assignment
250		};
251
252		let assign_core_call =
253			RelayRuntimePallets::Coretime(AssignCore(core, begin, assignment, end_hint));
254
255		let message = Xcm(vec![
256			Instruction::UnpaidExecution {
257				weight_limit: WeightLimit::Unlimited,
258				check_origin: None,
259			},
260			Instruction::Transact {
261				origin_kind: OriginKind::Native,
262				call: assign_core_call.encode().into(),
263				fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
264			},
265		]);
266
267		match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
268			Ok(_) => log::info!(
269				target: "runtime::coretime",
270				"Core assignment sent successfully."
271			),
272			Err(e) => log::error!(
273				target: "runtime::coretime",
274				"Core assignment failed to send: {:?}",
275				e
276			),
277		}
278	}
279
280	fn on_new_timeslice(_t: pallet_broker::Timeslice) {
281		let stash = RevenueAccumulationAccount::get();
282		let value =
283			Balances::reducible_balance(&stash, Preservation::Expendable, Fortitude::Polite);
284
285		if value > 0 {
286			log::debug!(target: "runtime::coretime", "Going to burn {value} stashed tokens at RC");
287			match burn_at_relay(&stash, value) {
288				Ok(()) => {
289					log::debug!(target: "runtime::coretime", "Succesfully burnt {value} tokens");
290				},
291				Err(err) => {
292					log::error!(target: "runtime::coretime", "burn_at_relay failed: {err:?}");
293				},
294			}
295		}
296	}
297}
298
299pub struct SovereignAccountOf;
300impl MaybeConvert<TaskId, AccountId> for SovereignAccountOf {
301	fn maybe_convert(id: TaskId) -> Option<AccountId> {
302		// Currently all tasks are parachains.
303		let location = Location::new(1, [Parachain(id)]);
304		LocationToAccountId::convert_location(&location)
305	}
306}
307
308impl pallet_broker::Config for Runtime {
309	type RuntimeEvent = RuntimeEvent;
310	type Currency = Balances;
311	type OnRevenue = BurnCoretimeRevenue;
312	type TimeslicePeriod = ConstU32<{ coretime::TIMESLICE_PERIOD }>;
313	type MaxLeasedCores = ConstU32<50>;
314	type MaxReservedCores = ConstU32<10>;
315	type Coretime = CoretimeAllocator;
316	type ConvertBalance = sp_runtime::traits::Identity;
317	type WeightInfo = weights::pallet_broker::WeightInfo<Runtime>;
318	type PalletId = BrokerPalletId;
319	type AdminOrigin = EnsureRoot<AccountId>;
320	type SovereignAccountOf = SovereignAccountOf;
321	type MaxAutoRenewals = ConstU32<100>;
322	type PriceAdapter = pallet_broker::CenterTargetPrice<Balance>;
323	type MinimumCreditPurchase = MinimumCreditPurchase;
324}