Skip to main content

df_hyperliquid_core/trade/builder/
fee.rs

1//! A builder's fee in tenths of a basis point, as an order's `f` and `maxBuilderFee` count it (10
2//! is 1 basis point). `approveBuilderFee` names the same figure as a percent.
3
4use crate::utils::dec::{Dec, Round};
5use crate::utils::sign::Map;
6use crate::utils::{Address, AssetKind};
7use serde::Deserialize;
8use std::fmt;
9
10/// Tenths of a basis point: 10 is 0.01%, 1000 is 1%.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize)]
12#[serde(transparent)]
13pub struct BuilderFee(u64);
14
15/// The most a builder may take on a perp order, main dex or HIP-3: 0.1%.
16pub const PERP_BUILDER_CAP: BuilderFee = BuilderFee(100);
17
18/// The most a builder may take on a spot order: 1%.
19pub const SPOT_BUILDER_CAP: BuilderFee = BuilderFee(1_000);
20
21/// HIP-4 takes builder codes as spot does.
22pub const OUTCOME_BUILDER_CAP: BuilderFee = SPOT_BUILDER_CAP;
23
24impl BuilderFee {
25    /// No fee.
26    pub const ZERO: BuilderFee = BuilderFee(0);
27
28    /// A fee of `tenths` tenths of a basis point.
29    #[must_use]
30    pub const fn from_tenths(tenths: u64) -> BuilderFee {
31        BuilderFee(tenths)
32    }
33
34    /// The fee in tenths of a basis point, as an order's `f` writes it.
35    #[must_use]
36    pub const fn tenths(self) -> u64 {
37        self.0
38    }
39
40    /// Whether the venue lets a builder take this fee on an order of `kind`: `Err` with the cap
41    /// when it is over it.
42    pub const fn allowed_on(self, kind: AssetKind) -> Result<(), OverCap> {
43        let cap = kind.builder_cap();
44        match self.0 > cap.0 {
45            true => Err(OverCap { fee: self, cap, kind }),
46            false => Ok(()),
47        }
48    }
49
50    /// The percent string `approveBuilderFee` takes as `maxFeeRate`: 880 is `0.88%`, 100 is `0.1%`,
51    /// 1000 is `1%`. It always matches `^[0-9]+(\.[0-9]+)?%$`.
52    #[must_use]
53    pub fn percent(self) -> String {
54        let figure = Dec::lit::<3>(i128::from(self.0)).to_wire();
55        format!("{figure}%")
56    }
57
58    /// A percent string back in tenths. `None` for anything that is not a
59    /// whole number of tenths of a basis point.
60    #[must_use]
61    pub fn from_percent(text: &str) -> Option<BuilderFee> {
62        let digits = text.trim().strip_suffix('%')?;
63        if !digits.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.') {
64            return None;
65        }
66        let figure = Dec::parse(digits).ok()?;
67        if figure.places() > 3 {
68            return None;
69        }
70        u64::try_from(figure.units_at(3, Round::Down)?).ok().map(BuilderFee)
71    }
72}
73
74impl fmt::Display for BuilderFee {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str(&self.percent())
77    }
78}
79
80/// Who routed the order and what it takes: `{b, f}`, the address lowercase,
81/// the fee in tenths of a basis point.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct Builder {
84    address: Address,
85    fee: BuilderFee,
86}
87
88impl Builder {
89    /// The account must have approved at least `fee` for this builder
90    /// (`approveBuilderFee`), or the venue refuses the order.
91    #[must_use]
92    pub const fn new(address: Address, fee: BuilderFee) -> Builder {
93        Builder { address, fee }
94    }
95
96    /// `b`: the builder's address.
97    #[must_use]
98    pub const fn address(&self) -> Address {
99        self.address
100    }
101
102    /// `f`: what the builder takes, in tenths of a basis point.
103    #[must_use]
104    pub const fn fee(&self) -> BuilderFee {
105        self.fee
106    }
107
108    /// `{b, f}`, as an `order` action carries it.
109    #[must_use]
110    pub fn wire(&self) -> Map {
111        Map::new().put("b", self.address.to_hex()).put("f", self.fee.tenths())
112    }
113}
114
115/// A builder fee over what the venue lets a builder take on these orders.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
117#[error("the builder fee of {} is over the {} {} order allows ({})", .fee.tenths(), .cap.tenths(), .kind.one(), .cap)]
118#[non_exhaustive]
119pub struct OverCap {
120    /// The fee asked for.
121    pub fee: BuilderFee,
122    /// The most the market kind allows.
123    pub cap: BuilderFee,
124    /// The market kind whose cap applies: the strictest among the orders.
125    pub kind: AssetKind,
126}
127
128#[cfg(test)]
129#[path = "tests/fee.rs"]
130mod tests;