dpp/tokens/
token_pricing_schedule.rs

1use crate::balances::credits::TokenAmount;
2use crate::errors::ProtocolError;
3use crate::fee::Credits;
4use bincode::{Decode, Encode};
5use platform_serialization_derive::{PlatformDeserialize, PlatformSerialize};
6#[cfg(feature = "serde-conversion")]
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::fmt::{self, Display, Formatter};
10
11/// Defines the pricing schedule for tokens in terms of credits.
12///
13/// A pricing schedule can either be a single, flat price applied to all
14/// token amounts, or a tiered pricing model where specific amounts
15/// correspond to specific credit values.
16#[derive(
17    Debug,
18    Clone,
19    Encode,
20    Decode,
21    Eq,
22    PartialEq,
23    Ord,
24    PartialOrd,
25    PlatformSerialize,
26    PlatformDeserialize,
27)]
28#[cfg_attr(feature = "serde-conversion", derive(Serialize, Deserialize))]
29pub enum TokenPricingSchedule {
30    /// A single flat price in credits for all token amounts.
31    ///
32    /// This variant is used when the pricing does not depend on
33    /// the number of tokens being purchased or processed.
34    SinglePrice(Credits),
35
36    /// A tiered pricing model where specific token amounts map to credit prices.
37    ///
38    /// This allows for more complex pricing structures, such as
39    /// volume discounts or progressive pricing. The map keys
40    /// represent token amount thresholds, and the values are the
41    /// corresponding credit prices.
42    /// If the first token amount is greater than 1 this means that the user can only
43    /// purchase that amount as a minimum at a time.
44    SetPrices(BTreeMap<TokenAmount, Credits>),
45}
46
47impl TokenPricingSchedule {
48    pub fn minimum_purchase_amount_and_price(&self) -> (TokenAmount, Credits) {
49        match self {
50            TokenPricingSchedule::SinglePrice(price) => (1, *price),
51            TokenPricingSchedule::SetPrices(prices) => prices
52                .first_key_value()
53                .map(|(amount, cost)| (*amount, *cost))
54                .unwrap_or_default(),
55        }
56    }
57}
58
59impl Display for TokenPricingSchedule {
60    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
61        match self {
62            TokenPricingSchedule::SinglePrice(credits) => {
63                write!(f, "SinglePrice: {}", credits)
64            }
65            TokenPricingSchedule::SetPrices(prices) => {
66                write!(f, "SetPrices: [")?;
67                for (i, (amount, credits)) in prices.iter().enumerate() {
68                    if i > 0 {
69                        write!(f, ", ")?;
70                    }
71                    write!(f, "{} => {}", amount, credits)?;
72                }
73                write!(f, "]")
74            }
75        }
76    }
77}