pallet_idn_manager/impls.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//! # Trait Implementations for the IDN Manager Pallet
18//!
19//! This file contains implementations of various traits required by the IDN Manager pallet.
20//! These implementations provide the concrete logic for calculating fees, managing deposits,
21//! and interacting with other pallets in the system.
22//!
23//! ## Key Implementations:
24//!
25//! - [`Subscription Trait`](SubscriptionTrait): Implemented for the [`Subscription`] struct,
26//! providing access to subscription details such as the subscriber account.
27//! - [`FeesManager`]: Implemented by [`FeesManagerImpl`], providing the logic for calculating
28//! subscription fees, managing fee differences, and collecting fees from subscribers.
29//! - [`DepositCalculator`]: Implemented by [`DepositCalculatorImpl`], providing the logic for
30//! calculating storage deposits and managing deposit differences.
31
32use crate::{
33 self as pallet_idn_manager,
34 traits::{BalanceDirection, DiffBalance, FeesError},
35 HoldReason, Subscription, SubscriptionTrait,
36};
37use codec::Encode;
38use frame_support::{
39 pallet_prelude::DispatchError,
40 traits::{
41 tokens::{
42 fungible::{hold::Mutate as HoldMutate, Inspect, Mutate},
43 Fortitude, Precision, Restriction,
44 },
45 Get,
46 },
47};
48use pallet_idn_manager::{DepositCalculator, FeesManager};
49use sp_arithmetic::traits::Unsigned;
50use sp_runtime::{traits::Zero, AccountId32, Saturating};
51use sp_std::{cmp::Ordering, marker::PhantomData};
52
53impl<AccountId, BlockNumber, Credits: Unsigned, Metadata, SubscriptionId, CallData>
54 SubscriptionTrait<AccountId>
55 for Subscription<AccountId, BlockNumber, Credits, Metadata, SubscriptionId, CallData>
56{
57 fn subscriber(&self) -> &AccountId {
58 &self.details.subscriber
59 }
60}
61
62/// This struct represent movement of balance.
63///
64/// * `balance` - how much balance being moved.
65/// * `direction` - if the balance are being collected or released.
66#[derive(Clone, Copy, PartialEq, Eq, Debug)]
67pub struct DiffBalanceImpl<Balance> {
68 balance: Balance,
69 direction: BalanceDirection,
70}
71
72impl<Balance: Copy> DiffBalance<Balance> for DiffBalanceImpl<Balance> {
73 fn balance(&self) -> Balance {
74 self.balance
75 }
76 fn direction(&self) -> BalanceDirection {
77 self.direction
78 }
79 fn new(balance: Balance, direction: BalanceDirection) -> Self {
80 Self { balance, direction }
81 }
82}
83
84/// A FeesManager implementation that holds a dynamic treasury account.
85///
86/// This implementation uses a dynamic treasury account specified in the `Config`
87/// to manage fees. It provides functions for calculating subscription fees,
88/// calculating the difference in fees, and collecting fees from subscribers.
89///
90/// # Type Parameters:
91/// * `Treasury`: A `Get<AccountId32>` implementation that provides the treasury account ID.
92/// * `Sub`: A `SubscriptionTrait<AccountId32>` implementation that provides access to subscription
93/// details.
94/// * `Balances`: A `Mutate<AccountId32>` implementation that provides the ability to hold and
95/// release balances.
96pub struct FeesManagerImpl<Treasury, Sub, Balances, Frequency, PulseIndex, Fee> {
97 _phantom: PhantomData<(Treasury, Sub, Balances, Frequency, PulseIndex, Fee)>,
98}
99
100/// Implementation of the FeesManager trait for the FeesManagerImpl struct.
101///
102/// # Tests
103///
104/// ## Calculate Subscription Fees Test
105#[doc = docify::embed!("./src/tests/pallet.rs", test_calculate_subscription_fees)]
106impl<Treasury, Sub, Balances, Frequency, PulseIndex, Fee>
107 FeesManager<
108 Balances::Balance,
109 u64,
110 Frequency,
111 PulseIndex,
112 Sub,
113 DispatchError,
114 AccountId32,
115 DiffBalanceImpl<Balances::Balance>,
116 > for FeesManagerImpl<Treasury, Sub, Balances, Frequency, PulseIndex, Fee>
117where
118 Treasury: Get<AccountId32>,
119 Sub: SubscriptionTrait<AccountId32>,
120 Balances: HoldMutate<AccountId32> + Mutate<AccountId32> + Inspect<AccountId32>,
121 Balances::Reason: From<HoldReason>,
122 Balances::Balance: From<u64>,
123 Fee: Get<u64>,
124 Frequency: Saturating,
125 PulseIndex: Saturating,
126 u64: From<Frequency>,
127 u64: From<PulseIndex>,
128{
129 /// Calculate the subscription fees based on the number of requested credits.
130 ///
131 /// This function implements a tiered pricing model with volume discounts:
132 /// - Tier 1 (1-10_000 credits): 100% of base fee per credit (no discount)
133 /// - Tier 2 (10_001-100_000 credits): 95% of base fee per credit (5% discount)
134 /// - Tier 3 (101-1000 credits): 90% of base fee per credit (10% discount)
135 /// - Tier 4 (1001-10000 credits): 80% of base fee per credit (20% discount)
136 /// - Tier 5 (10001+ credits): 70% of base fee per credit (30% discount)
137 ///
138 /// The fee calculation processes each tier sequentially:
139 /// 1. For each tier, calculate how many credits fall within that tier
140 /// 2. Apply the corresponding discount rate to those credits
141 /// 3. Sum up the fees across all tiers
142 fn calculate_subscription_fees(credits: &u64) -> Balances::Balance {
143 // Define tier boundaries and their respective discount rates (in basis points)
144 const TIERS: [(u64, u64); 5] = [
145 (1, 0), // 1-10_000: 0% discount
146 (10_001, 5), // 10_001-100_000: 5% discount
147 (100_001, 10), // 100_001-1_000_000: 10% discount
148 (1_000_001, 20), // 1_000_001-10_000_000: 20% discount
149 (10_000_001, 30), // 10_000_001+: 30% discount
150 ];
151
152 let mut total_fee = 0u64;
153 let mut remaining_credits = *credits;
154
155 for (i, &(current_tier_start, current_tier_discount)) in TIERS.iter().enumerate() {
156 // If no remaining credits exit loop.
157 if remaining_credits == 0 {
158 break;
159 }
160
161 let next_tier_start = TIERS.get(i + 1).map(|&(start, _)| start).unwrap_or(u64::MAX);
162
163 let credits_in_tier =
164 (credits.min(&next_tier_start.saturating_sub(1)) - current_tier_start + 1)
165 .min(remaining_credits);
166
167 let tier_fee = Fee::get()
168 .saturating_mul(credits_in_tier)
169 .saturating_mul(100 - current_tier_discount)
170 .saturating_div(100);
171
172 total_fee = total_fee.saturating_add(tier_fee);
173 remaining_credits = remaining_credits.saturating_sub(credits_in_tier);
174 }
175
176 total_fee.into()
177 }
178
179 /// Calculate the difference in fees when a subscription changes, determining whether
180 /// additional fees should be collected or excess fees should be released. This is useful for
181 /// subscription updates and kills for holding or releasing fees. Or when collecting fees from a
182 /// subscriber.
183 ///
184 /// This function compares the fees required before and after a subscription change,
185 /// then returns:
186 /// - The fee difference amount
187 /// - The direction of the balance transfer (collect from user, release to user, or no change)
188 fn calculate_diff_fees(
189 old_credits: &u64,
190 new_credits: &u64,
191 ) -> DiffBalanceImpl<Balances::Balance> {
192 let old_fees = Self::calculate_subscription_fees(old_credits);
193 let new_fees = Self::calculate_subscription_fees(new_credits);
194 let mut direction = BalanceDirection::None;
195 let fees = match new_fees.cmp(&old_fees) {
196 Ordering::Greater => {
197 direction = BalanceDirection::Collect;
198 new_fees - old_fees
199 },
200 Ordering::Less => {
201 direction = BalanceDirection::Release;
202 old_fees - new_fees
203 },
204 Ordering::Equal => Zero::zero(),
205 };
206 DiffBalanceImpl { balance: fees, direction }
207 }
208
209 /// Attempts to collect subscription fees from a subscriber and transfer them to the treasury
210 /// account.
211 ///
212 /// This function:
213 /// 1. Transfers the specified fees from the subscriber's held balance to the treasury account
214 /// 2. Verifies that the full fee amount was successfully collected
215 /// 3. Returns the actual amount collected or an appropriate error
216 ///
217 /// # Notes
218 /// - This function uses
219 /// [`transfer_on_hold`](frame_support::traits::tokens::fungible::hold::Mutate::transfer_on_hold)
220 /// which transfers from the subscriber's held balance
221 /// - The fees are held under the [`HoldReason::Fees`] reason code
222 /// - The transfer uses [`Precision::BestEffort`] which allows partial transfers if full amount
223 /// isn't available
224 /// - Despite using best effort, this function will return an error if less than the requested
225 /// amount is collected
226 fn collect_fees(
227 fees: &Balances::Balance,
228 sub: &Sub,
229 ) -> Result<Balances::Balance, FeesError<Balances::Balance, DispatchError>> {
230 // Ensure the treasury account is set for benchmarking purposes
231 #[cfg(feature = "runtime-benchmarks")]
232 if Balances::balance(&Treasury::get()) < Balances::minimum_balance() {
233 Balances::set_balance(
234 &Treasury::get(),
235 Balances::minimum_balance() - Balances::balance(&Treasury::get()),
236 );
237 }
238
239 // Collect the held fees from the subscriber
240 let collected = Balances::transfer_on_hold(
241 &HoldReason::Fees.into(),
242 sub.subscriber(),
243 &Treasury::get(),
244 *fees,
245 Precision::BestEffort,
246 Restriction::Free,
247 Fortitude::Polite,
248 )
249 .map_err(FeesError::Other)?;
250
251 // Ensure the correct credits were collected.
252 if collected < *fees {
253 return Err(FeesError::NotEnoughBalance { needed: *fees, balance: collected });
254 }
255
256 Ok(collected)
257 }
258
259 /// Get the number of credits consumed by a subscription when this one gets a pulse in a block.
260 fn get_consume_credits(_sub: Option<&Sub>) -> u64 {
261 1
262 }
263
264 /// Get the number of credits consumed by a subscription when this one is idle in a block.
265 fn get_idle_credits(_sub: Option<&Sub>) -> u64 {
266 1
267 }
268}
269
270/// A DepositCalculator implementation that uses a configurable deposit multiplier.
271///
272/// This struct is used to calculate the storage deposit required for a subscription. The deposit
273/// amount is calculated by multiplying the encoded size of the subscription data by the storage
274/// deposit multiplier.
275///
276/// # Tests
277///
278/// ## Hold Deposit Test
279#[doc = docify::embed!("./src/tests/pallet.rs", hold_deposit_works)]
280///
281/// ## Release Deposit Test
282#[doc = docify::embed!("./src/tests/pallet.rs", release_deposit_works)]
283pub struct DepositCalculatorImpl<SDMultiplier: Get<Deposit>, Deposit> {
284 _phantom: PhantomData<(SDMultiplier, Deposit)>,
285}
286
287impl<
288 Sub: SubscriptionTrait<AccountId32> + Encode,
289 SDMultiplier: Get<Deposit>,
290 Deposit: Saturating + From<u64> + Ord + Copy,
291 > DepositCalculator<Deposit, Sub, DiffBalanceImpl<Deposit>>
292 for DepositCalculatorImpl<SDMultiplier, Deposit>
293{
294 /// Calculate the storage deposit required for a subscription.
295 ///
296 /// This function computes the storage deposit amount based on the encoded size of the
297 /// subscription object multiplied by a configurable deposit multiplier.
298 ///
299 /// # Security Considerations
300 /// This function handles potential overflow scenarios by:
301 /// 1. Converting the encoded size from `usize` to `u64` with fallback to `u64::MAX` if the
302 /// conversion fails
303 /// 2. Using saturating multiplication to prevent arithmetic overflow
304 fn calculate_storage_deposit(sub: &Sub) -> Deposit {
305 // [SECURITY] Note: There is a theoretical edge case where if the `Deposit` type (e.g., u64)
306 // is larger than the machine architecture size (e.g., 32-bit platforms), an attacker
307 // could create a subscription object larger than u32::MAX bits and only pay a deposit for
308 // u32::MAX bits, not the full size. This risk is mitigated in practice by platform
309 // constraints and cost barriers.
310 let storage_deposit_multiplier = SDMultiplier::get();
311 let encoded_size = u64::try_from(sub.encoded_size()).unwrap_or(u64::MAX);
312 storage_deposit_multiplier.saturating_mul(encoded_size.into())
313 }
314
315 /// Calculate the difference in storage deposit between two subscriptions.
316 ///
317 /// This function compares the storage deposit requirements of two subscription states
318 /// and returns the difference along with the direction of the balance adjustment.
319 ///
320 /// # How It Works
321 /// 1. Calculates the storage deposit for both the old and new subscription states
322 /// 2. Compares the two deposits to determine if more deposit is needed, some can be released,
323 /// or no change is required
324 /// 3. Returns both the amount and direction of the required deposit adjustment
325 fn calculate_diff_deposit(old_sub: &Sub, new_sub: &Sub) -> DiffBalanceImpl<Deposit> {
326 let old_deposit = Self::calculate_storage_deposit(old_sub);
327 let new_deposit = Self::calculate_storage_deposit(new_sub);
328 let direction = match new_deposit.cmp(&old_deposit) {
329 Ordering::Greater => BalanceDirection::Collect,
330 Ordering::Less => BalanceDirection::Release,
331 Ordering::Equal => BalanceDirection::None,
332 };
333 DiffBalanceImpl { balance: new_deposit.saturating_sub(old_deposit), direction }
334 }
335}