pallet_idn_manager/traits/mod.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//! # IDN Subscription traits
18//!
19//! This file defines the traits that enable the IDN Manager pallet to interact with other modules.
20//! These traits abstract key functionalities.
21//!
22//! ## Core Concepts:
23//!
24//! - **Fees Management:** Governs the calculation, collection, and distribution of fees associated
25//! with subscriptions.
26//! - **Subscription Handling:** Provides a standardized way to access subscriber information.
27//! - **Storage Deposit Calculation:** Defines the logic for determining and managing storage
28//! deposits required for subscriptions.
29//!
30//! ## Key Traits:
31//!
32//! ### [`FeesManager`]
33//! Manages the economic aspects of subscriptions, including fee calculation, collection, and
34//! distribution.
35//!
36//! **Methods:**
37//! - [`calculate_credits`](FeesManager::calculate_credits): Calculates the minimum number of
38//! credits required to power a subscription given its frequency and desired number of pulses
39//! - [`calculate_subscription_fees`](FeesManager::calculate_subscription_fees): Determines the
40//! initial fee for a subscription based on the requested credits.
41//! - [`calculate_diff_fees`](FeesManager::calculate_diff_fees): Calculates the difference in fees
42//! when a subscription is modified (e.g., credits are added or removed).
43//! - [`collect_fees`](FeesManager::collect_fees): Transfers fees from the subscriber's account to
44//! the designated treasury.
45//! - [`get_consume_credits`](FeesManager::get_consume_credits): Returns the amount of credits
46//! that should be consumed when a subscription receives a pulse.
47//! - [`get_idle_credits`](FeesManager::get_idle_credits): Returns the amount of credits that
48//! should be consumed when a subscription skips receiving a pulse.
49//!
50//! ### [`Subscription`]
51//! Provides an interface for accessing the subscriber associated with a subscription.
52//!
53//! **Methods:**
54//! - [`subscriber`](Subscription::subscriber): Returns the account ID of the subscriber.
55//!
56//! ### [`DepositCalculator`]
57//! Manages the storage deposits required for subscriptions, ensuring that sufficient funds are
58//! reserved to cover the cost of storing subscription data.
59//!
60//! **Methods:**
61//! - [`calculate_storage_deposit`](DepositCalculator::calculate_storage_deposit): Calculates the
62//! storage deposit required for a given subscription.
63//! - [`calculate_diff_deposit`](DepositCalculator::calculate_diff_deposit): Calculates the
64//! difference in storage deposit between two subscriptions (e.g., when a subscription is
65//! updated).
66//!
67//! ## Data Structures:
68//!
69//! ### [`FeesError`]
70//! Represents potential errors that can occur during fees management.
71//!
72//! **Variants:**
73//! - [`NotEnoughBalance`](FeesError::NotEnoughBalance): Indicates that the subscriber's account
74//! has insufficient funds to cover the required fees.
75//! - [`Other`](FeesError::Other): Represents a generic error with an associated context.
76//!
77//! ### [`BalanceDirection`]
78//! Specifies the direction of balance movement (either collecting or releasing funds).
79//!
80//! **Variants:**
81//! - [`Collect`](BalanceDirection::Collect): Indicates that funds should be collected from the
82//! subscriber.
83//! - [`Release`](BalanceDirection::Release): Indicates that funds should be released to the
84//! subscriber.
85//! - [`None`](BalanceDirection::None): Indicates that no balance movement is required.
86//!
87//! ### [`DiffBalance`]
88//! Represents a change in balance, including the amount and direction of the change.
89//!
90//! **Fields:**
91//! - [`balance`](DiffBalance::balance): The amount of balance being moved.
92//! - [`direction`](DiffBalance::direction): The direction of the balance movement (using the
93//! `BalanceDirection` enum).
94
95mod example;
96
97/// Error type for fees management
98///
99/// Context is used to provide more information about uncategorized errors.
100pub enum FeesError<Fees, Context> {
101 /// Error indicating that the balance is insufficient to cover the required fees.
102 ///
103 /// # Variants
104 /// - `needed`: The amount of fees required.
105 /// - `balance`: The current balance available.
106 NotEnoughBalance {
107 needed: Fees,
108 balance: Fees,
109 },
110 Other(Context),
111}
112
113/// Enum to represent the direction of balance movement.
114#[derive(Clone, Copy, PartialEq, Eq, Debug)]
115pub enum BalanceDirection {
116 Collect,
117 Release,
118 // Balance isn't going anywhere. This is usually the case when diff is zero.
119 None,
120}
121
122/// This trait represent movement of balance.
123///
124/// * `balance` - how much balance being moved.
125/// * `direction` - if the balance are being collected or released.
126pub trait DiffBalance<Balance> {
127 fn balance(&self) -> Balance;
128 fn direction(&self) -> BalanceDirection;
129 fn new(balance: Balance, direction: BalanceDirection) -> Self;
130}
131
132/// Trait for fees managing
133///
134/// This is where the business model logic is specified. This logic is used to calculate, collect
135/// and distribute fees for subscriptions.
136///
137/// These are some examples of how this trait can be implemented:
138/// - Linear fee calculator: where the fees are calculated based on a linear function.
139#[doc = docify::embed!("./src/traits/example.rs", linear_fee_calculator)]
140/// - Tiered fee calculator: where the fees are calculated based on a tiered function.
141#[doc = docify::embed!("./src/traits/example.rs", tiered_fee_calculator)]
142pub trait FeesManager<Fees, Credits, F, P, Sub: Subscription<S>, Err, S, Diff: DiffBalance<Fees>>
143where
144 Credits: sp_runtime::Saturating + From<F> + From<P>,
145 P: sp_runtime::Saturating,
146 F: sp_runtime::Saturating,
147{
148 /// Calculate the minimum number of credits required to power the subscription under the given
149 /// frequency and lifetime credit calculation pertains to subscription frequency and lifetime,
150 /// agnostic of fees or impl. Note: if the subscription is paused during its lifetime,
151 /// additional credits may be required.
152 ///
153 /// Credits are calculated as: `lifetime * [(frequency - 1) * idle_credit + execute_credits]`
154 /// where
155 ///
156 /// * `frequency`: The (static) number of blocks to wait between pulse delivery
157 /// * `lifetime`: The desired number of pulses to be delivered during the subscription's
158 /// lifetime
159 fn calculate_credits(frequency: F, lifetime: P) -> Credits {
160 Credits::from(lifetime).saturating_mul(
161 Credits::from(frequency)
162 .saturating_mul(Self::get_idle_credits(None))
163 .saturating_add(Self::get_consume_credits(None)),
164 )
165 }
166
167 /// Calculate the fees for a subscription based on the credits of pulses required.
168 fn calculate_subscription_fees(credits: &Credits) -> Fees;
169 /// Calculate how much fees should be held or release when a subscription changes.
170 ///
171 /// * `old_credits` - the credits of pulses required before the change.
172 /// * `new_credits` - the credits of pulses required after the change, this will represent the
173 /// updated credits in an update operation. Or the credits actually consumed in a kill
174 /// operation.
175 fn calculate_diff_fees(old_credits: &Credits, new_credits: &Credits) -> Diff;
176 /// Distributes collected fees. Returns the fees that were effectively collected.
177 fn collect_fees(fees: &Fees, sub: &Sub) -> Result<Fees, FeesError<Fees, Err>>;
178 /// Returns how many credits this subscription pays for receiving a pulse
179 fn get_consume_credits(sub: Option<&Sub>) -> Credits;
180 /// Returns how many credits this subscription pays for skipping to receive a pulse
181 fn get_idle_credits(sub: Option<&Sub>) -> Credits;
182}
183
184/// Trait for accessing subscription information.
185pub trait Subscription<Subscriber> {
186 /// Returns a reference to the subscriber associated with the subscription.
187 fn subscriber(&self) -> &Subscriber;
188}
189
190impl Subscription<()> for () {
191 fn subscriber(&self) -> &() {
192 &()
193 }
194}
195
196/// Trait for storage deposit calculation
197///
198/// This trait is used to calculate the storage deposit required for a subscription based it.
199pub trait DepositCalculator<Deposit, Sub, Diff: DiffBalance<Deposit>> {
200 /// Calculate the storage deposit required for a subscription.
201 fn calculate_storage_deposit(sub: &Sub) -> Deposit;
202 /// Calculate the difference in storage deposit between two subscriptions.
203 ///
204 /// * `old_sub` - the old subscription.
205 /// * `new_sub` - the new subscription.
206 fn calculate_diff_deposit(old_sub: &Sub, new_sub: &Sub) -> Diff;
207}