coretime_westend_runtime/
coretime.rs1use crate::{xcm_config::LocationToAccountId, *};
18use codec::{Decode, Encode};
19use cumulus_pallet_parachain_system::RelaychainDataProvider;
20use cumulus_primitives_core::relay_chain;
21use frame_support::parameter_types;
22use pallet_broker::{
23 CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600, RCBlockNumberOf, TaskId,
24 CORE_MASK_BITS,
25};
26use pallet_on_demand_para::{PoolCapacityProvider, QueueOnDemandOrders};
27use parachains_common::{AccountId, Balance};
28use sp_runtime::traits::MaybeConvert;
29use westend_runtime_constants::system_parachain::coretime;
30use xcm::latest::prelude::*;
31use xcm_executor::traits::ConvertLocation;
32
33#[derive(Encode, Decode)]
37enum RelayRuntimePallets {
38 #[codec(index = 66)]
39 Coretime(CoretimeProviderCalls),
40}
41
42#[derive(Encode, Decode)]
44enum CoretimeProviderCalls {
45 #[codec(index = 1)]
46 RequestCoreCount(CoreIndex),
47 #[codec(index = 2)]
48 RequestRevenueInfoAt(relay_chain::BlockNumber),
49 #[codec(index = 3)]
50 CreditAccount(AccountId, Balance),
51 #[codec(index = 4)]
52 AssignCore(
53 CoreIndex,
54 relay_chain::BlockNumber,
55 Vec<(CoreAssignment, PartsOf57600)>,
56 Option<relay_chain::BlockNumber>,
57 ),
58 #[codec(index = 5)]
59 QueueOnDemandBatch(Vec<(ParaId, relay_chain::BlockNumber)>),
60}
61
62const MAX_ORDERS_PER_MESSAGE: u32 = 100;
65
66parameter_types! {
67 pub const BrokerPalletId: PalletId = PalletId(*b"py/broke");
68 pub const OnDemandPalletId: PalletId = PalletId(*b"py/ondmd");
69 pub const MinimumCreditPurchase: Balance = UNITS / 10;
70 pub const MinimumEndPrice: Balance = UNITS;
71}
72
73pub struct CoretimeAllocator;
77impl CoretimeInterface for CoretimeAllocator {
78 type AccountId = AccountId;
79 type Balance = Balance;
80 type RelayChainBlockNumberProvider = RelaychainDataProvider<Runtime>;
81
82 fn request_core_count(count: CoreIndex) {
83 use crate::coretime::CoretimeProviderCalls::RequestCoreCount;
84 let request_core_count_call = RelayRuntimePallets::Coretime(RequestCoreCount(count));
85
86 let call_weight = Weight::from_parts(200_000_000, 1700);
91
92 let message = Xcm(vec![
93 Instruction::UnpaidExecution {
94 weight_limit: WeightLimit::Unlimited,
95 check_origin: None,
96 },
97 Instruction::Transact {
98 origin_kind: OriginKind::Native,
99 call: request_core_count_call.encode().into(),
100 fallback_max_weight: Some(call_weight),
101 },
102 ]);
103
104 match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
105 Ok(_) => tracing::debug!(
106 target: "runtime::coretime",
107 "Request to update schedulable cores sent successfully."
108 ),
109 Err(e) => tracing::error!(
110 target: "runtime::coretime", error=?e,
111 "Failed to send request to update schedulable cores"
112 ),
113 }
114 }
115
116 fn request_revenue_info_at(when: RCBlockNumberOf<Self>) {
117 use crate::coretime::CoretimeProviderCalls::RequestRevenueInfoAt;
118 let request_revenue_info_at_call =
119 RelayRuntimePallets::Coretime(RequestRevenueInfoAt(when));
120
121 let message = Xcm(vec![
122 Instruction::UnpaidExecution {
123 weight_limit: WeightLimit::Unlimited,
124 check_origin: None,
125 },
126 Instruction::Transact {
127 origin_kind: OriginKind::Native,
128 call: request_revenue_info_at_call.encode().into(),
129 fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
130 },
131 ]);
132
133 match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
134 Ok(_) => tracing::debug!(
135 target: "runtime::coretime",
136 "Request for revenue information sent successfully."
137 ),
138 Err(e) => tracing::error!(
139 target: "runtime::coretime", error=?e,
140 "Request for revenue information failed to send"
141 ),
142 }
143 }
144
145 fn credit_account(who: Self::AccountId, amount: Self::Balance) {
146 use crate::coretime::CoretimeProviderCalls::CreditAccount;
147 let credit_account_call = RelayRuntimePallets::Coretime(CreditAccount(who, amount));
148
149 let message = Xcm(vec![
150 Instruction::UnpaidExecution {
151 weight_limit: WeightLimit::Unlimited,
152 check_origin: None,
153 },
154 Instruction::Transact {
155 origin_kind: OriginKind::Native,
156 call: credit_account_call.encode().into(),
157 fallback_max_weight: Some(Weight::from_parts(1_000_000_000, 200_000)),
158 },
159 ]);
160
161 match PolkadotXcm::send_xcm(Here, Location::parent(), message.clone()) {
162 Ok(_) => tracing::debug!(
163 target: "runtime::coretime",
164 "Instruction to credit account sent successfully."
165 ),
166 Err(e) => tracing::error!(
167 target: "runtime::coretime", error=?e,
168 "Instruction to credit account failed to send"
169 ),
170 }
171 }
172
173 fn assign_core(
174 core: CoreIndex,
175 begin: RCBlockNumberOf<Self>,
176 assignment: Vec<(CoreAssignment, PartsOf57600)>,
177 end_hint: Option<RCBlockNumberOf<Self>>,
178 ) {
179 use crate::coretime::CoretimeProviderCalls::AssignCore;
180
181 let call_weight = Weight::from_parts(790_000_000, 1600);
186
187 for chunk in assignment.chunks(28) {
192 let partial_assignment = chunk.to_vec();
193
194 let assign_core_call = RelayRuntimePallets::Coretime(AssignCore(
195 core,
196 begin,
197 partial_assignment,
198 end_hint,
199 ));
200
201 let message = Xcm(vec![
202 Instruction::UnpaidExecution {
203 weight_limit: WeightLimit::Unlimited,
204 check_origin: None,
205 },
206 Instruction::Transact {
207 origin_kind: OriginKind::Native,
208 call: assign_core_call.encode().into(),
209 fallback_max_weight: Some(call_weight),
210 },
211 ]);
212
213 match PolkadotXcm::send_xcm(Here, Location::parent(), message) {
214 Ok(_) => tracing::debug!(
215 target: "runtime::coretime",
216 "Core assignment sent successfully."
217 ),
218 Err(e) => tracing::error!(
219 target: "runtime::coretime", error=?e,
220 "Core assignment failed to send"
221 ),
222 }
223 }
224 }
225}
226
227impl QueueOnDemandOrders<relay_chain::BlockNumber> for CoretimeAllocator {
228 fn queue_batch(batch: Vec<(TaskId, relay_chain::BlockNumber)>) {
229 use crate::coretime::CoretimeProviderCalls::QueueOnDemandBatch;
230
231 let call_weight = Weight::from_parts(280_000_000, 86000);
236
237 let batch = batch
239 .into_iter()
240 .map(|(task, ordered_at)| (ParaId::from(task), ordered_at))
241 .collect::<Vec<_>>();
242 let queue_on_demand_batch_call = RelayRuntimePallets::Coretime(QueueOnDemandBatch(batch));
243
244 let message = Xcm(vec![
245 Instruction::UnpaidExecution {
246 weight_limit: WeightLimit::Unlimited,
247 check_origin: None,
248 },
249 Instruction::Transact {
250 origin_kind: OriginKind::Native,
251 call: queue_on_demand_batch_call.encode().into(),
252 fallback_max_weight: Some(call_weight),
253 },
254 ]);
255
256 match PolkadotXcm::send_xcm(Here, Location::parent(), message) {
257 Ok(_) => tracing::debug!(
258 target: "runtime::coretime",
259 "On-demand batch sent successfully."
260 ),
261 Err(e) => tracing::error!(
262 target: "runtime::coretime", error=?e,
263 "On-demand batch failed to send"
264 ),
265 }
266 }
267
268 #[cfg(feature = "runtime-benchmarks")]
269 fn ensure_successful_delivery() {
270 use cumulus_primitives_core::UpwardMessageSender;
271 ParachainSystem::ensure_successful_delivery();
272 }
273}
274
275pub struct BrokerPoolCapacity;
277impl PoolCapacityProvider for BrokerPoolCapacity {
278 fn pool_cores() -> u32 {
279 pallet_broker::Status::<Runtime>::get().map_or(0, |status| {
280 status
282 .private_pool_size
283 .saturating_add(status.system_pool_size)
284 .saturating_add(CORE_MASK_BITS as u32 - 1) /
285 CORE_MASK_BITS as u32
286 })
287 }
288
289 #[cfg(feature = "runtime-benchmarks")]
290 fn ensure_pool_cores(cores: u32) {
291 if Self::pool_cores() >= cores {
292 return;
293 }
294 pallet_broker::Status::<Runtime>::mutate(|status| {
295 let status = status.get_or_insert(pallet_broker::StatusRecord {
296 core_count: cores.try_into().unwrap_or(CoreIndex::MAX),
297 private_pool_size: 0,
298 system_pool_size: 0,
299 last_committed_timeslice: 0,
300 last_timeslice: 0,
301 });
302 let bits = cores.saturating_mul(CORE_MASK_BITS as u32);
304 status.system_pool_size = bits.saturating_sub(status.private_pool_size);
305 });
306 }
307}
308
309pub struct SovereignAccountOf;
310impl MaybeConvert<TaskId, AccountId> for SovereignAccountOf {
311 fn maybe_convert(id: TaskId) -> Option<AccountId> {
312 let location = Location::new(1, [Parachain(id)]);
314 LocationToAccountId::convert_location(&location)
315 }
316}
317
318impl pallet_broker::Config for Runtime {
319 type RuntimeEvent = RuntimeEvent;
320 type Currency = Balances;
321 type OnRevenue = AccumulateForward;
322 type TimeslicePeriod = ConstU32<{ coretime::TIMESLICE_PERIOD }>;
323 type MaxLeasedCores = ConstU32<50>;
324 type MaxReservedCores = ConstU32<50>;
325 type Coretime = CoretimeAllocator;
326 type OnDemandRevenue = OnDemand;
327 type ConvertBalance = sp_runtime::traits::Identity;
328 type WeightInfo = weights::pallet_broker::WeightInfo<Runtime>;
329 type PalletId = BrokerPalletId;
330 type AdminOrigin = EnsureRoot<AccountId>;
331 type SovereignAccountOf = SovereignAccountOf;
332 type MaxAutoRenewals = ConstU32<50>;
333 type PriceAdapter = pallet_broker::MinimumPrice<Balance, MinimumEndPrice>;
334 type MinimumCreditPurchase = MinimumCreditPurchase;
335}
336
337impl pallet_on_demand_para::Config for Runtime {
338 type WeightInfo = weights::pallet_on_demand_para::WeightInfo<Runtime>;
339 type Currency = Balances;
340 type AdminOrigin = EnsureRoot<AccountId>;
341 type RelayBlockNumberProvider = RelaychainDataProvider<Runtime>;
342 type PoolCapacityProvider = BrokerPoolCapacity;
343 type PricingProvider = pallet_on_demand_para::DefaultPricingProvider;
344 type OrderQueue = CoretimeAllocator;
345 type MaxBatchSize = ConstU32<MAX_ORDERS_PER_MESSAGE>;
346 type TimeslicePeriod = <Runtime as pallet_broker::Config>::TimeslicePeriod;
347 type MaxUnclaimedTimeslices = ConstU32<5>;
348 type PalletId = OnDemandPalletId;
349}