Skip to main content

df_hyperliquid_core/account/keys/
builder.rs

1//! Builder fees from the account's side: `approveBuilderFee`, what an account has approved a
2//! builder to charge (`maxBuilderFee`), every builder it has approved (`approvedBuilders`), and
3//! whether a builder can be paid at all. An order whose
4//! builder fee is over the approval is refused by the venue; what an order needs approved first is
5//! [`crate::trade::BuilderSetting::approval`].
6
7use crate::account::holdings::perps::{ClearinghouseState, clearinghouse_state};
8use crate::account::settings::mode::{Abstraction, abstraction};
9use crate::client::{ApiError, Transport, info, info_request, user_request};
10use crate::markets::Dex;
11use crate::trade::builder::fee::BuilderFee;
12use crate::utils::sign::{Field, NonceKey, UserAction, UserSigned};
13use crate::utils::{Address, Dec, Json};
14
15/// The least perps account value a builder needs, in USDC.
16pub const BUILDER_MINIMUM: Dec = Dec::from_int(100);
17
18/// The mode a builder needs: standard as set (`disabled`), not `default`, a mode never set.
19pub const BUILDER_MODE: Abstraction = Abstraction::Disabled;
20
21/// `approveBuilderFee`, signed by the account's own wallet: lets `builder`
22/// charge up to `max_fee` on this account's orders. `maxFeeRate` is the
23/// percent string (880 tenths is `0.88%`).
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ApproveBuilderFee {
26    max_fee_rate: String,
27    builder: Address,
28    nonce: u64,
29}
30
31impl ApproveBuilderFee {
32    /// Lets `builder` charge up to `max_fee`, signed at `nonce`.
33    #[must_use]
34    pub fn new(builder: Address, max_fee: BuilderFee, nonce: u64) -> ApproveBuilderFee {
35        ApproveBuilderFee { max_fee_rate: max_fee.percent(), builder, nonce }
36    }
37
38    /// `maxFeeRate` as posted.
39    #[must_use]
40    pub fn max_fee_rate(&self) -> &str {
41        &self.max_fee_rate
42    }
43
44    /// `maxFeeRate` back in tenths of a basis point.
45    #[must_use]
46    pub fn max_fee(&self) -> Option<BuilderFee> {
47        BuilderFee::from_percent(&self.max_fee_rate)
48    }
49
50    /// The builder approved.
51    #[must_use]
52    pub const fn builder(&self) -> Address {
53        self.builder
54    }
55}
56
57impl UserAction for ApproveBuilderFee {
58    fn user_signed(&self) -> UserSigned<'_> {
59        UserSigned::new("approveBuilderFee", "HyperliquidTransaction:ApproveBuilderFee", NonceKey::Nonce, self.nonce)
60            .field("maxFeeRate", Field::String(&self.max_fee_rate))
61            .field("builder", Field::Address(self.builder))
62    }
63}
64
65/// `{"type":"maxBuilderFee","user":..,"builder":..}`.
66#[must_use]
67pub fn max_builder_fee_request(user: Address, builder: Address) -> String {
68    info_request("maxBuilderFee", &[("user", Json::String(user.to_hex())), ("builder", Json::String(builder.to_hex()))])
69}
70
71/// What `user` has approved `builder` to charge, in tenths of a basis point;
72/// 0 for a builder never approved.
73pub async fn max_builder_fee(
74    transport: &impl Transport,
75    user: Address,
76    builder: Address,
77) -> Result<BuilderFee, ApiError> {
78    info(transport, max_builder_fee_request(user, builder)).await
79}
80
81/// `{"type":"approvedBuilders","user":..}`.
82#[must_use]
83pub fn approved_builders_request(user: Address) -> String {
84    user_request("approvedBuilders", user)
85}
86
87/// Every builder `user` has approved a fee for; empty for an account that has approved none.
88/// [`max_builder_fee`] reads what one of them may charge.
89pub async fn approved_builders(transport: &impl Transport, user: Address) -> Result<Vec<Address>, ApiError> {
90    info(transport, approved_builders_request(user)).await
91}
92
93/// Whether a builder can be paid now.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum Readiness {
96    /// The builder can be paid.
97    Ready,
98    /// Not ready, and every reason.
99    NotReady(Vec<NotReady>),
100}
101
102impl Readiness {
103    /// Whether the builder can be paid now.
104    #[must_use]
105    pub const fn is_ready(&self) -> bool {
106        matches!(self, Readiness::Ready)
107    }
108}
109
110/// One reason a builder is not ready.
111#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
112#[non_exhaustive]
113pub enum NotReady {
114    /// The builder's main-dex perps account value is under [`BUILDER_MINIMUM`].
115    #[error("{value} USDC perps account value, under the {BUILDER_MINIMUM} a builder needs")]
116    TooLittle {
117        /// The account value, in USDC.
118        value: Dec,
119    },
120    /// The builder's account is not in [`BUILDER_MODE`]; the mode it is in.
121    #[error("its account abstraction is {0}, and a builder needs standard")]
122    NotStandard(Abstraction),
123}
124
125/// Ready or not, from the builder's main dex (`marginSummary.accountValue`)
126/// and its `userAbstraction`.
127#[must_use]
128pub fn readiness(perp: &ClearinghouseState, mode: &Abstraction) -> Readiness {
129    let value = perp.margin_summary.account_value;
130    let mut why = Vec::new();
131    if value < BUILDER_MINIMUM {
132        why.push(NotReady::TooLittle { value });
133    }
134    if *mode != BUILDER_MODE {
135        why.push(NotReady::NotStandard(mode.clone()));
136    }
137    match why.is_empty() {
138        true => Readiness::Ready,
139        false => Readiness::NotReady(why),
140    }
141}
142
143/// Reads the builder's main dex and its mode, one after the other, and
144/// judges them. Weighs 22: 2 for `clearinghouseState`, 20 for
145/// `userAbstraction`.
146pub async fn builder_readiness(transport: &impl Transport, builder: Address) -> Result<Readiness, ApiError> {
147    let perp = clearinghouse_state(transport, builder, Dex::Main).await?;
148    let mode = abstraction(transport, builder).await?;
149    Ok(readiness(&perp, &mode))
150}
151
152#[cfg(test)]
153#[path = "tests/builder.rs"]
154mod tests;