Skip to main content

df_hyperliquid_core/trade/builder/
setting.rs

1//! Builder fees as a setting: what each market kind pays the caller's builder, held to that kind's
2//! cap, and what an order paying it needs first, by what the account has approved and which key
3//! signs. Whether the builder can be paid at all is [`crate::account::builder_readiness`].
4
5use crate::account::Key;
6use crate::trade::builder::fee::{Builder, BuilderFee, OverCap};
7use crate::trade::orders::PlaceOrder;
8use crate::utils::{Address, Asset, AssetKind};
9
10/// What each order pays the builder.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum FeeRule {
14    /// This many percent of each market kind's cap, cut down to a whole tenth of a basis point: 88 is
15    /// 88 of a perp's 100 and 880 of spot's 1000. At most 100.
16    ShareOfCap(u64),
17    /// One fee on every market; an order whose market allows less is refused,
18    /// never lowered.
19    Flat(BuilderFee),
20}
21
22/// The builder orders are routed through, and what they pay it.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct BuilderSetting {
25    address: Address,
26    rule: FeeRule,
27}
28
29impl BuilderSetting {
30    /// `percent` of each market's cap; `None` over 100.
31    #[must_use]
32    pub const fn share_of_cap(address: Address, percent: u64) -> Option<BuilderSetting> {
33        match percent <= 100 {
34            true => Some(BuilderSetting { address, rule: FeeRule::ShareOfCap(percent) }),
35            false => None,
36        }
37    }
38
39    /// `fee` on every market.
40    #[must_use]
41    pub const fn flat(address: Address, fee: BuilderFee) -> BuilderSetting {
42        BuilderSetting { address, rule: FeeRule::Flat(fee) }
43    }
44
45    /// The builder orders are routed through.
46    #[must_use]
47    pub const fn address(&self) -> Address {
48        self.address
49    }
50
51    /// What each order pays the builder.
52    #[must_use]
53    pub const fn rule(&self) -> FeeRule {
54        self.rule
55    }
56
57    /// What an order on `kind` pays, whether the market allows it or not.
58    #[must_use]
59    pub const fn fee_on(&self, kind: AssetKind) -> BuilderFee {
60        match self.rule {
61            FeeRule::ShareOfCap(percent) => {
62                BuilderFee::from_tenths(kind.builder_cap().tenths().saturating_mul(percent) / 100)
63            }
64            FeeRule::Flat(fee) => fee,
65        }
66    }
67
68    /// The builder an order on `kind` names, or why it cannot.
69    pub fn on(&self, kind: AssetKind) -> Result<Builder, OverCap> {
70        let fee = self.fee_on(kind);
71        fee.allowed_on(kind).map(|()| Builder::new(self.address, fee))
72    }
73
74    /// The builder one action over these assets names: held to the
75    /// strictest kind among them, so one perp order holds the whole action
76    /// to the perp cap. `None` for no assets.
77    pub fn on_assets(&self, assets: impl IntoIterator<Item = Asset>) -> Result<Option<Builder>, OverCap> {
78        AssetKind::strictest(assets).map(|kind| self.on(kind)).transpose()
79    }
80
81    /// The most an order on any market it may trade pays, which is what one
82    /// approval has to cover: 880 at 88% of each cap.
83    #[must_use]
84    pub fn most(&self) -> BuilderFee {
85        AssetKind::ALL
86            .into_iter()
87            .filter_map(|kind| self.on(kind).ok())
88            .map(|builder| builder.fee())
89            .max()
90            .unwrap_or_default()
91    }
92
93    /// What `order` needs before it is sent, by what the account has approved this builder to charge
94    /// and by which key signs. Only the account's own key may sign `approveBuilderFee`.
95    pub fn approval(&self, order: &PlaceOrder, approved: &Approved, by: Key) -> Result<Approval, ApprovalRefused> {
96        let Some(builder) = order.builder().filter(|builder| builder.fee() > BuilderFee::ZERO) else {
97            return Ok(Approval::Goes);
98        };
99        if builder.address() != self.address {
100            return Err(ApprovalRefused::OtherBuilder { named: builder.address(), set: self.address });
101        }
102        let fee = builder.fee();
103        let approved = match approved {
104            Approved::Upto(approved) if *approved >= fee => return Ok(Approval::Goes),
105            Approved::Upto(approved) => *approved,
106            Approved::Unread => return Err(ApprovalRefused::NotRead),
107            Approved::Failed(why) => return Err(ApprovalRefused::Unreadable(why.clone())),
108        };
109        let rate = self.most().max(fee);
110        match by {
111            Key::Main => Ok(Approval::ApproveFirst { approved, rate }),
112            Key::Agent => Err(ApprovalRefused::AgentCannotApprove { approved, rate }),
113        }
114    }
115}
116
117/// What the account has approved its builder to charge, as `maxBuilderFee`
118/// last answered or as the last approval the venue took.
119#[derive(Debug, Clone, PartialEq, Eq, Default)]
120#[non_exhaustive]
121pub enum Approved {
122    /// Nothing read yet.
123    #[default]
124    Unread,
125    /// Up to this.
126    Upto(BuilderFee),
127    /// The read failed, and why.
128    Failed(String),
129}
130
131impl Approved {
132    /// What the account has approved, in words.
133    #[must_use]
134    pub fn words(&self) -> String {
135        match self {
136            Approved::Unread => "not read yet".to_owned(),
137            Approved::Upto(fee) if *fee == BuilderFee::ZERO => "nothing yet".to_owned(),
138            Approved::Upto(fee) => format!("up to {fee}"),
139            Approved::Failed(why) => format!("would not read: {why}"),
140        }
141    }
142}
143
144/// What an order paying a builder needs before it is sent.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146#[non_exhaustive]
147pub enum Approval {
148    /// Nothing: no builder, a fee of 0, or a fee already approved.
149    Goes,
150    /// `approveBuilderFee` at `rate` first, signed by the account: it has
151    /// approved `approved`, under the order's fee. `rate` is the most any
152    /// market pays, so one approval covers them all.
153    ApproveFirst {
154        /// What the account has approved so far.
155        approved: BuilderFee,
156        /// The rate to approve.
157        rate: BuilderFee,
158    },
159}
160
161impl Approval {
162    /// The `maxFeeRate` `approveBuilderFee` names: `0.88%` for 880.
163    #[must_use]
164    pub fn max_fee_rate(&self) -> Option<String> {
165        match self {
166            Approval::Goes => None,
167            Approval::ApproveFirst { rate, .. } => Some(rate.percent()),
168        }
169    }
170}
171
172/// Why an order cannot go for its builder fee: what is not known is refused
173/// rather than guessed at.
174#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
175#[non_exhaustive]
176pub enum ApprovalRefused {
177    /// What the account has approved is not read yet.
178    #[error("the builder fee this account has approved is not read yet; try again in a moment")]
179    NotRead,
180    /// The read of what the account has approved failed; why.
181    #[error("the builder fee this account has approved would not read, so it is not guessed at: {0}")]
182    Unreadable(String),
183    /// The order needs `approveBuilderFee` first, and an agent key signs: only the account's own
184    /// key may sign that approval.
185    #[error(
186        "the account's main key has to approve the builder fee up to {rate} once (approved now: {approved}); an agent key cannot sign approveBuilderFee"
187    )]
188    AgentCannotApprove {
189        /// What the account has approved so far.
190        approved: BuilderFee,
191        /// The rate the account's own key has to approve.
192        rate: BuilderFee,
193    },
194    /// The order names another builder than the setting's.
195    #[error("the order names the builder {named}, and what the account approved was read for {set}")]
196    OtherBuilder {
197        /// The builder the order names.
198        named: Address,
199        /// The builder the setting names.
200        set: Address,
201    },
202}
203
204#[cfg(test)]
205#[path = "tests/setting.rs"]
206mod tests;