1#![expect(
3 clippy::result_large_err,
4 reason = "wallet methods preserve the established unboxed public ClientError contract"
5)]
6use std::{
52 collections::HashMap,
53 str::FromStr,
54 sync::{
55 atomic::{AtomicU64, Ordering},
56 Arc, Mutex as StdMutex, OnceLock, Weak,
57 },
58};
59
60#[cfg(feature = "kms")]
61use alloy::signers::aws::{aws_config, aws_sdk_kms, AwsSigner};
62use alloy::{
63 primitives::{Address, Signature, B256},
64 signers::{local::PrivateKeySigner, Signer},
65 sol,
66 sol_types::{Eip712Domain, SolStruct},
67};
68use hypercall_sdk_types::{
69 HcUpdateApiWalletAction, HlCancelByCloidAction, HlCancelByOidAction, HlLimitOrderAction,
70 HlSetAbstractionAction, OrderRoute, WalletAddress,
71};
72#[cfg(feature = "rfq-v2")]
73use hypercall_sdk_types::{RfqV2ReadGrant, RfqV2Signature};
74use tokio::sync::Mutex;
75
76#[cfg(feature = "kms")]
77use crate::error::SigningUnavailableReason;
78use crate::error::{ClientError, Result};
79
80pub(crate) fn evm_submission_lock(sender: Address) -> Arc<Mutex<()>> {
81 static LOCKS: OnceLock<StdMutex<HashMap<Address, Weak<Mutex<()>>>>> = OnceLock::new();
82
83 let mut locks = LOCKS
84 .get_or_init(|| StdMutex::new(HashMap::new()))
85 .lock()
86 .expect("EVM submission lock registry poisoned");
87 if let Some(lock) = locks.get(&sender).and_then(Weak::upgrade) {
88 return lock;
89 }
90
91 locks.retain(|_, lock| lock.strong_count() > 0);
92 let lock = Arc::new(Mutex::new(()));
93 locks.insert(sender, Arc::downgrade(&lock));
94 lock
95}
96
97#[derive(
99 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
100)]
101#[serde(transparent)]
102pub struct AccountAddress(WalletAddress);
103
104impl AccountAddress {
105 pub fn as_wallet_address(&self) -> &WalletAddress {
106 &self.0
107 }
108
109 pub fn into_wallet_address(self) -> WalletAddress {
110 self.0
111 }
112
113 pub fn as_hex(&self) -> String {
114 self.0.as_hex()
115 }
116}
117
118impl std::ops::Deref for AccountAddress {
119 type Target = WalletAddress;
120
121 fn deref(&self) -> &Self::Target {
122 &self.0
123 }
124}
125
126impl From<WalletAddress> for AccountAddress {
127 fn from(address: WalletAddress) -> Self {
128 Self(address)
129 }
130}
131
132impl From<&WalletAddress> for AccountAddress {
133 fn from(address: &WalletAddress) -> Self {
134 Self(*address)
135 }
136}
137
138impl From<AccountAddress> for WalletAddress {
139 fn from(address: AccountAddress) -> Self {
140 address.0
141 }
142}
143
144impl From<&AccountAddress> for AccountAddress {
145 fn from(address: &AccountAddress) -> Self {
146 *address
147 }
148}
149
150impl From<alloy::primitives::Address> for AccountAddress {
151 fn from(address: alloy::primitives::Address) -> Self {
152 Self(WalletAddress::from(address))
153 }
154}
155
156impl FromStr for AccountAddress {
157 type Err = <WalletAddress as FromStr>::Err;
158
159 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
160 WalletAddress::from_str(value).map(Self)
161 }
162}
163
164impl std::fmt::Display for AccountAddress {
165 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166 self.0.fmt(f)
167 }
168}
169
170impl std::fmt::Debug for AccountAddress {
171 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 self.0.fmt(f)
173 }
174}
175
176sol! {
177 #[derive(Debug, PartialEq, Eq)]
178 struct PlaceOrder {
179 address wallet;
180 string symbol;
181 string side;
182 string size;
183 string price;
184 string tif;
185 string route;
186 string clientId;
187 uint64 nonce;
188 }
189
190 #[derive(Debug, PartialEq, Eq)]
191 struct PlaceOrderReduceOnly {
192 address wallet;
193 string symbol;
194 string side;
195 string size;
196 string price;
197 string tif;
198 string route;
199 string clientId;
200 bool reduceOnly;
201 uint64 nonce;
202 }
203
204 #[derive(Debug, PartialEq, Eq)]
205 struct CancelOrder {
206 address wallet;
207 string orderId;
208 uint64 nonce;
209 }
210
211 #[derive(Debug, PartialEq, Eq)]
212 struct LimitOrder {
213 uint32 asset;
214 bool isBuy;
215 uint64 limitPx;
216 uint64 sz;
217 bool reduceOnly;
218 uint8 encodedTif;
219 uint128 cloid;
220 }
221
222 #[derive(Debug, PartialEq, Eq)]
223 struct CancelOrderByOid {
224 uint32 asset;
225 uint64 oid;
226 }
227
228 #[derive(Debug, PartialEq, Eq)]
229 struct CancelOrderByCloid {
230 uint32 asset;
231 uint128 cloid;
232 }
233
234 #[derive(Debug, PartialEq, Eq)]
235 struct HLOrder {
236 address account;
237 uint64 nonce;
238 LimitOrder action;
239 }
240
241 #[derive(Debug, PartialEq, Eq)]
242 struct HLCancel {
243 address account;
244 uint64 nonce;
245 CancelOrderByOid action;
246 }
247
248 #[derive(Debug, PartialEq, Eq)]
249 struct HLCancelByCloid {
250 address account;
251 uint64 nonce;
252 CancelOrderByCloid action;
253 }
254
255 #[derive(Debug, PartialEq, Eq)]
256 struct SendAsset {
257 address destination;
258 address subAccount;
259 uint32 srcDex;
260 uint32 dstDex;
261 uint64 token;
262 uint64 amountWei;
263 }
264
265 #[derive(Debug, PartialEq, Eq)]
266 struct HLSendAsset {
267 address account;
268 uint64 nonce;
269 SendAsset action;
270 }
271
272 #[derive(Debug, PartialEq, Eq)]
273 struct SetAbstraction {
274 address user;
275 uint8 abstraction;
276 }
277
278 #[derive(Debug, PartialEq, Eq)]
279 struct HLSetAbstraction {
280 address account;
281 uint64 nonce;
282 SetAbstraction action;
283 }
284
285 #[derive(Debug, PartialEq, Eq)]
286 struct UpdateApiWallet {
287 bytes32 name;
288 address addr;
289 }
290
291 #[derive(Debug, PartialEq, Eq)]
292 struct HCUpdateApiWallet {
293 address account;
294 uint64 nonce;
295 UpdateApiWallet action;
296 }
297
298 #[derive(Debug, PartialEq, Eq)]
299 struct SetMarginMode {
300 address wallet;
301 string marginMode;
302 uint64 nonce;
303 }
304
305 #[derive(Debug, PartialEq, Eq)]
306 struct SubmitRFQ {
307 bytes32 rfqId;
308 bytes32 legsHash;
309 address wallet;
310 uint64 nonce;
311 }
312
313 #[derive(Debug, PartialEq, Eq)]
314 struct SubmitRFQResponse {
315 bytes32 rfqId;
316 bytes32 legsHash;
317 int256 netPremium;
318 uint256 validForMs;
319 address qpWallet;
320 uint64 nonce;
321 }
322
323 #[derive(Debug, PartialEq, Eq)]
324 struct AcceptRFQQuote {
325 bytes32 rfqId;
326 bytes32 quoteId;
327 int256 netPremium;
328 address wallet;
329 uint64 nonce;
330 }
331
332 #[derive(Debug, PartialEq, Eq)]
333 struct SubmitAutoExecuteRfq {
334 bytes32 rfqId;
335 bytes32 legsHash;
336 int256 limitPrice;
337 address wallet;
338 uint64 nonce;
339 }
340
341 #[derive(Debug, PartialEq, Eq)]
342 struct ConnectQuoteProvider {
343 address wallet;
344 uint256 timestamp;
345 uint64 nonce;
346 }
347
348 #[derive(Debug, PartialEq, Eq)]
349 struct ReplaceOrder {
350 address wallet;
351 string orderId;
352 string symbol;
353 string side;
354 string size;
355 string price;
356 string tif;
357 string clientId;
358 uint64 nonce;
359 }
360
361 #[derive(Debug, PartialEq, Eq)]
362 struct ReplaceOrderReduceOnly {
363 address wallet;
364 string orderId;
365 string symbol;
366 string side;
367 string size;
368 string price;
369 string tif;
370 string clientId;
371 bool reduceOnly;
372 uint64 nonce;
373 }
374
375 #[derive(Debug, PartialEq, Eq)]
376 struct StandardMarginLiquidationOrder {
377 address wallet;
378 address liquidatedWallet;
379 string requestId;
380 string auctionId;
381 string bidUsdc;
382 string portfolioHash;
383 string auctionTermsHash;
384 string bidIntentHash;
385 uint64 auctionVersion;
386 uint64 nonce;
387 }
388
389 #[derive(Debug, PartialEq, Eq)]
390 struct WithdrawUsdc {
391 address wallet;
392 address account;
393 address destination;
394 string amount;
395 uint64 nonce;
396 }
397
398 #[derive(Debug, PartialEq, Eq)]
401 struct RedeemPoolShares {
402 address wallet;
403 string shares;
404 uint64 nonce;
405 }
406
407 #[derive(Debug, PartialEq, Eq)]
411 struct CancelPoolRedemptions {
412 address wallet;
413 string requestIds;
414 uint64 nonce;
415 }
416}
417
418pub(crate) fn hypercall_domain(chain_id: u32) -> Eip712Domain {
419 Eip712Domain {
420 name: Some("Hypercall".into()),
421 version: Some("1".into()),
422 chain_id: Some(alloy::primitives::U256::from(chain_id)),
423 verifying_contract: Some(alloy::primitives::Address::ZERO),
424 salt: None,
425 }
426}
427
428#[cfg(feature = "rfq-v2")]
429sol! {
430 struct AuthorizeRfqReadV2 {
432 address account;
433 uint64 issuedAtMs;
434 uint64 expiresAtMs;
435 uint64 nonce;
436 }
437}
438
439#[derive(Clone)]
440enum SignerBackend {
441 Local(PrivateKeySigner),
442 #[cfg(feature = "kms")]
443 AwsKms(AwsSigner),
444}
445
446impl SignerBackend {
447 fn address(&self) -> AccountAddress {
448 match self {
449 SignerBackend::Local(signer) => AccountAddress::from(signer.address()),
450 #[cfg(feature = "kms")]
451 SignerBackend::AwsKms(signer) => AccountAddress::from(signer.address()),
452 }
453 }
454
455 fn kind(&self) -> &'static str {
456 match self {
457 SignerBackend::Local(_) => "local",
458 #[cfg(feature = "kms")]
459 SignerBackend::AwsKms(_) => "aws-kms",
460 }
461 }
462
463 fn set_chain_id(&mut self, chain_id: u32) {
464 match self {
465 SignerBackend::Local(signer) => signer.set_chain_id(Some(u64::from(chain_id))),
466 #[cfg(feature = "kms")]
467 SignerBackend::AwsKms(signer) => signer.set_chain_id(Some(u64::from(chain_id))),
468 }
469 }
470
471 fn ethereum_wallet(&self) -> alloy::network::EthereumWallet {
472 match self {
473 SignerBackend::Local(signer) => alloy::network::EthereumWallet::from(signer.clone()),
474 #[cfg(feature = "kms")]
475 SignerBackend::AwsKms(signer) => alloy::network::EthereumWallet::from(signer.clone()),
476 }
477 }
478
479 async fn sign_typed_data<T: SolStruct + Send + Sync>(
480 &self,
481 message: &T,
482 domain: &Eip712Domain,
483 ) -> std::result::Result<Signature, alloy::signers::Error> {
484 match self {
485 SignerBackend::Local(signer) => signer.sign_typed_data(message, domain).await,
486 #[cfg(feature = "kms")]
487 SignerBackend::AwsKms(signer) => signer.sign_typed_data(message, domain).await,
488 }
489 }
490
491 async fn sign_message(
492 &self,
493 message: &[u8],
494 ) -> std::result::Result<Signature, alloy::signers::Error> {
495 match self {
496 SignerBackend::Local(signer) => signer.sign_message(message).await,
497 #[cfg(feature = "kms")]
498 SignerBackend::AwsKms(signer) => signer.sign_message(message).await,
499 }
500 }
501
502 fn try_private_key_hex(&self) -> Result<String> {
503 match self {
504 SignerBackend::Local(signer) => Ok(format!("0x{}", hex::encode(signer.to_bytes()))),
505 #[cfg(feature = "kms")]
506 SignerBackend::AwsKms(_) => Err(ClientError::SigningUnavailable(
507 SigningUnavailableReason::AwsKmsPrivateKeyMaterial,
508 )),
509 }
510 }
511}
512
513#[derive(Clone)]
515pub struct HypercallWallet {
516 pub address: AccountAddress,
518 signer: SignerBackend,
520 nonce_provider: Arc<dyn NonceProvider>,
521 chain_id: u32,
523}
524
525#[derive(Debug, Clone, Copy)]
526pub struct PlaceOrderSignature<'a> {
527 pub wallet: AccountAddress,
528 pub symbol: &'a str,
529 pub side: &'a str,
530 pub size: &'a str,
531 pub price: &'a str,
532 pub tif: &'a str,
533 pub route: OrderRoute,
534 pub client_id: &'a str,
535 pub reduce_only: bool,
536 pub nonce: u64,
537}
538
539#[derive(Debug, Clone, Copy)]
540pub struct CancelOrderSignature<'a> {
541 pub wallet: AccountAddress,
542 pub order_id: &'a str,
543 pub nonce: u64,
544}
545
546#[derive(Debug, Clone, Copy)]
547pub struct ReplaceOrderSignature<'a> {
548 pub wallet: AccountAddress,
549 pub order_id: &'a str,
550 pub symbol: &'a str,
551 pub side: &'a str,
552 pub size: &'a str,
553 pub price: &'a str,
554 pub tif: &'a str,
555 pub client_id: &'a str,
556 pub reduce_only: bool,
557 pub nonce: u64,
558}
559
560#[derive(Debug, Clone, Copy)]
561pub struct StandardMarginLiquidationSignature<'a> {
562 pub wallet: AccountAddress,
563 pub liquidated_wallet: AccountAddress,
564 pub request_id: &'a str,
565 pub auction_id: &'a str,
566 pub bid_usdc: &'a str,
567 pub portfolio_hash: &'a str,
568 pub auction_terms_hash: &'a str,
569 pub bid_intent_hash: &'a str,
570 pub auction_version: u64,
571 pub nonce: u64,
572}
573
574#[derive(Debug, Clone, Copy)]
575pub struct PerpLimitOrderSignature {
576 pub account: AccountAddress,
577 pub nonce: u64,
578 pub action: HlLimitOrderAction,
579}
580
581#[derive(Debug, Clone, Copy)]
582pub struct PerpCancelByOidSignature {
583 pub account: AccountAddress,
584 pub nonce: u64,
585 pub action: HlCancelByOidAction,
586}
587
588#[derive(Debug, Clone, Copy)]
589pub struct PerpCancelByCloidSignature {
590 pub account: AccountAddress,
591 pub nonce: u64,
592 pub action: HlCancelByCloidAction,
593}
594
595#[derive(Debug, Clone, Copy)]
596pub struct SetAccountAbstractionSignature {
597 pub account: AccountAddress,
598 pub nonce: u64,
599 pub action: HlSetAbstractionAction,
600}
601
602#[derive(Debug, Clone, Copy)]
603pub struct UpdateApiWalletSignature {
604 pub account: AccountAddress,
605 pub nonce: u64,
606 pub action: HcUpdateApiWalletAction,
607}
608
609#[derive(Debug, Clone, Copy)]
611pub struct StandardUsdcWithdrawalSignature<'a> {
612 pub wallet: AccountAddress,
613 pub account: AccountAddress,
614 pub destination: AccountAddress,
615 pub amount: &'a str,
616 pub nonce: u64,
617}
618
619#[derive(Debug, Clone, Copy)]
621pub struct PortfolioUsdcWithdrawalSignature {
622 pub account: AccountAddress,
623 pub destination: AccountAddress,
624 pub amount_wei: u64,
625 pub destination_dex: u32,
626 pub nonce: u64,
627}
628
629#[expect(
630 async_fn_in_trait,
631 reason = "public signer trait; callers choose their own executor, so futures carry no Send bound"
632)]
633pub trait HypercallSigner {
634 fn address(&self) -> AccountAddress;
635 fn next_nonce(&self) -> u64;
636 async fn sign_place_order_payload(&self, payload: PlaceOrderSignature<'_>) -> Result<String>;
637 async fn sign_cancel_order_payload(&self, payload: CancelOrderSignature<'_>) -> Result<String>;
638 async fn sign_replace_order_payload(
639 &self,
640 payload: ReplaceOrderSignature<'_>,
641 ) -> Result<String>;
642 async fn sign_set_margin_mode_payload(&self, margin_mode: &str, nonce: u64) -> Result<String>;
643 async fn sign_standard_margin_liquidation_payload(
644 &self,
645 payload: StandardMarginLiquidationSignature<'_>,
646 ) -> Result<String>;
647}
648
649#[expect(
650 async_fn_in_trait,
651 reason = "public signer trait; callers choose their own executor, so futures carry no Send bound"
652)]
653pub trait PerpDirectiveSigner: HypercallSigner {
654 async fn sign_perp_limit_order_payload(
655 &self,
656 payload: PerpLimitOrderSignature,
657 ) -> Result<String>;
658 async fn sign_perp_cancel_by_oid_payload(
659 &self,
660 payload: PerpCancelByOidSignature,
661 ) -> Result<String>;
662 async fn sign_perp_cancel_by_cloid_payload(
663 &self,
664 payload: PerpCancelByCloidSignature,
665 ) -> Result<String>;
666}
667
668#[expect(
669 async_fn_in_trait,
670 reason = "public signer trait; callers choose their own executor, so futures carry no Send bound"
671)]
672pub trait ManagerDirectiveSigner: HypercallSigner {
673 async fn sign_set_account_abstraction_payload(
674 &self,
675 payload: SetAccountAbstractionSignature,
676 ) -> Result<String>;
677}
678
679#[expect(
680 async_fn_in_trait,
681 reason = "public signer trait; callers choose their own executor, so futures carry no Send bound"
682)]
683pub trait ApiWalletDirectiveSigner: HypercallSigner {
684 async fn sign_update_api_wallet_payload(
685 &self,
686 payload: UpdateApiWalletSignature,
687 ) -> Result<String>;
688}
689
690#[expect(
692 async_fn_in_trait,
693 reason = "public signer trait; callers choose their own executor, so futures carry no Send bound"
694)]
695pub trait UsdcWithdrawalSigner: HypercallSigner {
696 async fn sign_standard_usdc_withdrawal_payload(
697 &self,
698 payload: StandardUsdcWithdrawalSignature<'_>,
699 ) -> Result<String>;
700 async fn sign_portfolio_usdc_withdrawal_payload(
701 &self,
702 payload: PortfolioUsdcWithdrawalSignature,
703 ) -> Result<String>;
704}
705
706fn epoch_seeded_nonce() -> u64 {
707 std::time::SystemTime::now()
708 .duration_since(std::time::UNIX_EPOCH)
709 .unwrap()
710 .as_millis() as u64
711}
712
713pub trait NonceProvider: Send + Sync {
714 fn next_nonce(&self) -> u64;
715 fn current_nonce(&self) -> u64;
716}
717
718#[derive(Debug)]
719pub struct AtomicNonceProvider {
720 counter: AtomicU64,
721}
722
723impl AtomicNonceProvider {
724 pub fn new(seed: u64) -> Self {
725 Self {
726 counter: AtomicU64::new(seed),
727 }
728 }
729
730 pub fn epoch_seeded() -> Self {
731 Self::new(epoch_seeded_nonce())
732 }
733}
734
735impl Default for AtomicNonceProvider {
736 fn default() -> Self {
737 Self::epoch_seeded()
738 }
739}
740
741impl NonceProvider for AtomicNonceProvider {
742 fn next_nonce(&self) -> u64 {
743 let now = epoch_seeded_nonce();
744 self.counter.fetch_max(now, Ordering::SeqCst);
745 self.counter.fetch_add(1, Ordering::SeqCst)
746 }
747
748 fn current_nonce(&self) -> u64 {
749 self.counter.load(Ordering::SeqCst)
750 }
751}
752
753impl HypercallSigner for HypercallWallet {
754 fn address(&self) -> AccountAddress {
755 self.address
756 }
757
758 fn next_nonce(&self) -> u64 {
759 HypercallWallet::next_nonce(self)
760 }
761
762 async fn sign_place_order_payload(&self, payload: PlaceOrderSignature<'_>) -> Result<String> {
763 HypercallWallet::sign_place_order_payload(self, payload).await
764 }
765
766 async fn sign_cancel_order_payload(&self, payload: CancelOrderSignature<'_>) -> Result<String> {
767 HypercallWallet::sign_cancel_order_payload(self, payload).await
768 }
769
770 async fn sign_replace_order_payload(
771 &self,
772 payload: ReplaceOrderSignature<'_>,
773 ) -> Result<String> {
774 HypercallWallet::sign_replace_order_payload(self, payload).await
775 }
776
777 async fn sign_set_margin_mode_payload(&self, margin_mode: &str, nonce: u64) -> Result<String> {
778 self.sign_set_margin_mode(margin_mode, nonce).await
779 }
780
781 async fn sign_standard_margin_liquidation_payload(
782 &self,
783 payload: StandardMarginLiquidationSignature<'_>,
784 ) -> Result<String> {
785 HypercallWallet::sign_standard_margin_liquidation_payload(self, payload).await
786 }
787}
788
789impl PerpDirectiveSigner for HypercallWallet {
790 async fn sign_perp_limit_order_payload(
791 &self,
792 payload: PerpLimitOrderSignature,
793 ) -> Result<String> {
794 HypercallWallet::sign_perp_limit_order_payload(self, payload).await
795 }
796
797 async fn sign_perp_cancel_by_oid_payload(
798 &self,
799 payload: PerpCancelByOidSignature,
800 ) -> Result<String> {
801 HypercallWallet::sign_perp_cancel_by_oid_payload(self, payload).await
802 }
803
804 async fn sign_perp_cancel_by_cloid_payload(
805 &self,
806 payload: PerpCancelByCloidSignature,
807 ) -> Result<String> {
808 HypercallWallet::sign_perp_cancel_by_cloid_payload(self, payload).await
809 }
810}
811
812impl ManagerDirectiveSigner for HypercallWallet {
813 async fn sign_set_account_abstraction_payload(
814 &self,
815 payload: SetAccountAbstractionSignature,
816 ) -> Result<String> {
817 HypercallWallet::sign_set_account_abstraction_payload(self, payload).await
818 }
819}
820
821impl ApiWalletDirectiveSigner for HypercallWallet {
822 async fn sign_update_api_wallet_payload(
823 &self,
824 payload: UpdateApiWalletSignature,
825 ) -> Result<String> {
826 HypercallWallet::sign_update_api_wallet_payload(self, payload).await
827 }
828}
829
830impl UsdcWithdrawalSigner for HypercallWallet {
831 async fn sign_standard_usdc_withdrawal_payload(
832 &self,
833 payload: StandardUsdcWithdrawalSignature<'_>,
834 ) -> Result<String> {
835 HypercallWallet::sign_standard_usdc_withdrawal_payload(self, payload).await
836 }
837
838 async fn sign_portfolio_usdc_withdrawal_payload(
839 &self,
840 payload: PortfolioUsdcWithdrawalSignature,
841 ) -> Result<String> {
842 HypercallWallet::sign_portfolio_usdc_withdrawal_payload(self, payload).await
843 }
844}
845
846impl HypercallWallet {
847 pub(crate) fn ethereum_wallet(&self) -> alloy::network::EthereumWallet {
848 self.signer.ethereum_wallet()
849 }
850
851 pub(crate) fn chain_id(&self) -> u64 {
852 u64::from(self.chain_id)
853 }
854
855 pub async fn sign_authentication_message(&self, timestamp: i64) -> Result<String> {
860 let message =
861 format!("Sign this message to authenticate for Hypercall\nTimestamp: {timestamp}");
862 let signature = self
863 .signer
864 .sign_message(message.as_bytes())
865 .await
866 .map_err(|error| {
867 ClientError::signing("Failed to sign authentication message", error)
868 })?;
869 Ok(format!("{signature}"))
870 }
871
872 #[cfg(feature = "rfq-v2")]
873 pub(crate) async fn sign_rfq_v2_typed_data<T: SolStruct + Send + Sync>(
875 &self,
876 message: &T,
877 what: &'static str,
878 ) -> Result<RfqV2Signature> {
879 let signature = self
880 .signer
881 .sign_typed_data(message, &self.hypercall_domain())
882 .await
883 .map_err(|error| ClientError::signing(format!("Failed to sign {what}"), error))?;
884 RfqV2Signature::from_bytes(signature.as_bytes())
885 .map_err(|error| ClientError::signing(format!("Invalid {what} signature"), error))
886 }
887
888 #[cfg(feature = "rfq-v2")]
889 pub async fn sign_rfq_v2_read_grant(
893 &self,
894 account: WalletAddress,
895 issued_at_ms: u64,
896 expires_at_ms: u64,
897 nonce: u64,
898 ) -> Result<RfqV2ReadGrant> {
899 let message = AuthorizeRfqReadV2 {
900 account: account.inner(),
901 issuedAtMs: issued_at_ms,
902 expiresAtMs: expires_at_ms,
903 nonce,
904 };
905 let signature = self
906 .sign_rfq_v2_typed_data(&message, "RFQ V2 read grant")
907 .await?;
908 Ok(RfqV2ReadGrant {
909 account,
910 issued_at_ms,
911 expires_at_ms,
912 nonce,
913 signature,
914 })
915 }
916
917 pub fn from_private_key(private_key: &str, chain_id: u32) -> Result<Self> {
923 let signer = PrivateKeySigner::from_str(private_key)
924 .map_err(|error| ClientError::signing("Invalid private key", error))?;
925
926 let signer = SignerBackend::Local(signer);
927 let address = signer.address();
928
929 Ok(Self {
930 address,
931 signer,
932 nonce_provider: Arc::new(AtomicNonceProvider::default()),
933 chain_id,
934 })
935 }
936
937 pub fn random(chain_id: u32) -> Self {
939 let signer = PrivateKeySigner::random();
940 let signer = SignerBackend::Local(signer);
941 let address = signer.address();
942
943 Self {
944 address,
945 signer,
946 nonce_provider: Arc::new(AtomicNonceProvider::default()),
947 chain_id,
948 }
949 }
950
951 pub fn from_bytes(bytes: &[u8; 32], chain_id: u32) -> Result<Self> {
953 let b256_key = B256::from_slice(bytes);
954 let signer = PrivateKeySigner::from_bytes(&b256_key)
955 .map_err(|error| ClientError::signing("Invalid private key bytes", error))?;
956
957 let signer = SignerBackend::Local(signer);
958 let address = signer.address();
959
960 Ok(Self {
961 address,
962 signer,
963 nonce_provider: Arc::new(AtomicNonceProvider::default()),
964 chain_id,
965 })
966 }
967
968 pub fn with_chain_id(mut self, chain_id: u32) -> Self {
970 self.chain_id = chain_id;
971 self.signer.set_chain_id(chain_id);
972 self
973 }
974
975 pub fn with_nonce_provider(mut self, nonce_provider: Arc<dyn NonceProvider>) -> Self {
977 self.nonce_provider = nonce_provider;
978 self
979 }
980
981 #[cfg(feature = "kms")]
986 pub async fn from_aws_kms_key_id(key_id: impl Into<String>, chain_id: u32) -> Result<Self> {
987 let key_id = key_id.into();
988 let aws_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
989 let kms_client = aws_sdk_kms::Client::new(&aws_config);
990 let signer = AwsSigner::new(kms_client, key_id, Some(u64::from(chain_id)))
991 .await
992 .map_err(|error| ClientError::signing("Failed to initialize AWS KMS wallet", error))?;
993 let signer = SignerBackend::AwsKms(signer);
994 let address = signer.address();
995
996 Ok(Self {
997 address,
998 signer,
999 nonce_provider: Arc::new(AtomicNonceProvider::default()),
1000 chain_id,
1001 })
1002 }
1003
1004 pub fn next_nonce(&self) -> u64 {
1008 self.nonce_provider.next_nonce()
1009 }
1010
1011 pub fn current_nonce(&self) -> u64 {
1013 self.nonce_provider.current_nonce()
1014 }
1015
1016 pub fn try_private_key_hex(&self) -> Result<String> {
1021 self.signer.try_private_key_hex()
1022 }
1023
1024 pub fn private_key_hex(&self) -> String {
1030 self.try_private_key_hex()
1031 .expect("private_key_hex is only available for local private-key wallets")
1032 }
1033
1034 fn hypercall_domain(&self) -> Eip712Domain {
1036 hypercall_domain(self.chain_id)
1037 }
1038
1039 fn directive_domain(&self, name: &'static str) -> Result<Eip712Domain> {
1040 if !matches!(self.chain_id, 998 | 999) {
1041 return Err(ClientError::InvalidInput(format!(
1042 "unsupported directive chain id: {}",
1043 self.chain_id
1044 )));
1045 }
1046 Ok(Eip712Domain {
1047 name: Some(name.into()),
1048 version: Some("1".into()),
1049 chain_id: Some(alloy::primitives::U256::from(self.chain_id)),
1050 verifying_contract: Some(alloy::primitives::Address::ZERO),
1051 salt: None,
1052 })
1053 }
1054
1055 pub async fn sign_perp_limit_order_payload(
1056 &self,
1057 payload: PerpLimitOrderSignature,
1058 ) -> Result<String> {
1059 let action = payload.action;
1060 let message = HLOrder {
1061 account: payload.account.as_wallet_address().inner(),
1062 nonce: payload.nonce,
1063 action: LimitOrder {
1064 asset: action.asset,
1065 isBuy: action.is_buy,
1066 limitPx: action.limit_px,
1067 sz: action.sz,
1068 reduceOnly: action.reduce_only,
1069 encodedTif: action.tif.encoded(),
1070 cloid: action.cloid,
1071 },
1072 };
1073 self.sign_directive(&message, "HLOrder", "HypercallApiSign")
1074 .await
1075 }
1076
1077 pub async fn sign_perp_cancel_by_oid_payload(
1078 &self,
1079 payload: PerpCancelByOidSignature,
1080 ) -> Result<String> {
1081 let message = HLCancel {
1082 account: payload.account.as_wallet_address().inner(),
1083 nonce: payload.nonce,
1084 action: CancelOrderByOid {
1085 asset: payload.action.asset,
1086 oid: payload.action.oid,
1087 },
1088 };
1089 self.sign_directive(&message, "HLCancel", "HypercallApiSign")
1090 .await
1091 }
1092
1093 pub async fn sign_perp_cancel_by_cloid_payload(
1094 &self,
1095 payload: PerpCancelByCloidSignature,
1096 ) -> Result<String> {
1097 let message = HLCancelByCloid {
1098 account: payload.account.as_wallet_address().inner(),
1099 nonce: payload.nonce,
1100 action: CancelOrderByCloid {
1101 asset: payload.action.asset,
1102 cloid: payload.action.cloid,
1103 },
1104 };
1105 self.sign_directive(&message, "HLCancelByCloid", "HypercallApiSign")
1106 .await
1107 }
1108
1109 pub async fn sign_set_account_abstraction_payload(
1110 &self,
1111 payload: SetAccountAbstractionSignature,
1112 ) -> Result<String> {
1113 let message = HLSetAbstraction {
1114 account: payload.account.as_wallet_address().inner(),
1115 nonce: payload.nonce,
1116 action: SetAbstraction {
1117 user: payload.action.user.inner(),
1118 abstraction: payload.action.abstraction.as_u8(),
1119 },
1120 };
1121 self.sign_directive(&message, "HLSetAbstraction", "HypercallManagerSign")
1122 .await
1123 }
1124
1125 pub async fn sign_update_api_wallet_payload(
1126 &self,
1127 payload: UpdateApiWalletSignature,
1128 ) -> Result<String> {
1129 let message = HCUpdateApiWallet {
1130 account: payload.account.as_wallet_address().inner(),
1131 nonce: payload.nonce,
1132 action: UpdateApiWallet {
1133 name: payload.action.name,
1134 addr: payload.action.addr.inner(),
1135 },
1136 };
1137 self.sign_directive(&message, "HCUpdateApiWallet", "HypercallManagerSign")
1138 .await
1139 }
1140
1141 pub async fn sign_standard_usdc_withdrawal_payload(
1143 &self,
1144 payload: StandardUsdcWithdrawalSignature<'_>,
1145 ) -> Result<String> {
1146 let message = WithdrawUsdc {
1147 wallet: payload.wallet.as_wallet_address().inner(),
1148 account: payload.account.as_wallet_address().inner(),
1149 destination: payload.destination.as_wallet_address().inner(),
1150 amount: payload.amount.to_string(),
1151 nonce: payload.nonce,
1152 };
1153 let signature = self
1154 .signer
1155 .sign_typed_data(&message, &self.hypercall_domain())
1156 .await
1157 .map_err(|error| ClientError::signing("Failed to sign WithdrawUsdc", error))?;
1158 Ok(format!("{signature}"))
1159 }
1160
1161 pub async fn sign_portfolio_usdc_withdrawal_payload(
1163 &self,
1164 payload: PortfolioUsdcWithdrawalSignature,
1165 ) -> Result<String> {
1166 let message = HLSendAsset {
1167 account: payload.account.as_wallet_address().inner(),
1168 nonce: payload.nonce,
1169 action: SendAsset {
1170 destination: payload.destination.as_wallet_address().inner(),
1171 subAccount: alloy::primitives::Address::ZERO,
1172 srcDex: u32::MAX,
1173 dstDex: payload.destination_dex,
1174 token: 0,
1175 amountWei: payload.amount_wei,
1176 },
1177 };
1178 self.sign_directive(&message, "HLSendAsset", "HypercallManagerSign")
1179 .await
1180 }
1181
1182 pub(crate) async fn sign_directive<T>(
1183 &self,
1184 message: &T,
1185 type_name: &str,
1186 domain_name: &'static str,
1187 ) -> Result<String>
1188 where
1189 T: SolStruct + Send + Sync,
1190 {
1191 let domain = self.directive_domain(domain_name)?;
1192 let signature = self
1193 .signer
1194 .sign_typed_data(message, &domain)
1195 .await
1196 .map_err(|error| ClientError::signing(format!("Failed to sign {type_name}"), error))?;
1197 Ok(format!("{signature}"))
1198 }
1199
1200 pub async fn sign_place_order_payload(
1202 &self,
1203 payload: PlaceOrderSignature<'_>,
1204 ) -> Result<String> {
1205 let domain = self.hypercall_domain();
1206 let signature = if payload.reduce_only {
1207 let message = PlaceOrderReduceOnly {
1208 wallet: payload.wallet.as_wallet_address().inner(),
1209 symbol: payload.symbol.to_string(),
1210 side: payload.side.to_string(),
1211 size: payload.size.to_string(),
1212 price: payload.price.to_string(),
1213 tif: payload.tif.to_string(),
1214 route: payload.route.as_signed_str().to_string(),
1215 clientId: payload.client_id.to_string(),
1216 reduceOnly: true,
1217 nonce: payload.nonce,
1218 };
1219 self.signer.sign_typed_data(&message, &domain).await
1220 } else {
1221 let message = PlaceOrder {
1222 wallet: payload.wallet.as_wallet_address().inner(),
1223 symbol: payload.symbol.to_string(),
1224 side: payload.side.to_string(),
1225 size: payload.size.to_string(),
1226 price: payload.price.to_string(),
1227 tif: payload.tif.to_string(),
1228 route: payload.route.as_signed_str().to_string(),
1229 clientId: payload.client_id.to_string(),
1230 nonce: payload.nonce,
1231 };
1232 self.signer.sign_typed_data(&message, &domain).await
1233 }
1234 .map_err(|error| ClientError::signing("Failed to sign PlaceOrder", error))?;
1235
1236 Ok(format!("{}", signature))
1237 }
1238
1239 pub async fn sign_cancel_order(&self, order_id: &str, nonce: u64) -> Result<String> {
1241 self.sign_cancel_order_payload(CancelOrderSignature {
1242 wallet: self.address,
1243 order_id,
1244 nonce,
1245 })
1246 .await
1247 }
1248
1249 pub async fn sign_cancel_order_payload(
1250 &self,
1251 payload: CancelOrderSignature<'_>,
1252 ) -> Result<String> {
1253 let message = CancelOrder {
1254 wallet: payload.wallet.as_wallet_address().inner(),
1255 orderId: payload.order_id.to_string(),
1256 nonce: payload.nonce,
1257 };
1258
1259 let domain = self.hypercall_domain();
1260 let signature = self
1261 .signer
1262 .sign_typed_data(&message, &domain)
1263 .await
1264 .map_err(|error| ClientError::signing("Failed to sign CancelOrder", error))?;
1265
1266 Ok(format!("{}", signature))
1267 }
1268
1269 pub async fn sign_replace_order_payload(
1271 &self,
1272 payload: ReplaceOrderSignature<'_>,
1273 ) -> Result<String> {
1274 let domain = self.hypercall_domain();
1275 let signature = if payload.reduce_only {
1276 let message = ReplaceOrderReduceOnly {
1277 wallet: payload.wallet.as_wallet_address().inner(),
1278 orderId: payload.order_id.to_string(),
1279 symbol: payload.symbol.to_string(),
1280 side: payload.side.to_string(),
1281 size: payload.size.to_string(),
1282 price: payload.price.to_string(),
1283 tif: payload.tif.to_string(),
1284 clientId: payload.client_id.to_string(),
1285 reduceOnly: true,
1286 nonce: payload.nonce,
1287 };
1288 self.signer.sign_typed_data(&message, &domain).await
1289 } else {
1290 let message = ReplaceOrder {
1291 wallet: payload.wallet.as_wallet_address().inner(),
1292 orderId: payload.order_id.to_string(),
1293 symbol: payload.symbol.to_string(),
1294 side: payload.side.to_string(),
1295 size: payload.size.to_string(),
1296 price: payload.price.to_string(),
1297 tif: payload.tif.to_string(),
1298 clientId: payload.client_id.to_string(),
1299 nonce: payload.nonce,
1300 };
1301 self.signer.sign_typed_data(&message, &domain).await
1302 }
1303 .map_err(|error| ClientError::signing("Failed to sign ReplaceOrder", error))?;
1304
1305 Ok(format!("{}", signature))
1306 }
1307
1308 pub async fn sign_standard_margin_liquidation_payload(
1309 &self,
1310 payload: StandardMarginLiquidationSignature<'_>,
1311 ) -> Result<String> {
1312 let message = StandardMarginLiquidationOrder {
1313 wallet: payload.wallet.as_wallet_address().inner(),
1314 liquidatedWallet: payload.liquidated_wallet.as_wallet_address().inner(),
1315 requestId: payload.request_id.to_string(),
1316 auctionId: payload.auction_id.to_string(),
1317 bidUsdc: payload.bid_usdc.to_string(),
1318 portfolioHash: payload.portfolio_hash.to_string(),
1319 auctionTermsHash: payload.auction_terms_hash.to_string(),
1320 bidIntentHash: payload.bid_intent_hash.to_string(),
1321 auctionVersion: payload.auction_version,
1322 nonce: payload.nonce,
1323 };
1324
1325 let domain = self.hypercall_domain();
1326 let signature = self
1327 .signer
1328 .sign_typed_data(&message, &domain)
1329 .await
1330 .map_err(|error| {
1331 ClientError::signing("Failed to sign StandardMarginLiquidationOrder", error)
1332 })?;
1333
1334 Ok(format!("{}", signature))
1335 }
1336
1337 pub async fn sign_set_margin_mode(&self, margin_mode: &str, nonce: u64) -> Result<String> {
1339 let message = SetMarginMode {
1340 wallet: self.address.as_wallet_address().inner(),
1341 marginMode: margin_mode.to_string(),
1342 nonce,
1343 };
1344 self.sign_hypercall_action(&message, "SetMarginMode").await
1345 }
1346
1347 pub(crate) async fn sign_hypercall_action<T: SolStruct + Send + Sync>(
1350 &self,
1351 message: &T,
1352 action: &str,
1353 ) -> Result<String> {
1354 let signature = self
1355 .signer
1356 .sign_typed_data(message, &self.hypercall_domain())
1357 .await
1358 .map_err(|error| ClientError::signing(format!("Failed to sign {action}"), error))?;
1359 Ok(signature.to_string())
1360 }
1361
1362 pub async fn sign_redeem_pool_shares(&self, shares: &str, nonce: u64) -> Result<String> {
1365 let message = RedeemPoolShares {
1366 wallet: self.address.as_wallet_address().inner(),
1367 shares: shares.to_string(),
1368 nonce,
1369 };
1370 self.sign_hypercall_action(&message, "RedeemPoolShares")
1371 .await
1372 }
1373
1374 pub async fn sign_cancel_pool_redemptions(
1377 &self,
1378 request_ids: &[&str],
1379 nonce: u64,
1380 ) -> Result<String> {
1381 let message = CancelPoolRedemptions {
1382 wallet: self.address.as_wallet_address().inner(),
1383 requestIds: request_ids.join(","),
1384 nonce,
1385 };
1386 self.sign_hypercall_action(&message, "CancelPoolRedemptions")
1387 .await
1388 }
1389
1390 pub async fn sign_submit_rfq(
1392 &self,
1393 rfq_id: [u8; 32],
1394 legs_hash: [u8; 32],
1395 nonce: u64,
1396 ) -> Result<String> {
1397 let message = SubmitRFQ {
1398 rfqId: alloy::primitives::FixedBytes(rfq_id),
1399 legsHash: alloy::primitives::FixedBytes(legs_hash),
1400 wallet: self.address.as_wallet_address().inner(),
1401 nonce,
1402 };
1403
1404 let domain = self.hypercall_domain();
1405 let signature = self
1406 .signer
1407 .sign_typed_data(&message, &domain)
1408 .await
1409 .map_err(|error| ClientError::signing("Failed to sign SubmitRFQ", error))?;
1410
1411 Ok(format!("{}", signature))
1412 }
1413
1414 pub async fn sign_submit_rfq_response(
1416 &self,
1417 rfq_id: [u8; 32],
1418 legs_hash: [u8; 32],
1419 net_premium: alloy::primitives::I256,
1420 valid_for_ms: alloy::primitives::U256,
1421 nonce: u64,
1422 ) -> Result<String> {
1423 let message = SubmitRFQResponse {
1424 rfqId: alloy::primitives::FixedBytes(rfq_id),
1425 legsHash: alloy::primitives::FixedBytes(legs_hash),
1426 netPremium: net_premium,
1427 validForMs: valid_for_ms,
1428 qpWallet: self.address.as_wallet_address().inner(),
1429 nonce,
1430 };
1431
1432 let domain = self.hypercall_domain();
1433 let signature = self
1434 .signer
1435 .sign_typed_data(&message, &domain)
1436 .await
1437 .map_err(|error| ClientError::signing("Failed to sign SubmitRFQResponse", error))?;
1438
1439 Ok(format!("{}", signature))
1440 }
1441
1442 pub async fn sign_accept_rfq_quote(
1444 &self,
1445 rfq_id: [u8; 32],
1446 quote_id: [u8; 32],
1447 net_premium: alloy::primitives::I256,
1448 nonce: u64,
1449 ) -> Result<String> {
1450 let message = AcceptRFQQuote {
1451 rfqId: alloy::primitives::FixedBytes(rfq_id),
1452 quoteId: alloy::primitives::FixedBytes(quote_id),
1453 netPremium: net_premium,
1454 wallet: self.address.as_wallet_address().inner(),
1455 nonce,
1456 };
1457
1458 let domain = self.hypercall_domain();
1459 let signature = self
1460 .signer
1461 .sign_typed_data(&message, &domain)
1462 .await
1463 .map_err(|error| ClientError::signing("Failed to sign AcceptRFQQuote", error))?;
1464
1465 Ok(format!("{}", signature))
1466 }
1467
1468 pub async fn sign_submit_auto_execute_rfq(
1470 &self,
1471 rfq_id: [u8; 32],
1472 legs_hash: [u8; 32],
1473 limit_price: alloy::primitives::I256,
1474 nonce: u64,
1475 ) -> Result<String> {
1476 let message = SubmitAutoExecuteRfq {
1477 rfqId: alloy::primitives::FixedBytes(rfq_id),
1478 legsHash: alloy::primitives::FixedBytes(legs_hash),
1479 limitPrice: limit_price,
1480 wallet: self.address.as_wallet_address().inner(),
1481 nonce,
1482 };
1483
1484 let domain = self.hypercall_domain();
1485 let signature = self
1486 .signer
1487 .sign_typed_data(&message, &domain)
1488 .await
1489 .map_err(|error| ClientError::signing("Failed to sign SubmitAutoExecuteRfq", error))?;
1490
1491 Ok(format!("{}", signature))
1492 }
1493
1494 pub async fn sign_connect_quote_provider(
1496 &self,
1497 timestamp: alloy::primitives::U256,
1498 nonce: u64,
1499 ) -> Result<String> {
1500 let message = ConnectQuoteProvider {
1501 wallet: self.address.as_wallet_address().inner(),
1502 timestamp,
1503 nonce,
1504 };
1505
1506 let domain = self.hypercall_domain();
1507 let signature = self
1508 .signer
1509 .sign_typed_data(&message, &domain)
1510 .await
1511 .map_err(|error| ClientError::signing("Failed to sign ConnectQuoteProvider", error))?;
1512
1513 Ok(format!("{}", signature))
1514 }
1515}
1516
1517impl std::fmt::Debug for HypercallWallet {
1518 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1519 f.debug_struct("HypercallWallet")
1520 .field("address", &self.address)
1521 .field("signer_backend", &self.signer.kind())
1522 .field("nonce", &self.current_nonce())
1523 .finish()
1524 }
1525}
1526
1527#[cfg(test)]
1528mod tests {
1529 use super::*;
1530 use alloy::primitives::Address;
1531
1532 const TEST_PRIVATE_KEY: &str =
1534 "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1535
1536 fn recover_address_from_signature(signature: &str, message_hash: &[u8; 32]) -> Address {
1537 let signature_bytes = hex::decode(signature.trim_start_matches("0x")).unwrap();
1538 assert_eq!(signature_bytes.len(), 65);
1539
1540 let parity = match signature_bytes[64] {
1541 0 | 27 => false,
1542 1 | 28 => true,
1543 v => panic!("invalid signature v value: {v}"),
1544 };
1545 let sig =
1546 alloy::primitives::Signature::from_bytes_and_parity(&signature_bytes[..64], parity);
1547
1548 sig.recover_address_from_prehash(&alloy::primitives::B256::from(*message_hash))
1549 .unwrap()
1550 }
1551
1552 fn recover_typed_signer<T: SolStruct>(
1553 message: &T,
1554 domain: &Eip712Domain,
1555 signature: &str,
1556 ) -> Address {
1557 let message_hash = message.eip712_signing_hash(domain);
1558 recover_address_from_signature(signature, &message_hash)
1559 }
1560
1561 fn place_signature(wallet: AccountAddress, nonce: u64) -> PlaceOrderSignature<'static> {
1562 PlaceOrderSignature {
1563 wallet,
1564 symbol: "BTC-20250131-100000-C",
1565 side: "Buy",
1566 size: "1",
1567 price: "100",
1568 tif: "gtc",
1569 route: OrderRoute::BestExecution,
1570 client_id: "cli_1",
1571 reduce_only: false,
1572 nonce,
1573 }
1574 }
1575
1576 fn replace_signature(wallet: AccountAddress, nonce: u64) -> ReplaceOrderSignature<'static> {
1577 ReplaceOrderSignature {
1578 wallet,
1579 order_id: "42",
1580 symbol: "BTC-20250131-100000-C",
1581 side: "Buy",
1582 size: "1",
1583 price: "100",
1584 tif: "gtc",
1585 client_id: "cli_replace",
1586 reduce_only: false,
1587 nonce,
1588 }
1589 }
1590
1591 #[test]
1592 fn test_random_wallet() {
1593 let wallet = HypercallWallet::random(998);
1594 assert_ne!(
1595 wallet.address.as_hex(),
1596 "0x0000000000000000000000000000000000000000"
1597 );
1598 }
1599
1600 #[test]
1601 fn test_from_private_key() {
1602 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1603 assert_eq!(
1605 wallet.address.as_hex().to_lowercase(),
1606 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1607 );
1608 }
1609
1610 #[test]
1611 fn test_from_private_key_without_prefix() {
1612 let key_without_prefix = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1613 let wallet = HypercallWallet::from_private_key(key_without_prefix, 998).unwrap();
1614 assert_eq!(
1615 wallet.address.as_hex().to_lowercase(),
1616 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1617 );
1618 }
1619
1620 #[test]
1621 fn test_from_private_key_invalid() {
1622 let result = HypercallWallet::from_private_key("invalid_key", 998);
1623 assert!(result.is_err());
1624 }
1625
1626 #[test]
1627 fn test_from_bytes() {
1628 let bytes: [u8; 32] = [
1629 0xac, 0x09, 0x74, 0xbe, 0xc3, 0x9a, 0x17, 0xe3, 0x6b, 0xa4, 0xa6, 0xb4, 0xd2, 0x38,
1630 0xff, 0x94, 0x4b, 0xac, 0xb4, 0x78, 0xcb, 0xed, 0x5e, 0xfc, 0xae, 0x78, 0x4d, 0x7b,
1631 0xf4, 0xf2, 0xff, 0x80,
1632 ];
1633 let wallet = HypercallWallet::from_bytes(&bytes, 998).unwrap();
1634 assert_eq!(
1635 wallet.address.as_hex().to_lowercase(),
1636 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1637 );
1638 }
1639
1640 #[test]
1641 fn test_nonce_management() {
1642 let wallet = HypercallWallet::random(998);
1643
1644 let initial = wallet.current_nonce();
1648 assert!(initial > 1, "expected epoch-seeded nonce, got {initial}");
1649
1650 let first = wallet.next_nonce();
1653 assert!(first >= initial);
1654 assert_eq!(wallet.current_nonce(), first + 1);
1655
1656 let second = wallet.next_nonce();
1657 assert!(second > first);
1658 assert_eq!(wallet.current_nonce(), second + 1);
1659 }
1660
1661 #[test]
1662 fn test_private_key_hex() {
1663 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1664 let hex = wallet.private_key_hex();
1665 assert!(hex.starts_with("0x"));
1666 assert_eq!(hex.len(), 66); assert_eq!(wallet.try_private_key_hex().unwrap(), hex);
1668 }
1669
1670 #[test]
1671 fn test_wallet_debug() {
1672 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1673 let debug = format!("{:?}", wallet);
1674 assert!(debug.contains("HypercallWallet"));
1675 assert!(debug.contains("address"));
1676 assert!(debug.contains("signer_backend"));
1677 assert!(debug.contains("nonce"));
1678 assert!(!debug.contains(TEST_PRIVATE_KEY));
1679 assert!(!debug.contains(TEST_PRIVATE_KEY.trim_start_matches("0x")));
1680 }
1681
1682 #[cfg(feature = "kms")]
1683 #[test]
1684 fn test_aws_kms_constructor_is_exposed_without_polling() {
1685 fn assert_send<T: Send>(_: T) {}
1686
1687 let future = HypercallWallet::from_aws_kms_key_id("alias/hypercall-test", 998);
1688 assert_send(future);
1689 }
1690
1691 #[test]
1692 fn test_wallet_clone() {
1693 let wallet1 = HypercallWallet::random(998);
1694 let wallet2 = wallet1.clone();
1695
1696 assert_eq!(wallet1.address, wallet2.address);
1697 }
1699
1700 #[tokio::test]
1701 async fn test_sign_place_order_includes_route() {
1702 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1703 let nonce = 7;
1704
1705 let signature = wallet
1706 .sign_place_order_payload(PlaceOrderSignature {
1707 wallet: wallet.address,
1708 symbol: "BTC-20250131-100000-C",
1709 side: "Buy",
1710 size: "1",
1711 price: "100",
1712 tif: "gtc",
1713 route: OrderRoute::BookOnly,
1714 client_id: "cli_1",
1715 reduce_only: false,
1716 nonce,
1717 })
1718 .await
1719 .unwrap();
1720
1721 let message = PlaceOrder {
1722 wallet: wallet.address.as_wallet_address().inner(),
1723 symbol: "BTC-20250131-100000-C".to_string(),
1724 side: "Buy".to_string(),
1725 size: "1".to_string(),
1726 price: "100".to_string(),
1727 tif: "gtc".to_string(),
1728 route: "book_only".to_string(),
1729 clientId: "cli_1".to_string(),
1730 nonce,
1731 };
1732 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1733 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1734 }
1735
1736 #[tokio::test]
1737 async fn test_sign_place_order_reduce_only_uses_reduce_only_payload() {
1738 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1739 let nonce = 8;
1740
1741 let signature = wallet
1742 .sign_place_order_payload(PlaceOrderSignature {
1743 wallet: wallet.address,
1744 symbol: "BTC-20250131-100000-C",
1745 side: "Sell",
1746 size: "1",
1747 price: "100",
1748 tif: "gtc",
1749 route: OrderRoute::BookOnly,
1750 client_id: "cli_ro",
1751 reduce_only: true,
1752 nonce,
1753 })
1754 .await
1755 .unwrap();
1756
1757 let reduce_only_message = PlaceOrderReduceOnly {
1758 wallet: wallet.address.as_wallet_address().inner(),
1759 symbol: "BTC-20250131-100000-C".to_string(),
1760 side: "Sell".to_string(),
1761 size: "1".to_string(),
1762 price: "100".to_string(),
1763 tif: "gtc".to_string(),
1764 route: "book_only".to_string(),
1765 clientId: "cli_ro".to_string(),
1766 reduceOnly: true,
1767 nonce,
1768 };
1769 let recovered =
1770 recover_typed_signer(&reduce_only_message, &wallet.hypercall_domain(), &signature);
1771 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1772
1773 let old_message = PlaceOrder {
1774 wallet: wallet.address.as_wallet_address().inner(),
1775 symbol: "BTC-20250131-100000-C".to_string(),
1776 side: "Sell".to_string(),
1777 size: "1".to_string(),
1778 price: "100".to_string(),
1779 tif: "gtc".to_string(),
1780 route: "book_only".to_string(),
1781 clientId: "cli_ro".to_string(),
1782 nonce,
1783 };
1784 let old_recovered =
1785 recover_typed_signer(&old_message, &wallet.hypercall_domain(), &signature);
1786 assert_ne!(old_recovered, wallet.address.as_wallet_address().inner());
1787 }
1788
1789 #[tokio::test]
1790 async fn test_sign_cancel_order() {
1791 let wallet = HypercallWallet::random(998);
1792 let nonce = wallet.next_nonce();
1793
1794 let signature = wallet.sign_cancel_order("12345", nonce).await.unwrap();
1795 assert!(!signature.is_empty());
1796 }
1797
1798 #[tokio::test]
1799 async fn test_sign_set_margin_mode() {
1800 let wallet = HypercallWallet::random(998);
1801 let nonce = wallet.next_nonce();
1802
1803 let signature = wallet
1804 .sign_set_margin_mode("portfolio", nonce)
1805 .await
1806 .unwrap();
1807
1808 assert!(!signature.is_empty());
1809 }
1810
1811 #[tokio::test]
1812 async fn test_signatures_are_deterministic() {
1813 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1815
1816 let sig1 = wallet
1817 .sign_place_order_payload(place_signature(wallet.address, 1))
1818 .await
1819 .unwrap();
1820
1821 let sig2 = wallet
1822 .sign_place_order_payload(place_signature(wallet.address, 1))
1823 .await
1824 .unwrap();
1825
1826 assert_eq!(sig1, sig2);
1827 }
1828
1829 #[tokio::test]
1830 async fn test_sign_submit_rfq() {
1831 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1832 let rfq_id = [1u8; 32];
1833 let legs_hash = [2u8; 32];
1834 let nonce = 1u64;
1835
1836 let signature = wallet
1837 .sign_submit_rfq(rfq_id, legs_hash, nonce)
1838 .await
1839 .unwrap();
1840 assert!(!signature.is_empty());
1841
1842 let message = SubmitRFQ {
1843 rfqId: alloy::primitives::FixedBytes(rfq_id),
1844 legsHash: alloy::primitives::FixedBytes(legs_hash),
1845 wallet: wallet.address.as_wallet_address().inner(),
1846 nonce,
1847 };
1848 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1849 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1850 }
1851
1852 #[tokio::test]
1853 async fn test_sign_submit_rfq_response() {
1854 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1855 let rfq_id = [1u8; 32];
1856 let legs_hash = [2u8; 32];
1857 let net_premium = alloy::primitives::I256::try_from(385_000_000i64).unwrap();
1858 let valid_for_ms = alloy::primitives::U256::from(3000u64);
1859 let nonce = 1u64;
1860
1861 let signature = wallet
1862 .sign_submit_rfq_response(rfq_id, legs_hash, net_premium, valid_for_ms, nonce)
1863 .await
1864 .unwrap();
1865 assert!(!signature.is_empty());
1866
1867 let message = SubmitRFQResponse {
1868 rfqId: alloy::primitives::FixedBytes(rfq_id),
1869 legsHash: alloy::primitives::FixedBytes(legs_hash),
1870 netPremium: net_premium,
1871 validForMs: valid_for_ms,
1872 qpWallet: wallet.address.as_wallet_address().inner(),
1873 nonce,
1874 };
1875 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1876 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1877 }
1878
1879 #[tokio::test]
1880 async fn test_sign_accept_rfq_quote() {
1881 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1882 let rfq_id = [1u8; 32];
1883 let quote_id = [3u8; 32];
1884 let net_premium = alloy::primitives::I256::try_from(385_000_000i64).unwrap();
1885 let nonce = 1u64;
1886
1887 let signature = wallet
1888 .sign_accept_rfq_quote(rfq_id, quote_id, net_premium, nonce)
1889 .await
1890 .unwrap();
1891 assert!(!signature.is_empty());
1892
1893 let message = AcceptRFQQuote {
1894 rfqId: alloy::primitives::FixedBytes(rfq_id),
1895 quoteId: alloy::primitives::FixedBytes(quote_id),
1896 netPremium: net_premium,
1897 wallet: wallet.address.as_wallet_address().inner(),
1898 nonce,
1899 };
1900 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1901 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1902 }
1903
1904 #[tokio::test]
1905 async fn test_sign_connect_quote_provider() {
1906 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1907 let timestamp = alloy::primitives::U256::from(1711036800000u64);
1908 let nonce = 1u64;
1909
1910 let signature = wallet
1911 .sign_connect_quote_provider(timestamp, nonce)
1912 .await
1913 .unwrap();
1914 assert!(!signature.is_empty());
1915
1916 let message = ConnectQuoteProvider {
1917 wallet: wallet.address.as_wallet_address().inner(),
1918 timestamp,
1919 nonce,
1920 };
1921 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1922 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1923 }
1924
1925 #[tokio::test]
1926 async fn test_sign_standard_margin_liquidation_order() {
1927 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1928 let liquidated_wallet = AccountAddress::from(
1929 WalletAddress::from_str("0x1111111111111111111111111111111111111111").unwrap(),
1930 );
1931 let nonce = 1u64;
1932
1933 let signature = wallet
1934 .sign_standard_margin_liquidation_payload(StandardMarginLiquidationSignature {
1935 wallet: wallet.address,
1936 liquidated_wallet,
1937 request_id: "01972be2-3d8a-7000-8000-000000000001",
1938 auction_id: "auction-1",
1939 bid_usdc: "100",
1940 portfolio_hash: "portfolio-hash",
1941 auction_terms_hash: "terms-hash",
1942 bid_intent_hash: "bid-intent-hash",
1943 auction_version: 1,
1944 nonce,
1945 })
1946 .await
1947 .unwrap();
1948 assert!(!signature.is_empty());
1949
1950 let message = StandardMarginLiquidationOrder {
1951 wallet: wallet.address.as_wallet_address().inner(),
1952 liquidatedWallet: liquidated_wallet.as_wallet_address().inner(),
1953 requestId: "01972be2-3d8a-7000-8000-000000000001".to_string(),
1954 auctionId: "auction-1".to_string(),
1955 bidUsdc: "100".to_string(),
1956 portfolioHash: "portfolio-hash".to_string(),
1957 auctionTermsHash: "terms-hash".to_string(),
1958 bidIntentHash: "bid-intent-hash".to_string(),
1959 auctionVersion: 1,
1960 nonce,
1961 };
1962 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1963 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1964 }
1965
1966 #[tokio::test]
1967 async fn test_rfq_signatures_are_deterministic() {
1968 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1969 let rfq_id = [1u8; 32];
1970 let legs_hash = [2u8; 32];
1971
1972 let sig1 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1973 let sig2 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1974 assert_eq!(sig1, sig2);
1975 }
1976
1977 #[tokio::test]
1978 async fn test_rfq_signatures_differ_with_different_nonce() {
1979 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1980 let rfq_id = [1u8; 32];
1981 let legs_hash = [2u8; 32];
1982
1983 let sig1 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1984 let sig2 = wallet.sign_submit_rfq(rfq_id, legs_hash, 2).await.unwrap();
1985 assert_ne!(sig1, sig2);
1986 }
1987
1988 #[tokio::test]
1989 async fn test_signatures_differ_with_different_nonce() {
1990 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1991
1992 let sig1 = wallet
1993 .sign_place_order_payload(place_signature(wallet.address, 1))
1994 .await
1995 .unwrap();
1996
1997 let sig2 = wallet
1998 .sign_place_order_payload(place_signature(wallet.address, 2))
1999 .await
2000 .unwrap();
2001
2002 assert_ne!(sig1, sig2);
2003 }
2004
2005 #[tokio::test]
2006 async fn test_sign_replace_order() {
2007 let wallet = HypercallWallet::random(998);
2008 let nonce = wallet.next_nonce();
2009
2010 let signature = wallet
2011 .sign_replace_order_payload(replace_signature(wallet.address, nonce))
2012 .await
2013 .unwrap();
2014
2015 assert!(!signature.is_empty());
2016 }
2017
2018 #[tokio::test]
2019 async fn test_replace_order_signature_roundtrip() {
2020 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
2021 let nonce = wallet.next_nonce();
2022 let order_id = "42";
2023 let symbol = "BTC-20250131-100000-C";
2024 let side = "Buy";
2025 let size = "5";
2026 let price = "0.05";
2027 let tif = "gtc";
2028 let client_id = "cli_rt";
2029
2030 let signature = wallet
2031 .sign_replace_order_payload(ReplaceOrderSignature {
2032 wallet: wallet.address,
2033 order_id,
2034 symbol,
2035 side,
2036 size,
2037 price,
2038 tif,
2039 client_id,
2040 reduce_only: false,
2041 nonce,
2042 })
2043 .await
2044 .unwrap();
2045
2046 let message = ReplaceOrder {
2047 wallet: wallet.address.as_wallet_address().inner(),
2048 orderId: order_id.to_string(),
2049 symbol: symbol.to_string(),
2050 side: side.to_string(),
2051 size: size.to_string(),
2052 price: price.to_string(),
2053 tif: tif.to_string(),
2054 clientId: client_id.to_string(),
2055 nonce,
2056 };
2057 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
2058 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
2059 }
2060
2061 #[tokio::test]
2062 async fn test_sign_replace_order_reduce_only_uses_reduce_only_payload() {
2063 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
2064 let nonce = wallet.next_nonce();
2065
2066 let signature = wallet
2067 .sign_replace_order_payload(ReplaceOrderSignature {
2068 wallet: wallet.address,
2069 order_id: "42",
2070 symbol: "BTC-20250131-100000-C",
2071 side: "Buy",
2072 size: "1",
2073 price: "100",
2074 tif: "gtc",
2075 client_id: "cli_replace_ro",
2076 reduce_only: true,
2077 nonce,
2078 })
2079 .await
2080 .unwrap();
2081
2082 let reduce_only_message = ReplaceOrderReduceOnly {
2083 wallet: wallet.address.as_wallet_address().inner(),
2084 orderId: "42".to_string(),
2085 symbol: "BTC-20250131-100000-C".to_string(),
2086 side: "Buy".to_string(),
2087 size: "1".to_string(),
2088 price: "100".to_string(),
2089 tif: "gtc".to_string(),
2090 clientId: "cli_replace_ro".to_string(),
2091 reduceOnly: true,
2092 nonce,
2093 };
2094 let recovered =
2095 recover_typed_signer(&reduce_only_message, &wallet.hypercall_domain(), &signature);
2096 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
2097
2098 let old_message = ReplaceOrder {
2099 wallet: wallet.address.as_wallet_address().inner(),
2100 orderId: "42".to_string(),
2101 symbol: "BTC-20250131-100000-C".to_string(),
2102 side: "Buy".to_string(),
2103 size: "1".to_string(),
2104 price: "100".to_string(),
2105 tif: "gtc".to_string(),
2106 clientId: "cli_replace_ro".to_string(),
2107 nonce,
2108 };
2109 let old_recovered =
2110 recover_typed_signer(&old_message, &wallet.hypercall_domain(), &signature);
2111 assert_ne!(old_recovered, wallet.address.as_wallet_address().inner());
2112 }
2113}
2114
2115#[cfg(test)]
2116#[path = "wallet_test.rs"]
2117mod directive_tests;