1#![expect(
4 clippy::result_large_err,
5 reason = "these helpers preserve the established unboxed public ClientError contract"
6)]
7
8use std::{str::FromStr, time::Duration};
9
10use alloy::eips::eip2718::Encodable2718;
11use alloy::network::{Ethereum, EthereumWallet, Network, ReceiptResponse, TransactionBuilder};
12use alloy::primitives::{Address, B256, U256};
13use alloy::providers::{Provider, ProviderBuilder};
14use alloy::sol;
15use hypercall_sdk_types::{
16 MarginMode, PortfolioUsdcWithdrawalResponse, StandardUsdcWithdrawalResponse,
17};
18use reqwest::Method;
19use rust_decimal::prelude::ToPrimitive;
20use rust_decimal::Decimal;
21use serde::{Deserialize, Serialize};
22
23use crate::api::HypercallClient;
24use crate::error::{ClientError, Result};
25use crate::wallet::{
26 evm_submission_lock, AccountAddress, HypercallWallet, PortfolioUsdcWithdrawalSignature,
27 StandardUsdcWithdrawalSignature, UsdcWithdrawalSigner,
28};
29
30const USDC_DECIMALS: u32 = 6;
31const HYPERCORE_USDC_DECIMALS: u32 = 8;
32const TRANSACTION_CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(120);
33
34type TransactionReceipt = <Ethereum as Network>::ReceiptResponse;
35type TransactionRequest = <Ethereum as Network>::TransactionRequest;
36
37sol! {
38 #[sol(rpc)]
39 interface HyperEvmUsdc {
40 function decimals() external view returns (uint8);
41 function balanceOf(address account) external view returns (uint256);
42 function allowance(address owner, address spender) external view returns (uint256);
43 function approve(address spender, uint256 amount) external returns (bool);
44 }
45
46 #[sol(rpc)]
47 interface HypercallExchange {
48 function usdc() external view returns (address);
49 function depositUsdcFor(address account, uint256 amount) external;
50 }
51
52 #[sol(rpc)]
53 interface HypercallDepositRouter {
54 function USDC() external view returns (address);
55 function deposit(address account, address token, uint256 amount, bool isPerp) external;
56 }
57}
58
59#[derive(Debug, Clone)]
61pub struct DepositUsdcParams {
62 pub rpc_url: String,
64 pub usdc_address: AccountAddress,
66 pub account: AccountAddress,
68 pub amount: Decimal,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct DepositUsdcResult {
75 pub approval_transaction_hash: Option<B256>,
77 pub deposit_transaction_hash: B256,
79 pub deposit_block_number: u64,
81}
82
83#[derive(Debug, Clone, Copy)]
85pub struct WithdrawUsdcParams {
86 pub account: AccountAddress,
88 pub destination: AccountAddress,
90 pub amount: Decimal,
94 pub nonce: Option<u64>,
96}
97
98#[derive(Debug, Clone, Copy)]
99enum DepositTarget {
100 Exchange(Address),
101 Router(Address),
102}
103
104struct DepositSubmitter {
105 wallet: EthereumWallet,
106 chain_id: u64,
107 address: Address,
108}
109
110impl DepositSubmitter {
111 fn new(wallet: &HypercallWallet) -> Self {
112 Self {
113 wallet: wallet.ethereum_wallet(),
114 chain_id: wallet.chain_id(),
115 address: wallet.address.as_wallet_address().inner(),
116 }
117 }
118}
119
120impl DepositTarget {
121 fn address(self) -> Address {
122 match self {
123 Self::Exchange(address) | Self::Router(address) => address,
124 }
125 }
126}
127
128#[derive(Serialize)]
129struct WithdrawUsdcRequest<'a> {
130 wallet: AccountAddress,
131 account: AccountAddress,
132 destination: AccountAddress,
133 amount: &'a str,
134 nonce: u64,
135 signature: String,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 destination_dex: Option<u32>,
138}
139
140#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
142pub struct WithdrawUsdcRoute {
143 pub destination: AccountAddress,
144 pub destination_dex: u32,
145}
146
147impl HypercallClient {
148 pub async fn deposit_standard_usdc(
150 &self,
151 funder: &HypercallWallet,
152 params: DepositUsdcParams,
153 ) -> Result<DepositUsdcResult> {
154 let amount_units = decimal_to_units(params.amount, USDC_DECIMALS, "deposit amount")?;
155 validate_nonzero(params.account, "deposit account")?;
156 validate_nonzero(params.usdc_address, "USDC address")?;
157
158 let exchange_info = self.get_exchange_info().await?;
159 validate_api_chain_id(exchange_info.chain_id, funder.chain_id())?;
160 let portfolio = self.get_portfolio_snapshot(params.account).await?;
161 validate_portfolio_identity(&portfolio, params.account, MarginMode::Standard)?;
162 let exchange = parse_nonzero_address(&exchange_info.exchange_address, "Exchange address")?;
163
164 self.execute_deposit(
165 funder,
166 params,
167 U256::from(amount_units),
168 DepositTarget::Exchange(exchange),
169 )
170 .await
171 }
172
173 pub async fn deposit_portfolio_usdc(
175 &self,
176 manager: &HypercallWallet,
177 params: DepositUsdcParams,
178 ) -> Result<DepositUsdcResult> {
179 let amount_units = decimal_to_units(params.amount, USDC_DECIMALS, "deposit amount")?;
180 validate_nonzero(params.account, "deposit account")?;
181 validate_nonzero(params.usdc_address, "USDC address")?;
182
183 let exchange_info = self.get_exchange_info().await?;
184 validate_api_chain_id(exchange_info.chain_id, manager.chain_id())?;
185 let router = portfolio_deposit_router(&exchange_info)?;
186 let portfolio = self.get_portfolio_snapshot(manager.address).await?;
187 validate_portfolio_identity(&portfolio, params.account, MarginMode::Portfolio)?;
188
189 self.execute_deposit(
190 manager,
191 params,
192 U256::from(amount_units),
193 DepositTarget::Router(router),
194 )
195 .await
196 }
197
198 pub async fn withdraw_standard_usdc<S>(
203 &self,
204 signer: &S,
205 params: WithdrawUsdcParams,
206 ) -> Result<StandardUsdcWithdrawalResponse>
207 where
208 S: UsdcWithdrawalSigner + ?Sized,
209 {
210 decimal_to_units(params.amount, USDC_DECIMALS, "withdrawal amount")?;
211 validate_withdrawal_addresses(params.account, params.destination)?;
212 let amount = canonical_decimal_string(params.amount);
213 let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
214 let wallet = signer.address();
215 let signature = signer
216 .sign_standard_usdc_withdrawal_payload(StandardUsdcWithdrawalSignature {
217 wallet,
218 account: params.account,
219 destination: params.destination,
220 amount: &amount,
221 nonce,
222 })
223 .await?;
224 let request = WithdrawUsdcRequest {
225 wallet,
226 account: params.account,
227 destination: params.destination,
228 amount: &amount,
229 nonce,
230 signature,
231 destination_dex: None,
232 };
233 self.submit_usdc_withdrawal(
234 "/withdraw/usdc",
235 &request,
236 "Standard Margin USDC withdrawal",
237 )
238 .await
239 }
240
241 pub async fn withdraw_portfolio_usdc<S>(
246 &self,
247 signer: &S,
248 params: WithdrawUsdcParams,
249 ) -> Result<PortfolioUsdcWithdrawalResponse>
250 where
251 S: UsdcWithdrawalSigner + ?Sized,
252 {
253 decimal_to_units(params.amount, USDC_DECIMALS, "portfolio withdrawal amount")?;
254 let route = self
255 .prepare_usdc_withdrawal_route(params.destination)
256 .await?;
257 self.withdraw_portfolio_usdc_with_route(signer, params, route)
258 .await
259 }
260
261 pub async fn prepare_usdc_withdrawal_route(
263 &self,
264 destination: AccountAddress,
265 ) -> Result<WithdrawUsdcRoute> {
266 let route: WithdrawUsdcRoute = Self::send_reqwest_json(
267 self.request(Method::GET, "/withdraw/usdc/route")
268 .query(&[("destination", destination.to_string())]),
269 "prepare USDC withdrawal route",
270 )
271 .await?;
272 if route.destination != destination {
273 return Err(ClientError::InvalidInput(
274 "withdrawal route response changed the destination".to_string(),
275 ));
276 }
277 validate_destination_dex(route.destination_dex)?;
278 Ok(route)
279 }
280
281 pub async fn withdraw_portfolio_usdc_with_route<S>(
286 &self,
287 signer: &S,
288 params: WithdrawUsdcParams,
289 route: WithdrawUsdcRoute,
290 ) -> Result<PortfolioUsdcWithdrawalResponse>
291 where
292 S: UsdcWithdrawalSigner + ?Sized,
293 {
294 let amount_wei = decimal_to_units(
295 params.amount,
296 HYPERCORE_USDC_DECIMALS,
297 "portfolio withdrawal amount",
298 )?;
299 let amount_wei = u64::try_from(amount_wei).map_err(|_| {
300 ClientError::InvalidInput(
301 "portfolio withdrawal amount exceeds HyperCore uint64 units".to_string(),
302 )
303 })?;
304 validate_withdrawal_addresses(params.account, params.destination)?;
305 if route.destination != params.destination {
306 return Err(ClientError::InvalidInput(
307 "prepared withdrawal route does not match the destination".to_string(),
308 ));
309 }
310 validate_destination_dex(route.destination_dex)?;
311 let amount = canonical_decimal_string(params.amount);
312 let nonce = params.nonce.unwrap_or_else(|| signer.next_nonce());
313 let wallet = signer.address();
314 let signature = signer
315 .sign_portfolio_usdc_withdrawal_payload(PortfolioUsdcWithdrawalSignature {
316 account: params.account,
317 destination: params.destination,
318 amount_wei,
319 destination_dex: route.destination_dex,
320 nonce,
321 })
322 .await?;
323 let request = WithdrawUsdcRequest {
324 wallet,
325 account: params.account,
326 destination: params.destination,
327 amount: &amount,
328 nonce,
329 signature,
330 destination_dex: Some(route.destination_dex),
331 };
332 self.submit_usdc_withdrawal(
333 "/withdraw/pm-usdc",
334 &request,
335 "Portfolio Margin USDC withdrawal",
336 )
337 .await
338 }
339
340 async fn submit_usdc_withdrawal<T>(
341 &self,
342 route: &str,
343 request: &WithdrawUsdcRequest<'_>,
344 action: &str,
345 ) -> Result<T>
346 where
347 T: serde::de::DeserializeOwned,
348 {
349 match Self::send_json_body(self.request(Method::POST, route), request, action).await {
350 Err(error) if withdrawal_submission_is_ambiguous(&error) => {
351 Err(ClientError::WithdrawalSubmissionAmbiguous {
352 action: action.to_owned(),
353 route: route.to_owned(),
354 account: request.account,
355 destination: request.destination,
356 destination_dex: request.destination_dex,
357 amount: request.amount.to_owned(),
358 nonce: request.nonce,
359 source: Box::new(error),
360 })
361 }
362 result => result,
363 }
364 }
365
366 async fn execute_deposit(
367 &self,
368 funder: &HypercallWallet,
369 params: DepositUsdcParams,
370 amount_units: U256,
371 target: DepositTarget,
372 ) -> Result<DepositUsdcResult> {
373 let rpc_url = params
374 .rpc_url
375 .parse()
376 .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
377 let provider = ProviderBuilder::new().connect_http(rpc_url);
378 let rpc_chain_id = provider
379 .get_chain_id()
380 .await
381 .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
382 validate_rpc_chain_id(rpc_chain_id, funder.chain_id())?;
383
384 let submission_lock = evm_submission_lock(funder.address.as_wallet_address().inner());
385 let _submission_guard = submission_lock.lock().await;
386 execute_deposit_on_provider(
387 &provider,
388 DepositSubmitter::new(funder),
389 params.usdc_address.as_wallet_address().inner(),
390 params.account.as_wallet_address().inner(),
391 amount_units,
392 target,
393 )
394 .await
395 }
396}
397
398fn validate_destination_dex(destination_dex: u32) -> Result<()> {
399 if matches!(destination_dex, 0 | u32::MAX) {
400 Ok(())
401 } else {
402 Err(ClientError::InvalidInput(
403 "withdrawal route response returned an unsupported destination dex".to_string(),
404 ))
405 }
406}
407
408async fn execute_deposit_on_provider<P>(
409 provider: &P,
410 submitter: DepositSubmitter,
411 usdc_address: Address,
412 account: Address,
413 amount_units: U256,
414 target: DepositTarget,
415) -> Result<DepositUsdcResult>
416where
417 P: Provider,
418{
419 let DepositSubmitter {
420 wallet,
421 chain_id,
422 address: funder,
423 } = submitter;
424 let canonical_usdc = match target {
425 DepositTarget::Exchange(exchange) => HypercallExchange::new(exchange, provider)
426 .usdc()
427 .call()
428 .await
429 .map_err(|error| onchain_error("read Exchange canonical USDC", error))?,
430 DepositTarget::Router(router) => HypercallDepositRouter::new(router, provider)
431 .USDC()
432 .call()
433 .await
434 .map_err(|error| onchain_error("read Router canonical USDC", error))?,
435 };
436 if canonical_usdc != usdc_address {
437 return Err(ClientError::InvalidInput(format!(
438 "supplied USDC address {usdc_address} does not match the funding contract's canonical USDC {canonical_usdc}"
439 )));
440 }
441
442 let usdc = HyperEvmUsdc::new(usdc_address, provider);
443 let decimals = usdc
444 .decimals()
445 .call()
446 .await
447 .map_err(|error| onchain_error("read USDC decimals", error))?;
448 if decimals != USDC_DECIMALS as u8 {
449 return Err(ClientError::InvalidInput(format!(
450 "USDC contract reports {decimals} decimals, expected {USDC_DECIMALS}"
451 )));
452 }
453 let balance = usdc
454 .balanceOf(funder)
455 .call()
456 .await
457 .map_err(|error| onchain_error("read HyperEVM USDC balance", error))?;
458 if balance < amount_units {
459 return Err(ClientError::InvalidInput(format!(
460 "insufficient HyperEVM USDC balance: have {balance} base units, need {amount_units}"
461 )));
462 }
463
464 let spender = target.address();
465 let allowance = usdc
466 .allowance(funder, spender)
467 .call()
468 .await
469 .map_err(|error| onchain_error("read HyperEVM USDC allowance", error))?;
470 let approval_transaction_hash = if allowance < amount_units {
471 let request = usdc
472 .approve(spender, amount_units)
473 .from(funder)
474 .into_transaction_request();
475 let (tx_hash, receipt) = submit_contract_transaction(
476 provider,
477 &wallet,
478 chain_id,
479 funder,
480 request,
481 "HyperEVM USDC approval",
482 )
483 .await?;
484 if !receipt.status() {
485 return Err(ClientError::TransactionReverted {
486 operation: "HyperEVM USDC approval",
487 transaction_hash: Some(tx_hash),
488 });
489 }
490 Some(tx_hash)
491 } else {
492 None
493 };
494
495 let request = match target {
496 DepositTarget::Exchange(exchange) => HypercallExchange::new(exchange, provider)
497 .depositUsdcFor(account, amount_units)
498 .from(funder)
499 .into_transaction_request(),
500 DepositTarget::Router(router) => HypercallDepositRouter::new(router, provider)
501 .deposit(account, usdc_address, amount_units, true)
502 .from(funder)
503 .into_transaction_request(),
504 };
505 let operation = approval_transaction_hash.map_or_else(
506 || "Hypercall USDC deposit".to_string(),
507 |tx_hash| format!("Hypercall USDC deposit after confirmed approval {tx_hash}"),
508 );
509 let (deposit_transaction_hash, receipt) =
510 submit_contract_transaction(provider, &wallet, chain_id, funder, request, &operation)
511 .await?;
512 if !receipt.status() {
513 return Err(ClientError::TransactionReverted {
514 operation: "Hypercall USDC deposit",
515 transaction_hash: Some(deposit_transaction_hash),
516 });
517 }
518 let deposit_block_number =
519 receipt
520 .block_number()
521 .ok_or(ClientError::MissingTransactionBlock {
522 transaction_hash: deposit_transaction_hash,
523 })?;
524
525 Ok(DepositUsdcResult {
526 approval_transaction_hash,
527 deposit_transaction_hash,
528 deposit_block_number,
529 })
530}
531
532fn withdrawal_submission_is_ambiguous(error: &ClientError) -> bool {
533 matches!(
534 error,
535 ClientError::Http(_)
536 | ClientError::Api {
537 status: 500..=599,
538 ..
539 }
540 )
541}
542
543async fn submit_contract_transaction<P>(
546 provider: &P,
547 wallet: &EthereumWallet,
548 chain_id: u64,
549 sender: Address,
550 mut request: TransactionRequest,
551 operation: &str,
552) -> Result<(B256, TransactionReceipt)>
553where
554 P: Provider,
555{
556 request.from = Some(sender);
557 request.chain_id = Some(chain_id);
558 request.nonce = Some(
559 provider
560 .get_transaction_count(sender)
561 .pending()
562 .await
563 .map_err(|error| {
564 onchain_error(format!("resolve pending nonce for {operation}"), error)
565 })?,
566 );
567 let fees = provider
568 .estimate_eip1559_fees()
569 .await
570 .map_err(|error| onchain_error(format!("estimate EIP-1559 fees for {operation}"), error))?;
571 request.max_fee_per_gas = Some(fees.max_fee_per_gas);
572 request.max_priority_fee_per_gas = Some(fees.max_priority_fee_per_gas);
573 request.gas = Some(
574 provider
575 .estimate_gas(request.clone())
576 .await
577 .map_err(|error| onchain_error(format!("estimate gas for {operation}"), error))?,
578 );
579
580 let signed = request
581 .build(wallet)
582 .await
583 .map_err(|error| onchain_error(format!("sign {operation}"), error))?;
584 let tx_hash = *signed.tx_hash();
585 let mut raw_transaction = Vec::with_capacity(signed.encode_2718_len());
586 signed.encode_2718(&mut raw_transaction);
587
588 let pending = provider
589 .send_raw_transaction(&raw_transaction)
590 .await
591 .map_err(|error| ClientError::TransactionSubmissionUnknown {
592 operation: operation.to_owned(),
593 transaction_hash: tx_hash,
594 source: Box::new(error),
595 })?;
596 let receipt = pending
597 .with_timeout(Some(TRANSACTION_CONFIRMATION_TIMEOUT))
598 .get_receipt()
599 .await
600 .map_err(|error| ClientError::TransactionConfirmationUnknown {
601 operation: operation.to_owned(),
602 transaction_hash: tx_hash,
603 source: Box::new(error),
604 })?;
605 Ok((tx_hash, receipt))
606}
607
608fn decimal_to_units(amount: Decimal, decimals: u32, name: &str) -> Result<u128> {
609 if amount <= Decimal::ZERO {
610 return Err(ClientError::InvalidInput(format!(
611 "{name} must be positive"
612 )));
613 }
614 let normalized = amount.normalize();
615 if normalized.scale() > decimals {
616 return Err(ClientError::InvalidInput(format!(
617 "{name} supports at most {decimals} decimal places"
618 )));
619 }
620 let multiplier = Decimal::from(10_u64.pow(decimals));
621 normalized
622 .checked_mul(multiplier)
623 .and_then(|scaled| scaled.to_u128())
624 .ok_or_else(|| ClientError::InvalidInput(format!("{name} is too large")))
625}
626
627fn canonical_decimal_string(amount: Decimal) -> String {
628 amount.normalize().to_string()
629}
630
631fn validate_nonzero(address: AccountAddress, name: &str) -> Result<()> {
632 if address.as_wallet_address().inner() == Address::ZERO {
633 return Err(ClientError::InvalidInput(format!("{name} must be nonzero")));
634 }
635 Ok(())
636}
637
638fn validate_withdrawal_addresses(
639 account: AccountAddress,
640 destination: AccountAddress,
641) -> Result<()> {
642 validate_nonzero(account, "withdrawal account")?;
643 validate_nonzero(destination, "withdrawal destination")
644}
645
646fn parse_nonzero_address(value: &str, name: &str) -> Result<Address> {
647 let address = Address::from_str(value)
648 .map_err(|source| ClientError::invalid_input(name.to_owned(), source))?;
649 if address == Address::ZERO {
650 return Err(ClientError::InvalidInput(format!("{name} must be nonzero")));
651 }
652 Ok(address)
653}
654
655fn validate_api_chain_id(api_chain_id: u64, wallet_chain_id: u64) -> Result<()> {
656 if api_chain_id == wallet_chain_id {
657 return Ok(());
658 }
659 Err(ClientError::InvalidInput(format!(
660 "API chain ID {api_chain_id} does not match wallet chain ID {wallet_chain_id}"
661 )))
662}
663
664fn validate_rpc_chain_id(rpc_chain_id: u64, wallet_chain_id: u64) -> Result<()> {
665 if rpc_chain_id == wallet_chain_id {
666 return Ok(());
667 }
668 Err(ClientError::InvalidInput(format!(
669 "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {wallet_chain_id}"
670 )))
671}
672
673fn validate_portfolio_identity(
674 portfolio: &hypercall_sdk_types::Portfolio,
675 expected_account: AccountAddress,
676 expected_mode: MarginMode,
677) -> Result<()> {
678 if portfolio.wallet_address != expected_account.into_wallet_address() {
679 return Err(ClientError::InvalidInput(format!(
680 "resolved account {} does not match requested account {expected_account}",
681 portfolio.wallet_address
682 )));
683 }
684 let actual_mode = portfolio
685 .margin_mode_kind()
686 .map_err(|source| ClientError::invalid_input("account margin mode", source))?;
687 if actual_mode != expected_mode {
688 return Err(ClientError::InvalidInput(format!(
689 "account {} uses {} margin, expected {} margin",
690 portfolio.wallet_address,
691 actual_mode.as_str(),
692 expected_mode.as_str()
693 )));
694 }
695 Ok(())
696}
697
698fn portfolio_deposit_router(
699 exchange_info: &hypercall_sdk_types::ExchangeInfoResponse,
700) -> Result<Address> {
701 if !exchange_info.portfolio_margin_deposits_enabled {
702 return Err(ClientError::InvalidInput(
703 "portfolio-margin deposits are disabled".to_string(),
704 ));
705 }
706 exchange_info
707 .deposit_router_address
708 .as_deref()
709 .ok_or_else(|| {
710 ClientError::InvalidInput("portfolio-margin deposit Router is unavailable".to_string())
711 })
712 .and_then(|address| parse_nonzero_address(address, "deposit Router address"))
713}
714
715fn onchain_error(
716 operation: impl Into<String>,
717 source: impl std::error::Error + Send + Sync + 'static,
718) -> ClientError {
719 ClientError::Onchain {
720 operation: operation.into(),
721 source: Box::new(source),
722 }
723}
724
725#[cfg(test)]
726#[path = "funding_test.rs"]
727mod tests;