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