1#![allow(
402 clippy::result_large_err,
403 reason = "these helpers preserve the established unboxed public ClientError contract"
404)]
405
406use std::collections::HashMap;
407use std::sync::{Arc, Mutex as StdMutex, OnceLock};
408use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
409
410use alloy::primitives::{Address, B256, U256};
411use alloy::providers::{Provider, ProviderBuilder};
412use alloy::sol;
413use alloy::sol_types::{Eip712Domain, SolStruct};
414use hypercall_sdk_types::tee_perp::{
415 TEE_API_WALLET_APPROVAL_REQUEST_ROUTE, TEE_API_WALLET_APPROVAL_ROUTE,
416 TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE, TEE_PERP_CANCEL_SUBMIT_ROUTE,
417 TEE_PERP_LEVERAGE_SUBMIT_ROUTE, TEE_PERP_MARKETS_ROUTE, TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
418 TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE, TEE_PERP_ORDER_MODIFY_ROUTE, TEE_PERP_ORDER_SUBMIT_ROUTE,
419 TEE_PERP_PREVIEW_ROUTE, TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE, TEE_PERP_TWAP_CANCEL_ROUTE,
420 TEE_PERP_TWAP_SUBMIT_ROUTE,
421};
422use hypercall_sdk_types::{
423 ApiResponse, DirectiveDeliveryStatus, DirectiveDomainStatus, DirectiveStatusResponse,
424 DirectiveSubmitRequest, DirectiveSubmitResponse, ExchangeInfoResponse, HlCancelByCloidAction,
425 HlCancelByOidAction, HlLimitOrderAction, PerpPreviewRequest, PerpPreviewResponse,
426 PerpTimeInForce, Side, TeeApiWalletApprovalPackage, TeeApiWalletApprovalRequest,
427 TeeApiWalletApprovalSubmitRequest, TeePerpCancelResponse, TeePerpLeverageAction,
428 TeePerpLeverageResponse, TeePerpLimitOrderType, TeePerpMarketsResponse,
429 TeePerpOrderBatchAction, TeePerpOrderBatchResponse, TeePerpOrderGrouping, TeePerpOrderResponse,
430 TeePerpOrderType, TeePerpOrderWire, TeePerpTpsl, TeePerpTriggerOrderType,
431 TeePerpVenueActionResponse, WalletAddress, MAX_TEE_PERP_ORDER_BATCH_CHILDREN,
432 TEE_PERP_VENUE_TTL_MS,
433};
434use hypercall_sdk_types::{
435 TeePerpBatchModifyAction, TeePerpBatchModifyResponse, TeePerpModifyAction,
436 TeePerpModifyResponse, TeePerpTwapAction, TeePerpTwapCancelAction, TeePerpTwapResponse,
437 DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN, MAX_TEE_PERP_BATCH_MODIFY_CHILDREN,
438 TEE_PERP_TWAP_MAX_MINUTES, TEE_PERP_TWAP_MIN_MINUTES,
439};
440use reqwest::Method;
441use rust_decimal::Decimal;
442use serde::Deserialize;
443
444use crate::api::HypercallClient;
445use crate::error::{ClientError, Result};
446use crate::perp::{
447 to_perp_units, PerpCancelByCloidParams, PerpCancelByOidParams, PerpLimitOrderParams,
448};
449use crate::wallet::{
450 evm_submission_lock, AccountAddress, HypercallSigner, HypercallWallet,
451 PerpCancelByCloidSignature, PerpCancelByOidSignature, PerpDirectiveSigner,
452 PerpLimitOrderSignature,
453};
454
455pub const PERP_MARKET_SLIPPAGE_BPS: u32 = 2_000;
459pub const HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES: u32 = 5;
461pub const HYPERLIQUID_PERP_MAX_PRICE_DECIMALS: u32 = 6;
463pub const PERP_SCALE_MIN_ORDERS: usize = 2;
465pub const PERP_SCALE_MAX_ORDERS: usize = 100;
467pub const HYPERLIQUID_MAINNET_INFO_URL: &str = "https://api.hyperliquid.xyz/info";
469pub const HYPERLIQUID_TESTNET_INFO_URL: &str = "https://api.hyperliquid-testnet.xyz/info";
471
472const BPS_DENOMINATOR: u32 = 10_000;
473const SERVER_CLOCK_TTL: Duration = Duration::from_secs(60);
474const SCALE_WORKING_SCALE: u32 = 12;
475const MAX_BATCH_CLOID_INDEX: usize = 255;
476const HYPERCALL_API_DOMAIN: &str = "HypercallApiSign";
477const HYPERCALL_MANAGER_DOMAIN: &str = "HypercallManagerSign";
478
479sol! {
480 #[derive(Debug, PartialEq, Eq)]
484 struct PerpOrderTerms {
485 uint32 asset;
486 bool isBuy;
487 uint64 limitPx;
488 uint64 sz;
489 bool reduceOnly;
490 uint8 encodedTif;
491 uint64 triggerPx;
492 bool isMarket;
493 uint8 tpsl;
494 uint128 cloid;
495 }
496
497 #[derive(Debug, PartialEq, Eq)]
498 struct HCPerpTriggerOrder {
499 address account;
500 uint64 nonce;
501 PerpOrderTerms order;
502 }
503
504 #[derive(Debug, PartialEq, Eq)]
505 struct HCPerpOrderBatch {
506 address account;
507 uint64 nonce;
508 uint8 grouping;
509 PerpOrderTerms[] orders;
510 }
511
512 #[derive(Debug, PartialEq, Eq)]
513 struct PerpLeverageChange {
514 uint32 asset;
515 bool isCross;
516 uint32 leverage;
517 }
518
519 #[derive(Debug, PartialEq, Eq)]
520 struct HCPerpLeverageChange {
521 address account;
522 uint64 nonce;
523 PerpLeverageChange action;
524 }
525
526 #[derive(Debug, PartialEq, Eq)]
530 struct PerpModifyTerms {
531 uint32 asset;
532 uint128 targetDirectiveId;
533 bool isBuy;
534 uint64 limitPx;
535 uint64 sz;
536 bool reduceOnly;
537 uint8 encodedTif;
538 uint128 cloid;
539 }
540
541 #[derive(Debug, PartialEq, Eq)]
542 struct HCPerpOrderModify {
543 address account;
544 uint64 nonce;
545 PerpModifyTerms action;
546 }
547
548 #[derive(Debug, PartialEq, Eq)]
550 struct HCPerpOrderBatchModify {
551 address account;
552 uint64 nonce;
553 PerpModifyTerms[] modifies;
554 }
555
556 #[derive(Debug, PartialEq, Eq)]
557 struct PerpTwapTerms {
558 uint32 asset;
559 bool isBuy;
560 uint64 sz;
561 bool reduceOnly;
562 uint32 minutes;
563 bool randomize;
564 }
565
566 #[derive(Debug, PartialEq, Eq)]
567 struct HCPerpTwapOrder {
568 address account;
569 uint64 nonce;
570 PerpTwapTerms action;
571 }
572
573 #[derive(Debug, PartialEq, Eq)]
574 struct PerpTwapCancelTerms {
575 uint32 asset;
576 uint64 twapId;
577 }
578
579 #[derive(Debug, PartialEq, Eq)]
580 struct HCPerpTwapCancel {
581 address account;
582 uint64 nonce;
583 PerpTwapCancelTerms action;
584 }
585
586 #[derive(Debug, PartialEq, Eq)]
587 struct AddApiWallet {
588 address apiWalletAddress;
589 string apiWalletName;
590 }
591
592 #[derive(Debug, PartialEq, Eq)]
593 struct HLAddApiWallet {
594 address account;
595 uint64 nonce;
596 AddApiWallet action;
597 }
598
599 #[sol(rpc)]
600 interface HypercallAccountBuilderApproval {
601 function approveZeroFeeBuilder(address builder) external;
602 }
603}
604
605#[derive(Debug, Clone, Copy)]
611pub struct TeePerpTriggerOrderSignature {
612 pub account: AccountAddress,
613 pub nonce: u64,
614 pub order: TeePerpOrderWire,
615}
616
617#[derive(Debug, Clone, Copy)]
619pub struct TeePerpOrderBatchSignature<'a> {
620 pub account: AccountAddress,
621 pub nonce: u64,
622 pub batch: &'a TeePerpOrderBatchAction,
623}
624
625#[derive(Debug, Clone, Copy)]
627pub struct TeePerpLeverageSignature {
628 pub account: AccountAddress,
629 pub nonce: u64,
630 pub action: TeePerpLeverageAction,
631}
632
633#[derive(Debug, Clone, Copy)]
635pub struct TeePerpModifySignature {
636 pub account: AccountAddress,
637 pub nonce: u64,
638 pub action: TeePerpModifyAction,
639}
640
641#[derive(Debug, Clone, Copy)]
644pub struct TeePerpBatchModifySignature<'a> {
645 pub account: AccountAddress,
646 pub nonce: u64,
647 pub batch: &'a TeePerpBatchModifyAction,
648}
649
650#[derive(Debug, Clone, Copy)]
652pub struct TeePerpTwapSignature {
653 pub account: AccountAddress,
654 pub nonce: u64,
655 pub action: TeePerpTwapAction,
656}
657
658#[derive(Debug, Clone, Copy)]
660pub struct TeePerpTwapCancelSignature {
661 pub account: AccountAddress,
662 pub nonce: u64,
663 pub action: TeePerpTwapCancelAction,
664}
665
666#[derive(Debug, Clone, Copy)]
668pub struct TeeApiWalletApprovalSignature<'a> {
669 pub account: AccountAddress,
670 pub nonce: u64,
671 pub api_wallet_address: AccountAddress,
672 pub api_wallet_name: &'a str,
673}
674
675#[expect(
680 async_fn_in_trait,
681 reason = "signers are used generically, never as Send-bound trait objects"
682)]
683pub trait TeePerpSigner: PerpDirectiveSigner {
684 async fn sign_tee_perp_trigger_order_payload(
685 &self,
686 payload: TeePerpTriggerOrderSignature,
687 ) -> Result<String>;
688 async fn sign_tee_perp_order_batch_payload(
689 &self,
690 payload: TeePerpOrderBatchSignature<'_>,
691 ) -> Result<String>;
692 async fn sign_tee_perp_leverage_payload(
693 &self,
694 payload: TeePerpLeverageSignature,
695 ) -> Result<String>;
696 async fn sign_tee_perp_modify_payload(&self, payload: TeePerpModifySignature)
697 -> Result<String>;
698 async fn sign_tee_perp_batch_modify_payload(
699 &self,
700 payload: TeePerpBatchModifySignature<'_>,
701 ) -> Result<String>;
702 async fn sign_tee_perp_twap_payload(&self, payload: TeePerpTwapSignature) -> Result<String>;
703 async fn sign_tee_perp_twap_cancel_payload(
704 &self,
705 payload: TeePerpTwapCancelSignature,
706 ) -> Result<String>;
707}
708
709#[expect(
711 async_fn_in_trait,
712 reason = "signers are used generically, never as Send-bound trait objects"
713)]
714pub trait TeeApiWalletManagerSigner: HypercallSigner {
715 async fn sign_authentication_payload(&self, timestamp: i64) -> Result<String>;
717 async fn sign_tee_api_wallet_approval_payload(
718 &self,
719 payload: TeeApiWalletApprovalSignature<'_>,
720 ) -> Result<String>;
721}
722
723fn perp_order_terms(order: &TeePerpOrderWire) -> PerpOrderTerms {
724 let (encoded_tif, trigger_px, is_market, tpsl) = match order.order_type {
725 TeePerpOrderType::Limit(limit) => (limit.tif.encoded(), 0, false, 0),
726 TeePerpOrderType::Trigger(trigger) => (
727 0,
728 trigger.trigger_px,
729 trigger.is_market,
730 trigger.tpsl.signed(),
731 ),
732 };
733 PerpOrderTerms {
734 asset: order.asset,
735 isBuy: order.is_buy,
736 limitPx: order.limit_px,
737 sz: order.sz,
738 reduceOnly: order.reduce_only,
739 encodedTif: encoded_tif,
740 triggerPx: trigger_px,
741 isMarket: is_market,
742 tpsl,
743 cloid: order.cloid,
744 }
745}
746
747fn trigger_order_message(payload: &TeePerpTriggerOrderSignature) -> Result<HCPerpTriggerOrder> {
748 if !matches!(payload.order.order_type, TeePerpOrderType::Trigger(_)) {
749 return Err(ClientError::InvalidInput(
750 "a TEE trigger submission needs a trigger order".into(),
751 ));
752 }
753 Ok(HCPerpTriggerOrder {
754 account: payload.account.as_wallet_address().inner(),
755 nonce: payload.nonce,
756 order: perp_order_terms(&payload.order),
757 })
758}
759
760fn order_batch_message(payload: &TeePerpOrderBatchSignature<'_>) -> Result<HCPerpOrderBatch> {
761 validate_batch(payload.batch)?;
762 Ok(HCPerpOrderBatch {
763 account: payload.account.as_wallet_address().inner(),
764 nonce: payload.nonce,
765 grouping: payload.batch.grouping.signed(),
766 orders: payload.batch.orders.iter().map(perp_order_terms).collect(),
767 })
768}
769
770fn leverage_message(payload: &TeePerpLeverageSignature) -> HCPerpLeverageChange {
771 HCPerpLeverageChange {
772 account: payload.account.as_wallet_address().inner(),
773 nonce: payload.nonce,
774 action: PerpLeverageChange {
775 asset: payload.action.asset,
776 isCross: payload.action.is_cross,
777 leverage: payload.action.leverage,
778 },
779 }
780}
781
782fn perp_modify_terms(action: &TeePerpModifyAction) -> PerpModifyTerms {
783 PerpModifyTerms {
784 asset: action.asset,
785 targetDirectiveId: action.target_directive_id.as_u128(),
786 isBuy: action.is_buy,
787 limitPx: action.limit_px,
788 sz: action.sz,
789 reduceOnly: action.reduce_only,
790 encodedTif: action.tif.encoded(),
791 cloid: action.cloid,
792 }
793}
794
795fn modify_message(payload: &TeePerpModifySignature) -> Result<HCPerpOrderModify> {
796 validate_modify_action(&payload.action)?;
797 Ok(HCPerpOrderModify {
798 account: payload.account.as_wallet_address().inner(),
799 nonce: payload.nonce,
800 action: perp_modify_terms(&payload.action),
801 })
802}
803
804fn batch_modify_message(
805 payload: &TeePerpBatchModifySignature<'_>,
806) -> Result<HCPerpOrderBatchModify> {
807 validate_batch_modify(payload.batch, MAX_TEE_PERP_BATCH_MODIFY_CHILDREN)?;
810 Ok(HCPerpOrderBatchModify {
811 account: payload.account.as_wallet_address().inner(),
812 nonce: payload.nonce,
813 modifies: payload
814 .batch
815 .modifies
816 .iter()
817 .map(perp_modify_terms)
818 .collect(),
819 })
820}
821
822fn twap_message(payload: &TeePerpTwapSignature) -> Result<HCPerpTwapOrder> {
823 validate_twap_action(&payload.action)?;
824 let action = payload.action;
825 Ok(HCPerpTwapOrder {
826 account: payload.account.as_wallet_address().inner(),
827 nonce: payload.nonce,
828 action: PerpTwapTerms {
829 asset: action.asset,
830 isBuy: action.is_buy,
831 sz: action.sz,
832 reduceOnly: action.reduce_only,
833 minutes: action.minutes,
834 randomize: action.randomize,
835 },
836 })
837}
838
839fn twap_cancel_message(payload: &TeePerpTwapCancelSignature) -> Result<HCPerpTwapCancel> {
840 if payload.action.twap_id == 0 {
841 return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
842 }
843 Ok(HCPerpTwapCancel {
844 account: payload.account.as_wallet_address().inner(),
845 nonce: payload.nonce,
846 action: PerpTwapCancelTerms {
847 asset: payload.action.asset,
848 twapId: payload.action.twap_id,
849 },
850 })
851}
852
853fn approval_message(payload: &TeeApiWalletApprovalSignature<'_>) -> HLAddApiWallet {
854 HLAddApiWallet {
855 account: payload.account.as_wallet_address().inner(),
856 nonce: payload.nonce,
857 action: AddApiWallet {
858 apiWalletAddress: payload.api_wallet_address.as_wallet_address().inner(),
859 apiWalletName: payload.api_wallet_name.to_string(),
860 },
861 }
862}
863
864fn signing_domain(name: &'static str, chain_id: u64) -> Result<Eip712Domain> {
865 if !matches!(chain_id, 998 | 999) {
866 return Err(ClientError::InvalidInput(format!(
867 "unsupported directive chain id: {chain_id}"
868 )));
869 }
870 Ok(Eip712Domain {
871 name: Some(name.into()),
872 version: Some("1".into()),
873 chain_id: Some(U256::from(chain_id)),
874 verifying_contract: Some(Address::ZERO),
875 salt: None,
876 })
877}
878
879pub fn tee_perp_trigger_order_signing_hash(
881 chain_id: u64,
882 payload: &TeePerpTriggerOrderSignature,
883) -> Result<B256> {
884 Ok(trigger_order_message(payload)?
885 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
886}
887
888pub fn tee_perp_order_batch_signing_hash(
890 chain_id: u64,
891 payload: &TeePerpOrderBatchSignature<'_>,
892) -> Result<B256> {
893 Ok(order_batch_message(payload)?
894 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
895}
896
897pub fn tee_perp_leverage_signing_hash(
899 chain_id: u64,
900 payload: &TeePerpLeverageSignature,
901) -> Result<B256> {
902 Ok(leverage_message(payload)
903 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
904}
905
906pub fn tee_perp_modify_signing_hash(
908 chain_id: u64,
909 payload: &TeePerpModifySignature,
910) -> Result<B256> {
911 Ok(modify_message(payload)?
912 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
913}
914
915pub fn tee_perp_batch_modify_signing_hash(
918 chain_id: u64,
919 payload: &TeePerpBatchModifySignature<'_>,
920) -> Result<B256> {
921 Ok(batch_modify_message(payload)?
922 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
923}
924
925pub fn tee_perp_twap_signing_hash(chain_id: u64, payload: &TeePerpTwapSignature) -> Result<B256> {
927 Ok(
928 twap_message(payload)?
929 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?),
930 )
931}
932
933pub fn tee_perp_twap_cancel_signing_hash(
935 chain_id: u64,
936 payload: &TeePerpTwapCancelSignature,
937) -> Result<B256> {
938 Ok(twap_cancel_message(payload)?
939 .eip712_signing_hash(&signing_domain(HYPERCALL_API_DOMAIN, chain_id)?))
940}
941
942pub fn tee_api_wallet_approval_signing_hash(
944 chain_id: u64,
945 payload: &TeeApiWalletApprovalSignature<'_>,
946) -> Result<B256> {
947 Ok(approval_message(payload)
948 .eip712_signing_hash(&signing_domain(HYPERCALL_MANAGER_DOMAIN, chain_id)?))
949}
950
951impl TeePerpSigner for HypercallWallet {
952 async fn sign_tee_perp_trigger_order_payload(
953 &self,
954 payload: TeePerpTriggerOrderSignature,
955 ) -> Result<String> {
956 let message = trigger_order_message(&payload)?;
957 self.sign_directive(&message, "HCPerpTriggerOrder", HYPERCALL_API_DOMAIN)
958 .await
959 }
960
961 async fn sign_tee_perp_order_batch_payload(
962 &self,
963 payload: TeePerpOrderBatchSignature<'_>,
964 ) -> Result<String> {
965 let message = order_batch_message(&payload)?;
966 self.sign_directive(&message, "HCPerpOrderBatch", HYPERCALL_API_DOMAIN)
967 .await
968 }
969
970 async fn sign_tee_perp_leverage_payload(
971 &self,
972 payload: TeePerpLeverageSignature,
973 ) -> Result<String> {
974 let message = leverage_message(&payload);
975 self.sign_directive(&message, "HCPerpLeverageChange", HYPERCALL_API_DOMAIN)
976 .await
977 }
978
979 async fn sign_tee_perp_modify_payload(
980 &self,
981 payload: TeePerpModifySignature,
982 ) -> Result<String> {
983 let message = modify_message(&payload)?;
984 self.sign_directive(&message, "HCPerpOrderModify", HYPERCALL_API_DOMAIN)
985 .await
986 }
987
988 async fn sign_tee_perp_batch_modify_payload(
989 &self,
990 payload: TeePerpBatchModifySignature<'_>,
991 ) -> Result<String> {
992 let message = batch_modify_message(&payload)?;
993 self.sign_directive(&message, "HCPerpOrderBatchModify", HYPERCALL_API_DOMAIN)
994 .await
995 }
996
997 async fn sign_tee_perp_twap_payload(&self, payload: TeePerpTwapSignature) -> Result<String> {
998 let message = twap_message(&payload)?;
999 self.sign_directive(&message, "HCPerpTwapOrder", HYPERCALL_API_DOMAIN)
1000 .await
1001 }
1002
1003 async fn sign_tee_perp_twap_cancel_payload(
1004 &self,
1005 payload: TeePerpTwapCancelSignature,
1006 ) -> Result<String> {
1007 let message = twap_cancel_message(&payload)?;
1008 self.sign_directive(&message, "HCPerpTwapCancel", HYPERCALL_API_DOMAIN)
1009 .await
1010 }
1011}
1012
1013impl TeeApiWalletManagerSigner for HypercallWallet {
1014 async fn sign_authentication_payload(&self, timestamp: i64) -> Result<String> {
1015 self.sign_authentication_message(timestamp).await
1016 }
1017
1018 async fn sign_tee_api_wallet_approval_payload(
1019 &self,
1020 payload: TeeApiWalletApprovalSignature<'_>,
1021 ) -> Result<String> {
1022 let message = approval_message(&payload);
1023 self.sign_directive(&message, "HLAddApiWallet", HYPERCALL_MANAGER_DOMAIN)
1024 .await
1025 }
1026}
1027
1028#[derive(Debug, Clone, Copy)]
1033struct ClockSample {
1034 offset_ms: i64,
1035 measured_at: Instant,
1036}
1037
1038#[derive(Debug, Clone, Default)]
1040pub(crate) struct ServerClock(Arc<StdMutex<Option<ClockSample>>>);
1041
1042impl ServerClock {
1043 fn cached_offset(&self) -> Option<i64> {
1044 let sample = *self.0.lock().expect("server clock cache poisoned");
1045 sample
1046 .filter(|sample| sample.measured_at.elapsed() < SERVER_CLOCK_TTL)
1047 .map(|sample| sample.offset_ms)
1048 }
1049
1050 fn store(&self, offset_ms: i64) {
1051 *self.0.lock().expect("server clock cache poisoned") = Some(ClockSample {
1052 offset_ms,
1053 measured_at: Instant::now(),
1054 });
1055 }
1056}
1057
1058fn local_now_ms() -> i64 {
1059 let elapsed = SystemTime::now()
1060 .duration_since(UNIX_EPOCH)
1061 .expect("system clock is before the Unix epoch");
1062 i64::try_from(elapsed.as_millis()).expect("Unix milliseconds fit in i64")
1063}
1064
1065pub(crate) fn server_clock_offset_ms(
1069 date_header: &str,
1070 sent_ms: i64,
1071 received_ms: i64,
1072) -> Option<i64> {
1073 let server_ms = parse_http_date_ms(date_header)?;
1074 if received_ms < sent_ms {
1075 return None;
1076 }
1077 Some(server_ms + 500 - (sent_ms + received_ms) / 2)
1078}
1079
1080pub(crate) fn parse_http_date_ms(value: &str) -> Option<i64> {
1082 let mut parts = value.trim().split_ascii_whitespace();
1083 let _weekday = parts.next()?;
1084 let day: i64 = parts.next()?.parse().ok()?;
1085 let month = match parts.next()? {
1086 "Jan" => 1,
1087 "Feb" => 2,
1088 "Mar" => 3,
1089 "Apr" => 4,
1090 "May" => 5,
1091 "Jun" => 6,
1092 "Jul" => 7,
1093 "Aug" => 8,
1094 "Sep" => 9,
1095 "Oct" => 10,
1096 "Nov" => 11,
1097 "Dec" => 12,
1098 _ => return None,
1099 };
1100 let year: i64 = parts.next()?.parse().ok()?;
1101 let mut time = parts.next()?.split(':');
1102 let hour: i64 = time.next()?.parse().ok()?;
1103 let minute: i64 = time.next()?.parse().ok()?;
1104 let second: i64 = time.next()?.parse().ok()?;
1105 if parts.next()? != "GMT" || parts.next().is_some() || time.next().is_some() {
1106 return None;
1107 }
1108 if !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
1109 return None;
1110 }
1111 let shifted_year = if month <= 2 { year - 1 } else { year };
1113 let era = shifted_year.div_euclid(400);
1114 let year_of_era = shifted_year - era * 400;
1115 let month_index = (month + 9) % 12;
1116 let day_of_year = (153 * month_index + 2) / 5 + day - 1;
1117 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
1118 let days = era * 146_097 + day_of_era - 719_468;
1119 Some(((days * 24 + hour) * 60 + minute) * 60_000 + second * 1_000)
1120}
1121
1122fn nonce_registry() -> &'static StdMutex<HashMap<Address, u64>> {
1123 static NONCES: OnceLock<StdMutex<HashMap<Address, u64>>> = OnceLock::new();
1124 NONCES.get_or_init(|| StdMutex::new(HashMap::new()))
1125}
1126
1127pub(crate) fn next_nonce_at(signer: Address, server_now_ms: u64) -> u64 {
1130 let mut nonces = nonce_registry().lock().expect("nonce registry poisoned");
1131 let last = nonces.entry(signer).or_insert(0);
1132 *last = (*last).max(server_now_ms) + 1;
1133 *last
1134}
1135
1136pub fn tee_perp_venue_expires_after_ms(nonce: u64) -> Option<u64> {
1139 if nonce == 0 {
1140 return None;
1141 }
1142 nonce.checked_add(TEE_PERP_VENUE_TTL_MS)
1143}
1144
1145pub fn tee_perp_nonce_in_window(nonce: u64, server_now_ms: u64) -> bool {
1147 tee_perp_venue_expires_after_ms(nonce).is_some_and(|expires| {
1148 expires > server_now_ms
1149 && expires
1150 <= server_now_ms.saturating_add(
1151 hypercall_sdk_types::tee_perp::TEE_PERP_MAX_VENUE_EXPIRY_WINDOW_MS,
1152 )
1153 })
1154}
1155
1156fn decimal_units(value: Decimal) -> Result<(u128, u32)> {
1161 if value <= Decimal::ZERO {
1162 return Err(ClientError::InvalidInput(format!(
1163 "{value} must be positive"
1164 )));
1165 }
1166 let normalized = value.normalize();
1167 let mantissa = u128::try_from(normalized.mantissa())
1168 .map_err(|_| ClientError::InvalidInput(format!("{value} must be positive")))?;
1169 Ok((mantissa, normalized.scale()))
1170}
1171
1172fn units_to_decimal(units: u128, scale: u32) -> Result<Decimal> {
1173 let units = i128::try_from(units)
1174 .map_err(|_| ClientError::InvalidInput("price out of range".into()))?;
1175 Decimal::try_from_i128_with_scale(units, scale)
1176 .map(|value| value.normalize())
1177 .map_err(|error| ClientError::InvalidInput(format!("price out of range: {error}")))
1178}
1179
1180fn pow10(exponent: u32) -> Result<u128> {
1181 10_u128
1182 .checked_pow(exponent)
1183 .ok_or(ClientError::ArithmeticOverflow {
1184 operation: "perp price scaling",
1185 })
1186}
1187
1188fn validate_size_decimals(size_decimals: u32) -> Result<u32> {
1189 if size_decimals > HYPERLIQUID_PERP_MAX_PRICE_DECIMALS {
1190 return Err(ClientError::InvalidInput(format!(
1191 "size decimals {size_decimals} exceed {HYPERLIQUID_PERP_MAX_PRICE_DECIMALS}"
1192 )));
1193 }
1194 Ok(size_decimals)
1195}
1196
1197pub fn perp_market_limit_price(
1205 reference: Decimal,
1206 side: Side,
1207 size_decimals: u32,
1208 slippage_bps: u32,
1209) -> Result<Decimal> {
1210 let size_decimals = validate_size_decimals(size_decimals)?;
1211 if slippage_bps >= BPS_DENOMINATOR {
1212 return Err(ClientError::InvalidInput(format!(
1213 "slippage {slippage_bps} bps must be below {BPS_DENOMINATOR}"
1214 )));
1215 }
1216 let (units, scale) = decimal_units(reference)?;
1217 let factor = match side {
1218 Side::Buy => BPS_DENOMINATOR + slippage_bps,
1219 Side::Sell => BPS_DENOMINATOR - slippage_bps,
1220 };
1221 let overflow = ClientError::ArithmeticOverflow {
1222 operation: "perp market price",
1223 };
1224 let numerator = units.checked_mul(u128::from(factor)).ok_or(overflow)?;
1225 let denominator = pow10(scale)?
1226 .checked_mul(u128::from(BPS_DENOMINATOR))
1227 .ok_or(ClientError::ArithmeticOverflow {
1228 operation: "perp market price",
1229 })?;
1230 let exponent: i64 = if numerator >= denominator {
1231 i64::try_from((numerator / denominator).to_string().len()).unwrap_or(i64::MAX) - 1
1232 } else {
1233 let mut scaled = numerator;
1234 let mut places = 0_i64;
1235 while scaled < denominator {
1236 scaled = scaled
1237 .checked_mul(10)
1238 .ok_or(ClientError::ArithmeticOverflow {
1239 operation: "perp market price",
1240 })?;
1241 places += 1;
1242 }
1243 -places
1244 };
1245 let max_decimals = i64::from(HYPERLIQUID_PERP_MAX_PRICE_DECIMALS - size_decimals);
1246 let sig_fig_exponent = exponent - i64::from(HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES) + 1;
1247 let tick_exponent = sig_fig_exponent.min(0).max(-max_decimals);
1248 let tick_scale = u32::try_from(-tick_exponent).expect("tick scale is non-negative");
1249 let scaled_numerator =
1250 numerator
1251 .checked_mul(pow10(tick_scale)?)
1252 .ok_or(ClientError::ArithmeticOverflow {
1253 operation: "perp market price",
1254 })?;
1255 let quotient = scaled_numerator / denominator;
1256 let ticks = if matches!(side, Side::Buy) || scaled_numerator.is_multiple_of(denominator) {
1257 quotient
1258 } else {
1259 quotient + 1
1260 };
1261 let price = units_to_decimal(ticks, tick_scale)?;
1262 let crosses = match side {
1263 Side::Buy => price >= reference,
1264 Side::Sell => price <= reference,
1265 };
1266 if !crosses || price <= Decimal::ZERO {
1267 return Err(ClientError::InvalidInput(format!(
1268 "no marketable tick within {slippage_bps} bps of {reference}; use a limit order"
1269 )));
1270 }
1271 Ok(price)
1272}
1273
1274fn round_working_price_to_tick(units: u128, side: Side, size_decimals: u32) -> Result<Decimal> {
1275 let magnitude = i64::try_from(units.to_string().len()).unwrap_or(i64::MAX)
1276 - 1
1277 - i64::from(SCALE_WORKING_SCALE);
1278 let sig_fig_decimals =
1279 (i64::from(HYPERLIQUID_PERP_MAX_PRICE_SIGNIFICANT_FIGURES) - 1 - magnitude).max(0);
1280 let decimals = sig_fig_decimals
1281 .min(i64::from(
1282 HYPERLIQUID_PERP_MAX_PRICE_DECIMALS - size_decimals,
1283 ))
1284 .max(0);
1285 let decimals = u32::try_from(decimals).expect("decimals are non-negative");
1286 let divisor = pow10(SCALE_WORKING_SCALE - decimals)?;
1287 let quotient = units / divisor;
1288 let ticks = if matches!(side, Side::Sell) && !units.is_multiple_of(divisor) {
1289 quotient + 1
1290 } else {
1291 quotient
1292 };
1293 units_to_decimal(ticks, decimals)
1294}
1295
1296fn to_working_units(value: Decimal, scale: u32, field: &str) -> Result<u128> {
1297 let (units, value_scale) = decimal_units(value)
1298 .map_err(|_| ClientError::InvalidInput(format!("{field} must be positive")))?;
1299 if value_scale > scale {
1300 Ok(units / pow10(value_scale - scale)?)
1301 } else {
1302 units
1303 .checked_mul(pow10(scale - value_scale)?)
1304 .ok_or(ClientError::ArithmeticOverflow {
1305 operation: "perp scale order",
1306 })
1307 }
1308}
1309
1310fn to_working_price_units(value: Decimal, field: &str) -> Result<u128> {
1314 let (units, value_scale) = decimal_units(value)
1315 .map_err(|_| ClientError::InvalidInput(format!("{field} must be positive")))?;
1316 if value_scale > SCALE_WORKING_SCALE
1317 && !units.is_multiple_of(pow10(value_scale - SCALE_WORKING_SCALE)?)
1318 {
1319 return Err(ClientError::InvalidInput(format!(
1320 "{field} supports at most {SCALE_WORKING_SCALE} decimal places"
1321 )));
1322 }
1323 to_working_units(value, SCALE_WORKING_SCALE, field)
1324}
1325
1326pub fn round_perp_price_to_tick(price: Decimal, side: Side, size_decimals: u32) -> Result<Decimal> {
1329 let size_decimals = validate_size_decimals(size_decimals)?;
1330 let units = to_working_price_units(price, "price")?;
1331 round_working_price_to_tick(units, side, size_decimals)
1332}
1333
1334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1336pub struct PerpScaleLeg {
1337 pub price: Decimal,
1338 pub size: Decimal,
1339}
1340
1341#[derive(Debug, Clone, Copy)]
1343pub struct PerpScaleOrderSpec {
1344 pub start_price: Decimal,
1345 pub end_price: Decimal,
1346 pub total_size: Decimal,
1347 pub order_count: usize,
1349 pub size_skew: Decimal,
1351 pub side: Side,
1352 pub size_decimals: u32,
1354}
1355
1356pub fn build_perp_scale_order_legs(spec: PerpScaleOrderSpec) -> Result<Vec<PerpScaleLeg>> {
1362 let lot_decimals = validate_size_decimals(spec.size_decimals)?;
1363 if !(PERP_SCALE_MIN_ORDERS..=PERP_SCALE_MAX_ORDERS).contains(&spec.order_count) {
1364 return Err(ClientError::InvalidInput(format!(
1365 "scale orders need {PERP_SCALE_MIN_ORDERS} to {PERP_SCALE_MAX_ORDERS} legs"
1366 )));
1367 }
1368 let one = pow10(SCALE_WORKING_SCALE)?;
1369 let start = to_working_price_units(spec.start_price, "start price")?;
1370 let end = to_working_price_units(spec.end_price, "end price")?;
1371 let skew = to_working_units(spec.size_skew, SCALE_WORKING_SCALE, "size skew")?;
1372 if skew == 0 || skew > 100 * one {
1373 return Err(ClientError::InvalidInput(
1374 "size skew must be positive and at most 100".into(),
1375 ));
1376 }
1377 if start == 0 || end == 0 || start == end {
1378 return Err(ClientError::InvalidInput(
1379 "scale start and end prices must be positive and distinct".into(),
1380 ));
1381 }
1382 let (size_units, size_scale) = decimal_units(spec.total_size)?;
1383 if size_scale > lot_decimals {
1384 return Err(ClientError::InvalidInput(format!(
1385 "total size {} has more than {lot_decimals} decimals",
1386 spec.total_size
1387 )));
1388 }
1389 let size_lots = size_units * pow10(lot_decimals - size_scale)?;
1390 let count = spec.order_count as u128;
1391 if size_lots < count {
1392 return Err(ClientError::InvalidInput(
1393 "total size is too small for this many legs".into(),
1394 ));
1395 }
1396
1397 let overflow = || ClientError::ArithmeticOverflow {
1398 operation: "perp scale order",
1399 };
1400 let steps = count - 1;
1401 let weights: Vec<i128> = (0..count)
1402 .map(|index| {
1403 let base = i128::try_from(steps * one).map_err(|_| overflow())?;
1404 let delta = (i128::try_from(skew).map_err(|_| overflow())?
1405 - i128::try_from(one).map_err(|_| overflow())?)
1406 * i128::try_from(index).map_err(|_| overflow())?;
1407 Ok(base + delta)
1408 })
1409 .collect::<Result<_>>()?;
1410 let total_weight: i128 = weights.iter().sum();
1411 let size_lots_signed = i128::try_from(size_lots).map_err(|_| overflow())?;
1412 let mut sizes: Vec<i128> = weights
1413 .iter()
1414 .map(|weight| {
1415 size_lots_signed
1416 .checked_mul(*weight)
1417 .map(|product| product / total_weight)
1418 .ok_or_else(overflow)
1419 })
1420 .collect::<Result<_>>()?;
1421 let mut remainder = size_lots_signed - sizes.iter().sum::<i128>();
1422 let mut index = sizes.len() - 1;
1423 while remainder > 0 {
1424 sizes[index] += 1;
1425 remainder -= 1;
1426 index = (index + sizes.len() - 1) % sizes.len();
1427 }
1428 if sizes.iter().any(|size| *size <= 0) {
1429 return Err(ClientError::InvalidInput(
1430 "total size is too small for this size skew".into(),
1431 ));
1432 }
1433
1434 let start_signed = i128::try_from(start).map_err(|_| overflow())?;
1435 let end_signed = i128::try_from(end).map_err(|_| overflow())?;
1436 let steps_signed = i128::try_from(steps).map_err(|_| overflow())?;
1437 sizes
1438 .into_iter()
1439 .enumerate()
1440 .map(|(index, lots)| {
1441 let index = i128::try_from(index).map_err(|_| overflow())?;
1442 let price_units = start_signed + (end_signed - start_signed) * index / steps_signed;
1443 let price_units = u128::try_from(price_units).map_err(|_| overflow())?;
1444 let price = round_working_price_to_tick(price_units, spec.side, lot_decimals)?;
1445 let size =
1446 units_to_decimal(u128::try_from(lots).map_err(|_| overflow())?, lot_decimals)?;
1447 if price <= Decimal::ZERO {
1448 return Err(ClientError::InvalidInput(
1449 "scale price range rounds to zero".into(),
1450 ));
1451 }
1452 Ok(PerpScaleLeg { price, size })
1453 })
1454 .collect()
1455}
1456
1457pub fn tee_perp_batch_cloid(nonce: u64, index: usize) -> Result<u128> {
1461 if nonce == 0 {
1462 return Err(ClientError::InvalidInput("nonce must be nonzero".into()));
1463 }
1464 if index >= MAX_BATCH_CLOID_INDEX {
1465 return Err(ClientError::InvalidInput(format!(
1466 "batch child index {index} exceeds {}",
1467 MAX_BATCH_CLOID_INDEX - 1
1468 )));
1469 }
1470 Ok((u128::from(nonce) << 8) + index as u128 + 1)
1471}
1472
1473fn nonzero_cloid(cloid: u128) -> Result<u128> {
1474 if cloid == 0 {
1475 return Err(ClientError::InvalidInput("cloid must not be zero".into()));
1476 }
1477 Ok(cloid)
1478}
1479
1480pub fn tee_perp_limit_order_wire(
1482 asset: u32,
1483 side: Side,
1484 price: Decimal,
1485 size: Decimal,
1486 tif: PerpTimeInForce,
1487 reduce_only: bool,
1488 cloid: u128,
1489) -> Result<TeePerpOrderWire> {
1490 Ok(TeePerpOrderWire {
1491 asset,
1492 is_buy: matches!(side, Side::Buy),
1493 limit_px: to_perp_units(price, "limit price")?,
1494 sz: to_perp_units(size, "size")?,
1495 reduce_only,
1496 order_type: TeePerpOrderType::Limit(TeePerpLimitOrderType { tif }),
1497 cloid: nonzero_cloid(cloid)?,
1498 })
1499}
1500
1501#[expect(
1505 clippy::too_many_arguments,
1506 reason = "each argument is one independent order term, as in the HL order wire"
1507)]
1508pub fn tee_perp_trigger_order_wire(
1509 asset: u32,
1510 side: Side,
1511 trigger_price: Decimal,
1512 limit_price: Decimal,
1513 size: Decimal,
1514 is_market: bool,
1515 tpsl: TeePerpTpsl,
1516 reduce_only: bool,
1517 cloid: u128,
1518) -> Result<TeePerpOrderWire> {
1519 Ok(TeePerpOrderWire {
1520 asset,
1521 is_buy: matches!(side, Side::Buy),
1522 limit_px: to_perp_units(limit_price, "limit price")?,
1523 sz: to_perp_units(size, "size")?,
1524 reduce_only,
1525 order_type: TeePerpOrderType::Trigger(TeePerpTriggerOrderType {
1526 trigger_px: to_perp_units(trigger_price, "trigger price")?,
1527 is_market,
1528 tpsl,
1529 }),
1530 cloid: nonzero_cloid(cloid)?,
1531 })
1532}
1533
1534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1536pub struct TeePerpExit {
1537 pub trigger_price: Decimal,
1538 pub limit_price: Decimal,
1540}
1541
1542impl TeePerpExit {
1543 pub fn market(
1546 trigger_price: Decimal,
1547 exit_side: Side,
1548 size_decimals: u32,
1549 slippage_bps: u32,
1550 ) -> Result<Self> {
1551 Ok(Self {
1552 trigger_price,
1553 limit_price: perp_market_limit_price(
1554 trigger_price,
1555 exit_side,
1556 size_decimals,
1557 slippage_bps,
1558 )?,
1559 })
1560 }
1561}
1562
1563fn opposite(side: Side) -> Side {
1564 match side {
1565 Side::Buy => Side::Sell,
1566 Side::Sell => Side::Buy,
1567 }
1568}
1569
1570fn exit_children(
1571 orders: &mut Vec<TeePerpOrderWire>,
1572 asset: u32,
1573 exit_side: Side,
1574 size: Decimal,
1575 take_profit: Option<TeePerpExit>,
1576 stop_loss: Option<TeePerpExit>,
1577 nonce: u64,
1578) -> Result<()> {
1579 if take_profit.is_none() && stop_loss.is_none() {
1580 return Err(ClientError::InvalidInput(
1581 "a TP/SL needs a take-profit or stop-loss price".into(),
1582 ));
1583 }
1584 for (tpsl, exit) in [(TeePerpTpsl::Tp, take_profit), (TeePerpTpsl::Sl, stop_loss)] {
1585 let Some(exit) = exit else { continue };
1586 let cloid = tee_perp_batch_cloid(nonce, orders.len())?;
1587 orders.push(tee_perp_trigger_order_wire(
1588 asset,
1589 exit_side,
1590 exit.trigger_price,
1591 exit.limit_price,
1592 size,
1593 true,
1594 tpsl,
1595 true,
1596 cloid,
1597 )?);
1598 }
1599 Ok(())
1600}
1601
1602#[derive(Debug, Clone, Copy)]
1604pub struct TeePerpBracketEntry {
1605 pub asset: u32,
1606 pub side: Side,
1607 pub price: Decimal,
1608 pub size: Decimal,
1609 pub tif: PerpTimeInForce,
1610 pub reduce_only: bool,
1611}
1612
1613pub fn build_tee_perp_bracket_batch(
1617 entry: TeePerpBracketEntry,
1618 take_profit: Option<TeePerpExit>,
1619 stop_loss: Option<TeePerpExit>,
1620 nonce: u64,
1621) -> Result<TeePerpOrderBatchAction> {
1622 let mut orders = vec![tee_perp_limit_order_wire(
1623 entry.asset,
1624 entry.side,
1625 entry.price,
1626 entry.size,
1627 entry.tif,
1628 entry.reduce_only,
1629 tee_perp_batch_cloid(nonce, 0)?,
1630 )?];
1631 exit_children(
1632 &mut orders,
1633 entry.asset,
1634 opposite(entry.side),
1635 entry.size,
1636 take_profit,
1637 stop_loss,
1638 nonce,
1639 )?;
1640 Ok(TeePerpOrderBatchAction {
1641 orders,
1642 grouping: TeePerpOrderGrouping::NormalTpsl,
1643 })
1644}
1645
1646pub fn build_tee_perp_position_tpsl_batch(
1650 asset: u32,
1651 position_side: Side,
1652 size: Decimal,
1653 take_profit: Option<TeePerpExit>,
1654 stop_loss: Option<TeePerpExit>,
1655 nonce: u64,
1656) -> Result<TeePerpOrderBatchAction> {
1657 let mut orders = Vec::with_capacity(2);
1658 exit_children(
1659 &mut orders,
1660 asset,
1661 opposite(position_side),
1662 size,
1663 take_profit,
1664 stop_loss,
1665 nonce,
1666 )?;
1667 Ok(TeePerpOrderBatchAction {
1668 orders,
1669 grouping: TeePerpOrderGrouping::PositionTpsl,
1670 })
1671}
1672
1673pub fn build_tee_perp_scale_batch(
1675 asset: u32,
1676 side: Side,
1677 legs: &[PerpScaleLeg],
1678 tif: PerpTimeInForce,
1679 reduce_only: bool,
1680 nonce: u64,
1681) -> Result<TeePerpOrderBatchAction> {
1682 let orders = legs
1683 .iter()
1684 .enumerate()
1685 .map(|(index, leg)| {
1686 tee_perp_limit_order_wire(
1687 asset,
1688 side,
1689 leg.price,
1690 leg.size,
1691 tif,
1692 reduce_only,
1693 tee_perp_batch_cloid(nonce, index)?,
1694 )
1695 })
1696 .collect::<Result<Vec<_>>>()?;
1697 let batch = TeePerpOrderBatchAction {
1698 orders,
1699 grouping: TeePerpOrderGrouping::Na,
1700 };
1701 validate_batch(&batch)?;
1702 Ok(batch)
1703}
1704
1705fn validate_batch(batch: &TeePerpOrderBatchAction) -> Result<()> {
1706 if batch.orders.is_empty() || batch.orders.len() > MAX_TEE_PERP_ORDER_BATCH_CHILDREN {
1707 return Err(ClientError::InvalidInput(format!(
1708 "an order batch needs 1 to {MAX_TEE_PERP_ORDER_BATCH_CHILDREN} orders"
1709 )));
1710 }
1711 let mut cloids = std::collections::BTreeSet::new();
1712 for order in &batch.orders {
1713 nonzero_cloid(order.cloid)?;
1714 if !cloids.insert(order.cloid) {
1715 return Err(ClientError::InvalidInput(
1716 "every order in a batch must use a distinct cloid".into(),
1717 ));
1718 }
1719 }
1720 Ok(())
1721}
1722
1723#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1735pub struct TeePerpOrderReplacement {
1736 pub asset: u32,
1737 pub target_directive_id: uuid::Uuid,
1738 pub cloid: u128,
1739 pub side: Side,
1740 pub price: Decimal,
1742 pub size: Decimal,
1744 pub tif: PerpTimeInForce,
1745 pub reduce_only: bool,
1746}
1747
1748impl TeePerpOrderReplacement {
1749 pub fn to_action(&self) -> Result<TeePerpModifyAction> {
1752 let action = TeePerpModifyAction {
1753 asset: self.asset,
1754 target_directive_id: self.target_directive_id,
1755 is_buy: matches!(self.side, Side::Buy),
1756 limit_px: to_perp_units(self.price, "limit price")?,
1757 sz: to_perp_units(self.size, "size")?,
1758 reduce_only: self.reduce_only,
1759 tif: self.tif,
1760 cloid: self.cloid,
1761 };
1762 validate_modify_action(&action)?;
1763 Ok(action)
1764 }
1765}
1766
1767fn validate_modify_action(action: &TeePerpModifyAction) -> Result<()> {
1770 if action.target_directive_id.is_nil() {
1771 return Err(ClientError::InvalidInput(
1772 "target_directive_id must not be nil".into(),
1773 ));
1774 }
1775 nonzero_cloid(action.cloid)?;
1776 if action.limit_px == 0 || action.sz == 0 {
1777 return Err(ClientError::InvalidInput(
1778 "a modify needs a positive limit price and size".into(),
1779 ));
1780 }
1781 Ok(())
1782}
1783
1784fn validate_batch_modify(batch: &TeePerpBatchModifyAction, max_children: usize) -> Result<()> {
1788 let cap = max_children.min(MAX_TEE_PERP_BATCH_MODIFY_CHILDREN);
1789 if batch.modifies.is_empty() || batch.modifies.len() > cap {
1790 return Err(ClientError::InvalidInput(format!(
1791 "a batch modify needs 1 to {cap} orders, got {}",
1792 batch.modifies.len()
1793 )));
1794 }
1795 let mut targets = std::collections::BTreeSet::new();
1796 let mut cloids = std::collections::BTreeSet::new();
1797 for action in &batch.modifies {
1798 validate_modify_action(action)?;
1799 if !targets.insert(action.target_directive_id) {
1800 return Err(ClientError::InvalidInput(format!(
1801 "batch modify targets order {} twice",
1802 action.target_directive_id
1803 )));
1804 }
1805 if !cloids.insert(action.cloid) {
1806 return Err(ClientError::InvalidInput(
1807 "every order in a batch modify must use a distinct cloid".into(),
1808 ));
1809 }
1810 }
1811 Ok(())
1812}
1813
1814pub fn build_tee_perp_batch_modify(
1819 replacements: &[TeePerpOrderReplacement],
1820 max_children: Option<usize>,
1821) -> Result<TeePerpBatchModifyAction> {
1822 let max_children = max_children.unwrap_or(DEFAULT_TEE_PERP_BATCH_MODIFY_MAX_CHILDREN);
1823 if max_children == 0 || max_children > MAX_TEE_PERP_BATCH_MODIFY_CHILDREN {
1824 return Err(ClientError::InvalidInput(format!(
1825 "max_children must be 1 to {MAX_TEE_PERP_BATCH_MODIFY_CHILDREN}"
1826 )));
1827 }
1828 let batch = TeePerpBatchModifyAction {
1829 modifies: replacements
1830 .iter()
1831 .map(TeePerpOrderReplacement::to_action)
1832 .collect::<Result<_>>()?,
1833 };
1834 validate_batch_modify(&batch, max_children)?;
1835 Ok(batch)
1836}
1837
1838fn validate_twap_action(action: &TeePerpTwapAction) -> Result<()> {
1839 if !(TEE_PERP_TWAP_MIN_MINUTES..=TEE_PERP_TWAP_MAX_MINUTES).contains(&action.minutes) {
1840 return Err(ClientError::InvalidInput(format!(
1841 "TWAP minutes must be {TEE_PERP_TWAP_MIN_MINUTES} to {TEE_PERP_TWAP_MAX_MINUTES}, got {}",
1842 action.minutes
1843 )));
1844 }
1845 if action.sz == 0 {
1846 return Err(ClientError::InvalidInput(
1847 "TWAP size must be positive".into(),
1848 ));
1849 }
1850 Ok(())
1851}
1852
1853trait SignedTeeSubmission: serde::Serialize {
1855 fn nonce(&self) -> u64;
1856}
1857
1858impl<A: serde::Serialize> SignedTeeSubmission for DirectiveSubmitRequest<A> {
1859 fn nonce(&self) -> u64 {
1860 self.nonce
1861 }
1862}
1863
1864impl SignedTeeSubmission for TeeApiWalletApprovalSubmitRequest {
1865 fn nonce(&self) -> u64 {
1866 self.nonce
1867 }
1868}
1869
1870fn tee_submission_is_ambiguous(error: &ClientError) -> bool {
1874 matches!(
1875 error,
1876 ClientError::Http(_)
1877 | ClientError::Api {
1878 status: 408 | 500..=599,
1879 ..
1880 }
1881 )
1882}
1883
1884#[path = "tee_perp_preview.rs"]
1885mod preview;
1886pub use preview::{perp_preview_batch_action, perp_preview_order};
1887
1888#[derive(Debug, Clone)]
1895pub struct TeePerpMarketOrderParams {
1896 pub account: AccountAddress,
1897 pub asset: u32,
1898 pub side: Side,
1899 pub size: Decimal,
1900 pub reference_price: Decimal,
1902 pub size_decimals: u32,
1904 pub slippage_bps: Option<u32>,
1906 pub reduce_only: bool,
1907 pub client_order_id: Option<u128>,
1908 pub nonce: Option<u64>,
1909}
1910
1911#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1913pub enum TeePerpTriggerExecution {
1914 Market {
1916 size_decimals: u32,
1917 slippage_bps: Option<u32>,
1919 },
1920 Limit { price: Decimal },
1922}
1923
1924#[derive(Debug, Clone)]
1926pub struct TeePerpTriggerOrderParams {
1927 pub account: AccountAddress,
1928 pub asset: u32,
1929 pub side: Side,
1930 pub size: Decimal,
1931 pub trigger_price: Decimal,
1932 pub tpsl: TeePerpTpsl,
1934 pub execution: TeePerpTriggerExecution,
1935 pub reduce_only: bool,
1936 pub client_order_id: Option<u128>,
1938 pub nonce: Option<u64>,
1939}
1940
1941#[derive(Debug, Clone)]
1943pub struct TeePerpBracketOrderParams {
1944 pub account: AccountAddress,
1945 pub entry: TeePerpBracketEntry,
1946 pub take_profit: Option<TeePerpExit>,
1947 pub stop_loss: Option<TeePerpExit>,
1948 pub nonce: Option<u64>,
1949}
1950
1951#[derive(Debug, Clone)]
1953pub struct TeePerpPositionTpslParams {
1954 pub account: AccountAddress,
1955 pub asset: u32,
1956 pub position_side: Side,
1958 pub size: Decimal,
1959 pub take_profit: Option<TeePerpExit>,
1960 pub stop_loss: Option<TeePerpExit>,
1961 pub nonce: Option<u64>,
1962}
1963
1964#[derive(Debug, Clone)]
1966pub struct TeePerpScaleOrderParams {
1967 pub account: AccountAddress,
1968 pub asset: u32,
1969 pub side: Side,
1970 pub legs: Vec<PerpScaleLeg>,
1972 pub tif: PerpTimeInForce,
1973 pub reduce_only: bool,
1974 pub nonce: Option<u64>,
1975}
1976
1977#[derive(Debug, Clone)]
1981pub struct TeePerpOrderBatchParams {
1982 pub account: AccountAddress,
1983 pub nonce: u64,
1984 pub batch: TeePerpOrderBatchAction,
1985}
1986
1987#[derive(Debug, Clone, Copy)]
1989pub struct TeePerpLeverageParams {
1990 pub account: AccountAddress,
1991 pub asset: u32,
1992 pub is_cross: bool,
1994 pub leverage: u32,
1996 pub nonce: Option<u64>,
1997}
1998
1999#[derive(Debug, Clone, Copy)]
2002pub struct TeePerpModifyParams {
2003 pub account: AccountAddress,
2004 pub replacement: TeePerpOrderReplacement,
2005 pub nonce: Option<u64>,
2006}
2007
2008#[derive(Debug, Clone)]
2011pub struct TeePerpBatchModifyParams {
2012 pub account: AccountAddress,
2013 pub replacements: Vec<TeePerpOrderReplacement>,
2015 pub max_children: Option<usize>,
2019 pub nonce: Option<u64>,
2020}
2021
2022#[derive(Debug, Clone, Copy)]
2024pub struct TeePerpTwapParams {
2025 pub account: AccountAddress,
2026 pub asset: u32,
2027 pub side: Side,
2028 pub size: Decimal,
2030 pub reduce_only: bool,
2031 pub minutes: u32,
2033 pub randomize: bool,
2035 pub nonce: Option<u64>,
2036}
2037
2038#[derive(Debug, Clone, Copy)]
2040pub struct TeePerpTwapCancelParams {
2041 pub account: AccountAddress,
2042 pub asset: u32,
2043 pub twap_id: u64,
2045 pub nonce: Option<u64>,
2046}
2047
2048#[derive(Debug, Clone)]
2050pub struct ApproveHypercallBuilderParams {
2051 pub rpc_url: String,
2053 pub account: AccountAddress,
2055 pub builder: Option<AccountAddress>,
2057}
2058
2059#[derive(Debug, Clone)]
2061pub struct TeeApiWalletApprovalChallenge {
2062 pub account: AccountAddress,
2063 pub manager: AccountAddress,
2064 pub timestamp: i64,
2066 pub authentication_signature: String,
2067 pub package: TeeApiWalletApprovalPackage,
2068}
2069
2070#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2072pub enum TeeApiWalletApprovalProgress {
2073 Pending,
2074 Finalized,
2075 Failed,
2076}
2077
2078pub fn tee_api_wallet_approval_progress(
2080 status: &DirectiveStatusResponse,
2081) -> TeeApiWalletApprovalProgress {
2082 if status.domain_status == DirectiveDomainStatus::Completed
2083 && status.delivery_status == DirectiveDeliveryStatus::Finalized
2084 {
2085 return TeeApiWalletApprovalProgress::Finalized;
2086 }
2087 if matches!(
2088 status.domain_status,
2089 DirectiveDomainStatus::Failed | DirectiveDomainStatus::Rejected
2090 ) || matches!(
2091 status.delivery_status,
2092 DirectiveDeliveryStatus::CoreRejected
2093 | DirectiveDeliveryStatus::Reverted
2094 | DirectiveDeliveryStatus::Expired
2095 | DirectiveDeliveryStatus::DeadLettered
2096 ) {
2097 return TeeApiWalletApprovalProgress::Failed;
2098 }
2099 TeeApiWalletApprovalProgress::Pending
2100}
2101
2102#[derive(Debug, Clone)]
2104pub struct TeeApiWalletEnrollment {
2105 pub api_wallet: AccountAddress,
2107 pub api_wallet_name: String,
2108 pub directive_id: Option<String>,
2110}
2111
2112#[derive(Debug, Clone, Copy)]
2114pub struct TeeApiWalletEnrollmentPolling {
2115 pub interval: Duration,
2116 pub attempts: u32,
2117}
2118
2119impl Default for TeeApiWalletEnrollmentPolling {
2120 fn default() -> Self {
2121 Self {
2122 interval: Duration::from_secs(2),
2123 attempts: 60,
2124 }
2125 }
2126}
2127
2128pub fn resolve_hypercall_builder_address(
2130 exchange_info: &ExchangeInfoResponse,
2131) -> Result<AccountAddress> {
2132 let configured = exchange_info.hl_builder_address.as_deref().ok_or_else(|| {
2133 ClientError::InvalidInput("exchange-info does not publish hl_builder_address".into())
2134 })?;
2135 let builder: AccountAddress = configured
2136 .parse()
2137 .map_err(|source| ClientError::invalid_input("hl_builder_address", source))?;
2138 if builder.as_wallet_address().inner() == Address::ZERO {
2139 return Err(ClientError::InvalidInput(
2140 "exchange-info publishes a zero hl_builder_address".into(),
2141 ));
2142 }
2143 Ok(builder)
2144}
2145
2146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2152pub struct HyperliquidLeverage {
2153 pub is_cross: bool,
2154 pub value: u32,
2155}
2156
2157#[derive(Debug, Deserialize)]
2158struct ActiveAssetData {
2159 user: String,
2160 coin: String,
2161 leverage: ActiveAssetLeverage,
2162}
2163
2164#[derive(Debug, Deserialize)]
2165struct ActiveAssetLeverage {
2166 #[serde(rename = "type")]
2167 kind: String,
2168 value: u32,
2169}
2170
2171#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2173pub struct HyperliquidUserRole {
2174 pub role: String,
2175 #[serde(default)]
2176 pub data: Option<HyperliquidUserRoleData>,
2177}
2178
2179#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
2180pub struct HyperliquidUserRoleData {
2181 #[serde(default)]
2182 pub user: Option<String>,
2183}
2184
2185impl HyperliquidUserRole {
2186 pub fn is_agent_for(&self, account: AccountAddress) -> bool {
2188 self.role == "agent"
2189 && self
2190 .data
2191 .as_ref()
2192 .and_then(|data| data.user.as_deref())
2193 .and_then(|user| user.parse::<AccountAddress>().ok())
2194 == Some(account)
2195 }
2196}
2197
2198#[derive(Debug, Clone)]
2200pub struct HyperliquidInfoClient {
2201 client: reqwest::Client,
2202 url: String,
2203}
2204
2205impl HyperliquidInfoClient {
2206 pub fn new(url: impl Into<String>) -> Self {
2207 Self {
2208 client: reqwest::Client::builder()
2209 .timeout(Duration::from_secs(15))
2210 .build()
2211 .expect("failed to build reqwest client"),
2212 url: url.into(),
2213 }
2214 }
2215
2216 pub fn mainnet() -> Self {
2217 Self::new(HYPERLIQUID_MAINNET_INFO_URL)
2218 }
2219
2220 pub fn testnet() -> Self {
2221 Self::new(HYPERLIQUID_TESTNET_INFO_URL)
2222 }
2223
2224 pub fn for_chain_id(chain_id: u64) -> Result<Self> {
2226 match chain_id {
2227 999 => Ok(Self::mainnet()),
2228 998 => Ok(Self::testnet()),
2229 _ => Err(ClientError::InvalidInput(format!(
2230 "unsupported Hyperliquid chain id: {chain_id}"
2231 ))),
2232 }
2233 }
2234
2235 async fn post<T: serde::de::DeserializeOwned>(
2236 &self,
2237 body: serde_json::Value,
2238 action: &str,
2239 ) -> Result<T> {
2240 HypercallClient::send_reqwest_json(self.client.post(&self.url).json(&body), action).await
2241 }
2242
2243 pub async fn user_role(&self, address: AccountAddress) -> Result<HyperliquidUserRole> {
2245 self.post(
2246 serde_json::json!({"type": "userRole", "user": address.to_string()}),
2247 "read Hyperliquid user role",
2248 )
2249 .await
2250 }
2251
2252 pub async fn is_tee_api_wallet_active(
2255 &self,
2256 account: AccountAddress,
2257 api_wallet: AccountAddress,
2258 ) -> Result<bool> {
2259 Ok(self.user_role(api_wallet).await?.is_agent_for(account))
2260 }
2261
2262 pub async fn active_asset_leverage(
2265 &self,
2266 account: AccountAddress,
2267 coin: &str,
2268 ) -> Result<HyperliquidLeverage> {
2269 let data: ActiveAssetData = self
2270 .post(
2271 serde_json::json!({"type": "activeAssetData", "user": account.to_string(), "coin": coin}),
2272 "read Hyperliquid active asset data",
2273 )
2274 .await?;
2275 let echoed_user = data.user.parse::<AccountAddress>().ok();
2276 if echoed_user != Some(account) || data.coin != coin {
2277 return Err(ClientError::Api {
2278 status: 200,
2279 message: "Hyperliquid returned leverage for a different account or market".into(),
2280 });
2281 }
2282 let is_cross = match data.leverage.kind.as_str() {
2283 "cross" => true,
2284 "isolated" => false,
2285 _ => {
2286 return Err(ClientError::Api {
2287 status: 200,
2288 message: "Hyperliquid returned an invalid leverage setting".into(),
2289 })
2290 }
2291 };
2292 if data.leverage.value < 1 {
2293 return Err(ClientError::Api {
2294 status: 200,
2295 message: "Hyperliquid returned an invalid leverage setting".into(),
2296 });
2297 }
2298 Ok(HyperliquidLeverage {
2299 is_cross,
2300 value: data.leverage.value,
2301 })
2302 }
2303}
2304
2305fn approval_typed_data_mismatch(field: &str) -> ClientError {
2310 ClientError::InvalidInput(format!(
2311 "TEE API wallet approval typed data does not match the package: {field}"
2312 ))
2313}
2314
2315fn validate_approval_typed_data(challenge: &TeeApiWalletApprovalChallenge) -> Result<()> {
2316 let typed = &challenge.package.typed_data;
2317 if typed["primaryType"] != "HLAddApiWallet" {
2318 return Err(approval_typed_data_mismatch("primaryType"));
2319 }
2320 if typed["domain"]["name"] != HYPERCALL_MANAGER_DOMAIN {
2321 return Err(approval_typed_data_mismatch("domain.name"));
2322 }
2323 let message = &typed["message"];
2324 let same_address = |value: &serde_json::Value, expected: WalletAddress| {
2325 value
2326 .as_str()
2327 .and_then(|text| text.parse::<WalletAddress>().ok())
2328 == Some(expected)
2329 };
2330 if !same_address(&message["account"], challenge.account.into_wallet_address()) {
2331 return Err(approval_typed_data_mismatch("message.account"));
2332 }
2333 let nonce = match &message["nonce"] {
2334 serde_json::Value::Number(number) => number.as_u64(),
2335 serde_json::Value::String(text) => text.parse().ok(),
2336 _ => None,
2337 };
2338 if nonce != Some(challenge.package.nonce) {
2339 return Err(approval_typed_data_mismatch("message.nonce"));
2340 }
2341 let action = &message["action"];
2342 if !same_address(
2343 &action["apiWalletAddress"],
2344 challenge.package.api_wallet_address,
2345 ) {
2346 return Err(approval_typed_data_mismatch(
2347 "message.action.apiWalletAddress",
2348 ));
2349 }
2350 if action["apiWalletName"] != challenge.package.api_wallet_name.as_str() {
2351 return Err(approval_typed_data_mismatch("message.action.apiWalletName"));
2352 }
2353 Ok(())
2354}
2355
2356fn onchain_error(
2357 operation: impl Into<String>,
2358 source: impl std::error::Error + Send + Sync + 'static,
2359) -> ClientError {
2360 ClientError::Onchain {
2361 operation: operation.into(),
2362 source: Box::new(source),
2363 }
2364}
2365
2366fn is_missing_function_revert(error: &alloy::contract::Error) -> bool {
2369 match error.as_revert_data() {
2370 Some(data) => data.is_empty(),
2371 None => error
2372 .to_string()
2373 .to_ascii_lowercase()
2374 .contains("execution reverted"),
2375 }
2376}
2377
2378impl HypercallClient {
2379 pub async fn server_now_ms(&self) -> Result<u64> {
2382 let offset = match self.server_clock.cached_offset() {
2383 Some(offset) => offset,
2384 None => {
2385 let sent_ms = local_now_ms();
2386 let response = self.request(Method::GET, "/health").send().await?;
2387 let received_ms = local_now_ms();
2388 let date = response
2389 .headers()
2390 .get(reqwest::header::DATE)
2391 .and_then(|value| value.to_str().ok())
2392 .ok_or_else(|| ClientError::Api {
2393 status: response.status().as_u16(),
2394 message: "/health response carries no Date header to stamp TEE nonces"
2395 .into(),
2396 })?;
2397 let offset =
2398 server_clock_offset_ms(date, sent_ms, received_ms).ok_or_else(|| {
2399 ClientError::Api {
2400 status: response.status().as_u16(),
2401 message: format!("/health Date header is not an HTTP date: {date}"),
2402 }
2403 })?;
2404 self.server_clock.store(offset);
2405 offset
2406 }
2407 };
2408 u64::try_from(local_now_ms() + offset).map_err(|_| ClientError::ArithmeticOverflow {
2409 operation: "server clock",
2410 })
2411 }
2412
2413 pub async fn next_tee_perp_nonce(&self, signer: AccountAddress) -> Result<u64> {
2416 let now = self.server_now_ms().await?;
2417 Ok(next_nonce_at(signer.as_wallet_address().inner(), now))
2418 }
2419
2420 async fn resolve_tee_nonce(&self, signer: AccountAddress, nonce: Option<u64>) -> Result<u64> {
2421 match nonce {
2422 Some(nonce) => Ok(nonce),
2423 None => self.next_tee_perp_nonce(signer).await,
2424 }
2425 }
2426
2427 async fn post_tee<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2428 where
2429 T: serde::de::DeserializeOwned,
2430 B: serde::Serialize + ?Sized,
2431 {
2432 Self::send_json_body(self.request(Method::POST, route), body, action).await
2433 }
2434
2435 async fn post_tee_signed<T, B>(&self, route: &str, body: &B, action: &str) -> Result<T>
2439 where
2440 T: serde::de::DeserializeOwned,
2441 B: SignedTeeSubmission,
2442 {
2443 let request_json = sonic_rs::to_string(body)
2444 .map_err(|source| ClientError::invalid_input("TEE request body", source))?;
2445 self.send_tee_submission(route, request_json, body.nonce(), action, false)
2446 .await
2447 }
2448
2449 async fn send_tee_submission<T>(
2450 &self,
2451 route: &str,
2452 request_json: String,
2453 nonce: u64,
2454 action: &str,
2455 resend: bool,
2456 ) -> Result<T>
2457 where
2458 T: serde::de::DeserializeOwned,
2459 {
2460 let request = self
2461 .request(Method::POST, route)
2462 .header(reqwest::header::CONTENT_TYPE, "application/json")
2463 .body(request_json.clone());
2464 match Self::send_reqwest_json(request, action).await {
2465 Err(error) if resend || tee_submission_is_ambiguous(&error) => {
2469 Err(ClientError::TeeSubmissionAmbiguous {
2470 action: action.to_owned(),
2471 route: route.to_owned(),
2472 nonce,
2473 request_json,
2474 source: Box::new(error),
2475 })
2476 }
2477 result => result,
2478 }
2479 }
2480
2481 pub async fn resend_tee_submission<T>(&self, route: &str, request_json: &str) -> Result<T>
2492 where
2493 T: serde::de::DeserializeOwned,
2494 {
2495 let nonce = serde_json::from_str::<serde_json::Value>(request_json)
2496 .ok()
2497 .and_then(|body| match &body["nonce"] {
2498 serde_json::Value::Number(number) => number.as_u64(),
2499 serde_json::Value::String(text) => text.parse().ok(),
2500 _ => None,
2501 })
2502 .ok_or_else(|| {
2503 ClientError::InvalidInput("request_json carries no signed nonce".into())
2504 })?;
2505 self.send_tee_submission(
2506 route,
2507 request_json.to_owned(),
2508 nonce,
2509 "resend TEE submission",
2510 true,
2511 )
2512 .await
2513 }
2514
2515 pub async fn place_tee_perp_limit_order<S>(
2519 &self,
2520 signer: &S,
2521 params: PerpLimitOrderParams,
2522 ) -> Result<TeePerpOrderResponse>
2523 where
2524 S: PerpDirectiveSigner + ?Sized,
2525 {
2526 let nonce = self
2527 .resolve_tee_nonce(signer.address(), params.nonce)
2528 .await?;
2529 let action = HlLimitOrderAction {
2530 asset: params.asset,
2531 is_buy: matches!(params.side, Side::Buy),
2532 limit_px: to_perp_units(params.price, "perp limit price")?,
2533 sz: to_perp_units(params.size, "perp size")?,
2534 reduce_only: params.reduce_only,
2535 tif: params.tif,
2536 cloid: nonzero_cloid(params.client_order_id.unwrap_or(u128::from(nonce)))?,
2537 };
2538 let signature = signer
2539 .sign_perp_limit_order_payload(PerpLimitOrderSignature {
2540 account: params.account,
2541 nonce,
2542 action,
2543 })
2544 .await?;
2545 let request = DirectiveSubmitRequest {
2546 account: params.account.into_wallet_address(),
2547 nonce,
2548 action,
2549 signature,
2550 };
2551 self.post_tee_signed(
2552 TEE_PERP_ORDER_SUBMIT_ROUTE,
2553 &request,
2554 "submit TEE perp order",
2555 )
2556 .await
2557 }
2558
2559 pub async fn place_tee_perp_market_order<S>(
2561 &self,
2562 signer: &S,
2563 params: TeePerpMarketOrderParams,
2564 ) -> Result<TeePerpOrderResponse>
2565 where
2566 S: PerpDirectiveSigner + ?Sized,
2567 {
2568 let size_decimals = validate_size_decimals(params.size_decimals)?;
2569 if params.size.normalize().scale() > size_decimals {
2570 return Err(ClientError::InvalidInput(format!(
2571 "size {} has more than {size_decimals} decimals",
2572 params.size
2573 )));
2574 }
2575 let price = perp_market_limit_price(
2576 params.reference_price,
2577 params.side,
2578 size_decimals,
2579 params.slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2580 )?;
2581 self.place_tee_perp_limit_order(
2582 signer,
2583 PerpLimitOrderParams {
2584 account: params.account,
2585 asset: params.asset,
2586 side: params.side,
2587 price,
2588 size: params.size,
2589 tif: PerpTimeInForce::Ioc,
2590 reduce_only: params.reduce_only,
2591 client_order_id: params.client_order_id,
2592 nonce: params.nonce,
2593 },
2594 )
2595 .await
2596 }
2597
2598 pub async fn place_tee_perp_trigger_order<S>(
2600 &self,
2601 signer: &S,
2602 params: TeePerpTriggerOrderParams,
2603 ) -> Result<TeePerpOrderBatchResponse>
2604 where
2605 S: TeePerpSigner + ?Sized,
2606 {
2607 let (limit_price, is_market) = match params.execution {
2608 TeePerpTriggerExecution::Market {
2609 size_decimals,
2610 slippage_bps,
2611 } => (
2612 perp_market_limit_price(
2613 params.trigger_price,
2614 params.side,
2615 size_decimals,
2616 slippage_bps.unwrap_or(PERP_MARKET_SLIPPAGE_BPS),
2617 )?,
2618 true,
2619 ),
2620 TeePerpTriggerExecution::Limit { price } => (price, false),
2621 };
2622 let nonce = self
2623 .resolve_tee_nonce(signer.address(), params.nonce)
2624 .await?;
2625 let cloid = match params.client_order_id {
2626 Some(cloid) => cloid,
2627 None => tee_perp_batch_cloid(nonce, 0)?,
2628 };
2629 let order = tee_perp_trigger_order_wire(
2630 params.asset,
2631 params.side,
2632 params.trigger_price,
2633 limit_price,
2634 params.size,
2635 is_market,
2636 params.tpsl,
2637 params.reduce_only,
2638 cloid,
2639 )?;
2640 let signature = signer
2641 .sign_tee_perp_trigger_order_payload(TeePerpTriggerOrderSignature {
2642 account: params.account,
2643 nonce,
2644 order,
2645 })
2646 .await?;
2647 let request = DirectiveSubmitRequest {
2648 account: params.account.into_wallet_address(),
2649 nonce,
2650 action: order,
2651 signature,
2652 };
2653 self.post_tee_signed(
2654 TEE_PERP_TRIGGER_ORDER_SUBMIT_ROUTE,
2655 &request,
2656 "submit TEE perp trigger order",
2657 )
2658 .await
2659 }
2660
2661 pub async fn place_tee_perp_order_batch<S>(
2663 &self,
2664 signer: &S,
2665 params: TeePerpOrderBatchParams,
2666 ) -> Result<TeePerpOrderBatchResponse>
2667 where
2668 S: TeePerpSigner + ?Sized,
2669 {
2670 validate_batch(¶ms.batch)?;
2671 let signature = signer
2672 .sign_tee_perp_order_batch_payload(TeePerpOrderBatchSignature {
2673 account: params.account,
2674 nonce: params.nonce,
2675 batch: ¶ms.batch,
2676 })
2677 .await?;
2678 let request = DirectiveSubmitRequest {
2679 account: params.account.into_wallet_address(),
2680 nonce: params.nonce,
2681 action: params.batch,
2682 signature,
2683 };
2684 self.post_tee_signed(
2685 TEE_PERP_ORDER_BATCH_SUBMIT_ROUTE,
2686 &request,
2687 "submit TEE perp order batch",
2688 )
2689 .await
2690 }
2691
2692 pub async fn place_tee_perp_bracket_order<S>(
2694 &self,
2695 signer: &S,
2696 params: TeePerpBracketOrderParams,
2697 ) -> Result<TeePerpOrderBatchResponse>
2698 where
2699 S: TeePerpSigner + ?Sized,
2700 {
2701 let nonce = self
2702 .resolve_tee_nonce(signer.address(), params.nonce)
2703 .await?;
2704 let batch = build_tee_perp_bracket_batch(
2705 params.entry,
2706 params.take_profit,
2707 params.stop_loss,
2708 nonce,
2709 )?;
2710 self.place_tee_perp_order_batch(
2711 signer,
2712 TeePerpOrderBatchParams {
2713 account: params.account,
2714 nonce,
2715 batch,
2716 },
2717 )
2718 .await
2719 }
2720
2721 pub async fn place_tee_perp_position_tpsl<S>(
2723 &self,
2724 signer: &S,
2725 params: TeePerpPositionTpslParams,
2726 ) -> Result<TeePerpOrderBatchResponse>
2727 where
2728 S: TeePerpSigner + ?Sized,
2729 {
2730 let nonce = self
2731 .resolve_tee_nonce(signer.address(), params.nonce)
2732 .await?;
2733 let batch = build_tee_perp_position_tpsl_batch(
2734 params.asset,
2735 params.position_side,
2736 params.size,
2737 params.take_profit,
2738 params.stop_loss,
2739 nonce,
2740 )?;
2741 self.place_tee_perp_order_batch(
2742 signer,
2743 TeePerpOrderBatchParams {
2744 account: params.account,
2745 nonce,
2746 batch,
2747 },
2748 )
2749 .await
2750 }
2751
2752 pub async fn place_tee_perp_scale_order<S>(
2754 &self,
2755 signer: &S,
2756 params: TeePerpScaleOrderParams,
2757 ) -> Result<TeePerpOrderBatchResponse>
2758 where
2759 S: TeePerpSigner + ?Sized,
2760 {
2761 let nonce = self
2762 .resolve_tee_nonce(signer.address(), params.nonce)
2763 .await?;
2764 let batch = build_tee_perp_scale_batch(
2765 params.asset,
2766 params.side,
2767 ¶ms.legs,
2768 params.tif,
2769 params.reduce_only,
2770 nonce,
2771 )?;
2772 self.place_tee_perp_order_batch(
2773 signer,
2774 TeePerpOrderBatchParams {
2775 account: params.account,
2776 nonce,
2777 batch,
2778 },
2779 )
2780 .await
2781 }
2782
2783 pub async fn cancel_tee_perp_order_by_oid<S>(
2785 &self,
2786 signer: &S,
2787 params: PerpCancelByOidParams,
2788 ) -> Result<TeePerpVenueActionResponse>
2789 where
2790 S: PerpDirectiveSigner + ?Sized,
2791 {
2792 if params.order_id == 0 {
2793 return Err(ClientError::InvalidInput("oid must not be zero".into()));
2794 }
2795 let nonce = self
2796 .resolve_tee_nonce(signer.address(), params.nonce)
2797 .await?;
2798 let action = HlCancelByOidAction {
2799 asset: params.asset,
2800 oid: params.order_id,
2801 };
2802 let signature = signer
2803 .sign_perp_cancel_by_oid_payload(PerpCancelByOidSignature {
2804 account: params.account,
2805 nonce,
2806 action,
2807 })
2808 .await?;
2809 let request = DirectiveSubmitRequest {
2810 account: params.account.into_wallet_address(),
2811 nonce,
2812 action,
2813 signature,
2814 };
2815 self.post_tee_signed(
2816 TEE_PERP_CANCEL_BY_OID_SUBMIT_ROUTE,
2817 &request,
2818 "submit TEE perp cancel by oid",
2819 )
2820 .await
2821 }
2822
2823 pub async fn cancel_tee_perp_order_by_cloid<S>(
2825 &self,
2826 signer: &S,
2827 params: PerpCancelByCloidParams,
2828 ) -> Result<TeePerpCancelResponse>
2829 where
2830 S: PerpDirectiveSigner + ?Sized,
2831 {
2832 let nonce = self
2833 .resolve_tee_nonce(signer.address(), params.nonce)
2834 .await?;
2835 let action = HlCancelByCloidAction {
2836 asset: params.asset,
2837 cloid: nonzero_cloid(params.client_order_id)?,
2838 };
2839 let signature = signer
2840 .sign_perp_cancel_by_cloid_payload(PerpCancelByCloidSignature {
2841 account: params.account,
2842 nonce,
2843 action,
2844 })
2845 .await?;
2846 let request = DirectiveSubmitRequest {
2847 account: params.account.into_wallet_address(),
2848 nonce,
2849 action,
2850 signature,
2851 };
2852 self.post_tee_signed(
2853 TEE_PERP_CANCEL_SUBMIT_ROUTE,
2854 &request,
2855 "submit TEE perp cancel by cloid",
2856 )
2857 .await
2858 }
2859
2860 pub async fn update_tee_perp_leverage<S>(
2863 &self,
2864 signer: &S,
2865 params: TeePerpLeverageParams,
2866 ) -> Result<TeePerpLeverageResponse>
2867 where
2868 S: TeePerpSigner + ?Sized,
2869 {
2870 if params.leverage == 0 {
2871 return Err(ClientError::InvalidInput(
2872 "leverage must be greater than zero".into(),
2873 ));
2874 }
2875 let nonce = self
2876 .resolve_tee_nonce(signer.address(), params.nonce)
2877 .await?;
2878 let action = TeePerpLeverageAction {
2879 asset: params.asset,
2880 is_cross: params.is_cross,
2881 leverage: params.leverage,
2882 };
2883 let signature = signer
2884 .sign_tee_perp_leverage_payload(TeePerpLeverageSignature {
2885 account: params.account,
2886 nonce,
2887 action,
2888 })
2889 .await?;
2890 let request = DirectiveSubmitRequest {
2891 account: params.account.into_wallet_address(),
2892 nonce,
2893 action,
2894 signature,
2895 };
2896 self.post_tee_signed(
2897 TEE_PERP_LEVERAGE_SUBMIT_ROUTE,
2898 &request,
2899 "submit TEE perp leverage",
2900 )
2901 .await
2902 }
2903
2904 pub async fn modify_tee_perp_order<S>(
2912 &self,
2913 signer: &S,
2914 params: TeePerpModifyParams,
2915 ) -> Result<TeePerpModifyResponse>
2916 where
2917 S: TeePerpSigner + ?Sized,
2918 {
2919 let action = params.replacement.to_action()?;
2920 let nonce = self
2921 .resolve_tee_nonce(signer.address(), params.nonce)
2922 .await?;
2923 let signature = signer
2924 .sign_tee_perp_modify_payload(TeePerpModifySignature {
2925 account: params.account,
2926 nonce,
2927 action,
2928 })
2929 .await?;
2930 let request = DirectiveSubmitRequest {
2931 account: params.account.into_wallet_address(),
2932 nonce,
2933 action,
2934 signature,
2935 };
2936 self.post_tee_signed(
2937 TEE_PERP_ORDER_MODIFY_ROUTE,
2938 &request,
2939 "submit TEE perp modify",
2940 )
2941 .await
2942 }
2943
2944 pub async fn batch_modify_tee_perp_orders<S>(
2961 &self,
2962 signer: &S,
2963 params: TeePerpBatchModifyParams,
2964 ) -> Result<TeePerpBatchModifyResponse>
2965 where
2966 S: TeePerpSigner + ?Sized,
2967 {
2968 let batch = build_tee_perp_batch_modify(¶ms.replacements, params.max_children)?;
2969 let nonce = self
2970 .resolve_tee_nonce(signer.address(), params.nonce)
2971 .await?;
2972 let signature = signer
2973 .sign_tee_perp_batch_modify_payload(TeePerpBatchModifySignature {
2974 account: params.account,
2975 nonce,
2976 batch: &batch,
2977 })
2978 .await?;
2979 let request = DirectiveSubmitRequest {
2980 account: params.account.into_wallet_address(),
2981 nonce,
2982 action: batch,
2983 signature,
2984 };
2985 self.post_tee_signed(
2986 TEE_PERP_ORDER_BATCH_MODIFY_ROUTE,
2987 &request,
2988 "submit TEE perp batch modify",
2989 )
2990 .await
2991 }
2992
2993 pub async fn place_tee_perp_twap_order<S>(
3001 &self,
3002 signer: &S,
3003 params: TeePerpTwapParams,
3004 ) -> Result<TeePerpTwapResponse>
3005 where
3006 S: TeePerpSigner + ?Sized,
3007 {
3008 let action = TeePerpTwapAction {
3009 asset: params.asset,
3010 is_buy: matches!(params.side, Side::Buy),
3011 sz: to_perp_units(params.size, "size")?,
3012 reduce_only: params.reduce_only,
3013 minutes: params.minutes,
3014 randomize: params.randomize,
3015 };
3016 validate_twap_action(&action)?;
3017 let nonce = self
3018 .resolve_tee_nonce(signer.address(), params.nonce)
3019 .await?;
3020 let signature = signer
3021 .sign_tee_perp_twap_payload(TeePerpTwapSignature {
3022 account: params.account,
3023 nonce,
3024 action,
3025 })
3026 .await?;
3027 let request = DirectiveSubmitRequest {
3028 account: params.account.into_wallet_address(),
3029 nonce,
3030 action,
3031 signature,
3032 };
3033 self.post_tee_signed(TEE_PERP_TWAP_SUBMIT_ROUTE, &request, "submit TEE perp TWAP")
3034 .await
3035 }
3036
3037 pub async fn cancel_tee_perp_twap<S>(
3040 &self,
3041 signer: &S,
3042 params: TeePerpTwapCancelParams,
3043 ) -> Result<TeePerpVenueActionResponse>
3044 where
3045 S: TeePerpSigner + ?Sized,
3046 {
3047 if params.twap_id == 0 {
3048 return Err(ClientError::InvalidInput("twap_id must not be zero".into()));
3049 }
3050 let nonce = self
3051 .resolve_tee_nonce(signer.address(), params.nonce)
3052 .await?;
3053 let action = TeePerpTwapCancelAction {
3054 asset: params.asset,
3055 twap_id: params.twap_id,
3056 };
3057 let signature = signer
3058 .sign_tee_perp_twap_cancel_payload(TeePerpTwapCancelSignature {
3059 account: params.account,
3060 nonce,
3061 action,
3062 })
3063 .await?;
3064 let request = DirectiveSubmitRequest {
3065 account: params.account.into_wallet_address(),
3066 nonce,
3067 action,
3068 signature,
3069 };
3070 self.post_tee_signed(
3071 TEE_PERP_TWAP_CANCEL_ROUTE,
3072 &request,
3073 "submit TEE perp TWAP cancel",
3074 )
3075 .await
3076 }
3077
3078 pub async fn preview_tee_perp_action(
3081 &self,
3082 request: &PerpPreviewRequest,
3083 ) -> Result<PerpPreviewResponse> {
3084 let envelope: ApiResponse<PerpPreviewResponse> = self
3085 .post_tee(TEE_PERP_PREVIEW_ROUTE, request, "preview TEE perp action")
3086 .await?;
3087 if !envelope.success {
3088 return Err(ClientError::Api {
3089 status: 200,
3090 message: envelope
3091 .error
3092 .unwrap_or_else(|| "TEE perp preview failed".into()),
3093 });
3094 }
3095 envelope.data.ok_or_else(|| ClientError::Api {
3096 status: 200,
3097 message: "TEE perp preview returned no data".into(),
3098 })
3099 }
3100
3101 pub async fn get_tee_perp_markets(&self) -> Result<TeePerpMarketsResponse> {
3103 Self::send_reqwest_json(
3104 self.request(Method::GET, TEE_PERP_MARKETS_ROUTE),
3105 "get TEE perp markets",
3106 )
3107 .await
3108 }
3109
3110 pub async fn request_tee_api_wallet_approval<S>(
3113 &self,
3114 manager: &S,
3115 account: AccountAddress,
3116 ) -> Result<TeeApiWalletApprovalChallenge>
3117 where
3118 S: TeeApiWalletManagerSigner + ?Sized,
3119 {
3120 let timestamp = i64::try_from(self.server_now_ms().await? / 1_000).map_err(|_| {
3121 ClientError::ArithmeticOverflow {
3122 operation: "authentication timestamp",
3123 }
3124 })?;
3125 let manager_address = manager.address();
3126 let authentication_signature = manager.sign_authentication_payload(timestamp).await?;
3127 let request = TeeApiWalletApprovalRequest {
3128 account: account.into_wallet_address(),
3129 manager: manager_address.into_wallet_address(),
3130 timestamp,
3131 signature: authentication_signature.clone(),
3132 };
3133 let package: TeeApiWalletApprovalPackage = self
3134 .post_tee(
3135 TEE_API_WALLET_APPROVAL_REQUEST_ROUTE,
3136 &request,
3137 "request TEE API wallet approval",
3138 )
3139 .await?;
3140 Ok(TeeApiWalletApprovalChallenge {
3141 account,
3142 manager: manager_address,
3143 timestamp,
3144 authentication_signature,
3145 package,
3146 })
3147 }
3148
3149 pub async fn submit_tee_api_wallet_approval<S>(
3152 &self,
3153 manager: &S,
3154 challenge: &TeeApiWalletApprovalChallenge,
3155 ) -> Result<DirectiveSubmitResponse>
3156 where
3157 S: TeeApiWalletManagerSigner + ?Sized,
3158 {
3159 validate_approval_typed_data(challenge)?;
3160 let signature = manager
3161 .sign_tee_api_wallet_approval_payload(TeeApiWalletApprovalSignature {
3162 account: challenge.account,
3163 nonce: challenge.package.nonce,
3164 api_wallet_address: AccountAddress::from(
3165 challenge.package.api_wallet_address.inner(),
3166 ),
3167 api_wallet_name: &challenge.package.api_wallet_name,
3168 })
3169 .await?;
3170 let request = TeeApiWalletApprovalSubmitRequest {
3171 account: challenge.account.into_wallet_address(),
3172 manager: challenge.manager.into_wallet_address(),
3173 timestamp: challenge.timestamp,
3174 authentication_signature: challenge.authentication_signature.clone(),
3175 tee_wallet_id: challenge.package.tee_wallet_id,
3176 nonce: challenge.package.nonce,
3177 signature,
3178 };
3179 self.post_tee_signed(
3180 TEE_API_WALLET_APPROVAL_ROUTE,
3181 &request,
3182 "submit TEE API wallet approval",
3183 )
3184 .await
3185 }
3186
3187 pub async fn enroll_tee_api_wallet<S>(
3192 &self,
3193 manager: &S,
3194 account: AccountAddress,
3195 hyperliquid: &HyperliquidInfoClient,
3196 polling: TeeApiWalletEnrollmentPolling,
3197 ) -> Result<TeeApiWalletEnrollment>
3198 where
3199 S: TeeApiWalletManagerSigner + ?Sized,
3200 {
3201 let challenge = self
3202 .request_tee_api_wallet_approval(manager, account)
3203 .await?;
3204 let api_wallet = AccountAddress::from(challenge.package.api_wallet_address.inner());
3205 let api_wallet_name = challenge.package.api_wallet_name.clone();
3206 if hyperliquid
3207 .is_tee_api_wallet_active(account, api_wallet)
3208 .await?
3209 {
3210 return Ok(TeeApiWalletEnrollment {
3211 api_wallet,
3212 api_wallet_name,
3213 directive_id: None,
3214 });
3215 }
3216 let response = self
3217 .submit_tee_api_wallet_approval(manager, &challenge)
3218 .await?;
3219 if let Some(rejection) = &response.rejection {
3220 return Err(ClientError::Api {
3221 status: 200,
3222 message: format!(
3223 "TEE API wallet approval rejected ({}): {}",
3224 rejection.code, rejection.message
3225 ),
3226 });
3227 }
3228 let mut finalized = false;
3229 for _ in 0..polling.attempts {
3230 if let Ok(status) = self.get_directive_status(&response.directive_id).await {
3232 match tee_api_wallet_approval_progress(&status) {
3233 TeeApiWalletApprovalProgress::Finalized => {
3234 finalized = true;
3235 break;
3236 }
3237 TeeApiWalletApprovalProgress::Failed => {
3238 return Err(ClientError::Api {
3239 status: 200,
3240 message: format!(
3241 "TEE API wallet approval {} failed: domain {:?}, delivery {:?}",
3242 response.directive_id, status.domain_status, status.delivery_status
3243 ),
3244 });
3245 }
3246 TeeApiWalletApprovalProgress::Pending => {}
3247 }
3248 }
3249 tokio::time::sleep(polling.interval).await;
3250 }
3251 if !finalized {
3252 return Err(ClientError::Api {
3253 status: 200,
3254 message: format!(
3255 "TEE API wallet approval {} is still pending",
3256 response.directive_id
3257 ),
3258 });
3259 }
3260 if !hyperliquid
3261 .is_tee_api_wallet_active(account, api_wallet)
3262 .await?
3263 {
3264 return Err(ClientError::Api {
3265 status: 200,
3266 message: "Hyperliquid did not bind the finalized TEE API wallet to this account"
3267 .into(),
3268 });
3269 }
3270 Ok(TeeApiWalletEnrollment {
3271 api_wallet,
3272 api_wallet_name,
3273 directive_id: Some(response.directive_id),
3274 })
3275 }
3276
3277 pub async fn approve_hypercall_builder(
3285 &self,
3286 manager: &HypercallWallet,
3287 params: ApproveHypercallBuilderParams,
3288 ) -> Result<B256> {
3289 let builder = match params.builder {
3290 Some(builder) => builder,
3291 None => resolve_hypercall_builder_address(&self.get_exchange_info().await?)?,
3292 };
3293 let builder = builder.as_wallet_address().inner();
3294 if builder == Address::ZERO {
3295 return Err(ClientError::InvalidInput("builder must not be zero".into()));
3296 }
3297 let rpc_url = params
3298 .rpc_url
3299 .parse()
3300 .map_err(|source| ClientError::invalid_input("HyperEVM RPC URL", source))?;
3301 let provider = ProviderBuilder::new()
3302 .wallet(manager.ethereum_wallet())
3303 .connect_http(rpc_url);
3304 let rpc_chain_id = provider
3305 .get_chain_id()
3306 .await
3307 .map_err(|error| onchain_error("read HyperEVM chain ID", error))?;
3308 if rpc_chain_id != manager.chain_id() {
3309 return Err(ClientError::InvalidInput(format!(
3310 "HyperEVM RPC chain ID {rpc_chain_id} does not match wallet chain ID {}",
3311 manager.chain_id()
3312 )));
3313 }
3314 let manager_address = manager.address.as_wallet_address().inner();
3315 let balance = provider
3316 .get_balance(manager_address)
3317 .await
3318 .map_err(|error| onchain_error("read manager HYPE balance", error))?;
3319 if balance.is_zero() {
3320 return Err(ClientError::InvalidInput(
3321 "the manager wallet needs a small amount of HYPE on HyperEVM to pay the network fee"
3322 .into(),
3323 ));
3324 }
3325 let account = HypercallAccountBuilderApproval::new(
3326 params.account.as_wallet_address().inner(),
3327 &provider,
3328 );
3329 let call = account.approveZeroFeeBuilder(builder).from(manager_address);
3330 if let Err(error) = call.call().await {
3331 if is_missing_function_revert(&error) {
3332 return Err(ClientError::InvalidInput(
3333 "this Account implementation predates approveZeroFeeBuilder (needs 0.2.4); trading cannot be enabled yet".into(),
3334 ));
3335 }
3336 return Err(onchain_error("simulate approveZeroFeeBuilder", error));
3337 }
3338 let submission_lock = evm_submission_lock(manager_address);
3339 let _guard = submission_lock.lock().await;
3340 let receipt = call
3341 .send()
3342 .await
3343 .map_err(|error| onchain_error("submit approveZeroFeeBuilder", error))?
3344 .with_timeout(Some(Duration::from_secs(60)))
3345 .get_receipt()
3346 .await
3347 .map_err(|error| onchain_error("confirm approveZeroFeeBuilder", error))?;
3348 if !receipt.status() {
3349 return Err(ClientError::TransactionReverted {
3350 operation: "approveZeroFeeBuilder",
3351 transaction_hash: Some(receipt.transaction_hash),
3352 });
3353 }
3354 Ok(receipt.transaction_hash)
3355 }
3356}
3357
3358#[cfg(test)]
3359#[path = "tee_perp_test.rs"]
3360mod tests;
3361
3362#[cfg(test)]
3363#[path = "tee_perp_modify_test.rs"]
3364mod modify_tests;