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
418fn 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
1345 let domain = self.hypercall_domain();
1346 let signature = self
1347 .signer
1348 .sign_typed_data(&message, &domain)
1349 .await
1350 .map_err(|error| ClientError::signing("Failed to sign SetMarginMode", error))?;
1351
1352 Ok(format!("{}", signature))
1353 }
1354
1355 pub async fn sign_redeem_pool_shares(&self, shares: &str, nonce: u64) -> Result<String> {
1358 let message = RedeemPoolShares {
1359 wallet: self.address.as_wallet_address().inner(),
1360 shares: shares.to_string(),
1361 nonce,
1362 };
1363
1364 let domain = self.hypercall_domain();
1365 let signature = self
1366 .signer
1367 .sign_typed_data(&message, &domain)
1368 .await
1369 .map_err(|error| ClientError::signing("Failed to sign RedeemPoolShares", error))?;
1370
1371 Ok(format!("{}", signature))
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
1387 let domain = self.hypercall_domain();
1388 let signature = self
1389 .signer
1390 .sign_typed_data(&message, &domain)
1391 .await
1392 .map_err(|error| ClientError::signing("Failed to sign CancelPoolRedemptions", error))?;
1393
1394 Ok(format!("{}", signature))
1395 }
1396
1397 pub async fn sign_submit_rfq(
1399 &self,
1400 rfq_id: [u8; 32],
1401 legs_hash: [u8; 32],
1402 nonce: u64,
1403 ) -> Result<String> {
1404 let message = SubmitRFQ {
1405 rfqId: alloy::primitives::FixedBytes(rfq_id),
1406 legsHash: alloy::primitives::FixedBytes(legs_hash),
1407 wallet: self.address.as_wallet_address().inner(),
1408 nonce,
1409 };
1410
1411 let domain = self.hypercall_domain();
1412 let signature = self
1413 .signer
1414 .sign_typed_data(&message, &domain)
1415 .await
1416 .map_err(|error| ClientError::signing("Failed to sign SubmitRFQ", error))?;
1417
1418 Ok(format!("{}", signature))
1419 }
1420
1421 pub async fn sign_submit_rfq_response(
1423 &self,
1424 rfq_id: [u8; 32],
1425 legs_hash: [u8; 32],
1426 net_premium: alloy::primitives::I256,
1427 valid_for_ms: alloy::primitives::U256,
1428 nonce: u64,
1429 ) -> Result<String> {
1430 let message = SubmitRFQResponse {
1431 rfqId: alloy::primitives::FixedBytes(rfq_id),
1432 legsHash: alloy::primitives::FixedBytes(legs_hash),
1433 netPremium: net_premium,
1434 validForMs: valid_for_ms,
1435 qpWallet: self.address.as_wallet_address().inner(),
1436 nonce,
1437 };
1438
1439 let domain = self.hypercall_domain();
1440 let signature = self
1441 .signer
1442 .sign_typed_data(&message, &domain)
1443 .await
1444 .map_err(|error| ClientError::signing("Failed to sign SubmitRFQResponse", error))?;
1445
1446 Ok(format!("{}", signature))
1447 }
1448
1449 pub async fn sign_accept_rfq_quote(
1451 &self,
1452 rfq_id: [u8; 32],
1453 quote_id: [u8; 32],
1454 net_premium: alloy::primitives::I256,
1455 nonce: u64,
1456 ) -> Result<String> {
1457 let message = AcceptRFQQuote {
1458 rfqId: alloy::primitives::FixedBytes(rfq_id),
1459 quoteId: alloy::primitives::FixedBytes(quote_id),
1460 netPremium: net_premium,
1461 wallet: self.address.as_wallet_address().inner(),
1462 nonce,
1463 };
1464
1465 let domain = self.hypercall_domain();
1466 let signature = self
1467 .signer
1468 .sign_typed_data(&message, &domain)
1469 .await
1470 .map_err(|error| ClientError::signing("Failed to sign AcceptRFQQuote", error))?;
1471
1472 Ok(format!("{}", signature))
1473 }
1474
1475 pub async fn sign_submit_auto_execute_rfq(
1477 &self,
1478 rfq_id: [u8; 32],
1479 legs_hash: [u8; 32],
1480 limit_price: alloy::primitives::I256,
1481 nonce: u64,
1482 ) -> Result<String> {
1483 let message = SubmitAutoExecuteRfq {
1484 rfqId: alloy::primitives::FixedBytes(rfq_id),
1485 legsHash: alloy::primitives::FixedBytes(legs_hash),
1486 limitPrice: limit_price,
1487 wallet: self.address.as_wallet_address().inner(),
1488 nonce,
1489 };
1490
1491 let domain = self.hypercall_domain();
1492 let signature = self
1493 .signer
1494 .sign_typed_data(&message, &domain)
1495 .await
1496 .map_err(|error| ClientError::signing("Failed to sign SubmitAutoExecuteRfq", error))?;
1497
1498 Ok(format!("{}", signature))
1499 }
1500
1501 pub async fn sign_connect_quote_provider(
1503 &self,
1504 timestamp: alloy::primitives::U256,
1505 nonce: u64,
1506 ) -> Result<String> {
1507 let message = ConnectQuoteProvider {
1508 wallet: self.address.as_wallet_address().inner(),
1509 timestamp,
1510 nonce,
1511 };
1512
1513 let domain = self.hypercall_domain();
1514 let signature = self
1515 .signer
1516 .sign_typed_data(&message, &domain)
1517 .await
1518 .map_err(|error| ClientError::signing("Failed to sign ConnectQuoteProvider", error))?;
1519
1520 Ok(format!("{}", signature))
1521 }
1522}
1523
1524impl std::fmt::Debug for HypercallWallet {
1525 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1526 f.debug_struct("HypercallWallet")
1527 .field("address", &self.address)
1528 .field("signer_backend", &self.signer.kind())
1529 .field("nonce", &self.current_nonce())
1530 .finish()
1531 }
1532}
1533
1534#[cfg(test)]
1535mod tests {
1536 use super::*;
1537 use alloy::primitives::Address;
1538
1539 const TEST_PRIVATE_KEY: &str =
1541 "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1542
1543 fn recover_address_from_signature(signature: &str, message_hash: &[u8; 32]) -> Address {
1544 let signature_bytes = hex::decode(signature.trim_start_matches("0x")).unwrap();
1545 assert_eq!(signature_bytes.len(), 65);
1546
1547 let parity = match signature_bytes[64] {
1548 0 | 27 => false,
1549 1 | 28 => true,
1550 v => panic!("invalid signature v value: {v}"),
1551 };
1552 let sig =
1553 alloy::primitives::Signature::from_bytes_and_parity(&signature_bytes[..64], parity);
1554
1555 sig.recover_address_from_prehash(&alloy::primitives::B256::from(*message_hash))
1556 .unwrap()
1557 }
1558
1559 fn recover_typed_signer<T: SolStruct>(
1560 message: &T,
1561 domain: &Eip712Domain,
1562 signature: &str,
1563 ) -> Address {
1564 let message_hash = message.eip712_signing_hash(domain);
1565 recover_address_from_signature(signature, &message_hash)
1566 }
1567
1568 fn place_signature(wallet: AccountAddress, nonce: u64) -> PlaceOrderSignature<'static> {
1569 PlaceOrderSignature {
1570 wallet,
1571 symbol: "BTC-20250131-100000-C",
1572 side: "Buy",
1573 size: "1",
1574 price: "100",
1575 tif: "gtc",
1576 route: OrderRoute::BestExecution,
1577 client_id: "cli_1",
1578 reduce_only: false,
1579 nonce,
1580 }
1581 }
1582
1583 fn replace_signature(wallet: AccountAddress, nonce: u64) -> ReplaceOrderSignature<'static> {
1584 ReplaceOrderSignature {
1585 wallet,
1586 order_id: "42",
1587 symbol: "BTC-20250131-100000-C",
1588 side: "Buy",
1589 size: "1",
1590 price: "100",
1591 tif: "gtc",
1592 client_id: "cli_replace",
1593 reduce_only: false,
1594 nonce,
1595 }
1596 }
1597
1598 #[test]
1599 fn test_random_wallet() {
1600 let wallet = HypercallWallet::random(998);
1601 assert_ne!(
1602 wallet.address.as_hex(),
1603 "0x0000000000000000000000000000000000000000"
1604 );
1605 }
1606
1607 #[test]
1608 fn test_from_private_key() {
1609 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1610 assert_eq!(
1612 wallet.address.as_hex().to_lowercase(),
1613 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1614 );
1615 }
1616
1617 #[test]
1618 fn test_from_private_key_without_prefix() {
1619 let key_without_prefix = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1620 let wallet = HypercallWallet::from_private_key(key_without_prefix, 998).unwrap();
1621 assert_eq!(
1622 wallet.address.as_hex().to_lowercase(),
1623 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1624 );
1625 }
1626
1627 #[test]
1628 fn test_from_private_key_invalid() {
1629 let result = HypercallWallet::from_private_key("invalid_key", 998);
1630 assert!(result.is_err());
1631 }
1632
1633 #[test]
1634 fn test_from_bytes() {
1635 let bytes: [u8; 32] = [
1636 0xac, 0x09, 0x74, 0xbe, 0xc3, 0x9a, 0x17, 0xe3, 0x6b, 0xa4, 0xa6, 0xb4, 0xd2, 0x38,
1637 0xff, 0x94, 0x4b, 0xac, 0xb4, 0x78, 0xcb, 0xed, 0x5e, 0xfc, 0xae, 0x78, 0x4d, 0x7b,
1638 0xf4, 0xf2, 0xff, 0x80,
1639 ];
1640 let wallet = HypercallWallet::from_bytes(&bytes, 998).unwrap();
1641 assert_eq!(
1642 wallet.address.as_hex().to_lowercase(),
1643 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
1644 );
1645 }
1646
1647 #[test]
1648 fn test_nonce_management() {
1649 let wallet = HypercallWallet::random(998);
1650
1651 let initial = wallet.current_nonce();
1655 assert!(initial > 1, "expected epoch-seeded nonce, got {initial}");
1656
1657 let first = wallet.next_nonce();
1660 assert!(first >= initial);
1661 assert_eq!(wallet.current_nonce(), first + 1);
1662
1663 let second = wallet.next_nonce();
1664 assert!(second > first);
1665 assert_eq!(wallet.current_nonce(), second + 1);
1666 }
1667
1668 #[test]
1669 fn test_private_key_hex() {
1670 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1671 let hex = wallet.private_key_hex();
1672 assert!(hex.starts_with("0x"));
1673 assert_eq!(hex.len(), 66); assert_eq!(wallet.try_private_key_hex().unwrap(), hex);
1675 }
1676
1677 #[test]
1678 fn test_wallet_debug() {
1679 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1680 let debug = format!("{:?}", wallet);
1681 assert!(debug.contains("HypercallWallet"));
1682 assert!(debug.contains("address"));
1683 assert!(debug.contains("signer_backend"));
1684 assert!(debug.contains("nonce"));
1685 assert!(!debug.contains(TEST_PRIVATE_KEY));
1686 assert!(!debug.contains(TEST_PRIVATE_KEY.trim_start_matches("0x")));
1687 }
1688
1689 #[cfg(feature = "kms")]
1690 #[test]
1691 fn test_aws_kms_constructor_is_exposed_without_polling() {
1692 fn assert_send<T: Send>(_: T) {}
1693
1694 let future = HypercallWallet::from_aws_kms_key_id("alias/hypercall-test", 998);
1695 assert_send(future);
1696 }
1697
1698 #[test]
1699 fn test_wallet_clone() {
1700 let wallet1 = HypercallWallet::random(998);
1701 let wallet2 = wallet1.clone();
1702
1703 assert_eq!(wallet1.address, wallet2.address);
1704 }
1706
1707 #[tokio::test]
1708 async fn test_sign_place_order_includes_route() {
1709 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1710 let nonce = 7;
1711
1712 let signature = wallet
1713 .sign_place_order_payload(PlaceOrderSignature {
1714 wallet: wallet.address,
1715 symbol: "BTC-20250131-100000-C",
1716 side: "Buy",
1717 size: "1",
1718 price: "100",
1719 tif: "gtc",
1720 route: OrderRoute::BookOnly,
1721 client_id: "cli_1",
1722 reduce_only: false,
1723 nonce,
1724 })
1725 .await
1726 .unwrap();
1727
1728 let message = PlaceOrder {
1729 wallet: wallet.address.as_wallet_address().inner(),
1730 symbol: "BTC-20250131-100000-C".to_string(),
1731 side: "Buy".to_string(),
1732 size: "1".to_string(),
1733 price: "100".to_string(),
1734 tif: "gtc".to_string(),
1735 route: "book_only".to_string(),
1736 clientId: "cli_1".to_string(),
1737 nonce,
1738 };
1739 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1740 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1741 }
1742
1743 #[tokio::test]
1744 async fn test_sign_place_order_reduce_only_uses_reduce_only_payload() {
1745 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1746 let nonce = 8;
1747
1748 let signature = wallet
1749 .sign_place_order_payload(PlaceOrderSignature {
1750 wallet: wallet.address,
1751 symbol: "BTC-20250131-100000-C",
1752 side: "Sell",
1753 size: "1",
1754 price: "100",
1755 tif: "gtc",
1756 route: OrderRoute::BookOnly,
1757 client_id: "cli_ro",
1758 reduce_only: true,
1759 nonce,
1760 })
1761 .await
1762 .unwrap();
1763
1764 let reduce_only_message = PlaceOrderReduceOnly {
1765 wallet: wallet.address.as_wallet_address().inner(),
1766 symbol: "BTC-20250131-100000-C".to_string(),
1767 side: "Sell".to_string(),
1768 size: "1".to_string(),
1769 price: "100".to_string(),
1770 tif: "gtc".to_string(),
1771 route: "book_only".to_string(),
1772 clientId: "cli_ro".to_string(),
1773 reduceOnly: true,
1774 nonce,
1775 };
1776 let recovered =
1777 recover_typed_signer(&reduce_only_message, &wallet.hypercall_domain(), &signature);
1778 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1779
1780 let old_message = PlaceOrder {
1781 wallet: wallet.address.as_wallet_address().inner(),
1782 symbol: "BTC-20250131-100000-C".to_string(),
1783 side: "Sell".to_string(),
1784 size: "1".to_string(),
1785 price: "100".to_string(),
1786 tif: "gtc".to_string(),
1787 route: "book_only".to_string(),
1788 clientId: "cli_ro".to_string(),
1789 nonce,
1790 };
1791 let old_recovered =
1792 recover_typed_signer(&old_message, &wallet.hypercall_domain(), &signature);
1793 assert_ne!(old_recovered, wallet.address.as_wallet_address().inner());
1794 }
1795
1796 #[tokio::test]
1797 async fn test_sign_cancel_order() {
1798 let wallet = HypercallWallet::random(998);
1799 let nonce = wallet.next_nonce();
1800
1801 let signature = wallet.sign_cancel_order("12345", nonce).await.unwrap();
1802 assert!(!signature.is_empty());
1803 }
1804
1805 #[tokio::test]
1806 async fn test_sign_set_margin_mode() {
1807 let wallet = HypercallWallet::random(998);
1808 let nonce = wallet.next_nonce();
1809
1810 let signature = wallet
1811 .sign_set_margin_mode("portfolio", nonce)
1812 .await
1813 .unwrap();
1814
1815 assert!(!signature.is_empty());
1816 }
1817
1818 #[tokio::test]
1819 async fn test_signatures_are_deterministic() {
1820 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1822
1823 let sig1 = wallet
1824 .sign_place_order_payload(place_signature(wallet.address, 1))
1825 .await
1826 .unwrap();
1827
1828 let sig2 = wallet
1829 .sign_place_order_payload(place_signature(wallet.address, 1))
1830 .await
1831 .unwrap();
1832
1833 assert_eq!(sig1, sig2);
1834 }
1835
1836 #[tokio::test]
1837 async fn test_sign_submit_rfq() {
1838 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1839 let rfq_id = [1u8; 32];
1840 let legs_hash = [2u8; 32];
1841 let nonce = 1u64;
1842
1843 let signature = wallet
1844 .sign_submit_rfq(rfq_id, legs_hash, nonce)
1845 .await
1846 .unwrap();
1847 assert!(!signature.is_empty());
1848
1849 let message = SubmitRFQ {
1850 rfqId: alloy::primitives::FixedBytes(rfq_id),
1851 legsHash: alloy::primitives::FixedBytes(legs_hash),
1852 wallet: wallet.address.as_wallet_address().inner(),
1853 nonce,
1854 };
1855 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1856 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1857 }
1858
1859 #[tokio::test]
1860 async fn test_sign_submit_rfq_response() {
1861 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1862 let rfq_id = [1u8; 32];
1863 let legs_hash = [2u8; 32];
1864 let net_premium = alloy::primitives::I256::try_from(385_000_000i64).unwrap();
1865 let valid_for_ms = alloy::primitives::U256::from(3000u64);
1866 let nonce = 1u64;
1867
1868 let signature = wallet
1869 .sign_submit_rfq_response(rfq_id, legs_hash, net_premium, valid_for_ms, nonce)
1870 .await
1871 .unwrap();
1872 assert!(!signature.is_empty());
1873
1874 let message = SubmitRFQResponse {
1875 rfqId: alloy::primitives::FixedBytes(rfq_id),
1876 legsHash: alloy::primitives::FixedBytes(legs_hash),
1877 netPremium: net_premium,
1878 validForMs: valid_for_ms,
1879 qpWallet: wallet.address.as_wallet_address().inner(),
1880 nonce,
1881 };
1882 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1883 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1884 }
1885
1886 #[tokio::test]
1887 async fn test_sign_accept_rfq_quote() {
1888 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1889 let rfq_id = [1u8; 32];
1890 let quote_id = [3u8; 32];
1891 let net_premium = alloy::primitives::I256::try_from(385_000_000i64).unwrap();
1892 let nonce = 1u64;
1893
1894 let signature = wallet
1895 .sign_accept_rfq_quote(rfq_id, quote_id, net_premium, nonce)
1896 .await
1897 .unwrap();
1898 assert!(!signature.is_empty());
1899
1900 let message = AcceptRFQQuote {
1901 rfqId: alloy::primitives::FixedBytes(rfq_id),
1902 quoteId: alloy::primitives::FixedBytes(quote_id),
1903 netPremium: net_premium,
1904 wallet: wallet.address.as_wallet_address().inner(),
1905 nonce,
1906 };
1907 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1908 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1909 }
1910
1911 #[tokio::test]
1912 async fn test_sign_connect_quote_provider() {
1913 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1914 let timestamp = alloy::primitives::U256::from(1711036800000u64);
1915 let nonce = 1u64;
1916
1917 let signature = wallet
1918 .sign_connect_quote_provider(timestamp, nonce)
1919 .await
1920 .unwrap();
1921 assert!(!signature.is_empty());
1922
1923 let message = ConnectQuoteProvider {
1924 wallet: wallet.address.as_wallet_address().inner(),
1925 timestamp,
1926 nonce,
1927 };
1928 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1929 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1930 }
1931
1932 #[tokio::test]
1933 async fn test_sign_standard_margin_liquidation_order() {
1934 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1935 let liquidated_wallet = AccountAddress::from(
1936 WalletAddress::from_str("0x1111111111111111111111111111111111111111").unwrap(),
1937 );
1938 let nonce = 1u64;
1939
1940 let signature = wallet
1941 .sign_standard_margin_liquidation_payload(StandardMarginLiquidationSignature {
1942 wallet: wallet.address,
1943 liquidated_wallet,
1944 request_id: "01972be2-3d8a-7000-8000-000000000001",
1945 auction_id: "auction-1",
1946 bid_usdc: "100",
1947 portfolio_hash: "portfolio-hash",
1948 auction_terms_hash: "terms-hash",
1949 bid_intent_hash: "bid-intent-hash",
1950 auction_version: 1,
1951 nonce,
1952 })
1953 .await
1954 .unwrap();
1955 assert!(!signature.is_empty());
1956
1957 let message = StandardMarginLiquidationOrder {
1958 wallet: wallet.address.as_wallet_address().inner(),
1959 liquidatedWallet: liquidated_wallet.as_wallet_address().inner(),
1960 requestId: "01972be2-3d8a-7000-8000-000000000001".to_string(),
1961 auctionId: "auction-1".to_string(),
1962 bidUsdc: "100".to_string(),
1963 portfolioHash: "portfolio-hash".to_string(),
1964 auctionTermsHash: "terms-hash".to_string(),
1965 bidIntentHash: "bid-intent-hash".to_string(),
1966 auctionVersion: 1,
1967 nonce,
1968 };
1969 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
1970 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
1971 }
1972
1973 #[tokio::test]
1974 async fn test_rfq_signatures_are_deterministic() {
1975 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1976 let rfq_id = [1u8; 32];
1977 let legs_hash = [2u8; 32];
1978
1979 let sig1 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1980 let sig2 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1981 assert_eq!(sig1, sig2);
1982 }
1983
1984 #[tokio::test]
1985 async fn test_rfq_signatures_differ_with_different_nonce() {
1986 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1987 let rfq_id = [1u8; 32];
1988 let legs_hash = [2u8; 32];
1989
1990 let sig1 = wallet.sign_submit_rfq(rfq_id, legs_hash, 1).await.unwrap();
1991 let sig2 = wallet.sign_submit_rfq(rfq_id, legs_hash, 2).await.unwrap();
1992 assert_ne!(sig1, sig2);
1993 }
1994
1995 #[tokio::test]
1996 async fn test_signatures_differ_with_different_nonce() {
1997 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
1998
1999 let sig1 = wallet
2000 .sign_place_order_payload(place_signature(wallet.address, 1))
2001 .await
2002 .unwrap();
2003
2004 let sig2 = wallet
2005 .sign_place_order_payload(place_signature(wallet.address, 2))
2006 .await
2007 .unwrap();
2008
2009 assert_ne!(sig1, sig2);
2010 }
2011
2012 #[tokio::test]
2013 async fn test_sign_replace_order() {
2014 let wallet = HypercallWallet::random(998);
2015 let nonce = wallet.next_nonce();
2016
2017 let signature = wallet
2018 .sign_replace_order_payload(replace_signature(wallet.address, nonce))
2019 .await
2020 .unwrap();
2021
2022 assert!(!signature.is_empty());
2023 }
2024
2025 #[tokio::test]
2026 async fn test_replace_order_signature_roundtrip() {
2027 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
2028 let nonce = wallet.next_nonce();
2029 let order_id = "42";
2030 let symbol = "BTC-20250131-100000-C";
2031 let side = "Buy";
2032 let size = "5";
2033 let price = "0.05";
2034 let tif = "gtc";
2035 let client_id = "cli_rt";
2036
2037 let signature = wallet
2038 .sign_replace_order_payload(ReplaceOrderSignature {
2039 wallet: wallet.address,
2040 order_id,
2041 symbol,
2042 side,
2043 size,
2044 price,
2045 tif,
2046 client_id,
2047 reduce_only: false,
2048 nonce,
2049 })
2050 .await
2051 .unwrap();
2052
2053 let message = ReplaceOrder {
2054 wallet: wallet.address.as_wallet_address().inner(),
2055 orderId: order_id.to_string(),
2056 symbol: symbol.to_string(),
2057 side: side.to_string(),
2058 size: size.to_string(),
2059 price: price.to_string(),
2060 tif: tif.to_string(),
2061 clientId: client_id.to_string(),
2062 nonce,
2063 };
2064 let recovered = recover_typed_signer(&message, &wallet.hypercall_domain(), &signature);
2065 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
2066 }
2067
2068 #[tokio::test]
2069 async fn test_sign_replace_order_reduce_only_uses_reduce_only_payload() {
2070 let wallet = HypercallWallet::from_private_key(TEST_PRIVATE_KEY, 998).unwrap();
2071 let nonce = wallet.next_nonce();
2072
2073 let signature = wallet
2074 .sign_replace_order_payload(ReplaceOrderSignature {
2075 wallet: wallet.address,
2076 order_id: "42",
2077 symbol: "BTC-20250131-100000-C",
2078 side: "Buy",
2079 size: "1",
2080 price: "100",
2081 tif: "gtc",
2082 client_id: "cli_replace_ro",
2083 reduce_only: true,
2084 nonce,
2085 })
2086 .await
2087 .unwrap();
2088
2089 let reduce_only_message = ReplaceOrderReduceOnly {
2090 wallet: wallet.address.as_wallet_address().inner(),
2091 orderId: "42".to_string(),
2092 symbol: "BTC-20250131-100000-C".to_string(),
2093 side: "Buy".to_string(),
2094 size: "1".to_string(),
2095 price: "100".to_string(),
2096 tif: "gtc".to_string(),
2097 clientId: "cli_replace_ro".to_string(),
2098 reduceOnly: true,
2099 nonce,
2100 };
2101 let recovered =
2102 recover_typed_signer(&reduce_only_message, &wallet.hypercall_domain(), &signature);
2103 assert_eq!(recovered, wallet.address.as_wallet_address().inner());
2104
2105 let old_message = ReplaceOrder {
2106 wallet: wallet.address.as_wallet_address().inner(),
2107 orderId: "42".to_string(),
2108 symbol: "BTC-20250131-100000-C".to_string(),
2109 side: "Buy".to_string(),
2110 size: "1".to_string(),
2111 price: "100".to_string(),
2112 tif: "gtc".to_string(),
2113 clientId: "cli_replace_ro".to_string(),
2114 nonce,
2115 };
2116 let old_recovered =
2117 recover_typed_signer(&old_message, &wallet.hypercall_domain(), &signature);
2118 assert_ne!(old_recovered, wallet.address.as_wallet_address().inner());
2119 }
2120}
2121
2122#[cfg(test)]
2123#[path = "wallet_test.rs"]
2124mod directive_tests;