Skip to main content

hypercall_client/
pm_financing.rs

1//! Portfolio Margin financing: read an account's PM loans and unpaid
2//! settlement obligations, and repay them from its HyperCore USDC.
3
4#![expect(
5    clippy::result_large_err,
6    reason = "these helpers preserve the established unboxed public ClientError contract"
7)]
8
9use alloy::sol;
10use reqwest::Method;
11use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13
14use crate::api::HypercallClient;
15use crate::error::{ClientError, Result};
16use crate::wallet::{AccountAddress, HypercallWallet};
17
18const API_ROUTE_PM_FINANCING: &str = "/v1/pm-financing";
19const API_ROUTE_PM_FINANCING_REPAY: &str = "/v1/pm-financing/repay";
20/// The signed `amount` that repays everything owed.
21const REPAY_ALL: &str = "all";
22/// Account.sol moves whole micro-USDC.
23const USDC_DECIMALS: u32 = 6;
24
25sol! {
26    /// Repay a Portfolio Margin account's PM financing from its HyperCore
27    /// USDC (`POST /v1/pm-financing/repay`), signed by the Account.sol
28    /// manager `wallet`. `amount` is the exact decimal string the request
29    /// carries, or `all`.
30    #[derive(Debug, PartialEq, Eq)]
31    struct RepayPmLoan {
32        address wallet;
33        address account;
34        string underlying;
35        string amount;
36        uint64 nonce;
37    }
38}
39
40/// How much PM financing to repay.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum RepayAmount {
43    /// An exact positive USDC amount with at most six decimal places.
44    Usdc(Decimal),
45    /// Everything owed on the loan, plus every unpaid settlement obligation.
46    All,
47}
48
49impl RepayAmount {
50    /// The `amount` string the request sends and the manager signs: `all`,
51    /// or the normalized decimal (`60.50` signs as `60.5`).
52    pub fn signed_amount(&self) -> Result<String> {
53        match self {
54            Self::All => Ok(REPAY_ALL.to_string()),
55            Self::Usdc(amount) => {
56                let amount = amount.normalize();
57                if amount <= Decimal::ZERO {
58                    return Err(ClientError::InvalidInput(
59                        "repay amount must be positive".to_string(),
60                    ));
61                }
62                if amount.scale() > USDC_DECIMALS {
63                    return Err(ClientError::InvalidInput(
64                        "repay amount must have at most 6 decimal places".to_string(),
65                    ));
66                }
67                Ok(amount.to_string())
68            }
69        }
70    }
71}
72
73/// A voluntary repayment of PM financing.
74#[derive(Debug, Clone)]
75pub struct RepayPmLoanParams {
76    /// The manager's Portfolio Margin Account.sol.
77    pub account: AccountAddress,
78    /// The loan's underlying, exactly as [`PmFinancingItem::underlying`]
79    /// lists it. Unpaid settlement obligations are always repaid first.
80    pub underlying: String,
81    pub amount: RepayAmount,
82    /// Millisecond time-bound nonce. Defaults to the wallet's next nonce.
83    /// Keep it to retry an ambiguous submission: an exact retry (same
84    /// account, underlying, amount and nonce) returns the original request.
85    pub nonce: Option<u64>,
86}
87
88/// `POST /v1/pm-financing/repay` acceptance. The USDC is reserved; the
89/// repayment lands once HyperCore confirms the transfer. Track it by
90/// `plan_id` in [`PmFinancingRepayment::requests`].
91#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
92pub struct PmLoanRepayResponse {
93    pub account: AccountAddress,
94    /// The request's id; an exact retry returns the same id.
95    pub request_id: String,
96    pub plan_id: String,
97    pub nonce: u64,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
101#[serde(rename_all = "snake_case")]
102pub enum PmFinancingItemKind {
103    Loan,
104    Settlement,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
108#[serde(rename_all = "snake_case")]
109pub enum PmFinancingItemStatus {
110    /// A floating loan: no deadline.
111    Open,
112    /// An unpaid settlement inside its cure period.
113    GracePeriod,
114    /// An unpaid settlement past its cure deadline.
115    Missed,
116}
117
118/// One loan or unpaid settlement obligation.
119#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
120pub struct PmFinancingItem {
121    pub kind: PmFinancingItemKind,
122    pub underlying: String,
123    pub expiry_ts_ms: Option<i64>,
124    pub principal_usdc: Decimal,
125    pub interest_usdc: Decimal,
126    pub paid_usdc: Option<Decimal>,
127    pub owed_usdc: Decimal,
128    pub since_ms: Option<u64>,
129    pub deadline_ms: Option<u64>,
130    pub status: PmFinancingItemStatus,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
134pub struct PmFinancingTotals {
135    pub loans_owed_usdc: Decimal,
136    pub settlements_owed_usdc: Decimal,
137    pub total_owed_usdc: Decimal,
138    pub missed_count: u64,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
142pub struct PmFinancingMargin {
143    pub equity_usdc: Decimal,
144    pub maintenance_requirement_usdc: Decimal,
145    /// Requirement over equity; `None` when equity is not positive.
146    pub margin_utilization: Option<Decimal>,
147}
148
149/// What a voluntary repayment may use now, and the latest requests.
150#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
151pub struct PmFinancingRepayment {
152    /// HyperCore USDC a new repayment may use: withdrawable minus active
153    /// withdrawal and recovery reservations. `None` before the engine has
154    /// the account's balance.
155    pub unreserved_withdrawable_usdc: Option<Decimal>,
156    /// Why a new request would be refused now; `None` when it would not.
157    /// [`PmRepaymentBlockedReason::rejection`] names the error such a
158    /// request gets.
159    pub blocked_reason: Option<PmRepaymentBlockedReason>,
160    /// The newest requests, newest first.
161    pub requests: Vec<PmLoanRepaymentRequest>,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
165pub struct PmLoanRepaymentRequest {
166    pub plan_id: String,
167    pub underlying: String,
168    pub amount_usdc: Decimal,
169    pub status: PmRepaymentStatus,
170    pub updated_at_ms: u64,
171}
172
173/// A voluntary repayment's recovery plan status, as the engine names it.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
175pub enum PmRepaymentStatus {
176    /// The account's HyperCore USDC is reserved; nothing has moved yet.
177    Planned,
178    /// The transfer was sent to HyperCore.
179    Submitted,
180    /// HyperCore confirmed the transfer; the repayment applies next.
181    Confirmed,
182    /// Transient: the recovery worker cancels the plan next.
183    Failed,
184    /// Transient: the recovery worker cancels the plan next.
185    TimedOut,
186    /// Nothing moved, or the transfer failed. Sign a new request.
187    Canceled,
188    /// Handed to operators.
189    EscalatedManual,
190    /// Part of the amount was applied.
191    PartiallyRepaid,
192    /// The repayment was applied.
193    Repaid,
194    /// A status this client version does not know.
195    #[serde(other)]
196    Unknown,
197}
198
199impl PmRepaymentStatus {
200    /// Whether the request is finished: `Repaid`, `Canceled` or
201    /// `EscalatedManual`. Poll [`HypercallClient::get_pm_financing`] until
202    /// this holds.
203    pub fn is_terminal(self) -> bool {
204        matches!(self, Self::Repaid | Self::Canceled | Self::EscalatedManual)
205    }
206}
207
208/// Why `GET /v1/pm-financing` says a new repayment would be refused now.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
210#[serde(rename_all = "snake_case")]
211pub enum PmRepaymentBlockedReason {
212    /// Another recovery plan of the account is still active.
213    RecoveryInProgress,
214    /// The account is below maintenance or in a liquidation state.
215    AccountUnhealthy,
216    /// A reason this client version does not know.
217    #[serde(other)]
218    Unknown,
219}
220
221impl PmRepaymentBlockedReason {
222    /// The rejection a repay request gets while this reason holds.
223    pub fn rejection(self) -> Option<PmRepayRejection> {
224        match self {
225            Self::RecoveryInProgress => Some(PmRepayRejection::RecoveryInProgress),
226            Self::AccountUnhealthy => Some(PmRepayRejection::AccountUnhealthy),
227            Self::Unknown => None,
228        }
229    }
230}
231
232/// A stable error code `POST /v1/pm-financing/repay` returns. Read it from a
233/// [`ClientError`] with [`PmRepayRejection::from_error`].
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum PmRepayRejection {
236    /// Voluntary repayment is off on this deployment (503).
237    Unavailable,
238    /// The nonce is outside the engine's time bounds (409). Sign again.
239    NonceOutOfBounds,
240    /// The nonce is bound to a different signed request (409).
241    NonceReused,
242    /// `underlying` names none of the account's loans or unpaid settlements
243    /// (400).
244    UnknownUnderlying,
245    /// The signer is not the account's engine-indexed manager (403).
246    Unauthorized,
247    /// The account is below maintenance or being liquidated (409). Matches
248    /// [`PmRepaymentBlockedReason::AccountUnhealthy`].
249    AccountUnhealthy,
250    /// Another recovery of the account is active (409). Matches
251    /// [`PmRepaymentBlockedReason::RecoveryInProgress`].
252    RecoveryInProgress,
253    /// Nothing is owed (409).
254    NothingOwed,
255    /// The amount is not a positive whole micro-USDC amount (400).
256    InvalidAmount,
257    /// An exact amount below the instance minimum that does not repay
258    /// everything owed (400).
259    BelowMinimum,
260    /// The amount exceeds what is owed (409).
261    ExceedsOwed,
262    /// The amount exceeds the unreserved withdrawable USDC (409).
263    InsufficientWithdrawable,
264    /// The engine refused it without a more specific code (422).
265    Rejected,
266    /// The signer is not the account's current Account.sol manager (403).
267    NotManager,
268    /// The API's nonce time-bound check failed (409). Sign again.
269    InvalidNonce,
270    /// The signature does not recover to `wallet`.
271    SignatureVerificationFailed,
272}
273
274impl PmRepayRejection {
275    pub const ALL: [Self; 16] = [
276        Self::Unavailable,
277        Self::NonceOutOfBounds,
278        Self::NonceReused,
279        Self::UnknownUnderlying,
280        Self::Unauthorized,
281        Self::AccountUnhealthy,
282        Self::RecoveryInProgress,
283        Self::NothingOwed,
284        Self::InvalidAmount,
285        Self::BelowMinimum,
286        Self::ExceedsOwed,
287        Self::InsufficientWithdrawable,
288        Self::Rejected,
289        Self::NotManager,
290        Self::InvalidNonce,
291        Self::SignatureVerificationFailed,
292    ];
293
294    /// The `code` the server sends.
295    pub const fn code(self) -> &'static str {
296        match self {
297            Self::Unavailable => "pm_voluntary_repayment_unavailable",
298            Self::NonceOutOfBounds => "pm_voluntary_repayment_nonce_out_of_bounds",
299            Self::NonceReused => "pm_voluntary_repayment_nonce_reused",
300            Self::UnknownUnderlying => "pm_voluntary_repayment_unknown_underlying",
301            Self::Unauthorized => "pm_voluntary_repayment_unauthorized",
302            Self::AccountUnhealthy => "pm_voluntary_repayment_account_unhealthy",
303            Self::RecoveryInProgress => "pm_voluntary_repayment_recovery_in_progress",
304            Self::NothingOwed => "pm_voluntary_repayment_nothing_owed",
305            Self::InvalidAmount => "pm_voluntary_repayment_invalid_amount",
306            Self::BelowMinimum => "pm_voluntary_repayment_below_minimum",
307            Self::ExceedsOwed => "pm_voluntary_repayment_exceeds_owed",
308            Self::InsufficientWithdrawable => "pm_voluntary_repayment_insufficient_withdrawable",
309            Self::Rejected => "pm_voluntary_repayment_rejected",
310            Self::NotManager => "forbidden",
311            Self::InvalidNonce => "invalid_nonce",
312            Self::SignatureVerificationFailed => "signature_verification_failed",
313        }
314    }
315
316    /// The rejection a server `code` names, if it is one of these.
317    pub fn from_code(code: &str) -> Option<Self> {
318        Self::ALL
319            .into_iter()
320            .find(|rejection| rejection.code() == code)
321    }
322
323    /// The rejection a failed [`HypercallClient::repay_pm_loan`] carries, if
324    /// the server named one.
325    pub fn from_error(error: &ClientError) -> Option<Self> {
326        Self::from_code(&error.api_error_code()?)
327    }
328
329    /// Whether signing the same request again with a fresh nonce may succeed
330    /// without anything else changing.
331    pub fn is_resignable(self) -> bool {
332        matches!(self, Self::NonceOutOfBounds | Self::InvalidNonce)
333    }
334}
335
336/// `GET /v1/pm-financing`: one wallet's PM borrowing.
337#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
338pub struct PmFinancingResponse {
339    pub wallet: AccountAddress,
340    /// The wallet's Portfolio Margin Account.sol, if it has one.
341    pub account: Option<AccountAddress>,
342    pub is_pm_account: bool,
343    pub measured_at_ms: u64,
344    pub borrow_apr: Decimal,
345    pub items: Vec<PmFinancingItem>,
346    pub totals: PmFinancingTotals,
347    pub margin: Option<PmFinancingMargin>,
348    /// Financed PM boxes, as the server returns them.
349    #[serde(default)]
350    pub box_financing: Option<serde_json::Value>,
351    /// Voluntary repayment capacity and requests. `None` for a Standard
352    /// account, or from a server without voluntary repayment.
353    #[serde(default)]
354    pub repayment: Option<PmFinancingRepayment>,
355}
356
357#[derive(Serialize)]
358struct RepayPmLoanRequest<'a> {
359    wallet: AccountAddress,
360    account: AccountAddress,
361    underlying: &'a str,
362    amount: &'a str,
363    nonce: u64,
364    signature: String,
365}
366
367impl HypercallWallet {
368    /// Sign a RepayPmLoan action. `amount` must be the exact string the
369    /// request sends (see [`RepayAmount::signed_amount`]).
370    pub async fn sign_repay_pm_loan(
371        &self,
372        account: AccountAddress,
373        underlying: &str,
374        amount: &str,
375        nonce: u64,
376    ) -> Result<String> {
377        let message = RepayPmLoan {
378            wallet: self.address.as_wallet_address().inner(),
379            account: account.as_wallet_address().inner(),
380            underlying: underlying.to_string(),
381            amount: amount.to_string(),
382            nonce,
383        };
384        self.sign_hypercall_action(&message, "RepayPmLoan").await
385    }
386}
387
388impl HypercallClient {
389    /// Read `wallet`'s PM loans, unpaid settlement obligations, margin and
390    /// voluntary repayment status. `wallet` is the manager or its Account.sol.
391    pub async fn get_pm_financing(&self, wallet: AccountAddress) -> Result<PmFinancingResponse> {
392        Self::send_reqwest_json(
393            self.request(Method::GET, API_ROUTE_PM_FINANCING)
394                .query(&[("wallet", wallet.to_string())]),
395            "get PM financing",
396        )
397        .await
398    }
399
400    /// Repay PM financing from the account's HyperCore USDC. `manager` must
401    /// be the account's Account.sol manager; API wallets and agents are
402    /// refused.
403    ///
404    /// Acceptance reserves the USDC; poll [`Self::get_pm_financing`] until
405    /// the request reaches `Repaid` or `Canceled`. Rejections surface as
406    /// [`ClientError::Api`] carrying a `pm_voluntary_repayment_*` code.
407    pub async fn repay_pm_loan(
408        &self,
409        manager: &HypercallWallet,
410        params: RepayPmLoanParams,
411    ) -> Result<PmLoanRepayResponse> {
412        if params.underlying.is_empty() {
413            return Err(ClientError::InvalidInput(
414                "underlying must name the loan's underlying".to_string(),
415            ));
416        }
417        let amount = params.amount.signed_amount()?;
418        let nonce = params.nonce.unwrap_or_else(|| manager.next_nonce());
419        let signature = manager
420            .sign_repay_pm_loan(params.account, &params.underlying, &amount, nonce)
421            .await?;
422        let request = RepayPmLoanRequest {
423            wallet: manager.address,
424            account: params.account,
425            underlying: &params.underlying,
426            amount: &amount,
427            nonce,
428            signature,
429        };
430        Self::send_json_body(
431            self.request(Method::POST, API_ROUTE_PM_FINANCING_REPAY),
432            &request,
433            "repay PM loan",
434        )
435        .await
436    }
437}
438
439#[cfg(test)]
440#[path = "pm_financing_test.rs"]
441mod tests;