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")]
73pub struct Referral {
74    /// Who referred the account (`referredBy`); `None` when no one did.
75    #[serde(default)]
76    pub referred_by: Option<ReferredBy>,
77    /// The account's own volume (`cumVlm`), in USDC.
78    pub cum_vlm: Dec,
79    /// Referral rewards not yet claimed (`unclaimedRewards`), in USDC.
80    pub unclaimed_rewards: Dec,
81    /// Referral rewards already claimed (`claimedRewards`), in USDC.
82    pub claimed_rewards: Dec,
83    /// What the account has earned as a builder (`builderRewards`), in USDC; zero when left out.
84    #[serde(default)]
85    pub builder_rewards: Dec,
86    /// Where the account stands as a referrer (`referrerState`).
87    pub referrer_state: ReferrerState,
88    /// Each quote token's figures, by the token's index (`0` USDC); not always sent.
89    #[serde(default)]
90    pub token_to_state: Option<Vec<(u32, TokenRewards)>>,
91}
92
93/// What an account traded and was paid in one quote token.
94#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub struct TokenRewards {
97    /// The account's own volume in this token (`cumVlm`).
98    pub cum_vlm: Dec,
99    /// Referral rewards in this token not yet claimed (`unclaimedRewards`).
100    pub unclaimed_rewards: Dec,
101    /// Referral rewards in this token already claimed (`claimedRewards`).
102    pub claimed_rewards: Dec,
103    /// What the account has earned in this token as a builder (`builderRewards`).
104    pub builder_rewards: Dec,
105}
106
107/// Who referred an account, and under which code.
108#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
109pub struct ReferredBy {
110    /// The address that owns the code.
111    pub referrer: Address,
112    /// The code the account was referred under.
113    pub code: String,
114}
115
116/// `stage` is `needToTrade` (with `required`, the volume still to trade),
117/// `needToCreateCode`, or `ready` (with the account's own `code`).
118#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
119pub struct ReferrerState {
120    /// `needToTrade`, `needToCreateCode` or `ready`.
121    pub stage: String,
122    /// The stage's figures; `None` when the stage has none.
123    #[serde(default)]
124    pub data: Option<ReferrerData>,
125}
126
127/// What a [`ReferrerState`] stage carries: the code once made, or the volume still to trade.
128#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct ReferrerData {
131    /// The account's own code (`code`); `None` until it has made one.
132    #[serde(default)]
133    pub code: Option<String>,
134    /// The volume still to trade before a code can be made (`required`), in USDC; `None` once
135    /// traded.
136    #[serde(default)]
137    pub required: Option<Dec>,
138    /// How many accounts were referred under the code (`nReferrals`); `None` when not sent.
139    #[serde(default)]
140    pub n_referrals: Option<u64>,
141    /// The accounts referred under the code.
142    #[serde(default)]
143    pub referral_states: Vec<ReferralState>,
144}
145
146/// One account referred under the code. Per-token figures are left unread.
147#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub struct ReferralState {
150    /// The referred account's address.
151    pub user: Address,
152    /// The referred account's volume (`cumVlm`), in USDC.
153    #[serde(default)]
154    pub cum_vlm: Dec,
155    /// The referred account's fees counted for rewards since it was referred
156    /// (`cumRewardedFeesSinceReferred`), in USDC.
157    #[serde(default)]
158    pub cum_rewarded_fees_since_referred: Dec,
159    /// What the referred account's fees have paid the referrer (`cumFeesRewardedToReferrer`), in
160    /// USDC.
161    #[serde(default)]
162    pub cum_fees_rewarded_to_referrer: Dec,
163    /// Milliseconds.
164    #[serde(default)]
165    pub time_joined: u64,
166}
167
168impl Referral {
169    /// One quote token's figures, by its index.
170    #[must_use]
171    pub fn token(&self, index: u32) -> Option<&TokenRewards> {
172        self.token_to_state.as_deref()?.iter().find(|(token, _)| *token == index).map(|(_, state)| state)
173    }
174
175    /// The account's own code, once it has made one.
176    #[must_use]
177    pub fn own_code(&self) -> Option<&str> {
178        self.referrer_state.data.as_ref()?.code.as_deref()
179    }
180
181    /// The code the account trades under, if any.
182    #[must_use]
183    pub fn referred_code(&self) -> Option<&str> {
184        self.referred_by.as_ref().map(|by| by.code.as_str())
185    }
186
187    /// Who owns the code the account trades under.
188    #[must_use]
189    pub fn referrer(&self) -> Option<Address> {
190        self.referred_by.as_ref().map(|by| by.referrer)
191    }
192
193    /// Whether the account owns `code`, and so cannot be referred under it.
194    /// Codes are compared without case.
195    #[must_use]
196    pub fn owns(&self, code: &str) -> bool {
197        self.own_code().is_some_and(|own| own.eq_ignore_ascii_case(code))
198    }
199}
200
201#[cfg(test)]
202#[path = "tests/referral.rs"]
203mod tests;