Skip to main content

df_hyperliquid_core/account/settings/
referral.rs

1//! Referrals: `setReferrer`, the L1 action that gives an account a referrer, `claimRewards`, which
2//! pays out what its referrals have earned it, and the `referral` read. The venue keeps the first
3//! code an account sets.
4
5use crate::account::{ActionKind, Signers};
6use crate::client::{ApiError, Transport, info, user_request};
7use crate::utils::sign::{L1Action, Map};
8use crate::utils::{Address, Dec};
9use serde::Deserialize;
10
11/// The longest code `setReferrer` takes.
12pub const LONGEST_CODE: usize = 20;
13
14/// A code [`SetReferrer::new`] refused, kept as given.
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[error("a referral code is 1 to {LONGEST_CODE} characters, which `{0}` is not")]
17pub struct BadCode(pub String);
18
19/// `setReferrer`: `{type, code}`. An agent may sign it for its master.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SetReferrer {
22    code: String,
23}
24
25impl SetReferrer {
26    /// Refers the account under `code`: 1 to [`LONGEST_CODE`] characters.
27    pub fn new(code: &str) -> Result<SetReferrer, BadCode> {
28        match (1..=LONGEST_CODE).contains(&code.chars().count()) {
29            true => Ok(SetReferrer { code: code.to_owned() }),
30            false => Err(BadCode(code.to_owned())),
31        }
32    }
33}
34
35impl L1Action for SetReferrer {
36    fn action(&self) -> Map {
37        Map::new().put("type", "setReferrer").put("code", self.code.clone())
38    }
39}
40
41/// `claimRewards`: `{type}` alone. Pays the account its unclaimed referral rewards
42/// ([`TokenRewards::unclaimed_rewards`]). An agent may sign it for its master.
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
44pub struct ClaimRewards;
45
46impl ClaimRewards {
47    /// L1: an agent may sign it for its master.
48    pub const KEY: Signers = ActionKind::ClaimRewards.signers();
49}
50
51impl L1Action for ClaimRewards {
52    fn action(&self) -> Map {
53        Map::new().put("type", "claimRewards")
54    }
55}
56
57/// `{"type":"referral","user":..}`.
58#[must_use]
59pub fn referral_request(user: Address) -> String {
60    user_request("referral", user)
61}
62
63/// Reads `referral`; see [`referral_request`].
64pub async fn referral(transport: &impl Transport, user: Address) -> Result<Referral, ApiError> {
65    info(transport, referral_request(user)).await
66}
67
68/// Who referred an account, and its own standing as a referrer. The top
69/// level's figures are USDC's; each quote token's are in `token_to_state`.
70/// Reward history is left unread.
71#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
72#[serde(rename_all = "camelCase")]
73#[non_exhaustive]
74pub struct Referral {
75    /// Who referred the account (`referredBy`); `None` when no one did.
76    #[serde(default)]
77    pub referred_by: Option<ReferredBy>,
78    /// The account's own volume (`cumVlm`), in USDC.
79    pub cum_vlm: Dec,
80    /// Referral rewards not yet claimed (`unclaimedRewards`), in USDC.
81    pub unclaimed_rewards: Dec,
82    /// Referral rewards already claimed (`claimedRewards`), in USDC.
83    pub claimed_rewards: Dec,
84    /// What the account has earned as a builder (`builderRewards`), in USDC; zero when left out.
85    #[serde(default)]
86    pub builder_rewards: Dec,
87    /// Where the account stands as a referrer (`referrerState`).
88    pub referrer_state: ReferrerState,
89    /// Each quote token's figures, by the token's index (`0` USDC); not always sent.
90    #[serde(default)]
91    pub token_to_state: Option<Vec<(u32, TokenRewards)>>,
92}
93
94/// What an account traded and was paid in one quote token.
95#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
96#[serde(rename_all = "camelCase")]
97#[non_exhaustive]
98pub struct TokenRewards {
99    /// The account's own volume in this token (`cumVlm`).
100    pub cum_vlm: Dec,
101    /// Referral rewards in this token not yet claimed (`unclaimedRewards`).
102    pub unclaimed_rewards: Dec,
103    /// Referral rewards in this token already claimed (`claimedRewards`).
104    pub claimed_rewards: Dec,
105    /// What the account has earned in this token as a builder (`builderRewards`).
106    pub builder_rewards: Dec,
107}
108
109/// Who referred an account, and under which code.
110#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
111#[non_exhaustive]
112pub struct ReferredBy {
113    /// The address that owns the code.
114    pub referrer: Address,
115    /// The code the account was referred under.
116    pub code: String,
117}
118
119/// `stage` is `needToTrade` (with `required`, the volume still to trade),
120/// `needToCreateCode`, or `ready` (with the account's own `code`).
121#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
122#[non_exhaustive]
123pub struct ReferrerState {
124    /// `needToTrade`, `needToCreateCode` or `ready`.
125    pub stage: String,
126    /// The stage's figures; `None` when the stage has none.
127    #[serde(default)]
128    pub data: Option<ReferrerData>,
129}
130
131/// What a [`ReferrerState`] stage carries: the code once made, or the volume still to trade.
132#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
133#[serde(rename_all = "camelCase")]
134#[non_exhaustive]
135pub struct ReferrerData {
136    /// The account's own code (`code`); `None` until it has made one.
137    #[serde(default)]
138    pub code: Option<String>,
139    /// The volume still to trade before a code can be made (`required`), in USDC; `None` once
140    /// traded.
141    #[serde(default)]
142    pub required: Option<Dec>,
143    /// How many accounts were referred under the code (`nReferrals`); `None` when not sent.
144    #[serde(default)]
145    pub n_referrals: Option<u64>,
146    /// The accounts referred under the code.
147    #[serde(default)]
148    pub referral_states: Vec<ReferralState>,
149}
150
151/// One account referred under the code. Per-token figures are left unread.
152#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
153#[serde(rename_all = "camelCase")]
154#[non_exhaustive]
155pub struct ReferralState {
156    /// The referred account's address.
157    pub user: Address,
158    /// The referred account's volume (`cumVlm`), in USDC.
159    #[serde(default)]
160    pub cum_vlm: Dec,
161    /// The referred account's fees counted for rewards since it was referred
162    /// (`cumRewardedFeesSinceReferred`), in USDC.
163    #[serde(default)]
164    pub cum_rewarded_fees_since_referred: Dec,
165    /// What the referred account's fees have paid the referrer (`cumFeesRewardedToReferrer`), in
166    /// USDC.
167    #[serde(default)]
168    pub cum_fees_rewarded_to_referrer: Dec,
169    /// Milliseconds.
170    #[serde(default)]
171    pub time_joined: u64,
172}
173
174impl Referral {
175    /// One quote token's figures, by its index.
176    #[must_use]
177    pub fn token(&self, index: u32) -> Option<&TokenRewards> {
178        self.token_to_state.as_deref()?.iter().find(|(token, _)| *token == index).map(|(_, state)| state)
179    }
180
181    /// The account's own code, once it has made one.
182    #[must_use]
183    pub fn own_code(&self) -> Option<&str> {
184        self.referrer_state.data.as_ref()?.code.as_deref()
185    }
186
187    /// The code the account trades under, if any.
188    #[must_use]
189    pub fn referred_code(&self) -> Option<&str> {
190        self.referred_by.as_ref().map(|by| by.code.as_str())
191    }
192
193    /// Who owns the code the account trades under.
194    #[must_use]
195    pub fn referrer(&self) -> Option<Address> {
196        self.referred_by.as_ref().map(|by| by.referrer)
197    }
198
199    /// Whether the account owns `code`, and so cannot be referred under it.
200    /// Codes are compared without case.
201    #[must_use]
202    pub fn owns(&self, code: &str) -> bool {
203        self.own_code().is_some_and(|own| own.eq_ignore_ascii_case(code))
204    }
205}
206
207#[cfg(test)]
208#[path = "tests/referral.rs"]
209mod tests;