pallet_idn_consumer/lib.rs
1/*
2 * Copyright 2025 by Ideal Labs, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Pallet IDN Consumer
18//!
19//! ## Overview
20//!
21//! The `pallet-idn-consumer` provides functionality for interacting with the Ideal Network (IDN) as
22//! a consumer. It allows parachains to subscribe to randomness pulses, request subscription quotes,
23//! and manage subscription states via XCM.
24//!
25//! ## Key Features
26//!
27//! - **Subscription Management:** Create, update, pause, reactivate, and terminate subscriptions.
28//! - **Randomness Consumption:** Consume randomness pulses delivered by the IDN.
29//! - **Quote Requests:** Request and consume subscription fee quotes.
30//! - **Subscription Info:** Retrieve and consume subscription details.
31//! - **XCM Integration:** Seamlessly interact with the IDN Manager pallet on the Ideal Network.
32
33#![cfg_attr(not(feature = "std"), no_std)]
34
35#[cfg(test)]
36mod tests;
37
38#[cfg(feature = "runtime-benchmarks")]
39mod benchmarking;
40
41pub mod primitives;
42pub mod traits;
43pub mod weights;
44
45use bp_idn::{
46 types::{
47 BlockNumber as IdnBlockNumber, CallData, CreateSubParams, Credits, Metadata, OriginKind,
48 QuoteRequest, QuoteSubParams, RequestReference, SubInfoRequest, UpdateSubParams,
49 },
50 Call as RuntimeCall, IdnManagerCall,
51};
52use cumulus_primitives_core::{Instruction::WithdrawAsset, ParaId};
53use frame_support::{
54 dispatch::DispatchResultWithPostInfo,
55 pallet_prelude::{Encode, EnsureOrigin, Get, IsType, Pays},
56};
57use frame_system::{ensure_signed, pallet_prelude::OriginFor};
58use scale_info::prelude::{boxed::Box, sync::Arc, vec};
59use sp_idn_traits::Hashable;
60use sp_runtime::traits::TryConvert;
61use traits::{PulseConsumer, QuoteConsumer, SubInfoConsumer};
62use xcm::{
63 v5::{
64 prelude::{
65 BuyExecution, DepositAsset, OriginKind as XcmOriginKind, RefundSurplus, Transact, Xcm,
66 },
67 Asset,
68 AssetFilter::Wild,
69 AssetId, Junction, Junctions, Location,
70 WeightLimit::Unlimited,
71 WildAsset::AllOf,
72 WildFungibility,
73 },
74 VersionedLocation, VersionedXcm,
75};
76use xcm_builder::SendController;
77
78pub use bp_idn::types::{Quote, RuntimePulse as Pulse, SubInfoResponse, SubscriptionId};
79pub use pallet::*;
80pub use weights::WeightInfo;
81
82#[frame_support::pallet]
83pub mod pallet {
84
85 use super::*;
86
87 #[pallet::config]
88 /// Configuration trait for the pallet.
89 ///
90 /// This trait defines the types and constants required to configure the pallet.
91 pub trait Config: frame_system::Config {
92 /// The overarching event type.
93 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
94
95 /// An implementation of the [`PulseConsumer`] trait, which defines how to consume a pulse.
96 type PulseConsumer: PulseConsumer<Pulse, SubscriptionId, (), ()>;
97
98 /// An implementation of the [`QuoteConsumer`] trait, which defines how to consume a quote.
99 type QuoteConsumer: QuoteConsumer<Quote, (), ()>;
100
101 /// An implementation of the [`SubInfoConsumer`] trait, which defines how to consume
102 /// subscription info.
103 type SubInfoConsumer: SubInfoConsumer<SubInfoResponse, (), ()>;
104
105 /// The location of the sibling IDN chain.
106 ///
107 /// Example definition:
108 /// ```nocompile
109 /// parameter_types! {
110 /// pub SiblingIdnLocation: Location = Location::new(1, Parachain(IDN_PARACHAIN_ID));
111 /// }
112 /// impl pallet_idn_consumer::Config for Runtime {
113 /// pub type SiblingIdnLocation = SiblingIdnLocation;
114 /// }
115 /// ```
116 #[pallet::constant]
117 type SiblingIdnLocation: Get<Location>;
118
119 /// The origin of the IDN chain.
120 ///
121 /// Example definition:
122 /// ```nocompile
123 /// type IdnOriginFilter = EnsureXcm<Equals<Self::SiblingIdnLocation>>
124 /// ```
125 type IdnOriginFilter: EnsureOrigin<Self::RuntimeOrigin, Success = Location>;
126
127 /// A type that exposes XCM APIs, allowing contracts to interact with other parachains and
128 /// execute XCM programs.
129 type Xcm: xcm_builder::SendController<OriginFor<Self>>;
130
131 /// This pallet's unique identifier.
132 #[pallet::constant]
133 type PalletId: Get<frame_support::PalletId>;
134
135 /// The parachain ID of this chain.
136 ///
137 /// Example definition:
138 /// ```nocompile
139 /// pub ParaId: ParaId = ParachainInfo::parachain_id();
140 /// ```
141 #[pallet::constant]
142 type ParaId: Get<ParaId>;
143
144 /// The maximum amount of fees to pay for the execution of a single XCM message sent to the
145 /// IDN chain, expressed in the IDN asset.
146 #[pallet::constant]
147 type MaxIdnXcmFees: Get<u128>;
148
149 /// The weight information for this pallet.
150 type WeightInfo: WeightInfo;
151
152 /// A type that can convert the local origin to a `Location`.
153 type LocalOriginToLocation: TryConvert<Self::RuntimeOrigin, Location>;
154 }
155
156 #[pallet::pallet]
157 pub struct Pallet<T>(_);
158
159 #[pallet::event]
160 /// Events emitted by this pallet.
161 #[pallet::generate_deposit(pub(super) fn deposit_event)]
162 pub enum Event<T: Config> {
163 /// A randomness pulse was successfully consumed.
164 ///
165 /// - `sub_id`: The subscription ID associated with the pulse.
166 RandomnessConsumed { sub_id: SubscriptionId },
167 /// A subscription quote was successfully consumed.
168 ///
169 /// - `quote`: The subscription quote that was consumed.
170 QuoteConsumed { quote: Quote },
171
172 /// Subscription info was successfully consumed.
173 ///
174 /// - `sub_id`: The subscription ID associated with the consumed info.
175 SubInfoConsumed { sub_id: SubscriptionId },
176 }
177
178 #[pallet::error]
179 /// Errors that may occur in this pallet.
180 #[derive(PartialEq)]
181 pub enum Error<T> {
182 /// An error occurred while consuming the pulse.
183 ConsumePulseError,
184
185 /// An error occurred while consuming the quote.
186 ConsumeQuoteError,
187
188 /// An error occurred while consuming the subscription info.
189 ConsumeSubInfoError,
190
191 /// An error occurred while converting the pallet index to a `u8`.
192 PalletIndexConversionError,
193
194 /// An error occurred while sending the XCM message.
195 XcmSendError,
196
197 /// The call data is too long to fit in the bounded vector.
198 CallDataTooLong,
199 }
200
201 #[pallet::call]
202 impl<T: Config> Pallet<T> {
203 /// Consumes a randomness pulse from the IDN chain.
204 ///
205 /// This function processes randomness pulses delivered by the IDN chain. The logic for
206 /// handling the pulse is defined in the [`PulseConsumer`] trait implementation.
207 ///
208 /// # Parameters
209 /// - `origin`: The origin of the call. Must be filtered by using the
210 /// [`Config::IdnOriginFilter`] type.
211 /// - `pulse`: The randomness pulse to be consumed.
212 /// - `sub_id`: The subscription ID associated with the pulse.
213 ///
214 /// # Errors
215 /// - [`Error::ConsumePulseError`]: If the pulse cannot be consumed.
216 #[pallet::call_index(0)]
217 #[pallet::weight(T::WeightInfo::consume_pulse())]
218 #[allow(clippy::useless_conversion)]
219 pub fn consume_pulse(
220 origin: OriginFor<T>,
221 pulse: Pulse,
222 sub_id: SubscriptionId,
223 ) -> DispatchResultWithPostInfo {
224 // ensure origin is valid
225 let _ = T::IdnOriginFilter::ensure_origin(origin)?;
226
227 T::PulseConsumer::consume_pulse(pulse, sub_id)
228 .map_err(|_| Error::<T>::ConsumePulseError)?;
229
230 Self::deposit_event(Event::RandomnessConsumed { sub_id });
231
232 Ok(Pays::No.into())
233 }
234
235 /// Consumes a subscription quote from the IDN chain.
236 ///
237 /// This function processes subscription fee quotes received from the IDN chain. The
238 /// behavior for handling the quote is defined in the [`QuoteConsumer`] trait
239 /// implementation.
240 ///
241 /// # Parameters
242 /// - `origin`: The origin of the call. Must be filtered by using the
243 /// [`Config::IdnOriginFilter`] type.
244 /// - `quote`: The subscription quote to be consumed.
245 ///
246 /// # Errors
247 /// - [`Error::ConsumeQuoteError`]: If the quote cannot be consumed.
248 #[pallet::call_index(1)]
249 #[pallet::weight(T::WeightInfo::consume_quote())]
250 #[allow(clippy::useless_conversion)]
251 pub fn consume_quote(origin: OriginFor<T>, quote: Quote) -> DispatchResultWithPostInfo {
252 // ensure origin is valid
253 let _ = T::IdnOriginFilter::ensure_origin(origin)?;
254
255 T::QuoteConsumer::consume_quote(quote.clone())
256 .map_err(|_| Error::<T>::ConsumeQuoteError)?;
257
258 Self::deposit_event(Event::QuoteConsumed { quote });
259
260 Ok(Pays::No.into())
261 }
262
263 /// Consumes subscription info from the IDN chain.
264 ///
265 /// This function processes subscription information received from the IDN chain. The
266 /// behavior for handling the subscription info is defined in the [`SubInfoConsumer`] trait
267 /// implementation.
268 ///
269 /// # Parameters
270 /// - `origin`: The origin of the call. Must be filtered by using the
271 /// [`Config::IdnOriginFilter`] type.
272 /// - `sub_info`: The subscription information to be consumed.
273 ///
274 /// # Errors
275 /// - [`Error::ConsumeSubInfoError`]: If the subscription info cannot be consumed.
276 #[pallet::call_index(2)]
277 #[pallet::weight(T::WeightInfo::consume_sub_info())]
278 #[allow(clippy::useless_conversion)]
279 pub fn consume_sub_info(
280 origin: OriginFor<T>,
281 sub_info: SubInfoResponse,
282 ) -> DispatchResultWithPostInfo {
283 // ensure origin is valid
284 let _ = T::IdnOriginFilter::ensure_origin(origin)?;
285
286 T::SubInfoConsumer::consume_sub_info(sub_info.clone())
287 .map_err(|_| Error::<T>::ConsumeSubInfoError)?;
288
289 Self::deposit_event(Event::SubInfoConsumed { sub_id: sub_info.sub.id });
290
291 Ok(Pays::No.into())
292 }
293
294 /// Dispatchable function to create a subscription on the consumer chain with sudo
295 /// privileges.
296 ///
297 /// # Parameters
298 /// - `origin`: Must be the root (sudo) origin.
299 /// - `credits`: Number of random values to receive.
300 /// - `frequency`: Distribution interval for pulses.
301 /// - `metadata`: Optional additional data for the subscription.
302 /// - `sub_id`: Optional subscription ID. If `None`, a new one will be generated.
303 /// - `origin_kind`: Optional Origin kind for the callback XCM message.
304 ///
305 /// # Returns
306 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
307 ///
308 /// # Errors
309 /// - Fails if the origin is not root.
310 /// - Fails if subscription creation fails (see [`Self::do_create_subscription`]).
311 ///
312 /// # Usage
313 /// This function is intended for privileged (sudo) operations, such as testing or
314 /// administrative tasks, to create a subscription directly on the consumer chain.
315 #[pallet::call_index(3)]
316 #[pallet::weight(T::WeightInfo::create_subscription())]
317 #[allow(clippy::useless_conversion)]
318 pub fn create_subscription(
319 origin: OriginFor<T>,
320 credits: Credits,
321 frequency: IdnBlockNumber,
322 metadata: Option<Metadata>,
323 sub_id: Option<SubscriptionId>,
324 origin_kind: Option<OriginKind>,
325 ) -> DispatchResultWithPostInfo {
326 ensure_signed(origin.clone())?;
327
328 Self::do_create_subscription(
329 origin,
330 credits,
331 frequency,
332 metadata,
333 sub_id,
334 origin_kind,
335 )?;
336 Ok(Pays::No.into())
337 }
338
339 /// Dispatchable function to pause a subscription on the consumer chain with sudo
340 /// privileges.
341 ///
342 /// # Parameters
343 /// - `origin`: Must be the root (sudo) origin.
344 /// - `sub_id`: The subscription ID to pause.
345 ///
346 /// # Returns
347 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
348 ///
349 /// # Errors
350 /// - Fails if the origin is not root.
351 /// - Fails if pausing the subscription fails.
352 ///
353 /// # Usage
354 /// This function is intended for privileged (sudo) operations, such as testing or
355 /// administrative tasks, to create a subscription directly on the consumer chain.
356 #[pallet::call_index(4)]
357 #[pallet::weight(T::WeightInfo::pause_subscription())]
358 #[allow(clippy::useless_conversion)]
359 pub fn pause_subscription(
360 origin: OriginFor<T>,
361 sub_id: SubscriptionId,
362 ) -> DispatchResultWithPostInfo {
363 ensure_signed(origin.clone())?;
364 Self::do_pause_subscription(origin, sub_id)?;
365 Ok(Pays::No.into())
366 }
367
368 /// Dispatchable function to kill a subscription on the consumer chain with sudo privileges.
369 ///
370 /// # Parameters
371 /// - `origin`: Must be the root (sudo) origin.
372 /// - `sub_id`: The subscription ID to kill.
373 ///
374 /// # Returns
375 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
376 ///
377 /// # Errors
378 /// - Fails if the origin is not root.
379 /// - Fails if killing the subscription fails.
380 ///
381 /// # Usage
382 /// This function is intended for privileged (sudo) operations, such as testing or
383 /// administrative tasks, to kill a subscription directly on the consumer chain.
384 #[pallet::call_index(5)]
385 #[pallet::weight(T::WeightInfo::kill_subscription())]
386 #[allow(clippy::useless_conversion)]
387 pub fn kill_subscription(
388 origin: OriginFor<T>,
389 sub_id: SubscriptionId,
390 ) -> DispatchResultWithPostInfo {
391 ensure_signed(origin.clone())?;
392 Self::do_kill_subscription(origin, sub_id)?;
393 Ok(Pays::No.into())
394 }
395
396 /// Dispatchable function to update a subscription on the consumer chain with sudo
397 /// privileges.
398 ///
399 /// # Parameters
400 /// - `origin`: Must be the root (sudo) origin.
401 /// - `sub_id`: The subscription ID to update.
402 /// - `credits`: Optional new number of random values to receive.
403 /// - `frequency`: Optional new distribution interval for pulses.
404 /// - `metadata`: Optional new metadata for the subscription.
405 ///
406 /// # Returns
407 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
408 ///
409 /// # Errors
410 /// - Fails if the origin is not root.
411 /// - Fails if updating the subscription fails.
412 ///
413 /// # Usage
414 /// This function is intended for privileged (sudo) operations, such as testing or
415 /// administrative tasks, to update a subscription directly on the consumer chain.
416 #[pallet::call_index(6)]
417 #[pallet::weight(T::WeightInfo::update_subscription())]
418 #[allow(clippy::useless_conversion)]
419 pub fn update_subscription(
420 origin: OriginFor<T>,
421 sub_id: SubscriptionId,
422 credits: Option<Credits>,
423 frequency: Option<IdnBlockNumber>,
424 metadata: Option<Option<Metadata>>,
425 ) -> DispatchResultWithPostInfo {
426 ensure_signed(origin.clone())?;
427 Self::do_update_subscription(origin, sub_id, credits, frequency, metadata)?;
428 Ok(Pays::No.into())
429 }
430
431 /// Dispatchable function to reactivate a subscription on the consumer chain with sudo
432 /// privileges.
433 ///
434 /// # Parameters
435 /// - `origin`: Must be the root (sudo) origin.
436 /// - `sub_id`: The subscription ID to reactivate.
437 ///
438 /// # Returns
439 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
440 ///
441 /// # Errors
442 /// - Fails if the origin is not root.
443 /// - Fails if reactivating the subscription fails.
444 ///
445 /// # Usage
446 /// This function is intended for privileged (sudo) operations, such as testing or
447 /// administrative tasks, to reactivate a subscription directly on the consumer chain.
448 #[pallet::call_index(7)]
449 #[pallet::weight(T::WeightInfo::reactivate_subscription())]
450 #[allow(clippy::useless_conversion)]
451 pub fn reactivate_subscription(
452 origin: OriginFor<T>,
453 sub_id: SubscriptionId,
454 ) -> DispatchResultWithPostInfo {
455 ensure_signed(origin.clone())?;
456 Self::do_reactivate_subscription(origin, sub_id)?;
457 Ok(Pays::No.into())
458 }
459
460 /// Dispatchable function to request a subscription quote from the consumer chain with sudo
461 /// privileges.
462 ///
463 /// # Parameters
464 /// - `origin`: Must be the root (sudo) origin.
465 /// - `number_of_pulses`: Number of random values to receive.
466 /// - `frequency`: Distribution interval for pulses.
467 /// - `metadata`: Optional additional data for the subscription.
468 /// - `sub_id`: Optional subscription ID.
469 /// - `req_ref`: Optional quote request reference.
470 /// - `origin_kind`: Optional Origin kind for the callback XCM message.
471 ///
472 /// # Returns
473 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
474 ///
475 /// # Errors
476 /// - Fails if the origin is not root.
477 /// - Fails if requesting the quote fails.
478 ///
479 /// # Usage
480 /// This function is intended for privileged (sudo) operations, such as testing or
481 /// administrative tasks, to request a quote directly on the consumer chain.
482 #[pallet::call_index(8)]
483 #[pallet::weight(T::WeightInfo::request_quote())]
484 #[allow(clippy::useless_conversion)]
485 pub fn request_quote(
486 origin: OriginFor<T>,
487 number_of_pulses: IdnBlockNumber,
488 frequency: IdnBlockNumber,
489 metadata: Option<Metadata>,
490 sub_id: Option<SubscriptionId>,
491 req_ref: Option<RequestReference>,
492 origin_kind: Option<OriginKind>,
493 ) -> DispatchResultWithPostInfo {
494 ensure_signed(origin.clone())?;
495 Self::do_request_quote(
496 origin,
497 number_of_pulses,
498 frequency,
499 metadata,
500 sub_id,
501 req_ref,
502 origin_kind,
503 )?;
504 Ok(Pays::No.into())
505 }
506
507 /// Dispatchable function to request subscription info from the consumer chain with sudo
508 /// privileges.
509 ///
510 /// # Parameters
511 /// - `origin`: Must be the root (sudo) origin.
512 /// - `sub_id`: The subscription ID to request info for.
513 /// - `req_ref`: Optional quote request reference.
514 /// - `origin_kind`: Optional Origin kind for the callback XCM message.
515 ///
516 /// # Returns
517 /// - [`DispatchResultWithPostInfo`]: Returns `Ok(Pays::No)` if successful.
518 ///
519 /// # Errors
520 /// - Fails if the origin is not root.
521 /// - Fails if requesting the subscription info fails.
522 ///
523 /// # Usage
524 /// This function is intended for privileged (sudo) operations, such as testing or
525 /// administrative tasks, to request subscription info directly on the consumer chain.
526 #[pallet::call_index(9)]
527 #[pallet::weight(T::WeightInfo::request_sub_info())]
528 #[allow(clippy::useless_conversion)]
529 pub fn request_sub_info(
530 origin: OriginFor<T>,
531 sub_id: SubscriptionId,
532 req_ref: Option<RequestReference>,
533 origin_kind: Option<OriginKind>,
534 ) -> DispatchResultWithPostInfo {
535 ensure_signed(origin.clone())?;
536 Self::do_request_sub_info(origin, sub_id, req_ref, origin_kind)?;
537 Ok(Pays::No.into())
538 }
539 }
540}
541
542impl<T: Config> Pallet<T> {
543 /// Creates a subscription.
544 pub fn do_create_subscription(
545 // Origin of the call, must be acceptable by the IDN XCM barrier
546 origin: OriginFor<T>,
547 // Number of random values to receive
548 credits: Credits,
549 // Distribution interval for pulses
550 frequency: IdnBlockNumber,
551 // Bounded vector for additional data
552 metadata: Option<Metadata>,
553 // Optional Subscription Id, if None, a new one will be generated
554 sub_id: Option<SubscriptionId>,
555 // Origin kind for the callback XCM message; defaults to `OriginKind::Xcm`
556 origin_kind: Option<OriginKind>,
557 ) -> Result<SubscriptionId, Error<T>> {
558 let origin_kind = origin_kind.unwrap_or(OriginKind::Xcm);
559 let mut params = CreateSubParams {
560 credits,
561 target: Self::self_para_sibling_location()?,
562 call: Self::pulse_callback_call_data()?,
563 frequency,
564 metadata,
565 sub_id,
566 origin_kind,
567 };
568
569 // If `sub_id` is not provided, generate a new one and assign it to the params
570 let sub_id = match sub_id {
571 Some(sub_id) => sub_id,
572 None => {
573 let salt = frame_system::Pallet::<T>::block_number().encode();
574 let sub_id = params.hash(&salt).into();
575 params.sub_id = Some(sub_id);
576 sub_id
577 },
578 };
579
580 let call = RuntimeCall::IdnManager(IdnManagerCall::create_subscription { params });
581
582 Self::xcm_send(origin, call)?;
583
584 Ok(sub_id)
585 }
586
587 /// Pauses a subscription.
588 pub fn do_pause_subscription(
589 // Origin of the call, must be accetable by the IDN XCM barrier
590 origin: OriginFor<T>,
591 sub_id: SubscriptionId,
592 ) -> Result<(), Error<T>> {
593 let call = RuntimeCall::IdnManager(IdnManagerCall::pause_subscription { sub_id });
594 Self::xcm_send(origin, call)
595 }
596
597 /// Kills a subscription.
598 pub fn do_kill_subscription(
599 // Origin of the call, must be accetable by the IDN XCM barrier
600 origin: OriginFor<T>,
601 sub_id: SubscriptionId,
602 ) -> Result<(), Error<T>> {
603 let call = RuntimeCall::IdnManager(IdnManagerCall::kill_subscription { sub_id });
604 Self::xcm_send(origin, call)
605 }
606
607 /// Updates a subscription.
608 pub fn do_update_subscription(
609 // Origin of the call, must be accetable by the IDN XCM barrier
610 origin: OriginFor<T>,
611 sub_id: SubscriptionId,
612 credits: Option<Credits>,
613 frequency: Option<IdnBlockNumber>,
614 metadata: Option<Option<Metadata>>,
615 ) -> Result<(), Error<T>> {
616 let params = UpdateSubParams { sub_id, credits, frequency, metadata };
617
618 let call = RuntimeCall::IdnManager(IdnManagerCall::update_subscription { params });
619
620 Self::xcm_send(origin, call)
621 }
622
623 /// Reactivates a subscription.
624 pub fn do_reactivate_subscription(
625 // Origin of the call, must be accetable by the IDN XCM barrier
626 origin: OriginFor<T>,
627 sub_id: SubscriptionId,
628 ) -> Result<(), Error<T>> {
629 let call = RuntimeCall::IdnManager(IdnManagerCall::reactivate_subscription { sub_id });
630 Self::xcm_send(origin, call)
631 }
632
633 /// Request a subscription quote for a given number of credits and frequency.
634 ///
635 /// This function dispatches an XCM message to the IDN chain to get the fee quote.
636 /// The request should then be handled by the IDN chain and return the fee quote to the
637 /// [`Pallet::consume_quote`] function along with the `req_ref`.
638 /// The `req_ref` is generated by this function and used to identify the request when returned.
639 pub fn do_request_quote(
640 // Origin of the call, must be accetable by the IDN XCM barrier
641 origin: OriginFor<T>,
642 // Number of random values to receive
643 number_of_pulses: IdnBlockNumber,
644 // Distribution interval for pulses
645 frequency: IdnBlockNumber,
646 // Bounded vector for additional data
647 metadata: Option<Metadata>,
648 // Optional Subscription Id
649 sub_id: Option<SubscriptionId>,
650 // Optional quote request reference, if None, a new one will be generated
651 req_ref: Option<RequestReference>,
652 // Origin kind for the callback XCM message; defaults to `OriginKind::Xcm`
653 origin_kind: Option<OriginKind>,
654 ) -> Result<RequestReference, Error<T>> {
655 let create_sub_params = CreateSubParams {
656 credits: 0,
657 target: Self::self_para_sibling_location()?,
658 // the `0` on the second element is the call index for the `consume` call
659 call: Self::pulse_callback_call_data()?,
660 frequency,
661 metadata,
662 sub_id,
663 // this is not the origin kind for the quote request callback, but for dummy
664 // subscription for quoting
665 origin_kind: OriginKind::default(),
666 };
667
668 // If `req_ref` is not provided, generate a new one and assign it to the params
669 let req_ref = match req_ref {
670 Some(req_ref) => req_ref,
671 None => {
672 let salt = frame_system::Pallet::<T>::block_number().encode();
673 create_sub_params.hash(&salt).into()
674 },
675 };
676
677 let quote_request =
678 QuoteRequest { req_ref, create_sub_params, lifetime_pulses: number_of_pulses };
679
680 let params = QuoteSubParams {
681 quote_request,
682 call: Self::quote_callback_call_data()?,
683 origin_kind: origin_kind.unwrap_or(OriginKind::Xcm),
684 };
685
686 let call = RuntimeCall::IdnManager(IdnManagerCall::quote_subscription { params });
687
688 Self::xcm_send(origin, call)?;
689
690 Ok(req_ref)
691 }
692
693 /// Request subscription info for a given subscription ID.
694 ///
695 /// This function dispatches an XCM message to the IDN chain to get the subscription info.
696 /// The request should then be handled by the IDN chain and return the subscription info to the
697 /// [`Pallet::consume_sub_info`] function along with the `req_ref`.
698 /// The `req_ref` is generated by this function and used to identify the request when returned.
699 pub fn do_request_sub_info(
700 // Origin of the call, must be accetable by the IDN XCM barrier
701 origin: OriginFor<T>,
702 sub_id: SubscriptionId,
703 // Optional quote request reference, if None, a new one will be generated
704 req_ref: Option<RequestReference>,
705 // Optional Origin kind for the callback XCM message
706 origin_kind: Option<OriginKind>,
707 ) -> Result<RequestReference, Error<T>> {
708 // If `req_ref` is not provided, generate a new one and assign it to the params
709 let req_ref = match req_ref {
710 Some(req_ref) => req_ref,
711 None => {
712 let salt = frame_system::Pallet::<T>::block_number().encode();
713 sub_id.hash(&salt).into()
714 },
715 };
716 let req = SubInfoRequest {
717 sub_id,
718 req_ref,
719 call: Self::sub_info_callback_call_data()?,
720 origin_kind: origin_kind.unwrap_or(OriginKind::Xcm),
721 };
722 let call = RuntimeCall::IdnManager(IdnManagerCall::get_subscription_info { req });
723
724 Self::xcm_send(origin, call)?;
725
726 Ok(req_ref)
727 }
728
729 /// Sends an XCM message to the Ideal Network (IDN) chain.
730 ///
731 /// This function constructs and dispatches an XCM message using the provided `RuntimeCall`.
732 /// The message includes the following instructions:
733 /// - `WithdrawAsset`: Withdraws the specified asset (IDN fee) from the sender's account.
734 /// - `BuyExecution`: Pays for the execution of the XCM message with the withdrawn asset.
735 /// - `Transact`: Executes the provided `RuntimeCall` on the target chain.
736 /// - `RefundSurplus`: Refunds any surplus fees to the sender.
737 /// - `DepositAsset`: Deposits the refunded asset back into the sender's account.
738 ///
739 /// The function ensures that the XCM message is properly versioned and sent to the target
740 /// location (`SiblingIdnLocation`). If the message fails to send, an `XcmSendError` is
741 /// returned.
742 ///
743 /// # Parameters
744 /// - `origin`: The origin of the call.
745 /// - `call`: The `RuntimeCall` to be executed on the target chain.
746 ///
747 /// # Returns
748 /// - `Ok(())` if the message is successfully sent.
749 /// - `Err(Error<T>)` if the message fails to send.
750 fn xcm_send(origin: OriginFor<T>, call: RuntimeCall) -> Result<(), Error<T>> {
751 let idn_fee_asset = Asset {
752 id: AssetId(Location { parents: 1, interior: Junctions::Here }),
753 fun: T::MaxIdnXcmFees::get().into(),
754 };
755
756 let xcm_call: Xcm<RuntimeCall> = Xcm(vec![
757 WithdrawAsset(idn_fee_asset.clone().into()),
758 BuyExecution { weight_limit: Unlimited, fees: idn_fee_asset.clone() },
759 Transact {
760 origin_kind: XcmOriginKind::Xcm,
761 fallback_max_weight: None,
762 call: call.encode().into(),
763 },
764 RefundSurplus,
765 DepositAsset {
766 assets: Wild(AllOf { id: idn_fee_asset.id, fun: WildFungibility::Fungible }),
767 // refund any surplus back to the origin's account
768 beneficiary: T::LocalOriginToLocation::try_convert(origin.clone())
769 .map_err(|_| Error::<T>::XcmSendError)?,
770 },
771 ]);
772
773 let versioned_target: Box<VersionedLocation> =
774 Box::new(T::SiblingIdnLocation::get().into());
775
776 let versioned_msg: Box<VersionedXcm<()>> = Box::new(xcm::VersionedXcm::V5(xcm_call.into()));
777
778 T::Xcm::send(origin, versioned_target, versioned_msg)
779 .map_err(|_err| Error::<T>::XcmSendError)?;
780
781 Ok(())
782 }
783
784 /// Get the index of this pallet in the runtime
785 fn pallet_index() -> Result<u8, Error<T>> {
786 <Self as frame_support::traits::PalletInfoAccess>::index()
787 .try_into()
788 .map_err(|_| Error::<T>::PalletIndexConversionError)
789 }
790
791 /// Get this parachain's Location as a sibling of the IDN chain.
792 fn self_para_sibling_location() -> Result<Location, Error<T>> {
793 Ok(Location {
794 parents: 1,
795 interior: Junctions::X1(Arc::new([Junction::Parachain(T::ParaId::get().into())])),
796 })
797 }
798
799 /// Get the call data for the [`Pallet::consume_pulse`] call
800 fn pulse_callback_call_data() -> Result<CallData, Error<T>> {
801 // IMPORTANT: The second element of the call index MUST MATCH the index of the
802 // `consume_pulse` dispatchable.
803 let call_index = [Self::pallet_index()?, 0];
804 CallData::try_from(call_index.to_vec()).map_err(|_| Error::<T>::CallDataTooLong)
805 }
806
807 /// Get the call data for the [`Pallet::consume_quote`] call
808 fn quote_callback_call_data() -> Result<CallData, Error<T>> {
809 // IMPORTANT: The second element of the call index MUST MATCH the index of the
810 // `consume_quote` dispatchable.
811 let call_index = [Self::pallet_index()?, 1];
812 CallData::try_from(call_index.to_vec()).map_err(|_| Error::<T>::CallDataTooLong)
813 }
814
815 /// Get the call data for the [`Pallet::consume_sub_info`] call
816 fn sub_info_callback_call_data() -> Result<CallData, Error<T>> {
817 // IMPORTANT: The second element of the call index MUST MATCH the index of the
818 // `consume_sub_info` dispatchable.
819 let call_index = [Self::pallet_index()?, 2];
820 CallData::try_from(call_index.to_vec()).map_err(|_| Error::<T>::CallDataTooLong)
821 }
822}