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        let cap = kind.builder_cap();
72        match fee > cap {
73            true => Err(OverCap { fee, cap, kind }),
74            false => Ok(Builder::new(self.address, fee)),
75        }
76    }
77
78    /// The builder one action over these assets names: held to the
79    /// strictest kind among them, so one perp order holds the whole action
80    /// to the perp cap. `None` for no assets.
81    pub fn on_assets(&self, assets: impl IntoIterator<Item = Asset>) -> Result<Option<Builder>, OverCap> {
82        AssetKind::strictest(assets).map(|kind| self.on(kind)).transpose()
83    }
84
85    /// The most an order on any market it may trade pays, which is what one
86    /// approval has to cover: 880 at 88% of each cap.
87    #[must_use]
88    pub fn most(&self) -> BuilderFee {
89        AssetKind::ALL
90            .into_iter()
91            .filter_map(|kind| self.on(kind).ok())
92            .map(|builder| builder.fee())
93            .max()
94            .unwrap_or_default()
95    }
96
97    /// What `order` needs before it is sent, by what the account has approved this builder to charge
98    /// and by which key signs. Only the account's own key may sign `approveBuilderFee`.
99    pub fn approval(&self, order: &PlaceOrder, approved: &Approved, by: Key) -> Result<Approval, ApprovalRefused> {
100        let Some(builder) = order.builder().filter(|builder| builder.fee() > BuilderFee::ZERO) else {
101            return Ok(Approval::Goes);
102        };
103        if builder.address() != self.address {
104            return Err(ApprovalRefused::OtherBuilder { named: builder.address(), set: self.address });
105        }
106        let fee = builder.fee();
107        let approved = match approved {
108            Approved::Upto(approved) if *approved >= fee => return Ok(Approval::Goes),
109            Approved::Upto(approved) => *approved,
110            Approved::Unread => return Err(ApprovalRefused::NotRead),
111            Approved::Failed(why) => return Err(ApprovalRefused::Unreadable(why.clone())),
112        };
113        let rate = self.most().max(fee);
114        match by {
115            Key::Main => Ok(Approval::ApproveFirst { approved, rate }),
116            Key::Agent => Err(ApprovalRefused::AgentCannotApprove { approved, rate }),
117        }
118    }
119}
120
121/// What the account has approved its builder to charge, as `maxBuilderFee`
122/// last answered or as the last approval the venue took.
123#[derive(Debug, Clone, PartialEq, Eq, Default)]
124#[non_exhaustive]
125pub enum Approved {
126    /// Nothing read yet.
127    #[default]
128    Unread,
129    /// Up to this.
130    Upto(BuilderFee),
131    /// The read failed, and why.
132    Failed(String),
133}
134
135impl Approved {
136    /// What the account has approved, in words.
137    #[must_use]
138    pub fn words(&self) -> String {
139        match self {
140            Approved::Unread => "not read yet".to_owned(),
141            Approved::Upto(fee) if *fee == BuilderFee::ZERO => "nothing yet".to_owned(),
142            Approved::Upto(fee) => format!("up to {fee}"),
143            Approved::Failed(why) => format!("would not read: {why}"),
144        }
145    }
146}
147
148/// What an order paying a builder needs before it is sent.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150#[non_exhaustive]
151pub enum Approval {
152    /// Nothing: no builder, a fee of 0, or a fee already approved.
153    Goes,
154    /// `approveBuilderFee` at `rate` first, signed by the account: it has
155    /// approved `approved`, under the order's fee. `rate` is the most any
156    /// market pays, so one approval covers them all.
157    ApproveFirst {
158        /// What the account has approved so far.
159        approved: BuilderFee,
160        /// The rate to approve.
161        rate: BuilderFee,
162    },
163}
164
165impl Approval {
166    /// The `maxFeeRate` `approveBuilderFee` names: `0.88%` for 880.
167    #[must_use]
168    pub fn max_fee_rate(&self) -> Option<String> {
169        match self {
170            Approval::Goes => None,
171            Approval::ApproveFirst { rate, .. } => Some(rate.percent()),
172        }
173    }
174}
175
176/// Why an order cannot go for its builder fee: what is not known is refused
177/// rather than guessed at.
178#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
179#[non_exhaustive]
180pub enum ApprovalRefused {
181    /// What the account has approved is not read yet.
182    #[error("the builder fee this account has approved is not read yet; try again in a moment")]
183    NotRead,
184    /// The read of what the account has approved failed; why.
185    #[error("the builder fee this account has approved would not read, so it is not guessed at: {0}")]
186    Unreadable(String),
187    /// The order needs `approveBuilderFee` first, and an agent key signs: only the account's own
188    /// key may sign that approval.
189    #[error(
190        "the account's main key has to approve the builder fee up to {rate} once (approved now: {approved}); an agent key cannot sign approveBuilderFee"
191    )]
192    AgentCannotApprove {
193        /// What the account has approved so far.
194        approved: BuilderFee,
195        /// The rate the account's own key has to approve.
196        rate: BuilderFee,
197    },
198    /// The order names another builder than the setting's.
199    #[error("the order names the builder {named}, and what the account approved was read for {set}")]
200    OtherBuilder {
201        /// The builder the order names.
202        named: Address,
203        /// The builder the setting names.
204        set: Address,
205    },
206}
207
208#[cfg(test)]
209#[path = "tests/setting.rs"]
210mod tests;