1#![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";
20const REPAY_ALL: &str = "all";
22const USDC_DECIMALS: u32 = 6;
24
25sol! {
26 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum RepayAmount {
43 Usdc(Decimal),
45 All,
47}
48
49impl RepayAmount {
50 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#[derive(Debug, Clone)]
75pub struct RepayPmLoanParams {
76 pub account: AccountAddress,
78 pub underlying: String,
81 pub amount: RepayAmount,
82 pub nonce: Option<u64>,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
92pub struct PmLoanRepayResponse {
93 pub account: AccountAddress,
94 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 Open,
112 GracePeriod,
114 Missed,
116}
117
118#[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 pub margin_utilization: Option<Decimal>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
151pub struct PmFinancingRepayment {
152 pub unreserved_withdrawable_usdc: Option<Decimal>,
156 pub blocked_reason: Option<PmRepaymentBlockedReason>,
160 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
175pub enum PmRepaymentStatus {
176 Planned,
178 Submitted,
180 Confirmed,
182 Failed,
184 TimedOut,
186 Canceled,
188 EscalatedManual,
190 PartiallyRepaid,
192 Repaid,
194 #[serde(other)]
196 Unknown,
197}
198
199impl PmRepaymentStatus {
200 pub fn is_terminal(self) -> bool {
204 matches!(self, Self::Repaid | Self::Canceled | Self::EscalatedManual)
205 }
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
210#[serde(rename_all = "snake_case")]
211pub enum PmRepaymentBlockedReason {
212 RecoveryInProgress,
214 AccountUnhealthy,
216 #[serde(other)]
218 Unknown,
219}
220
221impl PmRepaymentBlockedReason {
222 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum PmRepayRejection {
236 Unavailable,
238 NonceOutOfBounds,
240 NonceReused,
242 UnknownUnderlying,
245 Unauthorized,
247 AccountUnhealthy,
250 RecoveryInProgress,
253 NothingOwed,
255 InvalidAmount,
257 BelowMinimum,
260 ExceedsOwed,
262 InsufficientWithdrawable,
264 Rejected,
266 NotManager,
268 InvalidNonce,
270 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 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 pub fn from_code(code: &str) -> Option<Self> {
318 Self::ALL
319 .into_iter()
320 .find(|rejection| rejection.code() == code)
321 }
322
323 pub fn from_error(error: &ClientError) -> Option<Self> {
326 Self::from_code(&error.api_error_code()?)
327 }
328
329 pub fn is_resignable(self) -> bool {
332 matches!(self, Self::NonceOutOfBounds | Self::InvalidNonce)
333 }
334}
335
336#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
338pub struct PmFinancingResponse {
339 pub wallet: AccountAddress,
340 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 #[serde(default)]
350 pub box_financing: Option<serde_json::Value>,
351 #[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 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 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 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, ¶ms.underlying, &amount, nonce)
421 .await?;
422 let request = RepayPmLoanRequest {
423 wallet: manager.address,
424 account: params.account,
425 underlying: ¶ms.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;